@usenaive-sdk/managed-agents 0.0.0-stage → 0.12.1
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/README.md +79 -2
- package/dist/index.d.ts +13298 -0
- package/dist/index.js +7812 -0
- package/dist/index.js.map +1 -0
- package/package.json +42 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/id.ts","../../core/src/errors.ts","../../core/src/template-refusals.ts","../../core/src/schema/agent.ts","../../core/src/schema/common.ts","../../core/src/schema/audit-actions.ts","../../core/src/schema/browser.ts","../../core/src/schema/org.ts","../../core/src/schema/resource.ts","../../core/src/schema/files-library.ts","../../core/src/schema/session.ts","../../core/src/schema/outcome.ts","../../core/src/schema/social.ts","../../core/src/schema/harness.ts","../../core/src/schema/model-selection.ts","../../core/src/schema/trading.ts","../../core/src/schema/creator.ts","../../core/src/schema/digest.ts","../../core/src/schema/event.ts","../../core/src/schema/board.ts","../../core/src/schema/identity.ts","../../core/src/schema/comms.ts","../../core/src/schema/app.ts","../../core/src/schema/install.ts","../../core/src/schema/blueprint.ts","../../core/src/schema/creator-profile.ts","../../core/src/schema/mini-app.ts","../../core/src/schema/show.ts","../../core/src/schema/data.ts","../../core/src/schema/catalog.ts","../../core/src/schema/vault.ts","../../core/src/schema/social-data.ts","../../core/src/schema/handoff.ts","../../core/src/schema/compose.ts","../../core/src/schema/media.ts","../../core/src/schema/looks.ts","../../core/src/schema/media-judge.ts","../../core/src/schema/character.ts","../../core/src/schema/build-3d.ts","../../core/src/schema/app-data.ts","../../core/src/schema/stock-photo.ts","../../core/src/schema/tournament.ts","../../core/src/schema/qa.ts","../../core/src/schema/legal.ts","../../core/src/schema/wallet.ts","../../core/src/schema/operator.ts","../../core/src/schema/cards.ts","../../core/src/schema/proxy-trace.ts","../../core/src/schema/review.ts","../../core/src/schema/crm.ts","../../core/src/schema/ads.ts","../../core/src/schema/mcp-session.ts","../../core/src/session-token.ts","../../core/src/logo-svg.ts","../../core/src/brand-kit.ts","../../core/src/file-url.ts","../../core/src/people-data.ts","../../core/src/plan-state.ts","../src/account.ts","../src/http.ts","../src/apps.ts","../src/ads.ts","../src/automation.ts","../src/board.ts","../src/characters.ts","../src/browser.ts","../src/browser-sessions.ts","../src/comms.ts","../src/connections.ts","../src/database.ts","../src/digest.ts","../src/control-plane.ts","../src/clips.ts","../src/media-skills.ts","../src/media.ts","../src/identities.ts","../src/cards.ts","../src/legal.ts","../src/wallet.ts","../src/mobile-devices.ts","../src/crm.ts","../src/outcomes.ts","../src/proxy.ts","../src/social.ts","../src/data.ts","../src/social-data.ts","../src/storage.ts","../src/resources.ts","../src/stream.ts","../src/trading.ts","../src/vaults.ts","../src/mcp-sessions.ts","../src/mini-apps.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["/** Identifiers — one prefix per type, `prefix_` + Crockford base32 (canonical-spec §2). */\n\nexport type IdPrefix =\n | \"org\"\n | \"usr\"\n | \"key\"\n | \"mcs\"\n | \"agt\"\n | \"ses\"\n | \"evt\"\n | \"cmp\"\n | \"skl\"\n | \"fil\"\n | \"dep\"\n | \"whk\"\n | \"run\"\n | \"led\"\n | \"snp\"\n | \"vol\"\n | \"whd\"\n | \"aud\"\n /** Computer workspace (`canonical-spec §41`): one recorded command, one managed browser session. */\n | \"cmd\"\n | \"brw\"\n /** A mobile device — the third member of the computer suite (`canonical-spec §53`). */\n | \"mob\"\n /** An outcome: a rubric a grader holds a session to (`canonical-spec §58`). Not `out`, the outbound message. */\n | \"ocm\"\n /** The company's CRM (`canonical-spec §63`): a contact, and one line on its timeline. */\n | \"ctc\"\n | \"cta\"\n /**\n * P2 identity (`canonical-spec §22`–`§25`): a persona an agent acts as, a vault bound to it and one\n * credential in that vault, and the persona's endpoints — a domain, an email inbox, a phone\n * number, an inbound message, and one it sent (§24.1, ADR-1076).\n */\n | \"idn\"\n | \"vlt\"\n | \"vcr\"\n | \"dom\"\n | \"eml\"\n | \"pho\"\n | \"inb\"\n | \"out\"\n /**\n * The team board (`canonical-spec §28`): one board per coordinator session, a card on it, and one\n * comment on a card.\n */\n | \"brd\"\n | \"crd\"\n | \"bcm\"\n /** Support surface (`apps/central`): a ticket and one message on it. Not control-plane objects. */\n | \"tkt\"\n | \"spm\"\n /** Apps (`canonical-spec §29`): a hosted web application and one deployment of it. */\n | \"app\"\n | \"apd\"\n /** One applied blueprint declaration, per organization and project (`canonical-spec §29.6`). */\n | \"bpi\"\n /** A video clipping job (`canonical-spec §30`). */\n | \"clj\"\n /**\n * One published blueprint artifact (`canonical-spec §31`): the built tree of one blueprint ×\n * template × released version. The only id here that names a row belonging to no organization.\n */\n | \"bpa\"\n // core-gaps: contracts (`canonical-spec §32–§37`)\n /** An async media job — video, clip, transcription (§33, D5). */\n | \"med\"\n /** A trained character — a reusable, consistent persona rendered into media (§33.6, ADR-1269). */\n | \"chr\"\n /** One open managed browser, one saved login (identity-scoped, D4), one grant on it (§32.1). */\n | \"brw\"\n | \"bct\"\n | \"bgr\"\n /** One migration applied to an app's own database (§37.1). */\n | \"dbm\"\n /**\n * The creator program (`canonical-spec §42`): a creator, an application to become one, a referred\n * organization, one commission, one payout, and a creator template. Like `bpa`, rows belonging\n * to no organization; a template *version* has no id and is keyed `(template, version)`.\n */\n | \"crt\"\n | \"cra\"\n | \"crf\"\n | \"crc\"\n | \"crp\"\n | \"ctp\"\n /** A person's entry in the tournament (`canonical-spec §56`); no organization either. */\n | \"tne\"\n /** The QA tester program (`canonical-spec §60`): a tester, a job, an assignment, a bug, a chat message; no organization. */\n | \"qat\"\n | \"qaj\"\n | \"qaa\"\n | \"qab\"\n | \"qam\"\n /** A budget hold. Internal only: it is never a field on any wire object (`canonical-spec §2`). */\n | \"res\"\n /** One priced tool call. Internal only, and the settlement's idempotency key (`§11`, ADR-0272). */\n | \"tol\"\n /**\n * Identity-owned legal, wallet and cards (`canonical-spec §43`–`§45`): a verification and one of\n * its members, a company and one of its documents; a wallet and one transaction; a card and one\n * logged card transaction.\n */\n | \"lgv\"\n | \"lgm\"\n | \"lgc\"\n | \"lgd\"\n | \"wlt\"\n | \"wtx\"\n | \"vcd\"\n | \"vct\"\n /** A person's verdict on agent work given outside the approval box (`canonical-spec §47`). */\n | \"rev\"\n /** Not a stored object: the per-request id echoed in `x-request-id` and every envelope (§3). */\n | \"req\";\n\n/** Crockford base32, lowercase on the wire. Decoding is case-insensitive (i/l/o/u excluded). */\nconst ALPHABET = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst SUFFIX_LENGTH = 26;\nconst SUFFIX_PATTERN = new RegExp(`^[${ALPHABET}]{${SUFFIX_LENGTH},}$`);\n\n/** `${prefix}_` + 26 random Crockford base32 chars (130 bits). */\nexport function newId(prefix: IdPrefix): string {\n return idFromBytes(prefix, crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH)));\n}\n\n/**\n * `${prefix}_` + one Crockford char per byte of `bytes` (at least 26). Deterministic: the same\n * bytes name the same id, which is how a retried `Idempotency-Key` names the same `med_` job.\n */\nexport function idFromBytes(prefix: IdPrefix, bytes: Uint8Array): string {\n if (bytes.length < SUFFIX_LENGTH) throw new Error(`an id needs ${SUFFIX_LENGTH} bytes`);\n let suffix = \"\";\n for (const byte of bytes.subarray(0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/**\n * The same shape, **derived** rather than drawn: one seed always names one id.\n *\n * For work that can be redone — a render collected again because the wake that collected it died\n * before it could say so — a random id makes the retry a second object with a second row. Deriving\n * the id from the work's own idempotency key makes the retry name what is already there, so the\n * upsert behind it lands once and the bytes overwrite themselves (ADR-0514).\n */\nexport async function derivedId(prefix: IdPrefix, seed: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(seed));\n let suffix = \"\";\n for (const byte of new Uint8Array(digest, 0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/** True when `value` is a well-formed id of exactly this prefix (aliases such as `agent_` fail). */\nexport function isId(prefix: IdPrefix, value: string): boolean {\n const head = `${prefix}_`;\n if (!value.startsWith(head)) return false;\n return SUFFIX_PATTERN.test(value.slice(head.length).toLowerCase());\n}\n","/** The one error envelope and the one code taxonomy (canonical-spec §3). */\n\nexport type ErrorType =\n | \"invalid_request\"\n | \"authentication\"\n | \"permission\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limit\"\n | \"quota\"\n | \"api_error\"\n | \"not_implemented\";\n\n/** Every P1 code, with its coarse `type` and HTTP status. Adding one is a spec change. */\nconst CODES = {\n window_unavailable: [\"invalid_request\", 400],\n validation_failed: [\"invalid_request\", 400],\n unauthorized: [\"authentication\", 401],\n forbidden: [\"permission\", 403],\n not_found: [\"not_found\", 404],\n /** The path exists; the method does not. The response carries `Allow` (§3). */\n method_not_allowed: [\"invalid_request\", 405],\n budget_exceeded: [\"quota\", 402],\n insufficient_credits: [\"quota\", 402],\n /**\n * The organization holds no active plan, so it may not be used. `402`, alongside the other two\n * money codes, because the remedy is a payment — not `403`, which reads as \"your credential is\n * wrong\" and would send a customer to rotate a perfectly good key. Distinct from\n * `insufficient_credits`: that one means \"fund the balance\", this one means \"start the plan\".\n */\n subscription_required: [\"quota\", 402],\n version_conflict: [\"conflict\", 409],\n /**\n * The name is taken by a resource another project owns, and the request did not ask to take it\n * (ADR-0375). Nothing existing fits: `validation_failed` says the request is malformed and it is\n * not, `forbidden` reads as \"your credential is wrong\" and sends a customer to rotate a good key,\n * and `version_conflict` means optimistic concurrency.\n */\n name_conflict: [\"conflict\", 409],\n /**\n * A shared declaration moved underneath the applier: the install's `revision` is not the\n * `expected_revision` the apply carried (`§29.6`). Not `version_conflict`, which is one\n * immutable-versioned object's optimistic concurrency and whose remedy is to re-read that\n * object — this one carries a set of drifted PATHS and its remedy is a merge, and a client that\n * cannot tell them apart shows a config diff for a stale agent version.\n */\n revision_conflict: [\"conflict\", 409],\n idempotency_conflict: [\"conflict\", 409],\n /**\n * A lifecycle action asked of an object whose status does not admit it (§43–§45): forming a\n * company on an unverified verification, funding a `frozen` wallet, cancelling a card that is not\n * `active`. Not `version_conflict` — nothing raced; the remedy is to read the status.\n */\n state_conflict: [\"conflict\", 409],\n session_running: [\"conflict\", 409],\n session_terminal: [\"conflict\", 409],\n computer_unavailable: [\"conflict\", 409],\n /**\n * Two P2 additions (ADR-0118). Both mean \"not an error — retry later\", and no existing code\n * carries that: `feature_not_configured` is permanent, `computer_unavailable` is about a\n * sandbox, and `validation_failed` would tell a durable runtime to give up on something that\n * will succeed once verification or carrier approval clears.\n */\n job_not_ready: [\"conflict\", 409],\n compliance_pending: [\"conflict\", 409],\n // core-gaps: contracts (`canonical-spec §32`, §37; ADR-0448)\n /** `--app` omitted and the org has more than one fullstack app to resolve it to (§37.2). */\n ambiguous_app: [\"conflict\", 409],\n /** A saved browser login is held by a human-login flow for the next 15 minutes (§32.6). */\n context_locked: [\"conflict\", 409],\n rate_limited: [\"rate_limit\", 429],\n feature_not_configured: [\"not_implemented\", 501],\n internal_error: [\"api_error\", 500],\n /**\n * A configured upstream answered with a failure of its own — a 5xx, or a browser automation that\n * did nothing (§32.5). Not `internal_error`: the remedy is a retry, and nothing of ours broke.\n */\n provider_error: [\"api_error\", 502],\n} as const satisfies Record<string, readonly [ErrorType, number]>;\n\nexport type ErrorCode = keyof typeof CODES;\n\n/** Is `code` one of the taxonomy's codes — for a code read off another service's envelope. */\nexport const isErrorCode = (code: string): code is ErrorCode => Object.hasOwn(CODES, code);\n\nexport interface ErrorEnvelope {\n error: {\n type: ErrorType;\n code: ErrorCode;\n message: string;\n request_id: string;\n param?: string;\n };\n}\n\n/** How much of an error's own words one log line may carry (`faultOf`). */\nconst FAULT_MAX_CHARS = 2_000;\n\n/**\n * One error, as one **operator log line**. Never a customer-facing message — that is `toEnvelope` —\n * and never the error *object*.\n *\n * WHY NOT `console.error(prefix, error)`, which is what this replaces. Handed the object, the\n * runtime serialises whatever the thrower hung on it: a vendor client's `response`, `request` or\n * `config`, and with them the `authorization` header that carried our key (`CLAUDE.md §2`). It also\n * loses the one part worth reading — in production a media job failed every seven seconds for hours\n * and the captured line held stack frames with no message at all (ADR-0733). A derived string is\n * both safer and more legible.\n *\n * WHAT IS SAFE HERE is the same judgement `media-openrouter/src/wire.ts` already makes: that adapter\n * repeats a failed call's **status** and never its **body**, precisely because a body may quote the\n * request. So a vendor body never becomes a `message` in the first place, and a `message` is already\n * held repeatable — `providerFailure` puts an arbitrary `Error.message` into a *customer-facing*\n * `VettaError`. The cap is the backstop for the message we did not author.\n *\n * The name and the message are guaranteed rather than left to the stack: a `DOMException` carries its\n * whole answer in its name, and a workerd stack does not always repeat either of them — which is\n * exactly how the production line came out with frames and no reason at all.\n */\nexport function faultOf(error: unknown): string {\n if (!(error instanceof Error)) return `a non-Error ${typeof error} was thrown`;\n const head = `${error.name}: ${error.message}`;\n const stack = error.stack ?? \"\";\n const cause =\n error.cause instanceof Error\n ? ` | caused by ${error.cause.name}: ${error.cause.message}`\n : \"\";\n const body = stack.startsWith(head) ? stack : `${head}\\n${stack}`.trimEnd();\n // THE CAUSE IS RESERVED ITS ROOM BEFORE THE BODY SPENDS IT. Capping `body + cause` as one string\n // drops from the END, and the end is the cause — so on the one shape that most needs it, a\n // bundled worker's stack (every frame a one-line `index.js:1:NNNNN`, thousands of characters\n // before the first word of ours), the most diagnostic half was the first thing lost. The cause is\n // itself capped at half the line so that neither half can crowd the other out entirely: a real\n // cause is tens of characters and survives whole, and one long enough to be a payload still\n // leaves `head` and the top frames legible. The total is `FAULT_MAX_CHARS` either way.\n const room = cause.slice(0, FAULT_MAX_CHARS / 2);\n return `${body.slice(0, FAULT_MAX_CHARS - room.length)}${room}`;\n}\n\n/** The only error thrown across a boundary. SDKs subclass on `type`, branch on `code`. */\nexport class VettaError extends Error {\n readonly type: ErrorType;\n readonly code: ErrorCode;\n readonly httpStatus: number;\n readonly param: string | undefined;\n\n constructor(code: ErrorCode, message: string, param?: string) {\n super(message);\n this.name = \"VettaError\";\n const [type, httpStatus] = CODES[code];\n this.type = type;\n this.code = code;\n this.httpStatus = httpStatus;\n this.param = param;\n }\n\n toEnvelope(requestId: string): ErrorEnvelope {\n return {\n error: {\n type: this.type,\n code: this.code,\n message: this.message,\n request_id: requestId,\n ...(this.param === undefined ? {} : { param: this.param }),\n },\n };\n }\n}\n\n/**\n * A §9 `after` that names no row of the list it pages (ADR-1711). Read as page one it made a walk\n * count every row twice; read as an empty page it stopped the walk short. Either way, a 200.\n */\nexport const unknownCursor = (after: string): VettaError =>\n new VettaError(\"validation_failed\", `after: ${after} names no row of this list; omit it to start from the top`, \"after\");\n","/**\n * THE TEMPLATE GATE (`canonical-spec §42.2`, ADR-1551): every power a template made outside Naive\n * may not hand itself inside a customer's company, as one pure list in plain words. The API refuses\n * a version on the first of them at submit, approve and publish (`apps/api/src/creator-publish.ts`);\n * the creator's builder and the reviewer's checklist show all of them, in the same words. Our own\n * templates never pass through it: they are published from our repositories, not by a creator.\n *\n * The declaration is read loosely, so a half-written draft still gets its refusals. An agent that\n * does not read at all is itself refused (fail closed); the API's `parseProject` refuses it first.\n */\nimport { z } from \"zod\";\nimport { firesMoreOftenThan } from \"./cron\";\nimport { decimalStringFromMicro, microUsd } from \"./money\";\nimport { ASK_BY_DEFAULT_TOOLS, BudgetSchema, grantable, HandoffsField, ToolsetSchema, toolNameProblem } from \"./schema/agent\";\nimport { CREATOR_PROGRAM, type CreatorDeclaration, type CreatorTemplateKind, type TemplateReach } from \"./schema/creator\";\n\nexport interface TemplateRefusal {\n /** The field, as `agents.0.tools.default_config`; the API names it under `declaration.`. */\n path: string;\n message: string;\n}\n\n/**\n * What the gate needs besides the declaration: the template's kind, the app names its base declares,\n * and who can install it. `marketplace` is any organization; `own_org` is only the organization that\n * made it from its own company (ADR-1552), whose crew already held these powers there.\n */\nexport interface TemplateGateContext {\n kind: CreatorTemplateKind;\n apps: readonly string[];\n reach: TemplateReach;\n}\n\n/** How often a template's schedule may fire, at most: anything tighter is a beacon. */\nconst TEMPLATE_SCHEDULE_FLOOR_MINUTES = 15;\n/** The most one template agent may spend in a month, and one schedule run may spend (ADR-1551). */\nexport const TEMPLATE_BUDGET_CEILING_MICRO_USD = 100_000_000;\n/** The most a template's whole crew may spend in a month: one Pro plan's included credit (ADR-1551). */\nconst TEMPLATE_CREW_BUDGET_CEILING_MICRO_USD = 200_000_000;\n/** The most agents a template's crew may have (ADR-1551). */\nconst TEMPLATE_CREW_MAX_AGENTS = 8;\n/** The largest skill body review passes into a customer's company; a draft may hold 64 KiB. */\nexport const TEMPLATE_SKILL_MAX_BYTES = 16 * 1024;\n\n/** The most budget periods one month touches, so a cap is judged on its worst month. */\nconst PERIODS_PER_MONTH = { day: 31, week: 6, month: 1 } as const;\n/**\n * A URL, a `www.` host, a bare host with a path (`exfil.example.com/x`), or a bare host on a common\n * top-level domain (`exfil.example.com`). A file name (`brand.md`, `notes.txt`) is none of them.\n */\nconst LINK =\n /https?:\\/\\/|\\bwww\\.|\\b[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.[a-z]{2,}\\/|\\b[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.(?:com|net|org|io|ai|co|app|dev|xyz|me|info|biz|us|uk|de|fr|ru|cn|tv|cc|gg|ly|sh|so|to|site|online|store|shop|link|click|top|club|live|tech|cloud|pro)\\b/i;\n\n/** Whether a text carries a link the gate refuses: also the marketplace listing's words (ADR-1554). */\nexport const hasLink = (text: string): boolean => LINK.test(text);\n\n/**\n * What a listed template may not carry beyond links (ADR-1747): a company's own prompts are written\n * for its own people, so they can hold a key, an email address, a phone number or an @handle that\n * no other company should get. Key-shaped: a vendor prefix (`sk_live_`, `sk-`, `ghp_`, `AKIA`,\n * `xoxb-`, `AIza`) or 32+ letters and digits mixed in one run. A phone: `+` and 8 or more digits, or\n * `(555) 123-4567`. A handle: `@` and a name not inside an email address.\n */\nconst PRIVATE: readonly [(text: string) => boolean, string][] = [\n [\n (text) =>\n /\\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{8,}|\\bsk-[A-Za-z0-9_-]{16,}|\\bgh[pousr]_[A-Za-z0-9]{20,}|\\bAKIA[0-9A-Z]{16}\\b|\\bxox[abprs]-[A-Za-z0-9-]{10,}|\\bAIza[0-9A-Za-z_-]{30,}/.test(text) ||\n tokenIn(text),\n \"a key\",\n ],\n [\n (text) =>\n // Starts only where a run starts, or a long run with no @ is retried from every character.\n /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}/.test(text) ||\n /\\b[\\w.+-]+\\s*(?:\\(at\\)|\\[at\\]|\\sat\\s)\\s*[\\w-]+\\s*(?:\\(dot\\)|\\[dot\\]|\\sdot\\s)\\s*(?:com|net|org|io|co|ai|app|dev|me|us|uk|de|fr|es|ca|au)\\b/i.test(text),\n \"an email address\",\n ],\n [(text) => /\\+\\d[\\d\\s().-]{6,}\\d|\\(\\d{3}\\)\\s?\\d{3}[\\s.-]\\d{4}\\b|\\b\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4}\\b|\\b\\d{10}\\b/.test(text), \"a phone number\"],\n [(text) => /(?:^|[^\\w@.])@[A-Za-z0-9_][A-Za-z0-9_.]{1,29}/.test(text), \"an @handle\"],\n];\n\n/**\n * A run of 24 or more key characters with a letter and a digit that reads as random: at least 3.5\n * bits a character. A long word or a repeated id does not; a key, a token or a hash does. Some\n * long identifiers pass the bar too, and the refusal says to reword.\n */\nfunction tokenIn(text: string): boolean {\n for (const [run] of text.matchAll(/[A-Za-z0-9_+/=-]{24,}/g)) {\n if (!/\\d/.test(run) || !/[A-Za-z]/.test(run)) continue;\n const counts = new Map<string, number>();\n for (const char of run) counts.set(char, (counts.get(char) ?? 0) + 1);\n let bits = 0;\n for (const n of counts.values()) bits -= (n / run.length) * Math.log2(n / run.length);\n if (bits >= 3.5) return true;\n }\n return false;\n}\n\n/** The first kind of private text in `text`, or `null`. */\nexport const privateIn = (text: string): string | null => PRIVATE.find(([found]) => found(text))?.[1] ?? null;\n\n/** One text a template carries to every company that starts from it, as the approval card shows it. */\nexport interface ListedText {\n path: string;\n label: string;\n text: string;\n}\n\n/**\n * EVERY WORD A LISTING CARRIES (ADR-1747): each agent's name, description, system prompt, first task,\n * schedules and metadata, each skill's body, each app's brief and each question. The approval card\n * shows exactly these, and the gate scans exactly these, so a person never approves text they did not see.\n */\nexport function listedText(declaration: CreatorDeclaration): ListedText[] {\n const out: ListedText[] = [];\n const add = (path: string, label: string, text: string | undefined) => {\n if (text !== undefined && text.trim() !== \"\") out.push({ path, label, text });\n };\n declaration.agents.forEach((raw, i) => {\n const parsed = AgentView.safeParse(raw);\n if (!parsed.success) return;\n const agent = parsed.data;\n const who = `Agent \"${agent.name}\"`;\n add(`agents.${i}.name`, `${who} · name`, agent.name);\n add(`agents.${i}.description`, `${who} · description`, agent.description);\n add(`agents.${i}.system`, `${who} · system prompt`, agent.system);\n add(`agents.${i}.intake.message`, `${who} · first task`, agent.intake?.message);\n (agent.schedules ?? []).forEach((schedule, j) => {\n add(`agents.${i}.schedules.${j}.input`, `${who} · schedule \"${schedule.cron}\"`, schedule.input);\n add(`agents.${i}.schedules.${j}.summary`, `${who} · schedule \"${schedule.cron}\" summary`, schedule.summary);\n });\n for (const [key, value] of Object.entries(agent.metadata ?? {})) add(`agents.${i}.metadata.${key}`, `${who} · metadata ${key}`, JSON.stringify(value));\n add(`agents.${i}.output_schema`, `${who} · output schema`, descriptions(agent.output_schema).join(\"\\n\"));\n });\n declaration.skills.forEach((skill, i) => add(`skills.${i}.body`, `Skill \"${skill.slug}\"`, skill.body));\n (declaration.briefs ?? []).forEach((brief, i) => add(`briefs.${i}.brief`, `The ${brief.name} app's brief`, brief.brief));\n declaration.questions.forEach((question, i) => add(`questions.${i}`, `Question ${i + 1}`, strings(question).join(\"\\n\")));\n return out;\n}\n\n/** The platform's own tool namespace (`vetta.agents_list`); a template may allow its reads and its base's apps' tools. */\nconst PLATFORM_NAMESPACE = \"vetta\";\n/**\n * A platform tool that only reads (`agents_list`, `skills_list_versions`, `tools_search`). Every other\n * `vetta.*` tool changes the company it runs in: `agents_patch` rewrites a toolset, `tools_execute`\n * runs any tool. A template may never allow one of those, so a crew cannot hand itself a power with\n * no card (ADR-1551). A read the pattern misses is refused too, and the author sets it to ask. The\n * API's catalog test checks every name this passes is a read there (`apps/api/src/mcp-tools.test.ts`).\n */\nconst PLATFORM_READ = /(?:^|_)(?:list|get|search)(?:_|$)/;\n/** Reads by name that are not reads: listing a computer's folder runs on it; a build read advances a paid build. */\nconst PLATFORM_NOT_READ = new Set([\"computers_list_dir\", \"media_get_skill_build\"]);\n/** Whether a template may allow the platform tool named `action` (the part after `vetta.`). */\nexport const platformToolIsRead = (action: string): boolean =>\n PLATFORM_READ.test(action) && !/(?:^|_)create(?:_|$)/.test(action) && !PLATFORM_NOT_READ.has(action);\n\nconst ScheduleView = z.looseObject({\n cron: z.string(),\n timezone: z.string().optional(),\n input: z.string(),\n summary: z.string().optional(),\n budget_micro_usd: z.number(),\n identity: z.string().optional(),\n});\nconst AgentView = z.looseObject({\n name: z.string(),\n budget: BudgetSchema,\n description: z.string().optional(),\n system: z.string().optional(),\n tools: ToolsetSchema.optional(),\n handoffs: HandoffsField.optional(),\n mcp_servers: z.array(z.looseObject({ name: z.string() })).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n output_schema: z.unknown().optional(),\n identity: z.string().optional(),\n intake: z.looseObject({ message: z.string(), budget_micro_usd: z.number().optional() }).optional(),\n schedules: z.array(ScheduleView).optional(),\n});\ntype AgentView = z.infer<typeof AgentView>;\n\nconst dollars = (micro: number): string => `$${decimalStringFromMicro(microUsd(micro))}`;\nconst monthly = (agent: AgentView): number => agent.budget.cap_micro_usd * PERIODS_PER_MONTH[agent.budget.period];\n\n/** Every string anywhere inside a value: a question's words, wherever its shape puts them. */\nconst strings = (value: unknown): string[] => (typeof value === \"string\" ? [value] : value && typeof value === \"object\" ? Object.values(value).flatMap(strings) : []);\n\n/** Every `description` inside a JSON Schema: what the model reads about each field it fills. */\nconst descriptions = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.flatMap(descriptions)\n : value && typeof value === \"object\"\n ? Object.entries(value).flatMap(([key, inner]) => (key === \"description\" && typeof inner === \"string\" ? [inner] : descriptions(inner)))\n : [];\n\n/** Why `allow` on this tool is refused, or `null`. `allow` is read off the config itself, `enabled` or not. */\nfunction allowRefusal(name: string, apps: readonly string[]): string | null {\n if (name === \"apps\") return \"may build and change apps without asking. Set apps to ask or deny.\";\n // `grantable` is ADR-0810's one-call-at-a-time class: posts, payments, filings, spends, installs.\n if (ASK_BY_DEFAULT_TOOLS.has(name) || !grantable(name)) return `may use ${name} without asking. A tool that posts, pays, spends or files must ask every time.`;\n const namespace = /\\.|__/.test(name) ? name.split(/\\.|__/)[0]! : null;\n if (namespace === PLATFORM_NAMESPACE) {\n const action = name.slice(namespace.length).replace(/^\\.|^__/, \"\");\n return platformToolIsRead(action) ? null : `may use ${name} without asking. A template may allow the platform's tools only to read; a tool that changes your company must ask every time.`;\n }\n if (namespace !== null && !apps.includes(namespace)) {\n return `may use ${name} without asking. A template may allow only the platform's tools and its own apps' tools.`;\n }\n return null;\n}\n\n/** What a crew may not grant itself where it was not made: tools that run unasked, handoffs to the CEO, spend. */\nfunction powerRefusals(agent: AgentView, apps: readonly string[], refuse: (path: string, message: string) => void): void {\n // Absent tools is the route's default, `allow` for everything (`POST /v1/agents`).\n if (agent.tools === undefined) refuse(\"tools\", \"has no tool settings, so every tool runs without asking. Set the default to ask or deny.\");\n else {\n if (agent.tools.default_config.permission === \"allow\") refuse(\"tools.default_config\", \"lets every tool run without asking. Set the default to ask or deny.\");\n for (const [name, config] of Object.entries(agent.tools.configs)) {\n const why = config.permission === \"allow\" ? allowRefusal(name, apps) : null;\n if (why !== null) refuse(`tools.${name}`, why);\n }\n }\n // Every handoff but `false` reaches the CEO (`handoffAllows`), and absent is `true` (§31.7).\n if (agent.handoffs !== false) {\n refuse(\"handoffs\", \"can hand work to other agents. A crew from the marketplace can't message your CEO yet, so turn handoffs off.\");\n }\n if (monthly(agent) > TEMPLATE_BUDGET_CEILING_MICRO_USD) {\n refuse(\"budget.cap_micro_usd\", `may spend up to ${dollars(monthly(agent))} a month. A template agent may spend at most ${dollars(TEMPLATE_BUDGET_CEILING_MICRO_USD)} a month.`);\n }\n}\n\nfunction agentRefusals(raw: unknown, index: number, { apps, reach }: TemplateGateContext): TemplateRefusal[] {\n const at = `agents.${index}`;\n const parsed = AgentView.safeParse(raw);\n if (!parsed.success) return [{ path: at, message: `Agent ${index + 1} does not read as an agent.` }];\n const agent = parsed.data;\n const out: TemplateRefusal[] = [];\n const refuse = (path: string, message: string) => out.push({ path: `${at}.${path}`, message: `Agent \"${agent.name}\" ${message}` });\n const noLink = (text: string, path: string, what: string) => {\n if (LINK.test(text)) refuse(path, `has a link in ${what}. A template may not carry links.`);\n };\n\n // A creator declares no identities, so any claim names one of the base template's own personas.\n if (agent.identity !== undefined) refuse(\"identity\", `claims the identity \"${agent.identity}\", which this template does not declare.`);\n (agent.mcp_servers ?? []).forEach((server, j) => refuse(`mcp_servers.${j}`, `connects to the server \"${server.name}\". A template may not bring its own servers.`));\n // A key naming no tool governs nothing and `POST /v1/agents` refuses it, so the save is refused, not the install (ADR-1834).\n // The MCP spelling (`vetta__…`) is left to the power rules below, which read it as its dotted name; an install drops it.\n for (const name of Object.keys(agent.tools?.configs ?? {})) {\n if (name.includes(\"__\")) continue;\n const problem = toolNameProblem(name);\n if (problem !== null) refuse(`tools.configs.${name}`, `has a setting for a tool that does not exist (${problem}).`);\n }\n\n // The powers a crew grants itself matter where it was not made: another organization (ADR-1552).\n if (reach === \"marketplace\") powerRefusals(agent, apps, refuse);\n\n if (agent.intake?.budget_micro_usd !== undefined && agent.intake.budget_micro_usd > TEMPLATE_BUDGET_CEILING_MICRO_USD) {\n refuse(\"intake.budget_micro_usd\", `may spend ${dollars(agent.intake.budget_micro_usd)} on its first task. A run may spend at most ${dollars(TEMPLATE_BUDGET_CEILING_MICRO_USD)}.`);\n }\n\n noLink(agent.name, \"name\", \"its name\");\n if (agent.description !== undefined) noLink(agent.description, \"description\", \"its description\");\n if (agent.system !== undefined) noLink(agent.system, \"system\", \"its system prompt\");\n if (agent.intake !== undefined) noLink(agent.intake.message, \"intake.message\", \"its first task\");\n for (const [key, value] of Object.entries(agent.metadata ?? {})) noLink(JSON.stringify(value), `metadata.${key}`, `metadata ${key}`);\n for (const text of descriptions(agent.output_schema)) noLink(text, \"output_schema\", \"its output schema\");\n (agent.schedules ?? []).forEach((schedule, j) => {\n const path = `schedules.${j}`;\n const run = `the schedule \"${schedule.cron}\"`;\n if (schedule.identity !== undefined) refuse(`${path}.identity`, `runs ${run} as \"${schedule.identity}\", an identity this template does not declare.`);\n noLink(schedule.input, `${path}.input`, run);\n if (schedule.summary !== undefined) noLink(schedule.summary, `${path}.summary`, `the summary of ${run}`);\n if (firesMoreOftenThan(schedule.cron, TEMPLATE_SCHEDULE_FLOOR_MINUTES, schedule.timezone)) refuse(`${path}.cron`, `runs ${run} more often than every ${TEMPLATE_SCHEDULE_FLOOR_MINUTES} minutes.`);\n if (reach === \"marketplace\" && schedule.budget_micro_usd > TEMPLATE_BUDGET_CEILING_MICRO_USD) {\n refuse(`${path}.budget_micro_usd`, `may spend ${dollars(schedule.budget_micro_usd)} on one run of ${run}. A run may spend at most ${dollars(TEMPLATE_BUDGET_CEILING_MICRO_USD)}.`);\n }\n });\n return out;\n}\n\n/** The crew as a whole: how many seats, and what they may spend together in a month. */\nfunction crewRefusals(agents: unknown[]): TemplateRefusal[] {\n const out: TemplateRefusal[] = [];\n // A crew template with no crew would list as an app of ours on the app store's shelf (ADR-1555).\n if (agents.length === 0) out.push({ path: \"agents\", message: \"This crew has no agents. A template needs at least one.\" });\n if (agents.length > TEMPLATE_CREW_MAX_AGENTS) out.push({ path: \"agents\", message: `This crew has ${agents.length} agents. A template may have at most ${TEMPLATE_CREW_MAX_AGENTS}.` });\n const total = agents.reduce<number>((sum, raw) => {\n const agent = AgentView.safeParse(raw);\n return agent.success ? sum + monthly(agent.data) : sum;\n }, 0);\n if (total > TEMPLATE_CREW_BUDGET_CEILING_MICRO_USD) {\n out.push({ path: \"agents\", message: `This crew may spend up to ${dollars(total)} a month. A template's crew may spend at most ${dollars(TEMPLATE_CREW_BUDGET_CEILING_MICRO_USD)} a month.` });\n }\n return out;\n}\n\n/**\n * Every refusal for a template made outside Naive, in the order a person reads the declaration; `[]`\n * passes. A niche version brings one skill and no crew: its seats are the base template's own. Which\n * one it is comes from the template's `kind`, never from the declaration, so a crew cannot pass as one.\n */\nexport function templateRefusals(declaration: CreatorDeclaration, context: TemplateGateContext): TemplateRefusal[] {\n const { kind } = context;\n const niche = kind === \"niche\";\n const out: TemplateRefusal[] = [];\n if (niche !== (declaration.studio !== undefined)) {\n out.push({ path: \"studio\", message: niche ? \"A niche version needs its studio round.\" : \"A crew template can't carry a studio round.\" });\n }\n if (niche && declaration.skills.length !== 1) out.push({ path: \"skills\", message: \"A niche version carries exactly one skill.\" });\n if (!niche && context.reach === \"marketplace\") out.push(...crewRefusals(declaration.agents));\n if (!niche) out.push(...declaration.agents.flatMap((agent, i) => agentRefusals(agent, i, context)));\n const max = niche ? CREATOR_PROGRAM.studio.skill_max_bytes : TEMPLATE_SKILL_MAX_BYTES;\n declaration.skills.forEach((skill, i) => {\n const size = new TextEncoder().encode(skill.body).length;\n if (size > max) out.push({ path: `skills.${i}.body`, message: `Skill \"${skill.slug}\" is ${size} bytes. Review passes at most ${max}.` });\n if (LINK.test(skill.body)) out.push({ path: `skills.${i}.body`, message: `Skill \"${skill.slug}\" has a link. A template may not carry links.` });\n });\n (declaration.briefs ?? []).forEach((brief, i) => {\n if (LINK.test(brief.brief)) out.push({ path: `briefs.${i}.brief`, message: `The brief for the ${brief.name} app has a link. A template may not carry links.` });\n });\n declaration.questions.forEach((question, i) => {\n if (strings(question).some((text) => LINK.test(text))) out.push({ path: `questions.${i}`, message: `Question ${i + 1} has a link. A template may not carry links.` });\n });\n if (context.reach === \"marketplace\") {\n for (const { path, label, text } of listedText(declaration)) {\n const kind = privateIn(text);\n if (kind !== null) out.push({ path, message: `${label} has ${kind}. A listed template may not carry keys, email addresses, phone numbers or @handles; if it is not private, reword it.` });\n }\n }\n return out;\n}\n\n/** A change the marketplace copy makes to one field, in plain words (ADR-1554). */\nexport interface TemplateChange {\n path: string;\n message: string;\n}\n\nconst CENT = 10_000;\nconst PERIOD_WORD = { day: \"a day\", week: \"a week\", month: \"a month\" } as const;\ntype Raw = Record<string, unknown>;\n\n/**\n * THE COPY THE MARKETPLACE LISTS (ADR-1554). A company's own crew holds powers no template from the\n * marketplace may: its agents hand work to each other (and so reach the CEO), its tools may run\n * unasked, and its budgets are its own. Those are refused at `marketplace` reach, so a private\n * template is submitted as a copy that only ever TIGHTENS them, never anything else: every refused\n * `allow` becomes `ask`, handoffs turn off, and a budget over a ceiling is lowered to it — the crew's\n * total scaled down to its ceiling last. Prompts, skills and questions are never touched; the company\n * keeps its own settings. `changes` says each one in plain words; whatever `templateRefusals` still\n * finds on the copy blocks the submission.\n */\nexport function marketplaceCopy(declaration: CreatorDeclaration, apps: readonly string[]): { declaration: CreatorDeclaration; changes: TemplateChange[] } {\n const changes: TemplateChange[] = [];\n const agents = declaration.agents.map((raw, i) => {\n const parsed = AgentView.safeParse(raw);\n if (!parsed.success) return raw; // Refused as it is, by the gate.\n const agent = parsed.data;\n const out: Raw = { ...(raw as Raw) };\n const change = (path: string, message: string) => changes.push({ path: `agents.${i}.${path}`, message: `Agent \"${agent.name}\" ${message}` });\n if (agent.tools === undefined || agent.tools.default_config.permission === \"allow\") {\n out[\"tools\"] = { default_config: { permission: \"ask\" }, configs: agent.tools?.configs ?? {} };\n change(\"tools.default_config\", \"asks before it uses a tool you have not set.\");\n }\n const tools = out[\"tools\"] as { default_config: unknown; configs: Record<string, Raw> };\n const configs = Object.fromEntries(\n Object.entries(tools.configs).map(([name, config]) => {\n if (config[\"permission\"] !== \"allow\" || allowRefusal(name, apps) === null) return [name, config];\n change(`tools.${name}`, `asks before it uses ${name}.`);\n return [name, { ...config, permission: \"ask\" }];\n }),\n );\n out[\"tools\"] = { ...tools, configs };\n if (agent.handoffs !== false) {\n out[\"handoffs\"] = false;\n change(\"handoffs\", \"does not hand work to other agents. A crew from the marketplace can't message your CEO yet.\");\n }\n if (monthly(agent) > TEMPLATE_BUDGET_CEILING_MICRO_USD) {\n const cap = Math.floor(TEMPLATE_BUDGET_CEILING_MICRO_USD / PERIODS_PER_MONTH[agent.budget.period] / CENT) * CENT;\n out[\"budget\"] = { ...agent.budget, cap_micro_usd: cap }; // its task cap follows below, with the crew's\n }\n if (agent.schedules !== undefined) {\n out[\"schedules\"] = (raw as Raw & { schedules: Raw[] }).schedules.map((schedule, j) => {\n if ((schedule[\"budget_micro_usd\"] as number) <= TEMPLATE_BUDGET_CEILING_MICRO_USD) return schedule;\n change(`schedules.${j}.budget_micro_usd`, `spends at most ${dollars(TEMPLATE_BUDGET_CEILING_MICRO_USD)} on one run of the schedule \"${String(schedule[\"cron\"])}\".`);\n return { ...schedule, budget_micro_usd: TEMPLATE_BUDGET_CEILING_MICRO_USD };\n });\n }\n return out;\n });\n\n // The crew's month, after each agent's own ceiling; over the crew's, every cap shrinks by one factor.\n const views = agents.map((raw) => AgentView.safeParse(raw));\n const total = views.reduce((sum, view) => sum + (view.success ? monthly(view.data) : 0), 0);\n const scale = total > TEMPLATE_CREW_BUDGET_CEILING_MICRO_USD ? TEMPLATE_CREW_BUDGET_CEILING_MICRO_USD / total : 1;\n const budgeted = agents.map((raw, i) => {\n const before = AgentView.safeParse(declaration.agents[i]);\n const view = views[i]!;\n if (!before.success || !view.success) return raw;\n const cap = scale === 1 ? view.data.budget.cap_micro_usd : Math.floor((view.data.budget.cap_micro_usd * scale) / CENT) * CENT;\n if (cap === before.data.budget.cap_micro_usd) return raw;\n changes.push({\n path: `agents.${i}.budget.cap_micro_usd`,\n message: `Agent \"${view.data.name}\" may spend up to ${dollars(cap)} ${PERIOD_WORD[view.data.budget.period]}, down from ${dollars(before.data.budget.cap_micro_usd)}.`,\n });\n return { ...(raw as Raw), budget: { ...view.data.budget, cap_micro_usd: cap, max_task_micro_usd: Math.min(view.data.budget.max_task_micro_usd, cap) } };\n });\n return { declaration: { ...declaration, agents: budgeted }, changes };\n}\n","/**\n * Agents, immutable agent versions, and the one toolset schema (canonical-spec §6, §12, §13).\n * The layer an agent selects is its **harness** — never its runtime, which is the metered\n * infrastructure we provide and not a parameter (canonical-spec §19).\n */\n\nimport { z } from \"zod\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n WindowSchema,\n idOf,\n} from \"./common\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { MobileToolOptionsSchema } from \"./resource\";\nimport { HarnessIdSchema } from \"./harness\";\nimport { ModelSelectionPolicySchema } from \"./model-selection\";\nimport { TRADING_WRITE_TOOLS } from \"./trading\";\nimport type { SessionMode } from \"./session\";\n\n/** `allow` runs silently · `ask` pauses · `deny` never offers the tool to the model (§6). */\nexport const ToolPermissionSchema = z.enum([\"allow\", \"ask\", \"deny\"]);\nexport type ToolPermission = z.infer<typeof ToolPermissionSchema>;\n\n/**\n * Built-in P1 tools — the names an agent's `configs` may govern. External tools register through\n * the same shape (§6). `bash`, `read`, `write`, `edit`, `ls` and `find` are the harness's own\n * sandbox tools; `browser`, `read_skill`, `publish_file`, `web_search`, `web_fetch`,\n * `generate_image` and `generate_video` are Vetta's (ADR-0102, ADR-0275, ADR-0277). A customer can\n * only deny a tool it can name, so this list is the tool surface, not a subset of it — and that is\n * why the six team tools (§28) are here even though only an agent with a roster or a room seat is\n * ever offered one: a name that cannot be written into `configs` cannot be denied.\n *\n * It is also what makes a built-in **default-on**: the runtime never reads this constant, but the\n * CLI and the dashboard write `enabled:false` for every name *not* in it, so a tool omitted here is\n * silently denied everywhere except the raw API.\n */\nexport const BUILTIN_TOOLS = [\n \"bash\",\n \"read\",\n \"write\",\n \"edit\",\n \"ls\",\n \"find\",\n \"browser\",\n // The phone (§53.8): one per session, opened on first use; asks by default.\n \"mobile\",\n \"read_skill\",\n \"publish_file\",\n \"web_search\",\n \"web_fetch\",\n \"generate_image\",\n \"generate_video\",\n \"clip_video\",\n // An org skill from 1–3 reel links (§57.4, ADR-1355): default-on, asks by default (paid).\n \"build_media_skill\",\n // The running company, sent to the marketplace (§61.8, ADR-1747): an owner or admin approves each one.\n \"list_as_template\",\n // What the company earned there, paid out to its Stripe account (§61.10, ADR-1598): the same yes.\n \"pay_out_earnings\",\n // 3D (§59, ADR-1412): a generated mesh is a media job; a built one is a script run on the\n // computer and billed as computer seconds.\n \"generate_3d_model\",\n \"build_3d\",\n // The character primitive (§33.6, ADR-1269): train a reusable on-screen persona once, then pin it\n // into every render with `generate_image`'s `character` argument. Default-on like the generators\n // and fail-closed — all four answer `feature_not_configured` when the media backend trains no\n // characters (only the Soul family does) or Postgres is absent, so a deploy without them is safe.\n \"create_character\",\n \"get_character\",\n \"list_characters\",\n \"update_character\",\n \"delete_character\",\n \"apps\",\n \"send_to_agent\",\n \"wait_for_agents\",\n \"list_agents\",\n \"post_to_channel\",\n \"board_read\",\n \"board_write\",\n \"ask_operator\",\n \"request_tools\",\n \"project_context\",\n // core-gaps: contracts — names only (`canonical-spec §35.3`, §36.3, §39); U6/U7/U10 add the modules.\n \"transcribe_audio\",\n \"generate_speech\",\n // core-gaps: U11-sound-effects — a text prompt to a short generated audio clip (`§35.4`).\n \"generate_sound_effect\",\n // core-gaps: U12-music — a text prompt to an original song (`§35.6`).\n \"generate_music\",\n \"find_files\",\n // The read half of the library: `find_files` answers WHICH images exist, this one shows them\n // (§16.2, ADR-0758). Separate names because only one of the two costs context.\n \"view_image\",\n // The write half: `view_image` shows the model a file, this one puts it on the box's DISK so\n // bash can work on the bytes (ffmpeg joining a long-form render, say). The exact inverse of\n // `publish_file`, and the first way anything the platform itself produced could be read back.\n \"fetch_file\",\n \"find_stock_photo\",\n // Every public data domain (social included), searched, described and run by id (§54). Agents\n // get only these: §52's social_data_* names stay on REST, SDK and CLI, not as agent tools.\n \"data_search\",\n \"data_describe\",\n \"data_run\",\n \"session_spend\",\n // A view the chat draws — spend, post views, the roadmap, the week ahead — read by code (§48).\n \"show\",\n // The panel beside the chat, turned to an app, a file, a card, the board, the files or the store.\n \"open_panel\",\n // A card the model lays out, every number bound to a source code reads (§49).\n \"compose\",\n // Plan mode's two (§7.5): offered only to a session in plan mode or holding a plan.\n \"write_plan\",\n \"propose_plan\",\n] as const;\n\n/**\n * The tools the Effect ledger (`canonical-spec §19`, ADR-0822) runs again on a replay instead of\n * answering from its record, because the record would describe a world the replay has changed:\n *\n * - the effect is held by the turn and written at its commit, so a failed attempt lost it — the\n * thread `send_to_agent` queues, the park `wait_for_agents` asks for;\n * - the effect depends on state the arguments do not name, which the replay may have rewritten —\n * the box's files `publish_file` and `apps` read, the live page `browser` acts on.\n */\nexport const UNJOURNALED_TOOLS: ReadonlySet<string> = new Set([\n \"send_to_agent\",\n \"wait_for_agents\",\n \"publish_file\",\n \"apps\",\n \"browser\",\n]);\n\n/**\n * The platform's own namespaced tools — Vetta's, not a declared server's or a connected app's. They\n * ride on the session's identity and are offered only when it owns what they reach: an inbox\n * (§24.9), a social workspace (§27), the connections layer (§25). Named here so a dashboard can\n * tell them from an external `server.tool` it cannot enumerate. It also closes their namespaces: a\n * `configs` key in one that is not listed here is refused (`toolNameProblem`, ADR-1834), so a new\n * platform tool must be added here before any toolset can name it.\n */\nexport const PLATFORM_TOOLS = [\n \"email.inboxes\",\n \"email.read\",\n \"email.send\",\n \"phone.numbers\",\n \"phone.read\",\n \"phone.send\",\n \"crm.read\",\n \"crm.write\",\n \"social.accounts\",\n \"social.post\",\n \"social.status\",\n \"social.post_metrics\",\n \"connections.search\",\n \"connections.connect\",\n \"connections.status\",\n \"legal.verifications\",\n \"legal.verification\",\n \"legal.companies\",\n \"legal.company\",\n \"legal.documents\",\n \"legal.naics\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.balance\",\n \"wallet.transactions\",\n \"wallet.receipts\",\n \"wallet.quote\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.list\",\n \"card.show\",\n \"card.quote\",\n \"card.transactions\",\n \"card.spend\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n // The company's timezone (§20.6, ADR-0904): offered to every session; asks unless the owner sets it to allow.\n \"company.set_timezone\",\n // The company's logo (§20.7, ADR-1085): offered to every session; asks unless the owner sets it to allow.\n \"company.set_logo\",\n // The company's brand kit (ADR-1163): offered to every session; always asks, like the logo.\n \"company.set_brand\",\n // An app's key (§29.10, ADR-1004): minted only when a person approves the card that lists it.\n \"apps.request_access\",\n // A template app's own payments (§29.11): offered only to an agent whose toolset names them.\n \"payments\",\n \"payments_request\",\n // A key for an MCP server (§7.6, ADR-1623): the person types it into the card and their browser seals it.\n \"vault.request_secret\",\n // A withheld operator action (§7.7, ADR-1624): the agent proposes it, the person's browser runs it.\n \"operator.request\",\n // The identity's brokerage (§62.6): offered only with an active connection; the writes ask.\n \"trading.account\",\n \"trading.positions\",\n \"trading.orders\",\n \"trading.quote\",\n ...TRADING_WRITE_TOOLS,\n] as const;\n\n/**\n * Platform tools that publish, spend, file, reveal or change the company's settings, and therefore\n * default to `ask` unless the toolset says otherwise (§20.6, §27, §43.5, §44.4, §45.4). One list, so a bridge and a harness agree.\n */\nexport const ASK_BY_DEFAULT_TOOLS: ReadonlySet<string> = new Set([\n // Every phone is money by the minute (§53.8); a session grant waves the rest of the chat through.\n \"mobile\",\n // A data run is a paid scrape whose output the model reads: asked by default, so scraped text\n // cannot chain more paid runs unseen (§54).\n \"data_run\",\n // A video is up to dollars a call: its card is the price tag, seen before any spend (ADR-1472,\n // ADR-1611). A crew that renders unattended names it `allow` (the media blueprint's seats do).\n \"generate_video\",\n // A Mira edit is up to $1.48, held whole at submit: the card is its price tag (ADR-1310).\n \"edit_video\",\n // Training a character is a paid job that fixes a real-looking likeness from the photos it is\n // given: asked by default for the same reason as a data run, and so a person sees whose face.\n \"create_character\",\n // A media skill build runs paid sessions in the org (§57.4): the card is the go-ahead.\n \"build_media_skill\",\n // Listing the company for every other company is an owner's or admin's yes, each time (ADR-1747).\n \"list_as_template\",\n // So is moving its earnings out (ADR-1598).\n \"pay_out_earnings\",\n \"social.post\",\n \"social.cancel\",\n \"email.send\",\n \"phone.send\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n \"company.set_timezone\",\n \"company.set_logo\",\n \"company.set_brand\",\n \"apps.request_access\",\n // Money in on the owner's own Stripe account (§29.11, ADR-1572 as amended): every pay link and invoice is the owner's yes.\n \"payments_request\",\n \"vault.request_secret\",\n \"operator.request\",\n // Orders, cancels and closes move money at a broker (§62.6); live asks even under `allow` (D1).\n ...TRADING_WRITE_TOOLS,\n]);\n\n/**\n * The control plane's tools that spend money, move value or act in the outside world: the `SPENDS`\n * routes of `apps/api/src/mcp-tools.ts`, by tool name (a test there keeps the two equal).\n */\nexport const SPENDS_OR_PUBLISHES: ReadonlySet<string> = new Set([\n \"ads_activate_campaign\",\n \"ads_create_search_campaign\",\n \"connections_connect\",\n \"creator_publish_template\",\n \"creator_request_payout\",\n \"credits_change_subscription_plan\",\n \"credits_create_subscription\",\n \"credits_create_topup\",\n \"domains_purchase\",\n \"identities_cancel_card\",\n \"identities_cancel_trading_order\",\n \"identities_close_trading_position\",\n \"identities_create_company\",\n \"identities_create_post\",\n \"identities_issue_card\",\n \"identities_pay\",\n \"identities_place_trading_order\",\n \"identities_resend_member_link\",\n \"identities_reveal_credentials\",\n \"identities_send_email\",\n \"identities_send_sms\",\n \"identities_start_verification\",\n \"identities_submit_company\",\n \"identities_transfer\",\n \"media_create_clip\",\n \"media_create_skill_build\",\n \"media_create_conversation\",\n \"media_create_speech\",\n \"media_create_sound_effect\",\n \"media_create_music\",\n \"media_create_transcription\",\n \"social_data_create_run\",\n \"data_create_run\",\n \"mobile_devices_create\",\n \"media_generate_image\",\n \"media_generate_video\",\n \"media_create_mesh\",\n \"characters_create\",\n]);\n\n/** A control-plane call each person sees: it spends money or acts in the outside world. Any server's name. */\nconst seenEachTime = (name: unknown): boolean =>\n typeof name === \"string\" && [...SPENDS_OR_PUBLISHES].some((tool) => name === tool || name.endsWith(`.${tool}`) || name.endsWith(`__${tool}`));\n\n/**\n * Asks by default, yet may be granted for the chat: the phone (§53.8, ADR-1161). It is money by the\n * minute, not a publish, payment or filing whose arguments the model rewrites — and a phone is worked\n * in dozens of looks and taps, so a card per call would make it unusable. What a grant can spend is\n * bounded by one phone per session, its idle timer, and its maximum duration — at most 60 minutes on\n * an agent's phone (`MobileToolOptionsSchema`). The minutes settle against the session when the phone\n * ends; they are not held up front.\n */\nconst GRANTABLE_ASKERS: ReadonlySet<string> = new Set([\"mobile\"]);\n\n/**\n * Whether a tool may be granted for the rest of a chat (§7.3). Not one that publishes, pays or\n * files: a grant runs every later call with no card, and the model rewrites the arguments (ADR-0810).\n * That holds for the control plane's own such tools too, called directly or through the invoker\n * (`args.tool`). Nor a pause\n * (`asksAPerson`): a question, a toolset change or a plan is answered each time. Nor a template\n * install: each one hires a crew, so each is its own card (ADR-1104).\n */\nexport const grantable = (name: string, args: Record<string, unknown> = {}): boolean =>\n (GRANTABLE_ASKERS.has(name) || !ASK_BY_DEFAULT_TOOLS.has(name)) &&\n !asksAPerson(name) &&\n !namesInstall(name) &&\n !seenEachTime(name) &&\n !(invokesAnyTool(name) && (namesInstall(args[\"tool\"]) || seenEachTime(args[\"tool\"])));\n\n/** `edit_video`'s customer-facing name (§55). Customer strings read it from here, so a rename is one line. */\nexport const VIDEO_EDIT_NAME = \"Mira\";\n\n/**\n * Tools that take another tool's policy unless the toolset names them (ADR-1309): `edit_video` is\n * offered wherever `generate_video` is, as `allow`, `ask` or `deny` alike. Naming one in\n * `tools.configs` sets it on its own.\n *\n * A follower is NOT in `BUILTIN_TOOLS`, on purpose: the CLI and the dashboard write `enabled:false`\n * for every built-in they draw no row for, which would cut the follower off from its leader. So no\n * screen draws it, and `isToolName` still lets a config name it.\n */\nexport const FOLLOWS_TOOL: Readonly<Record<string, string>> = {\n edit_video: \"generate_video\",\n // Offered wherever posting is, so every persona's holder can call back its own post with no\n // template naming it (ADR-1613); it asks even beside an allowed `social.post`. Not drawn either.\n \"social.cancel\": \"social.post\",\n};\n\n/**\n * A video and its edit, each priced on its own card (ADR-1472, ADR-1611). No model-made change opens\n * either to `allow`: not a `request_tools` grant, and not the CEO's re-provisioning keeping an old\n * wiring's `allow`. Only a person's own toolset edit or a crew's declaration names them `allow`.\n */\nexport const PRICED_EACH_TIME: ReadonlySet<string> = new Set([\"generate_video\", ...Object.keys(FOLLOWS_TOOL)]);\n\n/**\n * Tools no policy can set to `allow` (`permissionOf`): each call is a signed-in owner's or admin's\n * decision. The logo is here because its API write is admin-only (ADR-1086): a member must not\n * change what every member sees by approving the agent's call.\n */\nexport const ALWAYS_ASKS: ReadonlySet<string> = new Set([\"apps.request_access\", \"company.set_logo\", \"company.set_brand\", \"list_as_template\", \"pay_out_earnings\", \"payments_request\", \"vault.request_secret\", \"operator.request\"]);\n\n/** The tool whose card seals a secret the person types (§7.6, ADR-1623): its allow carries the `credential`. */\nexport const REQUEST_SECRET = \"vault.request_secret\";\n\n/**\n * Tools no policy can set to `allow` (`permissionOf`), approvable by whoever answers the card:\n * `ALWAYS_ASKS`, plus `create_character`. Its `consent` attestation is a schema literal the model\n * fills in by itself, so only a person's yes on the card makes it true; with `allow` a training\n * would run, and bill, on consent nobody gave (ADR-1360). `deny` still forbids it.\n */\nexport const NEVER_ALLOWED: ReadonlySet<string> = new Set([...ALWAYS_ASKS, \"create_character\"]);\n\n/**\n * The tool that asks a person something (§7.1). Named here rather than spelled inline at each of\n * its reading sites, because `permissionOf` below has to recognise it and a typo there would\n * silently hand a model a tool that runs without ever asking anyone.\n */\nexport const ASK_OPERATOR = \"ask_operator\";\n\n/** The tool that proposes a change to this agent's own toolset (§7.4). Same rule, same reason. */\nexport const REQUEST_TOOLS = \"request_tools\";\n\n/** Plan mode's tools (§7.5): the compare-and-set on the plan, and the card that asks to build it. */\nexport const WRITE_PLAN = \"write_plan\";\nexport const PROPOSE_PLAN = \"propose_plan\";\n\n/**\n * The built-ins that ARE a pause: a person answers them, so none can ever be `allow`. `propose_plan`\n * is here because its allow is what leaves plan mode (§7.5): run unasked, it would record an\n * approval nobody gave and leave the session planning.\n */\nexport const asksAPerson = (name: string): boolean =>\n name === ASK_OPERATOR || name === REQUEST_TOOLS || name === PROPOSE_PLAN;\n\n/**\n * The control plane's tool invoker (`apps/api/src/mcp-meta.ts`): ONE tool that runs any of the\n * catalogue's 240, chosen by an argument, so it is enabled `allow` and the card is decided per\n * call from what it is invoking. Named here because two layers must recognise it and neither may\n * guess: the harness asks before a write (`harness-pi/src/catalogue.ts`), and a `scope: \"session\"`\n * grant for it is keyed on the TARGET in `args.tool` (`harness-pi/src/approvals.ts`) — a grant is\n * one tool name, and this name is every tool, so a grant for the bare invoker is dropped rather\n * than read as a standing licence to write anything for the rest of the chat with no card at all.\n *\n * Namespaced, because an MCP tool is `server.tool` and the server is the customer's to name.\n */\nexport const TOOLS_EXECUTE = \"tools_execute\";\n\n/** Its other half: the catalogue, searched instead of carried (`apps/api/src/mcp-meta.ts`). */\nexport const TOOLS_SEARCH = \"tools_search\";\n\n/**\n * The control-plane tools the CEO carries directly, beside the two above; the rest of the catalogue\n * it reaches only through `TOOLS_EXECUTE`. Why each one is here is `apps/web/app/lib/orchestrator.server.ts`.\n * It lives here because the catalogue's own descriptions have to agree with it: a carried tool's\n * description that names a sibling the CEO cannot call directly reads as \"call it directly\", and\n * the model did — `vetta__blueprints_list_installs`, answered \"not found\" (ADR-1025). The API's test\n * reads this list against the published descriptions (`apps/api/src/mcp-meta.test.ts`).\n */\nexport const ORCHESTRATOR_CORE_TOOLS = [\n \"agents_list\",\n \"agents_get\",\n \"sessions_create\",\n \"sessions_get\",\n \"sessions_list\",\n \"sessions_list_events\",\n \"files_list\",\n \"credits_get_balance\",\n // The plan: what the company pays and the credits it includes, which every cost answer starts from.\n \"credits_get_subscription\",\n \"blueprints_list_artifacts\",\n \"blueprints_list_installs\",\n \"blueprints_get_context\",\n // The three writes the dashboard's \"add\" buttons hand to the CEO as a prefilled chat (ADR-1473):\n // hire an agent, write a skill, set up a routine. Searched, the default model never found them —\n // staging 2026-10-23 on GLM 5.3 Flash: the skill and routine chats looped on `agents_list` and\n // made nothing, and the hire waited on a `request_tools` grant. Carried, the skill and the routine\n // run as they did through `tools_execute`.\n \"agents_create\",\n \"skills_push\",\n \"deployments_create\",\n // A rename or a new face for a hire. Through `tools_execute` it always cards (it is dangerous), so\n // the activated CEO's no-card hire (`CEO_HIRES`, ADR-1840) needs it carried.\n \"agents_patch\",\n] as const;\n\n/**\n * THE MODELS A NEW CEO STARTS ON, best first (ADR-0832): the owner's choice, then the fallback for a\n * deploy that does not serve it. Only the STARTING model: after creation it is the person's. The\n * dashboard's Hire page (`apps/web/app/lib/orchestrator.server.ts`) and `naive up`\n * (`packages/blueprints/src/tasks.ts`) both start a CEO on the first of these the deploy serves, so a\n * CEO made from the SDK is not put on whatever the catalogue happens to list first (ADR-1604).\n */\nexport const CEO_MODELS = [\"z-ai/glm-5.3-flash\", \"google/gemma-4-31B-it\", \"deepseek/deepseek-v4-flash-0731\"] as const;\n\n/**\n * THE BUILT-INS A CEO CARRIES WHILE ITS COMPANY IS SET UP (ADR-1108): asking, showing, planning and\n * reading what is set up. None of them needs a box, so a setup chat never buys one; everything that\n * does — a shell, files, a browser, apps, media — waits for activation. The control plane itself is\n * reached through the platform's own tool server, each call held to its route's `setup` flag. The API\n * refuses a setup CEO wired with anything else (`apps/api/src/setup-gate.ts`); the dashboard wires\n * it with exactly these (`apps/web/app/lib/orchestrator.server.ts`).\n */\nexport const SETUP_CEO_TOOLS: readonly string[] = [\n \"ask_operator\",\n \"show\",\n \"open_panel\",\n \"compose\",\n \"project_context\",\n \"list_agents\",\n \"write_plan\",\n \"propose_plan\",\n // The company's look, made in the chat once onboarding has the name (ADR-1163): each asks a person.\n \"company.set_logo\",\n \"company.set_brand\",\n];\n\nexport const invokesAnyTool = (name: string): boolean =>\n name === TOOLS_EXECUTE || name.endsWith(`.${TOOLS_EXECUTE}`) || name.endsWith(`__${TOOLS_EXECUTE}`);\n\n/** The template install (§31): the one held call whose `answers` a person may edit as they approve it (ADR-1030). */\nexport const INSTALL_TOOL = \"blueprints_apply_install\";\n\n/** Bare, namespaced (`vetta.…`) or in the MCP spelling (`vetta__…`) the invoker also runs (`bareToolName`). */\nexport const namesInstall = (name: unknown): boolean =>\n typeof name === \"string\" && (name === INSTALL_TOOL || name.endsWith(`.${INSTALL_TOOL}`) || name.endsWith(`__${INSTALL_TOOL}`));\n\n/** A ready media skill run as its channel (ADR-1407): the one install still the CEO's to ask for. */\nexport const isSkillChannel = (args: Record<string, unknown>): boolean =>\n typeof args[\"skill\"] === \"string\" && args[\"blueprint\"] === \"media\" && args[\"template\"] === \"faceless\";\n\n/**\n * A held call read as a template install — called directly or through the invoker, whose target's\n * arguments sit in `arguments` — or `null` for any other call. `answered` is the same call with its\n * `answers` replaced and nothing else touched: the one edit an approval may carry (§7, ADR-1030).\n */\nexport function installCall(\n name: string,\n args: Record<string, unknown>,\n): { args: Record<string, unknown>; answered: (answers: Record<string, unknown>) => Record<string, unknown> } | null {\n if (namesInstall(name)) return { args, answered: (answers) => ({ ...args, answers }) };\n const inner = args[\"arguments\"];\n if (!invokesAnyTool(name) || !namesInstall(args[\"tool\"]) || typeof inner !== \"object\" || inner === null || Array.isArray(inner)) return null;\n const own = inner as Record<string, unknown>;\n return { args: own, answered: (answers) => ({ ...args, arguments: { ...own, answers } }) };\n}\n\n/** The namespaces the platform's own tools live in (`PLATFORM_TOOLS`, `FOLLOWS_TOOL`): closed, unlike a connector's. */\nconst PLATFORM_NAMESPACES: ReadonlySet<string> = new Set(\n [...PLATFORM_TOOLS, ...Object.keys(FOLLOWS_TOOL)].filter((name) => name.includes(\".\")).map((name) => name.slice(0, name.indexOf(\".\"))),\n);\n\n/** `b` is `a` with two neighbouring letters swapped — the typo `emial` makes of `email`. */\nconst transposed = (a: string, b: string): boolean => {\n if (a.length !== b.length || a === b) return false;\n const i = [...a].findIndex((ch, n) => ch !== b[n]);\n return a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2);\n};\n\n/**\n * Why `name` cannot be a `configs` key, or `null` when it can (ADR-1834).\n *\n * A built-in, a follower, a platform tool, or a **namespaced** `<namespace>.<tool>` — the form every\n * tool that is not built in registers under: a connection contributes `<connector>.<tool>`\n * (`tracker.get_issue`), an MCP server `<server>.<tool>` (`vetta.agents_create`) and an app\n * `<app>.<tool>`. Those namespaces cannot be enumerated ahead of time — a template names an app or\n * connector before the org has it — so they stay open. The platform's own namespaces are closed: a\n * typo there (`email.sned`), a bare name that is no tool, or a platform namespace with two letters\n * swapped (`emial.send`) would leave a policy governing nothing, and an `ask` meant as an approval\n * gate silently absent, so each is refused by name.\n */\nexport function toolNameProblem(name: string): string | null {\n if ((BUILTIN_TOOLS as readonly string[]).includes(name) || name in FOLLOWS_TOOL || (PLATFORM_TOOLS as readonly string[]).includes(name)) return null;\n if (!/^[a-z0-9_-]+(\\.[a-z0-9_-]+)+$/i.test(name)) return `\\`${name}\\` is not a tool: name a built-in, or a namespaced \\`<namespace>.<tool>\\``;\n const namespace = name.slice(0, name.indexOf(\".\"));\n if (PLATFORM_NAMESPACES.has(namespace)) {\n const known = [...PLATFORM_TOOLS, ...Object.keys(FOLLOWS_TOOL)].filter((tool) => tool.startsWith(`${namespace}.`));\n return `\\`${name}\\` is not a tool; \\`${namespace}.*\\` is ${known.map((tool) => `\\`${tool}\\``).join(\", \")}`;\n }\n const meant = [...PLATFORM_NAMESPACES].find((platform) => transposed(platform, namespace));\n return meant === undefined ? null : `\\`${name}\\` is not a tool; did you mean \\`${meant}${name.slice(namespace.length)}\\`?`;\n}\n\n/** Is this a tool name a `configs` key may govern? (`toolNameProblem` says why not.) */\nexport const isToolName = (name: string): boolean => toolNameProblem(name) === null;\n\nexport const ToolConfigSchema = z.object({\n enabled: z.boolean(),\n permission: ToolPermissionSchema,\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * The toolset wrapper — the only `tools` schema (§6).\n *\n * Every tool's `config` is open — the web filters, the media pins and `apps.allowed_apps` are all\n * read leniently at the catalogue — except `browser`'s, which is the browser option object\n * (§32.2, `BrowserOptionsSchema`), and `mobile`'s (§53.8, `MobileToolOptionsSchema`): the runtime\n * answers a malformed one with a tool that cannot work, a refusal the author would never see, so\n * each is refused here, by field, wherever a toolset\n * is written (`POST/PATCH /v1/agents`, the CLI, a blueprint). Validated, not parsed: the stored\n * config keeps exactly the keys the author wrote, and the defaults are applied where it is read.\n */\nexport const ToolsetSchema = z\n .object({\n default_config: z.object({ permission: ToolPermissionSchema }),\n configs: z.record(z.string(), ToolConfigSchema),\n })\n .superRefine((tools, ctx) => {\n const checks = [[\"browser\", BrowserOptionsSchema], [\"mobile\", MobileToolOptionsSchema]] as const;\n for (const [name, schema] of checks) {\n const config = tools.configs[name]?.config;\n if (config === undefined) continue;\n for (const issue of schema.safeParse(config).error?.issues ?? []) {\n ctx.addIssue({ code: \"custom\", message: issue.message, path: [\"configs\", name, \"config\", ...issue.path] });\n }\n }\n });\nexport type Toolset = z.infer<typeof ToolsetSchema>;\n\n/**\n * The agent's policy for one tool. An unlisted tool takes `default_config.permission`, so a tool a\n * harness builds itself is governed by the same rule as one the platform injects (§6).\n *\n * IT LIVES IN `core` BECAUSE THREE DELIVERY PATHS APPLY IT and a tool reaching a model outside this\n * filter is a security hole: `harness-pi`'s catalogue gates its own tools with it, the session tool\n * bridge (`apps/runtime-do/src/bridge.ts`) filters what a boxed CLI is offered with it, and\n * `harness-vetta` filters the modules it is handed with it. Three copies is how one of them comes\n * to disagree, so there is one.\n */\nexport function permissionOf(toolset: Toolset): (name: string) => ToolPermission {\n return (name) => {\n const config = toolset.configs[name];\n if (config?.enabled === false) return \"deny\";\n const leader = FOLLOWS_TOOL[name];\n if (config === undefined && leader !== undefined) {\n // A follower that asks by default asks where its leader is allowed; it never widens a leader's ask or deny.\n const led = permissionOf(toolset)(leader);\n return led === \"allow\" && ASK_BY_DEFAULT_TOOLS.has(name) ? \"ask\" : led;\n }\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 session tool bridge (`apps/runtime-do/src/bridge.ts`, serving hermes and claude_code)\n * keeps only what this function calls `allow`, so it drops it without naming it. That is the\n * point: it cannot hold a `tools/call` open for the hours an answer takes (ADR-0400), and being\n * unable to say `allow` here is a stronger guarantee than a second copy of the rule in it.\n * `harness-pi` and `harness-vetta` (ADR-1276) read the `ask` and hold the call for a person.\n */\n if (asksAPerson(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // A key for an app is approved one card at a time, whatever the policy says (ADR-1009): with\n // `allow` an agent would mint its own keys with no person asked. `deny` still forbids it.\n if (NEVER_ALLOWED.has(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // Publishing, spending, filing and revealing default to approval; an explicit per-tool policy still\n // wins, and a default of `deny` stays `deny` — asking is never wider than what the agent was given.\n if (config?.permission) return config.permission;\n const fallback = toolset.default_config.permission;\n return fallback !== \"deny\" && ASK_BY_DEFAULT_TOOLS.has(name) ? \"ask\" : fallback;\n };\n}\n\n/**\n * What plan mode offers besides a tool whose module published `readOnly: true` (§7.5): asking,\n * the plan's two tools, and reading — the box, the web, the board, the roster, the library.\n */\nexport const PLAN_READ_ONLY: ReadonlySet<string> = new Set([\n ASK_OPERATOR,\n WRITE_PLAN,\n PROPOSE_PLAN,\n \"read\",\n \"ls\",\n \"find\",\n \"web_search\",\n \"web_fetch\",\n \"board_read\",\n \"list_agents\",\n \"read_skill\",\n \"find_files\",\n \"view_image\",\n \"session_spend\",\n \"project_context\",\n]);\n\n/**\n * PLAN MODE, AS A POLICY OVER THE AGENT'S OWN (§7.5). It only narrows: in plan mode a tool that is\n * neither on `PLAN_READ_ONLY` nor read-only by its own published hint is `deny`, which every\n * delivery path already reads as \"never built, never offered\". Everything else answers to `policy`\n * unchanged, so an agent that denies `web_search` still has none while planning.\n *\n * A FUNCTION, NOT A TOOLSET. A narrowed `Toolset` would be written back into the session's pin\n * (`runtime-do loop.ts` keeps a grant that way) and read off storage by the bridge, so plan mode\n * would outlive itself. Applied at each `permissionOf` site: the pi catalogue, the bridge and\n * `harness-vetta`. `readOnly` is the site's own knowledge of its modules.\n */\nexport function planPolicy(\n mode: SessionMode,\n policy: (name: string) => ToolPermission,\n readOnly: (name: string) => boolean,\n): (name: string) => ToolPermission {\n return (name) => {\n // THE PLAN'S OWN TWO ANSWER TO NO DEFAULT. An agent whose default is `deny` would otherwise plan\n // with no way to write the plan or put it to anyone, and one whose default is `ask` would park a\n // card on every write. They are only offered where a plan applies (`runtime-do plan.ts`).\n if (name === WRITE_PLAN) return \"allow\";\n if (name === PROPOSE_PLAN) return \"ask\";\n if (mode === \"build\") return policy(name);\n return PLAN_READ_ONLY.has(name) || readOnly(name) ? policy(name) : \"deny\";\n };\n}\n\n/**\n * Does this toolset carry an `ask_operator` a harness with no approval seam would have to serve?\n *\n * Read by NAME, and only when the toolset NAMES IT. `permissionOf` collapses `allow` to `ask` for\n * this tool, so a toolset that never mentions it still answers `ask` — and a gate that read the\n * bare answer would refuse every session and every roster on `hermes` and `claude_code` over a\n * capability their loops never publish (`bridge.ts` and `harness-vetta` keep only `allow`).\n *\n * It lives here because two gates ask it — `startSession` before any spend, and roster admission\n * one save earlier — and they were written apart: the roster's asked only about a literal\n * `permission: \"ask\"`, which `ask_operator` never carries, so a member configured with it saved\n * clean and then had the tool silently dropped at delegation instead of being refused. Two gates\n * asking one question is how one of them comes to answer it differently.\n */\nexport const asksOperator = (toolset: Toolset): boolean =>\n [ASK_OPERATOR, REQUEST_TOOLS].some(\n (name) => toolset.configs[name] !== undefined && permissionOf(toolset)(name) !== \"deny\",\n );\n\n/**\n * The `computerId` a session's tools are built against before its sandbox exists. A box is bought\n * by the first tool call that needs one, never at `POST /v1/sessions` (ADR-0099 → `box.ts`), so\n * until then this stands in for the id and the gated compute port swaps it for the real one. A\n * tool that only *records* the id (the browser) must treat it as \"no box yet\", not as a box.\n */\nexport const PENDING_BOX = \"pending\";\n\n/**\n * The `computerId` a hosted Vetta session's tools see: no computer, but an in-isolate workspace\n * answering `ctx.compute` (`harness-vetta/workspace-compute.ts`, ADR-1274). Not `\"\"`, which every\n * tool reads as \"nowhere to read or write\". The workspace lives in the session Durable Object's\n * ~128 MB heap and has no per-call RPC limit, so the file tools size their transfers to it\n * rather than to a box (`packages/tools/src/transfer.ts`).\n */\nexport const WORKSPACE_COMPUTER = \"workspace\";\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/** Human-facing mail sent when a hosted run yields control or finishes a turn. */\nexport const AgentNotificationsSchema = z\n .object({\n email: z.email().nullable(),\n approvals: z.boolean(),\n questions: z.boolean(),\n updates: z.boolean(),\n })\n .superRefine((settings, ctx) => {\n if (settings.email === null && (settings.approvals || settings.questions || settings.updates)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"email\"],\n message: \"an email address is required when a notification is enabled\",\n });\n }\n });\nexport type AgentNotifications = z.infer<typeof AgentNotificationsSchema>;\n\nexport const DEFAULT_AGENT_NOTIFICATIONS: AgentNotifications = {\n email: null,\n approvals: false,\n questions: false,\n updates: false,\n};\n\n/**\n * `slug` floats to the latest version at session start; `slug@N` is an immutable pin (§13). A\n * `naive/` prefix addresses the platform's catalogue (§31.9) instead of the organization's skills;\n * `naive/` alone names nothing.\n */\nexport const SkillRefSchema = z.string().regex(/^(naive\\/)?[a-z0-9][a-z0-9-]*(@\\d+)?$/, {\n error: \"expected `slug`, `slug@N`, `naive/slug` or `naive/slug@N`\",\n});\n\nconst SECRET_HEADER = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)$/i;\n\nexport const McpServerSchema = z\n .object({\n name: z.string().min(1).max(64),\n url: z.url().startsWith(\"https://\", { error: \"an MCP server URL must be HTTPS\" }),\n headers: z.record(z.string().max(128), z.string().max(4096)).optional(),\n })\n .superRefine((server, ctx) => {\n let url: URL | null = null;\n try {\n url = new URL(server.url);\n } catch {\n // The field-level URL validator reports the malformed value.\n }\n if (url && (url.username !== \"\" || url.password !== \"\")) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"url\"],\n message: \"credentials belong in a vault-bound MCP credential, not the server URL\",\n });\n }\n for (const name of Object.keys(server.headers ?? {})) {\n if (SECRET_HEADER.test(name)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"headers\", name],\n message: \"credentials belong in a vault-bound MCP credential, not agent config\",\n });\n }\n }\n });\n\n/**\n * Historical versions are data, not new configuration. They retain the schema that was valid when\n * written so a stricter create/patch boundary cannot turn an existing agent into a runtime 500.\n * The MCP transport still refuses plaintext before opening a socket or sending a credential.\n */\nexport const StoredMcpServerSchema = z.object({\n name: z.string(),\n url: z.url(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * One roster member of a team (§28). Four forms, and the bare `agt_…` string normalises to the\n * object form **at parse**, so exactly one shape reaches storage, validation and the response —\n * nothing downstream has to ask \"which spelling is this\".\n *\n * `self` is the coordinator delegating to a copy of itself; `advisor` is a bare model with no agent\n * behind it, so it names a `model` instead of an `id`.\n */\nexport const RosterEntrySchema = z.union([\n idOf(\"agt\").transform((id) => ({ type: \"agent\" as const, id })),\n z.object({\n type: z.literal(\"agent\"),\n id: idOf(\"agt\"),\n version: z.number().int().positive().optional(),\n }),\n z.object({ type: z.literal(\"self\") }),\n z.object({ type: z.literal(\"advisor\"), model: z.string().min(1) }),\n]);\nexport type RosterEntry = z.infer<typeof RosterEntrySchema>;\n\n/** A roster names at most one of each of these: they are singletons, not addressable members. */\nconst SINGLETON_ENTRIES = [\"self\", \"advisor\"] as const;\n\n/** The coordinator declaration. `board` opts into the shared board; its columns are fixed (§28). */\nexport const MultiagentSchema = z.object({\n type: z.literal(\"coordinator\"),\n agents: z\n .array(RosterEntrySchema)\n .min(1)\n .max(20)\n .refine(\n (roster) => SINGLETON_ENTRIES.every((t) => roster.filter((e) => e.type === t).length <= 1),\n { error: \"a roster carries at most one `self` and at most one `advisor` entry\" },\n ),\n board: z.boolean().optional(),\n});\nexport type Multiagent = z.infer<typeof MultiagentSchema>;\n\n/**\n * `multiagent` on the wire. `null` is required, not cosmetic: the coordinator echoes\n * `\"multiagent\": null` on every non-coordinator agent, and a `PATCH` of `null` is how a roster is\n * cleared — which `false` cannot say, because `false` is also the create-time default.\n */\nexport const MultiagentField = z.union([z.boolean(), MultiagentSchema, z.null()]);\nexport type MultiagentConfig = z.infer<typeof MultiagentField>;\n\n/** The one reading of the three arms: is there a team here, and what is it? */\nexport function normaliseMultiagent(value: MultiagentConfig): Multiagent | null {\n if (value === true) return { type: \"coordinator\", agents: [], board: false };\n if (value === false || value === null) return null;\n return value;\n}\n\n/**\n * `handoffs` on the wire (§28.12): who this agent may `send_to_agent`. `true` — any agent of\n * the organization; `false` — nobody, and none of the agent tools are offered; `\"team\"` — the agents\n * on its own `multiagent` roster; a list of agent **names** — those. Every policy but `false` also\n * reaches the CEO (`handoffAllows`). The create-time default is `true`, and a version minted before\n * the field existed reads as `true` (`handoffsOf`), so an agent nobody configured can reach anyone.\n */\nexport const HandoffsField = z.union([z.boolean(), z.literal(\"team\"), z.array(z.string().min(1)).max(50)]);\nexport type Handoffs = z.infer<typeof HandoffsField>;\n\n/** The field as every reader takes it: absent is `true`. */\nexport const handoffsOf = (config: { handoffs?: Handoffs | undefined }): Handoffs => config.handoffs ?? true;\n\n/** Whether the agent tools are offered at all: only `false` opts out, since `[]` still reaches the CEO. */\nexport const handoffsEnabled = (handoffs: Handoffs): boolean => handoffs !== false;\n\n/**\n * Whether a session of this version can run team members: it carries a `multiagent` roster, or its\n * `handoffs` offer `send_to_agent`, whose `wait: true` opens a member thread (§28.7). An outcome\n * refuses such a session in its first release (§58.2, ADR-1420).\n */\nexport const runsTeamMembers = (version: { multiagent: MultiagentConfig; handoffs?: Handoffs | undefined }): boolean =>\n normaliseMultiagent(version.multiagent) !== null || handoffsEnabled(handoffsOf(version));\n\n/**\n * Whether `name` is a seat this policy lets the agent reach — never itself (§28.15). `team` is the\n * roster as names, which only the caller can resolve; under any other policy it is not read. `ceo`\n * is the name of the org's agent marked `ORCHESTRATOR_ROLE` (or `null` if there is none): every\n * policy but `false` reaches it, named or not (§28.12, ADR-0842).\n */\nexport const handoffAllows = (\n handoffs: Handoffs,\n self: string,\n name: string,\n team: readonly string[],\n ceo: string | null,\n): boolean =>\n name !== self &&\n handoffs !== false &&\n (handoffs === true || name === ceo || (handoffs === \"team\" ? team : handoffs).includes(name));\n\n/** The config carried by an agent and frozen into every version (§12). */\nconst agentConfigShape = {\n model: z.string(),\n window: WindowSchema,\n system: z.string(),\n tools: ToolsetSchema,\n mcp_servers: z.array(StoredMcpServerSchema),\n skills: z.array(SkillRefSchema),\n multiagent: MultiagentField,\n /** Optional on the type so a version minted before §28.15 still parses; read it through `handoffsOf`. */\n handoffs: HandoffsField.optional(),\n /** §46.6: when set, every turn picks one of its options and `model` is the default. Absent before it existed. */\n model_selection: ModelSelectionPolicySchema.nullable().optional(),\n budget: BudgetSchema,\n /** Absent on older versions; the runtime treats it as all notifications off. */\n notifications: AgentNotificationsSchema.optional(),\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","/** Shared wire primitives — every canonical object is built from these (canonical-spec §§1-2, §9, §11, §17). */\n\nimport { z } from \"zod\";\nimport { AUDIT_ACTIONS } from \"./audit-actions\";\nimport { isId, type IdPrefix } from \"../id\";\n\n/** A string that is a well-formed id of exactly this prefix. */\nexport const idOf = (prefix: IdPrefix): z.ZodString =>\n z.string().refine((value) => isId(prefix, value), { error: `expected a ${prefix}_ id` });\n\n/** RFC 3339 UTC, `_at` suffix on the wire (§9). */\nexport const Timestamp = z.iso.datetime({ offset: true });\n\n/** Integer micro-USD (§1). The `MicroUsd` brand is for arithmetic in `core`; the wire is an integer. */\nexport const MicroUsdField = z.number().int();\n\nexport const Metadata = z.record(z.string(), z.unknown());\n\n/**\n * A JSON Schema document for a session's answer (`output_schema`, §16).\n *\n * Constrained to an object schema with at least one property, because the schema *becomes* the\n * `submit_output` tool's parameters and a tool call's arguments are always a JSON object: a\n * `{\"type\":\"string\"}` schema can never be satisfied by any call, and a `{}` schema is satisfied by\n * everything. Both would end the session with a silent `structured_output: null` (or an empty\n * document) that `structured_output_required` cannot even catch — the exact failure §16 exists to\n * delete. Refuse them at the boundary instead.\n */\nexport const JsonSchemaDocument = z\n .record(z.string(), z.unknown())\n .refine((schema) => schema.type === \"object\", {\n error: 'an output schema must be a JSON Schema with \"type\": \"object\"',\n })\n .refine(\n (schema) =>\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n Object.keys(schema.properties).length > 0,\n { error: \"an output schema must declare at least one property\" },\n );\n\n/** Completion window — these three strings, everywhere (§4). */\nexport const WindowSchema = z.enum([\"immediate\", \"priority\", \"loose\"]);\nexport type Window = z.infer<typeof WindowSchema>;\n\n/** The five metered token tiers (§11). */\nexport const TOKEN_TIERS = [\"input\", \"cache_write\", \"cache_read\", \"output\", \"reasoning\"] as const;\nexport const TokenTierSchema = z.enum(TOKEN_TIERS);\n\n/**\n * The tiers a **non-model** call bills under (§11). `search` is one priced retrieval call, `media`\n * one priced media job — the tier name IS the component on `GET /v1/agents/{id}/spend?by=component`,\n * so these are capability names a customer reads, never vendor names.\n */\n// core-gaps: contracts — `browser` (minutes + hosted actions, §32.8), `storage` (bucket-days, §38.3).\n// `email` is one outbound email send (§11, ADR-0818); `voice` is live voice call minutes (§35.5, ADR-1151);\n// `mobile` is one mobile device's minutes (§53.7).\nexport const TOOL_TIERS = [\"search\", \"media\", \"social\", \"browser\", \"storage\", \"email\", \"voice\", \"mobile\"] as const;\nexport type ToolTier = (typeof TOOL_TIERS)[number];\n\n/**\n * Every tier a ledger line item can carry: the five token tiers, the sandbox (`computer`), and the\n * priced tool tiers. `packages/billing` has emitted `computer` since ADR-0160 while this enum still\n * only admitted the five, so a sandbox debit failed validation on `GET /v1/credits/ledger` — the\n * wire schema was narrower than the money the ledger already stored.\n */\nexport const LINE_ITEM_TIERS = [...TOKEN_TIERS, \"computer\", ...TOOL_TIERS] as const;\nexport const LineItemTierSchema = z.enum(LINE_ITEM_TIERS);\nexport type LineItemTier = z.infer<typeof LineItemTierSchema>;\nexport const TokenUsageSchema = z.object({\n input: z.number().int().nonnegative(),\n cache_write: z.number().int().nonnegative(),\n cache_read: z.number().int().nonnegative(),\n output: z.number().int().nonnegative(),\n reasoning: z.number().int().nonnegative(),\n});\nexport type TokenUsage = z.infer<typeof TokenUsageSchema>;\n\n/**\n * The acting actor, threaded through auth → every mutation, audit entry and ledger row (§17).\n *\n * `system` names an effect no API principal caused — a credit reconciled from a verified payment\n * webhook, the initial test-tier grant, a debit committed by the durable loop. Its `id` names the\n * subsystem (`\"payment_webhook\"`, `\"bootstrap\"`), never a stored object (ADR-0065).\n */\nexport const PrincipalSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"user\"), id: idOf(\"usr\") }),\n z.object({ type: z.literal(\"key\"), id: idOf(\"key\") }),\n z.object({ type: z.literal(\"system\"), id: z.string().min(1) }),\n]);\nexport type Principal = z.infer<typeof PrincipalSchema>;\n\n/**\n * The audited actions (§17). The list is `./audit-actions`: one definition, so what the wire\n * validates and what the emitters write cannot diverge.\n */\nexport const AuditActionSchema = z.enum(AUDIT_ACTIONS);\n\n/** Cursor pagination envelope (§9). */\nexport const page = <T extends z.ZodType>(item: T) =>\n z.object({ data: z.array(item), has_more: z.boolean(), next_cursor: z.string().nullable() });\nexport const PAGE_LIMIT_DEFAULT = 20;\nexport const PAGE_LIMIT_MAX = 100;\n\n/** The one supported API version; every surface reads it from here rather than re-declaring it (§9). */\nexport const API_VERSION = \"2026-09-30\";\n\n/**\n * Every `Vetta-Version` date a caller may pin, oldest first (§9). A date outside this list is a\n * typo or a guess, and answering it with a 200 served under some *other* version is exactly the\n * quiet-success class this surface exists to refuse — so `readVersion` 400s on it.\n */\nexport const API_VERSIONS = [\"2026-01-01\", \"2026-09-01\", API_VERSION] as const;\n\n/**\n * From this pin onward the request contract is **strict**: unknown body keys and unknown query\n * parameters are rejected rather than silently dropped (readiness entry 7). Older pins keep the\n * lenient behaviour so a client already sending junk is not broken by a deploy.\n */\nexport const STRICT_REQUEST_VERSION = \"2026-09-01\";\n\n/**\n * From this pin onward a question's fields may be `connect` (ADR-1102) and `media` (ADR-1103). An\n * older pin parses only `text` and `choice`, and strictly: one new field in one parked question\n * threw on its whole session list. So an older pin is served each new field as `text` (ADR-1105).\n */\nexport const QUESTION_KINDS_VERSION = \"2026-09-30\";\n\n/** Published event-replay window (§8). */\nexport const EVENT_RETENTION_HOURS = 72;\n","/**\n * The 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. The one\n * exception is `AUDIT_ACTIONS_OPERATOR`: written by the operator console straight to the\n * database, with no API route to claim it.\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 \"crm.contact_deleted\",\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 /**\n * An owner or admin said yes to a call no policy may allow (`ALWAYS_ASKS`), with its arguments: the\n * record a route bound to that yes checks the agent's call against (ADR-1747).\n */\n \"tool.approved\",\n] as const;\n\n/** P1: the control plane a customer pays for and an auditor asks about first. */\nexport const AUDIT_ACTIONS_P1 = [\n \"agent.created\",\n \"agent.deleted\",\n \"agent.rollback\",\n \"computer.created\",\n \"computer.deleted\",\n \"computer.paused\",\n \"computer.resumed\",\n \"computer.snapshot_created\",\n \"computer.snapshot_deleted\",\n \"computer.updated\",\n \"computer.taken_over\",\n \"computer.handed_back\",\n \"browser.live_view_opened\",\n /** Mobile devices (`canonical-spec §53`). `act` is the working surface, unfiled like `exec`. */\n \"mobile_device.created\",\n \"mobile_device.updated\",\n \"mobile_device.deleted\",\n \"mobile_device.live_view_opened\",\n \"deployment.created\",\n \"deployment.updated\",\n \"deployment.deleted\",\n \"deployment.paused\",\n \"deployment.resumed\",\n \"deployment.run\",\n \"file.created\",\n \"file.published\",\n \"file.deleted\",\n \"member.invited\",\n \"org.updated\",\n \"subscription.updated\",\n \"subscription.canceled\",\n \"subscription.plan_changed\",\n \"session.budget_updated\",\n \"session.cancelled\",\n \"skill.created\",\n \"skill.version_created\",\n \"skill.deleted\",\n \"webhook.created\",\n \"webhook.updated\",\n \"webhook.deleted\",\n] as const;\n\n/** P2: identity and credentials. Not one of these was recorded anywhere before this change. */\nexport const AUDIT_ACTIONS_P2 = [\n \"identity.created\",\n \"identity.updated\",\n \"identity.deleted\",\n \"identity.granted\",\n \"identity.revoked\",\n \"vault.created\",\n \"vault.deleted\",\n \"credential.sealed\",\n \"credential.destroyed\",\n \"connection.created\",\n \"connection.disconnected\",\n \"connection.auth_config_created\",\n \"connection.auth_config_deleted\",\n \"domain.created\",\n \"domain.purchased\",\n \"domain.purchase_refunded\",\n \"domain.verified\",\n \"domain.deleted\",\n \"email.created\",\n \"email.deleted\",\n /** An inbox's wake turned on or off (ADR-1749). */\n \"email.updated\",\n \"phone.created\",\n \"phone.deleted\",\n \"phone.updated\",\n \"social.activated\",\n \"social.post_created\",\n \"social.post_deleted\",\n \"mcp_session.created\",\n \"mcp_session.revoked\",\n] as const;\n\n/**\n * P3: apps — hosted web applications (`canonical-spec §29`), and the install that applies a\n * declaration across them (§29.6). The install's row is the only trace of *which writer* moved a\n * whole organization's configuration, so it is exactly the kind of mutation §17 exists for.\n */\nexport const AUDIT_ACTIONS_P3 = [\n \"app.created\",\n \"app.updated\",\n \"app.deleted\",\n \"app.deployed\",\n \"app.secret_set\",\n \"app.secret_deleted\",\n \"app.domain_connected\",\n \"app.domain_disconnected\",\n \"app.db_queried\",\n /** A ticket was minted that lets one browser past an app's own operator gate (§29.7). */\n \"app.entered\",\n /** The dashboard password was read — the one audited reveal of an app secret (§29.7, ADR-0656). */\n \"app.access_read\",\n /** The dashboard password was regenerated (and a lost `DASHBOARD_TOKEN` copy repaired). */\n \"app.access_rotated\",\n \"app.payments_onboarding\",\n \"app.payments_refunded\",\n /** Money in without a store (ADR-1572 as amended): a pay link made or turned off, an invoice sent or voided. */\n \"app.payments_link_created\",\n \"app.payments_link_changed\",\n \"app.payments_invoice_sent\",\n /** A link was minted that serves one file's bytes to anyone holding it, for seven days (§40). */\n \"file.linked\",\n /** A trained persona (§33.6): a paid training started, or the character deleted and its name freed. */\n \"character.created\",\n \"character.updated\",\n \"character.deleted\",\n \"blueprint.installed\",\n /** An install's answers were rewritten — what a template's crew is told about the business (§31.8). */\n \"blueprint.context_updated\",\n /** A template taken out of the company: its crew fired, its row gone (§29.6, ADR-1513). */\n \"blueprint.removed\",\n /** A company's crew saved as a private template of the organization (§61, ADR-1552). */\n \"blueprint.duplicated\",\n /** A private template submitted to the marketplace for review (ADR-1554). */\n \"blueprint.submitted\",\n /** The one creator-program effect inside a tenant: a new organization attributed to a creator (§42.6). */\n \"referral.attributed\",\n /** A company's marketplace earnings transferred to its own Stripe account (ADR-1598). */\n \"earnings.paid_out\",\n /** The owner set up, or went on setting up, the Stripe account the company's earnings are paid to (ADR-1598). */\n \"earnings.account_set_up\",\n /** P4 outcomes (`canonical-spec §58.2`): a rubric written, and one held over a session. */\n \"outcome.created\",\n \"session.outcome_set\",\n] as const;\n\n/** Identity-owned ads, legal, wallet, cards and trading (`canonical-spec §43.4`, `§44.3`, `§45.3`, `§62.7`). */\nexport const AUDIT_ACTIONS_PRIMITIVES = [\n \"ad_campaign.created\",\n \"ad_campaign.activated\",\n \"ad_campaign.paused\",\n \"legal_verification.started\",\n \"legal_member.completed\",\n \"legal_member.link_resent\",\n \"legal_company.created\",\n \"legal_company.submitted\",\n \"wallet.created\",\n \"wallet.policy_updated\",\n \"wallet.frozen\",\n \"wallet.unfrozen\",\n \"wallet.funded\",\n \"wallet.transferred\",\n \"wallet.swept\",\n \"wallet.paid\",\n \"card.issued\",\n \"card.retried\",\n \"card.cancelled\",\n \"card.refunded\",\n /** The one read that files: a credential left the vault for a caller (§45.3). */\n \"card.credentials_revealed\",\n /** The identity's brokerage (`canonical-spec §62.7`). Never a token, envelope or OAuth state in `metadata`. */\n \"trading_connection.connect_started\",\n \"trading_connection.connected\",\n \"trading_connection.disconnected\",\n \"trading_order.placed\",\n \"trading_order.canceled\",\n \"trading_position.closed\",\n] as const;\n\n// core-gaps: contracts — the mutations §32, §36–§38 make audit rows of (REST passthrough and object\n// puts/gets are audit rows, not stream events).\nexport const AUDIT_ACTIONS_CORE_GAPS = [\n \"browser.context_saved\",\n \"browser.context_granted\",\n \"browser.context_revoked\",\n \"browser.credential_stored\",\n // core-gaps: U2-browser-api — §32.8's session events, audit-only when no session drove them.\n \"browser.session_opened\",\n \"browser.session_closed\",\n \"file.imported\",\n /** Files moved into or out of a folder, or a folder renamed, merged or dissolved (§36.4). */\n \"file.moved\",\n \"app.db_rest\",\n \"app.db_migrated\",\n \"app.bucket_created\",\n \"app.bucket_deleted\",\n \"app.storage_put\",\n \"app.storage_get\",\n // core-gaps: U9-storage\n \"app.storage_deleted\",\n] as const;\n\n/**\n * Filed in a customer's log by the operator console (`apps/central`), which writes the ledger\n * directly rather than through a route. A positive operator credit is `credits.topped_up` with\n * `metadata.source: \"central_operator_grant\"` like every other free grant; only a correction that\n * takes money back has its own action (ADR-1193).\n */\nexport const AUDIT_ACTIONS_OPERATOR = [\"credits.adjusted\"] as const;\n\nexport const AUDIT_ACTIONS = [\n ...AUDIT_ACTIONS_SHIPPED,\n ...AUDIT_ACTIONS_P1,\n ...AUDIT_ACTIONS_P2,\n ...AUDIT_ACTIONS_P3,\n ...AUDIT_ACTIONS_PRIMITIVES,\n ...AUDIT_ACTIONS_CORE_GAPS,\n ...AUDIT_ACTIONS_OPERATOR,\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","/**\n * core-gaps: contracts — the managed browser's wire objects (`canonical-spec §32`). One option\n * object read by `POST /v1/computers`, the `browser` tool's config and `browser_session`.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport { RoleSchema } from \"./org\";\n\n/** D2: the cap stays 360 minutes. */\nexport const BROWSER_MAX_TIMEOUT_MINUTES = 360;\nexport const BROWSER_REGIONS = [\"us-west\", \"us-east\", \"eu-central\", \"ap-southeast\"] as const;\nexport const BROWSER_OS = [\"windows\", \"mac\", \"linux\", \"mobile\", \"tablet\"] as const;\n/** The `browser` tool's `action` names (§32.7): the §32.4 page actions plus the saved-login flows. */\nexport const BROWSER_TOOL_ACTIONS = [\n \"goto\",\n \"click\",\n \"type\",\n \"extract\",\n \"act\",\n \"observe\",\n \"links\",\n \"screenshot\",\n \"login\",\n \"signup\",\n \"save_context\",\n] as const;\n\n/**\n * `allowed_domains` is a *narrowing* control, not a grant: omit it and the browser reaches the whole\n * public web. It is not what keeps the browser off private infrastructure — `isBlockedHost` bars\n * loopback, private, link-local and cloud-metadata hosts on every action regardless of this list, so\n * the open default widens reach to the public internet only. An explicit `[]` is still refused: a\n * caller who names the field means to bound it, and silently reaching nothing is the trap this\n * default exists to avoid.\n *\n * `proxy: true` with a `\"*\"` allowlist is refused: residential egress needs a bounded destination,\n * and because `\"*\"` is now the default, a proxied browser must name its domains outright.\n * `ask_actions` is read by the `browser` tool alone: with the tool at `allow`, a call whose action is\n * listed pauses for approval and every other one runs (§32.7).\n */\nexport const BrowserOptionsSchema = z\n .object({\n allowed_domains: z.array(z.string().min(1)).min(1).default([\"*\"]),\n timeout_minutes: z.number().int().min(1).max(BROWSER_MAX_TIMEOUT_MINUTES).default(15),\n region: z.enum(BROWSER_REGIONS).default(\"us-west\"),\n keep_alive: z.boolean().default(false),\n viewport: z\n .object({ width: z.number().int().positive(), height: z.number().int().positive() })\n .optional(),\n os: z.enum(BROWSER_OS).optional(),\n block_ads: z.boolean().default(false),\n solve_captchas: z.boolean().default(true),\n stealth: z.boolean().default(false),\n allow_writes: z.boolean().default(false),\n allow_extract: z.boolean().default(false),\n context_name: z.string().min(1).max(64).optional(),\n persist_context: z.boolean().default(false),\n human_login: z.boolean().default(false),\n proxy: z.boolean().default(false),\n ask_actions: z.array(z.enum(BROWSER_TOOL_ACTIONS)).default([\"signup\"]),\n })\n .refine((options) => !(options.proxy && options.allowed_domains.includes(\"*\")), {\n error: \"a proxied browser needs a bounded allow-list, not *\",\n path: [\"proxy\"],\n });\nexport type BrowserOptions = z.infer<typeof BrowserOptionsSchema>;\n// core-gaps: U2-browser-api — what a caller sends: every field may be omitted.\nexport type BrowserOptionsInput = z.input<typeof BrowserOptionsSchema>;\n\nexport const BrowserSessionStatusSchema = z.enum([\"creating\", \"active\", \"closed\", \"error\"]);\n\nexport const BrowserSessionSchema = z.object({\n id: idOf(\"brw\"),\n object: z.literal(\"browser_session\"),\n computer_id: idOf(\"cmp\").nullable(),\n /** The agent session that opened it, if an agent did; a REST caller's browser carries `null`. */\n session_id: idOf(\"ses\").nullable(),\n status: BrowserSessionStatusSchema,\n allowed_domains: z.array(z.string()),\n region: z.enum(BROWSER_REGIONS),\n context_id: idOf(\"bct\").nullable(),\n context_backed: z.boolean(),\n timeout_at: Timestamp,\n opened_at: Timestamp,\n closed_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type BrowserSession = z.infer<typeof BrowserSessionSchema>;\n\n/** A bearer credential for one browser (§32.3): minted for a person, never stored, never in another object. */\nexport const BrowserLiveViewSchema = z.object({\n object: z.literal(\"browser_live_view\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type BrowserLiveView = z.infer<typeof BrowserLiveViewSchema>;\n\n/** A saved login, identity-scoped like a vault (D4). */\nexport const BrowserContextSchema = z.object({\n id: idOf(\"bct\"),\n object: z.literal(\"browser_context\"),\n identity_id: idOf(\"idn\"),\n name: z.string(),\n service: z.string().nullable(),\n created_at: Timestamp,\n last_used_at: Timestamp.nullable(),\n});\nexport type BrowserContext = z.infer<typeof BrowserContextSchema>;\n\nexport const BrowserGranteeTypeSchema = z.enum([\"agent\", \"role\"]);\n\nexport const BrowserGrantSchema = z.object({\n id: idOf(\"bgr\"),\n object: z.literal(\"browser_grant\"),\n context_id: idOf(\"bct\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n created_at: Timestamp,\n});\nexport type BrowserGrant = z.infer<typeof BrowserGrantSchema>;\n\nexport const SaveBrowserContextSchema = z.object({\n name: z.string().min(1).max(64),\n identity_id: idOf(\"idn\"),\n service: z.string().min(1).optional(),\n});\n\nexport const CreateBrowserGrantSchema = z.object({\n identity_id: idOf(\"idn\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n});\n\nconst Selector = z.string().min(1);\nconst Instruction = z.string().min(1).max(4_096);\n\n/** §32.4 — the discriminant is `action`, the same word the tool uses. */\nexport const BrowserActionRequestSchema = z.discriminatedUnion(\"action\", [\n z.object({ action: z.literal(\"goto\"), url: z.string().url() }),\n z.object({ action: z.literal(\"click\"), selector: Selector }),\n z.object({ action: z.literal(\"type\"), selector: Selector, text: z.string() }),\n z.object({\n action: z.literal(\"extract\"),\n instruction: Instruction.optional(),\n selector: Selector.optional(),\n schema: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n action: z.literal(\"act\"),\n instruction: Instruction,\n variables: z.record(z.string(), z.string()).optional(),\n }),\n z.object({ action: z.literal(\"observe\"), instruction: Instruction }),\n z.object({\n action: z.literal(\"links\"),\n contains: z.string().optional(),\n limit: z.number().int().min(1).max(200).default(50),\n }),\n z.object({ action: z.literal(\"screenshot\") }),\n]);\nexport type BrowserActionRequest = z.infer<typeof BrowserActionRequestSchema>;\nexport const BROWSER_ACTIONS = BrowserActionRequestSchema.options.map(\n (option) => option.shape.action.value,\n);\n\nexport const BrowserActionResultSchema = z.object({\n object: z.literal(\"browser_action\"),\n action: z.enum(BROWSER_ACTIONS),\n url: z.string(),\n text: z.string().nullable(),\n data: z.unknown().nullable(),\n links: z.array(z.object({ href: z.string(), text: z.string() })).nullable(),\n elements: z.array(z.object({ selector: z.string(), description: z.string() })).nullable(),\n file_id: idOf(\"fil\").nullable(),\n performed: z.boolean(),\n});\nexport type BrowserActionResult = z.infer<typeof BrowserActionResultSchema>;\n\n/** `login`/`signup` bodies (§32.3). The password never appears on the wire except in `credentials`. */\nexport const BrowserLoginSchema = z.object({\n service: z.string().min(1),\n url: z.string().url(),\n identity_id: idOf(\"idn\"),\n});\nexport const BrowserSignupSchema = BrowserLoginSchema.extend({ email: z.string().email() });\nexport const BrowserCredentialSchema = z.object({\n identity_id: idOf(\"idn\"),\n service: z.string().min(1),\n email: z.string().email(),\n password: z.string().min(1),\n username: z.string().min(1).optional(),\n});\n\nexport const LiveViewSchema = z.object({ url: z.string().url(), expires_at: Timestamp });\n","/** Org, members, keys, credits ledger, webhooks, audit log (canonical-spec §10, §11, §14, §17). */\n\nimport { z } from \"zod\";\nimport {\n AuditActionSchema,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n LineItemTierSchema,\n idOf,\n} from \"./common\";\n\n/** Where every company starts (the owner's choice, ADR-0904); migration 0088's column default. */\nexport const DEFAULT_ORG_TIMEZONE = \"America/New_York\";\n\n/** The IANA name `Intl` resolves `name` to, or `undefined` when it is not one zone's name. */\nfunction canonicalZone(name: string): string | undefined {\n // `Intl` also takes `EST`, `PST` and `+05:00`: an abbreviation or an offset, not a place's zone.\n if (!name.includes(\"/\") && name !== \"UTC\") return undefined;\n try {\n const zone = new Intl.DateTimeFormat(\"en-US\", { timeZone: name }).resolvedOptions().timeZone;\n // `supportedValuesOf` lists every canonical zone but `UTC`, and none of `Etc/GMT+5`'s kind.\n return zone === \"UTC\" || Intl.supportedValuesOf(\"timeZone\").includes(zone) ? zone : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A company's timezone as written (§20.6, ADR-0904): an IANA name, stored as the canonical one\n * `Intl` resolves, so `US/Eastern` is kept as `America/New_York`. The API's `PATCH` and the agent's\n * `company.set_timezone` both parse through it.\n */\nexport const TimezoneSchema = z.string().transform((name, ctx) => {\n const zone = canonicalZone(name);\n if (zone === undefined) {\n ctx.addIssue({ code: \"custom\", message: \"not a timezone; use an IANA name such as America/Los_Angeles\" });\n return z.NEVER;\n }\n return zone;\n});\n\n/** The typefaces a brand kit names, each a stack every browser already has (ADR-1163). */\nexport const BRAND_TYPEFACES = [\"grotesk\", \"serif\", \"rounded\", \"mono\"] as const;\n\n/**\n * THE COMPANY'S BRAND KIT (ADR-1163): a palette, a typeface and a tagline, set beside the logo in\n * the setup chat and read by whoever makes things in the company's look. Its colours are drawn in\n * code from the logo; nothing here is a model's.\n */\nexport const BrandKitSchema = z\n .object({\n palette: z\n .array(z.object({ name: z.string().trim().min(1).max(24), hex: z.string().regex(/^#[0-9a-f]{6}$/) }).strict())\n .min(3)\n .max(6),\n typeface: z.enum(BRAND_TYPEFACES),\n tagline: z.string().trim().max(80),\n })\n .strict();\n\nexport type BrandKit = z.infer<typeof BrandKitSchema>;\n\nexport const OrganizationSchema = z.object({\n id: idOf(\"org\"),\n object: z.literal(\"organization\"),\n name: z.string(),\n balance_micro_usd: MicroUsdField,\n /**\n * The company's timezone, an IANA name (`America/New_York`, §20.6). Times the company chooses or\n * reads are in it: a new routine's zone, when a post goes out. `America/New_York` until changed.\n * Defaulted so a reply from a control plane older than 0088 (or a rolled-back Worker) still parses\n * in a newer SDK/CLI rather than throwing on every `orgs.get/list/update`.\n */\n timezone: z.string().min(1).default(DEFAULT_ORG_TIMEZONE),\n /**\n * The company's logo, an SVG a person or an agent drew (§20.7), passed by `checkLogoSvg`. `null`\n * until one is set. Defaulted so a reply from a control plane older than 0093 still parses.\n */\n logo_svg: z.string().nullable().default(null),\n /** Its brand kit (ADR-1163), `null` until one is set. Defaulted so an older control plane parses. */\n brand: BrandKitSchema.nullable().default(null),\n /**\n * Still being set up: made in a chat with its CEO and not yet activated by a payment (ADR-1108).\n * Defaulted `false`, so a reply from a control plane older than 0101 reads as an ordinary company.\n */\n setting_up: z.boolean().default(false),\n /** The `blueprint/template` a link named when the company was made, else `null` (ADR-1108). */\n start_template: z.string().nullable().default(null),\n /**\n * The company's CEO as the control plane records it (ADR-1108, ADR-1623): the one agent whose turns\n * get the control plane. `null` while none is. Defaulted so an older control plane's reply parses.\n */\n ceo_agent_id: idOf(\"agt\").nullable().default(null),\n created_at: Timestamp,\n});\n\nexport type Organization = z.infer<typeof OrganizationSchema>;\n\nexport const RoleSchema = z.enum([\"owner\", \"admin\", \"member\"]);\n\nexport type Role = z.infer<typeof RoleSchema>;\n\n/** Member ids are not in the `canonical-spec.md §2` prefix table; see the owed doc-fix in decisions. */\nexport const MemberSchema = z.object({\n id: z.string(),\n object: z.literal(\"member\"),\n email: z.email(),\n role: RoleSchema,\n invited_by: z.string().nullable(),\n /** When they first came in. `null` is an invite nobody has taken up (§20.12). */\n joined_at: Timestamp.nullable().optional(),\n /** On an invite's reply only: did the email go? `false` means tell them yourself (§20.12). */\n invite_sent: z.boolean().optional(),\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","/** Computers, snapshots, volumes, skills, files, deployments (canonical-spec §2, §12, §13). */\n\nimport { z } from \"zod\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, WindowSchema, idOf } from \"./common\";\nimport { FileLibraryFieldsSchema } from \"./files-library\";\nimport { SessionStatusSchema } from \"./session\";\n\nexport const ComputerStatusSchema = z.enum([\"creating\", \"running\", \"paused\", \"failed\", \"destroyed\"]);\nexport type ComputerStatus = z.infer<typeof ComputerStatusSchema>;\n\nexport const VolumeSchema = z.object({\n id: idOf(\"vol\"),\n size_gb: z.number().int().positive(),\n mount_path: z.string(),\n});\n\nexport const ComputerSchema = z.object({\n id: idOf(\"cmp\"),\n object: z.literal(\"computer\"),\n name: z.string(),\n vcpu: z.number().int().positive(),\n memory_mb: z.number().int().positive(),\n disk_gb: z.number().int().positive(),\n status: ComputerStatusSchema,\n // core-gaps: U2-browser-api — the whole option object (§32.2); `{ allowed_domains }` still parses.\n browser: BrowserOptionsSchema.nullable(),\n volume: VolumeSchema.nullable(),\n snapshot_id: idOf(\"snp\").nullable(),\n /**\n * The agent this computer belongs to (§41.8, ADR-0849); `null` for one made by `POST /v1/computers`.\n * Defaulted so a reply from an older control plane parses.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n created_at: Timestamp,\n});\nexport type Computer = z.infer<typeof ComputerSchema>;\n\nexport const SnapshotSchema = z.object({\n snapshot_id: idOf(\"snp\"),\n computer_id: idOf(\"cmp\"),\n created_at: Timestamp,\n});\n\n/** Computer workspace (§41): what a box is doing, what ran on it, what is on it, what browsed from it. */\n\n/** One in-VM sample (§41.1). `null` on the inspect of anything but a `running` box — a read never wakes one. */\nexport const ComputerProbeSchema = z.object({\n sampled_at: Timestamp,\n uptime_seconds: z.number().int().nonnegative(),\n processes: z.number().int().nonnegative(),\n load_1m: z.number().nonnegative(),\n memory_used_mb: z.number().int().nonnegative(),\n memory_total_mb: z.number().int().positive(),\n disk_used_gb: z.number().nonnegative(),\n disk_total_gb: z.number().positive(),\n});\nexport type ComputerProbe = z.infer<typeof ComputerProbeSchema>;\n\nexport const ComputerInspectSchema = z.object({\n object: z.literal(\"computer_inspect\"),\n id: idOf(\"cmp\"),\n status: ComputerStatusSchema,\n last_active_at: Timestamp.nullable(),\n /** Where the provider's file API is rooted (§41.1); `null` when it does not say. */\n home: z.string().min(1).nullable(),\n probe: ComputerProbeSchema.nullable(),\n});\nexport type ComputerInspect = z.infer<typeof ComputerInspectSchema>;\n\n/** Output cap per stream on a recorded command (§41.3); a cut sets `truncated`. */\nexport const COMMAND_OUTPUT_CAP = 65_536;\n\nexport const ComputerCommandSchema = z.object({\n id: idOf(\"cmd\"),\n object: z.literal(\"computer_command\"),\n computer_id: idOf(\"cmp\"),\n command: z.string(),\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n duration_ms: z.number().int().nonnegative(),\n stdout: z.string().max(COMMAND_OUTPUT_CAP),\n stderr: z.string().max(COMMAND_OUTPUT_CAP),\n truncated: z.boolean(),\n actor: PrincipalSchema,\n created_at: Timestamp,\n});\nexport type ComputerCommand = z.infer<typeof ComputerCommandSchema>;\n\n/** One `data:` frame of `POST …/exec/stream` (§41.2): output as it arrives, then exactly one `exit`. */\nexport const ExecStreamFrameSchema = z.union([\n z.object({ stdout: z.string() }),\n z.object({ stderr: z.string() }),\n z.object({\n exit: z.object({\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n /** The frames above stopped at the per-stream cap (ADR-1868); absent from older servers. */\n truncated: z.boolean().optional(),\n duration_ms: z.number().int().nonnegative(),\n command_id: idOf(\"cmd\"),\n }),\n }),\n]);\nexport type ExecStreamFrame = z.infer<typeof ExecStreamFrameSchema>;\n\nexport const FileEntryTypeSchema = z.enum([\"file\", \"directory\", \"symlink\", \"other\"]);\nexport const FileEntrySchema = z.object({\n name: z.string().min(1),\n path: z.string().min(1),\n type: FileEntryTypeSchema,\n size_bytes: z.number().int().nonnegative(),\n /** POSIX `st_mode`. */\n mode: z.number().int().nonnegative(),\n modified_at: Timestamp.nullable(),\n});\nexport type FileEntry = z.infer<typeof FileEntrySchema>;\n\nexport const ComputerUpdateSchema = z.strictObject({ name: z.string().min(1).max(200) });\nexport type ComputerUpdate = z.infer<typeof ComputerUpdateSchema>;\n\n/* ── Mobile devices (canonical-spec §53) ─────────────────────────────────────────────────────── */\n\nexport const MobileDeviceStatusSchema = z.enum([\"creating\", \"ready\", \"terminated\", \"failed\"]);\nexport type MobileDeviceStatus = z.infer<typeof MobileDeviceStatusSchema>;\nexport const MobilePlatformSchema = z.enum([\"android\", \"ios\"]);\nexport const MobileOsVersionSchema = z.enum([\"13\", \"14\", \"15\"]);\n/** `watch` is iOS only; the adapter maps `phone`/`tablet` onto each provider's own words (§53.1). */\nexport const MobileModelSchema = z.enum([\"phone\", \"tablet\", \"watch\"]);\nexport const MobileJurisdictionSchema = z.enum([\"us\", \"eu\", \"as\"]);\n/** `unfunded`: the platform ended it because the organization's balance or plan ran out (§53.7). */\nexport const MobileTerminationReasonSchema = z.enum([\"requested\", \"idle_timeout\", \"max_duration\", \"unfunded\", \"unknown\"]);\n\n/**\n * An app on a phone: the package name (Android) or App Store bundle id (iOS) — `com.example.shop`.\n * Installed at create (`apps[]`) or while the phone runs (`install_app`), from the platform's app\n * store (§53.1, ADR-1904).\n */\nexport const MobileAppPackage = z\n .string()\n .max(255)\n .regex(/^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_-]*)+$/, { error: \"an app is a package name such as com.example.app\" });\n\n/**\n * The platform rules a create body has to obey (§53.1): Android chooses an OS version, iOS cannot\n * (the provider offers none and refuses a create that names one, so the field is `null`); and the\n * provider offers phones only, so `tablet` and `watch` are refused (ADR-1162). One function so the\n * route, the CLI and a test all refuse with the same sentence.\n */\nexport function mobileSpecIssue(spec: {\n platform: MobileDevice[\"platform\"];\n os_version: MobileDevice[\"os_version\"];\n model: MobileDevice[\"model\"];\n}): { param: \"platform\" | \"os_version\" | \"model\"; message: string } | null {\n if (spec.platform === \"ios\" && spec.os_version !== null) return { param: \"os_version\", message: \"an ios device has no os_version to choose: omit it\" };\n if (spec.platform === \"android\" && spec.os_version === null) return { param: \"os_version\", message: \"an android device needs an os_version\" };\n if (spec.model !== \"phone\") return { param: \"model\", message: `${spec.model} devices are not available: only phone` };\n return null;\n}\n\nexport const MobileDeviceSchema = z.object({\n id: idOf(\"mob\"),\n object: z.literal(\"mobile_device\"),\n name: z.string(),\n platform: MobilePlatformSchema,\n /** `null` on iOS: the provider offers no version choice, so the object says so (§53.1). */\n os_version: MobileOsVersionSchema.nullable(),\n model: MobileModelSchema,\n jurisdiction: MobileJurisdictionSchema,\n status: MobileDeviceStatusSchema,\n /** Enforced by the platform's per-minute sweep from the last action; there is no pause (§53.1). */\n idle_timeout_minutes: z.number().int().min(1).max(180),\n max_duration_minutes: z.number().int().min(1).max(1440),\n apps: z.array(MobileAppPackage),\n termination_reason: MobileTerminationReasonSchema.nullable(),\n error: z.string().nullable(),\n created_at: Timestamp,\n terminated_at: Timestamp.nullable(),\n /** The agent session whose `mobile` tool opened it (§53.8); `null` for one made through the API. */\n session_id: idOf(\"ses\").nullable(),\n});\nexport type MobileDevice = z.infer<typeof MobileDeviceSchema>;\n\n/**\n * The `mobile` tool's `config` (§53.8): the §53.1 create fields, all optional, with the agent-tool\n * defaults applied where it is read. Strict, so a misspelt field is refused at the agent write\n * rather than silently becoming a default phone.\n */\nexport const MobileToolOptionsSchema = z\n .strictObject({\n /** Unset: Android. `ios` takes no `os_version` (§53.1). */\n platform: MobilePlatformSchema.optional(),\n os_version: MobileOsVersionSchema.nullable().optional(),\n model: MobileModelSchema.default(\"phone\"),\n jurisdiction: MobileJurisdictionSchema.default(\"us\"),\n idle_timeout_minutes: z.number().int().min(1).max(180).default(10),\n /**\n * At most an hour on an agent's phone: the tool may be granted for a whole chat, and the minutes\n * settle after the fact, so this is what bounds one phone's spend ($3.00 on Android, $4.80 on iOS).\n */\n max_duration_minutes: z.number().int().min(1).max(60).default(60),\n apps: z.array(MobileAppPackage).max(10).default([]),\n })\n .superRefine((o, ctx) => {\n const platform = o.platform ?? \"android\";\n const issue = mobileSpecIssue({ platform, model: o.model, os_version: o.os_version === undefined ? (platform === \"android\" ? \"15\" : null) : o.os_version });\n if (issue) ctx.addIssue({ code: \"custom\", message: issue.message, path: [issue.param] });\n });\nexport type MobileToolOptions = z.output<typeof MobileToolOptionsSchema>;\n\nexport const MobileDeviceUpdateSchema = z.strictObject({ name: z.string().min(1).max(200) });\n\n/** `{ text?, resource_id?, content_desc? }` — at least one, so a tap never targets \"anything\". */\nexport const MobileSelectorSchema = z\n .object({ text: z.string().min(1).optional(), resource_id: z.string().min(1).optional(), content_desc: z.string().min(1).optional() })\n .refine((s) => s.text !== undefined || s.resource_id !== undefined || s.content_desc !== undefined, {\n error: \"a selector needs text, resource_id or content_desc\",\n });\nexport type MobileSelector = z.infer<typeof MobileSelectorSchema>;\n\nconst Coordinate = z.number().int().nonnegative();\nexport const MOBILE_ACTION_TYPES = [\"screenshot\", \"element_tree\", \"tap\", \"type\", \"press_key\", \"scroll\", \"open_url\", \"launch_app\", \"install_app\"] as const;\n/** One action on a device (§53.4). A discriminated union so a refusal names the field. */\nexport const MobileActionSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"screenshot\") }),\n z.object({ type: z.literal(\"element_tree\") }),\n // Coordinates or a selector, never neither: a tap has to land somewhere.\n z\n .object({ type: z.literal(\"tap\"), x: Coordinate.optional(), y: Coordinate.optional(), selector: MobileSelectorSchema.optional() })\n .refine((t) => t.selector !== undefined || (t.x !== undefined && t.y !== undefined), {\n error: \"tap needs x and y, or a selector\",\n }),\n z.object({ type: z.literal(\"type\"), text: z.string().min(1).max(4096) }),\n z.object({ type: z.literal(\"press_key\"), key: z.string().min(1).max(64) }),\n z.object({\n type: z.literal(\"scroll\"),\n direction: z.enum([\"up\", \"down\", \"left\", \"right\"]),\n /** Screenshot pixels (default: 40% of the screen), §53.4. */\n amount: z.number().int().min(1).max(5000).optional(),\n }),\n z.object({ type: z.literal(\"open_url\"), url: z.url() }),\n /** An installed app by package name, at its launcher screen (§53.4). */\n z.object({ type: z.literal(\"launch_app\"), package: MobileAppPackage }),\n /** From the app store, on the running device: a package name on Android, a bundle id on iOS (§53.4). */\n z.object({ type: z.literal(\"install_app\"), app: MobileAppPackage }),\n]);\nexport type MobileAction = z.infer<typeof MobileActionSchema>;\n\n/** A JPEG as the adapter answers; the schema keeps `image/png` so no client breaks (§53.4). */\nexport const MobileImageSchema = z.object({ content_type: z.enum([\"image/png\", \"image/jpeg\"]), data: z.string() });\nexport const MobileActionResultSchema = z.object({\n object: z.literal(\"mobile_action_result\"),\n type: z.enum(MOBILE_ACTION_TYPES),\n output: z.unknown().nullable(),\n image: MobileImageSchema.nullable(),\n});\nexport type MobileActionResult = z.infer<typeof MobileActionResultSchema>;\n\n/** A bearer credential for one device's screen (§53.2): minted for a person, never stored. */\nexport const MobileLiveViewSchema = z.object({\n object: z.literal(\"mobile_live_view\"),\n url: z.url(),\n /** `null`: the provider publishes no expiry; the URL dies with the device. */\n expires_at: Timestamp.nullable(),\n /**\n * The same screen as a realtime stream a page can embed (§53.5): a WebSocket endpoint and the\n * device's bearer token. The same credential as `url`, in the shape an embedded player needs;\n * `null` when the provider offers none. Never stored, never logged, never in another object.\n */\n stream: z.object({ url: z.string().regex(/^wss:\\/\\//), token: z.string().min(1) }).nullable(),\n});\nexport type MobileLiveView = z.infer<typeof MobileLiveViewSchema>;\n\nexport const SkillSchema = z.object({\n id: idOf(\"skl\"),\n object: z.literal(\"skill\"),\n name: z.string(),\n description: z.string().nullable(),\n latest_version: z.number().int().positive(),\n created_at: Timestamp,\n});\n\n/**\n * One of an agent's `skills[]` entries, resolved at session start (§13): `slug` took the latest\n * version *then*, `slug@N` is frozen at `N`, and neither moves for the life of the session.\n *\n * It travels API → session runtime because that is where the two things that need it live: the\n * harness advertises `name`/`description` to the model and serves the body from `storage_key` on\n * demand (ADR-0106.4), and `read_skill` reads the same key. Resolving again inside the runtime\n * would re-resolve a floating `slug` mid-session, which §13 forbids.\n */\nexport const ResolvedSkillRefSchema = z.object({\n /** The reference exactly as the agent version wrote it: `slug` or `slug@N`. */\n ref: z.string().min(1),\n slug: z.string().min(1),\n version: z.number().int().positive(),\n description: z.string(),\n storage_key: z.string().min(1),\n});\n\nexport type ResolvedSkillRef = z.infer<typeof ResolvedSkillRefSchema>;\n\n/** Skill versions are immutable and content-addressed (§13). */\nexport const SkillVersionSchema = z.object({\n version: z.number().int().positive(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n size_bytes: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\n\n/**\n * One version of a skill the PLATFORM ships (§31.9) — the `naive/slug` half of §13's grammar. No\n * `id` and no organization: the catalogue is identical for every tenant and is addressed by\n * `(slug, version)` and nothing else. `content_hash` is the same lowercase sha-256 an organization\n * skill version carries as `sha256`; identical bytes never mint a version.\n *\n * The list (`GET /v1/skills/catalog`) returns this, newest version per slug, WITHOUT the body — the\n * body is the expensive half and is read on the version route (§13's progressive disclosure).\n */\nexport const SkillCatalogEntrySchema = z.object({\n object: z.literal(\"skill_catalog_entry\"),\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n version: z.number().int().positive(),\n name: z.string().min(1),\n description: z.string(),\n tags: z.array(z.string().min(1)),\n content_hash: z.string().regex(/^[0-9a-f]{64}$/),\n published_at: Timestamp,\n});\nexport type SkillCatalogEntry = z.infer<typeof SkillCatalogEntrySchema>;\n\n/** `GET /v1/skills/catalog/{slug}/versions/{n}` — the entry with its `SKILL.md` body. */\nexport const SkillCatalogVersionSchema = SkillCatalogEntrySchema.extend({ content: z.string() });\nexport type SkillCatalogVersion = z.infer<typeof SkillCatalogVersionSchema>;\n\nexport const FileSchema = z.object({\n id: idOf(\"fil\"),\n object: z.literal(\"file\"),\n name: z.string(),\n content_type: z.string(),\n size_bytes: z.number().int().nonnegative(),\n scope: z.enum([\"session\", \"published\"]),\n session_id: idOf(\"ses\").nullable(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n created_at: Timestamp,\n // The asset-library fields (`canonical-spec §36.1`), all nullable or defaulted.\n ...FileLibraryFieldsSchema.shape,\n /** The agent of `session_id`, joined at read (§36.1, ADR-0887); a writer never sets it. */\n agent_id: idOf(\"agt\").nullable().optional(),\n});\n/** `File` is a DOM global on a Worker, so the wire object is `FileObject` in TypeScript. */\nexport type FileObject = z.infer<typeof FileSchema>;\n\n/**\n * Whether a schedule will actually fire, which `enabled` alone cannot say (ADR-0104):\n * `paused` is `enabled: false`, and `unscheduled` is an enabled schedule on a deploy that runs no\n * clock — its `next_run_at` is `null`, because a date no tick will ever honour is worse than none.\n */\nexport const ScheduleStatusSchema = z.enum([\"scheduled\", \"paused\", \"unscheduled\"]);\nexport type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;\n\n/** A cron deployment. `agent_version` pins the exact version that fires (§12). */\nexport const DeploymentSchema = z.object({\n id: idOf(\"dep\"),\n object: z.literal(\"deployment\"),\n agent_id: idOf(\"agt\"),\n /** A pin. `null` tracks the agent's `current_version` on every fire (§12). */\n agent_version: z.number().int().positive().nullable(),\n cron: z.string(),\n /** IANA zone the `cron` is read in. \"0 9 * * 1\" means 09:00 *here*, across DST (ADR-0074). */\n timezone: z.string(),\n input_template: z.string(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n window: WindowSchema,\n /**\n * URL POSTed with the `session.idle` envelope when a fire goes idle; `null` pushes nothing.\n *\n * `https` for the same reason `POST /v1/webhooks` requires it — setting this materialises one of\n * those endpoints, and a signed delivery over cleartext is not a delivery. Until the push was\n * wired this field went nowhere, so nothing can be relying on an `http://` value (ADR-0161).\n */\n on_idle: z.url().startsWith(\"https://\", { error: \"a webhook URL must be https\" }).nullable(),\n /**\n * The persona every fire speaks as, or `null` to run as nobody (§22). Written as an `idn_` id\n * **or** the persona's name, the way a session names one, and always echoed as the id: a fire at\n * 3am must not be silenced by someone renaming the persona at noon.\n */\n identity: idOf(\"idn\").nullable(),\n enabled: z.boolean(),\n /** Derived per deploy, never stored — the row cannot know whether a clock is watching it. */\n schedule_status: ScheduleStatusSchema,\n /** The next fire, or `null` when nothing will fire it (`schedule_status` says which). */\n next_run_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Deployment = z.infer<typeof DeploymentSchema>;\n\n/** The persisted half: everything but the derived `schedule_status` (ADR-0104). */\nexport type StoredDeployment = Omit<Deployment, \"schedule_status\">;\n\nexport const DeploymentRunSchema = z.object({\n id: idOf(\"run\"),\n session_id: idOf(\"ses\"),\n status: SessionStatusSchema,\n started_at: Timestamp.nullable(),\n});\nexport type DeploymentRun = z.infer<typeof DeploymentRunSchema>;\n","/**\n * core-gaps: contracts — the library fields a file gains (`canonical-spec §36`). U7 composes them\n * into `FileSchema` with `FileSchema.extend(FileLibraryFieldsSchema.shape)`; every field is\n * nullable or defaulted so each existing row and writer stays valid.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const FILE_KINDS = [\"image\", \"video\", \"audio\", \"document\", \"other\", \"model\"] as const;\nexport const FileKindSchema = z.enum(FILE_KINDS);\nexport type FileKind = z.infer<typeof FileKindSchema>;\n\nexport const FILE_SOURCE_TYPES = [\n \"upload\",\n \"url_import\",\n \"image_generation\",\n \"video_generation\",\n \"video_clipping\",\n \"screenshot\",\n \"speech_generation\",\n \"mesh_generation\",\n \"model_build\",\n \"sound_effect\",\n \"music\",\n] as const;\nexport const FileSourceTypeSchema = z.enum(FILE_SOURCE_TYPES);\nexport type FileSourceType = z.infer<typeof FileSourceTypeSchema>;\n\nexport const FileSourceSchema = z.object({\n type: FileSourceTypeSchema,\n job_id: z.union([idOf(\"med\"), idOf(\"clj\")]).nullable(),\n url: z.string().url().nullable(),\n /** What a generator was asked with (§36.1, ADR-0886); absent on every other writer's row. */\n model: z.string().nullable().optional(),\n prompt: z.string().nullable().optional(),\n /** The library file this one was made from: an edit take's source clip (§55), for Before/After. */\n from_file_id: idOf(\"fil\").nullable().optional(),\n /** The trained character a render was pinned to (§33.6); absent when none was. */\n character_id: idOf(\"chr\").nullable().optional(),\n /** The look slug an image was drawn in (§33.6.1); absent when none was asked. */\n style: z.string().nullable().optional(),\n});\nexport type FileSource = z.infer<typeof FileSourceSchema>;\n\nexport const FileTagsSchema = z.array(z.string().min(1).max(64)).max(32);\n\n/** Characters a name may not carry anywhere: controls (a newline, a tab, NUL) and direction overrides. */\n// eslint-disable-next-line no-control-regex -- matching control characters is the point.\nconst FOLDER_FORBIDDEN = /[\\u0000-\\u001f\\u007f-\\u009f\\u202a-\\u202e\\u2066-\\u2069]/u;\n/** Characters that draw nothing; a name made only of these looks empty. A joiner inside an emoji is fine. */\nconst FOLDER_INVISIBLE = /[\\s\\u200b-\\u200d\\u2060\\ufeff]/gu;\n\n/**\n * A FOLDER IS A NAME ON THE FILE (`canonical-spec §36.4`, ADR-1470): one level, one per file, 1–64\n * characters and no `/`, so nesting can come later as paths. There is no folder table: a folder\n * exists while a file names it. Counted in code points, as Postgres's CHECK counts them and as the\n * Files tab counts them. Not `.` or `..`, no control or direction-override character, and at least\n * one character that draws: migration 0129's CHECK holds the same rules.\n */\nexport const FileFolderSchema = z\n .string()\n .trim()\n .min(1, \"a folder needs a name\")\n .refine((name) => [...name].length <= 64, \"a folder name can be at most 64 characters\")\n .refine((name) => !name.includes(\"/\"), \"a folder name can't contain /\")\n .refine((name) => name !== \".\" && name !== \"..\", \"a folder name can't be . or ..\")\n .refine((name) => !FOLDER_FORBIDDEN.test(name), \"a folder name can't contain line breaks, tabs or hidden direction marks\")\n .refine((name) => name.replace(FOLDER_INVISIBLE, \"\") !== \"\", \"a folder name needs a character you can see\");\n\nexport const FileLibraryFieldsSchema = z.object({\n title: z.string().max(256).nullable().default(null),\n description: z.string().max(4_096).nullable().default(null),\n tags: FileTagsSchema.default([]),\n kind: FileKindSchema.default(\"other\"),\n source: FileSourceSchema.nullable().default(null),\n thumbnail_file_id: idOf(\"fil\").nullable().default(null),\n width: z.number().int().positive().nullable().default(null),\n height: z.number().int().positive().nullable().default(null),\n duration_seconds: z.number().nonnegative().nullable().default(null),\n folder: FileFolderSchema.nullable().default(null),\n});\nexport type FileLibraryFields = z.infer<typeof FileLibraryFieldsSchema>;\n\n/** `PATCH /v1/files/{id}` — the fields a customer edits; `folder: null` takes it out of its folder. */\nexport const UpdateFileSchema = z.object({\n title: z.string().max(256).nullable().optional(),\n description: z.string().max(4_096).nullable().optional(),\n tags: FileTagsSchema.optional(),\n folder: FileFolderSchema.nullable().optional(),\n});\n\n/**\n * `POST /v1/files/move` — many files into one folder (`ids`), or a whole folder into another (`from`):\n * a rename, a merge when the name is taken, and with `folder: null` a dissolve. Files never move or\n * die with a folder; only the name on them changes.\n */\nexport const MoveFilesSchema = z\n .object({\n ids: z.array(idOf(\"fil\")).min(1).max(100).optional(),\n from: FileFolderSchema.optional(),\n folder: FileFolderSchema.nullable(),\n })\n .refine((body) => (body.ids === undefined) !== (body.from === undefined), \"name either `ids` or `from`\");\nexport type MoveFiles = z.infer<typeof MoveFilesSchema>;\n\n/** What a move answers: the name the files now carry (an existing folder's casing wins) and which moved. */\nexport const FileMoveSchema = z.object({\n object: z.literal(\"file_move\"),\n folder: z.string().nullable(),\n file_ids: z.array(idOf(\"fil\")),\n});\nexport type FileMove = z.infer<typeof FileMoveSchema>;\n\n/**\n * `POST /v1/files/delete` — up to 100 files deleted in one request (`canonical-spec §36.4`). Each is\n * what `DELETE /v1/files/{id}` does to one; an id the org does not hold is skipped. One request per\n * hundred is what lets a closing tab finish a big delete: a browser keeps 256 requests alive per page.\n */\nexport const DeleteFilesSchema = z.object({ ids: z.array(idOf(\"fil\")).min(1).max(100) });\nexport type DeleteFiles = z.infer<typeof DeleteFilesSchema>;\n\n/** What a bulk delete answers: the ids it deleted. */\nexport const FileDeleteSchema = z.object({\n object: z.literal(\"file_delete\"),\n file_ids: z.array(idOf(\"fil\")),\n});\nexport type FileDelete = z.infer<typeof FileDeleteSchema>;\n\n/** `GET /v1/files/folders` — one per name, newest first. `agent_id` is set when one agent made every file in it. */\nexport const FileFolderInfoSchema = z.object({\n object: z.literal(\"file_folder\"),\n name: z.string(),\n file_count: z.number().int().positive(),\n newest_at: z.string(),\n cover_file_ids: z.array(idOf(\"fil\")).max(4),\n agent_id: idOf(\"agt\").nullable(),\n});\nexport type FileFolderInfo = z.infer<typeof FileFolderInfoSchema>;\n\n/** `POST /v1/files/imports` — the route refuses private hosts and bodies over the upload cap. */\nexport const ImportFileSchema = z.object({\n url: z.string().url().startsWith(\"http\"),\n /** The stored file's name; omitted, the URL's last path segment (ADR-1874). */\n name: z.string().min(1).max(500).optional(),\n title: z.string().max(256).optional(),\n description: z.string().max(4_096).optional(),\n tags: FileTagsSchema.optional(),\n folder: FileFolderSchema.optional(),\n});\n\n/**\n * The signed upload's cap (`POST /v1/files/uploads`): the bytes stream past the API to the object\n * store, so this is not bound by the isolate the way the 25 MiB multipart upload is.\n */\nexport const FILE_UPLOAD_MAX_BYTES = 60 * 1024 * 1024;\n\n/** `POST /v1/files/uploads` — what the one-shot link will take, exactly. */\nexport const CreateFileUploadSchema = z.object({\n name: z.string().min(1).max(500),\n content_type: z\n .string()\n .max(255)\n .regex(/^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/, \"a MIME type such as video/mp4\"),\n size_bytes: z.number().int().positive().max(FILE_UPLOAD_MAX_BYTES),\n folder: FileFolderSchema.optional(),\n});\nexport type CreateFileUpload = z.infer<typeof CreateFileUploadSchema>;\n\n/** The answer: the `fil_` id the file will have, and where the bytes go (one PUT, 15 minutes). */\nexport const FileUploadTicketSchema = z.object({\n object: z.literal(\"file_upload\"),\n file_id: z.string(),\n upload_url: z.string(),\n expires_at: z.string(),\n});\nexport type FileUploadTicket = z.infer<typeof FileUploadTicketSchema>;\n/** The 3D content types (§59) that are not under `model/`. */\nconst MODEL_TYPES = new Set([\"application/x-blender\", \"application/sla\"]);\n\n/** `content_type` → `kind`, decided once at write and stored. */\nexport function fileKindOf(contentType: string): FileKind {\n const lower = contentType.toLowerCase();\n const [type] = lower.split(\"/\");\n if (type === \"image\" || type === \"video\" || type === \"audio\") return type;\n if (type === \"model\" || MODEL_TYPES.has(lower)) return \"model\";\n if (type === \"text\" || lower.includes(\"pdf\") || lower.includes(\"document\")) {\n return \"document\";\n }\n return \"other\";\n}\n","/** Sessions, the transcript message, and tool results (canonical-spec §5, §7, §10, §16). */\n\nimport { z } from \"zod\";\nimport { OutcomeEvaluationSchema } from \"./outcome\";\nimport { SocialPlatformSchema } from \"./social\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n Timestamp,\n TokenUsageSchema,\n WindowSchema,\n idOf,\n} from \"./common\";\n\n/** `idle` = resumable, `completed` = the agent declared done; both are non-`running` (§5). */\nexport const SessionStatusSchema = z.enum([\n \"queued\",\n \"running\",\n \"idle\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\nexport type SessionStatus = z.infer<typeof SessionStatusSchema>;\n\n/**\n * Plan mode (§7.5, ADR-0905). `build` is every session that never entered plan mode. Session state,\n * never agent config: it rides a send and is changed back only by a person.\n */\nexport const SessionModeSchema = z.enum([\"plan\", \"build\"]);\nexport type SessionMode = z.infer<typeof SessionModeSchema>;\n\n/** A plan's words are capped where a board card's body is (`BOARD_TEXT_MAX`, `board.ts`). */\nexport const PLAN_MAX_CHARS = 20_000;\n\n/**\n * The living plan (§7.5). Kept by the runtime beside the session's state, never in the transcript.\n * `version` 0 is no plan yet, and only then is `by` null.\n */\nexport const PlanSchema = z.object({\n object: z.literal(\"plan\"),\n markdown: z.string().max(PLAN_MAX_CHARS),\n version: z.number().int().nonnegative(),\n by: z.enum([\"agent\", \"owner\"]).nullable(),\n});\nexport type Plan = z.infer<typeof PlanSchema>;\n\n/** `write_plan`'s arguments and `PUT /v1/sessions/{id}/plan`'s body: one compare-and-set (§7.5). */\nexport const PlanWriteSchema = z.object({\n markdown: z.string().max(PLAN_MAX_CHARS).describe(\"The whole plan as Markdown; it replaces the version you read.\"),\n base_version: z.number().int().nonnegative().describe(\"The version you last read, 0 for the first plan. A stale one is refused.\"),\n});\nexport type PlanWrite = z.infer<typeof PlanWriteSchema>;\n\n/** `propose_plan`'s arguments (§7.5). `version` is hashed into the card's id, so a denied plan is written again before it is proposed again. */\nexport const ProposePlanSchema = z.object({\n version: z.number().int().positive().describe(\"The plan version to put to the person, as write_plan returned it.\"),\n spends_or_publishes: z\n .array(z.string().min(1).max(200))\n .max(10)\n .optional()\n .describe(\"Each step that spends money or publishes something, one line each, shown on the card.\"),\n});\n\n/** Set whenever a turn yields control — never treat `idle` as success (§5). */\nexport const StopReasonSchema = z.enum([\n \"end_turn\",\n \"awaiting_input\",\n \"awaiting_approval\",\n \"budget_paused\",\n \"interrupted\",\n \"error\",\n \"max_iterations\",\n /** A turn produced no message and no tool call — honest failure, never `end_turn` (entry 4). */\n \"context_exhausted\",\n /**\n * A coordinator yielded because every delegated child it is waiting on is still running (§28).\n * Distinct from `awaiting_input`: nobody is being asked for anything, so no human can unblock it —\n * the child's completion does. Reporting `idle`/`end_turn` here would claim the task was finished.\n */\n \"awaiting_delegation\",\n /**\n * The turn yielded because the agent asked the operator a question and cannot proceed without\n * the answer (§7.1). Distinct from all three neighbours, and none can stand in: `awaiting_input`\n * says only that there is nothing left to do, so a client reading it renders a bare composer\n * where a specific answer is owed; `awaiting_approval` says the block is a tool call to allow or\n * deny, and its route carries a verb and no payload; `awaiting_delegation` says no human can\n * unblock it at all. What is being asked is the parked `pending_actions` row.\n */\n \"awaiting_answer\",\n]);\nexport type StopReason = z.infer<typeof StopReasonSchema>;\n\n/**\n * THE STOPS THAT PARK A TURN ON A PERSON, in one place because four things must agree about them.\n *\n * A question is a `pending_actions` row exactly as an unapproved call is (§7.1); the two differ\n * only in which door the person answers through, and nothing that reads this cares about doors.\n * Everything here keeps the parked rows across the commit, cross-posts a member's rows to its\n * coordinator, renders the card, and — in the sandbox reaper — refuses to TTL the filesystem the\n * question is about out from under a session waiting on a human.\n *\n * This existed as three hand-written copies of `stop === \"awaiting_approval\"`, in\n * `apps/runtime-do/src/loop.ts`, `apps/web/app/lib/events.ts` and the reaper's SQL. Adding\n * `awaiting_answer` reached exactly one of them, and the other two silently answered a session\n * parked on a question as though nobody were waiting. `budget_paused` is deliberately NOT here: a\n * person unblocks it too, but there is no parked row and nothing renders a card.\n */\nexport const PARKED_STOP_REASONS = [\"awaiting_approval\", \"awaiting_answer\"] as const;\n\n/** Is this stop one a person has to clear? `null`/`undefined` — never ran, never parked. */\nexport const isParked = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (PARKED_STOP_REASONS as readonly string[]).includes(stop);\n\n/**\n * THE STOP THAT IS NOT A REST. `max_iterations` says a turn ran out of model calls, not that the\n * work stopped: `schedule` (`apps/runtime-do/src/loop.ts`) arms the alarm at once, so the next\n * turn's `session.running` follows that `session.idle` in milliseconds. A reader that treats this\n * idle as the end stops reading, and the answer arrives on a socket nobody is holding — measured on\n * staging as a CEO chat still showing `Working…` 21.7 s after the reply was in the log, with only a\n * reload to reveal it. Nobody is asked for anything either, so it is not a park.\n */\nexport const RESUMING_STOP_REASONS = [\"max_iterations\"] as const;\n\n/** Does the runtime wake itself from this stop? `null`/`undefined` — never ran, never stopped. */\nexport const isResuming = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (RESUMING_STOP_REASONS as readonly string[]).includes(stop);\n\n/** Where a session sits in a team (§28). `null` on every ordinary, undelegated session. */\nexport const ThreadRoleSchema = z.enum([\"coordinator\", \"member\"]);\nexport type ThreadRole = z.infer<typeof ThreadRoleSchema>;\n\nexport const MessageSchema = z.object({\n role: z.enum([\"system\", \"user\", \"assistant\", \"tool\"]),\n content: z.string(),\n tool_call_id: z.string().optional(),\n});\nexport type Message = z.infer<typeof MessageSchema>;\n\n/**\n * ONE IMAGE A TOOL HANDS BACK TO THE MODEL (§16.2) — **a link to it, never its bytes.**\n *\n * *** THIS EXISTS BECAUSE EVERY IMAGE THIS PLATFORM MAKES WAS INVISIBLE TO THE AGENT THAT MADE\n * IT. *** `ToolResult.content` is a string, so a tool that produced pixels could only describe\n * them: the browser's `screenshot` stored a PNG and returned the sentence \"screenshot of <url>\n * saved as fil_…\". The model was told a file existed and could never look at it. Measured on the\n * `media` blueprint (ADR-0758): asked to study a reference video it could read the caption,\n * hashtags and transcript of, and never a frame, the crew planned the wrong genre outright.\n *\n * IT CARRIED BASE64 FOR ONE RELEASE, AND THAT WAS THE WRONG SHAPE (ADR-0761). A tool result is not\n * a one-off payload: it lands in session history and is replayed to the provider on *every\n * subsequent turn*. At the shipped bound — 5 MB of base64 each, twelve per result — a single\n * screenshot-heavy turn could park 60 MB in a context that is then re-sent for the rest of the\n * session, and the mitigation ADR-0758 named (pi resizing oversized images as they enter history)\n * is `processImage`, a wasm image backend that does not exist in the session isolate, so it fails\n * open and passes the original block through. Every image a tool returns is already written to\n * storage and already has a `fil_`; the addressable form of it costs ~200 bytes and never grows.\n *\n * `url` is a **short-lived signed §40 read** at this deployment's own origin — the same mint the\n * social publish hands a provider to fetch once (`files.ts` `signedFileUrl`), not a presigned\n * object-store URL, because the Worker holds no S3 credential. It expires; a later turn that needs\n * to look again asks `view_image` again, which is cheaper than what it replaces.\n *\n * `media_type` is the wire's spelling of the same field the providers use, and it is restricted to\n * what they accept — a model cannot look at a PDF or an SVG, and a tool that sends one has made a\n * mistake worth refusing at the boundary rather than at the provider.\n *\n * There is no byte cap here any more because there are no bytes here any more. The one bound left\n * is the COUNT, on `ToolResult.images` below, and it is the only one this contract needs.\n */\nexport const ToolImageSchema = z.object({\n file_id: idOf(\"fil\"),\n url: z.string().url().describe(\"A short-lived signed read for the file's bytes.\"),\n media_type: z.enum([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]),\n});\nexport type ToolImage = z.infer<typeof ToolImageSchema>;\n\n/**\n * Normative tool result — the plugin contract depends on this shape (§16).\n *\n * `images` is OPTIONAL and additive: a result carrying none is byte-identical to one written\n * before the field existed, which is why no tool, plugin or stored row needed changing for it.\n * A tool that returns images SHOULD still set `content`, because the text is what a reader without\n * vision — a transcript, a log, an operator scrolling the session — is left with.\n *\n * At most 12, because this is a tool result and not an album: a turn that needs more frames than\n * that is sampling, and the sampling belongs in the tool. Since ADR-0761 this count is the ONLY\n * bound on the field — each entry is a link of fixed size, so there is no payload left to cap.\n */\nexport const ToolResultSchema = z.object({\n output: z.unknown(),\n is_error: z.boolean().optional(),\n content: z.string().optional(),\n images: z.array(ToolImageSchema).max(12).optional(),\n});\nexport type ToolResult = z.infer<typeof ToolResultSchema>;\n\n/**\n * One field of a parked question (§7.1). `key` is the name the answer comes back under; the rest is\n * how it is asked. The union is discriminated on `type` so a renderer branches on one word rather\n * than sniffing which optional properties happen to be present.\n */\nconst QuestionFieldBase = {\n key: z.string().min(1).max(64).describe(\"The name the answer comes back under.\"),\n label: z.string().min(1).max(200).describe(\"What the person sees.\"),\n help: z.string().max(500).optional().describe(\"One line under the label.\"),\n /**\n * A field that may be left blank, and it defaults to **false** — the rule \"every field must be\n * answered\" (`assertAnswers`) is still the rule, and this is the one documented way out of it.\n *\n * It exists for the question whose answer genuinely improves the work and does not gate it: a\n * template's setup form asking for a reference to imitate, say. Before the flag the only way to\n * ask such a thing was to make it mandatory — which forces an answer out of someone who has none,\n * and an invented answer is worse than an absent one, because the crew cannot tell them apart.\n *\n * Nothing downstream needs an \"if absent\" branch: `projectContextFor` already lists only the\n * questions that were answered, so an unanswered optional key is simply not in the context.\n *\n * ABSENT rather than `false`, which is why it is `.optional()` and not `.default(false)` like the\n * `multiple` and `other` beside it. Those two sit on the `choice` branch, where a renderer has to\n * branch on them and a definite value earns its place; this sits on the base, next to `help`,\n * which is absent-by-default for the same reason. A default here would make `optional: boolean`\n * required on the OUTPUT type — so every hand-written `QuestionField` in the codebase, and every\n * one written after it, would have to spell out the flag it does not use.\n */\n optional: z.boolean().optional().describe(\"true lets the person leave it blank.\"),\n};\n\nexport const QuestionFieldSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"text\").describe(\"text: a free-text answer.\"),\n placeholder: z.string().max(200).optional().describe(\"Example text shown in the empty box.\"),\n }),\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"choice\").describe(\"choice: pick from options.\"),\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\n .array(z.string().min(1).max(200))\n .min(2)\n .max(12)\n .describe(\"Two to twelve plain-word options; each is both the value and the label.\"),\n multiple: z.boolean().default(false).describe(\"true lets the person pick more than one.\"),\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).describe(\"false hides the free-text 'Other' answer.\"),\n /**\n * A PICTURE OR A LINE FOR AN OPTION (ADR-1103): a template's \"how it looks\" shows its looks, and\n * a niche says what it means in one line. Each names its option by its words; one naming no\n * option is ignored, never refused. With a picture on any option the dashboard draws the choice\n * as a grid of pictures. `image` is `https://`, or a path on the dashboard itself. An array\n * and not a map, because a model's tool schema cannot always take a map. An older reader drops\n * it and draws the plain list.\n */\n details: z\n .array(\n z.object({\n option: z.string().min(1).max(200).describe(\"The option this detail belongs to, word for word.\"),\n note: z.string().min(1).max(120).optional().describe(\"One line on what the option means.\"),\n image: z\n .string()\n .max(500)\n .regex(/^\\/(?:[^/]|$)/, \"an image is a path on the dashboard\")\n .optional()\n .describe(\"A picture of the option: a path on the dashboard.\"),\n }),\n )\n .max(12)\n .optional()\n .describe(\"A note or picture per option. Rarely needed.\"),\n }),\n /**\n * THE PERSON'S OWN MEDIA (ADR-1103): \"show us what you like\". The dashboard offers an upload for\n * images or a video, which land in the organization's files, and a box for a link. The answer is\n * the list: `fil_` ids and `https://` links, which an agent opens with `files_get`, `view_image`\n * or the browser. `placeholder` is the link box's.\n */\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"media\").describe(\"media: the person uploads images or a video, or pastes links.\"),\n placeholder: z.string().max(200).optional().describe(\"Example text shown in the link box.\"),\n }),\n]);\nexport type QuestionField = z.infer<typeof QuestionFieldSchema>;\n\n/** One piece of a `media` answer: a stored file, or a public link. */\nexport const MEDIA_ANSWER = /^(fil_[0-9a-z]+|https:\\/\\/\\S+)$/;\n\n/** The most pieces a `media` answer holds: an answer list's own bound (`answersOf`). */\nexport const MEDIA_MAX = 12;\n\n/**\n * A CONNECT CARD (ADR-1102): the networks an agent needs a person to sign in to. The card draws a\n * row per network with its Connect, and one Not now. The answer is written by the card, never by\n * the person: `connected: YouTube (@handle)` once every network holds an account, or `not now`.\n *\n * An agent's question only, never a template's: a template asks before anything is provisioned,\n * when there is no persona yet to hold the account.\n */\nexport const ConnectFieldSchema = z.object({\n ...QuestionFieldBase,\n type: z.literal(\"connect\").describe(\"connect: the person signs in to social networks. A question of its own.\"),\n platforms: z\n .array(SocialPlatformSchema)\n .min(1)\n .max(6)\n .describe(\"Social networks only. Any other app is connected with connections.connect, not here.\"),\n});\n\n/** A field of an agent's question (§7.1): a template's kinds, and the connect card. */\nexport const AskFieldSchema = z.discriminatedUnion(\"type\", [...QuestionFieldSchema.options, ConnectFieldSchema]);\nexport type AskField = z.infer<typeof AskFieldSchema>;\n\n/**\n * A field as a client pinned before `QUESTION_KINDS_VERSION` reads it (ADR-1105): `text` and\n * `choice` as they are, and a connect card or a media field as a text field that says how to answer\n * it. The answer is still checked against the real field (`answerProblems`).\n */\nexport function legacyField(field: AskField): AskField {\n if (field.type !== \"connect\" && field.type !== \"media\") return field;\n const { key, label, help, optional } = field;\n const placeholder =\n field.type === \"connect\"\n ? `connect ${field.platforms.join(\", \")} on the dashboard, then answer \"connected\", or \"not now\"`\n : \"links or fil_ ids, separated by spaces\";\n return { key, label, type: \"text\", placeholder, ...(help === undefined ? {} : { help }), ...(optional === undefined ? {} : { optional }) };\n}\n\n/**\n * The whole question (§7.1). Exported rather than left inline in `PendingActionSchema` because it\n * is the `ask_operator` tool's argument schema *and* the parked row's `question` branch, and those\n * two have to be the same shape: the row is built by parsing the call's arguments, and the tool\n * call is replayed from the row. Two spellings of the bounds is how they come to disagree.\n */\n/**\n * The most a person answers in one sitting. It is three and not a template's four (ADR-0965): the\n * published SDK parses `pending_actions[].question.fields` with `.max(3)`, so one four-field\n * question made every `sessions.get` and `sessions.list` of an older client throw. A template with\n * four setup questions is asked as two questions.\n */\nexport const QUESTION_FIELDS_MAX = 3;\n\nexport const QuestionSchema = z.object({\n prompt: z.string().min(1).max(1000).describe(\"The question, in one or two sentences.\"),\n fields: z.array(AskFieldSchema).min(1).max(QUESTION_FIELDS_MAX, {\n message: `a question has at most ${QUESTION_FIELDS_MAX} fields — ask the rest in a second question once these are answered`,\n }).describe(\n `Up to ${QUESTION_FIELDS_MAX} fields. Each has key, label and type, and type is exactly one of ` +\n 'text, choice (needs options), media, or connect (needs platforms; alone in its question). ' +\n 'Example: [{\"key\":\"city\",\"label\":\"Which city are you in?\",\"type\":\"text\"}]',\n ),\n}).refine((question) => question.fields.length === 1 || question.fields.every((field) => field.type !== \"connect\"), {\n // A connect card answers itself when the accounts land (ADR-1102); a field beside it would need\n // a Send the card does not have.\n message: \"a connect field is a question of its own: ask anything else in a separate question\",\n path: [\"fields\"],\n});\nexport type Question = z.infer<typeof QuestionSchema>;\n\n/**\n * What comes back (§7.1). Keyed by `QuestionField.key`; an array is a `multiple: true` choice, and\n * a string covers text, a single choice and whatever `other: true` let the person type instead.\n *\n * It is deliberately NOT validated against the question it answers. The agent wrote the question\n * and the agent reads the answer, so the only party that can judge \"that is not one of my options\"\n * is the model — and it can, because `other` means a free-text value was always legal. A schema\n * that rejected the operator's own words would be enforcing a rule §7.1 does not have.\n */\nconst answersOf = (max: number, message: string) =>\n z\n .record(\n z.string().min(1).max(64),\n z.union([z.string().max(2000), z.array(z.string().max(2000)).min(1).max(12)]),\n )\n .refine((answers) => Object.keys(answers).length <= max, { message });\n\nexport const AnswersSchema = answersOf(\n QUESTION_FIELDS_MAX,\n `a question has at most ${QUESTION_FIELDS_MAX} fields, so an answer has at most ${QUESTION_FIELDS_MAX} keys`,\n);\nexport type Answers = z.infer<typeof AnswersSchema>;\n\n/**\n * The most questions a template asks before anything is provisioned (ADR-0757). Four, one more than\n * a question holds (ADR-0965): the fourth is asked as a second question, but the install carries all\n * four answers at once.\n */\nexport const TEMPLATE_QUESTIONS_MAX = 4;\n\n/**\n * A template install's answers, as a person edits them on approval (ADR-1030). The same values as\n * `AnswersSchema`, capped at the template's questions and not at one question's fields, so a\n * four-question template's edit is not refused before `assertAnswers` checks its keys.\n */\nexport const InstallAnswersSchema = answersOf(\n TEMPLATE_QUESTIONS_MAX,\n `a template asks at most ${TEMPLATE_QUESTIONS_MAX} questions, so an install has at most ${TEMPLATE_QUESTIONS_MAX} answers`,\n);\n\n/** What is wrong with a `media` answer's pieces, or `null`: at most twelve files and https links. */\nfunction mediaProblem(key: string, values: readonly string[]): string | null {\n if (values.length > MEDIA_MAX) return `\\`${key}\\` takes at most ${MEDIA_MAX} files and links`;\n const odd = values.find((value) => !MEDIA_ANSWER.test(value));\n return odd === undefined ? null : `\\`${key}\\` takes \\`fil_\\` ids and https links, and \\`${odd}\\` is neither`;\n}\n\n/**\n * EVERYTHING WRONG WITH AN ANSWER SET, against the fields it answers (§7.1) — one rule, read by the\n * control plane before it files answers (`assertAnswers`) and by the studio before it puts an\n * install in front of a person (`InstallPlan`), so a card never offers to run what the control\n * plane will refuse. Empty means the answers stand.\n *\n * Every field must be answered unless it is `optional`, and an optional key that IS present is\n * checked like any other. A key the fields do not ask is wrong. A `choice` without `other` admits\n * only its options.\n */\nexport function answerProblems(\n fields: readonly AskField[],\n answers: Readonly<Record<string, unknown>>,\n): { key: string; message: string }[] {\n const problems: { key: string; message: string }[] = [];\n const asked = new Set(fields.map((field) => field.key));\n for (const key of Object.keys(answers)) {\n if (!asked.has(key)) problems.push({ key, message: `the question does not ask \\`${key}\\`` });\n }\n for (const field of fields) {\n const given = answers[field.key];\n if (given === undefined && field.optional) continue;\n const values = typeof given === \"string\" ? [given] : Array.isArray(given) ? given : [];\n if (values.length === 0 || values.some((value) => typeof value !== \"string\" || value.trim() === \"\")) {\n // A blank optional answer is refused too (an answer given is meant), but the fix is to leave\n // it out: measured, the CEO sent `reference: \"\"` for a question the person skipped.\n const message = field.optional ? `\\`${field.key}\\` was skipped, so leave it out rather than send it blank` : `\\`${field.key}\\` is unanswered`;\n problems.push({ key: field.key, message });\n continue;\n }\n if (field.type === \"text\" || field.type === \"connect\") {\n if (Array.isArray(given)) problems.push({ key: field.key, message: `\\`${field.key}\\` takes one string` });\n continue;\n }\n if (field.type === \"media\") {\n const problem = mediaProblem(field.key, values as string[]);\n if (problem !== null) problems.push({ key: field.key, message: problem });\n continue;\n }\n if (field.multiple !== Array.isArray(given)) {\n const shape = field.multiple ? \"an array of the options chosen\" : \"one option, as a string\";\n problems.push({ key: field.key, message: `\\`${field.key}\\` takes ${shape}` });\n continue;\n }\n // `other` is the free-text escape and defaults to true, so the closed check runs only on a\n // question that opted out of it — the one case where an unlisted answer is genuinely wrong.\n if (field.other) continue;\n const unlisted = (values as string[]).filter((value) => !field.options.includes(value));\n if (unlisted.length > 0) {\n problems.push({\n key: field.key,\n message: `\\`${field.key}\\` admits only the options it listed, and \\`${unlisted[0]}\\` is not one of them`,\n });\n }\n }\n return problems;\n}\n\n/**\n * What a parked session is blocked on (§6 `ask` permission, §7.1). Historically this was only the\n * tool calls an `ask` permission stopped; a question the agent asked the operator is now the second\n * kind, and it is **a row in this same array** rather than a new object, table or list — the park,\n * the sleep, the inbox wake, the transcript fold and the replay are all reused unmodified.\n *\n * `kind` defaults to `\"tool\"`, which is what makes the widening free: every row already sitting in\n * the `pending_actions` jsonb column predates the tag and keeps parsing, so there is no data\n * migration. Carrying an optional tag on this shape has precedent — `ThreadAction`\n * (`apps/runtime-do/src/team.ts`) already extends it with a DO-local `thread_id`.\n */\nexport const PendingActionSchema = z.object({\n kind: z.enum([\"tool\", \"question\"]).default(\"tool\"),\n tool_call_id: z.string(),\n name: z.string(),\n args: z.record(z.string(), z.unknown()),\n /**\n * Present iff `kind` is `\"question\"`, and it is the parse of `args` rather than a second source\n * of truth: `args` is what the model called and therefore what replays byte-identically, while\n * `question` is what a renderer reads without having to know that `ask_operator`'s arguments\n * happen to be the question. Same content, two jobs.\n */\n question: QuestionSchema.optional(),\n /**\n * The helper's thread a coordinator adopted this call from (§28, B-3; ADR-1101): the dashboard\n * marks that helper as waiting on you. Absent on the session's own calls.\n */\n thread_id: idOf(\"ses\").optional(),\n /**\n * The log position of the turn that parked this call (its `turn_key`), written by the runtime: the\n * card's own id (ADR-1624). `tool_call_id` is a hash of the call, so the same call proposed again in\n * a later turn has the same one; this tells the two cards apart. Absent on rows parked before it.\n */\n parked_seq: z.number().int().nonnegative().optional(),\n /**\n * This card is here because the chat has read people's data (§64): it says so, and offers no grant.\n */\n read_people: z.literal(true).optional(),\n});\nexport type PendingAction = z.infer<typeof PendingActionSchema>;\n\nexport const SessionSchema = z.object({\n id: idOf(\"ses\"),\n object: z.literal(\"session\"),\n agent_id: idOf(\"agt\"),\n agent_version: z.number().int().positive(),\n deployment_id: idOf(\"dep\").nullable(),\n /**\n * The persona this session acts as (`canonical-spec §22`). Chosen per task from the personas the\n * agent holds a grant to, and `null` when the caller named none — an agent with several\n * identities is not silently given one.\n */\n identity_id: idOf(\"idn\").nullable(),\n /**\n * The sandbox this session provisioned, or `null` when its toolset needs none. It is a real\n * `Computer`: it lists under `GET /v1/computers`, takes `exec`/`snapshot`, and is destroyed when\n * the session can no longer run a turn (ADR-0160).\n */\n computer_id: idOf(\"cmp\").nullable(),\n /**\n * The delegation lineage (§28). `parent_session_id` is the thread that delegated this one and\n * `root_session_id` the coordinator at the top of the tree; both `null` on a session a customer\n * started. A child is addressable on its own but is excluded from the default `GET /v1/sessions`\n * listing, so a team of ten does not bury the ten tasks the customer actually asked for.\n */\n parent_session_id: idOf(\"ses\").nullable(),\n root_session_id: idOf(\"ses\").nullable(),\n thread_role: ThreadRoleSchema.nullable(),\n /**\n * The model the latest send picked (§7 `model`), or `null` when none has and the session runs its\n * pinned version's model (§10, ADR-0832). Defaulted so a reply from an older control plane parses.\n */\n model: z.string().nullable().default(null),\n /** Plan mode (§7.5, §10): defaulted so a reply from an older control plane parses as `build`. */\n mode: SessionModeSchema.default(\"build\"),\n status: SessionStatusSchema,\n stop_reason: StopReasonSchema.nullable(),\n /**\n * Why a `failed` session stopped (§10, ADR-1712): the §3 code of its last attempt, the `code` its\n * final `session.idle` carries. `null` on every other session. A code, never a message, so it names\n * no vendor. Optional so a reply from an older control plane parses; read absent as `null`.\n */\n stop_code: z.string().nullable().optional(),\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 /** Every outcome held over this session, oldest first (§58.3). On `GET /v1/sessions/{id}` only. */\n outcome_evaluations: z.array(OutcomeEvaluationSchema).optional(),\n last_seq: z.number().int().nonnegative(),\n metadata: Metadata,\n started_at: Timestamp.nullable(),\n ended_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * `POST /v1/sessions/{id}/messages` — one send contract (§7). `queue:true` holds the message in\n * the inbox of a `running` session for the turn after this one; `interrupt:true` stops this one.\n * Both at once is refused: the two name opposite answers to the same question.\n */\n/**\n * A person's message to a session (§7): some text, kept exactly as sent. An empty or\n * whitespace-only message was accepted, woke a turn and was billed for nothing (ADR-1863).\n */\nexport const MessageText = z.string().regex(/\\S/, \"a message needs some text; an empty or whitespace-only one is refused\");\n\nexport const SendMessageSchema = z\n .object({\n message: MessageText,\n interrupt: z.boolean().optional(),\n queue: z.boolean().optional(),\n /** A catalogue id: this session runs on it from this message's turn on (§7, ADR-0832). */\n model: z.string().min(1).optional(),\n /** Plan mode from this message's turn on (§7.5, ADR-0905). */\n mode: SessionModeSchema.optional(),\n idempotency_key: z.string().optional(),\n })\n .refine((body) => !(body.interrupt === true && body.queue === true), {\n message: \"a send is either an interrupt or queued, not both\",\n path: [\"queue\"],\n });\n\n/**\n * `POST /v1/sessions/{id}/messages` → `202` (§7). The reply is the **acceptance**, not a session\n * snapshot: the turn has not run yet, so a snapshot could only report the state before the send.\n * `accepted_seq` is the event high-water mark at acceptance — every event this send produces has\n * `seq > accepted_seq`, which is what makes \"wait for my turn\" expressible (ADR-0108).\n */\nexport const SendAcceptedSchema = z.object({\n session_id: z.string(),\n status: SessionStatusSchema,\n accepted_seq: z.number().int().nonnegative(),\n /**\n * Only on a session the board woke for a card that is now `done` or held by another session\n * (§28.18, ADR-1615): the send went through, and this says which card, and who holds it now.\n */\n hint: z.string().optional(),\n});\nexport type SendAccepted = z.infer<typeof SendAcceptedSchema>;\n\n/**\n * `POST /v1/sessions/{id}/tool_confirmations` (§7).\n *\n * `scope` is HOW FAR THE ALLOW REACHES, and it is the one thing this body could not say. An\n * approval id is `tc_` + SHA-256 over the tool name and its canonical arguments\n * (`harness-pi/approvals.ts`), deliberately, so a decision survives the session sleeping — but that\n * makes every decision exactly one call, and a person setting an agent up answers the same tool\n * five times with different arguments, one model turn apart each. `scope: \"session\"` says \"this\n * TOOL, for the rest of THIS chat\": subsequent calls to that name run without a card.\n *\n * The bounds are the whole design and they are narrow on purpose. One session — it lives in that\n * session's transcript and nowhere else, so it cannot outlive the chat, cannot be read by another\n * session and is never written onto the agent. One tool NAME — never \"approve everything\", and\n * never a second tool. Opt-in per grant, so the default is still one card, one call. And it only\n * widens `allow`: a session-wide *deny* is a different feature nobody has asked for, and the route\n * refuses the pairing rather than inventing semantics for it.\n *\n * WHY THIS BODY AND NOT A SIBLING ROUTE, given `SessionAnswerSchema` below is a sibling for\n * looking like a widening: the objection there is that an optional `answers` would make the\n * REQUIRED field `decision` conditionally required, so neither body would be total any more.\n * `scope` does nothing of the kind. `tool_call_id` and `decision` stay required and mean exactly\n * what they meant; `scope` is a modifier on the verb, with a default that is today's behaviour, so\n * an omitted `scope` is byte-for-byte the request every existing client already sends.\n */\nexport const ToolConfirmationSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().optional(),\n scope: z.enum([\"call\", \"session\"]).default(\"call\"),\n /**\n * THE PERSON'S OWN ANSWERS for a template install they approve (ADR-1030): the call runs with\n * these in place of the `answers` the agent proposed, and with nothing else changed. A modifier on\n * `allow`, like `scope`: absent is the call as proposed. The route refuses it on a deny, on a session\n * grant, on any other tool, and on answers the template's questions refuse (`answerProblems`).\n */\n answers: InstallAnswersSchema.optional(),\n /**\n * THE MODEL THE PERSON PICKED for a `generate_video` they approve (ADR-1472): the call runs on it,\n * with nothing else changed. Like `answers`, a modifier on a one-call `allow`. The route refuses an\n * id off the priced list (`@vetta/billing/video-rates`) or one that cannot take the call's inputs.\n */\n model: z.string().min(1).optional(),\n /**\n * THE DIGEST OF WHAT THE CARD SHOWED, on a one-call `allow` of a card that reads it from the API\n * (a listing, ADR-1747). Filed with the yes, so the route it approves can refuse work that changed.\n */\n shown: z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .optional(),\n /**\n * THE CREDENTIAL THE PERSON SEALED for a `vault.request_secret` they approve (§7.6, ADR-1623). Their\n * browser sealed the value into the vault first; this is only its id. Like `model`, a modifier on a\n * one-call `allow`, and the only way to allow that tool.\n */\n credential: idOf(\"vcr\").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","/**\n * Outcomes (`canonical-spec §58`, ADR-1422, migration 0154) — a description and a rubric a grader\n * holds a session to. The grader is a delegated thread (§58.4), so nothing here calls a model.\n */\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/** The five results an evaluation settles to (§58.3); `text + CHECK` in `vetta.session_outcome`. */\nexport const OutcomeResultSchema = z.enum([\n \"satisfied\",\n \"needs_revision\",\n \"max_iterations_reached\",\n \"failed\",\n \"interrupted\",\n]);\nexport type OutcomeResult = z.infer<typeof OutcomeResultSchema>;\n\n/** `POST /v1/outcomes`. Exactly one of `rubric` (inline Markdown) and `rubric_file` (a `fil_` id). */\nexport const CreateOutcomeSchema = z\n .object({\n name: z.string().min(1).max(200),\n description: z.string().min(1).max(4_000),\n rubric: z.string().min(1).max(100_000).optional(),\n rubric_file: idOf(\"fil\").optional(),\n max_iterations: z.number().int().min(1).max(20).default(3),\n })\n .refine((body) => (body.rubric === undefined) !== (body.rubric_file === undefined), {\n message: \"give exactly one of `rubric` and `rubric_file`\",\n path: [\"rubric\"],\n });\nexport type CreateOutcome = z.infer<typeof CreateOutcomeSchema>;\n\n/** The outcome object (§58.1). Immutable: a changed rubric is a new outcome. */\nexport const OutcomeSchema = z.object({\n id: idOf(\"ocm\"),\n object: z.literal(\"outcome\"),\n name: z.string(),\n description: z.string(),\n rubric: z.string().nullable(),\n rubric_file: idOf(\"fil\").nullable(),\n max_iterations: z.number().int().min(1).max(20),\n created_at: Timestamp,\n});\nexport type Outcome = z.infer<typeof OutcomeSchema>;\n\n/** `POST /v1/sessions/{id}/outcome` (§58.2) — `sessions.setOutcome`. */\nexport const SetOutcomeSchema = z.object({ outcome: idOf(\"ocm\") });\n\n/**\n * What the runtime holds an evaluation to (§58.4): the outcome with its rubric already resolved to\n * text — a `rubric_file` is read by `apps/api` when the outcome is attached. Handed to the session's\n * object at create or attach; the object grades against it until a terminal result.\n */\nexport const OutcomeBriefSchema = z.object({\n outcome_id: idOf(\"ocm\"),\n description: z.string().min(1),\n rubric: z.string().min(1),\n max_iterations: z.number().int().min(1).max(20),\n});\nexport type OutcomeBrief = z.infer<typeof OutcomeBriefSchema>;\n\n/** One outcome held over one session (§58.3). The stored `null` result is `\"pending\"` on the wire. */\nexport const OutcomeEvaluationSchema = z.object({\n object: z.literal(\"outcome_evaluation\"),\n session_id: idOf(\"ses\"),\n outcome_id: idOf(\"ocm\"),\n result: z.union([OutcomeResultSchema, z.literal(\"pending\")]),\n iteration: z.number().int().nonnegative(),\n explanation: z.string().nullable(),\n attached_at: Timestamp,\n});\nexport type OutcomeEvaluation = z.infer<typeof OutcomeEvaluationSchema>;\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/**\n * The networks social data reads (§52): public posts, profiles and comments, no connected account.\n * Wider than `SOCIAL_PLATFORMS` because reading reaches networks publishing does not. X is `x`\n * here too; the adapter translates its upstream's own id.\n */\nexport const SOCIAL_DATA_PLATFORMS = [\n \"x\",\n \"instagram\",\n \"tiktok\",\n \"facebook\",\n \"reddit\",\n \"youtube\",\n \"snapchat\",\n \"linkedin\",\n \"threads\",\n \"telegram\",\n \"douyin\",\n \"kuaishou\",\n \"xiaohongshu\",\n \"weibo\",\n \"bilibili\",\n \"zhihu\",\n \"wechat\",\n \"lemon8\",\n \"pipixia\",\n \"toutiao\",\n \"xigua\",\n] as const;\nexport type SocialDataPlatform = (typeof SOCIAL_DATA_PLATFORMS)[number];\n\n/** The networks the social layer connects (§27); the catalogue's own id for X is `twitter`. */\nexport const SOCIAL_APPS: ReadonlySet<string> = new Set([...SOCIAL_PLATFORMS, \"twitter\"]);\nexport const isSocialApp = (connector: string): boolean =>\n SOCIAL_APPS.has(connector.trim().toLowerCase());\n\n/** Platforms whose provider contract accepts a text-only post. */\nexport const SOCIAL_TEXT_PLATFORMS = [\n \"bluesky\",\n \"facebook\",\n \"linkedin\",\n \"mastodon\",\n \"threads\",\n \"x\",\n] as const;\n\n/**\n * Platforms whose provider contract accepts a post of media plus a caption, and nothing\n * per-destination beyond it. Naming one is legal exactly when the post carries `media_urls` or\n * `file_ids` — a text-only post to a video network is one the provider would refuse.\n *\n * `pinterest` and `reddit` are in neither list on purpose: the provider requires a board name and\n * a subreddit respectively, per-post destinations `CreatePost` has no field for, so a post naming\n * one is refused here with that reason rather than at the provider (`canonical-spec.md §27`).\n */\nexport const SOCIAL_MEDIA_PLATFORMS = [\"instagram\", \"tiktok\", \"youtube\"] as const;\n\n/** Who may see a published post. Three words, because three is what the networks that have the\n * concept at all actually spell. */\nexport const SOCIAL_VISIBILITIES = [\"public\", \"unlisted\", \"private\"] as const;\n\n/**\n * Platforms whose provider contract carries a per-post visibility with all three of those\n * meanings. `linkedin` and `tiktok` have a privacy field too, but neither spells `unlisted` — a\n * post-to-connections and a post-to-self-only are a different axis — so mapping ours onto theirs\n * would be inventing a meaning. They are refused by name instead, like the media rule below.\n */\nexport const SOCIAL_VISIBILITY_PLATFORMS = [\"mastodon\", \"youtube\"] as const;\n\nexport const SocialVisibilitySchema = z.enum(SOCIAL_VISIBILITIES);\nexport type SocialVisibility = z.infer<typeof SocialVisibilitySchema>;\n\nexport const acceptsVisibility = (platform: string): boolean =>\n (SOCIAL_VISIBILITY_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about visibility, in the tool description and the field's own text. */\nexport const SOCIAL_VISIBILITY_RULE =\n `visibility is ${SOCIAL_VISIBILITIES.join(\", \")} and only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept it; omit it and the post publishes at ` +\n \"the account's own default, which on a video channel is normally public\";\n\n/**\n * A POST MARKED AI-GENERATED SAYS SO, TWICE (ADR-1360): the network's own AI-content label where its\n * API has one (TikTok, YouTube, Instagram, X, Pinterest — the adapter maps it), and a disclosure line\n * in the caption on every network, because most have no label and a label alone is easy to miss.\n * Opt-in only (ADR-1636): a post is marked only when its caller sets `ai_generated`; no seat config,\n * template or character render marks it. The publish path adds the line, so it holds whatever the\n * caption says.\n */\nexport const AI_DISCLOSURE = \"#AIgenerated\";\n\n/**\n * A caption that already discloses: the `#AIgenerated` tag itself, any case. Only the tag: a phrase\n * counted too, and \"100% real, not AI-generated!\" then posted with no disclosure at all.\n */\nconst DISCLOSED = /(^|[^a-z0-9_])#aigenerated(?![a-z0-9_])/i;\n\nexport const disclosesAi = (text: string): boolean => DISCLOSED.test(text);\n\n/**\n * The caption with the disclosure kept inside `max` characters: unchanged when its first `max`\n * characters already disclose, otherwise cut to make room and ended with `AI_DISCLOSURE` on its own\n * line — so a network that truncates (X at 280) still shows it.\n */\nexport function discloseAi(text: string, max = Number.POSITIVE_INFINITY): string {\n const kept = text.slice(0, max);\n if (disclosesAi(kept)) return kept;\n const tail = `\\n\\n${AI_DISCLOSURE}`;\n const body = text.slice(0, Math.max(0, max - tail.length)).trimEnd();\n return body === \"\" ? AI_DISCLOSURE : `${body}${tail}`;\n}\n\n/**\n * The outcome metrics the platform measures on a published post (§27, ADR-0768). `follower_delta`\n * is derived by the sweep from two `followers` readings; every other name is parsed from the\n * provider's analytics by the adapter. The only writer of these rows is the platform's own sweep.\n */\nexport const SOCIAL_METRICS = [\n \"views\",\n \"impressions\",\n \"likes\",\n \"comments\",\n \"shares\",\n \"watch_through_rate\",\n \"followers\",\n \"follower_delta\",\n] as const;\nexport type SocialMetric = (typeof SOCIAL_METRICS)[number];\n\nexport const SocialPlatformSchema = z.enum(SOCIAL_PLATFORMS);\nexport type SocialPlatform = z.infer<typeof SocialPlatformSchema>;\n\nexport const SocialTextPlatformSchema = z.enum(SOCIAL_TEXT_PLATFORMS);\nexport type SocialTextPlatform = z.infer<typeof SocialTextPlatformSchema>;\n\nconst isText = (platform: string): boolean =>\n (SOCIAL_TEXT_PLATFORMS as readonly string[]).includes(platform);\nconst isMedia = (platform: string): boolean =>\n (SOCIAL_MEDIA_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about the lists, in the tool description and the field's own text. */\nexport const SOCIAL_PLATFORM_RULE =\n `${SOCIAL_TEXT_PLATFORMS.join(\", \")} take a text-only post; ` +\n `${SOCIAL_MEDIA_PLATFORMS.join(\", \")} may be named only when the post carries media_urls or ` +\n `file_ids; ${SOCIAL_PLATFORMS.filter((platform) => !isText(platform) && !isMedia(platform)).join(\", \")} ` +\n \"cannot be posted to\";\n\n/**\n * The create-post rule, shared verbatim by the REST route and the agent tool so the two doors\n * cannot drift. Both halves are relationships between `platforms` and another field — the two\n * media fields, and `visibility` — so they live on the object rather than on any one field, and\n * each refusal names the platform it is about.\n */\nexport function checkPostTargets(\n value: {\n platforms: readonly string[];\n media_urls?: readonly unknown[] | undefined;\n file_ids?: readonly unknown[] | undefined;\n visibility?: string | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const named = [...new Set(value.platforms)];\n const unsupported = named.filter((platform) => !isText(platform) && !isMedia(platform));\n if (unsupported.length > 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${unsupported.join(\", \")} cannot be a post target: each needs a per-destination field ` +\n \"(a board, a subreddit) this post has no way to carry\",\n });\n return;\n }\n const needMedia = named.filter(isMedia);\n if (needMedia.length > 0 && (value.media_urls?.length ?? 0) + (value.file_ids?.length ?? 0) === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${needMedia.join(\", \")} publishes media, not text: attach at least one media_urls or ` +\n \"file_ids entry, or drop the platform\",\n });\n }\n if (value.visibility === undefined) return;\n const deaf = named.filter((platform) => !acceptsVisibility(platform));\n if (deaf.length === 0) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"visibility\"],\n message:\n `${deaf.join(\", \")} has no per-post visibility to publish under: only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept one, so drop visibility or send those ` +\n \"targets as their own post\",\n });\n}\n\nexport const SocialAccountSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_account\"),\n identity_id: idOf(\"idn\"),\n platform: SocialPlatformSchema,\n username: z.string().nullable(),\n display_name: z.string().nullable(),\n avatar_url: z.url().nullable(),\n connected_at: Timestamp.nullable(),\n});\nexport type SocialAccount = z.infer<typeof SocialAccountSchema>;\n\nexport const SocialPostStatusSchema = z.enum([\n \"draft\",\n \"scheduled\",\n \"processing\",\n \"posted\",\n \"failed\",\n \"deleted\",\n]);\nexport type SocialPostStatus = z.infer<typeof SocialPostStatusSchema>;\n\nexport const SocialPostSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_post\"),\n identity_id: idOf(\"idn\"),\n title: z.string(),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n error: z.string().nullable(),\n});\nexport type SocialPost = z.infer<typeof SocialPostSchema>;\n\nexport const SocialUploadSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_upload\"),\n identity_id: idOf(\"idn\"),\n type: z.enum([\"image\", \"video\", \"document\"]),\n url: z.url().nullable(),\n});\nexport type SocialUpload = z.infer<typeof SocialUploadSchema>;\n\nexport const SocialAnalyticsSchema = z.object({\n object: z.literal(\"social_analytics\"),\n identity_id: idOf(\"idn\"),\n resource_id: z.string().min(1),\n platform: SocialPlatformSchema.nullable(),\n data: z.unknown(),\n});\nexport type SocialAnalytics = z.infer<typeof SocialAnalyticsSchema>;\n\nexport const SocialCommentSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_comment\"),\n identity_id: idOf(\"idn\"),\n post_id: z.string().min(1),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n posted_at: Timestamp.nullable(),\n data: z.unknown(),\n});\nexport type SocialComment = z.infer<typeof SocialCommentSchema>;\n\n/** Where a post stands in `GET /v1/posts` (§27.1): waiting on a person, due, out, or refused. */\nexport const POST_STATUSES = [\"pending\", \"scheduled\", \"posted\", \"failed\"] as const;\nexport const PostStatusSchema = z.enum(POST_STATUSES);\nexport type PostStatus = z.infer<typeof PostStatusSchema>;\n\n/**\n * One post as the posts view lists it (§27.1, ADR-0890): a parked `social.post` call (`pending`) or\n * a `social_post` row. A pending post has no provider id yet, so its `id` is\n * `<session_id>:<tool_call_id>`, the address a decision is posted to.\n */\nexport const PostSchema = z.object({\n object: z.literal(\"post\"),\n id: z.string().min(1),\n status: PostStatusSchema,\n identity_id: z.string().nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n tool_call_id: z.string().nullable(),\n content: z.string().nullable(),\n platforms: z.array(z.string()),\n file_ids: z.array(z.string()),\n media_urls: z.array(z.string()),\n visibility: SocialVisibilitySchema.nullable(),\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The latest stored reading, `{metric: value}`; `null` before `social.post_metrics` read any. */\n metrics: z.record(z.string(), z.number()).nullable(),\n measured_at: Timestamp.nullable(),\n /** Pending only: the earlier post this call would repeat — same identity, network and file. */\n duplicate_of: z\n .object({\n id: z.string(),\n status: PostStatusSchema,\n platform: z.string(),\n at: Timestamp.nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n })\n .nullable(),\n created_at: Timestamp,\n});\nexport type Post = z.infer<typeof PostSchema>;\n","/**\n * The harness catalog — the one layer a customer selects at agent create (§19).\n *\n * `billing` is how the loop is paid for. `location` is where it can run. Hosted\n * sessions start only a hosted harness; a local one is stored and fails closed.\n */\n\nimport { z } from \"zod\";\n\nexport const HARNESS_IDS = [\"pi\", \"claude_code\", \"vetta\", \"hermes\"] as const;\nexport type HarnessId = (typeof HARNESS_IDS)[number];\n\nexport const HarnessIdSchema = z.enum(HARNESS_IDS);\n\n/**\n * The four facts an admission check can act on **today**, and no more (`CLAUDE.md §3`):\n *\n * - `approvals` — the loop can hold a tool call and wait for a decision on\n * `POST /v1/sessions/{id}/tool_confirmations` (§6). A loop without it cannot serve a toolset\n * whose permission is `ask`.\n * - `structuredOutput` — it can honour `structured_output_required` (§16).\n * - `streamingDeltas` — it emits incremental deltas rather than only a completed message (§8).\n * - `injectedTools` — THE PLATFORM'S TOOLS REACH THIS LOOP'S MODEL. Semantics, not mechanism: it\n * says the team tools (`send_to_agent`, `wait_for_agents`, `list_agents`, `board_read`,\n * `board_write`), an agent's `mcp_servers`, a connected account's tools, the Passport tools,\n * `social`, the app-declared MCP tools and `apps` are all offered to the model, governed by\n * `tools.configs`. There are TWO delivery mechanisms behind that one answer, and a caller should\n * not have to know which:\n * · an IN-ISOLATE loop reads `RuntimePort.runTurn`'s `input.tools` (`harness-pi/src/harness.ts`,\n * `harness-vetta/src/index.ts`);\n * · a PROCESS loop — a CLI in a micro-VM that carries its own toolset and could never read that\n * array — dials the session-scoped MCP bridge, `POST /v1/sandbox/mcp`, with the door token\n * already in its box. Which mechanism a harness uses is `RUNS_AS_A_PROCESS` below, and that\n * is the predicate `apps/runtime-do` gates its decorators on; it is NOT this field.\n * A `false` here is therefore still one fact with the same consequences — a coordinator cannot\n * run on such a loop, because its model would never be shown `send_to_agent` — but no published\n * harness declares it today.\n *\n * A `false` here is what lets a start refuse up front instead of promising behaviour the loop\n * cannot produce — the same fail-closed rule §4 applies to windows. Field names are TS\n * identifiers; the wire spells them `snake_case` like every other object (`code-standards §6`).\n */\nexport interface HarnessCapabilities {\n approvals: boolean;\n structuredOutput: boolean;\n streamingDeltas: boolean;\n injectedTools: boolean;\n}\n\n/**\n * Maturity, not place. `preview` says the loop runs but its contract may still move.\n *\n * `claude_code` is `ga` rather than a third `\"local\"` value: where a harness runs is already\n * `location`, and a `status` that answered the same question would be two fields to keep in\n * agreement — the day one changed, one of them would be wrong.\n */\nexport type HarnessStatus = \"ga\" | \"preview\";\n\n/**\n * WHAT A PARKED SESSION COSTS, WHICH IS NOT THE SAME QUESTION AS WHERE THE LOOP RUNS.\n *\n * `isolate` runs the loop in the session object itself: its workspace is rows in that object's own\n * storage, so a session between turns holds no sandbox and bills storage only. `sandbox` runs the\n * agent as a process on a micro-VM, which the session holds across turns — the same profile `pi`\n * has, and unavoidable for a harness that is a process rather than a loop we host.\n *\n * Published because it is a real difference in what a customer pays for an idle session, and\n * without it they would discover it from a bill rather than from the catalogue.\n */\nexport type HarnessExecution = \"isolate\" | \"sandbox\" | \"local\";\n\n/**\n * WHETHER THE HOSTED RUNTIME HAS A DISPATCHER FOR THIS LOOP — separate from `status`, and from\n * `location`, because it answers a different question: not \"how settled is the contract\" and not\n * \"whose machine runs it\", but \"will a session on it actually run today\".\n *\n * `vetta` is `preview` AND runnable; `hermes` is neither. Without this a session on a loop the\n * runtime refuses is admitted, queued, and then burns the turn engine's five-attempt retry ladder\n * on an error that can never succeed before parking as `failed` — minutes of a customer's time to\n * reach an answer we knew at start.\n */\n\nexport const HARNESSES = {\n pi: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Pi\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"ga\",\n capabilities: {\n approvals: true,\n structuredOutput: true,\n streamingDeltas: true,\n injectedTools: true,\n },\n },\n claude_code: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Claude Code\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * `approvals` IS THE LOAD-BEARING FALSE. The turn runs with `--permission-mode\n * bypassPermissions`, which is not a preference: measured, without it every tool call in\n * one-shot mode is DENIED outright — not prompted — and the turn still exits 0 having done\n * nothing. So nothing can hold a call for a decision, and `true` here would admit an `ask`\n * toolset and then bypass it in silence, which is the failure the catalogue exists to prevent.\n * `structured_output`: no schema is passed. `streaming_deltas`: the stream carries whole\n * assistant messages, never token deltas.\n *\n * `injectedTools` IS TRUE, AND NOT BECAUSE THE CLI LEARNED TO READ `input.tools` — it still\n * does not, and never will. `harness-claude-code-hosted` writes a per-turn MCP config in the\n * session's folder naming the session-scoped bridge and joins `--mcp-config …\n * --strict-mcp-config` to the command, so the platform's tools reach the model as MCP tools\n * of one server. `tools.configs` still governs them, by the same `server.tool` /\n * `<connector>.<tool>` names: the bridge applies `permissionOf` before it answers\n * `tools/list`, so a `deny` is never emitted and cannot be called. `approvals` staying\n * `false` is what makes an `ask` OMITTED rather than gated — nothing under\n * `bypassPermissions` can hold a call, so omission is the only honest enforcement, and\n * `startSession` still refuses an explicit `ask` toolset here outright.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n vetta: {\n execution: \"isolate\",\n runnable: true,\n label: \"Naive\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * `injectedTools`: `index.ts` spreads `input.tools` into the toolset it builds. `approvals`: an\n * `ask` call parks the turn on pi's ledger and runs once a person allows it (ADR-1276).\n */\n capabilities: {\n approvals: true,\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\n/**\n * Whether `orgId` may run `id`. `vetta` runs only for the orgs in `VETTA_HARNESS_ORG_IDS` (`*` for\n * every org) until it is proven. Asked at every start: a session's (`apps/api` `runnableHere`) and a\n * delegated thread's (`apps/runtime-do` `threads.ts`), ADR-1405.\n */\nexport function orgMayRun(id: HarnessId, vettaOrgs: ReadonlySet<string>, orgId: string): boolean {\n return id !== \"vetta\" || vettaOrgs.has(\"*\") || vettaOrgs.has(orgId);\n}\n\nexport function harnessOption(id: HarnessId): string {\n const spec = HARNESSES[id];\n const bill = spec.billing === \"usage\" ? \"Naive usage-based\" : \"your logged-in account\";\n const place = spec.location === \"hosted\" ? \"hosted\" : \"local CLI\";\n return `${spec.label} — ${bill}, ${place}`;\n}\n","/**\n * Model auto-selection (`canonical-spec §46`, ADR-0722): a caller names a few catalogue ids with a\n * one-line brief each and gets one of them back. Field-shape rules live here; the two rules that\n * need the catalogue (every option key is an exact entry id) or the ledger (the price) belong to\n * the route.\n *\n * The same `options`/`min_confidence` pair is a **policy** (§46.6, ADR-0723) when it rides beside a\n * `model` on a proxy call or an agent — there the sibling `model` is the default.\n *\n * A plain `z.object` with refinements, not a `.transform`/pipe: `parseBody` reads `.shape` to\n * refuse unknown keys under strict bodies.\n */\n\nimport { z } from \"zod\";\n\nexport const MODEL_SELECTION_MIN_OPTIONS = 2;\nexport const MODEL_SELECTION_MAX_OPTIONS = 16;\nexport const MODEL_SELECTION_MAX_MESSAGES = 32;\n/** Summed `content` length across every message — nothing is silently trimmed to fit. */\nexport const MODEL_SELECTION_MAX_CONTENT_CHARS = 32_000;\n\nexport const ModelSelectionMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().min(1),\n});\nexport type ModelSelectionMessage = z.infer<typeof ModelSelectionMessageSchema>;\n\nconst OptionsSchema = z\n .record(z.string().min(1), z.string().trim().min(1).max(500))\n .refine((options) => Object.keys(options).length >= MODEL_SELECTION_MIN_OPTIONS, {\n message: `at least ${MODEL_SELECTION_MIN_OPTIONS} options are required`,\n })\n .refine((options) => Object.keys(options).length <= MODEL_SELECTION_MAX_OPTIONS, {\n message: `at most ${MODEL_SELECTION_MAX_OPTIONS} options are allowed`,\n });\n\n/** §46.6: the selector's inputs minus the conversation and the default, which the carrier supplies. */\nexport const ModelSelectionPolicySchema = z.object({\n options: OptionsSchema,\n min_confidence: z.number().gt(0).max(1).optional(),\n});\nexport type ModelSelectionPolicy = z.infer<typeof ModelSelectionPolicySchema>;\n\n/** The one rule a policy cannot check alone: its default (`model`) must be one of its options. */\nexport const policyNamesDefault = (policy: ModelSelectionPolicy, model: string): boolean =>\n Object.hasOwn(policy.options, model);\n\n/**\n * The most recent turns that fit §46.2's caps, oldest first, for a conversation the caller cannot\n * be asked to shorten (§46.6). Every message is kept whole except the newest, which keeps its\n * tail when it alone is over the limit.\n */\nexport function selectionTail(messages: readonly ModelSelectionMessage[]): ModelSelectionMessage[] {\n const out: ModelSelectionMessage[] = [];\n let chars = 0;\n for (const message of [...messages].reverse()) {\n if (out.length === MODEL_SELECTION_MAX_MESSAGES) break;\n if (chars + message.content.length > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n if (out.length === 0) {\n out.push({ role: message.role, content: message.content.slice(-MODEL_SELECTION_MAX_CONTENT_CHARS) });\n }\n break;\n }\n chars += message.content.length;\n out.push(message);\n }\n return out.reverse();\n}\n\nexport const ModelSelectionRequestSchema = z\n .object({\n options: OptionsSchema,\n messages: z.array(ModelSelectionMessageSchema).min(1).max(MODEL_SELECTION_MAX_MESSAGES),\n default: z.string().min(1).optional(),\n min_confidence: z.number().gt(0).max(1).optional(),\n })\n .superRefine((body, ctx) => {\n const total = body.messages.reduce((sum, message) => sum + message.content.length, 0);\n if (total > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"messages\"],\n message: `total message content exceeds ${MODEL_SELECTION_MAX_CONTENT_CHARS} characters`,\n });\n }\n if (body.default !== undefined && !Object.hasOwn(body.options, body.default)) {\n ctx.addIssue({ code: \"custom\", path: [\"default\"], message: \"default must be one of the options\" });\n }\n if (body.min_confidence !== undefined && body.default === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"min_confidence\"],\n message: \"min_confidence requires a default to fall back to\",\n });\n }\n });\nexport type ModelSelectionRequest = z.infer<typeof ModelSelectionRequestSchema>;\n\nexport const ModelSelectionSchema = z.object({\n object: z.literal(\"model_selection\"),\n model: z.string().min(1),\n confidence: z.number().min(0).max(1).nullable(),\n probabilities: z.record(z.string(), z.number()).nullable(),\n defaulted: z.boolean(),\n spent_micro_usd: z.number().int().nonnegative(),\n usage: z.object({ input_tokens: z.number().int().nonnegative() }),\n});\nexport type ModelSelection = z.infer<typeof ModelSelectionSchema>;\n","/** Trading — a brokerage an identity connects, and an agent trades through (`canonical-spec §62`). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const TradingEnvSchema = z.enum([\"paper\", \"live\"]);\nexport type TradingEnv = z.infer<typeof TradingEnvSchema>;\n\nexport const TradingConnectionStatusSchema = z.enum([\"pending\", \"active\", \"expired\", \"failed\"]);\nexport type TradingConnectionStatus = z.infer<typeof TradingConnectionStatusSchema>;\n\nexport const TradingAssetClassSchema = z.enum([\"us_equity\", \"crypto\", \"us_option\"]);\nexport const TradingOrderSideSchema = z.enum([\"buy\", \"sell\"]);\nexport const TradingOrderTypeSchema = z.enum([\"market\", \"limit\", \"stop\", \"stop_limit\"]);\nexport const TradingTimeInForceSchema = z.enum([\"day\", \"gtc\", \"ioc\", \"fok\", \"opg\", \"cls\"]);\n\n/** A quantity is not money: a decimal string, so fractional shares and coins survive (§62.1). */\n/**\n * A symbol or a broker order id ends up as one URL path segment at the broker. Starting with a letter\n * or digit rules out `.` and `..`, which a URL parser collapses onto the collection — `DELETE` on the\n * collection closes every position or cancels every order.\n */\nexport const TradingSymbolSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9./-]{0,63}$/, \"a ticker like AAPL, or a pair like BTC/USD\");\n/**\n * A position's symbol, which is a path segment at the broker (close): no `/` at all — positions are\n * concatenated (`BTCUSD`), and a slash would let `BTC/..` climb back onto the collection. Order and\n * quote symbols keep `TradingSymbolSchema`: they travel in a body or a query string, never a path.\n */\nexport const TradingPositionSymbolSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,63}$/, \"a position symbol like AAPL or BTCUSD\");\nexport const TradingOrderIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/, \"an order id\");\n\nexport const TradingQtySchema = z\n .string()\n .regex(/^\\d+(\\.\\d{1,9})?$/, \"a decimal quantity like \\\"0.0125\\\"\")\n .refine((qty) => /[1-9]/.test(qty), \"must be greater than zero\");\n\n/** The broker-required consent text. It names Naïve because the brokerage OAuth app is Naïve's (ADR-1189). */\nexport const TRADING_DISCLOSURE =\n \"By allowing Naïve to access your brokerage account, you are granting Naïve access to your account \" +\n \"information and authorization to place transactions in your account at your direction. Your brokerage \" +\n \"does not warrant or guarantee that Naïve will work as advertised or expected. Before authorizing, learn \" +\n \"more about Naïve at https://usenaive.ai.\";\n\nexport const TradingConnectionSchema = z.object({\n object: z.literal(\"trading_connection\"),\n identity_id: idOf(\"idn\"),\n env: TradingEnvSchema,\n status: TradingConnectionStatusSchema,\n account_number: z.string().nullable(),\n scope: z.string().nullable(),\n status_reason: z.string().max(300).nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type TradingConnection = z.infer<typeof TradingConnectionSchema>;\n\nexport const TradingConnectSchema = z.object({\n object: z.literal(\"trading_connect\"),\n /** https only: a client opens this in a browser, so `javascript:`, `data:` or plain `http:` is refused. */\n authorize_url: z.url({ protocol: /^https$/ }),\n env: TradingEnvSchema,\n disclosure: z.string(),\n});\nexport type TradingConnect = z.infer<typeof TradingConnectSchema>;\n\nexport const TradingAccountSchema = z.object({\n object: z.literal(\"trading_account\"),\n env: TradingEnvSchema,\n account_number: z.string(),\n /** The broker's account status, verbatim. */\n status: z.string(),\n cash_micro_usd: MicroUsdField,\n buying_power_micro_usd: MicroUsdField,\n equity_micro_usd: MicroUsdField,\n});\nexport type TradingAccount = z.infer<typeof TradingAccountSchema>;\n\nexport const TradingPositionSchema = z.object({\n object: z.literal(\"trading_position\"),\n /** Crypto positions are concatenated (`BTCUSD`), unlike order and quote symbols (`BTC/USD`). */\n symbol: z.string().min(1),\n asset_class: TradingAssetClassSchema,\n side: z.enum([\"long\", \"short\"]),\n qty: z.string(),\n avg_entry_price_micro_usd: MicroUsdField,\n current_price_micro_usd: MicroUsdField.nullable(),\n market_value_micro_usd: MicroUsdField.nullable(),\n unrealized_pl_micro_usd: MicroUsdField.nullable(),\n});\nexport type TradingPosition = z.infer<typeof TradingPositionSchema>;\n\nexport const TradingOrderSchema = z.object({\n object: z.literal(\"trading_order\"),\n /** The broker's order id — opaque, not ours. */\n id: z.string().min(1),\n client_order_id: z.string().nullable(),\n symbol: z.string().min(1),\n asset_class: TradingAssetClassSchema,\n side: TradingOrderSideSchema,\n type: TradingOrderTypeSchema,\n time_in_force: TradingTimeInForceSchema,\n qty: z.string().nullable(),\n notional_micro_usd: MicroUsdField.nullable(),\n filled_qty: z.string(),\n filled_avg_price_micro_usd: MicroUsdField.nullable(),\n limit_price_micro_usd: MicroUsdField.nullable(),\n stop_price_micro_usd: MicroUsdField.nullable(),\n extended_hours: z.boolean(),\n /** The broker's order status, verbatim (`new`, `filled`, `canceled`, …). */\n status: z.string(),\n created_at: Timestamp,\n filled_at: Timestamp.nullable(),\n canceled_at: Timestamp.nullable(),\n});\nexport type TradingOrder = z.infer<typeof TradingOrderSchema>;\n\nexport const TradingQuoteSchema = z.object({\n object: z.literal(\"trading_quote\"),\n symbol: z.string().min(1),\n asset_class: z.enum([\"us_equity\", \"crypto\"]),\n bid_price_micro_usd: MicroUsdField,\n ask_price_micro_usd: MicroUsdField,\n bid_size: z.string(),\n ask_size: z.string(),\n quoted_at: Timestamp,\n});\nexport type TradingQuote = z.infer<typeof TradingQuoteSchema>;\n\nconst PositiveMicroUsd = MicroUsdField.positive();\n\n/**\n * §62.2. Exactly one of `qty`/`notional_micro_usd`; a limit price for `limit|stop_limit` only, a stop\n * price for `stop|stop_limit` only. No default `type` or `time_in_force`: a money path never guesses\n * `market`. Venue rules (crypto `gtc|ioc`, minimum notional) are the broker's to refuse.\n */\nconst OrderFields = {\n symbol: TradingSymbolSchema,\n side: TradingOrderSideSchema,\n type: TradingOrderTypeSchema,\n time_in_force: TradingTimeInForceSchema,\n qty: TradingQtySchema.optional(),\n notional_micro_usd: PositiveMicroUsd.optional(),\n limit_price_micro_usd: PositiveMicroUsd.optional(),\n stop_price_micro_usd: PositiveMicroUsd.optional(),\n extended_hours: z.boolean().optional(),\n};\n\ntype OrderShape = { type: z.infer<typeof TradingOrderTypeSchema>; qty?: string | undefined; notional_micro_usd?: number | undefined; limit_price_micro_usd?: number | undefined; stop_price_micro_usd?: number | undefined };\n\nfunction orderRules(body: OrderShape, ctx: z.RefinementCtx): void {\n const issue = (path: string, message: string) => ctx.addIssue({ code: \"custom\", path: [path], message });\n if ((body.qty === undefined) === (body.notional_micro_usd === undefined)) {\n issue(body.qty === undefined ? \"qty\" : \"notional_micro_usd\", \"give exactly one of qty or notional_micro_usd\");\n }\n const limited = body.type === \"limit\" || body.type === \"stop_limit\";\n const stopped = body.type === \"stop\" || body.type === \"stop_limit\";\n if (limited !== (body.limit_price_micro_usd !== undefined)) {\n issue(\"limit_price_micro_usd\", limited ? `required for a ${body.type} order` : `not allowed on a ${body.type} order`);\n }\n if (stopped !== (body.stop_price_micro_usd !== undefined)) {\n issue(\"stop_price_micro_usd\", stopped ? `required for a ${body.type} order` : `not allowed on a ${body.type} order`);\n }\n}\n\nexport const PlaceTradingOrderSchema = z\n .object({ env: TradingEnvSchema.optional(), ...OrderFields, client_order_id: z.string().min(1).max(128).optional() })\n .strict()\n .superRefine(orderRules);\nexport type PlaceTradingOrder = z.infer<typeof PlaceTradingOrderSchema>;\n\n/**\n * The agent's `trading.place_order` arguments (§62.6): `env` is required, so the approval card names\n * the account, and there is no `client_order_id` — the call's own Effect-ledger key is used.\n */\nexport const PlaceTradingOrderToolSchema = z.object({ env: TradingEnvSchema, ...OrderFields }).strict().superRefine(orderRules);\n\nconst CloseFields = {\n qty: TradingQtySchema.optional(),\n percentage: z\n .string()\n .regex(/^\\d+(\\.\\d{1,9})?$/, \"a decimal percentage like \\\"50\\\"\")\n .refine((p) => Number(p) > 0 && Number(p) <= 100, \"must be in (0, 100]\")\n .optional(),\n};\nconst atMostOne = (body: { qty?: string | undefined; percentage?: string | undefined }): boolean =>\n body.qty === undefined || body.percentage === undefined;\nconst AT_MOST_ONE = { path: [\"percentage\"], message: \"give at most one of qty or percentage\" };\n\n/** §62.2: at most one of `qty`/`percentage`; neither closes the whole position. */\nexport const CloseTradingPositionSchema = z\n .object({ env: TradingEnvSchema.optional(), ...CloseFields })\n .strict()\n .refine(atMostOne, AT_MOST_ONE);\nexport type CloseTradingPosition = z.infer<typeof CloseTradingPositionSchema>;\n\n/** The agent's `trading.close_position` arguments (§62.6): `env` required, the symbol in the body. */\nexport const CloseTradingPositionToolSchema = z\n .object({ env: TradingEnvSchema, symbol: TradingPositionSymbolSchema, ...CloseFields })\n .strict()\n .refine(atMostOne, AT_MOST_ONE);\n\n/** The agent's money-moving trading tools (§62.6): asked by default, never granted for the chat. */\nexport const TRADING_WRITE_TOOLS = [\"trading.place_order\", \"trading.cancel_order\", \"trading.close_position\"] as const;\n\n/**\n * D1 (ADR-1189): live never trades unasked. Under an `allow` policy, a write call still asks unless\n * it names `env: \"paper\"` — an omitted env may resolve to the identity's only connection, which may\n * be live. `permissionOf` is by name and cannot see the env, so the runtime asks this per call.\n */\nexport const tradingCallAsks = (name: string, args: Record<string, unknown>): boolean => isTradingWrite(name) && args[\"env\"] !== \"paper\";\n\n/** The same three writes as the control plane's MCP tools (`identities_*_trading_*`), on any server's name. */\nconst TRADING_ROUTE_WRITES = [\"identities_place_trading_order\", \"identities_cancel_trading_order\", \"identities_close_trading_position\"];\n\n/**\n * A trading write by either name: the platform tool, or the route's MCP tool called directly. An operator\n * may `allow` the MCP name by hand, and D1 must hold there too.\n */\nexport const isTradingWrite = (name: string): boolean =>\n (TRADING_WRITE_TOOLS as readonly string[]).includes(name) ||\n TRADING_ROUTE_WRITES.some((tool) => name === tool || name.endsWith(`.${tool}`) || name.endsWith(`__${tool}`));\n","/**\n * The creator program (`canonical-spec §42`) — creators, their applications, referrals,\n * commissions, payouts and creator templates.\n *\n * None of these objects belongs to an organization (§42.12): a creator is a person keyed by email,\n * and a referral or a commission *points at* an organization's rows without living in the tenant.\n * Money is integer micro-USD, `floor`ed, USD only (§1).\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** The referral code, and the namespace of every template the creator publishes: `c-<code>-<slug>`. */\nexport const CreatorCodeSchema = z\n .string()\n .regex(/^[a-z0-9]{3,24}$/, \"3 to 24 lowercase letters or digits\");\n\n/** `POST …/payouts` copies these onto the payout, so a later change never rewrites where money went. */\nexport const PayoutMethodSchema = z.enum([\"wise\", \"paypal\"]);\nexport type PayoutMethod = z.infer<typeof PayoutMethodSchema>;\n\nexport const PayoutDetailsSchema = z.object({\n method: PayoutMethodSchema,\n account: z.string().min(1).max(320),\n});\n\n/** `archived` is the admin's delete: off the list and inert like `suspended`, its history kept (§42.4). */\nexport const CreatorStatusSchema = z.enum([\"active\", \"suspended\", \"archived\"]);\nexport type CreatorStatus = z.infer<typeof CreatorStatusSchema>;\n\n/**\n * Where the creator came from — a reviewer's label, `null` when untagged (§42.1, ADR-1323).\n * `doomscroll` is set by self sign-up instead: links builds only, no referral earnings (ADR-1632).\n */\nexport const CreatorSourceSchema = z.enum([\"youtube\", \"channel_license\", \"doomscroll\"]);\nexport type CreatorSource = z.infer<typeof CreatorSourceSchema>;\n\n/**\n * A reviewer's per-creator studio budget override (§42.1). Positive µUSD, capped a long way above\n * the program default so a mistyped figure cannot hand one draft an unbounded spend.\n */\nexport const CreatorStudioBudgetSchema = MicroUsdField.positive().max(10_000_000_000);\n\nexport const CreatorSchema = z.object({\n id: idOf(\"crt\"),\n object: z.literal(\"creator\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n code: CreatorCodeSchema,\n status: CreatorStatusSchema,\n /** Optional on input so rows written before migration 0114 still parse; the API always answers it. */\n source: CreatorSourceSchema.nullable().optional(),\n payout: PayoutDetailsSchema.nullable(),\n clicks: z.number().int().nonnegative(),\n /** This creator's per-draft studio cap, overriding `CREATOR_PROGRAM.studio`; `null` = the default. */\n studio_budget_micro_usd: CreatorStudioBudgetSchema.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Creator = z.infer<typeof CreatorSchema>;\n\n/** What `GET /v1/me` carries for a signed-in person (§20.1, §42.3). */\nexport const IdentityCreatorSchema = CreatorSchema.pick({\n id: true,\n status: true,\n});\nexport type IdentityCreator = z.infer<typeof IdentityCreatorSchema>;\n\nexport const CreatorApplicationStatusSchema = z.enum([\n \"pending\",\n \"approved\",\n \"rejected\",\n]);\nexport type CreatorApplicationStatus = z.infer<\n typeof CreatorApplicationStatusSchema\n>;\n\nexport const CreatorApplicationSchema = z.object({\n id: idOf(\"cra\"),\n object: z.literal(\"creator_application\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n pitch: z.string().min(1).max(2000),\n links: z.array(z.url({ protocol: /^https$/ })).max(5),\n status: CreatorApplicationStatusSchema,\n note: z.string().nullable(),\n creator_id: idOf(\"crt\").nullable(),\n created_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorApplication = z.infer<typeof CreatorApplicationSchema>;\n\n/** Derived: `pending` until the first paid invoice, `active` for 12 months from it, `expired` after (§42.1). */\nexport const ReferralStatusSchema = z.enum([\"pending\", \"active\", \"expired\"]);\nexport type ReferralStatus = z.infer<typeof ReferralStatusSchema>;\n\nexport const ReferralSchema = z.object({\n id: idOf(\"crf\"),\n object: z.literal(\"referral\"),\n creator_id: idOf(\"crt\"),\n organization_id: idOf(\"org\"),\n status: ReferralStatusSchema,\n attributed_at: Timestamp,\n first_paid_at: Timestamp.nullable(),\n commission_until: Timestamp.nullable(),\n /** Opaque per-creator hash of the referred person, so organizations group by person; never the email. */\n person_key: z.string().nullable().optional(),\n});\nexport type Referral = z.infer<typeof ReferralSchema>;\n\n/**\n * `clawback` (0142, ADR-1594): a refund or a dispute taking back part of a row, or a won dispute giving it back.\n * `bonus` (0164, ADR-1763): a doomscroll account's fixed credit, for joining or for a template going live.\n */\nexport const CommissionKindSchema = z.enum([\"referral\", \"template\", \"clawback\", \"bonus\"]);\nexport type CommissionKind = z.infer<typeof CommissionKindSchema>;\n\n/** Derived from `available_at` and the payout the row is claimed by, never stored (§42.1). */\nexport const CommissionStatusSchema = z.enum([\n \"pending\",\n \"available\",\n \"claimed\",\n \"paid\",\n]);\nexport type CommissionStatus = z.infer<typeof CommissionStatusSchema>;\n\nexport const CommissionSchema = z.object({\n id: idOf(\"crc\"),\n object: z.literal(\"commission\"),\n creator_id: idOf(\"crt\"),\n kind: CommissionKindSchema,\n referral_id: idOf(\"crf\").nullable(),\n install_id: idOf(\"bpi\").nullable(),\n creator_template_id: idOf(\"ctp\").nullable(),\n /** The row a `clawback` changes; `null` on every other kind. Optional so a client typed before it still reads. */\n reverses_id: idOf(\"crc\").nullable().optional(),\n base_micro_usd: MicroUsdField.nonnegative(),\n /** Never negative, except on a `clawback`: what a refund or a dispute took back. */\n amount_micro_usd: MicroUsdField,\n status: CommissionStatusSchema,\n accrued_at: Timestamp,\n available_at: Timestamp,\n payout_id: idOf(\"crp\").nullable(),\n});\nexport type Commission = z.infer<typeof CommissionSchema>;\n\nexport const PayoutStatusSchema = z.enum([\"requested\", \"paid\", \"rejected\"]);\nexport type PayoutStatus = z.infer<typeof PayoutStatusSchema>;\n\nexport const PayoutSchema = z.object({\n id: idOf(\"crp\"),\n object: z.literal(\"payout\"),\n creator_id: idOf(\"crt\"),\n amount_micro_usd: MicroUsdField.positive(),\n currency: z.literal(\"USD\"),\n method: PayoutMethodSchema,\n account: z.string().min(1),\n status: PayoutStatusSchema,\n reference: z.string().nullable(),\n note: z.string().nullable(),\n requested_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type Payout = z.infer<typeof PayoutSchema>;\n\n/** The percentages and thresholds of §42.7, §42.9 and §42.10, in one place so no route restates them. */\nexport const CREATOR_PROGRAM = {\n referral_percent: 15,\n /** Of each qualifying subscription invoice of an org whose FIRST install was the template. */\n template_percent: 15,\n commission_months: 12,\n hold_days: 30,\n attribution_days: 30,\n /** A template install earns only for an org it was installed in within this many days of creation. */\n template_new_org_days: 35,\n minimum_payout_micro_usd: 100_000_000,\n /** How many of one company's listings may wait in review at once (ADR-1747). */\n listings_in_review: 3,\n /** The creator studio's per-draft spend caps; one session never plans past what the draft has left. */\n studio: {\n /** At least two whole rounds, a build plus one revision: 2 × (author + demo) = 44 ≤ 54 (ADR-1345). */\n draft_budget_micro_usd: 54_000_000,\n /** Sonnet-class author with dense frames and a transcript per video (ADR-1344). */\n author_budget_micro_usd: 12_000_000,\n /** One ~15 s three-scene sample: worst case ~$8.60 at customer price, so $10 (ADR-1345). */\n demo_budget_micro_usd: 10_000_000,\n /** One Opus judge of an internal build's ready round: frames, a transcript and a verdict (§57.6, ADR-1754). */\n judge_budget_micro_usd: 3_000_000,\n /** A sample's length when its build asks none, and the range a build may ask (§57.2, ADR-1762). */\n sample_seconds: 15,\n sample_seconds_min: 10,\n sample_seconds_max: 60,\n uploads: 3,\n upload_max_bytes: 60 * 1024 * 1024,\n upload_token_minutes: 15,\n skill_max_bytes: 32 * 1024,\n /** The reviewer's install check (§42.5): the hard cap on its one session, never charged to the draft. */\n review_check_budget_micro_usd: 5_000_000,\n },\n} as const;\n\n/**\n * Doomscroll's pay terms (ADR-1763, owner 2026-11-02), for a creator whose `source` is `doomscroll`:\n * a bonus on joining, a bonus for each of its first templates to go live, the template percent of the\n * FIRST payment of each new company that starts with one of its templates, and its own payout bar.\n * No hold: every row is available the moment it accrues, so only the payout bar gates a withdrawal\n * (owner 2026-11-02). Attribution is the program's (§42.9).\n */\nexport const DOOMSCROLL_PROGRAM = {\n join_bonus_micro_usd: 20_000_000,\n template_bonus_micro_usd: 1_000_000,\n template_bonus_cap: 10,\n template_percent: 15,\n minimum_payout_micro_usd: 200_000_000,\n hold_days: 0,\n} as const;\n\n/** How long this creator's commission is held before it is available: doomscroll's, else the program's. */\nexport const holdDaysOf = (creator: Pick<Creator, \"source\">): number =>\n creator.source === \"doomscroll\" ? DOOMSCROLL_PROGRAM.hold_days : CREATOR_PROGRAM.hold_days;\n\n/** The payout bar for this creator: doomscroll's, else the program's. */\nexport const minimumPayoutOf = (creator: Pick<Creator, \"source\">): number =>\n creator.source === \"doomscroll\" ? DOOMSCROLL_PROGRAM.minimum_payout_micro_usd : CREATOR_PROGRAM.minimum_payout_micro_usd;\n\n/** What a listed template earns, in the program's numbers: the tool, the card and the docs say this. */\nexport const TEMPLATE_EARNINGS = `${CREATOR_PROGRAM.template_percent}% of what each new company that starts with it pays, for ${CREATOR_PROGRAM.commission_months} months`;\n\n/**\n * The per-draft studio cap in force for a creator: their reviewer-set override, else the program\n * default. The API gate and every surface that prints a draft's cap read it through here, so an\n * override never shows on one screen and not the next.\n */\nexport const studioDraftBudget = (creator: Pick<Creator, \"studio_budget_micro_usd\"> | null | undefined): number =>\n creator?.studio_budget_micro_usd ?? CREATOR_PROGRAM.studio.draft_budget_micro_usd;\n\n/**\n * Creator Studio accepts reference videos and produces short-form video channel templates, so its\n * one base is the short-form media crew. Keep this in core: the creator UI and the API gate must\n * not drift back to different answers about what a studio draft installs.\n */\nexport const CREATOR_STUDIO_BASE = { blueprint: \"media\", template: \"faceless\" } as const;\n\n/** The creator's own part of the catalog key; `template` is `c-<code>-<slug>` (§42.8). */\nexport const CreatorTemplateSlugSchema = z\n .string()\n .max(32)\n .regex(\n /^[a-z0-9]+(-[a-z0-9]+)*$/,\n \"lowercase letters, digits and single dashes\",\n );\n\n/** The namespaced catalog key: what `POST /v1/blueprints/installs` receives as `template`. */\nexport const creatorTemplateName = (code: string, slug: string): string =>\n `c-${code}-${slug}`;\n\n/**\n * An org's own template's `slug` and `template` (§42.1, ADR-1338): its id's suffix, so unique without\n * a name, and `c-<suffix>` with one dash, which no creator's `c-<code>-<slug>` can equal.\n */\nexport const orgTemplateKeys = (id: string): { slug: string; template: string } => {\n const suffix = id.slice(id.indexOf(\"_\") + 1);\n return { slug: suffix, template: `c-${suffix}` };\n};\n\n/**\n * A named org template's `slug` and `template` (ADR-1758): its name in lowercase words, cut at a\n * word to fit the slug's 32 characters (`AI Animal Dancing in Subways` → `c-ai-animal-dancing-in-subways`),\n * so the catalog key and its page URL read as the template. `suffixed` appends the id's last four\n * characters for a name already taken. A name with no letter or digit has no words: the id's keys.\n */\nexport const namedTemplateKeys = (id: string, name: string, suffixed = false): { slug: string; template: string } => {\n const tail = suffixed ? `-${id.slice(-4)}` : \"\";\n const words = name.toLowerCase().normalize(\"NFKD\").replace(/[\\u0300-\\u036f]/g, \"\").match(/[a-z0-9]+/g) ?? [];\n let slug = \"\";\n for (const word of words) {\n const next = slug === \"\" ? word : `${slug}-${word}`;\n if (next.length + tail.length > 32) break;\n slug = next;\n }\n if (slug === \"\") return orgTemplateKeys(id);\n return { slug: slug + tail, template: `c-${slug}${tail}` };\n};\n\n/** One `SKILL.md` travelling with the declaration — a creator has no checkout for the engine's `file`. */\nexport const CreatorSkillSchema = z.object({\n slug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"lowercase letters, digits and dashes\"),\n body: z\n .string()\n .min(1)\n .max(64 * 1024),\n});\nexport type CreatorSkill = z.infer<typeof CreatorSkillSchema>;\n\n/**\n * The version `declaration` (§42.2). `agents[]` is exactly `AgentDeclSchema` and `questions[]`\n * exactly `QuestionFieldSchema`, but `AgentDeclSchema` lives in `@usenaive-sdk/blueprints`, which\n * depends on core — so core types those two arrays as `unknown` and the API validates a submission\n * by composing the artifact declaration and running the engine's `parseProject` over it. The draft\n * is checked for this shape only; a half-written crew may be saved.\n */\n/**\n * One of a company's own apps as words, never code (ADR-1552, R1): its name and what it does, its\n * screens and its data. A private template seeds each as an unassigned board card the new crew's CEO\n * builds once a person hands it over, the way the app store's starter briefs work.\n */\nexport const AppBriefSchema = z.object({\n name: z.string().min(1).max(60),\n brief: z.string().min(1).max(1200),\n});\nexport type AppBrief = z.infer<typeof AppBriefSchema>;\n\nexport const CreatorDeclarationSchema = z.object({\n agents: z.array(z.unknown()),\n questions: z.array(z.unknown()),\n skills: z.array(CreatorSkillSchema).max(16),\n /** A company's own apps (ADR-1552). Present, even empty, the template seeds no task of its base's. */\n briefs: z.array(AppBriefSchema).max(8).optional(),\n /** A `niche` version only: the studio round it froze (see `NicheVersionStudioSchema`, below). */\n studio: z.lazy(() => NicheVersionStudioSchema).optional(),\n});\nexport type CreatorDeclaration = z.infer<typeof CreatorDeclarationSchema>;\n\nexport const CreatorTemplateVersionStatusSchema = z.enum([\n \"in_review\",\n \"approved\",\n \"changes_requested\",\n]);\nexport type CreatorTemplateVersionStatus = z.infer<\n typeof CreatorTemplateVersionStatusSchema\n>;\n\nconst VersionNumber = z.number().int().positive();\n\n/** `crew`: the hand-built crew declaration; `niche`: authored by agents in the creator studio. */\nexport const CreatorTemplateKindSchema = z.enum([\"crew\", \"niche\"]);\nexport type CreatorTemplateKind = z.infer<typeof CreatorTemplateKindSchema>;\n\n/** The studio lifecycle of a `niche` template; a `crew` template stays `setup` and never reads it. */\nexport const StudioStateSchema = z.enum([\n \"setup\",\n \"building\",\n \"ready\",\n \"in_review\",\n \"live\",\n \"changes_requested\",\n]);\nexport type StudioState = z.infer<typeof StudioStateSchema>;\n\nexport const StudioUploadContentTypeSchema = z.enum([\n \"video/mp4\",\n \"video/quicktime\",\n \"video/webm\",\n]);\nexport type StudioUploadContentType = z.infer<\n typeof StudioUploadContentTypeSchema\n>;\n\nconst UploadPosition = z.number().int().min(1).max(CREATOR_PROGRAM.studio.uploads);\nconst StudioPrompt = z.string().max(100_000);\n\n/** One of the three reference videos; `file_id` is null until its PUT lands (a studio-org file). */\nexport const StudioUploadSchema = z.object({\n position: UploadPosition,\n file_id: z.string().nullable(),\n prompt: StudioPrompt,\n bytes: z.number().int().positive().max(CREATOR_PROGRAM.studio.upload_max_bytes),\n content_type: StudioUploadContentTypeSchema,\n filename: z.string().min(1).max(200),\n});\nexport type StudioUpload = z.infer<typeof StudioUploadSchema>;\n\nexport const ReviewCheckStateSchema = z.enum([\"installing\", \"running\", \"done\", \"failed\"]);\nexport type ReviewCheckState = z.infer<typeof ReviewCheckStateSchema>;\n\n/** `studio.review_check` (§42.1): a reviewer's install check of one version, replaced by the next. */\nexport const ReviewCheckSchema = z.object({\n version: VersionNumber,\n state: ReviewCheckStateSchema,\n project: z.string().min(1),\n session_id: z.string().nullable(),\n file_id: z.string().nullable(),\n skill_loaded: z.boolean().nullable(),\n cost_micro_usd: MicroUsdField.nonnegative(),\n error: z.string().nullable(),\n started_at: Timestamp,\n finished_at: Timestamp.nullable(),\n});\nexport type ReviewCheck = z.infer<typeof ReviewCheckSchema>;\n\n/** One reel link of a links build; `done` once its video is an upload at the same position. */\nexport const StudioImportSchema = z.object({\n position: UploadPosition,\n url: z.string(),\n job_id: z.string(),\n state: z.enum([\"pending\", \"done\", \"failed\"]),\n error: z.string().nullable(),\n});\nexport type StudioImport = z.infer<typeof StudioImportSchema>;\n\nconst Seconds = z.number().nonnegative();\n/**\n * One reel studied in code by its source job, before any author runs (§34.4, ADR-1521): the probe,\n * every scene cut, the stills the authoring skill cuts (the opening second, the cuts past it — at\n * most 24, spread evenly — and the last frame) as files of the job's org, one contact sheet tiling\n * those stills in order (6 a row), and the speech in timed segments, `words` empty since ADR-1674\n * (`null`: none could be read).\n */\nexport const ReelAnalysisSchema = z.object({\n duration_seconds: z.number().positive(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n fps: z.number().positive(),\n cuts_seconds: z.array(Seconds).max(5_000),\n stills: z.array(z.object({ seconds: Seconds, file_id: z.string().min(1) })).max(40),\n sheet_file_id: z.string().min(1).nullable(),\n transcript: z\n .object({\n language: z.string().nullable(),\n segments: z.array(z.object({ start_seconds: Seconds, end_seconds: Seconds, text: z.string() })).max(5_000),\n words: z.array(z.object({ word: z.string(), start_seconds: Seconds, end_seconds: Seconds })).max(50_000),\n })\n .nullable(),\n});\nexport type ReelAnalysis = z.infer<typeof ReelAnalysisSchema>;\n\n/** The org skill an org's own build saved its newest ready round as (§57.3). */\nexport const SavedSkillSchema = z.object({\n id: idOf(\"skl\"),\n slug: z.string(),\n version: z.number().int().positive(),\n});\n/**\n * `studio.skill`: the slug is claimed before the first push, so a retry or a later round reuses it;\n * `id`/`version` are `null` until a push is recorded. Written only by `patchStudioSkill`.\n */\nexport const StudioSkillSchema = SavedSkillSchema.extend({\n id: idOf(\"skl\").nullable(),\n version: z.number().int().positive().nullable(),\n});\nexport type StudioSkill = z.infer<typeof StudioSkillSchema>;\n\n/** `creator_template.studio` (migration 0098). Empty `{}` in the database reads as this default. */\nexport const CreatorStudioSchema = z.object({\n uploads: z.array(StudioUploadSchema).max(CREATOR_PROGRAM.studio.uploads).default([]),\n /** `links`: built from 1–3 reel links (`imports`), prompts optional; `upload`: the creator's three videos. */\n origin: z.enum([\"upload\", \"links\"]).default(\"upload\"),\n imports: z.array(StudioImportSchema).max(CREATOR_PROGRAM.studio.uploads).default([]),\n state: StudioStateSchema.default(\"setup\"),\n spend_micro_usd: MicroUsdField.nonnegative().default(0),\n rights_attested_at: Timestamp.nullable().default(null),\n review_check: ReviewCheckSchema.nullable().default(null),\n /** `null` until an org build's first ready round is saved; always `null` on a creator's template. */\n skill: StudioSkillSchema.nullable().default(null),\n /** An org build's asked sample length (§57.2, ADR-1762); `null` is `sample_seconds`. */\n seconds: z.number().int().min(10).max(60).nullable().default(null),\n /** An org build's own catalog text: its request's description when that fits a tagline; `null` lets the judge write one. */\n tagline: z.string().max(140).nullable().default(null),\n});\nexport type CreatorStudio = z.infer<typeof CreatorStudioSchema>;\n\n/** The sample length a build's demo renders and its judge expects (ADR-1762). */\nexport const studioSeconds = (studio: Pick<CreatorStudio, \"seconds\">): number => studio.seconds ?? CREATOR_PROGRAM.studio.sample_seconds;\n\n/** A longer sample is more scenes to render: the demo's and the draft's caps scale with it, never below the ~15 s piece's. */\nexport const studioScale = (studio: Pick<CreatorStudio, \"seconds\">): number => Math.max(1, studioSeconds(studio) / CREATOR_PROGRAM.studio.sample_seconds);\n\n/** The reviewer-curated catalog columns of a creator template (migration 0098). */\nexport const CreatorTemplateListingSchema = z.object({\n listed: z.boolean(),\n featured: z.boolean(),\n sort_order: z.number().int(),\n tagline: z.string().max(140).nullable(),\n hero_file_id: z.string().nullable(),\n /**\n * The reviewer's takedown of an organization's listed template (migration 0132, ADR-1554): out of\n * the catalog and closed to new submissions. A creator's template is taken down with its creator.\n */\n suspended: z.boolean(),\n /**\n * \"Naive verified\" (0141, ADR-1593): written only by the reviewer's listing route. No organization's\n * or creator's template is verified today; our own catalog rows are, by the catalog read itself.\n */\n verified: z.boolean(),\n});\nexport type CreatorTemplateListing = z.infer<typeof CreatorTemplateListingSchema>;\n\nexport const StudioRoundStateSchema = z.enum([\n \"queued\",\n \"authoring\",\n \"rendering\",\n \"ready\",\n \"failed\",\n]);\nexport type StudioRoundState = z.infer<typeof StudioRoundStateSchema>;\n\n/** A generated, brand-free reference frame: `file` is its path in the skill folder (`reference/…`). */\nexport const StudioFrameSchema = z.object({\n file: z.string().min(1),\n file_id: z.string().min(1),\n role: z.string(),\n});\nexport type StudioFrame = z.infer<typeof StudioFrameSchema>;\n\nexport const StudioSampleSchema = z.object({\n file_id: z.string().min(1),\n poster_file_id: z.string().nullable(),\n seconds: z.number().nonnegative(),\n title: z.string(),\n /** The video models its scenes rendered on, as their `media_job` rows served them; absent on older rounds. */\n video_models: z.array(z.string()).optional(),\n});\nexport type StudioSample = z.infer<typeof StudioSampleSchema>;\n\n/** One build or revision (`vetta.creator_template_round`), keyed `(template_id, n)`. */\nexport const CreatorTemplateRoundSchema = z.object({\n object: z.literal(\"creator_template_round\"),\n template_id: idOf(\"ctp\"),\n n: z.number().int().positive(),\n feedback: z.string().nullable(),\n state: StudioRoundStateSchema,\n author_session_id: z.string().nullable(),\n demo_session_id: z.string().nullable(),\n skill_md: z.string().nullable(),\n reference_json: z.unknown().nullable(),\n frames: z.array(StudioFrameSchema),\n samples: z.array(StudioSampleSchema),\n spend_micro_usd: MicroUsdField.nonnegative(),\n error: z.string().nullable(),\n created_at: Timestamp,\n finished_at: Timestamp.nullable(),\n});\nexport type CreatorTemplateRound = z.infer<typeof CreatorTemplateRoundSchema>;\n\n/** What a `niche` version freezes beside its one skill: what the reviewer and the publish read. */\nexport const NicheVersionStudioSchema = z.object({\n round: z.number().int().positive(),\n uploads: z.array(StudioUploadSchema),\n reference_json: z.unknown().nullable(),\n frames: z.array(StudioFrameSchema),\n samples: z.array(StudioSampleSchema),\n tagline: z.string().max(140),\n hero_sample_index: z.number().int().nonnegative(),\n});\nexport type NicheVersionStudio = z.infer<typeof NicheVersionStudioSchema>;\n\nexport const CreatorTemplateSchema = z.object({\n id: idOf(\"ctp\"),\n object: z.literal(\"creator_template\"),\n /** Exactly one of the two is set (§42.1, migration 0116): a creator's template, or an org's own. */\n creator_id: idOf(\"crt\").nullable(),\n org_id: idOf(\"org\").nullable(),\n blueprint: z.string().min(1),\n base_template: z.string().min(1),\n slug: CreatorTemplateSlugSchema,\n template: z.string().min(1).max(64),\n name: z.string().min(1).max(80),\n description: z.string().max(2000),\n declaration: CreatorDeclarationSchema,\n published_version: VersionNumber.nullable(),\n latest_version: z\n .object({\n version: VersionNumber,\n status: CreatorTemplateVersionStatusSchema,\n })\n .nullable(),\n kind: CreatorTemplateKindSchema,\n studio: CreatorStudioSchema,\n listing: CreatorTemplateListingSchema,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type CreatorTemplate = z.infer<typeof CreatorTemplateSchema>;\n\n/**\n * SUBMIT A PRIVATE TEMPLATE TO THE MARKETPLACE (ADR-1554). The listing an organization writes: what\n * the marketplace card says, an existing file of its own as the hero (or none), and what is new.\n */\nexport const TemplateSubmissionListingSchema = z\n .object({\n name: z.string().trim().min(1).max(80),\n tagline: z.string().trim().min(1).max(140),\n hero_file_id: idOf(\"fil\").nullable(),\n release_notes: z.string().trim().min(1).max(2000),\n })\n .strict();\nexport type TemplateSubmissionListing = z.infer<typeof TemplateSubmissionListingSchema>;\n\n/** Who may install a version once approved: any organization, or only the one that saved it (ADR-1552). */\nexport const TemplateReachSchema = z.enum([\"marketplace\", \"own_org\"]);\nexport type TemplateReach = z.infer<typeof TemplateReachSchema>;\n\n/** Keyed `(template_id, version)`; immutable but for `status`, `note`, `decided_at`, `artifact_id`. */\nexport const CreatorTemplateVersionSchema = z.object({\n object: z.literal(\"creator_template_version\"),\n template_id: idOf(\"ctp\"),\n version: VersionNumber,\n declaration: CreatorDeclarationSchema,\n status: CreatorTemplateVersionStatusSchema,\n note: z.string().nullable(),\n artifact_id: idOf(\"bpa\").nullable(),\n /**\n * Who may install it once approved (0132): `marketplace` is any organization, `own_org` only the\n * organization that saved it (ADR-1552). Every creator version is `marketplace`; only a\n * `marketplace` version of an organization's template is ever in the public catalog (ADR-1554).\n */\n reach: TemplateReachSchema,\n /** What an organization asked its marketplace listing to say; `null` on every other version. */\n listing: TemplateSubmissionListingSchema.nullable(),\n submitted_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorTemplateVersion = z.infer<\n typeof CreatorTemplateVersionSchema\n>;\n\n/** `GET /v1/creator/balance` — the caller's commissions summed by derived status (§42.4). */\nexport const CreatorBalanceSchema = z.object({\n object: z.literal(\"creator_balance\"),\n pending_micro_usd: MicroUsdField.nonnegative(),\n available_micro_usd: MicroUsdField.nonnegative(),\n claimed_micro_usd: MicroUsdField.nonnegative(),\n paid_micro_usd: MicroUsdField.nonnegative(),\n /** The program's bar, or doomscroll's for a doomscroll account (ADR-1763). */\n minimum_payout_micro_usd: z.union([z.literal(CREATOR_PROGRAM.minimum_payout_micro_usd), z.literal(DOOMSCROLL_PROGRAM.minimum_payout_micro_usd)]),\n});\nexport type CreatorBalance = z.infer<typeof CreatorBalanceSchema>;\n\n/** `POST /v1/referral_clicks` (§42.6) — what the landing page times its 30-day cookie by. */\nexport const ReferralClickSchema = z.object({\n object: z.literal(\"referral_click\"),\n code: CreatorCodeSchema,\n creator: z.object({ display_name: z.string().min(1) }),\n expires_at: Timestamp,\n});\nexport type ReferralClick = z.infer<typeof ReferralClickSchema>;\n\nconst Day = z.iso.date();\n\n/** One shape for both analytics routes (§42.11); the template route narrows to one template's installs. */\nexport const CreatorAnalyticsSchema = z.object({\n object: z.literal(\"creator_analytics\"),\n days: z.number().int().min(1).max(90),\n from: Day,\n to: Day,\n clicks: z.number().int().nonnegative(),\n referrals: z.number().int().nonnegative(),\n installs: z.number().int().nonnegative(),\n active_installs: z.number().int().nonnegative(),\n /** Distinct orgs with at least one commission-bearing invoice in the window (invoice-based template commission). */\n paying_orgs: z.number().int().nonnegative().optional(),\n /** DEPRECATED with the 5% usage accrual; optional until `analytics()` stops returning it. */\n usage_by_day: z\n .array(z.object({ day: Day, debit_micro_usd: MicroUsdField.nonnegative() }))\n .optional(),\n commission_micro_usd: z.object({\n pending: MicroUsdField.nonnegative(),\n available: MicroUsdField.nonnegative(),\n claimed: MicroUsdField.nonnegative(),\n paid: MicroUsdField.nonnegative(),\n }),\n commissions_by_template: z.array(\n z.object({\n creator_template_id: idOf(\"ctp\"),\n amount_micro_usd: MicroUsdField.nonnegative(),\n }),\n ),\n /** Every install covered, newest first: the day it was created and the day its twelve months end. */\n install_windows: z\n .array(z.object({ install_id: idOf(\"bpi\"), from: Day, until: Day }))\n .optional(),\n});\nexport type CreatorAnalytics = z.infer<typeof CreatorAnalyticsSchema>;\n\n// ── The creator studio's wire (`/v1/creator/templates/:id/{uploads,rounds,studio}`, `/v1/creator-admin/listings`)\n\n/** `POST /v1/creator/templates` — `kind: niche` makes a studio template; `crew` is the old builder. */\nexport const CreatorTemplateCreateKindSchema = z.object({\n kind: CreatorTemplateKindSchema.default(\"crew\"),\n});\n\n/** `POST /v1/creator/templates/:id/uploads`. */\nexport const StudioUploadCreateSchema = z.object({\n position: UploadPosition,\n filename: z.string().min(1).max(200),\n content_type: StudioUploadContentTypeSchema,\n bytes: z.number().int().positive().max(CREATOR_PROGRAM.studio.upload_max_bytes),\n});\nexport type StudioUploadCreate = z.infer<typeof StudioUploadCreateSchema>;\n\n/** Its answer: the browser PUTs the bytes to `upload_url` (one-shot, `upload_token_minutes`). */\nexport const StudioUploadTicketSchema = z.object({\n object: z.literal(\"studio_upload_ticket\"),\n position: UploadPosition,\n upload_url: z.url(),\n expires_at: Timestamp,\n});\nexport type StudioUploadTicket = z.infer<typeof StudioUploadTicketSchema>;\n\n/** `PATCH /v1/creator/templates/:id/uploads/:position`. */\nexport const StudioUploadPatchSchema = z.object({ prompt: StudioPrompt });\nexport type StudioUploadPatch = z.infer<typeof StudioUploadPatchSchema>;\n\n/** `PUT /v1/creator/uploads/:token` answers the upload as now stored. */\nexport const StudioUploadResultSchema = z.object({\n object: z.literal(\"studio_upload\"),\n template_id: idOf(\"ctp\"),\n upload: StudioUploadSchema,\n});\nexport type StudioUploadResult = z.infer<typeof StudioUploadResultSchema>;\n\n/**\n * `POST /v1/creator/templates/:id/rounds`. An upload build needs three uploads with prompts; a links\n * build needs its imported uploads (prompts optional). A revision needs `feedback`; `rights_attested`\n * is recorded when sent, never required.\n */\nexport const StudioRoundCreateSchema = z.object({\n feedback: z.string().min(1).max(4000).optional(),\n rights_attested: z.boolean().optional(),\n});\nexport type StudioRoundCreate = z.infer<typeof StudioRoundCreateSchema>;\n\nexport const StudioBudgetSchema = z.object({\n draft_micro_usd: MicroUsdField.nonnegative(),\n spent_micro_usd: MicroUsdField.nonnegative(),\n remaining_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type StudioBudget = z.infer<typeof StudioBudgetSchema>;\n\n/** `GET /v1/creator/templates/:id/studio` — advances the newest round on read, then answers this. */\nexport const CreatorStudioViewSchema = z.object({\n object: z.literal(\"creator_studio\"),\n template_id: idOf(\"ctp\"),\n studio: CreatorStudioSchema,\n /** Newest first. */\n rounds: z.array(CreatorTemplateRoundSchema),\n budget: StudioBudgetSchema,\n});\nexport type CreatorStudioView = z.infer<typeof CreatorStudioViewSchema>;\n\n/** `POST /v1/creator/templates/:id/versions` for a `niche` template (a `crew` template sends `{}`). */\nexport const NicheSubmitSchema = z.object({\n round: z.number().int().positive(),\n listing: z.object({\n tagline: z.string().min(1).max(140),\n hero_sample_index: z.number().int().nonnegative(),\n }),\n});\nexport type NicheSubmit = z.infer<typeof NicheSubmitSchema>;\n\n/** `PATCH /v1/creator-admin/listings/:template_id`. */\nexport const CreatorListingPatchSchema = CreatorTemplateListingSchema.partial();\nexport type CreatorListingPatch = z.infer<typeof CreatorListingPatchSchema>;\n\n/** One row of `GET /v1/creator-admin/listings`: a published creator template, an internal media skill build (§57.5), or an org template approved for the marketplace, and its curation. */\nexport const CreatorListingSchema = z.object({\n object: z.literal(\"creator_listing\"),\n template_id: idOf(\"ctp\"),\n template: z.string().min(1),\n name: z.string(),\n kind: CreatorTemplateKindSchema,\n blueprint: z.string(),\n base_template: z.string(),\n published_version: VersionNumber.nullable(),\n /** Its creator; `null` on an internal org's media skill build (§57.5: naïve made it) and on an organization's template, which `organization` names instead (ADR-1554). */\n creator: z\n .object({\n id: idOf(\"crt\"),\n display_name: z.string(),\n code: CreatorCodeSchema,\n status: CreatorStatusSchema,\n })\n .nullable(),\n /** The organization whose template this is (ADR-1554); `null` on a creator's and on an internal build. */\n organization: z.object({ id: idOf(\"org\"), name: z.string() }).nullable(),\n listing: CreatorTemplateListingSchema,\n /** Installs of the template, and distinct orgs among them that earned a template commission. */\n deploys: z.number().int().nonnegative().optional(),\n paying_orgs: z.number().int().nonnegative().optional(),\n updated_at: Timestamp,\n});\nexport type CreatorListing = z.infer<typeof CreatorListingSchema>;\n\n/**\n * \"Duplicate this company\" (`canonical-spec §61`, ADR-1552). The draft is the exporter's allow-list\n * of the company's crew on its first-party base, after the rewrite took company specifics out of the\n * prompts. `rewrites` is each text the rewrite changed, before and after, for a person to approve\n * whole; `skipped_skills` names the skills left behind because they point at this company's files.\n */\n/** A crew version's declaration with no `studio`: a company's crew is never a niche composition. */\nconst CompanyDeclarationSchema = CreatorDeclarationSchema.omit({ studio: true });\n\nexport const CompanyTemplateDraftRequestSchema = z.object({ project: z.string().min(1).max(64).optional() }).strict();\n\nexport const CompanyTemplateRewriteSchema = z.object({ label: z.string().min(1), before: z.string(), after: z.string() });\nexport type CompanyTemplateRewrite = z.infer<typeof CompanyTemplateRewriteSchema>;\n\nexport const CompanyTemplateDraftSchema = z.object({\n object: z.literal(\"company_template_draft\"),\n blueprint: z.string().min(1),\n base_template: z.string().min(1),\n project: z.string().min(1).nullable(),\n declaration: CompanyDeclarationSchema,\n rewrites: z.array(CompanyTemplateRewriteSchema),\n skipped_skills: z.array(z.string().min(1)),\n});\nexport type CompanyTemplateDraft = z.infer<typeof CompanyTemplateDraftSchema>;\n\n/** Save the approved draft as a private template; the answer is its `blueprint_artifact` (§31). */\nexport const CompanyTemplateCreateSchema = z\n .object({\n name: z.string().trim().min(1).max(80),\n project: z.string().min(1).max(64).optional(),\n declaration: CompanyDeclarationSchema,\n })\n .strict();\n\n/** A marketplace submission as its organization sees it: the version, the review's state and the reviewer's note. */\nexport const TemplateSubmissionSchema = z.object({\n object: z.literal(\"template_submission\"),\n version: VersionNumber,\n status: CreatorTemplateVersionStatusSchema,\n note: z.string().nullable(),\n listing: TemplateSubmissionListingSchema,\n submitted_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type TemplateSubmission = z.infer<typeof TemplateSubmissionSchema>;\n\n/** One plain sentence about a field: a change the listed copy makes, or a refusal that blocks it. */\nexport const TemplateNoticeSchema = z.object({ path: z.string(), message: z.string() });\n\n/**\n * `POST /v1/listings` (ADR-1747): the running company, listed. `project` names the crew, the newest\n * install when absent. Reached only by the `list_as_template` tool, after an owner or admin approved it.\n */\nexport const ListingRequestSchema = z\n .object({\n ...TemplateSubmissionListingSchema.shape,\n project: z.string().min(1).max(64).optional(),\n hero_file_id: idOf(\"fil\").nullable().default(null),\n release_notes: z.string().trim().min(1).max(2000).default(\"First release.\"),\n })\n .strict();\nexport type ListingRequest = z.input<typeof ListingRequestSchema>;\n\n/**\n * What `list_as_template` would list (ADR-1747). A `crew` company lists its crew; a `channel` company\n * (its install runs a media skill it built) lists that style. `changes` are what the listed copy\n * tightens, `refusals` what still blocks it, `skipped_skills` the skills that stay behind.\n */\nexport const ListingKindSchema = z.enum([\"crew\", \"channel\"]);\nexport const ListingChecksSchema = z.object({\n object: z.literal(\"listing_checks\"),\n kind: ListingKindSchema,\n project: z.string().nullable(),\n changes: z.array(TemplateNoticeSchema),\n refusals: z.array(TemplateNoticeSchema),\n skipped_skills: z.array(z.string()),\n /** Every word that is listed (`listedText`), so the card shows exactly what an approval sends. */\n listed: z.array(z.object({ path: z.string(), label: z.string(), text: z.string() })),\n /** SHA-256 of what is listed. The card sends it with its yes; the listing is refused if it changed since. */\n digest: z.string().regex(/^[0-9a-f]{64}$/),\n});\nexport type ListingChecks = z.infer<typeof ListingChecksSchema>;\n\n/** `POST /v1/listings` → `201`: the template the company is listed as, and its submission, in review. */\nexport const ListingSchema = TemplateSubmissionSchema.extend({\n object: z.literal(\"listing\"),\n kind: ListingKindSchema,\n template_id: idOf(\"ctp\"),\n});\nexport type Listing = z.infer<typeof ListingSchema>;\n\n/**\n * `GET /v1/listings` (ADR-1821): the company's own marketplace listings, newest first, for its\n * Marketplace tab. Each is its template's newest marketplace submission; `taken_down` is the\n * reviewer's suspension or unlisting. `balance_micro_usd` is what its listings earned, net of refunds,\n * that no payout has sent yet; `ready_micro_usd` the part past the hold that a payout would send now.\n * Both `null` without `billing:read`, or where the company's data is not configured; `ready_micro_usd`\n * is also `null` where payouts are not turned on.\n */\nexport const OwnListingSchema = ListingSchema.extend({\n blueprint: z.string(),\n template: z.string(),\n taken_down: z.boolean(),\n});\nexport type OwnListing = z.infer<typeof OwnListingSchema>;\nexport const OwnListingsSchema = z.object({\n object: z.literal(\"listings\"),\n balance_micro_usd: MicroUsdField.nullable(),\n ready_micro_usd: MicroUsdField.nullable(),\n data: z.array(OwnListingSchema),\n});\nexport type OwnListings = z.infer<typeof OwnListingsSchema>;\n\n/**\n * `POST /v1/earnings/payouts` (ADR-1598): \"pay me out\", from chat. `country` is where the company is:\n * its card hands it to the owner's set-up (`POST /v1/earnings/payouts/account`), which makes the Stripe\n * account; US when absent. The same body sets that account up.\n */\nexport const EarningsPayoutRequestSchema = z\n .object({\n country: z\n .string()\n .regex(/^[A-Z]{2}$/)\n .optional(),\n })\n .strict();\nexport type EarningsPayoutRequest = z.input<typeof EarningsPayoutRequestSchema>;\n\n/**\n * Its answer. `paid`: `amount_micro_usd` went to the company's Stripe account. `onboarding`: the owner\n * has not finished setting up where it is paid; ask again once they have. `below_minimum`: less than\n * `CREATOR_PROGRAM.minimum_payout_micro_usd` has cleared the hold. Otherwise `amount_micro_usd` is what\n * has cleared the hold, net of refunds, and is not yet paid.\n */\nexport const EarningsPayoutSchema = z.object({\n object: z.literal(\"earnings_payout\"),\n status: z.enum([\"paid\", \"onboarding\", \"below_minimum\"]),\n amount_micro_usd: MicroUsdField,\n payout_id: idOf(\"crp\").nullable(),\n});\nexport type EarningsPayout = z.infer<typeof EarningsPayoutSchema>;\n\n/**\n * `POST /v1/earnings/payouts/account` (ADR-1598): the owner, signed in, sets up where the company's\n * earnings are paid. `ready`: Stripe can pay the account. Otherwise `onboarding_url` is Stripe's page\n * for the owner's details, answered to the owner's own request and never to a chat.\n */\nexport const EarningsPayoutAccountSchema = z.object({\n object: z.literal(\"earnings_payout_account\"),\n ready: z.boolean(),\n onboarding_url: z.string().url().nullable(),\n});\nexport type EarningsPayoutAccount = z.infer<typeof EarningsPayoutAccountSchema>;\n","/** `GET /v1/digest` (§20.10). Its own file: `session.ts` reading `AgentSchema` is an import cycle. */\nimport { z } from \"zod\";\nimport { AgentSchema } from \"./agent\";\nimport { PARKED_STOP_REASONS, SessionSchema } from \"./session\";\n\n/** The parks a person can clear, one `waiting` list each in `GET /v1/digest` (§20.10). */\nexport const DIGEST_WAITING = [...PARKED_STOP_REASONS, \"budget_paused\"] as const;\n\n/** A list cut at its cap (§20.10). No cursor: past the cap, page the list route. */\nconst capped = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item), has_more: z.boolean() });\n\n/** `GET /v1/digest` (§20.10): the company's sessions and agents, in one read. */\nexport const DigestSchema = z.object({\n object: z.literal(\"digest\"),\n agents: capped(AgentSchema),\n waiting: z.object({\n awaiting_approval: capped(SessionSchema),\n awaiting_answer: capped(SessionSchema),\n budget_paused: capped(SessionSchema),\n }),\n failed: capped(SessionSchema),\n recent: capped(SessionSchema),\n channels: z.object({ data: z.array(SessionSchema) }),\n});\nexport type Digest = z.infer<typeof DigestSchema>;\n","/** Events — `{domain}.{action}` types on a gap-free `seq` (canonical-spec §8, §10, §15). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, idOf } from \"./common\";\nimport { AnswersSchema } from \"./session\";\n\nexport const EventTypeSchema = z.enum([\n \"message.delta\",\n /**\n * The agent's answer (no `role`), or a user row `{ role: \"user\", content, client_message_id? }` (§8).\n * A user row the runtime wrote itself — a media job's result, a tool grant — carries\n * `from: \"platform\"` and is the platform's notice, not a caller's words (§8, ADR-0870).\n */\n \"message.completed\",\n /** A caller's message, durable in the inbox and not yet admitted to a turn (§7, §8): `{ client_message_id, content }`. */\n \"message.accepted\",\n /** A person's fan-out, on the sender's log without waking it (§8, §28.16): `{ client_message_id, content, handoffs, refusals }`. */\n \"handoff.sent\",\n \"tool.started\",\n \"tool.completed\",\n \"tool.confirm\",\n /** A person's decision on a parked call, stamped with the inbox write that delivers it (§8, ADR-0764). */\n \"tool.confirm.resolved\",\n /** A person's answer to a parked question, stamped the same way (§7.1, §8, ADR-1049). */\n \"tool.confirm.answered\",\n \"session.running\",\n \"session.usage\",\n \"session.idle\",\n /** A failed attempt the loop will retry (§8): `{ attempt, in_ms, code }`. */\n \"session.retrying\",\n /** The session's mode changed (§7.5): `{ mode: \"plan\" | \"build\" }`. */\n \"session.mode\",\n /** A write to the session's plan, by the agent or its owner (§7.5): the plan object. */\n \"plan.updated\",\n /**\n * The turn ran, but without something it needed (§8): `{ reason, detail? }`.\n *\n * Emitted for a turn whose sandbox could not be woken. That turn used to be indistinguishable\n * from a success — the model was handed the failure as a tool result, answered around it from the\n * transcript, and the session ended `idle`/`end_turn` with no field anywhere saying the\n * filesystem had been unavailable. This is the field. `reason` is open on purpose; today it is\n * `\"sandbox_unavailable\"`, `\"vendor_resume_unavailable\"`, or `\"app_tools_unavailable\"` — an app the\n * agent's toolset names gave no tools this turn (§29.5, `runtime-do app-mcp-tools.ts`).\n *\n * `detail` is the boot failure's own message, and it is here because `reason` alone reads the\n * same for a vendor outage and for a fault of ours. Staging round 3 spent its whole budget\n * establishing with raw Connect RPC that the vendor was refusing every `ResumeSession` on the\n * account — a question the adapter could have answered, since its give-up names the vendor state\n * it last saw and how long it waited (`compute-tenki index.ts`). It is diagnostic prose, not a\n * contract: never parse it, and it may be absent.\n */\n \"session.degraded\",\n /**\n * The session let go of a sandbox that would not resume and will run the next turn on a fresh\n * one: `{ from, reason, failures, replacements }`.\n *\n * *** THE ONE TURN WHERE A FILESYSTEM ACTUALLY GOES MISSING USED TO BE THE SILENT ONE. ***\n * `session.degraded` marks the turns whose resume FAILED, and those turns lose nothing — the box\n * is still there and the next turn may still get it back. The turn that swaps the box is the\n * damaging one, and it has no failure to report: it provisions a replacement and runs normally.\n * Staging watched a session answer `cat: … No such file or directory` with nothing in its event\n * log to tell that apart from the file never having been written, and support could not tell\n * either. `from` is the box that was let go of, so a customer can still reach it through\n * `GET /v1/computers/:id` while it lives.\n *\n * `reason` is open like `session.degraded`'s, and it carries the one distinction an operator\n * cannot make any other way: `\"resume_refused\"` is the FIRST swap, where everything knowable here\n * says the fault is that box's, and `\"vendor_resume_unavailable\"` is a swap that follows one — a\n * fault that already outlived a fresh machine, so it is the account and not the box.\n * `replacements` counts them. There is no third swap: past `box.ts MAX_BOX_REPLACEMENTS` the\n * session keeps the box it holds and reports `session.degraded` under that same\n * `vendor_resume_unavailable` reason, rather than abandoning one more live micro-VM every cycle\n * for a fault a fresh one demonstrably does not fix.\n */\n \"session.computer_replaced\",\n \"budget.exceeded\",\n \"span.model_request.start\",\n \"span.model_request.end\",\n // Pre-model spans (§15): what the gap before the first model request was spent on.\n \"span.transcript_load.start\",\n \"span.transcript_load.end\",\n \"span.harness_load.start\",\n \"span.harness_load.end\",\n \"span.harness_build.start\",\n \"span.harness_build.end\",\n \"span.box_resume.start\",\n \"span.box_resume.end\",\n /**\n * A delegated thread's lifecycle, on the **coordinator's** stream (§28). The child's own\n * `ses_…` rides inside `data.thread_id` — the event schema gains no field and `vetta.event` gains\n * no column, so one reader of `{session_id, seq}` still sees every event in one order.\n */\n \"thread.created\",\n \"thread.running\",\n \"thread.idle\",\n \"thread.terminated\",\n /**\n * An outcome's grade (§58.5), on the GRADED session's stream: `started` when the grader thread is\n * minted, `progress` when it starts a turn (a heartbeat), `completed` when the result is written —\n * `{ outcome_id, iteration, thread_id, result, explanation, criteria, token_usage, consumed_micro_usd }`.\n */\n \"outcome.evaluation.started\",\n \"outcome.evaluation.progress\",\n \"outcome.evaluation.completed\",\n // core-gaps: contracts (`canonical-spec §32.8`, §33.5, §36.3, §37.3, §38.3)\n \"browser.session.opened\",\n \"browser.session.closed\",\n \"browser.context.saved\",\n \"browser.context.granted\",\n \"browser.context.revoked\",\n \"media.job.queued\",\n \"media.job.completed\",\n \"media.job.failed\",\n \"file.imported\",\n \"app.db.migrated\",\n \"app.storage.bucket.created\",\n \"app.storage.bucket.deleted\",\n // identity money (`canonical-spec §44.3`, §45.3). Every one of these is driven over REST, which\n // has no session stream, so the org's webhook subscriptions are the only push a customer gets.\n \"wallet.created\",\n \"wallet.policy.updated\",\n \"wallet.transaction.confirmed\",\n \"wallet.swept\",\n \"card.issued\",\n \"card.failed\",\n \"card.cancelled\",\n \"card.refunded\",\n \"card.credentials_revealed\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\nexport const EventSchema = z.object({\n id: idOf(\"evt\"),\n seq: z.number().int().positive(),\n type: EventTypeSchema,\n session_id: idOf(\"ses\"),\n data: z.record(z.string(), z.unknown()),\n created_at: Timestamp,\n});\nexport type Event = z.infer<typeof EventSchema>;\n\n/**\n * `thread.*` data. Loose on purpose: `thread_id` is the whole added contract, and each event is\n * free to carry more (which member, why it stopped) without a schema change per field.\n */\nexport const ThreadEventDataSchema = z.looseObject({ thread_id: idOf(\"ses\") });\n\n/**\n * `tool.confirm.resolved` data (§8, ADR-0764). `decision` and `scope` are the `tool_confirmations`\n * vocabulary (§7). `actor` is `null` only for a decision queued by a caller that predates it;\n * `proposed_args` is `null` when no parked row matched; `final_args` is what runs — the person's\n * edit of a template install's answers (ADR-1030), otherwise equal to `proposed_args`.\n */\nexport const ToolConfirmResolvedDataSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().nullable(),\n scope: z.enum([\"call\", \"session\"]),\n actor: PrincipalSchema.nullable(),\n decided_at: Timestamp,\n proposed_args: z.record(z.string(), z.unknown()).nullable(),\n final_args: z.record(z.string(), z.unknown()).nullable(),\n});\nexport type ToolConfirmResolvedData = z.infer<typeof ToolConfirmResolvedDataSchema>;\n\n/**\n * `tool.confirm.answered` data (§8, ADR-1049): the answers exactly as `POST …/answers` took them.\n * Without it an answer reached only the model's transcript, and no reader of the log could say what\n * the person had said.\n */\nexport const ToolConfirmAnsweredDataSchema = z.object({\n tool_call_id: z.string(),\n answers: AnswersSchema,\n answered_at: Timestamp,\n});\nexport type ToolConfirmAnsweredData = z.infer<typeof ToolConfirmAnsweredDataSchema>;\n\n/** `session.usage` data — emitted before every idle/terminal transition (§10, §15). */\nexport const SessionUsageDataSchema = z.object({\n token_usage: TokenUsageSchema,\n consumed_micro_usd: MicroUsdField.nonnegative(),\n active_seconds: z.number().nonnegative(),\n tool_calls: z.number().int().nonnegative(),\n});\n","/**\n * The team board — the shared, durable coordination surface a coordinator session and every thread\n * it delegates to read and write (canonical-spec §28).\n *\n * The statuses are **fixed**, not configurable columns. A per-team column list would make every\n * board tool's contract depend on the agent's config: `board_write` could not name a legal status\n * without first reading the board, and no two teams' transcripts would be comparable. Four states\n * cover the thing a board is for — what is queued, what is being worked, what is stuck, what is\n * finished — and `blocked_by` carries the *reason* a card is stuck as data rather than as a lane.\n */\n\nimport { z } from \"zod\";\nimport { derivedId } from \"../id\";\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 * The longest a card's brief, its note or a comment may be, in characters (ADR-1705). One number at\n * every door (a member's `board_write`, the HTTP routes, a template's tasks). They disagreed, 20,000\n * against 8,192, so a card an agent wrote could not be re-created or edited through the API.\n */\nexport const BOARD_TEXT_MAX = 20_000;\n\n/**\n * A unit of work. `assignee` is an agent's name — not an id — because that is what a coordinator\n * writes in a tool call and what a member recognises as itself; `null` is unclaimed.\n *\n * Assignment is the wake (§28.18): `woken_session_id` is the session the board started for the\n * assignee, `null` until it has — which is what makes the card *due*. `reported_status` is the\n * `done`/`blocked` the board's owner was last told about. Neither is writable by a client.\n */\nexport const BoardCardSchema = z.object({\n id: idOf(\"crd\"),\n object: z.literal(\"board_card\"),\n board_id: idOf(\"brd\"),\n title: z.string().min(1),\n /** The brief — what was asked. */\n body: z.string(),\n /** What the holder wrote back; a `done` carries one. */\n note: z.string().nullable().default(null),\n status: BoardStatusSchema,\n assignee: z.string().nullable(),\n /** The cards this one waits on. A `blocked` card with an empty list is stuck on the world. */\n blocked_by: z.array(idOf(\"crd\")),\n // The wake fields default on read: a reader whose API predates one still gets the card (§28.11).\n woken_session_id: idOf(\"ses\").nullable().default(null),\n reported_status: BoardStatusSchema.nullable().default(null),\n /** Sessions the board has started for this card; the third is its last (§28.18). */\n wake_count: z.number().int().nonnegative().default(0),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type BoardCard = z.infer<typeof BoardCardSchema>;\n\n/**\n * THE FIRST WEEK'S CARDS (ADR-1511). Activating writes the CEO's plan as at most this many cards,\n * keyed `onboard-plan:<n>` (`apps/api/src/first-week.ts`). A card's id is derived from its board and\n * key (`cardId` in `@vetta/db`), so these are the only ids a plan card can have. The wire carries no\n * mark, so this is how the chat tells the plan's cards from the template's own tasks.\n */\nexport const FIRST_WEEK_MOST = 12;\nexport const firstWeekKey = (n: number): string => `onboard-plan:${n}`;\nexport const firstWeekCardIds = (board: string): Promise<string[]> =>\n Promise.all(Array.from({ length: FIRST_WEEK_MOST }, (_, i) => derivedId(\"crd\", `${board}:${firstWeekKey(i + 1)}:0`)));\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","/**\n * The three identity primitives that touch the outside world — a **web domain**, an **email\n * inbox** on it, and a **phone number** — plus the normalised **inbound message** that arrives at\n * either endpoint and the **outbound message** one sent (`canonical-spec §24`,\n * `docs/identity/{domains,email,phone,inbound}.mdx`).\n *\n * The gates at the bottom are the whole point of this file. A domain carries four independent\n * readiness tracks and each capability hangs off exactly one of them; a number cannot text until a\n * carrier has approved its campaign. Those rules are pure functions here, tested here, and called\n * from the routes — so \"deliverable\" is a computed fact and never an assumption. Sending mail from\n * a domain whose SPF/DKIM is not published is the worst outcome available to us: it does not fail,\n * it silently lands in spam.\n */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { PrincipalSchema, Timestamp, idOf } from \"./common\";\n\n// ── Domain ────────────────────────────────────────────────────────────────────\n\n/**\n * Where the domain lives. A purchased domain uses the same mail/DNS readiness tracks, but its\n * creation is separately gated by `billing:write` and an explicit live-price ceiling.\n */\nexport const DomainKindSchema = z.enum([\"system\", \"external\", \"purchased\"]);\nexport type DomainKind = z.infer<typeof DomainKindSchema>;\n\n/** Email/company track. `failed` is ours: the docs give no terminal state and one is needed. */\nexport const DomainStatusSchema = z.enum([\"pending_dns\", \"active\", \"failed\"]);\n/** Mail DNS (SPF/DKIM) track — what **sending** hangs on. */\nexport const DomainDnsStatusSchema = z.enum([\"pending_verification\", \"provisioned\", \"failed\"]);\n/**\n * Inbound (MX) track — what **receiving** hangs on. Not in `docs/identity/domains.mdx`, which\n * gates receive on \"verified for inbound at the email layer\" in two tables and then exposes no\n * field for it, leaving the gate unqueryable. Doc-fix owed (ADR-0119).\n */\nexport const DomainInboundStatusSchema = z.enum([\"pending\", \"verified\", \"failed\"]);\n/** App/HTTP track, entirely independent of the three above. */\nexport const DomainAppConnectStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const DnsRecordSchema = z.object({\n type: z.enum([\"TXT\", \"CNAME\", \"MX\"]),\n host: z.string(),\n value: z.string(),\n priority: z.number().int().nullable(),\n /** Vetta owns this record: `_dmarc`, DKIM, inbound MX. The agent may read it, never write it. */\n managed: z.boolean(),\n});\nexport type DnsRecord = z.infer<typeof DnsRecordSchema>;\n\nexport const DomainSchema = z.object({\n id: idOf(\"dom\"),\n object: z.literal(\"domain\"),\n /** A domain belongs to the **organization**, not to one identity: two identities share one. */\n name: z.string(),\n kind: DomainKindSchema,\n status: DomainStatusSchema,\n dns_status: DomainDnsStatusSchema,\n inbound_status: DomainInboundStatusSchema,\n app_connect_status: DomainAppConnectStatusSchema,\n records: z.array(DnsRecordSchema),\n last_verified_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Domain = z.infer<typeof DomainSchema>;\n\n/** A fully-qualified domain name, lowercase, no trailing dot. */\nexport const FQDN = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/;\n\n/**\n * Records the agent may never edit — DKIM, DMARC and the inbound MX keep mail working at all.\n *\n * Matched **label by label**, not by suffix: an email layer asked for a subdomain returns its\n * records relative to the registrable zone, so DKIM for `sub.example.com` arrives as the host\n * `sel._domainkey.sub`. A suffix test calls that editable and invites an agent to delete the key\n * that signs its own mail (observed live, 2026-08-22).\n */\nexport function isManagedHost(host: string): boolean {\n const h = host.toLowerCase().replace(/\\.$/, \"\");\n if (h === \"@\") return true;\n return h.split(\".\").some((label) => label === \"_dmarc\" || label === \"_domainkey\");\n}\n\n// ── Email inbox ───────────────────────────────────────────────────────────────\n\n/** Manual localparts: the documented character class, floored at 2 and capped at RFC 5321's 64. */\nexport const LOCALPART = /^[a-z0-9._-]{2,64}$/;\n/** Auto-provisioned localparts are derived from the agent name and capped at 32. */\nexport const AUTO_LOCALPART_MAX = 32;\n\nexport const EmailInboxSchema = z.object({\n id: idOf(\"eml\"),\n object: z.literal(\"email_inbox\"),\n identity_id: idOf(\"idn\"),\n domain_id: idOf(\"dom\"),\n address: z.string(),\n localpart: z.string(),\n /** Mail to the address wakes exactly this agent, while it holds the inbox's persona (ADR-1401). */\n owning_agent_id: idOf(\"agt\"),\n /**\n * Whether mail to the address wakes its owner (ADR-1749). A new inbox wakes (§24.7); one made\n * before the wake shipped was set up under \"inbound wakes nothing\" and starts off, until someone\n * turns it on (`PATCH`). Absent on an older payload, read as off.\n */\n wake: z.boolean().default(false),\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 /**\n * The agent an inbound text is for, as `EmailInbox.owning_agent_id` is for mail. `null` for a\n * number bought without one or before 0124, and defaulted so an older reply parses (ADR-1430).\n */\n owning_agent_id: idOf(\"agt\").nullable().default(null),\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\n/** Why a wake guard refused a stored message (`canonical-spec §24.7`, ADR-1430). */\nexport const InboundGuardReasonSchema = z.enum([\n \"sender_rate_limit\",\n \"auto_reply\",\n \"own_persona\",\n \"thread_turn_cap\",\n \"endpoint_rate_limit\",\n]);\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 (ADR-1401); `null` when it woke none — held, unowned, or refused. */\n session_id: idOf(\"ses\").nullable(),\n /** The wake guard that refused it; `null` when none did. Defaulted for older replies. */\n guard_reason: InboundGuardReasonSchema.nullable().default(null),\n received_at: Timestamp,\n /**\n * When a person marked it read (`POST …/messages/{mid}/read`); `null` is unread. Defaulted so a\n * reply from an older control plane parses (ADR-1076).\n */\n read_at: Timestamp.nullable().default(null),\n});\nexport type InboundMessage = z.infer<typeof InboundMessageSchema>;\n\n// ── Outbound message ──────────────────────────────────────────────────────────\n\n/**\n * A message the persona sent, kept by us after the provider accepted it (ADR-1076). Written by\n * both doors that send: the API route (`actor` names the key or person) and the `email.send` tool\n * (`sent_by_agent_id` names the agent). Only mail is recorded today; `channel` is the inbound\n * enum because a text is the same kind of row.\n */\nexport const OutboundMessageSchema = z.object({\n id: idOf(\"out\"),\n object: z.literal(\"outbound_message\"),\n channel: InboundMessageSchema.shape.channel,\n identity_id: idOf(\"idn\"),\n /** The `eml_` endpoint it was sent from. */\n endpoint_id: z.string(),\n from: z.string(),\n to: z.array(z.string()),\n subject: z.string().nullable(),\n text: z.string(),\n sent_by_agent_id: idOf(\"agt\").nullable(),\n actor: PrincipalSchema.nullable(),\n sent_at: Timestamp,\n});\nexport type OutboundMessage = z.infer<typeof OutboundMessageSchema>;\n\n// ── The gates ─────────────────────────────────────────────────────────────────\n\n/**\n * Creating an inbox needs the company track cleared. `job_not_ready` and not `validation_failed`:\n * the caller did nothing wrong and the call will succeed once DNS propagates, so a durable runtime\n * must retry rather than give up (ADR-0118).\n */\nexport function assertInboxCreatable(domain: Domain, param: \"domain_id\" | \"address\" = \"domain_id\"): 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 param,\n );\n}\n\n/** Sending needs SPF/DKIM published and verified. Un-gated, mail silently lands in spam. */\nexport function assertSendable(domain: Domain): void {\n if (domain.dns_status === \"provisioned\") return;\n throw new VettaError(\n \"job_not_ready\",\n `domain ${domain.name} is not deliverable: dns_status is ${domain.dns_status}, sending needs \"provisioned\"`,\n );\n}\n\n/**\n * Receiving needs MX in place. Not an assert: an inbound message for a domain that cannot receive\n * is **dropped**, never bounced back at the sender and never turned into a wake.\n */\nexport function canReceive(domain: Domain): boolean {\n return domain.inbound_status === \"verified\";\n}\n\n/** Outbound SMS is refused until the carrier campaign is approved — this is a legal gate, not ours. */\nexport function assertSmsSendable(phone: PhoneNumber): void {\n if (phone.campaign_status === \"approved\") return;\n throw new VettaError(\n \"compliance_pending\",\n `outbound messaging for ${phone.e164} is not registered yet: campaign is ${phone.campaign_status}`,\n );\n}\n\n/** The one invariant tying the two together — nothing else may write `sms_outbound`. */\nexport function smsCapabilities(campaign: z.infer<typeof CampaignStatusSchema>): {\n sms_inbound: boolean;\n sms_outbound: boolean;\n voice: false;\n} {\n return { sms_inbound: true, sms_outbound: campaign === \"approved\", voice: false };\n}\n","/**\n * Hosted web applications (`canonical-spec §29`). An app is an **organization-level** resource —\n * a deployed site with, for `fullstack`, a managed backend provisioned per app. It is never owned\n * by an agent: agents are immutable versioned config, an app is production infrastructure that\n * outlives any agent or session. Provenance lives in the audit log (§17).\n *\n * Nothing provider-shaped appears here: the hosting and backend project handles are server\n * columns, and the wire object carries only what a customer may see.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport type { Scope } from \"./org\";\n\n/**\n * `bundle` runs a bundle the platform released (a store, ADR-1571): its code is never the\n * customer's, it brings its own database and file store, and it is hosted apart from the others.\n */\nexport const AppTypeSchema = z.enum([\"frontend_only\", \"fullstack\", \"bundle\"]);\nexport type AppType = z.infer<typeof AppTypeSchema>;\n\n/** `deleted` is computed off the soft-delete column, never stored in the status column. */\nexport const AppStatusSchema = z.enum([\"provisioning\", \"active\", \"error\"]);\nexport type AppStatus = z.infer<typeof AppStatusSchema>;\n\n/**\n * The path of the MCP endpoint an app serves (`§29.1`) — an absolute path, so the runtime can\n * resolve it as `url + mcp` whatever the app's current canonical URL is. Shared by the API and IaC.\n */\nexport const AppMcpPathSchema = z.string().regex(/^\\/\\S*$/, \"must be an absolute path beginning with /\").max(128);\n\nexport const AppSchema = z.object({\n id: idOf(\"app\"),\n object: z.literal(\"app\"),\n name: z.string(),\n description: z.string().nullable(),\n type: AppTypeSchema,\n /**\n * The customer's own project name that made this app, or `null` for one made outside a project\n * (ADR-0375). Customer-visible, unlike the provider handles: it is the word the customer typed,\n * and the refusal that guards a name quotes it.\n */\n project: z.string().nullable(),\n status: AppStatusSchema,\n /** The address the app answers on — platform hostname until a custom domain connects. */\n url: z.string().nullable(),\n /** White-label words when `status` is `error`; never the provider's. */\n error: z.string().nullable(),\n /** Where the app serves MCP, or `null`. The bearer token for it is a server column. */\n mcp: AppMcpPathSchema.nullable(),\n /**\n * Is this a gated blueprint dashboard — one the Studio opens through `/apps/{id}/open` rather\n * than linking its `url` (`§29.1`)? True when the platform holds the app's `DASHBOARD_TOKEN`\n * or a secret of that name exists on the app; derived on read, never stored.\n */\n dashboard: z.boolean(),\n created_at: Timestamp,\n});\nexport type App = z.infer<typeof AppSchema>;\n\nexport const AppDeploymentStatusSchema = z.enum([\"queued\", \"building\", \"ready\", \"error\"]);\nexport type AppDeploymentStatus = z.infer<typeof AppDeploymentStatusSchema>;\n\nexport const AppDeploymentSchema = z.object({\n id: idOf(\"apd\"),\n object: z.literal(\"app_deployment\"),\n app_id: idOf(\"app\"),\n status: AppDeploymentStatusSchema,\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The client's opaque digest of the files, echoed verbatim so it can skip an unchanged deploy. */\n content_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppDeployment = z.infer<typeof AppDeploymentSchema>;\n\n/** The file-map a deployment was posted with, kept so an agent can open and re-ship it (§29.2). */\nexport const AppDeploymentFilesSchema = z.object({\n object: z.literal(\"app_deployment_files\"),\n deployment_id: idOf(\"apd\"),\n files: z.record(z.string().min(1), z.string()),\n});\nexport type AppDeploymentFiles = z.infer<typeof AppDeploymentFilesSchema>;\n\n/** Metadata only — the value goes to the host project's environment and is never readable back. */\nexport const AppSecretSchema = z.object({\n object: z.literal(\"app_secret\"),\n name: z.string(),\n /** The client's opaque digest of the value, echoed verbatim so it can skip an unchanged write. */\n value_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppSecret = z.infer<typeof AppSecretSchema>;\n\n/**\n * A one-click way into an app that gates itself with a platform-generated bearer (`§29.7`).\n *\n * `ticket` is a short-lived, signed statement of who is opening the app — an HMAC keyed by the\n * app's `DASHBOARD_TOKEN`, never the value (§29.10) — and `url` is the app's own endpoint that trades one for a session\n * cookie. It is posted, not linked: a credential in a query string lands in the app's server logs,\n * the browser's history and every later `Referer`.\n */\nexport const AppEntrySchema = z.object({\n object: z.literal(\"app_entry\"),\n url: z.string(),\n ticket: z.string(),\n});\nexport type AppEntry = z.infer<typeof AppEntrySchema>;\n\n/**\n * How a person gets into an app's dashboard without the Studio (`§29.2`, `§29.7`): the app's\n * address and its platform-generated `DASHBOARD_PASSWORD`, `null` until one is provisioned. The\n * one audited reveal of an app secret — the password exists to be typed by a human (ADR-0656).\n */\nexport const AppAccessSchema = z.object({\n object: z.literal(\"app_access\"),\n url: z.string().nullable(),\n password: z.string().nullable(),\n});\nexport type AppAccess = z.infer<typeof AppAccessSchema>;\n\nexport const AppDomainStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const AppDomainSchema = z.object({\n object: z.literal(\"app_domain\"),\n app_id: idOf(\"app\"),\n domain_id: idOf(\"dom\"),\n domain: z.string(),\n status: AppDomainStatusSchema,\n created_at: Timestamp,\n});\nexport type AppDomain = z.infer<typeof AppDomainSchema>;\n\n/** `A-Z0-9_`, not starting with a digit — what every runtime accepts as an env name. */\nexport const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;\n\n/**\n * App names become provider project names and platform hostnames, so the grammar is the\n * DNS-label one: lowercase alphanumerics and hyphens, no edge hyphens, 63 max.\n */\nexport const APP_NAME = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/**\n * WHAT AN APP'S OWN KEY MAY HOLD (`§29.10`, ADR-1004, ADR-1009). An app asks, the owner approves\n * on a card, and the key carries exactly the approved subset. Reads are the default ask.\n * `files:read` is the whole company library, not the app's own files; the card says so.\n *\n * THE AGENT THAT WRITES THE APP CAN READ ITS KEY: it writes the server code that holds it. So no\n * scope here may reach past what that agent already has. `sessions:write` answers approval cards\n * (`POST /v1/sessions/{id}/tool_confirmations`) and `agents:write` rewrites any agent's tool\n * policy and every app's secrets and entry tickets: either one lets the agent approve itself. Only\n * `files:write` is left to ask for. Never `admin`, `billing:write`, `webhooks:*`, `audit:read`,\n * `computers:write` or `proxy:write` either: a key baked into an app must not mint keys, spend,\n * redirect traffic or run code.\n */\nexport const APP_READ_SCOPES = [\"agents:read\", \"sessions:read\", \"billing:read\", \"files:read\"] as const satisfies readonly Scope[];\nexport const APP_WRITE_SCOPES = [\"files:write\"] as const satisfies readonly Scope[];\nexport type AppScope = (typeof APP_READ_SCOPES)[number] | (typeof APP_WRITE_SCOPES)[number];\n\n/**\n * WHAT AN APP'S OWN KEY LETS IT DO (`§29.10`, ADR-1048): the union of the scopes of every live key\n * linked to the app (`api_key.app_id`), in every mode — never a key id, a prefix or a name. Empty\n * when no linked key is live. A key set by hand, or minted before keys named their app, is not here:\n * the Studio reads the app's `NAIVE_API_KEY` secret to say so rather than claim \"no access\".\n */\nexport const AppPermissionsSchema = z.object({\n object: z.literal(\"app_permissions\"),\n app_id: idOf(\"app\"),\n scopes: z.array(z.string()),\n});\nexport type AppPermissions = z.infer<typeof AppPermissionsSchema>;\n\n/**\n * THE APP ENGINEER'S MARKER (`§29.8`). The engineer is an ordinary agent that *points at* one app\n * through `metadata.role`/`metadata.app_id`; the dashboard hides it from every roster it draws, so\n * the marker is the only thing that can find it — and the only thing that can reap it when its app\n * goes. It lives here rather than in the studio because the delete route is the other reader.\n */\nexport const APP_ENGINEER_MARKER = \"app-engineer\" as const;\n\n/** Is this agent the engineer of that app? Metadata only: the marker is the whole relationship. */\nexport const isAppEngineerOf =\n (appId: string) =>\n (agent: { metadata: Record<string, unknown> }): boolean =>\n agent.metadata[\"role\"] === APP_ENGINEER_MARKER && agent.metadata[\"app_id\"] === appId;\n","/**\n * The blueprint install (`canonical-spec §29.6`) — one applied declaration per\n * (organization, project), and the drift a `revision_conflict` names.\n *\n * `naive up` needed no server-side state while the only writer was a person with a clone: its\n * working tree was the manifest. The studio applying the same declaration makes two writers on one\n * organization, and neither can see the other. This row is what they share.\n *\n * It is not a second source of truth for what is provisioned — apps, agents, skills, identities and\n * vaults stay keyed by name on their own routes. It records *that* an apply happened, with what, by\n * whom, and against which revision.\n */\n\nimport { z } from \"zod\";\nimport { SkillRefSchema } from \"./agent\";\nimport { Timestamp, idOf } from \"./common\";\n\n/** Which of the two writers applied a revision. */\nexport const BlueprintInstallSourceSchema = z.enum([\"studio\", \"cli\"]);\nexport type BlueprintInstallSource = z.infer<typeof BlueprintInstallSourceSchema>;\n\n/**\n * Whether one revision's reconcile is finished (§29.6). `report: null` alone cannot say: an apply\n * that only recorded and a hosted apply that has not run yet look the same without it. A hosted apply\n * a signed-in person makes answers `pending` and runs after the response; the row moves to `applied`\n * when the report is stamped, or to `failed` with `failure` set when the run threw. An install\n * recorded for a company still being set up is `held`: nothing is built until it is activated, and\n * then it moves to `pending` (ADR-1108).\n */\nexport const BlueprintInstallStatusSchema = z.enum([\"held\", \"pending\", \"applied\", \"failed\"]);\nexport type BlueprintInstallStatus = z.infer<typeof BlueprintInstallStatusSchema>;\n\n/**\n * What one apply did to one resource. This is the vocabulary `naive up` has printed since it\n * existed; it is written HERE, and imported by `@usenaive-sdk/blueprints`, for the reason\n * `CLAUDE.md §2` gives: the hosted apply publishes the engine's report on the install (below), so\n * it is a wire shape, and a wire shape has exactly one definition. The engine re-exports these two\n * names unchanged, so nothing downstream of it learns a second word for the same thing.\n */\nexport const ResourceActionSchema = z.enum([\"created\", \"updated\", \"unchanged\", \"deleted\", \"refused\"]);\nexport type ResourceAction = z.infer<typeof ResourceActionSchema>;\n\n/**\n * What a re-apply left as someone changed it (ADR-1482): an app's deployment (the template's new\n * tree then waits as its upstream, §29.6), a template agent's system prompt or skills, or a timer.\n */\nexport const KeptEditSchema = z.enum([\"deployment\", \"system\", \"skills\", \"schedule\"]);\nexport type KeptEdit = z.infer<typeof KeptEditSchema>;\n\n/** One line of an apply: what was named, what happened to it, and — for a refusal — why. */\nexport const ResourceReportSchema = z.object({\n name: z.string().min(1),\n action: ResourceActionSchema,\n /** The `agt_`/`app_`/`ses_`… the line resolved to. Absent on a refusal that never got an id. */\n id: z.string().optional(),\n /** An app's hostname once its build went live; `null` while it has none. Apps only. */\n url: z.string().nullable().optional(),\n /**\n * What a TASK is called and who owes it. `name` is the declaration key (`first-render`), which is\n * how a re-apply finds the same card and is not a sentence anybody wants read to them. The\n * dashboard's opening message lists the team's work, so it needs the title the board shows and the\n * seat that holds it. Tasks only.\n */\n title: z.string().optional(),\n assignee: z.string().optional(),\n /**\n * A SCHEDULE'S brief, in one short line — the opening sentence of its `input_template`. A\n * schedules line is named `<agent> @ <cron>`, which says when something runs and nothing at all\n * about what it does, so a roadmap built from these lines could only ever have been a timetable.\n * Written here rather than read back from the deployment so the receipt stays the one read the\n * welcome needs. Schedules only.\n */\n summary: z.string().optional(),\n reason: z.string().optional(),\n /**\n * What the apply left as someone changed it, so the line's `action` stays `unchanged` (or\n * `updated` when something else on it changed). `deployment` means an upstream waits for a merge\n * (§29.6, ADR-1482). Absent: nothing was kept.\n */\n kept_edits: z.array(KeptEditSchema).optional(),\n});\nexport type ResourceReportLine = z.infer<typeof ResourceReportSchema>;\n\n/**\n * What an apply DID — the engine's own `UpReport`, minus the two fields that are answers to a\n * question nobody asks a stored row (`dry_run`, and the pair naming the crew, which the install\n * already carries in `blueprint`/`template`).\n *\n * `intake` is its own list rather than a line under `agents` because an intake line's `id` is a\n * `ses_`: folding it in would put a session id in the field a reader uses to find an agent\n * (ADR-0410). `skipped` names live rows the engine could not parse and stepped over. `deselected`\n * names the agents and apps the operator's `selection` left out (§31.2) — a choice, kept apart from\n * `skipped` (a failure to read) and `refused` (a failure to do). Defaulted, because every report\n * stored before it was written without it and means \"nothing was left out\".\n */\nexport const BlueprintReportSchema = z.object({\n skills: z.array(ResourceReportSchema),\n identities: z.array(ResourceReportSchema),\n vaults: z.array(ResourceReportSchema),\n apps: z.array(ResourceReportSchema),\n agents: z.array(ResourceReportSchema),\n schedules: z.array(ResourceReportSchema),\n intake: z.array(ResourceReportSchema),\n /** One line per declared task (§31.11), `id` the card's `crd_`. Defaulted so older rows parse. */\n tasks: z.array(ResourceReportSchema).default([]),\n skipped: z.array(z.string()),\n deselected: z.array(z.string()).default([]),\n});\nexport type BlueprintReport = z.infer<typeof BlueprintReportSchema>;\n\n/**\n * Which of the declared crew an apply takes (§31.2), by declared name. Omitting it from the apply\n * body means everything; a selection missing a `required` agent or app is `validation_failed`.\n */\nexport const BlueprintSelectionSchema = z.object({\n agents: z.array(z.string().min(1)),\n apps: z.array(z.string().min(1)),\n});\nexport type BlueprintSelection = z.infer<typeof BlueprintSelectionSchema>;\n\nexport const BlueprintInstallSchema = z.object({\n id: idOf(\"bpi\"),\n object: z.literal(\"blueprint_install\"),\n /** The customer's own `defineProject({ name })` — the same word `app.project` stamps (§29.2). */\n project: z.string().min(1),\n /** The pair the declaration resolved to; `null` for a declaration that names no blueprint. */\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n /**\n * Applies, not versions of anything: 1 on the first apply, +1 on each one after, whichever writer\n * made it. It is not an agent version and it never rolls back.\n */\n revision: z.number().int().positive(),\n /**\n * The blueprint artifact version this came from, or `null` when it was applied from a working\n * tree — an operator editing a clone has no version to name.\n */\n artifact_version: z.string().nullable(),\n /**\n * The setup answers this project was configured with (§7.1 fields, keyed by their `key`), so a\n * re-apply does not re-ask and both writers configure from the same answers. Configuration only:\n * a secret is a vault credential (§23) or an app secret (§29.2), and neither is ever an answer.\n */\n answers: z.record(z.string(), z.unknown()),\n /**\n * NO `declaration` ON THE WIRE, and that is the reconciliation of §29.6 with §31.1.\n *\n * The applied bytes are stored — a `revision_conflict` names the paths two writers disagree at,\n * and it can only do that by holding what was applied. They are not published. An apply that\n * names a published `blueprint` and `template` sends no declaration: the server reads the\n * catalog's, which §31.1 says never leaves it. Echoing it back on the 201 (and again on every\n * later list) would hand any organization that can sign up the whole private config of a\n * blueprint it has installed nothing of — every agent's system prompt, its `mcp_servers`, its\n * vault credential declarations and its app `env` keys. A caller that sent a declaration already\n * has it, so nothing is lost by not saying it twice.\n */\n source: BlueprintInstallSourceSchema,\n /**\n * WHAT THE APPLY DID, or `null` when it did nothing but record.\n *\n * An apply that sends its own `declaration` has already reconciled it — that is what `naive up`\n * is — so the row it writes is a record and this is `null`. An apply that names a **published**\n * pair has reconciled nothing: it was never given the bytes (§31.1), so the server reads them\n * from the catalog and runs the same engine over them, and this is what that run reported.\n *\n * It is stored rather than only returned because a refusal inside a successful apply — an app\n * whose `env` reads a variable no hosted run has, a session refused for credit — is the one fact\n * a person needs after the screen that showed it is gone.\n */\n report: BlueprintReportSchema.nullable(),\n status: BlueprintInstallStatusSchema,\n /**\n * Why a `failed` run threw, in one sentence — or, on an `applied` row, which `required` agent or\n * app the apply refused and why (§29.6). `null` otherwise. Never a stack or a key.\n */\n failure: z.string().nullable(),\n /**\n * The `selection` the apply carried, or `null` — every row written before §31.2 and every apply\n * that omitted it, both meaning \"everything\". Defaulted so those rows parse unchanged.\n */\n selection: BlueprintSelectionSchema.nullable().default(null),\n /** When the answers were last edited through `PATCH …/installs/{id}` (§31.8); `null` if never. */\n context_updated_at: Timestamp.nullable().default(null),\n /**\n * What this install's agent, app, identity and vault names start with (§29.6, ADR-1104): `\"\"`\n * when its template's names were free in the organization, `\"<project>-\"` when any was already\n * another project's. Decided once, by the apply that created the row, and never again. `null` is\n * an install from before that rule, or one a working tree recorded: its names are the template's.\n * Optional only so a Worker from before the field still parses; this API always sends it.\n */\n name_prefix: z.string().nullable().optional(),\n /**\n * The one skill this install is bound to (§29.6, ADR-1346): pinned in every seat on every hosted\n * apply of it, and in no other install's. `null` when it is bound to none. Set by the apply's own\n * `skill`; optional only so a Worker from before the field still parses.\n */\n skill: SkillRefSchema.nullable().optional(),\n applied_at: Timestamp,\n created_at: Timestamp,\n});\nexport type BlueprintInstall = z.infer<typeof BlueprintInstallSchema>;\n\n/** One answered setup question, as the crew reads it: the question's `label`, not just its `key`. */\nexport const ProjectContextAnswerSchema = z.object({\n key: z.string().min(1),\n label: z.string(),\n value: z.union([z.string(), z.array(z.string())]),\n});\nexport type ProjectContextAnswer = z.infer<typeof ProjectContextAnswerSchema>;\n\n/**\n * What a template's crew knows about the business it runs (§31.8): the install row's answers joined\n * to the artifact's questions, the report's apps with their URLs, and the crew with its roles.\n * Derived from the latest `applied` install and its report — only an edit to `answers` is stored.\n * `GET /v1/blueprints/installs/{id}/context`, the built-in `project_context` tool, and the\n * orchestrator's `vetta.blueprints_get_context` all return this one object.\n */\nexport const ProjectContextSchema = z.object({\n object: z.literal(\"project_context\"),\n project: z.string().min(1),\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n artifact_version: z.string().nullable(),\n answers: z.array(ProjectContextAnswerSchema),\n apps: z.array(z.object({ name: z.string().min(1), url: z.string().nullable() })),\n agents: z.array(z.object({ name: z.string().min(1), role: z.string().nullable() })),\n /** `context_updated_at` once the answers have been edited, `applied_at` until then. */\n updated_at: Timestamp,\n});\nexport type ProjectContext = z.infer<typeof ProjectContextSchema>;\n\n/**\n * How many drifted paths a `revision_conflict` message names before it says \"and N more\". A\n * declaration can disagree in hundreds of places and an unbounded refusal is unreadable; a bounded\n * one plus a count still tells the operator whether the other writer touched anything they own.\n */\nexport const DRIFT_PATHS_IN_MESSAGE = 20;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction walk(stored: unknown, incoming: unknown, at: string, into: string[]): void {\n if (isRecord(stored) && isRecord(incoming)) {\n for (const key of new Set([...Object.keys(stored), ...Object.keys(incoming)])) {\n walk(stored[key], incoming[key], at === \"\" ? key : `${at}.${key}`, into);\n }\n return;\n }\n if (Array.isArray(stored) && Array.isArray(incoming)) {\n for (let i = 0; i < Math.max(stored.length, incoming.length); i++) {\n walk(stored[i], incoming[i], `${at}.${i}`, into);\n }\n return;\n }\n if (JSON.stringify(stored ?? null) !== JSON.stringify(incoming ?? null)) into.push(at || \"(root)\");\n}\n\n/**\n * The paths at which a stored declaration and the one being applied disagree — `agents.2.model`,\n * `apps.0.mcp` — sorted, so two runs of the same conflict read the same.\n *\n * This is the canonical, key-sorted comparison `packages/blueprints/src/report.ts` already uses,\n * obtained structurally: the walk visits the union of an object's keys, so key ORDER is never a\n * change, while array order is meaning and is compared position by position. A key present on one\n * side and absent on the other is drift at that path — unlike `report.ts`'s `changed`, which is\n * asked about one declared field at a time and treats absence as \"not declared\". Here both sides\n * are whole declarations, so an added or dropped resource is exactly what an operator needs named.\n *\n * Computable server-side only because the declaration is stored, which is why storing it is not\n * redundancy (§29.6).\n */\nexport function driftedPaths(stored: unknown, incoming: unknown): string[] {\n const found: string[] = [];\n walk(stored, incoming, \"\", found);\n return found.sort();\n}\n","/**\n * The blueprint catalog (`canonical-spec §31`) — the built output of one blueprint × template ×\n * released version, published once and shared by every organization.\n *\n * A hosted run does not fork a blueprint into per-customer storage: the repository is\n * byte-identical for every operator, the template choice is one line out of a closed set, and the\n * answers, posts and accounts are runtime rows. So the build runs once per pair per release and\n * this is the row it produces.\n *\n * Nothing tenant-shaped appears here, and that is not an omission — the row has no `org_id` at all\n * (§31.1). Two of the things behind it never reach the wire either: each tree's `files_ref` is the\n * object-store key of that app's built bytes (the `provider_ref` posture, §29.1) and `declaration`\n * is the config only the reconciler reads. `questions`, `schedules`, `agents`, `apps` and\n * `identities` are the halves lifted out of it that a client genuinely needs — the crew because the\n * screen that asks a person to run a company has to show them the company first (§31.5), the\n * personas because it asks for their accounts before the crew exists (§31.10).\n */\n\nimport { z } from \"zod\";\nimport { SkillRefSchema } from \"./agent\";\nimport { AppTypeSchema } from \"./app\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { CreatorProfileSchema } from \"./creator-profile\";\nimport { MiniAppIconSchema, MiniAppSlugSchema } from \"./mini-app\";\nimport { QuestionFieldSchema } from \"./session\";\nimport { SocialPlatformSchema } from \"./social\";\n\n/**\n * One timer this template's crew runs, flattened out of the declaration's `agents[].schedules[]`\n * so the landing page can print what a crew does before anyone has signed up (§31.3).\n *\n * `agent` is the declared agent's **name**, not an `agt_` id: at the moment this is printed no\n * agent exists to have one.\n */\nexport const BlueprintScheduleSchema = z.object({\n agent: z.string().min(1),\n cron: z.string().min(1),\n timezone: z.string().nullable(),\n /** The message each fire opens its session with — the sentence worth printing. */\n input: z.string().min(1),\n /** What a fire does in a few words, as the template says it (ADR-1172); absent on a row that declares none. */\n summary: z.string().min(1).optional(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type BlueprintSchedule = z.infer<typeof BlueprintScheduleSchema>;\n\n/**\n * One timer's cap as the operator set it on the apply (§29.6 `budgets`), naming the timer by the\n * same `(agent, cron)` the published `schedules` row carries — the only key a schedule has before it\n * is a deployment. The published `budget_micro_usd` is the recommendation this replaces.\n */\nexport const BlueprintBudgetSchema = BlueprintScheduleSchema.pick({ agent: true, cron: true, budget_micro_usd: true });\nexport type BlueprintBudget = z.infer<typeof BlueprintBudgetSchema>;\n\n/**\n * One agent this template provisions, flattened out of the declaration's `agents[]` (§31.5).\n *\n * A third half lifted out of `declaration` for the same reason the first two were: somebody outside\n * the reconciler needs it. Nobody should be asked to provision a company without being shown who is\n * in it, and the crew cannot be read off `schedules` — an agent with no timer would simply not\n * appear, which is exactly the coordinator a template is usually built around.\n *\n * `name` is the declared name, not an `agt_` id, for the reason it is on a schedule: at the moment\n * this is printed no agent exists to have one. `briefed` is whether the declaration gives this\n * agent an `intake` (§31.4) — the difference between a crew that is provisioned and a crew that has\n * started working, and the sentence a person is entitled to read before they pay for it. `intake`\n * is that first message's text, null when the declaration briefs nobody — and ABSENT on a row\n * published before this release, which is why it is optional (see `BlueprintAppSchema` below).\n *\n * `role` (two or three words beside the name), `skills` (§13 refs, verbatim), `tools` (the built-in\n * and `<app>.<tool>` names the declaration allows this agent, sorted) and `required` (whether an\n * install may leave it out, §31.2) are the WS12 v2 half of the same reading, optional for the same\n * reason: rows published before them lack them.\n */\nexport const BlueprintCrewSchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n model: z.string().min(1),\n briefed: z.boolean(),\n intake: z.string().nullable().optional(),\n /** What the first session may spend: the intake's own cap, else the agent's (§31.4). Set iff `briefed`. */\n intake_micro_usd: MicroUsdField.nonnegative().optional(),\n role: z.string().min(1).optional(),\n skills: z.array(SkillRefSchema).optional(),\n tools: z.array(z.string().min(1)).optional(),\n required: z.boolean().optional(),\n});\nexport type BlueprintCrew = z.infer<typeof BlueprintCrewSchema>;\n\n/**\n * One app this template deploys, flattened out of the declaration's `apps[]` (§31.5). `mcp` is the\n * path it serves MCP on (§29.5) or null; `tools` is the tool names (no `<app>.` prefix) any agent's\n * `tools.configs` names under it, sorted.\n *\n * *** THESE TWO AND `BlueprintCrewSchema.intake` ARE OPTIONAL, AND THAT IS THE ROLLOUT. ***\n *\n * A deploy does not rebuild the catalog: every published row was written by whichever release was\n * current when its blueprint released, and not one row live today carries any of the three. Making\n * them required makes the artifact a client cannot read the artifact the platform is serving —\n * and `apps/naive-lp-v2` parses that live catalog at build time and fails the build by design on a\n * row it cannot read, so every landing-page build between this deploy and the republish of every\n * artifact would hard-fail. Absent means \"the release that published this row did not carry it\";\n * every screen that reads them already draws that as an app with no MCP path and no tools.\n */\nexport const BlueprintAppSchema = z.object({\n name: z.string().min(1),\n type: AppTypeSchema,\n description: z.string().nullable(),\n mcp: z.string().nullable().optional(),\n tools: z.array(z.string().min(1)).optional(),\n /** Whether an install may deselect it (§31.2). Optional: the rollout argument above. */\n required: z.boolean().optional(),\n});\nexport type BlueprintApp = z.infer<typeof BlueprintAppSchema>;\n\n/**\n * One persona this template's crew acts as, flattened out of the declaration's `identities[]`\n * (§31.10). `name` is the declared name — the same name the apply's `upsertIdentity` finds it by.\n * Its accounts are connected after the apply, and they are where the crew posts (ADR-0922).\n */\nexport const BlueprintIdentitySchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n});\nexport type BlueprintIdentity = z.infer<typeof BlueprintIdentitySchema>;\n\n/**\n * Lowercase sha-256 hex — exactly what `contentHash()` in `@usenaive-sdk/blueprints`\n * (`src/files.ts`) returns over a deployment's file map.\n *\n * §29.2's `content_hash` is a free string the server stores and never checks, because a *customer*\n * supplies it. This one is ours: an install skips the upload when it equals the newest deployment's\n * hash, so the two must be the same digest of the same bytes. Pinning the shape here is what turns\n * a drift into a failing parse instead of a silent re-upload on every install.\n */\nexport const ContentHashSchema = z.string().regex(/^[0-9a-f]{64}$/, \"a lowercase sha-256 hex digest\");\n\n/** One seeded card as the catalog prints it (§31.5): what it asks for, and whose it is (`null`: the CEO's to hand out). */\nexport const BlueprintTaskSchema = z.object({ title: z.string().min(1), assignee: z.string().min(1).nullable() });\nexport type BlueprintTask = z.infer<typeof BlueprintTaskSchema>;\n\n/** One mini app the template declares (§50), as a catalog lists it: its slug, name and tile. */\nexport const BlueprintMiniAppSchema = z.object({ slug: MiniAppSlugSchema, name: z.string().min(1), icon: MiniAppIconSchema });\nexport type BlueprintMiniApp = z.infer<typeof BlueprintMiniAppSchema>;\n\n/**\n * One app's built tree (§31.1). A blueprint ships as many as it declares with a `deploy_dir` —\n * `media` one, `agency` two (`dashboard` and `site`) — so the artifact addresses a tree PER APP,\n * keyed by the name the declaration gives it.\n *\n * The digest is per app because the skip is per app: §29.2 compares against a *deployment*, and a\n * deployment belongs to one app, so one hash over every tree would move whenever any single app\n * changed and send every other app's unchanged bytes up again on every install.\n *\n * The row's own entry also carries `files_ref`, the object-store key of these bytes. It is a\n * provider handle and stays server-side (§29.1) — and it stays there BY THIS SCHEMA: the store\n * parses stored trees through it on the way out, and zod's default strip is what removes the key.\n * A field added here reaches the wire; that is the thing to know before adding one.\n */\nexport const BlueprintTreeSchema = z.object({\n /** `apps[].name` in the declaration — the same name §31.5 prints and the install ensures by. */\n app: z.string().min(1),\n content_hash: ContentHashSchema,\n});\nexport type BlueprintTree = z.infer<typeof BlueprintTreeSchema>;\n\nexport const BlueprintArtifactSchema = z.object({\n id: idOf(\"bpa\"),\n object: z.literal(\"blueprint_artifact\"),\n /** The machine — its repository, screens and `/api/*`. */\n blueprint: z.string().min(1),\n /** Which of that blueprint's templates provides the crew. */\n template: z.string().min(1),\n /** The blueprint repository's own released version. Stored, never parsed (ADR-0401). */\n version: z.string().min(1),\n /**\n * What a person calls the template, one line on what its crew does, and the networks it publishes\n * to — printed, never provisioned (§31.5, ADR-0921). `platforms` is decoration: where the crew\n * posts is the accounts connected to its persona. Optional for the §31.5 rollout reason.\n */\n title: z.string().min(1).optional(),\n description: z.string().min(1).optional(),\n platforms: z.array(SocialPlatformSchema).optional(),\n /**\n * The built trees, one per deployable app, ordered as the declaration orders its apps. Empty for\n * a data-only blueprint: it declares no app, builds nothing, and still ships a crew (ADR-0900).\n */\n trees: z.array(BlueprintTreeSchema),\n /**\n * The setup questions, asked by the studio **before** provisioning. `QuestionField` (§7.1) is\n * reused rather than restated: a setup question and a question a parked agent asks are the same\n * object at different times, so one component renders both.\n */\n questions: z.array(QuestionFieldSchema),\n schedules: z.array(BlueprintScheduleSchema),\n /** Who the crew is, and what it deploys — §31.5. Derived from `declaration`, never stored twice. */\n agents: z.array(BlueprintCrewSchema),\n apps: z.array(BlueprintAppSchema),\n /**\n * The agents a template creates per client the operator signs — printed, never provisioned by an\n * apply (§31.1). Absent on rows published before WS12 v2, hence optional.\n */\n crew_per_client: z.array(BlueprintCrewSchema).optional(),\n /**\n * The personas the crew posts from, and which accounts to connect to each before the crew\n * exists (§31.10). Derived from `declaration` like `agents`; optional for the §31.5 rollout reason.\n */\n identities: z.array(BlueprintIdentitySchema).optional(),\n /**\n * The crew's first work: the cards an apply seeds on the board (§31.11), as a title and who has\n * it, in the declared order. Derived from `declaration` like `agents`, so a person reads day one\n * before paying for it (the launch roadmap, ADR-1170); optional for the §31.5 rollout reason.\n */\n tasks: z.array(BlueprintTaskSchema).optional(),\n /**\n * The mini apps the template brings (§50.1): no tree, no deploy, so they are not in `apps`, and a\n * person is shown them beside the hosted ones before paying (ADR-1171). Derived from\n * `declaration.mini_apps` like `tasks`; optional for the §31.5 rollout reason.\n */\n mini_apps: z.array(BlueprintMiniAppSchema).optional(),\n /** The first week in the template's own words (ADR-1172): Day 1, what each day after it carries, and what follows the week. */\n roadmap: z.object({ day_one: z.string().min(1).optional(), every_day: z.string().min(1).optional(), after: z.string().min(1).optional() }).optional(),\n /**\n * The creator template a row was published from (§42.8), `null` on every first-party row.\n * `creator_name` is the public display name the landing page credits. The API sends all three\n * on every row; they are optional here only so an artifact typed before §42 still reads.\n */\n creator_template_id: idOf(\"ctp\").nullish(),\n creator_template_version: z.number().int().positive().nullish(),\n creator_name: z.string().min(1).nullish(),\n /**\n * \"Naive verified\" (ADR-1593): every first-party row, and a row whose template the reviewer\n * verified. Derived by the catalog read, never stored on the row. Optional so an artifact typed\n * before it still reads; absent is not verified.\n */\n verified: z.boolean().optional(),\n /**\n * Who the template is by (`canonical-spec §65`, ADR-1831): `NAIVE_PROFILE` on a first-party row and\n * on a build of Naive's own organizations, else the creator's or the listing company's profile.\n * The live credit; `creator_name` is the name stamped at first publish, kept for older readers.\n * Optional for the §31.5 rollout reason.\n */\n author: CreatorProfileSchema.optional(),\n /**\n * The listing a reviewer curated for a creator row (§42.8): its one-line pitch, and a public\n * sample video with its poster frame. Optional and nullish — a first-party row and a row whose\n * listing names no hero carry none, and the landing page prints only what is present.\n */\n creator_tagline: z.string().min(1).nullish(),\n creator_hero_url: z.string().url().nullish(),\n creator_hero_poster_url: z.string().url().nullish(),\n /**\n * What the crew can do once installed, in plain lines (ADR-1550): computed by the engine's\n * `whatItCanDo` from the declaration, on the toolset an install writes. Every line, never cut:\n * the risk lines rank last. Never stored. Optional so an artifact typed before it still reads.\n */\n can_do: z.array(z.string().min(1)).optional(),\n published_at: Timestamp,\n});\nexport type BlueprintArtifact = z.infer<typeof BlueprintArtifactSchema>;\n","/**\n * The public profile a listed template credits (`canonical-spec §65`, ADR-1831): a creator's, a\n * company's, or Naive's. Three things are editable (picture, name, description); the handle is\n * derived once, when the profile is first made, and never changes, so a profile page's link never\n * breaks.\n *\n * Naive is not a row: `NAIVE_PROFILE` is this constant, and every first-party template, and every\n * build of Naive's own organizations, resolves to it. It is the only profile with `verified: true`.\n */\nimport { z } from \"zod\";\n\n/** Lowercase words joined by single hyphens, ≤ 40: a creator's `code`, or `<company-slug>-<6 of its org id>`. */\nexport const ProfileHandleSchema = z.string().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/).max(40);\n\nexport const CreatorProfileSchema = z.object({\n object: z.literal(\"creator_profile\"),\n handle: ProfileHandleSchema,\n name: z.string().trim().min(1).max(60),\n description: z.string().trim().max(280),\n /** A public `https://` image; `null` shows a monogram. */\n avatar_url: z.url().nullable(),\n /** `true` only on `NAIVE_PROFILE`. */\n verified: z.boolean(),\n});\nexport type CreatorProfile = z.infer<typeof CreatorProfileSchema>;\n\n/** The kinds of picture accepted, and the most bytes one may decode to. */\nexport const PROFILE_AVATAR_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\"] as const;\nexport const PROFILE_AVATAR_MAX_BYTES = 512 * 1024;\n\n/**\n * A new picture, as base64 in the JSON body so every client stays JSON-only (ADR-1832). The server\n * checks the decoded bytes against `content_type` and the size cap.\n */\nexport const ProfileAvatarSchema = z.object({\n content_type: z.enum(PROFILE_AVATAR_TYPES),\n /** ≤ 512 KiB decoded: 4/3 of it, rounded up to a whole base64 quantum. */\n data: z.base64().max(Math.ceil(PROFILE_AVATAR_MAX_BYTES / 3) * 4),\n});\nexport type ProfileAvatar = z.infer<typeof ProfileAvatarSchema>;\n\n/** `PATCH …/profile`: each field optional; `avatar: null` removes the picture. */\nexport const CreatorProfilePatchSchema = z\n .object({\n name: CreatorProfileSchema.shape.name.optional(),\n description: CreatorProfileSchema.shape.description.optional(),\n avatar: ProfileAvatarSchema.nullable().optional(),\n })\n .strict();\nexport type CreatorProfilePatch = z.infer<typeof CreatorProfilePatchSchema>;\n\n/** Naive's own profile: a constant, never a row, and the only verified one. */\nexport const NAIVE_PROFILE: CreatorProfile = Object.freeze({\n object: \"creator_profile\",\n handle: \"naive\",\n name: \"Naive\",\n description: \"Templates built and run by the Naive team.\",\n avatar_url: \"https://usenaive.ai/apple-touch-icon.png\",\n verified: true,\n});\n","/**\n * MINI APPS — a template's pages of the platform's data-bound blocks (canonical-spec §50, ADR-0982).\n * A template declares its mini apps as data; the platform resolves every binding and the studio\n * draws every mini app with one general UI. A page's spec is `compose`'s (§49): a flat element map\n * under one root, words written by the author, every number a `$source` binding code resolves. The\n * catalog is the same one, plus the blocks a page needs: sections, what waits on a person, what the\n * agents are doing, the accounts, the posts, the setup's answers and the company's media library.\n */\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { PendingActionSchema, TEMPLATE_QUESTIONS_MAX } from \"./session\";\nimport { PostSchema, SocialPlatformSchema } from \"./social\";\nimport { RoadmapViewSchema } from \"./show\";\nimport { Bound, bound, box, catalog, element, Key, label, leaf, Resolved, spec, unknownComponent, words } from \"./catalog\";\n\nexport const PAGE_BLOCKS = [\n \"Page\", \"Section\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\",\n \"Needs\", \"Activity\", \"Accounts\", \"Posts\", \"Answers\", \"MediaLibrary\", \"AdsLibrary\", \"SeoLibrary\", \"Crm\", \"Calendar\",\n] as const;\nexport const MAX_PAGE_ELEMENTS = 48;\n/** The icons a mini app may wear on its tile: a small fixed set, drawn by the studio. Never an agent's face. */\nexport const MINI_APP_ICONS = [\"grid\", \"list\", \"chart\", \"calendar\", \"play\", \"megaphone\", \"person\"] as const;\nexport const MiniAppIconSchema = z.enum(MINI_APP_ICONS);\nexport type MiniAppIcon = z.infer<typeof MiniAppIconSchema>;\nconst SLUG = \"[a-z][a-z0-9-]{0,39}\";\nexport const MiniAppSlugSchema = z.string().regex(new RegExp(`^${SLUG}$`), \"a slug is lowercase letters, digits and -\");\n\n/** Where a section's head may lead: a platform place, or a mini app (one of its pages, if named). */\nconst Place = z\n .string()\n .regex(new RegExp(`^/(board|connections|apps/${SLUG}(\\\\?page=${SLUG})?)$`), \"a section links to /board, /connections or /apps/<slug>[?page=<slug>]\");\nconst POSTS = [\"waiting\", \"scheduled\", \"posted\"] as const;\nconst PostStatus = z.enum(POSTS);\n/** How a list of posts is drawn (ADR-1020): rows, one sideways row of cards, or a picture grid. */\nconst PostLayout = z.enum([\"list\", \"row\", \"grid\"]);\n/** One status, or several read into one list in the order given (ADR-1010). */\nconst PostStatuses = z.union([PostStatus, z.array(PostStatus).min(1).max(3).refine((all) => new Set(all).size === all.length, \"each status once\")]);\n\n/** A page's side of the shared slots: a roadmap may be shorter per group, media is up to six tiles. */\nconst PageBound = {\n ...Bound,\n board: bound([\"roadmap\"], { per_group: z.number().int().min(1).max(5).default(5) }),\n media: bound([\"latest_media\", \"newest_media\"], { count: z.number().int().min(1).max(6).default(4) }),\n};\nconst PageResolved = {\n ...Resolved,\n board: z.strictObject({ $source: z.literal(\"roadmap\"), per_group: z.number().int(), groups: RoadmapViewSchema.shape.groups }),\n media: z.array(z.strictObject({ id: z.string(), kind: z.enum([\"image\", \"video\"]) })).max(6),\n};\n\n/** The page's own blocks, bound or resolved. */\nfunction pageBlocks<Needs extends z.ZodType, Agents extends z.ZodType, Accounts extends z.ZodType, Posts extends z.ZodType, Answers extends z.ZodType>(slot: {\n needs: Needs;\n agents: Agents;\n accounts: Accounts;\n posts: Posts;\n answers: Answers;\n}) {\n return {\n Page: element(\"Page\", {}, box, \"The page itself, the root and only the root.\"),\n Section: element(\"Section\", { title: words(40), to: Place.optional(), hide_empty: z.boolean().optional() }, box, \"A titled part of the page; hidden when every block in it is empty, if asked.\"),\n Needs: element(\"Needs\", { label, needs: slot.needs }, leaf, \"What waits on a person: approvals, questions, spent caps.\"),\n Activity: element(\"Activity\", { label, agents: slot.agents }, leaf, \"The agents working or waiting, and on what.\"),\n Accounts: element(\"Accounts\", { accounts: slot.accounts }, leaf, \"The template's networks: connected with a handle, or not.\"),\n Posts: element(\n \"Posts\",\n { label, layout: PostLayout.optional(), posts: slot.posts },\n leaf,\n \"Posts waiting on a person, scheduled, or posted; several statuses make one list. Drawn as rows (list, the default), one sideways row of cards (row), or a picture grid (grid).\",\n ),\n Answers: element(\"Answers\", { answers: slot.answers }, leaf, \"The setup's answers in one line, linking to the setup.\"),\n // No binding: the studio's gallery reads and pages the company's files itself (ADR-0987).\n MediaLibrary: element(\"MediaLibrary\", {}, leaf, \"Every picture and clip the company's agents made, with filters, sort and a viewer.\"),\n // No binding either: the studio reads the files tagged `ad` and edits their tags itself (ADR-1391).\n AdsLibrary: element(\"AdsLibrary\", {}, leaf, \"The company's ads by campaign, with review, approve and a player.\"),\n // The same for the files tagged `seo`: written work by client, kind and stage.\n SeoLibrary: element(\"SeoLibrary\", {}, leaf, \"The company's SEO and GEO documents by client, with review, approve and a reader.\"),\n Crm: element(\"Crm\", {}, leaf, \"The company's clients by stage, each with its next step and its timeline.\"),\n Calendar: element(\"Calendar\", {}, leaf, \"The company's month: meetings and the follow-ups due.\"),\n };\n}\n\nconst OwnBound = pageBlocks({\n needs: bound([\"needs\"], {}),\n agents: bound([\"agents_activity\"], {}),\n accounts: bound([\"accounts\"], {}),\n posts: bound([\"posts\"], { status: PostStatuses, limit: z.number().int().min(1).max(50).default(10) }),\n answers: bound([\"answers\"], { keys: z.array(Key).min(1).max(TEMPLATE_QUESTIONS_MAX) }),\n});\n\nconst Need = z.object({\n session_id: z.string(),\n agent_id: z.string(),\n agent: z.string(),\n since: Timestamp,\n /** The chat's stored title, or `null`: the studio names it by when it began. */\n title: z.string().nullable(),\n kind: z.enum([\"tool\", \"question\", \"budget\"]),\n /** The call or question it is held on; `null` for a spent cap. */\n action: PendingActionSchema.nullable(),\n});\nconst Working = z.object({\n agent_id: z.string(),\n agent: z.string(),\n state: z.enum([\"working\", \"waiting\"]),\n session_id: z.string().nullable(),\n title: z.string().nullable(),\n at: Timestamp,\n});\n\nconst OwnResolved = pageBlocks({\n needs: z.strictObject({ $source: z.literal(\"needs\"), items: z.array(Need) }),\n agents: z.strictObject({ $source: z.literal(\"agents_activity\"), agents: z.array(Working) }),\n accounts: z.strictObject({\n $source: z.literal(\"accounts\"),\n accounts: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean(), handle: z.string().nullable() })),\n }),\n posts: z.strictObject({ $source: z.literal(\"posts\"), status: z.union([PostStatus, z.array(PostStatus)]), limit: z.number().int(), posts: z.array(PostSchema), more: z.boolean() }),\n answers: z.strictObject({\n $source: z.literal(\"answers\"),\n keys: z.array(z.string()),\n values: z.array(z.string()),\n template: z.object({ blueprint: z.string(), template: z.string() }).nullable(),\n }),\n});\n\nconst BoundBlocks = { ...catalog(PageBound), ...OwnBound };\nconst ResolvedBlocks = { ...catalog(PageResolved), ...OwnResolved };\n\n/** A block whose source could not be read: one quiet line in its place, never the page down. */\nconst Unread = element(\"Unread\", { of: z.string(), label: z.string().nullable(), reason: z.string() }, leaf, \"A block that could not be read.\");\n\n/* Spelled out for each side, as `compose.ts` does: a helper generic over the blocks loses their types. */\nconst B = BoundBlocks;\nexport const PageSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [B.Page, B.Section, B.Stack, B.Grid, B.Metric, B.LineChart, B.BarList, B.Progress, B.Roadmap, B.Schedule, B.Media, B.Text, B.Needs, B.Activity, B.Accounts, B.Posts, B.Answers, B.MediaLibrary, B.AdsLibrary, B.SeoLibrary, B.Crm, B.Calendar],\n unknownComponent(PAGE_BLOCKS),\n ),\n \"Page\",\n MAX_PAGE_ELEMENTS,\n);\nexport type PageSpec = z.infer<typeof PageSpecSchema>;\nexport type PageElement = PageSpec[\"elements\"][string];\n\nconst R = ResolvedBlocks;\n/** One resolved block: checked as it is read, so a bad one is one `Unread` line, not the page down. */\nexport const ResolvedPageElementSchema = z.discriminatedUnion(\n \"type\",\n [R.Page, R.Section, R.Stack, R.Grid, R.Metric, R.LineChart, R.BarList, R.Progress, R.Roadmap, R.Schedule, R.Media, R.Text, R.Needs, R.Activity, R.Accounts, R.Posts, R.Answers, R.MediaLibrary, R.AdsLibrary, R.SeoLibrary, R.Crm, R.Calendar, Unread],\n unknownComponent(PAGE_BLOCKS),\n);\nexport const ResolvedPageSpecSchema = spec(ResolvedPageElementSchema, \"Page\", MAX_PAGE_ELEMENTS);\nexport type ResolvedPageSpec = z.infer<typeof ResolvedPageSpecSchema>;\nexport type ResolvedPageElement = ResolvedPageSpec[\"elements\"][string];\n/** One block's resolved props: what the studio's renderer draws. */\nexport type BlockProps<T extends ResolvedPageElement[\"type\"]> = Extract<ResolvedPageElement, { type: T }>[\"props\"];\n\nconst unique = (items: { slug: string }[]) => new Set(items.map((item) => item.slug)).size === items.length;\n\n/** One page of a mini app: a tab of its own, under its own title. */\nexport const MiniAppPageSchema = z.strictObject({ slug: MiniAppSlugSchema, title: words(24), spec: PageSpecSchema });\n\n/** One mini app as a template declares it: data only, checked with the catalog when it is read (§50.2). */\nexport const MiniAppDeclSchema = z.strictObject({\n slug: MiniAppSlugSchema,\n name: words(40),\n icon: MiniAppIconSchema,\n pages: z.array(MiniAppPageSchema).min(1).max(6).refine(unique, \"each page's slug is its own\"),\n});\nexport type MiniAppDecl = z.infer<typeof MiniAppDeclSchema>;\n\n/** The tag that makes a file an ad: the Ads app lists these, and is in the company's Apps once one exists. */\nexport const AD_TAG = \"ad\";\n\n/**\n * ADS (owner, 2026-10-18: \"the ad studio should be an app in the apps … super simple and clean and easy\n * to organise\"; ADR-1391). The one mini app no template declares: any company can open it from the app\n * store, and it joins the company's Apps once the company has an ad. Its whole page is the ads block.\n */\nexport const ADS_APP: MiniAppDecl = {\n slug: \"ads\",\n name: \"Ads\",\n icon: \"megaphone\",\n pages: [{ slug: \"ads\", title: \"Ads\", spec: { root: \"page\", elements: { page: { type: \"Page\", props: {}, children: [\"ads\"] }, ads: { type: \"AdsLibrary\", props: {} } } } }],\n};\n/**\n * The tag that makes a file an SEO or GEO deliverable. With it: `client:<ctc_id>` (the CRM contact it is\n * for), `kind:article|answer-block|page|audit|serp-report` and `stage:review|approved|live` (none is review).\n */\nexport const SEO_TAG = \"seo\";\n\n/**\n * SEO & GEO: the company's written search work, read and approved by client. Unlike Ads the platform\n * never lists it; a template that wants it declares it, and its whole page is the SEO block.\n */\nexport const SEO_APP: MiniAppDecl = {\n slug: \"seo-geo\",\n name: \"SEO & GEO\",\n icon: \"list\",\n pages: [{ slug: \"seo\", title: \"SEO & GEO\", spec: { root: \"page\", elements: { page: { type: \"Page\", props: {}, children: [\"seo\"] }, seo: { type: \"SeoLibrary\", props: {} } } } }],\n};\nexport const MiniAppDeclsSchema = z.array(MiniAppDeclSchema).max(8).refine(unique, \"each mini app's slug is its own\");\n\n/**\n * WHAT A MINI APP READS (§50.3, ADR-1048), derived by code from its declaration, never written by\n * its author: every `$source` bound on any of its pages, `media_library` for the library block,\n * `ads_library` for the ads block, `seo_library` for the SEO block, and\n * `posts_waiting` where a posts list shows posts waiting on a person — which that person can allow\n * or refuse from it. Sorted, each once.\n */\nexport function miniAppReads(app: MiniAppDecl): string[] {\n const reads = new Set<string>();\n for (const page of app.pages) {\n for (const element of Object.values(page.spec.elements)) {\n if (element.type === \"MediaLibrary\") reads.add(\"media_library\");\n if (element.type === \"AdsLibrary\") reads.add(\"ads_library\");\n if (element.type === \"SeoLibrary\") reads.add(\"seo_library\");\n if (element.type === \"Crm\") reads.add(\"crm\");\n if (element.type === \"Calendar\") reads.add(\"calendar\");\n for (const value of Object.values(element.props as Record<string, unknown>)) {\n const source = typeof value === \"object\" && value !== null && \"$source\" in value ? (value as { $source: unknown; status?: unknown }) : null;\n if (typeof source?.$source !== \"string\") continue;\n reads.add(source.$source);\n if (source.$source === \"posts\" && [source.status].flat().includes(\"waiting\")) reads.add(\"posts_waiting\");\n }\n }\n }\n return [...reads].sort();\n}\n\n/** `GET /v1/mini-apps` — the mini apps a company has, in its template's order (§50.3). */\nexport const MiniAppSummarySchema = z.object({\n object: z.literal(\"mini_app\"),\n slug: MiniAppSlugSchema,\n name: z.string(),\n icon: MiniAppIconSchema,\n pages: z.array(z.object({ slug: MiniAppSlugSchema, title: z.string() })).min(1),\n /** What it reads (`miniAppReads`). Absent from an older API: the Studio then claims nothing it cannot see. */\n reads: z.array(z.string()).optional(),\n /** The install's project, which its crew's `metadata.project` names: who runs the app. Absent from an older API. */\n project: z.string().optional(),\n});\nexport type MiniAppSummary = z.infer<typeof MiniAppSummarySchema>;\n\n/**\n * `GET /v1/mini-apps/{slug}` — one mini app with one page read, every binding at `as_of` on the\n * company's clock. `networks` is the applied template's networks for the header's marks, each with\n * whether a persona is connected to it (`null`: that could not be read; ADR-0992).\n */\nexport const MiniAppSchema = MiniAppSummarySchema.extend({\n networks: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean().nullable() })),\n page: MiniAppSlugSchema,\n as_of: Timestamp,\n timezone: z.string().min(1),\n spec: ResolvedPageSpecSchema,\n});\nexport type MiniApp = z.infer<typeof MiniAppSchema>;\n","/**\n * `show` — a view of the company the chat draws (canonical-spec §48). The model names a source;\n * code reads the data and writes the view, title included, so no number on the figure was typed\n * by the model. The same schema is the tool's argument parser, its result, and the web's reader.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { BoardStatusSchema } from \"./board\";\nimport { DATA_DOMAINS } from \"./data\";\n\nexport const SHOW_SOURCES = [\"spend_by_day\", \"post_views\", \"roadmap\", \"schedule\", \"calendar\", \"earnings\", \"audit\", \"data_catalog\"] as const;\nexport const ShowSourceSchema = z.enum(SHOW_SOURCES);\n\n/**\n * FLAT, ON PURPOSE. A discriminated union of per-source arguments becomes a root `oneOf`, which\n * providers refuse and which `defineTool`'s key repair cannot read (it only knows an object's\n * keys). `days` is read by `spend_by_day` alone.\n */\nexport const ShowArgsSchema = z.object({\n source: ShowSourceSchema.describe(\n \"What to show: spend_by_day (company spend per day, a line), post_views (views per recent post, bars), \" +\n \"roadmap (the board's work by status), schedule (routines and scheduled posts over the next 7 days), \" +\n \"earnings (what the company's marketplace templates have earned, and each listing's review), \" +\n \"audit (the audit log's raw entries, filterable), data_catalog (the priced data tools, searchable).\",\n ),\n days: z.number().int().min(2).max(30).optional().describe(\"spend_by_day only: days back, today included. Default 14.\"),\n actor: z.string().max(64).optional().describe(\"audit: one principal id, usr_… or key_….\"),\n action: z.string().max(100).optional().describe(\"audit: one action, e.g. api_key.created.\"),\n resource: z.string().max(100).optional().describe(\"audit: one resource id.\"),\n request_id: z.string().max(100).optional().describe(\"audit: the entries one request wrote.\"),\n from: Timestamp.optional().describe(\"audit: from this instant, inclusive.\"),\n to: Timestamp.optional().describe(\"audit: until this instant, exclusive.\"),\n query: z.string().max(200).optional().describe(\"data_catalog: what to search for.\"),\n domain: z.enum(DATA_DOMAINS).optional().describe(\"data_catalog: one domain.\"),\n});\nexport type ShowArgs = z.infer<typeof ShowArgsSchema>;\n\n/** A calendar day on the company's clock (§20.6). */\nconst Day = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nconst Count = z.number().int().nonnegative();\n\n/** What every view carries: its title (written by code), when it was read, and the company's clock. */\nconst head = { title: z.string().min(1), as_of: Timestamp, timezone: z.string().min(1) };\n\nexport const SpendByDayViewSchema = z.object({\n source: z.literal(\"spend_by_day\"),\n ...head,\n days: z.array(z.object({ day: Day, micro_usd: Count })).min(2).max(30),\n});\n\nexport const PostViewsViewSchema = z.object({\n source: z.literal(\"post_views\"),\n ...head,\n posts: z\n .array(z.object({ post_id: z.string().min(1), label: z.string(), networks: z.array(z.string()), posted_at: Timestamp, views: Count }))\n .max(12),\n});\n\nexport const RoadmapViewSchema = z.object({\n source: z.literal(\"roadmap\"),\n ...head,\n groups: z.array(\n z.object({\n status: BoardStatusSchema,\n count: Count,\n cards: z.array(z.object({ title: z.string(), assignee: z.string().nullable(), waits_on: z.array(z.string()) })).max(5),\n }),\n ),\n});\n\nexport const ScheduleViewSchema = z.object({\n source: z.literal(\"schedule\"),\n ...head,\n days: z\n .array(\n z.object({\n day: Day,\n count: Count,\n items: z\n .array(\n z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"routine\"), at: Timestamp, agent: z.string(), text: z.string(), runs: z.number().int().min(1).max(100) }),\n z.object({ kind: z.literal(\"post\"), at: Timestamp, networks: z.array(z.string()), text: z.string() }),\n ]),\n )\n .max(8),\n }),\n )\n .max(7),\n});\n\n/** The CRM's week (§63): what's next is the card, the rest its rows, soonest first. */\nexport const CalendarViewSchema = z.object({\n source: z.literal(\"calendar\"),\n ...head,\n items: z\n .array(\n z.object({\n kind: z.enum([\"meeting\", \"follow_up\"]),\n at: Timestamp,\n ends_at: Timestamp.nullable(),\n title: z.string(),\n who: z.string().nullable(),\n }),\n )\n .max(8),\n more: Count,\n});\n\n/**\n * What the company's listed templates earned (ADR-1748): `pending` is still in the hold, `available`\n * is past it, both net of refunds; a row a payout claimed is no longer in either (ADR-1598). `percent` and `months` are `CREATOR_PROGRAM`'s, written\n * by code like every other number here. Each listing is its newest submission's name and review.\n */\nexport const EarningsViewSchema = z.object({\n source: z.literal(\"earnings\"),\n ...head,\n pending_micro_usd: z.number().int(),\n available_micro_usd: z.number().int(),\n percent: z.number().int(),\n months: z.number().int(),\n listings: z.array(z.object({ name: z.string(), status: z.enum([\"in_review\", \"listed\", \"changes_requested\", \"taken_down\"]), earned_micro_usd: z.number().int() })).max(12),\n});\n\n/**\n * THE AUDIT LOG, AS ITS RAW ROWS (§17, ADR-1621). The view carries only the filters it opens on; the\n * chat reads the rows from `GET /v1/audit_logs` under the person's own session, pages them and lets\n * the person change the filters. No model writes or summarises a row, so the record stays exact.\n */\nexport const AuditViewSchema = z.object({\n source: z.literal(\"audit\"),\n ...head,\n filters: z.object({\n actor: z.string().optional(),\n action: z.string().optional(),\n resource: z.string().optional(),\n request_id: z.string().optional(),\n from: Timestamp.optional(),\n to: Timestamp.optional(),\n }),\n});\n\n/** The priced data catalogue (§54): opened on a search; the chat reads `GET /v1/data/tools`. */\nexport const DataCatalogViewSchema = z.object({\n source: z.literal(\"data_catalog\"),\n ...head,\n filters: z.object({ query: z.string().optional(), domain: z.enum(DATA_DOMAINS).optional() }),\n});\n\nexport const ShowViewSchema = z.discriminatedUnion(\"source\", [\n AuditViewSchema,\n DataCatalogViewSchema,\n SpendByDayViewSchema,\n PostViewsViewSchema,\n RoadmapViewSchema,\n ScheduleViewSchema,\n CalendarViewSchema,\n EarningsViewSchema,\n]);\nexport type ShowView = z.infer<typeof ShowViewSchema>;\nexport type ScheduleItem = z.infer<typeof ScheduleViewSchema>[\"days\"][number][\"items\"][number];\n","/**\n * Data — public data reads through one priced catalogue (`canonical-spec §54`): social media,\n * people and companies, funding, search results, SEO, markets, news, law, weather, jobs, property,\n * reviews, trade and travel. Social data (§52) is this catalogue's `social` domain.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { SOCIAL_DATA_PLATFORMS } from \"./social\";\n\n/** What a data tool is about. Customer-facing names: never a source's or a vendor's. */\nexport const DATA_DOMAINS = [\n \"social\",\n \"search\",\n \"people\",\n \"companies\",\n \"compliance\",\n \"funding\",\n \"seo\",\n \"finance\",\n \"crypto\",\n \"news\",\n \"legal\",\n \"weather\",\n \"jobs\",\n \"real_estate\",\n \"reviews\",\n \"trade\",\n \"shopping\",\n \"travel\",\n] as const;\nexport type DataDomain = (typeof DATA_DOMAINS)[number];\n\nexport const DATA_PRICE_BASES = [\"per_call\", \"per_result\", \"varies\"] as const;\n\n/**\n * The most results one priced-per-result run may buy: the adapter clamps any result count the caller\n * sent to it, and every run (agent or REST) is admitted at that many results (`canonical-spec §54`).\n */\nexport const DATA_MAX_RESULTS = 25;\n/** The input fields upstream tools most often name a result count by (the form's defaults). */\nexport const DATA_COUNT_FIELDS = [\"limit\", \"maxItems\", \"max_results\", \"resultsLimit\", \"count\", \"num\"] as const;\n\n/**\n * Whether an input field names a result count, the clamp's test (§54). By words, so `maxResults`,\n * `results_per_page`, `maxPosts`, `pageSize` and `numComments` count, and `account` or `discount` do\n * not. Errs toward counting: a filter like `maxAge` lowered to 25 costs a narrower answer, while a\n * count the clamp misses buys results nobody was admitted for.\n */\nexport function isDataCountField(key: string): boolean {\n if ((DATA_COUNT_FIELDS as readonly string[]).includes(key)) return true;\n const words = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n const [first] = words;\n const last = words.at(-1);\n if (first === \"max\" || first === \"num\" || first === \"number\" || first === \"top\" || first === \"first\") return words.length > 1 || first === \"top\" || first === \"first\";\n if (words.includes(\"limit\") || words.includes(\"per\")) return true;\n if (last === \"count\" || last === \"limit\" || last === \"total\") return true;\n return last === \"size\" && (words.includes(\"page\") || words.includes(\"batch\") || words.includes(\"result\") || words.includes(\"results\"));\n}\n\nconst Params = z.record(z.string(), z.unknown());\n\nexport const DataToolQuerySchema = z.object({\n query: z.string().min(1).max(200),\n domain: z.enum(DATA_DOMAINS).optional(),\n /** Only with `domain: \"social\"` (or none): tools for one network. */\n platform: z.enum(SOCIAL_DATA_PLATFORMS).optional(),\n limit: z.coerce.number().int().min(1).max(20).default(8),\n});\nexport type DataToolQuery = z.infer<typeof DataToolQuerySchema>;\n\n/** What the caller pays, not what it costs the platform. */\nexport const DataPriceSchema = z.object({\n basis: z.enum(DATA_PRICE_BASES),\n micro_usd: z.number().int().nonnegative(),\n text: z.string(),\n});\n\nexport const DataToolSchema = z.object({\n object: z.literal(\"data_tool\"),\n /** Opaque; pass it back unchanged. */\n id: z.string().min(1),\n name: z.string(),\n description: z.string(),\n domains: z.array(z.enum(DATA_DOMAINS)),\n /** The networks a `social` tool reads; empty for every other domain. */\n platforms: z.array(z.enum(SOCIAL_DATA_PLATFORMS)),\n price: DataPriceSchema,\n});\nexport type DataTool = z.infer<typeof DataToolSchema>;\n\nexport const DataToolInputSchema = z.object({ path: Params.optional(), query: Params.optional(), body: Params.optional() });\n\nexport const DataToolDetailSchema = DataToolSchema.extend({ input: DataToolInputSchema, notes: z.array(z.string()) });\nexport type DataToolDetail = z.infer<typeof DataToolDetailSchema>;\n\nexport const DataRunRequestSchema = z.object({\n tool_id: z.string().min(1).max(400),\n path: Params.optional(),\n query: Params.optional(),\n body: Params.optional(),\n});\nexport type DataRunRequest = z.infer<typeof DataRunRequestSchema>;\n\nexport const DataRunSchema = z.object({\n object: z.literal(\"data_run\"),\n tool_id: z.string(),\n status: z.enum([\"succeeded\", \"failed\"]),\n data: z.unknown(),\n error: z.string().nullable(),\n cost_micro_usd: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\nexport type DataRun = z.infer<typeof DataRunSchema>;\n","/**\n * The block catalog shared by `compose` (§49) and mini apps (§50): the components, the rule that a\n * number is a binding code resolves, and the tree check. One catalog, built with different slots:\n * with bindings for what an author writes, with resolved values for what a renderer draws.\n * Internal to `schema/`: `compose.ts` and `mini-app.ts` export what the wire needs.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\nimport { PostViewsViewSchema, RoadmapViewSchema, ScheduleViewSchema } from \"./show\";\n\nexport const Key = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,39}$/, \"an element key is a short name: a letter, then letters, digits, - or _\");\nexport const Count = z.number().int().nonnegative();\n\n/**\n * WORDS ARE THE MODEL'S; DIGITS ARE NOT. A title or a note that says \"up 18%\" would put a number on\n * the card that no code read. The window a value covers is written by the chat from its binding\n * (\"Last 7 days\"), so the model never needs a digit. The ASCII regex is what the JSON Schema the\n * model is shown carries (a `\\p{…}` pattern is one some providers' validators cannot compile); the\n * refine closes every other script's digits, fractions and numeral signs (`١٢`, `18`, `½`, `Ⅻ`).\n * Number WORDS (\"twelve thousand\") no pattern can close: that is the model's words, unchecked for\n * meaning like any label (ADR-0955).\n */\nconst DIGIT = \"words only: a digit is refused, because every number on the card is read by code from a $source binding\";\nexport const words = (max: number) =>\n z\n .string()\n .trim()\n .min(1)\n .max(max)\n .regex(/^[^0-9]*$/, DIGIT)\n .refine((text) => !/\\p{N}/u.test(text), DIGIT);\n\nexport const Days = z.number().int().min(1).max(30).default(7).describe(\"The window: today and the days before it, on the company's clock.\");\n\n/** A binding to one of `sources`. A literal where one belongs is refused with the fix. */\nexport function bound<const S extends readonly [string, ...string[]], T extends z.ZodRawShape>(sources: S, shape: T) {\n const example = JSON.stringify({ $source: sources[0] });\n return z.strictObject(\n { $source: z.enum(sources), ...shape },\n { error: (issue) => (issue.code === \"invalid_type\" ? `must be a binding such as ${example}: a literal value is refused, code reads every number` : undefined) },\n );\n}\n\n/** The model's side: every data slot is a binding (or, for media, the ids of the company's files). */\nexport const Bound = {\n value: bound([\"views_total\", \"spend_total\"], { days: Days }).describe(\n \"views_total: the latest views of the posts published in the window. spend_total: the company's spend in the window (the CEO only).\",\n ),\n delta: bound([\"views_change\"], {}).describe(\n \"views_change: the value's views_total against the same number of days before it, as a percentage.\",\n ),\n series: bound([\"spend_by_day\"], { days: z.number().int().min(2).max(30).default(14) }).describe(\"spend_by_day: the company's spend per day (the CEO only).\"),\n bars: bound([\"post_views\"], { limit: z.number().int().min(1).max(12).default(5).describe(\"How many posts.\") }).describe(\n \"post_views: each recent post's latest views, newest first.\",\n ),\n progress: bound([\"posts_this_week\"], {}).describe(\"posts_this_week: posts since Monday against the weekly cadence from setup or the channel plan, else 3× a week.\"),\n board: bound([\"roadmap\"], {}).describe(\"roadmap: the board's work by status.\"),\n week: bound([\"schedule\"], {}).describe(\"schedule: routines and scheduled posts over the next 7 days.\"),\n media: z\n .union([bound([\"latest_media\"], { count: z.number().int().min(1).max(4).default(1) }), z.array(idOf(\"fil\")).min(1).max(4)])\n .describe('{\"$source\":\"latest_media\",\"count\":1} for the newest posted pictures or clips, or up to 4 fil_ ids.'),\n};\n\nexport const SpendDay = z.strictObject({ day: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/), micro_usd: Count });\n\n/** The result's side: each binding as it was asked, with what code read for it. */\nexport const Resolved = {\n value: z.discriminatedUnion(\"$source\", [\n z.strictObject({ $source: z.literal(\"views_total\"), days: z.number().int(), value: Count, posts: Count }),\n z.strictObject({ $source: z.literal(\"spend_total\"), days: z.number().int(), value: Count }),\n ]),\n delta: z.strictObject({ $source: z.literal(\"views_change\"), days: z.number().int(), current: Count, previous: Count }),\n series: z.strictObject({ $source: z.literal(\"spend_by_day\"), days: z.number().int(), points: z.array(SpendDay).min(2).max(30) }),\n bars: z.strictObject({ $source: z.literal(\"post_views\"), limit: z.number().int(), posts: PostViewsViewSchema.shape.posts }),\n progress: z.strictObject({ $source: z.literal(\"posts_this_week\"), value: Count, max: z.number().int().positive(), cadence: z.string() }),\n board: z.strictObject({ $source: z.literal(\"roadmap\"), groups: RoadmapViewSchema.shape.groups }),\n week: z.strictObject({ $source: z.literal(\"schedule\"), days: ScheduleViewSchema.shape.days }),\n media: z.array(z.strictObject({ id: idOf(\"fil\"), kind: z.enum([\"image\", \"video\"]) })).min(1).max(4),\n};\n\n/** An element that holds children, and one that holds none. */\nexport const box = { children: z.array(Key).min(1).max(12) };\nexport const leaf = { children: z.array(Key).max(0).optional() };\nexport const label = words(40).optional();\nexport const element = <T extends string, P extends z.ZodRawShape, C extends z.ZodRawShape>(type: T, props: P, children: C, about: string) =>\n z.strictObject({ type: z.literal(type), props: z.strictObject(props), ...children }).describe(about);\n\n/**\n * The components, once. `box` elements hold children; every other element is a leaf. One type\n * parameter per slot: a single `S extends Record<…, ZodType>` loses each slot's type to `unknown`.\n */\nexport function catalog<\n Value extends z.ZodType,\n Delta extends z.ZodType,\n Series extends z.ZodType,\n Bars extends z.ZodType,\n Goal extends z.ZodType,\n Board extends z.ZodType,\n Week extends z.ZodType,\n Files extends z.ZodType,\n>(slot: { value: Value; delta: Delta; series: Series; bars: Bars; progress: Goal; board: Board; week: Week; media: Files }) {\n return {\n Card: element(\"Card\", { title: words(60) }, box, \"The root, and only the root.\"),\n Stack: element(\"Stack\", {}, box, \"Children one under another.\"),\n Grid: element(\"Grid\", { columns: z.literal([1, 2, 3]) }, box, \"Children side by side.\"),\n Metric: element(\"Metric\", { label: words(40), value: slot.value, delta: slot.delta.optional() }, leaf, \"One big number, and optionally its change.\"),\n LineChart: element(\"LineChart\", { label, series: slot.series }, leaf, \"A line over days.\"),\n BarList: element(\"BarList\", { label, bars: slot.bars }, leaf, \"One bar per post.\"),\n Progress: element(\"Progress\", { label: words(40), progress: slot.progress }, leaf, \"A value against its goal.\"),\n Roadmap: element(\"Roadmap\", { label, board: slot.board }, leaf, \"The board grouped by status.\"),\n Schedule: element(\"Schedule\", { label, week: slot.week }, leaf, \"The week ahead, day by day.\"),\n Media: element(\"Media\", { label, files: slot.media }, leaf, \"Pictures or clips the company holds.\"),\n Text: element(\"Text\", { text: words(240) }, leaf, \"A short note in words.\"),\n };\n}\n\n/** An element outside the catalog is refused with the list. */\nexport const unknownComponent = (names: readonly string[]) => ({\n error: (issue: { code?: string }) => (issue.code === \"invalid_union\" ? `unknown component: use one of ${names.join(\", \")}` : undefined),\n});\n\n/**\n * THE TREE, CHECKED IN CODE. json-render draws whatever the map names and silently skips a child it\n * cannot find; here a missing child, a second parent, an orphan, a nested root or a root of the wrong\n * type is refused, so what the chat draws is exactly what the model sent.\n */\nfunction tree(rootType: string, max: number, spec: { root: string; elements: Record<string, { type: string; children?: string[] | undefined }> }, ctx: z.RefinementCtx): void {\n const refuse = (message: string, path: (string | number)[] = []) => ctx.addIssue({ code: \"custom\", message, path });\n const keys = Object.keys(spec.elements);\n // Own keys only: `toString` and `constructor` answer on every object, and are not elements.\n const has = (key: string): boolean => Object.hasOwn(spec.elements, key);\n if (keys.length > max) return refuse(`at most ${max} elements`, [\"elements\"]);\n const root = has(spec.root) ? spec.elements[spec.root] : undefined;\n if (!root) return refuse(`root names \"${spec.root}\", which is not in elements`, [\"root\"]);\n if (root.type !== rootType) return refuse(`the root must be a ${rootType}`, [\"root\"]);\n const parent = new Map<string, string>();\n for (const key of keys) {\n for (const child of spec.elements[key]!.children ?? []) {\n if (!has(child)) return refuse(`\"${child}\" is not in elements`, [\"elements\", key, \"children\"]);\n if (child === spec.root || parent.has(child)) return refuse(`\"${child}\" has more than one parent`, [\"elements\", key, \"children\"]);\n if (spec.elements[child]!.type === rootType) return refuse(`a ${rootType} is the root only; group with Stack or Grid`, [\"elements\", child, \"type\"]);\n parent.set(child, key);\n }\n }\n // One parent each and none for the root, so a walk down from the root ends; what it misses is\n // an orphan or a loop of its own.\n const reached = new Set([spec.root]);\n for (const key of reached) for (const child of spec.elements[key]!.children ?? []) reached.add(child);\n const lost = keys.find((key) => !reached.has(key));\n if (lost) refuse(`\"${lost}\" is not under the root`, [\"elements\", lost]);\n}\n\n/** A flat element map under one `root` of `rootType`, at most `max` elements, checked as a tree. */\nexport const spec = <E extends z.ZodType<{ type: string; children?: string[] | undefined }>>(element: E, rootType: string, max: number) =>\n z\n .strictObject({\n root: Key.describe(`The key of the top element, which must be a ${rootType}.`),\n elements: z.record(Key, element).describe(\"Every element by key; an element's children name other keys here.\"),\n })\n .superRefine((value, ctx) => tree(rootType, max, value, ctx));\n","/**\n * The credential vault (`canonical-spec.md §23`, `docs/identity/vault.mdx`, `docs/api/vaults.mdx`).\n *\n * One property defines this object and every field below serves it: **the value is write-only.**\n * It is accepted on create, sealed, and never returned by any endpoint — there is no reveal route,\n * no `value` on any read schema, and no update route (rotation is create-new + delete-old, so\n * `last_injected_at` stays attributable to exactly one secret).\n *\n * Note what is *absent* on purpose: `VaultCredentialSchema` has no `value`, so a handler that\n * parsed a row through it could not emit one even by accident. That is the guarantee expressed as\n * a type rather than as a convention.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/**\n * The three kinds `docs/identity/vault.mdx` publishes.\n *\n * · `static_bearer` / `mcp_oauth` are injected **server-side, in our own isolate**, when the MCP\n * client connects to `mcp_server_url`. The token never enters the sandbox, so the guarantee holds\n * with no vendor capability we do not have.\n * · `env_var` promises substitution at an egress proxy on the sandbox's network path. No such\n * boundary exists (`memory/vendor-tenki.md §5`: no egress allowlist, no per-domain policy, no\n * proxy hook), so the route refuses it with `feature_not_configured` rather than storing a secret\n * whose central safety property we cannot deliver (ADR-0117).\n */\nexport const VaultCredentialKindSchema = z.enum([\"env_var\", \"static_bearer\", \"mcp_oauth\"]);\nexport type VaultCredentialKind = z.infer<typeof VaultCredentialKindSchema>;\n\n/** A vault belongs to exactly one identity; `null` until the identity stream lands the object. */\nexport const VaultSchema = z.object({\n id: idOf(\"vlt\"),\n object: z.literal(\"vault\"),\n identity_id: idOf(\"idn\").nullable(),\n display_name: z.string().min(1).max(128),\n credential_count: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\nexport type Vault = z.infer<typeof VaultSchema>;\n\n/**\n * Credential **metadata**. Every read surface returns this and only this.\n *\n * `placeholder_ref` is not a secret and is returned deliberately: a caller needs it to write the\n * reference into a script. It names a credential; it authenticates nothing.\n */\nexport const VaultCredentialSchema = z.object({\n id: idOf(\"vcr\"),\n object: z.literal(\"vault_credential\"),\n vault_id: idOf(\"vlt\"),\n kind: VaultCredentialKindSchema,\n /** For `env_var`, the environment variable name. For the MCP kinds, a display label. */\n key: z.string().min(1).max(128),\n /** The exact destination host an `env_var` credential is bound to. Never a wildcard. */\n host: z.string().nullable(),\n /** The exact MCP server URL an `mcp_*` token is matched to. */\n mcp_server_url: z.url().nullable(),\n /**\n * The one agent this credential may be injected into (ADR-1097). `null` is any agent that\n * declares `mcp_server_url` — except the platform's own `/v1/mcp`, whose key is never injected\n * unbound. Set at create, by `admin`, and immutable like the rest. Defaults to `null` so a\n * client reading a control plane older than the field still parses the row.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n placeholder_ref: z.string(),\n expires_at: Timestamp.nullable(),\n last_injected_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type VaultCredential = z.infer<typeof VaultCredentialSchema>;\n\n/**\n * `vault.request_secret`'s arguments (§7.6, ADR-1623). The model names only which of ITS OWN declared\n * MCP servers needs a key: never a URL, a vault or a label, so it chooses no target. The card and the\n * control plane resolve the name against the session's agent version; an undeclared name is refused.\n * `mcp_server_url` and `credential` are written by the control plane from the person's confirmation,\n * over anything the model put there: the server's declared URL and the credential the card sealed.\n */\nexport const RequestSecretArgsSchema = z.object({\n mcp_server: z.string().min(1).max(64).describe(\"The name of one of your declared MCP servers that needs a key.\"),\n reason: z.string().max(300).optional().describe(\"One sentence on what the key unlocks.\"),\n mcp_server_url: z.url().optional().describe(\"Leave this out: set from your declared server.\"),\n credential: idOf(\"vcr\").optional().describe(\"Leave this out: set once the person seals the key.\"),\n});\n/**\n * Declared server names the secret card never seals for (ADR-1623): the platform's own tool server\n * (`vetta`) and the names the CEO's control-plane bindings use (`ceo_…`, `control_plane…`, ADR-1100).\n * A member can declare a server under any name; an admin's seal must not mint something that reads as\n * the CEO's binding.\n */\nexport const reservedServerName = (name: string): boolean => name === \"vetta\" || name.startsWith(\"ceo_\") || name.startsWith(\"control_plane\");\n/** The sealed key's name: the server's, and the card it was sealed on, so a key answers only its own card. */\nexport const sealedKeyName = (server: string, toolCallId: string, at: number): string => `${server}:${toolCallId}:${at}`;\n/** How long a sealed key may wait for its card's allow: past this it was sealed for some earlier card. */\nexport const SEAL_FRESH_MS = 15 * 60_000;\n/** The vault a sealed key lands in when the card makes one: the company's, bound per agent by `agent_id`. */\nexport const AGENT_KEYS_VAULT = \"Agent keys\";\n/**\n * The vault the CEO's binding lives in (ADR-1097): the one the dashboard reads the CEO from, and the\n * only one whose `ceo_<agent id>` binding records the CEO (ADR-1623).\n */\nexport const CONTROL_PLANE_VAULT = \"Orchestrator control plane\";\nexport type RequestSecretArgs = z.infer<typeof RequestSecretArgsSchema>;\n","/**\n * Social data — public social media reads through one priced catalogue (`canonical-spec §52`): the\n * data catalogue's `social` domain (§54) under its own names, so the wire stays what it shipped as.\n */\n\nimport { z } from \"zod\";\nimport {\n DATA_PRICE_BASES,\n DataPriceSchema,\n DataRunRequestSchema,\n DataRunSchema,\n DataToolInputSchema,\n DataToolQuerySchema,\n DataToolSchema,\n} from \"./data\";\n\nexport const SOCIAL_DATA_PRICE_BASES = DATA_PRICE_BASES;\n\nexport const SocialDataToolQuerySchema = DataToolQuerySchema.omit({ domain: true });\nexport type SocialDataToolQuery = z.infer<typeof SocialDataToolQuerySchema>;\n\nexport const SocialDataToolSchema = DataToolSchema.omit({ domains: true }).extend({\n object: z.literal(\"social_data_tool\"),\n price: DataPriceSchema,\n});\nexport type SocialDataTool = z.infer<typeof SocialDataToolSchema>;\n\nexport const SocialDataToolDetailSchema = SocialDataToolSchema.extend({ input: DataToolInputSchema, notes: z.array(z.string()) });\nexport type SocialDataToolDetail = z.infer<typeof SocialDataToolDetailSchema>;\n\nexport const SocialDataRunRequestSchema = DataRunRequestSchema;\nexport type SocialDataRunRequest = z.infer<typeof SocialDataRunRequestSchema>;\n\nexport const SocialDataRunSchema = DataRunSchema.extend({ object: z.literal(\"social_data_run\") });\nexport type SocialDataRun = z.infer<typeof SocialDataRunSchema>;\n","/**\n * Handoffs — `send_to_agent` with `wait: false` (canonical-spec §28.12, §28.15): an agent starts a\n * top-level session on another agent of its organization and carries on. Who it may reach is the\n * agent's `handoffs` field (`schema/agent.ts`), the same field that governs a `wait: true` thread.\n *\n * The body the door takes, the answer it returns and the mark the receiver's row carries are one\n * shape each, here, so the runtime, the API and a blueprint cannot drift apart on any of them.\n */\n\nimport { z } from \"zod\";\nimport { isId } from \"../id\";\nimport { idOf, type Metadata } from \"./common\";\n\n/** The most targets one human send may fan out to (§28.16): a room seats a coordinator and up to six. */\nexport const MAX_HANDOFF_TARGETS = 6;\n\n/** A sender at this depth is refused: a chain — or a cycle — ends in five sessions at most (§28.15). */\nexport const MAX_HANDOFF_DEPTH = 4;\nexport const MAX_HANDOFFS_PER_SESSION = 8;\n\n/**\n * The `agent` a hand-off names for a chat of the sender's own seat. Taken only with a `client`, from a\n * sender that works for no client (§66): a scheduled pass starts each client's work in a chat of its own.\n */\nexport const HANDOFF_SELF = \"self\";\n\nexport const HandoffRequestSchema = z.object({\n agent: z.string().min(1),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n /** Set by the session's own code, never the model: the sender has read people's data (§64). */\n read_people: z.literal(true).optional(),\n /**\n * The client the receiver's chat works for (§66). Only a sender that works for no client may name one,\n * and the API checks it is a contact on file; a client's own chat hands its client on by itself, and\n * naming another is refused. It is how a scheduled pass starts each client's work in a chat of its own.\n */\n client: idOf(\"ctc\").optional(),\n});\nexport type HandoffRequest = z.infer<typeof HandoffRequestSchema>;\n\nexport const HandoffSchema = z.object({\n object: z.literal(\"handoff\"),\n session_id: idOf(\"ses\"),\n status: z.enum([\"queued\", \"already_running\"]),\n handoff_key: z.string().nullable(),\n});\nexport type Handoff = z.infer<typeof HandoffSchema>;\n\n/**\n * `POST /v1/sessions/{id}/handoffs` (§28.16): a person hands `{id}`'s work to several agents in one\n * call. Each target is an `agt_` id or a name; the sender is the session in the path.\n */\nexport const SessionHandoffRequestSchema = z.object({\n agents: z.array(z.string().min(1)).min(1).max(MAX_HANDOFF_TARGETS),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n});\nexport type SessionHandoffRequest = z.infer<typeof SessionHandoffRequestSchema>;\n\n/** One target the door would not start: a row of the batch, never the whole answer (§28.16). */\nexport const HandoffRefusalSchema = z.object({\n object: z.literal(\"handoff_refusal\"),\n agent: z.string(),\n code: z.string(),\n message: z.string(),\n});\nexport type HandoffRefusal = z.infer<typeof HandoffRefusalSchema>;\n\n/** The human door's answer: §28.15's `Handoff` per admitted target, plus the seat it landed on. */\nexport const HandoffBatchSchema = z.object({\n object: z.literal(\"handoff_batch\"),\n handoffs: z.array(HandoffSchema.extend({ agent_id: idOf(\"agt\") })),\n refusals: z.array(HandoffRefusalSchema),\n});\nexport type HandoffBatch = z.infer<typeof HandoffBatchSchema>;\n\n/** `metadata.handoff` on the receiver's session row (§28.15). */\nexport const SessionHandoffSchema = z.object({\n from_session: idOf(\"ses\"),\n from_agent: idOf(\"agt\"),\n key: z.string().nullable(),\n depth: z.number().int().positive(),\n});\nexport type SessionHandoff = z.infer<typeof SessionHandoffSchema>;\n\n/** The mark a row carries, or `null` for a session nobody handed off. Lenient: metadata is the customer's. */\nexport function handoffOf(metadata: z.infer<typeof Metadata>): SessionHandoff | null {\n const parsed = SessionHandoffSchema.safeParse(metadata[\"handoff\"]);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * `metadata.role` of the one standing agent the dashboard calls the CEO. It is also the mark the\n * **company board** is found by (§28.18): the CEO owns that board and every live agent sits on it,\n * which is a fact the database reads (`@vetta/db` `seatFor`) and the runtime reads, so the string\n * lives here rather than once per reader.\n */\nexport const ORCHESTRATOR_ROLE = \"orchestrator\" as const;\n\n/** A room (§28.16) is a coordinator whose `metadata.role` is `\"group\"` or `\"orchestrator\"`; read off a pinned version. */\nexport const isRoom = (version: { metadata: z.infer<typeof Metadata> }): boolean =>\n version.metadata[\"role\"] === \"group\" || version.metadata[\"role\"] === ORCHESTRATOR_ROLE;\n\n/**\n * WHEN THE CHANNEL MARK BEGAN — the boundary one-time adoption may reach back over, and no further.\n *\n * From this instant a channel's session is MARKED at creation (`metadata.room`), so nothing created\n * from here on ever needs adopting. Adoption exists only for the channels that predate the mark, and\n * bounding it here is what keeps it from being a live rule: without the bound it considers every\n * unmarked top-level session of the coordinator forever, which includes the private 1:1 chat a\n * person starts from the agent page tomorrow — one dashboard read and the channel owns that chat's\n * transcript, permanently, with nothing in the product to undo it.\n *\n * It is NOT the cutoff that was tried and rejected on this branch. That one adopted only sessions\n * created AFTER a date, which strands exactly the legacy channels adoption is for. This is the\n * opposite bound: legacy sessions are eligible, new ones never are. It needs no migration and no\n * backfill, and it stops mattering once every channel that predates it has been read once.\n */\nexport const ROOM_ADOPTION_BEFORE = \"2026-09-19T00:00:00.000Z\";\n\n/** A room's `handoff_key` (§28.16), minted from the root session it names; `roomOfKey` reads it back. */\nexport const roomKey = (rootId: string): string => `room:${rootId}`;\n\n/** A room's `handoff_key` is `room:<root session id>` (§28.16); this reads the root off one, or `null` for any other key. */\nexport function roomOfKey(key: string | null | undefined): string | null {\n const root = key?.startsWith(\"room:\") ? key.slice(\"room:\".length) : \"\";\n return isId(\"ses\", root) ? root : null;\n}\n\n/**\n * A SEAT is a member's session in a room (§28.16): top-level and handed off under `room:<root>`.\n * It answers into the room, so it is the room's plumbing, never one of its agent's own chats; a\n * person reads it from the room and does not type into it. This reads the root it sits in, or `null`.\n */\nexport const seatOf = (session: { parent_session_id: string | null; metadata: z.infer<typeof Metadata> }): string | null =>\n session.parent_session_id === null ? roomOfKey(handoffOf(session.metadata)?.key) : null;\n\n/**\n * What a receiver handed off under a room's key is told about the room (§28.15 `channel`): the\n * root it may post into, the room agent's name, and the roster less itself. `null` outside a room.\n */\nexport const ChannelBriefSchema = z.object({\n root_session_id: idOf(\"ses\"),\n name: z.string().min(1),\n members: z.array(z.string().min(1)),\n /**\n * The receiver's own name, so it can tell the part of a post addressed to it from a teammate's\n * (ADR-1099). Optional: a brief pinned before it existed still parses.\n */\n you: z.string().min(1).optional(),\n});\nexport type ChannelBrief = z.infer<typeof ChannelBriefSchema>;\n\n/** `POST /v1/sandbox/channel/messages` (§28.16): a member's words for its room, and the door's answer. */\nexport const ChannelPostRequestSchema = z.object({\n message: z.string().min(1).max(20_000),\n /** Set by the session's own code, never the model: the sender has read people's data (§64). */\n read_people: z.literal(true).optional(),\n});\nexport type ChannelPostRequest = z.infer<typeof ChannelPostRequestSchema>;\n\nexport const ChannelPostSchema = z.object({\n object: z.literal(\"channel_post\"),\n root_session_id: idOf(\"ses\"),\n queued: z.boolean(),\n});\nexport type ChannelPost = z.infer<typeof ChannelPostSchema>;\n\n/** How many voices a live call can speak a channel in (`canonical-spec §35.5`, ADR-1166). */\nexport const VOICE_SLOTS = 9;\n\n/**\n * THE VOICE A CHANNEL MEMBER SPEAKS IN ON A CALL (`canonical-spec §35.5`, ADR-1166): a stable\n * FNV-1a hash of its agent id onto 1..`VOICE_SLOTS`, so the bridge that speaks and the dashboard\n * that captions agree with no shared state. Two members may share a slot; nine voices is the cap.\n */\nexport function voiceSlotFor(agentId: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < agentId.length; i++) hash = Math.imul(hash ^ agentId.charCodeAt(i), 0x01000193);\n return ((hash >>> 0) % VOICE_SLOTS) + 1;\n}\n","/**\n * `compose` — a card the model lays out and code fills (canonical-spec §49, ADR-0955–0957). The\n * model writes a json-render spec: a flat map of elements under one `root`. It chooses the\n * components, their order and their words. It never writes a number: every value, series or\n * percentage on the card is a BINDING, `{ \"$source\": \"views_total\", \"days\": 7 }`, that code resolves\n * from Postgres when the tool runs. The tool's result is the same spec with each binding filled in.\n *\n * One catalog, written once (`catalog`), is built twice: with bindings for the model's argument\n * (`ComposeSpecSchema`), and with resolved values for the frozen result the chat draws\n * (`ComposedSpecSchema`). The two cannot drift apart, because they are the same components.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { Bound, catalog, Resolved, spec, unknownComponent } from \"./catalog\";\n\nexport const COMPOSE_COMPONENTS = [\"Card\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\"] as const;\nexport const MAX_COMPOSE_ELEMENTS = 24;\n\n/** The model's spec: bindings where the numbers go. */\nconst BoundComponents = catalog(Bound);\n/*\n * The union is spelled out for each side. A helper generic over the catalog loses every slot's type\n * to `unknown`, as `catalog`'s own parameters did before they were split.\n */\nexport const ComposeSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n BoundComponents.Card, BoundComponents.Stack, BoundComponents.Grid, BoundComponents.Metric, BoundComponents.LineChart, BoundComponents.BarList,\n BoundComponents.Progress, BoundComponents.Roadmap, BoundComponents.Schedule, BoundComponents.Media, BoundComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport type ComposeSpec = z.infer<typeof ComposeSpecSchema>;\nexport type ComposeElement = ComposeSpec[\"elements\"][string];\n\n/** FLAT, like `show`'s (ADR-0945): the spec sits inside one property of a plain object. */\nexport const ComposeArgsSchema = z.object({\n spec: ComposeSpecSchema.describe(\n 'A json-render spec: { \"root\": key, \"elements\": { key: { \"type\", \"props\", \"children\"? } } }.',\n ),\n});\n\n/** Each component with its values resolved: the props the chat's renderer is typed by. */\nexport const ComposedComponents = catalog(Resolved);\n\n/** The frozen result: the spec with every binding resolved, as read at `as_of` on the company's clock. */\nexport const ComposedSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n ComposedComponents.Card, ComposedComponents.Stack, ComposedComponents.Grid, ComposedComponents.Metric, ComposedComponents.LineChart,\n ComposedComponents.BarList, ComposedComponents.Progress, ComposedComponents.Roadmap, ComposedComponents.Schedule, ComposedComponents.Media,\n ComposedComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport const ComposedSchema = z.object({ as_of: Timestamp, timezone: z.string().min(1), spec: ComposedSpecSchema });\nexport type Composed = z.infer<typeof ComposedSchema>;\nexport type ComposedElement = Composed[\"spec\"][\"elements\"][string];\n/** One component's resolved props: what a block in the studio is typed by. */\nexport type ComposedProps<T extends ComposedElement[\"type\"]> = Extract<ComposedElement, { type: T }>[\"props\"];\n","/**\n * core-gaps: contracts — media as REST (`canonical-spec §33–§35`): the `med_` job that every\n * async kind shares (D5), and the request/result shapes of images, videos, clips and audio.\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { CreatorTemplateRoundSchema, SavedSkillSchema, StudioStateSchema } from \"./creator\";\nimport { FileSchema } from \"./resource\";\nimport { lookOf, unknownLookMessage } from \"./looks\";\nimport { MediaSkillReviewSchema } from \"./media-judge\";\n\n/**\n * The catalogue's `kind` (`§33.3`, `§35.1`): what `GET /v1/media/models?kind=` and the CLI's\n * `--kind` select. Distinct from the job kinds below — a catalogue row is a capability, a job is\n * work in flight.\n */\nexport const MEDIA_MODEL_KINDS = [\"image\", \"video\", \"mesh\", \"stt\", \"tts\", \"s2s\"] as const;\nexport type MediaModelKind = (typeof MEDIA_MODEL_KINDS)[number];\nexport const isMediaModelKind = (value: string): value is MediaModelKind =>\n MEDIA_MODEL_KINDS.some((kind) => kind === value);\n\n/** `image` is synchronous (a `fil_` straight back), so it is not a job kind. */\nexport const MEDIA_JOB_KINDS = [\"video\", \"clip\", \"transcription\", \"mesh\"] as const;\nexport const MediaJobKindSchema = z.enum(MEDIA_JOB_KINDS);\nexport const MediaJobStatusSchema = z.enum([\"queued\", \"processing\", \"completed\", \"failed\"]);\n\nconst PublicUrl = z.string().url().startsWith(\"http\");\nconst Score = z.number().int().min(0).max(100);\nconst Seconds = z.number().nonnegative();\n\nexport const VideoResultSchema = z.object({\n files: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n content_type: z.string(),\n width: z.number().int().positive().nullable(),\n height: z.number().int().positive().nullable(),\n duration_seconds: Seconds.nullable(),\n }),\n ),\n});\n\nexport const ViralityScoreSchema = z.object({\n total: Score,\n shareability: Score,\n hook_strength: Score,\n story_quality: Score,\n emotional_impact: Score,\n});\n\nexport const ClipResultSchema = z.object({\n clips: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n title: z.string(),\n start_seconds: Seconds,\n end_seconds: Seconds,\n duration_seconds: Seconds,\n virality: ViralityScoreSchema,\n }),\n ),\n});\n\nexport const TranscriptSchema = z.object({\n text: z.string(),\n language: z.string().nullable(),\n duration_seconds: Seconds.nullable(),\n segments: z.array(z.object({ start_seconds: Seconds, end_seconds: Seconds, text: z.string() })),\n});\n\n/** A finished mesh job (§59): the generated GLB, one file. */\nexport const MeshResultSchema = z.object({\n files: z.array(\n z.object({ file_id: idOf(\"fil\"), content_type: z.string(), bytes: z.number().int().nonnegative() }),\n ),\n});\n\nexport const MediaJobResultSchema = z.union([\n VideoResultSchema,\n ClipResultSchema,\n TranscriptSchema,\n MeshResultSchema,\n]);\n\nexport const MediaJobSchema = z.object({\n id: idOf(\"med\"),\n object: z.literal(\"media_job\"),\n kind: MediaJobKindSchema,\n status: MediaJobStatusSchema,\n model: z.string().nullable(),\n input: z.record(z.string(), z.unknown()),\n result: MediaJobResultSchema.nullable(),\n error: z.object({ code: z.string(), message: z.string() }).nullable(),\n cost_micro_usd: MicroUsdField.nullable(),\n session_id: idOf(\"ses\").nullable(),\n created_at: Timestamp,\n completed_at: Timestamp.nullable(),\n});\nexport type MediaJob = z.infer<typeof MediaJobSchema>;\n\n/** The least `character_strength` a render takes: below it the provider drops the face (`§33.6`). */\nexport const CHARACTER_STRENGTH_MIN = 0.5;\n\n/**\n * A frame shape `W:H` (`§33.2`, ADR-1874): positive integers whose long side is at most 8× the short\n * side — the widest any catalogued model takes (1:8, 8:1). Anything else used to be clamped to the\n * nearest shape the model takes, then billed; it is refused before any provider or ledger is reached.\n */\nconst MAX_ASPECT = 8;\nexport const AspectRatioSchema = z.string().refine((value) => {\n const match = /^([1-9]\\d{0,3}):([1-9]\\d{0,3})$/.exec(value);\n if (!match) return false;\n const [w, h] = [Number(match[1]), Number(match[2])];\n return Math.max(w, h) <= MAX_ASPECT * Math.min(w, h);\n}, `a W:H frame shape such as 16:9, no wider than 1:${MAX_ASPECT} or ${MAX_ASPECT}:1`);\n\nexport const ImageRequestSchema = z.object({\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n /** Each a public URL or a stored file's `fil_` id, the API signing the read the provider fetches. */\n image_urls: z.array(z.union([PublicUrl, idOf(\"fil\")])).max(4).optional(),\n aspect_ratio: AspectRatioSchema.optional(),\n seed: z.number().int().optional(),\n n: z.number().int().min(1).max(4).default(1),\n /** Render as a trained character, by `chr_` id or name (`§33.6`); with `image_urls` (stills of it) a set edit of them. */\n character: z.string().min(1).optional(),\n /** A look from the fixed catalogue, by name or slug (`§33.6.1`). */\n style: z.string().min(1).max(60).optional(),\n /** 0.5..1: how strictly the character's face is held; only with `character`. Below 0.5 the face is lost. */\n character_strength: z.number().min(CHARACTER_STRENGTH_MIN).max(1).optional(),\n}).superRefine((request, ctx) => {\n if (request.style !== undefined && lookOf(request.style) === undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"style\"], message: unknownLookMessage(request.style) });\n }\n if (request.character_strength !== undefined && request.character === undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"character_strength\"], message: \"character_strength needs a character\" });\n }\n});\n\n/** Why a character video must start from a still of that character (`§33.6`). */\nexport const CHARACTER_VIDEO_FRAME =\n \"a character video starts from a still of that character: render one with generate_image{character} and pass its file as image_urls\";\n\nexport const VideoRequestSchema = z.object({\n /** Omitted: the platform's video default while the catalogue publishes it (`resolveModel`, §33.2). */\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n /** The first frame: a public URL or a stored still's `fil_` id, the API signing the read. */\n image_urls: z.array(z.union([PublicUrl, idOf(\"fil\")])).max(1).optional(),\n /** The source clip of a video-to-video edit (ADR-0814). */\n video_url: PublicUrl.optional(),\n aspect_ratio: AspectRatioSchema.optional(),\n seed: z.number().int().optional(),\n seconds: z.number().int().min(1).max(60).optional(),\n /** The character on screen (`§33.6`): `image_urls[0]` must be a still rendered as them. */\n character: z.string().min(1).optional(),\n}).superRefine((request, ctx) => {\n if (request.character !== undefined && (request.image_urls ?? []).length === 0) {\n ctx.addIssue({ code: \"custom\", path: [\"image_urls\"], message: CHARACTER_VIDEO_FRAME });\n }\n});\n\n/**\n * `POST /v1/media/meshes` (§59): exactly one of a prompt (text-to-3D) or 1–4 photos (image-to-3D;\n * 2–4 ordered views select a multi-view model). `rig` is honoured only by a model that rigs, and\n * requires `texture` (a rigged model is always textured).\n */\nexport const MeshRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n prompt: z.string().min(1).max(2_000).optional(),\n image_urls: z.array(z.union([PublicUrl, idOf(\"fil\")])).min(1).max(4).optional(),\n texture: z.boolean().default(true),\n rig: z.boolean().default(false),\n seed: z.number().int().optional(),\n })\n .refine((request) => (request.prompt === undefined) !== (request.image_urls === undefined), {\n error: \"exactly one of prompt or image_urls\",\n path: [\"prompt\"],\n })\n .refine((request) => request.prompt === undefined || request.prompt.trim() !== \"\", {\n error: \"prompt is empty\",\n path: [\"prompt\"],\n })\n .refine((request) => !(request.rig && request.texture === false), {\n error: \"rig requires texture: a rigged model is always textured\",\n path: [\"rig\"],\n });\nexport type MeshRequest = z.infer<typeof MeshRequestSchema>;\n\nexport const ImageGenerationSchema = z.object({\n object: z.literal(\"image_generation\"),\n model: z.string(),\n files: z.array(FileSchema),\n cost_micro_usd: MicroUsdField,\n});\n\nconst ClipLength = z.number().int().min(5).max(180);\nexport const ClipRequestSchema = z.object({\n video_url: PublicUrl,\n aspect_ratio: z.enum([\"9:16\", \"16:9\"]).default(\"9:16\"),\n remove_silence: z.boolean().default(false),\n caption_preset: z.enum([\"none\", \"clean\", \"bold\", \"karaoke\"]).default(\"none\"),\n language: z.string().min(2).optional(),\n min_seconds: ClipLength.default(15),\n max_seconds: ClipLength.default(60),\n title: z.string().min(1).optional(),\n});\nexport type ClipRequest = z.infer<typeof ClipRequestSchema>;\n\nexport const AudioFormatSchema = z.enum([\"mp3\", \"wav\", \"ogg\"]);\n\n/** Exactly one source — a library file or a public URL. */\nexport const TranscriptionRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\").optional(),\n url: PublicUrl.optional(),\n language: z.string().min(2).optional(),\n timestamps: z.boolean().default(true),\n })\n .refine((request) => (request.file_id === undefined) !== (request.url === undefined), {\n error: \"exactly one of file_id or url\",\n path: [\"file_id\"],\n });\n\nexport const SpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n text: z.string().min(1).max(4_096),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n speed: z.number().min(0.5).max(2).optional(),\n});\n\nexport const SpeechToSpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\"),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n});\n\nexport const SpeechGenerationSchema = z.object({\n object: z.literal(\"speech_generation\"),\n model: z.string(),\n file: FileSchema,\n duration_seconds: Seconds.nullable(),\n cost_micro_usd: MicroUsdField,\n});\n\n/** The studio states a media build can be in: it never reaches review (§57.2's `?state=`). */\nexport const MediaSkillBuildStateSchema = StudioStateSchema.extract([\"setup\", \"building\", \"ready\"]);\n\n/**\n * A build's round with its judge's review (§57.6): always null outside the internal org. Absent\n * reads as null, so a client on this schema still parses an API from before the judge.\n */\nexport const MediaSkillRoundSchema = CreatorTemplateRoundSchema.extend({ review: MediaSkillReviewSchema.nullable().default(null) });\nexport type MediaSkillRound = z.infer<typeof MediaSkillRoundSchema>;\n\n/** `canonical-spec §57`: an org skill built from 1–3 public reel links; rounds carry signed reads. */\nexport const MediaSkillBuildSchema = z.object({\n id: idOf(\"ctp\"),\n object: z.literal(\"media_skill_build\"),\n name: z.string(),\n state: StudioStateSchema,\n urls: z.array(z.string()),\n rounds: z.array(MediaSkillRoundSchema),\n skill: SavedSkillSchema.nullable(),\n spend_micro_usd: MicroUsdField.nonnegative(),\n created_at: Timestamp,\n});\nexport type MediaSkillBuild = z.infer<typeof MediaSkillBuildSchema>;\n\n/** Strict, so a body carrying both shapes is refused rather than read as one (§57.2). */\nexport const MediaSkillBuildCreateSchema = z\n .object({\n urls: z.array(z.string().min(1)).min(1).max(3),\n name: z.string().trim().min(1).max(80).optional(),\n description: z.string().trim().min(1).max(2000).optional(),\n /** The sample's length in seconds (ADR-1762); absent is the studio's ~15 s piece. */\n seconds: z.number().int().min(10).max(60).optional(),\n })\n .strict();\n\nexport const MediaSkillBuildReviseSchema = z.object({ build_id: idOf(\"ctp\"), feedback: z.string().min(1).max(4000) }).strict();\n\n/** `POST /v1/media/skills`: start a build, or revise one by `build_id`. */\nexport const MediaSkillBuildRequestSchema = z.union([MediaSkillBuildCreateSchema, MediaSkillBuildReviseSchema]);\n/**\n * core-gaps: U11-sound-effects — a text prompt to a short generated audio clip (`§35.4`). Synchronous\n * like speech: the clip (at most 30 s) lands in Files as a `fil_` and the one call settles its cost.\n */\nexport const SoundEffectRequestSchema = z.object({\n prompt: z.string().min(1).max(500),\n /** 0.5–30 s; omitted, the generator picks a length from the prompt. */\n duration_seconds: z.number().min(0.5).max(30).optional(),\n /** Make the clip loop seamlessly — for ambience and backgrounds. */\n loop: z.boolean().default(false),\n});\n\nexport const SoundGenerationSchema = z.object({\n object: z.literal(\"sound_generation\"),\n file: FileSchema,\n duration_seconds: Seconds.nullable(),\n cost_micro_usd: MicroUsdField,\n});\n\n/**\n * core-gaps: U12-music — a text prompt to an original song (`§35.6`). Synchronous like sound effects:\n * the song (up to 5 min) lands in Files as a `fil_` and the one call settles its cost.\n */\nexport const MusicRequestSchema = z.object({\n prompt: z.string().min(1).max(2000),\n /** 3–300 s; omitted, 30 s. */\n length_seconds: z.number().min(3).max(300).optional(),\n /** Force an instrumental track with no vocals. */\n instrumental: z.boolean().default(false),\n});\n\nexport const MusicGenerationSchema = z.object({\n object: z.literal(\"music_generation\"),\n file: FileSchema,\n duration_seconds: Seconds.nullable(),\n cost_micro_usd: MicroUsdField,\n});\n\n/** A Mira edit submitted without a session (`canonical-spec §55`). The tool's arguments, on the wire. */\nexport const EditRequestSchema = z.object({\n video: z.string().min(1),\n prompt: z.string().min(1).max(1_000),\n references: z.array(z.string().min(1)).max(4).optional(),\n mode: z.enum([\"scene\", \"outfit_or_object\", \"person_swap\"]).optional(),\n});\n\nconst EditFailureCodeSchema = z.enum([\"bad_source\", \"refused\", \"timed_out\", \"provider_error\", \"cancelled\"]);\n\n/** What `POST /v1/media/edits` and `GET /v1/media/edits/:id` answer. No checkpoint, route or vendor. */\nexport const EditJobSchema = z.object({\n id: idOf(\"med\"),\n object: z.literal(\"edit_job\"),\n status: MediaJobStatusSchema,\n video: z.string(),\n prompt: z.string(),\n references: z.array(z.string()),\n mode: z.enum([\"scene\", \"outfit_or_object\", \"person_swap\"]).nullable(),\n result: z.object({ file_id: z.string().startsWith(\"fil_\") }).nullable(),\n error: z.object({ code: EditFailureCodeSchema, message: z.string() }).nullable(),\n cost_micro_usd: MicroUsdField.nullable(),\n created_at: Timestamp,\n completed_at: Timestamp.nullable(),\n});\nexport type EditJob = z.infer<typeof EditJobSchema>;\nexport type EditRequest = z.input<typeof EditRequestSchema>;\n","/**\n * Looks — the fixed catalogue of named visual styles a `generate_image` render can be drawn in\n * (`canonical-spec §33.6.1`, ADR-1360).\n *\n * A look is **ours**: our name, our slug, our description. Every model gets the look's `prompt` appended\n * to the request's, so `style` works on every image model. Each prompt says what it is NOT, because on\n * staging (round 2) a look that only described itself lost to the shot's own wording and came out as a\n * clean studio portrait. Round 3: naming the phone (\"vertical phone photo, handheld and slightly tilted\")\n * drew the frame sideways, twice over or inside phone-app chrome, so Phone snap never says phone. Round 4\n * (18 Oct, 59 probes): \"single upright frame … exactly one person\" still drew phone chrome or a\n * sideways frame on 3 of 12; \"alone … one full-bleed photograph\" on 1 of 12, and every character still\n * now gets a frame check that renders a bad one again (`@vetta/media` `withFrameCheck`).\n * Digital cam (a flash snapshot) is retired (18 Oct): no prompt moved every face into flash light (Hank\n * stayed in soft studio light on every probe), so a look that renders for some faces and not others is\n * not offered at all. Hank's pack has Foggy morning instead (infra/seed-platform-characters.ts).\n * Candid selfie (1 Nov, ADR-1812) is the owner's bar for every creator: real skin up close, in low light, never\n * retouched. It never names a phone or a flash, for the reasons above.\n */\n\nexport interface Look {\n /** The stable key: what a request's `style` resolves to and what provenance records. */\n readonly slug: string;\n /** The customer-facing name: what setup shows and what a character's `style_pack` lists. */\n readonly name: string;\n /** One line on the look, as setup and the Characters tab show it. */\n readonly description: string;\n /**\n * What a render is told (`LOOK_LEAD` + prompt, packages/media): concrete camera, light and setting, because the one-line\n * description alone left looks like Realistic and Digital cam near-identical on staging (ADR-1360).\n */\n readonly prompt: string;\n}\n\nexport const LOOKS: readonly Look[] = [\n { slug: \"candid-selfie\", name: \"Candid selfie\", description: \"Close-up at arm's length in low light; real skin, loose hair, unretouched.\", prompt: \"Close-up selfie held at arm's length in soft low indoor light, cropped a little off-centre with shallow focus: real unretouched skin with visible pores, freckles and beauty spots left as they are, faint shine, loose strands of hair, a relaxed unposed expression, the slight grain and softness of a small camera in low light. Not a studio portrait, not airbrushed, no beauty filter. Alone, one full-bleed photograph.\" },\n { slug: \"phone-snap\", name: \"Phone snap\", description: \"Natural light, casual phone framing, soft HDR glow; looks real.\", prompt: \"An unposed snapshot a friend took from a few feet away: natural mixed daylight, an ordinary lived-in place (kitchen, café, street, car) behind, off-centre composition, everything sharp with no background blur, slight HDR and a little sensor noise; the person is alone and fills one full-bleed photograph; not a studio portrait, no studio backdrop or studio lighting.\" },\n { slug: \"realistic\", name: \"Realistic\", description: \"No filter, crisp true-to-life detail in skin, light and fabric.\", prompt: \"Unretouched documentary photograph: true-to-life skin texture with visible pores, neutral daylight, natural colour, no filter, no beauty retouching.\" },\n { slug: \"everyday\", name: \"Everyday\", description: \"Clean, balanced, natural colour; the all-purpose look.\", prompt: \"Everyday moment in a lived-in place, mid-activity rather than posing, clean balanced daylight, natural colour, medium shot.\" },\n { slug: \"library\", name: \"Library\", description: \"Soft indoor light, cozy academia, books and warm wood.\", prompt: \"In a library or book-lined study: soft warm indoor lamplight, wooden shelves of books behind, cozy academia mood.\" },\n { slug: \"quiet-luxury\", name: \"Quiet luxury\", description: \"Understated expensive: neutral tones, fine fabrics, calm interiors.\", prompt: \"Quiet luxury editorial: neutral beige, cream and camel tones, fine tailored fabrics, a calm high-end interior, soft even light.\" },\n { slug: \"through-the-glass\", name: \"Through the glass\", description: \"Seen through a window or café pane; a quiet observed moment.\", prompt: \"Photographed from the street through a clear café or shop window: faint street reflections and a little glare layered over the glass, part of the window frame at the edge, the person sharp behind it in a quiet moment; the glass is clear, no fog, mist, condensation or haze anywhere.\" },\n { slug: \"flight-mode\", name: \"Flight mode\", description: \"Airports and terminals, the feeling of being in transit.\", prompt: \"In an airport terminal or by a departure-board window: travel bag, boarding-gate light, the feeling of being in transit.\" },\n { slug: \"selfcare\", name: \"Selfcare\", description: \"Candles, skincare and robes; glowing calm in muted tones.\", prompt: \"Selfcare at home: robe, candles and skincare, glowing soft light, muted calm tones.\" },\n { slug: \"japandi\", name: \"Japandi\", description: \"Warm minimalism: clean lines, natural light, pale wood.\", prompt: \"Japandi interior: warm minimalism, pale wood, clean lines, linen, soft natural window light.\" },\n { slug: \"foggy-morning\", name: \"Foggy morning\", description: \"Muted colour, soft horizon, dreamlike morning stillness.\", prompt: \"Outdoors on a foggy morning: muted colour, soft hazy horizon, dreamlike stillness.\" },\n { slug: \"rainy-day\", name: \"Rainy day\", description: \"Moody sky, wet-pavement reflections, soft sweaters, slow and cinematic.\", prompt: \"Outdoors in the rain: visible falling raindrops and rain streaks in the air, damp hair, an umbrella or a hood, a soft sweater or raincoat, glossy wet street with reflections, overcast grey sky, slow cinematic mood; a real street, not a studio backdrop.\" },\n { slug: \"90s-editorial\", name: \"90s editorial\", description: \"Retro fashion-magazine image: film grain, soft blur, moody colour.\", prompt: \"1990s fashion-magazine editorial shot on 35mm film: heavy visible film grain, slightly soft focus, faded warm colour with crushed blacks, on location (city street, hotel room or rooftop), a styled fashion pose and a 90s outfit; not a plain studio backdrop, not a clean digital portrait.\" },\n { slug: \"wide-angle-outfit\", name: \"Wide-angle outfit\", description: \"Waist-down wide-angle outfit shot, candid and playful.\", prompt: \"Full-body wide-angle outfit shot from a low angle, the whole outfit and shoes in frame, candid and playful.\" },\n { slug: \"elevator-mirror\", name: \"Elevator mirror\", description: \"Full-length mirror selfie in an elevator.\", prompt: \"Full-length mirror selfie in an elevator: phone in hand, the whole outfit reflected, metal walls.\" },\n { slug: \"escalator\", name: \"Escalator\", description: \"Mid-motion on an escalator, effortless mall-street style.\", prompt: \"Mid-motion on a mall escalator, full outfit in frame, effortless street style.\" },\n { slug: \"tokyo-street-style\", name: \"Tokyo street style\", description: \"Layered looks, sharp silhouettes and bold colour, street-snap energy.\", prompt: \"Tokyo street-style snap on a city street: layered outfit, sharp silhouette, bold colour, signage behind.\" },\n];\n\nexport const LOOK_NAMES: readonly string[] = LOOKS.map((look) => look.name);\n\n/**\n * The looks a trained character gets when its create names none (ADR-1360): the same three the AI\n * Influencer template gives a face trained from only \"Their usual looks\" (media-blueprint\n * `DEFAULT_TRAINED_LOOKS`), so a face trained from the Characters tab has looks too.\n */\nexport const DEFAULT_TRAINED_LOOKS: readonly string[] = [\"Candid selfie\", \"Phone snap\", \"Realistic\"];\n\nconst BY_KEY = new Map<string, Look>(\n LOOKS.flatMap((look) => [\n [look.slug, look],\n [look.name.toLowerCase(), look],\n ]),\n);\n\n/** The look a name or slug names, case-insensitive; `undefined` for anything else. */\nexport function lookOf(nameOrSlug: string): Look | undefined {\n return BY_KEY.get(nameOrSlug.trim().toLowerCase());\n}\n\n/** The refusal sentence for a value that names no look. */\nexport const unknownLookMessage = (value: string): string =>\n `${value} is not a look; use one of: ${LOOK_NAMES.join(\", \")}`;\n","/**\n * The media skill judge (`canonical-spec §57.6`, ADR-1754): an agent that watches a ready round's\n * sample beside the build's reference reels and answers `JudgeOutputSchema`; `decideReview` turns\n * that answer into accepted / rejected / needs_you in code. A rejected round revises itself with the\n * stored `feedback` up to `max_auto_rounds` (owner decision 2026-10-28); the user may still revise at\n * any time with their own feedback or the stored one.\n * Only the internal org's link builds are judged; everything else keeps human review.\n */\nimport { z } from \"zod\";\n\n/** Every new studio draft's sections (ADR-1344); a links build also needs `## Source links`. */\nexport const STUDIO_SKILL_HEADINGS = [\n \"## When to load it\",\n \"## Character bible\",\n \"## World and themes\",\n \"## Story patterns\",\n \"## Dialogue and voice\",\n \"## Scene grammar\",\n \"## Look\",\n \"## Captions and music\",\n \"## Must not change\",\n \"## Allowed variation\",\n \"## What to file\",\n \"## What not to do\",\n] as const;\n\n/** The judge's numbers in one place so they can be tuned without touching the code that reads them. */\nexport const MEDIA_JUDGE = {\n model: \"anthropic/claude-opus-5.5\",\n weights: { fidelity: 0.3, visual: 0.2, story: 0.2, character: 0.15, audio: 0.1, appeal: 0.05 },\n accept_score: 4.0,\n min_score: 3,\n max_fixes: 3,\n /** A rejected round below this one starts the next with the judge's fixes: 3 ⇒ up to 2 automatic revisions. */\n max_auto_rounds: 3,\n /** A review still judging this long after it was queued is decided `needs_you`. */\n stuck_after_ms: 30 * 60_000,\n sweep_per_tick: 20,\n /** The catalog page a published listing lives on (the same one the admin links). */\n live_url_base: \"https://usenaive.ai/businesses/\",\n /** White-label (CLAUDE.md §2): a listing's name or tagline naming a vendor is not publishable. */\n vendor_words:\n /\\b(openai|anthropic|claude|gpt|gemini|openrouter|cloudflare|tenki|browserbase|stripe|vercel|supabase|neon|resend|twilio|composio|nango|minimax|hailuo|seedance|bytedance|elevenlabs|kling|runway|veo|sora|higgsfield|flux)\\b/i,\n} as const;\n\nconst text = (max: number) => z.string().max(max);\nconst Score = z.object({ score: z.number().int().min(1).max(5), why: text(300) });\n/**\n * The judge's gates. G3 (no real people or brand IP) was removed by the owner on 2026-10-30: a format\n * should match its references as closely as it can, characters, style and music included. The other\n * ids keep their numbers so stored reviews read the same; a review stored with G3 still parses.\n */\nconst JUDGE_GATES = [\"G1\", \"G2\", \"G4\", \"G5\"] as const;\n\n/** What the judge submits: a probe of the sample, gates G1, G2, G4 and G5, six scores, issues and a recommendation. */\nexport const JudgeOutputSchema = z.object({\n probe: z.object({ aspect: z.string().max(20), seconds: z.number().nonnegative(), has_audio: z.boolean(), scenes: z.number().int().nonnegative() }),\n gates: z\n .array(z.object({ id: z.enum(JUDGE_GATES), pass: z.boolean(), evidence: text(400) }))\n .length(JUDGE_GATES.length)\n .refine((gates) => new Set(gates.map((gate) => gate.id)).size === JUDGE_GATES.length, \"each of G1, G2, G4 and G5 once\"),\n scores: z.object({ fidelity: Score, visual: Score, story: Score, character: Score, audio: Score, appeal: Score }),\n issues: z\n .array(\n z.object({\n severity: z.enum([\"blocker\", \"major\", \"minor\"]),\n cause: z.enum([\"skill\", \"render\", \"source\"]),\n section: z.enum(STUDIO_SKILL_HEADINGS).nullable(),\n problem: text(400),\n fix: text(400),\n }),\n )\n .max(8),\n recommendation: z.enum([\"accept\", \"reject\", \"needs_you\"]),\n confidence: z.enum([\"high\", \"medium\", \"low\"]),\n summary: text(280),\n listing: z.object({ tagline: z.string().min(1).max(140), hero_sample_index: z.number().int().nonnegative() }),\n});\nexport type JudgeOutput = z.infer<typeof JudgeOutputSchema>;\n\nexport const MediaSkillReviewStateSchema = z.enum([\"queued\", \"judging\", \"decided\", \"failed\"]);\nexport type MediaSkillReviewState = z.infer<typeof MediaSkillReviewStateSchema>;\nexport const MediaSkillReviewDecisionSchema = z.enum([\"accepted\", \"rejected\", \"needs_you\"]);\nexport type MediaSkillReviewDecision = z.infer<typeof MediaSkillReviewDecisionSchema>;\n/** G1, G2, G4 and G5 are the judge's; G6 (publishable) is computed in code; G3 only in reviews stored before 2026-10-30. */\nexport const ReviewGateSchema = z.object({ id: z.enum([\"G1\", \"G2\", \"G3\", \"G4\", \"G5\", \"G6\"]), pass: z.boolean(), evidence: z.string() });\nexport type ReviewGate = z.infer<typeof ReviewGateSchema>;\n\n/**\n * What a rejected round did next (§57.6): `revising` started `next_round` with the judge's fixes;\n * `stopped` started nothing, and says why — except `round_failed`, which keeps `next_round`: the round\n * it started failed. Null unless the decision is `rejected`.\n */\nexport const MediaSkillReviewAutoSchema = z.object({\n state: z.enum([\"revising\", \"stopped\"]),\n next_round: z.number().int().positive().nullable(),\n stopped_because: z.enum([\"round_limit\", \"no_budget\", \"no_credit\", \"could_not_start\", \"round_failed\"]).nullable(),\n});\nexport type MediaSkillReviewAuto = z.infer<typeof MediaSkillReviewAutoSchema>;\n\n/** The wire `review` on each round of a `media_skill_build` (§57.6); null outside the internal org. */\nexport const MediaSkillReviewSchema = z.object({\n state: MediaSkillReviewStateSchema,\n /** Null while queued or judging, and when a revise superseded it. */\n decision: MediaSkillReviewDecisionSchema.nullable(),\n /** Weighted 1–5, rounded to 2 dp; null until decided from a verdict. */\n score: z.number().nullable(),\n /** G1–G6 once judged, `[]` otherwise. */\n gates: z.array(ReviewGateSchema),\n scores: JudgeOutputSchema.shape.scores.nullable(),\n issues: JudgeOutputSchema.shape.issues,\n summary: z.string().nullable(),\n /** Only on rejected: send as-is as a revise's `feedback`. */\n feedback: z.string().nullable(),\n /** Why it needs a person, \"superseded\", or why an accepted round's publish failed. */\n reason: z.string().nullable(),\n /** Only once accepted and published. */\n listing: z.object({ template: z.string(), url: z.string() }).nullable(),\n /** Only on rejected: the automatic revision it started, or why it stopped. Absent (an API before it) ⇒ null. */\n auto: MediaSkillReviewAutoSchema.nullable().default(null),\n});\nexport type MediaSkillReview = z.infer<typeof MediaSkillReviewSchema>;\n\ntype Verdict = \"accept\" | \"reject\" | \"needs_you\";\nconst SEVERITY = { blocker: 0, major: 1, minor: 2 } as const;\n\n/**\n * The decision, in code, from the judge's answer and the publishability gate G6 (§57.6):\n * - low confidence → needs_you;\n * - every gate passes, weighted ≥ `accept_score`, no score under `min_score`, and the judge\n * recommends accept → accepted;\n * - a gate fails or weighted < `accept_score`, at least one issue is the skill's, and the judge\n * does not recommend accept → rejected, with the top `max_fixes` skill issues as feedback;\n * - anything else → needs_you, with a fixed reason.\n */\nexport function decideReview(input: { round: number; output: JudgeOutput; g6: { pass: boolean; evidence: string } }): {\n decision: MediaSkillReviewDecision;\n score: number;\n gates: ReviewGate[];\n feedback: string | null;\n reason: string | null;\n} {\n const { output } = input;\n const keys = Object.keys(MEDIA_JUDGE.weights) as (keyof typeof MEDIA_JUDGE.weights)[];\n const weighted = keys.reduce((sum, key) => sum + MEDIA_JUDGE.weights[key] * output.scores[key].score, 0);\n // Every weighted sum is a whole number of hundredths; the float sum is not (4,4,4,5,3,3 sums to\n // 3.9999999999999996), so the threshold reads the rounded score.\n const score = Math.round(weighted * 100) / 100;\n const gates: ReviewGate[] = [...output.gates, { id: \"G6\", ...input.g6 }];\n const base = { score, gates, feedback: null, reason: null };\n if (output.confidence === \"low\") return { ...base, decision: \"needs_you\", reason: \"the judge's confidence is low\" };\n\n const failing = gates.some((gate) => !gate.pass) || score < MEDIA_JUDGE.accept_score;\n const skill = output.issues.filter((issue) => issue.cause === \"skill\");\n const computed: Verdict = !failing && keys.every((key) => output.scores[key].score >= MEDIA_JUDGE.min_score)\n ? \"accept\"\n : failing && skill.length > 0 ? \"reject\" : \"needs_you\";\n if (computed === \"accept\" && output.recommendation === \"accept\") return { ...base, decision: \"accepted\" };\n if (computed === \"reject\" && output.recommendation !== \"accept\") {\n const top = skill\n .map((issue, i) => ({ issue, i }))\n .sort((a, b) => SEVERITY[a.issue.severity] - SEVERITY[b.issue.severity] || a.i - b.i)\n .slice(0, MEDIA_JUDGE.max_fixes)\n .map(({ issue }, i) => `${i + 1}. ${issue.section === null ? \"\" : `[${issue.section.replace(/^## /, \"\")}] `}${issue.problem} → ${issue.fix}`);\n // Two decimals, like the badge and the verdict message: 3.05 must not read as 3.0.\n const head = `Automated review of round ${input.round} (score ${score.toFixed(2)}/5). Change only these; keep everything else:`;\n return { ...base, decision: \"rejected\", feedback: [head, ...top].join(\"\\n\") };\n }\n const reason = !input.g6.pass\n ? `not publishable: ${input.g6.evidence}`\n : failing && skill.length === 0\n ? \"only render or source issues; revising the skill would not fix them\"\n : output.recommendation !== computed\n ? `the judge recommends ${output.recommendation} but the scores say ${computed}`\n : `a score is under ${MEDIA_JUDGE.min_score} though every gate passes`;\n return { ...base, decision: \"needs_you\", reason };\n}\n","/**\n * Characters — a reusable, consistent **persona** rendered into media (`canonical-spec §33.6`,\n * ADR-1269).\n *\n * A character is trained once from a handful of reference stills and then pinned into every later\n * image, so the same face, hair and build carry across a whole channel — the capability the\n * AI-influencer work needs and that a one-shot `generate_image` cannot give, because two renders of\n * \"a young woman with freckles\" are two different women. It is the media sibling of an `idn_`\n * identity: an identity is *who an agent is being* to the world (an inbox, a number); a character is\n * *who an agent renders as* on screen.\n *\n * Training is asynchronous and slow (minutes), so the record carries a `status` that walks\n * `training → ready`/`failed`, exactly as a `med_` video job does. `ready` is the only state in\n * which it may be pinned into a render. The provider's own handle for the trained character is a\n * server column, never a wire field (`CLAUDE.md §2`, like `subscription.ref`): a customer addresses\n * a character by its `chr_` id or its name, and what trained it is ours to know.\n */\n\nimport { z } from \"zod\";\nimport { Metadata, Timestamp, idOf } from \"./common\";\nimport { lookOf, unknownLookMessage } from \"./looks\";\n\n/**\n * Bounded because the name is surfaced to the model verbatim, and an unbounded name is a prompt —\n * and at the trainer's own limit, so a name we accept is never one the provider then refuses.\n */\nexport const CHARACTER_NAME_MAX = 100;\nexport const CHARACTER_DESCRIPTION_MAX = 1024;\n/** One to this many reference stills train a character; more angles train a stronger likeness. */\nexport const CHARACTER_IMAGES_MAX = 16;\n\n/** `training` covers every not-yet-terminal provider state; `ready` is the only renderable one. */\nexport const CHARACTER_STATUSES = [\"training\", \"ready\", \"failed\"] as const;\nexport const CharacterStatusSchema = z.enum(CHARACTER_STATUSES);\nexport type CharacterStatus = z.infer<typeof CharacterStatusSchema>;\n\n/** `platform` = a prebuilt character every org reads and none can write (ADR-1360). */\nexport const CHARACTER_SCOPES = [\"organization\", \"platform\"] as const;\nexport const CharacterScopeSchema = z.enum(CHARACTER_SCOPES);\n\n/** Each persona line is surfaced to the model when it writes as the character. */\nexport const CHARACTER_PERSONA_MAX = 500;\n/** The most looks a character's `style_pack` names. */\nexport const CHARACTER_STYLE_PACK_MAX = 12;\n\nconst PersonaLine = z.string().max(CHARACTER_PERSONA_MAX).optional();\n/** How a character talks and dresses — read when writing or rendering as them. */\nexport const CharacterPersonaSchema = z.object({\n niche: PersonaLine.describe(\"The topic or audience the character makes content for, e.g. 'budget travel for students'.\"),\n bio: PersonaLine.describe(\"A short backstory: who the character is, in a sentence or two.\"),\n voice: PersonaLine.describe(\"How the character talks: tone, pace, words they use or avoid.\"),\n wardrobe: PersonaLine.describe(\"What the character usually wears on screen.\"),\n hooks: PersonaLine.describe(\"Opening lines or catchphrases the character uses to start a video.\"),\n voice_id: z.string().max(64).optional().describe(\"Their speech voice, passed as `voice`.\"),\n});\nexport type CharacterPersona = z.infer<typeof CharacterPersonaSchema>;\n\n/** Look names (`looks.ts`), each validated, as a character's usual looks. */\nexport const StylePackSchema = z\n .array(z.string())\n .max(CHARACTER_STYLE_PACK_MAX)\n .superRefine((names, ctx) => {\n names.forEach((name, index) => {\n if (lookOf(name) === undefined) ctx.addIssue({ code: \"custom\", path: [index], message: unknownLookMessage(name) });\n });\n });\n\n/**\n * WHAT A PERSON CONFIRMS BEFORE A FACE IS TRAINED FROM PHOTOS (ADR-1360). Training makes a lasting,\n * reusable likeness of a real face, so `POST /v1/characters` and `create_character` refuse without an\n * explicit attestation, and the row keeps who confirmed it, when, and these words (`metadata.consent`).\n * Plain words: it is shown on the Characters tab's checkbox and on the training's approval card.\n */\nexport const CHARACTER_CONSENT_STATEMENT =\n \"I confirm the person in these photos is me, or has given me permission to create an AI likeness of them, and is not a public figure.\";\n\n/** The attestation a training must carry: `{ attested: true }`, nothing else accepted. */\nexport const CharacterConsentSchema = z.object({\n attested: z\n .literal(true, { error: \"consent.attested must be true: confirm the person in the photos agreed to an AI likeness\" })\n .describe(\"true only when the person confirmed the photos are of them, or of someone who agreed to an AI likeness, and not a public figure.\"),\n});\nexport type CharacterConsent = z.infer<typeof CharacterConsentSchema>;\n\n/** The consent as stored on a trained character's row (`metadata.consent`). */\nexport interface CharacterConsentRecord {\n attested: true;\n /** Who confirmed it: a member's id, an API key's id, or the session whose approved call it was. */\n by: string;\n at: string;\n statement: string;\n /** On a session's `create_character`: whether a person allowed this exact call on its card. */\n approved?: boolean;\n}\n\nexport const CharacterSchema = z.object({\n id: idOf(\"chr\"),\n object: z.literal(\"character\"),\n /** Human-facing name. Surfaced to the model and how a person addresses the character. */\n name: z.string().min(1).max(CHARACTER_NAME_MAX),\n /** What the character is — looks, vibe, wardrobe — read by the model when it renders as them. */\n description: z.string().max(CHARACTER_DESCRIPTION_MAX).nullable(),\n status: CharacterStatusSchema,\n /** The reference stills it was trained from, as given: a stored file's `fil_` id or a public URL. */\n source_images: z.array(z.string()),\n /** A trained preview once there is one; `null` while training or when none was produced. */\n thumbnail_url: z.string().nullable(),\n /** Why a `failed` training failed, in our words; `null` otherwise. Never a vendor name. */\n reason: z.string().nullable(),\n /** Ours (`organization`) or a prebuilt character every org reads (`platform`). */\n scope: CharacterScopeSchema.default(\"organization\"),\n persona: CharacterPersonaSchema.nullable().default(null),\n /** Look names the character is usually drawn in; `[]` means any look. */\n style_pack: z.array(z.string()).default([]),\n /** Dashboard image paths (`/setup/…`) of a platform character; `[]` otherwise. */\n sheet: z.array(z.string()).default([]),\n metadata: Metadata,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Character = z.infer<typeof CharacterSchema>;\n","import { z } from \"zod\";\nimport { idOf } from \"./common\";\n\n/**\n * `build_3d` / `POST /v1/computers/{id}/build-3d` (§59): run a build123d (`cad`) or Blender\n * (`blender`) script in the computer, check the result, render previews and publish the exports.\n * The agent tool and the REST route parse the same body, so they cannot drift.\n */\nexport const BUILD_3D_ENGINES = [\"cad\", \"blender\"] as const;\nexport const BUILD_3D_FORMATS = [\"step\", \"stl\", \"3mf\", \"glb\", \"obj\", \"blend\"] as const;\nexport const BUILD_3D_VIEWS = [\"iso\", \"front\", \"top\", \"side\"] as const;\nexport type Build3dFormat = (typeof BUILD_3D_FORMATS)[number];\n\nexport const Build3dRequestSchema = z.object({\n engine: z.enum(BUILD_3D_ENGINES).describe(\"`cad` runs a build123d Python script (precise parts); `blender` runs a Blender Python script (models, scenes).\"),\n script: z.string().min(1).max(200_000).describe(\"The full Python script to run in the computer.\"),\n name: z.string().regex(/^[a-z0-9_-]{1,64}$/).describe(\"File name for the exports, without an extension: lowercase letters, digits, - and _.\"),\n export: z.array(z.enum(BUILD_3D_FORMATS)).min(1).max(6).optional().describe(\"File formats to export the result as.\"),\n render: z\n .union([\n z.object({\n views: z.array(z.enum(BUILD_3D_VIEWS)).min(1).max(4).optional().describe(\"Camera angles to render previews from.\"),\n size: z.number().int().min(256).max(1024).optional().describe(\"Preview image width and height in pixels.\"),\n }),\n z.literal(false),\n ])\n .optional()\n .describe(\"Preview renders to make, or false for none.\"),\n publish: z.boolean().default(true).describe(\"Publish the exported files so they get shareable links.\"),\n timeout_s: z.number().int().min(10).max(600).default(120).describe(\"Seconds the script may run before it is stopped.\"),\n});\nexport type Build3dRequest = z.infer<typeof Build3dRequestSchema>;\n\nexport const Build3dResultSchema = z.object({\n ok: z.boolean(),\n files: z.array(\n z.object({ file_id: idOf(\"fil\"), name: z.string(), content_type: z.string(), bytes: z.number().int().nonnegative() }),\n ),\n previews: z.array(idOf(\"fil\")),\n checks: z.object({\n valid_solid: z.boolean().nullable(),\n watertight: z.boolean(),\n bbox_mm: z.tuple([z.number(), z.number(), z.number()]),\n volume_cm3: z.number().nullable(),\n triangles: z.number().int().nonnegative(),\n }).nullable(),\n error: z.object({ message: z.string(), line: z.number().int().nullable() }).nullable(),\n log_tail: z.string().max(4_096),\n compute_seconds: z.number().nonnegative(),\n});\nexport type Build3dResult = z.infer<typeof Build3dResultSchema>;\n","/**\n * core-gaps: contracts — an app backend's database and object storage on the wire\n * (`canonical-spec §37`, §38). Buckets and objects are customer-named and carry no id prefix.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const DbTableSchema = z.object({\n object: z.literal(\"db_table\"),\n name: z.string(),\n schema: z.string().default(\"public\"),\n rows: z.number().int().nonnegative().nullable(),\n size_bytes: z.number().int().nonnegative().nullable(),\n});\nexport type DbTable = z.infer<typeof DbTableSchema>;\n\nexport const DbMigrationSchema = z.object({\n id: idOf(\"dbm\"),\n object: z.literal(\"db_migration\"),\n name: z.string(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n applied_at: Timestamp,\n statements: z.number().int().nonnegative(),\n});\nexport type DbMigration = z.infer<typeof DbMigrationSchema>;\n\nexport const ApplyDbMigrationSchema = z.object({\n name: z.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9_-]*$/),\n sql: z.string().min(1),\n});\n\nexport const DB_REST_METHODS = [\"GET\", \"POST\", \"PATCH\", \"PUT\", \"DELETE\", \"HEAD\"] as const;\nexport const DbRestMethodSchema = z.enum(DB_REST_METHODS);\n\nexport const BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\n\nexport const BucketSchema = z.object({\n object: z.literal(\"bucket\"),\n name: z.string().regex(BUCKET_NAME),\n public: z.boolean(),\n created_at: Timestamp,\n});\nexport type Bucket = z.infer<typeof BucketSchema>;\n\nexport const CreateBucketSchema = z.object({\n name: z.string().regex(BUCKET_NAME, { error: \"3–63 lowercase letters, digits and hyphens\" }),\n public: z.boolean().default(false),\n});\n\nexport const StorageObjectSchema = z.object({\n object: z.literal(\"storage_object\"),\n bucket: z.string(),\n key: z.string().min(1),\n size_bytes: z.number().int().nonnegative(),\n content_type: z.string(),\n etag: z.string().nullable(),\n updated_at: Timestamp,\n});\nexport type StorageObject = z.infer<typeof StorageObjectSchema>;\n\nexport const SignedUrlMethodSchema = z.enum([\"PUT\", \"GET\"]);\nexport const SignedUrlSchema = z.object({\n object: z.literal(\"signed_url\"),\n url: z.string().url(),\n method: SignedUrlMethodSchema,\n expires_at: Timestamp,\n});\nexport type SignedUrl = z.infer<typeof SignedUrlSchema>;\n\n/** `POST …/objects/{key}/upload-url` — a PUT the caller streams the bytes to. */\nexport const CreateUploadUrlSchema = z.object({\n content_type: z.string().min(1),\n expires_seconds: z.number().int().min(60).max(3_600).default(900),\n});\n","/**\n * core-gaps: contracts — stock photo search (`canonical-spec §39`, D6). The `id` is the\n * provider's, opaque and unprefixed; `attribution_url` is the one field allowed to point at the\n * provider's domain, because the licence requires it.\n */\n\nimport { z } from \"zod\";\n\nexport const STOCK_PHOTO_ORIENTATIONS = [\"landscape\", \"portrait\", \"square\"] as const;\nexport const STOCK_PHOTO_SIZES = [\"small\", \"medium\", \"large\"] as const;\n\nexport const StockPhotoQuerySchema = z.object({\n query: z.string().min(1).max(200),\n count: z.coerce.number().int().min(1).max(30).default(10),\n orientation: z.enum(STOCK_PHOTO_ORIENTATIONS).optional(),\n color: z.string().min(1).max(32).optional(),\n size: z.enum(STOCK_PHOTO_SIZES).optional(),\n});\nexport type StockPhotoQuery = z.infer<typeof StockPhotoQuerySchema>;\n\nexport const StockPhotoSchema = z.object({\n object: z.literal(\"stock_photo\"),\n id: z.string().min(1),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n url: z.string().url(),\n preview_url: z.string().url(),\n alt: z.string().nullable(),\n photographer: z.string().nullable(),\n attribution_url: z.string().url().nullable(),\n dominant_color: z.string().nullable(),\n /** A neutral name to import the photo under (`stock-<id>.<ext>`): the CDN's own file name carries its brand (ADR-1874). Optional on the wire so a newer client reads an older API; the API always sends it. */\n file_name: z.string().min(1).optional(),\n});\nexport type StockPhoto = z.infer<typeof StockPhotoSchema>;\n\n/** `stock-<id>.<ext>`, the extension read off the image URL's path (`jpeg` when it has none). */\nexport function stockFileName(id: string, url: string): string {\n const ext = /\\.(jpe?g|png|webp|gif)$/i.exec(new URL(url).pathname)?.[1]?.toLowerCase() ?? \"jpeg\";\n return `stock-${id.replace(/[^A-Za-z0-9_-]/g, \"\")}.${ext}`;\n}\n","/**\n * The Autonomous Company 30 Day Tournament (`canonical-spec §56`): a person joins by answering a few\n * questions, once, when they sign up or later in the studio, and stays entered — the tournament is\n * ongoing, so nobody re-applies. There is no review — the entry IS the admission. Like a creator, an entry is a person's row keyed by email and belongs\n * to no organization (§56.3).\n *\n * The caps and which fields may be blank are the landing page's application form's, unchanged, so an\n * answer that fit there fits here. The email is not an answer: it is the account's.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nconst required = (max: number) =>\n z.string().trim().min(1, \"Fill this in.\").max(max, `Keep it under ${max} characters.`);\nconst optional = (max: number) => z.string().trim().max(max, `Keep it under ${max} characters.`).optional();\n\nexport const TournamentAnswersSchema = z.object({\n name: required(100),\n university: optional(150),\n company: required(100),\n building: required(2000).min(20, \"Tell us a little more about what you're building.\"),\n x: optional(300),\n github: optional(300),\n linkedin: optional(300),\n projects: optional(1500),\n knowledge: required(1000),\n motivation: required(1000),\n});\nexport type TournamentAnswers = z.infer<typeof TournamentAnswersSchema>;\n\n/** One person in the tournament. Joining again rewrites the answers on the same row. */\nexport const TournamentEntrySchema = z.object({\n id: idOf(\"tne\"),\n object: z.literal(\"tournament_entry\"),\n email: z.email(),\n answers: TournamentAnswersSchema,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type TournamentEntry = z.infer<typeof TournamentEntrySchema>;\n","/**\n * The QA tester program (`canonical-spec §60`): a reviewer opens jobs (one published template each)\n * and adds testers by email; a tester takes up to two jobs at once, each a fresh test company. Like a\n * creator, none of these rows belongs to an organization.\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const QaJobStatusSchema = z.enum([\"open\", \"closed\"]);\nexport type QaJobStatus = z.infer<typeof QaJobStatusSchema>;\nexport const QaAssignmentStatusSchema = z.enum([\"active\", \"ended\"]);\nexport type QaAssignmentStatus = z.infer<typeof QaAssignmentStatusSchema>;\nexport const QaBugStatusSchema = z.enum([\"pending\", \"approved\", \"rejected\"]);\nexport type QaBugStatus = z.infer<typeof QaBugStatusSchema>;\n/** A report on the Bugs/Feedback tab: a bug in a job's company, or feedback on anything. */\nexport const QaBugKindSchema = z.enum([\"bug\", \"feedback\"]);\nexport type QaBugKind = z.infer<typeof QaBugKindSchema>;\n\nexport const QaJobSchema = z.object({\n id: idOf(\"qaj\"),\n object: z.literal(\"qa_job\"),\n name: z.string(),\n template: z.string(),\n blurb: z.string(),\n seats: z.number().int(),\n /** Active assignments; `seats - taken` is what is left. */\n taken: z.number().int(),\n status: QaJobStatusSchema,\n created_at: Timestamp,\n});\nexport type QaJob = z.infer<typeof QaJobSchema>;\n\nexport const QaTesterSchema = z.object({\n id: idOf(\"qat\"),\n object: z.literal(\"qa_tester\"),\n email: z.string(),\n payout_details: z.string().nullable(),\n active_jobs: z.number().int(),\n created_at: Timestamp,\n /** The desk sign-in's password; on the reviewer's routes only. */\n desk_password: z.string().nullable().optional(),\n});\nexport type QaTester = z.infer<typeof QaTesterSchema>;\n\nexport const QaAssignmentSchema = z.object({\n id: idOf(\"qaa\"),\n object: z.literal(\"qa_assignment\"),\n tester_id: idOf(\"qat\"),\n job_id: idOf(\"qaj\"),\n job_name: z.string(),\n template: z.string(),\n organization_id: idOf(\"org\").nullable(),\n login_email: z.string(),\n login_password: z.string().nullable(),\n status: QaAssignmentStatusSchema,\n /** Distinct UTC days with a usage debit since the job was taken (until it ended). */\n days_active: z.number().int(),\n spent_micro_usd: MicroUsdField,\n balance_micro_usd: MicroUsdField,\n created_at: Timestamp,\n ended_at: Timestamp.nullable(),\n});\nexport type QaAssignment = z.infer<typeof QaAssignmentSchema>;\n\n/** A file attached to a report; its bytes are read by index (`…/bugs/:id/attachments/:n`). */\nexport const QaBugAttachmentSchema = z.object({\n name: z.string(),\n content_type: z.string(),\n size_bytes: z.number().int(),\n});\nexport type QaBugAttachment = z.infer<typeof QaBugAttachmentSchema>;\n\nexport const QaBugSchema = z.object({\n id: idOf(\"qab\"),\n object: z.literal(\"qa_bug\"),\n tester_id: idOf(\"qat\"),\n /** The job it is about; `null` for feedback on the program as a whole. */\n assignment_id: idOf(\"qaa\").nullable(),\n /** That job's name, for reading the report; `null` with no job. */\n job_name: z.string().nullable(),\n kind: QaBugKindSchema,\n title: z.string(),\n details: z.string(),\n attachments: z.array(QaBugAttachmentSchema),\n status: QaBugStatusSchema,\n /** What the reviewer set on approving it; `null` while pending and when rejected. */\n reward_micro_usd: MicroUsdField.nullable(),\n paid_at: Timestamp.nullable(),\n created_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type QaBug = z.infer<typeof QaBugSchema>;\n\n/** Who wrote a chat message: the tester, or anyone on the team (§60.6). */\nexport const QaChatAuthorSchema = z.enum([\"tester\", \"team\"]);\nexport type QaChatAuthor = z.infer<typeof QaChatAuthorSchema>;\n\nexport const QaMessageSchema = z.object({\n id: idOf(\"qam\"),\n object: z.literal(\"qa_message\"),\n tester_id: idOf(\"qat\"),\n author: QaChatAuthorSchema,\n /** Empty only when the message is images alone. */\n body: z.string().max(4000),\n /** Images, read by index (`…/chat/messages/:id/attachments/:n`). */\n attachments: z.array(QaBugAttachmentSchema),\n created_at: Timestamp,\n});\nexport type QaMessage = z.infer<typeof QaMessageSchema>;\n\n/** One tester's thread as the team's inbox lists it. */\nexport const QaChatThreadSchema = z.object({\n object: z.literal(\"qa_chat_thread\"),\n tester_id: idOf(\"qat\"),\n email: z.string(),\n last_message: QaMessageSchema.nullable(),\n /** The tester's messages the team has not read. */\n unread: z.number().int().nonnegative(),\n});\nexport type QaChatThread = z.infer<typeof QaChatThreadSchema>;\n\n/** A thread's messages, oldest first (the newest 200), and when the other side last read it. */\nexport const QaChatSchema = z.object({\n object: z.literal(\"qa_chat\"),\n tester_id: idOf(\"qat\"),\n messages: z.array(QaMessageSchema),\n read_by_tester: Timestamp.nullable(),\n read_by_team: Timestamp.nullable(),\n});\nexport type QaChat = z.infer<typeof QaChatSchema>;\n\n/** `POST …/chat/ticket`: the socket to open within a minute; ask again to reconnect. */\nexport const QaChatTicketSchema = z.object({\n object: z.literal(\"qa_chat_ticket\"),\n url: z.string().url(),\n expires_at: Timestamp,\n});\nexport type QaChatTicket = z.infer<typeof QaChatTicketSchema>;\n\n/** `GET /v1/qa/me`: the tester's desk. */\nexport const QaDeskSchema = z.object({\n object: z.literal(\"qa_desk\"),\n tester: QaTesterSchema,\n assignments: z.array(QaAssignmentSchema),\n bugs: z.array(QaBugSchema),\n /** The team's messages the tester has not read. */\n chat_unread: z.number().int().nonnegative(),\n});\nexport type QaDesk = z.infer<typeof QaDeskSchema>;\n","/** Identity-owned legal: verifications and companies (`canonical-spec.md §43`). */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const LEGAL_MEMBER_STATUSES = [\n \"pending\",\n \"link_ready\",\n \"link_sent\",\n \"in_progress\",\n \"pending_review\",\n \"verified\",\n \"failed\",\n] as const;\nexport const LegalMemberStatusSchema = z.enum(LEGAL_MEMBER_STATUSES);\nexport type LegalMemberStatus = z.infer<typeof LegalMemberStatusSchema>;\n\nexport const LEGAL_VERIFICATION_STATUSES = [\"in_progress\", \"pending_review\", \"verified\", \"failed\"] as const;\nexport const LegalVerificationStatusSchema = z.enum(LEGAL_VERIFICATION_STATUSES);\nexport type LegalVerificationStatus = z.infer<typeof LegalVerificationStatusSchema>;\n\nexport const LEGAL_COMPANY_STATUSES = [\"awaiting_payment\", \"paid\", \"submitted\", \"formed\", \"failed\"] as const;\nexport const LegalCompanyStatusSchema = z.enum(LEGAL_COMPANY_STATUSES);\nexport type LegalCompanyStatus = z.infer<typeof LegalCompanyStatusSchema>;\n\nexport const LEGAL_DOCUMENT_KINDS = [\"articles\", \"ein_letter\", \"operating_agreement\", \"other\"] as const;\nexport const LegalDocumentKindSchema = z.enum(LEGAL_DOCUMENT_KINDS);\nexport type LegalDocumentKind = z.infer<typeof LegalDocumentKindSchema>;\n\nexport const LegalMemberRoleSchema = z.enum([\"primary\", \"secondary\"]);\nexport const LegalEinStatusSchema = z.enum([\"none\", \"pending\", \"issued\"]);\nexport const LegalRequiredActionKindSchema = z.enum([\"signature\", \"information\", \"payment\", \"other\"]);\nexport type LegalRequiredActionKind = z.infer<typeof LegalRequiredActionKindSchema>;\n\n/** The 50 states plus DC, two-letter and uppercase. */\nexport const US_STATES = [\n \"AL\", \"AK\", \"AZ\", \"AR\", \"CA\", \"CO\", \"CT\", \"DE\", \"DC\", \"FL\", \"GA\", \"HI\", \"ID\", \"IL\", \"IN\", \"IA\", \"KS\",\n \"KY\", \"LA\", \"ME\", \"MD\", \"MA\", \"MI\", \"MN\", \"MS\", \"MO\", \"MT\", \"NE\", \"NV\", \"NH\", \"NJ\", \"NM\", \"NY\", \"NC\",\n \"ND\", \"OH\", \"OK\", \"OR\", \"PA\", \"RI\", \"SC\", \"SD\", \"TN\", \"TX\", \"UT\", \"VT\", \"VA\", \"WA\", \"WV\", \"WI\", \"WY\",\n] as const;\nexport const UsStateSchema = z.enum(US_STATES);\nexport type UsState = z.infer<typeof UsStateSchema>;\n\nexport const LegalMemberInputSchema = z.object({\n first_name: z.string().min(1).max(128).describe(\"The member's legal first name.\"),\n last_name: z.string().min(1).max(128).describe(\"The member's legal last name.\"),\n email: z.string().min(1).max(320).describe(\"Where the member's verification link is sent.\"),\n role: LegalMemberRoleSchema.describe(\"primary for exactly one member; secondary for the rest.\"),\n is_responsible_party: z.boolean().describe(\"true for exactly one member: the person the IRS contacts.\"),\n ownership_percent: z.number().int().describe(\"Whole percent owned; all members sum to 100.\"),\n});\nexport type LegalMemberInput = z.infer<typeof LegalMemberInputSchema>;\n\nexport const LegalMemberSchema = LegalMemberInputSchema.extend({\n id: idOf(\"lgm\"),\n object: z.literal(\"legal_member\"),\n verification_id: idOf(\"lgv\"),\n status: LegalMemberStatusSchema,\n link_url: z.url().nullable(),\n link_expires_at: Timestamp.nullable(),\n completed_at: Timestamp.nullable(),\n});\nexport type LegalMember = z.infer<typeof LegalMemberSchema>;\n\nexport const LegalVerificationSchema = z.object({\n id: idOf(\"lgv\"),\n object: z.literal(\"legal_verification\"),\n identity_id: idOf(\"idn\"),\n status: LegalVerificationStatusSchema,\n members: z.array(LegalMemberSchema),\n ready_for_formation: z.boolean(),\n started_at: Timestamp,\n completed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalVerification = z.infer<typeof LegalVerificationSchema>;\n\nexport const StartLegalVerificationSchema = z.object({\n members: z.array(LegalMemberInputSchema).describe(\"Every owner and officer to verify; each gets a hosted link to complete.\"),\n});\nexport type StartLegalVerification = z.infer<typeof StartLegalVerificationSchema>;\n\nexport const CompleteLegalMemberSchema = z.object({ token: z.string().min(1) });\n\nexport const LegalNameOptionSchema = z.object({ name: z.string().min(1).max(200), ending: z.literal(\"LLC\") });\nexport type LegalNameOption = z.infer<typeof LegalNameOptionSchema>;\n\nexport const LegalMailingAddressSchema = z.object({\n line1: z.string().min(1).max(200).describe(\"Street address.\"),\n line2: z.string().max(200).nullable().describe(\"Suite or unit, or null.\"),\n city: z.string().min(1).max(100).describe(\"City.\"),\n state: UsStateSchema.describe(\"Two-letter state code.\"),\n postal_code: z.string().min(1).max(16).describe(\"ZIP code.\"),\n country: z.literal(\"US\").describe(\"Always US.\"),\n});\nexport type LegalMailingAddress = z.infer<typeof LegalMailingAddressSchema>;\n\nexport const LegalRequiredActionSchema = z.object({\n kind: LegalRequiredActionKindSchema,\n description: z.string(),\n url: z.url().nullable(),\n});\nexport type LegalRequiredAction = z.infer<typeof LegalRequiredActionSchema>;\n\n/** The one length rule the provider imposes on a company description. */\nexport const LEGAL_DESCRIPTION_MAX = 50;\n\nexport const CreateLegalCompanySchema = z.object({\n verification_id: idOf(\"lgv\").describe(\"The completed verification of the members forming it.\"),\n state: UsStateSchema.describe(\"The US state to form in, as its two-letter code.\"),\n name_options: z.array(z.string().min(1).max(200)).min(1).max(3).describe(\"Up to three names in order of preference, without the LLC ending.\"),\n naics_code: z.string().regex(/^\\d{2,6}$/).describe(\"The industry code, from legal.naics.\"),\n description: z.string().min(1).max(LEGAL_DESCRIPTION_MAX).describe(\"What the business does, in a sentence.\"),\n mailing_address: LegalMailingAddressSchema.describe(\"A US address where the company receives mail.\"),\n});\nexport type CreateLegalCompany = z.infer<typeof CreateLegalCompanySchema>;\n\nexport const LegalCompanySchema = CreateLegalCompanySchema.omit({ name_options: true }).extend({\n id: idOf(\"lgc\"),\n object: z.literal(\"legal_company\"),\n identity_id: idOf(\"idn\"),\n status: LegalCompanyStatusSchema,\n entity_type: z.literal(\"llc\"),\n name_options: z.array(LegalNameOptionSchema),\n legal_name: z.string().nullable(),\n ein_status: LegalEinStatusSchema,\n price_micro_usd: MicroUsdField,\n required_actions: z.array(LegalRequiredActionSchema),\n failure_reason: z.string().max(256).nullable(),\n submitted_at: Timestamp.nullable(),\n formed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalCompany = z.infer<typeof LegalCompanySchema>;\n\nexport const LegalDocumentSchema = z.object({\n id: idOf(\"lgd\"),\n object: z.literal(\"legal_document\"),\n company_id: idOf(\"lgc\"),\n kind: LegalDocumentKindSchema,\n name: z.string(),\n created_at: Timestamp,\n});\nexport type LegalDocument = z.infer<typeof LegalDocumentSchema>;\n\nexport const LegalDocumentLinkSchema = z.object({\n object: z.literal(\"legal_document_link\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type LegalDocumentLink = z.infer<typeof LegalDocumentLinkSchema>;\n\nexport const NaicsCodeSchema = z.object({\n object: z.literal(\"naics_code\"),\n code: z.string().regex(/^\\d{2,6}$/),\n title: z.string(),\n});\nexport type NaicsCode = z.infer<typeof NaicsCodeSchema>;\n\nexport const LegalStateSchema = z.object({\n object: z.literal(\"legal_state\"),\n code: UsStateSchema,\n name: z.string(),\n formation_fee_micro_usd: MicroUsdField,\n});\nexport type LegalState = z.infer<typeof LegalStateSchema>;\n\n/** What the provider's webhook tells us about one hosted session, vendor words already translated. */\nexport const LegalWebhookEventSchema = z.object({\n provider_session_ref: z.string().min(1),\n status: z.enum([\"verified\", \"failed\", \"pending_review\"]),\n metadata: Metadata,\n});\nexport type LegalWebhookEvent = z.infer<typeof LegalWebhookEventSchema>;\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** The legacy `validateMembers` rules, messages verbatim, as one `validation_failed` (§43.3). */\nexport function checkMembers(members: readonly LegalMemberInput[]): void {\n const refuse = (message: string): never => {\n throw new VettaError(\"validation_failed\", message, \"members\");\n };\n if (members.length === 0) refuse(\"At least one member is required\");\n const primaryCount = members.filter((m) => m.role === \"primary\").length;\n if (primaryCount !== 1) refuse(`Exactly one member must have role 'primary', found ${primaryCount}`);\n const rpCount = members.filter((m) => m.is_responsible_party).length;\n if (rpCount !== 1) refuse(`Exactly one member must be designated as responsible party, found ${rpCount}`);\n for (const m of members) {\n if (m.ownership_percent < 0 || m.ownership_percent > 100) {\n refuse(`Ownership percentage must be 0-100, got ${m.ownership_percent} for ${m.email}`);\n }\n }\n const totalOwnership = members.reduce((sum, m) => sum + m.ownership_percent, 0);\n if (totalOwnership !== 100) refuse(`Ownership percentages must sum to 100, got ${totalOwnership}`);\n for (const m of members) if (!EMAIL.test(m.email)) refuse(`Invalid email address: ${m.email}`);\n}\n\nconst LLC_ENDING = /\\s*(?:,\\s*)?(?:l\\.?l\\.?c\\.?|limited\\s+liability\\s+company)\\s*$/i;\n\n/** Strips any spelling of the LLC ending and answers the canonical `{ name, ending }` (§43.3). */\nexport function canonicalName(raw: string): LegalNameOption {\n const name = raw.replace(LLC_ENDING, \"\").trim();\n if (name.length === 0) throw new VettaError(\"validation_failed\", \"A company name is required\", \"name_options\");\n return { name, ending: \"LLC\" };\n}\n\n/** The display form of a name option: `\"<name> LLC\"`. */\nexport const displayName = (option: LegalNameOption): string => `${option.name} ${option.ending}`;\n\n/** The legacy status machine: any failed → failed; any review → pending_review; all verified → verified. */\nexport function verificationStatus(statuses: readonly LegalMemberStatus[]): LegalVerificationStatus {\n if (statuses.some((s) => s === \"failed\")) return \"failed\";\n if (statuses.some((s) => s === \"pending_review\")) return \"pending_review\";\n if (statuses.length > 0 && statuses.every((s) => s === \"verified\")) return \"verified\";\n return \"in_progress\";\n}\n\n/**\n * What a store keeps for each legal object: the wire shape less its transient/derived fields, plus\n * the provider handles. No handle is a person's data and no hosted-session token is a field here,\n * so a record can only ever project into a safe wire object (§43.1, PII boundary).\n */\nexport type LegalVerificationRecord = Omit<LegalVerification, \"object\" | \"members\" | \"ready_for_formation\">;\nexport type LegalMemberRecord = Omit<LegalMember, \"object\" | \"link_url\"> & {\n provider_session_ref: string | null;\n provider_person_ref: string | null;\n created_at: string;\n updated_at: string;\n};\nexport type LegalCompanyRecord = Omit<LegalCompany, \"object\"> & {\n ledger_entry_id: string | null;\n provider_customer_ref: string | null;\n provider_formation_ref: string | null;\n};\nexport type LegalDocumentRecord = Omit<LegalDocument, \"object\"> & { provider_document_ref: string };\n\n/** Member states a webhook redelivery or a poll may no longer move (§43.2). */\nexport const isTerminalMember = (status: LegalMemberStatus): boolean => status === \"verified\" || status === \"failed\";\n\n/** A provider outcome lands on a member unless the member is already final (§43.2). */\nexport function settleMember(\n member: LegalMemberRecord,\n outcome: { status: LegalMemberStatus; providerPersonRef: string | null },\n now: string,\n): LegalMemberRecord {\n if (isTerminalMember(member.status) || outcome.status === \"in_progress\") return member;\n return {\n ...member,\n status: outcome.status,\n provider_person_ref: outcome.providerPersonRef ?? member.provider_person_ref,\n completed_at: isTerminalMember(outcome.status) ? now : member.completed_at,\n updated_at: now,\n };\n}\n\n/** The parent follows its members (`verificationStatus`); the same record back means nothing moved. */\nexport function settleVerification(\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n now: string,\n): LegalVerificationRecord {\n const status = verificationStatus(members.map((m) => m.status));\n if (status === record.status) return record;\n const done = status === \"verified\" || status === \"failed\";\n return { ...record, status, completed_at: done ? now : null, updated_at: now };\n}\n\n/**\n * What a paid company files as: the row plus its members by verified-person handle. The adapter reads\n * each person's PII back from the provider vault; nothing personal crosses here (§43.1).\n */\nexport function formationInput(record: LegalCompanyRecord, members: readonly LegalMemberRecord[]) {\n const { postal_code: postalCode, ...address } = record.mailing_address;\n return {\n idempotencyKey: record.id,\n state: record.state,\n nameOptions: record.name_options,\n naicsCode: record.naics_code,\n description: record.description,\n mailingAddress: { ...address, postalCode },\n members: members.map((m) => {\n if (m.provider_person_ref === null) {\n throw new VettaError(\"state_conflict\", \"every member must be verified before the formation is filed\");\n }\n return {\n role: m.role,\n is_responsible_party: m.is_responsible_party,\n ownership_percent: m.ownership_percent,\n providerPersonRef: m.provider_person_ref,\n };\n }),\n };\n}\n\n/** Folds the provider's view of a filing into the row; `formed` and `failed` are final. */\nexport function foldFormation(\n record: LegalCompanyRecord,\n state: {\n providerFormationRef: string;\n status: Extract<LegalCompanyStatus, \"submitted\" | \"formed\" | \"failed\">;\n legalName: string | null;\n einStatus: LegalCompany[\"ein_status\"];\n requiredActions: LegalRequiredAction[];\n failureReason: string | null;\n },\n now: string,\n): LegalCompanyRecord {\n return {\n ...record,\n status: state.status,\n legal_name: state.legalName,\n ein_status: state.einStatus,\n required_actions: state.requiredActions,\n failure_reason: state.failureReason,\n provider_formation_ref: state.providerFormationRef,\n submitted_at: record.submitted_at ?? now,\n formed_at: state.status === \"formed\" ? (record.formed_at ?? now) : record.formed_at,\n updated_at: now,\n };\n}\n\n/** The wire member; `linkUrl` is only ever the link this very call minted (create / resend). */\nexport function toLegalMember(record: LegalMemberRecord, linkUrl: string | null = null): LegalMember {\n const { provider_session_ref: _s, provider_person_ref: _p, created_at: _c, updated_at: _u, ...safe } = record;\n return { object: \"legal_member\", ...safe, link_url: linkUrl };\n}\n\nexport function toLegalVerification(record: LegalVerificationRecord, members: LegalMember[]): LegalVerification {\n return { object: \"legal_verification\", ...record, members, ready_for_formation: record.status === \"verified\" };\n}\n\n/** Links are only ever the ones this call minted; a read never carries one (§43.1). */\nexport const verificationView = (\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n links = new Map<string, string>(),\n): LegalVerification =>\n toLegalVerification(record, members.map((m) => toLegalMember(m, links.get(m.id) ?? null)));\n\nexport function toLegalCompany(record: LegalCompanyRecord): LegalCompany {\n const { ledger_entry_id: _l, provider_customer_ref: _c, provider_formation_ref: _f, ...safe } = record;\n return { object: \"legal_company\", ...safe };\n}\n\nexport function toLegalDocument(record: LegalDocumentRecord): LegalDocument {\n const { provider_document_ref: _r, ...safe } = record;\n return { object: \"legal_document\", ...safe };\n}\n","/** Identity-owned custodied wallet with x402 payments (`canonical-spec.md §44`). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** CAIP-2 on the wire: Base Sepolia (the default) and Base mainnet. */\nexport const WALLET_NETWORKS = [\"eip155:84532\", \"eip155:8453\"] as const;\nexport const WalletNetworkSchema = z.enum(WALLET_NETWORKS);\nexport type WalletNetwork = z.infer<typeof WalletNetworkSchema>;\nexport const DEFAULT_WALLET_NETWORK: WalletNetwork = \"eip155:84532\";\n\n/** The CLI / IaC aliases, resolved client-side to the CAIP-2 value. */\nexport const WALLET_NETWORK_ALIASES: Record<\"base-testnet\" | \"base\", WalletNetwork> = {\n \"base-testnet\": \"eip155:84532\",\n base: \"eip155:8453\",\n};\n\n/** `?network=` on every wallet route: which of the identity's wallets a call addresses. */\nexport const WalletSelectSchema = z.object({ network: WalletNetworkSchema.optional() });\nexport type WalletSelect = z.infer<typeof WalletSelectSchema>;\n\nexport const WALLET_STATUSES = [\"active\", \"frozen\", \"swept\"] as const;\nexport const WalletStatusSchema = z.enum(WALLET_STATUSES);\nexport type WalletStatus = z.infer<typeof WalletStatusSchema>;\n\nexport const WALLET_TRANSACTION_KINDS = [\"fund\", \"transfer\", \"pay\", \"sweep\"] as const;\nexport const WalletTransactionKindSchema = z.enum(WALLET_TRANSACTION_KINDS);\nexport type WalletTransactionKind = z.infer<typeof WalletTransactionKindSchema>;\n\nexport const WALLET_TRANSACTION_STATUSES = [\"pending\", \"confirmed\", \"failed\"] as const;\nexport const WalletTransactionStatusSchema = z.enum(WALLET_TRANSACTION_STATUSES);\nexport type WalletTransactionStatus = z.infer<typeof WalletTransactionStatusSchema>;\n\nexport const WalletDirectionSchema = z.enum([\"in\", \"out\"]);\nexport const WalletFundSourceSchema = z.enum([\"faucet\", \"treasury\"]);\n\nexport const EvmAddressSchema = z.string().regex(/^0x[0-9a-fA-F]{40}$/, \"expected a 0x address\");\nexport const TxHashSchema = z.string().regex(/^0x[0-9a-fA-F]{64}$/, \"expected a 0x transaction hash\");\n\n/** $0.50: the legacy default per-transaction cap. */\nexport const DEFAULT_PER_TX_CAP_MICRO_USD = 500_000;\n\n/** The custody vendor's testnet faucet grants a fixed 1 USDC per request: what it adds, and what the operator card says it adds. */\nexport const TESTNET_FAUCET_MICRO_USD = 1_000_000;\n\nexport const WalletPolicySchema = z.object({\n per_tx_cap_micro_usd: MicroUsdField.nonnegative(),\n daily_cap_micro_usd: MicroUsdField.positive().nullable(),\n low_balance_micro_usd: MicroUsdField.nonnegative().nullable(),\n});\nexport type WalletPolicy = z.infer<typeof WalletPolicySchema>;\n\nexport const isTestnet = (network: WalletNetwork): boolean => network === \"eip155:84532\";\n\n/** The UTC day a `wallet_spend_counter` row is keyed by. */\nexport const walletDay = (nowIso: string): string => nowIso.slice(0, 10);\n\n/**\n * Why an outward amount is refused by the wallet's own policy, or `null` when it fits. The one\n * rule the route and the agent tool both enforce before the custody provider sees a request.\n */\nexport function walletCapViolation(\n policy: WalletPolicy,\n amountMicroUsd: number,\n spentTodayMicroUsd: number,\n): string | null {\n if (amountMicroUsd > policy.per_tx_cap_micro_usd) return \"the amount exceeds per_tx_cap_micro_usd\";\n if (policy.daily_cap_micro_usd !== null && spentTodayMicroUsd + amountMicroUsd > policy.daily_cap_micro_usd) {\n return \"the amount exceeds daily_cap_micro_usd for today\";\n }\n return null;\n}\n\n/** The cheapest requirement on the wallet's own network — the one a quote reports and a pay signs. */\nexport function pickPaymentRequirement<T extends { network: WalletNetwork; amountMicroUsd: number }>(\n requirements: readonly T[],\n network: WalletNetwork,\n): T | undefined {\n return requirements\n .filter((requirement) => requirement.network === network)\n .sort((a, b) => a.amountMicroUsd - b.amountMicroUsd)[0];\n}\n\nexport const WalletSchema = z.object({\n id: idOf(\"wlt\"),\n object: z.literal(\"wallet\"),\n identity_id: idOf(\"idn\"),\n status: WalletStatusSchema,\n network: WalletNetworkSchema,\n address: EvmAddressSchema,\n asset: z.literal(\"usdc\"),\n balance_micro_usd: MicroUsdField,\n policy: WalletPolicySchema,\n spent_today_micro_usd: MicroUsdField,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Wallet = z.infer<typeof WalletSchema>;\n\nexport const CreateWalletSchema = z.object({\n network: WalletNetworkSchema.optional(),\n policy: WalletPolicySchema.partial().optional(),\n});\nexport type CreateWallet = z.infer<typeof CreateWalletSchema>;\n\nexport const UpdateWalletPolicySchema = WalletPolicySchema.partial();\n\nexport const FundWalletSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n source: WalletFundSourceSchema,\n});\nexport type FundWallet = z.infer<typeof FundWalletSchema>;\n\nexport const TransferWalletSchema = z.object({\n to: z.union([EvmAddressSchema, idOf(\"idn\")]),\n amount_micro_usd: MicroUsdField.positive(),\n purpose: z.string().min(1).max(256),\n});\nexport type TransferWallet = z.infer<typeof TransferWalletSchema>;\n\nexport const SweepWalletSchema = z.object({ to: EvmAddressSchema.optional() });\n\nexport const WalletTransactionSchema = z.object({\n id: idOf(\"wtx\"),\n object: z.literal(\"wallet_transaction\"),\n wallet_id: idOf(\"wlt\"),\n kind: WalletTransactionKindSchema,\n direction: WalletDirectionSchema,\n amount_micro_usd: MicroUsdField,\n counterparty: z.string().nullable(),\n origin: z.string().nullable(),\n purpose: z.string().nullable(),\n tx_hash: TxHashSchema.nullable(),\n session_id: idOf(\"ses\").nullable(),\n status: WalletTransactionStatusSchema,\n created_at: Timestamp,\n});\nexport type WalletTransaction = z.infer<typeof WalletTransactionSchema>;\n\nexport const ListWalletTransactionsSchema = z.object({\n kind: WalletTransactionKindSchema.optional().describe(\"Only this kind of movement.\"),\n direction: WalletDirectionSchema.optional().describe(\"in: money received. out: money spent.\"),\n origin: z.string().optional().describe(\"Only payments to this site origin, e.g. https://api.example.com.\"),\n since: Timestamp.optional().describe(\"Only at or after this ISO 8601 instant.\"),\n});\nexport type ListWalletTransactions = z.infer<typeof ListWalletTransactionsSchema>;\n\nconst HttpMethodSchema = z.enum([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nexport const WalletQuoteRequestSchema = z.object({\n url: z.url().describe(\"The paid endpoint's URL.\"),\n method: HttpMethodSchema.optional().describe(\"The HTTP method the endpoint expects; GET when omitted.\"),\n});\nexport type WalletQuoteRequest = z.infer<typeof WalletQuoteRequestSchema>;\n\nexport const WalletQuoteSchema = z.object({\n object: z.literal(\"wallet_quote\"),\n url: z.url(),\n payable: z.boolean(),\n network: WalletNetworkSchema.nullable(),\n asset: z.literal(\"usdc\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n pay_to: EvmAddressSchema.nullable(),\n description: z.string().nullable(),\n max_timeout_seconds: z.number().int().nullable(),\n});\nexport type WalletQuote = z.infer<typeof WalletQuoteSchema>;\n\nexport const WalletPayRequestSchema = WalletQuoteRequestSchema.extend({\n max_amount_micro_usd: MicroUsdField.positive().optional().describe(\"Refuse to pay more than this, in micro-USD (1 USD = 1000000).\"),\n});\nexport type WalletPayRequest = z.infer<typeof WalletPayRequestSchema>;\n\n/** The paid response's body is echoed up to this many bytes. */\nexport const WALLET_RESPONSE_BODY_MAX = 64 * 1024;\n\nexport const WalletPaymentSchema = z.object({\n object: z.literal(\"wallet_payment\"),\n paid: z.boolean(),\n transaction_id: idOf(\"wtx\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n response_status: z.number().int(),\n response_body: z.string().max(WALLET_RESPONSE_BODY_MAX),\n});\nexport type WalletPayment = z.infer<typeof WalletPaymentSchema>;\n\nexport * from \"./wallet-flow\";\nexport * from \"./wallet-outbound\";\n","/**\n * `operator.request` (`canonical-spec §7.7`, ADR-1624): an operator action an agent may PROPOSE and\n * only a person may approve. Each action is one withheld route (`apps/api/src/mcp-tools.ts`\n * `WITHHELD`); the person's allow runs it in the control plane (`apps/api/src/routes/operator.ts`)\n * and the control plane writes what it answered into `outcome`, which is all the tool reports.\n *\n * Not here, on purpose: funding from the treasury and sweeping (no treasury is provisioned, so both\n * fail; and a sweep's address is not a model's to name). A field an action does not take is refused.\n * One flat object, not a union: every agent carries this schema on every turn.\n */\nimport { z } from \"zod\";\nimport { MicroUsdField, idOf } from \"./common\";\nimport { WalletNetworkSchema } from \"./wallet\";\n\nexport const OPERATOR_REQUEST = \"operator.request\";\n\nexport const OPERATOR_ACTIONS = [\"wallet.create\", \"wallet.policy\", \"wallet.freeze\", \"wallet.unfreeze\", \"wallet.faucet\", \"card.retry\", \"card.refund\"] as const;\nexport type OperatorAction = (typeof OPERATOR_ACTIONS)[number];\n\n/** Beyond `action`, `identity`, `reason` and `outcome`: what each action takes, and of that what it needs. */\nconst TAKES: Record<OperatorAction, { may: readonly string[]; must: readonly string[] }> = {\n \"wallet.create\": { may: [\"network\", \"policy\"], must: [] },\n \"wallet.policy\": { may: [\"network\", \"policy\"], must: [\"policy\"] },\n \"wallet.freeze\": { may: [\"network\"], must: [] },\n \"wallet.unfreeze\": { may: [\"network\"], must: [] },\n \"wallet.faucet\": { may: [], must: [] },\n \"card.retry\": { may: [\"card\"], must: [\"card\"] },\n \"card.refund\": { may: [\"card\"], must: [\"card\"] },\n};\nconst ALWAYS = new Set([\"action\", \"identity\", \"reason\", \"outcome\"]);\n\nexport const OperatorRequestArgsSchema = z\n .strictObject({\n action: z.enum(OPERATOR_ACTIONS).describe(\"The operator action to propose.\"),\n identity: idOf(\"idn\").describe(\"The persona whose wallet or card it is.\"),\n network: WalletNetworkSchema.optional().describe(\"wallet.*: which network's wallet; the testnet when left out.\"),\n policy: z\n .strictObject({\n per_tx_cap_micro_usd: MicroUsdField.nonnegative().optional().describe(\"Most one payment may be.\"),\n daily_cap_micro_usd: MicroUsdField.positive().nullable().optional().describe(\"Most it may pay in a day; null for no daily cap.\"),\n low_balance_micro_usd: MicroUsdField.nonnegative().nullable().optional().describe(\"Balance that raises an alert; null for none.\"),\n })\n .optional()\n .describe(\"wallet.create, wallet.policy: the spending limits, in micro-USD.\"),\n card: idOf(\"vcd\").optional().describe(\"card.retry, card.refund: the card.\"),\n reason: z.string().max(300).optional().describe(\"One sentence on why, shown on the card.\"),\n outcome: z.record(z.string(), z.unknown()).optional().describe(\"Leave this out: set to what the action answered once the person approves.\"),\n })\n .superRefine((args, ctx) => {\n const takes = TAKES[args.action];\n for (const [key, value] of Object.entries(args)) {\n if (value !== undefined && !ALWAYS.has(key) && !takes.may.includes(key)) ctx.addIssue({ code: \"custom\", path: [key], message: `${args.action} does not take ${key}` });\n }\n for (const key of takes.must) {\n if (args[key as keyof typeof args] === undefined) ctx.addIssue({ code: \"custom\", path: [key], message: `${args.action} needs ${key}` });\n }\n });\nexport type OperatorRequest = z.infer<typeof OperatorRequestArgsSchema>;\n\n/** `GET /v1/sessions/{id}/operator_preview?tool_call_id=` (§7.7): the operator card's words, from the store. */\nexport const OperatorPreviewSchema = z.object({\n object: z.literal(\"operator_preview\"),\n tool_call_id: z.string(),\n action: z.enum(OPERATOR_ACTIONS),\n persona: z.object({ id: idOf(\"idn\"), name: z.string() }).nullable(),\n title: z.string(),\n verb: z.string(),\n rows: z.array(z.object({ label: z.string(), value: z.string() })),\n runnable: z.boolean(),\n why: z.string().nullable(),\n});\nexport type OperatorPreview = z.infer<typeof OperatorPreviewSchema>;\n","/** Identity-owned prepaid virtual cards (`canonical-spec.md §45`). */\n\nimport { z } from \"zod\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const CARD_STATUSES = [\"pending_payment\", \"issuing\", \"active\", \"failed\", \"cancelled\", \"refunded\"] as const;\nexport const CardStatusSchema = z.enum(CARD_STATUSES);\nexport type CardStatus = z.infer<typeof CardStatusSchema>;\n\n/** The prepaid product's floor and the hard ceiling; the live bounds come from `card_quote`. */\nexport const CARD_MIN_LOAD_MICRO_USD = 1_000_000;\nexport const CARD_MAX_LOAD_MICRO_USD = 150_000_000;\n/**\n * A load is priced to the issuer as a decimal amount of dollars, so it has to land on a whole\n * cent: 21_000_009 µUSD would be ordered as `21.000009` and the row would then overstate the card\n * by the remainder for the rest of its life.\n */\nexport const CARD_LOAD_GRANULARITY_MICRO_USD = 10_000;\n\n/** `GET …/transactions?limit=`: the legacy defaults, kept. */\nexport const CARD_TRANSACTIONS_DEFAULT_LIMIT = 50;\nexport const CARD_TRANSACTIONS_MAX_LIMIT = 200;\n\nexport const CardSchema = z.object({\n id: idOf(\"vcd\"),\n object: z.literal(\"card\"),\n identity_id: idOf(\"idn\"),\n kind: z.literal(\"prepaid\"),\n status: CardStatusSchema,\n label: z.string().min(1).max(128),\n brand: z.string().nullable(),\n last4: z.string().regex(/^\\d{4}$/).nullable(),\n load_micro_usd: MicroUsdField,\n spent_micro_usd: MicroUsdField,\n currency: z.literal(\"usd\"),\n expires_at: Timestamp.nullable(),\n failure_reason: z.string().max(256).nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Card = z.infer<typeof CardSchema>;\n\nexport const IssueCardSchema = z.object({\n label: CardSchema.shape.label.describe(\"A name for the card, e.g. what it pays for.\"),\n load_micro_usd: MicroUsdField.min(CARD_MIN_LOAD_MICRO_USD)\n .max(CARD_MAX_LOAD_MICRO_USD)\n .multipleOf(CARD_LOAD_GRANULARITY_MICRO_USD)\n .describe(\"The card's spending limit in micro-USD: $1 to $150, in whole cents.\"),\n});\nexport type IssueCard = z.infer<typeof IssueCardSchema>;\n\nexport const CardQuoteRequestSchema = IssueCardSchema.pick({ load_micro_usd: true });\n\nexport const CardQuoteSchema = z.object({\n object: z.literal(\"card_quote\"),\n load_micro_usd: MicroUsdField,\n price_micro_usd: MicroUsdField,\n brand: z.string().nullable(),\n min_load_micro_usd: MicroUsdField,\n max_load_micro_usd: MicroUsdField,\n});\nexport type CardQuote = z.infer<typeof CardQuoteSchema>;\n\n/** The one shape that ever carries a secret; answered by one route, never cached, never stored in a row type. */\nexport const CardCredentialsSchema = z.object({\n object: z.literal(\"card_credentials\"),\n card_id: idOf(\"vcd\"),\n number: z.string().min(1),\n pin: z.string().nullable(),\n cvv: z.string().nullable(),\n expiry: z.string().nullable(),\n url: z.url().nullable(),\n instructions: z.string().nullable(),\n revealed_at: Timestamp,\n});\nexport type CardCredentials = z.infer<typeof CardCredentialsSchema>;\n\nexport const CardTransactionSchema = z.object({\n id: idOf(\"vct\"),\n object: z.literal(\"card_transaction\"),\n card_id: idOf(\"vcd\"),\n amount_micro_usd: MicroUsdField,\n merchant: z.string().nullable(),\n description: z.string().nullable(),\n session_id: idOf(\"ses\").nullable(),\n metadata: Metadata,\n created_at: Timestamp,\n});\nexport type CardTransaction = z.infer<typeof CardTransactionSchema>;\n\nexport const LogCardTransactionSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n merchant: z.string().max(256).optional(),\n description: z.string().max(1024).optional(),\n metadata: Metadata.optional(),\n});\nexport type LogCardTransaction = z.infer<typeof LogCardTransactionSchema>;\n\nexport const ListCardsSchema = z.object({ status: CardStatusSchema.optional() });\n\n/**\n * The stored card: the wire object plus the server columns no projection returns — what was paid,\n * the ledger key that paid it, and the issuer's references. Routes and tools both hold one and hand\n * out `wireCard(record)`, never the record.\n */\nexport interface CardRecord extends Card {\n price_micro_usd: number;\n ledger_entry_id: string | null;\n provider_product_ref: string | null;\n provider_order_ref: string | null;\n idempotency_key: string | null;\n}\n\nexport function wireCard(record: CardRecord): Card {\n const {\n price_micro_usd: _price,\n ledger_entry_id: _ledger,\n provider_product_ref: _product,\n provider_order_ref: _order,\n idempotency_key: _key,\n ...card\n } = record;\n return card;\n}\n","/**\n * The proxy call trace (`canonical-spec §26.5`, ADR-0745, migration 0077) — what a call to\n * `/v1/proxy/*` actually said, beside the ledger debit that says what it cost.\n *\n * A hosted agent turn leaves a transcript. A proxy call left exactly one row in the whole schema:\n * its `ledger_entry` debit. This object is the other half — the same call's prompt, reply, routing\n * and upstream attribution. Since ADR-0762 it also records every hosted-harness model call\n * (`source: \"harness\"`), literally and joinably to its session and event `seq`, and keeps it:\n * `expires_at` is null on new rows and the bodies are inline (`content_scope: full`, ADR-0794).\n *\n * `id` IS THE JOIN. It is the request id the proxy already uses three ways — `x-request-id`, the\n * reply's message id, and the ledger entry's `idempotency_key` — so a trace and its debit need no\n * correlation column to find each other.\n */\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, WindowSchema, idOf } from \"./common\";\n\n/**\n * Which door the call came in by. `anthropic` / `openai` are the two public proxy envelopes; `native`\n * is a hosted harness's own call through `ChatTransport`, which has no public envelope (ADR-0762).\n */\nexport const ProxyDialectSchema = z.enum([\"anthropic\", \"openai\", \"native\"]);\nexport type ProxyDialect = z.infer<typeof ProxyDialectSchema>;\n\n/**\n * Where a trace row's bodies are, written onto the row itself (ADR-0762, superseding ADR-0745's\n * configurable scope — capture is always full now).\n *\n * `full` — the bodies are inline on the row, in Postgres: every new row (ADR-0794 — records in\n * Postgres, files in object storage). `object` was ADR-0762's object-storage form, never shipped to\n * production and no longer written or read back; `metadata` survives only on rows from before\n * ADR-0762. Both remain in the enum so an old row still parses.\n */\nexport const ProxyTraceContentScopeSchema = z.enum([\"full\", \"metadata\", \"object\"]);\nexport type ProxyTraceContentScope = z.infer<typeof ProxyTraceContentScopeSchema>;\n\n/** A tool call as the model made it: its id is what the tool's own events join on. */\nconst TraceToolCall = z.object({ id: z.string().optional(), name: z.string(), arguments: z.string() });\n\n/**\n * One prompt as the transport saw it: the vendor-neutral `ChatMessage` shape, never a dialect's\n * envelope, and LITERAL since ADR-0762 — assistant `tool_calls` with their ids, `tool_call_id` on a\n * tool result, image links on a user turn, the full tool schema array, the output allowance. Rows\n * from before ADR-0762 carry `{role, content}` messages and `tool_names` only.\n */\nexport const ProxyTraceRequestSchema = z.object({\n model: z.string().optional(),\n window: WindowSchema.optional(),\n system: z.string(),\n messages: z.array(\n z.looseObject({\n role: z.string(),\n content: z.string(),\n tool_calls: z.array(z.looseObject({ id: z.string(), name: z.string() })).optional(),\n tool_call_id: z.string().optional(),\n }),\n ),\n tools: z\n .array(z.object({ name: z.string(), description: z.string(), parameters: z.record(z.string(), z.unknown()) }))\n .optional(),\n tool_schema_hash: z.string().optional(),\n max_output_tokens: z.number().int().optional(),\n tool_names: z.array(z.string()).optional(),\n});\n\n/**\n * One reply as it was assembled from the stream, whichever dialect it was then rendered into —\n * including the model's reasoning and any provider `reasoning_details` blocks, verbatim (ADR-0793).\n */\nexport const ProxyTraceResponseSchema = z.object({\n text: z.string(),\n reasoning: z.string().optional(),\n reasoning_details: z.array(z.unknown()).optional(),\n tool_calls: z.array(TraceToolCall),\n /** A call that threw, was abandoned or never completed (ADR-0794): the reply is what streamed before. */\n is_error: z.literal(true).optional(),\n /** The error's class name — never its message — or `incomplete` for a stream that just stopped. */\n error_class: z.string().optional(),\n partial: z.literal(true).optional(),\n});\n\n/**\n * Lowercase hex sha-256 of the stored body — present on every row. Since ADR-0762 nothing is\n * truncated, so it is the hash of the whole body: the request with its tool array replaced by\n * `tool_schema_hash`, and the reply. It is also the body's object-storage key.\n */\nconst Sha256 = z.string().regex(/^[0-9a-f]{64}$/);\n\nexport const ProxyCallTraceSchema = z.object({\n /** The request id: also `x-request-id`, the reply's `id`, and the ledger entry's idempotency key. */\n id: idOf(\"req\"),\n object: z.literal(\"proxy_call_trace\"),\n dialect: ProxyDialectSchema,\n /** The principal that made the call (§17). An API key here is the answer to \"who sent this\". */\n actor: PrincipalSchema,\n /** The public model id the caller asked for. */\n model: z.string(),\n window: WindowSchema,\n /** The model the reply said served it — where `vetta/auto` resolves — or null if it named none. */\n resolved_model: z.string().nullable(),\n /**\n * The serving provider and the gateway's own generation id. Null on every row written before the\n * adapter stops dropping them (Track A); together they are what lets an upstream invoice line be\n * matched back to an organization, a key and a ledger entry.\n */\n provider: z.string().nullable(),\n generation_id: z.string().nullable(),\n stop: z.enum([\"end_turn\", \"tool_use\", \"length\"]).nullable(),\n usage: TokenUsageSchema,\n /** What the customer was charged, µUSD. The ledger entry is the authority; this is its copy. */\n billed_micro_usd: MicroUsdField.nullable(),\n /** What the vendor said it cost, µUSD. A CROSS-CHECK, NEVER A DEBIT. */\n vendor_cost_micro_usd: MicroUsdField.nullable(),\n duration_ms: z.number().int().nonnegative().nullable(),\n content_scope: ProxyTraceContentScopeSchema,\n /** `proxy` — a `/v1/proxy/*` call; `harness` — a hosted harness's own model call (ADR-0762). */\n source: z.enum([\"proxy\", \"harness\"]),\n /** The session the call belongs to: a harness call's, or a sandbox token's `sub` on the proxy. */\n session_id: z.string().nullable(),\n /**\n * The `seq` of the call's `span.model_request.end` event — or of its `.start` when the call failed\n * or its `.end` was withheld (ADR-0794). Null on the proxy, which writes no event.\n */\n seq: z.number().int().nullable(),\n /** The board card the session was woken for (`session.metadata.board.card_id`), or null. */\n board_card_id: z.string().nullable(),\n /** The ids of the tool calls this reply made — the join to the `tool.*` events they caused. */\n tool_call_ids: z.array(z.string()),\n /** sha-256 of the canonical JSON of the tool schema array the model was offered, or null. */\n tool_schema_hash: Sha256.nullable(),\n request_sha256: Sha256,\n response_sha256: Sha256,\n /** The UTF-8 size of each stored body. */\n request_bytes: z.number().int().nonnegative(),\n response_bytes: z.number().int().nonnegative(),\n /** Inline in `full` scope — every new row. Null on a legacy `metadata` or `object` row. */\n request: ProxyTraceRequestSchema.nullable(),\n response: ProxyTraceResponseSchema.nullable(),\n /** Always false since ADR-0762 (nothing is cut); true only on rows from before it. */\n truncated: z.boolean(),\n created_at: Timestamp,\n /** When the reaper deletes this row. Null since ADR-0762: model I/O is kept, not expired. */\n expires_at: Timestamp.nullable(),\n});\nexport type ProxyCallTrace = z.infer<typeof ProxyCallTraceSchema>;\n","/**\n * A review (`canonical-spec §47`, ADR-0796, migration 0083) — a person's verdict on agent work given\n * outside Vetta's approval box: a post rejected in an app's queue, a caption edited before it ships.\n * The approval box's own decisions are `tool.confirm.resolved` events (ADR-0764); this is the same\n * judgement from everywhere else, joined to the session and board card by the files it names.\n */\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const ReviewDecisionSchema = z.enum([\"approve\", \"reject\", \"edit\"]);\nexport type ReviewDecision = z.infer<typeof ReviewDecisionSchema>;\n\n/** A reviewed field set (`{caption, title}` for a post); free-form, bounded. */\nconst Fields = z.record(z.string().max(100), z.unknown()).nullable().optional();\n\n/** `POST /v1/reviews`. The actor is the calling principal and is never part of the body. */\nexport const CreateReviewSchema = z.object({\n decision: ReviewDecisionSchema,\n reason: z.string().max(4_000).nullable().optional(),\n file_ids: z.array(idOf(\"fil\")).max(50).optional(),\n session_id: idOf(\"ses\").optional(),\n subject: z.record(z.string().max(100), z.unknown()).optional(),\n before: Fields,\n after: Fields,\n});\nexport type CreateReview = z.infer<typeof CreateReviewSchema>;\n\n/** What `POST /v1/reviews` answers: the review and what it was linked to. */\nexport interface ReviewCreated {\n id: string;\n object: \"review\";\n session_id: string | null;\n board_card_id: string | null;\n}\n","/**\n * THE COMPANY'S CRM AND CALENDAR (`canonical-spec §63`, ADR-1820). One person or client per row, with\n * a stage, a value and the next step, and one timeline under each. A meeting is a dated line on that\n * timeline (with no contact, it is the company's own), so the Calendar is a view of the same rows:\n * meetings and the follow-ups due, never a second copy.\n */\nimport { z } from \"zod\";\nimport { idOf, Timestamp } from \"./common\";\n\nexport const CRM_STAGES = [\"lead\", \"talking\", \"proposal\", \"won\", \"lost\"] as const;\nexport const CrmStageSchema = z.enum(CRM_STAGES);\nexport type CrmStage = z.infer<typeof CrmStageSchema>;\n\nexport const CRM_ACTIVITY_KINDS = [\"note\", \"email\", \"call\", \"meeting\", \"stage\"] as const;\nexport const CrmActivityKindSchema = z.enum(CRM_ACTIVITY_KINDS);\nexport type CrmActivityKind = z.infer<typeof CrmActivityKindSchema>;\n\n/** How many contacts a company's list reads: far past a real pipeline, and a bound on one request. */\nexport const CRM_MAX_LISTED = 5000;\n\nexport const CrmContactSchema = z.object({\n id: idOf(\"ctc\"),\n object: z.literal(\"crm_contact\"),\n name: z.string(),\n company: z.string().nullable(),\n email: z.string().nullable(),\n phone: z.string().nullable(),\n stage: CrmStageSchema,\n /** What the client is worth, integer micro-USD (§2). */\n value_micro_usd: z.number().int().nonnegative().nullable(),\n next_step: z.string().nullable(),\n next_step_at: Timestamp.nullable(),\n /** Where they came from, in a few words: \"referral\", \"site\", \"outreach\". */\n source: z.string().nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type CrmContact = z.infer<typeof CrmContactSchema>;\n\nexport const CrmActivitySchema = z.object({\n id: idOf(\"cta\"),\n object: z.literal(\"crm_activity\"),\n contact_id: idOf(\"ctc\").nullable(),\n kind: CrmActivityKindSchema,\n body: z.string(),\n /** When it happened, or for a meeting when it starts. */\n at: Timestamp,\n ends_at: Timestamp.nullable(),\n /** The `agt_` id of the agent that wrote it; `null` is a person. */\n by: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type CrmActivity = z.infer<typeof CrmActivitySchema>;\n\n/** One contact and its whole timeline, newest first. */\nexport const CrmContactDetailSchema = CrmContactSchema.extend({ activity: z.array(CrmActivitySchema) });\nexport type CrmContactDetail = z.infer<typeof CrmContactDetailSchema>;\n\nconst Name = z.string().trim().min(1).max(200);\nconst Line = z.string().trim().min(1).max(500);\nconst Email = z.email().max(320).transform((email) => email.toLowerCase());\nconst Phone = z.string().trim().min(3).max(40);\n\nconst contactFields = {\n company: Name.nullable(),\n email: Email.nullable(),\n phone: Phone.nullable(),\n stage: CrmStageSchema,\n value_micro_usd: z.number().int().nonnegative().nullable(),\n next_step: Line.nullable(),\n next_step_at: z.iso.datetime({ offset: true }).nullable(),\n source: z.string().trim().min(1).max(80).nullable(),\n};\n\n/** Adding an email already on file updates that contact: a retry or a second agent never doubles one. */\nexport const CreateCrmContactSchema = z.strictObject({ name: Name, ...z.object(contactFields).partial().shape });\nexport type CreateCrmContact = z.output<typeof CreateCrmContactSchema>;\n\nexport const UpdateCrmContactSchema = z.strictObject({ name: Name, ...contactFields }).partial();\nexport type UpdateCrmContact = z.output<typeof UpdateCrmContactSchema>;\n\nconst meetingEnds = (body: { at?: string | undefined; ends_at?: string | null | undefined }, issue: z.RefinementCtx) => {\n if (body.at && body.ends_at && Date.parse(body.ends_at) <= Date.parse(body.at)) issue.addIssue({ code: \"custom\", path: [\"ends_at\"], message: \"must be after it starts\" });\n};\n\n/** A person or an agent never writes a `stage` line: the contact's own move does (`updateCrmContact`). */\nexport const CreateCrmActivitySchema = z\n .strictObject({\n contact_id: idOf(\"ctc\").nullable().optional(),\n kind: z.enum([\"note\", \"email\", \"call\", \"meeting\"]),\n body: z.string().trim().min(1).max(4000),\n at: z.iso.datetime({ offset: true }).optional(),\n ends_at: z.iso.datetime({ offset: true }).nullable().optional(),\n })\n .superRefine((body, issue) => {\n meetingEnds(body, issue);\n if (body.kind === \"meeting\" && !body.at) issue.addIssue({ code: \"custom\", path: [\"at\"], message: \"a meeting needs its start\" });\n if (body.kind !== \"meeting\" && !body.contact_id) issue.addIssue({ code: \"custom\", path: [\"contact_id\"], message: \"only a meeting stands without a contact\" });\n });\nexport type CreateCrmActivity = z.output<typeof CreateCrmActivitySchema>;\n\n/** Moving or renaming a meeting, or correcting a note. */\nexport const UpdateCrmActivitySchema = z\n .strictObject({ body: z.string().trim().min(1).max(4000), at: z.iso.datetime({ offset: true }), ends_at: z.iso.datetime({ offset: true }).nullable() })\n .partial()\n .superRefine((body, issue) => {\n meetingEnds(body, issue);\n // A new end alone can't be checked here, and could land before the start it doesn't name.\n if (body.ends_at && !body.at) issue.addIssue({ code: \"custom\", path: [\"at\"], message: \"give the start with the end\" });\n });\nexport type UpdateCrmActivity = z.output<typeof UpdateCrmActivitySchema>;\n\n/** One thing on the Calendar: a meeting, or a contact's next step on the day it is due. */\nexport const CalendarItemSchema = z.object({\n object: z.literal(\"calendar_item\"),\n kind: z.enum([\"meeting\", \"follow_up\"]),\n /** A meeting's `cta_` id, or the `ctc_` id of the contact the follow-up belongs to. */\n id: z.string(),\n contact_id: idOf(\"ctc\").nullable(),\n contact_name: z.string().nullable(),\n title: z.string(),\n at: Timestamp,\n ends_at: Timestamp.nullable(),\n by: z.string().nullable(),\n});\nexport type CalendarItem = z.infer<typeof CalendarItemSchema>;\n","/** Paid advertising managed through an identity-owned connected account (§51). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField } from \"./common\";\n\nexport const AdProviderSchema = z.enum([\"google\"]);\nexport type AdProvider = z.infer<typeof AdProviderSchema>;\n\nexport const AdCampaignStatusSchema = z.enum([\"enabled\", \"paused\", \"removed\", \"unknown\"]);\nexport type AdCampaignStatus = z.infer<typeof AdCampaignStatusSchema>;\n\nexport const AdCampaignSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"ad_campaign\"),\n provider: AdProviderSchema,\n connection_id: z.string().min(1),\n customer_id: z.string().regex(/^\\d{10}$/),\n resource_name: z.string().min(1),\n name: z.string().min(1),\n type: z.literal(\"search\"),\n status: AdCampaignStatusSchema,\n /** Null for provider campaigns with no ad; list and status reads are campaign-based. */\n final_url: z.url().nullable(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n start_date: z.iso.date(),\n end_date: z.iso.date(),\n});\nexport type AdCampaign = z.infer<typeof AdCampaignSchema>;\n\nexport const AdCampaignInsightsSchema = z.object({\n object: z.literal(\"ad_campaign_insights\"),\n provider: AdProviderSchema,\n campaign_id: z.string().min(1),\n impressions: z.number().int().nonnegative(),\n clicks: z.number().int().nonnegative(),\n conversions: z.number().nonnegative(),\n spend_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type AdCampaignInsights = z.infer<typeof AdCampaignInsightsSchema>;\n","/** A revocable credential and policy for the Vetta MCP endpoint. */\nimport { z } from \"zod\";\nimport { idOf, Timestamp } from \"./common\";\nimport { ScopeSchema } from \"./org\";\n\nexport const McpSessionSchema = z.object({\n id: idOf(\"mcs\"),\n object: z.literal(\"mcp_session\"),\n name: z.string().min(1).max(128),\n identity_id: idOf(\"idn\").nullable(),\n /** The person whose connected agent this is (ADR-1810). `null` on a session an operator made for a system. */\n member_id: idOf(\"usr\").nullable().default(null),\n scopes: z.array(ScopeSchema),\n allowed_tools: z.array(z.string().regex(/^[a-z0-9_]+$/).max(128)),\n /** Non-sensitive display fragment; the bearer itself is returned only when minted. */\n prefix: z.string().startsWith(\"mcp_\").max(12),\n expires_at: Timestamp,\n revoked_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\n\nexport type McpSession = z.infer<typeof McpSessionSchema>;\n\n/** A connected agent names no tools (§20.11): its scopes bound it. Anything else may call only what it names. */\nexport const mcpSessionAllows = (session: Pick<McpSession, \"allowed_tools\" | \"member_id\">, tool: string): boolean =>\n typeof session.member_id === \"string\" || session.allowed_tools.includes(tool);\n","/**\n * The dashboard's short-lived bearer credential (`canonical-spec.md §20`). It is **signed, not\n * stored**: an HMAC over a JSON payload, so a login writes no row, a logout needs no revocation\n * table, and the credential cannot outlive its `exp`.\n *\n * It is presented in `Authorization: Bearer` exactly like an API key, and like an API key it is a\n * server-side secret — the dashboard keeps it in an httpOnly session and never sends it to a\n * browser (ADR-0017).\n */\nimport { VettaError } from \"./errors\";\nimport { SCOPES, type Role, type Scope } from \"./schema/index\";\n\n/** `test` or `live` — the tier a credential spends in. Mirrors the column `api_key.mode`. */\nexport type KeyMode = \"test\" | \"live\";\n\nexport const SESSION_TOKEN_PREFIX = \"vt_\";\n/** Thirty days. The dashboard has no refresh credential, so this is also its absolute sign-in. */\nexport const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;\n\nexport interface SessionClaims {\n /** The `usr_` member id in `org`, or the provider subject when the person has no membership. */\n sub: string;\n email: string;\n /** `null` until the person picks or creates an organization (`canonical-spec.md §20.4`). */\n org: string | null;\n /** The member's role in `org`, and what `scopes` was derived from. `null` when `org` is. */\n role: Role | null;\n mode: KeyMode;\n /** Derived from `role`, never chosen by the caller (`canonical-spec.md §20.4`). */\n scopes: Scope[];\n /** Epoch seconds. */\n exp: number;\n /**\n * MINTED FOR A SANDBOX, NOT FOR A PERSON. A class-B harness runs as a process inside a customer's\n * micro-VM and needs a credential to reach our metered model door; this marks that token so\n * `authenticate` gives it a `system` principal instead of inventing a `usr_` that names a `ses_`.\n *\n * It is deliberately a claim rather than an inference from `scopes`: the day a person's token\n * happens to carry one scope, an inference would silently reclassify them.\n */\n sandbox?: boolean;\n /**\n * MINTED FOR ONE AGENT'S TURN: the `agt_` id whose platform tools this token opens\n * (`apps/runtime-do/src/platform-tools.ts`). Like `sandbox`, it names a subsystem, never a person,\n * and it reaches only the routes marked `agent: true` (`apps/api/src/router.ts`). That list is the\n * boundary. `scopes` only has to cover it.\n */\n agent?: string;\n /**\n * MINTED FOR THE CEO'S TURN, NOT FOR A PERSON (ADR-1100): the `agt_` id of the agent the\n * control-plane credential is bound to (ADR-1097). Like `sandbox`, it names a subsystem, so the\n * token files as `system:agent:<id>` and is never `ctx.user`. Its `scopes` are the least of what\n * every person who drove the session holds, within `ORCHESTRATOR_SCOPES`, derived by the runtime\n * when it mints (`apps/runtime-do/src/drivers.ts`).\n */\n orchestrator?: string;\n}\n\n/**\n * The scopes an agent's platform token carries: enough for every route marked `agent: true`, and\n * the API's test checks they still are. They do not limit the token. The route list does, because\n * `agents:read` alone would open every persona's inbox (ADR-1096).\n */\nexport const AGENT_TOKEN_SCOPES: Scope[] = [\"billing:read\", \"agents:read\", \"agents:write\"];\n\n/**\n * Role → scopes (`canonical-spec.md §20.4`). A plain member gets everything except the three that\n * can spend money, mint credentials or redirect the org's outbound traffic; `admin` implies the\n * rest, so an owner needs the one entry. Derived here and never taken from the caller. Here rather\n * than in `apps/api` because the runtime derives the CEO's turn from it too.\n */\nconst MEMBER_DENIED: Scope[] = [\"admin\", \"billing:write\", \"webhooks:*\"];\n\nexport function scopesForRole(role: Role): Scope[] {\n if (role === \"owner\" || role === \"admin\") return [\"admin\"];\n return SCOPES.filter((scope) => !MEMBER_DENIED.includes(scope));\n}\n\n/**\n * The most the CEO's turn may hold (ADR-0190): everything a person can drive, minus `admin`, which\n * would let it mint keys and seal credentials — the two that turn a prompt injection into a\n * standing one. A turn holds less when the people driving it do (ADR-1100).\n */\nexport const ORCHESTRATOR_SCOPES: readonly Scope[] = [\n \"agents:read\",\n \"agents:write\",\n \"sessions:read\",\n \"sessions:write\",\n \"computers:write\",\n \"files:read\",\n \"files:write\",\n \"billing:read\",\n \"billing:write\",\n \"webhooks:*\",\n \"audit:read\",\n];\n\nconst encoder = new TextEncoder();\n\nfunction b64url(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes)).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction unb64url(text: string): Uint8Array {\n const padded = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nasync function sign(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload))));\n}\n\n/** Length-checked before the byte compare, so a wrong-length signature cannot be timed (§14). */\nfunction equalsConstantTime(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index += 1) difference |= a.charCodeAt(index) ^ b.charCodeAt(index);\n return difference === 0;\n}\n\nexport async function mintSessionToken(secret: string, claims: SessionClaims): Promise<string> {\n const payload = b64url(encoder.encode(JSON.stringify(claims)));\n return `${SESSION_TOKEN_PREFIX}${payload}.${await sign(secret, payload)}`;\n}\n\n/** Bad signature, bad shape and expiry are one answer: `unauthorized`, naming no internal detail. */\nexport async function readSessionToken(\n secret: string | null,\n token: string,\n nowSeconds: number,\n): Promise<SessionClaims> {\n if (secret === null || secret === \"\") {\n throw new VettaError(\"feature_not_configured\", \"dashboard sign-in is not configured\");\n }\n const [payload, signature] = token.slice(SESSION_TOKEN_PREFIX.length).split(\".\");\n if (!payload || !signature) throw new VettaError(\"unauthorized\", \"invalid session token\");\n if (!equalsConstantTime(await sign(secret, payload), signature)) {\n throw new VettaError(\"unauthorized\", \"invalid session token\");\n }\n const claims = JSON.parse(new TextDecoder().decode(unb64url(payload))) as SessionClaims;\n if (typeof claims.exp !== \"number\" || claims.exp <= nowSeconds) {\n throw new VettaError(\"unauthorized\", \"this sign-in has expired; sign in again\");\n }\n // One token speaks for one kind of caller: a box, an agent's turn, the CEO's turn, or a person.\n const named = (claim: unknown): boolean => claim !== undefined;\n const kinds = [claims.sandbox === true, named(claims.agent), named(claims.orchestrator)].filter(Boolean).length;\n const blank = [claims.agent, claims.orchestrator].some((claim) => named(claim) && (typeof claim !== \"string\" || claim === \"\"));\n if (kinds > 1 || blank) throw new VettaError(\"unauthorized\", \"invalid session token\");\n return claims;\n}\n","/**\n * The company's logo, as the SVG a person or an agent wrote (`canonical-spec §20.7`, ADR-1085).\n * `checkLogoSvg` is the only gate: the API's `PATCH /v1/organizations/{id}` and the agent's\n * `company.set_logo` both call it, and store what it answers.\n *\n * An allow-list read by a small tokenizer, not a DOM (a Worker has none) and not a deny-list: every\n * byte must be an allowed element, an allowed attribute with a quoted value of plain characters,\n * whitespace, or words inside `<title>`/`<desc>`. Anything the tokenizer cannot account for is\n * refused, with a sentence the writer can act on.\n */\n\nconst MAX_BYTES = 16 * 1024;\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nconst ELEMENTS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\", \"defs\",\n \"linearGradient\", \"radialGradient\", \"stop\", \"title\", \"desc\", \"clipPath\", \"mask\",\n]);\n\nconst ATTRIBUTES = new Set([\n \"viewBox\", \"xmlns\", \"width\", \"height\", \"x\", \"y\", \"x1\", \"y1\", \"x2\", \"y2\", \"cx\", \"cy\", \"r\", \"rx\",\n \"ry\", \"d\", \"points\", \"fill\", \"stroke\", \"stroke-width\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-dasharray\", \"opacity\", \"fill-opacity\", \"stroke-opacity\", \"fill-rule\",\n \"clip-rule\", \"transform\", \"offset\", \"stop-color\", \"stop-opacity\", \"gradientUnits\",\n \"gradientTransform\", \"id\", \"clip-path\", \"mask\", \"preserveAspectRatio\", \"fx\", \"fy\", \"spreadMethod\",\n \"role\", \"aria-hidden\",\n]);\n\n/** Elements that hold words and nothing else. */\nconst WORDS = new Set([\"title\", \"desc\"]);\n\nconst HINTS: Record<string, string> = {\n text: \"draw the letters as paths\",\n tspan: \"draw the letters as paths\",\n textPath: \"draw the letters as paths\",\n image: \"draw it with shapes; a logo embeds no image\",\n foreignObject: \"draw it with shapes\",\n script: \"a logo runs no code\",\n style: \"set fill and stroke as attributes on each shape\",\n use: \"draw the shape again where it repeats\",\n a: \"a logo links nowhere\",\n};\n\nconst OPEN = /<([A-Za-z][\\w:.-]*)/y;\nconst CLOSE = /<\\/([A-Za-z][\\w:.-]*)[ \\t\\r\\n]*>/y;\nconst ATTRIBUTE = /[ \\t\\r\\n]+([A-Za-z_:][\\w:.-]*)[ \\t\\r\\n]*=[ \\t\\r\\n]*(?:\"([^\"]*)\"|'([^']*)')/y;\n/** Characters XML refuses, or Postgres `text` does (NUL). Matching them is the point. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/;\nconst TAG_END = /[ \\t\\r\\n]*(\\/?)>/y;\nconst LOCAL_URL = /url\\(#[A-Za-z_][\\w.-]*\\)/g;\nconst VALUE_CHARS = /^[\\w \\t\\r\\n#.,%()+-]*$/;\nconst VIEW_BOX = /^\\s*-?[\\d.]+(?:[\\s,]+-?[\\d.]+){3}\\s*$/;\n/** A checked root's start tag: no value holds `>` or `=`, so this reads only its own attributes. */\nconst ROOT_NS = /^<svg[^>]*\\sxmlns\\s*=/;\n\nexport type LogoCheck = { ok: true; svg: string } | { ok: false; reason: string };\n\n/**\n * An `<svg>` with `xmlns` on its root. The studio draws a logo as an `<img>` of a data URL, and a\n * browser draws an SVG without its namespace there as nothing. The web calls it too, on a logo an\n * agent proposes, before any check has run.\n */\nexport function withSvgNamespace(input: string): string {\n const svg = input.trim();\n return !/^<svg[\\s>]/.test(svg) || ROOT_NS.test(svg) ? svg : `<svg xmlns=\"${SVG_NS}\"${svg.slice(\"<svg\".length)}`;\n}\n\n/** The answer always carries `xmlns` on its root (`withSvgNamespace`). */\nexport function checkLogoSvg(input: string): LogoCheck {\n const svg = input.trim();\n const reason = firstProblem(svg);\n if (reason !== undefined) return { ok: false, reason };\n return { ok: true, svg: withSvgNamespace(svg) };\n}\n\nfunction firstProblem(svg: string): string | undefined {\n if (new TextEncoder().encode(svg).length > MAX_BYTES) {\n return `the logo is over 16 KB: simplify it — fewer points, shorter paths`;\n }\n // XML's own whitespace only, in tags and between them: a no-break space reads as a separator to a\n // regex and as an error to a browser, and a NUL is refused by the database.\n if (CONTROL.test(svg)) return \"control characters are not allowed: remove them\";\n if (!svg.startsWith(\"<svg\")) return `the logo must be one <svg viewBox=\"…\">…</svg> element, with nothing around it`;\n const open: string[] = [];\n let at = 0;\n let closed = false;\n while (at < svg.length) {\n const lt = svg.indexOf(\"<\", at);\n const text = svg.slice(at, lt === -1 ? svg.length : lt);\n const problem = textProblem(text, open.at(-1));\n if (problem) return problem;\n if (lt === -1) break;\n if (closed) return \"nothing may follow the closing </svg>\";\n const special = declaration(svg, lt);\n if (special) return special;\n CLOSE.lastIndex = lt;\n const close = CLOSE.exec(svg);\n if (close) {\n const name = close[1] ?? \"\";\n const expected = open.pop();\n if (expected !== name) return expected ? `</${name}> closes <${expected}>: close it with </${expected}>` : `</${name}> closes nothing`;\n closed = open.length === 0;\n at = CLOSE.lastIndex;\n continue;\n }\n const tag = readElement(svg, lt, open);\n if (typeof tag === \"string\") return tag;\n if (!tag.selfClosing) open.push(tag.name);\n at = tag.end;\n }\n return open.length > 0 ? `<${open.at(-1)}> is never closed` : undefined;\n}\n\nfunction textProblem(text: string, parent: string | undefined): string | undefined {\n if (text.includes(\"&\")) return \"entities (&…;) are not allowed: write the character itself, or leave it out\";\n if (text.trim() !== \"\" && !(parent !== undefined && WORDS.has(parent))) {\n return \"words outside <title> or <desc> are not allowed: draw letters as paths\";\n }\n return undefined;\n}\n\nfunction declaration(svg: string, lt: number): string | undefined {\n if (svg.startsWith(\"<!--\", lt)) return \"comments are not allowed: remove them\";\n if (svg.startsWith(\"<![CDATA[\", lt)) return \"CDATA is not allowed: remove it\";\n if (svg.startsWith(\"<!\", lt)) return \"a DOCTYPE or entity declaration is not allowed: remove it\";\n if (svg.startsWith(\"<?\", lt)) return \"processing instructions (<?…?>) are not allowed: remove them\";\n return undefined;\n}\n\n/** One start tag at `lt`: its name, whether it closes itself, and where it ends — or why it is refused. */\nfunction readElement(svg: string, lt: number, open: string[]): { name: string; selfClosing: boolean; end: number } | string {\n OPEN.lastIndex = lt;\n const name = OPEN.exec(svg)?.[1];\n if (name === undefined) return \"a `<` must start an element: write shapes, not markup fragments\";\n const refused = elementProblem(name, open);\n if (refused) return refused;\n const attributes = new Map<string, string>();\n let at = OPEN.lastIndex;\n for (;;) {\n TAG_END.lastIndex = at;\n const end = TAG_END.exec(svg);\n if (end) {\n const selfClosing = end[1] === \"/\";\n const root = name === \"svg\" ? rootProblem(attributes, selfClosing) : undefined;\n return root ?? { name, selfClosing, end: TAG_END.lastIndex };\n }\n ATTRIBUTE.lastIndex = at;\n const attribute = ATTRIBUTE.exec(svg);\n if (!attribute) return `<${name}>'s attributes must each be name=\"value\", quoted, separated by spaces`;\n const [, key = \"\", double, single] = attribute;\n const value = double ?? single ?? \"\";\n if (attributes.has(key)) return `\\`${key}\\` is set twice on <${name}>: keep one`;\n const problem = attributeProblem(name, key, value);\n if (problem) return problem;\n attributes.set(key, value);\n at = ATTRIBUTE.lastIndex;\n }\n}\n\nfunction elementProblem(name: string, open: string[]): string | undefined {\n const parent = open.at(-1);\n if (parent === undefined && name !== \"svg\") return `the logo must be one <svg> element, not <${name}>`;\n if (parent !== undefined && name === \"svg\") return \"one <svg> only: group shapes with <g>, not a nested <svg>\";\n if (parent !== undefined && WORDS.has(parent)) return `<${parent}> holds words only, not <${name}>`;\n if (ELEMENTS.has(name)) return undefined;\n const hint = HINTS[name] ?? (name.startsWith(\"animate\") || name === \"set\" ? \"a logo holds still\" : undefined);\n if (hint) return `<${name}> is not allowed: ${hint}`;\n const lower = [...ELEMENTS].find((allowed) => allowed.toLowerCase() === name.toLowerCase());\n if (lower) return `<${name}> must be written <${lower}>`;\n return `<${name}> is not allowed: use only ${[...ELEMENTS].map((element) => `<${element}>`).join(\", \")}`;\n}\n\nfunction attributeProblem(element: string, name: string, value: string): string | undefined {\n if (/^on/i.test(name)) return `\\`${name}\\` is not allowed: a logo runs no code`;\n if (/href$/i.test(name)) return `\\`${name}\\` is not allowed: a logo links to nothing; draw the shape where it is used`;\n if (name === \"style\") return \"`style` is not allowed: set fill, stroke and opacity as attributes\";\n if (name === \"class\") return \"`class` is not allowed: set fill and stroke as attributes on each shape\";\n if (!ATTRIBUTES.has(name)) return `\\`${name}\\` is not allowed on <${element}>: drop it (presentation and geometry attributes only)`;\n if (name === \"xmlns\") return value === SVG_NS ? undefined : `xmlns must be \"${SVG_NS}\" or left out`;\n const lower = value.toLowerCase();\n if (lower.includes(\"javascript:\")) return `\\`${name}\\` holds a script: a logo runs no code`;\n if (lower.includes(\"data:\")) return `\\`${name}\\` embeds data: draw it with shapes instead`;\n if (lower.includes(\"http\")) return `\\`${name}\\` points to the web: a logo loads nothing`;\n if (value.includes(\"&\")) return `\\`${name}\\` holds an entity (&…;): write the character itself`;\n if (value.includes(\"<\")) return `\\`${name}\\` holds a \\`<\\`: values are numbers, colours and names`;\n if (lower.replace(LOCAL_URL, \"\").includes(\"url(\")) return `\\`${name}\\` may reference only url(#id), written exactly so`;\n if (!VALUE_CHARS.test(value)) return `\\`${name}\\` holds a character a logo does not need: use numbers, names, #colours and url(#id)`;\n return undefined;\n}\n\nfunction rootProblem(attributes: Map<string, string>, selfClosing: boolean): string | undefined {\n const viewBox = attributes.get(\"viewBox\");\n if (viewBox === undefined) return `the <svg> needs a viewBox, such as viewBox=\"0 0 64 64\"`;\n if (!VIEW_BOX.test(viewBox)) return `viewBox must be four numbers, such as \"0 0 64 64\"`;\n if (selfClosing) return \"the <svg> is empty: draw the mark inside it\";\n return undefined;\n}\n","import { z } from \"zod\";\nimport { BRAND_TYPEFACES, BrandKitSchema, type BrandKit } from \"./schema/org\";\n\n/**\n * THE COMPANY'S BRAND KIT, DRAWN IN CODE (ADR-1163). One colour chooses it: the palette is built\n * around that colour — a dark, the colour itself, a tint, a paper and an accent — in one of a few\n * harmonies. The CEO names the colour (`company.set_brand`); the code draws the swatches, so a kit\n * always reads, whatever the model would have picked. The same colour and harmony, the same kit.\n */\n\n/** Where the accent sits from the colour, one harmony per shuffle. */\nconst HARMONIES = [165, 40, 120, 200] as const;\nexport const BRAND_HARMONIES = HARMONIES.length;\n\ntype Rgb = [number, number, number];\n\nconst hexToRgb = (hex: string): Rgb => {\n const full = hex.length === 4 ? `#${[...hex.slice(1)].map((c) => c + c).join(\"\")}` : hex;\n return [0, 2, 4].map((at) => parseInt(full.slice(1 + at, 3 + at), 16)) as Rgb;\n};\n\nconst hueOf = ([r, g, b]: Rgb): number => {\n const [rn, gn, bn] = [r / 255, g / 255, b / 255];\n const max = Math.max(rn, gn, bn);\n const d = max - Math.min(rn, gn, bn);\n if (d === 0) return 0;\n const h = max === rn ? (gn - bn) / d + (gn < bn ? 6 : 0) : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4;\n return Math.round(h * 60);\n};\n\nconst hslToHex = (h: number, s: number, l: number): string => {\n const sn = s / 100;\n const ln = l / 100;\n const k = (n: number) => (n + h / 30) % 12;\n const a = sn * Math.min(ln, 1 - ln);\n const f = (n: number) => ln - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));\n return `#${[0, 8, 4].map((n) => Math.round(f(n) * 255).toString(16).padStart(2, \"0\")).join(\"\")}`;\n};\n\n/** Names a person would use for a swatch; the nearest one names it. */\nconst NAMES: [string, string][] = [\n [\"Midnight\", \"#191970\"], [\"Ink\", \"#1b1f3b\"], [\"Espresso\", \"#3b2a24\"], [\"Forest\", \"#1f3d2b\"], [\"Aubergine\", \"#3b1f35\"],\n [\"Navy\", \"#1b2a4a\"], [\"Charcoal\", \"#2b2b2b\"], [\"Oxblood\", \"#4a1c1c\"], [\"Deep Teal\", \"#0f3b3b\"], [\"Plum\", \"#4b2342\"],\n [\"Tomato\", \"#e5533d\"], [\"Tangerine\", \"#f28c28\"], [\"Marigold\", \"#f2b705\"], [\"Lemon\", \"#f7e04b\"], [\"Lime\", \"#a3d93b\"],\n [\"Emerald\", \"#1faa6b\"], [\"Jade\", \"#1fa39a\"], [\"Teal\", \"#1b9aaa\"], [\"Azure\", \"#2d8cf0\"], [\"Cobalt\", \"#2f5bea\"],\n [\"Ultramarine\", \"#3f3fd6\"], [\"Iris\", \"#6b5bea\"], [\"Violet\", \"#8b5cf6\"], [\"Orchid\", \"#c05bd6\"], [\"Magenta\", \"#d63fa0\"],\n [\"Rose\", \"#e5487a\"], [\"Coral\", \"#f07260\"], [\"Terracotta\", \"#c8623f\"], [\"Ochre\", \"#c89b3c\"], [\"Olive\", \"#8a8f3c\"],\n [\"Moss\", \"#6b8f4e\"], [\"Periwinkle\", \"#c5c9ff\"], [\"Lavender\", \"#dcd0ff\"], [\"Blush\", \"#ffd6de\"], [\"Peach\", \"#ffd9bf\"],\n [\"Butter\", \"#fff1b8\"], [\"Pistachio\", \"#d6f5a8\"], [\"Mint\", \"#c9f2dc\"], [\"Seafoam\", \"#c2efe8\"], [\"Sky\", \"#cde8ff\"],\n [\"Lilac\", \"#eed2f7\"], [\"Linen\", \"#f5f0e8\"], [\"Ivory\", \"#fbf8ef\"], [\"Porcelain\", \"#f3f5f7\"], [\"Bone\", \"#eee9df\"],\n [\"Mist\", \"#eef2f7\"], [\"Sand\", \"#efe6d8\"],\n];\n\n/** The nearest name not already taken, by a weighted distance the eye roughly agrees with. */\nfunction nameOf(hex: string, taken: Set<string>): string {\n const [r, g, b] = hexToRgb(hex);\n const distance = ([nr, ng, nb]: Rgb) => 2 * (r - nr) ** 2 + 4 * (g - ng) ** 2 + 3 * (b - nb) ** 2;\n const ranked = NAMES.map(([name, at]) => ({ name, d: distance(hexToRgb(at)) })).sort((a, b) => a.d - b.d);\n const name = (ranked.find((one) => !taken.has(one.name)) ?? ranked[0]!).name;\n taken.add(name);\n return name;\n}\n\n/** Black or white, whichever reads on `hex`. */\nexport function inkOn(hex: string): \"#ffffff\" | \"#111111\" {\n const [r, g, b] = hexToRgb(hex).map((c) => {\n const v = c / 255;\n return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n }) as Rgb;\n return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.4 ? \"#111111\" : \"#ffffff\";\n}\n\n/** The five swatches, darkest first: the dark, the colour, its tint, the paper, the accent. */\nexport function paletteFrom(hue: number, harmony: number): BrandKit[\"palette\"] {\n const h = ((hue % 360) + 360) % 360;\n const accent = (h + HARMONIES[((harmony % BRAND_HARMONIES) + BRAND_HARMONIES) % BRAND_HARMONIES]!) % 360;\n const hexes = [hslToHex(h, 45, 13), hslToHex(h, 72, 52), hslToHex(h, 80, 82), hslToHex(h, 30, 95), hslToHex(accent, 78, 72)];\n const taken = new Set<string>();\n return hexes.map((hex) => ({ name: nameOf(hex, taken), hex }));\n}\n\n/**\n * What `company.set_brand` takes. One schema for the tool and for the studio's card, so the card\n * never previews a kit the tool would refuse.\n */\nexport const BrandKitArgsSchema = z.object({\n colour: z\n .string()\n .regex(/^#[0-9a-fA-F]{6}$/)\n .describe(\"The brand's main colour, as #rrggbb — usually the logo's own. The palette is drawn around it.\"),\n harmony: z\n .number()\n .int()\n .min(0)\n .max(BRAND_HARMONIES - 1)\n .optional()\n .describe(\"Which accent the palette takes, 0–3. Change it when asked for other colours with the same main one.\"),\n typeface: z.enum(BRAND_TYPEFACES).describe(\"grotesk (clean), serif (classic), rounded (friendly) or mono (technical).\"),\n tagline: z.string().max(80).optional().describe(\"One short line under the name. Leave it out when there is none.\"),\n});\nexport type BrandKitArgs = z.infer<typeof BrandKitArgsSchema>;\n\n/** The kit a colour, a harmony, a typeface and a line make; the schema has passed it. */\nexport function brandKitFrom(input: { colour: string; harmony?: number | undefined; typeface: BrandKit[\"typeface\"]; tagline?: string | undefined }): BrandKit {\n return BrandKitSchema.parse({\n palette: paletteFrom(hueOf(hexToRgb(input.colour.toLowerCase())), input.harmony ?? 0),\n typeface: input.typeface,\n tagline: (input.tagline ?? \"\").trim().slice(0, 80),\n });\n}\n","/**\n * The §40 signed read for one stored file — the HMAC and the address, in one place.\n *\n * It lives here for the reason `session-token.ts` does: `apps/api` already depends on\n * `apps/runtime-do`, so a *session tool* that must MINT one of these could not import the minter\n * from the route that verifies it without a cycle. One definition, so what mints and what verifies\n * cannot drift — and they must not, because a link that verifies differently than it was signed is\n * a 403 on a URL the model was told to look at.\n *\n * The construction is unchanged from the one `apps/api/src/routes/files.ts` has served since §40:\n * an HMAC over **every other field in the URL**, so there is nothing in it a holder can edit, and\n * `{name}` rides in the path rather than a query parameter so the URL ends in a real file extension\n * — which is what lets a `<video>` tag, a fetch-once publishing provider, and now a model provider\n * fetching an `image_url` type the thing from its address alone.\n */\n\nconst encoder = new TextEncoder();\n\n/**\n * The bound for a link minted BY A SESSION rather than by a person or an API key (ADR-0725).\n *\n * What it hands back is an unauthenticated bearer capability to raw org media: whoever holds the\n * string reads the bytes, with no credential and no further check. Seven days is the right trade\n * for a review link a person opens out of an email tomorrow (`files.ts` `FILE_URL_TTL_MS`). It is\n * the wrong trade for a link whose only consumer is a provider fetching it once, seconds from now,\n * minted on the one path a prompt injection can reach — so the window is sized to that fetch.\n *\n * It is here rather than in `files.ts` because three callers now mint at this bound — the\n * `POST /v1/files/{id}/url` route, the social publish, and the image link a tool result carries\n * (§16.2) — and the three must agree.\n */\nexport const SESSION_FILE_URL_TTL_MS = 15 * 60_000;\n\n/**\n * WHERE A GENERATED ASSET'S BYTES ARE (`canonical-spec §33.5`, ADR-0885): the media bucket, under a\n * `media:` scheme no other key can begin with — every other writer's key starts with an org id,\n * `naive/`, `model-io/` or a blueprint slug, none of which holds a colon. The row's `storage_key`\n * says it, and the storage adapter routes by it; nothing infers it from a path segment.\n */\nexport const mediaStorageKey = (org: string, id: string): string => `media:${org}/${id}`;\nexport const isMediaStorageKey = (key: string): boolean => key.startsWith(\"media:\");\n\n/** Everything the MAC covers. Change one field and every URL ever minted stops verifying. */\nexport interface FileUrlParts {\n org: string;\n id: string;\n name: string;\n /** Epoch milliseconds. */\n expires: number;\n /** The bytes are a generated asset's, in the media bucket; absent for every other file. */\n store?: \"media\" | undefined;\n}\n\n/** The store a file's link reads from, by its row's key. */\nexport const storeOf = (storageKey: string): FileUrlParts[\"store\"] =>\n isMediaStorageKey(storageKey) ? \"media\" : undefined;\n\nfunction b64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The MAC alone. `v1` is in the signed string so a future construction cannot be replayed as this one. */\nexport async function signFileUrl(secret: string, parts: FileUrlParts): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n // A media link signs its store, so it cannot be edited into a read of the other bucket; every\n // other link signs exactly what it always did, so no URL already handed out stops working.\n const store = parts.store === \"media\" ? \":media\" : \"\";\n const message = `vetta.file-url.v1:${parts.org}:${parts.id}:${parts.name}:${parts.expires}${store}`;\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message))));\n}\n\n/** Constant-time over equal-length strings; unequal lengths are already a mismatch. */\nexport function fileUrlMacMatches(expected: string, given: string): boolean {\n if (expected.length !== given.length) return false;\n let diff = 0;\n for (let i = 0; i < expected.length; i += 1) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * The whole address, at `origin`. Callers own the TTL, because the two callers want very different\n * ones: seven days for a review link a person opens tomorrow, fifteen minutes for a capability\n * minted on a path a prompt injection can reach (`files.ts`, ADR-0725).\n */\nexport async function fileUrl(secret: string, origin: string, parts: FileUrlParts): Promise<string> {\n const url = new URL(`/v1/files/${parts.id}/${encodeURIComponent(parts.name)}`, origin);\n url.searchParams.set(\"org\", parts.org);\n url.searchParams.set(\"expires\", String(parts.expires));\n if (parts.store === \"media\") url.searchParams.set(\"in\", \"media\");\n url.searchParams.set(\"sig\", await signFileUrl(secret, parts));\n return url.toString();\n}\n","import { ASK_BY_DEFAULT_TOOLS, invokesAnyTool, PLATFORM_TOOLS } from \"./schema/agent\";\n\n/**\n * ONCE A CHAT HAS READ PEOPLE'S DATA, NOTHING THE MODEL CHOOSES CAN CARRY IT OUT (`canonical-spec §64`,\n * ADR-1764).\n *\n * Mail, lead forms and web pages are written by strangers, and a model cannot be relied on to ignore\n * what they tell it. So this is decided in code, per call, and no prompt can change it. A list of \"our\n * domains\" can't do it: agents have to read the web and write to clients, and the box's shell has one\n * network switch, on or off (ADR-0089). So it follows the data instead. A chat that has read a person's\n * details is flagged, and from then on every tool is one of three things:\n *\n * - `free`: its bytes stay with us, or it goes where it always goes. The model can't aim it.\n * - `ask`: a person reads the call and says yes, every time. No grant covers it.\n * - `blocked`: nobody can read it on a card (a shell line, a whole site), so no card is offered.\n *\n * A tool this file doesn't name asks: a new tool is outbound until someone says otherwise.\n */\nexport type OnceRead = \"free\" | \"ask\" | \"blocked\";\n\n/** What a tool's server published about it: the invoker's target, or the tool itself. */\nexport interface ToolFacts {\n readOnly?: boolean | undefined;\n /** A hosted app's own MCP tool. The company's own apps aren't counted as a read of people's data. */\n source?: \"app\" | undefined;\n}\n\nconst PLATFORM: ReadonlySet<string> = new Set([...PLATFORM_TOOLS, ...ASK_BY_DEFAULT_TOOLS]);\n\n/** The platform's reads of a person's details, or of anything else that must not leave. */\nconst PEOPLE_TOOLS: ReadonlySet<string> = new Set([\n \"crm.read\",\n \"email.read\",\n \"phone.read\",\n \"legal.verifications\",\n \"legal.verification\",\n \"legal.companies\",\n \"legal.company\",\n \"legal.documents\",\n \"wallet.transactions\",\n \"wallet.receipts\",\n \"card.list\",\n \"card.show\",\n \"card.transactions\",\n \"card.credentials\",\n]);\n\n/** The same reads through the control plane's invoker, by route tool name (a test there holds them to the routes). */\nexport const PEOPLE_ROUTES: ReadonlySet<string> = new Set([\n \"crm_list_contacts\",\n \"crm_get_contact\",\n \"crm_calendar\",\n \"identities_list_messages\",\n \"identities_list_sent\",\n \"identities_list_verifications\",\n \"identities_get_verification\",\n \"identities_list_companies\",\n \"identities_get_company\",\n \"identities_list_documents\",\n \"identities_get_document_link\",\n \"identities_list_transactions\",\n \"identities_list_cards\",\n \"identities_get_card\",\n \"identities_reveal_credentials\",\n \"identities_list_card_transactions\",\n // A transcript holds whatever its tools returned, so reading one is reading that.\n \"sessions_list_events\",\n \"sessions_stream_events\",\n \"sessions_get_workspace\",\n \"voice_get_call\",\n \"proxy_list_calls\",\n \"proxy_get_call\",\n \"audit_logs_list\",\n]);\n\n/** The tools that stay with us, or go where they always go. Everything else asks. */\nconst FREE: ReadonlySet<string> = new Set([\n // The chat's own computer, read. What goes onto it is `ONTO_DISK`.\n \"read\",\n \"ls\",\n \"find\",\n // The company's own records, read or written here.\n \"publish_file\",\n \"find_files\",\n \"view_image\",\n \"project_context\",\n \"read_skill\",\n \"board_read\",\n \"crm.read\",\n \"crm.write\",\n \"email.inboxes\",\n \"email.read\",\n \"phone.numbers\",\n \"phone.read\",\n // What the person sees in the chat.\n \"show\",\n \"compose\",\n \"open_panel\",\n \"ask_operator\",\n \"write_plan\",\n \"propose_plan\",\n \"session_spend\",\n \"submit_output\",\n // A teammate. The flag travels with the message (`§64`).\n \"send_to_agent\",\n \"wait_for_agents\",\n \"list_agents\",\n \"post_to_channel\",\n // A person's yes is already this tool's whole job.\n \"request_tools\",\n // A search's words reach only the search vendor, a limit `§64` states.\n \"web_search\",\n \"data_search\",\n \"data_describe\",\n \"list_characters\",\n \"get_character\",\n \"delete_character\",\n]);\n\n/**\n * What puts bytes on the agent's computer. Free on a seat with no shell. On a seat that holds one it's\n * blocked: a process started before the flag, or a later chat that isn't flagged, could send the file.\n */\nconst ONTO_DISK: ReadonlySet<string> = new Set([\"write\", \"edit\", \"fetch_file\"]);\n\n/** Free until an argument names an address, which the vendor would then fetch for us. */\nconst FETCHES_GIVEN_URLS: ReadonlySet<string> = new Set([\n \"generate_image\",\n \"generate_video\",\n \"edit_video\",\n \"clip_video\",\n \"transcribe_audio\",\n \"generate_speech\",\n \"generate_sound_effect\",\n \"generate_music\",\n \"generate_3d_model\",\n \"find_stock_photo\",\n \"create_character\",\n]);\n\nconst BLOCKED: ReadonlySet<string> = new Set([\"bash\", \"build_3d\", \"computers_exec_command\", \"computers_stream_command\", \"apps_create_deployment\"]);\n\n/** The `apps` actions that publish nothing: everything else puts bytes on a public site or in its keys. */\nconst APPS_READS: ReadonlySet<string> = new Set([\"list\", \"status\", \"pull\"]);\n\n/** The browser's reads of the page already open: every other action can write to the page or leave it. */\nconst BROWSER_READS: ReadonlySet<string> = new Set([\"extract\", \"observe\", \"links\", \"screenshot\"]);\n\n/** The control plane's own tools, published to a session under the server name `vetta`. */\nconst onControlPlane = (name: string): boolean => name.startsWith(\"vetta.\") || name.startsWith(\"vetta__\");\n\n/** `vetta.tool` and `vetta__tool` are the same route as `tool`. */\nconst bare = (name: unknown): string => (typeof name === \"string\" ? (name.split(/\\.|__/).pop() ?? name) : \"\");\n\nconst namesAnAddress = (value: unknown): boolean => {\n // `https:evil.test` and a tab inside the word parse as an address too, so the slashes prove nothing.\n if (typeof value === \"string\") return /https?:/i.test(value.replace(/[\\s\\p{Cc}]/gu, \"\"));\n if (Array.isArray(value)) return value.some(namesAnAddress);\n return typeof value === \"object\" && value !== null && Object.values(value).some(namesAnAddress);\n};\n\n/** Whether this call reads people's data through the platform itself: its own tools, or the invoker's routes. */\nexport const readsPlatformPeople = (name: string, args: Record<string, unknown>): boolean => {\n if (PEOPLE_TOOLS.has(name)) return true;\n if (name === \"show\") return args[\"source\"] === \"calendar\";\n if (invokesAnyTool(name)) return PEOPLE_ROUTES.has(bare(args[\"tool\"]));\n return onControlPlane(name) && PEOPLE_ROUTES.has(bare(name));\n};\n\n/**\n * Whether this call reads people's data. A connected app or a declared MCP server is someone's inbox\n * or CRM until it says it only writes; a hosted app's own tools aren't counted (`§64` states it).\n */\nexport function readsPeople(name: string, args: Record<string, unknown>, facts: ToolFacts = {}): boolean {\n if (readsPlatformPeople(name, args)) return true;\n if (invokesAnyTool(name) || onControlPlane(name) || PLATFORM.has(name)) return false;\n return name.includes(\".\") && facts.source !== \"app\" && facts.readOnly !== false;\n}\n\n/**\n * A server's word that a tool only reads, trusted from us and from the company's own apps. An outside\n * server is whatever it says it is, and `readOnly` on a fetch tool would open any address.\n */\nconst trustedRead = (name: string, facts: ToolFacts): boolean =>\n facts.readOnly === true && (!name.includes(\".\") || PLATFORM.has(name) || onControlPlane(name) || facts.source === \"app\");\n\n/** What this call is in a chat that has read people's data. `holdsShell`: this seat's policy offers `bash`. */\nexport function onceRead(name: string, args: Record<string, unknown>, facts: ToolFacts = {}, holdsShell = false): OnceRead {\n if (invokesAnyTool(name)) {\n if (BLOCKED.has(bare(args[\"tool\"]))) return \"blocked\";\n return name === \"tools_execute\" || onControlPlane(name) ? (facts.readOnly === true ? \"free\" : \"ask\") : \"ask\";\n }\n if (onControlPlane(name)) {\n if (BLOCKED.has(bare(name))) return \"blocked\";\n return bare(name) === \"tools_search\" || facts.readOnly === true ? \"free\" : \"ask\";\n }\n if (BLOCKED.has(name)) return \"blocked\";\n if (ONTO_DISK.has(name)) return holdsShell ? \"blocked\" : \"free\";\n if (name === \"apps\") return APPS_READS.has(String(args[\"action\"])) ? \"free\" : \"blocked\";\n if (name === \"browser\") return BROWSER_READS.has(String(args[\"action\"])) ? \"free\" : \"ask\";\n if (FREE.has(name) || name === \"tools_search\" || trustedRead(name, facts)) return \"free\";\n if (FETCHES_GIVEN_URLS.has(name)) return namesAnAddress(args) ? \"ask\" : \"free\";\n return \"ask\";\n}\n\n/** What the model reads when a call is blocked. */\nexport const BLOCKED_ONCE_READ = (name: string): string =>\n `${name} can't run in this chat, because it has read people's data and this could carry it out. Say so plainly, and ask the person to start a new chat for this work.`;\n\n/** Where a session keeps whether it has read. Durable, and written before the read's result is returned. */\nexport interface PeopleLedger {\n read(): Promise<boolean>;\n mark(): Promise<void>;\n}\n\n/** The ledger's read, failing shut: a read that throws is a chat that has read people's data. */\nexport async function hasRead(ledger: PeopleLedger): Promise<boolean> {\n try {\n return await ledger.read();\n } catch {\n return true;\n }\n}\n\n/** A ledger that lives in memory: a test's. */\nexport function memoryPeopleLedger(read_people = false): PeopleLedger & { state: { read_people: boolean } } {\n const state = { read_people };\n return { state, read: async () => state.read_people, mark: async () => void (state.read_people = true) };\n}\n","/**\n * THE PLAN GATE'S RULE, IN ONE PLACE (ADR-0150, ADR-1108, ADR-1195 [central-state]).\n *\n * `apps/api/src/gate.ts` decides whether an organization may be used; the operator console reads\n * the same rows to say what state each organization is in. Two copies of \"is this plan usable\"\n * drift — the console used to read `subscription_status` alone and called a plan whose renewals had\n * stopped arriving `active` while the API refused every call to it. Both now ask this module.\n *\n * Pure and storage-free: callers pass the plan's fields as RFC 3339 strings (or `Date`s) and a\n * clock, so the API's wire-shaped `Subscription` and a raw database row both fit.\n */\n\n/**\n * How far past a known period end an `active` plan is still honoured. The provider re-sends the\n * lifecycle event and the renewal invoice on every rollover, so a period end this stale means the\n * callbacks stopped arriving, not that a customer is a few hours late.\n */\nexport const STALE_PLAN_SLACK_MS = 3 * 24 * 60 * 60 * 1_000;\n\ntype Instant = string | Date | null;\n\n/** The fields of a plan the gate reads. `status` is the stored subscription status. */\nexport interface PlanGateFields {\n status: string;\n current_period_end: Instant;\n grace_until: Instant;\n}\n\ntype Now = string | Date;\n\nconst ms = (at: Instant): number | null => (at === null ? null : typeof at === \"string\" ? Date.parse(at) : at.getTime());\nconst nowMs = (now: Now): number => (typeof now === \"string\" ? Date.parse(now) : now.getTime());\n\n/**\n * An `active` plan whose known period end is more than `STALE_PLAN_SLACK_MS` behind. `null` is *not*\n * stale: a plan bought at a checkout is granted before any lifecycle event has named a period.\n */\nexport function planIsStale(plan: Pick<PlanGateFields, \"current_period_end\">, now: Now): boolean {\n const end = ms(plan.current_period_end);\n if (end === null) return false;\n return nowMs(now) > end + STALE_PLAN_SLACK_MS;\n}\n\n/**\n * Is this organization entitled to be used right now? `active` yes unless stale; `past_due` only\n * until its stamped `grace_until` (an unset one is *no* grace); everything else no.\n */\nexport function planEntitled(plan: PlanGateFields, now: Now): boolean {\n if (plan.status === \"active\") return !planIsStale(plan, now);\n if (plan.status !== \"past_due\") return false;\n const grace = ms(plan.grace_until);\n return grace !== null && nowMs(now) < grace;\n}\n\n/** The setup fields of a company (migration 0101). */\nexport interface SetupFields {\n activated_at: Instant;\n created_by: string | null;\n status: string;\n}\n\n/**\n * Still being set up (ADR-1108): made at `/setup` (the only writer of `created_by`), never\n * activated, and holding no plan. A never-paid company from before 0101 has no `created_by` and is\n * locked behind the plan as it always was; one holding any plan has paid, even where an older\n * Worker took the payment without stamping `activated_at`.\n */\nexport function orgIsSettingUp(org: SetupFields): boolean {\n return org.activated_at === null && org.created_by !== null && org.status === \"none\";\n}\n\n/**\n * One state per organization, for people reading an account:\n *\n * setup being set up before payment; only its CEO runs (ADR-1108)\n * trialing entitled, inside a free trial\n * canceling entitled, but asked to stop at period end\n * active entitled, paid\n * grace `past_due`, still inside its stamped grace window\n * stale reads `active`, but the period end is too old to honour — the API refuses it\n * locked not entitled: no plan, cancelled, or past due with the grace spent\n *\n * `setup`, `stale` and `locked` are exactly the organizations the gate refuses (setup admits its\n * CEO alone); the other four are the ones it admits.\n */\nexport const ORG_PLAN_STATES = [\"setup\", \"trialing\", \"canceling\", \"active\", \"grace\", \"stale\", \"locked\"] as const;\nexport type OrgPlanState = (typeof ORG_PLAN_STATES)[number];\n\nexport interface OrgPlanFields extends PlanGateFields {\n activated_at: Instant;\n created_by: string | null;\n cancel_at_period_end: boolean;\n trial_end: Instant;\n}\n\nexport function orgPlanState(org: OrgPlanFields, now: Now): OrgPlanState {\n if (orgIsSettingUp(org)) return \"setup\";\n if (!planEntitled(org, now)) return org.status === \"active\" ? \"stale\" : \"locked\";\n if (org.status === \"past_due\") return \"grace\";\n if (org.cancel_at_period_end) return \"canceling\";\n const trialEnd = ms(org.trial_end);\n if (trialEnd !== null && trialEnd > nowMs(now)) return \"trialing\";\n return \"active\";\n}\n","/**\n * The organization itself: members, scoped API keys, and the prepaid USD balance with its ledger\n * (`canonical-spec.md §10, §11, §17`). Money stays integer micro-USD on the wire — nothing here\n * converts (§1); the CLI does that once, at its own boundary.\n */\nimport {\n ApiKeySchema,\n AuditEntrySchema,\n IdentityCreatorSchema,\n LedgerEntrySchema,\n LineItemTierSchema,\n MemberSchema,\n OrganizationSchema,\n PrincipalSchema,\n RoleSchema,\n ScopeSchema,\n TopupSchema,\n TournamentEntrySchema,\n page,\n type AuditAction,\n type BrandKit,\n type TournamentAnswers,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, tolerantPage, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\n/**\n * The ledger as a published client parses it: a tier added after this release (the phone's `mobile`\n * was one) must not fail the whole page, so an unknown tier is kept as its string. Parsing only: the\n * type stays `LedgerEntry`, the tiers this release knows, so no caller's exhaustive switch changes.\n */\nconst ClientLedgerEntrySchema = LedgerEntrySchema.extend({\n line_items: z.array(LedgerEntrySchema.shape.line_items.element.extend({ tier: LineItemTierSchema.or(z.string()) })),\n}) as unknown as typeof LedgerEntrySchema;\n\n/** Enums come from `core`; re-declaring either here would be a second taxonomy (`CLAUDE.md §2`). */\ntype Scope = z.infer<typeof ScopeSchema>;\ntype Role = z.infer<typeof RoleSchema>;\n\n/**\n * `GET /v1/me` (`canonical-spec.md §20.1`) — the first call any client makes, and the reason none\n * of them needs an `org_` id as input any more.\n */\nexport const IdentitySchema = z.object({\n object: z.literal(\"identity\"),\n principal: PrincipalSchema,\n organization: z\n .object({ id: z.string(), name: z.string(), mode: z.enum([\"test\", \"live\"]) })\n .nullable(),\n scopes: z.array(ScopeSchema),\n user: z.object({ email: z.string(), role: RoleSchema.nullable() }).nullable(),\n /** The creator row for the session's email, or `null` (§42.3). Absent from planes before §42. */\n creator: IdentityCreatorSchema.nullish(),\n});\n\nexport type Identity = z.infer<typeof IdentitySchema>;\n\n/** `POST /v1/auth/session` (§20.4). `token` is a bearer credential — never put it in a browser. */\nexport const AuthSessionSchema = z.object({\n object: z.literal(\"auth_session\"),\n token: z.string(),\n expires_at: z.string(),\n user: z.object({ email: z.string() }),\n organization_id: z.string().nullable(),\n organizations: z.array(z.object({ id: z.string(), name: z.string(), role: RoleSchema })),\n});\n\nexport type AuthSession = z.infer<typeof AuthSessionSchema>;\n\n/** Only the mint replies carry these three: the secret exists once, and it names its org and tier. */\nexport const MintedKeySchema = ApiKeySchema.extend({\n secret: z.string(),\n org_id: z.string(),\n mode: z.enum([\"test\", \"live\"]),\n});\n\n/** `POST /v1/organizations` answers the same envelope for an operator and a customer (§20.3). */\nexport const CreatedOrganizationSchema = z.object({\n organization: OrganizationSchema,\n api_key: MintedKeySchema,\n});\n\nexport const BalanceSchema = z.object({\n object: z.literal(\"credit_balance\"),\n balance_micro_usd: z.number().int(),\n mode: z.enum([\"test\", \"live\"]),\n});\n\nexport const PlanSchema = z.enum([\"standard\", \"pro\"]);\nexport type Plan = z.infer<typeof PlanSchema>;\n\n/**\n * The monthly plan. Not the same thing as the balance next door: this is the right to use the\n * organization at all, and every route outside billing is refused with `subscription_required`\n * (402) until it reads `active`. `action_url` is the hosted page to send the customer to, and is\n * `null` on a read. A free trial reads `active` with `trial_end` set — there is no `trialing`\n * status. The plan fields are optional so an older server still parses.\n */\nexport const SubscriptionSchema = z.object({\n object: z.literal(\"subscription\"),\n status: z.enum([\"none\", \"active\", \"past_due\", \"canceled\"]),\n /** `standard` or `pro`; `null` until the organization first subscribes. */\n plan: PlanSchema.nullable().optional(),\n /** The plan's monthly list price; `null` while `plan` is. */\n price_micro_usd: z.number().int().nullable().optional(),\n /** Credit added to the balance each paid month (it rolls over); `null` while `plan` is. */\n included_credit_micro_usd: z.number().int().nullable().optional(),\n /** Set only while a free trial is running: the moment it converts to a paid plan. */\n trial_end: z.string().nullable().optional(),\n /** The plan a scheduled change moves to at `current_period_end` (a downgrade), else `null`. */\n pending_plan: PlanSchema.nullable().optional(),\n /** Whether `subscribe({ plan: \"standard\" })` from this caller would start a free trial. */\n trial_eligible: z.boolean().optional(),\n /** Days of free trial this deployment gives on Standard; `0` = trials are off. Absent from an older server. */\n trial_days: z.number().int().optional(),\n /** The credit a trial starts with, micro-USD. Absent from an older server. */\n trial_credit_micro_usd: z.number().int().optional(),\n /** The plans this deployment sells; absent from an older server, which sells Standard only. */\n plans_available: z.array(z.string()).optional(),\n /**\n * The card the plan bills (its last four, `4242`), on `subscription({ includePaymentMethod: true })`\n * only, which needs `billing:write`; `null` when there is none or it could not be read. Absent otherwise.\n */\n payment_method: z.object({ last4: z.string() }).nullable().optional(),\n /** Each plan in `plans_available` with its monthly list price and credit, readable before one is held. Absent from an older server. */\n plans: z\n .array(z.object({ plan: z.string(), price_micro_usd: z.number().int(), included_credit_micro_usd: z.number().int() }))\n .optional(),\n current_period_end: z.string().nullable(),\n /** While `past_due`, the moment the organization stops working. `null` ⇒ no grace. */\n grace_until: z.string().nullable(),\n /** The plan runs to `current_period_end` and then stops — a cancellation already asked for. */\n cancel_at_period_end: z.boolean(),\n action_url: z.string().nullable(),\n});\n\n/**\n * A link to the payment provider's own hosted account page — card, invoices, cancellation. The\n * page is single-use and expires, so it is followed, never stored.\n */\nexport const BillingPortalSessionSchema = z.object({\n object: z.literal(\"billing_portal_session\"),\n action_url: z.string(),\n});\n\n/**\n * What the two anti-enumerating routes answer. `delivery` is a fact about the *deployment* — could\n * it hand the message to a mailer at all — and never about the address, which is what makes it safe\n * to show. A screen reads it to choose between \"check your inbox\" and \"here is the other way in\".\n */\nexport const AcknowledgedSchema = z.object({\n object: z.string(),\n delivery: z.enum([\"sent\", \"undeliverable\"]),\n});\n\nexport type Acknowledged = z.infer<typeof AcknowledgedSchema>;\n\nexport const auth = (config: ClientConfig) => ({\n /** Who this credential is. No scope, no org id needed — that is the whole point (§20.1). */\n me: () => request(config, IdentitySchema, { method: \"GET\", path: \"/v1/me\" }),\n /**\n * Sign in, finish an external sign-in, or re-scope the session already held to another\n * organization (§20.4). `provider_token` is the access token an external provider sign-in came\n * back with; the control plane re-verifies it against the provider and refuses an address the\n * provider has not proved.\n */\n session: (body: {\n email?: string;\n password?: string;\n provider_token?: string;\n organization_id?: string;\n /** The site signing in (ADR-1633); absent is the dashboard. */\n site?: \"app\" | \"creators\" | \"doomscroll\" | \"testers\";\n /** Sign up on `site` with an account already held (a provider sign-in from a sign-up page). */\n join?: boolean;\n }) => request(config, AuthSessionSchema, { method: \"POST\", path: \"/v1/auth/session\", body }),\n /** `tournament` enters the tournament with the account (§56); a taken address writes none. */\n register: (body: { email: string; password: string; tournament?: TournamentAnswers }) =>\n request(\n config,\n z.object({\n object: z.literal(\"auth_user\"),\n email: z.string(),\n confirmation_required: z.boolean(),\n /** The same line for every address: an existing account gets no mail. Absent from an older server. */\n hint: z.string().optional(),\n }),\n { method: \"POST\", path: \"/v1/auth/users\", body },\n ),\n /** Enter the tournament as the signed-in person, or rewrite the answers (§56). */\n joinTournament: (body: { answers: TournamentAnswers }) =>\n request(config, TournamentEntrySchema, { method: \"POST\", path: \"/v1/tournament/entries\", body }),\n /** The signed-in person's tournament entry, `null` when they have not joined. */\n tournamentEntry: () =>\n request(\n config,\n z.object({ object: z.literal(\"tournament_status\"), entry: TournamentEntrySchema.nullable() }),\n { method: \"GET\", path: \"/v1/tournament/entry\" },\n ),\n /**\n * Begin a password reset (§20.4). Answers 202 whether or not the address has an account — the\n * caller must not branch on it, and there is nothing in the reply to branch on.\n */\n recover: (body: { email: string }) =>\n request(config, AcknowledgedSchema, { method: \"POST\", path: \"/v1/auth/recover\", body }),\n /** Finish a reset with the token the mailed link carried. */\n resetPassword: (body: { token: string; password: string }) =>\n request(config, z.object({ object: z.literal(\"auth_password\"), updated: z.boolean() }), {\n method: \"POST\",\n path: \"/v1/auth/password\",\n body,\n }),\n /** Re-send a confirmation. Same 202, same silence about who exists. */\n resendConfirmation: (body: { email: string }) =>\n request(config, AcknowledgedSchema, { method: \"POST\", path: \"/v1/auth/confirmations\", body }),\n});\n\nexport const orgs = (config: ClientConfig) => ({\n /** The organizations this credential reaches (§20.2). */\n list: (query: ListQuery = {}) =>\n request(config, page(OrganizationSchema), { method: \"GET\", path: \"/v1/organizations\", query }),\n /**\n * Creates a new organization and answers a working key for it, secret shown once (§20.3).\n * Signed-in customer onboarding creates a live organization; an API key preserves its own mode.\n */\n create: (body: { name: string; referral_code?: string }) =>\n request(config, CreatedOrganizationSchema, { method: \"POST\", path: \"/v1/organizations\", body }),\n /** The company a signed-in person is setting up, found or made (ADR-1108). */\n setup: (body: { template?: string; referral_code?: string } = {}) =>\n request(config, z.object({ organization: OrganizationSchema }), { method: \"POST\", path: \"/v1/organizations/setup\", body }),\n get: (id: string) =>\n request(config, OrganizationSchema, { method: \"GET\", path: `/v1/organizations/${encodeURIComponent(id)}` }),\n /** A rename, a new timezone (IANA, §20.6), a logo (SVG, §20.7; `null` clears it), or any together. */\n update: (id: string, body: { name?: string; timezone?: string; logo_svg?: string | null; brand?: BrandKit | null }) =>\n request(config, OrganizationSchema, { method: \"PATCH\", path: `/v1/organizations/${encodeURIComponent(id)}`, body }),\n members: (id: string, query: ListQuery = {}) =>\n request(config, page(MemberSchema), {\n method: \"GET\",\n path: `/v1/organizations/${encodeURIComponent(id)}/members`,\n query,\n }),\n addMember: (id: string, body: { email: string; role: Role }) =>\n request(config, MemberSchema, {\n method: \"POST\",\n path: `/v1/organizations/${encodeURIComponent(id)}/members`,\n body,\n }),\n setRole: (id: string, userId: string, role: Role) =>\n request(config, MemberSchema, {\n method: \"PATCH\",\n path: `/v1/organizations/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`,\n body: { role },\n }),\n removeMember: (id: string, userId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/organizations/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`,\n }),\n});\n\nexport const keys = (config: ClientConfig) => ({\n /** The only response that ever carries `secret`; a key can only mint one in its own mode. */\n create: (body: { name: string; scopes: Scope[] }) =>\n request(config, MintedKeySchema, { method: \"POST\", path: \"/v1/api_keys\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(ApiKeySchema), { method: \"GET\", path: \"/v1/api_keys\", query }),\n rotate: (id: string) =>\n request(config, MintedKeySchema, { method: \"POST\", path: `/v1/api_keys/${encodeURIComponent(id)}/rotate`, body: {} }),\n revoke: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/api_keys/${encodeURIComponent(id)}` }),\n});\n\n// Sums, not single debits: an adjustment line can take a tier or a day below zero, and a refused\n// parse would blank Home and Cost with no figure and no error.\nconst Micro = z.number().int();\nconst SpendSchema = z.object({\n spent_micro_usd: Micro,\n by_tier: z.record(z.string(), Micro),\n by_agent: z.array(z.object({ agent_id: z.string(), spent_micro_usd: Micro })),\n by_session: z.array(z.object({ session_id: z.string(), spent_micro_usd: Micro })),\n by_day: z.array(z.object({ day: z.string(), micro_usd: Micro })).optional(),\n});\n\nexport type LedgerFilter = ListQuery & {\n type?: \"debit\" | \"credit\" | undefined;\n session_id?: string | undefined;\n agent_id?: string | undefined;\n deployment_id?: string | undefined;\n from?: string | undefined;\n to?: string | undefined;\n};\n\nexport const credits = (config: ClientConfig) => ({\n show: () => request(config, BalanceSchema, { method: \"GET\", path: \"/v1/credits/balance\" }),\n /** Opens a hosted checkout and credits **nothing**: only the verified callback moves the balance. */\n topup: (amountMicroUsd: number, options: { return_to?: string } = {}) =>\n request(config, TopupSchema, {\n method: \"POST\",\n path: \"/v1/credits/topups\",\n body: { amount_micro_usd: amountMicroUsd, ...options },\n }),\n ledger: (query: LedgerFilter = {}) =>\n request(config, page(ClientLedgerEntrySchema), { method: \"GET\", path: \"/v1/credits/ledger\", query }),\n /**\n * What the ledger's filters spent over the whole range, summed by the server — never a page's sum:\n * the total, per tier, the dearest 50 agents and sessions. `days` (alone) answers `by_day` and those days' total instead.\n */\n spend: (query: Omit<LedgerFilter, \"type\" | \"limit\" | \"after\"> & { days?: number | undefined; timezone?: string | undefined } = {}) =>\n request(config, SpendSchema, { method: \"GET\", path: \"/v1/credits/spend\", query }),\n /**\n * The organization's plan — what makes every other route callable at all. `includePaymentMethod`\n * also names the card it bills (`payment_method`), which costs a read at the payment provider and\n * needs `billing:write` (`403 forbidden` without it, and from a model).\n */\n subscription: (options: { includePaymentMethod?: boolean } = {}) =>\n request(config, SubscriptionSchema, {\n method: \"GET\",\n path: \"/v1/credits/subscription\",\n ...(options.includePaymentMethod === true ? { query: { include_payment_method: \"true\" } } : {}),\n }),\n /**\n * Opens the hosted checkout for a plan (default `standard`, with the free trial when\n * `trial_eligible`); the organization becomes usable when it is paid or the trial starts.\n */\n subscribe: (options: { plan?: Plan } = {}) =>\n request(config, SubscriptionSchema, {\n method: \"POST\",\n path: \"/v1/credits/subscription\",\n body: options.plan === undefined ? {} : { plan: options.plan },\n }),\n /**\n * Changes an active plan. `pro` is immediate (prorated, charged now, ends a running trial);\n * `standard` from Pro takes effect at `current_period_end` and reads back as `pending_plan`.\n * Asking for `pro` again before then takes the downgrade back.\n */\n changePlan: (plan: Plan) =>\n request(config, SubscriptionSchema, {\n method: \"PATCH\",\n path: \"/v1/credits/subscription\",\n body: { plan },\n }),\n /**\n * Stops the plan at the end of the period already paid for — never immediately. The state\n * follows the provider's callback, so the answer reports the request, not a completed change.\n */\n cancelSubscription: () =>\n request(config, SubscriptionSchema, { method: \"DELETE\", path: \"/v1/credits/subscription\" }),\n /**\n * A link to the hosted account page: change the card, read the invoices, cancel. Opens nothing\n * and changes nothing — an organization that never subscribed has no account, and this answers\n * `404 not_found` rather than an empty page.\n */\n billingPortal: () =>\n request(config, BillingPortalSessionSchema, {\n method: \"POST\",\n path: \"/v1/credits/billing_portal\",\n body: {},\n }),\n});\n\nexport type AuditFilter = ListQuery & {\n /** A principal id — a member `usr_…` or a key `key_…`. */\n actor?: string | undefined;\n /** A resource id, e.g. one `agt_…`. */\n resource?: string | undefined;\n action?: string | undefined;\n /** One request's entries, by the `request_id` the operator's logs carry. */\n request_id?: string | undefined;\n from?: string | undefined;\n to?: string | undefined;\n};\n\n/**\n * An entry whose `action` this build may not know (`docs/api/audit-logs`: \"treat `action` as an\n * open string\"). The vocabulary only grows and the server deploys on its own schedule, so a strict\n * enum here made one newer row throw away the whole page — a customer's audit screen and\n * `vetta audit list` both failed after a single operator credit (ADR-1193). The known actions keep\n * their autocompletion; an unknown one arrives as the server spelled it rather than being hidden,\n * because an audit trail that silently drops rows is worse than one that shows an unfamiliar name.\n */\nconst OpenAuditEntrySchema = AuditEntrySchema.extend({\n action: z.string() as unknown as z.ZodType<AuditAction | (string & {})>,\n});\n\n/**\n * The control-plane trail (`canonical-spec.md §17`). Read-only by construction: it only grows.\n * The page is parsed leniently (`tolerantPage`): a row this build cannot read at all costs that\n * row, not the page.\n */\nexport const auditLogs = (config: ClientConfig) => ({\n list: (query: AuditFilter = {}) =>\n request(config, tolerantPage(OpenAuditEntrySchema), { method: \"GET\", path: \"/v1/audit_logs\", query }),\n});\n","/**\n * The one HTTP boundary of the internal client. Every call goes through `request`, so the bearer\n * key, the `Vetta-Version` date header (`canonical-spec.md §9`), the `Idempotency-Key` on every\n * mutating verb (§9) and the single error envelope (§3) are handled in exactly one place.\n *\n * Responses are parsed with the zod schemas from `@vetta/core` — the client never re-declares a\n * wire shape (`code-standards §2`).\n */\nimport { API_VERSION, VettaError, type ErrorCode } from \"@vetta/core\";\nimport { z } from \"zod\";\n\nexport type Method = \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\";\n\nconst MUTATING = new Set<Method>([\"POST\", \"PATCH\", \"PUT\", \"DELETE\"]);\n\nexport interface Call {\n method: Method;\n path: string;\n /** `undefined` values are dropped, so callers pass optional filters straight through. */\n query?: Record<string, string | number | undefined>;\n /**\n * JSON unless it is a `FormData`, which goes on the wire as multipart (`POST /v1/files`), or a\n * `Uint8Array`, which goes verbatim under the caller's own `content-type` (an object `PUT`, §38).\n */\n body?: unknown;\n /**\n * Headers this one route needs on top of the four every call carries. One route uses it: the\n * model proxy takes its completion window as `Vetta-Window`, because the Messages envelope it\n * serves has no field for one (`canonical-spec.md §26`).\n */\n headers?: Record<string, string>;\n}\n\nexport interface ClientConfig {\n baseUrl: string;\n apiKey: string;\n /** Optional in `createClient` (the global `fetch`); tests inject one to assert exact traffic and the CLI owns its own (`code-standards §9`). */\n fetch: typeof globalThis.fetch;\n /** Optional in `createClient` (a random UUID per write); tests inject a deterministic key per mutating call (`canonical-spec.md §9`). */\n idempotencyKey: () => string;\n}\n\n/**\n * The error envelope (§3) as a client sees it. `type` and `status` come off the response rather\n * than being re-derived from `code`: the server owns the code→(type,status) table (`core`), and a\n * client that re-declared it would be a second taxonomy.\n */\nexport class ApiError extends Error {\n readonly type: string;\n readonly code: string;\n readonly status: number;\n readonly requestId: string;\n readonly param: string | undefined;\n\n constructor(status: number, envelope: z.infer<typeof EnvelopeSchema>[\"error\"]) {\n super(envelope.message);\n this.name = \"ApiError\";\n this.type = envelope.type;\n this.code = envelope.code;\n this.status = status;\n this.requestId = envelope.request_id;\n this.param = envelope.param;\n }\n}\n\n/**\n * A 2xx BODY THIS SDK CANNOT READ: client/server drift. It was a bare `ZodError`, which names no\n * request, so the failure most worth reporting could not be reported. It is an `ApiError` with the\n * fallback `apiErrorFrom` uses for an unreadable 500 (`internal_error`), the real status\n * and `x-request-id`, plus the call and the zod issues.\n */\nexport class ResponseParseError extends ApiError {\n readonly method: Method;\n readonly path: string;\n readonly issues: z.ZodError[\"issues\"];\n\n constructor(response: Pick<Response, \"status\" | \"headers\">, call: Call, error: z.ZodError) {\n const where = (issue: z.ZodError[\"issues\"][number]) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`;\n const more = error.issues.length > 3 ? `; +${error.issues.length - 3} more` : \"\";\n const first = error.issues.slice(0, 3).map(where).join(\"; \");\n super(response.status, {\n type: \"api_error\",\n code: \"internal_error\",\n message: `${call.method} ${call.path} answered in a shape this SDK cannot read — ${first}${more}`,\n request_id: response.headers.get(\"x-request-id\") ?? \"\",\n });\n this.name = \"ResponseParseError\";\n this.method = call.method;\n this.path = call.path;\n this.issues = error.issues;\n }\n}\n\n/** Shape-only: the taxonomy itself lives in `core`, this just deserializes §3 defensively. */\nconst EnvelopeSchema = z.object({\n error: z.object({\n type: z.string(),\n code: z.string(),\n message: z.string(),\n request_id: z.string(),\n param: z.string().optional(),\n }),\n});\n\n/** `{id, object, deleted}` — the delete acknowledgement. Not yet a `core` schema; see ADR-0043. */\nexport const DeletedSchema = z.object({\n id: z.string(),\n object: z.string(),\n deleted: z.boolean(),\n});\n\n/** Endpoints whose body `core` does not model yet (shell exec, billing). Passed through verbatim. */\nexport const RawSchema = z.record(z.string(), z.unknown());\n\n/**\n * A PAGE WHOSE ROWS MAY BE NEWER THAN THIS CLIENT (`canonical-spec §8`).\n *\n * The event type set is additive and the Worker deploys on its own schedule, so every published\n * client eventually meets a row it has no schema for. `page(EventSchema).parse` threw the WHOLE\n * page away for one such row — a customer on `0.3.0` reading any session that carries a message\n * got a `ZodError` instead of a transcript. `stream.ts` already refuses that trade: it skips the\n * frame and keeps the cursor. This is the same rule for a list.\n *\n * The envelope stays strict. `has_more` and `next_cursor` are how a caller pages to the end, and a\n * client that could not read those would be guessing rather than degrading.\n *\n * `skipped` counts the rows left out, so a skip is never silent. Throwing would undo the point of\n * this function (one newer row would cost the whole page again), so the page reports the count.\n */\nexport function tolerantPage<T extends z.ZodType>(item: T): z.ZodType<{\n data: z.output<T>[];\n has_more: boolean;\n next_cursor: string | null;\n skipped: number;\n}> {\n return z\n .object({ data: z.array(z.unknown()), has_more: z.boolean(), next_cursor: z.string().nullable() })\n .transform((body) => {\n const data = body.data.flatMap((row) => {\n const parsed = item.safeParse(row);\n return parsed.success ? [parsed.data as z.output<T>] : [];\n });\n return { ...body, data, skipped: body.data.length - data.length };\n });\n}\n\n/**\n * Every id in a path is `encodeURIComponent`-ed at its call site, so it stays one segment (QA Q19).\n * Three ids no encoding keeps in place: `new URL()` folds `.` and `..` into the route even\n * percent-encoded (`agents.delete(\"..\")` is `DELETE /v1/`), and the API drops a trailing empty one\n * (`agents.get(\"\")` is the list). No id is any of them, so such a call is refused before it is sent,\n * as the `validation_failed` the server would answer for any other malformed request.\n */\nconst DOT_SEGMENT = /^(?:\\.|%2e){1,2}$/i;\n\nfunction url(config: ClientConfig, call: Call): string {\n const segments = call.path.split(\"/\");\n if (segments.some((segment) => DOT_SEGMENT.test(segment)) || segments.at(-1) === \"\") {\n const message = `an id cannot be \".\", \"..\" or empty: ${call.path}`;\n throw new ApiError(400, { type: \"invalid_request\", code: \"validation_failed\", message, request_id: \"\" });\n }\n const target = new URL(config.baseUrl.replace(/\\/+$/, \"\") + call.path);\n for (const [key, value] of Object.entries(call.query ?? {})) {\n if (value !== undefined) target.searchParams.set(key, String(value));\n }\n return target.toString();\n}\n\nexport function headersFor(config: ClientConfig, call: Call, accept: string): Headers {\n const headers = new Headers({\n authorization: `Bearer ${config.apiKey}`,\n \"vetta-version\": API_VERSION,\n accept,\n });\n // A multipart body must keep the boundary `fetch` generates, so it declares no content-type.\n if (call.body !== undefined && !(call.body instanceof FormData) && !(call.body instanceof Uint8Array)) {\n headers.set(\"content-type\", \"application/json\");\n }\n if (MUTATING.has(call.method)) headers.set(\"idempotency-key\", config.idempotencyKey());\n for (const [name, value] of Object.entries(call.headers ?? {})) headers.set(name, value);\n return headers;\n}\n\n/** Raw response — used by the SSE consumer, which reads the body itself. */\nexport async function send(config: ClientConfig, call: Call, accept: string): Promise<Response> {\n const body =\n call.body instanceof FormData || call.body instanceof Uint8Array ? call.body : JSON.stringify(call.body);\n // Called bare: reached as `config.fetch(…)` its `this` is the config, which a browser and workerd\n // refuse as an Illegal invocation (`deployment-runbook.md §8`).\n const { fetch } = config;\n return fetch(url(config, call), {\n method: call.method,\n headers: headersFor(config, call, accept),\n ...(call.body === undefined ? {} : { body }),\n });\n}\n\n/**\n * A failure body that is not the envelope — an edge or firewall HTML page, an upstream's plain text —\n * still has a status worth branching on (QA 2026-11-03, ADR-1817). Only taxonomy codes (`core`), and\n * only where the status names one; any other status stays `internal_error`. A 502/503/504 is\n * `provider_error`: something in front of the API failed, and the remedy is a retry.\n */\nconst CODE_BY_STATUS: Record<number, ErrorCode> = {\n 400: \"validation_failed\",\n 401: \"unauthorized\",\n 403: \"forbidden\",\n 404: \"not_found\",\n 405: \"method_not_allowed\",\n 413: \"validation_failed\",\n 415: \"validation_failed\",\n 422: \"validation_failed\",\n 429: \"rate_limited\",\n 501: \"feature_not_configured\",\n 502: \"provider_error\",\n 503: \"provider_error\",\n 504: \"provider_error\",\n};\n\n/**\n * The API answers every 403 with the envelope (§3), so a 403 without one never reached it: the edge\n * in front refused the request, most often because a body reads like SQL (QA 2026-11-03, ADR-1897).\n * It wins over the generic fixed message below.\n */\nconst BLOCKED_AT_EDGE =\n \"the request was blocked before it reached the API (HTTP 403); this can happen when a request body looks like SQL\";\n\n/**\n * The message for a failure body that is not the envelope. It is FIXED and never quotes the body:\n * an edge or proxy page carries the vendor's name and ids, and this message reaches customers\n * through the CLI and the web app (white-label, ADR-1817).\n */\nfunction unreadableMessage(status: number): string {\n if (status === 403) return BLOCKED_AT_EDGE;\n if (status === 401) return \"HTTP 401: the API key was rejected and the response had no readable details; check the API key and that baseUrl points at the API\";\n return `HTTP ${status}: the error response had no readable details`;\n}\n\n/** Turns a non-2xx response into the one envelope; a body that is not one is coded from its status. */\nexport function apiErrorFrom(response: Response, text: string): ApiError {\n const envelope = EnvelopeSchema.safeParse(parseJson(text));\n if (envelope.success) return new ApiError(response.status, envelope.data.error);\n const code = CODE_BY_STATUS[response.status] ?? \"internal_error\";\n return new ApiError(response.status, {\n type: new VettaError(code, \"\").type,\n code,\n message: unreadableMessage(response.status),\n request_id: response.headers.get(\"x-request-id\") ?? \"\",\n });\n}\n\nfunction parseJson(text: string): unknown {\n if (text.trim() === \"\") return {};\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return null;\n }\n}\n\n/** JSON call: throws `ApiError` on any non-2xx, and `ResponseParseError` on a body `schema` refuses. */\nexport async function request<T>(\n config: ClientConfig,\n schema: z.ZodType<T>,\n call: Call,\n): Promise<T> {\n const response = await send(config, call, \"application/json\");\n const text = await response.text();\n if (!response.ok) throw apiErrorFrom(response, text);\n const parsed = schema.safeParse(parseJson(text));\n if (!parsed.success) throw new ResponseParseError(response, call, parsed.error);\n return parsed.data;\n}\n\n/** Body as bytes with the type it was stored under — an object read (`GET …/objects/{key}`, §38). */\nexport async function bytes(config: ClientConfig, call: Call): Promise<{ bytes: Uint8Array; contentType: string }> {\n const response = await send(config, call, \"*/*\");\n if (!response.ok) throw apiErrorFrom(response, await response.text());\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: response.headers.get(\"content-type\") ?? \"application/octet-stream\",\n };\n}\n\n/** Body as text — the one endpoint that answers with bytes (`GET /v1/files/{id}?download=true`). */\nexport async function text(config: ClientConfig, call: Call): Promise<string> {\n const response = await send(config, call, \"*/*\");\n const body = await response.text();\n if (!response.ok) throw apiErrorFrom(response, body);\n return body;\n}\n","/**\n * Vetta Apps — hosted web applications (`canonical-spec §29`, `docs/api/apps.mdx`). One method per\n * route. An app is org-level like a domain; the asynchronous halves (a fullstack backend, a\n * running build) advance on read, so polling is `get`/`deployments.list` again.\n */\nimport {\n AppDeploymentFilesSchema,\n AppDeploymentSchema,\n AppDomainSchema,\n AppAccessSchema,\n AppPermissionsSchema,\n AppEntrySchema,\n AppSchema,\n AppSecretSchema,\n BlueprintArtifactSchema,\n BlueprintInstallSchema,\n CompanyTemplateDraftSchema,\n EarningsPayoutAccountSchema,\n ListingChecksSchema,\n OwnListingsSchema,\n ProjectContextSchema,\n page,\n type CompanyTemplateDraft,\n type AppType,\n type BlueprintBudget,\n type BlueprintSelection,\n CreatorProfileSchema,\n type CreatorProfilePatch,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, tolerantPage, type ClientConfig } from \"./http\";\n\n/** `GET /v1/blueprints/preview` — what a new project of a published pair would be called here. */\nexport const InstallPreviewSchema = z.object({\n object: z.literal(\"install_preview\"),\n project: z.string(),\n blueprint: z.string(),\n template: z.string(),\n artifact_version: z.string(),\n /** `\"\"`, or `\"<project>-\"` when any of the crew's names is taken here (ADR-1104). */\n name_prefix: z.string(),\n agents: z.array(z.string()),\n apps: z.array(z.string()),\n identities: z.array(z.string()),\n});\nexport type InstallPreview = z.infer<typeof InstallPreviewSchema>;\n\n/**\n * `mcp` is the path the app serves MCP on (`\"/mcp\"`); `fullstack` only.\n *\n * `project` names the project this app belongs to, and the server refuses a name another project\n * owns (ADR-0375). `adopt` transfers such a name deliberately — it is how `naive up --adopt`\n * reaches the wire, and it is never a default.\n */\nexport type AppCreate = {\n name: string;\n description?: string;\n type?: AppType;\n mcp?: string;\n project?: string;\n adopt?: boolean;\n};\n/** `mcp: null` forgets the token; a new path mints one; the current path is a no-op (§29.2). */\n/** `project` is an ownership assertion, never written: the server refuses a stamp you do not own. */\nexport type AppPatch = { name?: string; description?: string | null; mcp?: string | null; project?: string };\n\n/**\n * One apply of one declaration (`canonical-spec §29.6`). It lives on this namespace because §29.6\n * is inside §29: the install is the row `app.project` was always pointing at.\n *\n * `expected_revision` is `expected_version` (§12), copied — omit it for the deliberate\n * unconditional apply; send it and a mismatch is refused `409 revision_conflict` whose message\n * names the paths at which the stored declaration and this one disagree. `0` is a create: a\n * project that already exists is refused (ADR-1104).\n */\nexport type InstallApply = {\n project: string;\n /**\n * Omit it only when `blueprint` and `template` name a published artifact — the catalog holds that\n * declaration server-side (§31.1) and the apply reads it there. A working tree always has one.\n */\n declaration?: Record<string, unknown>;\n blueprint?: string | null;\n template?: string | null;\n artifact_version?: string | null;\n answers?: Record<string, unknown>;\n /**\n * The caps to arm the published pair's timers with, one per `schedules` row named by its\n * `(agent, cron)`; a timer not named keeps its published cap. Read only when the catalog supplies\n * the declaration (§29.6).\n */\n budgets?: BlueprintBudget[];\n /**\n * Which of the artifact's agents and apps to provision, by name (§31.2). Omitted is everything;\n * a selection that leaves out a `required` one is refused `validation_failed` naming it.\n */\n selection?: BlueprintSelection;\n source?: \"studio\" | \"cli\";\n expected_revision?: number;\n};\n\n/** The catalog list's own filters, beside the pagination every list takes (`canonical-spec §31`). */\nexport type ArtifactQuery = {\n blueprint?: string | undefined;\n template?: string | undefined;\n limit?: number | undefined;\n after?: string | undefined;\n};\n\nconst list = <T extends z.ZodType>(item: T) => z.object({ object: z.literal(\"list\"), data: z.array(item) });\n\nexport const DbResultSchema = z.object({\n object: z.literal(\"app_db_result\"),\n rows: z.array(z.unknown()),\n row_count: z.number(),\n});\n\nexport const apps = (config: ClientConfig) => ({\n /** Idempotent on the name: creating an app that exists returns it. */\n create: (body: AppCreate) => request(config, AppSchema, { method: \"POST\", path: \"/v1/apps\", body }),\n /**\n * `name` is the by-name lookup app upsert is built on (§29.2): app names are unique per\n * organization, so it answers with one row or none. It was on the route and on\n * `packages/blueprints` — which reaches `/v1/apps?name=` through the raw request helper — and on\n * this method's type it was missing, so an SDK caller had to list the whole org and filter.\n */\n list: (\n query: { name?: string | undefined; limit?: number | undefined; after?: string | undefined } = {},\n ) => request(config, page(AppSchema), { method: \"GET\", path: \"/v1/apps\", query }),\n get: (id: string) => request(config, AppSchema, { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}` }),\n update: (id: string, body: AppPatch) =>\n request(config, AppSchema, { method: \"PATCH\", path: `/v1/apps/${encodeURIComponent(id)}`, body }),\n /** Tears down the hosting project and, for `fullstack`, the app database with it. */\n delete: (id: string) => request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/apps/${encodeURIComponent(id)}` }),\n\n /**\n * Ships the whole site in one call: path → base64 bytes. The build then runs; poll the list.\n * `content_hash` is an opaque digest of the files, echoed on reads so a client can skip an\n * unchanged site next time.\n */\n deploy: (id: string, files: Record<string, string>, content_hash?: string) =>\n request(config, AppDeploymentSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(id)}/deployments`,\n body: content_hash === undefined ? { files } : { files, content_hash },\n }),\n /**\n * Ships one of the app's earlier deployments again, as a new one, from the files the platform\n * kept: nothing is downloaded or uploaded, so a site of any deployable size comes back.\n */\n redeploy: (id: string, fromDeployment: string) =>\n request(config, AppDeploymentSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(id)}/deployments`,\n body: { from_deployment: fromDeployment },\n }),\n deployments: (id: string, query: { limit?: number | undefined } = {}) =>\n request(config, page(AppDeploymentSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/deployments`, query }),\n /** The file-map a deployment shipped, path → base64; `not_found` for a build made before files were kept. */\n deploymentFiles: (id: string, deploymentId: string) =>\n request(config, AppDeploymentFilesSchema, { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/deployments/${encodeURIComponent(deploymentId)}/files` }),\n\n /**\n * Write-only: the value goes to the app's environment and never comes back on any read.\n * `value_hash` is an opaque digest of the value, echoed on reads so a client can skip an\n * unchanged write next time.\n */\n setSecret: (id: string, body: { name: string; value: string; value_hash?: string }) =>\n request(config, AppSecretSchema, { method: \"POST\", path: `/v1/apps/${encodeURIComponent(id)}/secrets`, body }),\n secrets: (id: string) =>\n request(config, list(AppSecretSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/secrets` }),\n deleteSecret: (id: string, name: string) =>\n request(config, z.object({ object: z.literal(\"app_secret\"), name: z.string(), deleted: z.boolean() }), {\n method: \"DELETE\",\n path: `/v1/apps/${encodeURIComponent(id)}/secrets/${encodeURIComponent(name)}`,\n }),\n\n /**\n * A one-click way into an app whose operator gate the platform generated (§29.7).\n *\n * Answers `{ url, ticket }` and never the token itself: the ticket is a two-minute HMAC keyed by\n * it. POST the ticket to the url as a form field from the operator's browser — the app trades it\n * for its own session cookie — and never put it in a query string.\n */\n entry: (id: string) => request(config, AppEntrySchema, { method: \"POST\", path: `/v1/apps/${encodeURIComponent(id)}/entry` }),\n\n /**\n * How a person gets in without the Studio (§29.2, ADR-0656): the app's url and its generated\n * `DASHBOARD_PASSWORD` — `null` until one is provisioned. The one audited reveal of an app secret;\n * `rotateAccess` regenerates the password **and** the `DASHBOARD_TOKEN`, and answers the new\n * password. The token always turns because the dashboard's session cookie *is* the token: a\n * rotation that left it alone would hand the next person a new password while the last one kept\n * thirty days of `/api/*`. Rotating is revoking, and it signs out every browser already signed\n * in. Hand the value to a person; never put it in a URL or a log.\n */\n /** What the app's own key lets it do with Naive: its scopes, never the key (§29.10, ADR-1048). */\n permissions: (id: string) => request(config, AppPermissionsSchema, { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/permissions` }),\n access: (id: string) => request(config, AppAccessSchema, { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/access` }),\n rotateAccess: (id: string) => request(config, AppAccessSchema, { method: \"POST\", path: `/v1/apps/${encodeURIComponent(id)}/access` }),\n\n /** The domain must already exist at `/v1/domains`; connecting is pointing, never registering. */\n connectDomain: (id: string, domainId: string) =>\n request(config, AppDomainSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(id)}/domains`,\n body: { domain_id: domainId },\n }),\n domains: (id: string) =>\n request(config, list(AppDomainSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(id)}/domains` }),\n disconnectDomain: (id: string, domain: string) =>\n request(config, z.object({ object: z.literal(\"app_domain\"), domain: z.string(), deleted: z.boolean() }), {\n method: \"DELETE\",\n path: `/v1/apps/${encodeURIComponent(id)}/domains/${encodeURIComponent(domain)}`,\n }),\n\n /**\n * The install: what was applied to a project, by which writer, against which revision. `apply`\n * of a declaration RECORDS it and provisions nothing. `apply` of a published pair, made by a\n * signed-in person, may answer `202` with `status: \"pending\"`: the reconcile runs after the\n * response, and `list({ project })` is how the row is watched until it says `applied` or `failed`.\n */\n installs: {\n apply: (body: InstallApply) =>\n request(config, BlueprintInstallSchema, {\n method: \"POST\",\n path: \"/v1/blueprints/installs\",\n body,\n }),\n list: (\n query: { project?: string | undefined; limit?: number | undefined; after?: string | undefined } = {},\n ) =>\n request(config, page(BlueprintInstallSchema), {\n method: \"GET\",\n path: \"/v1/blueprints/installs\",\n query,\n }),\n /**\n * Rewrites the answers the crew reads as its project context (§31.8) — validated against the\n * artifact's questions, stamped `context_updated_at`, and NOT a new revision: nothing is\n * re-provisioned by it.\n */\n update: (id: string, body: { answers: Record<string, string | string[]> }) =>\n request(config, BlueprintInstallSchema, {\n method: \"PATCH\",\n path: `/v1/blueprints/installs/${encodeURIComponent(id)}`,\n body,\n }),\n /** What the crew's `project_context` tool reads (§31.8), derived from this install and its report. */\n context: (id: string) =>\n request(config, ProjectContextSchema, { method: \"GET\", path: `/v1/blueprints/installs/${encodeURIComponent(id)}/context` }),\n /**\n * Removes the template from the company (ADR-1513): fires its crew and drops the install. Its apps,\n * personas, skills, files and chats stay. The owner's own sign-in only; an API key is refused.\n */\n remove: (id: string) => request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/blueprints/installs/${encodeURIComponent(id)}` }),\n /**\n * A dry run of applying a published pair as a NEW project (ADR-1512): the names its agents, apps\n * and personas would take here — prefixed when one clashes (ADR-1104) — refused as the apply would\n * refuse it. Writes nothing.\n */\n preview: (query: { blueprint: string; template: string; project: string }) =>\n request(config, InstallPreviewSchema, { method: \"GET\", path: \"/v1/blueprints/preview\", query }),\n },\n\n /**\n * The published catalog (`canonical-spec §31`) — every blueprint × template that can be run, with\n * the setup questions to ask first, the crew and apps it provisions, and the timers it runs.\n *\n * It sits on this namespace beside `installs` because it is the other half of one act: the\n * artifact is what is applied and the install is the record that it was. `blueprint` and\n * `template` narrow it, and an apply of one of these rows sends that pair in place of a\n * declaration it was never given.\n *\n * The page is parsed leniently (`tolerantPage`): a row this build cannot read — a data-only\n * blueprint's empty `trees` (ADR-0900) met a build that required one — is skipped, not thrown.\n */\n artifacts: {\n list: (query: ArtifactQuery = {}) =>\n request(config, tolerantPage(BlueprintArtifactSchema), {\n method: \"GET\",\n path: \"/v1/blueprints/artifacts\",\n query,\n }),\n },\n\n /**\n * \"Duplicate this company\" (`canonical-spec §61`): `draft` exports the crew and rewrites its company\n * specifics (a metered model call), `create` saves the draft a person approved as a PRIVATE template\n * of this organization, and `list` reads those back as catalog rows. Install one with\n * `installs.apply({ blueprint, template, project, expected_revision: 0 })`; no other organization can.\n * A company is listed in the marketplace from chat (`list_as_template`, ADR-1747), not from these.\n */\n companyTemplates: {\n draft: (body: { project?: string | undefined } = {}) => request(config, CompanyTemplateDraftSchema, { method: \"POST\", path: \"/v1/company_templates/draft\", body }),\n create: (body: { name: string; project?: string | undefined; declaration: CompanyTemplateDraft[\"declaration\"] }) =>\n request(config, BlueprintArtifactSchema, { method: \"POST\", path: \"/v1/company_templates\", body }),\n list: (query: { template?: string | undefined; limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, tolerantPage(BlueprintArtifactSchema), { method: \"GET\", path: \"/v1/company_templates\", query }),\n },\n\n /** The company's own listings (ADR-1821), and what `list_as_template` would list (ADR-1747): its card reads this. Only the tool posts a listing. */\n listings: {\n list: () => request(config, OwnListingsSchema, { method: \"GET\", path: \"/v1/listings\" }),\n checks: (query: { project?: string | undefined } = {}) => request(config, ListingChecksSchema, { method: \"GET\", path: \"/v1/listings/checks\", query }),\n },\n\n /**\n * The company's public profile, which its listed templates credit (`canonical-spec §65`): picture,\n * name and description. In one of Naive's own organizations it is `NAIVE_PROFILE` and `update`\n * answers `version_conflict`. Only an owner or admin may update; `avatar: null` removes the picture.\n */\n profile: {\n get: () => request(config, CreatorProfileSchema, { method: \"GET\", path: \"/v1/listings/profile\" }),\n update: (body: CreatorProfilePatch) => request(config, CreatorProfileSchema, { method: \"PATCH\", path: \"/v1/listings/profile\", body }),\n },\n\n /** Where the company's marketplace earnings are paid (ADR-1598): its owner, signed in, sets it up. Only the tool pays out. */\n earnings: {\n setUpPayouts: (body: { country?: string | undefined } = {}) => request(config, EarningsPayoutAccountSchema, { method: \"POST\", path: \"/v1/earnings/payouts/account\", body }),\n },\n\n /** The app-scoped database — `fullstack` apps only; a frontend-only app answers 501. */\n query: (id: string, query: string) =>\n request(config, DbResultSchema, { method: \"POST\", path: `/v1/apps/${encodeURIComponent(id)}/db/query`, body: { query } }),\n});\n","/** Connected-account paid advertising (`canonical-spec.md §51`). */\n\nimport { AdCampaignInsightsSchema, AdCampaignSchema, page } from \"@vetta/core\";\nimport { ApiError, request, type ClientConfig } from \"./http\";\n\nexport interface SearchCampaignCreate {\n provider: \"google\";\n connection_id: string;\n /** Google Ads customer ID without dashes. */\n customer_id: string;\n name: string;\n final_url: string;\n /** Finite campaign-total budget, in micro-USD. */\n budget_micro_usd: number;\n cpc_ceiling_micro_usd: number;\n start_date: string;\n end_date: string;\n keywords: string[];\n headlines: string[];\n descriptions: string[];\n}\n\nexport interface AdAccount {\n connection_id: string;\n customer_id: string;\n}\n\n/**\n * Every read and status change names one connected ad account; there is no cross-account list. A\n * JS caller that leaves it out got a bare `TypeError` (QA); it is now a rejected `validation_failed`\n * naming the field, before anything is sent, as the API answers the same request.\n */\nfunction need<T extends AdAccount>(account: T | undefined): T {\n if (account?.connection_id && account.customer_id) return account;\n const param = account?.connection_id ? \"customer_id\" : \"connection_id\";\n const message = `${param} is required: pass { connection_id, customer_id } for the connected ad account`;\n throw new ApiError(400, { type: \"invalid_request\", code: \"validation_failed\", message, request_id: \"\", param });\n}\n\nconst query = (account: AdAccount) => {\n const { connection_id, customer_id } = need(account);\n return { connection_id, customer_id };\n};\n\nexport const ads = (config: ClientConfig) => ({\n /** Creates the complete Google Search campaign paused. This call never starts spend. */\n createSearchCampaign: (body: SearchCampaignCreate) =>\n request(config, AdCampaignSchema, { method: \"POST\", path: \"/v1/ads/search_campaigns\", body }),\n listCampaigns: async (account: AdAccount) =>\n request(config, page(AdCampaignSchema), { method: \"GET\", path: \"/v1/ads/campaigns\", query: query(account) }),\n insights: async (campaign: string, account: AdAccount) =>\n request(config, AdCampaignInsightsSchema, {\n method: \"GET\",\n path: `/v1/ads/campaigns/${encodeURIComponent(campaign)}/insights`,\n query: query(account),\n }),\n /** Starts external Google Ads charges. The literal acknowledgement is intentionally unavoidable. */\n activate: async (campaign: string, account: AdAccount & { acknowledge_external_spend: true }) =>\n request(config, AdCampaignSchema, {\n method: \"POST\",\n path: `/v1/ads/campaigns/${encodeURIComponent(campaign)}/activate`,\n body: need(account),\n }),\n pause: async (campaign: string, account: AdAccount) =>\n request(config, AdCampaignSchema, {\n method: \"POST\",\n path: `/v1/ads/campaigns/${encodeURIComponent(campaign)}/pause`,\n body: need(account),\n }),\n});\n","/**\n * Deployments (an agent on a cron) and outbound webhook subscriptions — the two surfaces that run\n * without a human at the terminal (`canonical-spec.md §12, §14`).\n *\n * Two replies carry a secret that exists **once**: `POST /v1/webhooks` and `POST …/rotate`. The\n * canonical `WebhookEndpointSchema` has no `secret` field, and parsing with it would silently drop\n * the only copy — so both are parsed with a schema that keeps it.\n */\nimport {\n DeploymentRunSchema,\n DeploymentSchema,\n WebhookDeliverySchema,\n WebhookEndpointSchema,\n page,\n type Deployment,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\ntype DeploymentConfig = Omit<\n Deployment,\n \"id\" | \"object\" | \"next_run_at\" | \"created_at\" | \"schedule_status\"\n>;\n/** `budget_micro_usd` is required, as the route requires it; `0` runs on the agent's task budget (ADR-1875). */\nexport type DeploymentCreate = Pick<DeploymentConfig, \"agent_id\" | \"cron\" | \"input_template\" | \"budget_micro_usd\"> &\n Partial<DeploymentConfig>;\nexport type DeploymentPatch = Partial<Omit<DeploymentConfig, \"agent_id\">>;\n\nexport const deployments = (config: ClientConfig) => ({\n /** `agent_version` pins the exact version this cron fires (§12); `timezone` reads the cron (ADR-0074). */\n create: (body: DeploymentCreate) =>\n request(config, DeploymentSchema, { method: \"POST\", path: \"/v1/deployments\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(DeploymentSchema), { method: \"GET\", path: \"/v1/deployments\", query }),\n get: (id: string) =>\n request(config, DeploymentSchema, { method: \"GET\", path: `/v1/deployments/${encodeURIComponent(id)}` }),\n update: (id: string, body: DeploymentPatch) =>\n request(config, DeploymentSchema, { method: \"PATCH\", path: `/v1/deployments/${encodeURIComponent(id)}`, body }),\n /** Fire once, now — the \"run it and see\" verb; `enabled` is the schedule. */\n run: (id: string) =>\n request(config, DeploymentRunSchema, {\n method: \"POST\",\n path: `/v1/deployments/${encodeURIComponent(id)}/run`,\n body: {},\n }),\n runs: (id: string, query: ListQuery = {}) =>\n request(config, page(DeploymentRunSchema), {\n method: \"GET\",\n path: `/v1/deployments/${encodeURIComponent(id)}/runs`,\n query,\n }),\n pause: (id: string) =>\n request(config, DeploymentSchema, {\n method: \"POST\",\n path: `/v1/deployments/${encodeURIComponent(id)}/pause`,\n body: {},\n }),\n resume: (id: string) =>\n request(config, DeploymentSchema, {\n method: \"POST\",\n path: `/v1/deployments/${encodeURIComponent(id)}/resume`,\n body: {},\n }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/deployments/${encodeURIComponent(id)}` }),\n});\n\n/** Shown once, at create. Keeping `secret` on the parse is the whole point of this schema. */\nexport const WebhookCreatedSchema = WebhookEndpointSchema.extend({ secret: z.string() });\n\n/** Both secrets sign until `overlap_expires_at`, so a receiver can redeploy without dropping one. */\nexport const RotatedSchema = z.object({\n id: z.string(),\n secret: z.string(),\n overlap_expires_at: z.string(),\n});\n\nexport type WebhookPatch = { url?: string; events?: string[]; enabled?: boolean };\n\nexport const webhooks = (config: ClientConfig) => ({\n create: (body: { url: string; events: string[] }) =>\n request(config, WebhookCreatedSchema, { method: \"POST\", path: \"/v1/webhooks\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(WebhookEndpointSchema), { method: \"GET\", path: \"/v1/webhooks\", query }),\n get: (id: string) =>\n request(config, WebhookEndpointSchema, { method: \"GET\", path: `/v1/webhooks/${encodeURIComponent(id)}` }),\n update: (id: string, body: WebhookPatch) =>\n request(config, WebhookEndpointSchema, { method: \"PATCH\", path: `/v1/webhooks/${encodeURIComponent(id)}`, body }),\n rotate: (id: string, overlapHours?: number) =>\n request(config, RotatedSchema, {\n method: \"POST\",\n path: `/v1/webhooks/${encodeURIComponent(id)}/rotate`,\n body: overlapHours === undefined ? {} : { overlap_hours: overlapHours },\n }),\n deliveries: (id: string, query: ListQuery = {}) =>\n request(config, page(WebhookDeliverySchema), {\n method: \"GET\",\n path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries`,\n query,\n }),\n delivery: (id: string, deliveryId: string) =>\n request(config, WebhookDeliverySchema, {\n method: \"GET\",\n path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries/${encodeURIComponent(deliveryId)}`,\n }),\n /** Sends a `webhook.test` envelope to the endpoint's real URL and answers the `pending` row. */\n test: (id: string) =>\n request(config, WebhookDeliverySchema, { method: \"POST\", path: `/v1/webhooks/${encodeURIComponent(id)}/test` }),\n /** Resends a past delivery's exact envelope; a new attempt, the same `evt_` id. */\n redeliver: (id: string, deliveryId: string) =>\n request(config, WebhookDeliverySchema, {\n method: \"POST\",\n path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries/${encodeURIComponent(deliveryId)}/redeliver`,\n }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/webhooks/${encodeURIComponent(id)}` }),\n});\n","/**\n * The team board (`canonical-spec §28.6`, `docs/team/board.mdx`). The durable half of a team: a\n * coordinator's transcript scrolls away, the card that says who holds what does not.\n *\n * **A board is addressed by its `brd_` id or by the `agt_` id of the agent that owns it.** That is\n * the whole reason `cards.create` is reachable on a team that has never written a card: a board\n * with no cards has never told anyone its id, so an agent id is the only reference a caller can\n * have.\n *\n * There is one board per agent, so `create` is really an *ensure*: calling it twice is not a conflict\n * and answers the same board. Asking a caller to invent a comment's `author` was the other half of\n * that mistake — the server knows the principal, so it signs the comment and there is no field.\n *\n * `get` returns the **board**. It used to take an agent id and answer a page of *cards*, which read\n * as an object getter and was not one — nothing in this client could read a board's own id, its\n * owner, or how much work stood on it. The cards live under `cards`, where the name says so, and\n * `cards.ofAgent` keeps the one route that answers an agent's cards directly.\n *\n * The four statuses are fixed (`todo|doing|blocked|done`) and are not configurable columns: a\n * per-team column list would make `board_write`'s contract depend on the agent's config. The reason\n * a card is stuck rides in `blocked_by`, as data rather than as a lane.\n */\nimport {\n BoardCardSchema,\n BoardCommentSchema,\n BoardSchema,\n page,\n type BoardStatus,\n} from \"@vetta/core\";\nimport type { ListQuery } from \"./control-plane\";\nimport { request, type ClientConfig } from \"./http\";\n\n/**\n * Every field but the title is optional; the wire fills in `todo`, unassigned and unblocked.\n * `key` (≤128 chars, §28.16) makes the create idempotent: the same key on the same board answers\n * the card it made the first time, so a template's seed can be re-applied without a second card.\n */\nexport type CardCreate = {\n title: string;\n body?: string | undefined;\n status?: BoardStatus | undefined;\n assignee?: string | null | undefined;\n blocked_by?: string[] | undefined;\n key?: string | undefined;\n};\n\n/**\n * A move is `{status}` and nothing else. `assignee: null` unclaims; omitting it changes nothing.\n * `note` is what the holder wrote back — a `done` needs one on the call or already on the card.\n */\nexport type CardPatch = Partial<Omit<CardCreate, \"key\">> & { note?: string | undefined };\n\nexport const board = (config: ClientConfig) => ({\n /** One board: its id, its owner, and how many cards stand in each column. `not_found` for an agent with no board yet. */\n get: (boardRef: string) =>\n request(config, BoardSchema, { method: \"GET\", path: `/v1/boards/${encodeURIComponent(boardRef)}` }),\n /** Ensure the agent's board — `201` when this call minted it, `200` when it found one. */\n create: (agentId: string) =>\n request(config, BoardSchema, { method: \"POST\", path: `/v1/boards`, body: { agent_id: agentId } }),\n\n cards: {\n /**\n * A page of the board's cards. **`limit`/`after` are not a nicety here.** Both card routes sort\n * by column *before* they paginate, so a caller with no way to send a limit or walk a cursor\n * does not lose the tail of a list — it loses the last columns whole, and a `done` column that\n * renders empty reads as work never done.\n */\n list: (boardRef: string, query: ListQuery = {}) =>\n request(config, page(BoardCardSchema), { method: \"GET\", path: `/v1/boards/${encodeURIComponent(boardRef)}/cards`, query }),\n /** The same cards, reached from the agent — an empty page, and no board created, if the team has none. */\n ofAgent: (agentId: string, query: ListQuery = {}) =>\n request(config, page(BoardCardSchema), { method: \"GET\", path: `/v1/agents/${encodeURIComponent(agentId)}/board`, query }),\n create: (boardRef: string, body: CardCreate) =>\n request(config, BoardCardSchema, { method: \"POST\", path: `/v1/boards/${encodeURIComponent(boardRef)}/cards`, body }),\n get: (boardRef: string, cardId: string) =>\n request(config, BoardCardSchema, { method: \"GET\", path: `/v1/boards/${encodeURIComponent(boardRef)}/cards/${encodeURIComponent(cardId)}` }),\n update: (boardRef: string, cardId: string, body: CardPatch) =>\n request(config, BoardCardSchema, {\n method: \"PATCH\",\n path: `/v1/boards/${encodeURIComponent(boardRef)}/cards/${encodeURIComponent(cardId)}`,\n body,\n }),\n /**\n * Hand a card to a teammate by name (§28.18) — a `todo` card with an assignee and no open\n * blocker starts a session of theirs in this request, or after their current card when they are\n * busy. `null` takes it back.\n */\n assign: (boardRef: string, cardId: string, assignee: string | null) =>\n request(config, BoardCardSchema, {\n method: \"PATCH\",\n path: `/v1/boards/${encodeURIComponent(boardRef)}/cards/${encodeURIComponent(cardId)}`,\n body: { assignee },\n }),\n /** A card's comments, oldest first — they are a conversation, and the write shipped alone. */\n comments: (boardRef: string, cardId: string, query: ListQuery = {}) =>\n request(config, page(BoardCommentSchema), {\n method: \"GET\",\n path: `/v1/boards/${encodeURIComponent(boardRef)}/cards/${encodeURIComponent(cardId)}/comments`,\n query,\n }),\n /** No `author`: the server signs the comment with the principal behind this key. */\n comment: (boardRef: string, cardId: string, body: { body: string }) =>\n request(config, BoardCommentSchema, {\n method: \"POST\",\n path: `/v1/boards/${encodeURIComponent(boardRef)}/cards/${encodeURIComponent(cardId)}/comments`,\n body,\n }),\n },\n});\n","/**\n * Characters — a trained, reusable on-screen persona (`canonical-spec §33.6`). One method per route,\n * every response parsed with `@vetta/core`'s `CharacterSchema`: the wire object, never the provider's\n * handle for what it trained. `create` answers `202` with the character in `training`; `get` advances\n * it and is what a caller polls until `ready`, then names it as `character` on `media.images.generate`.\n */\nimport {\n CharacterSchema,\n page,\n type Character,\n type CharacterConsent,\n type CharacterPersona,\n type CharacterStatus,\n} from \"@vetta/core\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\nexport type { Character, CharacterConsent, CharacterPersona };\n\nexport type CharacterCreate = {\n name: string;\n description?: string | null | undefined;\n /** 1–16 reference photos of one person: each a stored file's `fil_` id or a public http(s) URL. */\n image_urls: string[];\n /** How the character talks and dresses; each line at most 500 characters. */\n persona?: CharacterPersona | undefined;\n /** Look names the character is usually drawn in, at most 12. */\n style_pack?: string[] | undefined;\n /**\n * Required: `{ attested: true }` — the person in the photos is you, or agreed to an AI likeness,\n * and is not a public figure (`CHARACTER_CONSENT_STATEMENT`). Kept on the character with who\n * confirmed it and when; photos of a public figure are refused.\n */\n consent: CharacterConsent;\n};\n\nexport type CharacterUpdate = {\n name?: string | undefined;\n description?: string | null | undefined;\n persona?: CharacterPersona | undefined;\n style_pack?: string[] | undefined;\n};\n\n/** `scope`: `organization` (yours) or `platform` (prebuilt, every org's to read; ADR-1360). */\nexport type CharacterFilter = { status?: CharacterStatus | undefined; scope?: Character[\"scope\"] | undefined };\n\nexport const characters = (config: ClientConfig) => ({\n /**\n * Paid: billed once per `Idempotency-Key`, which the client attaches to every write — or pass one\n * held for the form, so a resubmit names the training the first one started.\n */\n create: (body: CharacterCreate, opts: { idempotencyKey?: string } = {}) =>\n request(config, CharacterSchema, {\n method: \"POST\",\n path: \"/v1/characters\",\n body,\n ...(opts.idempotencyKey === undefined ? {} : { headers: { \"idempotency-key\": opts.idempotencyKey } }),\n }),\n list: (query: ListQuery & CharacterFilter = {}) =>\n request(config, page(CharacterSchema), { method: \"GET\", path: \"/v1/characters\", query }),\n /** `ref` is a `chr_` id **or** the character's name — the API resolves both. */\n get: (ref: string) =>\n request(config, CharacterSchema, { method: \"GET\", path: `/v1/characters/${encodeURIComponent(ref)}` }),\n /** Who it is: name, description, persona (merged by line) and looks, never the face. A prebuilt one is `409`. */\n update: (ref: string, body: CharacterUpdate) =>\n request(config, CharacterSchema, { method: \"PATCH\", path: `/v1/characters/${encodeURIComponent(ref)}`, body }),\n /** A soft delete: it can no longer be rendered as, and its name is free again. A prebuilt one is `409`. */\n delete: (ref: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/characters/${encodeURIComponent(ref)}` }),\n});\n","/**\n * The browser a computer carries (`canonical-spec §32`, `docs/api/browser.mdx`).\n *\n * `computers.browser(id)` binds one computer and exposes its actions: the eight\n * `BrowserActionRequest` kinds are one route (`POST …/browser/actions`, one body per kind, spelled\n * out one method each so the surface parsers read them), plus the session reads and the\n * identity-scoped login surface. The transport attaches `Idempotency-Key` to every mutation, which\n * covers the two the contract *requires* it on (`goto`, `act`). `variables` for `act` travel once,\n * on the call, and are never in a result.\n *\n * `contexts.grant` and `contexts.revoke` are human-session only — an API key gets `403 forbidden` —\n * and are here because a dashboard session is a caller of this client too. The live-view route is\n * deliberately absent: its URL is a bearer credential (§32.1), and the dashboard serves it\n * same-origin rather than through a method a script could log.\n */\nimport {\n BrowserActionResultSchema,\n BrowserContextSchema,\n BrowserGrantSchema,\n BrowserSessionSchema,\n VaultCredentialSchema,\n} from \"@vetta/core\";\nimport type {\n BrowserActionRequestSchema,\n BrowserCredentialSchema,\n BrowserLoginSchema,\n BrowserOptionsSchema,\n BrowserSignupSchema,\n CreateBrowserGrantSchema,\n SaveBrowserContextSchema,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\n\n/** The `browser` block of `computers.create`, before defaults are applied. */\nexport type BrowserOptionsInput = z.input<typeof BrowserOptionsSchema>;\n/** The request bodies, as a caller writes them (§32.3, §32.4). */\nexport type BrowserActionRequest = z.input<typeof BrowserActionRequestSchema>;\nexport type BrowserLogin = z.input<typeof BrowserLoginSchema>;\nexport type BrowserSignup = z.input<typeof BrowserSignupSchema>;\nexport type BrowserCredential = z.input<typeof BrowserCredentialSchema>;\nexport type SaveBrowserContext = z.input<typeof SaveBrowserContextSchema>;\nexport type CreateBrowserGrant = z.input<typeof CreateBrowserGrantSchema>;\n\ntype Of<K extends BrowserActionRequest[\"action\"]> = Omit<\n Extract<BrowserActionRequest, { action: K }>,\n \"action\"\n>;\n\n/** `204` when nothing was open (§32.3) is an empty body; the closed `browser_session` otherwise. */\nconst ClosedSchema = BrowserSessionSchema.or(z.object({}).strict());\n\nexport const computerBrowser = (config: ClientConfig, id: string) => ({\n goto: (url: string) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"goto\", url },\n }),\n click: (selector: string) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"click\", selector },\n }),\n type: (selector: string, text: string) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"type\", selector, text },\n }),\n /** `variables` fill `%name%` placeholders in the instruction and never come back in a result. */\n act: (instruction: string, variables?: Record<string, string>) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"act\", instruction, ...(variables === undefined ? {} : { variables }) },\n }),\n extract: (body: Of<\"extract\"> = {}) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"extract\", ...body },\n }),\n observe: (instruction: string) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"observe\", instruction },\n }),\n links: (query: Of<\"links\"> = {}) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"links\", ...query },\n }),\n screenshot: () =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/actions`,\n body: { action: \"screenshot\" },\n }),\n /** `404 not_found` when no browser is open on the computer. */\n status: () =>\n request(config, BrowserSessionSchema, { method: \"GET\", path: `/v1/computers/${encodeURIComponent(id)}/browser` }),\n /** The closed session with its `closed_at`, or `null` when nothing was open; closing is idempotent. */\n close: async () => {\n const closed = await request(config, ClosedSchema, {\n method: \"DELETE\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser`,\n });\n return \"object\" in closed ? closed : null;\n },\n saveContext: (body: SaveBrowserContext) =>\n request(config, BrowserContextSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/context`,\n body,\n }),\n /** Fills the vault credential `login:<service>` through placeholders; no plaintext returns. */\n login: (body: BrowserLogin) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/login`,\n body,\n }),\n signup: (body: BrowserSignup) =>\n request(config, BrowserActionResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/browser/signup`,\n body,\n }),\n});\n\nexport const browser = (config: ClientConfig) => ({\n credentials: {\n /** Seals `login:<service>` in the identity's vault. The reply is metadata — no value in it. */\n save: (body: BrowserCredential) =>\n request(config, VaultCredentialSchema, {\n method: \"POST\",\n path: \"/v1/browser/credentials\",\n body,\n }),\n },\n contexts: {\n /** Human session only. The same grantee twice is a `200` replay of the existing grant. */\n grant: (name: string, body: CreateBrowserGrant) =>\n request(config, BrowserGrantSchema, {\n method: \"POST\",\n path: `/v1/browser/contexts/${encodeURIComponent(name)}/grants`,\n body,\n }),\n /** Human session only. Deletes the context and every grant on it. */\n revoke: (name: string, identityId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/browser/contexts/${encodeURIComponent(name)}`,\n query: { identity_id: identityId },\n }),\n },\n});\n","/**\n * The managed browsers an agent opened beside a computer (`canonical-spec §41.6`,\n * `docs/api/browser-sessions.mdx`). The list is the computer's own rows, readable with any key, and is not\n * paginated — a computer drives a handful — so it comes back whole in the usual page envelope.\n *\n * `liveView` returns a bearer credential: the URL grants control of the browser with no further\n * auth. Hold it in memory, render it, and let it expire; never store or log it.\n */\nimport { BrowserLiveViewSchema, BrowserSessionSchema, page } from \"@vetta/core\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport const browserSessions = (config: ClientConfig) => ({\n list: (computerId: string) =>\n request(config, page(BrowserSessionSchema), {\n method: \"GET\",\n path: `/v1/computers/${encodeURIComponent(computerId)}/browser_sessions`,\n }),\n liveView: (computerId: string, id: string) =>\n request(config, BrowserLiveViewSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(computerId)}/browser_sessions/${encodeURIComponent(id)}/live_view`,\n body: {},\n }),\n});\n","/**\n * Comms — web domains, email inboxes and phone numbers (`canonical-spec §24`,\n * `docs/identity/{domains,email,phone}.mdx`). One method per route, the same rule as every other\n * group here: nothing names a route `apps/api/src/routes/index.ts` does not serve.\n *\n * **A domain is org-level; an inbox and a number are identity-level.** The docs nest domains under\n * an identity and the API does not (ADR-0119) — this file follows the API, because the client is a\n * transcription of the route table and not of the prose.\n *\n * The send acknowledgements are modelled here rather than in `@vetta/core` for the same reason\n * `DeletedSchema` is: they are two-field receipts the core schema set does not carry yet.\n */\nimport {\n DnsRecordSchema,\n DomainSchema,\n EmailInboxSchema,\n InboundMessageSchema,\n OutboundMessageSchema,\n PhoneNumberSchema,\n page,\n type DomainKind,\n type PhoneTierSchema,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\n\n/** `POST /v1/identities/{id}/emails/{eid}/send` — 202, the provider's message id deliberately absent. */\nconst EmailSendSchema = z.object({\n object: z.literal(\"email_send\"),\n accepted: z.boolean(),\n from: z.string(),\n to: z.array(z.string()),\n sent_at: z.string(),\n});\n\nconst SmsSendSchema = z.object({\n object: z.literal(\"sms_send\"),\n accepted: z.boolean(),\n from: z.string(),\n to: z.string(),\n sent_at: z.string(),\n});\n\n/** `sole_prop` | `standard` — the carrier registration tier (`core` exports the schema, not the type). */\nexport type PhoneTier = z.infer<typeof PhoneTierSchema>;\n\nexport type DomainCreate = { name?: string; kind: DomainKind; receive?: boolean };\nexport type DomainPurchase = { name: string; max_price_micro_usd: number; receive?: boolean };\nconst DomainQuoteSchema = z.object({\n object: z.literal(\"domain_quote\"),\n name: z.string(),\n available: z.boolean(),\n tier: z.enum([\"standard\", \"premium\"]).nullable(),\n registration_price_micro_usd: z.number().int().nullable(),\n renewal_price_micro_usd: z.number().int().nullable(),\n currency: z.literal(\"usd\"),\n reason: z.string().nullable(),\n});\nexport type InboxCreate =\n | { address: string; owning_agent_id: string }\n | { domain_id: string; owning_agent_id: string };\nexport type EmailSend = { to: string[]; subject: string; text: string };\nexport type PhoneProvision = {\n country?: string;\n tier: PhoneTier;\n legal_name: string;\n /** `standard` only. Write-through: handed to the carrier and never stored by us. */\n tax_id?: string;\n /** `sole_prop` only — the handset that receives the verification passcode. Never stored. */\n contact_phone?: string;\n e164?: string;\n /** The agent an inbound text is for. */\n owning_agent_id?: string;\n};\n\nexport const domains = (config: ClientConfig) => ({\n /** Connect a BYOD domain or mint the org's system subdomain. Idempotent on the name. */\n create: (body: DomainCreate) =>\n request(config, DomainSchema, { method: \"POST\", path: \"/v1/domains\", body }),\n /** Read-only authoritative availability and one-year pricing. */\n quote: (name: string) =>\n request(config, DomainQuoteSchema, { method: \"POST\", path: \"/v1/domains/quote\", body: { name } }),\n /** Debits Naive credits and buys through the platform registrar; never accepts card details. */\n purchase: (body: DomainPurchase) =>\n request(config, DomainSchema, { method: \"POST\", path: \"/v1/domains/purchase\", body }),\n list: (query: { limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, page(DomainSchema), { method: \"GET\", path: \"/v1/domains\", query }),\n get: (id: string) => request(config, DomainSchema, { method: \"GET\", path: `/v1/domains/${encodeURIComponent(id)}` }),\n /** Re-runnable. Each readiness track advances on its own; the domain comes back as the answer. */\n verify: (id: string) =>\n request(config, DomainSchema, { method: \"POST\", path: `/v1/domains/${encodeURIComponent(id)}/verify` }),\n /** Always allowed, on every kind — reading the zone is never the dangerous half. */\n records: (id: string) =>\n request(config, z.object({ object: z.literal(\"list\"), data: z.array(DnsRecordSchema) }), {\n method: \"GET\",\n path: `/v1/domains/${encodeURIComponent(id)}/records`,\n }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/domains/${encodeURIComponent(id)}` }),\n});\n\nexport const emails = (config: ClientConfig) => ({\n create: (identityId: string, body: InboxCreate) =>\n request(config, EmailInboxSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/emails`,\n body,\n }),\n list: (identityId: string, query: { limit?: number | undefined } = {}) =>\n request(config, page(EmailInboxSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/emails`,\n query,\n }),\n /** Turn on or off whether mail to the inbox wakes its owner. An inbox from before the wake shipped is off. */\n update: (identityId: string, inboxId: string, body: { wake: boolean }) =>\n request(config, EmailInboxSchema, {\n method: \"PATCH\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/emails/${encodeURIComponent(inboxId)}`,\n body,\n }),\n delete: (identityId: string, inboxId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/emails/${encodeURIComponent(inboxId)}`,\n }),\n /** Gated on the domain's `dns_status`; a premature send is a retryable `job_not_ready`. */\n send: (identityId: string, inboxId: string, body: EmailSend) =>\n request(config, EmailSendSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/emails/${encodeURIComponent(inboxId)}/send`,\n body,\n }),\n /** Everything that arrived for this persona, both channels unless one is named. */\n messages: (\n identityId: string,\n query: { channel?: \"email\" | \"sms\" | undefined; limit?: number | undefined } = {},\n ) =>\n request(config, page(InboundMessageSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/messages`,\n query,\n }),\n /** Mark one arrived message read or unread; a message already read keeps its first time. */\n markRead: (identityId: string, messageId: string, read: boolean) =>\n request(config, InboundMessageSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/messages/${encodeURIComponent(messageId)}/read`,\n body: { read },\n }),\n /** What the persona sent, newest first — through the API and through its agent alike. */\n sent: (identityId: string, query: { limit?: number | undefined } = {}) =>\n request(config, page(OutboundMessageSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/sent`,\n query,\n }),\n});\n\nexport const phones = (config: ClientConfig) => ({\n /** 202, not 201: the number exists and can receive, but outbound waits on a carrier decision. */\n provision: (identityId: string, body: PhoneProvision) =>\n request(config, PhoneNumberSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/phones`,\n body,\n }),\n list: (identityId: string, query: { limit?: number | undefined } = {}) =>\n request(config, page(PhoneNumberSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/phones`,\n query,\n }),\n /** Set, or clear with `null`, the agent this number's inbound texts are for. */\n update: (identityId: string, phoneId: string, body: { owning_agent_id: string | null }) =>\n request(config, PhoneNumberSchema, {\n method: \"PATCH\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/phones/${encodeURIComponent(phoneId)}`,\n body,\n }),\n release: (identityId: string, phoneId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/phones/${encodeURIComponent(phoneId)}`,\n }),\n /** Refused with `compliance_pending` until the campaign is approved. That is a carrier rule. */\n send: (identityId: string, phoneId: string, body: { to: string; text: string }) =>\n request(config, SmsSendSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identityId)}/phones/${encodeURIComponent(phoneId)}/send`,\n body,\n }),\n});\n","/**\n * Connections — \"Passport\" (`canonical-spec §25`, `docs/identity/connections.mdx`). One method per\n * route, the same rule as every other group: nothing here names a route `apps/api` does not serve.\n *\n * The wire shapes are declared here rather than in `@vetta/core` for the same reason the API route\n * file stores nothing — a connected account is the **provider's** object, reconciled on read, not\n * a row of ours. `@vetta/ports` owns the TypeScript interface for the seam; this owns the parse.\n *\n * **These seven routes are live, not stubs.** ADR-0121's note that they all answer 501\n * `feature_not_configured` for want of an aggregator credential is stale: driven against staging on\n * 2026-08-23, `createAuthConfig` minted a real `ac_` config and `connect` returned a `status:\n * \"initiated\"` account with a working connect link. Where a route *does* still refuse, the caller\n * is told so in the control plane's own words rather than handed an empty list.\n */\nimport { page } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, apiErrorFrom, request, send, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\n/**\n * A connector is an **app id** out of the catalogue `apps.list` searches — `zendesk`, `linear`,\n * `intercom`. There is deliberately no enum: the catalogue is the provider's, runs to over a\n * thousand apps and changes without a release of ours, so a constant here would be a list that is\n * wrong the day it ships (ADR-0266). The five old category words still resolve as aliases.\n */\nexport type Connector = string;\n\nexport const CONNECTION_AUTHS = [\"managed_oauth\", \"oauth\", \"api_key\"] as const;\nexport type ConnectionAuth = (typeof CONNECTION_AUTHS)[number];\n\n/** One value the person authorizing must supply — an account subdomain, a region, a workspace. */\nexport const ConnectionFieldSchema = z.object({\n name: z.string(),\n label: z.string(),\n description: z.string(),\n required: z.boolean(),\n});\nexport type ConnectionField = z.infer<typeof ConnectionFieldSchema>;\n\nexport const AuthConfigSchema = z.object({\n object: z.literal(\"auth_config\"),\n id: z.string(),\n connector: z.string(),\n auth: z.enum(CONNECTION_AUTHS),\n scopes: z.array(z.string()),\n /** The operations a connection made from this config may call. Pinned at creation. */\n tools: z.array(z.string()),\n /** Supply these to `connect`, or the hosted page asks the person for them instead. */\n connect_fields: z.array(ConnectionFieldSchema),\n created_at: z.string(),\n});\nexport type AuthConfig = z.infer<typeof AuthConfigSchema>;\n\n/** The four documented states; `disconnected` means the stored credential was dropped. */\nexport const ConnectionSchema = z.object({\n object: z.literal(\"connection\"),\n id: z.string(),\n auth_config_id: z.string(),\n identity_id: z.string(),\n connector: z.string(),\n status: z.enum([\"initiated\", \"active\", \"failed\", \"disconnected\"]),\n status_reason: z.string().nullable(),\n /** The hosted authorization URL. Present only while `initiated`. */\n connect_link: z.string().nullable(),\n connect_link_expires_at: z.string().nullable(),\n last_refreshed_at: z.string().nullable(),\n created_at: z.string(),\n});\nexport type Connection = z.infer<typeof ConnectionSchema>;\nexport type ConnectionStatus = Connection[\"status\"];\n\n/** One app in the catalogue. `slug` is what `connector` takes. */\nexport const ConnectionAppSchema = z.object({\n object: z.literal(\"connection_app\"),\n slug: z.string(),\n name: z.string(),\n description: z.string(),\n categories: z.array(z.string()),\n /** Which setup paths work: `managed_oauth` is one call, `oauth` needs your own app first. */\n auth: z.array(z.enum(CONNECTION_AUTHS)),\n tool_count: z.number(),\n});\nexport type ConnectionApp = z.infer<typeof ConnectionAppSchema>;\n\nexport const ConnectionAppDetailSchema = ConnectionAppSchema.extend({\n /** The operations pinned when `tools` is not given to `createAuthConfig`. */\n default_tools: z.array(z.string()),\n connect_fields: z.array(ConnectionFieldSchema),\n});\nexport type ConnectionAppDetail = z.infer<typeof ConnectionAppDetailSchema>;\n\n/** The catalogue is cursor-paged by the provider, so `next_cursor` is opaque, not a row id. */\nexport const ConnectionAppPage = z.object({\n object: z.literal(\"list\"),\n data: z.array(ConnectionAppSchema),\n has_more: z.boolean(),\n next_cursor: z.string().nullable(),\n});\n\nexport type AuthConfigCreate = {\n connector: Connector;\n auth?: ConnectionAuth;\n scopes?: string[];\n /** Pin the callable operations. Omitted, the app's own featured set is pinned instead. */\n tools?: string[];\n client_id?: string;\n};\n\nexport const connections = (config: ClientConfig) => ({\n /**\n * Search the app catalogue — the first call in the flow, and the one that replaced the enum.\n * `search` matches an app's name, id or description; the reply's `slug` is what `connector` takes.\n */\n listApps: (query: { search?: string | undefined; limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, ConnectionAppPage, { method: \"GET\", path: \"/v1/connections/apps\", query }),\n /** One app, whole: auth methods, the operations pinned by default, what `connect` will ask for. */\n getApp: (slug: string) =>\n request(config, ConnectionAppDetailSchema, {\n method: \"GET\",\n path: `/v1/connections/apps/${encodeURIComponent(slug)}`,\n }),\n /**\n * The app's logo as an image — the one method here that answers with bytes, not JSON. The\n * catalogue publishes no logo URL (the host would name our provider), so this is how one is drawn.\n */\n appLogo: async (slug: string): Promise<Blob> => {\n const response = await send(config, { method: \"GET\", path: `/v1/connections/apps/${encodeURIComponent(slug)}/logo` }, \"image/*\");\n if (!response.ok) throw apiErrorFrom(response, await response.text());\n return response.blob();\n },\n\n /** Org-level: *how* a connector authenticates. Shared across every identity that connects it. */\n createAuthConfig: (body: AuthConfigCreate) =>\n request(config, AuthConfigSchema, {\n method: \"POST\",\n path: \"/v1/connections/auth_configs\",\n body,\n }),\n listAuthConfigs: (query: { limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, page(AuthConfigSchema), {\n method: \"GET\",\n path: \"/v1/connections/auth_configs\",\n query,\n }),\n deleteAuthConfig: (id: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/connections/auth_configs/${encodeURIComponent(id)}`,\n }),\n\n /**\n * Mints a connected account and its Connect Link; the account starts `initiated`. `billing:write`\n * on the wire, not `agents:write` — a managed account is a per-account charge at the provider.\n */\n connect: (body: { auth_config_id: string; identity: string; fields?: Record<string, string> }) =>\n request(config, ConnectionSchema, { method: \"POST\", path: \"/v1/connections\", body }),\n list: (query: ListQuery & { identity?: string | undefined } = {}) =>\n request(config, page(ConnectionSchema), { method: \"GET\", path: \"/v1/connections\", query }),\n /** Reconciles status against the provider before answering — this read *is* the refresh. */\n get: (id: string) =>\n request(config, ConnectionSchema, { method: \"GET\", path: `/v1/connections/${encodeURIComponent(id)}` }),\n /** Revoke. The provider drops the stored credential and every later call is refused. */\n disconnect: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/connections/${encodeURIComponent(id)}` }),\n});\n","/**\n * core-gaps: U8-database — the app database as its own primitive (`canonical-spec §37`,\n * `docs/api/database.mdx`). Every method takes an optional `app` (an `app_` id or a name); absent,\n * the server resolves the organization's only fullstack app (`/v1/apps/default/…`, §37.2) and\n * answers `409 ambiguous_app` naming the candidates when there are several.\n *\n * `from(table)` speaks the backend's REST filter syntax — `{ done: \"eq.false\" }` — as the service\n * role: row-level policies do not apply, so this is admin access (D8).\n */\nimport { DbMigrationSchema, DbTableSchema } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DbResultSchema } from \"./apps\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport type DbOptions = { app?: string | undefined };\n\n/**\n * A REST filter: column → operator expression (`eq.1`, `gte.2026-01-01`, `like.*milk*`,\n * `in.(a,b)`, `is.null`, `not.eq.1`). A bare number, boolean or string is shorthand for `eq.`;\n * `null` for `is.null`; an array for `in.(…)`.\n */\nexport type DbFilter = Record<string, string | number | boolean | null | readonly (string | number)[]>;\n\n/**\n * How `select` orders and pages: `order` is the REST layer's `column[.asc|.desc][.nullsfirst|.nullslast]`.\n * One read returns at most 1,000 rows whatever `limit` says; page past that with `order` plus\n * `offset` (0, 1000, 2000, …) until a page comes back shorter than 1,000.\n */\nexport type DbPage = { order?: string | undefined; limit?: number | undefined; offset?: number | undefined };\n\nconst OPERATOR =\n /^(not\\.)?(eq|neq|gt|gte|lt|lte|like|ilike|match|imatch|is|isdistinct|in|cs|cd|ov|sl|sr|nxr|nxl|adj|fts|plfts|phfts|wfts)\\./;\n\nexport function filterQuery(filter: DbFilter = {}): Record<string, string> {\n const query: Record<string, string> = {};\n for (const [column, value] of Object.entries(filter)) {\n if (value === null) query[column] = \"is.null\";\n else if (Array.isArray(value)) query[column] = `in.(${value.join(\",\")})`;\n else if (typeof value === \"string\" && OPERATOR.test(value)) query[column] = value;\n else query[column] = `eq.${String(value)}`;\n }\n return query;\n}\n\nfunction pageQuery({ order, limit, offset }: DbPage = {}): Record<string, string> {\n return {\n ...(order !== undefined && { order }),\n ...(limit !== undefined && { limit: String(limit) }),\n ...(offset !== undefined && { offset: String(offset) }),\n };\n}\n\n/** A write answered without a body (`201`/`204`, no representation) wrote nothing back: no rows. */\nconst rows = z.preprocess(\n (value) => (value !== null && typeof value === \"object\" && !Array.isArray(value) && Object.keys(value).length === 0 ? [] : value),\n z.array(z.unknown()),\n);\nconst list = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item) });\nconst app = (options: DbOptions | undefined) => options?.app ?? \"default\";\n\n/** Ask for the affected rows back on every write, so the caller sees what the database did. */\nconst REPRESENT = { prefer: \"return=representation\" };\n/** `upsert`: an insert whose duplicates update the row, on the primary key or the columns `onConflict` names. */\nconst MERGE = { prefer: \"return=representation,resolution=merge-duplicates\" };\n\nexport const database = (config: ClientConfig) => ({\n query: (sql: string, options?: DbOptions) =>\n request(config, DbResultSchema, { method: \"POST\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/query`, body: { query: sql } }),\n tables: async (options?: DbOptions) =>\n (await request(config, list(DbTableSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/tables` })).data,\n migrate: (name: string, sql: string, options?: DbOptions) =>\n request(config, DbMigrationSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(app(options))}/db/migrations`,\n body: { name, sql },\n }),\n migrations: async (options?: DbOptions) =>\n (await request(config, list(DbMigrationSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/migrations` }))\n .data,\n\n /** One table of the REST layer; the verbs below ride the routes under `/db/rest/*`. */\n from: (table: string, options?: DbOptions) => ({\n select: (columns = \"*\", filter?: DbFilter, page?: DbPage) =>\n request(config, rows, {\n method: \"GET\",\n path: `/v1/apps/${encodeURIComponent(app(options))}/db/rest/${encodeURIComponent(table)}`,\n query: { select: columns, ...filterQuery(filter), ...pageQuery(page) },\n }),\n insert: (records: readonly Record<string, unknown>[]) =>\n request(config, rows, {\n method: \"POST\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/rest/${encodeURIComponent(table)}`,\n body: records,\n headers: REPRESENT,\n }),\n upsert: (records: readonly Record<string, unknown>[], conflict?: { onConflict?: string | undefined }) =>\n request(config, rows, {\n method: \"POST\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/rest/${encodeURIComponent(table)}`,\n query: { on_conflict: conflict?.onConflict },\n body: records,\n headers: MERGE,\n }),\n update: (patch: Record<string, unknown>, filter: DbFilter) =>\n request(config, rows, {\n method: \"PATCH\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/rest/${encodeURIComponent(table)}`,\n query: filterQuery(filter),\n body: patch,\n headers: REPRESENT,\n }),\n delete: (filter: DbFilter) =>\n request(config, rows, {\n method: \"DELETE\", path: `/v1/apps/${encodeURIComponent(app(options))}/db/rest/${encodeURIComponent(table)}`,\n query: filterQuery(filter),\n headers: REPRESENT,\n }),\n }),\n});\n","/**\n * The company's sessions and agents in one read (`canonical-spec §20.10`): what the Studio rail\n * draws. Each list is cut at a cap; past it, page `sessions.list` or `agents.list`.\n */\nimport { DigestSchema } from \"@vetta/core\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport const digest = (config: ClientConfig) => ({\n get: () => request(config, DigestSchema, { method: \"GET\", path: \"/v1/digest\" }),\n});\n","/**\n * Agents, sessions and events — the control-plane surface `apps/api` serves today\n * (`workstreams/02-control-plane-api.md`). One method per route; the route table *is* the client.\n *\n * Request bodies are derived from the `core` object types rather than re-declared: a create body is\n * the object minus its server-assigned fields (`code-standards §2`).\n */\nimport {\n OperatorPreviewSchema,\n AgentSchema,\n AgentVersionSchema,\n ComputerSchema,\n EventSchema,\n HandoffBatchSchema,\n MEDIA_MODEL_KINDS,\n MediaJobSchema,\n ModelSelectionSchema,\n OutcomeEvaluationSchema,\n PlanSchema,\n SendAcceptedSchema,\n SessionSchema,\n StockPhotoSchema,\n SpeechGenerationSchema,\n WindowSchema,\n page,\n type Agent,\n type ModelSelectionRequest,\n type PlanWrite,\n type Session,\n type SessionHandoffRequest,\n type SessionMode,\n type StopReason,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\n// core-gaps: U6-audio\nimport type { SpeechCreate, SpeechToSpeechCreate, TranscriptionCreate } from \"./audio\";\nimport { DeletedSchema, request, tolerantPage, type ClientConfig } from \"./http\";\n// core-gaps: U5-clips-api\nimport { media as mediaClips } from \"./clips\";\nimport { media as mediaSkills } from \"./media-skills\";\n\n/**\n * Two wire objects `canonical-spec.md` does not carry a schema for, declared here rather than added\n * to `core`: a spend report is an aggregation, not a stored object, and a catalogue entry is a\n * constant of the deploy. `by_component` is absent unless `?by=component` was asked for.\n */\nexport const AgentSpendSchema = z.object({\n agent_id: z.string(),\n period: z.enum([\"day\", \"week\", \"month\"]),\n period_start: z.string(),\n spent_micro_usd: z.number().int(),\n by_component: z.record(z.string(), z.number().int()).optional(),\n});\n\nexport const ModelSchema = z.object({\n object: z.literal(\"model\"),\n id: z.string(),\n context_window: z.number().int(),\n /** What the pre-flight quote bounds, per model: the provider's ceiling, clamped to ours. */\n max_output_tokens: z.number().int(),\n supported_windows: z.array(WindowSchema),\n efforts: z.array(z.enum([\"low\", \"medium\", \"high\"])),\n});\n\n/** A deleted agent leaves every roster that named it; `removed_from` is each lead, at the version that dropped it (ADR-1870). */\nconst AgentDeletedSchema = DeletedSchema.extend({\n removed_from: z.array(z.object({ id: z.string(), name: z.string(), version: z.number().int() })).default([]),\n});\n\ntype AgentConfig = Omit<Agent, \"id\" | \"object\" | \"harness\" | \"current_version\" | \"created_at\">;\n/**\n * `harness` is the agent loop (§19). `pi` is the default; `harnesses.list()` is the live set.\n * `budget` is required, as the route requires it (ADR-1864).\n */\nexport type AgentCreate = Pick<AgentConfig, \"name\" | \"model\" | \"budget\"> &\n Partial<AgentConfig> &\n Partial<Pick<Agent, \"harness\">>;\n/** `harness` may be resent by `apply` and is ignored; it is not a change. */\nexport type AgentPatch = Partial<AgentConfig> &\n Partial<Pick<Agent, \"harness\">> & { expected_version?: number };\n\nexport type SessionCreate = { agent_id: string; message: string } & Partial<\n Pick<\n Session,\n \"agent_version\" | \"window\" | \"budget_micro_usd\" | \"deployment_id\" | \"output_schema\" | \"metadata\" | \"mode\"\n >\n> & {\n /**\n * The persona this task acts as — an `idn_` id or the persona's name (`canonical-spec §22`).\n * Spelled `identity` on the way in and answered as `identity_id` on the session, which is why it\n * is not a `Pick` of `Session`.\n */\n identity?: string | undefined;\n /**\n * Refuse a would-be clean ending that produced no document matching `output_schema` (§16). Not a\n * `Pick` of `Session`: the flag is carried on the agent version, not echoed on the session row.\n */\n structured_output_required?: boolean | undefined;\n /** An `ocm_` outcome to grade the session against from its first turn (§58.2). */\n outcome?: string | undefined;\n};\n\n/** Cursor pagination (§9). `| undefined` is explicit so a caller can forward an unset CLI flag. */\nexport type ListQuery = { limit?: number | undefined; after?: string | undefined };\n\nexport const agents = (config: ClientConfig) => ({\n create: (body: AgentCreate) =>\n request(config, AgentSchema, { method: \"POST\", path: \"/v1/agents\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(AgentSchema), { method: \"GET\", path: \"/v1/agents\", query }),\n get: (id: string) => request(config, AgentSchema, { method: \"GET\", path: `/v1/agents/${encodeURIComponent(id)}` }),\n update: (id: string, body: AgentPatch) =>\n request(config, AgentSchema, { method: \"PATCH\", path: `/v1/agents/${encodeURIComponent(id)}`, body }),\n listVersions: (id: string) =>\n request(config, page(AgentVersionSchema), {\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(id)}/versions`,\n }),\n getVersion: (id: string, version: number) =>\n request(config, AgentVersionSchema, {\n method: \"GET\",\n path: `/v1/agents/${encodeURIComponent(id)}/versions/${encodeURIComponent(version)}`,\n }),\n /** Mints a **new** version cloning `to_version`; history is never rewritten (§12). */\n rollback: (id: string, body: { to_version: number; expected_version?: number }) =>\n request(config, AgentSchema, { method: \"POST\", path: `/v1/agents/${encodeURIComponent(id)}/rollback`, body }),\n /** Metered spend for the agent's current budget period; `by: \"component\"` adds the breakdown. */\n spend: (id: string, query: { by?: \"component\" | undefined } = {}) =>\n request(config, AgentSpendSchema, { method: \"GET\", path: `/v1/agents/${encodeURIComponent(id)}/spend`, query }),\n /** The agent's one computer (§41.8), or `null` before any session has needed one. */\n computer: (id: string) =>\n request(config, ComputerSchema.nullable(), { method: \"GET\", path: `/v1/agents/${encodeURIComponent(id)}/computer` }),\n delete: (id: string) =>\n request(config, AgentDeletedSchema, { method: \"DELETE\", path: `/v1/agents/${encodeURIComponent(id)}` }),\n});\n\n/**\n * The catalogue a caller picks `--model` from — a **live read** of the network's own list rather\n * than a constant of the deploy, so it pages and searches (`canonical-spec.md §4.1`). The `window`\n * filter answers \"what could I run in this window?\" and is the derivation the router refuses on, so\n * a model listed for a window is never rejected for it.\n */\nexport const models = (config: ClientConfig) => ({\n list: (query: { window?: string | undefined; search?: string | undefined } & ListQuery = {}) =>\n request(config, page(ModelSchema), { method: \"GET\", path: \"/v1/models\", query }),\n /** One model by id. An id carries a `/`, so it is encoded here and decoded by the route. */\n retrieve: (id: string) =>\n request(config, ModelSchema, { method: \"GET\", path: `/v1/models/${encodeURIComponent(id)}` }),\n /**\n * Name one of the caller's own catalogue ids for its next call (`canonical-spec §46`). An opt-in\n * and nothing more: `pick.model` goes into `proxy.messages` or an agent's `model` as any id would.\n */\n autoSelect: (body: ModelSelectionRequest) =>\n request(config, ModelSelectionSchema, { method: \"POST\", path: \"/v1/models/auto_select\", body }),\n});\nexport type { ModelSelection, ModelSelectionRequest } from \"@vetta/core\";\n\n/**\n * One entry of the harness catalogue (`canonical-spec.md §19`). `base` is the value that goes in an\n * agent's `harness` field.\n *\n * `capabilities` is the part worth reading before you create an agent: a loop that declares\n * `approvals: false` cannot serve a toolset whose permission is `ask`, and a start that asks for\n * one it does not declare is refused up front rather than quietly downgraded.\n */\nexport const HarnessSchema = z.object({\n base: z.string(),\n label: z.string(),\n location: z.enum([\"hosted\", \"local\"]),\n billing: z.enum([\"usage\", \"account\"]),\n status: z.enum([\"ga\", \"preview\"]),\n /** Where the loop runs, and therefore what an idle session holds. */\n execution: z.enum([\"isolate\", \"sandbox\", \"local\"]),\n /** Whether a session on it runs today — separate from how settled its contract is. */\n runnable: z.boolean(),\n capabilities: z.object({\n approvals: z.boolean(),\n structured_output: z.boolean(),\n streaming_deltas: z.boolean(),\n /**\n * Whether the platform's tools REACH this loop's model — team tools, `mcp_servers`,\n * connections, social, apps — all still governed by the agent's `tools` policy. It does not\n * say how they get there: a loop we host is handed them in the turn, an agent that is a CLI\n * process in a machine of its own dials a session-scoped tool endpoint instead.\n *\n * Two limits it does not cover, on a harness of the second kind: `wait_for_agents` does not\n * pause the turn in flight (a coordinator still parks once it goes idle and still opens its\n * threads — it costs a few extra model calls, it does not break), and a tool whose permission\n * is `ask` is left out rather than gated, because such a harness also declares\n * `approvals: false` and a start that asks for one is refused up front.\n */\n injected_tools: z.boolean(),\n }),\n});\n\n/**\n * The catalogue a caller picks `harness` from. Unlike `models`, this is a constant of the deploy —\n * a harness needs an adapter compiled in, so the list cannot change without a release. It still\n * pages like everything else (§9) so that a caller writes one loop for both catalogues.\n */\nexport const harnesses = (config: ClientConfig) => ({\n list: (query: ListQuery = {}) =>\n request(config, page(HarnessSchema), { method: \"GET\", path: \"/v1/harnesses\", query }),\n /** One harness by base. A base with no adapter behind it is a 404, not an empty row. */\n retrieve: (base: string) =>\n request(config, HarnessSchema, { method: \"GET\", path: `/v1/harnesses/${encodeURIComponent(base)}` }),\n});\n\n/**\n * One model `generate_image` / `generate_video` will accept, out of the provider's **live**\n * catalogue (ADR-0286). There is no enum. Image and video rows carry no price: what those jobs\n * cost is only knowable once they finish. A mesh row lists `prices`, one customer µUSD figure per\n * texture and rig combination (§59).\n */\nexport const MediaModelSchema = z.object({\n object: z.literal(\"media_model\"),\n id: z.string(),\n name: z.string(),\n kind: z.enum(MEDIA_MODEL_KINDS),\n description: z.string(),\n prices: z\n .array(z.object({ texture: z.boolean(), rig: z.boolean(), micro_usd: z.number().int() }))\n .optional(),\n});\nexport type MediaModel = z.infer<typeof MediaModelSchema>;\n\n/** Cursor-paged over the provider's own list, so `next_cursor` is opaque rather than a row id. */\nexport const MediaModelPage = z.object({\n object: z.literal(\"list\"),\n data: z.array(MediaModelSchema),\n has_more: z.boolean(),\n next_cursor: z.string().nullable(),\n});\n\n// core-gaps: U10-stock-photos\n/**\n * Not a cursor page: the library pages by number, and `count` is the whole page (§39). `id` is the\n * library's own and carries no prefix; to hold the bytes as a `fil_`, import `url` through\n * `files.imports`.\n */\nexport const StockPhotoList = z.object({ data: z.array(StockPhotoSchema) });\nexport type { StockPhoto } from \"@vetta/core\";\n\nexport type StockPhotoQuery = {\n query: string;\n count?: number | undefined;\n orientation?: \"landscape\" | \"portrait\" | \"square\" | undefined;\n color?: string | undefined;\n size?: \"small\" | \"medium\" | \"large\" | undefined;\n};\n\n/** The generation catalogue. `kind` is required: image and video are two capabilities, two lists. */\nexport const media = (config: ClientConfig) => ({\n // core-gaps: U6-audio — speech to text, text to speech and speech to speech (`§35`; bodies in `audio.ts`).\n audio: {\n transcribe: (body: TranscriptionCreate) =>\n request(config, MediaJobSchema, { method: \"POST\", path: \"/v1/media/audio/transcriptions\", body }),\n get: (id: string) =>\n request(config, MediaJobSchema, { method: \"GET\", path: `/v1/media/audio/transcriptions/${encodeURIComponent(id)}` }),\n speak: (body: SpeechCreate) =>\n request(config, SpeechGenerationSchema, { method: \"POST\", path: \"/v1/media/audio/speech\", body }),\n // core-gaps: A0-audio-router\n converse: (body: SpeechToSpeechCreate) =>\n request(config, SpeechGenerationSchema, { method: \"POST\", path: \"/v1/media/audio/conversations\", body }),\n },\n listModels: (query: {\n kind: MediaModel[\"kind\"];\n search?: string | undefined;\n limit?: number | undefined;\n after?: string | undefined;\n }) => request(config, MediaModelPage, { method: \"GET\", path: \"/v1/media/models\", query }),\n // core-gaps: U10-stock-photos\n stock: {\n search: (query: StockPhotoQuery) =>\n request(config, StockPhotoList, { method: \"GET\", path: \"/v1/media/stock\", query }),\n },\n // core-gaps: U5-clips-api\n ...mediaClips(config),\n ...mediaSkills(config),\n});\n\nexport type SessionFilter = {\n agent_id?: string | undefined;\n status?: string | undefined;\n /**\n * Why a session yielded, which is the only way to ask for the ones a person has to answer:\n * `awaiting_approval` is the review queue, `budget_paused` the out-of-money queue. Neither is a\n * `status` — both are `idle` — so a caller filtering on `status` alone cannot tell them apart\n * from a session that simply finished its turn.\n */\n stop_reason?: StopReason | undefined;\n deployment_id?: string | undefined;\n /** A coordinator's id lists its delegated threads; omitted, only top-level sessions (§28). */\n parent_session_id?: string | undefined;\n /** The sessions a root fanned out through the human door (§28.16): `metadata.handoff.from_session`. */\n handoff_from?: string | undefined;\n /** Top-level sessions handed off under this exact key; `room:<root>` is a room's seated members (§28.16). */\n handoff_key?: string | undefined;\n /** A channel's own sessions: the coordinator's top-level rows marked `metadata.room` = its id (§28.16). */\n room?: string | undefined;\n};\n\n/** A caller-chosen `Idempotency-Key`, or nothing (the client mints one per call). */\nexport const keyed = (opts: { idempotencyKey?: string }): Record<string, string> =>\n opts.idempotencyKey === undefined ? {} : { \"idempotency-key\": opts.idempotencyKey };\n\nexport const sessions = (config: ClientConfig) => ({\n /** Creates **and** starts, with the initial message, in one call (§7). */\n /** `idempotencyKey` is also the first message's `client_message_id` on the log (§7). */\n create: (body: SessionCreate, opts: { idempotencyKey?: string } = {}) =>\n request(config, SessionSchema, { method: \"POST\", path: \"/v1/sessions\", body, headers: keyed(opts) }),\n list: (query: ListQuery & SessionFilter = {}) =>\n request(config, page(SessionSchema), { method: \"GET\", path: \"/v1/sessions\", query }),\n get: (id: string) => request(config, SessionSchema, { method: \"GET\", path: `/v1/sessions/${encodeURIComponent(id)}` }),\n /** The operator card's words for one parked `operator.request`, read from the store (§7.7). */\n operatorPreview: (id: string, toolCallId: string) =>\n request(config, OperatorPreviewSchema, { method: \"GET\", path: `/v1/sessions/${encodeURIComponent(id)}/operator_preview`, query: { tool_call_id: toolCallId } }),\n /**\n * `interrupt:true` steers a running session; `queue:true` holds the message for the turn after\n * this one; neither, a running session is `session_running` (§7). `model` runs the session on that\n * catalogue id from this message's turn on. `mode: \"plan\"` runs it read-only until the person\n * approves the plan; `\"build\"` leaves plan mode (§7.5).\n */\n send: (\n id: string,\n body: { message: string; interrupt?: boolean; queue?: boolean; model?: string; mode?: SessionMode },\n /** The key is the message's `client_message_id` on the log (§7): pass the id the caller drew it under. */\n opts: { idempotencyKey?: string } = {},\n ) =>\n request(config, SendAcceptedSchema, {\n method: \"POST\",\n path: `/v1/sessions/${encodeURIComponent(id)}/messages`,\n body,\n headers: keyed(opts),\n }),\n /**\n * The human door (§28.16): this session hands `message` to one to six agents, by id or name, under\n * the same policy as the model's `send_to_agent`. Refused seats come back inline, not as an error.\n */\n /** `idempotencyKey` is also the `client_message_id` of the `handoff.sent` row the door records (§8). */\n handoffs: (id: string, body: SessionHandoffRequest, opts: { idempotencyKey?: string } = {}) =>\n request(config, HandoffBatchSchema, { method: \"POST\", path: `/v1/sessions/${encodeURIComponent(id)}/handoffs`, body, headers: keyed(opts) }),\n interrupt: (id: string, body: { message?: string | null } = {}) =>\n request(config, SessionSchema, { method: \"POST\", path: `/v1/sessions/${encodeURIComponent(id)}/interrupt`, body }),\n /**\n * `scope: \"session\"` turns an `allow` into a grant: that TOOL NAME runs without a card for the\n * rest of this session, and nothing else does. Omitted — the default — is one call, one decision.\n * `answers` on an allow of a template install runs it with the person's own answers (ADR-1030);\n * `model` on an allow of `generate_video` runs it on the model they picked (ADR-1472).\n */\n confirmTool: (\n id: string,\n body: {\n tool_call_id: string;\n decision: \"allow\" | \"deny\";\n reason?: string;\n scope?: \"call\" | \"session\";\n answers?: Record<string, string | string[]>;\n model?: string;\n shown?: string;\n /** A `vault.request_secret`'s sealed credential, on its allow (§7.6). Never a value. */\n credential?: string;\n },\n ) =>\n request(config, SessionSchema, {\n method: \"POST\",\n path: `/v1/sessions/${encodeURIComponent(id)}/tool_confirmations`,\n body,\n }),\n /**\n * Answers a session parked on a question (`stop_reason: \"awaiting_answer\"`, §7.2). A sibling of\n * `confirmTool`, not a variant of it: a held tool call takes a verb and no payload, a question\n * takes a payload and no verb, and one method carrying both would make each half optional.\n */\n answer: (id: string, body: { tool_call_id: string; answers: Record<string, string | string[]> }) =>\n request(config, SessionSchema, { method: \"POST\", path: `/v1/sessions/${encodeURIComponent(id)}/answers`, body }),\n /**\n * Holds the session to an outcome (§58.2): only while `idle`, and it replaces the active one, whose\n * unfinished evaluation ends `interrupted`. Answers the new evaluation at `result: \"pending\"`.\n */\n setOutcome: (id: string, body: { outcome: string }) =>\n request(config, OutcomeEvaluationSchema, { method: \"POST\", path: `/v1/sessions/${encodeURIComponent(id)}/outcome`, body }),\n cancel: (id: string) =>\n request(config, SessionSchema, { method: \"POST\", path: `/v1/sessions/${encodeURIComponent(id)}/cancel`, body: {} }),\n /** Raise only — a cap at or below what is consumed would be retroactive. */\n setBudget: (id: string, capMicroUsd: number) =>\n request(config, SessionSchema, {\n method: \"PATCH\",\n path: `/v1/sessions/${encodeURIComponent(id)}/budget`,\n body: { cap_micro_usd: capMicroUsd },\n }),\n /** The session's living plan (§7.5): version 0 and empty until one is written. */\n plan: (id: string) => request(config, PlanSchema, { method: \"GET\", path: `/v1/sessions/${encodeURIComponent(id)}/plan` }),\n /** The owner's edit, a compare-and-set: a stale `base_version` is `version_conflict` (409). */\n writePlan: (id: string, body: PlanWrite) =>\n request(config, PlanSchema, { method: \"PUT\", path: `/v1/sessions/${encodeURIComponent(id)}/plan`, body }),\n /**\n * The sessions this one delegated to (`canonical-spec §28.5`). A thread is a session, so every\n * method above works on one by its own id; delegated children are kept out of `list`, which is\n * why they are found here.\n */\n threads: (id: string, query: ListQuery = {}) =>\n request(config, page(SessionSchema), { method: \"GET\", path: `/v1/sessions/${encodeURIComponent(id)}/threads`, query }),\n /**\n * `after_seq` is exclusive (§8). `includeAccepted` asks for the `message.accepted` rows the list\n * leaves out by default — the browser's pending bubbles, not the agent's work.\n *\n * The page is parsed leniently (`tolerantPage`): a row of a type this build has no schema for is\n * skipped rather than thrown, so one added event type cannot take a whole transcript with it.\n */\n events: (\n id: string,\n query: { after_seq?: number | undefined; limit?: number | undefined; includeAccepted?: boolean } = {},\n ) =>\n request(config, tolerantPage(EventSchema), {\n method: \"GET\",\n path: `/v1/sessions/${encodeURIComponent(id)}/events`,\n query: {\n after_seq: query.after_seq,\n limit: query.limit,\n ...(query.includeAccepted === true ? { include_accepted: \"true\" } : {}),\n },\n }),\n});\n","/**\n * Video clipping as a customer resource (`canonical-spec.md §34`, core-gaps U5-clips-api). One\n * method per route: submit a public video URL, poll the `med_` job, list the org's jobs. The job\n * shape is the shared `media_job` (§33.1) with `kind: \"clip\"`. Declared as a `media` fragment and\n * spread into the `media` namespace in `control-plane.ts`, so callers write `vetta.media.clips.*`.\n */\nimport { MediaJobSchema, page } from \"@vetta/core\";\nimport type { ClipRequestSchema, MediaJobStatusSchema } from \"@vetta/core\";\nimport type { z } from \"zod\";\nimport { request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\nexport type ClipCreate = z.input<typeof ClipRequestSchema>;\nexport type ClipFilter = { status?: z.infer<typeof MediaJobStatusSchema> | undefined } & ListQuery;\n\nexport const media = (config: ClientConfig) => ({\n clips: {\n /** `202` with the queued job; the call carries an `Idempotency-Key` like every create. */\n create: (body: ClipCreate) =>\n request(config, MediaJobSchema, { method: \"POST\", path: \"/v1/media/clips\", body }),\n get: (id: string) =>\n request(config, MediaJobSchema, { method: \"GET\", path: `/v1/media/clips/${encodeURIComponent(id)}` }),\n list: (query: ClipFilter = {}) =>\n request(config, page(MediaJobSchema), { method: \"GET\", path: \"/v1/media/clips\", query }),\n },\n});\n","/**\n * Media skill builds (`canonical-spec.md §57`): an org skill built from 1–3 public reel links. A\n * build and a revision are the same `POST /v1/media/skills` (the body's shape tells them apart), so\n * both carry the automatic `Idempotency-Key`. Spread into `media` in `control-plane.ts`, so callers\n * write `vetta.media.skills.*`.\n */\nimport { MediaSkillBuildSchema, page } from \"@vetta/core\";\nimport type { MediaSkillBuild, MediaSkillBuildStateSchema } from \"@vetta/core\";\nimport type { z } from \"zod\";\nimport { request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\nexport type MediaSkillCreate = { urls: string[]; name?: string | undefined; description?: string | undefined };\nexport type MediaSkillFilter = { state?: z.infer<typeof MediaSkillBuildStateSchema> | undefined } & ListQuery;\nexport type { MediaSkillBuild };\n\nexport const media = (config: ClientConfig) => ({\n skills: {\n /** `202` with the build; poll `get` until `state` is `ready`. */\n create: (body: MediaSkillCreate) =>\n request(config, MediaSkillBuildSchema, { method: \"POST\", path: \"/v1/media/skills\", body }),\n /** Runs the next round of a build you own; `409 version_conflict` while a round is running. */\n revise: (id: string, body: { feedback: string }) =>\n request(config, MediaSkillBuildSchema, {\n method: \"POST\",\n path: \"/v1/media/skills\",\n body: { build_id: id, feedback: body.feedback },\n }),\n get: (id: string) =>\n request(config, MediaSkillBuildSchema, { method: \"GET\", path: `/v1/media/skills/${encodeURIComponent(id)}` }),\n list: (query: MediaSkillFilter = {}) =>\n request(config, page(MediaSkillBuildSchema), { method: \"GET\", path: \"/v1/media/skills\", query }),\n },\n});\n","/**\n * core-gaps: U4-media-api — generation as REST (`canonical-spec §33`). `images.generate` is\n * synchronous and answers the files; `videos.generate` answers a `queued` `media_job` that `get`\n * follows to `completed`. The catalogue (`listModels`) stays where it was, spread in below.\n */\nimport {\n EditJobSchema,\n ImageGenerationSchema,\n MediaJobSchema,\n MusicGenerationSchema,\n SoundGenerationSchema,\n page,\n type EditRequestSchema,\n type ImageRequestSchema,\n type MeshRequestSchema,\n type MusicRequestSchema,\n type SoundEffectRequestSchema,\n type VideoRequestSchema,\n} from \"@vetta/core\";\nimport type { z } from \"zod\";\nimport { media as catalogue, type ListQuery } from \"./control-plane\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport type EditRequest = z.input<typeof EditRequestSchema>;\nexport type EditJob = z.infer<typeof EditJobSchema>;\nexport type ImageRequest = z.input<typeof ImageRequestSchema>;\nexport type MeshRequest = z.input<typeof MeshRequestSchema>;\nexport type VideoRequest = z.input<typeof VideoRequestSchema>;\nexport type SoundEffectRequest = z.input<typeof SoundEffectRequestSchema>;\nexport type MusicRequest = z.input<typeof MusicRequestSchema>;\nexport type ImageGeneration = z.infer<typeof ImageGenerationSchema>;\nexport type SoundGeneration = z.infer<typeof SoundGenerationSchema>;\nexport type MusicGeneration = z.infer<typeof MusicGenerationSchema>;\nexport type MediaJob = z.infer<typeof MediaJobSchema>;\n\nexport type MediaFilter = {\n kind?: MediaJob[\"kind\"] | undefined;\n status?: MediaJob[\"status\"] | undefined;\n /** A session's jobs; REST-submitted jobs carry no session and are listed without this. */\n session_id?: string | undefined;\n};\n\nconst generation = (config: ClientConfig) => ({\n images: {\n generate: (body: ImageRequest) =>\n request(config, ImageGenerationSchema, {\n method: \"POST\",\n path: \"/v1/media/images\",\n body,\n }),\n },\n videos: {\n generate: (body: VideoRequest) =>\n request(config, MediaJobSchema, {\n method: \"POST\",\n path: \"/v1/media/videos\",\n body,\n }),\n },\n /** A 3D model (GLB) from a prompt or 1–4 photos (§59): a `queued` `media_job` of `kind: \"mesh\"`. */\n meshes: {\n create: (body: MeshRequest) =>\n request(config, MediaJobSchema, {\n method: \"POST\",\n path: \"/v1/media/meshes\",\n body,\n }),\n },\n // core-gaps: U11-sound-effects — synchronous like an image: the clip comes straight back as a file.\n soundEffects: {\n generate: (body: SoundEffectRequest) =>\n request(config, SoundGenerationSchema, {\n method: \"POST\",\n path: \"/v1/media/sound-effects\",\n body,\n }),\n },\n // core-gaps: U12-music — synchronous like a sound effect: the song comes straight back as a file.\n music: {\n generate: (body: MusicRequest) =>\n request(config, MusicGenerationSchema, {\n method: \"POST\",\n path: \"/v1/media/music\",\n body,\n }),\n },\n edits: {\n create: (body: EditRequest) =>\n request(config, EditJobSchema, {\n method: \"POST\",\n path: \"/v1/media/edits\",\n body,\n }),\n get: (id: string) =>\n request(config, EditJobSchema, { method: \"GET\", path: `/v1/media/edits/${encodeURIComponent(id)}` }),\n },\n get: (id: string) =>\n request(config, MediaJobSchema, { method: \"GET\", path: `/v1/media/${encodeURIComponent(id)}` }),\n list: (query: ListQuery & MediaFilter = {}) =>\n request(config, page(MediaJobSchema), {\n method: \"GET\",\n path: \"/v1/media\",\n query,\n }),\n});\n\nexport const media = (config: ClientConfig) => ({\n ...catalogue(config),\n ...generation(config),\n});\n","/**\n * Identities — the personas an agent acts as (`canonical-spec §22`). One method per route, the\n * same rule as every other group here: nothing in this file names a route `apps/api` does not\n * serve, and every response is parsed with the `@vetta/core` schema rather than a local shape.\n *\n * `attach`/`detach` hang off the agent, because the grant is about which personas *that agent* may\n * be. They are the write surface for the relationship; `PATCH /v1/agents {identity: [...]}` is the\n * spelling `docs/api/identities.mdx` shows and it is an owed doc-fix, not a second route (ADR-0116).\n */\nimport { EmailInboxSchema, IdentitySchema, InboundMessageSchema, PhoneNumberSchema, page } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { cards } from \"./cards\";\nimport type { ListQuery } from \"./control-plane\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\nimport { legal } from \"./legal\";\nimport { wallet } from \"./wallet\";\n\n/** The grant, echoed back. `created` is false when the persona was already attached. */\nconst GrantSchema = z.object({\n object: z.literal(\"agent_identity\"),\n agent_id: z.string(),\n identity_id: z.string(),\n attached: z.boolean(),\n created: z.boolean().optional(),\n});\n\nconst AgentRefSchema = z.object({ id: z.string(), name: z.string() });\n\nexport type IdentityCreate = { name: string; description?: string | null; metadata?: Record<string, unknown> };\nexport type IdentityPatch = Partial<IdentityCreate>;\n\n/**\n * THE ENDPOINTS A PERSONA OWNS. `IdentitySchema` carries `emails`/`phones`/`connections` as\n * denormalised string arrays; these are the addressable objects behind them, and they are what a\n * screen needs to show status or delete a row. Each is a separate route because each can be\n * served, empty, or refused independently — `connections` answers 501 wherever no connections\n * credential is bound, and a caller must be able to tell that apart from \"none\".\n *\n * Spread into `identities` rather than nested: `client.identities.inboxes(id)` is the call a\n * reader expects, and keeping the factory separate keeps either function inside the size budget.\n */\nconst endpoints = (config: ClientConfig) => ({\n inboxes: (ref: string, query: ListQuery = {}) =>\n request(config, page(EmailInboxSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(ref)}/emails`, query }),\n deleteInbox: (ref: string, inboxId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/identities/${encodeURIComponent(ref)}/emails/${encodeURIComponent(inboxId)}`,\n }),\n phones: (ref: string, query: ListQuery = {}) =>\n request(config, page(PhoneNumberSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(ref)}/phones`, query }),\n /** Irreversible at the carrier: the number goes back to the pool and cannot be reclaimed. */\n releasePhone: (ref: string, phoneId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/identities/${encodeURIComponent(ref)}/phones/${encodeURIComponent(phoneId)}`,\n }),\n messages: (ref: string, query: { channel?: \"email\" | \"sms\" | undefined } = {}) =>\n request(config, page(InboundMessageSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(ref)}/messages`,\n query,\n }),\n});\n\nexport const identities = (config: ClientConfig) => ({\n create: (body: IdentityCreate) =>\n request(config, IdentitySchema, { method: \"POST\", path: \"/v1/identities\", body }),\n list: (query: { limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, page(IdentitySchema), { method: \"GET\", path: \"/v1/identities\", query }),\n /** `ref` is an `idn_` id **or** the persona's name — the API resolves both. */\n get: (ref: string) =>\n request(config, IdentitySchema, { method: \"GET\", path: `/v1/identities/${encodeURIComponent(ref)}` }),\n update: (ref: string, body: IdentityPatch) =>\n request(config, IdentitySchema, { method: \"PATCH\", path: `/v1/identities/${encodeURIComponent(ref)}`, body }),\n delete: (ref: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/identities/${encodeURIComponent(ref)}` }),\n /** The live agents holding this persona — run this before revoking it. */\n agents: (ref: string) =>\n request(config, page(AgentRefSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(ref)}/agents` }),\n\n held: (agentId: string) =>\n request(config, page(IdentitySchema), { method: \"GET\", path: `/v1/agents/${encodeURIComponent(agentId)}/identities` }),\n attach: (agentId: string, identity: string) =>\n request(config, GrantSchema, {\n method: \"POST\",\n path: `/v1/agents/${encodeURIComponent(agentId)}/identities`,\n body: { identity },\n }),\n detach: (agentId: string, identityId: string) =>\n request(config, GrantSchema, {\n method: \"DELETE\",\n path: `/v1/agents/${encodeURIComponent(agentId)}/identities/${encodeURIComponent(identityId)}`,\n }),\n\n ...endpoints(config),\n // Identity-owned primitives (`canonical-spec §43–§45`); each takes the identity as its first argument.\n legal: legal(config),\n wallet: wallet(config),\n cards: cards(config),\n});\n","/**\n * Prepaid virtual cards owned by an identity (`canonical-spec.md §45`), reached as\n * `client.identities.cards.*`. `revealCredentials` is the one call that returns a card number: it\n * is audited server-side, answers `not_found` unless the card is `active`, and keeps its own name\n * so a grep of a codebase finds every reveal. Everything else returns the safe `card` projection.\n */\n\nimport {\n CardCredentialsSchema,\n CardQuoteSchema,\n CardSchema,\n CardTransactionSchema,\n page,\n type CardStatus,\n type IssueCard,\n type LogCardTransaction,\n} from \"@vetta/core\";\nimport { request, type ClientConfig } from \"./http\";\nimport { keyed, type ListQuery } from \"./control-plane\";\n\nexport const cards = (config: ClientConfig) => ({\n list: (identity: string, query: ListQuery & { status?: CardStatus | undefined } = {}) =>\n request(config, page(CardSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/cards`, query }),\n /** Buys a card. A retry passes the first call's `idempotencyKey`, so it gets that card instead of buying a second. */\n issue: (identity: string, body: IssueCard, opts: { idempotencyKey?: string } = {}) =>\n request(config, CardSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/cards`, body, headers: keyed(opts) }),\n quote: (identity: string, body: { load_micro_usd: number }) =>\n request(config, CardQuoteSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/quote`,\n body,\n }),\n get: (identity: string, cardId: string) =>\n request(config, CardSchema, { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}` }),\n revealCredentials: (identity: string, cardId: string) =>\n request(config, CardCredentialsSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/credentials`,\n }),\n retry: (identity: string, cardId: string) =>\n request(config, CardSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/retry`,\n }),\n cancel: (identity: string, cardId: string) =>\n request(config, CardSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/cancel`,\n }),\n refund: (identity: string, cardId: string) =>\n request(config, CardSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/refund`,\n }),\n transactions: (identity: string, cardId: string, query: ListQuery = {}) =>\n request(config, page(CardTransactionSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/transactions`,\n query,\n }),\n logTransaction: (identity: string, cardId: string, body: LogCardTransaction) =>\n request(config, CardTransactionSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/cards/${encodeURIComponent(cardId)}/transactions`,\n body,\n }),\n});\n","/**\n * Identity-owned legal verification and formation (`canonical-spec.md §43`), reached as\n * `client.identities.legal.*`. Every method is a thin typed call; a deployment without a legal\n * provider bound answers `feature_not_configured`.\n */\n\nimport {\n LegalCompanySchema,\n LegalDocumentLinkSchema,\n LegalDocumentSchema,\n LegalMemberSchema,\n LegalStateSchema,\n LegalVerificationSchema,\n NaicsCodeSchema,\n page,\n type CreateLegalCompany,\n type StartLegalVerification,\n} from \"@vetta/core\";\nimport { request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\nconst verifications = (config: ClientConfig) => ({\n verifications: (identity: string, query: ListQuery = {}) =>\n request(config, page(LegalVerificationSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/verifications`,\n query,\n }),\n startVerification: (identity: string, body: StartLegalVerification) =>\n request(config, LegalVerificationSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/verifications`,\n body,\n }),\n verification: (identity: string, verificationId: string) =>\n request(config, LegalVerificationSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/verifications/${encodeURIComponent(verificationId)}`,\n }),\n completeMember: (identity: string, verificationId: string, memberId: string, body: { token: string }) =>\n request(config, LegalMemberSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/verifications/${encodeURIComponent(verificationId)}/members/${encodeURIComponent(memberId)}/complete`,\n body,\n }),\n resendMemberLink: (identity: string, verificationId: string, memberId: string) =>\n request(config, LegalMemberSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/verifications/${encodeURIComponent(verificationId)}/members/${encodeURIComponent(memberId)}/resend`,\n }),\n});\n\nconst companies = (config: ClientConfig) => ({\n companies: (identity: string, query: ListQuery = {}) =>\n request(config, page(LegalCompanySchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies`,\n query,\n }),\n createCompany: (identity: string, body: CreateLegalCompany) =>\n request(config, LegalCompanySchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies`,\n body,\n }),\n company: (identity: string, companyId: string) =>\n request(config, LegalCompanySchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies/${encodeURIComponent(companyId)}`,\n }),\n submitCompany: (identity: string, companyId: string) =>\n request(config, LegalCompanySchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies/${encodeURIComponent(companyId)}/submit`,\n }),\n documents: (identity: string, companyId: string, query: ListQuery = {}) =>\n request(config, page(LegalDocumentSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies/${encodeURIComponent(companyId)}/documents`,\n query,\n }),\n documentLink: (identity: string, companyId: string, documentId: string) =>\n request(config, LegalDocumentLinkSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/legal/companies/${encodeURIComponent(companyId)}/documents/${encodeURIComponent(documentId)}`,\n }),\n naicsCodes: (query: ListQuery & { q?: string | undefined } = {}) =>\n request(config, page(NaicsCodeSchema), { method: \"GET\", path: \"/v1/legal/naics_codes\", query }),\n states: (query: ListQuery = {}) =>\n request(config, page(LegalStateSchema), { method: \"GET\", path: \"/v1/legal/states\", query }),\n});\n\nexport const legal = (config: ClientConfig) => ({\n ...verifications(config),\n ...companies(config),\n});\n","/**\n * The custodied wallets an identity may hold — one per network, with x402 quote and pay\n * (`canonical-spec.md §44`), reached as `client.identities.wallet.*`. Every method takes a trailing\n * `{ network }` naming which wallet it addresses (`?network=`); absent, the testnet wallet. Money is\n * integer micro-USD. A deployment without a custody provider bound answers `feature_not_configured`.\n */\n\nimport {\n page,\n WalletPaymentSchema,\n WalletQuoteSchema,\n WalletSchema,\n WalletTransactionSchema,\n type CreateWallet,\n type FundWallet,\n type ListWalletTransactions,\n type TransferWallet,\n type WalletPayRequest,\n type WalletPolicy,\n type WalletQuoteRequest,\n type WalletSelect,\n} from \"@vetta/core\";\nimport { request, type ClientConfig } from \"./http\";\nimport { keyed, type ListQuery } from \"./control-plane\";\n\nexport const wallet = (config: ClientConfig) => {\n return {\n get: (identity: string, select: WalletSelect = {}) =>\n request(config, WalletSchema, { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet`, query: select }),\n /** Returns the existing wallet when the identity already holds one on `body.network`. */\n create: (identity: string, body: CreateWallet = {}) =>\n request(config, WalletSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet`, body }),\n updatePolicy: (identity: string, body: Partial<WalletPolicy>, select: WalletSelect = {}) =>\n request(config, WalletSchema, { method: \"PATCH\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/policy`, body, query: select }),\n freeze: (identity: string, select: WalletSelect = {}) =>\n request(config, WalletSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/freeze`, query: select }),\n unfreeze: (identity: string, select: WalletSelect = {}) =>\n request(config, WalletSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/unfreeze`, query: select }),\n /** The three money moves take an `idempotencyKey` so a retry of one move reuses its key and moves the money once. */\n fund: (identity: string, body: FundWallet, select: WalletSelect = {}, opts: { idempotencyKey?: string } = {}) =>\n request(config, WalletTransactionSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/fund`, body, query: select, headers: keyed(opts) }),\n transfer: (identity: string, body: TransferWallet, select: WalletSelect = {}, opts: { idempotencyKey?: string } = {}) =>\n request(config, WalletTransactionSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/transfer`, body, query: select, headers: keyed(opts) }),\n sweep: (identity: string, body: { to?: string } = {}, select: WalletSelect = {}, opts: { idempotencyKey?: string } = {}) =>\n request(config, WalletTransactionSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/sweep`, body, query: select, headers: keyed(opts) }),\n transactions: (identity: string, query: ListQuery & ListWalletTransactions & WalletSelect = {}) =>\n request(config, page(WalletTransactionSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/transactions`, query }),\n /** x402 receipts: the `pay` transactions (canonical-spec §44.2). */\n receipts: (identity: string, query: ListQuery & Omit<ListWalletTransactions, \"kind\"> & WalletSelect = {}) =>\n request(config, page(WalletTransactionSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/wallet/transactions`,\n query: { ...query, kind: \"pay\" },\n }),\n quote: (identity: string, body: WalletQuoteRequest, select: WalletSelect = {}) =>\n request(config, WalletQuoteSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/quote`, body, query: select }),\n pay: (identity: string, body: WalletPayRequest, select: WalletSelect = {}) =>\n request(config, WalletPaymentSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/wallet/pay`, body, query: select }),\n };\n};\n","/**\n * Mobile devices — the third member of the computer suite (`canonical-spec §53`,\n * `docs/api/mobile-devices.mdx`). A cloud phone you look at, act on and destroy.\n *\n * `liveView` returns the device's dashboard page as `url`, and `stream`: a bearer credential that\n * shows and drives the screen with no further auth. Hold it in memory, play it, and let it die with\n * the device; never store or log it. Only a signed-in member (the dashboard) is given `stream`; with\n * an API key it is `null`, and `url` is where the screen plays.\n */\nimport {\n MobileActionResultSchema,\n MobileDeviceSchema,\n MobileLiveViewSchema,\n page,\n type MobileAction,\n type MobileDevice,\n} from \"@vetta/core\";\nimport type { ListQuery } from \"./control-plane\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\n\nexport type MobileDeviceCreate = Partial<\n Pick<MobileDevice, \"name\" | \"platform\" | \"os_version\" | \"model\" | \"jurisdiction\" | \"idle_timeout_minutes\" | \"max_duration_minutes\" | \"apps\" | \"session_id\">\n>;\n\n/** An `install_app` result's `output` (§53.4). `installing`: still going — act again with the same app to look. */\nexport interface MobileInstallAppOutput {\n app: string;\n status: \"installed\" | \"installing\" | \"failed\";\n error: string | null;\n}\n\nexport const mobileDevices = (config: ClientConfig) => ({\n /** `202`: the answer carries whatever status is true when the provider has been asked (§53.2). */\n create: (body: MobileDeviceCreate) =>\n request(config, MobileDeviceSchema, { method: \"POST\", path: \"/v1/mobile_devices\", body }),\n /** `session_id` narrows the list to the phone that agent session opened (§53.8). */\n list: (query: ListQuery & { session_id?: string | undefined } = {}) =>\n request(config, page(MobileDeviceSchema), { method: \"GET\", path: \"/v1/mobile_devices\", query }),\n /** Reconciles the row from the provider — the read that notices an idle-timer termination (§53.3). */\n get: (id: string) =>\n request(config, MobileDeviceSchema, { method: \"GET\", path: `/v1/mobile_devices/${encodeURIComponent(id)}` }),\n /** The name, and nothing else. */\n update: (id: string, body: { name: string }) =>\n request(config, MobileDeviceSchema, { method: \"PATCH\", path: `/v1/mobile_devices/${encodeURIComponent(id)}`, body }),\n /** One action (§53.4). Only a `screenshot` answers with `image` filled (a JPEG); `install_app`'s `output` is a `MobileInstallAppOutput`. */\n act: (id: string, action: MobileAction) =>\n request(config, MobileActionResultSchema, { method: \"POST\", path: `/v1/mobile_devices/${encodeURIComponent(id)}/act`, body: action }),\n liveView: (id: string) =>\n request(config, MobileLiveViewSchema, { method: \"POST\", path: `/v1/mobile_devices/${encodeURIComponent(id)}/live_view`, body: {} }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/mobile_devices/${encodeURIComponent(id)}` }),\n});\n","/**\n * The company's CRM and Calendar (`canonical-spec §63`, `docs/api/crm.mdx`): contacts by stage, each\n * with a timeline, and a meeting as a dated line on it. Needs `agents:write`, the reads too.\n */\nimport { CalendarItemSchema, CrmActivitySchema, CrmContactDetailSchema, CrmContactSchema, page, type CreateCrmActivitySchema, type CreateCrmContactSchema, type CrmStage, type UpdateCrmActivitySchema, type UpdateCrmContactSchema } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport type { ListQuery } from \"./control-plane\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport type CrmContactCreate = z.input<typeof CreateCrmContactSchema>;\nexport type CrmContactUpdate = z.input<typeof UpdateCrmContactSchema>;\nexport type CrmActivityCreate = z.input<typeof CreateCrmActivitySchema>;\nexport type CrmActivityUpdate = z.input<typeof UpdateCrmActivitySchema>;\n\nconst Deleted = z.object({ id: z.string(), object: z.string(), deleted: z.literal(true) });\n\nexport const crm = (config: ClientConfig) => ({\n contacts: {\n /** Newest touched first. `q` looks through the name, the company and the email. */\n list: (query: ListQuery & { stage?: CrmStage; q?: string } = {}) => request(config, page(CrmContactSchema), { method: \"GET\", path: \"/v1/crm/contacts\", query }),\n /** An email already on file adds to that contact. */\n create: (body: CrmContactCreate) => request(config, CrmContactSchema, { method: \"POST\", path: \"/v1/crm/contacts\", body }),\n /** The contact and its timeline, newest first. */\n get: (id: string) => request(config, CrmContactDetailSchema, { method: \"GET\", path: `/v1/crm/contacts/${encodeURIComponent(id)}` }),\n update: (id: string, body: CrmContactUpdate) => request(config, CrmContactSchema, { method: \"PATCH\", path: `/v1/crm/contacts/${encodeURIComponent(id)}`, body }),\n /** Gone with its timeline. */\n delete: (id: string) => request(config, Deleted, { method: \"DELETE\", path: `/v1/crm/contacts/${encodeURIComponent(id)}` }),\n },\n activity: {\n /** A note, an email, a call, or a meeting, which alone may stand without a contact. */\n create: (body: CrmActivityCreate) => request(config, CrmActivitySchema, { method: \"POST\", path: \"/v1/crm/activity\", body }),\n update: (id: string, body: CrmActivityUpdate) => request(config, CrmActivitySchema, { method: \"PATCH\", path: `/v1/crm/activity/${encodeURIComponent(id)}`, body }),\n delete: (id: string) => request(config, Deleted, { method: \"DELETE\", path: `/v1/crm/activity/${encodeURIComponent(id)}` }),\n },\n /** Meetings and the follow-ups due in `[from, to)`, soonest first. */\n calendar: (query: { from: string; to: string }) => request(config, page(CalendarItemSchema), { method: \"GET\", path: \"/v1/crm/calendar\", query }),\n});\n","/**\n * Outcomes (`canonical-spec §58`, `docs/capabilities/outcomes.mdx`): a description and a Markdown\n * rubric a grader holds a session to. Immutable — no update, no delete; a changed rubric is a new\n * outcome. Attaching one to a session is `sessions.setOutcome`.\n */\nimport { OutcomeSchema, page, type CreateOutcomeSchema } from \"@vetta/core\";\nimport type { z } from \"zod\";\nimport type { ListQuery } from \"./control-plane\";\nimport { request, type ClientConfig } from \"./http\";\n\n/** Exactly one of `rubric` (inline Markdown) and `rubric_file` (a `fil_` id); `max_iterations` defaults to 3. */\nexport type OutcomeCreate = z.input<typeof CreateOutcomeSchema>;\n\nexport const outcomes = (config: ClientConfig) => ({\n create: (body: OutcomeCreate) => request(config, OutcomeSchema, { method: \"POST\", path: \"/v1/outcomes\", body }),\n /** Newest first. */\n list: (query: ListQuery = {}) => request(config, page(OutcomeSchema), { method: \"GET\", path: \"/v1/outcomes\", query }),\n get: (id: string) => request(config, OutcomeSchema, { method: \"GET\", path: `/v1/outcomes/${encodeURIComponent(id)}` }),\n});\n","/**\n * The model proxy — `POST /v1/proxy/anthropic/v1/messages` (`canonical-spec.md §26`,\n * `docs/api/proxy.mdx`). One org-level model call: no session, no agent, no event log.\n *\n * **Why this exists when ADR-0276 said it should not.** That decision refused a typed method on\n * the grounds that the endpoint's whole value is an *existing* Messages-dialect client working\n * unchanged, so ours would be a second, worse way to reach `client.sessions`. The first half still\n * holds and is why there is no streaming method here — a client that streams already has one, and\n * the endpoint exists so it keeps working. The second half does not: `sessions` runs a durable\n * agent and bills a session, this books an org-level debit with no session id on the ledger entry,\n * and until now the only way to reach it from our own client was `send()`, hand-rolling the header,\n * the path and the parse at every call site. The CLI needed exactly that (`vetta proxy message`).\n * Reversed in ADR-0278.\n *\n * The wire shapes are declared here, not in `@vetta/core`, for `connections.ts`' reason: this is a\n * **dialect** we serve for compatibility, not one of our objects. `core` owns what we store.\n */\nimport { ProxyCallTraceSchema, page, type ModelSelectionPolicy, type Window } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport type { ListQuery } from \"./control-plane\";\nimport { request, type ClientConfig } from \"./http\";\n\n/** A block on the way out. `tool_result` answers a `tool_use` the model asked for last turn. */\nexport type ProxyBlock =\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> }\n | { type: \"tool_result\"; tool_use_id: string; content: string };\n\n/**\n * The request. Every field the endpoint carries and **nothing else**: a sampling parameter it\n * cannot honour is refused there with `validation_failed` naming the key, so declaring one here\n * would only let the compiler bless a call the server rejects.\n *\n * `stream` is absent on purpose — this method parses one JSON body. Streaming is the job of the\n * Messages-dialect client the endpoint exists for; point it at `<baseUrl>/v1/proxy/anthropic`.\n */\nexport interface ProxyMessageCreate {\n /** A Vetta model id, exactly as `client.models.list()` returns it. */\n model: string;\n /**\n * Optional: let the evaluation model pick which of these ids answers, per call (§46.6). `model`\n * must be one of the keys and is the default; the reply's `model` names the pick, and the\n * evaluator's tokens are one more `input` line on the same ledger entry.\n */\n model_selection?: ModelSelectionPolicy;\n messages: { role: \"user\" | \"assistant\"; content: string | ProxyBlock[] }[];\n /** The output allowance, and therefore the size of the pre-flight quote held against the balance. */\n max_tokens: number;\n system?: string;\n tools?: { name: string; description?: string; input_schema: Record<string, unknown> }[];\n}\n\nconst TextBlock = z.object({ type: z.literal(\"text\"), text: z.string() });\nconst ToolUseBlock = z.object({\n type: z.literal(\"tool_use\"),\n id: z.string(),\n name: z.string(),\n input: z.record(z.string(), z.unknown()),\n});\n\n/**\n * The reply. `id` is the request id — the same value on `x-request-id` and on the ledger entry, so\n * the message, the log line and the charge all name one thing. `usage` is the dialect's four\n * counters; the exact five-tier split is on `client.credits.ledger()`.\n */\nexport const ProxyMessageSchema = z.object({\n id: z.string(),\n type: z.literal(\"message\"),\n role: z.literal(\"assistant\"),\n model: z.string(),\n /** The model that actually answered — what `vetta/auto` became; null when the reply named none. Absent from an older API. */\n resolved_model: z.string().nullable().optional(),\n content: z.array(z.discriminatedUnion(\"type\", [TextBlock, ToolUseBlock])),\n stop_reason: z.string().nullable(),\n stop_sequence: z.string().nullable(),\n usage: z.object({\n input_tokens: z.number().int(),\n output_tokens: z.number().int(),\n cache_read_input_tokens: z.number().int(),\n cache_creation_input_tokens: z.number().int(),\n }),\n});\nexport type ProxyMessage = z.infer<typeof ProxyMessageSchema>;\n\n\n/**\n * The Chat Completions dialect on the same proxy. It exists for a client — or a class-B harness —\n * that speaks this envelope and nothing else; the reasoning in this file's header applies verbatim,\n * including why there is no streaming method.\n */\nexport interface ProxyCompletionCreate {\n /** A Vetta model id, exactly as `client.models.list()` returns it. */\n model: string;\n /** As on `ProxyMessageCreate`: an optional per-call pick among these ids, `model` the default. */\n model_selection?: ModelSelectionPolicy;\n messages: { role: \"system\" | \"user\" | \"assistant\" | \"tool\"; content: string | null; tool_call_id?: string }[];\n /** Optional here, unlike the Messages door: omitted means \"as much as this model may emit\". */\n max_completion_tokens?: number;\n max_tokens?: number;\n temperature?: number;\n tools?: { type: \"function\"; function: { name: string; description?: string; parameters?: Record<string, unknown> } }[];\n}\n\nexport const ProxyCompletionSchema = z.object({\n id: z.string(),\n object: z.literal(\"chat.completion\"),\n created: z.number().int(),\n model: z.string(),\n /** As on `ProxyMessageSchema`: the model that actually answered. */\n resolved_model: z.string().nullable().optional(),\n choices: z.array(\n z.object({\n index: z.number().int(),\n message: z.object({\n role: z.literal(\"assistant\"),\n content: z.string().nullable(),\n tool_calls: z\n .array(z.object({\n id: z.string(),\n type: z.literal(\"function\"),\n function: z.object({ name: z.string(), arguments: z.string() }),\n }))\n .optional(),\n }),\n finish_reason: z.string(),\n }),\n ),\n usage: z.object({\n prompt_tokens: z.number().int(),\n completion_tokens: z.number().int(),\n total_tokens: z.number().int(),\n prompt_tokens_details: z.object({ cached_tokens: z.number().int() }),\n completion_tokens_details: z.object({ reasoning_tokens: z.number().int() }),\n }),\n});\nexport type ProxyCompletion = z.infer<typeof ProxyCompletionSchema>;\n\nexport const proxy = (config: ClientConfig) => ({\n /**\n * One model call against the organization's balance.\n *\n * `window` is a **header**, not a body field: the envelope has no room for one and inventing a\n * field would make it ours rather than compatible. Unset means `immediate`, and a window is\n * never quietly downgraded — a `(model, window)` pair with no published price is refused with\n * `window_unavailable` before anything is spent.\n */\n messages: (body: ProxyMessageCreate, window?: Window) =>\n request(config, ProxyMessageSchema, {\n method: \"POST\",\n path: \"/v1/proxy/anthropic/v1/messages\",\n body,\n ...(window === undefined ? {} : { headers: { \"vetta-window\": window } }),\n }),\n /** The same call, same balance, same rate card, in the Chat Completions dialect. */\n completions: (body: ProxyCompletionCreate, window?: Window) =>\n request(config, ProxyCompletionSchema, {\n method: \"POST\",\n path: \"/v1/proxy/openai/v1/chat/completions\",\n body,\n ...(window === undefined ? {} : { headers: { \"vetta-window\": window } }),\n }),\n /**\n * WHAT THE CALLS ABOVE ACTUALLY SAID (`canonical-spec §26.5`, ADR-0745).\n *\n * A proxy call books a ledger debit; these two read the other half of it — the key that sent it,\n * the model that answered, what the vendor charged us, and, when the deploy stores content, the\n * prompt and the reply. Both take `audit:read`, NOT the `proxy:write` the calls themselves take:\n * these rows hold the organization's prompts, and `proxy:write` is the scope handed to a sandbox\n * precisely so that it buys one model call and nothing else.\n *\n * A trace is not forever. Every row carries `expires_at`, and a reaper deletes it when it passes.\n */\n calls: (query: ListQuery = {}) =>\n request(config, page(ProxyCallTraceSchema), { method: \"GET\", path: \"/v1/proxy/calls\", query }),\n /** One trace, by the request id the reply and the ledger entry already carry. */\n call: (requestId: string) =>\n request(config, ProxyCallTraceSchema, { method: \"GET\", path: `/v1/proxy/calls/${encodeURIComponent(requestId)}` }),\n});\n","/** Identity-owned social setup and text publishing (`canonical-spec.md §27`). */\n\nimport {\n PostSchema,\n SOCIAL_PLATFORMS,\n SOCIAL_TEXT_PLATFORMS,\n SocialAccountSchema,\n SocialAnalyticsSchema,\n SocialCommentSchema,\n SocialPostSchema,\n SocialUploadSchema,\n SOCIAL_VISIBILITIES,\n type SocialPlatform,\n type SocialTextPlatform,\n type PostStatus,\n type SocialVisibility,\n page,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\nexport const SocialWorkspaceSchema = z.object({\n object: z.literal(\"social_workspace\"),\n identity_id: z.string(),\n activated: z.boolean(),\n accounts: z.array(SocialAccountSchema),\n});\nexport type SocialWorkspace = z.infer<typeof SocialWorkspaceSchema>;\n\nconst SocialPortalSchema = z.object({ object: z.literal(\"social_portal_link\"), url: z.url() });\n\nexport interface SocialPostCreate {\n content: string;\n title?: string;\n platforms: SocialPlatform[];\n scheduled_at?: string;\n media_urls?: string[];\n file_ids?: string[];\n /** Omit to publish at the connected account's own default. */\n visibility?: SocialVisibility;\n /**\n * Opt-in AI label: each network's AI label where it has one, and `#AIgenerated` at the end of the\n * caption. Without it a post is unlabelled, including one with a file rendered as a character.\n */\n ai_generated?: boolean;\n}\n\nconst setup = (config: ClientConfig) => ({\n activate: (identity: string) =>\n request(config, SocialWorkspaceSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/activate`,\n }),\n status: (identity: string) =>\n request(config, SocialWorkspaceSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social`,\n }),\n portal: (\n identity: string,\n /** `expires_in` is seconds, 300 to 172 800; omitted, the deployment picks an hour. */\n body: { redirect_url?: string; platforms?: SocialPlatform[]; expires_in?: number } = {},\n ) =>\n request(config, SocialPortalSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/portal`,\n body,\n }),\n accounts: (identity: string, query: ListQuery = {}) =>\n request(config, page(SocialAccountSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/accounts`,\n query,\n }),\n accountAnalytics: (identity: string, account: string) =>\n request(config, SocialAnalyticsSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/accounts/${encodeURIComponent(account)}/analytics`,\n }),\n upload: (identity: string, body: { url: string }) =>\n request(config, SocialUploadSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/uploads`,\n body,\n }),\n});\n\nconst publishing = (config: ClientConfig) => ({\n createPost: (identity: string, body: SocialPostCreate) =>\n request(config, SocialPostSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/posts`,\n body,\n }),\n getPost: (identity: string, post: string) =>\n request(config, SocialPostSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/posts/${encodeURIComponent(post)}`,\n }),\n deletePost: (identity: string, post: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/posts/${encodeURIComponent(post)}`,\n }),\n postAnalytics: (identity: string, post: string) =>\n request(config, SocialAnalyticsSchema, {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/posts/${encodeURIComponent(post)}/analytics`,\n }),\n /**\n * `GET /v1/posts` — every post the company files, across identities and sessions (§27.1): the\n * `social.post` calls waiting on a person (`pending`), and the ones sent, with their latest numbers.\n * `reconcile: false` lists what is stored without asking the provider about due posts first.\n */\n listPosts: ({ reconcile, ...query }: { status?: PostStatus; identity_id?: string; agent_id?: string; reconcile?: boolean } & ListQuery = {}) =>\n request(config, page(PostSchema), {\n method: \"GET\",\n path: \"/v1/posts\",\n query: { ...query, ...(reconcile === undefined ? {} : { reconcile: String(reconcile) }) },\n }),\n comments: (identity: string, post: string, query: ListQuery = {}) =>\n request(config, page(SocialCommentSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/social/posts/${encodeURIComponent(post)}/comments`,\n query,\n }),\n});\n\nexport const social = (config: ClientConfig) => ({\n ...setup(config),\n ...publishing(config),\n});\n\nexport { SOCIAL_PLATFORMS, SOCIAL_TEXT_PLATFORMS, SOCIAL_VISIBILITIES };\nexport type { PostStatus, SocialPlatform, SocialTextPlatform, SocialVisibility };\n","/** Public data reads through one priced catalogue, every domain (`canonical-spec §54.1`). */\n\nimport {\n DataRunSchema,\n DataToolDetailSchema,\n DataToolSchema,\n type DataDomain,\n type DataRunRequest,\n type SocialDataPlatform,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport type { DataDomain, DataRun, DataRunRequest, DataTool, DataToolDetail } from \"@vetta/core\";\n\nexport interface DataToolSearch {\n query: string;\n domain?: DataDomain | undefined;\n /** Social tools for one network. */\n platform?: SocialDataPlatform | undefined;\n limit?: number | undefined;\n}\n\nconst ToolList = z.object({ data: z.array(DataToolSchema) });\n\nexport const data = (config: ClientConfig) => ({\n /** Free. Ranked best first; the page is the whole answer (no cursor). */\n searchTools: (query: DataToolSearch) => request(config, ToolList, { method: \"GET\", path: \"/v1/data/tools\", query: { ...query } }),\n /** Free. The input schema (`path`, `query`, `body`) a run must follow, its price and notes. */\n getTool: (id: string) => request(config, DataToolDetailSchema, { method: \"GET\", path: `/v1/data/tools/${encodeURIComponent(id)}` }),\n /** Priced at the tool's listed price; answers when the run ends (up to ~2 minutes). */\n run: (body: DataRunRequest) => request(config, DataRunSchema, { method: \"POST\", path: \"/v1/data/runs\", body }),\n});\n","/** Public social media reads through one priced catalogue (`canonical-spec §52.1`). */\n\nimport {\n SocialDataRunSchema,\n SocialDataToolDetailSchema,\n SocialDataToolSchema,\n type SocialDataPlatform,\n type SocialDataRunRequest,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { request, type ClientConfig } from \"./http\";\n\nexport type { SocialDataRun, SocialDataTool, SocialDataToolDetail, SocialDataRunRequest } from \"@vetta/core\";\n\nexport interface SocialDataToolSearch {\n query: string;\n platform?: SocialDataPlatform | undefined;\n limit?: number | undefined;\n}\n\nconst ToolList = z.object({ data: z.array(SocialDataToolSchema) });\n\nexport const socialData = (config: ClientConfig) => ({\n /** Free. Ranked best first; the page is the whole answer (no cursor). */\n searchTools: (query: SocialDataToolSearch) =>\n request(config, ToolList, { method: \"GET\", path: \"/v1/social_data/tools\", query: { ...query } }),\n /** Free. The input schema (`path`, `query`, `body`) a run must follow, its price and notes. */\n getTool: (id: string) =>\n request(config, SocialDataToolDetailSchema, { method: \"GET\", path: `/v1/social_data/tools/${encodeURIComponent(id)}` }),\n /** Priced at the tool's listed price; answers when the run ends (up to ~2 minutes). */\n run: (body: SocialDataRunRequest) =>\n request(config, SocialDataRunSchema, { method: \"POST\", path: \"/v1/social_data/runs\", body }),\n});\n","/**\n * App object storage (`canonical-spec §38`, `docs/api/storage.mdx`) as a standalone facade: every\n * method takes an optional `app`, and without one the organization's single `fullstack` app is the\n * app (§37.2) — two candidates is `409 ambiguous_app` naming both, none is `404 not_found`. The\n * resolution is a client-side list, so it is one extra `GET /v1/apps` per call, never a cache.\n */\nimport { BucketSchema, SignedUrlSchema, StorageObjectSchema, page } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { apps } from \"./apps\";\nimport { ApiError, bytes, request, type ClientConfig } from \"./http\";\n\n/** `app` names the app explicitly; absent, the org's one `fullstack` app is resolved (§37.2). */\nexport type AppOption = { app?: string | undefined };\nexport type ObjectListQuery = AppOption & { prefix?: string | undefined; limit?: number | undefined; after?: string | undefined };\nexport type UploadOptions = AppOption & { contentType?: string | undefined };\nexport type UploadUrlOptions = AppOption & { contentType: string; expiresSeconds?: number | undefined };\n\nconst list = <T extends z.ZodType>(item: T) => z.object({ object: z.literal(\"list\"), data: z.array(item) });\nconst BucketDeletedSchema = z.object({ object: z.literal(\"bucket\"), name: z.string(), deleted: z.boolean() });\n\nconst envelope = (status: number, code: string, message: string) =>\n new ApiError(status, { type: status === 409 ? \"conflict\" : \"not_found\", code, message, request_id: \"\", param: \"app\" });\n\n/** The one place the standalone facades resolve \"which app\" (§37.2); `db` shares it. */\nexport const resolveApp = async (config: ClientConfig, app: string | undefined): Promise<string> => {\n if (app !== undefined) return app;\n const listed = await apps(config).list({ limit: 100 });\n const candidates = listed.data.filter((row) => row.type === \"fullstack\").map((row) => row.id);\n if (candidates.length === 1 && candidates[0] !== undefined) return candidates[0];\n if (candidates.length === 0) throw envelope(404, \"not_found\", \"this organization has no fullstack app; pass `app`\");\n throw envelope(409, \"ambiguous_app\", `more than one fullstack app; pass \\`app\\`: ${candidates.join(\", \")}`);\n};\n\n/** Each segment is encoded on its own so `users/alice.json` stays two segments on the wire. */\nconst keyPath = (key: string) => key.split(\"/\").map(encodeURIComponent).join(\"/\");\n\n/** `upload` takes bytes, a string, or anything else as JSON; the content type follows unless given. */\nfunction encode(data: Uint8Array | string | unknown): { body: Uint8Array; type: string } {\n if (data instanceof Uint8Array) return { body: data, type: \"application/octet-stream\" };\n if (typeof data === \"string\") return { body: new TextEncoder().encode(data), type: \"text/plain; charset=utf-8\" };\n return { body: new TextEncoder().encode(JSON.stringify(data)), type: \"application/json\" };\n}\n\nexport const storage = (config: ClientConfig) => ({\n buckets: {\n list: (options: AppOption = {}) =>\n resolveApp(config, options.app).then((app) =>\n request(config, list(BucketSchema), { method: \"GET\", path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets` }),\n ),\n create: (name: string, options: AppOption & { public?: boolean | undefined } = {}) =>\n resolveApp(config, options.app).then((app) =>\n request(config, BucketSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets`,\n body: { name, public: options.public ?? false },\n }),\n ),\n /** `force` empties the bucket first; without it a non-empty bucket is refused. */\n delete: (name: string, options: AppOption & { force?: boolean | undefined } = {}) =>\n resolveApp(config, options.app).then((app) =>\n request(config, BucketDeletedSchema, {\n method: \"DELETE\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(name)}`,\n query: { force: options.force ? \"true\" : undefined },\n }),\n ),\n },\n\n list: async (bucket: string, query: ObjectListQuery = {}) => {\n const app = await resolveApp(config, query.app);\n return request(config, page(StorageObjectSchema), {\n method: \"GET\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects`,\n query: { prefix: query.prefix, limit: query.limit, after: query.after },\n });\n },\n /** Inline, up to 50 MiB; anything larger goes through `signedUploadUrl`. */\n upload: async (bucket: string, key: string, data: Uint8Array | string | unknown, options: UploadOptions = {}) => {\n const app = await resolveApp(config, options.app);\n const encoded = encode(data);\n return request(config, StorageObjectSchema, {\n method: \"PUT\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects/${keyPath(key)}`,\n body: encoded.body,\n headers: { \"content-type\": options.contentType ?? encoded.type },\n });\n },\n /** The bytes and the type they were stored under. */\n download: async (bucket: string, key: string, options: AppOption = {}) => {\n const app = await resolveApp(config, options.app);\n return bytes(config, { method: \"GET\", path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects/${keyPath(key)}` });\n },\n /** One delete per key, in order; a missing key is not an error (the delete is idempotent). */\n remove: async (bucket: string, keys: string[], options: AppOption = {}): Promise<void> => {\n const app = await resolveApp(config, options.app);\n for (const key of keys) {\n await request(config, z.unknown(), { method: \"DELETE\", path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects/${keyPath(key)}` });\n }\n },\n /** A `PUT` URL the caller streams the bytes to; `expiresSeconds` is 60–3600, default 900. */\n signedUploadUrl: async (bucket: string, key: string, options: UploadUrlOptions) => {\n const app = await resolveApp(config, options.app);\n return request(config, SignedUrlSchema, {\n method: \"POST\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects/${keyPath(key)}/upload-url`,\n body: { content_type: options.contentType, expires_seconds: options.expiresSeconds },\n });\n },\n /** A one-hour `GET` URL for the object, for handing to a browser or another service. */\n signedUrl: async (bucket: string, key: string, options: AppOption = {}) => {\n const app = await resolveApp(config, options.app);\n return request(config, SignedUrlSchema, {\n method: \"GET\",\n path: `/v1/apps/${encodeURIComponent(app)}/storage/buckets/${encodeURIComponent(bucket)}/objects/${keyPath(key)}`,\n query: { signed: \"true\" },\n });\n },\n});\n","/**\n * Computers, skills and files — the three resources a session works *with*\n * (`workstreams/07-cli.md`, \"Contracts consumed\"). Objects come from `core`; one method per route.\n */\nimport {\n type Build3dRequestSchema,\n Build3dResultSchema,\n ComputerCommandSchema,\n ComputerInspectSchema,\n ComputerSchema,\n ExecStreamFrameSchema,\n FileEntrySchema,\n FileFolderInfoSchema,\n FileDeleteSchema,\n FileMoveSchema,\n FileSchema,\n FileUploadTicketSchema,\n SkillCatalogEntrySchema,\n SkillCatalogVersionSchema,\n type CreateFileUpload,\n type DeleteFiles,\n type MoveFiles,\n type FileKind,\n type FileSourceType,\n SkillSchema,\n SkillVersionSchema,\n SnapshotSchema,\n page,\n type BrowserOptionsInput,\n type Computer,\n type ComputerUpdate,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { computerBrowser } from \"./browser\";\nimport { bytes, DeletedSchema, RawSchema, request, text, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\nimport { streamFrames } from \"./stream\";\n\n// core-gaps: U2-browser-api — `browser` is the caller's shape: `{ allowed_domains }` alone still creates.\nexport type ComputerCreate = Partial<Pick<Computer, \"name\" | \"vcpu\" | \"memory_mb\" | \"disk_gb\">> & {\n snapshot_id?: string;\n browser?: BrowserOptionsInput | null;\n};\n\n/** `build3d`'s body as a caller writes it: `publish` and `timeout_s` (REST max 300) may be omitted. */\nexport type Build3dRequestInput = z.input<typeof Build3dRequestSchema>;\n\n/** The shell result the CLI prints and exits on (`apps/api/src/routes/computers.ts`). */\nexport const ExecResultSchema = z.object({\n stdout: z.string(),\n stderr: z.string(),\n exit_code: z.number().int(),\n duration_ms: z.number().int().nonnegative().optional(),\n /** Killed at `timeout_ms`, and `stdout`/`stderr` cut at the per-stream cap (ADR-1868). */\n timed_out: z.boolean().optional(),\n truncated: z.boolean().optional(),\n});\n\n/** `read` `write` `list` `mkdir` `remove` — five routes, five bodies, one shape on the wire. */\nexport type FsOp = \"read\" | \"write\" | \"list\" | \"mkdir\" | \"remove\";\n\nconst DirectorySchema = z.object({ entries: z.array(FileEntrySchema) });\n\n/** The computer as a workspace (`canonical-spec §41`): what it is doing, what has run on it. */\nconst workspace = (config: ClientConfig) => ({\n /** The name, and nothing else (§41.5). */\n update: (id: string, body: ComputerUpdate) =>\n request(config, ComputerSchema, { method: \"PATCH\", path: `/v1/computers/${encodeURIComponent(id)}`, body }),\n /** Provider-reported status and a probe of a running box; never wakes a paused one (§41.1). */\n inspect: (id: string) =>\n request(config, ComputerInspectSchema, { method: \"GET\", path: `/v1/computers/${encodeURIComponent(id)}/inspect` }),\n /**\n * The same run as `exec`, frame by frame (§41.2): `{stdout}`/`{stderr}` as they arrive, then one\n * `{exit}` naming the `computer_command` row it was recorded as. One connection, no resume.\n */\n execStream: (id: string, command: string, opts: { timeoutMs?: number } = {}) =>\n streamFrames(config, ExecStreamFrameSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/exec/stream`,\n body: { command, ...(opts.timeoutMs === undefined ? {} : { timeout_ms: opts.timeoutMs }) },\n }),\n /** What has been run on the box, newest first (§41.3). */\n commands: (id: string, query: ListQuery = {}) =>\n request(config, page(ComputerCommandSchema), {\n method: \"GET\",\n path: `/v1/computers/${encodeURIComponent(id)}/commands`,\n query,\n }),\n /** The typed listing (§41.4); `fs(id, \"list\", …)` is the same route untyped. */\n listDir: (id: string, path: string) =>\n request(config, DirectorySchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/fs/list`,\n body: { path },\n }).then((reply) => reply.entries),\n /** Run a build123d (`cad`) or Blender script on the box, check it, render it, publish it (§59). */\n build3d: (id: string, body: Build3dRequestInput) =>\n request(config, Build3dResultSchema, { method: \"POST\", path: `/v1/computers/${encodeURIComponent(id)}/build-3d`, body }),\n});\n\nexport const computers = (config: ClientConfig) => ({\n ...workspace(config),\n create: (body: ComputerCreate) =>\n request(config, ComputerSchema, { method: \"POST\", path: \"/v1/computers\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(ComputerSchema), { method: \"GET\", path: \"/v1/computers\", query }),\n get: (id: string) =>\n request(config, ComputerSchema, { method: \"GET\", path: `/v1/computers/${encodeURIComponent(id)}` }),\n exec: (id: string, command: string, timeoutMs?: number) =>\n request(config, ExecResultSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/exec`,\n body: { command, ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }) },\n }),\n /** Paused bills storage only — the first efficiency lever (`memory/context.md`). */\n pause: (id: string) =>\n request(config, ComputerSchema, { method: \"POST\", path: `/v1/computers/${encodeURIComponent(id)}/pause`, body: {} }),\n resume: (id: string) =>\n request(config, ComputerSchema, { method: \"POST\", path: `/v1/computers/${encodeURIComponent(id)}/resume`, body: {} }),\n /** An agent's computer only (§41.8): a person holds it, and its sessions wait until it is handed back. */\n takeOver: (id: string) =>\n request(config, ComputerSchema, { method: \"POST\", path: `/v1/computers/${encodeURIComponent(id)}/takeover`, body: {} }),\n handBack: (id: string) =>\n request(config, ComputerSchema, { method: \"DELETE\", path: `/v1/computers/${encodeURIComponent(id)}/takeover` }),\n snapshot: (id: string) =>\n request(config, SnapshotSchema, {\n method: \"POST\",\n path: `/v1/computers/${encodeURIComponent(id)}/snapshot`,\n body: {},\n }),\n /** The org's snapshots, newest first (§41.9); a snapshot outlives the computer it came from. */\n listSnapshots: (query: ListQuery = {}) =>\n request(config, page(SnapshotSchema), { method: \"GET\", path: \"/v1/snapshots\", query }),\n /** `state_conflict` (409) while a live computer was restored from it. */\n deleteSnapshot: (snapshotId: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/snapshots/${encodeURIComponent(snapshotId)}` }),\n /** The reply differs per op (`{content}`, `{entries}`, `{created}`…), so it is passed through. */\n fs: (id: string, op: FsOp, body: Record<string, string>) =>\n request(config, RawSchema, { method: \"POST\", path: `/v1/computers/${encodeURIComponent(id)}/fs/${encodeURIComponent(op)}`, body }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/computers/${encodeURIComponent(id)}` }),\n // core-gaps: U3-browser-clients\n /** The browser on one computer (`canonical-spec §32`): `computers.browser(id).goto(url)`. */\n browser: (id: string) => computerBrowser(config, id),\n});\n\n/**\n * The bytes of a skill plus the optional integrity claim. `sha256` is checked against the server's\n * own digest of `content` and rejected on mismatch — it never *supplies* the digest, so a push\n * cannot mint a version under a hash the bytes do not have (`apps/api/src/routes/skills.ts`).\n */\nexport type SkillContent = { content: string; description?: string; sha256?: string };\n\n/**\n * A version **as a push or a version listing returns it** — `core`'s `SkillVersionSchema` plus the\n * two fields `versionBody` (`apps/api/src/routes/skills.ts`) adds to say which skill it belongs to.\n * Extended rather than re-declared: the immutable version shape still has exactly one definition.\n *\n * Without `id` here zod would strip it, and `push(...).id` — the natural input to `pushVersion` —\n * would silently be `undefined`.\n */\nexport const SkillPushSchema = SkillVersionSchema.extend({\n id: z.string(),\n slug: z.string(),\n});\n\nexport const skills = (config: ClientConfig) => ({\n /**\n * `POST /v1/skills` — create-or-version **by slug**. Content-addressed: an identical push is a\n * no-op, a change mints a version (§13). Use this when the caller knows the slug it wants and\n * does not care whether the skill already exists.\n */\n push: (body: SkillContent & { slug: string }) =>\n request(config, SkillPushSchema, { method: \"POST\", path: \"/v1/skills\", body }),\n /**\n * `POST /v1/skills/{id}/versions` — the same push addressed at a skill that **already exists**,\n * by id or slug. Distinct from `push`: this 404s on an unknown skill instead of creating one, so\n * a release pipeline pinned to a skill id cannot silently mint a second skill after a rename.\n */\n pushVersion: (ref: string, body: SkillContent) =>\n request(config, SkillPushSchema, {\n method: \"POST\",\n path: `/v1/skills/${encodeURIComponent(ref)}/versions`,\n body,\n }),\n list: (query: ListQuery = {}) =>\n request(config, page(SkillSchema), { method: \"GET\", path: \"/v1/skills\", query }),\n get: (slug: string) => request(config, SkillSchema, { method: \"GET\", path: `/v1/skills/${encodeURIComponent(slug)}` }),\n listVersions: (slug: string, query: ListQuery = {}) =>\n request(config, page(SkillVersionSchema), {\n method: \"GET\",\n path: `/v1/skills/${encodeURIComponent(slug)}/versions`,\n query,\n }),\n /** Progressive disclosure: the body costs this second call, never every turn (§13). */\n getVersion: (slug: string, version: number) =>\n request(config, RawSchema, { method: \"GET\", path: `/v1/skills/${encodeURIComponent(slug)}/versions/${encodeURIComponent(version)}` }),\n delete: (slug: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/skills/${encodeURIComponent(slug)}` }),\n\n /**\n * The platform's own skills (§31.9) — what a `naive/slug` ref resolves against. Org-less and\n * read-only from here: it is written by the publish script, never by a tenant.\n */\n catalog: {\n /** The newest version of every slug, without `content`; `retrieve` costs the body (§13). */\n list: (query: ListQuery & { tag?: string | undefined; search?: string | undefined } = {}) =>\n request(config, page(SkillCatalogEntrySchema), { method: \"GET\", path: \"/v1/skills/catalog\", query }),\n /** The newest version of ONE slug, without `content` — what a `naive/<slug>` ref resolves to. */\n get: (slug: string) =>\n request(config, SkillCatalogEntrySchema, { method: \"GET\", path: `/v1/skills/catalog/${encodeURIComponent(slug)}` }),\n retrieve: (slug: string, version: number) =>\n request(config, SkillCatalogVersionSchema, {\n method: \"GET\",\n path: `/v1/skills/catalog/${encodeURIComponent(slug)}/versions/${encodeURIComponent(version)}`,\n }),\n },\n});\n\nexport type FileFilter = ListQuery & {\n scope?: \"session\" | \"published\" | undefined;\n session_id?: string | undefined;\n // core-gaps: U7-files-library — the asset-library filters (`canonical-spec §36.2`).\n /** One kind, or a comma list: `\"image,video\"` is the media gallery (ADR-0887). */\n kind?: FileKind | (string & {}) | undefined;\n source?: FileSourceType | undefined;\n tag?: string | undefined;\n search?: string | undefined;\n /** None of these kinds, comma-separated: `\"image,video\"` is the Files tab without the gallery. */\n exclude_kind?: FileKind | (string & {}) | undefined;\n /** Files an agent's sessions made. */\n agent_id?: string | undefined;\n /** Exactly these `fil_` ids, comma-separated, at most 100. */\n ids?: string | undefined;\n /** `desc` (newest first, the default) or `asc`. */\n order?: \"desc\" | \"asc\" | undefined;\n /** The files in this folder, matched without regard to case (`canonical-spec §36.4`). */\n folder?: string | undefined;\n /** A character's renders: files whose `source.character_id` is this `chr_` (ADR-1360). */\n character?: string | undefined;\n};\n\nexport interface FileUpdate {\n title?: string | null | undefined;\n description?: string | null | undefined;\n tags?: string[] | undefined;\n /** Into this folder (an existing one's casing wins); `null` takes it out of its folder. */\n folder?: string | null | undefined;\n}\n\nexport interface FileImport {\n url: string;\n /** Omitted, the URL's last path segment; a stock photo's `file_name` is the neutral one. */\n name?: string | undefined;\n title?: string | undefined;\n description?: string | undefined;\n tags?: string[] | undefined;\n folder?: string | undefined;\n}\n\n/** What `POST /v1/files/{id}/url` answers (`canonical-spec §40`). */\nexport const FileUrlSchema = z.object({\n object: z.literal(\"file_url\"),\n url: z.string(),\n expires_at: z.string(),\n});\n\nexport const files = (config: ClientConfig) => ({\n /** `multipart/form-data`: the `file` part carries the bytes, the rest is metadata. */\n upload: (form: FormData) =>\n request(config, FileSchema, { method: \"POST\", path: \"/v1/files\", body: form }),\n list: (query: FileFilter = {}) =>\n request(config, page(FileSchema), { method: \"GET\", path: \"/v1/files\", query }),\n get: (id: string) => request(config, FileSchema, { method: \"GET\", path: `/v1/files/${encodeURIComponent(id)}` }),\n /**\n * The file as UTF-8 text, through the API — a download is authorized by the same key as every\n * other read. A binary file (an image, audio, video) comes back mangled: use `downloadBytes`.\n */\n download: (id: string) =>\n text(config, { method: \"GET\", path: `/v1/files/${encodeURIComponent(id)}`, query: { download: \"true\" } }),\n /** The same download, unmangled — for binary files (an STL, a PNG) that text would corrupt. */\n downloadBytes: (id: string) =>\n bytes(config, { method: \"GET\", path: `/v1/files/${encodeURIComponent(id)}`, query: { download: \"true\" } }).then((got) => got.bytes),\n /**\n * `canonical-spec §40` — an address for this file that needs no key, good for seven days. What a\n * `<video>` or an `<img>` tag can open, and what a fetch-once publishing provider is handed.\n */\n url: (id: string) =>\n request(config, FileUrlSchema, { method: \"POST\", path: `/v1/files/${encodeURIComponent(id)}/url`, body: {} }),\n /** The promotion boundary: session scratch becomes a durable org artifact. Idempotent. */\n publish: (id: string) =>\n request(config, FileSchema, { method: \"POST\", path: `/v1/files/${encodeURIComponent(id)}/publish`, body: {} }),\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/files/${encodeURIComponent(id)}` }),\n // core-gaps: U7-files-library\n /** Library metadata only — title, description, tags. The bytes and the name never change. */\n update: (id: string, body: FileUpdate) =>\n request(config, FileSchema, { method: \"PATCH\", path: `/v1/files/${encodeURIComponent(id)}`, body }),\n /** Server-side fetch of a public URL into a `published` file, under the client's idempotency key. */\n import: (body: FileImport) =>\n request(config, FileSchema, { method: \"POST\", path: \"/v1/files/imports\", body }),\n /**\n * A one-shot link for up to 60 MiB of bytes: PUT them to `upload_url` within 15 minutes, with the\n * `Content-Type` and `Content-Length` declared here. The answer to that PUT is the `published` file.\n */\n createUpload: (body: CreateFileUpload) =>\n request(config, FileUploadTicketSchema, { method: \"POST\", path: \"/v1/files/uploads\", body }),\n /**\n * Files into a folder (`ids`), or a whole folder renamed or merged into another (`from`); `folder:\n * null` takes them out. Only the name on the files changes (`canonical-spec §36.4`).\n */\n move: (body: MoveFiles) =>\n request(config, FileMoveSchema, { method: \"POST\", path: \"/v1/files/move\", body }),\n /** Up to 100 files deleted in one request; an id the org does not hold is skipped (`canonical-spec §36.4`). */\n deleteMany: (body: DeleteFiles) =>\n request(config, FileDeleteSchema, { method: \"POST\", path: \"/v1/files/delete\", body }),\n /** Every folder, newest first: its file count, newest time, cover ids and its one maker agent. */\n folders: () =>\n request(config, page(FileFolderInfoSchema), { method: \"GET\", path: \"/v1/files/folders\" }),\n});\n","/**\n * The resumable event stream (`canonical-spec.md §8`) — the client half of our best primitive.\n *\n * `after_seq` is **exclusive**, SSE `id:` carries the `seq`, so a dropped connection is resumed by\n * reconnecting with the last `seq` seen: gap-free and duplicate-free. Anything at or below the\n * cursor is dropped on the floor, so an overlapping replay can never emit a duplicate.\n */\nimport { EventSchema, type Event, type Session } from \"@vetta/core\";\nimport type { z } from \"zod\";\nimport { sessions } from \"./control-plane\";\nimport { ApiError, apiErrorFrom, ResponseParseError, send, type Call, type ClientConfig } from \"./http\";\n\nexport interface StreamOptions {\n /** Resume point; events with `seq > after_seq` are delivered. Default 0 = from the beginning. */\n afterSeq?: number;\n /** Consecutive reconnects tolerated before the stream gives up. */\n maxRetries?: number;\n /**\n * Default `true`: a `session.idle` that parks the session on its own grade (`awaiting_delegation`\n * while an `outcome.evaluation.started` seen on this stream has no `completed` yet, §58.4) does not\n * end the stream — it runs on through the grade (and any revision turn) to the idle that follows a\n * terminal result. `false` ends at the first `session.idle`, as before outcomes.\n */\n throughGrades?: boolean;\n}\n\n/** Waited before reopening a stream the server closed while a grade is out (its quiet window ends). */\nconst GRADE_RECONNECT_MS = 1_000;\n\n/** The `{ outcome_id, iteration }` an `outcome.evaluation.*` event is about, as one key. */\nfunction gradeKey(event: Event): string {\n const data = event.data as { outcome_id?: unknown; iteration?: unknown };\n return `${String(data.outcome_id)}:${String(data.iteration)}`;\n}\n\n/** Splits an SSE wire buffer into complete frames, returning the trailing partial frame. */\nfunction frames(buffer: string): { done: string[]; rest: string } {\n const parts = buffer.split(\"\\n\\n\");\n return { done: parts.slice(0, -1), rest: parts[parts.length - 1] ?? \"\" };\n}\n\n/** The `data:` lines of one frame, joined. Comment frames (`: …`) are the empty string. */\nfunction dataOf(frame: string): string {\n return frame\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).trim())\n .join(\"\\n\");\n}\n\n/**\n * One SSE connection, as the parsed `data:` payload of each frame. Ends when the server closes the\n * stream; a non-2xx answer is the error envelope, thrown before anything is yielded.\n */\nasync function* connect(\n config: ClientConfig,\n call: Call,\n opened?: (response: Response) => void,\n): AsyncGenerator<unknown> {\n const response = await send(config, call, \"text/event-stream\");\n if (!response.ok || response.body === null) {\n throw apiErrorFrom(response, await response.text());\n }\n opened?.(response);\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n for (;;) {\n const chunk = await reader.read();\n if (chunk.done) break;\n buffer += decoder.decode(chunk.value, { stream: true });\n const { done, rest } = frames(buffer);\n buffer = rest;\n for (const frame of done) {\n const data = dataOf(frame);\n if (data !== \"\") yield JSON.parse(data);\n }\n }\n } finally {\n // The consumer stops at `session.idle`; without this the socket stays open until the edge\n // times it out, and `vetta run` sits there for a minute after the agent has finished.\n await reader.cancel().catch(() => undefined);\n }\n}\n\n/**\n * One SSE route as its parsed frames — the shape `computers.execStream` (`canonical-spec §41.2`)\n * has: one connection, no resume, each `data:` payload checked against `schema` before it is\n * yielded; a frame it refuses is a `ResponseParseError` naming the call, never a bare `ZodError`.\n * The resumable session stream below is this plus a cursor.\n */\nexport async function* streamFrames<T>(\n config: ClientConfig,\n schema: z.ZodType<T>,\n call: Call,\n): AsyncGenerator<T> {\n let response: Response | undefined;\n for await (const data of connect(config, call, (opened) => (response = opened))) {\n const parsed = schema.safeParse(data);\n if (!parsed.success) throw new ResponseParseError(response ?? new Response(), call, parsed.error);\n yield parsed.data;\n }\n}\n\n/**\n * *** A RESUME PAST THE SESSION'S LAST IDLE HUNG (QA 2026-11-03, ADR-1866). *** The stream ends on a\n * `session.idle` it delivers, and a cursor at or past the end of an idle session's log has none\n * left to deliver: the server holds a quiet stream open for its 60 s window (it must — the dashboard\n * keeps one open across turns), and the loop below reconnected on every close, ~6 minutes of\n * nothing. So a resume reads the live session first (§7, ADR-0728): one that is not working and\n * has nothing past the cursor is already where this stream would end. A send makes the session read\n * `running` at once (its inbox is non-empty), so send-then-resume still waits for the turn; a park\n * on a grade runs on.\n */\nfunction settled(session: Session, afterSeq: number, throughGrades: boolean): boolean {\n if (session.status === \"running\" || session.status === \"queued\") return false;\n if (throughGrades && session.stop_reason === \"awaiting_delegation\") return false;\n return session.last_seq <= afterSeq;\n}\n\n/**\n * Events for one session, resuming across drops. Ends when the session goes idle (the last event\n * before a terminal transition, §5) or after `maxRetries` consecutive failed reconnects. A graded\n * session's park on its own grade is not that idle unless `throughGrades` is `false` (§58.5). A\n * resume (`afterSeq > 0`) on a session already idle or ended, with nothing past the cursor, yields\n * nothing and returns at once.\n */\nexport async function* streamEvents(\n config: ClientConfig,\n sessionId: string,\n options: StreamOptions = {},\n): AsyncGenerator<Event> {\n const maxRetries = options.maxRetries ?? 5;\n const throughGrades = options.throughGrades ?? true;\n let lastSeq = options.afterSeq ?? 0;\n let failures = 0;\n /** Grades started on this stream and not yet completed. */\n const grading = new Set<string>();\n /** Passed a grade park and not yet the idle that ends the run: a quiet close is not a drop. */\n let held = false;\n if (lastSeq > 0 && settled(await sessions(config).get(sessionId), lastSeq, throughGrades)) return;\n for (;;) {\n try {\n const call: Call = {\n method: \"GET\",\n path: `/v1/sessions/${encodeURIComponent(sessionId)}/stream`,\n query: { after_seq: lastSeq },\n };\n for await (const payload of connect(config, call)) {\n /**\n * AN EVENT TYPE THIS CLIENT DOES NOT KNOW IS NOT AN ERROR (§8). The type set is additive\n * and the Worker deploys on its own schedule, so every client published before a type was\n * added meets it eventually; a strict parse turned that into a thrown `ZodError` that the\n * reconnect loop could only repeat until `maxRetries` ran out, i.e. one added row killed\n * the stream. The frame is skipped and the cursor is left where it was — `seq` is\n * monotonic, so the reconnect that follows a real drop simply replays and skips it again.\n */\n const decoded = EventSchema.safeParse(payload);\n if (!decoded.success) continue;\n const event = decoded.data;\n if (event.seq <= lastSeq) continue;\n lastSeq = event.seq;\n failures = 0;\n if (event.type === \"outcome.evaluation.started\") grading.add(gradeKey(event));\n if (event.type === \"outcome.evaluation.completed\") grading.delete(gradeKey(event));\n yield event;\n // Leave as soon as the session yields control. The server keeps the connection open for\n // its own keepalive window, so waiting for it to close would hang a finished run (§5, §8).\n // A park on the session's own grade is not yielding control: the answer is not graded yet.\n if (event.type === \"session.idle\") {\n held = throughGrades && grading.size > 0 && parkedOnGrade(event);\n if (!held) return;\n }\n }\n } catch (cause) {\n // A 4xx is the server's answer, not a dropped connection — retrying it just repeats it.\n if (cause instanceof ApiError && cause.status < 500 && cause.status !== 429) throw cause;\n if (++failures > maxRetries) throw cause;\n continue;\n }\n // A grade is out and the server's quiet window ended: nothing is wrong, the grader is working.\n // Reopen after a beat rather than spend the reconnect budget a real drop needs.\n if (held) {\n await new Promise((resolve) => setTimeout(resolve, GRADE_RECONNECT_MS));\n continue;\n }\n // The server closed without an idle event: reconnect on the same cursor until the budget runs out.\n if (++failures > maxRetries) return;\n }\n}\n\n/** The graded turn's park: `idle` with `awaiting_delegation` while its grader thread runs (§58.4). */\nfunction parkedOnGrade(event: Event): boolean {\n return (event.data as { stop_reason?: unknown }).stop_reason === \"awaiting_delegation\";\n}\n","/**\n * Trading — a brokerage account an identity connects, and the reads and writes made through it\n * (`canonical-spec §62`). Every method takes the identity (an `idn_` id or its name) first.\n *\n * `connect` answers an `authorize_url` and the `disclosure` a person must be shown before they open\n * it. `env` is optional on the reads and writes: with one active connection it is implied, with both\n * it is required. A write here is the caller's own decision (the key needs `billing:write`); it is\n * not an approval card. `placeOrder` sends this call's `Idempotency-Key` as the broker's\n * `client_order_id` unless the body names one, so a retried request cannot place twice.\n */\nimport {\n TradingAccountSchema,\n TradingConnectSchema,\n TradingConnectionSchema,\n TradingEnvSchema,\n TradingOrderSchema,\n TradingPositionSchema,\n TradingQuoteSchema,\n type CloseTradingPosition,\n type PlaceTradingOrder,\n type TradingEnv,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\n\nconst list = <T extends z.ZodType>(item: T) => z.object({ object: z.literal(\"list\"), data: z.array(item) });\nconst DisconnectedSchema = z.object({\n object: z.literal(\"trading_connection\"),\n identity_id: z.string(),\n env: TradingEnvSchema,\n deleted: z.literal(true),\n});\n\nexport type TradingEnvQuery = { env?: TradingEnv | undefined };\nexport type TradingOrdersQuery = TradingEnvQuery & { status?: \"open\" | \"closed\" | \"all\" | undefined; limit?: number | undefined };\nexport type TradingQuotesQuery = TradingEnvQuery & { symbols: string[]; asset_class?: \"us_equity\" | \"crypto\" | undefined };\n\nexport const trading = (config: ClientConfig) => ({\n /** Starts OAuth for one env. Show `disclosure` before opening `authorize_url`. */\n connect: (identity: string, body: { env: TradingEnv }) =>\n request(config, TradingConnectSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/connect`, body }),\n /**\n * Finishes a connect as the signed-in caller, with the `state`, `code` or `error` the brokerage\n * sent back (the dashboard does this on `/trading/complete`). Only a state minted in the caller's\n * own organization is accepted. Answers the connection: `active`, or `failed` with its reason.\n */\n complete: (body: { state: string; code?: string | undefined; error?: string | undefined }) =>\n request(config, TradingConnectionSchema, { method: \"POST\", path: \"/v1/trading/oauth/complete\", body }),\n connections: (identity: string) =>\n request(config, list(TradingConnectionSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/connections` }),\n disconnect: (identity: string, env: TradingEnv) =>\n request(config, DisconnectedSchema, { method: \"DELETE\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/connections/${encodeURIComponent(env)}` }),\n account: (identity: string, query: TradingEnvQuery = {}) =>\n request(config, TradingAccountSchema, { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/account`, query }),\n positions: (identity: string, query: TradingEnvQuery = {}) =>\n request(config, list(TradingPositionSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/positions`, query }),\n orders: (identity: string, query: TradingOrdersQuery = {}) =>\n request(config, list(TradingOrderSchema), { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/orders`, query }),\n order: (identity: string, orderId: string, query: TradingEnvQuery = {}) =>\n request(config, TradingOrderSchema, { method: \"GET\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/orders/${encodeURIComponent(orderId)}`, query }),\n /** Latest bid/ask. Crypto symbols are slashed (`BTC/USD`). */\n quotes: (identity: string, { symbols, ...query }: TradingQuotesQuery) =>\n request(config, list(TradingQuoteSchema), {\n method: \"GET\",\n path: `/v1/identities/${encodeURIComponent(identity)}/trading/quotes`,\n query: { ...query, symbols: symbols?.join(\",\") },\n }),\n placeOrder: (identity: string, body: PlaceTradingOrder) =>\n request(config, TradingOrderSchema, { method: \"POST\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/orders`, body }),\n cancelOrder: (identity: string, orderId: string, query: TradingEnvQuery = {}) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/identities/${encodeURIComponent(identity)}/trading/orders/${encodeURIComponent(orderId)}`, query }),\n /** Neither `qty` nor `percentage` closes the whole position. Answers the closing order. */\n closePosition: (identity: string, symbol: string, body: CloseTradingPosition = {}) =>\n request(config, TradingOrderSchema, {\n method: \"POST\",\n path: `/v1/identities/${encodeURIComponent(identity)}/trading/positions/${encodeURIComponent(symbol)}/close`,\n body,\n }),\n});\n","/**\n * The credential vault (`canonical-spec §23`, `docs/api/vaults.mdx`).\n *\n * **There is no read method here, and that is the contract, not an omission.** The control plane\n * serves no reveal route; `VaultCredentialSchema` has no `value` field, so `list` cannot return one\n * even if a future handler tried. Anything that wanted a value would have to invent a route this\n * file is forbidden to name (`index.ts`: nothing here names a route `apps/api` does not serve).\n *\n * Rotation is create-new + delete-old — there is no `update`, so `last_injected_at` stays\n * attributable to exactly one secret.\n */\nimport { VaultCredentialSchema, VaultSchema, page, type VaultCredentialKind } from \"@vetta/core\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\n\nexport type VaultCreate = { display_name: string; identity_id?: string | null };\n\n/**\n * The write side of a credential. `value` travels once, on this call, and is sealed server-side.\n * `host` is only meaningful for `env_var`; `mcp_server_url` is required for the two MCP kinds.\n */\nexport type CredentialCreate = {\n kind: VaultCredentialKind;\n key: string;\n value: string;\n host?: string;\n mcp_server_url?: string;\n /** The one agent the credential may be injected into; absent, any agent declaring the URL. */\n agent_id?: string;\n expires_at?: string;\n};\n\nexport const vaults = (config: ClientConfig) => ({\n create: (body: VaultCreate) =>\n request(config, VaultSchema, { method: \"POST\", path: \"/v1/vaults\", body }),\n list: (query: { limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, page(VaultSchema), { method: \"GET\", path: \"/v1/vaults\", query }),\n get: (id: string) => request(config, VaultSchema, { method: \"GET\", path: `/v1/vaults/${encodeURIComponent(id)}` }),\n /** Soft-deletes the vault; its credentials go for real. Irreversible for the secrets. */\n delete: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/vaults/${encodeURIComponent(id)}` }),\n\n credentials: {\n /** The only call in the system that carries a secret. The response is metadata only. */\n create: (vaultId: string, body: CredentialCreate) =>\n request(config, VaultCredentialSchema, {\n method: \"POST\",\n path: `/v1/vaults/${encodeURIComponent(vaultId)}/credentials`,\n body,\n }),\n list: (vaultId: string, query: { limit?: number | undefined; after?: string | undefined } = {}) =>\n request(config, page(VaultCredentialSchema), {\n method: \"GET\",\n path: `/v1/vaults/${encodeURIComponent(vaultId)}/credentials`,\n query,\n }),\n delete: (vaultId: string, credentialId: string) =>\n request(config, DeletedSchema, {\n method: \"DELETE\",\n path: `/v1/vaults/${encodeURIComponent(vaultId)}/credentials/${encodeURIComponent(credentialId)}`,\n }),\n },\n});\n","import { McpSessionSchema, ScopeSchema, page, type McpSession, type Scope } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeletedSchema, request, type ClientConfig } from \"./http\";\nimport type { ListQuery } from \"./control-plane\";\n\n/** With `name` alone, a signed-in person connects their own agent; `scopes` and `allowed_tools` are an operator's. */\nexport interface McpSessionCreate {\n name: string;\n identity_id?: string | null | undefined;\n scopes?: Scope[] | undefined;\n allowed_tools?: string[] | undefined;\n expires_in_seconds?: number | undefined;\n}\n\nexport const MintedMcpSessionSchema = McpSessionSchema.extend({\n secret: z.string().startsWith(\"mcp_\"),\n url: z.string(),\n scopes: z.array(ScopeSchema),\n});\n\nexport const mcpSessions = (config: ClientConfig) => ({\n create: (body: McpSessionCreate) =>\n request(config, MintedMcpSessionSchema, { method: \"POST\", path: \"/v1/mcp_sessions\", body }),\n list: (query: ListQuery = {}) =>\n request(config, page(McpSessionSchema), { method: \"GET\", path: \"/v1/mcp_sessions\", query }),\n get: (id: string) =>\n request(config, McpSessionSchema, { method: \"GET\", path: `/v1/mcp_sessions/${encodeURIComponent(id)}` }),\n revoke: (id: string) =>\n request(config, DeletedSchema, { method: \"DELETE\", path: `/v1/mcp_sessions/${encodeURIComponent(id)}` }),\n});\n\nexport type { McpSession };\n","/**\n * The company's mini apps (`canonical-spec §50`): what its template declares. `get` answers one\n * page — the named one, else the first — with every binding read, on the company's clock.\n */\nimport { MiniAppSchema, MiniAppSummarySchema } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { request, type ClientConfig } from \"./http\";\n\nconst MiniAppList = z.object({ data: z.array(MiniAppSummarySchema), has_more: z.boolean(), next_cursor: z.string().nullable() });\n\nexport const miniApps = (config: ClientConfig) => ({\n list: () => request(config, MiniAppList, { method: \"GET\", path: \"/v1/mini-apps\" }),\n get: (slug: string, page?: string) =>\n request(config, MiniAppSchema, { method: \"GET\", path: `/v1/mini-apps/${encodeURIComponent(slug)}`, ...(page ? { query: { page } } : {}) }),\n});\n","/**\n * Per-agent tool configuration (`canonical-spec.md §6`, `docs/capabilities/tools.mdx`).\n *\n * A toolset already goes over the wire as `agents.create`/`agents.update`'s `tools`, so nothing\n * here is a route. What was missing is the two things a caller needs to *write* one safely:\n *\n * 1. **Types for the config a tool reads.** `ToolConfigSchema.config` is `Record<string, unknown>`\n * on the wire and has to stay that way — an MCP or connection tool's config is the *tool's*,\n * not ours. But the built-ins whose config we do define are worth typing, because a misspelled\n * `allowed_domain` is ignored by design (a bad value must never fail a turn, ADR-0275) and the\n * only place that typo can still be caught is here, before it is sent.\n * 2. **A merge that does not destroy the rest of the toolset.** `configs` is the whole map, so\n * \"let this agent use one more model\" read as a `PATCH` means resending every other tool\n * unchanged. Doing that by hand is how an update silently disables something.\n */\nimport { isToolName, type ToolPermission, type Toolset } from \"@vetta/core\";\n\n/**\n * `web_search` and `web_fetch`. Configured **separately** — searching broadly while fetching only\n * from trusted hosts is the common shape — and each list matches a domain with its subdomains, so\n * `example.com` covers `docs.example.com` and never `notexample.com`.\n */\nexport interface WebToolConfig {\n /** Non-empty makes the list closed: nothing outside it is reachable. Absent is the open web. */\n allowed_domains?: string[];\n /** Always wins over `allowed_domains`, so one entry carves a hole in a broad allow-list. */\n blocked_domains?: string[];\n /** How much of a fetched page may enter the context. Defaults to `4000`; the rest is truncated. */\n max_content_tokens?: number;\n}\n\n/**\n * `generate_image` and `generate_video`. **Omit `models` and the agent gets the low-cost models\n * only** — both tools are on by default, so naming a premium model here is the deliberate step\n * that opens it up. The agent picks from the list and the cheapest is its default.\n */\nexport interface MediaToolConfig {\n models?: string[];\n}\n\n/** What to change about one tool. Every field is optional; what you omit keeps its current value. */\nexport interface ToolSettings {\n enabled?: boolean;\n permission?: ToolPermission;\n /** Merged over the tool's existing config, key by key, so one flag does not clear the others. */\n config?: WebToolConfig | MediaToolConfig | Record<string, unknown>;\n}\n\n/**\n * The toolset with one tool reconfigured — every other entry untouched, ready to send as\n * `agents.update(id, { tools })`.\n *\n * A tool absent from `configs` is created enabled, at the toolset's own default permission, because\n * a caller naming a tool means to use it. The name must be a built-in or a namespaced\n * `<namespace>.<tool>` (`core.isToolName`): the namespaced set comes from the org's live\n * connections and cannot be enumerated here, but a bare misspelling is still caught.\n */\nexport function withTool(tools: Toolset, name: string, settings: ToolSettings): Toolset {\n if (!isToolName(name)) {\n throw new TypeError(\n `\\`${name}\\` is not a built-in tool, and a connection or MCP tool is namespaced like \\`tracker.get_issue\\``,\n );\n }\n const current = tools.configs[name];\n const config = { ...current?.config, ...settings.config };\n return {\n ...tools,\n configs: {\n ...tools.configs,\n [name]: {\n enabled: settings.enabled ?? current?.enabled ?? true,\n permission: settings.permission ?? current?.permission ?? tools.default_config.permission,\n ...(Object.keys(config).length === 0 ? {} : { config }),\n },\n },\n };\n}\n","/**\n * `@usenaive-sdk/managed-agents` — the public typed client for the Vetta API. It is also the thin client the\n * CLI and the dashboard call, so it stays intentionally thin: no retries policy, no pagination\n * magic, no vendor names. One method per route, responses parsed with the `core` zod schemas, one\n * error envelope, one place that attaches `Idempotency-Key` and `Vetta-Version`. `docs/sdk/typescript.mdx`\n * is its published reference, and its method index is generated from this file's exports.\n *\n * The method table is the route table: every route `apps/api/src/routes/index.ts` serves is\n * reachable from exactly one method here, and nothing here names a route that surface does not\n * serve. Two methods are parameterized over a family rather than split per route — `computers.fs`\n * takes the op (five `/fs/*` routes; `listDir` is the typed listing) and `sessions.stream` /\n * `computers.execStream` are the two SSE consumers — and the routes that\n * are deliberately absent each have a written reason: the machine-only ones no customer credential\n * ever calls (provider-signed inbound receivers, the clip worker, `GET /v1/openapi.json`, the\n * bootstrap-gated `POST /v1/auth/confirmed_users`, the two MCP servers, the signed file read), and\n * the two whose answer is a bearer credential or a REST passthrough `database.from()` already\n * spells (`GET /v1/computers/:id/browser/live-view`, `HEAD`/`PUT /v1/apps/:id/db/rest/*`). The\n * model proxy was one until `proxy.messages` (ADR-0278): the endpoint exists so a *foreign* client\n * works unchanged, which is why there is still no streaming method. `development/INTERFACE-COVERAGE.md`\n * is that accounting, regenerated by `scripts/interface-parity`; it is checked there, not asserted here.\n */\nimport { auditLogs, auth, credits, keys, orgs } from \"./account\";\nimport { apps } from \"./apps\";\nimport { ads } from \"./ads\";\nimport { deployments, webhooks } from \"./automation\";\nimport { board } from \"./board\";\nimport { characters } from \"./characters\";\nimport { browser } from \"./browser\";\nimport { browserSessions } from \"./browser-sessions\";\nimport { domains, emails, phones } from \"./comms\";\nimport { connections } from \"./connections\";\n// core-gaps: U8-database\nimport { database } from \"./database\";\nimport { digest } from \"./digest\";\nimport { agents, harnesses, models, sessions } from \"./control-plane\";\n// core-gaps: U4-media-api — the catalogue plus generation (`media.ts` spreads `control-plane`'s in).\nimport { media } from \"./media\";\nimport { identities } from \"./identities\";\nimport { mobileDevices } from \"./mobile-devices\";\nimport { crm } from \"./crm\";\nimport { outcomes } from \"./outcomes\";\nimport type { ClientConfig } from \"./http\";\nimport { proxy } from \"./proxy\";\nimport { social } from \"./social\";\nimport { data } from \"./data\";\nimport { socialData } from \"./social-data\";\n// core-gaps: U9-storage\nimport { storage } from \"./storage\";\nimport { computers, files, skills } from \"./resources\";\nimport { trading } from \"./trading\";\nimport { vaults } from \"./vaults\";\nimport { mcpSessions } from \"./mcp-sessions\";\nimport { miniApps } from \"./mini-apps\";\nimport { streamEvents, type StreamOptions } from \"./stream\";\nimport type { Event } from \"@vetta/core\";\n\n/** The API origin. Every route already starts with `/v1`, so a baseUrl ending in `/v1` is trimmed back to it. */\nexport const DEFAULT_BASE_URL = \"https://api.vetta.sh\";\n\n/**\n * Only `apiKey` is required; `baseUrl` defaults to `https://api.vetta.sh`. Left out, `fetch` is the global one, looked up per call\n * (so a stub or polyfill installed after the client is made still applies), and `idempotencyKey` is\n * a random UUID per write. Tests and the CLI still inject both.\n */\nexport function createClient(options: Partial<ClientConfig> & Pick<ClientConfig, \"apiKey\">) {\n const config: ClientConfig = {\n ...options,\n baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\").replace(/\\/v1$/, \"\"),\n fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),\n idempotencyKey: options.idempotencyKey ?? (() => crypto.randomUUID()),\n };\n return {\n config,\n agents: agents(config),\n ads: ads(config),\n apps: apps(config),\n board: board(config),\n identities: identities(config),\n connections: connections(config),\n social: social(config),\n socialData: socialData(config),\n data: data(config),\n // core-gaps: U9-storage\n storage: storage(config),\n vaults: vaults(config),\n miniApps: miniApps(config),\n digest: digest(config),\n domains: domains(config),\n emails: emails(config),\n phones: phones(config),\n media: media(config),\n /** Trained on-screen personas a render pins (§33.6): `create`, then `get` until `ready`. */\n characters: characters(config),\n models: models(config),\n harnesses: harnesses(config),\n proxy: proxy(config),\n sessions: sessions(config),\n computers: computers(config),\n browserSessions: browserSessions(config),\n mobileDevices: mobileDevices(config),\n /** A brokerage an identity connects, and the orders placed through it (§62). */\n trading: trading(config),\n skills: skills(config),\n outcomes: outcomes(config),\n crm: crm(config),\n files: files(config),\n deployments: deployments(config),\n webhooks: webhooks(config),\n auth: auth(config),\n orgs: orgs(config),\n keys: keys(config),\n mcpSessions: mcpSessions(config),\n credits: credits(config),\n auditLogs: auditLogs(config),\n // core-gaps: U3-browser-clients\n /** Saved logins: `browser.credentials.save`, `browser.contexts.{grant,revoke}` (§32.3). */\n browser: browser(config),\n // core-gaps: U8-database\n database: database(config),\n /** Gap-free resumable event stream; `afterSeq` is exclusive (`canonical-spec.md §8`). */\n stream: (sessionId: string, options?: StreamOptions): AsyncGenerator<Event> =>\n streamEvents(config, sessionId, options),\n };\n}\n\nexport type VettaClient = ReturnType<typeof createClient>;\n\n/** `send` is the raw-response escape hatch: the dashboard re-serves the SSE body same-origin so\n * the control-plane key never reaches the browser (`architecture.md §8`). */\nexport { ApiError, ResponseParseError, apiErrorFrom, send, type ClientConfig, type Call, type Method } from \"./http\";\nexport type { AppCreate, AppPatch } from \"./apps\";\nexport type { AdAccount, SearchCampaignCreate } from \"./ads\";\nexport type { InstallApply, InstallPreview } from \"./apps\";\n// core-gaps: U8-database\nexport { filterQuery, type DbFilter, type DbOptions, type DbPage } from \"./database\";\nexport type { AgentCreate, AgentPatch, MediaModel, SessionCreate, ListQuery, SessionFilter } from \"./control-plane\";\n/**\n * The three wire types a review surface has to *name*, not merely receive. `sessions.list` and\n * `sessions.confirmTool` already hand back parsed sessions, but a component that renders one takes\n * it as a prop — and a caller outside this repo cannot reach `@vetta/core` to spell the prop's\n * type. `PendingAction` is the object being approved: `{ tool_call_id, name, args }`.\n */\nexport type { Handoffs, PendingAction, Session, StopReason } from \"@vetta/core\";\nexport type { IdentityCreate, IdentityPatch } from \"./identities\";\nexport type { Post } from \"@vetta/core\";\n/** `computers.build3d`'s answer (§59), so a caller can name it: `ok`, the published files, checks. */\nexport type { Build3dResult } from \"@vetta/core\";\nexport type {\n PostStatus,\n SocialPlatform,\n SocialPostCreate,\n SocialTextPlatform,\n SocialVisibility,\n SocialWorkspace,\n} from \"./social\";\nexport { SOCIAL_PLATFORMS, SOCIAL_TEXT_PLATFORMS, SOCIAL_VISIBILITIES } from \"./social\";\nexport type {\n SocialDataRun,\n SocialDataRunRequest,\n SocialDataTool,\n SocialDataToolDetail,\n SocialDataToolSearch,\n} from \"./social-data\";\nexport type { DataDomain, DataRun, DataRunRequest, DataTool, DataToolDetail, DataToolSearch } from \"./data\";\nexport type { CredentialCreate, VaultCreate } from \"./vaults\";\nexport type { CardCreate, CardPatch } from \"./board\";\nexport type { DomainCreate, DomainPurchase, EmailSend, InboxCreate, PhoneProvision, PhoneTier } from \"./comms\";\nexport type { Build3dRequestInput, ComputerCreate, FileFilter, FsOp, SkillContent } from \"./resources\";\n// core-gaps: U7-files-library\nexport type { FileImport, FileUpdate } from \"./resources\";\n// core-gaps: U3-browser-clients\nexport type {\n BrowserActionRequest,\n BrowserCredential,\n BrowserLogin,\n BrowserOptionsInput,\n BrowserSignup,\n CreateBrowserGrant,\n SaveBrowserContext,\n} from \"./browser\";\nexport type { MobileDeviceCreate, MobileInstallAppOutput } from \"./mobile-devices\";\nexport type { OutcomeCreate } from \"./outcomes\";\nexport type { CrmActivityCreate, CrmActivityUpdate, CrmContactCreate, CrmContactUpdate } from \"./crm\";\nexport type { Outcome, OutcomeEvaluation } from \"@vetta/core\";\nexport type { MobileAction, MobileActionResult, MobileDevice, MobileLiveView } from \"@vetta/core\";\nexport type { TradingEnvQuery, TradingOrdersQuery, TradingQuotesQuery } from \"./trading\";\nexport type {\n CloseTradingPosition,\n PlaceTradingOrder,\n TradingAccount,\n TradingConnect,\n TradingConnection,\n TradingEnv,\n TradingOrder,\n TradingPosition,\n TradingQuote,\n} from \"@vetta/core\";\nexport type { DeploymentCreate, DeploymentPatch, WebhookPatch } from \"./automation\";\nexport type { AuditFilter, AuthSession, Identity, LedgerFilter, Plan } from \"./account\";\n// core-gaps: U10-stock-photos\nexport type { StockPhoto, StockPhotoQuery } from \"./control-plane\";\nexport type { ModelSelection, ModelSelectionRequest } from \"./control-plane\";\nexport type { ModelSelectionPolicy } from \"@vetta/core\";\nexport { CONNECTION_AUTHS } from \"./connections\";\nexport type {\n AuthConfig,\n AuthConfigCreate,\n Connection,\n ConnectionApp,\n ConnectionAppDetail,\n ConnectionAuth,\n ConnectionField,\n ConnectionStatus,\n Connector,\n} from \"./connections\";\nexport type { StreamOptions } from \"./stream\";\n// core-gaps: U9-storage\nexport { resolveApp } from \"./storage\";\nexport type { AppOption, ObjectListQuery, UploadOptions, UploadUrlOptions } from \"./storage\";\n// core-gaps: U5-clips-api\nexport type { ClipCreate, ClipFilter } from \"./clips\";\nexport type { MediaSkillBuild, MediaSkillCreate, MediaSkillFilter } from \"./media-skills\";\nexport type { ProxyBlock, ProxyMessage, ProxyMessageCreate } from \"./proxy\";\nexport type { McpSession, McpSessionCreate } from \"./mcp-sessions\";\n/** Not a route: a toolset is a field on the agent, and this is how a caller writes one safely. */\nexport { withTool } from \"./tools\";\nexport type { MediaToolConfig, ToolSettings, WebToolConfig } from \"./tools\";\n// core-gaps: U6-audio\nexport type { SpeechCreate, SpeechToSpeechCreate, TranscriptionCreate } from \"./audio\";\n// core-gaps: U4-media-api\nexport type { EditJob, EditRequest, ImageGeneration, ImageRequest, MediaFilter, MediaJob, MeshRequest, VideoRequest } from \"./media\";\nexport type { Character, CharacterCreate, CharacterFilter } from \"./characters\";\n"],"mappings":";AAuHA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,KAAK,aAAa,KAAK;AAkC/D,SAAS,KAAK,QAAkB,OAAwB;AAC7D,QAAMA,QAAO,GAAG,MAAM;AACtB,MAAI,CAAC,MAAM,WAAWA,KAAI,EAAG,QAAO;AACpC,SAAO,eAAe,KAAK,M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,MAAM;AAAA,IACnB,UAAU,SAAS,MAAM;AAAA,IACzB,WAAW,UAAU,MAAM;AAAA,IAC3B,iBAAiB,gBAAgB,MAAM;AAAA,IACvC,eAAe,cAAc,MAAM;AAAA;AAAA,IAEnC,SAAS,QAAQ,MAAM;AAAA,IACvB,QAAQ,OAAO,MAAM;AAAA,IACrB,UAAU,SAAS,MAAM;AAAA,IACzB,KAAK,IAAI,MAAM;AAAA,IACf,OAAO,MAAM,MAAM;AAAA,IACnB,aAAa,YAAY,MAAM;AAAA,IAC/B,UAAU,SAAS,MAAM;AAAA,IACzB,MAAM,KAAK,MAAM;AAAA,IACjB,MAAM,KAAK,MAAM;AAAA,IACjB,MAAM,KAAK,MAAM;AAAA,IACjB,aAAa,YAAY,MAAM;AAAA,IAC/B,SAAS,QAAQ,MAAM;AAAA,IACvB,WAAW,UAAU,MAAM;AAAA;AAAA;AAAA,IAG3B,SAAS,QAAQ,MAAM;AAAA;AAAA,IAEvB,UAAU,SAAS,MAAM;AAAA;AAAA,IAEzB,QAAQ,CAAC,WAAmBC,aAC1B,aAAa,QAAQ,WAAWA,QAAO;AAAA,EAC3C;AACF;","names":["head","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","spec","z","z","z","z","z","z","z","z","z","z","url","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","Day","z","z","Count","text","sources","spec","keys","element","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","Score","Seconds","request","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","encoder","z","z","envelope","data","text","z","IdentitySchema","PlanSchema","query","z","z","query","files","z","query","z","query","query","z","z","url","text","query","z","z","query","z","z","query","z","query","z","list","page","z","query","media","query","z","query","media","query","media","z","query","query","query","z","query","query","z","z","query","query","z","z","query","z","z","query","z","z","query","z","ToolList","z","query","z","list","z","app","data","query","keys","z","data","z","query","text","z","list","z","query","query","z","z","query","z","z","page","media","options"]}
|