@byok-sdk/protocol 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/capability-constants.ts","../src/version.ts","../src/task-state.ts","../src/failure-reason.ts","../src/constants.ts","../src/sealed-split-table.ts","../src/wire-additions.ts","../src/blob.ts","../src/agent-egress.ts","../src/sealed-payload.ts","../src/provider-profile-binding.ts","../src/provider-provisioning.ts","../src/plain-json.ts","../src/result-schema.ts","../src/terminal-projection.ts","../src/input-preparation.ts","../src/agent-event.ts","../src/agent-home-projection.ts","../src/e2ee-member.ts","../src/open-vocabulary.ts","../src/messages.ts","../src/agent-memory-intent.ts","../src/agent-memory-projection.ts","../src/envelope.ts","../src/errors.ts","../src/codec.ts","../src/http-api.ts","../src/bot-turn-outcome.ts"],"names":["text","z","encoder","size","LONE_SURROGATE","completionIdentity","AppliedCompletionSchema","RejectedCompletionSchema"],"mappings":";;;AAWO,IAAM,8BAAA,CAAiC,EAIvC,IAAM,8BAAA,CAAiC,sBAEvC,IAAM,oCAAA,CAAuC,4BAG7C,IAAM,qCAAA,CAAwC,6BAG9C,IAAM,+BAAA,CAAkC,uBAExC,IAAM,uCAAA,CAA0C,+BAEhD,IAAM,wCAAA,CAA2C,gCAEjD,IAAM,sCAAA,CAAyC,8BAG/C,IAAM,gCAAA,CAAmC,wBAGzC,IAAM,wCAAA,CAA2C,gCAGjD,IAAM,gCAAA,CAAmC,wBAGzC,IAAM,mCAAA,CAAsC,2BAG5C,IAAM,gCAAA,CAAmC,2BAGzC,IAAM,8BAAA,CAAiC,yBAGvC,IAAM,kCAAA,CAAqC,0BAG3C,IAAM,iCAAA,CAAoC,6BAGpC,wCAAA,CAA2C,oCAG3C,8CAAA,CAAiD,0CAGjD,kCAAA,CACX,CAAA,yBAAA,EAA4B,8BAA8B,CAAA,EAQrD,IAAM,0BAA4B,oBAQlC,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CAA0C,EAAC,CAC7B,CACd,MAAM,MAAA,CAAuB,CAC3B,KAAM,QAAA,CAAU,oBAAA,CAAsB,KAAA,CACtC,WAAA,CAAa,CAAA,EAAG,yBAAyB,CAAA,qFAAA,CAAA,CACzC,GAAI,SAAS,MAAA,CAAS,CAAE,QAAA,CAAU,CAAC,GAAG,QAAQ,CAAE,CAAA,CAAI,EAAC,CACrD,UAAA,CAAY,SACd,CAAA,CACA,MAAM,QAAA,CAAW,iBAAA,CAAkB,MAAM,CAAA,CACzC,GAAI,CAAC,QAAA,CAAS,EAAA,EAAM,QAAA,CAAS,MAAA,GAAW,UAAA,CAAY,CAClD,MAAM,IAAI,yBAAA,CAA0B,oBAAA,CAAsB,CAAA,UAAA,EAAa,QAAA,CAAS,KAAK,CAAA,YAAA,EAAe,uBAAuB,CAAA,CAAE,CAC/H,CACA,GAAI,CAAC,QAAA,CAAS,EAAA,CAAI,MAAM,IAAI,yBAAA,CAA0B,YAAA,CAAc,IAAA,CAAK,SAAA,CAAU,QAAA,CAAS,MAAM,CAAC,CAAA,CACnG,MAAM,KAAA,CAAQ,qBAAA,CAAsB,QAAA,CAAS,SAAS,CAAA,CACtD,GAAI,QAAU,IAAA,EAAQ,KAAA,CAAQ,wBAAA,CAA0B,CACtD,MAAM,IAAI,yBAAA,CAA0B,aAAA,CAAe,sBAAsB,KAAA,EAAS,WAAW,CAAA,YAAA,EAAe,wBAAwB,CAAA,CAAE,CACxI,CACA,OAAO,SAAS,SAClB","file":"index.js","sourcesContent":["/**\n * The ONE version of the input-preparation contract, shared by this relay wire\n * (the `agent.input.preparation` payload and the completion receipt summary)\n * and by the device-local request, receipt and artifact\n * (`@byok-sdk/client`'s `INPUT_PREPARATION_VERSION`, which is this value).\n *\n * The relay wire carries no version field of its own, so a version change is\n * made visible where admission actually happens: in the capability token\n * below. See `INPUT_PREPARATION_VERSION` in the client for what each version\n * changed.\n */\nexport const INPUT_PREPARATION_WIRE_VERSION = 9 as const;\n\n\n/** Additive daemon capability names. Server/cloud admission consumes these exactly. */\nexport const AGENT_EGRESS_POLICY_CAPABILITY = 'agent-egress-policy' as const;\n\nexport const AGENT_EGRESS_RELIABLE_ACK_CAPABILITY = 'agent-egress-reliable-ack' as const;\n\n/** Admits the distinct offer whose runtime mints its session only after start. */\nexport const AGENT_EGRESS_FRESH_SESSION_CAPABILITY = 'agent-egress-fresh-session' as const;\n\n/** Admits the distinct Agent-authored message lane; activity policy remains independent. */\nexport const AGENT_MESSAGE_EGRESS_CAPABILITY = 'agent-message-egress' as const;\n\nexport const AGENT_CONTENT_WORKSPACE_READ_CAPABILITY = 'agent-content-workspace-read' as const;\n\nexport const AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY = 'agent-content-transcript-read' as const;\n\nexport const AGENT_CONTENT_ARTIFACT_READ_CAPABILITY = 'agent-content-artifact-read' as const;\n\n/** Capability required before a task-free Agent-home projection is admitted. */\nexport const AGENT_HOME_PROJECTION_CAPABILITY = 'agent-home-projection' as const;\n\n/** Capability required before an offer may select terminal projection behavior. */\nexport const TERMINAL_PROJECTION_SELECTION_CAPABILITY = 'terminal-projection-selection' as const;\n\n/** Contract §8.1's capability gate for `byok-task-assertion-v1` tool authority. */\nexport const HOST_MCP_TASK_CONTEXT_CAPABILITY = 'host-mcp-task-context' as const;\n\n/** Daemon capability required before an exact local provider profile may be offered. */\nexport const PROVIDER_PROFILE_BINDING_CAPABILITY = 'provider-profile-binding' as const;\n\n/** Device capability required before a Host may enqueue `provider.provisioning.available`. */\nexport const PROVIDER_PROVISIONING_CAPABILITY = 'provider-provisioning.v1' as const;\n\n/** Device capability required before a Host may enqueue `agent.memory.intent.available`. */\nexport const AGENT_MEMORY_INTENT_CAPABILITY = 'agent-memory-intent.v1' as const;\n\n/** Capability required before the optional hosted Agent-memory projection can be used. */\nexport const AGENT_MEMORY_PROJECTION_CAPABILITY = 'agent.memory.projection' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory`. */\nexport const AGENT_MEMORY_SELECTION_CAPABILITY = 'agent-memory-selection' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory: 'read-if-admitted'`. */\nexport const AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY = 'agent-memory-read-if-admitted' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory: 'read-write-if-admitted'`. */\nexport const AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY = 'agent-memory-read-write-if-admitted' as const;\n\n/** Exact capability of the single input-preparation wire authority. */\nexport const AGENT_INPUT_PREPARATION_CAPABILITY =\n `agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}` as const;\n\n/**\n * Sealed payload v1 (#654). A device advertises it before a Host may send it\n * a sealed offer or steer; a server advertises it before a device may send it\n * sealed task output or a sealed decline code. Both gates read\n * `WIRE_ADDITIONS`.\n */\nexport const SEALED_PAYLOAD_CAPABILITY = 'sealed-payload-v1' as const;\n\n/**\n * Sealed payload v2 (#1045): the `agent-message` and `memory-projection`\n * categories. A device advertises it before a Host may send it an offer whose\n * `sealing` names either category, or a sealed message disposition; a server\n * advertises it before a device may send it a sealed `agent.message.publish`.\n */\nexport const SEALED_PAYLOAD_V2_CAPABILITY = 'sealed-payload-v2' as const;\n\n/**\n * A server advertises it before a device may send a sealed task output that\n * names its ciphertext blob (`sealed.ciphertextRef`) instead of carrying it\n * inline. The server then holds the blob for the life of the task.\n */\nexport const SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY = 'sealed-output-ciphertext-ref' as const;\n\n/**\n * A server advertises it before a device may send `task.fail.failure`, the\n * machine-readable runtime failure class (#869).\n */\nexport const RUNTIME_FAILURE_CLASS_CAPABILITY = 'runtime-failure-class' as const;\n\n/** A server advertises it before a device may send `task.fail.failure.scope` (#1271). */\nexport const RUNTIME_QUOTA_SCOPE_CAPABILITY = 'runtime-quota-scope' as const;\n\n/**\n * The connection understands the typed pre-claim runtime-unavailable cause\n * (#1103 D8): `task.decline.runtimeUnavailable`, `conn.hello.runtimeUnavailable`\n * and the presence projection. A daemon declares it when it emits the cause.\n * Older peers ignore the unknown flag; absence means the peer may not read\n * the cause, so a Host falls back to `retryable` and treats the cause as\n * unknown. It never infers availability or allow from absence.\n */\nexport const RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY = 'runtime-unavailable-cause' as const;\n/**\n * The closed classes of `task.fail.failure.class`: the vendored OAR\n * `FailureClass` values. `unknown` means the runtime gave no structured\n * evidence. Single value authority shared by schema validation and\n * schema-free consumers.\n */\nexport const RUNTIME_FAILURE_CLASSES = [\n 'auth', 'quota', 'rate_limited', 'billing', 'model_unavailable', 'input_too_large', 'invalid_request',\n 'overloaded', 'provider', 'runtime_exited', 'limit_reached', 'output_schema', 'unknown',\n] as const;\n\n/** The values of a `quota` failure's `scope` (#1271), shared by schema and schema-free consumers. */\nexport const RUNTIME_QUOTA_SCOPES = ['account', 'model'] as const;\n\n/** Single value authority shared by schema validation and schema-free consumers. */\nexport const PREPARED_AGENT_MEMORY_MODES = ['none', 'read', 'read-write'] as const;\n\nexport function isPreparedAgentMemoryMode(value: unknown): value is (typeof PREPARED_AGENT_MEMORY_MODES)[number] {\n return typeof value === 'string' && PREPARED_AGENT_MEMORY_MODES.some(mode => mode === value);\n}\n","/** Bounded volatile navigation; only cursor is a durable acknowledgement. */\nexport const MAILBOX_READ_AHEAD_MAX_SEQS = 4096;\nexport const MAILBOX_READ_AHEAD_CAPABILITY = 'mailbox-read-ahead';\n\n/**\n * Wire protocol version. Every v4 change is a version bump, a gated addition\n * or a strip-safe addition: see docs/protocol.md \"Freeze rule\", which is the\n * one statement of the rule, and `src/wire-additions.ts`, which declares the\n * receiver-capability gates and additions. No v4 release has been published\n * yet, so `src/__tests__/compat.test.ts` has no published v4 decoder to prove\n * additions against; cross-release gates stay unproven until one exists.\n *\n * v4 completes the ADR-034 cutover and retires the approval paths kept for\n * pre-M5 peers. It removes the v3 handshake answer, the runtime-only offers\n * (with and without toolsets) with their sealed twins, and the\n * `strict-agent-only` flag: every offer is Agent-bound. `approvalId` is\n * required on `task.await_approval`, `task.approve` and `task.reject`, so a\n * decision resolves only the approval it names. `task.approval_resolved` is\n * baseline: the daemon reports every locally resolved approval, and the\n * server no longer infers one from later task activity. The three approval\n * capability flags of v3 are gone. A v3 envelope is rejected; there is no v3 reader. Drain, then\n * upgrade server and client together.\n *\n * v3 made `schema` required on the `terminalProjection.mode:\n * 'result-document'` arm (`terminal-projection.ts`, `result-schema.ts`): the\n * offer freezes the outcome schema, and the outcome reaches the Host only as\n * `task.complete.document`. That narrows a strict shape, so it is a wire\n * major. A v2 envelope is rejected; there is no v2 reader and no capability\n * negotiation between the two result-document shapes. Drain, then upgrade\n * server and client together. Every addition v2 declared is part of the v3\n * baseline, and the v2 `result-document` capability flag is gone: every v3\n * server keeps `task.complete.document`.\n *\n * v2 removed the task offer's `policy` (`PermissionPolicy`), the runtime\n * capability `permissionModes` and the input-preparation `permissionMode`.\n * Sessions run without an SDK permission gate; each local agent keeps its\n * own guardrails. A v1 envelope is rejected; there is no v1 reader.\n * v2 also removed the egress policy's `metadata-status` activity mode, its\n * `activity.mode` field and the `sanitizer_rejected` drop reason. Agent\n * egress goes to the Host as the runtime produced it.\n * v2 also removed the input-preparation artifact's `toolImplementationKinds`\n * and the readiness reason `executor_identity_unproven`. The SDK does not\n * attest tool executables. The artifact names its counted tools in\n * `toolNames`.\n */\nexport const PROTOCOL_VERSION = 4;\n\n/**\n * The device runs `homeAccess: 'memory-reader'` Agent offers: each reader\n * Attempt gets its own run directory under the Agent home, and readers are\n * counted apart from the one writer. The Agent offers are strict, so a host\n * must refuse a reader offer to a device without this flag before it creates\n * the task.\n */\nexport const AGENT_HOME_READERS_CAPABILITY = 'agent-home-readers' as const;\n\n/**\n * Capability flags. The daemon sends its flags in `conn.hello`; the server\n * sends its own on every long-poll response (`EventsPollResponse`). Additional\n * flags may be introduced without a protocol version bump; unrecognized flags\n * must be ignored by both sides.\n *\n * `dispatch-selection` (additive-minor) is a correctness gate for the\n * optional offer `dispatchSelection` control field. An older v1 daemon\n * legally strips unknown optional fields, so a server must never send an\n * authoritative provider/model selection unless the target connection\n * advertises this flag. Absence means reject before task creation, not send\n * an offer that could reach a different provider.\n *\n * `toolset-selection` (additive-minor) means the daemon understands an\n * offer's `requiredToolsets` and can resolve its logical ids against local\n * MCP configuration.\n */\nexport const CUSTOM_HARNESS_CAPABILITY = 'custom-harness' as const;\n\nexport const CAPABILITY_FLAGS = [\n 'steer',\n 'blob-upload',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\n AGENT_HOME_READERS_CAPABILITY,\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_HOME_PROJECTION_CAPABILITY,\n AGENT_INPUT_PREPARATION_CAPABILITY,\n TERMINAL_PROJECTION_SELECTION_CAPABILITY,\n HOST_MCP_TASK_CONTEXT_CAPABILITY,\n CUSTOM_HARNESS_CAPABILITY,\n MAILBOX_READ_AHEAD_CAPABILITY,\n PROVIDER_PROVISIONING_CAPABILITY,\n AGENT_MEMORY_INTENT_CAPABILITY,\n AGENT_MEMORY_SELECTION_CAPABILITY,\n AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,\n AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,\n 'agent-message-draft',\n SEALED_PAYLOAD_CAPABILITY,\n SEALED_PAYLOAD_V2_CAPABILITY,\n SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,\n RUNTIME_FAILURE_CLASS_CAPABILITY,\n RUNTIME_QUOTA_SCOPE_CAPABILITY,\n RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY,\n] as const;\n\nexport type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number];\nimport {\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_HOME_PROJECTION_CAPABILITY,\n TERMINAL_PROJECTION_SELECTION_CAPABILITY,\n HOST_MCP_TASK_CONTEXT_CAPABILITY,\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n PROVIDER_PROVISIONING_CAPABILITY,\n AGENT_MEMORY_INTENT_CAPABILITY,\n AGENT_MEMORY_SELECTION_CAPABILITY,\n AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,\n AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,\n AGENT_INPUT_PREPARATION_CAPABILITY,\n SEALED_PAYLOAD_CAPABILITY,\n SEALED_PAYLOAD_V2_CAPABILITY,\n SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,\n RUNTIME_FAILURE_CLASS_CAPABILITY,\n RUNTIME_QUOTA_SCOPE_CAPABILITY,\n RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY,\n} from './capability-constants';\n","export const TASK_STATES = [\n 'Offered',\n 'Claimed',\n 'Running',\n 'AwaitApproval',\n 'Complete',\n 'Failed',\n 'Cancelled',\n] as const;\n\nexport type TaskState = (typeof TASK_STATES)[number];\n\n/**\n * Legal state transitions for a task. `Complete` / `Failed` / `Cancelled` are\n * terminal (no outgoing edges). `Running` and `AwaitApproval` form a loop:\n * the daemon can request approval mid-run and resume once the server\n * approves (or fail/cancel out of the approval wait).\n *\n * `Offered -> Failed` (M1 gap #5, \"Declined vs. Failed\"): a daemon that\n * declines an offer pre-claim (`task.decline`) reports it through the\n * existing `Failed` state rather than a new `Declined` state. A decline and\n * a post-claim failure are the same outcome from the dispatcher's point of\n * view — this attempt produced no result, `reason`/`retryable` say why and\n * whether retrying elsewhere makes sense — so reusing `Failed` keeps the\n * state machine minimal instead of forking every terminal-state consumer\n * into \"Failed or Declined, handle both\". See docs/protocol.md for the full\n * writeup.\n */\nexport const TASK_TRANSITIONS: Readonly<Record<TaskState, readonly TaskState[]>> = {\n Offered: ['Claimed', 'Cancelled', 'Failed'],\n Claimed: ['Running', 'Failed', 'Cancelled'],\n Running: ['AwaitApproval', 'Complete', 'Failed', 'Cancelled'],\n AwaitApproval: ['Running', 'Failed', 'Cancelled'],\n Complete: [],\n Failed: [],\n Cancelled: [],\n};\n\n/** Whether `from -> to` is a legal transition per {@link TASK_TRANSITIONS}. */\nexport function canTransition(from: TaskState, to: TaskState): boolean {\n return TASK_TRANSITIONS[from].includes(to);\n}\n","/**\n * The single authority for the display text of a `task.fail` `reason` (#1124).\n *\n * A runtime's stderr tail can carry credentials a runtime or proxy printed\n * while failing. The `task.fail` schema applies this to `reason` on every\n * parse, so `createEnvelope` bounds what a daemon sends (sealed or not) and\n * every decode bounds what a receiver holds. The raw tail stays local, on the\n * adapter's `RuntimeExecutionFailure`. The result is a fixed point: applying\n * it to its own output changes nothing, so a bounded envelope round-trips\n * byte-for-byte.\n *\n * Every pattern starts at a literal and its runs never backtrack into a\n * failure, so the cost stays linear in the input length.\n */\n\n/** Maximum UTF-8 bytes of a `task.fail` `reason` after normalization, truncation marker included. */\nexport const TASK_FAIL_REASON_MAX_BYTES = 2048;\n\nconst REDACTED = '[redacted]';\n\n// A secret value: a quoted string (an unclosed quote runs to the end of the\n// line), or an unquoted run. A backslash and its following character belong\n// to the value together, so an escaped quote cannot expose a secret suffix.\n// A dangling backslash in an unclosed value is consumed too. Every alternative\n// succeeds greedily without backtracking. An unquoted value never starts with `[` or `…`, so a\n// redaction or truncation marker is never mistaken for a value on a second pass.\nconst VALUE = String.raw`(?:\"(?:\\\\[^\\n]|[^\"\\\\\\n])*(?:\\\\)?\"?|'(?:\\\\[^\\n]|[^'\\\\\\n])*(?:\\\\)?'?|[^\\s\"'\\[\\u2026,;&|][^\\s\"',;&|]*)`;\n\n// Bounded runs keep a failed match from rescanning a long run at every literal.\nconst GAP = '[ \\\\t]{0,16}';\n\nconst RULES: ReadonlyArray<readonly [RegExp, string]> = [\n // `Authorization: Bearer …`, `proxy-authorization=Basic …`, JSON `\"authorization\": \"…\"`.\n [new RegExp(String.raw`\\b((?:proxy-)?authorization)([\"']?${GAP}[:=]${GAP})(?:(?:bearer|basic|token|digest)[ \\t]{1,16})?${VALUE}`, 'gi'), `$1$2${REDACTED}`],\n [/\\b(bearer)[ \\t]{1,16}[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${REDACTED}`],\n // `ANTHROPIC_API_KEY=…`, `x-api-key: …`, `GITHUB_TOKEN=…`, `client_secret: …`, `DB_PASSWORD_FILE=…`.\n [new RegExp(String.raw`(key|token|secret|passw(?:or)?d[\\w.-]{0,64})([\"']?${GAP}[:=]${GAP})${VALUE}`, 'gi'), `$1$2${REDACTED}`],\n // URL userinfo: `postgres://user:pass@host`, `https://token@host`.\n [/:\\/\\/[^\\s/?#@]{1,256}@/g, `://${REDACTED}@`],\n // Provider key shapes.\n [/\\bsk-[A-Za-z0-9_-]{16,}/g, REDACTED],\n [/\\bxai-[A-Za-z0-9_-]{16,}/g, REDACTED],\n [/\\bAIza[0-9A-Za-z_-]{30,}/g, REDACTED],\n [/\\bgh[pousr]_[A-Za-z0-9]{20,}/g, REDACTED],\n [/\\bgithub_pat_[A-Za-z0-9_]{20,}/g, REDACTED],\n [/\\bAKIA[0-9A-Z]{16}/g, REDACTED],\n // JWT-like tokens.\n [/\\beyJ[A-Za-z0-9_-]{10,}(?:\\.[A-Za-z0-9_-]*){0,2}/g, REDACTED],\n];\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\nfunction redact(text: string): string {\n let out = text;\n for (const [pattern, replacement] of RULES) out = out.replace(pattern, replacement);\n return out;\n}\n\n/**\n * Redact credentials from a failure reason, then cap it at\n * {@link TASK_FAIL_REASON_MAX_BYTES} UTF-8 bytes on a code-point boundary\n * with a `…[truncated N bytes]` marker, where N counts the dropped redacted\n * bytes.\n */\nexport function boundFailureReason(reason: string): string {\n const redacted = redact(reason);\n const bytes = encoder.encode(redacted);\n if (bytes.length <= TASK_FAIL_REASON_MAX_BYTES) return redacted;\n // Reserve the widest marker this input can need; the final one is no wider.\n let keep = TASK_FAIL_REASON_MAX_BYTES - encoder.encode(`\\u2026[truncated ${bytes.length} bytes]`).length;\n while (keep > 0 && ((bytes[keep] ?? 0) & 0xc0) === 0x80) keep -= 1;\n return `${decoder.decode(bytes.subarray(0, keep))}\\u2026[truncated ${bytes.length - keep} bytes]`;\n}\n","/** Schema-free protocol values. Import this entry when runtime schemas are unnecessary. */\nexport * from './version';\nexport * from './task-state';\nexport * from './capability-constants';\nexport * from './failure-reason';\n\n/** Maximum raw UTF-8 content bytes in one local Host Agent-memory export; no truncation. */\nexport const AGENT_MEMORY_MAX_SNAPSHOT_BYTES = 1024 * 1024;\n/** Maximum memory files in one local Host export, including MEMORY.md. */\nexport const AGENT_MEMORY_MAX_SNAPSHOT_FILES = 128;\n\n/** The frozen wire runtime ids. Any other adapter id is a custom harness (`harnessId`). */\nexport const RUNTIME_IDS = Object.freeze(['pi', 'claude', 'codex'] as const);\n\n/**\n * Why a runtime is unavailable before claim (#1103 D6). Append-only: a cause is\n * never renamed, removed or given a new meaning. The wire reads an unknown\n * well-formed token as `unknown` and keeps it verbatim (#1121), so a newer\n * device can add one without a protocol bump. Names are snake_case, unlike the\n * kebab-case detection kinds, because the mapping is explicit and never a\n * string transformation.\n */\nexport const RUNTIME_UNAVAILABLE_CAUSES = Object.freeze([\n /** Detection: `not-found`. */\n 'not_installed',\n /** Detection: `not-executable`. */\n 'not_executable',\n /** Detection: `timeout`. */\n 'probe_timeout',\n /** Detection: `probe-failed`. */\n 'probe_failed',\n /** Detection: `refused` / `app_server_unavailable`. */\n 'app_server_unavailable',\n /** Detection: `refused` / `acp_unavailable`. */\n 'acp_unavailable',\n /** Detection: `refused` / `platform_unsupported`. */\n 'platform_unsupported',\n /** The login-shell environment capture failed (#1095). */\n 'environment_unavailable',\n /** A Host-configured version policy blocked the installed token (#1103). */\n 'version_blocked',\n /** The offer named an id this daemon has no adapter for. */\n 'runtime_not_configured',\n /** The device runtime allowlist excludes the requested id. */\n 'runtime_not_allowed',\n /** Automatic selection exhausted every candidate. */\n 'none_available',\n] as const);\n\n/** One append-only `runtime_unavailable` cause. */\nexport type RuntimeUnavailableCause = (typeof RUNTIME_UNAVAILABLE_CAUSES)[number];\n\n/** Maximum length of a served model name. */\nexport const TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH = 160;\n","/**\n * The split table of sealed payload v1 and v2 (#654 design §8.1, §9.3;\n * #1045): for each sealable message type, the field that marks its sealed\n * branch, its data category, its identity fields, the fields that move into\n * the ciphertext, the fields its sealed branch drops, and the rule of each\n * digest field (D16).\n *\n * Plain data with no runtime imports, so `wire-additions.ts` can derive the\n * sealed gates from it and stay free of zod.\n */\nimport type { MessageType } from './messages';\nimport type { SealedPayloadCategory } from './sealed-payload';\n\n/**\n * How the sealed branch of a type treats one digest field of its plaintext\n * branch (D16, design §9.3).\n *\n * - `ciphertext-sha256`: the SHA-256 of the sealed bytes, for a Host that\n * checks the bytes it stores (a ciphertext blob).\n * - `keyed-mac`: a keyed MAC under the scope's MAC key; the Host forwards it.\n * - `sealed`: the field moves into the ciphertext with its parent.\n * - `plain`: a digest that no sealed content derives, kept in plaintext.\n * - `forbidden`: the sealed branch does not carry it in v1.\n */\nexport type SealedDigestRule = 'ciphertext-sha256' | 'keyed-mac' | 'sealed' | 'plain' | 'forbidden';\n\n/** One sealable message type in the split table. */\nexport interface SealedSplitEntry {\n /**\n * The payload field whose presence marks the sealed branch: `sealing` (the\n * task's sealing policy) on `task.offer`, whose task may seal only its\n * output and so carry no `sealed` member; `sealed` everywhere else. The AAD\n * and the content MAC bind the wire type as the family.\n */\n readonly marker: 'sealing' | 'sealed';\n readonly category: SealedPayloadCategory;\n /**\n * Payload fields that, after the envelope `task_id`, name this write in the\n * AAD and the content MAC (§8.2, §9.1). The sealed branch requires them.\n */\n readonly identity: readonly string[];\n /**\n * Top-level fields of the plaintext branch that move into the ciphertext.\n * The sealed branch does not have them; the receiver merges the opened\n * object back and validates the plaintext branch.\n */\n readonly moved: readonly string[];\n /**\n * Top-level fields that also move into this ciphertext when the task's\n * frozen `sealing` names the category (#1045): on a task that seals\n * `memory-projection`, a terminal seals its `agentHomeMemoryChange`. The\n * sealed branch schema cannot see the task's sealing, so the Host and the\n * device check these fields; read them with {@link sealedMovedFields}.\n */\n readonly movedWith?: { readonly [category in SealedPayloadCategory]?: readonly string[] };\n /** Top-level fields of the plaintext branch that the sealed branch drops. */\n readonly forbidden: readonly string[];\n /**\n * Every path of the plaintext branch whose name contains `digest`, `hash` or\n * `revision` (case-insensitive), with its rule. A schema test keeps this\n * complete.\n */\n readonly digests: { readonly [path: string]: SealedDigestRule };\n /**\n * UTF-8 byte limits of moved fields that replace the plaintext branch's limit\n * of that field after the merge (decision 12b). The category limit still\n * bounds the whole opened content.\n */\n readonly limits?: { readonly [field: string]: number };\n /**\n * The sealed form carries inline ciphertext only, never `ciphertextRef`\n * (decision 12e). The Host keeps it in a tail row that expires, so it holds\n * no blob for it. The schema does not check this; the Host and the device do.\n */\n readonly inlineOnly?: true;\n}\n\n/** A terminal of a task that seals `memory-projection` seals its memory-change evidence. */\nconst MEMORY_EVIDENCE = { 'memory-projection': ['agentHomeMemoryChange'] } as const;\n\n/** The Host wrote the projection it names, so its hash tells the Host nothing new. */\nconst TERMINAL_DIGESTS = {\n 'agentRef.profileRevision': 'plain',\n 'agentHomeProjection.profileRevision': 'plain',\n 'agentHomeProjection.projectionHash': 'plain',\n} as const satisfies SealedSplitEntry['digests'];\n\n/**\n * The split table (design §8.3): each sealable message type, the marker of its\n * sealed branch, its category, identity, moved and forbidden fields, and the\n * rule of each digest field. It is the one authority; the schemas, the gates,\n * the Host's comparison projection and the receiver's merge read it.\n *\n * A sealed offer carries the task's `sealing`. When the categories include\n * `task-input`, `instruction` is sealed; otherwise it stays plaintext and only\n * the task output is sealed. A prepared Execution is never sealed.\n *\n * Blob bytes have no sealing rule yet, so a sealed branch carries no plaintext\n * blob reference: `artifactRefs` and the artifact `blobRef` are dropped until\n * that rule exists. A sealed artifact is inline content, so its `inline`\n * takes up to 2 MiB instead of the plaintext 64 KB (decision 12b).\n */\nexport const SEALED_SPLIT_TABLE = Object.freeze({\n 'task.offer': {\n marker: 'sealing',\n category: 'task-input',\n identity: [],\n moved: ['instruction'],\n forbidden: ['preparation'],\n digests: {\n 'instruction.blobRef.contentHash': 'sealed',\n 'agentRef.profileRevision': 'plain',\n 'dispatchSelection.providerProfile.profileRevision': 'plain',\n 'dispatchSelection.providerProfile.profileHash': 'plain',\n 'egressPolicy.policyRevision': 'plain',\n 'preparation.requestDigest': 'forbidden',\n 'preparation.artifactDigest': 'forbidden',\n },\n },\n 'task.steer': { marker: 'sealed', category: 'task-input', identity: ['steerId'], moved: ['text'], forbidden: [], digests: {} },\n 'task.complete': {\n marker: 'sealed',\n category: 'task-output',\n identity: [],\n moved: ['summary', 'finalMessage', 'document'],\n movedWith: MEMORY_EVIDENCE,\n forbidden: ['artifactRefs', 'preparedObservation'],\n digests: {\n ...TERMINAL_DIGESTS,\n 'artifactRefs[].contentHash': 'forbidden',\n 'preparedObservation.requestDigest': 'forbidden',\n },\n },\n 'task.fail': {\n marker: 'sealed',\n category: 'task-output',\n identity: [],\n moved: ['reason'],\n movedWith: MEMORY_EVIDENCE,\n forbidden: ['preparedObservation'],\n digests: { ...TERMINAL_DIGESTS, 'preparedObservation.requestDigest': 'forbidden' },\n },\n 'task.decline': {\n marker: 'sealed', category: 'task-output', identity: [], moved: ['reason'], forbidden: [], digests: { 'agentRef.profileRevision': 'plain' },\n },\n 'task.cancelled': {\n marker: 'sealed', category: 'task-output', identity: [], moved: ['reason'], movedWith: MEMORY_EVIDENCE, forbidden: [], digests: TERMINAL_DIGESTS,\n },\n 'task.progress': {\n marker: 'sealed', category: 'task-output', identity: ['seq'], moved: ['events'], forbidden: [], digests: { 'events[].spill.blob.contentHash': 'sealed' },\n inlineOnly: true,\n },\n 'task.artifact': {\n marker: 'sealed', category: 'task-output', identity: ['artifactId'], moved: ['inline'], forbidden: ['blobRef'], digests: { 'blobRef.contentHash': 'forbidden' },\n limits: { inline: 2 * 1024 * 1024 },\n },\n 'task.await_approval': {\n marker: 'sealed', category: 'task-output', identity: ['approvalId'], moved: ['summary'], forbidden: [], digests: {},\n inlineOnly: true,\n },\n // #1045 C2. The plaintext SHA-256 of the body would let the Host confirm a\n // guessed message, and the exact byte count would undo the padding, so the\n // sealed branch drops both; the sealed member's keyed `contentMac` names\n // the content instead. `cursor` is in the identity, so the Host cannot\n // reorder sealed messages of one session.\n 'agent.message.publish': {\n marker: 'sealed',\n category: 'agent-message',\n identity: ['messageId', 'cursor'],\n moved: ['body'],\n forbidden: ['contentHash', 'byteCount'],\n digests: { 'agentRef.profileRevision': 'plain', contentHash: 'forbidden' },\n },\n} as const satisfies { readonly [type in MessageType]?: SealedSplitEntry });\n\n/**\n * The receiver capability each category's sealed branches need: the v1\n * categories `sealed-payload-v1`, the #1045 categories `sealed-payload-v2`.\n */\nexport const SEALED_CATEGORY_CAPABILITY = Object.freeze({\n 'task-input': 'sealed-payload-v1',\n 'agent-message': 'sealed-payload-v2',\n 'task-output': 'sealed-payload-v1',\n 'memory-projection': 'sealed-payload-v2',\n} as const satisfies { readonly [category in SealedPayloadCategory]: string });\n\n/**\n * The top-level fields a `type` message of a task whose frozen `sealing`\n * lists `categories` moves into its ciphertext: the type's `moved` fields and\n * the `movedWith` fields of each listed category.\n */\nexport function sealedMovedFields(type: SealableMessageType, categories: readonly SealedPayloadCategory[]): readonly string[] {\n const entry: SealedSplitEntry = SEALED_SPLIT_TABLE[type];\n return [...entry.moved, ...categories.flatMap((category) => entry.movedWith?.[category] ?? [])];\n}\n\n/** A message type with a sealed branch. */\nexport type SealableMessageType = keyof typeof SEALED_SPLIT_TABLE;\n\nexport function isSealableMessageType(type: string): type is SealableMessageType {\n return Object.hasOwn(SEALED_SPLIT_TABLE, type);\n}\n\n/** Whether a `type` payload takes its sealed branch: it carries the type's marker field. */\nexport function isSealedPayload(type: string, payload: unknown): boolean {\n return isSealableMessageType(type) && payload !== null && typeof payload === 'object'\n && (payload as Readonly<Record<string, unknown>>)[SEALED_SPLIT_TABLE[type].marker] !== undefined;\n}\n","/**\n * The one table of receiver-capability gates and wire additions\n * (docs/protocol.md \"Freeze rule\").\n *\n * A v4 change takes exactly one of three paths: a version bump, a gated\n * addition, or a strip-safe addition. Envelope and HTTP rows have explicit\n * kinds. The last two are declared here.\n *\n * - `gated`: the sender must not emit the surface unless the receiver\n * durably advertised `capability`. A field entry applies when the payload\n * carries the field (and, with `value`, when the field equals it, or when\n * the field is an array that includes it); a dotted field names a nested\n * field, for example `sealed.ciphertextRef`. A type entry applies to every\n * message of that type. Server-to-daemon surfaces\n * are gated by a device flag, daemon-to-server surfaces by a server flag.\n * - `strip-safe`: an optional field an older receiver drops without changing\n * what it executes or acknowledges.\n *\n * v3 baseline: every v3 decoder reads every surface v2 had, so the v2\n * strip-safe rows and the v2 `result-document` gate are gone. The device\n * gates kept below name capabilities a daemon advertises only when it is\n * configured for them (Agent home, egress, input preparation, provisioning,\n * memory intents and so on): they gate on the receiver's configuration.\n *\n * v4 baseline: every v4 server reads `task.approval_resolved`, so its\n * `approval_resolved` gate is gone. One `task.offer` replaces the Agent offer\n * types and sealed is a payload branch, so a gate that a v3 type carried is a\n * field or value row here. The offer is strict, so a daemon that does not know\n * one of its fields stops instead of stripping it. The daemon also refuses an offer whose rows name a flag it did not advertise. No\n * v4 release has been published yet, so no published decoder proves these rows\n * across releases.\n *\n * Senders derive their admission flags from {@link requiredReceiverCapabilities}\n * and nowhere else, so a gate cannot exist in one place and be missing in\n * another. This module imports no runtime code except the plain-data split\n * table, so it stays free of zod.\n */\nimport type { MessageType } from './messages';\nimport { SEALED_CATEGORY_CAPABILITY, SEALED_SPLIT_TABLE, type SealableMessageType, type SealedSplitEntry } from './sealed-split-table';\nimport type { CapabilityFlag } from './version';\n\ntype HttpWireSurface =\n | 'ChallengeRequest' | 'ChallengeResponse' | 'TokenRequest' | 'TokenResponse'\n | 'PairRequest' | 'PairResponse' | 'EventsPollQuery' | 'EventsPollResponse' | 'MessagesSendRequest' | 'MessagesSendResponse'\n | 'PresencePublishRequest';\n\nexport type WireAddition =\n | {\n readonly kind: 'envelope';\n readonly rule: 'gated';\n readonly surface: MessageType;\n readonly field?: string;\n readonly value?: string;\n readonly capability: CapabilityFlag;\n readonly advertisedBy: 'device' | 'server';\n }\n | { readonly kind: 'envelope'; readonly rule: 'strip-safe'; readonly surface: MessageType; readonly field: string }\n | { readonly kind: 'http'; readonly rule: 'strip-safe'; readonly surface: HttpWireSurface; readonly field: string };\n\nconst MATRIX_FIELDS = ['toolAuthorizationAuto', 'durablePi', 'preparedLane', 'isolation'] as const;\n\nconst offerRow = (field: string | undefined, capability: CapabilityFlag, value?: string): WireAddition => ({\n kind: 'envelope', rule: 'gated', surface: 'task.offer',\n ...(field === undefined ? {} : { field }), ...(value === undefined ? {} : { value }),\n capability, advertisedBy: 'device',\n});\n\n/**\n * Sealed payload (#654, #1045), one table entry at a time: the marker of each\n * sealed branch is gated on its category's flag (`sealed-payload-v1` for task\n * input and output, `sealed-payload-v2` for Agent messages), a\n * server-to-daemon type on the device flag, a daemon-to-server type on the\n * server flag. The sealed branch shares every other row of its type, and a\n * field it moves or drops is absent from it, so sealing never removes a gate\n * that the same fields would need. A daemon-to-server sealed type that may\n * name its ciphertext blob is also gated on that field. The four sealed\n * failure codes on the plaintext `task.decline` are value gates.\n */\nfunction sealedRows(): WireAddition[] {\n return (Object.keys(SEALED_SPLIT_TABLE) as SealableMessageType[]).flatMap((surface) => {\n const entry: SealedSplitEntry = SEALED_SPLIT_TABLE[surface];\n const advertisedBy = entry.category === 'task-input' ? 'device' : 'server';\n const byReference: WireAddition[] = advertisedBy === 'server' && entry.inlineOnly !== true\n ? [{ kind: 'envelope', rule: 'gated', surface, field: 'sealed.ciphertextRef', capability: 'sealed-output-ciphertext-ref', advertisedBy }]\n : [];\n const capability = SEALED_CATEGORY_CAPABILITY[entry.category];\n return [{ kind: 'envelope', rule: 'gated', surface, field: entry.marker, capability, advertisedBy }, ...byReference];\n });\n}\n\n/**\n * Sealed payload v2 (#1045) outside the split table: an offer whose frozen\n * `sealing` lists a v2 category, and the disposition of a sealed message,\n * which names it by `contentMac`. Both go to a device.\n */\nconst SEALED_V2_ROWS: readonly WireAddition[] = [\n offerRow('sealing.categories', 'sealed-payload-v2', 'agent-message'),\n offerRow('sealing.categories', 'sealed-payload-v2', 'memory-projection'),\n { kind: 'envelope', rule: 'gated', surface: 'agent.message.disposition', field: 'contentMac', capability: 'sealed-payload-v2', advertisedBy: 'device' },\n];\nconst SEALED_DECLINE_CODE = (value: string): WireAddition =>\n ({ kind: 'envelope', rule: 'gated', surface: 'task.decline', field: 'code', value, capability: 'sealed-payload-v1', advertisedBy: 'server' });\n\nconst PLAIN_ROWS: readonly WireAddition[] = [\n // Server to daemon: the offer. Every offer binds an Agent; each optional\n // field and value names the device flag a daemon advertises when it is\n // configured for it.\n offerRow(undefined, 'agent-home-contract'),\n offerRow('dispatchSelection', 'dispatch-selection'),\n offerRow('requiredToolsets', 'toolset-selection'),\n offerRow('terminalProjection', 'terminal-projection-selection'),\n offerRow('homeAccess', 'agent-home-readers'),\n offerRow('harnessId', 'custom-harness'),\n offerRow('agentMemory', 'agent-memory-selection'),\n offerRow('agentMemory', 'agent-memory-read-if-admitted', 'read-if-admitted'),\n offerRow('agentMemory', 'agent-memory-read-write-if-admitted', 'read-write-if-admitted'),\n offerRow('egressPolicy', 'agent-egress-policy'),\n offerRow('egressPolicy', 'agent-egress-reliable-ack'),\n offerRow('messageEgress', 'agent-message-egress'),\n offerRow('session.mode', 'agent-egress-fresh-session', 'fresh'),\n offerRow('preparation', 'agent-input-preparation-v9'),\n // Server to daemon: Agent control messages.\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'workspace', capability: 'agent-content-workspace-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'transcript', capability: 'agent-content-transcript-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'artifact', capability: 'agent-content-artifact-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.home.projection', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.home.projection', capability: 'agent-home-projection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.input.preparation', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.input.preparation', capability: 'agent-input-preparation-v9', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'provider.provisioning.available', capability: 'provider-provisioning.v1', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.memory.intent.available', capability: 'agent-memory-intent.v1', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'e2ee.key_package.available', capability: 'sealed-payload-v1', advertisedBy: 'device' },\n // One optional runtime capability, shared by discovery and the claim snapshot.\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimes[].capabilities.messageDraft' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'harnesses[].capabilities.messageDraft' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.claim', field: 'capabilities.messageDraft' },\n // The capability matrix (#1103): discovery data on the same runtime capability object.\n ...MATRIX_FIELDS.flatMap((field): WireAddition[] => [\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: `runtimes[].capabilities.${field}` },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: `harnesses[].capabilities.${field}` },\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.claim', field: `capabilities.${field}` },\n ]),\n // Version policy and runtime-unavailable discovery (#1103 B2b). All are\n // strip-safe: an older receiver drops them, and absence means unknown — it\n // must never be read as `allow` or `available`. Presence keeps the built-in\n // runtime identity domain; harness policy travels only on conn.hello.\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimes[].versionPolicy' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'harnesses[].versionPolicy' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimeUnavailable' },\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimes[].versionPolicy' },\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimeUnavailable' },\n // Presence carries the conn.hello capability matrix (#1103); a published cloud drops it.\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimes[].capabilities' },\n // Optional MCP event identity is observability only; older receivers may omit it.\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.progress', field: 'events[].mcp' },\n // Daemon to server.\n { kind: 'envelope', rule: 'gated', surface: 'agent.message.draft', capability: 'agent-message-draft', advertisedBy: 'server' },\n { kind: 'envelope', rule: 'gated', surface: 'task.fail', field: 'failure', capability: 'runtime-failure-class', advertisedBy: 'server' },\n { kind: 'envelope', rule: 'gated', surface: 'task.fail', field: 'failure.scope', capability: 'runtime-quota-scope', advertisedBy: 'server' },\n // Typed pre-claim runtime-unavailable cause (#1103 B2a). An older server\n // drops the nested field and still records the open `runtime_unavailable`\n // code; the cause never changes what the receiver executes.\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.decline', field: 'runtimeUnavailable' },\n // Relative token lifetime (#1114). A published device drops it and keeps\n // reading `expiresAt`, which the Host still sends.\n { kind: 'http', rule: 'strip-safe', surface: 'TokenResponse', field: 'expiresIn' },\n // Relative token lifetime (#1114), as on the token response; a published\n // device drops it.\n { kind: 'http', rule: 'strip-safe', surface: 'PairResponse', field: 'expiresIn' },\n];\n\nexport const WIRE_ADDITIONS: readonly WireAddition[] = Object.freeze([\n ...PLAIN_ROWS,\n ...sealedRows(),\n ...SEALED_V2_ROWS,\n SEALED_DECLINE_CODE('sealed_key_unavailable'),\n SEALED_DECLINE_CODE('sealed_open_failed'),\n SEALED_DECLINE_CODE('sealed_content_mac_mismatch'),\n SEALED_DECLINE_CODE('sealing_policy_mismatch'),\n] satisfies readonly WireAddition[]);\n\n/**\n * Every capability the receiver must have durably advertised before a sender\n * may emit this message. Deduplicated, in table order. A sender refuses (before\n * creating the task or appending to the mailbox) when any is missing.\n */\nexport function requiredReceiverCapabilities(type: MessageType, payload: unknown): CapabilityFlag[] {\n const fields = payload !== null && typeof payload === 'object' ? (payload as Record<string, unknown>) : {};\n const required: CapabilityFlag[] = [];\n for (const entry of WIRE_ADDITIONS) {\n if (entry.kind !== 'envelope' || entry.rule !== 'gated' || entry.surface !== type) continue;\n if (entry.field !== undefined) {\n const value = entry.field.split('.').reduce<unknown>(\n (parent, segment) => (parent !== null && typeof parent === 'object' ? (parent as Record<string, unknown>)[segment] : undefined),\n fields,\n );\n if (value === undefined) continue;\n if (entry.value !== undefined && !(Array.isArray(value) ? value.includes(entry.value) : value === entry.value)) continue;\n }\n if (!required.includes(entry.capability)) required.push(entry.capability);\n }\n return required;\n}\n","import { z } from 'zod';\n\n/**\n * Canonical `contentHash` format (finding F9): `sha256:` followed by exactly\n * 64 lowercase hex characters (a SHA-256 digest). Pinned here — the single\n * source of truth both `BlobRefSchema` and `CreateBlobRequestSchema`\n * (`http-api.ts`) validate against — rather than left as a bare `z.string()`\n * that silently accepted any prefix (or none) and left the server to\n * reconcile the mismatch with an ad hoc normalization step. No compat shim:\n * the wire is pre-freeze (`v` stays `1`), so this is a straight tightening,\n * not a migration.\n */\nexport const CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * Reference to a large payload that was pushed out-of-band (presigned PUT) or\n * is fetchable out-of-band (presigned GET), rather than inlined in an envelope.\n */\nexport const BlobRefSchema = z.object({\n blobId: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be \"sha256:<64 lowercase hex>\"'),\n size: z.number().int().nonnegative(),\n contentType: z.string(),\n url: z.string().optional(),\n});\n\nexport type BlobRef = z.infer<typeof BlobRefSchema>;\n","import { z } from 'zod';\n\n/**\n * Agent-local/cloud egress is an explicit, versioned contract. This module\n * owns the public policy and fact vocabulary; transport messages compose it\n * with Agent identity in `messages.ts` so the two directions do not create\n * competing policy shapes.\n */\n\nconst POLICY_REVISION = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'policyRevision must not contain control characters');\n\nconst POSITIVE_LIMIT = z.number().int().positive().max(2_147_483_647);\nexport const AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES = 16 * 1024;\nexport const AGENT_MESSAGE_MAX_BYTES = 256 * 1024;\nexport const AgentMessageContractSchema = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u, 'message contract must be an opaque portable identifier');\nexport const AgentMessageContentTypeSchema = z.enum(['text/plain', 'text/markdown']);\nexport const AgentMessageDestinationBindingSchema = z\n .string()\n .min(1)\n .max(2048)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'destination binding must not contain control characters');\nexport const AgentMessageFreshnessCursorSchema = z\n .string()\n .min(1)\n .max(512)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'freshness cursor must not contain control characters');\n/** Host-only product authority. It is never serialized into an Agent offer or message envelope. */\nexport const AgentMessageServerContextSchema = z\n .object({\n destinationBinding: AgentMessageDestinationBindingSchema,\n freshnessCursor: AgentMessageFreshnessCursorSchema.optional(),\n })\n .strict();\nexport const AgentMessageEgressRequirementSchema = z\n .object({\n mode: z.literal('required'),\n contract: AgentMessageContractSchema,\n contentType: AgentMessageContentTypeSchema,\n maxBytes: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\n })\n .strict();\nexport type AgentMessageEgressRequirement = z.infer<typeof AgentMessageEgressRequirementSchema>;\nexport type AgentMessageContentType = z.infer<typeof AgentMessageContentTypeSchema>;\nexport type AgentMessageServerContext = z.infer<typeof AgentMessageServerContextSchema>;\nexport const AgentContentMimeTypeSchema = z\n .string()\n .min(3)\n .max(255)\n .regex(/^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/iu, 'MIME types must be explicit type/subtype values');\n\n/** Explicit MIME and byte policy for one independently-authorized content surface. */\nexport const ContentReadPolicySchema = z\n .object({\n maxBytes: POSITIVE_LIMIT,\n allowedMimeTypes: z.array(AgentContentMimeTypeSchema).min(1).max(32),\n })\n .strict();\nexport type ContentReadPolicy = z.infer<typeof ContentReadPolicySchema>;\n\n/**\n * The latest-value activity lane. Agent events go to the Host as the runtime\n * produced them; these limits only bound transport (coalesce window and one\n * event's byte size).\n */\nexport const AgentEgressActivityPolicySchema = z\n .object({\n delivery: z.literal('latest-value'),\n maxCoalesceMs: POSITIVE_LIMIT,\n maxEventBytes: POSITIVE_LIMIT,\n })\n .strict();\nexport type AgentEgressActivityPolicy = z.infer<typeof AgentEgressActivityPolicySchema>;\n\nexport const AgentReliableQuotaPolicySchema = z\n .object({\n maxPendingEventsPerAgent: POSITIVE_LIMIT,\n maxPendingBytesPerAgent: POSITIVE_LIMIT,\n maxPendingBytesPerTenant: POSITIVE_LIMIT,\n })\n .strict();\nexport type AgentReliableQuotaPolicy = z.infer<typeof AgentReliableQuotaPolicySchema>;\n\n/**\n * The only consumable policy shape for Agent egress. It selects transport\n * limits and the Host content-read surfaces. It does not filter, redact or\n * omit Agent egress content. Callers must select a revision and all three\n * content-read surfaces independently.\n */\nexport const AgentEgressPolicySchema = z\n .object({\n policyRevision: POLICY_REVISION,\n activity: AgentEgressActivityPolicySchema,\n reliable: AgentReliableQuotaPolicySchema,\n transfers: z\n .object({\n workspace: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n transcript: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n artifact: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n })\n .strict(),\n })\n .strict();\nexport type AgentEgressPolicy = z.infer<typeof AgentEgressPolicySchema>;\n\n/** Delivery stores are semantically distinct; this enum is never a durable boolean. */\nexport const AgentEgressLaneSchema = z.enum(['reliable', 'latest-value']);\nexport type AgentEgressLane = z.infer<typeof AgentEgressLaneSchema>;\n\n/** Every refusal/replacement is observable rather than silently degrading to another lane. */\nexport const AgentEgressDropReasonSchema = z.enum([\n 'policy_denied',\n 'capability_missing',\n 'quota_exceeded',\n 'backpressure',\n 'coalesced',\n 'disconnected',\n 'invalid_envelope',\n 'ack_mismatch',\n]);\nexport type AgentEgressDropReason = z.infer<typeof AgentEgressDropReasonSchema>;\n\nexport const AgentContentReadSurfaceSchema = z.enum(['workspace', 'transcript', 'artifact']);\nexport type AgentContentReadSurface = z.infer<typeof AgentContentReadSurfaceSchema>;\n\n/** The product-selected actor is explicit; tenant/device are bound by the authenticated transport. */\nexport const AgentContentActorKindSchema = z.enum(['user', 'agent', 'system']);\nexport type AgentContentActorKind = z.infer<typeof AgentContentActorKindSchema>;\n\nexport const AgentContentActorSchema = z\n .object({\n kind: AgentContentActorKindSchema,\n id: z.string().min(1).max(512).regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'actor id must not contain control characters'),\n })\n .strict();\nexport type AgentContentActor = z.infer<typeof AgentContentActorSchema>;\n\n/** No byte/text interpretation is inferred from a target name or MIME declaration. */\nexport const AgentContentDecodeAsSchema = z.enum(['bytes', 'utf8']);\nexport type AgentContentDecodeAs = z.infer<typeof AgentContentDecodeAsSchema>;\n\nexport const AgentContentReadDecisionSchema = z.enum(['allowed', 'denied']);\nexport type AgentContentReadDecision = z.infer<typeof AgentContentReadDecisionSchema>;\n\nexport const AgentContentReadDenialReasonSchema = z.enum([\n 'invalid-request',\n 'policy-disabled',\n 'capability-missing',\n 'policy-revision-mismatch',\n 'absolute-target',\n 'non-relative-target',\n 'dot-segment',\n 'sensitive-name',\n 'root-not-allowlisted',\n 'root-invalid',\n 'path-escape',\n 'target-missing',\n 'symlink',\n 'not-regular-file',\n 'byte-limit',\n 'mime-not-allowlisted',\n 'text-not-allowlisted',\n 'text-decode-failed',\n 'identity-mismatch',\n]);\nexport type AgentContentReadDenialReason = z.infer<typeof AgentContentReadDenialReasonSchema>;\n\n/** SHA-256 transport receipt hash, never a content byte projection. */\nexport const AgentEgressContentHashSchema = z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/u, 'contentHash must be a lowercase SHA-256 digest');\n\nexport const AgentEgressPolicyRevisionSchema = POLICY_REVISION;\n","/**\n * Sealed payload on the hosted wire: v1 (#654 design §8.1, §8.3, §8.6) and\n * the v2 categories (#1045).\n *\n * Sealed is a property of the payload, not a message type: each sealable\n * type's payload is a plaintext branch or a sealed branch. The sealed branch is\n * the plaintext fields without the ones one data category moves into the\n * ciphertext, plus a sealed member; its marker field is gated on\n * `sealed-payload-v1`, and the payload is strict, so a decoder that does not\n * know the branch refuses the whole message. The Host reads only the sealed\n * member's outer fields. It checks the shape here:\n * version, suite, encodings, a legal padded length, and exactly one of inline\n * `ciphertext` and `ciphertextRef`. Inline is the only legal form up to\n * {@link SEALED_INLINE_MAX_PADDED_LENGTH}; above it, the ciphertext is a blob.\n * So one content has one legal wire form, and two submissions compare by\n * their outer fields only.\n *\n * `@byok-sdk/core/sealed-payload` seals and opens the bytes. Protocol does\n * not depend on core, so this module repeats the header rules and the padded\n * length function; a cross-package test keeps the two equal.\n */\nimport { z } from 'zod';\n\nimport { AGENT_MESSAGE_MAX_BYTES } from './agent-egress';\nimport { BlobRefSchema, CONTENT_HASH_RE } from './blob';\n\nimport { SEALED_SPLIT_TABLE, isSealableMessageType, sealedMovedFields, type SealedSplitEntry } from './sealed-split-table';\n\nexport { SEALED_SPLIT_TABLE, isSealableMessageType, isSealedPayload, sealedMovedFields } from './sealed-split-table';\nexport type { SealableMessageType, SealedDigestRule, SealedSplitEntry } from './sealed-split-table';\n\nexport const SEALED_PAYLOAD_VERSION = 1;\n/** The only suite v1 admits. A new suite is a new constant and a new capability, never a parser branch. */\nexport const SEALED_PAYLOAD_SUITE = 'byok-sealed-v1.hkdf-sha256.aes-256-gcm';\n\n/**\n * C1–C4 in canonical order. A task lists its sealing categories in this order.\n * Input preparation and drafts have no category; they stay plaintext.\n */\nexport const SEALED_PAYLOAD_CATEGORIES = ['task-input', 'agent-message', 'task-output', 'memory-projection'] as const;\nexport type SealedPayloadCategory = (typeof SEALED_PAYLOAD_CATEGORIES)[number];\n\n/**\n * Closed `task.decline` codes of a receiver that refuses sealed task input\n * (§8.3). They are plaintext: a device without the scope key cannot seal a\n * reason. A device sends them only to a server that advertised\n * `sealed-payload-v1`.\n */\nexport const SEALED_DECLINE_CODES = [\n 'sealed_key_unavailable',\n 'sealed_open_failed',\n 'sealed_content_mac_mismatch',\n 'sealing_policy_mismatch',\n] as const;\nexport type SealedDeclineCode = (typeof SEALED_DECLINE_CODES)[number];\n\n/**\n * The closed plaintext codes of a task whose output is sealed (#654 12d).\n * It lists each output type that has a plaintext form on such a task, with\n * the codes that each field moved or dropped by its sealed branch may hold.\n * Such a field that is not listed here must be absent. An output type with a\n * sealed branch that is not listed has no plaintext form. An\n * interrupted task reports `daemon_interrupted`; a device that cannot seal\n * reports `sealed_key_unavailable`. The Host check, the daemon and the member\n * display read this one list, and compare by exact match.\n */\nexport const SEALED_TASK_PLAIN_CODES = Object.freeze({\n 'task.fail': { reason: ['daemon_interrupted', 'sealed_key_unavailable'] },\n 'task.decline': { reason: SEALED_DECLINE_CODES },\n 'task.cancelled': { reason: [] },\n} as const);\n\n/**\n * True when `payload` is a legal plaintext `type` message of a task whose\n * output is sealed under `categories`: each field that the `task-output`\n * sealed branch of `type` moves (with the `movedWith` fields of `categories`)\n * or drops is absent or holds one of {@link SEALED_TASK_PLAIN_CODES}. A type\n * that has a sealed output branch and is not listed there is never legal. A\n * plaintext decline also names its code as `code`. A type with no sealed\n * output branch is always legal.\n */\nexport function isSealedTaskPlainOutput(type: string, payload: object, categories: readonly SealedPayloadCategory[]): boolean {\n const codes: { readonly [field: string]: readonly string[] } = Object.hasOwn(SEALED_TASK_PLAIN_CODES, type)\n ? SEALED_TASK_PLAIN_CODES[type as keyof typeof SEALED_TASK_PLAIN_CODES]\n : {};\n const entry: SealedSplitEntry | undefined = isSealableMessageType(type) ? SEALED_SPLIT_TABLE[type] : undefined;\n const fields: readonly string[] = entry?.category === 'task-output'\n ? [...sealedMovedFields(type as keyof typeof SEALED_SPLIT_TABLE, categories), ...entry.forbidden]\n : [];\n if (fields.length > 0 && !Object.hasOwn(SEALED_TASK_PLAIN_CODES, type)) return false;\n const record = payload as Readonly<Record<string, unknown>>;\n for (const field of fields) {\n const value = record[field];\n if (value !== undefined && !(typeof value === 'string' && (codes[field] ?? []).includes(value))) return false;\n }\n return type !== 'task.decline' || record.reason === undefined || record.code === record.reason;\n}\n\n/** Padded frames above this length travel as a ciphertext blob (§8.6). */\nexport const SEALED_INLINE_MAX_PADDED_LENGTH = 256 * 1024;\n\n/** Plaintext limit of every category, in UTF-8 bytes of canonical JSON (D8). */\nexport const SEALED_PAYLOAD_MAX_CONTENT_LENGTH = 2 * 1024 * 1024;\n\n/** `{\"body\":\"\"}`: the canonical JSON of a sealed message around its body. */\nconst SEALED_AGENT_MESSAGE_FRAME_BYTES = 11;\n/**\n * The canonical JSON escaping bound: `JSON.stringify` turns a one-byte\n * control character into the six bytes `\\u00XX`, and nothing grows more per\n * UTF-8 byte (a lone surrogate, three bytes, becomes six).\n */\nconst JSON_STRING_MAX_EXPANSION = 6;\n\n/**\n * The largest opened content of a sealed `agent.message.publish` whose body\n * is at most `maxBytes` UTF-8 bytes (#1045 O2): `6 × maxBytes + 11`. At\n * `AGENT_MESSAGE_MAX_BYTES` it is 1,572,875, below\n * {@link SEALED_PAYLOAD_MAX_CONTENT_LENGTH}, so every legal body seals. The\n * device seals within it, and the Host bounds a sealed message's\n * `paddedLength` by `sealedPayloadPaddedLength(4 + this)` for the task's\n * frozen `maxBytes`.\n */\nexport function sealedAgentMessageMaxContentLength(maxBytes: number): number {\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > AGENT_MESSAGE_MAX_BYTES) {\n throw new RangeError(`An Agent message limit must be an integer from 1 to ${AGENT_MESSAGE_MAX_BYTES}`);\n }\n return JSON_STRING_MAX_EXPANSION * maxBytes + SEALED_AGENT_MESSAGE_FRAME_BYTES;\n}\n\nconst AEAD_TAG_BYTES = 16;\nconst FRAME_HEADER_BYTES = 4;\nconst ALIGNED_FRAME_LIMIT = 16 * 1024;\nconst FRAME_ALIGNMENT = 256;\nconst SALT_BYTES = 32;\nconst NONCE_BYTES = 12;\n\nfunction floorLog2(value: number): number {\n let exponent = 0;\n for (let remaining = value; remaining >= 2; remaining = Math.floor(remaining / 2)) exponent += 1;\n return exponent;\n}\n\n/**\n * The one legal padded length of a frame of `frameLength` bytes\n * (`4 + contentLength`): the next multiple of 256 up to 16 KiB, Padmé above.\n */\nexport function sealedPayloadPaddedLength(frameLength: number): number {\n if (!Number.isSafeInteger(frameLength) || frameLength < FRAME_HEADER_BYTES) {\n throw new RangeError('Sealed frame length must be a safe integer of at least 4');\n }\n if (frameLength <= ALIGNED_FRAME_LIMIT) return Math.ceil(frameLength / FRAME_ALIGNMENT) * FRAME_ALIGNMENT;\n const exponent = floorLog2(frameLength);\n const step = 2 ** (exponent - (floorLog2(exponent) + 1));\n return Math.ceil(frameLength / step) * step;\n}\n\n/** The largest padded length a sealed content may have. */\nexport const SEALED_PAYLOAD_MAX_PADDED_LENGTH = sealedPayloadPaddedLength(\n FRAME_HEADER_BYTES + SEALED_PAYLOAD_MAX_CONTENT_LENGTH,\n);\n\nfunction isLegalPaddedLength(value: number): boolean {\n return Number.isSafeInteger(value)\n && value >= FRAME_ALIGNMENT\n && value <= SEALED_PAYLOAD_MAX_PADDED_LENGTH\n && sealedPayloadPaddedLength(value) === value;\n}\n\nconst BASE64URL_VALUE = /^[A-Za-z0-9_-]*$/u;\nconst BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\n/**\n * The byte length of canonical unpadded base64url, or `undefined`. Canonical\n * means no padding, no impossible length, and zero unused bits in the last\n * character, so one byte string has exactly one encoding.\n */\nexport function sealedBase64UrlByteLength(value: string): number | undefined {\n if (!BASE64URL_VALUE.test(value)) return undefined;\n const tail = value.length % 4;\n if (tail === 1) return undefined;\n if (tail !== 0) {\n const last = BASE64URL_ALPHABET.indexOf(value[value.length - 1]!);\n const unusedBits = tail === 2 ? 0b1111 : 0b11;\n if ((last & unusedBits) !== 0) return undefined;\n }\n return Math.floor(value.length / 4) * 3 + (tail === 0 ? 0 : tail - 1);\n}\n\nfunction base64UrlOf(bytes: number) {\n return z.string().refine((value) => sealedBase64UrlByteLength(value) === bytes, `must be canonical unpadded base64url of ${bytes} bytes`);\n}\n\nconst PositiveIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);\n\n/**\n * One sealed content (§8.1) of one category. The outer fields are what the\n * Host reads; the ciphertext is the padded frame plus the 16-byte AES-GCM tag.\n * A message type fixes its category, so its schema names it as a literal. An\n * inline-only content refuses a padded length above the inline maximum.\n */\nfunction sealedPayloadSchema<Category extends z.ZodType<SealedPayloadCategory>>(category: Category, inlineOnly = false) {\n return z\n .object({\n v: z.literal(SEALED_PAYLOAD_VERSION),\n suite: z.literal(SEALED_PAYLOAD_SUITE),\n category,\n scope: z\n .object({\n id: z.string().min(1),\n epoch: PositiveIntegerSchema,\n keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u),\n })\n .strict(),\n chainHead: z\n .object({\n seq: PositiveIntegerSchema,\n hash: z.string().regex(CONTENT_HASH_RE),\n })\n .strict(),\n sender: z.string().regex(/^[A-Za-z0-9_-]{43}$/u),\n salt: base64UrlOf(SALT_BYTES),\n nonce: base64UrlOf(NONCE_BYTES),\n paddedLength: PositiveIntegerSchema.refine(isLegalPaddedLength, 'must be a legal padded frame length within the v1 limit'),\n contentMac: z.string().regex(/^hmac-sha256:[0-9a-f]{64}$/u),\n ciphertext: z.string().optional(),\n /** The ciphertext blob. A presigned `url` is transport detail and never part of a sealed member. */\n ciphertextRef: BlobRefSchema.omit({ url: true }).strict().optional(),\n })\n .strict()\n .superRefine((sealed, ctx) => {\n const ciphertextLength = sealed.paddedLength + AEAD_TAG_BYTES;\n const inline = sealed.paddedLength <= SEALED_INLINE_MAX_PADDED_LENGTH;\n if (inlineOnly && !inline) {\n ctx.addIssue({ code: 'custom', path: ['paddedLength'], message: `an inline-only content has a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH}` });\n return;\n }\n if (inline) {\n if (sealed.ciphertextRef !== undefined || sealed.ciphertext === undefined) {\n ctx.addIssue({ code: 'custom', path: ['ciphertext'], message: `a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH} carries inline ciphertext only` });\n } else if (sealedBase64UrlByteLength(sealed.ciphertext) !== ciphertextLength) {\n ctx.addIssue({ code: 'custom', path: ['ciphertext'], message: 'ciphertext must be canonical base64url of paddedLength + 16 bytes' });\n }\n return;\n }\n if (sealed.ciphertext !== undefined || sealed.ciphertextRef === undefined) {\n ctx.addIssue({ code: 'custom', path: ['ciphertextRef'], message: `a padded length above ${SEALED_INLINE_MAX_PADDED_LENGTH} carries ciphertextRef only` });\n } else if (sealed.ciphertextRef.size !== ciphertextLength) {\n ctx.addIssue({ code: 'custom', path: ['ciphertextRef', 'size'], message: 'ciphertextRef size must equal paddedLength + 16' });\n }\n });\n}\n\n/** A sealed member of any category. */\nexport const SealedPayloadSchema = sealedPayloadSchema(z.enum(SEALED_PAYLOAD_CATEGORIES));\nexport type SealedPayload = z.infer<typeof SealedPayloadSchema>;\n/** The sealed member of a task-input message (offers, steer). */\nexport const SealedTaskInputSchema = sealedPayloadSchema(z.literal('task-input'));\n/** The sealed member of a task-output message. */\nexport const SealedTaskOutputSchema = sealedPayloadSchema(z.literal('task-output'));\n/** The sealed member of an `agent.message.publish` (#1045 C2). */\nexport const SealedAgentMessageSchema = sealedPayloadSchema(z.literal('agent-message'));\n/**\n * The sealed member of a memory projection (#1045 C4). It is inline only\n * (owner decision O2): the Host keeps one latest snapshot per Agent and holds\n * no ciphertext blob for it.\n */\nexport const SealedMemoryProjectionSchema = sealedPayloadSchema(z.literal('memory-projection'), true);\n\nfunction isCanonicalCategoryList(categories: readonly string[]): boolean {\n return categories.every((category, index) => index === 0\n || SEALED_PAYLOAD_CATEGORIES.indexOf(categories[index - 1] as SealedPayloadCategory)\n < SEALED_PAYLOAD_CATEGORIES.indexOf(category as SealedPayloadCategory));\n}\n\n/**\n * A task's frozen sealing policy (§6.2). The offer carries it in plaintext.\n * `epoch` is the epoch of the offer's task-input content, and the lowest epoch\n * the task accepts. `memory-projection` needs `task-output`: a terminal seals\n * the task's memory-change evidence inside its task-output ciphertext.\n */\nexport const TaskSealingSchema = z\n .object({\n scopeId: z.string().min(1),\n epoch: PositiveIntegerSchema,\n categories: z\n .array(z.enum(SEALED_PAYLOAD_CATEGORIES))\n .min(1)\n .refine(isCanonicalCategoryList, 'categories must be unique and in canonical order')\n .refine(\n (categories) => !categories.includes('memory-projection') || categories.includes('task-output'),\n 'a task that seals memory-projection seals task-output too',\n ),\n })\n .strict();\nexport type TaskSealing = z.infer<typeof TaskSealingSchema>;\n\n/**\n * A canonical UTC instant, `YYYY-MM-DDTHH:mm:ss.sssZ` and a real calendar\n * instant. This is the form core binds as `notAfter` in the AAD\n * (`@byok-sdk/core` `isCanonicalTimestamp`), so a device can rebuild the AAD\n * from the wire value byte for byte.\n */\nconst CanonicalInstantSchema = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/u)\n .refine((value) => {\n const instant = Date.parse(value);\n return Number.isFinite(instant) && new Date(instant).toISOString() === value;\n }, 'must be a canonical UTC instant');\n\n/**\n * The routine template of a sealed execution (design §6.3). The offer's\n * `sealed` member is then the template, family `routine.template`, which the\n * member sealed once for every occurrence. The device rebuilds its binding\n * from these fields: identity `{ routineId, definitionVersion }`, no device,\n * the offer's `agentRef` and `sealing.categories`, and `notAfter`. They travel\n * in plaintext because the AAD binds them. `definitionVersion` is an integer,\n * because the binding tells `4` and `\"4\"` apart. The device, not the Host,\n * checks `notAfter` against its clock.\n */\nexport const RoutineRefSchema = z\n .object({\n routineId: z.string().min(1),\n definitionVersion: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n notAfter: CanonicalInstantSchema,\n })\n .strict();\n\n\n/**\n * The rule of a sealed offer, for `superRefine`: `sealed` is present exactly\n * when the task's `sealing` includes `task-input`, and then `instruction` is\n * absent and `sealed.scope` is the task's scope at the task's epoch. When the\n * task seals only its output, `instruction` is plaintext and required. A\n * `routineRef` names a routine template, which is sealed task input, so it\n * needs a task that seals `task-input`.\n *\n * Whether a task's later messages must be sealed is the Host's and the\n * device's check: they know the task's `sealing`, this payload does not.\n */\nexport function sealedOfferRule(\n payload: { readonly instruction?: unknown; readonly sealing: TaskSealing; readonly sealed?: SealedPayload; readonly routineRef?: unknown },\n ctx: z.RefinementCtx,\n): void {\n const { instruction, sealing, sealed, routineRef } = payload;\n if (!sealing.categories.includes('task-input')) {\n if (routineRef !== undefined) ctx.addIssue({ code: 'custom', path: ['routineRef'], message: 'a routine template is sealed task input, so routineRef needs a task that seals task-input' });\n if (sealed !== undefined) ctx.addIssue({ code: 'custom', path: ['sealed'], message: 'a task that does not seal task-input carries no sealed member' });\n if (instruction === undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a task that does not seal task-input carries a plaintext instruction' });\n return;\n }\n if (sealed === undefined) {\n ctx.addIssue({ code: 'custom', path: ['sealed'], message: 'a task that seals task-input carries the sealed instruction' });\n return;\n }\n if (instruction !== undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a sealed instruction never travels in plaintext too' });\n if (sealed.scope.id !== sealing.scopeId || sealed.scope.epoch !== sealing.epoch) {\n ctx.addIssue({ code: 'custom', path: ['sealed', 'scope'], message: 'the offer task-input must be sealed under the task scope at the task epoch' });\n }\n}\n","import { z } from 'zod';\n\n/** Opaque, portable local profile identity. It is one logical id, never a path. */\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u, 'provider profile refs must be lowercase portable identifiers');\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/** Monotonic local profile revision represented canonically on the wire. */\nexport const ProviderProfileRevisionSchema = z\n .string()\n .regex(/^(?:0|[1-9][0-9]{0,19})$/u, 'provider profile revision must be canonical decimal');\nexport type ProviderProfileRevision = z.infer<typeof ProviderProfileRevisionSchema>;\n\n/** Hash of the normalized, non-secret local profile projection. */\nexport const ProviderProfileHashSchema = z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/u, 'provider profile hash must be lowercase sha256');\nexport type ProviderProfileHash = z.infer<typeof ProviderProfileHashSchema>;\n\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\nexport type ProviderModelCapability = z.infer<typeof ProviderModelCapabilitySchema>;\n\n/** Credential-free exact desired binding. Endpoint and auth material stay device-local. */\nexport const ProviderProfileBindingSchema = z\n .object({\n profileRef: ProviderProfileRefSchema,\n profileRevision: ProviderProfileRevisionSchema,\n profileHash: ProviderProfileHashSchema,\n modelId: z.string().min(1).max(160).regex(/^[^\\u0000\\r\\n]+$/u),\n requiredCapabilities: z.array(ProviderModelCapabilitySchema).max(8),\n })\n .strict()\n .superRefine((binding, ctx) => {\n if (new Set(binding.requiredCapabilities).size !== binding.requiredCapabilities.length) {\n ctx.addIssue({ code: 'custom', path: ['requiredCapabilities'], message: 'duplicate provider capability' });\n }\n });\nexport type ProviderProfileBinding = z.infer<typeof ProviderProfileBindingSchema>;\n","import { z } from 'zod';\nimport {\n ProviderModelCapabilitySchema,\n ProviderProfileBindingSchema,\n ProviderProfileRefSchema,\n} from './provider-profile-binding';\n\n/**\n * Sealed provider provisioning — the wire half.\n *\n * A Host provisions a device-local provider profile (and its API key) without\n * the key ever crossing this SDK's wire. The ciphertext, its configuration and\n * the device's pull of both travel over the HOST's own authenticated device\n * routes; this package defines only:\n *\n * - the task-free server -> daemon notice `provider.provisioning.available`,\n * whose payload is exactly `{ requestId }` (see `messages.ts`);\n * - the device capability that gates that notice;\n * - the credential-free completion a device reports and the durable readback a\n * Host returns for it;\n * - the device-proof operation name a device signs when it registers its\n * provider-secret sealing key.\n *\n * Notice-and-fetch is the point: the daemon journals mailbox rows before they\n * are acknowledged and a mailbox never deletes an unacknowledged row, so a\n * ciphertext carried inside the envelope would outlive the provisioning window\n * in two places. The strict one-field payload makes that unrepresentable.\n *\n * Audiences, route paths and product names are Host vocabulary and stay out of\n * this package.\n */\n\n/**\n * Device-proof `operation` for the signed claim that registers the device's\n * provider-secret sealing public key (`{ keyId, epoch, publicJwk }`).\n */\nexport const PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION = 'provider-secret-sealing-key.register' as const;\n\n/**\n * Server -> daemon: a provisioning request is waiting for this device.\n *\n * `.strict()` and exactly one field. There is deliberately no configuration,\n * no ciphertext, no provider identity and no Agent identity: the device fetches\n * all of that from the Host under its own device authentication, so a mailbox\n * row or journal line never holds more than an opaque request id.\n */\nexport const ProviderProvisioningAvailablePayloadSchema = z\n .object({\n requestId: z.uuid(),\n })\n .strict();\nexport type ProviderProvisioningAvailablePayload = z.infer<typeof ProviderProvisioningAvailablePayloadSchema>;\n\nexport const PROVIDER_PROVISIONING_OPERATIONS = ['configure', 'update_model', 'replace_secret', 'delete'] as const;\nexport const ProviderProvisioningOperationSchema = z.enum(PROVIDER_PROVISIONING_OPERATIONS);\nexport type ProviderProvisioningOperation = z.infer<typeof ProviderProvisioningOperationSchema>;\n\n/** PostgreSQL BIGINT maximum, carried as decimal text to avoid JavaScript precision loss. */\nexport const PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM = '9223372036854775807' as const;\n\n/**\n * Non-secret, monotonic per-profile operation generation. It is bound into the\n * sealed request's associated data and into the device's local state, so an\n * older generation is always refused. Canonical positive decimal text.\n */\nexport const ProviderProvisioningOperationGenerationSchema = z\n .string()\n .regex(/^[1-9][0-9]{0,18}$/u, 'operationGeneration must be a canonical positive decimal string')\n .refine(\n (value) =>\n value.length < PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM.length ||\n value <= PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM,\n `operationGeneration must not exceed ${PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM}`,\n );\nexport type ProviderProvisioningOperationGeneration = z.infer<typeof ProviderProvisioningOperationGenerationSchema>;\n\n/**\n * SHA-256 of the canonical non-secret operation the device evaluated. Two\n * completions for one request id are the same result only when this digest\n * (and the rest of the completion) is identical. Pinned to `@byok-sdk/core`\n * `providerProvisioningRequestDigest(request)` (the value `@byok-sdk/keys`\n * returns as `result.requestDigest`); see docs/protocol.md §2.3.\n */\nexport const ProviderProvisioningOperationDigestSchema = z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/u, 'operationDigest must be lowercase sha256');\nexport type ProviderProvisioningOperationDigest = z.infer<typeof ProviderProvisioningOperationDigestSchema>;\n\n/**\n * Closed rejection set. Codes name a failed check, never a value: no plaintext,\n * no ciphertext, no OS error detail. `local_commit_interrupted` also covers a\n * request that finds the same or another operation still pending locally.\n *\n * `request_expired` and `sealing_key_rotated` may also be decided by the Host\n * before the device ever completes the request (see\n * {@link PROVIDER_PROVISIONING_HOST_TERMINAL_CODES}).\n */\nexport const PROVIDER_PROVISIONING_REJECTION_CODES = [\n 'request_invalid',\n 'request_conflict',\n 'request_expired',\n 'request_not_yet_valid',\n 'request_window_invalid',\n 'sealing_key_rotated',\n 'enrollment_mismatch',\n 'agent_not_placed',\n 'config_digest_mismatch',\n 'operation_generation_stale',\n 'profile_changed',\n 'profile_not_found',\n 'credential_scope_mismatch',\n 'provider_kind_unsupported',\n 'pi_model_invalid',\n 'capabilities_invalid',\n 'seal_open_failed',\n 'secret_invalid',\n 'local_commit_interrupted',\n 'secret_store_unavailable',\n] as const;\nexport const ProviderProvisioningRejectionCodeSchema = z.enum(PROVIDER_PROVISIONING_REJECTION_CODES);\nexport type ProviderProvisioningRejectionCode = z.infer<typeof ProviderProvisioningRejectionCodeSchema>;\n\n/** Rejections a Host may record on its own authority, without a device completion. */\nexport const PROVIDER_PROVISIONING_HOST_TERMINAL_CODES = ['request_expired', 'sealing_key_rotated'] as const satisfies\n readonly ProviderProvisioningRejectionCode[];\n\n/**\n * Credential-free projection of the device's provider status after an applied\n * operation. It reports WHETHER a secret is configured, never the secret, and\n * carries no endpoint or auth material: those stay device-local.\n */\nexport const ProviderProvisioningProviderStatusSchema = z\n .object({\n profileRef: ProviderProfileRefSchema,\n providerKind: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u, 'providerKind must be a lowercase portable identifier'),\n modelId: z.string().min(1).max(160).regex(/^[^\\u0000\\r\\n]+$/u),\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n secretConfigured: z.boolean(),\n })\n .strict()\n .superRefine((status, ctx) => {\n if (new Set(status.capabilities).size !== status.capabilities.length) {\n ctx.addIssue({ code: 'custom', path: ['capabilities'], message: 'duplicate provider capability' });\n }\n });\nexport type ProviderProvisioningProviderStatus = z.infer<typeof ProviderProvisioningProviderStatusSchema>;\n\n/**\n * Closed outcome set of the device's one post-apply check of the stored key\n * against its vendor. It is a HINT for the Host UI, never a readiness input:\n * a saved key is not a validated key, and a network failure does not block\n * provisioning.\n *\n * - `credential_rejected`: the vendor explicitly refused the credential.\n * - `rate_limited`, `quota_or_billing`, `model_not_permitted`: the credential\n * was accepted but the call could not be served for that reason.\n * - `provider_error`: the vendor answered with an error that is none of the\n * classes above.\n * - `unreachable`, `timeout`: no vendor answer within the device's bounds.\n * - `not_run`: no check was made (for example `delete`, or an endpoint without\n * credential auth).\n *\n * No vendor text, status body or error detail crosses this boundary.\n */\nexport const PROVIDER_PROVISIONING_KEY_CHECK_RESULTS = [\n 'ok',\n 'credential_rejected',\n 'rate_limited',\n 'quota_or_billing',\n 'model_not_permitted',\n 'provider_error',\n 'unreachable',\n 'timeout',\n 'not_run',\n] as const;\nexport const ProviderProvisioningKeyCheckResultSchema = z.enum(PROVIDER_PROVISIONING_KEY_CHECK_RESULTS);\nexport type ProviderProvisioningKeyCheckResult = z.infer<typeof ProviderProvisioningKeyCheckResultSchema>;\n\nexport const ProviderProvisioningKeyCheckSchema = z\n .object({\n result: ProviderProvisioningKeyCheckResultSchema,\n })\n .strict();\nexport type ProviderProvisioningKeyCheck = z.infer<typeof ProviderProvisioningKeyCheckSchema>;\n\nconst completionIdentity = {\n requestId: z.uuid(),\n operation: ProviderProvisioningOperationSchema,\n operationGeneration: ProviderProvisioningOperationGenerationSchema,\n operationDigest: ProviderProvisioningOperationDigestSchema,\n} as const;\n\nconst AppliedCompletionSchema = z\n .object({\n outcome: z.literal('applied'),\n ...completionIdentity,\n providerStatus: ProviderProvisioningProviderStatusSchema.nullable(),\n binding: ProviderProfileBindingSchema.nullable(),\n keyCheck: ProviderProvisioningKeyCheckSchema,\n })\n .strict();\n\nconst RejectedCompletionSchema = z\n .object({\n outcome: z.literal('rejected'),\n ...completionIdentity,\n code: ProviderProvisioningRejectionCodeSchema,\n })\n .strict();\n\n/**\n * The terminal, credential-free result of one provisioning request, reported\n * by the device to the Host.\n *\n * `applied` carries the post-operation status and exact binding — both absent\n * (`null`) for `delete` and only for `delete`. `configure` and\n * `replace_secret` write a secret, so an applied result for either must report\n * `secretConfigured: true`. `replace_secret` leaves the profile revision and\n * hash unchanged; the binding it reports is the same exact binding as before.\n * Every applied result carries the required `keyCheck` hint; a `delete` has no\n * key left to check and must report `not_run`.\n */\nexport const ProviderProvisioningCompletionSchema = z\n .discriminatedUnion('outcome', [AppliedCompletionSchema, RejectedCompletionSchema])\n .superRefine((completion, ctx) => {\n if (completion.outcome !== 'applied') return;\n const { operation, providerStatus, binding } = completion;\n if (operation === 'delete') {\n if (completion.keyCheck.result !== 'not_run') {\n ctx.addIssue({ code: 'custom', path: ['keyCheck', 'result'], message: 'an applied delete must report keyCheck not_run' });\n }\n if (providerStatus !== null) {\n ctx.addIssue({ code: 'custom', path: ['providerStatus'], message: 'an applied delete reports no provider status' });\n }\n if (binding !== null) {\n ctx.addIssue({ code: 'custom', path: ['binding'], message: 'an applied delete reports no binding' });\n }\n return;\n }\n if (providerStatus === null) {\n ctx.addIssue({ code: 'custom', path: ['providerStatus'], message: `an applied ${operation} must report provider status` });\n }\n if (binding === null) {\n ctx.addIssue({ code: 'custom', path: ['binding'], message: `an applied ${operation} must report its exact binding` });\n }\n if (providerStatus === null || binding === null) return;\n if (providerStatus.profileRef !== binding.profileRef) {\n ctx.addIssue({ code: 'custom', path: ['binding', 'profileRef'], message: 'binding profileRef must equal providerStatus profileRef' });\n }\n if (providerStatus.modelId !== binding.modelId) {\n ctx.addIssue({ code: 'custom', path: ['binding', 'modelId'], message: 'binding modelId must equal providerStatus modelId' });\n }\n if ((operation === 'configure' || operation === 'replace_secret') && !providerStatus.secretConfigured) {\n ctx.addIssue({\n code: 'custom',\n path: ['providerStatus', 'secretConfigured'],\n message: `an applied ${operation} must report a configured secret`,\n });\n }\n });\nexport type ProviderProvisioningCompletion = z.infer<typeof ProviderProvisioningCompletionSchema>;\n\n/**\n * How the Host's durable record relates to the completion it was handed:\n *\n * - `recorded`: this completion became the request's first terminal fact.\n * - `idempotent`: an identical completion (same operation digest and result)\n * was already recorded; the stored result is returned and nothing is\n * rewritten.\n * - `conflict`: a different completion (different operation digest or result)\n * is already recorded; the stored one is returned unchanged.\n * - `host_terminal`: the Host had already terminated the request on its own\n * authority ({@link PROVIDER_PROVISIONING_HOST_TERMINAL_CODES}), for example\n * because it expired before the device fetched it.\n */\nexport const PROVIDER_PROVISIONING_DISPOSITIONS = ['recorded', 'idempotent', 'conflict', 'host_terminal'] as const;\nexport const ProviderProvisioningDispositionSchema = z.enum(PROVIDER_PROVISIONING_DISPOSITIONS);\nexport type ProviderProvisioningDisposition = z.infer<typeof ProviderProvisioningDispositionSchema>;\n\n/**\n * The Host's durable terminal readback for one provisioning request.\n *\n * `completion` is the terminal fact the Host has STORED, which on `conflict`\n * is not the one the device submitted. Every readback is terminal — there is\n * no `pending` — so a daemon that holds one may acknowledge the notice: an\n * expired, rotated, rejected or conflicting request is a deterministic end\n * state that no redelivery can change.\n */\nexport const ProviderProvisioningReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n disposition: ProviderProvisioningDispositionSchema,\n completion: ProviderProvisioningCompletionSchema,\n completedAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((readback, ctx) => {\n if (readback.completion.requestId !== readback.requestId) {\n ctx.addIssue({ code: 'custom', path: ['completion', 'requestId'], message: 'completion requestId must equal readback requestId' });\n }\n if (\n readback.disposition === 'host_terminal' &&\n (readback.completion.outcome !== 'rejected' ||\n !(PROVIDER_PROVISIONING_HOST_TERMINAL_CODES as readonly string[]).includes(readback.completion.code))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['completion'],\n message: `a host_terminal readback must carry a rejected completion with one of: ${PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.join(', ')}`,\n });\n }\n });\nexport type ProviderProvisioningReadback = z.infer<typeof ProviderProvisioningReadbackSchema>;\n","/**\n * Plain-JSON-data canonicalization shared by every bounded JSON channel of\n * the wire: `task.complete.document` (`checkResultDocument`, messages.ts) and\n * the result-document schema and outcome (`result-schema.ts`). One rule, one\n * implementation, so the channels cannot disagree about what \"plain JSON\n * data\" means or how its canonical UTF-8 size is measured.\n *\n * Zod-free and free of node builtins.\n */\n\n/** Outcome of {@link canonicalizePlainJson} without a depth bound. */\nexport type PlainJsonCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: unknown }\n | { readonly ok: false; readonly reason: 'not-serializable' }\n | { readonly ok: false; readonly reason: 'over-cap'; readonly bytes: number }\n | { readonly ok: false; readonly reason: 'not-plain-json' };\n\n/** Outcome of {@link canonicalizePlainJson} with a container-nesting bound. */\nexport type BoundedPlainJsonCheck =\n | PlainJsonCheck\n | { readonly ok: false; readonly reason: 'too-deep'; readonly bytes: number };\n\n/**\n * Structural equality between a value and its own JSON round trip, written\n * out by hand (no node builtins — this package deliberately has none) over\n * exactly the three shapes pure JSON data can take.\n *\n * The asymmetry is the point: `a` is the CALLER's object, which may contain\n * anything JavaScript allows, while `b` is always the output of\n * `JSON.parse` — pure data. So every case where `a` is something JSON cannot\n * represent (a `Date`, a function, `undefined`, `NaN`, a symbol, a getter\n * that answers differently the second time, an object whose `toJSON` rewrote\n * it) shows up here as a shape or value mismatch against `b`, and is\n * rejected. `NaN !== NaN` falls out of strict equality for free, which is\n * exactly what we want: `NaN` serializes to `null`, so it is not\n * representable and must not pass.\n *\n * The one case structural comparison alone cannot see — an object whose data\n * lives somewhere other than its own enumerable string keys, e.g. a\n * populated `Map` — gets its own explicit rejection in the object branch\n * below.\n */\nfunction isSameJsonData(a: unknown, b: unknown): boolean {\n if (a === null || b === null) return a === b;\n\n const typeOfA = typeof a;\n if (typeOfA !== typeof b) return false;\n\n if (typeOfA !== 'object') {\n // string | number | boolean. Anything else (function, symbol, bigint,\n // undefined) can never equal a JSON.parse output, and `NaN === NaN` is\n // false, so this single comparison covers every primitive case.\n return a === b;\n }\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n\n if (aIsArray) {\n const arrayA = a as unknown[];\n const arrayB = b as unknown[];\n if (arrayA.length !== arrayB.length) return false;\n for (let index = 0; index < arrayA.length; index += 1) {\n if (!isSameJsonData(arrayA[index], arrayB[index])) return false;\n }\n return true;\n }\n\n const objectA = a as Record<string, unknown>;\n const objectB = b as Record<string, unknown>;\n const keysA = Object.keys(objectA); // own enumerable string keys\n const keysB = Object.keys(objectB);\n\n // An object whose data does NOT live in its own enumerable string keys is\n // invisible to both `JSON.stringify` and the key comparison below — a\n // populated `Map`/`Set` serializes to `{}` and would otherwise compare\n // EQUAL to that `{}`, delivering an empty document as the task's truthful\n // structured result. That is the same silent-wrong-output class the whole\n // plain-data contract exists to stop, so a container-shaped value with no\n // own enumerable string keys and a non-plain prototype is rejected here.\n // Applied at every object node (this function recurses), so a nested\n // `Map`/`Set`/exotic instance dies exactly like a top-level one.\n //\n // The boundary this deliberately draws: a class instance WITH own\n // enumerable fields still passes, because its data really is in those\n // fields and survives the round trip intact. A class whose values come\n // from PROTOTYPE-level getters does not — those are invisible to JSON, so\n // such an instance is not plain JSON data and is outside this contract by\n // definition (docs/protocol.md §7.2). `Object.create(null)` is explicitly\n // fine: a null prototype is plain data, just without `Object.prototype`.\n if (keysA.length === 0) {\n const prototypeA: unknown = Object.getPrototypeOf(objectA);\n if (prototypeA !== Object.prototype && prototypeA !== null) return false;\n }\n\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) return false;\n if (!isSameJsonData(objectA[key], objectB[key])) return false;\n }\n return true;\n}\n\n/**\n * Container nesting depth of pure JSON data (a `JSON.parse` output), computed\n * iteratively so no input can exhaust the call stack. A scalar is depth 0,\n * `{}` and `[]` are depth 1. Stops as soon as `limit` is exceeded.\n */\nexport function jsonDepthExceeds(value: unknown, limit: number): boolean {\n const stack: { readonly node: unknown; readonly depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (node === null || typeof node !== 'object') continue;\n const next = depth + 1;\n if (next > limit) return true;\n const children = Array.isArray(node) ? node : Object.values(node as Record<string, unknown>);\n for (const child of children) stack.push({ node: child, depth: next });\n }\n return false;\n}\n\n/**\n * Canonicalize `value` as plain JSON data within `maxBytes` canonical UTF-8\n * bytes:\n *\n * 1. `JSON.stringify` must succeed and not return `undefined`.\n * 2. Its UTF-8 byte length must be at most `maxBytes`.\n * 3. `JSON.parse` that string: the CANONICAL SNAPSHOT (pure data).\n * 4. With `maxDepth`, the snapshot's container nesting must be at most\n * `maxDepth`. This runs before step 5, so the recursive comparison\n * below is bounded by it.\n * 5. The original must be structurally equal to the snapshot\n * (`isSameJsonData`).\n *\n * On success a sender uses `canonical`, never the original reference.\n */\nexport function canonicalizePlainJson(value: unknown, maxBytes: number): PlainJsonCheck;\nexport function canonicalizePlainJson(value: unknown, maxBytes: number, maxDepth: number): BoundedPlainJsonCheck;\nexport function canonicalizePlainJson(value: unknown, maxBytes: number, maxDepth?: number): BoundedPlainJsonCheck {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return { ok: false, reason: 'not-serializable' };\n }\n if (json === undefined) return { ok: false, reason: 'not-serializable' };\n\n const bytes = new TextEncoder().encode(json).length;\n if (bytes > maxBytes) return { ok: false, reason: 'over-cap', bytes };\n\n const canonical: unknown = JSON.parse(json);\n if (maxDepth !== undefined && jsonDepthExceeds(canonical, maxDepth)) return { ok: false, reason: 'too-deep', bytes };\n if (!isSameJsonData(value, canonical)) return { ok: false, reason: 'not-plain-json' };\n\n return { ok: true, bytes, canonical };\n}\n","/**\n * Result-document schema subset (wire v3, docs/protocol.md §7.2).\n *\n * A `terminalProjection.mode: 'result-document'` offer freezes one JSON\n * Schema for the task's structured outcome. This module owns the two checks\n * every party applies to it:\n *\n * - {@link checkResultSchema}: the admission guard. It decides whether a\n * candidate schema is inside the subset this SDK accepts. It is ours, and\n * it is the only admission authority: the instance validator below never\n * sees a schema the guard did not admit.\n * - {@link validateResultOutcome}: re-runs the guard, bounds the outcome,\n * then validates the outcome against the admitted schema with\n * `@cfworker/json-schema` (draft 2020-12, interpreted; no code generation).\n *\n * The subset (PRD §8.3): `type`, `properties`, `required`,\n * `additionalProperties` (only `false`), `items`, `enum`, `const`, `oneOf`,\n * `minLength`, `maxLength`, `minItems`, `maxItems`, `minimum`, `maximum`,\n * `description`. Every other keyword is refused, so `$ref`, `pattern`,\n * `format` and the other draft 2020-12 vocabularies are unreachable in the\n * library. The root must be `type: 'object'`; root `oneOf` is allowed.\n *\n * Zod-free and free of node builtins.\n */\nimport { Validator, type OutputUnit } from '@cfworker/json-schema';\nimport { canonicalizePlainJson, type BoundedPlainJsonCheck } from './plain-json';\n\n/** Maximum canonical JSON UTF-8 size of a result-document schema. */\nexport const RESULT_SCHEMA_MAX_BYTES = 16_384;\n/** Maximum canonical JSON UTF-8 size of a submitted outcome document. */\nexport const RESULT_OUTCOME_MAX_BYTES = 65_536;\n/**\n * Maximum subschema nesting below the root (each `properties` member, `items`\n * and `oneOf` branch is one level). With the 16 KiB cap this bounds how much\n * schema structure one validation walks.\n */\nexport const RESULT_SCHEMA_MAX_DEPTH = 32;\n/**\n * Maximum JSON container nesting of a schema or outcome document, checked\n * iteratively before any recursive routine runs on it.\n */\nexport const RESULT_JSON_MAX_DEPTH = 128;\n/** Maximum number of issues one failed check reports. */\nexport const RESULT_ISSUES_MAX_COUNT = 20;\n/** Maximum UTF-8 size of the reported issue list, as JSON. */\nexport const RESULT_ISSUES_MAX_BYTES = 4_096;\n/**\n * Pointer, keyword and message strings in an issue are cut to this many UTF-16\n * units. Even fully `\\u`-escaped, one issue then fits the byte cap, so a\n * failure always reports at least one issue.\n */\nconst ISSUE_STRING_MAX_LENGTH = 128;\n\nexport const RESULT_SCHEMA_KEYWORDS = Object.freeze([\n 'type',\n 'properties',\n 'required',\n 'additionalProperties',\n 'items',\n 'enum',\n 'const',\n 'oneOf',\n 'minLength',\n 'maxLength',\n 'minItems',\n 'maxItems',\n 'minimum',\n 'maximum',\n 'description',\n] as const);\nexport type ResultSchemaKeyword = (typeof RESULT_SCHEMA_KEYWORDS)[number];\n\nexport const RESULT_SCHEMA_INSTANCE_TYPES = Object.freeze([\n 'object',\n 'array',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'null',\n] as const);\nexport type ResultSchemaInstanceType = (typeof RESULT_SCHEMA_INSTANCE_TYPES)[number];\n\n/** A schema inside the admitted subset. Only {@link checkResultSchema} proves a value is one. */\nexport interface ResultSchema {\n readonly type?: ResultSchemaInstanceType | readonly ResultSchemaInstanceType[];\n readonly properties?: { readonly [name: string]: ResultSchema };\n readonly required?: readonly string[];\n readonly additionalProperties?: false;\n readonly items?: ResultSchema;\n readonly enum?: readonly unknown[];\n readonly const?: unknown;\n readonly oneOf?: readonly ResultSchema[];\n readonly minLength?: number;\n readonly maxLength?: number;\n readonly minItems?: number;\n readonly maxItems?: number;\n readonly minimum?: number;\n readonly maximum?: number;\n readonly description?: string;\n}\n\n/**\n * One bounded failure detail. `pointer` is an RFC 6901 JSON Pointer into the\n * checked document: the schema for admission issues, the outcome for\n * validation issues (`''` is the document root). `keyword` is the JSON Schema\n * keyword at fault, or a document-level code: `not-serializable`,\n * `not-plain-json`, `over-cap`, `too-deep` (JSON nesting), `schema` (a\n * subschema that is not an object) or `depth` (subschema nesting).\n */\nexport interface ResultIssue {\n readonly pointer: string;\n readonly keyword: string;\n readonly message: string;\n}\n\n/** Document-level failure shared by the schema and outcome checks. */\nexport type ResultDocumentFailureReason = 'not-serializable' | 'not-plain-json' | 'over-cap' | 'too-deep';\n\ninterface ResultFailure<Reason extends string> {\n readonly ok: false;\n readonly reason: Reason;\n /** Canonical UTF-8 size, when it was measured. */\n readonly bytes?: number;\n /** At least one issue; at most {@link RESULT_ISSUES_MAX_COUNT} and {@link RESULT_ISSUES_MAX_BYTES}. */\n readonly issues: readonly ResultIssue[];\n /** True when issues were dropped to respect the caps. */\n readonly truncated: boolean;\n}\n\nexport type ResultSchemaCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: ResultSchema }\n | ResultFailure<ResultDocumentFailureReason | 'not-subset'>;\n\nexport type ResultOutcomeCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: unknown }\n | ResultFailure<'schema-not-admitted' | ResultDocumentFailureReason | 'schema-mismatch'>;\n\nconst KEYWORDS = new Set<string>(RESULT_SCHEMA_KEYWORDS);\nconst INSTANCE_TYPES = new Set<string>(RESULT_SCHEMA_INSTANCE_TYPES);\nconst encoder = new TextEncoder();\n\nfunction cut(value: string): string {\n return value.length <= ISSUE_STRING_MAX_LENGTH ? value : `${value.slice(0, ISSUE_STRING_MAX_LENGTH - 1)}…`;\n}\n\n/** Collects issues under the count and byte caps. */\nclass IssueSink {\n readonly issues: ResultIssue[] = [];\n truncated = false;\n private bytes = 2; // \"[]\"\n\n add(pointer: string, keyword: string, message: string): void {\n const issue: ResultIssue = { pointer: cut(pointer), keyword: cut(keyword), message: cut(message) };\n const size = encoder.encode(JSON.stringify(issue)).length + (this.issues.length === 0 ? 0 : 1);\n if (this.issues.length >= RESULT_ISSUES_MAX_COUNT || this.bytes + size > RESULT_ISSUES_MAX_BYTES) {\n this.truncated = true;\n return;\n }\n this.issues.push(issue);\n this.bytes += size;\n }\n\n get empty(): boolean {\n return this.issues.length === 0 && !this.truncated;\n }\n}\n\nfunction pointerTo(base: string, token: string | number): string {\n return `${base}/${String(token).replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isNonNegativeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\n/**\n * True when any string or property name in pure JSON data is not well-formed\n * Unicode. A lone surrogate has no UTF-8 encoding, so the measured canonical\n * size would not describe it, and the library cannot build a pointer to it.\n * Iterative; the caller has already bounded the nesting depth.\n */\nfunction hasLoneSurrogate(value: unknown): boolean {\n const stack: unknown[] = [value];\n while (stack.length > 0) {\n const node = stack.pop();\n if (typeof node === 'string') {\n if (LONE_SURROGATE.test(node)) return true;\n } else if (Array.isArray(node)) {\n for (const member of node) stack.push(member);\n } else if (node !== null && typeof node === 'object') {\n for (const [key, member] of Object.entries(node)) {\n if (LONE_SURROGATE.test(key)) return true;\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/** Canonical plain JSON within the byte and depth caps, in well-formed Unicode. */\nfunction canonicalDocument(value: unknown, maxBytes: number): BoundedPlainJsonCheck {\n const check = canonicalizePlainJson(value, maxBytes, RESULT_JSON_MAX_DEPTH);\n if (check.ok && hasLoneSurrogate(check.canonical)) return { ok: false, reason: 'not-plain-json' };\n return check;\n}\n\nfunction documentFailure(\n check: Exclude<BoundedPlainJsonCheck, { ok: true }>,\n what: string,\n maxBytes: number,\n): ResultFailure<ResultDocumentFailureReason> {\n const sink = new IssueSink();\n switch (check.reason) {\n case 'not-serializable':\n sink.add('', check.reason, `${what} is not JSON-serializable`);\n return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };\n case 'not-plain-json':\n sink.add('', check.reason, `${what} is not plain JSON data in well-formed Unicode`);\n return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };\n case 'over-cap':\n sink.add('', check.reason, `${what} is ${check.bytes} bytes as canonical JSON (UTF-8); the cap is ${maxBytes}`);\n return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };\n case 'too-deep':\n sink.add('', check.reason, `${what} nests JSON containers deeper than ${RESULT_JSON_MAX_DEPTH}`);\n return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };\n }\n}\n\n/** Walks one subschema of an already-canonical (pure JSON) document. */\nfunction checkSubschema(node: unknown, pointer: string, depth: number, sink: IssueSink, requireObjectRoot = true): void {\n if (!isObject(node)) {\n sink.add(pointer, 'schema', 'a subschema must be a JSON object');\n return;\n }\n if (depth > RESULT_SCHEMA_MAX_DEPTH) {\n sink.add(pointer, 'depth', `subschemas nest deeper than ${RESULT_SCHEMA_MAX_DEPTH} levels`);\n return;\n }\n for (const key of Object.keys(node)) {\n if (!KEYWORDS.has(key)) sink.add(pointerTo(pointer, key), key, 'keyword is outside the result schema subset');\n }\n if (requireObjectRoot && depth === 0 && node.type !== 'object') {\n sink.add(pointerTo(pointer, 'type'), 'type', \"the root schema must declare type: 'object'\");\n }\n\n if (Object.hasOwn(node, 'type')) {\n const type = node.type;\n const valid = typeof type === 'string'\n ? INSTANCE_TYPES.has(type)\n : Array.isArray(type) && type.length > 0\n && type.every((member) => typeof member === 'string' && INSTANCE_TYPES.has(member))\n && new Set(type).size === type.length;\n if (!valid) sink.add(pointerTo(pointer, 'type'), 'type', 'must be a JSON type name or a non-empty array of unique type names');\n }\n if (Object.hasOwn(node, 'properties')) {\n const properties = node.properties;\n const at = pointerTo(pointer, 'properties');\n if (!isObject(properties)) sink.add(at, 'properties', 'must be an object of subschemas');\n else for (const [name, subschema] of Object.entries(properties)) checkSubschema(subschema, pointerTo(at, name), depth + 1, sink);\n }\n if (Object.hasOwn(node, 'required')) {\n const required = node.required;\n if (!Array.isArray(required) || !required.every((name) => typeof name === 'string') || new Set(required).size !== required.length) {\n sink.add(pointerTo(pointer, 'required'), 'required', 'must be an array of unique property names');\n }\n }\n if (Object.hasOwn(node, 'additionalProperties') && node.additionalProperties !== false) {\n sink.add(pointerTo(pointer, 'additionalProperties'), 'additionalProperties', 'only additionalProperties: false is allowed');\n }\n if (Object.hasOwn(node, 'items')) {\n if (!isObject(node.items)) sink.add(pointerTo(pointer, 'items'), 'items', 'must be one subschema object');\n else checkSubschema(node.items, pointerTo(pointer, 'items'), depth + 1, sink);\n }\n if (Object.hasOwn(node, 'enum') && (!Array.isArray(node.enum) || node.enum.length === 0)) {\n sink.add(pointerTo(pointer, 'enum'), 'enum', 'must be a non-empty array');\n }\n if (Object.hasOwn(node, 'oneOf')) {\n const oneOf = node.oneOf;\n const at = pointerTo(pointer, 'oneOf');\n if (!Array.isArray(oneOf) || oneOf.length === 0) sink.add(at, 'oneOf', 'must be a non-empty array of subschemas');\n else oneOf.forEach((subschema, index) => checkSubschema(subschema, pointerTo(at, index), depth + 1, sink));\n }\n for (const keyword of ['minLength', 'maxLength', 'minItems', 'maxItems'] as const) {\n if (Object.hasOwn(node, keyword) && !isNonNegativeInteger(node[keyword])) {\n sink.add(pointerTo(pointer, keyword), keyword, 'must be a non-negative integer');\n }\n }\n for (const keyword of ['minimum', 'maximum'] as const) {\n if (Object.hasOwn(node, keyword) && typeof node[keyword] !== 'number') {\n sink.add(pointerTo(pointer, keyword), keyword, 'must be a number');\n }\n }\n if (Object.hasOwn(node, 'description') && typeof node.description !== 'string') {\n sink.add(pointerTo(pointer, 'description'), 'description', 'must be a string');\n }\n}\n\n/**\n * The admission guard for a result-document schema. Accepts only plain JSON\n * data of at most {@link RESULT_SCHEMA_MAX_BYTES} canonical UTF-8 bytes that\n * lies inside the subset (module comment). On success, `canonical` is the\n * snapshot every party freezes and validates against.\n */\nexport function checkResultSchema(schema: unknown): ResultSchemaCheck {\n const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);\n if (!document.ok) return documentFailure(document, 'the result schema', RESULT_SCHEMA_MAX_BYTES);\n const sink = new IssueSink();\n checkSubschema(document.canonical, '', 0, sink);\n if (!sink.empty) return { ok: false, reason: 'not-subset', bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };\n return { ok: true, bytes: document.bytes, canonical: document.canonical as ResultSchema };\n}\n\n/**\n * Deep copy of pure JSON data with null-prototype objects. The library tests\n * property presence with `in`, so a prototype would make `required:\n * ['constructor']` pass on `{}`; a null prototype makes presence own-only.\n */\nfunction withoutPrototypes(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (Array.isArray(value)) return value.map(withoutPrototypes);\n const copy = Object.create(null) as Record<string, unknown>;\n for (const [key, member] of Object.entries(value)) {\n Object.defineProperty(copy, key, { value: withoutPrototypes(member), enumerable: true, writable: true, configurable: true });\n }\n return copy;\n}\n\n/** `#/a~1b/0` (the library's URI-encoded fragment) to the RFC 6901 pointer `/a~1b/0`. */\nfunction fragmentToPointer(location: string): string {\n return decodeURI(location.startsWith('#') ? location.slice(1) : location);\n}\n\n/**\n * Validate one outcome document against a result schema. The guard\n * ({@link checkResultSchema}) always runs first; a schema it refuses is\n * `schema-not-admitted` and never reaches the library. The outcome must be\n * plain JSON data of at most {@link RESULT_OUTCOME_MAX_BYTES} canonical UTF-8\n * bytes, checked before validation. On success, `canonical` is the snapshot\n * a sender stages and puts on the wire.\n */\nexport function validateResultOutcome(schema: unknown, outcome: unknown): ResultOutcomeCheck {\n const admitted = checkResultSchema(schema);\n if (!admitted.ok) {\n return { ok: false, reason: 'schema-not-admitted', bytes: admitted.bytes, issues: admitted.issues, truncated: admitted.truncated };\n }\n const document = canonicalDocument(outcome, RESULT_OUTCOME_MAX_BYTES);\n if (!document.ok) return documentFailure(document, 'the outcome', RESULT_OUTCOME_MAX_BYTES);\n\n // Short-circuit: each level stops at its first failure, so the error list\n // follows one failing path instead of growing with every failing pair.\n const validator = new Validator(withoutPrototypes(admitted.canonical) as Record<string, unknown>, '2020-12', true);\n const result = validator.validate(withoutPrototypes(document.canonical));\n if (result.valid) return { ok: true, bytes: document.bytes, canonical: document.canonical };\n\n const sink = new IssueSink();\n for (const unit of result.errors as readonly OutputUnit[]) sink.add(fragmentToPointer(unit.instanceLocation), unit.keyword, unit.error);\n return { ok: false, reason: 'schema-mismatch', bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };\n}\n\nconst MAX_BYTES_PER_CODE_POINT = 6;\n/**\n * Longest JSON.stringify of a finite double: 25, e.g. \"-0.0000012345678901234567\"\n * (fixed notation down to 1e-6 with 17 significant digits and a sign). Exponent\n * forms are at most 24 (\"-1.7976931348623157e+308\").\n */\nconst MAX_NUMBER_BYTES = 25;\n/**\n * Longest JSON.stringify of an integer-valued double: 22 in fixed notation\n * (\"-999999999999999900000\", |x| < 1e21) and 24 in exponent notation.\n */\nconst MAX_INTEGER_BYTES = 24;\n/** Below this magnitude JSON.stringify writes an integer in plain decimal digits. */\nconst DECIMAL_LIMIT = 1e21;\nconst enc = new TextEncoder();\nconst size = (v: unknown) => enc.encode(JSON.stringify(v)).length;\n\ntype Node = ResultSchema;\n\nfunction typeBound(node: Node, type: string): number | null {\n switch (type) {\n case 'null': return 4;\n case 'boolean': return 5;\n case 'integer': {\n // Tighten only when both ends are finite and below 1e21 in magnitude:\n // then every integer in range is plain decimal and its length grows with |x|.\n const lo = typeof node.minimum === 'number' ? Math.ceil(node.minimum) : undefined;\n const hi = typeof node.maximum === 'number' ? Math.floor(node.maximum) : undefined;\n if (lo === undefined || hi === undefined || !(Math.abs(lo) < DECIMAL_LIMIT) || !(Math.abs(hi) < DECIMAL_LIMIT)) return MAX_INTEGER_BYTES;\n return Math.min(MAX_INTEGER_BYTES, Math.max(String(lo).length, String(hi).length));\n }\n case 'number':\n return MAX_NUMBER_BYTES;\n case 'string':\n return typeof node.maxLength === 'number' ? 2 + MAX_BYTES_PER_CODE_POINT * node.maxLength : null;\n case 'array': {\n if (node.maxItems === 0) return 2;\n if (typeof node.maxItems !== 'number' || node.items === undefined) return null;\n const item = outcomeBound(node.items);\n return item === null ? null : 2 + node.maxItems * item + Math.max(0, node.maxItems - 1);\n }\n case 'object': {\n if (node.additionalProperties !== false) return null;\n const entries = Object.entries(node.properties ?? {});\n let total = 2 + Math.max(0, entries.length - 1);\n for (const [name, sub] of entries) {\n const b = outcomeBound(sub);\n if (b === null) return null;\n total += size(name) + 1 + b;\n }\n return total;\n }\n default: return null;\n }\n}\n\n/** Conservative upper bound in canonical UTF-8 bytes, or null when no finite bound follows from the schema. */\nfunction outcomeBound(schema: ResultSchema): number | null {\n const node = schema as Node;\n const bounds: number[] = [];\n if (Object.hasOwn(node, 'const')) bounds.push(size(node.const));\n if (Array.isArray(node.enum)) bounds.push(Math.max(...node.enum.map(size)));\n if (Array.isArray(node.oneOf)) {\n const branches = node.oneOf.map(outcomeBound);\n if (branches.every((b): b is number => b !== null)) bounds.push(Math.max(...branches));\n }\n if (node.type !== undefined) {\n const types = Array.isArray(node.type) ? node.type : [node.type];\n const each = types.map(t => typeBound(node, t));\n if (each.every((b): b is number => b !== null)) bounds.push(Math.max(...each));\n }\n return bounds.length === 0 ? null : Math.min(...bounds);\n}\n\n/**\n * Conservative canonical UTF-8 bound, or null for an invalid or unbounded schema.\n * Strings cost at most 6 bytes per code point. Number costs 25; integer costs\n * 24, tightened only when both ends have magnitude below 1e21. A bound need\n * not be attainable when constraints intersect or oneOf branches overlap.\n */\nexport function resultOutcomeMaxBytes(schema: ResultSchema): number | null {\n // Inspect data descriptors before canonicalization can invoke a callback.\n const pending: unknown[] = [schema];\n const seen = new Set<object>();\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value === 'function') return null;\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && prototype !== Array.prototype) return null;\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {\n if (name === 'toJSON' && (!Object.hasOwn(descriptor, 'value') || typeof descriptor.value === 'function')) return null;\n if (!descriptor.enumerable) continue;\n if (!Object.hasOwn(descriptor, 'value')) return null;\n pending.push(descriptor.value);\n }\n }\n const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);\n if (!document.ok) return null;\n const sink = new IssueSink();\n // A fragment can be any instance type, unlike a result-document root.\n checkSubschema(document.canonical, '', 0, sink, false);\n if (!sink.empty) return null;\n return outcomeBound(document.canonical as ResultSchema);\n}\n","import { z } from 'zod';\nimport { checkResultSchema, type ResultSchema } from './result-schema';\n\nexport const TerminalProjectionContractSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, 'terminal projection contracts must be opaque lowercase ids');\n\n/**\n * The frozen outcome schema of a result-document offer (wire v3). The value\n * is kept exactly as sent; {@link checkResultSchema} decides admission, so\n * every decode (Host submit, server/cloud parse, daemon admission) applies\n * the one subset guard and reports its capped issues.\n */\nexport const ResultDocumentSchemaSchema = z.custom<ResultSchema>().superRefine((value, ctx) => {\n const check = checkResultSchema(value);\n if (check.ok) return;\n for (const issue of check.issues) {\n ctx.addIssue({\n code: 'custom',\n message: `result schema ${check.reason} at '${issue.pointer}' (${issue.keyword}): ${issue.message}`,\n params: { reason: check.reason, pointer: issue.pointer, keyword: issue.keyword },\n });\n }\n if (check.truncated) {\n ctx.addIssue({ code: 'custom', message: 'result schema issues truncated', params: { reason: check.reason, truncated: true } });\n }\n});\n\n/** Offer-scoped authority: explicit bypass or one required structured result with its frozen schema. */\nexport const TerminalProjectionSelectionSchema = z.discriminatedUnion('mode', [\n z.object({ mode: z.literal('none') }).strict(),\n z.object({\n mode: z.literal('result-document'),\n contract: TerminalProjectionContractSchema,\n schema: ResultDocumentSchemaSchema,\n }).strict(),\n]);\nexport type TerminalProjectionSelection = z.infer<typeof TerminalProjectionSelectionSchema>;\n","import { z } from 'zod';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\nimport { AgentEgressContentHashSchema } from './agent-egress';\n\n/**\n * Remote authenticated runtime input preparation — the wire half of\n * `docs/researches/runtime-input-preparation-contract.md` §19 (channel shape)\n * and the C07 G4 design decision §17 B.\n *\n * This module owns ONLY the leaf shapes. The server -> device payload lives in\n * `messages.ts` beside every other message payload (so the one inline byte\n * bound `MAX_INLINE_BYTES` stays a single module-local authority), and the two\n * authenticated HTTP bodies live in `http-api.ts`.\n *\n * Three structural rules this surface exists to hold:\n *\n * 1. The request carries NO tools, NO tool executors and NO runtime identity.\n * Those are LOCAL observations: only the device can honestly say which MCP\n * toolsets it has, what schemas their servers publish, and which native\n * package closure is installed. A Host that could state them would be\n * stating an identity it cannot verify.\n * 2. The receipt summary discloses identities, digests, sizes, counter\n * evidence and readiness — never D, never P(D), never the snapshot. A\n * digest proves content identity; it is not a disclosure channel and not a\n * bearer token (§10.3.4).\n * 3. Every shape here is `.strict()`. This is control data: an unrecognized\n * field must be REJECTED, not silently stripped, per docs/protocol.md's\n * freeze-rule asymmetry. Adding a field post-freeze is therefore a\n * breaking change.\n */\n\nimport { PREPARED_AGENT_MEMORY_MODES } from './capability-constants';\n\n/** The preparation surface uses the package-wide lowercase `sha256:<hex>` transport form. */\nexport const InputPreparationContentHashSchema = AgentEgressContentHashSchema;\n\n/**\n * Opaque, non-empty, single-line control identifiers (policy revision, profile\n * id, model id, reference, digest, ...). The SDK never interprets these; it\n * only refuses values that could not survive being a key, a log line or a\n * pathname component.\n */\nconst OPAQUE_ID = z\n .string()\n .min(1)\n .max(512)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'control identifiers must not contain control characters');\n\n/** Longer opaque text that is still one line — base URLs, method names, endpoints. */\nconst OPAQUE_TEXT = z\n .string()\n .min(1)\n .max(2048)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'control text must not contain control characters');\n\n/**\n * The operator-assigned limits-policy revision a device must already hold. The\n * SDK compares it for exact equality and never negotiates it: a device whose\n * configured revision differs rejects rather than preparing under a policy the\n * caller believed was in force.\n */\nexport const InputPreparationPolicyRevisionSchema = OPAQUE_ID;\n\n/**\n * Host-owned Profile identity. It rides beside `agentRef` rather than inside\n * it because `AgentRefSchema` is the frozen generic Agent identity shared by\n * every other message, and widening that would be a breaking change to all of\n * them. The device never trusts this value directly — its configured local\n * authority resolver validates it against trusted local Profile records before\n * anything is compiled.\n */\nexport const InputPreparationProfileIdSchema = OPAQUE_ID;\n\n/** Explicit prepared SDK memory selection; never defaulted. */\nexport const PreparedAgentMemoryModeSchema = z.enum(PREPARED_AGENT_MEMORY_MODES);\nexport type PreparedAgentMemoryMode = z.infer<typeof PreparedAgentMemoryModeSchema>;\n\n\n// ---------------------------------------------------------------------------\n// Source / selection\n// ---------------------------------------------------------------------------\n\n/**\n * The canonical Host source snapshot this input was assembled from. Both\n * values are Host authority carried verbatim so the receipt binds the exact\n * revision/digest a later consumer must re-present. The SDK interprets\n * neither.\n */\nexport const InputPreparationSourceSchema = z\n .object({ revision: OPAQUE_ID, digest: OPAQUE_ID })\n .strict();\nexport type InputPreparationSource = z.infer<typeof InputPreparationSourceSchema>;\n\nexport const InputPreparationModelCostSchema = z\n .object({\n input: z.number().finite(),\n output: z.number().finite(),\n cacheRead: z.number().finite(),\n cacheWrite: z.number().finite(),\n })\n .strict();\n\n/**\n * One provider-side effort token, or `null` where the model supports no such\n * level.\n *\n * This shape and the `compat` shape below are RESTATED from the device-local\n * authority (`packages/keys/src/pi-model-config.ts`'s `PiModelConfigSchema`)\n * rather than imported: the release graph\n * (`scripts/release/check-package-graph.mjs`) keeps `@byok-sdk/keys` and the\n * dispatch packages disjoint, exactly as `provider-profile.ts`'s\n * `PROVIDER_PROFILE_REF_PATTERN` is restated for the wire. The two definitions\n * are pinned equal by a test that can see both\n * (`packages/client/src/__tests__/input-preparation-model-parity.test.ts`), so\n * a drift is a failing check rather than a silently narrower wire.\n */\nconst THINKING_EFFORT = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-zA-Z0-9_-]+$/u)\n .nullable();\n\n/**\n * The complete level -> effort mapping the launched model declares. All seven\n * keys are required and no other key is admitted: a partial map would be a map\n * whose missing levels someone downstream had to invent.\n */\nconst InputPreparationThinkingLevelMapSchema = z\n .object({\n off: THINKING_EFFORT,\n minimal: THINKING_EFFORT,\n low: THINKING_EFFORT,\n medium: THINKING_EFFORT,\n high: THINKING_EFFORT,\n xhigh: THINKING_EFFORT,\n max: THINKING_EFFORT,\n })\n .strict();\n\n/**\n * The declared request-body compatibility flags of the launched model.\n *\n * Every member is optional and NOTHING here is defaulted: an absent flag means\n * the configuration declared none, which is a different fact from declaring\n * `false`, and the native compiler owns what an absent flag does.\n */\nconst InputPreparationModelCompatSchema = z\n .object({\n supportsStore: z.boolean().optional(),\n supportsDeveloperRole: z.boolean().optional(),\n supportsReasoningEffort: z.boolean().optional(),\n supportsUsageInStreaming: z.boolean().optional(),\n maxTokensField: z.enum(['max_completion_tokens', 'max_tokens']).optional(),\n thinkingFormat: z\n .enum([\n 'openai',\n 'openrouter',\n 'deepseek',\n 'together',\n 'baseten',\n 'zai',\n 'qwen',\n 'chat-template',\n 'qwen-chat-template',\n 'string-thinking',\n 'ant-ling',\n ])\n .optional(),\n zaiToolStream: z.boolean().optional(),\n })\n .strict();\n\n/**\n * The exact model identity the request compiles for.\n *\n * `api` is a single literal, not an open enum: `openai-completions` is the one\n * API the frozen B-P1 native validator admits, and widening it is a\n * registration, not a parser relaxation.\n *\n * `thinkingLevelMap` and `compat` are the two body-affecting declarations a\n * locally configured provider profile projects into the model entry the runtime\n * is launched with. They are OPTIONAL because a model configuration may declare\n * neither, and absent stays absent on every carrier: nothing here defaults,\n * coerces or infers one, since a preparation whose model gained a field on the\n * way through would no longer equal the session model it was counted for.\n */\nexport const InputPreparationModelSchema = z\n .object({\n id: OPAQUE_ID,\n name: OPAQUE_ID,\n api: z.literal('openai-completions'),\n provider: OPAQUE_ID,\n baseUrl: OPAQUE_TEXT,\n reasoning: z.boolean(),\n input: z.array(z.enum(['text', 'image'])).min(1).max(8),\n cost: InputPreparationModelCostSchema,\n contextWindow: z.number().int().positive(),\n maxTokens: z.number().int().positive(),\n thinkingLevelMap: InputPreparationThinkingLevelMapSchema.optional(),\n compat: InputPreparationModelCompatSchema.optional(),\n })\n .strict();\nexport type InputPreparationModel = z.infer<typeof InputPreparationModelSchema>;\n\n/**\n * Body-affecting options only. Transport options are deliberately not on this wire.\n *\n * `toolChoice` admits `auto` and `none` and nothing else: the native prepared\n * boundary compiles through the simple stream path, which cannot express\n * `required`, so a Host stating it would be stating an option no compiler on\n * the other side can produce. It is refused HERE, by the schema, rather than\n * surviving to a native refusal nobody can read.\n *\n * `reasoningEffort` names a requested thinking level. The native compiler maps\n * it through the launched model's own level map and clamps it exactly as the\n * live session does, so the effort token that reaches the body is the model's,\n * never this value verbatim.\n */\nexport const InputPreparationOptionsSchema = z\n .object({\n cacheRetention: z.enum(['none', 'short', 'long']),\n maxTokens: z.number().int().positive(),\n temperature: z.number().finite().optional(),\n toolChoice: z.enum(['auto', 'none']).optional(),\n reasoningEffort: z.enum(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']).optional(),\n })\n .strict();\nexport type InputPreparationOptions = z.infer<typeof InputPreparationOptionsSchema>;\n\nexport const InputPreparationSelectionSchema = z\n .object({ model: InputPreparationModelSchema, options: InputPreparationOptionsSchema })\n .strict();\nexport type InputPreparationSelection = z.infer<typeof InputPreparationSelectionSchema>;\n\n// ---------------------------------------------------------------------------\n// Context document — the Host-authorized half of the compiled snapshot\n// ---------------------------------------------------------------------------\n\n/** Complete Host-authored prompt. No Pi renderer or device-local input is consulted. */\nexport const InputPreparationPromptSnapshotSchema = z.object({ systemPrompt: z.string() }).strict();\n\n/**\n * One model-visible user message. Text-only: multimodal content and any extra\n * field are not inferred, they reject.\n */\nexport const InputPreparationUserMessageSchema = z\n .object({\n role: z.literal('user'),\n content: z.string(),\n timestamp: z.number().int(),\n })\n .strict();\n\n/**\n * One host-canonical assistant text message.\n *\n * A different fact from a provider-generated assistant turn: the host asserts\n * this text was already said, and nothing generated it here. It carries no\n * `api`, `provider`, `model`, `usage` or `stopReason`, and `.strict()` is what\n * keeps one from being fabricated on the way in — an assistant message with\n * provenance fields, or without the `origin` discriminant, is a claim this\n * surface cannot check, so it rejects rather than being narrowed to one it can.\n */\nexport const InputPreparationHostCanonicalAssistantMessageSchema = z\n .object({\n role: z.literal('assistant'),\n origin: z.literal('host_canonical'),\n content: z.string(),\n timestamp: z.number().int(),\n })\n .strict();\n\n/**\n * The whole support set a caller may state: text-only user history,\n * host-canonical assistant text history, and the current user message.\n *\n * A discriminated union on `role`, so an unsupported kind is refused by name\n * rather than by a shape error on whichever member happened to be tried first.\n * Provider-generated assistant turns, tool-result history and multimodal\n * content are not members and are not inferred; adding one is a registration\n * here AND in the device's hand-written parse, never a relaxation of either.\n */\nexport const InputPreparationMessageSchema = z.discriminatedUnion('role', [\n InputPreparationUserMessageSchema,\n InputPreparationHostCanonicalAssistantMessageSchema,\n]);\nexport type InputPreparationMessage = z.infer<typeof InputPreparationMessageSchema>;\n\n/**\n * What `context.inline` (or the referenced blob) decodes to.\n *\n * Deliberately NOT the whole compiled snapshot: `tools` is absent because the\n * device adds it from its own MCP observation. A Host that could send `tools`\n * could claim a toolset the device does not have.\n */\nexport const InputPreparationContextDocumentSchema = z\n .object({\n prompt: InputPreparationPromptSnapshotSchema,\n messages: z.array(InputPreparationMessageSchema).max(4096),\n })\n .strict();\nexport type InputPreparationContextDocument = z.infer<typeof InputPreparationContextDocumentSchema>;\n\n// ---------------------------------------------------------------------------\n// Receipt summary — the only thing a completion discloses about the artifact\n// ---------------------------------------------------------------------------\n\n/**\n * Durable lifecycle state of one local preparation record.\n *\n * `prepared` is the one successful terminal state: the artifact is compiled,\n * persisted, and — when the device has an optional counter configured — its\n * counter answered. A device with no counter reaches `prepared` without ever\n * entering `counting`.\n */\nexport const InputPreparationStateSchema = z.enum([\n 'reserved',\n 'counting',\n 'prepared',\n 'cancelled',\n 'failed',\n 'counter_interrupted',\n]);\nexport type InputPreparationState = z.infer<typeof InputPreparationStateSchema>;\n\n/**\n * Why a receipt is not ready. An empty list is the only thing that makes\n * `ready` true.\n *\n * `ready` means the preparation CAN BE CONSUMED — the artifact is intact and\n * unexpired, the native compiler's projection is content-complete, every\n * residual key is ruled by an applicable Host accounting policy, D is text\n * only, and — only when the device has an\n * optional counter configured — that count is provider-authoritative and\n * covered. No count is required: the size evidence is\n * `artifact.requestBytes`, the exact byte length of the frozen D. It is\n * deliberately NOT Host budget admission: the device performs no budget\n * arithmetic, so a ready receipt says the evidence holds, never that the\n * spend fits a window.\n */\nexport const InputPreparationReadinessReasonSchema = z.enum([\n /** The record has not reached `prepared` (it is `reserved` or `counting`). */\n 'not_prepared',\n 'counter_interrupted',\n 'cancelled',\n 'failed',\n 'artifact_expired',\n /** A counter IS present and its authority is not `provider` (a fixture never reaches ready). */\n 'counter_authority_not_production',\n /** A counter IS present and it reported its projection as not covered. */\n 'counter_coverage_incomplete',\n /**\n * D, the frozen provider request, carries a message content part whose\n * `type` is not `text`. The first release admits text-only D; a multimodal\n * part is not sized by `requestBytes` in any way the Host's ruling covers.\n */\n 'request_content_not_text',\n /** The native compiler's projection kind is not `content_complete`. */\n 'projection_unknown',\n /** The artifact carries a residual key the accounting policy does not rule on. */\n 'residual_not_ruled',\n /** The request named no accounting policy. There is no default. */\n 'accounting_policy_missing',\n /** The named policy was ruled for a different runtime, endpoint or model. */\n 'accounting_policy_inapplicable',\n /**\n * The record was prepared against a runtime contract this build no longer\n * speaks: its binding declares a prepared-compiler version other than the one\n * this build prepares and consumes against. The artifact is not re-read\n * through the current contract and is not translated — a projection frozen\n * under another compiler's classification table is evidence about a request\n * this build cannot re-derive.\n */\n 'runtime_contract_superseded',\n]);\nexport type InputPreparationReadinessReason = z.infer<typeof InputPreparationReadinessReasonSchema>;\n\n/**\n * Runtime/compiler identity derived from the VERIFIED installed package\n * closure on the device. A Host never states it and cannot override it.\n */\nexport const InputPreparationRuntimeIdentitySchema = z\n .object({\n packageName: OPAQUE_ID,\n packageVersion: OPAQUE_ID,\n tarballIntegrity: z.string().regex(/^sha512-[A-Za-z0-9+/]+={0,2}$/u),\n provenanceDigest: z.string().regex(/^[0-9a-f]{64}$/u),\n closureDigest: z.string().regex(/^[0-9a-f]{64}$/u),\n upstreamCommit: OPAQUE_ID,\n envelopeFormat: OPAQUE_ID,\n requestFormat: OPAQUE_ID,\n compilerVersion: z.number().int().nonnegative(),\n })\n .strict();\nexport type InputPreparationRuntimeIdentity = z.infer<typeof InputPreparationRuntimeIdentitySchema>;\n\nexport const InputPreparationCounterTargetSchema = z\n .object({ endpoint: OPAQUE_TEXT, modelId: OPAQUE_ID })\n .strict();\n\n/**\n * The Host's ruling about which residual keys of D its accounting already\n * accounts for.\n *\n * Host authority, carried verbatim. The device performs exactly one check\n * against it — APPLICABILITY — and never any budget arithmetic: every residual\n * key the artifact carries must be named here, and the ruling must have been\n * made for this preparation's own runtime identity and endpoint/model. There\n * is no default: a request that names none produces a receipt carrying\n * `accounting_policy_missing`, because \"nobody ruled\" and \"everything is\n * ruled\" are different facts.\n */\nexport const InputPreparationAccountingPolicyRefSchema = z\n .object({\n revision: OPAQUE_ID,\n /** The runtime identity string this ruling was made for. */\n ruledRuntime: OPAQUE_ID,\n /** The endpoint/model this ruling was made for. */\n ruledTarget: InputPreparationCounterTargetSchema,\n /** Every residual key the Host's accounting already accounts for. */\n ruledResidualKeys: z.array(OPAQUE_ID).max(64),\n })\n .strict();\nexport type InputPreparationAccountingPolicyRef = z.infer<typeof InputPreparationAccountingPolicyRefSchema>;\n\n/**\n * What the provider side of a count asserted, and which exact projection it\n * was asserted about.\n *\n * Required, fixture included: a number without the identity of the bytes it\n * was taken over is not evidence. The device compares `projectionDigest`\n * against the artifact's own projection digest and `endpoint`/`modelId`\n * against the counted target, and refuses the count outright on a mismatch.\n *\n * `asserted` is the provider's own answer, stored and never second-guessed —\n * re-deriving a usage number locally is the shadow accounting this surface\n * exists to avoid. It carries no output or whole-request field: the Host holds\n * its own request, and `binding.requestDigest` is the check that ties the two.\n */\nexport const InputPreparationCounterProviderEvidenceSchema = z\n .object({\n projectionDigest: z.string().regex(/^[0-9a-f]{64}$/u, 'a projection digest is lowercase sha-256 hex'),\n endpoint: OPAQUE_TEXT,\n modelId: OPAQUE_ID,\n asserted: z\n .object({\n httpStatus: z.number().int(),\n usageFields: z.record(OPAQUE_ID, z.number().finite()),\n responseDigest: OPAQUE_ID,\n })\n .strict(),\n })\n .strict();\n\n/**\n * Counter evidence exactly as the device's OPTIONAL adapter reported it.\n * Absent when the device has no counter configured, which is a legal, ready-\n * capable state: the size evidence is `artifact.requestBytes`.\n *\n * `authority: 'test_fixture'` is a first-class value, not a debug flag: a\n * fixture result can never produce a ready receipt, which is what keeps an\n * offline suite from ever looking like production accounting evidence.\n */\nexport const InputPreparationCounterEvidenceSchema = z\n .object({\n method: OPAQUE_ID,\n methodVersion: OPAQUE_ID,\n authority: z.enum(['provider', 'test_fixture']),\n value: z.number().int().nonnegative(),\n coverage: z\n .object({ covered: z.boolean(), reason: z.string().max(512).optional() })\n .strict(),\n providerEvidence: InputPreparationCounterProviderEvidenceSchema,\n target: InputPreparationCounterTargetSchema,\n calledAt: z.iso.datetime({ offset: true }),\n completedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\n\n/**\n * What the native compiler proved about ONE top-level key of D that lies\n * outside P(D).\n *\n * These classes describe STRUCTURE and nothing else. No class states, implies\n * or denies that a key influences a provider's token count — that is an\n * external accounting fact the compiler cannot prove — which is exactly why\n * the device re-derives nothing from them and routes the question to the\n * Host's own {@link InputPreparationAccountingPolicyRefSchema}.\n */\nexport const InputPreparationResidualValueClassSchema = z.enum([\n 'constant',\n 'boolean',\n 'bounded_integer',\n 'bounded_number',\n 'finite_number',\n 'closed_enum',\n 'nonempty_string',\n 'object_shape',\n]);\nexport type InputPreparationResidualValueClass = z.infer<typeof InputPreparationResidualValueClassSchema>;\n\nexport const InputPreparationResidualKeySchema = z\n .object({ key: OPAQUE_ID, valueClass: InputPreparationResidualValueClassSchema })\n .strict();\n\n/**\n * What the native compiler proves about P(D), copied verbatim off the envelope.\n *\n * `content_complete` — every context-derived byte of D is byte-identically\n * inside P(D), and every remaining top-level key was classified. `unknown` —\n * the compiler failed closed, claims nothing, and leaves `residual` empty.\n *\n * `digest` is sha-256 over the exact counted-projection bytes. The device\n * recomputes it and refuses the artifact on a mismatch; it never recomputes\n * the KIND, because the classification table belongs to the compiler and a\n * local copy of it would be a shadow parser for the same semantic fact.\n */\nexport const InputPreparationProjectionSchema = z\n .object({\n version: z.literal(3),\n kind: z.enum(['content_complete', 'unknown']),\n digest: z.string().regex(/^[0-9a-f]{64}$/u, 'a projection digest is lowercase sha-256 hex'),\n })\n .strict();\n\n/**\n * Identities, sizes and the native compiler's structural projection contract.\n * Never D, never P(D), never the snapshot.\n *\n * The three tool-surface fields are what make drift between preparation and\n * launch checkable rather than assumed:\n *\n * - `observationDigest` binds everything the device OBSERVED — the projected\n * tools and their executor fingerprints — so a launch whose live\n * observation differs is a different manifest, whatever the schemas say.\n * - `toolBindingDigest` binds only the facts that can be re-derived WITHOUT\n * spawning a server: the toolset definition revisions and the configured\n * argv. It is what a replay of an already-recorded requestId compares\n * against, because re-probing to detect drift would be the second executor\n * fact the idempotency key exists to prevent.\n * - `toolNames` lists the counted model-visible tool names, sorted. A launch\n * that registers a different set can name the tool that appeared or\n * vanished.\n */\nexport const InputPreparationArtifactSummarySchema = z\n .object({\n requestDigest: OPAQUE_ID,\n envelopeDigest: OPAQUE_ID,\n toolManifestDigest: OPAQUE_ID,\n /**\n * The exact UTF-8 byte length of the frozen provider request D, measured\n * by the device's own compiler. The ONE size evidence a receipt carries:\n * the Host rules the budget (`requestBytes + C + max_tokens <= window`)\n * against it. Never a token count and never an estimate.\n */\n requestBytes: z.number().int().nonnegative(),\n projectionBytes: z.number().int().nonnegative(),\n projection: InputPreparationProjectionSchema,\n residual: z.array(InputPreparationResidualKeySchema).max(64),\n observationDigest: OPAQUE_ID,\n toolBindingDigest: OPAQUE_ID,\n toolNames: z.array(OPAQUE_ID),\n })\n .strict();\n\n/** The immutable binding a receipt carries and a later consumer must re-present. */\nexport const InputPreparationBindingSchema = z\n .object({\n terminalProjection: TerminalProjectionSelectionSchema.optional(),\n agentMemory: PreparedAgentMemoryModeSchema,\n scopeId: OPAQUE_ID,\n deviceId: OPAQUE_ID,\n agentRef: OPAQUE_ID,\n profileId: OPAQUE_ID,\n profileRevision: OPAQUE_ID,\n source: InputPreparationSourceSchema,\n target: InputPreparationCounterTargetSchema,\n policyRevision: OPAQUE_ID,\n runtime: InputPreparationRuntimeIdentitySchema,\n requestDigest: OPAQUE_ID,\n /**\n * The Host's accounting ruling this preparation was requested under,\n * copied verbatim. Absent when the request named none — never filled in,\n * and never narrowed to one the device would have chosen.\n */\n accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional(),\n })\n .strict();\n\n/**\n * The exact receipt projection a device reports back.\n *\n * `reference` names the record inside the device-local authenticated scope\n * that created it. It is not a capability: local lookup re-resolves authority\n * on every call and derives the record key from the trusted grant.\n */\nexport const InputPreparationReceiptSummarySchema = z\n .object({\n reference: OPAQUE_ID,\n state: InputPreparationStateSchema,\n binding: InputPreparationBindingSchema,\n artifact: InputPreparationArtifactSummarySchema.optional(),\n counter: InputPreparationCounterEvidenceSchema.optional(),\n ready: z.boolean(),\n readinessReasons: z.array(InputPreparationReadinessReasonSchema).max(16),\n detail: OPAQUE_ID.optional(),\n artifactExpiresAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((value, ctx) => {\n // `ready` is a derived fact, never an independently asserted one. Letting\n // the two disagree on the wire would make a not-ready receipt admissible\n // by simply flipping a boolean.\n if (value.ready !== (value.readinessReasons.length === 0)) {\n ctx.addIssue({\n code: 'custom',\n path: ['ready'],\n message: 'ready must be true exactly when readinessReasons is empty',\n });\n }\n });\nexport type InputPreparationReceiptSummary = z.infer<typeof InputPreparationReceiptSummarySchema>;\n\n// ---------------------------------------------------------------------------\n// Offer binding — what a prepared Execution names on the offer wire\n// ---------------------------------------------------------------------------\n\n/**\n * The device-local reference one receipt answered with\n * ({@link InputPreparationReceiptSummarySchema}'s `reference`).\n *\n * The same opaque identifier, spelled as its own schema so the offer wire and\n * the receipt wire cannot drift into two definitions of one value. It is NOT a\n * capability: the device re-resolves authority on every lookup and derives the\n * record key from its own trusted grant, so presenting another scope's\n * reference finds nothing.\n */\nexport const InputPreparationReferenceSchema = OPAQUE_ID;\n\n/**\n * The preparation a prepared `task.offer` names, re-presented by the Host from\n * the receipt it was given.\n *\n * Nothing here is authority. Every value is COMPARED against the device's own\n * durable record before an Execution is admitted, and a difference declines the\n * offer non-retryably — a Host that could state a binding would be stating what\n * this device counted.\n *\n * `artifactDigest` is optional for one structural reason, not as a compatibility\n * seam: a receipt discloses `artifact` only once there is one\n * ({@link InputPreparationArtifactSummarySchema} is optional on the receipt), so\n * a Host holding a not-yet-prepared receipt has no envelope digest to re-present.\n * When it is present it is compared like everything else.\n */\nexport const InputPreparationOfferBindingSchema = z\n .object({\n reference: InputPreparationReferenceSchema,\n /** `InputPreparationBindingSchema.requestDigest`, as the receipt reported it. */\n requestDigest: OPAQUE_ID,\n /** `InputPreparationArtifactSummarySchema.envelopeDigest`, when the receipt carried one. */\n artifactDigest: OPAQUE_ID.optional(),\n })\n .strict();\nexport type InputPreparationOfferBinding = z.infer<typeof InputPreparationOfferBindingSchema>;\n\n/**\n * Why a device refused to prepare at all. These are the device-owned typed\n * rejections; none of them ever accompanies an artifact.\n *\n * `input_preparation_unconfigured` is the answer from a device that advertised\n * nothing: the whole surface is off there. It is reported rather than thrown so\n * one mis-targeted request cannot freeze the device's mailbox cursor behind it.\n */\nexport const InputPreparationRejectionReasonSchema = z.enum([\n 'input_preparation_unconfigured',\n 'bad_request',\n 'authority_unavailable',\n 'scope_denied',\n 'policy_revision_mismatch',\n 'runtime_identity_unavailable',\n 'unsupported_input',\n 'limit_exceeded',\n 'request_conflict',\n 'not_found',\n 'counter_unavailable',\n 'counter_interrupted',\n 'durable_write_failed',\n 'cancelled',\n 'context_unresolvable',\n 'context_hash_mismatch',\n 'toolsets_unobservable',\n 'deadline_elapsed',\n /**\n * A repeat of an already-recorded `requestId` arrived after the facts its\n * executor fingerprints were frozen against changed — a toolset definition\n * revision or a configured server argv. The recorded receipt is not re-derived and no\n * server is re-probed; the repeat is refused so the caller mints a new\n * preparation instead of silently receiving one bound to stale evidence.\n */\n 'observation_drift',\n /**\n * The device compiled the input, then found that the `prompt_prepared` frame\n * the runtime would have to be handed exceeds the single-frame byte cap that\n * runtime enforces. The bound belongs to the runtime, not to the operator's\n * retention policy, so it is decided first and nothing is retained: a\n * preparation that could never be delivered is not a smaller preparation.\n */\n 'rpc_frame_too_large',\n /**\n * The device's input-preparation lane is off because its durable record log\n * holds a record from an older record schema version. The rest of the\n * device runs; this lane refuses until an operator archives that log. No\n * record is migrated, read forward or deleted.\n */\n 'input_preparation_record_log_unsupported',\n]);\nexport type InputPreparationRejectionReason = z.infer<typeof InputPreparationRejectionReasonSchema>;\n","import { z } from 'zod';\nimport { BlobRefSchema } from './blob';\nimport { TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH } from './constants';\n\n/**\n * Maximum UTF-16 length of {@link AgentEventSpillSchema}'s `unstoredReason`.\n * The reason is a bounded diagnostic string, not a place to inline the\n * content that failed to store: the whole point of a spill descriptor is\n * that the event stays under the daemon's inline-event cap even when the\n * blob upload failed.\n */\nexport const AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH = 512;\n\n/**\n * Additive descriptor attached to a `tool_use` / `tool_result` event whose\n * `input` / `output` was too large to travel inline and was therefore\n * REPLACED, at the daemon's ingestion boundary, by a bounded head/tail\n * preview (`{ preview: { head, tail } }`). See\n * `packages/client/src/daemon/event-spill.ts` for the producer and\n * `DaemonConfig.maxInlineEventBytes` for the cap.\n *\n * Presence of this field is the ONLY signal that the inline field is a\n * projection rather than the whole value — a consumer that reads\n * `tool_result.output` (or `tool_use.input`) without checking `spill` is\n * reading a preview and calling it the result.\n *\n * Exactly one of `blob` / `unstoredReason` is present, and the union is\n * closed on purpose:\n *\n * - `blob` — the full `JSON.stringify(<field>)` bytes are readable from the\n * blob plane (protocol §7) under that `BlobRef`; `contentHash` is the\n * sha256 of exactly those bytes, so a consumer can verify what it read\n * back is what was omitted.\n * - `unstoredReason` — the omitted bytes are not readable from this event:\n * either the upload failed, or it succeeded but the returned locator did\n * not fit the daemon's inline cap. Either way the content is not reachable\n * through this event; the reason says which. This exists so an unreadable\n * omission is observable rather than silently indistinguishable from a\n * small output.\n *\n * `.strict()` because this is an SDK-authored descriptor with a closed\n * shape, not free-form runtime data: an unrecognized key here means a\n * producer and a consumer disagree about what the omission means, which is\n * exactly the case that must fail loudly.\n */\nexport const AgentEventSpillSchema = z\n .object({\n /** Which field of the event was replaced by a preview. */\n field: z.enum(['input', 'output']),\n /** UTF-8 byte length of the full `JSON.stringify(<field>)` that was spilled. */\n totalBytes: z.number().int().nonnegative(),\n /** `totalBytes` minus the UTF-8 bytes of the retained preview head + tail. */\n omittedBytes: z.number().int().nonnegative(),\n /** Always the JSON serialization of the field — never the tool's own notion of a content type. */\n contentType: z.literal('application/json'),\n /** Where the omitted bytes are readable. Mutually exclusive with `unstoredReason`. */\n blob: BlobRefSchema.optional(),\n /** Why the omitted bytes are NOT readable. Mutually exclusive with `blob`. */\n unstoredReason: z.string().min(1).max(AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH).optional(),\n })\n .strict()\n .refine(\n (spill) => (spill.blob === undefined) !== (spill.unstoredReason === undefined),\n 'spill must carry exactly one of blob (the omitted bytes are readable) or unstoredReason (they are not)',\n );\n\nexport type AgentEventSpill = z.infer<typeof AgentEventSpillSchema>;\n\n/**\n * Normalized event shape that every runtime adapter (pi / claude / codex)\n * translates its native JSONL output into. This is the interior of a\n * `task.progress` payload's `events` array.\n */\nexport const AgentEventSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('progress'), text: z.string() }),\n z.object({\n type: z.literal('tool_use'),\n tool: z.string(),\n /** Authoritative MCP identity, absent when the adapter cannot resolve it. */\n mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),\n input: z.unknown().optional(),\n toolCallId: z.string().regex(/\\S/, 'toolCallId must contain a non-whitespace character').optional(),\n /** Present only when `input` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */\n spill: AgentEventSpillSchema.optional(),\n }),\n z.object({\n type: z.literal('tool_result'),\n tool: z.string(),\n /** Authoritative MCP identity, absent when the adapter cannot resolve it. */\n mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),\n output: z.unknown().optional(),\n toolCallId: z.string().regex(/\\S/, 'toolCallId must contain a non-whitespace character').optional(),\n isError: z.boolean().optional(),\n /** Present only when `output` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */\n spill: AgentEventSpillSchema.optional(),\n }),\n z.object({ type: z.literal('artifact'), name: z.string(), contentType: z.string() }),\n z.object({ type: z.literal('turn_end') }),\n z.object({ type: z.literal('error'), message: z.string() }),\n /**\n * Token usage reported by a runtime turn — maps from codex\n * `turn.completed.usage` and claude `result` usage (adapters wired up in a\n * later wave; this is just the variant + schema). All fields optional\n * because runtimes report different subsets.\n */\n z.object({\n type: z.literal('usage'),\n inputTokens: z.number().int().nonnegative().optional(),\n cachedInputTokens: z.number().int().nonnegative().optional(),\n outputTokens: z.number().int().nonnegative().optional(),\n reasoningTokens: z.number().int().nonnegative().optional(),\n totalTokens: z.number().int().nonnegative().optional(),\n // Context occupancy is independent of provider cost counters. Unknown stays absent.\n contextTokens: z.number().int().nonnegative().optional(),\n contextWindow: z.number().int().positive().optional(),\n contextSource: z.enum(['provider', 'estimate']).optional(),\n // Served model as the runtime reported it, never the requested id.\n model: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),\n }),\n]);\n\nexport type AgentEvent = z.infer<typeof AgentEventSchema>;\n\n/**\n * Known AgentEvent variant type discriminators — DERIVED directly from\n * {@link AgentEventSchema}'s own discriminated-union variants via\n * `z.toJSONSchema`, rather than hand-maintained as a second literal list.\n * This used to be a standalone array kept in sync with the schema above by\n * hand (dual authority); the freeze guard\n * (`__tests__/freeze-guard.test.ts`'s \"dual-authority cross-check\") already\n * asserted the two matched using this EXACT SAME `z.toJSONSchema` extraction\n * mechanism, which is why deriving it this way is safe: the guard already\n * proved this extraction produces the identical set the hand-written list\n * held. With the derivation below, the two can no longer drift apart at\n * all — there is only one authority now, {@link AgentEventSchema} itself.\n * The freeze guard test is kept anyway (now definitionally true rather than\n * a live check) as a regression net in case a future refactor reintroduces a\n * hand-written list.\n *\n * Exported (not module-private) so {@link isKnownAgentEvent} /\n * {@link partitionAgentEvents} (and the freeze guard) can check against the\n * exact same set without each reaching into zod's discriminated-union\n * internals directly. `z.toJSONSchema`'s output shape here (`.oneOf[].\n * properties.type.const`) is a public, documented zod v4 API — not\n * reaching into `._def`/internal fields — same as the freeze guard already\n * relies on.\n */\nexport const KNOWN_AGENT_EVENT_TYPES: readonly string[] = (\n z.toJSONSchema(AgentEventSchema) as unknown as { oneOf: Array<{ properties: { type: { const: string } } }> }\n).oneOf.map((branch) => branch.properties.type.const);\n\n/**\n * Pre-freeze compatibility widening (the freeze blocker this schema fixes):\n * an unknown-type event — one a future runtime/protocol minor version\n * introduces — parses as an opaque passthrough placeholder instead of\n * hard-failing the entire `task.progress` batch it arrived in. Without this,\n * `TaskProgressPayloadSchema.events: z.array(AgentEventSchema)` would throw\n * on the whole array the moment one event had an unrecognized `type`, which\n * made the wire's \"additive new variants are non-breaking\" promise false for\n * the installed base — and unfixable post-freeze.\n *\n * The `.refine` guard is load-bearing, not decorative: it excludes every\n * KNOWN type literal, so a *malformed* known variant (e.g. `progress`\n * missing `text`) still fails validation instead of silently matching this\n * fallback. Tolerance is only for unknown TYPES, never for malformed known\n * ones — see {@link AgentEventOrUnknownSchema}, which is what actually\n * combines this with {@link AgentEventSchema} for real use.\n *\n * Deliberately asymmetric with envelope-level control/security fields\n * (`instruction` — see `messages.ts`), which stay\n * fail-closed on unknown shapes with no equivalent widening: this tolerance\n * applies only to observability data (agent progress events), never to\n * control/security surfaces. That asymmetry is the freeze rule.\n */\nexport const UnknownAgentEventSchema = z\n .object({ type: z.string() })\n .passthrough()\n .refine(\n (event) => !KNOWN_AGENT_EVENT_TYPES.includes(event.type),\n 'type refers to a known AgentEvent variant; malformed known variants must fail through AgentEventSchema, not fall back to unknown-tolerance',\n );\n\nexport type UnknownAgentEvent = z.infer<typeof UnknownAgentEventSchema>;\n\n/**\n * The actual element schema for `TaskProgressPayloadSchema.events`\n * (`messages.ts`): a known, fully-typed {@link AgentEvent} OR an opaque\n * unknown-type placeholder. `z.union` (not `discriminatedUnion`) is required\n * here because the fallback branch matches on \"not one of the known\n * literals\", which a discriminated union can't express directly.\n */\nexport const AgentEventOrUnknownSchema = z.union([AgentEventSchema, UnknownAgentEventSchema]);\n\nexport type AgentEventOrUnknown = z.infer<typeof AgentEventOrUnknownSchema>;\n\n/**\n * Type guard distinguishing a known, fully-typed {@link AgentEvent} from an\n * {@link UnknownAgentEvent} passthrough placeholder.\n */\nexport function isKnownAgentEvent(event: AgentEventOrUnknown): event is AgentEvent {\n return KNOWN_AGENT_EVENT_TYPES.includes(event.type);\n}\n\n/**\n * Split a `task.progress` events array into known (typed, actionable) and\n * unknown (opaque, safe-to-skip) events. Consumers should process `known`\n * and skip `unknown` rather than throwing on it — that's the point of the\n * pre-freeze tolerance above.\n */\nexport function partitionAgentEvents(events: readonly AgentEventOrUnknown[]): {\n known: AgentEvent[];\n unknown: UnknownAgentEvent[];\n} {\n const known: AgentEvent[] = [];\n const unknown: UnknownAgentEvent[] = [];\n for (const event of events) {\n if (isKnownAgentEvent(event)) {\n known.push(event);\n } else {\n unknown.push(event);\n }\n }\n return { known, unknown };\n}\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema } from './agent-egress';\n\n/** Maximum UTF-8 encoded JSON bytes carried by one projection payload. */\nexport const AGENT_HOME_PROJECTION_MAX_BYTES = 64 * 1024;\n\n/** PostgreSQL BIGINT maximum, kept as decimal text to avoid JavaScript precision loss. */\nexport const AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM = '9223372036854775807' as const;\n\n/**\n * Canonical positive decimal Profile revision for this projection contract.\n *\n * This deliberately stays local to the projection contract: the generic\n * AgentRef used by existing task and egress messages remains opaque. Values\n * cross the JavaScript/PostgreSQL boundary as text and are compared\n * lexically after canonical syntax validation.\n */\nexport const AgentHomeProjectionProfileRevisionSchema = z\n .string()\n .regex(/^[1-9][0-9]{0,18}$/u, 'profileRevision must be a canonical positive decimal string')\n .refine(\n (value) =>\n value.length < AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM.length ||\n value <= AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM,\n `profileRevision must not exceed PostgreSQL BIGINT maximum ${AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM}`,\n );\nexport type AgentHomeProjectionProfileRevision = z.infer<typeof AgentHomeProjectionProfileRevisionSchema>;\n\n/** The projection hash uses the package-wide lowercase SHA-256 transport form. */\nexport const AgentHomeProjectionHashSchema = AgentEgressContentHashSchema;\nexport type AgentHomeProjectionHash = z.infer<typeof AgentHomeProjectionHashSchema>;\n\n/** Terminal local-apply outcome carried by the exact completion request. */\nexport const AgentHomeProjectionOutcomeSchema = z.enum(['applied', 'idempotent', 'stale', 'conflict']);\nexport type AgentHomeProjectionOutcome = z.infer<typeof AgentHomeProjectionOutcomeSchema>;\n\n/**\n * Bounded opaque JSON. The SDK enforces only byte size and does not interpret\n * Salesko or any other product's fields. Credential custody remains outside\n * this protocol surface; this schema intentionally defines no credential\n * fields and is not a DLP scanner.\n */\nexport type AgentHomeProjectionValue =\n | string\n | number\n | boolean\n | null\n | AgentHomeProjectionValue[]\n | { [key: string]: AgentHomeProjectionValue };\n\nexport const AgentHomeProjectionValueSchema: z.ZodType<AgentHomeProjectionValue> = z\n .json()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= AGENT_HOME_PROJECTION_MAX_BYTES,\n `projection must not exceed ${AGENT_HOME_PROJECTION_MAX_BYTES} UTF-8 JSON bytes`,\n );\n","/**\n * Member keys, the member chain and scope key packages as the Host stores\n * them (#654 design §7.2–§7.4, E2c).\n *\n * The Host checks shapes only. It never hashes an entry or verifies a\n * signature: members walk the chain themselves (§7.3), so a Host check adds\n * no trust. `@byok-sdk/core/sealed-payload` creates and verifies these values.\n * Protocol does not depend on core, so this module repeats core's shape\n * rules; a cross-package test in `@byok-sdk/cloud` keeps the two equal.\n */\nimport { z } from 'zod';\n\nimport { CONTENT_HASH_RE } from './blob';\n\n/** The most chain entries one append accepts. */\nexport const E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES = 64;\n/** The largest canonical JSON entry, in UTF-8 bytes. */\nexport const E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES = 65_536;\n/** The most chain entries one read returns. */\nexport const E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES = 256;\n/** The most scope key packages one put accepts. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PUT_MAX = 256;\n/** The most packages one paged device read returns. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX = 16;\n/**\n * The longest scope id, in UTF-16 code units, as for other opaque Host ids.\n * Core sets no maximum, so the scope key package shape (which the parity test\n * compares with core) leaves it out, and the Host checks it on every put and\n * read. The key package notice is Host-built wire, so its schema carries it.\n */\nexport const E2EE_SCOPE_ID_MAX_LENGTH = 512;\n\n// Device-proof operations of the three device write routes. Each route binds\n// one operation, and the proof's `resource` is the route path.\n/** Register the device's member key bundle and its device pairing MAC (§7.2 step 3). */\nexport const E2EE_MEMBER_KEY_REGISTER_OPERATION = 'e2ee-member-key.register' as const;\n/** Append member chain entries. */\nexport const E2EE_MEMBER_CHAIN_APPEND_OPERATION = 'e2ee-member-chain.append' as const;\n/** Put scope key packages. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION = 'e2ee-scope-key-package.put' as const;\n\n/**\n * Canonical unpadded base64url of exactly `bytes` bytes: the length is fixed,\n * and the unused low bits of the last character are zero, so one value has\n * one text form.\n */\nfunction base64UrlBytes(bytes: number) {\n const length = Math.ceil((bytes * 4) / 3);\n const last = ['[A-Za-z0-9_-]', '[AQgw]', '[AEIMQUYcgkosw048]'][bytes % 3];\n return z.string().regex(new RegExp(`^[A-Za-z0-9_-]{${length - 1}}${last}$`, 'u'));\n}\n\nconst MemberIdSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/u);\nconst PositiveSafeIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);\nconst SignatureSchema = base64UrlBytes(64);\n\nconst P256PublicJwkSchema = z.strictObject({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: base64UrlBytes(32),\n y: base64UrlBytes(32),\n});\n\n/** A member's public key bundle. A device member names its SDK device id; a client member has none. */\nexport const E2eeMemberKeyBundleSchema = z.strictObject({\n v: z.literal(1),\n memberId: MemberIdSchema,\n signingPublicJwk: P256PublicJwkSchema,\n kemPublicJwk: P256PublicJwkSchema,\n kemEpoch: PositiveSafeIntegerSchema,\n kemSig: SignatureSchema,\n deviceId: z.string().min(1).optional(),\n});\nexport type E2eeMemberKeyBundle = z.infer<typeof E2eeMemberKeyBundleSchema>;\n\nexport const E2EE_MEMBER_CHAIN_OPS = ['add', 'remove', 'rotate', 'scope-policy', 'shred'] as const;\n\n/**\n * The subject of a `shred` entry (design §11.2). The Host reads it to delete\n * the scope's key packages (owner batch §50g A), so it checks this one\n * subject strictly. Core's walk refuses any other `shred` subject too. Like\n * core, it sets no maximum length: a scope id the Host never stored has no\n * packages to delete.\n */\nconst E2eeScopeShredSubjectSchema = z.strictObject({ scopeId: z.string().min(1) });\n\n/**\n * The subject of a `rotate` entry. The Host reads `memberId` and `kemEpoch`\n * to raise the member's KEM floor (#654 E5b-2, owner batch §77a), so it\n * checks this subject as strictly as core's walk does.\n */\nconst E2eeMemberRotateSubjectSchema = z.strictObject({\n memberId: MemberIdSchema,\n kemPublicJwk: P256PublicJwkSchema,\n kemEpoch: PositiveSafeIntegerSchema,\n kemSig: SignatureSchema,\n});\n\n/**\n * One signed member chain entry. `subject` must be a JSON object; the Host\n * stores the entry as canonical JSON, which refuses any value outside JSON.\n * A `shred` subject must also be exactly `{ scopeId }`.\n */\nexport const E2eeMemberChainEntrySchema = z\n .strictObject({\n v: z.literal(1),\n tenantId: z.string().min(1),\n seq: PositiveSafeIntegerSchema,\n prev: z.union([z.null(), z.string().regex(CONTENT_HASH_RE)]),\n op: z.enum(E2EE_MEMBER_CHAIN_OPS),\n subject: z.custom<Readonly<Record<string, unknown>>>(\n value => value !== null && typeof value === 'object' && !Array.isArray(value),\n ),\n signer: MemberIdSchema,\n sig: SignatureSchema,\n })\n .refine(entry => (entry.seq === 1) === (entry.prev === null), {\n path: ['prev'],\n message: 'the first entry, and only the first, has no prev',\n })\n .refine(entry => entry.op !== 'shred' || E2eeScopeShredSubjectSchema.safeParse(entry.subject).success, {\n path: ['subject'],\n message: 'a shred subject is exactly { scopeId }',\n })\n .refine(entry => entry.op !== 'rotate' || E2eeMemberRotateSubjectSchema.safeParse(entry.subject).success, {\n path: ['subject'],\n message: 'a rotate subject is exactly { memberId, kemPublicJwk, kemEpoch, kemSig }',\n });\nexport type E2eeMemberChainEntry = z.infer<typeof E2eeMemberChainEntrySchema>;\n\nconst E2eeScopeKeyPackageV1Schema = z.strictObject({\n v: z.literal(1),\n tenantId: z.string().min(1),\n scopeId: z.string().min(1),\n epoch: PositiveSafeIntegerSchema,\n keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u),\n recipient: MemberIdSchema,\n sender: MemberIdSchema,\n enc: base64UrlBytes(65),\n ciphertext: base64UrlBytes(48),\n sig: SignatureSchema,\n});\n\n/** One scope key wrapped to one member's KEM key of `recipientKemEpoch` (§7.4, §77a). A put takes version 2 only. */\nexport const E2eeScopeKeyPackageV2Schema = z.strictObject({\n ...E2eeScopeKeyPackageV1Schema.shape,\n v: z.literal(2),\n recipientKemEpoch: PositiveSafeIntegerSchema,\n});\n\n/** A stored package as a read returns it: version 1 from before `e2ee.member.kem-epoch`, version 2 after. */\nexport const E2eeScopeKeyPackageSchema = z.union([E2eeScopeKeyPackageV1Schema, E2eeScopeKeyPackageV2Schema]);\nexport type E2eeScopeKeyPackage = z.infer<typeof E2eeScopeKeyPackageSchema>;\n\n/** A pairing MAC (§7.2 steps 3 and 4): HMAC-SHA-256 under `pv`, which the Host never holds. */\nexport const E2eePairingMacSchema = base64UrlBytes(32);\n\n/**\n * The device registration body. `member` is the device's own bundle, so it\n * names the device id; `mac` is the device pairing MAC over it under `pv`.\n */\nexport const E2eeMemberKeyRegisterRequestSchema = z.strictObject({\n member: E2eeMemberKeyBundleSchema.refine(member => member.deviceId !== undefined, {\n message: 'a device member names its deviceId',\n }),\n mac: E2eePairingMacSchema,\n});\nexport type E2eeMemberKeyRegisterRequest = z.infer<typeof E2eeMemberKeyRegisterRequestSchema>;\n\n/** What the client relays to the device in pairing step 4. The client member has no device id. */\nexport const E2eeClientPairingMacSchema = z.strictObject({\n mac: E2eePairingMacSchema,\n member: E2eeMemberKeyBundleSchema.refine(member => member.deviceId === undefined, {\n message: 'a client member has no deviceId',\n }),\n chainHead: z.strictObject({ seq: PositiveSafeIntegerSchema, hash: z.string().regex(CONTENT_HASH_RE) }),\n});\nexport type E2eeClientPairingMac = z.infer<typeof E2eeClientPairingMacSchema>;\n\n/**\n * Server -> daemon `e2ee.key_package.available` (E2c-3): the Host stored a\n * scope key package for this device's member. The payload names only the\n * scope epoch; the device fetches the package from its device route (§7.4,\n * notice-and-fetch), so a mailbox row never holds key material. Gated by\n * `sealed-payload-v1`.\n */\nexport const E2eeKeyPackageAvailablePayloadSchema = z.strictObject({\n scopeId: z.string().min(1).max(E2EE_SCOPE_ID_MAX_LENGTH),\n epoch: PositiveSafeIntegerSchema,\n});\nexport type E2eeKeyPackageAvailablePayload = z.infer<typeof E2eeKeyPackageAvailablePayloadSchema>;\n","import { z } from 'zod';\n\n/**\n * #1121: a device -> Host vocabulary a newer device may extend — a failure\n * class, a decline code, a content denial reason. A receiver must not refuse\n * the whole report for a value it does not know: it keeps the known meaning\n * of the values it knows and records any other well-formed token as\n * `unknown`, with the raw token kept beside it (`reported<Field>`). Control\n * vocabularies (message types, decisions, outcomes that select a shape) stay\n * closed.\n */\nconst OPEN_VOCABULARY_TOKEN = /^[a-z][a-z0-9_-]{0,63}$/;\n\n/** Any well-formed open-vocabulary token, without a membership rule. */\nexport function openVocabularyToken(): z.ZodString {\n return z.string().regex(OPEN_VOCABULARY_TOKEN);\n}\n\n/** A well-formed token that is none of `known`: the raw value a receiver keeps as `reported<Field>`. */\nexport function unrecognizedToken(known: readonly string[]): z.ZodString {\n return openVocabularyToken().refine((value) => !known.includes(value), {\n message: 'a recognized value is not reported as unrecognized',\n });\n}\n","import { PreparedAgentMemoryModeSchema } from './input-preparation';\nimport { z } from 'zod';\nimport { RUNTIME_FAILURE_CLASSES, RUNTIME_IDS, RUNTIME_QUOTA_SCOPES, RUNTIME_UNAVAILABLE_CAUSES, TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH, boundFailureReason, type RuntimeUnavailableCause } from './constants';\nimport { BlobRefSchema } from './blob';\nimport {\n SEALED_DECLINE_CODES,\n SealedTaskInputSchema,\n SealedAgentMessageSchema,\n SealedTaskOutputSchema,\n RoutineRefSchema,\n TaskSealingSchema,\n sealedOfferRule,\n} from './sealed-payload';\nimport { AgentEventOrUnknownSchema } from './agent-event';\nimport {\n AgentContentActorSchema,\n AgentContentDecodeAsSchema,\n AgentContentMimeTypeSchema,\n AgentContentReadDenialReasonSchema,\n AgentContentReadSurfaceSchema,\n AgentEgressContentHashSchema,\n AgentEgressPolicyRevisionSchema,\n AgentEgressPolicySchema,\n AgentMessageContractSchema,\n AgentMessageContentTypeSchema,\n AgentMessageEgressRequirementSchema,\n AGENT_MESSAGE_MAX_BYTES,\n AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,\n ContentReadPolicySchema,\n} from './agent-egress';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionProfileRevisionSchema,\n AgentHomeProjectionValueSchema,\n} from './agent-home-projection';\nimport { ProviderProvisioningAvailablePayloadSchema } from './provider-provisioning';\nimport { E2eeKeyPackageAvailablePayloadSchema } from './e2ee-member';\nimport {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\nimport { openVocabularyToken, unrecognizedToken } from './open-vocabulary';\nimport { ProviderProfileBindingSchema } from './provider-profile-binding';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\nimport { canonicalizePlainJson, type PlainJsonCheck } from './plain-json';\n\n/** Max size of an inlined artifact payload, per the delivery-model spec (<=64KB). */\nconst MAX_INLINE_BYTES = 64 * 1024;\n\nfunction isWithinInlineByteLimit(value: string): boolean {\n return new TextEncoder().encode(value).length <= MAX_INLINE_BYTES;\n}\n\n// ---------------------------------------------------------------------------\n// conn.* — connection handshake\n// ---------------------------------------------------------------------------\n\nexport const RuntimeIdSchema = z.enum(RUNTIME_IDS);\nexport type RuntimeId = z.infer<typeof RuntimeIdSchema>;\n\n/**\n * The append-only pre-claim runtime-unavailable cause (#1103 D6). An unknown\n * well-formed token is accepted and kept verbatim, so a newer device can add\n * one without a protocol bump; {@link readRuntimeUnavailableCause} is the\n * typed reading.\n */\nconst RuntimeUnavailableCauseSchema = z.union([\n z.enum(RUNTIME_UNAVAILABLE_CAUSES),\n unrecognizedToken(RUNTIME_UNAVAILABLE_CAUSES),\n]);\n\n/** A runtime-unavailable cause as this version understands it; unknown reads as `unknown` with the raw token kept. */\nexport type RuntimeUnavailableCauseReading =\n | { readonly cause: RuntimeUnavailableCause }\n | { readonly cause: 'unknown'; readonly reportedCause: string };\n\nexport function readRuntimeUnavailableCause(cause: string): RuntimeUnavailableCauseReading {\n return (RUNTIME_UNAVAILABLE_CAUSES as readonly string[]).includes(cause)\n ? { cause: cause as RuntimeUnavailableCause }\n : { cause: 'unknown', reportedCause: cause };\n}\n\n/** Wire-safe protocol version number: bounded before JSON reaches a store or comparison. */\nexport const ProtocolVersionNumberSchema = z\n .number()\n .int()\n .nonnegative()\n .max(2_147_483_647);\n\n/**\n * Per-runtime feature flags reported in `conn.hello.runtimes[].capabilities`\n * (pre-freeze addition). Distinct from the connection-level `CAPABILITY_FLAGS`\n * (`version.ts`) / `conn.hello.capabilities` array: those are protocol-level\n * flags negotiated for the whole connection, while this is what one specific\n * detected runtime (pi/claude/codex) supports. The whole field is optional\n * end-to-end — older daemons omit `capabilities` entirely — and every field\n * inside it is itself optional, since detection can be partial.\n *\n * Unrecognized keys inside `capabilities` itself, by contrast, are silently\n * stripped (zod's default object behavior — same as every other payload\n * schema in this file) rather than passed through: this is a closed, typed\n * shape consumers can rely on, and a genuinely new capability flag gets added\n * here explicitly rather than round-tripped opaquely.\n */\nexport const RuntimeCapabilitiesSchema = z.object({\n steer: z.boolean().optional(),\n resume: z.boolean().optional(),\n approvalInteractive: z.boolean().optional(),\n /** Whether this runtime can project a locally configured MCP toolset into one task. */\n mcpToolsets: z.boolean().optional(),\n messageDraft: z.boolean().optional(),\n /** The capability matrix (#1103): what the runtime's adapter descriptor declares. Discovery data, not a gate. */\n toolAuthorizationAuto: z.boolean().optional(),\n durablePi: z.boolean().optional(),\n preparedLane: z.boolean().optional(),\n isolation: z.object({\n userContext: z.boolean().optional(),\n userMcpServers: z.boolean().optional(),\n sessionPersistence: z.boolean().optional(),\n }).optional(),\n});\nexport type RuntimeCapabilities = z.infer<typeof RuntimeCapabilitiesSchema>;\n\n/**\n * The effective version policy's verdict, projected for discovery (#1103 D8).\n * Only `state` and the policy's qualified token travel: `matched` and the\n * allow/warn/block spec lists stay local. Absence means **unknown**, never\n * `allow`: an older daemon or an adapter without a policy omits the field.\n */\nexport const RuntimeVersionPolicyProjectionSchema = z.object({\n state: z.enum(['allow', 'warn', 'block']),\n qualifiedVersion: z.string().min(1).max(256).optional(),\n});\nexport type RuntimeVersionPolicyProjection = z.infer<typeof RuntimeVersionPolicyProjectionSchema>;\n\n/**\n * Runtime detection info reported in `conn.hello`. Supersedes the M0\n * `agents: unknown` field (M1 gap #4): typed, so the server no longer has to\n * best-effort-normalize an untyped blob.\n */\nexport const RuntimeInfoSchema = z.object({\n id: RuntimeIdSchema,\n version: z.string().optional(),\n authPresent: z.boolean().optional(),\n /** Optional: older daemons omit this entirely (pre-freeze addition). */\n capabilities: RuntimeCapabilitiesSchema.optional(),\n /** #1103 D8: strip-safe discovery projection; absent means unknown. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\nexport type RuntimeInfo = z.infer<typeof RuntimeInfoSchema>;\n\n/** Custom identities are disjoint from the frozen built-in runtime enum. */\nexport const HarnessIdSchema = z.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/)\n .refine(value => !(RUNTIME_IDS as readonly string[]).includes(value), 'built-in runtime must use runtime');\nexport type HarnessId = z.infer<typeof HarnessIdSchema>;\nexport const HarnessInfoSchema = z.object({\n id: HarnessIdSchema,\n version: z.string().min(1).max(128).optional(),\n capabilities: RuntimeCapabilitiesSchema,\n /** #1103 D8: the same version-policy projection a built-in runtime carries. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\nexport type HarnessInfo = z.infer<typeof HarnessInfoSchema>;\nexport const HarnessInventorySchema = z.array(HarnessInfoSchema).max(64)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate harness identity');\n\n/**\n * One non-available runtime or harness in `conn.hello.runtimeUnavailable`\n * (#1103 D8). The id stays in the existing identity domain: a built-in\n * runtime id or a custom harness id. The cause is the append-only\n * vocabulary, and `retryable` carries the same per-cause default a\n * `task.decline` reports. Absence of the whole array means unknown, never\n * \"everything is available\".\n */\nexport const RuntimeUnavailableEntrySchema = z.object({\n id: z.union([RuntimeIdSchema, HarnessIdSchema]),\n cause: RuntimeUnavailableCauseSchema,\n retryable: z.boolean(),\n});\nexport type RuntimeUnavailableEntry = z.infer<typeof RuntimeUnavailableEntrySchema>;\n\n/** Bounded, unique by id: 16 entries are more runtimes than one daemon hosts. */\nconst RuntimeUnavailableListSchema = z.array(RuntimeUnavailableEntrySchema).max(16)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate runtime-unavailable identity');\n\n/** Maximum logical toolsets one daemon may advertise as locally configured. */\nexport const CONFIGURED_TOOLSETS_MAX_ITEMS = 64;\n\n/**\n * Logical, host-owned MCP toolset identifier. A task may request this name,\n * but the executable/server definition behind it exists only in the daemon's\n * local configuration and never crosses the SaaS wire.\n */\nexport const ToolsetIdSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, 'toolset ids must be lowercase logical identifiers');\nexport type ToolsetId = z.infer<typeof ToolsetIdSchema>;\n\n/** Stable Agent identity carried across transport and storage. */\nexport const AGENT_REF_MAX_BYTES = 160;\nconst AGENT_REF_VALUE = z\n .string()\n .min(1)\n .max(AGENT_REF_MAX_BYTES)\n .refine((value) => new TextEncoder().encode(value).byteLength <= AGENT_REF_MAX_BYTES, {\n message: `AgentRef values must not exceed ${AGENT_REF_MAX_BYTES} UTF-8 bytes`,\n })\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'AgentRef values must not contain control characters');\n\nconst WINDOWS_RESERVED_AGENT_SEGMENT = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\..*)?$/iu;\n\n/**\n * Agent ids are opaque to the SDK but must remain one safe pathname segment;\n * the SDK owns the deterministic `<hostStorageRoot>/agents/<agentId>` mapping.\n */\nexport const AgentRefSchema = z\n .object({\n agentId: AGENT_REF_VALUE.regex(/^[^\\\\/:<>\"|?*]+$/u, 'agentId must be one portable pathname segment').refine(\n (value) => value !== '.' && value !== '..',\n 'agentId must not be a dot segment',\n ).refine(\n (value) => !/[. ]$/u.test(value) && !WINDOWS_RESERVED_AGENT_SEGMENT.test(value),\n 'agentId must be a portable Windows-safe pathname segment',\n ),\n profileRevision: AGENT_REF_VALUE,\n })\n .strict();\nexport type AgentRef = z.infer<typeof AgentRefSchema>;\n\n/** AgentRef constrained to the canonical Profile revision required by projection control. */\nexport const AgentHomeProjectionAgentRefSchema = AgentRefSchema.extend({\n profileRevision: AgentHomeProjectionProfileRevisionSchema,\n}).strict();\nexport type AgentHomeProjectionAgentRef = z.infer<typeof AgentHomeProjectionAgentRefSchema>;\n\nfunction rejectDuplicateToolsets(\n ids: readonly string[],\n ctx: z.RefinementCtx,\n label: 'configured' | 'required',\n): void {\n const seen = new Set<string>();\n for (const [index, id] of ids.entries()) {\n if (seen.has(id)) {\n ctx.addIssue({ code: 'custom', path: [index], message: `duplicate ${label} toolset: ${id}` });\n }\n seen.add(id);\n }\n}\n\n/**\n * Device-local inventory projected for discovery. IDs only: executable MCP\n * definitions, arguments, environment and credentials never enter this shape.\n * Empty means known-none; omission on the containing message means unknown.\n */\nexport const ConfiguredToolsetsSchema = z\n .array(ToolsetIdSchema)\n .max(CONFIGURED_TOOLSETS_MAX_ITEMS)\n .superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'configured'));\n\n/** daemon -> server: opening handshake. */\nexport const ConnHelloPayloadSchema = z.object({\n protocolVersions: z.array(ProtocolVersionNumberSchema).max(16),\n capabilities: z.array(z.string()),\n deviceId: z.string(),\n productId: z.string(),\n /** U4a Local Agent release identity; this is the sole client-version authority. */\n clientVersion: z.string().min(1).max(128).optional(),\n /** Runtimes detected on this device (M1 gap #4; replaces `agents`). */\n runtimes: z.array(RuntimeInfoSchema).optional(),\n harnesses: HarnessInventorySchema.optional(),\n /** #1103 D8: non-available runtimes and harnesses; strip-safe and absent means unknown. */\n runtimeUnavailable: RuntimeUnavailableListSchema.optional(),\n /** Validated logical IDs configured on this device; definitions and secrets stay local. */\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n /**\n * Last `seq` this device has seen from the server (M1 redelivery cursor).\n * Omitted on a device's first-ever connection. The server replays any\n * server->daemon envelopes with `seq > cursor` it still holds — see\n * docs/protocol.md \"At-least-once delivery\".\n */\n cursor: z.number().int().optional(),\n});\nexport type ConnHelloPayload = z.infer<typeof ConnHelloPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// server -> daemon: task.*\n//\n// Every type in this section carries a *required* envelope `task_id` (M1 gap\n// #1) and a *required* envelope `seq` — a per-device monotonic counter the\n// daemon uses as a redelivery cursor (M1 gap; see `conn.hello.cursor` above\n// and docs/protocol.md \"At-least-once delivery\"). None of these payloads\n// duplicate `taskId` at the payload level (M1 gap #7): the envelope's\n// `task_id` is the single routing key.\n// ---------------------------------------------------------------------------\n\n/**\n * The out-of-band-reference form of an offer's `instruction` (the\n * alternative to an inlined string). `.strict()`: this is control data — it's\n * the task instruction itself,\n * the thing that authorizes what work gets done — so per the freeze rule's\n * observability-vs-control asymmetry (docs/protocol.md \"Freeze rule\") an\n * unrecognized field here must be REJECTED, not silently stripped the way an\n * ordinary payload's unknown field is. Without `.strict()`, a hypothetical\n * future field riding along next to `blobRef` (e.g. a routing/priority\n * override) would be silently discarded instead of failing the parse —\n * exactly the kind of silent reinterpretation the freeze rule forbids for\n * control/security payloads. Consequence: adding a field to this shape\n * post-freeze is a BREAKING change (version bump required), not the usual\n * non-breaking additive-optional-field case.\n */\nconst InstructionBlobRefSchema = z.object({ blobRef: BlobRefSchema }).strict();\n\nconst DispatchTargetIdSchema = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[^\\u0000\\r\\n]+$/u, 'dispatch target ids must not contain control line breaks');\n\n/**\n * The web-selected runtime/model target carried end to end with a task.\n *\n * This is an additive v1 field. The discriminated union makes lane ownership\n * fail closed at decode time: subscription credentials can only belong to the\n * vendor CLIs, while a BYOK provider can only be executed through Pi.\n */\nexport const DispatchSelectionSchema = z.discriminatedUnion('lane', [\n z\n .object({\n lane: z.literal('subscription'),\n runtimeId: z.enum(['claude', 'codex']),\n providerId: z.null(),\n modelId: DispatchTargetIdSchema,\n })\n .strict(),\n z\n .object({\n lane: z.literal('byok'),\n runtimeId: z.literal('pi'),\n providerId: DispatchTargetIdSchema,\n modelId: DispatchTargetIdSchema,\n })\n .strict(),\n z\n .object({\n lane: z.literal('byok-profile'),\n runtimeId: z.literal('pi'),\n providerProfile: ProviderProfileBindingSchema,\n })\n .strict(),\n]);\nexport type DispatchSelection = z.infer<typeof DispatchSelectionSchema>;\n\n/**\n * #654: the plaintext branch of a sealable type refuses the sealed members.\n * Without this, a loose schema would strip them, and sealed content or a\n * sealing policy would pass as plaintext. A strict schema needs it too: its\n * unknown-key check sees only enumerable keys, so a non-enumerable `sealed` or\n * `sealing` would be dropped. A sealed message takes the type's sealed branch.\n */\nconst NO_SEALED_MEMBER = { sealed: z.never().optional(), sealing: z.never().optional() };\n\n/** Every named toolset is required; duplicates are rejected instead of silently de-duplicated. */\nexport const RequiredToolsetsSchema = z\n .array(ToolsetIdSchema)\n .min(1)\n .max(16)\n .superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'required'));\n\n/**\n * How an Agent Attempt uses its Agent home. `memory-reader` runs the Attempt\n * in its own run directory, `<home>/.byok/runs/<taskId>/`, beside other\n * reader Attempts and at most one writer Attempt. The home stays an ancestor\n * of that cwd, so the runtime still finds the persona and memory. Absent means\n * a writer: the Attempt runs in the canonical home, and one home has at most\n * one writer at a time. The SDK does not make memory read-only; a reader\n * terminal reports memory changes in `agentHomeMemoryChange`. A host sends this\n * field only to a device that advertises `agent-home-readers`: the Agent\n * offers are strict, so an older daemon cannot accept it.\n */\nexport const AgentHomeAccessSchema = z.literal('memory-reader');\nexport type AgentHomeAccess = z.infer<typeof AgentHomeAccessSchema>;\n\n/**\n * The `agentMemory` of an ordinary Agent offer: the prepared modes plus\n * `read-if-admitted` and `read-write-if-admitted`. When the daemon admits the\n * memory MCP they run as `read` and `read-write`; when it does not, both run as\n * `none`. A host sends each only to a device that advertises\n * `agent-memory-read-if-admitted` or `agent-memory-read-write-if-admitted`. A\n * `memory-reader` Attempt cannot select `read-write-if-admitted`. Prepared\n * offers refuse both.\n */\nexport const AgentMemorySelectionSchema = z.enum([\n ...PreparedAgentMemoryModeSchema.options, 'read-if-admitted', 'read-write-if-admitted',\n]);\nexport type AgentMemorySelection = z.infer<typeof AgentMemorySelectionSchema>;\n\n/**\n * How a `task.offer` starts its runtime session. `resume` continues the named\n * session; `fresh` lets the selected runtime mint one after start. It is\n * required, so an offer without a resume reference is never read as fresh.\n */\nexport const SessionSelectionSchema = z.discriminatedUnion('mode', [\n z.object({ mode: z.literal('resume'), sessionRef: z.string().min(1).max(512) }).strict(),\n z.object({ mode: z.literal('fresh') }).strict(),\n]);\nexport type SessionSelection = z.infer<typeof SessionSelectionSchema>;\n\n/**\n * The fields both `task.offer` branches carry. Every offer binds a durable\n * host-owned Agent (`agentRef`). Each optional field is gated on its own\n * device flag (`wire-additions.ts`); the offer is strict, so a daemon that does\n * not know a field stops its cursor instead of stripping it.\n *\n * `agentMemory` selects the Agent memory of this one task (see\n * {@link AgentMemorySelectionSchema}); absent keeps the daemon admission.\n * `preparation` names an already-counted prepared Execution (see\n * {@link offerRule}): every value under it is the Host re-presenting what the\n * device already told it, and the device declines non-retryably on any\n * difference from its own record.\n */\nconst OFFER_FIELDS = {\n agentRef: AgentRefSchema,\n session: SessionSelectionSchema,\n preparation: InputPreparationOfferBindingSchema.optional(),\n agentMemory: AgentMemorySelectionSchema.optional(),\n homeAccess: AgentHomeAccessSchema.optional(),\n requiredToolsets: RequiredToolsetsSchema.optional(),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n dispatchSelection: DispatchSelectionSchema.optional(),\n terminalProjection: TerminalProjectionSelectionSchema.optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .strict()\n .optional(),\n egressPolicy: AgentEgressPolicySchema.optional(),\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n};\n\ntype OfferRuleInput = {\n readonly instruction?: unknown;\n readonly session: SessionSelection;\n readonly preparation?: unknown;\n readonly agentMemory?: AgentMemorySelection;\n readonly egressPolicy?: unknown;\n readonly messageEgress?: unknown;\n readonly routineRef?: unknown;\n};\n\n/**\n * The cross-field rules of a `task.offer`, for `superRefine`:\n *\n * - A prepared offer (`preparation`) carries no `instruction`: the user request\n * is already inside the frozen envelope the prepared record retained. It\n * never resumes, and it selects a prepared `agentMemory` mode.\n * - A plaintext offer that is not prepared carries an `instruction`. A sealed\n * offer's instruction is checked by {@link sealedOfferRule}.\n * - A fresh or prepared offer carries an `egressPolicy`; `messageEgress` needs one.\n * - A `routineRef` names an execution, so it needs a fresh session.\n */\nfunction offerRule(payload: OfferRuleInput, ctx: z.RefinementCtx, plaintext: boolean): void {\n const { instruction, session, preparation, agentMemory, egressPolicy, messageEgress, routineRef } = payload;\n if (preparation !== undefined) {\n if (instruction !== undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a prepared offer carries no instruction' });\n if (session.mode !== 'fresh') ctx.addIssue({ code: 'custom', path: ['session'], message: 'a prepared offer never resumes' });\n if (!PreparedAgentMemoryModeSchema.safeParse(agentMemory).success) {\n ctx.addIssue({ code: 'custom', path: ['agentMemory'], message: 'a prepared offer selects a prepared agentMemory mode' });\n }\n } else if (plaintext && instruction === undefined) {\n ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'an offer that is not prepared carries an instruction' });\n }\n if ((preparation !== undefined || session.mode === 'fresh') && egressPolicy === undefined) {\n ctx.addIssue({ code: 'custom', path: ['egressPolicy'], message: 'a fresh or prepared offer carries an egressPolicy' });\n }\n if (messageEgress !== undefined && egressPolicy === undefined) {\n ctx.addIssue({ code: 'custom', path: ['messageEgress'], message: 'messageEgress needs an egressPolicy' });\n }\n if (routineRef !== undefined && session.mode !== 'fresh') {\n ctx.addIssue({ code: 'custom', path: ['routineRef'], message: 'a routine occurrence is an execution, so it needs a fresh session' });\n }\n}\n\n/** The plaintext branch of `task.offer`, before its cross-field rules. */\nconst TaskOfferPlainFields = z\n .object({\n ...NO_SEALED_MEMBER,\n routineRef: z.never().optional(),\n instruction: z.union([z.string(), InstructionBlobRefSchema]).optional(),\n ...OFFER_FIELDS,\n })\n .strict();\n\n/**\n * The sealed branch of `task.offer`, before its rules. `sealing` marks it: the\n * task's frozen sealing policy. When the policy includes `task-input`,\n * `instruction` moves into `sealed` (or `sealed` is a routine template named by\n * `routineRef`); otherwise `instruction` stays plaintext and only the output is\n * sealed. A prepared Execution is never sealed (`SEALED_SPLIT_TABLE` forbids\n * `preparation`).\n */\nconst TaskOfferSealedFields = z\n .object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]).optional(),\n sealing: TaskSealingSchema,\n sealed: SealedTaskInputSchema.optional(),\n routineRef: RoutineRefSchema.optional(),\n ...OFFER_FIELDS,\n preparation: z.never().optional(),\n })\n .strict();\n\n/** server -> daemon: a `task.offer` of a task that is not sealed. */\nexport const TaskOfferPlainPayloadSchema = TaskOfferPlainFields.superRefine((payload, ctx) => offerRule(payload, ctx, true));\nexport type TaskOfferPlainPayload = z.infer<typeof TaskOfferPlainPayloadSchema>;\n\n/** server -> daemon: a `task.offer` of a sealed task. */\nexport const TaskOfferSealedPayloadSchema = TaskOfferSealedFields.superRefine((payload, ctx) => {\n offerRule(payload, ctx, false);\n sealedOfferRule(payload, ctx);\n});\nexport type TaskOfferSealedPayload = z.infer<typeof TaskOfferSealedPayloadSchema>;\n\n/**\n * server -> daemon: the one task-opening offer. Both branches are strict, so a\n * field this decoder does not know stops the daemon's cursor (the long-poll\n * treats it like an unknown type) instead of being stripped. The plaintext\n * branch comes first and refuses `sealing`, so a sealed offer always takes the\n * sealed branch; narrow with `payload.sealing !== undefined`.\n */\nexport const TaskOfferPayloadSchema = z.union([\n TaskOfferPlainPayloadSchema as typeof TaskOfferPlainPayloadSchema,\n TaskOfferSealedPayloadSchema as typeof TaskOfferSealedPayloadSchema,\n]);\nexport type TaskOfferPayload = z.infer<typeof TaskOfferPayloadSchema>;\n\nconst EGRESS_SAFE_VALUE = z\n .json()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 256 * 1024,\n 'egress payload exceeds 256KiB',\n );\nconst EGRESS_SESSION_REF = z.string().min(1).max(512);\n\n/** Daemon -> cloud: one durable reliable-lane item, forwarded as the Agent produced it. */\nexport const AgentEgressReliablePayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n policyRevision: AgentEgressPolicyRevisionSchema,\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n payload: EGRESS_SAFE_VALUE,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().nonnegative().max(256 * 1024),\n })\n .strict();\nexport type AgentEgressReliablePayload = z.infer<typeof AgentEgressReliablePayloadSchema>;\n\n/** Cloud -> daemon: exact acknowledgement for one reliable egress record. */\nexport const AgentEgressAckPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n policyRevision: AgentEgressPolicyRevisionSchema,\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n receiptId: z.uuid(),\n })\n .strict();\nexport type AgentEgressAckPayload = z.infer<typeof AgentEgressAckPayloadSchema>;\n\nconst AGENT_MESSAGE_BODY = z.string().min(1).refine(\n (value) => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_MAX_BYTES,\n `Agent message body exceeds ${AGENT_MESSAGE_MAX_BYTES} bytes`,\n);\n\n/** Daemon -> server: one Agent-authored message, independent from task activity. */\n/** Display-only text. Offsets count UTF-8 bytes within one revision. */\nexport const AgentMessageDraftPayloadSchema = z.object({\n agentRef: AgentRefSchema,\n revision: z.number().int().min(1),\n offset: z.number().int().nonnegative(),\n text: z.string().refine(\n value => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,\n `Agent message draft frame exceeds ${AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES} bytes`,\n ),\n overflow: z.literal(true).optional(),\n}).strict();\nexport type AgentMessageDraftPayload = z.infer<typeof AgentMessageDraftPayloadSchema>;\n\n/** The fields of an Agent message that every branch carries in plaintext. */\nconst AGENT_MESSAGE_IDENTITY = {\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n};\n\n/** Daemon -> server: one Agent message in plaintext. */\nexport const AgentMessagePublishPlainPayloadSchema = z\n .object({\n ...AGENT_MESSAGE_IDENTITY,\n contentType: AgentMessageContentTypeSchema,\n body: AGENT_MESSAGE_BODY,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\n ...NO_SEALED_MEMBER,\n })\n .strict()\n .superRefine((value, context) => {\n const actual = new TextEncoder().encode(value.body).byteLength;\n if (actual !== value.byteCount) {\n context.addIssue({ code: 'custom', path: ['byteCount'], message: 'byteCount must equal UTF-8 body bytes' });\n }\n });\nexport type AgentMessagePublishPlainPayload = z.infer<typeof AgentMessagePublishPlainPayloadSchema>;\n\n/**\n * Daemon -> server: one Agent message of a task whose `sealing` lists\n * `agent-message` (#1045 C2). `body` is sealed; `contentHash` and\n * `byteCount` are not carried, and `messageId` and `cursor` name the write in\n * the AAD and the content MAC. Gated on `sealed-payload-v2`.\n */\nexport const AgentMessagePublishSealedPayloadSchema = z\n .object({ ...AGENT_MESSAGE_IDENTITY, contentType: AgentMessageContentTypeSchema, sealed: SealedAgentMessageSchema })\n .strict();\nexport type AgentMessagePublishSealedPayload = z.infer<typeof AgentMessagePublishSealedPayloadSchema>;\n\n/** Narrow with `payload.sealed !== undefined`; the plaintext branch's `sealed` is `never`. */\nexport const AgentMessagePublishPayloadSchema = z.union([\n AgentMessagePublishPlainPayloadSchema as typeof AgentMessagePublishPlainPayloadSchema,\n AgentMessagePublishSealedPayloadSchema as typeof AgentMessagePublishSealedPayloadSchema,\n]);\nexport type AgentMessagePublishPayload = z.infer<typeof AgentMessagePublishPayloadSchema>;\n\nconst AGENT_MESSAGE_DISPOSITION = {\n ...AGENT_MESSAGE_IDENTITY,\n outcome: z.enum(['accepted', 'held', 'refused']),\n receiptId: z.uuid(),\n reasonCode: z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u).optional(),\n};\n\n/** Server -> daemon: the disposition of a plaintext message, naming its `contentHash`. */\nexport const AgentMessageDispositionPlainPayloadSchema = z\n .object({ ...AGENT_MESSAGE_DISPOSITION, contentHash: AgentEgressContentHashSchema, contentMac: z.never().optional() })\n .strict();\nexport type AgentMessageDispositionPlainPayload = z.infer<typeof AgentMessageDispositionPlainPayloadSchema>;\n\n/**\n * Server -> daemon: the disposition of a sealed message (#1045 C2). It names\n * the message by its sealed member's `contentMac`, because the sealed message\n * carries no `contentHash`. Gated on `sealed-payload-v2`.\n */\nexport const AgentMessageDispositionSealedPayloadSchema = z\n .object({\n ...AGENT_MESSAGE_DISPOSITION,\n contentMac: SealedAgentMessageSchema.shape.contentMac,\n contentHash: z.never().optional(),\n })\n .strict();\nexport type AgentMessageDispositionSealedPayload = z.infer<typeof AgentMessageDispositionSealedPayloadSchema>;\n\n/** Narrow with `payload.contentMac !== undefined`. */\nexport const AgentMessageDispositionPayloadSchema = z.union([\n AgentMessageDispositionPlainPayloadSchema as typeof AgentMessageDispositionPlainPayloadSchema,\n AgentMessageDispositionSealedPayloadSchema as typeof AgentMessageDispositionSealedPayloadSchema,\n]);\nexport type AgentMessageDispositionPayload = z.infer<typeof AgentMessageDispositionPayloadSchema>;\n\nconst AGENT_CONTENT_TARGET = z\n .string()\n .min(1)\n .max(1024)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'content target must not contain control characters')\n .refine(\n (value) =>\n !value.startsWith('/') &&\n !value.includes('\\\\') &&\n value.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..'),\n 'content target must be a portable relative path without dot segments',\n );\nconst AGENT_CONTENT_CWD = z\n .string()\n .min(1)\n .max(4096)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'cwd must not contain control characters')\n .regex(/^(?:\\/|[A-Za-z]:[\\\\/])/u, 'cwd must be absolute');\n\n/** Server -> daemon: one exact, independently-capability-gated content read. */\nexport const AgentContentReadPayloadSchema = z\n .object({\n requestId: z.uuid(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n policy: ContentReadPolicySchema,\n })\n .strict();\nexport type AgentContentReadPayload = z.infer<typeof AgentContentReadPayloadSchema>;\n\n/** Daemon -> cloud: durable, content-free content-read audit fact. */\nexport const AgentContentReceiptPayloadSchema = z.discriminatedUnion('decision', [\n z\n .object({\n requestId: z.uuid(),\n /** Stable reliable-delivery identity. Content receipts use their requestId. */\n eventId: z.uuid(),\n /** Stable positive cursor allocated by the durable Agent spool. */\n cursor: z.number().int().positive(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n decision: z.literal('allowed'),\n byteCount: z.number().int().nonnegative(),\n contentHash: AgentEgressContentHashSchema,\n blobRef: BlobRefSchema,\n })\n .strict(),\n z\n .object({\n requestId: z.uuid(),\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n decision: z.literal('denied'),\n byteCount: z.literal(0),\n /** Open (#1121): a well-formed reason this version does not know is accepted and kept verbatim. */\n reason: z.union([AgentContentReadDenialReasonSchema, unrecognizedToken(AgentContentReadDenialReasonSchema.options)]),\n })\n .strict(),\n]).superRefine((value, ctx) => {\n if (value.decision !== 'allowed') return;\n if (value.blobRef.size !== value.byteCount) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'size'], message: 'blobRef size must equal byteCount' });\n }\n if (value.blobRef.contentHash !== value.contentHash) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'contentHash'], message: 'blobRef contentHash must equal contentHash' });\n }\n if (value.blobRef.contentType !== value.mimeType) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'contentType'], message: 'blobRef contentType must equal mimeType' });\n }\n});\nexport type AgentContentReceiptPayload = z.infer<typeof AgentContentReceiptPayloadSchema>;\n\n/**\n * Server -> daemon: one task-free exact-device Agent-home projection.\n *\n * `agentRef.profileRevision` is the projection contract's canonical comparable\n * revision. It is validated without interpreting the opaque product\n * projection, whose fields are never inspected for product semantics.\n */\nexport const AgentHomeProjectionPayloadSchema = z\n .object({\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n projection: AgentHomeProjectionValueSchema,\n })\n .strict();\nexport type AgentHomeProjectionPayload = z.infer<typeof AgentHomeProjectionPayloadSchema>;\n\n/**\n * Server -> daemon: a Host-approved Agent memory intent is waiting for this\n * device (capability `agent-memory-intent.v1`, see `agent-memory-intent.ts`).\n *\n * `.strict()` and exactly two fields. There is deliberately no path, operation,\n * revision or content: the device fetches the immutable intent from the Host\n * under its own device authentication, so a mailbox row or journal line never\n * holds memory content. `agentRef` routes the home lease and the local ledger\n * and must equal the fetched intent's `agentRef`.\n */\nexport const AgentMemoryIntentAvailablePayloadSchema = z\n .object({\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n })\n .strict();\nexport type AgentMemoryIntentAvailablePayload = z.infer<typeof AgentMemoryIntentAvailablePayloadSchema>;\n\n/**\n * The inlined form of `agent.input.preparation`'s authorized context document.\n *\n * Bounded by the SAME `MAX_INLINE_BYTES` (64 KiB) every other inlined artifact\n * on this wire is bounded by — there is no preparation-specific enlargement.\n * Anything larger uses the blob-ref form below, exactly the way a large task\n * instruction does; it is never implicitly chunked.\n */\nconst InputPreparationInlineContextSchema = z\n .object({\n inline: z\n .string()\n .refine(isWithinInlineByteLimit, `inline context must not exceed ${MAX_INLINE_BYTES} UTF-8 bytes`),\n })\n .strict();\n\n/**\n * The out-of-band form. `contentHash` is stated a second time next to the\n * `BlobRef` on purpose and must equal it: the device verifies the DECODED\n * bytes against this field, so a blob store that serves different bytes under\n * the same id is caught locally rather than compiled.\n */\nconst InputPreparationBlobContextSchema = z\n .object({ blobRef: BlobRefSchema, contentHash: InputPreparationContentHashSchema })\n .strict()\n .superRefine((value, ctx) => {\n if (value.blobRef.contentHash !== value.contentHash) {\n ctx.addIssue({\n code: 'custom',\n path: ['blobRef', 'contentHash'],\n message: 'blobRef contentHash must equal contentHash',\n });\n }\n });\n\n/**\n * Server -> daemon: one task-free, exact-device remote input preparation.\n *\n * Distinct message type rather than an optional field on an existing one, for\n * the same N/N-1 reason the Agent offers are: an optional field could be\n * legally STRIPPED by a daemon that predates this contract, which would then\n * answer as though a preparation it never performed had somehow been handled.\n * An unknown type (`parseMessage` -> `UnknownMessageTypeError`) is not skipped\n * cleanly either: on long-poll it freezes the cursor, so the enqueue capability\n * gate is the compatibility boundary.\n *\n * What is deliberately NOT here (§17 B): `tools`, `toolExecutors`, runtime or\n * compiler identity, `tenantId` and `deviceId`. The first three are local\n * observations; the last two come from the device's own authenticated record,\n * never from the payload — a sender that could name them could redirect a\n * preparation's binding to a device it does not own.\n *\n * `deadlineAt` may only ever be TIGHTENED locally: the device clamps to\n * `min(deadlineAt - now, limits.preparationDeadlineMs)`, so a generous Host\n * deadline cannot enlarge a configured local bound.\n */\nexport const AgentInputPreparationPayloadSchema = z\n .object({\n agentMemory: PreparedAgentMemoryModeSchema,\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n source: InputPreparationSourceSchema,\n selection: InputPreparationSelectionSchema,\n deadlineAt: z.iso.datetime({ offset: true }),\n context: z.union([InputPreparationInlineContextSchema, InputPreparationBlobContextSchema]),\n requiredToolsets: z.array(ToolsetIdSchema).max(16).superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'required')),\n /**\n * The Host's accounting ruling for this preparation, carried verbatim onto\n * the receipt's binding. Optional and defaulted NOWHERE: a payload that\n * omits it produces a receipt that says `accounting_policy_missing`, which\n * is the honest answer — the device rules on no residual key by itself.\n */\n accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional(),\n })\n .strict();\nexport type AgentInputPreparationPayload = z.infer<typeof AgentInputPreparationPayloadSchema>;\n\n/**\n * server -> daemon: approve a pending `task.await_approval` request.\n *\n * Semantics (M1 gap #3): the server's own state is authoritative on its own\n * action — calling the server-side `approve()` API moves the task record\n * `AwaitApproval -> Running` immediately. This wire message is a best-effort\n * *notification* telling the daemon to resume the paused runtime session; the\n * daemon does not send a dedicated ack. Its outcome is observable through the\n * task's existing message stream (e.g. `task.progress` resuming, or\n * `task.fail`/`task.cancelled` if resuming turns out to be impossible) — no\n * new ack message type is introduced. See docs/protocol.md \"Approval flow\".\n *\n * `approvalId` (required since v4): the SPECIFIC pending approval this\n * decision resolves. The daemon compares it against its own\n * currently-dispatched approval id (`ActiveTask.pendingApprovalId`,\n * `packages/client`'s `task-runner.ts`) and treats a mismatch as a stale,\n * audit-only no-op, so a late decision never lands on the task's next\n * approval — see `TaskRunner.handleApprove`.\n */\nexport const TaskApprovePayloadSchema = z.object({\n approvalId: z.string().min(1),\n});\nexport type TaskApprovePayload = z.infer<typeof TaskApprovePayloadSchema>;\n\n/**\n * server -> daemon: reject a pending `task.await_approval` request.\n *\n * Same best-effort-notification semantics as `task.approve` (M1 gap #3): the\n * server moves its own record `AwaitApproval -> Failed` immediately; this\n * message just tells the daemon to stop, and the daemon reports the outcome\n * via its existing `task.fail` terminal message.\n *\n * `approvalId` (required since v4): same targeting as\n * `TaskApprovePayloadSchema.approvalId` above, applied to the reject path\n * (`TaskRunner.handleReject`).\n */\nexport const TaskRejectPayloadSchema = z.object({\n reason: z.string().optional(),\n approvalId: z.string().min(1),\n});\nexport type TaskRejectPayload = z.infer<typeof TaskRejectPayloadSchema>;\n\n/**\n * server -> daemon: cancel a task in any non-terminal state.\n *\n * Same best-effort-notification semantics (M1 gap #3): the server moves its\n * own record to `Cancelled` immediately on its own action and does not wait\n * for a daemon ack; this message just tells the daemon to stop local work.\n * The daemon reports the outcome via the explicit `task.cancelled` terminal\n * message (M1 gap #6) — not `task.fail`.\n */\nexport const TaskCancelPayloadSchema = z.object({\n reason: z.string().optional(),\n});\nexport type TaskCancelPayload = z.infer<typeof TaskCancelPayloadSchema>;\n\n/** server -> daemon: inject steering text into a running task. */\nconst TaskSteerPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n text: z.string(),\n});\n\n// ---------------------------------------------------------------------------\n// daemon -> server: task.*\n//\n// Every type in this section carries a *required* envelope `task_id` (M1 gap\n// #1 — these all route by task id). Envelope `seq` (the redelivery cursor)\n// stays optional in this direction: M1 only specifies at-least-once\n// server->daemon redelivery, not a daemon->server one (see\n// docs/protocol.md).\n// ---------------------------------------------------------------------------\n\n/** Maximum offer admission duration, and of each phase in it (seven days). */\nexport const OFFER_ADMISSION_MAX_DURATION_MS = 604_800_000;\nconst OfferAdmissionDurationSchema = z.number().int().nonnegative().max(OFFER_ADMISSION_MAX_DURATION_MS);\n/**\n * #1014: how long this device spent admitting an offer, in milliseconds of its\n * monotonic clock, from receiving the offer to sending the claim or decline\n * that ends admission. A phase is present only when it ran; the time no phase\n * names is `totalMs` minus their sum.\n */\nexport const OfferAdmissionTimingsSchema = z.object({\n totalMs: OfferAdmissionDurationSchema,\n agentHomeWaitMs: OfferAdmissionDurationSchema.optional(),\n messageHelperPreflightMs: OfferAdmissionDurationSchema.optional(),\n resultHelperPreflightMs: OfferAdmissionDurationSchema.optional(),\n toolsetProbeMs: OfferAdmissionDurationSchema.optional(),\n runtimeLaunchMs: OfferAdmissionDurationSchema.optional(),\n}).strict();\nexport type OfferAdmissionTimings = z.infer<typeof OfferAdmissionTimingsSchema>;\n\n/**\n * daemon -> server: claim an offered task (idempotent CAS on the server\n * side). `taskId` used to be duplicated here; it is now carried only by the\n * envelope's `task_id` (M1 gap #7).\n *\n * Claiming no longer implies the task is `Running` (M1 gap #2) — see\n * `task.started`.\n *\n * `runtime` (M5, additive-minor — docs/protocol.md §3.1): the ACTUAL\n * adapter this device selected for the task, distinct from the offer's\n * own `runtime` (the merely REQUESTED one, `TaskOfferPayloadSchema`'s `runtime`\n * above). When an offer names no runtime the daemon auto-selects (pi-first —\n * `TaskRunner.pickAdapter`, `packages/client`'s `task-runner.ts`), and before\n * this field existed the server had no way to learn which adapter actually\n * ran — `TaskSnapshot.runtime` (`packages/server`'s `types.ts`) only ever\n * recorded what was requested. Plain optional property on this already-\n * tolerant `z.object()`: an old server simply never reads it, so this needed\n * no version bump and no emission gating — a new daemon sends it\n * unconditionally, regardless of whether the connected server is new enough\n * to store it.\n *\n * `capabilities` (S0/D-4, additive-minor — docs/protocol.md §2.4): the\n * TASK-level capability authority — what the claiming adapter reported about\n * itself at the moment it took this task, reusing `RuntimeCapabilitiesSchema`\n * (above) rather than introducing a second capability shape. Same source of\n * truth as `conn.hello.runtimes[].capabilities`, different scope: `conn.hello`\n * is CONNECTION-level discovery (\"what could this device run\"), which no\n * server-side task control decision may read, because it describes a device,\n * not the adapter that claimed this task. This field is task-shaped: it shares a lifecycle with\n * the task↔runtime binding the claim itself establishes, so a control gate\n * (`steerTask()`, `packages/server`'s `hub.ts`) can key off it and stay\n * correct across reconnects, adapter-set changes, and transports. Plain\n * optional property on this already-tolerant `z.object()`, exactly like\n * `runtime` above: an old daemon simply omits it, and a consumer that gates on\n * it must fail closed on absence rather than assume a default.\n */\nexport const TaskClaimPayloadSchema = z.object({\n deviceId: z.string(),\n agentId: z.string().optional(),\n agentRef: AgentRefSchema.optional(),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n capabilities: RuntimeCapabilitiesSchema.optional(),\n admission: OfferAdmissionTimingsSchema.optional(),\n});\nexport type TaskClaimPayload = z.infer<typeof TaskClaimPayloadSchema>;\n\n/**\n * daemon -> server: explicit `Claimed -> Running` transition (M1 gap #2).\n * A `task.claim` no longer implies the task started running; the daemon\n * sends this once it has actually started the runtime session for the task.\n */\nexport const TaskStartedPayloadSchema = z.object({});\nexport type TaskStartedPayload = z.infer<typeof TaskStartedPayloadSchema>;\n\n/**\n * daemon -> server: decline an offer *before* claiming it (M1 gap #5) — e.g.\n * no compatible/available runtime. Fail-closed rejections must use this instead of silently\n * dropping the offer.\n *\n * Decision (see docs/protocol.md \"Declined vs. Failed\" for the full\n * writeup): declining does *not* introduce a new `Declined` terminal state.\n * It maps onto the existing `Failed` state via a new `Offered -> Failed`\n * transition. `reason`/`retryable` intentionally mirror `TaskFailPayload`\n * semantics, because a pre-claim decline and a post-claim failure are the same\n * outcome from the dispatcher's point of view (this attempt produced no\n * result; here's whether retrying — e.g. offering to a different device —\n * makes sense), and keeping the state machine minimal avoids forking every\n * terminal-state consumer into \"Failed or Declined, handle both\".\n */\nconst HOME_DECLINE_CODES = ['agent_home_writer_busy', 'agent_home_reader_busy'] as const;\nconst DECLINE_CODES = [...HOME_DECLINE_CODES, ...SEALED_DECLINE_CODES] as const;\nexport type TaskDeclineCode = (typeof DECLINE_CODES)[number];\n/**\n * The decline code is open (#1121): a well-formed code this version does not\n * know is accepted and kept verbatim, so the decline is still recorded.\n * {@link readDeclineCode} is the typed reading.\n */\n/**\n * The typed reason a runtime was unavailable before claim (#1103 D6).\n * Append-only: an unknown well-formed cause is accepted and kept verbatim\n * (#1121), and {@link readRuntimeUnavailableCause} is the typed reading. The\n * login-shell capture code travels only with `environment_unavailable`\n * (#1095); it is an open well-formed token so the protocol never owns the\n * client's closed environment-code list.\n */\nconst RuntimeUnavailableSchema = z.object({\n cause: RuntimeUnavailableCauseSchema,\n code: openVocabularyToken().optional(),\n}).refine((value) => value.code === undefined || value.cause === 'environment_unavailable', {\n message: 'only environment_unavailable carries an environment code',\n});\n\nconst DeclineFields = z.object({\n ...NO_SEALED_MEMBER,\n reason: z.string(),\n retryable: z.boolean().optional(),\n agentRef: AgentRefSchema.optional(),\n code: z.union([z.enum(DECLINE_CODES), unrecognizedToken(DECLINE_CODES)]).optional(),\n runtimeUnavailable: RuntimeUnavailableSchema.optional(),\n admission: OfferAdmissionTimingsSchema.optional(),\n});\n\n/** A decline code as this version understands it: one it does not know reads as `unknown`, its raw token kept. */\nexport type TaskDeclineCodeReading =\n | { readonly code: TaskDeclineCode }\n | { readonly code: 'unknown'; readonly reportedCode: string };\n\nexport function readDeclineCode(code: string): TaskDeclineCodeReading {\n return (DECLINE_CODES as readonly string[]).includes(code)\n ? { code: code as TaskDeclineCode }\n : { code: 'unknown', reportedCode: code };\n}\n/**\n * #654: a sealed decline code names a fixed, non-retryable outcome and\n * carries no content, so its `reason` is the code itself. A free-text reason\n * or `retryable: true` never goes with it.\n */\nconst TaskDeclinePlainPayloadSchema = DeclineFields.refine(\n (p) => !(SEALED_DECLINE_CODES as readonly unknown[]).includes(p.code) || (p.reason === p.code && p.retryable !== true),\n { message: 'a sealed code needs reason === code, not retryable' },\n);\n\n/**\n * daemon -> server: batch of normalized agent events.\n *\n * `events` elements are known-or-unknown (`AgentEventOrUnknownSchema` —\n * `agent-event.ts`), not bare `AgentEventSchema`: pre-freeze, an unrecognized\n * event `type` must not fail the whole batch, since a peer running a newer\n * minor version may have emitted an additive event variant this schema\n * doesn't know about yet. See `agent-event.ts` for the full rationale and\n * `partitionAgentEvents`/`isKnownAgentEvent` for how consumers should skip\n * unknowns instead of choking on them.\n */\nconst TaskProgressPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n seq: z.number().int(),\n events: z.array(AgentEventOrUnknownSchema),\n});\n\n/** daemon -> server: an artifact produced by the task, inline or by blob ref. */\nconst TaskArtifactPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n name: z.string(),\n contentType: z.string(),\n inline: z\n .string()\n .refine(isWithinInlineByteLimit, {\n message: 'inline artifact payload exceeds 64KB limit',\n })\n .optional(),\n blobRef: BlobRefSchema.optional(),\n});\n\n/**\n * daemon -> server: task is blocked on an out-of-band approval.\n *\n * `approvalId` (required since v4): the daemon's own locally-generated\n * identity for THIS SPECIFIC pending approval (`ApprovalRegistry`,\n * `packages/client`'s `approvals.ts`). The server echoes it on the\n * `task.approve`/`task.reject` that decides this approval.\n */\nconst TaskAwaitApprovalPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n summary: z.string(),\n approvalId: z.string().min(1),\n});\n\n/**\n * Hard cap (1 MiB) on a single `task.complete.document` (see\n * {@link TaskCompletePayloadSchema}), measured as the UTF-8 byte length of\n * its canonical JSON encoding — NOT as a node/key count, since a document is\n * schema-neutral and its object shape is unbounded by design.\n *\n * The cap is a REJECT-AT-BOUNDARY limit on both sides: a daemon that\n * produces an over-cap document reports `task.fail` instead of sending it,\n * and a server rejects an over-cap document at schema validation. It is\n * never truncated — a truncated JSON document is not valid JSON, so\n * \"shrinking to fit\" can only hand the consumer garbage.\n *\n * 1 MiB is the conservative ceiling declared by the first real consumer\n * (`docs/researches/2026-08-12-salesko-consumption-evidence.md` §1/§2:\n * smallest real frame 8.4 KiB, typical 48-96 KiB, 512 KiB comfortable).\n * Producers should stay at or under ~512 KiB (docs/protocol.md); the extra\n * headroom exists because raising a protocol cap later is additive while\n * lowering one is breaking. A result too big for this channel belongs in\n * `artifactRefs` (the multi-file/binary/oversized channel), not here.\n */\nexport const RESULT_DOCUMENT_MAX_BYTES = 1_048_576;\n\n/**\n * Outcome of {@link checkResultDocument}.\n *\n * `bytes` is the measured canonical JSON UTF-8 byte length, present on both\n * the accept and the over-cap rejection so a caller can name the actual size\n * in a failure reason. `canonical` is the CANONICAL SNAPSHOT — the value a\n * sender must actually put on the wire; see {@link checkResultDocument}.\n */\nexport type ResultDocumentCheck = PlainJsonCheck;\n\n/**\n * THE single authority for \"is this a legal `task.complete.document`\", and\n * the one place its canonical form is produced. `TaskCompletePayloadSchema`'s\n * own refinement calls it, and the daemon-side pre-send gate\n * (`packages/client`'s `task-runner.ts`) imports and calls the exact same\n * function rather than re-deriving any part of it: a daemon that measured or\n * judged a document even slightly differently from the server that validates\n * it would either reject documents the wire would have accepted, or hand the\n * server a payload it is about to reject after the runtime session already\n * ended.\n *\n * **The contract is: a document must be PLAIN JSON DATA.** Not \"an object\n * that happens to survive `JSON.stringify`\" — that bar is far too low, and\n * two concrete attacks/mistakes live under it:\n *\n * 1. `JSON.stringify` succeeding does not mean the value was preserved. An\n * `undefined`-valued key, a `NaN`, a function-valued property, or a\n * `Date` all serialize \"successfully\" while silently becoming something\n * else (dropped, `null`, or a string). The result is a well-formed,\n * under-cap document that is not what the producer had — a confidently\n * wrong terminal result, the worst outcome this channel has.\n * 2. `toJSON(key)` receives the property key it is being serialized under,\n * so an object can legally answer one way at the root (`key === ''`,\n * where this function measures it) and a completely different way when\n * nested inside the envelope payload (`key === 'document'`, where the\n * codec actually serializes it). A root-only measurement is therefore\n * not a bound on what goes on the wire at all. The same hole exists for\n * any getter that answers differently on a second read.\n *\n * Both die together via the same mechanism. The steps:\n *\n * 1. `JSON.stringify` must succeed and not return `undefined`.\n * 2. Its UTF-8 byte length must be within {@link RESULT_DOCUMENT_MAX_BYTES}.\n * 3. `JSON.parse` that string — the CANONICAL SNAPSHOT. It is pure data:\n * no `toJSON`, no getters, no prototype, nothing left that can answer\n * differently a second time.\n * 4. The original must be structurally equal to the snapshot\n * (`isSameJsonData`, `plain-json.ts`). Any mismatch means the value was not plain\n * JSON data, and it is rejected rather than silently transformed.\n *\n * On success the snapshot is returned as `canonical`, and **every sender\n * must put THAT on the wire, never the original reference** — which is what\n * closes the contextual-`toJSON`/unstable-getter hole for good: pure data\n * serializes identically at the root and nested, so what was measured is\n * necessarily what is sent. The check is idempotent on pure data, so the\n * server re-running it on an already-parsed payload is a no-op that always\n * agrees.\n */\nexport function checkResultDocument(document: unknown): ResultDocumentCheck {\n return canonicalizePlainJson(document, RESULT_DOCUMENT_MAX_BYTES);\n}\n\n/** Maximum provider-reported prompt or completion token count retained in one terminal observation. */\nexport const TERMINAL_INFERENCE_USAGE_MAX_TOKENS = 1_000_000_000;\n/** Maximum device-observed elapsed duration retained in one terminal observation (seven days). */\nexport const TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS = 604_800_000;\nexport const TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH = 160;\nexport const TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH = 128;\n\nconst TerminalInferenceUsageNumberSchema = z\n .number()\n .int()\n .safe()\n .nonnegative()\n .max(TERMINAL_INFERENCE_USAGE_MAX_TOKENS);\n\nconst TerminalInferenceUsageDurationSchema = z\n .number()\n .int()\n .safe()\n .nonnegative()\n .max(TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS);\n\n/** Canonical device observation time: an ISO-8601 UTC instant with milliseconds. */\nconst TerminalInferenceReportedAtSchema = z\n .iso\n .datetime({ offset: true, precision: 3 })\n .refine((value) => value.endsWith('Z'), 'reportedAt must be canonical UTC (Z)');\n\n/**\n * A bounded, non-billing observation associated with one terminal runtime\n * outcome. It is optional on every terminal payload so a pre-U2 daemon remains\n * a legal v1 peer. `promptTokens` and `completionTokens` are values a runtime\n * reported for its final observed turn; they are not a storage-accounting or\n * invoice authority.\n */\nexport const TerminalInferenceUsageSchema = z.object({\n /** The adapter that actually started this task, never a requested fallback. */\n runtime: RuntimeIdSchema,\n /** Omitted unless the adapter itself exposed this provider observation. */\n provider: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH).optional(),\n /** Omitted unless the adapter itself exposed this model observation. */\n model: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),\n /** Direct projection of the runtime's final observed input token count. */\n promptTokens: TerminalInferenceUsageNumberSchema.optional(),\n /** Direct projection of the runtime's final observed output token count. */\n completionTokens: TerminalInferenceUsageNumberSchema.optional(),\n /** Device-observed elapsed duration for the started task. */\n durationMs: TerminalInferenceUsageDurationSchema.optional(),\n /** Process-immutable Local Agent release version, owned outside the protocol. */\n clientVersion: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH),\n /** Device observation time, never server receipt time. */\n reportedAt: TerminalInferenceReportedAtSchema,\n});\nexport type TerminalInferenceUsage = z.infer<typeof TerminalInferenceUsageSchema>;\n\n/**\n * The prepared-only terminal observation: what the runtime reported about the\n * provider calls of ONE prepared Execution, bound to the frozen request it\n * launched.\n *\n * - `requestDigest` — the frozen artifact's own request digest\n * (`InputPreparationArtifactSummarySchema.requestDigest`), so the Host\n * compares these numbers against exactly the D whose `requestBytes` it\n * ruled on.\n * - `initialPromptTokens` — the prompt tokens of the FIRST provider call. It\n * is the only call whose request is D; every later call is an ordinary tool\n * continuation. Prompt tokens are the provider's whole prompt, cache reads\n * and writes included.\n * - `maxPromptTokens` — the largest prompt of any provider call of the\n * Execution, so `maxPromptTokens >= initialPromptTokens`.\n *\n * A separate field, deliberately NOT {@link TerminalInferenceUsageSchema}:\n * that one is telemetry and never task-state authority, while this one is the\n * evidence a Host checks its own budget ruling against. The device performs no\n * budget arithmetic over it. Strict, like every other control shape: an\n * unrecognized field is rejected, not stripped.\n */\nexport const TerminalPreparedObservationSchema = z\n .object({\n requestDigest: InputPreparationArtifactSummarySchema.shape.requestDigest,\n initialPromptTokens: TerminalInferenceUsageNumberSchema,\n maxPromptTokens: TerminalInferenceUsageNumberSchema,\n })\n .strict()\n .refine((value) => value.maxPromptTokens >= value.initialPromptTokens, {\n message: 'maxPromptTokens must not be below initialPromptTokens',\n path: ['maxPromptTokens'],\n });\nexport type TerminalPreparedObservation = z.infer<typeof TerminalPreparedObservationSchema>;\n\n/**\n * The task-free Agent-home projection (`agent.home_projection`) that the\n * device had already applied when an Agent Attempt started. The writer lease\n * keeps a new projection out of the home until the Attempt ends, so this is\n * the persona the Attempt ran with. The SDK does not compare it with the\n * offer's `agentRef.profileRevision`: the host decides whether a mismatch\n * matters. Absent when the task was not Agent-bound, or when the home had no\n * applied projection record.\n */\nexport const TerminalAgentHomeProjectionSchema = z\n .object({\n profileRevision: AgentHomeProjectionProfileRevisionSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n })\n .strict();\nexport type TerminalAgentHomeProjection = z.infer<typeof TerminalAgentHomeProjectionSchema>;\n\n/** Maximum memory files one reader digest covers: `MEMORY.md` plus every entry under `notes/`. */\nexport const AGENT_HOME_MEMORY_DIGEST_MAX_FILES = 256;\n/** Maximum bytes of memory files one reader digest reads. */\nexport const AGENT_HOME_MEMORY_DIGEST_MAX_BYTES = 16 * 1024 * 1024;\n/** Maximum length of one changed memory path, relative to the Agent home. */\nexport const AGENT_HOME_MEMORY_PATH_MAX_LENGTH = 1024;\n\nconst AgentHomeMemoryChangedPathsSchema = z\n .array(z.string().min(1).max(AGENT_HOME_MEMORY_PATH_MAX_LENGTH).regex(/^[^\\u0000]+$/u))\n .min(1)\n // A path can leave one digest and another can enter the other one.\n .max(AGENT_HOME_MEMORY_DIGEST_MAX_FILES * 2);\n\n/**\n * Memory-change evidence of one `memory-reader` Attempt. The device hashes\n * `MEMORY.md` and every file under `notes/` when the reader starts and again\n * at its terminal, and compares the two digests.\n *\n * - `unchanged`: the digests are equal.\n * - `reader-attributed`: the digests differ and no writer Attempt of the home\n * overlapped this reader. A reader Attempt changed memory: this one, or\n * another reader that overlapped it.\n * - `unattributed`: the digests differ and a writer Attempt overlapped this\n * reader, so the change has no single source.\n * - `unmeasured`: the digest bound was exceeded, or a read failed.\n *\n * `paths` lists the changed files relative to the home, with `/` separators.\n * The device sees only Attempts it runs; a host that writes memory files\n * itself while readers run makes the attribution ambiguous. Absent on writer\n * terminals and on a claimed failure before the Attempt became active.\n */\nexport const TerminalAgentHomeMemoryChangeSchema = z.discriminatedUnion('outcome', [\n z.object({ outcome: z.literal('unchanged') }).strict(),\n z.object({ outcome: z.literal('reader-attributed'), paths: AgentHomeMemoryChangedPathsSchema }).strict(),\n z.object({ outcome: z.literal('unattributed'), paths: AgentHomeMemoryChangedPathsSchema }).strict(),\n z.object({ outcome: z.literal('unmeasured') }).strict(),\n]);\nexport type TerminalAgentHomeMemoryChange = z.infer<typeof TerminalAgentHomeMemoryChangeSchema>;\n\n/**\n * daemon -> server: task finished successfully.\n *\n * `document` (docs/protocol.md §7.2): the OPTIONAL\n * structured terminal result of the task — one JSON value the product on the\n * other side consumes as the task's actual output, as opposed to `summary`\n * (human-readable prose) or `artifactRefs` (files). Deliberately\n * `z.unknown()`: this SDK never understands, validates, or transforms the\n * product's own document schema — that validation belongs to the consumer.\n * The only constraints the wire imposes are the ones\n * {@link checkResultDocument} enforces: it must be PLAIN JSON DATA (equal to\n * its own JSON round trip — see that function for why \"stringify succeeded\"\n * is not enough), and its canonical JSON UTF-8 encoding must be at most\n * {@link RESULT_DOCUMENT_MAX_BYTES}. An over-cap document is REJECTED here,\n * never truncated (see that constant's own doc comment). A sender puts the\n * check's `canonical` snapshot on the wire, never the original object.\n *\n * Wire v3: every v3 server keeps this field, so no capability flag gates it\n * (the v2 `result-document` flag is gone). For a\n * `terminalProjection.mode: 'result-document'` offer it carries the outcome\n * the daemon validated against the offer's frozen schema\n * (`validateResultOutcome`, `result-schema.ts`, at most\n * `RESULT_OUTCOME_MAX_BYTES`).\n */\nconst TaskCompletePlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n harnessId: HarnessIdSchema.optional(),\n summary: z.string(),\n /**\n * The runtime's closing reply: the assistant text after the last tool\n * interaction, or the last whole message for a runtime whose `progress`\n * events are whole messages (Codex). `summary` keeps the whole run's text,\n * so a host reads the final answer here without parsing commentary out of\n * it. Absent when the run ended with no closing text. An older server strips\n * this optional field; the host then sees it absent and keeps `summary`.\n */\n finalMessage: z.string().optional(),\n sessionRef: z.string(),\n artifactRefs: z.array(BlobRefSchema).optional(),\n document: z\n .unknown()\n .optional()\n .refine((value) => value === undefined || checkResultDocument(value).ok, {\n message: `task.complete.document must be plain JSON data (equal to its own JSON round trip) and at most ${RESULT_DOCUMENT_MAX_BYTES} bytes as canonical JSON (UTF-8)`,\n }),\n usage: TerminalInferenceUsageSchema.optional(),\n /** Present on a prepared Execution only — see {@link TerminalPreparedObservationSchema}. */\n preparedObservation: TerminalPreparedObservationSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/** A runtime failure class this version knows (#869). `unknown` means the runtime gave no structured evidence. */\nexport const RuntimeFailureClassSchema = z.enum(RUNTIME_FAILURE_CLASSES);\nexport type RuntimeFailureClass = z.infer<typeof RuntimeFailureClassSchema>;\n\n/** Whether a `quota` limit covers the whole account or one model (#1271). */\nexport const RuntimeQuotaScopeSchema = z.enum(RUNTIME_QUOTA_SCOPES);\nexport type RuntimeQuotaScope = z.infer<typeof RuntimeQuotaScopeSchema>;\n\n/**\n * The machine-readable failure of a `task.fail` (#869); `reason` stays display\n * text. `resetsAt` (ISO 8601 UTC) and `scope` exist only on `quota`, and only\n * when the runtime reported them. `scope` is gated on the server's\n * `runtime-quota-scope` flag (#1271).\n *\n * The class is open (#1121): a well-formed class this version does not know,\n * with whatever fields a newer device put beside it, is accepted and kept\n * verbatim, so the terminal is still recorded. {@link readTaskFailure} is the\n * typed reading.\n */\nexport const TaskFailureSchema = z.union([\n z.object({ class: z.literal('quota'), resetsAt: z.iso.datetime().optional(), scope: RuntimeQuotaScopeSchema.optional() }).strict(),\n z.object({ class: RuntimeFailureClassSchema.exclude(['quota']) }).strict(),\n z.looseObject({ class: unrecognizedToken(RUNTIME_FAILURE_CLASSES) }),\n]);\nexport type TaskFailure = z.infer<typeof TaskFailureSchema>;\n\n/** A {@link TaskFailure} as this version understands it: a class it does not know reads as `unknown`, its raw token kept. */\nexport type TaskFailureReading =\n | { readonly class: 'quota'; readonly resetsAt?: string; readonly scope?: RuntimeQuotaScope }\n | { readonly class: Exclude<RuntimeFailureClass, 'quota' | 'unknown'> }\n | { readonly class: 'unknown'; readonly reportedClass?: string };\n\nexport function readTaskFailure(failure: TaskFailure): TaskFailureReading {\n if ((RUNTIME_FAILURE_CLASSES as readonly string[]).includes(failure.class)) return failure as TaskFailureReading;\n return { class: 'unknown', reportedClass: failure.class };\n}\n\n/** daemon -> server: task failed. */\nconst TaskFailPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n /** Local interruption observation bound to the immutable offer; does not assert a cloud claim. */\n recovery: z.object({ kind: z.literal('daemon_interrupted'), offerId: z.uuid() }).strict().optional(),\n harnessId: HarnessIdSchema.optional(),\n /**\n * Display text, bounded by `boundFailureReason` on every parse (#1124):\n * credentials redacted, at most `TASK_FAIL_REASON_MAX_BYTES` UTF-8 bytes.\n * `createEnvelope` and every decode apply it, so one place bounds every\n * sender and receiver. A longer reason is truncated, never refused.\n */\n reason: z.string().transform(boundFailureReason),\n retryable: z.boolean().optional(),\n /** Gated on the server's `runtime-failure-class` flag. Plaintext on the sealed branch too. */\n failure: TaskFailureSchema.optional(),\n usage: TerminalInferenceUsageSchema.optional(),\n /** Present on a prepared Execution that observed provider usage before failing. */\n preparedObservation: TerminalPreparedObservationSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/**\n * daemon -> server: task ended in the `Cancelled` state (M1 gap #6) — either\n * in response to a server-sent `task.cancel`, or a cancellation the daemon\n * observed/decided locally (e.g. a local stop action) that the server didn't\n * initiate. This is the canonical way to report a `Cancelled` outcome; it\n * supersedes the M0 convention of `task.fail({ reason: 'cancelled' })`.\n *\n * This is deliberately its own message rather than folded into `task.fail`\n * (decision: prefer the explicit message — see docs/protocol.md) because\n * `Cancelled` is semantically distinct from `Failed`: one is an intentional\n * stop, the other an error. Overloading `task.fail` with a magic\n * `reason: 'cancelled'` string convention hid that distinction on the wire.\n *\n * Dual-purpose on receipt: if the server already moved its own record to\n * `Cancelled` (it initiated the cancel — M1 gap #3's \"server state is\n * authoritative\" rule), this is an idempotent no-op ack. If the server\n * hasn't yet (a locally-observed cancellation), this is the authoritative\n * trigger that moves `Claimed`/`Running`/`AwaitApproval -> Cancelled`.\n */\nconst TaskCancelledPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n harnessId: HarnessIdSchema.optional(),\n reason: z.string().optional(),\n usage: TerminalInferenceUsageSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/**\n * daemon -> server: a pending `task.await_approval` was resolved entirely\n * LOCALLY on the device — the local control-socket `approvals.resolve` RPC,\n * a fail-closed `requestApproval` timeout, or a fail-closed eviction/finish\n * rejection (see `packages/client`'s `task-runner.ts`/`approvals.ts`) —\n * *without* a wire `task.approve`/`task.reject` ever having been exchanged\n * for it. Baseline since v4: the daemon reports every local resolution, and\n * this report is the server's only source for one; the server does not infer\n * a resolution from later task activity.\n *\n * Observability-class tolerance applies (not control/security — see the\n * freeze rule's asymmetry, `docs/protocol.md`): this is a daemon reporting\n * what it already did locally, not a payload that grants/denies anything on\n * its own — the receiving server's own state machine (`TASK_TRANSITIONS`,\n * `task-state.ts`) is still what decides whether the reported resolution is\n * legal to apply. Plain `z.object()` (not `.strict()`), same as every other\n * non-control payload in this file.\n *\n * `resolvedBy` is a single-value enum (`'local'`) rather than a bare string:\n * a later wave could add a DISTINCT value as a gated addition, while the\n * shape stays closed and typed today.\n */\nexport const TaskApprovalResolvedPayloadSchema = z.object({\n approvalId: z.string(),\n decision: z.enum(['approve', 'reject']),\n resolvedBy: z.enum(['local']),\n at: z.iso.datetime({ offset: true }),\n});\nexport type TaskApprovalResolvedPayload = z.infer<typeof TaskApprovalResolvedPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// Sealed payload v1 (#654): the sealed branch of each sealable type\n//\n// A sealable type's payload is a union: the plaintext branch (which refuses\n// `sealed` and `sealing`) and a strict sealed branch. The sealed branch is the\n// plaintext fields without the ones `SEALED_SPLIT_TABLE` moves into the\n// ciphertext or drops, plus `sealed`. The wire `type` stays plaintext. Each\n// sealed branch is gated on `sealed-payload-v1` by its marker field\n// (`wire-additions.ts`). `task.offer`'s branches are above.\n// ---------------------------------------------------------------------------\n\n/**\n * server -> daemon: sealed steering text. `steerId` names this steer in the\n * AAD and the content MAC, so the Host cannot replay an earlier steer of the\n * same task as a new one.\n */\nexport const TaskSteerSealedPayloadSchema = z.object({ steerId: z.uuid(), sealed: SealedTaskInputSchema }).strict();\nexport type TaskSteerSealedPayload = z.infer<typeof TaskSteerSealedPayloadSchema>;\n\n/**\n * daemon -> server: `task.complete` of a sealed task. `summary`,\n * `finalMessage` and `document` are sealed. `artifactRefs` and\n * `preparedObservation` are not carried in v1.\n */\nexport const TaskCompleteSealedPayloadSchema = TaskCompletePlainPayloadSchema.omit({\n summary: true,\n finalMessage: true,\n document: true,\n artifactRefs: true,\n preparedObservation: true,\n})\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskCompleteSealedPayload = z.infer<typeof TaskCompleteSealedPayloadSchema>;\n\n/** daemon -> server: `task.fail` of a sealed task. `reason` is sealed; `preparedObservation` is not carried in v1. */\nexport const TaskFailSealedPayloadSchema = TaskFailPlainPayloadSchema.omit({ reason: true, preparedObservation: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskFailSealedPayload = z.infer<typeof TaskFailSealedPayloadSchema>;\n\n/**\n * daemon -> server: `task.decline` of a sealed task with a sealed `reason`.\n * The sealed decline codes go only on the plaintext branch: a device that\n * cannot open or use the scope key often cannot seal a reply either.\n */\nexport const TaskDeclineSealedPayloadSchema = DeclineFields.omit({ reason: true })\n .extend({\n code: z.union([z.enum(HOME_DECLINE_CODES), unrecognizedToken(DECLINE_CODES)]).optional(),\n sealed: SealedTaskOutputSchema,\n })\n .strict();\nexport type TaskDeclineSealedPayload = z.infer<typeof TaskDeclineSealedPayloadSchema>;\n\n/** daemon -> server: `task.cancelled` of a sealed task. `reason` is sealed. */\nexport const TaskCancelledSealedPayloadSchema = TaskCancelledPlainPayloadSchema.omit({ reason: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskCancelledSealedPayload = z.infer<typeof TaskCancelledSealedPayloadSchema>;\n\n/** daemon -> server: `task.progress` of a sealed task. `events` is sealed; `seq` names the batch. */\nexport const TaskProgressSealedPayloadSchema = TaskProgressPlainPayloadSchema.omit({ events: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskProgressSealedPayload = z.infer<typeof TaskProgressSealedPayloadSchema>;\n\n/**\n * daemon -> server: an inline artifact of a sealed task. `inline` is sealed; a\n * blob artifact is not carried in v1. `artifactId` names the write in the AAD\n * and the content MAC, because two artifacts of one task may share a `name`.\n */\nexport const TaskArtifactSealedPayloadSchema = TaskArtifactPlainPayloadSchema.omit({ inline: true, blobRef: true })\n .extend({ artifactId: z.uuid(), sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskArtifactSealedPayload = z.infer<typeof TaskArtifactSealedPayloadSchema>;\n\n/** daemon -> server: `task.await_approval` of a sealed task. `summary` is sealed; `approvalId` is required. */\nexport const TaskAwaitApprovalSealedPayloadSchema = TaskAwaitApprovalPlainPayloadSchema.omit({ summary: true })\n .extend({ approvalId: z.string().min(1), sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskAwaitApprovalSealedPayload = z.infer<typeof TaskAwaitApprovalSealedPayloadSchema>;\n\n// Each sealable payload: the plaintext branch first, then the sealed branch.\n// Narrow with `payload.sealed !== undefined`; the plaintext branch's `sealed` is `never`.\n// Each member is written `X as typeof X` (see `MESSAGE_PAYLOAD_SCHEMAS`).\n\nexport const TaskSteerPayloadSchema = z.union([\n TaskSteerPlainPayloadSchema as typeof TaskSteerPlainPayloadSchema,\n TaskSteerSealedPayloadSchema as typeof TaskSteerSealedPayloadSchema,\n]);\nexport type TaskSteerPayload = z.infer<typeof TaskSteerPayloadSchema>;\n\nexport const TaskDeclinePayloadSchema = z.union([\n TaskDeclinePlainPayloadSchema as typeof TaskDeclinePlainPayloadSchema,\n TaskDeclineSealedPayloadSchema as typeof TaskDeclineSealedPayloadSchema,\n]);\nexport type TaskDeclinePayload = z.infer<typeof TaskDeclinePayloadSchema>;\n\nexport const TaskProgressPayloadSchema = z.union([\n TaskProgressPlainPayloadSchema as typeof TaskProgressPlainPayloadSchema,\n TaskProgressSealedPayloadSchema as typeof TaskProgressSealedPayloadSchema,\n]);\nexport type TaskProgressPayload = z.infer<typeof TaskProgressPayloadSchema>;\n\nexport const TaskArtifactPayloadSchema = z.union([\n TaskArtifactPlainPayloadSchema as typeof TaskArtifactPlainPayloadSchema,\n TaskArtifactSealedPayloadSchema as typeof TaskArtifactSealedPayloadSchema,\n]);\nexport type TaskArtifactPayload = z.infer<typeof TaskArtifactPayloadSchema>;\n\nexport const TaskAwaitApprovalPayloadSchema = z.union([\n TaskAwaitApprovalPlainPayloadSchema as typeof TaskAwaitApprovalPlainPayloadSchema,\n TaskAwaitApprovalSealedPayloadSchema as typeof TaskAwaitApprovalSealedPayloadSchema,\n]);\nexport type TaskAwaitApprovalPayload = z.infer<typeof TaskAwaitApprovalPayloadSchema>;\n\nexport const TaskCompletePayloadSchema = z.union([\n TaskCompletePlainPayloadSchema as typeof TaskCompletePlainPayloadSchema,\n TaskCompleteSealedPayloadSchema as typeof TaskCompleteSealedPayloadSchema,\n]);\nexport type TaskCompletePayload = z.infer<typeof TaskCompletePayloadSchema>;\n\nexport const TaskFailPayloadSchema = z.union([\n TaskFailPlainPayloadSchema as typeof TaskFailPlainPayloadSchema,\n TaskFailSealedPayloadSchema as typeof TaskFailSealedPayloadSchema,\n]);\nexport type TaskFailPayload = z.infer<typeof TaskFailPayloadSchema>;\n\nexport const TaskCancelledPayloadSchema = z.union([\n TaskCancelledPlainPayloadSchema as typeof TaskCancelledPlainPayloadSchema,\n TaskCancelledSealedPayloadSchema as typeof TaskCancelledSealedPayloadSchema,\n]);\nexport type TaskCancelledPayload = z.infer<typeof TaskCancelledPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// registry — single source of truth mapping message type -> payload schema\n// ---------------------------------------------------------------------------\n\n/**\n * Each value is written `X as typeof X`. The assertion is type-only (no\n * runtime code). It makes declaration emit name each schema (`typeof X`)\n * instead of copying its full type, which keeps the published `.d.ts` small.\n * Every new entry follows this rule. Entries are grouped by direction.\n */\nexport const MESSAGE_PAYLOAD_SCHEMAS = {\n 'conn.hello': ConnHelloPayloadSchema as typeof ConnHelloPayloadSchema,\n 'task.offer': TaskOfferPayloadSchema as typeof TaskOfferPayloadSchema,\n 'agent.egress.ack': AgentEgressAckPayloadSchema as typeof AgentEgressAckPayloadSchema,\n 'agent.message.disposition': AgentMessageDispositionPayloadSchema as typeof AgentMessageDispositionPayloadSchema,\n 'agent.content.read': AgentContentReadPayloadSchema as typeof AgentContentReadPayloadSchema,\n 'agent.home.projection': AgentHomeProjectionPayloadSchema as typeof AgentHomeProjectionPayloadSchema,\n 'agent.input.preparation': AgentInputPreparationPayloadSchema as typeof AgentInputPreparationPayloadSchema,\n 'provider.provisioning.available': ProviderProvisioningAvailablePayloadSchema as typeof ProviderProvisioningAvailablePayloadSchema,\n 'agent.memory.intent.available': AgentMemoryIntentAvailablePayloadSchema as typeof AgentMemoryIntentAvailablePayloadSchema,\n 'task.approve': TaskApprovePayloadSchema as typeof TaskApprovePayloadSchema,\n 'task.reject': TaskRejectPayloadSchema as typeof TaskRejectPayloadSchema,\n 'task.cancel': TaskCancelPayloadSchema as typeof TaskCancelPayloadSchema,\n 'task.steer': TaskSteerPayloadSchema as typeof TaskSteerPayloadSchema,\n 'e2ee.key_package.available': E2eeKeyPackageAvailablePayloadSchema as typeof E2eeKeyPackageAvailablePayloadSchema,\n 'task.claim': TaskClaimPayloadSchema as typeof TaskClaimPayloadSchema,\n 'task.started': TaskStartedPayloadSchema as typeof TaskStartedPayloadSchema,\n 'task.decline': TaskDeclinePayloadSchema as typeof TaskDeclinePayloadSchema,\n 'task.progress': TaskProgressPayloadSchema as typeof TaskProgressPayloadSchema,\n 'task.artifact': TaskArtifactPayloadSchema as typeof TaskArtifactPayloadSchema,\n 'task.await_approval': TaskAwaitApprovalPayloadSchema as typeof TaskAwaitApprovalPayloadSchema,\n 'task.complete': TaskCompletePayloadSchema as typeof TaskCompletePayloadSchema,\n 'task.fail': TaskFailPayloadSchema as typeof TaskFailPayloadSchema,\n 'task.cancelled': TaskCancelledPayloadSchema as typeof TaskCancelledPayloadSchema,\n 'task.approval_resolved': TaskApprovalResolvedPayloadSchema as typeof TaskApprovalResolvedPayloadSchema,\n 'agent.egress.reliable': AgentEgressReliablePayloadSchema as typeof AgentEgressReliablePayloadSchema,\n 'agent.message.draft': AgentMessageDraftPayloadSchema as typeof AgentMessageDraftPayloadSchema,\n 'agent.message.publish': AgentMessagePublishPayloadSchema as typeof AgentMessagePublishPayloadSchema,\n 'agent.content.receipt': AgentContentReceiptPayloadSchema as typeof AgentContentReceiptPayloadSchema,\n} as const;\n\nexport type MessageType = keyof typeof MESSAGE_PAYLOAD_SCHEMAS;\n\nexport const MESSAGE_TYPES = Object.keys(MESSAGE_PAYLOAD_SCHEMAS) as MessageType[];\n\n/**\n * Message types the server sends to the daemon. Used by {@link EnvelopeSchema}\n * (`envelope.ts`) to decide which branches require envelope `seq` (M1\n * redelivery cursor).\n */\nexport const SERVER_TO_DAEMON_TYPES = [\n 'task.offer',\n 'agent.egress.ack',\n 'agent.message.disposition',\n 'agent.content.read',\n 'agent.home.projection',\n 'agent.input.preparation',\n 'provider.provisioning.available',\n 'agent.memory.intent.available',\n 'task.approve',\n 'task.reject',\n 'task.cancel',\n 'task.steer',\n 'e2ee.key_package.available',\n] as const satisfies readonly MessageType[];\n\n/**\n * Message types the daemon sends to the server — the flip side of\n * {@link SERVER_TO_DAEMON_TYPES}. `conn.hello` is deliberately excluded: the\n * inbound gate handles a bearer-authenticated `conn.hello` as a capability\n * snapshot on its own, before the type-allow check.\n *\n * Used by `handleInboundEnvelope` (`@byok-sdk/cloud`'s `inbound.ts`) as the\n * type-allow gate for every inbound `POST /byok/messages` envelope (finding\n * P2): a `type` outside this set — a server -> daemon type arriving inbound,\n * or anything unrecognized — is rejected before it's dispatched to any\n * handler or counted `accepted` on the `/byok/messages` wire.\n */\nexport const DAEMON_TO_SERVER_TYPES = [\n 'task.claim',\n 'task.started',\n 'task.decline',\n 'task.progress',\n 'task.artifact',\n 'task.await_approval',\n 'task.complete',\n 'task.fail',\n 'task.cancelled',\n 'task.approval_resolved',\n 'agent.egress.reliable',\n 'agent.message.draft',\n 'agent.message.publish',\n 'agent.content.receipt',\n] as const satisfies readonly MessageType[];\n","import { z } from 'zod';\nimport { AgentHomeProjectionAgentRefSchema } from './messages';\n\n/**\n * Host-approved Agent memory intents — the wire half.\n *\n * A Host (the only approval authority) approves one exact memory operation on\n * one device-local Agent home. The device (the only memory content authority)\n * applies it with its existing sha256 CAS at most once and reports a terminal,\n * content-free completion. This package defines only:\n *\n * - the device capability that gates the task-free server -> daemon notice\n * `agent.memory.intent.available`, whose strict payload is exactly\n * `{ intentId, agentRef }` (see `messages.ts`);\n * - the immutable intent a Host releases over its own device routes;\n * - the fetch request/response a device exchanges with those routes;\n * - the terminal completion a device reports and the durable readback a Host\n * returns for it.\n *\n * Notice-and-fetch is the point: memory content never rides the mailbox or the\n * device journal. The only field that carries content is `content` on a\n * `release` of a `replace` intent.\n *\n * Path authority stays with the device. This schema applies only the syntactic\n * bounds the device ledger relies on (at most 1024 ASCII bytes that need no\n * JSON escaping); the exact memory path rule (`MEMORY.md` or\n * `notes/<safe>/…md`) and the `MEMORY.md` delete ban are evaluated by the\n * device and reported as `path_invalid` / `memory_md_not_deletable`. Host-only\n * path policy is Host vocabulary and stays out of this package, as do\n * audiences, route paths and product names.\n *\n * `operationDigest` is pinned to `@byok-sdk/core`\n * `agentMemoryIntentOperationDigest(...)`, which a device recomputes with its\n * own enrolled tenant and device ids.\n */\n\n/** Maximum UTF-8 byte length of a released `replace` body (one memory file): 256 KiB. */\nexport const AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES = 262_144;\n/** Maximum byte length of an intent `path` (ASCII, so bytes = characters). */\nexport const AGENT_MEMORY_INTENT_PATH_MAX_BYTES = 1024;\n/** Maximum byte length of an opaque `approvalRef` (ASCII, so bytes = characters). */\nexport const AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES = 128;\n\nconst SHA256_REVISION = /^sha256:[0-9a-f]{64}$/u;\n\n/** A memory file revision: `sha256:` over the file bytes (a missing file is the empty-bytes digest). */\nexport const AgentMemoryIntentRevisionSchema = z\n .string()\n .regex(SHA256_REVISION, 'revision must be lowercase sha256:<64 hex>');\nexport type AgentMemoryIntentRevision = z.infer<typeof AgentMemoryIntentRevisionSchema>;\n\n/** The identity-and-operation binding; see `@byok-sdk/core` `agentMemoryIntentOperationDigest`. */\nexport const AgentMemoryIntentOperationDigestSchema = z\n .string()\n .regex(SHA256_REVISION, 'operationDigest must be lowercase sha256:<64 hex>');\nexport type AgentMemoryIntentOperationDigest = z.infer<typeof AgentMemoryIntentOperationDigestSchema>;\n\n/**\n * Syntactic bound only: 1..1024 printable ASCII characters that need no JSON\n * escaping (no `\"`, no `\\`, no control characters). The device applies the\n * exact memory path rule.\n */\nexport const AgentMemoryIntentPathSchema = z\n .string()\n .min(1)\n .max(AGENT_MEMORY_INTENT_PATH_MAX_BYTES)\n .regex(/^[\\x20\\x21\\x23-\\x5b\\x5d-\\x7e]+$/u, 'path must be printable ASCII without quote or backslash');\nexport type AgentMemoryIntentPath = z.infer<typeof AgentMemoryIntentPathSchema>;\n\n/** Opaque audit correlation. The device records it and never evaluates it. */\nexport const AgentMemoryIntentApprovalRefSchema = z\n .string()\n .regex(\n new RegExp(`^[A-Za-z0-9._:-]{1,${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES}}$`, 'u'),\n `approvalRef must be 1..${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES} characters of [A-Za-z0-9._:-]`,\n );\nexport type AgentMemoryIntentApprovalRef = z.infer<typeof AgentMemoryIntentApprovalRefSchema>;\n\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\nconst utf8 = new TextEncoder();\n\n/** A `replace` body: well-formed Unicode whose UTF-8 encoding is at most 256 KiB. */\nexport const AgentMemoryIntentContentSchema = z\n .string()\n .refine((value) => !LONE_SURROGATE.test(value), 'content must be well-formed Unicode (encodable as UTF-8)')\n .refine(\n (value) => utf8.encode(value).byteLength <= AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES,\n `content must not exceed ${AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES} UTF-8 bytes`,\n );\nexport type AgentMemoryIntentContent = z.infer<typeof AgentMemoryIntentContentSchema>;\n\nexport const AGENT_MEMORY_INTENT_OPERATIONS = ['replace', 'delete'] as const;\nexport const AgentMemoryIntentOperationSchema = z.enum(AGENT_MEMORY_INTENT_OPERATIONS);\nexport type AgentMemoryIntentOperation = z.infer<typeof AgentMemoryIntentOperationSchema>;\n\n/**\n * The immutable Host-approved intent.\n *\n * - `replace`: `targetRevision` is the digest of the approved body and must\n * differ from `baseRevision`; `content` appears only inside a `release`.\n * - `delete`: `targetRevision` is `null` and there is never `content`.\n */\nexport const AgentMemoryIntentV1Schema = z\n .object({\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n path: AgentMemoryIntentPathSchema,\n operation: AgentMemoryIntentOperationSchema,\n baseRevision: AgentMemoryIntentRevisionSchema,\n targetRevision: AgentMemoryIntentRevisionSchema.nullable(),\n content: AgentMemoryIntentContentSchema.optional(),\n approvalRef: AgentMemoryIntentApprovalRefSchema,\n operationDigest: AgentMemoryIntentOperationDigestSchema,\n })\n .strict()\n .superRefine((intent, ctx) => {\n if (intent.operation === 'delete') {\n if (intent.targetRevision !== null) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'a delete intent has a null targetRevision' });\n }\n if (intent.content !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['content'], message: 'a delete intent never carries content' });\n }\n return;\n }\n if (intent.targetRevision === null) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'a replace intent requires a targetRevision' });\n } else if (intent.targetRevision === intent.baseRevision) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'targetRevision must differ from baseRevision' });\n }\n });\nexport type AgentMemoryIntentV1 = z.infer<typeof AgentMemoryIntentV1Schema>;\n\n// ---------------------------------------------------------------------------\n// Completion and readback\n// ---------------------------------------------------------------------------\n\n/**\n * Codes a Host decides on its own authority. They are the only `withheld`\n * codes and the only codes a `host_terminal` readback may carry.\n */\nexport const AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES = [\n 'intent_revoked',\n 'intent_expired',\n 'placement_changed',\n 'profile_revision_changed',\n] as const;\nexport const AgentMemoryIntentHostTerminalCodeSchema = z.enum(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES);\nexport type AgentMemoryIntentHostTerminalCode = z.infer<typeof AgentMemoryIntentHostTerminalCodeSchema>;\n\n/**\n * Closed rejection set. A code names the failed check, never a value. Every\n * `rejected` completion means the device wrote no `applying` record and made\n * zero memory writes.\n */\nexport const AGENT_MEMORY_INTENT_REJECTION_CODES = [\n 'intent_invalid',\n 'path_invalid',\n 'memory_md_not_deletable',\n 'content_invalid',\n 'intent_digest_mismatch',\n 'agent_ref_mismatch',\n 'agent_home_unavailable',\n ...AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES,\n] as const;\nexport const AgentMemoryIntentRejectionCodeSchema = z.enum(AGENT_MEMORY_INTENT_REJECTION_CODES);\nexport type AgentMemoryIntentRejectionCode = z.infer<typeof AgentMemoryIntentRejectionCodeSchema>;\n\n/** One device observation of the target file. The observation instant is not on the wire. */\nexport const AgentMemoryIntentFileObservationSchema = z\n .object({\n exists: z.boolean(),\n revision: AgentMemoryIntentRevisionSchema,\n })\n .strict();\nexport type AgentMemoryIntentFileObservation = z.infer<typeof AgentMemoryIntentFileObservationSchema>;\n\nconst completionIdentity = {\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n path: AgentMemoryIntentPathSchema,\n operation: AgentMemoryIntentOperationSchema,\n operationDigest: AgentMemoryIntentOperationDigestSchema,\n} as const;\n\nconst AppliedCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('applied'), result: AgentMemoryIntentFileObservationSchema })\n .strict();\nconst ConflictCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('conflict'), observed: AgentMemoryIntentFileObservationSchema })\n .strict();\nconst RejectedCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('rejected'), code: AgentMemoryIntentRejectionCodeSchema })\n .strict();\nconst UncertainCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('uncertain'), observed: AgentMemoryIntentFileObservationSchema })\n .strict();\n\n/**\n * The terminal, content-free result of one intent, reported by the device.\n *\n * - `applied`: the live-path CAS returned success; `result` is the file after it.\n * - `conflict`: the live-path CAS refused on revision; this attempt wrote nothing.\n * - `rejected`: no `applying` record was written; zero writes.\n * - `uncertain`: whether this intent wrote is unknown; `observed` is only the\n * current file, never provenance.\n *\n * There is no non-terminal outcome.\n */\nexport const AgentMemoryIntentCompletionSchema = z.discriminatedUnion('outcome', [\n AppliedCompletionSchema,\n ConflictCompletionSchema,\n RejectedCompletionSchema,\n UncertainCompletionSchema,\n]);\nexport type AgentMemoryIntentCompletion = z.infer<typeof AgentMemoryIntentCompletionSchema>;\n\n/**\n * How the Host's durable record relates to the completion it was handed:\n *\n * - `recorded`: this completion became the intent's first terminal fact.\n * - `idempotent`: an identical completion was already recorded.\n * - `conflict`: a different completion is already recorded; it is returned.\n * - `host_terminal`: the Host had already terminated the intent on its own\n * authority ({@link AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES}).\n */\nexport const AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS = ['recorded', 'idempotent', 'conflict', 'host_terminal'] as const;\nexport const AgentMemoryIntentReadbackDispositionSchema = z.enum(AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS);\nexport type AgentMemoryIntentReadbackDisposition = z.infer<typeof AgentMemoryIntentReadbackDispositionSchema>;\n\n/**\n * The Host's durable terminal readback for one intent. `completion` is the\n * terminal fact the Host has STORED; on `host_terminal` it is always a\n * `rejected` completion carrying a Host code. `recordedAt` is the Host record\n * time, never a device observation time.\n */\nexport const AgentMemoryIntentReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n intentId: z.uuid(),\n disposition: AgentMemoryIntentReadbackDispositionSchema,\n completion: AgentMemoryIntentCompletionSchema,\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((readback, ctx) => {\n if (readback.completion.intentId !== readback.intentId) {\n ctx.addIssue({ code: 'custom', path: ['completion', 'intentId'], message: 'completion intentId must equal readback intentId' });\n }\n if (\n readback.disposition === 'host_terminal' &&\n (readback.completion.outcome !== 'rejected' ||\n !(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES as readonly string[]).includes(readback.completion.code))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['completion'],\n message: `a host_terminal readback must carry a rejected completion with one of: ${AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.join(', ')}`,\n });\n }\n });\nexport type AgentMemoryIntentReadback = z.infer<typeof AgentMemoryIntentReadbackSchema>;\n\n// ---------------------------------------------------------------------------\n// Fetch\n// ---------------------------------------------------------------------------\n\n/**\n * `held`: the device reserved a ledger slot and may receive a release.\n * `none`: the device could not reserve; the Host must not change intent state\n * or release content.\n */\nexport const AGENT_MEMORY_INTENT_RESERVATIONS = ['held', 'none'] as const;\nexport const AgentMemoryIntentReservationSchema = z.enum(AGENT_MEMORY_INTENT_RESERVATIONS);\nexport type AgentMemoryIntentReservation = z.infer<typeof AgentMemoryIntentReservationSchema>;\n\n/**\n * The SDK half of a fetch. Device authentication (the tenant and device a Host\n * trusts) is Host transport vocabulary and is not part of this schema.\n */\nexport const AgentMemoryIntentFetchRequestSchema = z\n .object({\n intentId: z.uuid(),\n reservation: AgentMemoryIntentReservationSchema,\n })\n .strict();\nexport type AgentMemoryIntentFetchRequest = z.infer<typeof AgentMemoryIntentFetchRequestSchema>;\n\nexport const AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS = ['release', 'withheld', 'terminal', 'deferred'] as const;\nexport type AgentMemoryIntentFetchDisposition = (typeof AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS)[number];\n\n/** Which fetch dispositions a Host may answer for each request reservation. */\nexport const AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION = {\n held: ['release', 'withheld', 'terminal'],\n none: ['terminal', 'deferred'],\n} as const satisfies Record<AgentMemoryIntentReservation, readonly AgentMemoryIntentFetchDisposition[]>;\n\nfunction requireNoContent(intent: AgentMemoryIntentV1, ctx: z.RefinementCtx, disposition: string): void {\n if (intent.content !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['intent', 'content'], message: `a ${disposition} fetch response never carries content` });\n }\n}\n\nconst ReleaseFetchResponseSchema = z\n .object({ disposition: z.literal('release'), intent: AgentMemoryIntentV1Schema })\n .strict()\n .superRefine((response, ctx) => {\n if (response.intent.operation === 'replace' && response.intent.content === undefined) {\n ctx.addIssue({ code: 'custom', path: ['intent', 'content'], message: 'a replace release must carry content' });\n }\n });\n\nconst WithheldFetchResponseSchema = z\n .object({ disposition: z.literal('withheld'), intent: AgentMemoryIntentV1Schema, code: AgentMemoryIntentHostTerminalCodeSchema })\n .strict()\n .superRefine((response, ctx) => requireNoContent(response.intent, ctx, 'withheld'));\n\nconst TerminalFetchResponseSchema = z\n .object({ disposition: z.literal('terminal'), intent: AgentMemoryIntentV1Schema, readback: AgentMemoryIntentReadbackSchema })\n .strict()\n .superRefine((response, ctx) => {\n requireNoContent(response.intent, ctx, 'terminal');\n const { intent, readback } = response;\n if (readback.intentId !== intent.intentId) {\n ctx.addIssue({ code: 'custom', path: ['readback', 'intentId'], message: 'readback intentId must equal intent intentId' });\n }\n const completion = readback.completion;\n if (\n completion.agentRef.agentId !== intent.agentRef.agentId ||\n completion.agentRef.profileRevision !== intent.agentRef.profileRevision ||\n completion.path !== intent.path ||\n completion.operation !== intent.operation ||\n completion.operationDigest !== intent.operationDigest\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['readback', 'completion'],\n message: 'readback completion identity must equal the intent identity and operationDigest',\n });\n }\n });\n\nconst DeferredFetchResponseSchema = z\n .object({ disposition: z.literal('deferred'), intent: AgentMemoryIntentV1Schema })\n .strict()\n .superRefine((response, ctx) => requireNoContent(response.intent, ctx, 'deferred'));\n\n/**\n * A Host fetch answer, independent of the request reservation. A device must\n * parse with {@link agentMemoryIntentFetchResponseSchemaFor} so a `release` or\n * `withheld` answer to a `none` request (or a `deferred` answer to a `held`\n * request) is refused.\n */\nexport const AgentMemoryIntentFetchResponseSchema = z.discriminatedUnion('disposition', [\n ReleaseFetchResponseSchema,\n WithheldFetchResponseSchema,\n TerminalFetchResponseSchema,\n DeferredFetchResponseSchema,\n]);\nexport type AgentMemoryIntentFetchResponse = z.infer<typeof AgentMemoryIntentFetchResponseSchema>;\n\n/** The fetch answer schema bound to the reservation the device sent. */\nexport function agentMemoryIntentFetchResponseSchemaFor(reservation: AgentMemoryIntentReservation) {\n const allowed: readonly AgentMemoryIntentFetchDisposition[] =\n AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION[AgentMemoryIntentReservationSchema.parse(reservation)];\n return AgentMemoryIntentFetchResponseSchema.superRefine((response, ctx) => {\n if (!allowed.includes(response.disposition)) {\n ctx.addIssue({\n code: 'custom',\n path: ['disposition'],\n message: `a ${reservation} reservation allows only: ${allowed.join(', ')}`,\n });\n }\n });\n}\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema, AgentEgressPolicyRevisionSchema } from './agent-egress';\nimport { AgentRefSchema, RuntimeIdSchema } from './messages';\nimport { SealedMemoryProjectionSchema } from './sealed-payload';\n\n/** One hosted projection is bounded before it enters the redaction or storage seam. */\nexport const AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES = 512 * 1024;\n\n/** PostgreSQL `integer` ceiling shared by writer epochs and source sequences. */\nexport const AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE = 2_147_483_647;\n\nconst OPAQUE_REFERENCE_MAX_BYTES = 512;\nconst opaqueReference = (field: string) => z\n .string()\n .min(1)\n .max(OPAQUE_REFERENCE_MAX_BYTES)\n .refine((value) => new TextEncoder().encode(value).byteLength <= OPAQUE_REFERENCE_MAX_BYTES, {\n message: `${field} must not exceed ${OPAQUE_REFERENCE_MAX_BYTES} UTF-8 bytes`,\n })\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, `${field} must not contain control characters`);\n\n/** Opaque, embedder-issued authorization grant. It is never interpreted as a consent boolean. */\nexport const AgentMemoryProjectionGrantRefSchema = opaqueReference('grantRef');\nexport type AgentMemoryProjectionGrantRef = z.infer<typeof AgentMemoryProjectionGrantRefSchema>;\n\n/** Exact local runtime session identity. No cwd or local source path is portable. */\nexport const AgentMemoryProjectionSessionRefSchema = opaqueReference('sessionRef');\nexport type AgentMemoryProjectionSessionRef = z.infer<typeof AgentMemoryProjectionSessionRefSchema>;\n\n/** Positive epoch that changes only when the local single-writer authority changes. */\nexport const AgentMemoryProjectionWriterEpochSchema = z\n .number()\n .int()\n .positive()\n .max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);\nexport type AgentMemoryProjectionWriterEpoch = z.infer<typeof AgentMemoryProjectionWriterEpochSchema>;\n\n/** Positive sequence within one writer epoch. A new epoch starts at one. */\nexport const AgentMemoryProjectionSourceSeqSchema = z\n .number()\n .int()\n .positive()\n .max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);\nexport type AgentMemoryProjectionSourceSeq = z.infer<typeof AgentMemoryProjectionSourceSeqSchema>;\n\n/** Byte length implied by the unpadded base64url transport string. */\nexport function agentMemoryProjectionBase64UrlByteLength(value: string): number | undefined {\n if (!/^[A-Za-z0-9_-]*$/u.test(value) || value.length % 4 === 1) return undefined;\n const complete = Math.floor(value.length / 4) * 3;\n const tail = value.length % 4;\n return complete + (tail === 0 ? 0 : tail - 1);\n}\n\n/**\n * The only body-bearing field in the hosted contract. It is already redacted\n * by the embedder; source bytes, raw-source hashes, cwd, and local paths never\n * cross this boundary. The hosted store re-hashes these bytes before commit.\n */\nexport const AgentMemoryProjectionSnapshotSchema = z\n .object({\n redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n redactedBytes: z.string().max(Math.ceil(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES / 3) * 4),\n })\n .strict()\n .superRefine((snapshot, ctx) => {\n const actual = agentMemoryProjectionBase64UrlByteLength(snapshot.redactedBytes);\n if (actual === undefined) {\n ctx.addIssue({ code: 'custom', path: ['redactedBytes'], message: 'redactedBytes must be unpadded base64url' });\n return;\n }\n if (actual !== snapshot.redactedByteCount) {\n ctx.addIssue({\n code: 'custom',\n path: ['redactedByteCount'],\n message: 'redactedByteCount must equal the decoded redactedBytes length',\n });\n }\n });\nexport type AgentMemoryProjectionSnapshot = z.infer<typeof AgentMemoryProjectionSnapshotSchema>;\n\n/** The plaintext identity and ordering fields of every mutation branch. */\nconst MUTATION_IDENTITY = {\n taskId: z.string().min(1).max(512),\n agentRef: AgentRefSchema,\n sessionRef: AgentMemoryProjectionSessionRefSchema,\n runtimeId: RuntimeIdSchema,\n grantRef: AgentMemoryProjectionGrantRefSchema,\n writerEpoch: AgentMemoryProjectionWriterEpochSchema,\n sourceSeq: AgentMemoryProjectionSourceSeqSchema,\n mutationId: z.uuid(),\n policyRevision: AgentEgressPolicyRevisionSchema,\n};\n\n/**\n * Device -> hosted mutation for one redacted full snapshot. It intentionally\n * contains no tenant/device identity: authenticated transport supplies both.\n * The snapshot is a one-way copy of local `MEMORY.md` plus local `notes/`, not\n * a remote authoring, merge, import, history, or RAG contract.\n */\nexport const AgentMemoryProjectionPlainMutationSchema = z\n .object({ ...MUTATION_IDENTITY, snapshot: AgentMemoryProjectionSnapshotSchema, sealed: z.never().optional() })\n .strict();\nexport type AgentMemoryProjectionPlainMutation = z.infer<typeof AgentMemoryProjectionPlainMutationSchema>;\n\n/**\n * The mutation under a grant that names a sealing scope (#1045 C4). The\n * redacted snapshot is sealed, inline only, under the Agent's memory scope;\n * its plaintext hash and byte count are not carried. The AAD binds\n * `{ agentId, writerEpoch, sourceSeq, mutationId }`, so the Host cannot move\n * a snapshot to another Agent, epoch or position.\n */\nexport const AgentMemoryProjectionSealedMutationSchema = z\n .object({ ...MUTATION_IDENTITY, sealed: SealedMemoryProjectionSchema, snapshot: z.never().optional() })\n .strict();\nexport type AgentMemoryProjectionSealedMutation = z.infer<typeof AgentMemoryProjectionSealedMutationSchema>;\n\n/** Narrow with `mutation.sealed !== undefined`. */\nexport const AgentMemoryProjectionMutationSchema = z.union([\n AgentMemoryProjectionPlainMutationSchema as typeof AgentMemoryProjectionPlainMutationSchema,\n AgentMemoryProjectionSealedMutationSchema as typeof AgentMemoryProjectionSealedMutationSchema,\n]);\nexport type AgentMemoryProjectionMutation = z.infer<typeof AgentMemoryProjectionMutationSchema>;\n\n/** Stable meter receipt for one accepted redacted snapshot; it never carries the snapshot body. */\nexport const AgentMemoryProjectionMeteringReceiptSchema = z\n .object({\n meteringReceiptId: z.uuid(),\n acceptedRedactedBytes: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\nexport type AgentMemoryProjectionMeteringReceipt = z.infer<typeof AgentMemoryProjectionMeteringReceiptSchema>;\n\nconst RECEIPT_IDENTITY = {\n outcome: z.enum(['accepted', 'idempotent']),\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n ...MUTATION_IDENTITY,\n};\n\n/** Immutable commit readback. It repeats identity and redacted metadata, never redacted bytes. */\nexport const AgentMemoryProjectionPlainReceiptSchema = z\n .object({\n ...RECEIPT_IDENTITY,\n redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n metering: AgentMemoryProjectionMeteringReceiptSchema,\n })\n .strict();\nexport type AgentMemoryProjectionPlainReceipt = z.infer<typeof AgentMemoryProjectionPlainReceiptSchema>;\n\n/** Stable meter receipt for one accepted sealed snapshot: the Host meters the padded length it stores. */\nexport const AgentMemoryProjectionSealedMeteringReceiptSchema = z\n .object({\n meteringReceiptId: z.uuid(),\n acceptedPaddedBytes: SealedMemoryProjectionSchema.shape.paddedLength,\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\nexport type AgentMemoryProjectionSealedMeteringReceipt = z.infer<typeof AgentMemoryProjectionSealedMeteringReceiptSchema>;\n\n/** Immutable commit readback of a sealed snapshot: identity and the sealed member's `contentMac` and padded length. */\nexport const AgentMemoryProjectionSealedReceiptSchema = z\n .object({\n ...RECEIPT_IDENTITY,\n contentMac: SealedMemoryProjectionSchema.shape.contentMac,\n paddedLength: SealedMemoryProjectionSchema.shape.paddedLength,\n metering: AgentMemoryProjectionSealedMeteringReceiptSchema,\n })\n .strict();\nexport type AgentMemoryProjectionSealedReceipt = z.infer<typeof AgentMemoryProjectionSealedReceiptSchema>;\n\nexport const AgentMemoryProjectionReceiptSchema = z.union([\n AgentMemoryProjectionPlainReceiptSchema as typeof AgentMemoryProjectionPlainReceiptSchema,\n AgentMemoryProjectionSealedReceiptSchema as typeof AgentMemoryProjectionSealedReceiptSchema,\n]);\nexport type AgentMemoryProjectionReceipt = z.infer<typeof AgentMemoryProjectionReceiptSchema>;\n\n/**\n * Server-side erase result. The returned epoch is the minimum legal epoch for\n * a later host-issued writer grant; erased source epochs can never re-enter.\n */\nexport const AgentMemoryProjectionEraseResultSchema = z\n .object({ nextWriterEpoch: AgentMemoryProjectionWriterEpochSchema })\n .strict();\nexport type AgentMemoryProjectionEraseResult = z.infer<typeof AgentMemoryProjectionEraseResultSchema>;\n","import { z } from 'zod';\nimport { MESSAGE_PAYLOAD_SCHEMAS, SERVER_TO_DAEMON_TYPES, type MessageType } from './messages';\nimport { PROTOCOL_VERSION } from './version';\n\nconst REQUIRED_TASK_ID = z.string().min(1);\nconst OPTIONAL_TASK_ID = REQUIRED_TASK_ID.optional();\nconst FORBIDDEN_TASK_ID = z.never().optional();\nconst REQUIRED_SEQ = z.number().int();\nconst OPTIONAL_SEQ = REQUIRED_SEQ.optional();\n\n/**\n * The schema `envelopeShape` returns, written out so declaration emit names\n * each branch of `EnvelopeSchema` instead of copying every payload type.\n * Type-only: it must stay equal to the inferred `z.object` type below.\n */\ntype EnvelopeShape<T extends MessageType, TaskId extends z.ZodTypeAny, Seq extends z.ZodTypeAny> = z.ZodObject<{\n v: z.ZodNumber;\n id: z.ZodUUID;\n ts: z.ZodISODateTime;\n type: z.ZodLiteral<T>;\n task_id: TaskId;\n session_ref: z.ZodOptional<z.ZodString>;\n seq: Seq;\n payload: (typeof MESSAGE_PAYLOAD_SCHEMAS)[T];\n}, z.core.$strip>;\n\n/**\n * Build the full envelope schema for one message type. Field order here\n * matches the spec's documented shape (`v, id, ts, type, task_id?,\n * session_ref?, seq?, payload`) so parsed output has predictable key order.\n *\n * `taskId`/`seq` are passed in as concrete schemas (not a boolean flag)\n * so each call site's return type is precisely the required-or-optional\n * shape for that branch — `z.infer<typeof EnvelopeSchema>` then reflects the\n * per-message-type requiredness rather than collapsing it to `string |\n * undefined` for every branch.\n */\nfunction envelopeShape<\n T extends MessageType,\n TaskId extends z.ZodTypeAny,\n Seq extends z.ZodTypeAny,\n>(type: T, taskId: TaskId, seq: Seq): EnvelopeShape<T, TaskId, Seq> {\n return z.object({\n // A known payload shape does not authorize interpreting another wire major\n // as v1. Keep the public number type and all supported v1 bytes unchanged.\n v: z.number().int().refine((version): boolean => version === PROTOCOL_VERSION, {\n message: 'unsupported protocol version',\n }),\n id: z.uuid(),\n ts: z.iso.datetime({ offset: true }),\n type: z.literal(type),\n task_id: taskId,\n session_ref: z.string().optional(),\n seq,\n payload: MESSAGE_PAYLOAD_SCHEMAS[type],\n });\n}\n\n/**\n * The wire envelope: common transport fields plus a `payload` whose shape is\n * determined by `type`. Unknown top-level fields are tolerated (stripped) for\n * forward-compat; unknown `type` values do not match any branch below and are\n * handled explicitly by {@link parseMessage} in `codec.ts`.\n *\n * Two cross-cutting requiredness rules, fixed at M1 (see docs/protocol.md\n * \"M0 -> M1 breaking changes\"):\n *\n * - `task_id` is REQUIRED for every `task.*` type (they all route by task id)\n * and stays optional for `conn.*` (M1 gap #1).\n * - `seq` is REQUIRED for every type the *server* sends to the daemon — a\n * per-device monotonic counter used as a redelivery cursor — and stays\n * optional for daemon -> server types (M1 redelivery cursor; see\n * `conn.hello.cursor` in `messages.ts`).\n */\nexport const EnvelopeSchema = z.discriminatedUnion('type', [\n // conn.hello: task_id stays optional (no task routing); it is\n // daemon -> server, so there is no cursor to satisfy on this leg.\n envelopeShape('conn.hello', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n\n // server -> daemon: seq required (per-device redelivery cursor); task.*\n // also requires task_id (routing key).\n envelopeShape('task.offer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.egress.ack', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.message.disposition', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.content.read', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.home.projection', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.input.preparation', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('provider.provisioning.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.memory.intent.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.approve', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.reject', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.cancel', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.steer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('e2ee.key_package.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n\n // daemon -> server: task.* requires task_id (routing key); envelope-level\n // seq is not required in this direction (no daemon->server redelivery\n // cursor — see docs/protocol.md).\n envelopeShape('task.claim', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.started', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.decline', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.progress', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.artifact', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.await_approval', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.complete', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.fail', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.cancelled', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.approval_resolved', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.egress.reliable', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.message.draft', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.message.publish', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.content.receipt', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n]);\n\nexport type Envelope = z.infer<typeof EnvelopeSchema>;\n\n/** `true` for every message type the server sends to the daemon (envelope `seq` is required for these). */\nexport function isServerToDaemonType(type: MessageType): boolean {\n return (SERVER_TO_DAEMON_TYPES as readonly MessageType[]).includes(type);\n}\n","import type { ZodError } from 'zod';\n\n/** Base class for all protocol decode/validation errors. */\nexport class ProtocolError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ProtocolError';\n }\n}\n\n/** The input was not valid JSON at all (only thrown by `decodeEnvelope`). */\nexport class EnvelopeParseError extends ProtocolError {\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n this.name = 'EnvelopeParseError';\n }\n}\n\n/**\n * The `type` field did not match any known message type. This is distinct\n * from {@link EnvelopeValidationError} on purpose: a daemon/server on an\n * older minor version should catch this specifically and skip the message\n * instead of treating it as a bug, since a newer peer may have introduced an\n * additive message type it doesn't understand yet.\n */\nexport class UnknownMessageTypeError extends ProtocolError {\n public readonly type: unknown;\n\n constructor(type: unknown) {\n super(`Unknown message type: ${String(type)}`);\n this.name = 'UnknownMessageTypeError';\n this.type = type;\n }\n}\n\n/** The `type` field was recognized but the envelope/payload failed schema validation. */\nexport class EnvelopeValidationError extends ProtocolError {\n public readonly issues: ZodError;\n\n constructor(message: string, issues: ZodError) {\n super(message, { cause: issues });\n this.name = 'EnvelopeValidationError';\n this.issues = issues;\n }\n}\n","import type { z } from 'zod';\nimport { EnvelopeSchema, type Envelope } from './envelope';\nimport { MESSAGE_TYPES, MESSAGE_PAYLOAD_SCHEMAS, type MessageType } from './messages';\nimport { PROTOCOL_VERSION } from './version';\nimport { EnvelopeParseError, EnvelopeValidationError, UnknownMessageTypeError } from './errors';\n\nconst MESSAGE_TYPE_SET = new Set<string>(MESSAGE_TYPES);\n\nfunction decodeText(input: string | Uint8Array): string {\n return typeof input === 'string' ? input : new TextDecoder('utf-8').decode(input);\n}\n\n/**\n * Validate an already-parsed JS value as an {@link Envelope}, narrowing\n * `payload` by `type`. Throws {@link UnknownMessageTypeError} when `type`\n * isn't a recognized message type (safe for the caller to skip/ignore), or\n * {@link EnvelopeValidationError} when a recognized type fails schema\n * validation.\n */\nexport function parseMessage(data: unknown): Envelope {\n const result = EnvelopeSchema.safeParse(data);\n if (result.success) {\n return result.data;\n }\n\n const typeValue =\n typeof data === 'object' && data !== null && !Array.isArray(data)\n ? (data as Record<string, unknown>).type\n : undefined;\n\n if (typeof typeValue !== 'string' || !MESSAGE_TYPE_SET.has(typeValue)) {\n throw new UnknownMessageTypeError(typeValue);\n }\n\n throw new EnvelopeValidationError(\n `Envelope failed validation for type \"${typeValue}\"`,\n result.error,\n );\n}\n\n/**\n * Decode a single NDJSON line into a validated {@link Envelope}. Accepts a\n * string or raw bytes (e.g. a binary transport frame) — isomorphic, no\n * stream handling required of the caller.\n */\nexport function decodeEnvelope(line: string | Uint8Array): Envelope {\n const text = decodeText(line).replace(/[\\r\\n]+$/, '');\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (cause) {\n throw new EnvelopeParseError('Envelope line is not valid JSON', cause);\n }\n return parseMessage(json);\n}\n\n/** Encode an {@link Envelope} as a single-line NDJSON string (trailing `\\n` included). */\nexport function encodeEnvelope(env: Envelope): string {\n return `${JSON.stringify(env)}\\n`;\n}\n\n// ---------------------------------------------------------------------------\n// createEnvelope — finding F1: `taskId`/`seq` used to be uniformly optional\n// regardless of `type`, so e.g. `createEnvelope('task.offer', payload)` (no\n// `taskId`, no `seq`) type-checked cleanly and only failed much later, at\n// runtime, wherever the resulting envelope happened to get decoded — often\n// on the *other* side of the wire, several hops from the actual mistake.\n//\n// `EnvelopeShapeOptions` is the per-type source of truth for `taskId`/`seq`\n// requiredness, deliberately parallel to `envelope.ts`'s own\n// `envelopeShape()` calls (which encode the identical rule at the schema\n// level — see docs/protocol.md §1.1/§1.2): every `task.*` type requires\n// `taskId`; every type the *server* sends to the daemon additionally\n// requires `seq`. `createEnvelope`'s `opts` parameter is conditionally\n// required/optional per `T` from this map (`RequiredKeys`/`CreateEnvelopeArgs`\n// below), so a call site missing a required field is a compile error, not a\n// runtime surprise. The constructed envelope is also validated against\n// {@link EnvelopeSchema} before being returned, throwing\n// {@link EnvelopeValidationError} on failure — a second, runtime-level net\n// for whatever the type system can't catch (e.g. a payload widened via `as`).\n// ---------------------------------------------------------------------------\n\ninterface EnvelopeShapeOptions {\n 'conn.hello': { taskId?: string; seq?: number };\n 'task.offer': { taskId: string; seq: number };\n 'agent.egress.ack': { taskId?: string; seq: number };\n 'agent.message.disposition': { taskId: string; seq: number };\n 'agent.content.read': { taskId?: string; seq: number };\n 'agent.home.projection': { taskId?: never; seq: number };\n 'agent.input.preparation': { taskId?: never; seq: number };\n 'provider.provisioning.available': { taskId?: never; seq: number };\n 'agent.memory.intent.available': { taskId?: never; seq: number };\n 'task.approve': { taskId: string; seq: number };\n 'task.reject': { taskId: string; seq: number };\n 'task.cancel': { taskId: string; seq: number };\n 'task.steer': { taskId: string; seq: number };\n 'e2ee.key_package.available': { taskId?: never; seq: number };\n 'task.claim': { taskId: string; seq?: number };\n 'task.started': { taskId: string; seq?: number };\n 'task.decline': { taskId: string; seq?: number };\n 'task.progress': { taskId: string; seq?: number };\n 'task.artifact': { taskId: string; seq?: number };\n 'task.await_approval': { taskId: string; seq?: number };\n 'task.complete': { taskId: string; seq?: number };\n 'task.fail': { taskId: string; seq?: number };\n 'task.cancelled': { taskId: string; seq?: number };\n 'task.approval_resolved': { taskId: string; seq?: number };\n 'agent.egress.reliable': { taskId?: string; seq?: number };\n 'agent.message.draft': { taskId: string; seq?: number };\n 'agent.message.publish': { taskId: string; seq?: number };\n 'agent.content.receipt': { taskId?: string; seq?: number };\n}\n\ninterface EnvelopeCommonOptions {\n id?: string;\n ts?: string;\n v?: number;\n /** Always optional regardless of `type` (docs/protocol.md §1.3). */\n sessionRef?: string;\n}\n\n/** Public options shape for `createEnvelope<T>` — conditionally required `taskId`/`seq` per `EnvelopeShapeOptions[T]`, plus the always-optional common fields. Defaults to the full `MessageType` union (a loose, all-optional-ish shape) when `T` isn't pinned, which is also what `createEnvelope`'s own implementation uses internally to read `opts` without fighting the per-call-site conditional. */\nexport type CreateEnvelopeOptions<T extends MessageType = MessageType> = EnvelopeCommonOptions &\n EnvelopeShapeOptions[T];\n\n/** `never` unless every key of `T` is optional — i.e. whether `createEnvelope`'s `opts` argument can be omitted entirely for a given message type. */\ntype RequiredKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];\n\n/** The rest-parameter shape for `createEnvelope`'s 3rd argument: present-and-optional when `T` needs nothing, present-and-required when it needs `taskId` and/or `seq`. */\ntype CreateEnvelopeArgs<T extends MessageType> = RequiredKeys<EnvelopeShapeOptions[T]> extends never\n ? [opts?: CreateEnvelopeOptions<T>]\n : [opts: CreateEnvelopeOptions<T>];\n\ntype PayloadOf<T extends MessageType> = z.infer<(typeof MESSAGE_PAYLOAD_SCHEMAS)[T]>;\n\n/**\n * Build a well-formed {@link Envelope}, filling `v`/`id`/`ts` with defaults.\n * `opts` (`taskId`/`seq`) is required or optional depending on `type` — see\n * the module doc above — and the constructed envelope is validated against\n * {@link EnvelopeSchema} before being returned, throwing\n * {@link EnvelopeValidationError} if it doesn't satisfy the schema.\n */\nexport function createEnvelope<T extends MessageType>(\n type: T,\n payload: PayloadOf<T>,\n ...rest: CreateEnvelopeArgs<T>\n): Extract<Envelope, { type: T }> {\n // `rest[0]`'s precise per-T type doesn't survive being read back out\n // inside a generic function body (a well-known TS limitation, not a\n // soundness gap: every concrete instantiation of `T` at the call site was\n // already checked against `CreateEnvelopeArgs<T>` above) — `opts` is\n // treated as the loose, common shape here, and the schema validation below\n // is what actually guards this function's output either way.\n const opts = (rest[0] ?? {}) as CreateEnvelopeOptions;\n const envelope = {\n v: opts.v ?? PROTOCOL_VERSION,\n id: opts.id ?? crypto.randomUUID(),\n ts: opts.ts ?? new Date().toISOString(),\n type,\n ...(opts.taskId !== undefined ? { task_id: opts.taskId } : {}),\n ...(opts.sessionRef !== undefined ? { session_ref: opts.sessionRef } : {}),\n ...(opts.seq !== undefined ? { seq: opts.seq } : {}),\n payload,\n };\n\n const result = EnvelopeSchema.safeParse(envelope);\n if (!result.success) {\n throw new EnvelopeValidationError(`createEnvelope built an invalid envelope for type \"${type}\"`, result.error);\n }\n return result.data as Extract<Envelope, { type: T }>;\n}\n","import { z } from 'zod';\nimport { PROTOCOL_VERSION } from './version';\nimport { CONTENT_HASH_RE } from './blob';\nimport {\n AgentRefSchema,\n ConfiguredToolsetsSchema,\n ProtocolVersionNumberSchema,\n RuntimeCapabilitiesSchema,\n RuntimeIdSchema,\n RuntimeUnavailableEntrySchema,\n RuntimeVersionPolicyProjectionSchema,\n AgentHomeProjectionAgentRefSchema,\n} from './messages';\nimport {\n InputPreparationProfileIdSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationReceiptSummarySchema,\n InputPreparationRejectionReasonSchema,\n} from './input-preparation';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionOutcomeSchema,\n} from './agent-home-projection';\nimport {\n AgentMemoryProjectionMutationSchema,\n AgentMemoryProjectionReceiptSchema,\n} from './agent-memory-projection';\n\n/**\n * HTTP-side request/response shapes for the reference server's auth and blob\n * endpoints (M1 Part B). These are plain HTTP bodies, not wire envelopes —\n * kept in a separate module from `envelope.ts`/`messages.ts` because they\n * are HTTP request/response bodies rather than mailbox envelopes. Documented\n * in full in docs/protocol.md (\"Auth flows\", \"Blob flows\", \"Long-poll\").\n *\n * The wire protocol version (`v:1`) is unaffected by any of this: pairing,\n * token renewal, and blob transfer are separate HTTP calls around the\n * long-poll mailbox lifecycle, not envelope types.\n */\n\n// ---------------------------------------------------------------------------\n// POST /byok/pair (v2) — one-time device pairing. An out-of-band pairing\n// code (minted by the SaaS's own auth/device-flow UI) plus a freshly\n// generated Ed25519 device keypair (private key never leaves the device)\n// register the device and mint its first access token.\n// ---------------------------------------------------------------------------\n\nexport const PairRequestSchema = z.object({\n pairingCode: z.string(),\n deviceName: z.string(),\n /** Ed25519 public key, base64url-encoded. Private key stays device-local (OS keychain or 0600 file). */\n devicePublicKey: z.string(),\n /**\n * Optional client-hashed physical machine identity: lowercase hex SHA-256 of\n * the product id and an OS-provided machine identifier, never the raw\n * identifier itself. It names no tenant and no product — those still come\n * only from the redeemed pairing code's claims — so it can only ever\n * supersede the SAME tenant/product's prior active device rows carrying this\n * exact digest. A client that cannot resolve one omits the field entirely.\n */\n machineId: z.string().regex(/^[0-9a-f]{64}$/u).optional(),\n});\nexport type PairRequest = z.infer<typeof PairRequestSchema>;\n\n/**\n * The authenticated tenant projection is opaque to the wire protocol. It is\n * bounded so a malformed control-plane value cannot become an unbounded local\n * key prefix, while deliberately imposing no product-specific format.\n *\n * Keep these runtime checks aligned with `@byok-sdk/core`'s TenantId mint\n * point: trimming or normalizing here would make the response disagree with\n * the authenticated device row that authored it.\n */\nexport const PAIR_RESPONSE_TENANT_ID_MAX_LENGTH = 200;\nexport const PairResponseTenantIdSchema = z\n .string()\n .min(1)\n .max(PAIR_RESPONSE_TENANT_ID_MAX_LENGTH)\n .refine((value) => value.trim() === value, {\n message: 'tenantId must not have leading or trailing whitespace',\n })\n .refine((value) => !value.includes('\\u0000'), {\n message: 'tenantId must not contain a NUL character',\n });\n\nexport const PairResponseSchema = z.object({\n deviceId: z.string(),\n /** JWT, ~1h lifetime. */\n accessToken: z.string(),\n /** Opaque hint for when/how to renew (e.g. an ISO timestamp); not itself a credential. */\n refreshHint: z.string().optional(),\n /**\n * Lifetime of `accessToken` in seconds, relative to when the device receives\n * this response. The device-side lifetime authority (#1114): a device never\n * compares a server timestamp with its own clock. Optional on the wire\n * because published v4 hosts omit it; the client requires it.\n */\n expiresIn: z.number().int().positive().optional(),\n /** Exact opaque, non-secret tenant binding from the authenticated device row. */\n tenantId: PairResponseTenantIdSchema,\n});\nexport type PairResponse = z.infer<typeof PairResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/challenge + POST /byok/token — token renewal without re-pairing.\n// Two-step challenge/response proves possession of the device private key\n// without ever transmitting it: the server hands out a one-time nonce, the\n// client signs it locally with the device key, and trades the signature for\n// a fresh access token.\n// ---------------------------------------------------------------------------\n\nexport const ChallengeRequestSchema = z.object({\n deviceId: z.string(),\n});\nexport type ChallengeRequest = z.infer<typeof ChallengeRequestSchema>;\n\nexport const ChallengeResponseSchema = z.object({\n /** One-time value the client must sign with its device private key. */\n nonce: z.string(),\n});\nexport type ChallengeResponse = z.infer<typeof ChallengeResponseSchema>;\n\nexport const TokenRequestSchema = z.object({\n deviceId: z.string(),\n nonce: z.string(),\n /** Ed25519 signature over `nonce`, base64url-encoded. */\n signature: z.string(),\n});\nexport type TokenRequest = z.infer<typeof TokenRequestSchema>;\n\nexport const TokenResponseSchema = z.object({\n accessToken: z.string(),\n /** Absolute server-clock expiry. Kept for published devices; current devices derive lifetime from `expiresIn`. */\n expiresAt: z.iso.datetime({ offset: true }),\n /**\n * Lifetime of `accessToken` in seconds, relative to when the device receives\n * this response (#1114). Optional on the wire because published v4 hosts\n * omit it; the client requires it.\n */\n expiresIn: z.number().int().positive().optional(),\n});\nexport type TokenResponse = z.infer<typeof TokenResponseSchema>;\n\n/**\n * The one typed `401` body of `/byok/challenge` and `/byok/token`: the device\n * id resolves to no registration (§6.3). Revocation deletes the registration,\n * so an unknown device and a revoked one answer with this same body and stay\n * indistinguishable. Every other `401` on these routes (bad signature, used\n * or expired nonce) stays untyped, and a client must not read it as\n * revocation.\n */\nexport const DEVICE_NOT_REGISTERED_CODE = 'device_not_registered';\nexport const DeviceNotRegisteredResponseSchema = z.object({\n error: z.string(),\n code: z.literal(DEVICE_NOT_REGISTERED_CODE),\n});\nexport type DeviceNotRegisteredResponse = z.infer<typeof DeviceNotRegisteredResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// PUT /byok/presence — first-hop daemon observation. The body carries only\n// facts captured by the daemon's frozen start snapshot; omitted release,\n// runtime, and auth fields remain unknown rather than guessed.\n// ---------------------------------------------------------------------------\n\n/** The hosted default is byte-bounded independently; this caps protocol input before it reaches a handler. */\nexport const PRESENCE_DETAIL_MAX_LENGTH = 512;\nexport const PRESENCE_RUNTIME_VERSION_MAX_LENGTH = 128;\n\n/**\n * Presence is a readiness observation. It retains only the facts the cloud\n * persists and bounds every string/array/numeric input at this public request\n * boundary. `capabilities` is the same capability matrix `conn.hello` reports\n * for the runtime (#1103), so a Host can read it before dispatch.\n */\nconst PresenceRuntimeFactSchema = z.object({\n id: RuntimeIdSchema,\n version: z.string().min(1).max(PRESENCE_RUNTIME_VERSION_MAX_LENGTH).optional(),\n authPresent: z.boolean().optional(),\n capabilities: RuntimeCapabilitiesSchema.optional(),\n /** #1103 D8: strip-safe discovery projection; absent means unknown. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\n\n/**\n * Presence carries the built-in runtime identity domain only (#1103 D8): a\n * custom harness id would fail an older server's whole-body decode, so\n * harness policies and versions travel on `conn.hello.harnesses[]`, never\n * here. The cause vocabulary is the same append-only one.\n */\nconst PresenceRuntimeUnavailableEntrySchema = RuntimeUnavailableEntrySchema.extend({ id: RuntimeIdSchema });\nconst PresenceRuntimeUnavailableSchema = z.array(PresenceRuntimeUnavailableEntrySchema).max(16)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate runtime-unavailable identity');\n\nexport const PresencePublishRequestSchema = z.object({\n level: z.enum(['online', 'thinking', 'working', 'error', 'offline']),\n detail: z.string().max(PRESENCE_DETAIL_MAX_LENGTH).optional(),\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n /** U4a Local Agent release version; never inferred from a host package. */\n clientVersion: z.string().min(1).max(128).optional(),\n protocolVersions: z.array(ProtocolVersionNumberSchema).max(16).optional(),\n /** Runtime version/auth facts from the same real probe as conn.hello. */\n runtimes: z.array(PresenceRuntimeFactSchema).max(16).optional(),\n /** #1103 D8: non-available built-in runtimes; strip-safe and absent means unknown. */\n runtimeUnavailable: PresenceRuntimeUnavailableSchema.optional(),\n});\nexport type PresencePublishRequest = z.infer<typeof PresencePublishRequestSchema>;\n\n/**\n * Revocation is server-side only (dashboard/API call on the SaaS's own\n * device registry) — there is no wire message for it. A revoked device's\n * next `/byok/challenge`, `/byok/token`, or authenticated mailbox call gets a 401;\n * the daemon's only recourse is to re-run `/byok/pair` from scratch.\n */\n\n// ---------------------------------------------------------------------------\n// Blob endpoints — presigned upload/download. Authed (bearer access token).\n// `BlobRef` (`blob.ts`) is unchanged; these are the HTTP calls that produce\n// the presigned URLs a `BlobRef` points at.\n// ---------------------------------------------------------------------------\n\n/** POST /byok/blobs request: declare a blob before uploading it. `contentHash` must be the canonical `sha256:<64 lowercase hex>` form (finding F9) — the server rejects anything else outright, no normalization. */\nexport const CreateBlobRequestSchema = z.object({\n size: z.number().int().nonnegative(),\n contentType: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be \"sha256:<64 lowercase hex>\"'),\n});\nexport type CreateBlobRequest = z.infer<typeof CreateBlobRequestSchema>;\n\n/** POST /byok/blobs response: presigned PUT target for the declared blob. */\nexport const CreateBlobResponseSchema = z.object({\n blobId: z.string(),\n uploadUrl: z.string(),\n});\nexport type CreateBlobResponse = z.infer<typeof CreateBlobResponseSchema>;\n\n/** GET /byok/blobs/:id/url response: presigned GET target for an existing blob. */\nexport const BlobDownloadUrlResponseSchema = z.object({\n downloadUrl: z.string(),\n});\nexport type BlobDownloadUrlResponse = z.infer<typeof BlobDownloadUrlResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// GET /byok/events?cursor=N — the daemon's authenticated receive transport.\n// Holds the request open ~50s waiting for new events and uses the mailbox's\n// at-least-once/cursor semantics (see docs/protocol.md \"At-least-once delivery\").\n// ---------------------------------------------------------------------------\n\nexport const EventsPollQuerySchema = z.object({\n /** Volatile navigation within the advertised read-ahead window; never acknowledges work. */\n afterSeq: z.number().int().nonnegative().optional(),\n /** Last reliably processed seq; the only acknowledgement. Omitted on the first poll. */\n cursor: z.number().int().nonnegative().optional(),\n});\nexport type EventsPollQuery = z.infer<typeof EventsPollQuerySchema>;\n\n/**\n * Deployment-owned activity limits. A v3 responder advertises them on every\n * events page and on every answer whose `conn.hello` it accepted; there is no\n * client-side default.\n */\nexport const ActivityIngressSchema = z.object({\n activityMaxEvents: z.number().int().positive(),\n activityMaxBytes: z.number().int().min(2),\n});\nexport type ActivityIngress = z.infer<typeof ActivityIngressSchema>;\nexport const OUTBOUND_REFUSAL_REASONS = ['payload_invalid', 'not_permitted', 'limit_exceeded', 'state_conflict', 'unsupported'] as const;\n/** `unknown` is an unrecognized wire reason string, kept as an observation. */\nexport type OutboundRefusalReason = typeof OUTBOUND_REFUSAL_REASONS[number] | 'unknown';\nfunction isOutboundRefusalCode(value: string): value is typeof OUTBOUND_REFUSAL_REASONS[number] {\n return (OUTBOUND_REFUSAL_REASONS as readonly string[]).includes(value);\n}\nexport const MessageSendOutcomeSchema = z.object({\n id: z.uuid(),\n outcome: z.enum(['accepted', 'duplicate', 'rejected']),\n /** Decodes to an {@link OutboundRefusalReason}; an unrecognized string becomes `unknown`. */\n reason: z.string().max(64).transform((value): OutboundRefusalReason => (isOutboundRefusalCode(value) ? value : 'unknown')).optional(),\n});\nexport type MessageSendOutcome = z.infer<typeof MessageSendOutcomeSchema>;\n\nexport const EventsPollResponseSchema = z.object({\n /**\n * Not-yet-decoded entries (#386). This schema decodes the page only; each\n * entry is decoded on its own with `parseMessage`, so one unknown or invalid\n * entry stalls its own sequence instead of failing every entry in the page.\n */\n events: z.array(z.unknown()),\n cursor: z.number().int(),\n /**\n * Required: the server capabilities for THIS long-poll response. Each page\n * replaces the daemon's advertisement; an empty list advertises nothing.\n */\n capabilities: z.array(z.string()),\n /** Required in v3: the activity limits that apply to new progress pushes. */\n ingress: ActivityIngressSchema,\n});\nexport type EventsPollResponse = z.infer<typeof EventsPollResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/messages — finding F6: long-poll is now a full transport, not\n// receive-only. While a device is long-polling for S->D traffic (§8), it has\n// no live WS to carry its own D->S envelopes (task.claim, task.progress,\n// task.complete, etc.) — this endpoint is that path: a batch of envelopes,\n// authed the same way as every other bearer-authed route, routed through the\n// identical inbound handling a WS connection's messages get. See\n// docs/protocol.md §8.\n// ---------------------------------------------------------------------------\n\n/**\n * Batch size ceiling for a single `POST /byok/messages` call — generous for\n * normal redelivery-catchup bursts, but bounded so one request can't force\n * the server to process an unbounded batch. Exported (not just a local\n * const) so the client's own outbound drain (`ConnectionManager.drainOutbox`,\n * finding P1) can chunk against the exact same number instead of a\n * hard-coded, driftable copy of it.\n */\nexport const MAX_MESSAGES_PER_BATCH = 256;\n\n/** Request body ceiling for `POST /byok/messages`; the cloud answers 413 above it, so the client chunks its drain by it. */\nexport const MESSAGES_SEND_MAX_BODY_BYTES = 2 * 1024 * 1024;\n\n/**\n * The batch frame only (#1121). Each entry must speak this wire major and\n * carry the UUID its outcome is correlated by; everything else is decoded per\n * entry with `parseMessage`, so one invalid envelope is answered\n * `rejected: payload_invalid` on its own instead of failing every envelope in\n * the batch — the same split as `EventsPollResponseSchema.events` (#386) on\n * the receive side. A different `v` still fails the whole request: the wire\n * major belongs to the sender, which could not read this version's outcomes.\n */\nexport const MessagesSendRequestSchema = z.object({\n messages: z.array(z.looseObject({ v: z.literal(PROTOCOL_VERSION), id: z.uuid() })).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendRequest = z.infer<typeof MessagesSendRequestSchema>;\n\n/**\n * `accepted` counts every envelope the inbound gate (`@byok-sdk/cloud`'s\n * `handleInboundEnvelope`) answered `'accepted'` *or* `'duplicate'` for — a deduped replay is a wire-level\n * success even though the business mutation did not run a second time.\n * `rejected` is omitted when zero. `outcomes` is required and correlates\n * exactly one result with each posted envelope; a rejected outcome carries its\n * reason. `ingress` is required on an answer whose `conn.hello` was accepted\n * (or deduplicated). The client enforces the per-envelope rules against the\n * posted batch and treats a violation as an unusable response.\n *\n * `capabilities` (additive) is the same server capability advertisement a\n * `GET /byok/events` response carries. A server includes it when the batch\n * carries `conn.hello`: the daemon's handshake is a lone `conn.hello` POST,\n * so its answer carries readiness and capabilities in one round trip.\n * Absence means \"no update\" — the daemon keeps the advertisement it already\n * holds — never an empty list.\n */\nexport const MessagesSendResponseSchema = z.object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative().optional(),\n capabilities: z.array(z.string()).optional(),\n ingress: ActivityIngressSchema.optional(),\n outcomes: z.array(MessageSendOutcomeSchema).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendResponse = z.infer<typeof MessagesSendResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// Task-free Agent-home projection completion/readback. These are authenticated\n// HTTP bodies, not daemon/server envelope messages. The completion request is\n// terminal and binds the exact request, AgentRef and projection hash; the\n// readback additionally carries the tenant/device routing identity and allows\n// `pending` before a daemon completion is durably recorded.\n// ---------------------------------------------------------------------------\n\nexport const AgentHomeProjectionCompletionRequestSchema = z\n .object({\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n outcome: AgentHomeProjectionOutcomeSchema,\n })\n .strict();\nexport type AgentHomeProjectionCompletionRequest = z.infer<typeof AgentHomeProjectionCompletionRequestSchema>;\n\nexport const AgentHomeProjectionStatusSchema = z.enum([\n 'pending',\n 'applied',\n 'idempotent',\n 'stale',\n 'conflict',\n]);\nexport type AgentHomeProjectionStatus = z.infer<typeof AgentHomeProjectionStatusSchema>;\n\nexport const AgentHomeProjectionReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n status: AgentHomeProjectionStatusSchema,\n completedAt: z.iso.datetime({ offset: true }).optional(),\n })\n .strict();\nexport type AgentHomeProjectionReadback = z.infer<typeof AgentHomeProjectionReadbackSchema>;\n\n// ---------------------------------------------------------------------------\n// Remote input preparation completion/readback. Same shape as the Agent-home\n// pair above and for the same reason: the device -> cloud leg of a task-free\n// control request is a direct AUTHENTICATED HTTP call, not a mailbox envelope,\n// because the daemon may advance its server -> daemon cursor only once the\n// terminal fact is durably recorded — and an outbox envelope gives it nothing\n// to wait on.\n//\n// The completion is a discriminated union rather than an outcome enum plus\n// optional siblings: `prepared` without a receipt, or `rejected` carrying one,\n// must both be unrepresentable rather than merely discouraged.\n// ---------------------------------------------------------------------------\n\nexport const InputPreparationCompletionRequestSchema = z.discriminatedUnion('outcome', [\n z\n .object({\n outcome: z.literal('prepared'),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n receipt: InputPreparationReceiptSummarySchema,\n })\n .strict(),\n z\n .object({\n outcome: z.literal('rejected'),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n reason: InputPreparationRejectionReasonSchema,\n })\n .strict(),\n]);\nexport type InputPreparationCompletionRequest = z.infer<typeof InputPreparationCompletionRequestSchema>;\n\n/** `pending` until the device records a terminal fact; the other two are terminal. */\nexport const InputPreparationStatusSchema = z.enum(['pending', 'prepared', 'rejected']);\nexport type InputPreparationStatus = z.infer<typeof InputPreparationStatusSchema>;\n\n/**\n * Tenant/device/request-bound durable readback. `receipt` and `reason` are\n * present only on their own terminal status, never together and never on\n * `pending`.\n */\nexport const InputPreparationReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n status: InputPreparationStatusSchema,\n receipt: InputPreparationReceiptSummarySchema.optional(),\n reason: InputPreparationRejectionReasonSchema.optional(),\n completedAt: z.iso.datetime({ offset: true }).optional(),\n })\n .strict()\n .superRefine((value, ctx) => {\n const expectsReceipt = value.status === 'prepared';\n const expectsReason = value.status === 'rejected';\n if (expectsReceipt !== (value.receipt !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['receipt'], message: 'receipt is present exactly when status is \"prepared\"' });\n }\n if (expectsReason !== (value.reason !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['reason'], message: 'reason is present exactly when status is \"rejected\"' });\n }\n if ((value.status !== 'pending') !== (value.completedAt !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['completedAt'], message: 'completedAt is present exactly when the status is terminal' });\n }\n });\nexport type InputPreparationReadback = z.infer<typeof InputPreparationReadbackSchema>;\n\n/**\n * Query identity for the status GET. The request key is\n * `(deviceId, agentRef, requestId)`; `deviceId` comes from bearer auth, the\n * path carries `requestId`, so only the AgentRef halves travel as query\n * parameters.\n */\nexport const InputPreparationStatusQuerySchema = z\n .object({\n agentId: z.string().min(1),\n profileRevision: z.string().min(1),\n })\n .strict();\nexport type InputPreparationStatusQuery = z.infer<typeof InputPreparationStatusQuerySchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/agent-memory-projections — optional hosted, redacted, one-way\n// snapshots. Tenant and device identity come only from bearer authentication.\n// ---------------------------------------------------------------------------\n\nexport const AgentMemoryProjectionCommitRequestSchema = AgentMemoryProjectionMutationSchema;\nexport type AgentMemoryProjectionCommitRequest = z.infer<typeof AgentMemoryProjectionCommitRequestSchema>;\n\nexport const AgentMemoryProjectionCommitResponseSchema = AgentMemoryProjectionReceiptSchema;\nexport type AgentMemoryProjectionCommitResponse = z.infer<typeof AgentMemoryProjectionCommitResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// Route paths — the single source of truth for the `/byok/*` HTTP surface.\n//\n// These literals were previously hand-copied across client, cloud, server, and\n// testkit; the doc comments above already named every one of them but exported\n// no constant. They ARE the wire contract (unlike the host-owned, opaque\n// capability vocabulary of ADR-010, which stays out of protocol), so they live\n// here and every package imports them — a route change is now one edit.\n//\n// Two shapes:\n// - Static paths (`BYOK_*_PATH`) — used identically by routers and clients.\n// - Parameterized routes: a router template (`BYOK_*_ROUTE`, with `:param`\n// placeholders) for mounting, plus a builder (`byok*Path(...)`) that fills\n// the params for a client request. Each builder reproduces its call site\n// byte-for-byte, including whether a segment is `encodeURIComponent`-encoded.\n// ---------------------------------------------------------------------------\n\n/** `POST /byok/pair` — one-time device pairing (§6). */\nexport const BYOK_PAIR_PATH = '/byok/pair';\n/** `POST /byok/challenge` — token-renewal challenge (§6.3). */\nexport const BYOK_CHALLENGE_PATH = '/byok/challenge';\n/** `POST /byok/token` — token-renewal exchange (§6.3). */\nexport const BYOK_TOKEN_PATH = '/byok/token';\n\n/** `GET /byok/capabilities` — ADR-010 declaration route. */\nexport const BYOK_CAPABILITIES_PATH = '/byok/capabilities';\n\n/** `GET /byok/events` — long-poll receive (§8). */\nexport const BYOK_EVENTS_PATH = '/byok/events';\n/** `POST /byok/messages` — long-poll batched send (§8.2). */\nexport const BYOK_MESSAGES_PATH = '/byok/messages';\n\n/** `PUT /byok/agent-home-projections/:requestId/completion`. */\nexport const BYOK_AGENT_HOME_PROJECTIONS_PATH = '/byok/agent-home-projections';\nexport const BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE =\n '/byok/agent-home-projections/:requestId/completion';\nexport function byokAgentHomeProjectionCompletionPath(requestId: string): string {\n return `${BYOK_AGENT_HOME_PROJECTIONS_PATH}/${encodeURIComponent(requestId)}/completion`;\n}\n\n/** `PUT /byok/input-preparations/:requestId/completion` and `GET /byok/input-preparations/:requestId`. */\nexport const BYOK_INPUT_PREPARATIONS_PATH = '/byok/input-preparations';\nexport const BYOK_INPUT_PREPARATION_COMPLETION_ROUTE = '/byok/input-preparations/:requestId/completion';\nexport const BYOK_INPUT_PREPARATION_STATUS_ROUTE = '/byok/input-preparations/:requestId';\nexport function byokInputPreparationCompletionPath(requestId: string): string {\n return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}/completion`;\n}\nexport function byokInputPreparationStatusPath(requestId: string): string {\n return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}`;\n}\n\n/** `POST /byok/agent-memory-projections` — optional local-to-hosted redacted snapshot commit. */\nexport const BYOK_AGENT_MEMORY_PROJECTIONS_PATH = '/byok/agent-memory-projections';\n\n/** `PUT /byok/presence` — presence heartbeat. */\nexport const BYOK_PRESENCE_PATH = '/byok/presence';\n\n/** `GET /byok/board` — coordination board list/poll. */\nexport const BYOK_BOARD_PATH = '/byok/board';\n/** `GET /byok/board/stream` — coordination board SSE. */\nexport const BYOK_BOARD_STREAM_PATH = '/byok/board/stream';\n/** Router template — `POST /byok/board/:id/claim`. */\nexport const BYOK_BOARD_CLAIM_ROUTE = '/byok/board/:id/claim';\n/** Router template — `POST /byok/board/:id/unclaim`. */\nexport const BYOK_BOARD_UNCLAIM_ROUTE = '/byok/board/:id/unclaim';\n/** Router template — `POST /byok/board/:id/status`. */\nexport const BYOK_BOARD_STATUS_ROUTE = '/byok/board/:id/status';\n\n/** `GET /byok/records` — truth manifest list (§12.3). */\nexport const BYOK_RECORDS_PATH = '/byok/records';\n/** Router template for a single truth record — `GET`/`PUT /byok/records/:kind/:key`. */\nexport const BYOK_RECORD_ROUTE = '/byok/records/:kind/:key';\n/** Client builder for a truth record path. Mirrors the `:kind/:key` template, each segment URL-encoded. */\nexport function byokRecordPath(kind: string, key: string): string {\n return `/byok/records/${encodeURIComponent(kind)}/${encodeURIComponent(key)}`;\n}\n\n/** `POST /byok/e2ee/member-key` — device proof: register the device's member key bundle and pairing MAC (#654). */\nexport const BYOK_E2EE_MEMBER_KEY_PATH = '/byok/e2ee/member-key';\n/** `POST /byok/e2ee/chain` (device proof: append) and `GET` (device: read) — the member chain. */\nexport const BYOK_E2EE_CHAIN_PATH = '/byok/e2ee/chain';\n/** `POST /byok/e2ee/key-packages` (device proof: put) and `GET` (device: this device's packages). */\nexport const BYOK_E2EE_KEY_PACKAGES_PATH = '/byok/e2ee/key-packages';\n/** `GET /byok/e2ee/pairing-mac` — device: the client pairing MAC relayed to this device. */\nexport const BYOK_E2EE_PAIRING_MAC_PATH = '/byok/e2ee/pairing-mac';\n\n/** `GET /byok/skill-packs` — skill-pack manifest catalogue. */\nexport const BYOK_SKILL_PACKS_PATH = '/byok/skill-packs';\n/** Router template for a skill-pack file — `GET /byok/skill-packs/:name/files/:path`. */\nexport const BYOK_SKILL_PACK_FILE_ROUTE = '/byok/skill-packs/:name/files/:path';\n/** Client builder for a skill-pack file path. Mirrors the `:name`/`:path` template, each segment URL-encoded. */\nexport function byokSkillPackFilePath(name: string, path: string): string {\n return `/byok/skill-packs/${encodeURIComponent(name)}/files/${encodeURIComponent(path)}`;\n}\n\n/** `POST /byok/blobs` — declare a blob upload (§7). */\nexport const BYOK_BLOBS_PATH = '/byok/blobs';\n/** Router template — `POST /byok/blobs/:id/finalize`. */\nexport const BYOK_BLOB_FINALIZE_ROUTE = '/byok/blobs/:id/finalize';\n/** Router template — `GET /byok/blobs/:id/url`. */\nexport const BYOK_BLOB_URL_ROUTE = '/byok/blobs/:id/url';\n/** Router template for the two presigned byte routes — `PUT`/`GET /byok/blobs/:id/content`. */\nexport const BYOK_BLOB_CONTENT_ROUTE = '/byok/blobs/:id/content';\n/** Client builder — `POST /byok/blobs/:id/finalize`, blob id URL-encoded (client-supplied). */\nexport function byokBlobFinalizePath(blobId: string): string {\n return `/byok/blobs/${encodeURIComponent(blobId)}/finalize`;\n}\n/** Client builder — `GET /byok/blobs/:id/url`, blob id URL-encoded (client-supplied). */\nexport function byokBlobUrlPath(blobId: string): string {\n return `/byok/blobs/${encodeURIComponent(blobId)}/url`;\n}\n/**\n * Path portion of a presigned `/byok/blobs/:id/content` URL. The blob id here\n * is a server-minted token (NOT URL-encoded, matching the reference stores that\n * mint these signed URLs); callers append the `?sig=&exp=` query themselves.\n */\nexport function byokBlobContentPath(blobId: string): string {\n return `/byok/blobs/${blobId}/content`;\n}\n","import {\n RESULT_OUTCOME_MAX_BYTES, RESULT_SCHEMA_MAX_BYTES, checkResultSchema, type ResultSchema,\n resultOutcomeMaxBytes,\n} from './result-schema';\n\nexport const BOT_TURN_OUTCOME_CONTRACT = 'bot-turn-outcome.v1';\n\n/** Code-point and item caps for Bot turn outcomes. */\nexport const BOT_TURN_OUTCOME_LIMITS = Object.freeze({\n delegateMaxItems: 2,\n delegateRequestMaxLength: 1_000,\n cancelDelegationMaxItems: 2,\n askUserQuestionMaxLength: 400,\n askUserOptionsMaxItems: 6,\n askUserOptionIdMaxLength: 24,\n askUserOptionLabelMaxLength: 80,\n confirmableActionMaxItems: 1,\n confirmableSummaryMaxLength: 300,\n confirmableDraftMaxBytes: 16_384,\n createRoutineMaxItems: 1,\n updateRoutineMaxItems: 1,\n cancelRoutineMaxItems: 2,\n routinePromptMaxLength: 500,\n postTextMaxLength: 2_730,\n roomCallMembersMaxItems: 4,\n createBotMaxItems: 3,\n updateBotMaxItems: 1,\n deleteBotMaxItems: 1,\n botNameMaxLength: 40,\n botRoleMaxLength: 80,\n botPersonaMaxLength: 300,\n createRoomMaxItems: 1,\n updateRoomMaxItems: 1,\n roomNameMaxLength: 40,\n roomMembersMaxItems: 12,\n roomAnnouncementMaxLength: 300,\n teamNoteMaxLength: 300,\n});\nconst L = BOT_TURN_OUTCOME_LIMITS;\n\nexport type NonEmptyIds = readonly [string, ...string[]];\nconst text = (maxLength: number): ResultSchema =>\n ({ type: 'string', minLength: 1, maxLength });\nconst oneOfIds = (ids: NonEmptyIds): ResultSchema => ({ enum: [...ids] });\nconst closed = (properties: Record<string, ResultSchema>, required: string[]): ResultSchema =>\n ({ type: 'object', additionalProperties: false, required, properties });\nconst list = (items: ResultSchema, maxItems: number): ResultSchema =>\n ({ type: 'array', minItems: 1, maxItems, items });\n\n/** ISO 8601 order, Monday first. Equal to core's list. A server test checks parity. */\nexport const ROUTINE_DAYS_OF_WEEK = Object.freeze(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const);\nexport type RoutineDayOfWeek = (typeof ROUTINE_DAYS_OF_WEEK)[number];\nconst integer = (minimum: number, maximum: number): ResultSchema => ({ type: 'integer', minimum, maximum });\n\nexport type BotTurnOutcomeSchemaErrorCode = 'not-subset' | 'schema-over-budget' | 'over-budget' | 'draft-over-budget';\n\nexport class BotTurnOutcomeSchemaError extends Error {\n constructor(readonly code: BotTurnOutcomeSchemaErrorCode, message: string) {\n super(message); this.name = 'BotTurnOutcomeSchemaError';\n }\n}\n\n/**\n * `checked` (default): field types, ranges and enums sit once in the outer\n * properties; each oneOf branch lists only its allowed names and required\n * fields, with additionalProperties false. An instance matches exactly one\n * branch: daysOfWeek and dayOfMonth never appear together; month needs\n * dayOfMonth. `flat`: the same outer object without the oneOf; the Host then\n * refuses those two combinations at apply time. Use `flat` only under the\n * schema budget rule of composeBotTurnOutcomeSchema. Neither form sees\n * duplicate days, a day the month never has (Apr 31), or Feb 29.\n */\nexport type RoutineScheduleShape = 'checked' | 'flat';\nfunction schedule(timeZones: NonEmptyIds, shape: RoutineScheduleShape): ResultSchema {\n const fields = {\n minute: integer(0, 59), hour: integer(0, 23),\n daysOfWeek: { type: 'array', minItems: 1, maxItems: 7, items: { enum: [...ROUTINE_DAYS_OF_WEEK] } } as ResultSchema,\n dayOfMonth: integer(1, 31), month: integer(1, 12), tz: oneOfIds(timeZones),\n };\n const outer: ResultSchema = {\n description: 'Local time in tz. No day field: every day. daysOfWeek: those days only. dayOfMonth: that day of each month, or of month only.',\n ...closed(fields, ['minute', 'hour', 'tz']),\n };\n if (shape === 'flat') return outer;\n // The outer object already requires minute, hour and tz; a branch adds only its own day field.\n const only = (names: string[], required: string[]): ResultSchema =>\n ({ additionalProperties: false, ...(required.length ? { required } : {}), properties: Object.fromEntries(names.map(n => [n, {}])) });\n return { ...outer, oneOf: [\n only(['minute', 'hour', 'tz'], []),\n only(['minute', 'hour', 'daysOfWeek', 'tz'], ['daysOfWeek']),\n only(['minute', 'hour', 'dayOfMonth', 'month', 'tz'], ['dayOfMonth']),\n ] };\n}\nfunction roomFields(members: NonEmptyIds): Record<string, ResultSchema> {\n return {\n name: text(L.roomNameMaxLength),\n members: { type: 'array', minItems: 1, maxItems: L.roomMembersMaxItems, items: oneOfIds(members) },\n admin: oneOfIds(members), mode: { enum: ['mention', 'admin'] }, announcement: text(L.roomAnnouncementMaxLength),\n };\n}\n\n/**\n * Every id is a Host-filled enum. New objects use Host-offered localId slots\n * (e.g. \"new_bot_1\"), so a same-outcome reference is also an enum member.\n */\nexport const botTurnOutcomeFragments = {\n /** `to` lists this Bot first: delegating to yourself is a continuation. */\n delegate(o: { to: NonEmptyIds }): ResultSchema {\n return list(closed({ to: oneOfIds(o.to), request: text(L.delegateRequestMaxLength) }, ['to', 'request']), L.delegateMaxItems);\n },\n /** Owner-authorized Main Bot turns only. The Host lists open delegations. */\n cancelDelegation(o: { delegationIds: NonEmptyIds }): ResultSchema {\n return list(closed({ delegationId: oneOfIds(o.delegationIds) }, ['delegationId']), L.cancelDelegationMaxItems);\n },\n askUser(): ResultSchema {\n const question = text(L.askUserQuestionMaxLength);\n const option = closed({ id: text(L.askUserOptionIdMaxLength), label: text(L.askUserOptionLabelMaxLength) }, ['id', 'label']);\n return { oneOf: [\n closed({ question, answerKind: { const: 'text' } }, ['question', 'answerKind']),\n closed({ question, answerKind: { const: 'single_choice' },\n options: { type: 'array', minItems: 2, maxItems: L.askUserOptionsMaxItems, items: option } }, ['question', 'answerKind', 'options']),\n ] };\n },\n /** One branch per Host action; each draft needs a finite bound of at most confirmableDraftMaxBytes. */\n confirmableAction(o: { actions: readonly [{ action: string; draft: ResultSchema }, ...{ action: string; draft: ResultSchema }[]] }): ResultSchema {\n for (const { action, draft } of o.actions) {\n const bound = resultOutcomeMaxBytes(draft);\n if (bound === null || bound > L.confirmableDraftMaxBytes) {\n throw new BotTurnOutcomeSchemaError('draft-over-budget', `draft for ${action} is ${bound ?? 'unbounded'}; cap ${L.confirmableDraftMaxBytes}`);\n }\n }\n const branches = o.actions.map(({ action, draft }) =>\n closed({ action: { const: action }, summary: text(L.confirmableSummaryMaxLength), draft }, ['action', 'summary', 'draft']));\n return list(branches.length === 1 ? branches[0]! : { oneOf: branches }, L.confirmableActionMaxItems);\n },\n /** `targets` only for a Main Bot: the Bot itself first, then team Bots. Omitted means the Bot itself. */\n createRoutine(o: { localIds: NonEmptyIds; timeZones: NonEmptyIds; targets?: NonEmptyIds; scheduleShape?: RoutineScheduleShape }): ResultSchema {\n return list(closed({\n localId: oneOfIds(o.localIds), schedule: schedule(o.timeZones, o.scheduleShape ?? 'checked'), prompt: text(L.routinePromptMaxLength),\n ...(o.targets ? { target: oneOfIds(o.targets) } : {}),\n }, ['localId', 'schedule', 'prompt']), L.createRoutineMaxItems);\n },\n updateRoutine(o: { routineIds: NonEmptyIds; timeZones: NonEmptyIds; scheduleShape?: RoutineScheduleShape }): ResultSchema {\n return list(closed({ routineId: oneOfIds(o.routineIds), schedule: schedule(o.timeZones, o.scheduleShape ?? 'checked'), prompt: text(L.routinePromptMaxLength) },\n ['routineId']), L.updateRoutineMaxItems);\n },\n cancelRoutine(o: { routineIds: NonEmptyIds }): ResultSchema {\n return list(closed({ routineId: oneOfIds(o.routineIds) }, ['routineId']), L.cancelRoutineMaxItems);\n },\n /** Room turns only. Exactly one of post or pass. */\n speech(): ResultSchema {\n return { oneOf: [\n closed({ kind: { const: 'post' }, text: text(L.postTextMaxLength) }, ['kind', 'text']),\n closed({ kind: { const: 'pass' } }, ['kind']),\n ] };\n },\n roomCall(o: { members: NonEmptyIds }): ResultSchema {\n return closed({ members: { type: 'array', minItems: 1, maxItems: L.roomCallMembersMaxItems, items: oneOfIds(o.members) } }, ['members']);\n },\n createBot(o: { localIds: NonEmptyIds; models: NonEmptyIds }): ResultSchema {\n return list(closed({\n localId: oneOfIds(o.localIds), name: text(L.botNameMaxLength), role: text(L.botRoleMaxLength),\n persona: text(L.botPersonaMaxLength), model: oneOfIds(o.models),\n }, ['localId', 'name', 'role', 'persona', 'model']), L.createBotMaxItems);\n },\n updateBot(o: { botIds: NonEmptyIds; models: NonEmptyIds }): ResultSchema {\n return list(closed({\n botId: oneOfIds(o.botIds), name: text(L.botNameMaxLength), role: text(L.botRoleMaxLength),\n persona: text(L.botPersonaMaxLength), model: oneOfIds(o.models),\n }, ['botId']), L.updateBotMaxItems);\n },\n deleteBot(o: { botIds: NonEmptyIds }): ResultSchema {\n return list(closed({ botId: oneOfIds(o.botIds) }, ['botId']), L.deleteBotMaxItems);\n },\n /** `members`: team Bot ids plus the create_bot localId slots of this outcome. */\n createRoom(o: { localIds: NonEmptyIds; members: NonEmptyIds }): ResultSchema {\n return list(closed({ localId: oneOfIds(o.localIds), ...roomFields(o.members) }, ['localId', 'name', 'members']), L.createRoomMaxItems);\n },\n updateRoom(o: { roomIds: NonEmptyIds; members: NonEmptyIds }): ResultSchema {\n return list(closed({ roomId: oneOfIds(o.roomIds), ...roomFields(o.members) }, ['roomId']), L.updateRoomMaxItems);\n },\n teamNote(): ResultSchema {\n return closed({ text: text(L.teamNoteMaxLength) }, ['text']);\n },\n};\n\nexport type BotTurnOutcomeKind =\n | 'delegate' | 'cancel_delegation' | 'ask_user' | 'confirmable_action' | 'create_routine' | 'update_routine' | 'cancel_routine'\n | 'speech' | 'room_call' | 'create_bot' | 'update_bot' | 'delete_bot' | 'create_room' | 'update_room' | 'team_note';\n\n/**\n * Host composition: pick fragments, freeze the result in the offer. Refuses a\n * schema outside the K7 subset ('not-subset'), a schema above\n * RESULT_SCHEMA_MAX_BYTES ('schema-over-budget'), or one whose largest\n * instance could exceed RESULT_OUTCOME_MAX_BYTES ('over-budget').\n *\n * Schema budget rule, before the offer is frozen: only 'schema-over-budget'\n * allows the Host to rebuild the routine fragments with scheduleShape 'flat'.\n * If the schema is still over, the Host blocks the turn with a visible reason\n * or runs its defined batch selection. It never drops authorized ids from an\n * enum silently.\n */\nexport function composeBotTurnOutcomeSchema(\n fragments: BotTurnOutcomeFragments,\n required: readonly BotTurnOutcomeKind[] = [],\n): ResultSchema {\n const schema: ResultSchema = {\n type: 'object', additionalProperties: false,\n description: `${BOT_TURN_OUTCOME_CONTRACT}: actions for the Host. Omit a field for no action of that kind; {} means no actions.`,\n ...(required.length ? { required: [...required] } : {}),\n properties: fragments,\n };\n const admitted = checkResultSchema(schema);\n if (!admitted.ok && admitted.reason === 'over-cap') {\n throw new BotTurnOutcomeSchemaError('schema-over-budget', `schema is ${admitted.bytes} bytes; cap ${RESULT_SCHEMA_MAX_BYTES}`);\n }\n if (!admitted.ok) throw new BotTurnOutcomeSchemaError('not-subset', JSON.stringify(admitted.issues));\n const bound = resultOutcomeMaxBytes(admitted.canonical);\n if (bound === null || bound > RESULT_OUTCOME_MAX_BYTES) {\n throw new BotTurnOutcomeSchemaError('over-budget', `largest outcome is ${bound ?? 'unbounded'} bytes; cap ${RESULT_OUTCOME_MAX_BYTES}`);\n }\n return admitted.canonical;\n}\n\nexport type BotTurnOutcomeFragments = Partial<Readonly<Record<BotTurnOutcomeKind, ResultSchema>>>;\n\nexport interface DelegateAction { readonly to: string; readonly request: string }\nexport interface CancelDelegationAction { readonly delegationId: string }\nexport type AskUserAction =\n | { readonly question: string; readonly answerKind: 'text' }\n | { readonly question: string; readonly answerKind: 'single_choice';\n readonly options: readonly { readonly id: string; readonly label: string }[] };\nexport interface ConfirmableAction<Draft = unknown> { readonly action: string; readonly summary: string; readonly draft: Draft }\n/**\n * No day field: every day. daysOfWeek and dayOfMonth never appear together;\n * month needs dayOfMonth. Under the 'flat' shape the schema does not enforce\n * this; the Host narrows to this type only after checkRoutineSchedule passes.\n */\nexport type RoutineScheduleFields =\n | { readonly minute: number; readonly hour: number; readonly tz: string }\n | { readonly minute: number; readonly hour: number; readonly daysOfWeek: readonly RoutineDayOfWeek[]; readonly tz: string }\n | { readonly minute: number; readonly hour: number; readonly dayOfMonth: number; readonly month?: number; readonly tz: string };\nexport interface CreateRoutineAction { readonly localId: string; readonly schedule: RoutineScheduleFields; readonly prompt: string; readonly target?: string }\nexport interface UpdateRoutineAction { readonly routineId: string; readonly schedule?: RoutineScheduleFields; readonly prompt?: string }\nexport interface CancelRoutineAction { readonly routineId: string }\nexport type RoomSpeech = { readonly kind: 'post'; readonly text: string } | { readonly kind: 'pass' };\nexport interface RoomCallAction { readonly members: readonly string[] }\nexport interface CreateBotAction { readonly localId: string; readonly name: string; readonly role: string; readonly persona: string; readonly model: string }\nexport interface UpdateBotAction { readonly botId: string; readonly name?: string; readonly role?: string; readonly persona?: string; readonly model?: string }\nexport interface DeleteBotAction { readonly botId: string }\nexport interface RoomFields {\n readonly name: string; readonly members: readonly string[]; readonly admin?: string;\n readonly mode?: 'mention' | 'admin'; readonly announcement?: string;\n}\nexport interface CreateRoomAction extends RoomFields { readonly localId: string }\nexport interface UpdateRoomAction extends Partial<RoomFields> { readonly roomId: string }\nexport interface TeamNoteAction { readonly text: string }\n\n/** Shape of a document that passed a schema composed from these fragments. */\nexport interface BotTurnOutcome {\n readonly delegate?: readonly DelegateAction[];\n readonly cancel_delegation?: readonly CancelDelegationAction[];\n readonly ask_user?: AskUserAction;\n readonly confirmable_action?: readonly ConfirmableAction[];\n readonly create_routine?: readonly CreateRoutineAction[];\n readonly update_routine?: readonly UpdateRoutineAction[];\n readonly cancel_routine?: readonly CancelRoutineAction[];\n readonly speech?: RoomSpeech;\n readonly room_call?: RoomCallAction;\n readonly create_bot?: readonly CreateBotAction[];\n readonly update_bot?: readonly UpdateBotAction[];\n readonly delete_bot?: readonly DeleteBotAction[];\n readonly create_room?: readonly CreateRoomAction[];\n readonly update_room?: readonly UpdateRoomAction[];\n readonly team_note?: TeamNoteAction;\n}\n"]}
1
+ {"version":3,"sources":["../src/capability-constants.ts","../src/version.ts","../src/task-state.ts","../src/failure-reason.ts","../src/constants.ts","../src/sealed-split-table.ts","../src/wire-additions.ts","../src/blob.ts","../src/agent-egress.ts","../src/sealed-payload.ts","../src/provider-profile-binding.ts","../src/provider-provisioning.ts","../src/plain-json.ts","../src/result-schema.ts","../src/terminal-projection.ts","../src/input-preparation.ts","../src/agent-event.ts","../src/agent-home-projection.ts","../src/e2ee-member.ts","../src/open-vocabulary.ts","../src/messages.ts","../src/agent-memory-intent.ts","../src/agent-memory-projection.ts","../src/envelope.ts","../src/errors.ts","../src/codec.ts","../src/http-api.ts","../src/bot-turn-outcome.ts"],"names":["text","z","encoder","size","LONE_SURROGATE","completionIdentity","AppliedCompletionSchema","RejectedCompletionSchema"],"mappings":";;;AAWO,IAAM,8BAAA,CAAiC,EAIvC,IAAM,8BAAA,CAAiC,sBAEvC,IAAM,oCAAA,CAAuC,4BAG7C,IAAM,qCAAA,CAAwC,6BAG9C,IAAM,+BAAA,CAAkC,uBAExC,IAAM,uCAAA,CAA0C,+BAEhD,IAAM,wCAAA,CAA2C,gCAEjD,IAAM,sCAAA,CAAyC,8BAG/C,IAAM,gCAAA,CAAmC,wBAGzC,IAAM,wCAAA,CAA2C,gCAGjD,IAAM,gCAAA,CAAmC,wBAGzC,IAAM,mCAAA,CAAsC,2BAG5C,IAAM,gCAAA,CAAmC,2BAGzC,IAAM,8BAAA,CAAiC,yBAGvC,IAAM,kCAAA,CAAqC,0BAG3C,IAAM,iCAAA,CAAoC,6BAGpC,wCAAA,CAA2C,oCAG3C,8CAAA,CAAiD,0CAGjD,kCAAA,CACX,CAAA,yBAAA,EAA4B,8BAA8B,CAAA,EAQrD,IAAM,0BAA4B,oBA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AAA,CAA0C,EAAC,CAC7B,CACd,MAAM,MAAA,CAAuB,CAC3B,KAAM,QAAA,CAAU,oBAAA,CAAsB,KAAA,CACtC,WAAA,CAAa,CAAA,EAAG,yBAAyB,CAAA,qFAAA,CAAA,CACzC,GAAI,SAAS,MAAA,CAAS,CAAE,QAAA,CAAU,CAAC,GAAG,QAAQ,CAAE,CAAA,CAAI,EAAC,CACrD,UAAA,CAAY,SACd,CAAA,CACA,MAAM,QAAA,CAAW,iBAAA,CAAkB,MAAM,CAAA,CACzC,GAAI,CAAC,QAAA,CAAS,EAAA,EAAM,QAAA,CAAS,MAAA,GAAW,UAAA,CAAY,CAClD,MAAM,IAAI,yBAAA,CAA0B,oBAAA,CAAsB,CAAA,UAAA,EAAa,QAAA,CAAS,KAAK,CAAA,YAAA,EAAe,uBAAuB,CAAA,CAAE,CAC/H,CACA,GAAI,CAAC,QAAA,CAAS,EAAA,CAAI,MAAM,IAAI,yBAAA,CAA0B,YAAA,CAAc,IAAA,CAAK,SAAA,CAAU,QAAA,CAAS,MAAM,CAAC,CAAA,CACnG,MAAM,KAAA,CAAQ,qBAAA,CAAsB,QAAA,CAAS,SAAS,CAAA,CACtD,GAAI,QAAU,IAAA,EAAQ,KAAA,CAAQ,wBAAA,CAA0B,CACtD,MAAM,IAAI,yBAAA,CAA0B,aAAA,CAAe,sBAAsB,KAAA,EAAS,WAAW,CAAA,YAAA,EAAe,wBAAwB,CAAA,CAAE,CACxI,CACA,OAAO,SAAS,SAClB","file":"index.js","sourcesContent":["/**\n * The ONE version of the input-preparation contract, shared by this relay wire\n * (the `agent.input.preparation` payload and the completion receipt summary)\n * and by the device-local request, receipt and artifact\n * (`@byok-sdk/client`'s `INPUT_PREPARATION_VERSION`, which is this value).\n *\n * The relay wire carries no version field of its own, so a version change is\n * made visible where admission actually happens: in the capability token\n * below. See `INPUT_PREPARATION_VERSION` in the client for what each version\n * changed.\n */\nexport const INPUT_PREPARATION_WIRE_VERSION = 9 as const;\n\n\n/** Additive daemon capability names. Server/cloud admission consumes these exactly. */\nexport const AGENT_EGRESS_POLICY_CAPABILITY = 'agent-egress-policy' as const;\n\nexport const AGENT_EGRESS_RELIABLE_ACK_CAPABILITY = 'agent-egress-reliable-ack' as const;\n\n/** Admits the distinct offer whose runtime mints its session only after start. */\nexport const AGENT_EGRESS_FRESH_SESSION_CAPABILITY = 'agent-egress-fresh-session' as const;\n\n/** Admits the distinct Agent-authored message lane; activity policy remains independent. */\nexport const AGENT_MESSAGE_EGRESS_CAPABILITY = 'agent-message-egress' as const;\n\nexport const AGENT_CONTENT_WORKSPACE_READ_CAPABILITY = 'agent-content-workspace-read' as const;\n\nexport const AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY = 'agent-content-transcript-read' as const;\n\nexport const AGENT_CONTENT_ARTIFACT_READ_CAPABILITY = 'agent-content-artifact-read' as const;\n\n/** Capability required before a task-free Agent-home projection is admitted. */\nexport const AGENT_HOME_PROJECTION_CAPABILITY = 'agent-home-projection' as const;\n\n/** Capability required before an offer may select terminal projection behavior. */\nexport const TERMINAL_PROJECTION_SELECTION_CAPABILITY = 'terminal-projection-selection' as const;\n\n/** Contract §8.1's capability gate for `byok-task-assertion-v1` tool authority. */\nexport const HOST_MCP_TASK_CONTEXT_CAPABILITY = 'host-mcp-task-context' as const;\n\n/** Daemon capability required before an exact local provider profile may be offered. */\nexport const PROVIDER_PROFILE_BINDING_CAPABILITY = 'provider-profile-binding' as const;\n\n/** Device capability required before a Host may enqueue `provider.provisioning.available`. */\nexport const PROVIDER_PROVISIONING_CAPABILITY = 'provider-provisioning.v1' as const;\n\n/** Device capability required before a Host may enqueue `agent.memory.intent.available`. */\nexport const AGENT_MEMORY_INTENT_CAPABILITY = 'agent-memory-intent.v1' as const;\n\n/** Capability required before the optional hosted Agent-memory projection can be used. */\nexport const AGENT_MEMORY_PROJECTION_CAPABILITY = 'agent.memory.projection' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory`. */\nexport const AGENT_MEMORY_SELECTION_CAPABILITY = 'agent-memory-selection' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory: 'read-if-admitted'`. */\nexport const AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY = 'agent-memory-read-if-admitted' as const;\n\n/** Device capability required before an ordinary Agent offer may carry `agentMemory: 'read-write-if-admitted'`. */\nexport const AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY = 'agent-memory-read-write-if-admitted' as const;\n\n/** Exact capability of the single input-preparation wire authority. */\nexport const AGENT_INPUT_PREPARATION_CAPABILITY =\n `agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}` as const;\n\n/**\n * Sealed payload v1 (#654). A device advertises it before a Host may send it\n * a sealed offer or steer; a server advertises it before a device may send it\n * sealed task output or a sealed decline code. Both gates read\n * `WIRE_ADDITIONS`.\n */\nexport const SEALED_PAYLOAD_CAPABILITY = 'sealed-payload-v1' as const;\n\n/**\n * Sealed payload v2 (#1045): the `agent-message` and `memory-projection`\n * categories. A device advertises it before a Host may send it an offer whose\n * `sealing` names either category, or a sealed message disposition; a server\n * advertises it before a device may send it a sealed `agent.message.publish`.\n */\nexport const SEALED_PAYLOAD_V2_CAPABILITY = 'sealed-payload-v2' as const;\n\n/**\n * A server advertises it before a device may send a sealed task output that\n * names its ciphertext blob (`sealed.ciphertextRef`) instead of carrying it\n * inline. The server then holds the blob for the life of the task.\n */\nexport const SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY = 'sealed-output-ciphertext-ref' as const;\n\n/**\n * A server advertises it before a device may send `task.fail.failure`, the\n * machine-readable runtime failure class (#869).\n */\nexport const RUNTIME_FAILURE_CLASS_CAPABILITY = 'runtime-failure-class' as const;\n\n/** A server advertises it before a device may send `task.fail.failure.scope` (#1271). */\nexport const RUNTIME_QUOTA_SCOPE_CAPABILITY = 'runtime-quota-scope' as const;\n\n/**\n * The connection understands the typed pre-claim runtime-unavailable cause\n * (#1103 D8): `task.decline.runtimeUnavailable`, `conn.hello.runtimeUnavailable`\n * and the presence projection. A daemon declares it when it emits the cause.\n * Older peers ignore the unknown flag; absence means the peer may not read\n * the cause, so a Host falls back to `retryable` and treats the cause as\n * unknown. It never infers availability or allow from absence.\n */\nexport const RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY = 'runtime-unavailable-cause' as const;\n/**\n * The closed classes of `task.fail.failure.class`: the vendored OAR\n * `FailureClass` values. `unknown` means the runtime gave no structured\n * evidence. Single value authority shared by schema validation and\n * schema-free consumers.\n */\nexport const RUNTIME_FAILURE_CLASSES = [\n 'auth', 'quota', 'rate_limited', 'billing', 'model_unavailable', 'input_too_large', 'invalid_request',\n 'overloaded', 'provider', 'runtime_exited', 'limit_reached', 'output_schema', 'unknown',\n] as const;\n\n/** The values of a `quota` failure's `scope` (#1271), shared by schema and schema-free consumers. */\nexport const RUNTIME_QUOTA_SCOPES = ['account', 'model'] as const;\n\n/** Single value authority shared by schema validation and schema-free consumers. */\nexport const PREPARED_AGENT_MEMORY_MODES = ['none', 'read', 'read-write'] as const;\n\nexport function isPreparedAgentMemoryMode(value: unknown): value is (typeof PREPARED_AGENT_MEMORY_MODES)[number] {\n return typeof value === 'string' && PREPARED_AGENT_MEMORY_MODES.some(mode => mode === value);\n}\n","/** Bounded volatile navigation; only cursor is a durable acknowledgement. */\nexport const MAILBOX_READ_AHEAD_MAX_SEQS = 4096;\nexport const MAILBOX_READ_AHEAD_CAPABILITY = 'mailbox-read-ahead';\n\n/**\n * Wire protocol version. Every v5 change is a version bump, a gated addition\n * or a strip-safe addition: see docs/protocol.md \"Freeze rule\", which is the\n * one statement of the rule, and `src/wire-additions.ts`, which declares the\n * receiver-capability gates and additions. No v5 release has been published\n * yet, so `src/__tests__/compat.test.ts` has no published v5 decoder to prove\n * additions against; cross-release gates stay unproven until one exists.\n *\n * v5 renames the runtime capability `durablePi` to `durableLane`, beside\n * `preparedLane`, on `conn.hello` runtimes and harnesses, `task.claim` and\n * presence: the durable worker is a lane an adapter declares, not a Pi name\n * on the wire. Nothing else changes. A v4 envelope is rejected; there is no\n * v4 reader. Drain, then upgrade server and client together.\n *\n * v4 completes the ADR-034 cutover and retires the approval paths kept for\n * pre-M5 peers. It removes the v3 handshake answer, the runtime-only offers\n * (with and without toolsets) with their sealed twins, and the\n * `strict-agent-only` flag: every offer is Agent-bound. `approvalId` is\n * required on `task.await_approval`, `task.approve` and `task.reject`, so a\n * decision resolves only the approval it names. `task.approval_resolved` is\n * baseline: the daemon reports every locally resolved approval, and the\n * server no longer infers one from later task activity. The three approval\n * capability flags of v3 are gone. A v3 envelope is rejected; there is no v3 reader. Drain, then\n * upgrade server and client together.\n *\n * v3 made `schema` required on the `terminalProjection.mode:\n * 'result-document'` arm (`terminal-projection.ts`, `result-schema.ts`): the\n * offer freezes the outcome schema, and the outcome reaches the Host only as\n * `task.complete.document`. That narrows a strict shape, so it is a wire\n * major. A v2 envelope is rejected; there is no v2 reader and no capability\n * negotiation between the two result-document shapes. Drain, then upgrade\n * server and client together. Every addition v2 declared is part of the v3\n * baseline, and the v2 `result-document` capability flag is gone: every v3\n * server keeps `task.complete.document`.\n *\n * v2 removed the task offer's `policy` (`PermissionPolicy`), the runtime\n * capability `permissionModes` and the input-preparation `permissionMode`.\n * Sessions run without an SDK permission gate; each local agent keeps its\n * own guardrails. A v1 envelope is rejected; there is no v1 reader.\n * v2 also removed the egress policy's `metadata-status` activity mode, its\n * `activity.mode` field and the `sanitizer_rejected` drop reason. Agent\n * egress goes to the Host as the runtime produced it.\n * v2 also removed the input-preparation artifact's `toolImplementationKinds`\n * and the readiness reason `executor_identity_unproven`. The SDK does not\n * attest tool executables. The artifact names its counted tools in\n * `toolNames`.\n */\nexport const PROTOCOL_VERSION = 5;\n\n/**\n * The device runs `homeAccess: 'memory-reader'` Agent offers: each reader\n * Attempt gets its own run directory under the Agent home, and readers are\n * counted apart from the one writer. The Agent offers are strict, so a host\n * must refuse a reader offer to a device without this flag before it creates\n * the task.\n */\nexport const AGENT_HOME_READERS_CAPABILITY = 'agent-home-readers' as const;\n\n/**\n * Capability flags. The daemon sends its flags in `conn.hello`; the server\n * sends its own on every long-poll response (`EventsPollResponse`). Additional\n * flags may be introduced without a protocol version bump; unrecognized flags\n * must be ignored by both sides.\n *\n * `dispatch-selection` (additive-minor) is a correctness gate for the\n * optional offer `dispatchSelection` control field. An older v1 daemon\n * legally strips unknown optional fields, so a server must never send an\n * authoritative provider/model selection unless the target connection\n * advertises this flag. Absence means reject before task creation, not send\n * an offer that could reach a different provider.\n *\n * `toolset-selection` (additive-minor) means the daemon understands an\n * offer's `requiredToolsets` and can resolve its logical ids against local\n * MCP configuration.\n */\nexport const CUSTOM_HARNESS_CAPABILITY = 'custom-harness' as const;\n\nexport const CAPABILITY_FLAGS = [\n 'steer',\n 'blob-upload',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\n AGENT_HOME_READERS_CAPABILITY,\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_HOME_PROJECTION_CAPABILITY,\n AGENT_INPUT_PREPARATION_CAPABILITY,\n TERMINAL_PROJECTION_SELECTION_CAPABILITY,\n HOST_MCP_TASK_CONTEXT_CAPABILITY,\n CUSTOM_HARNESS_CAPABILITY,\n MAILBOX_READ_AHEAD_CAPABILITY,\n PROVIDER_PROVISIONING_CAPABILITY,\n AGENT_MEMORY_INTENT_CAPABILITY,\n AGENT_MEMORY_SELECTION_CAPABILITY,\n AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,\n AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,\n 'agent-message-draft',\n SEALED_PAYLOAD_CAPABILITY,\n SEALED_PAYLOAD_V2_CAPABILITY,\n SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,\n RUNTIME_FAILURE_CLASS_CAPABILITY,\n RUNTIME_QUOTA_SCOPE_CAPABILITY,\n RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY,\n] as const;\n\nexport type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number];\nimport {\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_HOME_PROJECTION_CAPABILITY,\n TERMINAL_PROJECTION_SELECTION_CAPABILITY,\n HOST_MCP_TASK_CONTEXT_CAPABILITY,\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n PROVIDER_PROVISIONING_CAPABILITY,\n AGENT_MEMORY_INTENT_CAPABILITY,\n AGENT_MEMORY_SELECTION_CAPABILITY,\n AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,\n AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,\n AGENT_INPUT_PREPARATION_CAPABILITY,\n SEALED_PAYLOAD_CAPABILITY,\n SEALED_PAYLOAD_V2_CAPABILITY,\n SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,\n RUNTIME_FAILURE_CLASS_CAPABILITY,\n RUNTIME_QUOTA_SCOPE_CAPABILITY,\n RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY,\n} from './capability-constants';\n","export const TASK_STATES = [\n 'Offered',\n 'Claimed',\n 'Running',\n 'AwaitApproval',\n 'Complete',\n 'Failed',\n 'Cancelled',\n] as const;\n\nexport type TaskState = (typeof TASK_STATES)[number];\n\n/**\n * Legal state transitions for a task. `Complete` / `Failed` / `Cancelled` are\n * terminal (no outgoing edges). `Running` and `AwaitApproval` form a loop:\n * the daemon can request approval mid-run and resume once the server\n * approves (or fail/cancel out of the approval wait).\n *\n * `Offered -> Failed` (M1 gap #5, \"Declined vs. Failed\"): a daemon that\n * declines an offer pre-claim (`task.decline`) reports it through the\n * existing `Failed` state rather than a new `Declined` state. A decline and\n * a post-claim failure are the same outcome from the dispatcher's point of\n * view — this attempt produced no result, `reason`/`retryable` say why and\n * whether retrying elsewhere makes sense — so reusing `Failed` keeps the\n * state machine minimal instead of forking every terminal-state consumer\n * into \"Failed or Declined, handle both\". See docs/protocol.md for the full\n * writeup.\n */\nexport const TASK_TRANSITIONS: Readonly<Record<TaskState, readonly TaskState[]>> = {\n Offered: ['Claimed', 'Cancelled', 'Failed'],\n Claimed: ['Running', 'Failed', 'Cancelled'],\n Running: ['AwaitApproval', 'Complete', 'Failed', 'Cancelled'],\n AwaitApproval: ['Running', 'Failed', 'Cancelled'],\n Complete: [],\n Failed: [],\n Cancelled: [],\n};\n\n/** Whether `from -> to` is a legal transition per {@link TASK_TRANSITIONS}. */\nexport function canTransition(from: TaskState, to: TaskState): boolean {\n return TASK_TRANSITIONS[from].includes(to);\n}\n","/**\n * The single authority for the display text of a `task.fail` `reason` (#1124).\n *\n * A runtime's stderr tail can carry credentials a runtime or proxy printed\n * while failing. The `task.fail` schema applies this to `reason` on every\n * parse, so `createEnvelope` bounds what a daemon sends (sealed or not) and\n * every decode bounds what a receiver holds. The raw tail stays local, on the\n * adapter's `RuntimeExecutionFailure`. The result is a fixed point: applying\n * it to its own output changes nothing, so a bounded envelope round-trips\n * byte-for-byte.\n *\n * Every pattern starts at a literal and its runs never backtrack into a\n * failure, so the cost stays linear in the input length.\n */\n\n/** Maximum UTF-8 bytes of a `task.fail` `reason` after normalization, truncation marker included. */\nexport const TASK_FAIL_REASON_MAX_BYTES = 2048;\n\nconst REDACTED = '[redacted]';\n\n// A secret value: a quoted string (an unclosed quote runs to the end of the\n// line), or an unquoted run. A backslash and its following character belong\n// to the value together, so an escaped quote cannot expose a secret suffix.\n// A dangling backslash in an unclosed value is consumed too. Every alternative\n// succeeds greedily without backtracking. An unquoted value never starts with `[` or `…`, so a\n// redaction or truncation marker is never mistaken for a value on a second pass.\nconst VALUE = String.raw`(?:\"(?:\\\\[^\\n]|[^\"\\\\\\n])*(?:\\\\)?\"?|'(?:\\\\[^\\n]|[^'\\\\\\n])*(?:\\\\)?'?|[^\\s\"'\\[\\u2026,;&|][^\\s\"',;&|]*)`;\n\n// Bounded runs keep a failed match from rescanning a long run at every literal.\nconst GAP = '[ \\\\t]{0,16}';\n\nconst RULES: ReadonlyArray<readonly [RegExp, string]> = [\n // `Authorization: Bearer …`, `proxy-authorization=Basic …`, JSON `\"authorization\": \"…\"`.\n [new RegExp(String.raw`\\b((?:proxy-)?authorization)([\"']?${GAP}[:=]${GAP})(?:(?:bearer|basic|token|digest)[ \\t]{1,16})?${VALUE}`, 'gi'), `$1$2${REDACTED}`],\n [/\\b(bearer)[ \\t]{1,16}[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${REDACTED}`],\n // `ANTHROPIC_API_KEY=…`, `x-api-key: …`, `GITHUB_TOKEN=…`, `client_secret: …`, `DB_PASSWORD_FILE=…`.\n [new RegExp(String.raw`(key|token|secret|passw(?:or)?d[\\w.-]{0,64})([\"']?${GAP}[:=]${GAP})${VALUE}`, 'gi'), `$1$2${REDACTED}`],\n // URL userinfo: `postgres://user:pass@host`, `https://token@host`.\n [/:\\/\\/[^\\s/?#@]{1,256}@/g, `://${REDACTED}@`],\n // Provider key shapes.\n [/\\bsk-[A-Za-z0-9_-]{16,}/g, REDACTED],\n [/\\bxai-[A-Za-z0-9_-]{16,}/g, REDACTED],\n [/\\bAIza[0-9A-Za-z_-]{30,}/g, REDACTED],\n [/\\bgh[pousr]_[A-Za-z0-9]{20,}/g, REDACTED],\n [/\\bgithub_pat_[A-Za-z0-9_]{20,}/g, REDACTED],\n [/\\bAKIA[0-9A-Z]{16}/g, REDACTED],\n // JWT-like tokens.\n [/\\beyJ[A-Za-z0-9_-]{10,}(?:\\.[A-Za-z0-9_-]*){0,2}/g, REDACTED],\n];\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\nfunction redact(text: string): string {\n let out = text;\n for (const [pattern, replacement] of RULES) out = out.replace(pattern, replacement);\n return out;\n}\n\n/**\n * Redact credentials from a failure reason, then cap it at\n * {@link TASK_FAIL_REASON_MAX_BYTES} UTF-8 bytes on a code-point boundary\n * with a `…[truncated N bytes]` marker, where N counts the dropped redacted\n * bytes.\n */\nexport function boundFailureReason(reason: string): string {\n const redacted = redact(reason);\n const bytes = encoder.encode(redacted);\n if (bytes.length <= TASK_FAIL_REASON_MAX_BYTES) return redacted;\n // Reserve the widest marker this input can need; the final one is no wider.\n let keep = TASK_FAIL_REASON_MAX_BYTES - encoder.encode(`\\u2026[truncated ${bytes.length} bytes]`).length;\n while (keep > 0 && ((bytes[keep] ?? 0) & 0xc0) === 0x80) keep -= 1;\n return `${decoder.decode(bytes.subarray(0, keep))}\\u2026[truncated ${bytes.length - keep} bytes]`;\n}\n","/** Schema-free protocol values. Import this entry when runtime schemas are unnecessary. */\nexport * from './version';\nexport * from './task-state';\nexport * from './capability-constants';\nexport * from './failure-reason';\n\n/** Maximum raw UTF-8 content bytes in one local Host Agent-memory export; no truncation. */\nexport const AGENT_MEMORY_MAX_SNAPSHOT_BYTES = 1024 * 1024;\n/** Maximum memory files in one local Host export, including MEMORY.md. */\nexport const AGENT_MEMORY_MAX_SNAPSHOT_FILES = 128;\n\n/** The frozen wire runtime ids. Any other adapter id is a custom harness (`harnessId`). */\nexport const RUNTIME_IDS = Object.freeze(['pi', 'claude', 'codex'] as const);\n\n/**\n * Why a runtime is unavailable before claim (#1103 D6). Append-only: a cause is\n * never renamed, removed or given a new meaning. The wire reads an unknown\n * well-formed token as `unknown` and keeps it verbatim (#1121), so a newer\n * device can add one without a protocol bump. Names are snake_case, unlike the\n * kebab-case detection kinds, because the mapping is explicit and never a\n * string transformation.\n */\nexport const RUNTIME_UNAVAILABLE_CAUSES = Object.freeze([\n /** Detection: `not-found`. */\n 'not_installed',\n /** Detection: `not-executable`. */\n 'not_executable',\n /** Detection: `timeout`. */\n 'probe_timeout',\n /** Detection: `probe-failed`. */\n 'probe_failed',\n /** Detection: `refused` / `app_server_unavailable`. */\n 'app_server_unavailable',\n /** Detection: `refused` / `acp_unavailable`. */\n 'acp_unavailable',\n /** Detection: `refused` / `platform_unsupported`. */\n 'platform_unsupported',\n /** The login-shell environment capture failed (#1095). */\n 'environment_unavailable',\n /** A Host-configured version policy blocked the installed token (#1103). */\n 'version_blocked',\n /** The offer named an id this daemon has no adapter for. */\n 'runtime_not_configured',\n /** The device runtime allowlist excludes the requested id. */\n 'runtime_not_allowed',\n /** Automatic selection exhausted every candidate. */\n 'none_available',\n] as const);\n\n/** One append-only `runtime_unavailable` cause. */\nexport type RuntimeUnavailableCause = (typeof RUNTIME_UNAVAILABLE_CAUSES)[number];\n\n/** Maximum length of a served model name. */\nexport const TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH = 160;\n","/**\n * The split table of sealed payload v1 and v2 (#654 design §8.1, §9.3;\n * #1045): for each sealable message type, the field that marks its sealed\n * branch, its data category, its identity fields, the fields that move into\n * the ciphertext, the fields its sealed branch drops, and the rule of each\n * digest field (D16).\n *\n * Plain data with no runtime imports, so `wire-additions.ts` can derive the\n * sealed gates from it and stay free of zod.\n */\nimport type { MessageType } from './messages';\nimport type { SealedPayloadCategory } from './sealed-payload';\n\n/**\n * How the sealed branch of a type treats one digest field of its plaintext\n * branch (D16, design §9.3).\n *\n * - `ciphertext-sha256`: the SHA-256 of the sealed bytes, for a Host that\n * checks the bytes it stores (a ciphertext blob).\n * - `keyed-mac`: a keyed MAC under the scope's MAC key; the Host forwards it.\n * - `sealed`: the field moves into the ciphertext with its parent.\n * - `plain`: a digest that no sealed content derives, kept in plaintext.\n * - `forbidden`: the sealed branch does not carry it in v1.\n */\nexport type SealedDigestRule = 'ciphertext-sha256' | 'keyed-mac' | 'sealed' | 'plain' | 'forbidden';\n\n/** One sealable message type in the split table. */\nexport interface SealedSplitEntry {\n /**\n * The payload field whose presence marks the sealed branch: `sealing` (the\n * task's sealing policy) on `task.offer`, whose task may seal only its\n * output and so carry no `sealed` member; `sealed` everywhere else. The AAD\n * and the content MAC bind the wire type as the family.\n */\n readonly marker: 'sealing' | 'sealed';\n readonly category: SealedPayloadCategory;\n /**\n * Payload fields that, after the envelope `task_id`, name this write in the\n * AAD and the content MAC (§8.2, §9.1). The sealed branch requires them.\n */\n readonly identity: readonly string[];\n /**\n * Top-level fields of the plaintext branch that move into the ciphertext.\n * The sealed branch does not have them; the receiver merges the opened\n * object back and validates the plaintext branch.\n */\n readonly moved: readonly string[];\n /**\n * Top-level fields that also move into this ciphertext when the task's\n * frozen `sealing` names the category (#1045): on a task that seals\n * `memory-projection`, a terminal seals its `agentHomeMemoryChange`. The\n * sealed branch schema cannot see the task's sealing, so the Host and the\n * device check these fields; read them with {@link sealedMovedFields}.\n */\n readonly movedWith?: { readonly [category in SealedPayloadCategory]?: readonly string[] };\n /** Top-level fields of the plaintext branch that the sealed branch drops. */\n readonly forbidden: readonly string[];\n /**\n * Every path of the plaintext branch whose name contains `digest`, `hash` or\n * `revision` (case-insensitive), with its rule. A schema test keeps this\n * complete.\n */\n readonly digests: { readonly [path: string]: SealedDigestRule };\n /**\n * UTF-8 byte limits of moved fields that replace the plaintext branch's limit\n * of that field after the merge (decision 12b). The category limit still\n * bounds the whole opened content.\n */\n readonly limits?: { readonly [field: string]: number };\n /**\n * The sealed form carries inline ciphertext only, never `ciphertextRef`\n * (decision 12e). The Host keeps it in a tail row that expires, so it holds\n * no blob for it. The schema does not check this; the Host and the device do.\n */\n readonly inlineOnly?: true;\n}\n\n/** A terminal of a task that seals `memory-projection` seals its memory-change evidence. */\nconst MEMORY_EVIDENCE = { 'memory-projection': ['agentHomeMemoryChange'] } as const;\n\n/** The Host wrote the projection it names, so its hash tells the Host nothing new. */\nconst TERMINAL_DIGESTS = {\n 'agentRef.profileRevision': 'plain',\n 'agentHomeProjection.profileRevision': 'plain',\n 'agentHomeProjection.projectionHash': 'plain',\n} as const satisfies SealedSplitEntry['digests'];\n\n/**\n * The split table (design §8.3): each sealable message type, the marker of its\n * sealed branch, its category, identity, moved and forbidden fields, and the\n * rule of each digest field. It is the one authority; the schemas, the gates,\n * the Host's comparison projection and the receiver's merge read it.\n *\n * A sealed offer carries the task's `sealing`. When the categories include\n * `task-input`, `instruction` is sealed; otherwise it stays plaintext and only\n * the task output is sealed. A prepared Execution is never sealed.\n *\n * Blob bytes have no sealing rule yet, so a sealed branch carries no plaintext\n * blob reference: `artifactRefs` and the artifact `blobRef` are dropped until\n * that rule exists. A sealed artifact is inline content, so its `inline`\n * takes up to 2 MiB instead of the plaintext 64 KB (decision 12b).\n */\nexport const SEALED_SPLIT_TABLE = Object.freeze({\n 'task.offer': {\n marker: 'sealing',\n category: 'task-input',\n identity: [],\n moved: ['instruction'],\n forbidden: ['preparation'],\n digests: {\n 'instruction.blobRef.contentHash': 'sealed',\n 'agentRef.profileRevision': 'plain',\n 'dispatchSelection.providerProfile.profileRevision': 'plain',\n 'dispatchSelection.providerProfile.profileHash': 'plain',\n 'egressPolicy.policyRevision': 'plain',\n 'preparation.requestDigest': 'forbidden',\n 'preparation.artifactDigest': 'forbidden',\n },\n },\n 'task.steer': { marker: 'sealed', category: 'task-input', identity: ['steerId'], moved: ['text'], forbidden: [], digests: {} },\n 'task.complete': {\n marker: 'sealed',\n category: 'task-output',\n identity: [],\n moved: ['summary', 'finalMessage', 'document'],\n movedWith: MEMORY_EVIDENCE,\n forbidden: ['artifactRefs', 'preparedObservation'],\n digests: {\n ...TERMINAL_DIGESTS,\n 'artifactRefs[].contentHash': 'forbidden',\n 'preparedObservation.requestDigest': 'forbidden',\n },\n },\n 'task.fail': {\n marker: 'sealed',\n category: 'task-output',\n identity: [],\n moved: ['reason'],\n movedWith: MEMORY_EVIDENCE,\n forbidden: ['preparedObservation'],\n digests: { ...TERMINAL_DIGESTS, 'preparedObservation.requestDigest': 'forbidden' },\n },\n 'task.decline': {\n marker: 'sealed', category: 'task-output', identity: [], moved: ['reason'], forbidden: [], digests: { 'agentRef.profileRevision': 'plain' },\n },\n 'task.cancelled': {\n marker: 'sealed', category: 'task-output', identity: [], moved: ['reason'], movedWith: MEMORY_EVIDENCE, forbidden: [], digests: TERMINAL_DIGESTS,\n },\n 'task.progress': {\n marker: 'sealed', category: 'task-output', identity: ['seq'], moved: ['events'], forbidden: [], digests: { 'events[].spill.blob.contentHash': 'sealed' },\n inlineOnly: true,\n },\n 'task.artifact': {\n marker: 'sealed', category: 'task-output', identity: ['artifactId'], moved: ['inline'], forbidden: ['blobRef'], digests: { 'blobRef.contentHash': 'forbidden' },\n limits: { inline: 2 * 1024 * 1024 },\n },\n 'task.await_approval': {\n marker: 'sealed', category: 'task-output', identity: ['approvalId'], moved: ['summary'], forbidden: [], digests: {},\n inlineOnly: true,\n },\n // #1045 C2. The plaintext SHA-256 of the body would let the Host confirm a\n // guessed message, and the exact byte count would undo the padding, so the\n // sealed branch drops both; the sealed member's keyed `contentMac` names\n // the content instead. `cursor` is in the identity, so the Host cannot\n // reorder sealed messages of one session.\n 'agent.message.publish': {\n marker: 'sealed',\n category: 'agent-message',\n identity: ['messageId', 'cursor'],\n moved: ['body'],\n forbidden: ['contentHash', 'byteCount'],\n digests: { 'agentRef.profileRevision': 'plain', contentHash: 'forbidden' },\n },\n} as const satisfies { readonly [type in MessageType]?: SealedSplitEntry });\n\n/**\n * The receiver capability each category's sealed branches need: the v1\n * categories `sealed-payload-v1`, the #1045 categories `sealed-payload-v2`.\n */\nexport const SEALED_CATEGORY_CAPABILITY = Object.freeze({\n 'task-input': 'sealed-payload-v1',\n 'agent-message': 'sealed-payload-v2',\n 'task-output': 'sealed-payload-v1',\n 'memory-projection': 'sealed-payload-v2',\n} as const satisfies { readonly [category in SealedPayloadCategory]: string });\n\n/**\n * The top-level fields a `type` message of a task whose frozen `sealing`\n * lists `categories` moves into its ciphertext: the type's `moved` fields and\n * the `movedWith` fields of each listed category.\n */\nexport function sealedMovedFields(type: SealableMessageType, categories: readonly SealedPayloadCategory[]): readonly string[] {\n const entry: SealedSplitEntry = SEALED_SPLIT_TABLE[type];\n return [...entry.moved, ...categories.flatMap((category) => entry.movedWith?.[category] ?? [])];\n}\n\n/** A message type with a sealed branch. */\nexport type SealableMessageType = keyof typeof SEALED_SPLIT_TABLE;\n\nexport function isSealableMessageType(type: string): type is SealableMessageType {\n return Object.hasOwn(SEALED_SPLIT_TABLE, type);\n}\n\n/** Whether a `type` payload takes its sealed branch: it carries the type's marker field. */\nexport function isSealedPayload(type: string, payload: unknown): boolean {\n return isSealableMessageType(type) && payload !== null && typeof payload === 'object'\n && (payload as Readonly<Record<string, unknown>>)[SEALED_SPLIT_TABLE[type].marker] !== undefined;\n}\n","/**\n * The one table of receiver-capability gates and wire additions\n * (docs/protocol.md \"Freeze rule\").\n *\n * A v4 change takes exactly one of three paths: a version bump, a gated\n * addition, or a strip-safe addition. Envelope and HTTP rows have explicit\n * kinds. The last two are declared here.\n *\n * - `gated`: the sender must not emit the surface unless the receiver\n * durably advertised `capability`. A field entry applies when the payload\n * carries the field (and, with `value`, when the field equals it, or when\n * the field is an array that includes it); a dotted field names a nested\n * field, for example `sealed.ciphertextRef`. A type entry applies to every\n * message of that type. Server-to-daemon surfaces\n * are gated by a device flag, daemon-to-server surfaces by a server flag.\n * - `strip-safe`: an optional field an older receiver drops without changing\n * what it executes or acknowledges.\n *\n * v3 baseline: every v3 decoder reads every surface v2 had, so the v2\n * strip-safe rows and the v2 `result-document` gate are gone. The device\n * gates kept below name capabilities a daemon advertises only when it is\n * configured for them (Agent home, egress, input preparation, provisioning,\n * memory intents and so on): they gate on the receiver's configuration.\n *\n * v4 baseline: every v4 server reads `task.approval_resolved`, so its\n * `approval_resolved` gate is gone. One `task.offer` replaces the Agent offer\n * types and sealed is a payload branch, so a gate that a v3 type carried is a\n * field or value row here. The offer is strict, so a daemon that does not know\n * one of its fields stops instead of stripping it. The daemon also refuses an offer whose rows name a flag it did not advertise. No\n * v4 release has been published yet, so no published decoder proves these rows\n * across releases.\n *\n * Senders derive their admission flags from {@link requiredReceiverCapabilities}\n * and nowhere else, so a gate cannot exist in one place and be missing in\n * another. This module imports no runtime code except the plain-data split\n * table, so it stays free of zod.\n */\nimport type { MessageType } from './messages';\nimport { SEALED_CATEGORY_CAPABILITY, SEALED_SPLIT_TABLE, type SealableMessageType, type SealedSplitEntry } from './sealed-split-table';\nimport type { CapabilityFlag } from './version';\n\ntype HttpWireSurface =\n | 'ChallengeRequest' | 'ChallengeResponse' | 'TokenRequest' | 'TokenResponse'\n | 'PairRequest' | 'PairResponse' | 'EventsPollQuery' | 'EventsPollResponse' | 'MessagesSendRequest' | 'MessagesSendResponse'\n | 'PresencePublishRequest';\n\nexport type WireAddition =\n | {\n readonly kind: 'envelope';\n readonly rule: 'gated';\n readonly surface: MessageType;\n readonly field?: string;\n readonly value?: string;\n readonly capability: CapabilityFlag;\n readonly advertisedBy: 'device' | 'server';\n }\n | { readonly kind: 'envelope'; readonly rule: 'strip-safe'; readonly surface: MessageType; readonly field: string }\n | { readonly kind: 'http'; readonly rule: 'strip-safe'; readonly surface: HttpWireSurface; readonly field: string };\n\nconst MATRIX_FIELDS = ['toolAuthorizationAuto', 'durableLane', 'preparedLane', 'isolation'] as const;\n\nconst offerRow = (field: string | undefined, capability: CapabilityFlag, value?: string): WireAddition => ({\n kind: 'envelope', rule: 'gated', surface: 'task.offer',\n ...(field === undefined ? {} : { field }), ...(value === undefined ? {} : { value }),\n capability, advertisedBy: 'device',\n});\n\n/**\n * Sealed payload (#654, #1045), one table entry at a time: the marker of each\n * sealed branch is gated on its category's flag (`sealed-payload-v1` for task\n * input and output, `sealed-payload-v2` for Agent messages), a\n * server-to-daemon type on the device flag, a daemon-to-server type on the\n * server flag. The sealed branch shares every other row of its type, and a\n * field it moves or drops is absent from it, so sealing never removes a gate\n * that the same fields would need. A daemon-to-server sealed type that may\n * name its ciphertext blob is also gated on that field. The four sealed\n * failure codes on the plaintext `task.decline` are value gates.\n */\nfunction sealedRows(): WireAddition[] {\n return (Object.keys(SEALED_SPLIT_TABLE) as SealableMessageType[]).flatMap((surface) => {\n const entry: SealedSplitEntry = SEALED_SPLIT_TABLE[surface];\n const advertisedBy = entry.category === 'task-input' ? 'device' : 'server';\n const byReference: WireAddition[] = advertisedBy === 'server' && entry.inlineOnly !== true\n ? [{ kind: 'envelope', rule: 'gated', surface, field: 'sealed.ciphertextRef', capability: 'sealed-output-ciphertext-ref', advertisedBy }]\n : [];\n const capability = SEALED_CATEGORY_CAPABILITY[entry.category];\n return [{ kind: 'envelope', rule: 'gated', surface, field: entry.marker, capability, advertisedBy }, ...byReference];\n });\n}\n\n/**\n * Sealed payload v2 (#1045) outside the split table: an offer whose frozen\n * `sealing` lists a v2 category, and the disposition of a sealed message,\n * which names it by `contentMac`. Both go to a device.\n */\nconst SEALED_V2_ROWS: readonly WireAddition[] = [\n offerRow('sealing.categories', 'sealed-payload-v2', 'agent-message'),\n offerRow('sealing.categories', 'sealed-payload-v2', 'memory-projection'),\n { kind: 'envelope', rule: 'gated', surface: 'agent.message.disposition', field: 'contentMac', capability: 'sealed-payload-v2', advertisedBy: 'device' },\n];\nconst SEALED_DECLINE_CODE = (value: string): WireAddition =>\n ({ kind: 'envelope', rule: 'gated', surface: 'task.decline', field: 'code', value, capability: 'sealed-payload-v1', advertisedBy: 'server' });\n\nconst PLAIN_ROWS: readonly WireAddition[] = [\n // Server to daemon: the offer. Every offer binds an Agent; each optional\n // field and value names the device flag a daemon advertises when it is\n // configured for it.\n offerRow(undefined, 'agent-home-contract'),\n offerRow('dispatchSelection', 'dispatch-selection'),\n offerRow('requiredToolsets', 'toolset-selection'),\n offerRow('terminalProjection', 'terminal-projection-selection'),\n offerRow('homeAccess', 'agent-home-readers'),\n offerRow('harnessId', 'custom-harness'),\n offerRow('agentMemory', 'agent-memory-selection'),\n offerRow('agentMemory', 'agent-memory-read-if-admitted', 'read-if-admitted'),\n offerRow('agentMemory', 'agent-memory-read-write-if-admitted', 'read-write-if-admitted'),\n offerRow('egressPolicy', 'agent-egress-policy'),\n offerRow('egressPolicy', 'agent-egress-reliable-ack'),\n offerRow('messageEgress', 'agent-message-egress'),\n offerRow('session.mode', 'agent-egress-fresh-session', 'fresh'),\n offerRow('preparation', 'agent-input-preparation-v9'),\n // Server to daemon: Agent control messages.\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'workspace', capability: 'agent-content-workspace-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'transcript', capability: 'agent-content-transcript-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.content.read', field: 'surface', value: 'artifact', capability: 'agent-content-artifact-read', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.home.projection', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.home.projection', capability: 'agent-home-projection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.input.preparation', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.input.preparation', capability: 'agent-input-preparation-v9', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'provider.provisioning.available', capability: 'provider-provisioning.v1', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'agent.memory.intent.available', capability: 'agent-memory-intent.v1', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'e2ee.key_package.available', capability: 'sealed-payload-v1', advertisedBy: 'device' },\n // One optional runtime capability, shared by discovery and the claim snapshot.\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimes[].capabilities.messageDraft' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'harnesses[].capabilities.messageDraft' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.claim', field: 'capabilities.messageDraft' },\n // The capability matrix (#1103): discovery data on the same runtime capability object.\n ...MATRIX_FIELDS.flatMap((field): WireAddition[] => [\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: `runtimes[].capabilities.${field}` },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: `harnesses[].capabilities.${field}` },\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.claim', field: `capabilities.${field}` },\n ]),\n // Version policy and runtime-unavailable discovery (#1103 B2b). All are\n // strip-safe: an older receiver drops them, and absence means unknown — it\n // must never be read as `allow` or `available`. Presence keeps the built-in\n // runtime identity domain; harness policy travels only on conn.hello.\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimes[].versionPolicy' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'harnesses[].versionPolicy' },\n { kind: 'envelope', rule: 'strip-safe', surface: 'conn.hello', field: 'runtimeUnavailable' },\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimes[].versionPolicy' },\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimeUnavailable' },\n // Presence carries the conn.hello capability matrix (#1103); a published cloud drops it.\n { kind: 'http', rule: 'strip-safe', surface: 'PresencePublishRequest', field: 'runtimes[].capabilities' },\n // Optional MCP event identity is observability only; older receivers may omit it.\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.progress', field: 'events[].mcp' },\n // Daemon to server.\n { kind: 'envelope', rule: 'gated', surface: 'agent.message.draft', capability: 'agent-message-draft', advertisedBy: 'server' },\n { kind: 'envelope', rule: 'gated', surface: 'task.fail', field: 'failure', capability: 'runtime-failure-class', advertisedBy: 'server' },\n { kind: 'envelope', rule: 'gated', surface: 'task.fail', field: 'failure.scope', capability: 'runtime-quota-scope', advertisedBy: 'server' },\n // Typed pre-claim runtime-unavailable cause (#1103 B2a). An older server\n // drops the nested field and still records the open `runtime_unavailable`\n // code; the cause never changes what the receiver executes.\n { kind: 'envelope', rule: 'strip-safe', surface: 'task.decline', field: 'runtimeUnavailable' },\n // Relative token lifetime (#1114). A published device drops it and keeps\n // reading `expiresAt`, which the Host still sends.\n { kind: 'http', rule: 'strip-safe', surface: 'TokenResponse', field: 'expiresIn' },\n // Relative token lifetime (#1114), as on the token response; a published\n // device drops it.\n { kind: 'http', rule: 'strip-safe', surface: 'PairResponse', field: 'expiresIn' },\n];\n\nexport const WIRE_ADDITIONS: readonly WireAddition[] = Object.freeze([\n ...PLAIN_ROWS,\n ...sealedRows(),\n ...SEALED_V2_ROWS,\n SEALED_DECLINE_CODE('sealed_key_unavailable'),\n SEALED_DECLINE_CODE('sealed_open_failed'),\n SEALED_DECLINE_CODE('sealed_content_mac_mismatch'),\n SEALED_DECLINE_CODE('sealing_policy_mismatch'),\n] satisfies readonly WireAddition[]);\n\n/**\n * Every capability the receiver must have durably advertised before a sender\n * may emit this message. Deduplicated, in table order. A sender refuses (before\n * creating the task or appending to the mailbox) when any is missing.\n */\nexport function requiredReceiverCapabilities(type: MessageType, payload: unknown): CapabilityFlag[] {\n const fields = payload !== null && typeof payload === 'object' ? (payload as Record<string, unknown>) : {};\n const required: CapabilityFlag[] = [];\n for (const entry of WIRE_ADDITIONS) {\n if (entry.kind !== 'envelope' || entry.rule !== 'gated' || entry.surface !== type) continue;\n if (entry.field !== undefined) {\n const value = entry.field.split('.').reduce<unknown>(\n (parent, segment) => (parent !== null && typeof parent === 'object' ? (parent as Record<string, unknown>)[segment] : undefined),\n fields,\n );\n if (value === undefined) continue;\n if (entry.value !== undefined && !(Array.isArray(value) ? value.includes(entry.value) : value === entry.value)) continue;\n }\n if (!required.includes(entry.capability)) required.push(entry.capability);\n }\n return required;\n}\n","import { z } from 'zod';\n\n/**\n * Canonical `contentHash` format (finding F9): `sha256:` followed by exactly\n * 64 lowercase hex characters (a SHA-256 digest). Pinned here — the single\n * source of truth both `BlobRefSchema` and `CreateBlobRequestSchema`\n * (`http-api.ts`) validate against — rather than left as a bare `z.string()`\n * that silently accepted any prefix (or none) and left the server to\n * reconcile the mismatch with an ad hoc normalization step. No compat shim:\n * the wire is pre-freeze (`v` stays `1`), so this is a straight tightening,\n * not a migration.\n */\nexport const CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * Reference to a large payload that was pushed out-of-band (presigned PUT) or\n * is fetchable out-of-band (presigned GET), rather than inlined in an envelope.\n */\nexport const BlobRefSchema = z.object({\n blobId: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be \"sha256:<64 lowercase hex>\"'),\n size: z.number().int().nonnegative(),\n contentType: z.string(),\n url: z.string().optional(),\n});\n\nexport type BlobRef = z.infer<typeof BlobRefSchema>;\n","import { z } from 'zod';\n\n/**\n * Agent-local/cloud egress is an explicit, versioned contract. This module\n * owns the public policy and fact vocabulary; transport messages compose it\n * with Agent identity in `messages.ts` so the two directions do not create\n * competing policy shapes.\n */\n\nconst POLICY_REVISION = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'policyRevision must not contain control characters');\n\nconst POSITIVE_LIMIT = z.number().int().positive().max(2_147_483_647);\nexport const AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES = 16 * 1024;\nexport const AGENT_MESSAGE_MAX_BYTES = 256 * 1024;\nexport const AgentMessageContractSchema = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u, 'message contract must be an opaque portable identifier');\nexport const AgentMessageContentTypeSchema = z.enum(['text/plain', 'text/markdown']);\nexport const AgentMessageDestinationBindingSchema = z\n .string()\n .min(1)\n .max(2048)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'destination binding must not contain control characters');\nexport const AgentMessageFreshnessCursorSchema = z\n .string()\n .min(1)\n .max(512)\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'freshness cursor must not contain control characters');\n/** Host-only product authority. It is never serialized into an Agent offer or message envelope. */\nexport const AgentMessageServerContextSchema = z\n .object({\n destinationBinding: AgentMessageDestinationBindingSchema,\n freshnessCursor: AgentMessageFreshnessCursorSchema.optional(),\n })\n .strict();\nexport const AgentMessageEgressRequirementSchema = z\n .object({\n mode: z.literal('required'),\n contract: AgentMessageContractSchema,\n contentType: AgentMessageContentTypeSchema,\n maxBytes: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\n })\n .strict();\nexport type AgentMessageEgressRequirement = z.infer<typeof AgentMessageEgressRequirementSchema>;\nexport type AgentMessageContentType = z.infer<typeof AgentMessageContentTypeSchema>;\nexport type AgentMessageServerContext = z.infer<typeof AgentMessageServerContextSchema>;\nexport const AgentContentMimeTypeSchema = z\n .string()\n .min(3)\n .max(255)\n .regex(/^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/iu, 'MIME types must be explicit type/subtype values');\n\n/** Explicit MIME and byte policy for one independently-authorized content surface. */\nexport const ContentReadPolicySchema = z\n .object({\n maxBytes: POSITIVE_LIMIT,\n allowedMimeTypes: z.array(AgentContentMimeTypeSchema).min(1).max(32),\n })\n .strict();\nexport type ContentReadPolicy = z.infer<typeof ContentReadPolicySchema>;\n\n/**\n * The latest-value activity lane. Agent events go to the Host as the runtime\n * produced them; these limits only bound transport (coalesce window and one\n * event's byte size).\n */\nexport const AgentEgressActivityPolicySchema = z\n .object({\n delivery: z.literal('latest-value'),\n maxCoalesceMs: POSITIVE_LIMIT,\n maxEventBytes: POSITIVE_LIMIT,\n })\n .strict();\nexport type AgentEgressActivityPolicy = z.infer<typeof AgentEgressActivityPolicySchema>;\n\nexport const AgentReliableQuotaPolicySchema = z\n .object({\n maxPendingEventsPerAgent: POSITIVE_LIMIT,\n maxPendingBytesPerAgent: POSITIVE_LIMIT,\n maxPendingBytesPerTenant: POSITIVE_LIMIT,\n })\n .strict();\nexport type AgentReliableQuotaPolicy = z.infer<typeof AgentReliableQuotaPolicySchema>;\n\n/**\n * The only consumable policy shape for Agent egress. It selects transport\n * limits and the Host content-read surfaces. It does not filter, redact or\n * omit Agent egress content. Callers must select a revision and all three\n * content-read surfaces independently.\n */\nexport const AgentEgressPolicySchema = z\n .object({\n policyRevision: POLICY_REVISION,\n activity: AgentEgressActivityPolicySchema,\n reliable: AgentReliableQuotaPolicySchema,\n transfers: z\n .object({\n workspace: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n transcript: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n artifact: z.union([z.literal('disabled'), ContentReadPolicySchema]),\n })\n .strict(),\n })\n .strict();\nexport type AgentEgressPolicy = z.infer<typeof AgentEgressPolicySchema>;\n\n/** Delivery stores are semantically distinct; this enum is never a durable boolean. */\nexport const AgentEgressLaneSchema = z.enum(['reliable', 'latest-value']);\nexport type AgentEgressLane = z.infer<typeof AgentEgressLaneSchema>;\n\n/** Every refusal/replacement is observable rather than silently degrading to another lane. */\nexport const AgentEgressDropReasonSchema = z.enum([\n 'policy_denied',\n 'capability_missing',\n 'quota_exceeded',\n 'backpressure',\n 'coalesced',\n 'disconnected',\n 'invalid_envelope',\n 'ack_mismatch',\n]);\nexport type AgentEgressDropReason = z.infer<typeof AgentEgressDropReasonSchema>;\n\nexport const AgentContentReadSurfaceSchema = z.enum(['workspace', 'transcript', 'artifact']);\nexport type AgentContentReadSurface = z.infer<typeof AgentContentReadSurfaceSchema>;\n\n/** The product-selected actor is explicit; tenant/device are bound by the authenticated transport. */\nexport const AgentContentActorKindSchema = z.enum(['user', 'agent', 'system']);\nexport type AgentContentActorKind = z.infer<typeof AgentContentActorKindSchema>;\n\nexport const AgentContentActorSchema = z\n .object({\n kind: AgentContentActorKindSchema,\n id: z.string().min(1).max(512).regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'actor id must not contain control characters'),\n })\n .strict();\nexport type AgentContentActor = z.infer<typeof AgentContentActorSchema>;\n\n/** No byte/text interpretation is inferred from a target name or MIME declaration. */\nexport const AgentContentDecodeAsSchema = z.enum(['bytes', 'utf8']);\nexport type AgentContentDecodeAs = z.infer<typeof AgentContentDecodeAsSchema>;\n\nexport const AgentContentReadDecisionSchema = z.enum(['allowed', 'denied']);\nexport type AgentContentReadDecision = z.infer<typeof AgentContentReadDecisionSchema>;\n\nexport const AgentContentReadDenialReasonSchema = z.enum([\n 'invalid-request',\n 'policy-disabled',\n 'capability-missing',\n 'policy-revision-mismatch',\n 'absolute-target',\n 'non-relative-target',\n 'dot-segment',\n 'sensitive-name',\n 'root-not-allowlisted',\n 'root-invalid',\n 'path-escape',\n 'target-missing',\n 'symlink',\n 'not-regular-file',\n 'byte-limit',\n 'mime-not-allowlisted',\n 'text-not-allowlisted',\n 'text-decode-failed',\n 'identity-mismatch',\n]);\nexport type AgentContentReadDenialReason = z.infer<typeof AgentContentReadDenialReasonSchema>;\n\n/** SHA-256 transport receipt hash, never a content byte projection. */\nexport const AgentEgressContentHashSchema = z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/u, 'contentHash must be a lowercase SHA-256 digest');\n\nexport const AgentEgressPolicyRevisionSchema = POLICY_REVISION;\n","/**\n * Sealed payload on the hosted wire: v1 (#654 design §8.1, §8.3, §8.6) and\n * the v2 categories (#1045).\n *\n * Sealed is a property of the payload, not a message type: each sealable\n * type's payload is a plaintext branch or a sealed branch. The sealed branch is\n * the plaintext fields without the ones one data category moves into the\n * ciphertext, plus a sealed member; its marker field is gated on\n * `sealed-payload-v1`, and the payload is strict, so a decoder that does not\n * know the branch refuses the whole message. The Host reads only the sealed\n * member's outer fields. It checks the shape here:\n * version, suite, encodings, a legal padded length, and exactly one of inline\n * `ciphertext` and `ciphertextRef`. Inline is the only legal form up to\n * {@link SEALED_INLINE_MAX_PADDED_LENGTH}; above it, the ciphertext is a blob.\n * So one content has one legal wire form, and two submissions compare by\n * their outer fields only.\n *\n * `@byok-sdk/core/sealed-payload` seals and opens the bytes. Protocol does\n * not depend on core, so this module repeats the header rules and the padded\n * length function; a cross-package test keeps the two equal.\n */\nimport { z } from 'zod';\n\nimport { AGENT_MESSAGE_MAX_BYTES } from './agent-egress';\nimport { BlobRefSchema, CONTENT_HASH_RE } from './blob';\n\nimport { SEALED_SPLIT_TABLE, isSealableMessageType, sealedMovedFields, type SealedSplitEntry } from './sealed-split-table';\n\nexport { SEALED_SPLIT_TABLE, isSealableMessageType, isSealedPayload, sealedMovedFields } from './sealed-split-table';\nexport type { SealableMessageType, SealedDigestRule, SealedSplitEntry } from './sealed-split-table';\n\nexport const SEALED_PAYLOAD_VERSION = 1;\n/** The only suite v1 admits. A new suite is a new constant and a new capability, never a parser branch. */\nexport const SEALED_PAYLOAD_SUITE = 'byok-sealed-v1.hkdf-sha256.aes-256-gcm';\n\n/**\n * C1–C4 in canonical order. A task lists its sealing categories in this order.\n * Input preparation and drafts have no category; they stay plaintext.\n */\nexport const SEALED_PAYLOAD_CATEGORIES = ['task-input', 'agent-message', 'task-output', 'memory-projection'] as const;\nexport type SealedPayloadCategory = (typeof SEALED_PAYLOAD_CATEGORIES)[number];\n\n/**\n * Closed `task.decline` codes of a receiver that refuses sealed task input\n * (§8.3). They are plaintext: a device without the scope key cannot seal a\n * reason. A device sends them only to a server that advertised\n * `sealed-payload-v1`.\n */\nexport const SEALED_DECLINE_CODES = [\n 'sealed_key_unavailable',\n 'sealed_open_failed',\n 'sealed_content_mac_mismatch',\n 'sealing_policy_mismatch',\n] as const;\nexport type SealedDeclineCode = (typeof SEALED_DECLINE_CODES)[number];\n\n/**\n * The closed plaintext codes of a task whose output is sealed (#654 12d).\n * It lists each output type that has a plaintext form on such a task, with\n * the codes that each field moved or dropped by its sealed branch may hold.\n * Such a field that is not listed here must be absent. An output type with a\n * sealed branch that is not listed has no plaintext form. An\n * interrupted task reports `daemon_interrupted`; a device that cannot seal\n * reports `sealed_key_unavailable`. The Host check, the daemon and the member\n * display read this one list, and compare by exact match.\n */\nexport const SEALED_TASK_PLAIN_CODES = Object.freeze({\n 'task.fail': { reason: ['daemon_interrupted', 'sealed_key_unavailable'] },\n 'task.decline': { reason: SEALED_DECLINE_CODES },\n 'task.cancelled': { reason: [] },\n} as const);\n\n/**\n * True when `payload` is a legal plaintext `type` message of a task whose\n * output is sealed under `categories`: each field that the `task-output`\n * sealed branch of `type` moves (with the `movedWith` fields of `categories`)\n * or drops is absent or holds one of {@link SEALED_TASK_PLAIN_CODES}. A type\n * that has a sealed output branch and is not listed there is never legal. A\n * plaintext decline also names its code as `code`. A type with no sealed\n * output branch is always legal.\n */\nexport function isSealedTaskPlainOutput(type: string, payload: object, categories: readonly SealedPayloadCategory[]): boolean {\n const codes: { readonly [field: string]: readonly string[] } = Object.hasOwn(SEALED_TASK_PLAIN_CODES, type)\n ? SEALED_TASK_PLAIN_CODES[type as keyof typeof SEALED_TASK_PLAIN_CODES]\n : {};\n const entry: SealedSplitEntry | undefined = isSealableMessageType(type) ? SEALED_SPLIT_TABLE[type] : undefined;\n const fields: readonly string[] = entry?.category === 'task-output'\n ? [...sealedMovedFields(type as keyof typeof SEALED_SPLIT_TABLE, categories), ...entry.forbidden]\n : [];\n if (fields.length > 0 && !Object.hasOwn(SEALED_TASK_PLAIN_CODES, type)) return false;\n const record = payload as Readonly<Record<string, unknown>>;\n for (const field of fields) {\n const value = record[field];\n if (value !== undefined && !(typeof value === 'string' && (codes[field] ?? []).includes(value))) return false;\n }\n return type !== 'task.decline' || record.reason === undefined || record.code === record.reason;\n}\n\n/** Padded frames above this length travel as a ciphertext blob (§8.6). */\nexport const SEALED_INLINE_MAX_PADDED_LENGTH = 256 * 1024;\n\n/** Plaintext limit of every category, in UTF-8 bytes of canonical JSON (D8). */\nexport const SEALED_PAYLOAD_MAX_CONTENT_LENGTH = 2 * 1024 * 1024;\n\n/** `{\"body\":\"\"}`: the canonical JSON of a sealed message around its body. */\nconst SEALED_AGENT_MESSAGE_FRAME_BYTES = 11;\n/**\n * The canonical JSON escaping bound: `JSON.stringify` turns a one-byte\n * control character into the six bytes `\\u00XX`, and nothing grows more per\n * UTF-8 byte (a lone surrogate, three bytes, becomes six).\n */\nconst JSON_STRING_MAX_EXPANSION = 6;\n\n/**\n * The largest opened content of a sealed `agent.message.publish` whose body\n * is at most `maxBytes` UTF-8 bytes (#1045 O2): `6 × maxBytes + 11`. At\n * `AGENT_MESSAGE_MAX_BYTES` it is 1,572,875, below\n * {@link SEALED_PAYLOAD_MAX_CONTENT_LENGTH}, so every legal body seals. The\n * device seals within it, and the Host bounds a sealed message's\n * `paddedLength` by `sealedPayloadPaddedLength(4 + this)` for the task's\n * frozen `maxBytes`.\n */\nexport function sealedAgentMessageMaxContentLength(maxBytes: number): number {\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > AGENT_MESSAGE_MAX_BYTES) {\n throw new RangeError(`An Agent message limit must be an integer from 1 to ${AGENT_MESSAGE_MAX_BYTES}`);\n }\n return JSON_STRING_MAX_EXPANSION * maxBytes + SEALED_AGENT_MESSAGE_FRAME_BYTES;\n}\n\nconst AEAD_TAG_BYTES = 16;\nconst FRAME_HEADER_BYTES = 4;\nconst ALIGNED_FRAME_LIMIT = 16 * 1024;\nconst FRAME_ALIGNMENT = 256;\nconst SALT_BYTES = 32;\nconst NONCE_BYTES = 12;\n\nfunction floorLog2(value: number): number {\n let exponent = 0;\n for (let remaining = value; remaining >= 2; remaining = Math.floor(remaining / 2)) exponent += 1;\n return exponent;\n}\n\n/**\n * The one legal padded length of a frame of `frameLength` bytes\n * (`4 + contentLength`): the next multiple of 256 up to 16 KiB, Padmé above.\n */\nexport function sealedPayloadPaddedLength(frameLength: number): number {\n if (!Number.isSafeInteger(frameLength) || frameLength < FRAME_HEADER_BYTES) {\n throw new RangeError('Sealed frame length must be a safe integer of at least 4');\n }\n if (frameLength <= ALIGNED_FRAME_LIMIT) return Math.ceil(frameLength / FRAME_ALIGNMENT) * FRAME_ALIGNMENT;\n const exponent = floorLog2(frameLength);\n const step = 2 ** (exponent - (floorLog2(exponent) + 1));\n return Math.ceil(frameLength / step) * step;\n}\n\n/** The largest padded length a sealed content may have. */\nexport const SEALED_PAYLOAD_MAX_PADDED_LENGTH = sealedPayloadPaddedLength(\n FRAME_HEADER_BYTES + SEALED_PAYLOAD_MAX_CONTENT_LENGTH,\n);\n\nfunction isLegalPaddedLength(value: number): boolean {\n return Number.isSafeInteger(value)\n && value >= FRAME_ALIGNMENT\n && value <= SEALED_PAYLOAD_MAX_PADDED_LENGTH\n && sealedPayloadPaddedLength(value) === value;\n}\n\nconst BASE64URL_VALUE = /^[A-Za-z0-9_-]*$/u;\nconst BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\n/**\n * The byte length of canonical unpadded base64url, or `undefined`. Canonical\n * means no padding, no impossible length, and zero unused bits in the last\n * character, so one byte string has exactly one encoding.\n */\nexport function sealedBase64UrlByteLength(value: string): number | undefined {\n if (!BASE64URL_VALUE.test(value)) return undefined;\n const tail = value.length % 4;\n if (tail === 1) return undefined;\n if (tail !== 0) {\n const last = BASE64URL_ALPHABET.indexOf(value[value.length - 1]!);\n const unusedBits = tail === 2 ? 0b1111 : 0b11;\n if ((last & unusedBits) !== 0) return undefined;\n }\n return Math.floor(value.length / 4) * 3 + (tail === 0 ? 0 : tail - 1);\n}\n\nfunction base64UrlOf(bytes: number) {\n return z.string().refine((value) => sealedBase64UrlByteLength(value) === bytes, `must be canonical unpadded base64url of ${bytes} bytes`);\n}\n\nconst PositiveIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);\n\n/**\n * One sealed content (§8.1) of one category. The outer fields are what the\n * Host reads; the ciphertext is the padded frame plus the 16-byte AES-GCM tag.\n * A message type fixes its category, so its schema names it as a literal. An\n * inline-only content refuses a padded length above the inline maximum.\n */\nfunction sealedPayloadSchema<Category extends z.ZodType<SealedPayloadCategory>>(category: Category, inlineOnly = false) {\n return z\n .object({\n v: z.literal(SEALED_PAYLOAD_VERSION),\n suite: z.literal(SEALED_PAYLOAD_SUITE),\n category,\n scope: z\n .object({\n id: z.string().min(1),\n epoch: PositiveIntegerSchema,\n keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u),\n })\n .strict(),\n chainHead: z\n .object({\n seq: PositiveIntegerSchema,\n hash: z.string().regex(CONTENT_HASH_RE),\n })\n .strict(),\n sender: z.string().regex(/^[A-Za-z0-9_-]{43}$/u),\n salt: base64UrlOf(SALT_BYTES),\n nonce: base64UrlOf(NONCE_BYTES),\n paddedLength: PositiveIntegerSchema.refine(isLegalPaddedLength, 'must be a legal padded frame length within the v1 limit'),\n contentMac: z.string().regex(/^hmac-sha256:[0-9a-f]{64}$/u),\n ciphertext: z.string().optional(),\n /** The ciphertext blob. A presigned `url` is transport detail and never part of a sealed member. */\n ciphertextRef: BlobRefSchema.omit({ url: true }).strict().optional(),\n })\n .strict()\n .superRefine((sealed, ctx) => {\n const ciphertextLength = sealed.paddedLength + AEAD_TAG_BYTES;\n const inline = sealed.paddedLength <= SEALED_INLINE_MAX_PADDED_LENGTH;\n if (inlineOnly && !inline) {\n ctx.addIssue({ code: 'custom', path: ['paddedLength'], message: `an inline-only content has a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH}` });\n return;\n }\n if (inline) {\n if (sealed.ciphertextRef !== undefined || sealed.ciphertext === undefined) {\n ctx.addIssue({ code: 'custom', path: ['ciphertext'], message: `a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH} carries inline ciphertext only` });\n } else if (sealedBase64UrlByteLength(sealed.ciphertext) !== ciphertextLength) {\n ctx.addIssue({ code: 'custom', path: ['ciphertext'], message: 'ciphertext must be canonical base64url of paddedLength + 16 bytes' });\n }\n return;\n }\n if (sealed.ciphertext !== undefined || sealed.ciphertextRef === undefined) {\n ctx.addIssue({ code: 'custom', path: ['ciphertextRef'], message: `a padded length above ${SEALED_INLINE_MAX_PADDED_LENGTH} carries ciphertextRef only` });\n } else if (sealed.ciphertextRef.size !== ciphertextLength) {\n ctx.addIssue({ code: 'custom', path: ['ciphertextRef', 'size'], message: 'ciphertextRef size must equal paddedLength + 16' });\n }\n });\n}\n\n/** A sealed member of any category. */\nexport const SealedPayloadSchema = sealedPayloadSchema(z.enum(SEALED_PAYLOAD_CATEGORIES));\nexport type SealedPayload = z.infer<typeof SealedPayloadSchema>;\n/** The sealed member of a task-input message (offers, steer). */\nexport const SealedTaskInputSchema = sealedPayloadSchema(z.literal('task-input'));\n/** The sealed member of a task-output message. */\nexport const SealedTaskOutputSchema = sealedPayloadSchema(z.literal('task-output'));\n/** The sealed member of an `agent.message.publish` (#1045 C2). */\nexport const SealedAgentMessageSchema = sealedPayloadSchema(z.literal('agent-message'));\n/**\n * The sealed member of a memory projection (#1045 C4). It is inline only\n * (owner decision O2): the Host keeps one latest snapshot per Agent and holds\n * no ciphertext blob for it.\n */\nexport const SealedMemoryProjectionSchema = sealedPayloadSchema(z.literal('memory-projection'), true);\n\nfunction isCanonicalCategoryList(categories: readonly string[]): boolean {\n return categories.every((category, index) => index === 0\n || SEALED_PAYLOAD_CATEGORIES.indexOf(categories[index - 1] as SealedPayloadCategory)\n < SEALED_PAYLOAD_CATEGORIES.indexOf(category as SealedPayloadCategory));\n}\n\n/**\n * A task's frozen sealing policy (§6.2). The offer carries it in plaintext.\n * `epoch` is the epoch of the offer's task-input content, and the lowest epoch\n * the task accepts. `memory-projection` needs `task-output`: a terminal seals\n * the task's memory-change evidence inside its task-output ciphertext.\n */\nexport const TaskSealingSchema = z\n .object({\n scopeId: z.string().min(1),\n epoch: PositiveIntegerSchema,\n categories: z\n .array(z.enum(SEALED_PAYLOAD_CATEGORIES))\n .min(1)\n .refine(isCanonicalCategoryList, 'categories must be unique and in canonical order')\n .refine(\n (categories) => !categories.includes('memory-projection') || categories.includes('task-output'),\n 'a task that seals memory-projection seals task-output too',\n ),\n })\n .strict();\nexport type TaskSealing = z.infer<typeof TaskSealingSchema>;\n\n/**\n * A canonical UTC instant, `YYYY-MM-DDTHH:mm:ss.sssZ` and a real calendar\n * instant. This is the form core binds as `notAfter` in the AAD\n * (`@byok-sdk/core` `isCanonicalTimestamp`), so a device can rebuild the AAD\n * from the wire value byte for byte.\n */\nconst CanonicalInstantSchema = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/u)\n .refine((value) => {\n const instant = Date.parse(value);\n return Number.isFinite(instant) && new Date(instant).toISOString() === value;\n }, 'must be a canonical UTC instant');\n\n/**\n * The routine template of a sealed execution (design §6.3). The offer's\n * `sealed` member is then the template, family `routine.template`, which the\n * member sealed once for every occurrence. The device rebuilds its binding\n * from these fields: identity `{ routineId, definitionVersion }`, no device,\n * the offer's `agentRef` and `sealing.categories`, and `notAfter`. They travel\n * in plaintext because the AAD binds them. `definitionVersion` is an integer,\n * because the binding tells `4` and `\"4\"` apart. The device, not the Host,\n * checks `notAfter` against its clock.\n */\nexport const RoutineRefSchema = z\n .object({\n routineId: z.string().min(1),\n definitionVersion: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n notAfter: CanonicalInstantSchema,\n })\n .strict();\n\n\n/**\n * The rule of a sealed offer, for `superRefine`: `sealed` is present exactly\n * when the task's `sealing` includes `task-input`, and then `instruction` is\n * absent and `sealed.scope` is the task's scope at the task's epoch. When the\n * task seals only its output, `instruction` is plaintext and required. A\n * `routineRef` names a routine template, which is sealed task input, so it\n * needs a task that seals `task-input`.\n *\n * Whether a task's later messages must be sealed is the Host's and the\n * device's check: they know the task's `sealing`, this payload does not.\n */\nexport function sealedOfferRule(\n payload: { readonly instruction?: unknown; readonly sealing: TaskSealing; readonly sealed?: SealedPayload; readonly routineRef?: unknown },\n ctx: z.RefinementCtx,\n): void {\n const { instruction, sealing, sealed, routineRef } = payload;\n if (!sealing.categories.includes('task-input')) {\n if (routineRef !== undefined) ctx.addIssue({ code: 'custom', path: ['routineRef'], message: 'a routine template is sealed task input, so routineRef needs a task that seals task-input' });\n if (sealed !== undefined) ctx.addIssue({ code: 'custom', path: ['sealed'], message: 'a task that does not seal task-input carries no sealed member' });\n if (instruction === undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a task that does not seal task-input carries a plaintext instruction' });\n return;\n }\n if (sealed === undefined) {\n ctx.addIssue({ code: 'custom', path: ['sealed'], message: 'a task that seals task-input carries the sealed instruction' });\n return;\n }\n if (instruction !== undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a sealed instruction never travels in plaintext too' });\n if (sealed.scope.id !== sealing.scopeId || sealed.scope.epoch !== sealing.epoch) {\n ctx.addIssue({ code: 'custom', path: ['sealed', 'scope'], message: 'the offer task-input must be sealed under the task scope at the task epoch' });\n }\n}\n","import { z } from 'zod';\n\n/** Opaque, portable local profile identity. It is one logical id, never a path. */\nexport const ProviderProfileRefSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u, 'provider profile refs must be lowercase portable identifiers');\nexport type ProviderProfileRef = z.infer<typeof ProviderProfileRefSchema>;\n\n/** Monotonic local profile revision represented canonically on the wire. */\nexport const ProviderProfileRevisionSchema = z\n .string()\n .regex(/^(?:0|[1-9][0-9]{0,19})$/u, 'provider profile revision must be canonical decimal');\nexport type ProviderProfileRevision = z.infer<typeof ProviderProfileRevisionSchema>;\n\n/** Hash of the normalized, non-secret local profile projection. */\nexport const ProviderProfileHashSchema = z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/u, 'provider profile hash must be lowercase sha256');\nexport type ProviderProfileHash = z.infer<typeof ProviderProfileHashSchema>;\n\nexport const PROVIDER_MODEL_CAPABILITIES = ['image-input'] as const;\nexport const ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);\nexport type ProviderModelCapability = z.infer<typeof ProviderModelCapabilitySchema>;\n\n/** Credential-free exact desired binding. Endpoint and auth material stay device-local. */\nexport const ProviderProfileBindingSchema = z\n .object({\n profileRef: ProviderProfileRefSchema,\n profileRevision: ProviderProfileRevisionSchema,\n profileHash: ProviderProfileHashSchema,\n modelId: z.string().min(1).max(160).regex(/^[^\\u0000\\r\\n]+$/u),\n requiredCapabilities: z.array(ProviderModelCapabilitySchema).max(8),\n })\n .strict()\n .superRefine((binding, ctx) => {\n if (new Set(binding.requiredCapabilities).size !== binding.requiredCapabilities.length) {\n ctx.addIssue({ code: 'custom', path: ['requiredCapabilities'], message: 'duplicate provider capability' });\n }\n });\nexport type ProviderProfileBinding = z.infer<typeof ProviderProfileBindingSchema>;\n","import { z } from 'zod';\nimport {\n ProviderModelCapabilitySchema,\n ProviderProfileBindingSchema,\n ProviderProfileRefSchema,\n} from './provider-profile-binding';\n\n/**\n * Sealed provider provisioning — the wire half.\n *\n * A Host provisions a device-local provider profile (and its API key) without\n * the key ever crossing this SDK's wire. The ciphertext, its configuration and\n * the device's pull of both travel over the HOST's own authenticated device\n * routes; this package defines only:\n *\n * - the task-free server -> daemon notice `provider.provisioning.available`,\n * whose payload is exactly `{ requestId }` (see `messages.ts`);\n * - the device capability that gates that notice;\n * - the credential-free completion a device reports and the durable readback a\n * Host returns for it;\n * - the device-proof operation name a device signs when it registers its\n * provider-secret sealing key.\n *\n * Notice-and-fetch is the point: the daemon journals mailbox rows before they\n * are acknowledged and a mailbox never deletes an unacknowledged row, so a\n * ciphertext carried inside the envelope would outlive the provisioning window\n * in two places. The strict one-field payload makes that unrepresentable.\n *\n * Audiences, route paths and product names are Host vocabulary and stay out of\n * this package.\n */\n\n/**\n * Device-proof `operation` for the signed claim that registers the device's\n * provider-secret sealing public key (`{ keyId, epoch, publicJwk }`).\n */\nexport const PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION = 'provider-secret-sealing-key.register' as const;\n\n/**\n * Server -> daemon: a provisioning request is waiting for this device.\n *\n * `.strict()` and exactly one field. There is deliberately no configuration,\n * no ciphertext, no provider identity and no Agent identity: the device fetches\n * all of that from the Host under its own device authentication, so a mailbox\n * row or journal line never holds more than an opaque request id.\n */\nexport const ProviderProvisioningAvailablePayloadSchema = z\n .object({\n requestId: z.uuid(),\n })\n .strict();\nexport type ProviderProvisioningAvailablePayload = z.infer<typeof ProviderProvisioningAvailablePayloadSchema>;\n\nexport const PROVIDER_PROVISIONING_OPERATIONS = ['configure', 'update_model', 'replace_secret', 'delete'] as const;\nexport const ProviderProvisioningOperationSchema = z.enum(PROVIDER_PROVISIONING_OPERATIONS);\nexport type ProviderProvisioningOperation = z.infer<typeof ProviderProvisioningOperationSchema>;\n\n/** PostgreSQL BIGINT maximum, carried as decimal text to avoid JavaScript precision loss. */\nexport const PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM = '9223372036854775807' as const;\n\n/**\n * Non-secret, monotonic per-profile operation generation. It is bound into the\n * sealed request's associated data and into the device's local state, so an\n * older generation is always refused. Canonical positive decimal text.\n */\nexport const ProviderProvisioningOperationGenerationSchema = z\n .string()\n .regex(/^[1-9][0-9]{0,18}$/u, 'operationGeneration must be a canonical positive decimal string')\n .refine(\n (value) =>\n value.length < PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM.length ||\n value <= PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM,\n `operationGeneration must not exceed ${PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM}`,\n );\nexport type ProviderProvisioningOperationGeneration = z.infer<typeof ProviderProvisioningOperationGenerationSchema>;\n\n/**\n * SHA-256 of the canonical non-secret operation the device evaluated. Two\n * completions for one request id are the same result only when this digest\n * (and the rest of the completion) is identical. Pinned to `@byok-sdk/core`\n * `providerProvisioningRequestDigest(request)` (the value `@byok-sdk/keys`\n * returns as `result.requestDigest`); see docs/protocol.md §2.3.\n */\nexport const ProviderProvisioningOperationDigestSchema = z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/u, 'operationDigest must be lowercase sha256');\nexport type ProviderProvisioningOperationDigest = z.infer<typeof ProviderProvisioningOperationDigestSchema>;\n\n/**\n * Closed rejection set. Codes name a failed check, never a value: no plaintext,\n * no ciphertext, no OS error detail. `local_commit_interrupted` also covers a\n * request that finds the same or another operation still pending locally.\n *\n * `request_expired` and `sealing_key_rotated` may also be decided by the Host\n * before the device ever completes the request (see\n * {@link PROVIDER_PROVISIONING_HOST_TERMINAL_CODES}).\n */\nexport const PROVIDER_PROVISIONING_REJECTION_CODES = [\n 'request_invalid',\n 'request_conflict',\n 'request_expired',\n 'request_not_yet_valid',\n 'request_window_invalid',\n 'sealing_key_rotated',\n 'enrollment_mismatch',\n 'agent_not_placed',\n 'config_digest_mismatch',\n 'operation_generation_stale',\n 'profile_changed',\n 'profile_not_found',\n 'credential_scope_mismatch',\n 'provider_kind_unsupported',\n 'pi_model_invalid',\n 'capabilities_invalid',\n 'seal_open_failed',\n 'secret_invalid',\n 'local_commit_interrupted',\n 'secret_store_unavailable',\n] as const;\nexport const ProviderProvisioningRejectionCodeSchema = z.enum(PROVIDER_PROVISIONING_REJECTION_CODES);\nexport type ProviderProvisioningRejectionCode = z.infer<typeof ProviderProvisioningRejectionCodeSchema>;\n\n/** Rejections a Host may record on its own authority, without a device completion. */\nexport const PROVIDER_PROVISIONING_HOST_TERMINAL_CODES = ['request_expired', 'sealing_key_rotated'] as const satisfies\n readonly ProviderProvisioningRejectionCode[];\n\n/**\n * Credential-free projection of the device's provider status after an applied\n * operation. It reports WHETHER a secret is configured, never the secret, and\n * carries no endpoint or auth material: those stay device-local.\n */\nexport const ProviderProvisioningProviderStatusSchema = z\n .object({\n profileRef: ProviderProfileRefSchema,\n providerKind: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u, 'providerKind must be a lowercase portable identifier'),\n modelId: z.string().min(1).max(160).regex(/^[^\\u0000\\r\\n]+$/u),\n capabilities: z.array(ProviderModelCapabilitySchema).max(8),\n secretConfigured: z.boolean(),\n })\n .strict()\n .superRefine((status, ctx) => {\n if (new Set(status.capabilities).size !== status.capabilities.length) {\n ctx.addIssue({ code: 'custom', path: ['capabilities'], message: 'duplicate provider capability' });\n }\n });\nexport type ProviderProvisioningProviderStatus = z.infer<typeof ProviderProvisioningProviderStatusSchema>;\n\n/**\n * Closed outcome set of the device's one post-apply check of the stored key\n * against its vendor. It is a HINT for the Host UI, never a readiness input:\n * a saved key is not a validated key, and a network failure does not block\n * provisioning.\n *\n * - `credential_rejected`: the vendor explicitly refused the credential.\n * - `rate_limited`, `quota_or_billing`, `model_not_permitted`: the credential\n * was accepted but the call could not be served for that reason.\n * - `provider_error`: the vendor answered with an error that is none of the\n * classes above.\n * - `unreachable`, `timeout`: no vendor answer within the device's bounds.\n * - `not_run`: no check was made (for example `delete`, or an endpoint without\n * credential auth).\n *\n * No vendor text, status body or error detail crosses this boundary.\n */\nexport const PROVIDER_PROVISIONING_KEY_CHECK_RESULTS = [\n 'ok',\n 'credential_rejected',\n 'rate_limited',\n 'quota_or_billing',\n 'model_not_permitted',\n 'provider_error',\n 'unreachable',\n 'timeout',\n 'not_run',\n] as const;\nexport const ProviderProvisioningKeyCheckResultSchema = z.enum(PROVIDER_PROVISIONING_KEY_CHECK_RESULTS);\nexport type ProviderProvisioningKeyCheckResult = z.infer<typeof ProviderProvisioningKeyCheckResultSchema>;\n\nexport const ProviderProvisioningKeyCheckSchema = z\n .object({\n result: ProviderProvisioningKeyCheckResultSchema,\n })\n .strict();\nexport type ProviderProvisioningKeyCheck = z.infer<typeof ProviderProvisioningKeyCheckSchema>;\n\nconst completionIdentity = {\n requestId: z.uuid(),\n operation: ProviderProvisioningOperationSchema,\n operationGeneration: ProviderProvisioningOperationGenerationSchema,\n operationDigest: ProviderProvisioningOperationDigestSchema,\n} as const;\n\nconst AppliedCompletionSchema = z\n .object({\n outcome: z.literal('applied'),\n ...completionIdentity,\n providerStatus: ProviderProvisioningProviderStatusSchema.nullable(),\n binding: ProviderProfileBindingSchema.nullable(),\n keyCheck: ProviderProvisioningKeyCheckSchema,\n })\n .strict();\n\nconst RejectedCompletionSchema = z\n .object({\n outcome: z.literal('rejected'),\n ...completionIdentity,\n code: ProviderProvisioningRejectionCodeSchema,\n })\n .strict();\n\n/**\n * The terminal, credential-free result of one provisioning request, reported\n * by the device to the Host.\n *\n * `applied` carries the post-operation status and exact binding — both absent\n * (`null`) for `delete` and only for `delete`. `configure` and\n * `replace_secret` write a secret, so an applied result for either must report\n * `secretConfigured: true`. `replace_secret` leaves the profile revision and\n * hash unchanged; the binding it reports is the same exact binding as before.\n * Every applied result carries the required `keyCheck` hint; a `delete` has no\n * key left to check and must report `not_run`.\n */\nexport const ProviderProvisioningCompletionSchema = z\n .discriminatedUnion('outcome', [AppliedCompletionSchema, RejectedCompletionSchema])\n .superRefine((completion, ctx) => {\n if (completion.outcome !== 'applied') return;\n const { operation, providerStatus, binding } = completion;\n if (operation === 'delete') {\n if (completion.keyCheck.result !== 'not_run') {\n ctx.addIssue({ code: 'custom', path: ['keyCheck', 'result'], message: 'an applied delete must report keyCheck not_run' });\n }\n if (providerStatus !== null) {\n ctx.addIssue({ code: 'custom', path: ['providerStatus'], message: 'an applied delete reports no provider status' });\n }\n if (binding !== null) {\n ctx.addIssue({ code: 'custom', path: ['binding'], message: 'an applied delete reports no binding' });\n }\n return;\n }\n if (providerStatus === null) {\n ctx.addIssue({ code: 'custom', path: ['providerStatus'], message: `an applied ${operation} must report provider status` });\n }\n if (binding === null) {\n ctx.addIssue({ code: 'custom', path: ['binding'], message: `an applied ${operation} must report its exact binding` });\n }\n if (providerStatus === null || binding === null) return;\n if (providerStatus.profileRef !== binding.profileRef) {\n ctx.addIssue({ code: 'custom', path: ['binding', 'profileRef'], message: 'binding profileRef must equal providerStatus profileRef' });\n }\n if (providerStatus.modelId !== binding.modelId) {\n ctx.addIssue({ code: 'custom', path: ['binding', 'modelId'], message: 'binding modelId must equal providerStatus modelId' });\n }\n if ((operation === 'configure' || operation === 'replace_secret') && !providerStatus.secretConfigured) {\n ctx.addIssue({\n code: 'custom',\n path: ['providerStatus', 'secretConfigured'],\n message: `an applied ${operation} must report a configured secret`,\n });\n }\n });\nexport type ProviderProvisioningCompletion = z.infer<typeof ProviderProvisioningCompletionSchema>;\n\n/**\n * How the Host's durable record relates to the completion it was handed:\n *\n * - `recorded`: this completion became the request's first terminal fact.\n * - `idempotent`: an identical completion (same operation digest and result)\n * was already recorded; the stored result is returned and nothing is\n * rewritten.\n * - `conflict`: a different completion (different operation digest or result)\n * is already recorded; the stored one is returned unchanged.\n * - `host_terminal`: the Host had already terminated the request on its own\n * authority ({@link PROVIDER_PROVISIONING_HOST_TERMINAL_CODES}), for example\n * because it expired before the device fetched it.\n */\nexport const PROVIDER_PROVISIONING_DISPOSITIONS = ['recorded', 'idempotent', 'conflict', 'host_terminal'] as const;\nexport const ProviderProvisioningDispositionSchema = z.enum(PROVIDER_PROVISIONING_DISPOSITIONS);\nexport type ProviderProvisioningDisposition = z.infer<typeof ProviderProvisioningDispositionSchema>;\n\n/**\n * The Host's durable terminal readback for one provisioning request.\n *\n * `completion` is the terminal fact the Host has STORED, which on `conflict`\n * is not the one the device submitted. Every readback is terminal — there is\n * no `pending` — so a daemon that holds one may acknowledge the notice: an\n * expired, rotated, rejected or conflicting request is a deterministic end\n * state that no redelivery can change.\n */\nexport const ProviderProvisioningReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n disposition: ProviderProvisioningDispositionSchema,\n completion: ProviderProvisioningCompletionSchema,\n completedAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((readback, ctx) => {\n if (readback.completion.requestId !== readback.requestId) {\n ctx.addIssue({ code: 'custom', path: ['completion', 'requestId'], message: 'completion requestId must equal readback requestId' });\n }\n if (\n readback.disposition === 'host_terminal' &&\n (readback.completion.outcome !== 'rejected' ||\n !(PROVIDER_PROVISIONING_HOST_TERMINAL_CODES as readonly string[]).includes(readback.completion.code))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['completion'],\n message: `a host_terminal readback must carry a rejected completion with one of: ${PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.join(', ')}`,\n });\n }\n });\nexport type ProviderProvisioningReadback = z.infer<typeof ProviderProvisioningReadbackSchema>;\n","/**\n * Plain-JSON-data canonicalization shared by every bounded JSON channel of\n * the wire: `task.complete.document` (`checkResultDocument`, messages.ts) and\n * the result-document schema and outcome (`result-schema.ts`). One rule, one\n * implementation, so the channels cannot disagree about what \"plain JSON\n * data\" means or how its canonical UTF-8 size is measured.\n *\n * Zod-free and free of node builtins.\n */\n\n/** Outcome of {@link canonicalizePlainJson} without a depth bound. */\nexport type PlainJsonCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: unknown }\n | { readonly ok: false; readonly reason: 'not-serializable' }\n | { readonly ok: false; readonly reason: 'over-cap'; readonly bytes: number }\n | { readonly ok: false; readonly reason: 'not-plain-json' };\n\n/** Outcome of {@link canonicalizePlainJson} with a container-nesting bound. */\nexport type BoundedPlainJsonCheck =\n | PlainJsonCheck\n | { readonly ok: false; readonly reason: 'too-deep'; readonly bytes: number };\n\n/**\n * Structural equality between a value and its own JSON round trip, written\n * out by hand (no node builtins — this package deliberately has none) over\n * exactly the three shapes pure JSON data can take.\n *\n * The asymmetry is the point: `a` is the CALLER's object, which may contain\n * anything JavaScript allows, while `b` is always the output of\n * `JSON.parse` — pure data. So every case where `a` is something JSON cannot\n * represent (a `Date`, a function, `undefined`, `NaN`, a symbol, a getter\n * that answers differently the second time, an object whose `toJSON` rewrote\n * it) shows up here as a shape or value mismatch against `b`, and is\n * rejected. `NaN !== NaN` falls out of strict equality for free, which is\n * exactly what we want: `NaN` serializes to `null`, so it is not\n * representable and must not pass.\n *\n * The one case structural comparison alone cannot see — an object whose data\n * lives somewhere other than its own enumerable string keys, e.g. a\n * populated `Map` — gets its own explicit rejection in the object branch\n * below.\n */\nfunction isSameJsonData(a: unknown, b: unknown): boolean {\n if (a === null || b === null) return a === b;\n\n const typeOfA = typeof a;\n if (typeOfA !== typeof b) return false;\n\n if (typeOfA !== 'object') {\n // string | number | boolean. Anything else (function, symbol, bigint,\n // undefined) can never equal a JSON.parse output, and `NaN === NaN` is\n // false, so this single comparison covers every primitive case.\n return a === b;\n }\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n\n if (aIsArray) {\n const arrayA = a as unknown[];\n const arrayB = b as unknown[];\n if (arrayA.length !== arrayB.length) return false;\n for (let index = 0; index < arrayA.length; index += 1) {\n if (!isSameJsonData(arrayA[index], arrayB[index])) return false;\n }\n return true;\n }\n\n const objectA = a as Record<string, unknown>;\n const objectB = b as Record<string, unknown>;\n const keysA = Object.keys(objectA); // own enumerable string keys\n const keysB = Object.keys(objectB);\n\n // An object whose data does NOT live in its own enumerable string keys is\n // invisible to both `JSON.stringify` and the key comparison below — a\n // populated `Map`/`Set` serializes to `{}` and would otherwise compare\n // EQUAL to that `{}`, delivering an empty document as the task's truthful\n // structured result. That is the same silent-wrong-output class the whole\n // plain-data contract exists to stop, so a container-shaped value with no\n // own enumerable string keys and a non-plain prototype is rejected here.\n // Applied at every object node (this function recurses), so a nested\n // `Map`/`Set`/exotic instance dies exactly like a top-level one.\n //\n // The boundary this deliberately draws: a class instance WITH own\n // enumerable fields still passes, because its data really is in those\n // fields and survives the round trip intact. A class whose values come\n // from PROTOTYPE-level getters does not — those are invisible to JSON, so\n // such an instance is not plain JSON data and is outside this contract by\n // definition (docs/protocol.md §7.2). `Object.create(null)` is explicitly\n // fine: a null prototype is plain data, just without `Object.prototype`.\n if (keysA.length === 0) {\n const prototypeA: unknown = Object.getPrototypeOf(objectA);\n if (prototypeA !== Object.prototype && prototypeA !== null) return false;\n }\n\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) return false;\n if (!isSameJsonData(objectA[key], objectB[key])) return false;\n }\n return true;\n}\n\n/**\n * Container nesting depth of pure JSON data (a `JSON.parse` output), computed\n * iteratively so no input can exhaust the call stack. A scalar is depth 0,\n * `{}` and `[]` are depth 1. Stops as soon as `limit` is exceeded.\n */\nexport function jsonDepthExceeds(value: unknown, limit: number): boolean {\n const stack: { readonly node: unknown; readonly depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (node === null || typeof node !== 'object') continue;\n const next = depth + 1;\n if (next > limit) return true;\n const children = Array.isArray(node) ? node : Object.values(node as Record<string, unknown>);\n for (const child of children) stack.push({ node: child, depth: next });\n }\n return false;\n}\n\n/**\n * Canonicalize `value` as plain JSON data within `maxBytes` canonical UTF-8\n * bytes:\n *\n * 1. `JSON.stringify` must succeed and not return `undefined`.\n * 2. Its UTF-8 byte length must be at most `maxBytes`.\n * 3. `JSON.parse` that string: the CANONICAL SNAPSHOT (pure data).\n * 4. With `maxDepth`, the snapshot's container nesting must be at most\n * `maxDepth`. This runs before step 5, so the recursive comparison\n * below is bounded by it.\n * 5. The original must be structurally equal to the snapshot\n * (`isSameJsonData`).\n *\n * On success a sender uses `canonical`, never the original reference.\n */\nexport function canonicalizePlainJson(value: unknown, maxBytes: number): PlainJsonCheck;\nexport function canonicalizePlainJson(value: unknown, maxBytes: number, maxDepth: number): BoundedPlainJsonCheck;\nexport function canonicalizePlainJson(value: unknown, maxBytes: number, maxDepth?: number): BoundedPlainJsonCheck {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return { ok: false, reason: 'not-serializable' };\n }\n if (json === undefined) return { ok: false, reason: 'not-serializable' };\n\n const bytes = new TextEncoder().encode(json).length;\n if (bytes > maxBytes) return { ok: false, reason: 'over-cap', bytes };\n\n const canonical: unknown = JSON.parse(json);\n if (maxDepth !== undefined && jsonDepthExceeds(canonical, maxDepth)) return { ok: false, reason: 'too-deep', bytes };\n if (!isSameJsonData(value, canonical)) return { ok: false, reason: 'not-plain-json' };\n\n return { ok: true, bytes, canonical };\n}\n","/**\n * Result-document schema subset (wire v3, docs/protocol.md §7.2).\n *\n * A `terminalProjection.mode: 'result-document'` offer freezes one JSON\n * Schema for the task's structured outcome. This module owns the two checks\n * every party applies to it:\n *\n * - {@link checkResultSchema}: the admission guard. It decides whether a\n * candidate schema is inside the subset this SDK accepts. It is ours, and\n * it is the only admission authority: the instance validator below never\n * sees a schema the guard did not admit.\n * - {@link validateResultOutcome}: re-runs the guard, bounds the outcome,\n * then validates the outcome against the admitted schema with\n * `@cfworker/json-schema` (draft 2020-12, interpreted; no code generation).\n *\n * The subset (PRD §8.3): `type`, `properties`, `required`,\n * `additionalProperties` (only `false`), `items`, `enum`, `const`, `oneOf`,\n * `minLength`, `maxLength`, `minItems`, `maxItems`, `minimum`, `maximum`,\n * `description`. Every other keyword is refused, so `$ref`, `pattern`,\n * `format` and the other draft 2020-12 vocabularies are unreachable in the\n * library. The root must be `type: 'object'`; root `oneOf` is allowed.\n *\n * Zod-free and free of node builtins.\n */\nimport { Validator, type OutputUnit } from '@cfworker/json-schema';\nimport { canonicalizePlainJson, type BoundedPlainJsonCheck } from './plain-json';\n\n/** Maximum canonical JSON UTF-8 size of a result-document schema. */\nexport const RESULT_SCHEMA_MAX_BYTES = 16_384;\n/** Maximum canonical JSON UTF-8 size of a submitted outcome document. */\nexport const RESULT_OUTCOME_MAX_BYTES = 65_536;\n/**\n * Maximum subschema nesting below the root (each `properties` member, `items`\n * and `oneOf` branch is one level). With the 16 KiB cap this bounds how much\n * schema structure one validation walks.\n */\nexport const RESULT_SCHEMA_MAX_DEPTH = 32;\n/**\n * Maximum JSON container nesting of a schema or outcome document, checked\n * iteratively before any recursive routine runs on it.\n */\nexport const RESULT_JSON_MAX_DEPTH = 128;\n/** Maximum number of issues one failed check reports. */\nexport const RESULT_ISSUES_MAX_COUNT = 20;\n/** Maximum UTF-8 size of the reported issue list, as JSON. */\nexport const RESULT_ISSUES_MAX_BYTES = 4_096;\n/**\n * Pointer, keyword and message strings in an issue are cut to this many UTF-16\n * units. Even fully `\\u`-escaped, one issue then fits the byte cap, so a\n * failure always reports at least one issue.\n */\nconst ISSUE_STRING_MAX_LENGTH = 128;\n\nexport const RESULT_SCHEMA_KEYWORDS = Object.freeze([\n 'type',\n 'properties',\n 'required',\n 'additionalProperties',\n 'items',\n 'enum',\n 'const',\n 'oneOf',\n 'minLength',\n 'maxLength',\n 'minItems',\n 'maxItems',\n 'minimum',\n 'maximum',\n 'description',\n] as const);\nexport type ResultSchemaKeyword = (typeof RESULT_SCHEMA_KEYWORDS)[number];\n\nexport const RESULT_SCHEMA_INSTANCE_TYPES = Object.freeze([\n 'object',\n 'array',\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'null',\n] as const);\nexport type ResultSchemaInstanceType = (typeof RESULT_SCHEMA_INSTANCE_TYPES)[number];\n\n/** A schema inside the admitted subset. Only {@link checkResultSchema} proves a value is one. */\nexport interface ResultSchema {\n readonly type?: ResultSchemaInstanceType | readonly ResultSchemaInstanceType[];\n readonly properties?: { readonly [name: string]: ResultSchema };\n readonly required?: readonly string[];\n readonly additionalProperties?: false;\n readonly items?: ResultSchema;\n readonly enum?: readonly unknown[];\n readonly const?: unknown;\n readonly oneOf?: readonly ResultSchema[];\n readonly minLength?: number;\n readonly maxLength?: number;\n readonly minItems?: number;\n readonly maxItems?: number;\n readonly minimum?: number;\n readonly maximum?: number;\n readonly description?: string;\n}\n\n/**\n * One bounded failure detail. `pointer` is an RFC 6901 JSON Pointer into the\n * checked document: the schema for admission issues, the outcome for\n * validation issues (`''` is the document root). `keyword` is the JSON Schema\n * keyword at fault, or a document-level code: `not-serializable`,\n * `not-plain-json`, `over-cap`, `too-deep` (JSON nesting), `schema` (a\n * subschema that is not an object) or `depth` (subschema nesting).\n */\nexport interface ResultIssue {\n readonly pointer: string;\n readonly keyword: string;\n readonly message: string;\n}\n\n/** Document-level failure shared by the schema and outcome checks. */\nexport type ResultDocumentFailureReason = 'not-serializable' | 'not-plain-json' | 'over-cap' | 'too-deep';\n\ninterface ResultFailure<Reason extends string> {\n readonly ok: false;\n readonly reason: Reason;\n /** Canonical UTF-8 size, when it was measured. */\n readonly bytes?: number;\n /** At least one issue; at most {@link RESULT_ISSUES_MAX_COUNT} and {@link RESULT_ISSUES_MAX_BYTES}. */\n readonly issues: readonly ResultIssue[];\n /** True when issues were dropped to respect the caps. */\n readonly truncated: boolean;\n}\n\nexport type ResultSchemaCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: ResultSchema }\n | ResultFailure<ResultDocumentFailureReason | 'not-subset'>;\n\nexport type ResultOutcomeCheck =\n | { readonly ok: true; readonly bytes: number; readonly canonical: unknown }\n | ResultFailure<'schema-not-admitted' | ResultDocumentFailureReason | 'schema-mismatch'>;\n\nconst KEYWORDS = new Set<string>(RESULT_SCHEMA_KEYWORDS);\nconst INSTANCE_TYPES = new Set<string>(RESULT_SCHEMA_INSTANCE_TYPES);\nconst encoder = new TextEncoder();\n\nfunction cut(value: string): string {\n return value.length <= ISSUE_STRING_MAX_LENGTH ? value : `${value.slice(0, ISSUE_STRING_MAX_LENGTH - 1)}…`;\n}\n\n/** Collects issues under the count and byte caps. */\nclass IssueSink {\n readonly issues: ResultIssue[] = [];\n truncated = false;\n private bytes = 2; // \"[]\"\n\n add(pointer: string, keyword: string, message: string): void {\n const issue: ResultIssue = { pointer: cut(pointer), keyword: cut(keyword), message: cut(message) };\n const size = encoder.encode(JSON.stringify(issue)).length + (this.issues.length === 0 ? 0 : 1);\n if (this.issues.length >= RESULT_ISSUES_MAX_COUNT || this.bytes + size > RESULT_ISSUES_MAX_BYTES) {\n this.truncated = true;\n return;\n }\n this.issues.push(issue);\n this.bytes += size;\n }\n\n get empty(): boolean {\n return this.issues.length === 0 && !this.truncated;\n }\n}\n\nfunction pointerTo(base: string, token: string | number): string {\n return `${base}/${String(token).replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isNonNegativeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\n/**\n * True when any string or property name in pure JSON data is not well-formed\n * Unicode. A lone surrogate has no UTF-8 encoding, so the measured canonical\n * size would not describe it, and the library cannot build a pointer to it.\n * Iterative; the caller has already bounded the nesting depth.\n */\nfunction hasLoneSurrogate(value: unknown): boolean {\n const stack: unknown[] = [value];\n while (stack.length > 0) {\n const node = stack.pop();\n if (typeof node === 'string') {\n if (LONE_SURROGATE.test(node)) return true;\n } else if (Array.isArray(node)) {\n for (const member of node) stack.push(member);\n } else if (node !== null && typeof node === 'object') {\n for (const [key, member] of Object.entries(node)) {\n if (LONE_SURROGATE.test(key)) return true;\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/** Canonical plain JSON within the byte and depth caps, in well-formed Unicode. */\nfunction canonicalDocument(value: unknown, maxBytes: number): BoundedPlainJsonCheck {\n const check = canonicalizePlainJson(value, maxBytes, RESULT_JSON_MAX_DEPTH);\n if (check.ok && hasLoneSurrogate(check.canonical)) return { ok: false, reason: 'not-plain-json' };\n return check;\n}\n\nfunction documentFailure(\n check: Exclude<BoundedPlainJsonCheck, { ok: true }>,\n what: string,\n maxBytes: number,\n): ResultFailure<ResultDocumentFailureReason> {\n const sink = new IssueSink();\n switch (check.reason) {\n case 'not-serializable':\n sink.add('', check.reason, `${what} is not JSON-serializable`);\n return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };\n case 'not-plain-json':\n sink.add('', check.reason, `${what} is not plain JSON data in well-formed Unicode`);\n return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };\n case 'over-cap':\n sink.add('', check.reason, `${what} is ${check.bytes} bytes as canonical JSON (UTF-8); the cap is ${maxBytes}`);\n return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };\n case 'too-deep':\n sink.add('', check.reason, `${what} nests JSON containers deeper than ${RESULT_JSON_MAX_DEPTH}`);\n return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };\n }\n}\n\n/** Walks one subschema of an already-canonical (pure JSON) document. */\nfunction checkSubschema(node: unknown, pointer: string, depth: number, sink: IssueSink, requireObjectRoot = true): void {\n if (!isObject(node)) {\n sink.add(pointer, 'schema', 'a subschema must be a JSON object');\n return;\n }\n if (depth > RESULT_SCHEMA_MAX_DEPTH) {\n sink.add(pointer, 'depth', `subschemas nest deeper than ${RESULT_SCHEMA_MAX_DEPTH} levels`);\n return;\n }\n for (const key of Object.keys(node)) {\n if (!KEYWORDS.has(key)) sink.add(pointerTo(pointer, key), key, 'keyword is outside the result schema subset');\n }\n if (requireObjectRoot && depth === 0 && node.type !== 'object') {\n sink.add(pointerTo(pointer, 'type'), 'type', \"the root schema must declare type: 'object'\");\n }\n\n if (Object.hasOwn(node, 'type')) {\n const type = node.type;\n const valid = typeof type === 'string'\n ? INSTANCE_TYPES.has(type)\n : Array.isArray(type) && type.length > 0\n && type.every((member) => typeof member === 'string' && INSTANCE_TYPES.has(member))\n && new Set(type).size === type.length;\n if (!valid) sink.add(pointerTo(pointer, 'type'), 'type', 'must be a JSON type name or a non-empty array of unique type names');\n }\n if (Object.hasOwn(node, 'properties')) {\n const properties = node.properties;\n const at = pointerTo(pointer, 'properties');\n if (!isObject(properties)) sink.add(at, 'properties', 'must be an object of subschemas');\n else for (const [name, subschema] of Object.entries(properties)) checkSubschema(subschema, pointerTo(at, name), depth + 1, sink);\n }\n if (Object.hasOwn(node, 'required')) {\n const required = node.required;\n if (!Array.isArray(required) || !required.every((name) => typeof name === 'string') || new Set(required).size !== required.length) {\n sink.add(pointerTo(pointer, 'required'), 'required', 'must be an array of unique property names');\n }\n }\n if (Object.hasOwn(node, 'additionalProperties') && node.additionalProperties !== false) {\n sink.add(pointerTo(pointer, 'additionalProperties'), 'additionalProperties', 'only additionalProperties: false is allowed');\n }\n if (Object.hasOwn(node, 'items')) {\n if (!isObject(node.items)) sink.add(pointerTo(pointer, 'items'), 'items', 'must be one subschema object');\n else checkSubschema(node.items, pointerTo(pointer, 'items'), depth + 1, sink);\n }\n if (Object.hasOwn(node, 'enum') && (!Array.isArray(node.enum) || node.enum.length === 0)) {\n sink.add(pointerTo(pointer, 'enum'), 'enum', 'must be a non-empty array');\n }\n if (Object.hasOwn(node, 'oneOf')) {\n const oneOf = node.oneOf;\n const at = pointerTo(pointer, 'oneOf');\n if (!Array.isArray(oneOf) || oneOf.length === 0) sink.add(at, 'oneOf', 'must be a non-empty array of subschemas');\n else oneOf.forEach((subschema, index) => checkSubschema(subschema, pointerTo(at, index), depth + 1, sink));\n }\n for (const keyword of ['minLength', 'maxLength', 'minItems', 'maxItems'] as const) {\n if (Object.hasOwn(node, keyword) && !isNonNegativeInteger(node[keyword])) {\n sink.add(pointerTo(pointer, keyword), keyword, 'must be a non-negative integer');\n }\n }\n for (const keyword of ['minimum', 'maximum'] as const) {\n if (Object.hasOwn(node, keyword) && typeof node[keyword] !== 'number') {\n sink.add(pointerTo(pointer, keyword), keyword, 'must be a number');\n }\n }\n if (Object.hasOwn(node, 'description') && typeof node.description !== 'string') {\n sink.add(pointerTo(pointer, 'description'), 'description', 'must be a string');\n }\n}\n\n/**\n * The admission guard for a result-document schema. Accepts only plain JSON\n * data of at most {@link RESULT_SCHEMA_MAX_BYTES} canonical UTF-8 bytes that\n * lies inside the subset (module comment). On success, `canonical` is the\n * snapshot every party freezes and validates against.\n */\nexport function checkResultSchema(schema: unknown): ResultSchemaCheck {\n const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);\n if (!document.ok) return documentFailure(document, 'the result schema', RESULT_SCHEMA_MAX_BYTES);\n const sink = new IssueSink();\n checkSubschema(document.canonical, '', 0, sink);\n if (!sink.empty) return { ok: false, reason: 'not-subset', bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };\n return { ok: true, bytes: document.bytes, canonical: document.canonical as ResultSchema };\n}\n\n/**\n * Deep copy of pure JSON data with null-prototype objects. The library tests\n * property presence with `in`, so a prototype would make `required:\n * ['constructor']` pass on `{}`; a null prototype makes presence own-only.\n */\nfunction withoutPrototypes(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (Array.isArray(value)) return value.map(withoutPrototypes);\n const copy = Object.create(null) as Record<string, unknown>;\n for (const [key, member] of Object.entries(value)) {\n Object.defineProperty(copy, key, { value: withoutPrototypes(member), enumerable: true, writable: true, configurable: true });\n }\n return copy;\n}\n\n/** `#/a~1b/0` (the library's URI-encoded fragment) to the RFC 6901 pointer `/a~1b/0`. */\nfunction fragmentToPointer(location: string): string {\n return decodeURI(location.startsWith('#') ? location.slice(1) : location);\n}\n\n/**\n * Validate one outcome document against a result schema. The guard\n * ({@link checkResultSchema}) always runs first; a schema it refuses is\n * `schema-not-admitted` and never reaches the library. The outcome must be\n * plain JSON data of at most {@link RESULT_OUTCOME_MAX_BYTES} canonical UTF-8\n * bytes, checked before validation. On success, `canonical` is the snapshot\n * a sender stages and puts on the wire.\n */\nexport function validateResultOutcome(schema: unknown, outcome: unknown): ResultOutcomeCheck {\n const admitted = checkResultSchema(schema);\n if (!admitted.ok) {\n return { ok: false, reason: 'schema-not-admitted', bytes: admitted.bytes, issues: admitted.issues, truncated: admitted.truncated };\n }\n const document = canonicalDocument(outcome, RESULT_OUTCOME_MAX_BYTES);\n if (!document.ok) return documentFailure(document, 'the outcome', RESULT_OUTCOME_MAX_BYTES);\n\n // Short-circuit: each level stops at its first failure, so the error list\n // follows one failing path instead of growing with every failing pair.\n const validator = new Validator(withoutPrototypes(admitted.canonical) as Record<string, unknown>, '2020-12', true);\n const result = validator.validate(withoutPrototypes(document.canonical));\n if (result.valid) return { ok: true, bytes: document.bytes, canonical: document.canonical };\n\n const sink = new IssueSink();\n for (const unit of result.errors as readonly OutputUnit[]) sink.add(fragmentToPointer(unit.instanceLocation), unit.keyword, unit.error);\n return { ok: false, reason: 'schema-mismatch', bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };\n}\n\nconst MAX_BYTES_PER_CODE_POINT = 6;\n/**\n * Longest JSON.stringify of a finite double: 25, e.g. \"-0.0000012345678901234567\"\n * (fixed notation down to 1e-6 with 17 significant digits and a sign). Exponent\n * forms are at most 24 (\"-1.7976931348623157e+308\").\n */\nconst MAX_NUMBER_BYTES = 25;\n/**\n * Longest JSON.stringify of an integer-valued double: 22 in fixed notation\n * (\"-999999999999999900000\", |x| < 1e21) and 24 in exponent notation.\n */\nconst MAX_INTEGER_BYTES = 24;\n/** Below this magnitude JSON.stringify writes an integer in plain decimal digits. */\nconst DECIMAL_LIMIT = 1e21;\nconst enc = new TextEncoder();\nconst size = (v: unknown) => enc.encode(JSON.stringify(v)).length;\n\ntype Node = ResultSchema;\n\nfunction typeBound(node: Node, type: string): number | null {\n switch (type) {\n case 'null': return 4;\n case 'boolean': return 5;\n case 'integer': {\n // Tighten only when both ends are finite and below 1e21 in magnitude:\n // then every integer in range is plain decimal and its length grows with |x|.\n const lo = typeof node.minimum === 'number' ? Math.ceil(node.minimum) : undefined;\n const hi = typeof node.maximum === 'number' ? Math.floor(node.maximum) : undefined;\n if (lo === undefined || hi === undefined || !(Math.abs(lo) < DECIMAL_LIMIT) || !(Math.abs(hi) < DECIMAL_LIMIT)) return MAX_INTEGER_BYTES;\n return Math.min(MAX_INTEGER_BYTES, Math.max(String(lo).length, String(hi).length));\n }\n case 'number':\n return MAX_NUMBER_BYTES;\n case 'string':\n return typeof node.maxLength === 'number' ? 2 + MAX_BYTES_PER_CODE_POINT * node.maxLength : null;\n case 'array': {\n if (node.maxItems === 0) return 2;\n if (typeof node.maxItems !== 'number' || node.items === undefined) return null;\n const item = outcomeBound(node.items);\n return item === null ? null : 2 + node.maxItems * item + Math.max(0, node.maxItems - 1);\n }\n case 'object': {\n if (node.additionalProperties !== false) return null;\n const entries = Object.entries(node.properties ?? {});\n let total = 2 + Math.max(0, entries.length - 1);\n for (const [name, sub] of entries) {\n const b = outcomeBound(sub);\n if (b === null) return null;\n total += size(name) + 1 + b;\n }\n return total;\n }\n default: return null;\n }\n}\n\n/** Conservative upper bound in canonical UTF-8 bytes, or null when no finite bound follows from the schema. */\nfunction outcomeBound(schema: ResultSchema): number | null {\n const node = schema as Node;\n const bounds: number[] = [];\n if (Object.hasOwn(node, 'const')) bounds.push(size(node.const));\n if (Array.isArray(node.enum)) bounds.push(Math.max(...node.enum.map(size)));\n if (Array.isArray(node.oneOf)) {\n const branches = node.oneOf.map(outcomeBound);\n if (branches.every((b): b is number => b !== null)) bounds.push(Math.max(...branches));\n }\n if (node.type !== undefined) {\n const types = Array.isArray(node.type) ? node.type : [node.type];\n const each = types.map(t => typeBound(node, t));\n if (each.every((b): b is number => b !== null)) bounds.push(Math.max(...each));\n }\n return bounds.length === 0 ? null : Math.min(...bounds);\n}\n\n/**\n * Conservative canonical UTF-8 bound, or null for an invalid or unbounded schema.\n * Strings cost at most 6 bytes per code point. Number costs 25; integer costs\n * 24, tightened only when both ends have magnitude below 1e21. A bound need\n * not be attainable when constraints intersect or oneOf branches overlap.\n */\nexport function resultOutcomeMaxBytes(schema: ResultSchema): number | null {\n // Inspect data descriptors before canonicalization can invoke a callback.\n const pending: unknown[] = [schema];\n const seen = new Set<object>();\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value === 'function') return null;\n if (value === null || typeof value !== 'object' || seen.has(value)) continue;\n seen.add(value);\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && prototype !== Array.prototype) return null;\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {\n if (name === 'toJSON' && (!Object.hasOwn(descriptor, 'value') || typeof descriptor.value === 'function')) return null;\n if (!descriptor.enumerable) continue;\n if (!Object.hasOwn(descriptor, 'value')) return null;\n pending.push(descriptor.value);\n }\n }\n const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);\n if (!document.ok) return null;\n const sink = new IssueSink();\n // A fragment can be any instance type, unlike a result-document root.\n checkSubschema(document.canonical, '', 0, sink, false);\n if (!sink.empty) return null;\n return outcomeBound(document.canonical as ResultSchema);\n}\n","import { z } from 'zod';\nimport { checkResultSchema, type ResultSchema } from './result-schema';\n\nexport const TerminalProjectionContractSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, 'terminal projection contracts must be opaque lowercase ids');\n\n/**\n * The frozen outcome schema of a result-document offer (wire v3). The value\n * is kept exactly as sent; {@link checkResultSchema} decides admission, so\n * every decode (Host submit, server/cloud parse, daemon admission) applies\n * the one subset guard and reports its capped issues.\n */\nexport const ResultDocumentSchemaSchema = z.custom<ResultSchema>().superRefine((value, ctx) => {\n const check = checkResultSchema(value);\n if (check.ok) return;\n for (const issue of check.issues) {\n ctx.addIssue({\n code: 'custom',\n message: `result schema ${check.reason} at '${issue.pointer}' (${issue.keyword}): ${issue.message}`,\n params: { reason: check.reason, pointer: issue.pointer, keyword: issue.keyword },\n });\n }\n if (check.truncated) {\n ctx.addIssue({ code: 'custom', message: 'result schema issues truncated', params: { reason: check.reason, truncated: true } });\n }\n});\n\n/** Offer-scoped authority: explicit bypass or one required structured result with its frozen schema. */\nexport const TerminalProjectionSelectionSchema = z.discriminatedUnion('mode', [\n z.object({ mode: z.literal('none') }).strict(),\n z.object({\n mode: z.literal('result-document'),\n contract: TerminalProjectionContractSchema,\n schema: ResultDocumentSchemaSchema,\n }).strict(),\n]);\nexport type TerminalProjectionSelection = z.infer<typeof TerminalProjectionSelectionSchema>;\n","import { z } from 'zod';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\nimport { AgentEgressContentHashSchema } from './agent-egress';\n\n/**\n * Remote authenticated runtime input preparation — the wire half of\n * `docs/researches/runtime-input-preparation-contract.md` §19 (channel shape)\n * and the C07 G4 design decision §17 B.\n *\n * This module owns ONLY the leaf shapes. The server -> device payload lives in\n * `messages.ts` beside every other message payload (so the one inline byte\n * bound `MAX_INLINE_BYTES` stays a single module-local authority), and the two\n * authenticated HTTP bodies live in `http-api.ts`.\n *\n * Three structural rules this surface exists to hold:\n *\n * 1. The request carries NO tools, NO tool executors and NO runtime identity.\n * Those are LOCAL observations: only the device can honestly say which MCP\n * toolsets it has, what schemas their servers publish, and which native\n * package closure is installed. A Host that could state them would be\n * stating an identity it cannot verify.\n * 2. The receipt summary discloses identities, digests, sizes, counter\n * evidence and readiness — never D, never P(D), never the snapshot. A\n * digest proves content identity; it is not a disclosure channel and not a\n * bearer token (§10.3.4).\n * 3. Every shape here is `.strict()`. This is control data: an unrecognized\n * field must be REJECTED, not silently stripped, per docs/protocol.md's\n * freeze-rule asymmetry. Adding a field post-freeze is therefore a\n * breaking change.\n */\n\nimport { PREPARED_AGENT_MEMORY_MODES } from './capability-constants';\n\n/** The preparation surface uses the package-wide lowercase `sha256:<hex>` transport form. */\nexport const InputPreparationContentHashSchema = AgentEgressContentHashSchema;\n\n/**\n * Opaque, non-empty, single-line control identifiers (policy revision, profile\n * id, model id, reference, digest, ...). The SDK never interprets these; it\n * only refuses values that could not survive being a key, a log line or a\n * pathname component.\n */\nconst OPAQUE_ID = z\n .string()\n .min(1)\n .max(512)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'control identifiers must not contain control characters');\n\n/** Longer opaque text that is still one line — base URLs, method names, endpoints. */\nconst OPAQUE_TEXT = z\n .string()\n .min(1)\n .max(2048)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'control text must not contain control characters');\n\n/**\n * The operator-assigned limits-policy revision a device must already hold. The\n * SDK compares it for exact equality and never negotiates it: a device whose\n * configured revision differs rejects rather than preparing under a policy the\n * caller believed was in force.\n */\nexport const InputPreparationPolicyRevisionSchema = OPAQUE_ID;\n\n/**\n * Host-owned Profile identity. It rides beside `agentRef` rather than inside\n * it because `AgentRefSchema` is the frozen generic Agent identity shared by\n * every other message, and widening that would be a breaking change to all of\n * them. The device never trusts this value directly — its configured local\n * authority resolver validates it against trusted local Profile records before\n * anything is compiled.\n */\nexport const InputPreparationProfileIdSchema = OPAQUE_ID;\n\n/** Explicit prepared SDK memory selection; never defaulted. */\nexport const PreparedAgentMemoryModeSchema = z.enum(PREPARED_AGENT_MEMORY_MODES);\nexport type PreparedAgentMemoryMode = z.infer<typeof PreparedAgentMemoryModeSchema>;\n\n\n// ---------------------------------------------------------------------------\n// Source / selection\n// ---------------------------------------------------------------------------\n\n/**\n * The canonical Host source snapshot this input was assembled from. Both\n * values are Host authority carried verbatim so the receipt binds the exact\n * revision/digest a later consumer must re-present. The SDK interprets\n * neither.\n */\nexport const InputPreparationSourceSchema = z\n .object({ revision: OPAQUE_ID, digest: OPAQUE_ID })\n .strict();\nexport type InputPreparationSource = z.infer<typeof InputPreparationSourceSchema>;\n\nexport const InputPreparationModelCostSchema = z\n .object({\n input: z.number().finite(),\n output: z.number().finite(),\n cacheRead: z.number().finite(),\n cacheWrite: z.number().finite(),\n })\n .strict();\n\n/**\n * One provider-side effort token, or `null` where the model supports no such\n * level.\n *\n * This shape and the `compat` shape below are RESTATED from the device-local\n * authority (`packages/keys/src/pi-model-config.ts`'s `PiModelConfigSchema`)\n * rather than imported: the release graph\n * (`scripts/release/check-package-graph.mjs`) keeps `@byok-sdk/keys` and the\n * dispatch packages disjoint, exactly as `provider-profile.ts`'s\n * `PROVIDER_PROFILE_REF_PATTERN` is restated for the wire. The two definitions\n * are pinned equal by a test that can see both\n * (`packages/client/src/__tests__/input-preparation-model-parity.test.ts`), so\n * a drift is a failing check rather than a silently narrower wire.\n */\nconst THINKING_EFFORT = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-zA-Z0-9_-]+$/u)\n .nullable();\n\n/**\n * The complete level -> effort mapping the launched model declares. All seven\n * keys are required and no other key is admitted: a partial map would be a map\n * whose missing levels someone downstream had to invent.\n */\nconst InputPreparationThinkingLevelMapSchema = z\n .object({\n off: THINKING_EFFORT,\n minimal: THINKING_EFFORT,\n low: THINKING_EFFORT,\n medium: THINKING_EFFORT,\n high: THINKING_EFFORT,\n xhigh: THINKING_EFFORT,\n max: THINKING_EFFORT,\n })\n .strict();\n\n/**\n * The declared request-body compatibility flags of the launched model.\n *\n * Every member is optional and NOTHING here is defaulted: an absent flag means\n * the configuration declared none, which is a different fact from declaring\n * `false`, and the native compiler owns what an absent flag does.\n */\nconst InputPreparationModelCompatSchema = z\n .object({\n supportsStore: z.boolean().optional(),\n supportsDeveloperRole: z.boolean().optional(),\n supportsReasoningEffort: z.boolean().optional(),\n supportsUsageInStreaming: z.boolean().optional(),\n maxTokensField: z.enum(['max_completion_tokens', 'max_tokens']).optional(),\n thinkingFormat: z\n .enum([\n 'openai',\n 'openrouter',\n 'deepseek',\n 'together',\n 'baseten',\n 'zai',\n 'qwen',\n 'chat-template',\n 'qwen-chat-template',\n 'string-thinking',\n 'ant-ling',\n ])\n .optional(),\n zaiToolStream: z.boolean().optional(),\n })\n .strict();\n\n/**\n * The exact model identity the request compiles for.\n *\n * `api` is a single literal, not an open enum: `openai-completions` is the one\n * API the frozen B-P1 native validator admits, and widening it is a\n * registration, not a parser relaxation.\n *\n * `thinkingLevelMap` and `compat` are the two body-affecting declarations a\n * locally configured provider profile projects into the model entry the runtime\n * is launched with. They are OPTIONAL because a model configuration may declare\n * neither, and absent stays absent on every carrier: nothing here defaults,\n * coerces or infers one, since a preparation whose model gained a field on the\n * way through would no longer equal the session model it was counted for.\n */\nexport const InputPreparationModelSchema = z\n .object({\n id: OPAQUE_ID,\n name: OPAQUE_ID,\n api: z.literal('openai-completions'),\n provider: OPAQUE_ID,\n baseUrl: OPAQUE_TEXT,\n reasoning: z.boolean(),\n input: z.array(z.enum(['text', 'image'])).min(1).max(8),\n cost: InputPreparationModelCostSchema,\n contextWindow: z.number().int().positive(),\n maxTokens: z.number().int().positive(),\n thinkingLevelMap: InputPreparationThinkingLevelMapSchema.optional(),\n compat: InputPreparationModelCompatSchema.optional(),\n })\n .strict();\nexport type InputPreparationModel = z.infer<typeof InputPreparationModelSchema>;\n\n/**\n * Body-affecting options only. Transport options are deliberately not on this wire.\n *\n * `toolChoice` admits `auto` and `none` and nothing else: the native prepared\n * boundary compiles through the simple stream path, which cannot express\n * `required`, so a Host stating it would be stating an option no compiler on\n * the other side can produce. It is refused HERE, by the schema, rather than\n * surviving to a native refusal nobody can read.\n *\n * `reasoningEffort` names a requested thinking level. The native compiler maps\n * it through the launched model's own level map and clamps it exactly as the\n * live session does, so the effort token that reaches the body is the model's,\n * never this value verbatim.\n */\nexport const InputPreparationOptionsSchema = z\n .object({\n cacheRetention: z.enum(['none', 'short', 'long']),\n maxTokens: z.number().int().positive(),\n temperature: z.number().finite().optional(),\n toolChoice: z.enum(['auto', 'none']).optional(),\n reasoningEffort: z.enum(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']).optional(),\n })\n .strict();\nexport type InputPreparationOptions = z.infer<typeof InputPreparationOptionsSchema>;\n\nexport const InputPreparationSelectionSchema = z\n .object({ model: InputPreparationModelSchema, options: InputPreparationOptionsSchema })\n .strict();\nexport type InputPreparationSelection = z.infer<typeof InputPreparationSelectionSchema>;\n\n// ---------------------------------------------------------------------------\n// Context document — the Host-authorized half of the compiled snapshot\n// ---------------------------------------------------------------------------\n\n/** Complete Host-authored prompt. No Pi renderer or device-local input is consulted. */\nexport const InputPreparationPromptSnapshotSchema = z.object({ systemPrompt: z.string() }).strict();\n\n/**\n * One model-visible user message. Text-only: multimodal content and any extra\n * field are not inferred, they reject.\n */\nexport const InputPreparationUserMessageSchema = z\n .object({\n role: z.literal('user'),\n content: z.string(),\n timestamp: z.number().int(),\n })\n .strict();\n\n/**\n * One host-canonical assistant text message.\n *\n * A different fact from a provider-generated assistant turn: the host asserts\n * this text was already said, and nothing generated it here. It carries no\n * `api`, `provider`, `model`, `usage` or `stopReason`, and `.strict()` is what\n * keeps one from being fabricated on the way in — an assistant message with\n * provenance fields, or without the `origin` discriminant, is a claim this\n * surface cannot check, so it rejects rather than being narrowed to one it can.\n */\nexport const InputPreparationHostCanonicalAssistantMessageSchema = z\n .object({\n role: z.literal('assistant'),\n origin: z.literal('host_canonical'),\n content: z.string(),\n timestamp: z.number().int(),\n })\n .strict();\n\n/**\n * The whole support set a caller may state: text-only user history,\n * host-canonical assistant text history, and the current user message.\n *\n * A discriminated union on `role`, so an unsupported kind is refused by name\n * rather than by a shape error on whichever member happened to be tried first.\n * Provider-generated assistant turns, tool-result history and multimodal\n * content are not members and are not inferred; adding one is a registration\n * here AND in the device's hand-written parse, never a relaxation of either.\n */\nexport const InputPreparationMessageSchema = z.discriminatedUnion('role', [\n InputPreparationUserMessageSchema,\n InputPreparationHostCanonicalAssistantMessageSchema,\n]);\nexport type InputPreparationMessage = z.infer<typeof InputPreparationMessageSchema>;\n\n/**\n * What `context.inline` (or the referenced blob) decodes to.\n *\n * Deliberately NOT the whole compiled snapshot: `tools` is absent because the\n * device adds it from its own MCP observation. A Host that could send `tools`\n * could claim a toolset the device does not have.\n */\nexport const InputPreparationContextDocumentSchema = z\n .object({\n prompt: InputPreparationPromptSnapshotSchema,\n messages: z.array(InputPreparationMessageSchema).max(4096),\n })\n .strict();\nexport type InputPreparationContextDocument = z.infer<typeof InputPreparationContextDocumentSchema>;\n\n// ---------------------------------------------------------------------------\n// Receipt summary — the only thing a completion discloses about the artifact\n// ---------------------------------------------------------------------------\n\n/**\n * Durable lifecycle state of one local preparation record.\n *\n * `prepared` is the one successful terminal state: the artifact is compiled,\n * persisted, and — when the device has an optional counter configured — its\n * counter answered. A device with no counter reaches `prepared` without ever\n * entering `counting`.\n */\nexport const InputPreparationStateSchema = z.enum([\n 'reserved',\n 'counting',\n 'prepared',\n 'cancelled',\n 'failed',\n 'counter_interrupted',\n]);\nexport type InputPreparationState = z.infer<typeof InputPreparationStateSchema>;\n\n/**\n * Why a receipt is not ready. An empty list is the only thing that makes\n * `ready` true.\n *\n * `ready` means the preparation CAN BE CONSUMED — the artifact is intact and\n * unexpired, the native compiler's projection is content-complete, every\n * residual key is ruled by an applicable Host accounting policy, D is text\n * only, and — only when the device has an\n * optional counter configured — that count is provider-authoritative and\n * covered. No count is required: the size evidence is\n * `artifact.requestBytes`, the exact byte length of the frozen D. It is\n * deliberately NOT Host budget admission: the device performs no budget\n * arithmetic, so a ready receipt says the evidence holds, never that the\n * spend fits a window.\n */\nexport const InputPreparationReadinessReasonSchema = z.enum([\n /** The record has not reached `prepared` (it is `reserved` or `counting`). */\n 'not_prepared',\n 'counter_interrupted',\n 'cancelled',\n 'failed',\n 'artifact_expired',\n /** A counter IS present and its authority is not `provider` (a fixture never reaches ready). */\n 'counter_authority_not_production',\n /** A counter IS present and it reported its projection as not covered. */\n 'counter_coverage_incomplete',\n /**\n * D, the frozen provider request, carries a message content part whose\n * `type` is not `text`. The first release admits text-only D; a multimodal\n * part is not sized by `requestBytes` in any way the Host's ruling covers.\n */\n 'request_content_not_text',\n /** The native compiler's projection kind is not `content_complete`. */\n 'projection_unknown',\n /** The artifact carries a residual key the accounting policy does not rule on. */\n 'residual_not_ruled',\n /** The request named no accounting policy. There is no default. */\n 'accounting_policy_missing',\n /** The named policy was ruled for a different runtime, endpoint or model. */\n 'accounting_policy_inapplicable',\n /**\n * The record was prepared against a runtime contract this build no longer\n * speaks: its binding declares a prepared-compiler version other than the one\n * this build prepares and consumes against. The artifact is not re-read\n * through the current contract and is not translated — a projection frozen\n * under another compiler's classification table is evidence about a request\n * this build cannot re-derive.\n */\n 'runtime_contract_superseded',\n]);\nexport type InputPreparationReadinessReason = z.infer<typeof InputPreparationReadinessReasonSchema>;\n\n/**\n * Runtime/compiler identity derived from the VERIFIED installed package\n * closure on the device. A Host never states it and cannot override it.\n */\nexport const InputPreparationRuntimeIdentitySchema = z\n .object({\n packageName: OPAQUE_ID,\n packageVersion: OPAQUE_ID,\n tarballIntegrity: z.string().regex(/^sha512-[A-Za-z0-9+/]+={0,2}$/u),\n provenanceDigest: z.string().regex(/^[0-9a-f]{64}$/u),\n closureDigest: z.string().regex(/^[0-9a-f]{64}$/u),\n upstreamCommit: OPAQUE_ID,\n envelopeFormat: OPAQUE_ID,\n requestFormat: OPAQUE_ID,\n compilerVersion: z.number().int().nonnegative(),\n })\n .strict();\nexport type InputPreparationRuntimeIdentity = z.infer<typeof InputPreparationRuntimeIdentitySchema>;\n\nexport const InputPreparationCounterTargetSchema = z\n .object({ endpoint: OPAQUE_TEXT, modelId: OPAQUE_ID })\n .strict();\n\n/**\n * The Host's ruling about which residual keys of D its accounting already\n * accounts for.\n *\n * Host authority, carried verbatim. The device performs exactly one check\n * against it — APPLICABILITY — and never any budget arithmetic: every residual\n * key the artifact carries must be named here, and the ruling must have been\n * made for this preparation's own runtime identity and endpoint/model. There\n * is no default: a request that names none produces a receipt carrying\n * `accounting_policy_missing`, because \"nobody ruled\" and \"everything is\n * ruled\" are different facts.\n */\nexport const InputPreparationAccountingPolicyRefSchema = z\n .object({\n revision: OPAQUE_ID,\n /** The runtime identity string this ruling was made for. */\n ruledRuntime: OPAQUE_ID,\n /** The endpoint/model this ruling was made for. */\n ruledTarget: InputPreparationCounterTargetSchema,\n /** Every residual key the Host's accounting already accounts for. */\n ruledResidualKeys: z.array(OPAQUE_ID).max(64),\n })\n .strict();\nexport type InputPreparationAccountingPolicyRef = z.infer<typeof InputPreparationAccountingPolicyRefSchema>;\n\n/**\n * What the provider side of a count asserted, and which exact projection it\n * was asserted about.\n *\n * Required, fixture included: a number without the identity of the bytes it\n * was taken over is not evidence. The device compares `projectionDigest`\n * against the artifact's own projection digest and `endpoint`/`modelId`\n * against the counted target, and refuses the count outright on a mismatch.\n *\n * `asserted` is the provider's own answer, stored and never second-guessed —\n * re-deriving a usage number locally is the shadow accounting this surface\n * exists to avoid. It carries no output or whole-request field: the Host holds\n * its own request, and `binding.requestDigest` is the check that ties the two.\n */\nexport const InputPreparationCounterProviderEvidenceSchema = z\n .object({\n projectionDigest: z.string().regex(/^[0-9a-f]{64}$/u, 'a projection digest is lowercase sha-256 hex'),\n endpoint: OPAQUE_TEXT,\n modelId: OPAQUE_ID,\n asserted: z\n .object({\n httpStatus: z.number().int(),\n usageFields: z.record(OPAQUE_ID, z.number().finite()),\n responseDigest: OPAQUE_ID,\n })\n .strict(),\n })\n .strict();\n\n/**\n * Counter evidence exactly as the device's OPTIONAL adapter reported it.\n * Absent when the device has no counter configured, which is a legal, ready-\n * capable state: the size evidence is `artifact.requestBytes`.\n *\n * `authority: 'test_fixture'` is a first-class value, not a debug flag: a\n * fixture result can never produce a ready receipt, which is what keeps an\n * offline suite from ever looking like production accounting evidence.\n */\nexport const InputPreparationCounterEvidenceSchema = z\n .object({\n method: OPAQUE_ID,\n methodVersion: OPAQUE_ID,\n authority: z.enum(['provider', 'test_fixture']),\n value: z.number().int().nonnegative(),\n coverage: z\n .object({ covered: z.boolean(), reason: z.string().max(512).optional() })\n .strict(),\n providerEvidence: InputPreparationCounterProviderEvidenceSchema,\n target: InputPreparationCounterTargetSchema,\n calledAt: z.iso.datetime({ offset: true }),\n completedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\n\n/**\n * What the native compiler proved about ONE top-level key of D that lies\n * outside P(D).\n *\n * These classes describe STRUCTURE and nothing else. No class states, implies\n * or denies that a key influences a provider's token count — that is an\n * external accounting fact the compiler cannot prove — which is exactly why\n * the device re-derives nothing from them and routes the question to the\n * Host's own {@link InputPreparationAccountingPolicyRefSchema}.\n */\nexport const InputPreparationResidualValueClassSchema = z.enum([\n 'constant',\n 'boolean',\n 'bounded_integer',\n 'bounded_number',\n 'finite_number',\n 'closed_enum',\n 'nonempty_string',\n 'object_shape',\n]);\nexport type InputPreparationResidualValueClass = z.infer<typeof InputPreparationResidualValueClassSchema>;\n\nexport const InputPreparationResidualKeySchema = z\n .object({ key: OPAQUE_ID, valueClass: InputPreparationResidualValueClassSchema })\n .strict();\n\n/**\n * What the native compiler proves about P(D), copied verbatim off the envelope.\n *\n * `content_complete` — every context-derived byte of D is byte-identically\n * inside P(D), and every remaining top-level key was classified. `unknown` —\n * the compiler failed closed, claims nothing, and leaves `residual` empty.\n *\n * `digest` is sha-256 over the exact counted-projection bytes. The device\n * recomputes it and refuses the artifact on a mismatch; it never recomputes\n * the KIND, because the classification table belongs to the compiler and a\n * local copy of it would be a shadow parser for the same semantic fact.\n */\nexport const InputPreparationProjectionSchema = z\n .object({\n version: z.literal(3),\n kind: z.enum(['content_complete', 'unknown']),\n digest: z.string().regex(/^[0-9a-f]{64}$/u, 'a projection digest is lowercase sha-256 hex'),\n })\n .strict();\n\n/**\n * Identities, sizes and the native compiler's structural projection contract.\n * Never D, never P(D), never the snapshot.\n *\n * The three tool-surface fields are what make drift between preparation and\n * launch checkable rather than assumed:\n *\n * - `observationDigest` binds everything the device OBSERVED — the projected\n * tools and their executor fingerprints — so a launch whose live\n * observation differs is a different manifest, whatever the schemas say.\n * - `toolBindingDigest` binds only the facts that can be re-derived WITHOUT\n * spawning a server: the toolset definition revisions and the configured\n * argv. It is what a replay of an already-recorded requestId compares\n * against, because re-probing to detect drift would be the second executor\n * fact the idempotency key exists to prevent.\n * - `toolNames` lists the counted model-visible tool names, sorted. A launch\n * that registers a different set can name the tool that appeared or\n * vanished.\n */\nexport const InputPreparationArtifactSummarySchema = z\n .object({\n requestDigest: OPAQUE_ID,\n envelopeDigest: OPAQUE_ID,\n toolManifestDigest: OPAQUE_ID,\n /**\n * The exact UTF-8 byte length of the frozen provider request D, measured\n * by the device's own compiler. The ONE size evidence a receipt carries:\n * the Host rules the budget (`requestBytes + C + max_tokens <= window`)\n * against it. Never a token count and never an estimate.\n */\n requestBytes: z.number().int().nonnegative(),\n projectionBytes: z.number().int().nonnegative(),\n projection: InputPreparationProjectionSchema,\n residual: z.array(InputPreparationResidualKeySchema).max(64),\n observationDigest: OPAQUE_ID,\n toolBindingDigest: OPAQUE_ID,\n toolNames: z.array(OPAQUE_ID),\n })\n .strict();\n\n/** The immutable binding a receipt carries and a later consumer must re-present. */\nexport const InputPreparationBindingSchema = z\n .object({\n terminalProjection: TerminalProjectionSelectionSchema.optional(),\n agentMemory: PreparedAgentMemoryModeSchema,\n scopeId: OPAQUE_ID,\n deviceId: OPAQUE_ID,\n agentRef: OPAQUE_ID,\n profileId: OPAQUE_ID,\n profileRevision: OPAQUE_ID,\n source: InputPreparationSourceSchema,\n target: InputPreparationCounterTargetSchema,\n policyRevision: OPAQUE_ID,\n runtime: InputPreparationRuntimeIdentitySchema,\n requestDigest: OPAQUE_ID,\n /**\n * The Host's accounting ruling this preparation was requested under,\n * copied verbatim. Absent when the request named none — never filled in,\n * and never narrowed to one the device would have chosen.\n */\n accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional(),\n })\n .strict();\n\n/**\n * The exact receipt projection a device reports back.\n *\n * `reference` names the record inside the device-local authenticated scope\n * that created it. It is not a capability: local lookup re-resolves authority\n * on every call and derives the record key from the trusted grant.\n */\nexport const InputPreparationReceiptSummarySchema = z\n .object({\n reference: OPAQUE_ID,\n state: InputPreparationStateSchema,\n binding: InputPreparationBindingSchema,\n artifact: InputPreparationArtifactSummarySchema.optional(),\n counter: InputPreparationCounterEvidenceSchema.optional(),\n ready: z.boolean(),\n readinessReasons: z.array(InputPreparationReadinessReasonSchema).max(16),\n detail: OPAQUE_ID.optional(),\n artifactExpiresAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((value, ctx) => {\n // `ready` is a derived fact, never an independently asserted one. Letting\n // the two disagree on the wire would make a not-ready receipt admissible\n // by simply flipping a boolean.\n if (value.ready !== (value.readinessReasons.length === 0)) {\n ctx.addIssue({\n code: 'custom',\n path: ['ready'],\n message: 'ready must be true exactly when readinessReasons is empty',\n });\n }\n });\nexport type InputPreparationReceiptSummary = z.infer<typeof InputPreparationReceiptSummarySchema>;\n\n// ---------------------------------------------------------------------------\n// Offer binding — what a prepared Execution names on the offer wire\n// ---------------------------------------------------------------------------\n\n/**\n * The device-local reference one receipt answered with\n * ({@link InputPreparationReceiptSummarySchema}'s `reference`).\n *\n * The same opaque identifier, spelled as its own schema so the offer wire and\n * the receipt wire cannot drift into two definitions of one value. It is NOT a\n * capability: the device re-resolves authority on every lookup and derives the\n * record key from its own trusted grant, so presenting another scope's\n * reference finds nothing.\n */\nexport const InputPreparationReferenceSchema = OPAQUE_ID;\n\n/**\n * The preparation a prepared `task.offer` names, re-presented by the Host from\n * the receipt it was given.\n *\n * Nothing here is authority. Every value is COMPARED against the device's own\n * durable record before an Execution is admitted, and a difference declines the\n * offer non-retryably — a Host that could state a binding would be stating what\n * this device counted.\n *\n * `artifactDigest` is optional for one structural reason, not as a compatibility\n * seam: a receipt discloses `artifact` only once there is one\n * ({@link InputPreparationArtifactSummarySchema} is optional on the receipt), so\n * a Host holding a not-yet-prepared receipt has no envelope digest to re-present.\n * When it is present it is compared like everything else.\n */\nexport const InputPreparationOfferBindingSchema = z\n .object({\n reference: InputPreparationReferenceSchema,\n /** `InputPreparationBindingSchema.requestDigest`, as the receipt reported it. */\n requestDigest: OPAQUE_ID,\n /** `InputPreparationArtifactSummarySchema.envelopeDigest`, when the receipt carried one. */\n artifactDigest: OPAQUE_ID.optional(),\n })\n .strict();\nexport type InputPreparationOfferBinding = z.infer<typeof InputPreparationOfferBindingSchema>;\n\n/**\n * Why a device refused to prepare at all. These are the device-owned typed\n * rejections; none of them ever accompanies an artifact.\n *\n * `input_preparation_unconfigured` is the answer from a device that advertised\n * nothing: the whole surface is off there. It is reported rather than thrown so\n * one mis-targeted request cannot freeze the device's mailbox cursor behind it.\n */\nexport const InputPreparationRejectionReasonSchema = z.enum([\n 'input_preparation_unconfigured',\n 'bad_request',\n 'authority_unavailable',\n 'scope_denied',\n 'policy_revision_mismatch',\n 'runtime_identity_unavailable',\n 'unsupported_input',\n 'limit_exceeded',\n 'request_conflict',\n 'not_found',\n 'counter_unavailable',\n 'counter_interrupted',\n 'durable_write_failed',\n 'cancelled',\n 'context_unresolvable',\n 'context_hash_mismatch',\n 'toolsets_unobservable',\n 'deadline_elapsed',\n /**\n * A repeat of an already-recorded `requestId` arrived after the facts its\n * executor fingerprints were frozen against changed — a toolset definition\n * revision or a configured server argv. The recorded receipt is not re-derived and no\n * server is re-probed; the repeat is refused so the caller mints a new\n * preparation instead of silently receiving one bound to stale evidence.\n */\n 'observation_drift',\n /**\n * The device compiled the input, then found that the `prompt_prepared` frame\n * the runtime would have to be handed exceeds the single-frame byte cap that\n * runtime enforces. The bound belongs to the runtime, not to the operator's\n * retention policy, so it is decided first and nothing is retained: a\n * preparation that could never be delivered is not a smaller preparation.\n */\n 'rpc_frame_too_large',\n /**\n * The device's input-preparation lane is off because its durable record log\n * holds a record from an older record schema version. The rest of the\n * device runs; this lane refuses until an operator archives that log. No\n * record is migrated, read forward or deleted.\n */\n 'input_preparation_record_log_unsupported',\n]);\nexport type InputPreparationRejectionReason = z.infer<typeof InputPreparationRejectionReasonSchema>;\n","import { z } from 'zod';\nimport { BlobRefSchema } from './blob';\nimport { TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH } from './constants';\n\n/**\n * Maximum UTF-16 length of {@link AgentEventSpillSchema}'s `unstoredReason`.\n * The reason is a bounded diagnostic string, not a place to inline the\n * content that failed to store: the whole point of a spill descriptor is\n * that the event stays under the daemon's inline-event cap even when the\n * blob upload failed.\n */\nexport const AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH = 512;\n\n/**\n * Additive descriptor attached to a `tool_use` / `tool_result` event whose\n * `input` / `output` was too large to travel inline and was therefore\n * REPLACED, at the daemon's ingestion boundary, by a bounded head/tail\n * preview (`{ preview: { head, tail } }`). See\n * `packages/client/src/daemon/event-spill.ts` for the producer and\n * `DaemonConfig.maxInlineEventBytes` for the cap.\n *\n * Presence of this field is the ONLY signal that the inline field is a\n * projection rather than the whole value — a consumer that reads\n * `tool_result.output` (or `tool_use.input`) without checking `spill` is\n * reading a preview and calling it the result.\n *\n * Exactly one of `blob` / `unstoredReason` is present, and the union is\n * closed on purpose:\n *\n * - `blob` — the full `JSON.stringify(<field>)` bytes are readable from the\n * blob plane (protocol §7) under that `BlobRef`; `contentHash` is the\n * sha256 of exactly those bytes, so a consumer can verify what it read\n * back is what was omitted.\n * - `unstoredReason` — the omitted bytes are not readable from this event:\n * either the upload failed, or it succeeded but the returned locator did\n * not fit the daemon's inline cap. Either way the content is not reachable\n * through this event; the reason says which. This exists so an unreadable\n * omission is observable rather than silently indistinguishable from a\n * small output.\n *\n * `.strict()` because this is an SDK-authored descriptor with a closed\n * shape, not free-form runtime data: an unrecognized key here means a\n * producer and a consumer disagree about what the omission means, which is\n * exactly the case that must fail loudly.\n */\nexport const AgentEventSpillSchema = z\n .object({\n /** Which field of the event was replaced by a preview. */\n field: z.enum(['input', 'output']),\n /** UTF-8 byte length of the full `JSON.stringify(<field>)` that was spilled. */\n totalBytes: z.number().int().nonnegative(),\n /** `totalBytes` minus the UTF-8 bytes of the retained preview head + tail. */\n omittedBytes: z.number().int().nonnegative(),\n /** Always the JSON serialization of the field — never the tool's own notion of a content type. */\n contentType: z.literal('application/json'),\n /** Where the omitted bytes are readable. Mutually exclusive with `unstoredReason`. */\n blob: BlobRefSchema.optional(),\n /** Why the omitted bytes are NOT readable. Mutually exclusive with `blob`. */\n unstoredReason: z.string().min(1).max(AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH).optional(),\n })\n .strict()\n .refine(\n (spill) => (spill.blob === undefined) !== (spill.unstoredReason === undefined),\n 'spill must carry exactly one of blob (the omitted bytes are readable) or unstoredReason (they are not)',\n );\n\nexport type AgentEventSpill = z.infer<typeof AgentEventSpillSchema>;\n\n/**\n * Normalized event shape that every runtime adapter (pi / claude / codex)\n * translates its native JSONL output into. This is the interior of a\n * `task.progress` payload's `events` array.\n */\nexport const AgentEventSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('progress'), text: z.string() }),\n z.object({\n type: z.literal('tool_use'),\n tool: z.string(),\n /** Authoritative MCP identity, absent when the adapter cannot resolve it. */\n mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),\n input: z.unknown().optional(),\n toolCallId: z.string().regex(/\\S/, 'toolCallId must contain a non-whitespace character').optional(),\n /** Present only when `input` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */\n spill: AgentEventSpillSchema.optional(),\n }),\n z.object({\n type: z.literal('tool_result'),\n tool: z.string(),\n /** Authoritative MCP identity, absent when the adapter cannot resolve it. */\n mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),\n output: z.unknown().optional(),\n toolCallId: z.string().regex(/\\S/, 'toolCallId must contain a non-whitespace character').optional(),\n isError: z.boolean().optional(),\n /** Present only when `output` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */\n spill: AgentEventSpillSchema.optional(),\n }),\n z.object({ type: z.literal('artifact'), name: z.string(), contentType: z.string() }),\n z.object({ type: z.literal('turn_end') }),\n z.object({ type: z.literal('error'), message: z.string() }),\n /**\n * Token usage reported by a runtime turn — maps from codex\n * `turn.completed.usage` and claude `result` usage (adapters wired up in a\n * later wave; this is just the variant + schema). All fields optional\n * because runtimes report different subsets.\n */\n z.object({\n type: z.literal('usage'),\n inputTokens: z.number().int().nonnegative().optional(),\n cachedInputTokens: z.number().int().nonnegative().optional(),\n outputTokens: z.number().int().nonnegative().optional(),\n reasoningTokens: z.number().int().nonnegative().optional(),\n totalTokens: z.number().int().nonnegative().optional(),\n // Context occupancy is independent of provider cost counters. Unknown stays absent.\n contextTokens: z.number().int().nonnegative().optional(),\n contextWindow: z.number().int().positive().optional(),\n contextSource: z.enum(['provider', 'estimate']).optional(),\n // Served model as the runtime reported it, never the requested id.\n model: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),\n }),\n]);\n\nexport type AgentEvent = z.infer<typeof AgentEventSchema>;\n\n/**\n * Known AgentEvent variant type discriminators — DERIVED directly from\n * {@link AgentEventSchema}'s own discriminated-union variants via\n * `z.toJSONSchema`, rather than hand-maintained as a second literal list.\n * This used to be a standalone array kept in sync with the schema above by\n * hand (dual authority); the freeze guard\n * (`__tests__/freeze-guard.test.ts`'s \"dual-authority cross-check\") already\n * asserted the two matched using this EXACT SAME `z.toJSONSchema` extraction\n * mechanism, which is why deriving it this way is safe: the guard already\n * proved this extraction produces the identical set the hand-written list\n * held. With the derivation below, the two can no longer drift apart at\n * all — there is only one authority now, {@link AgentEventSchema} itself.\n * The freeze guard test is kept anyway (now definitionally true rather than\n * a live check) as a regression net in case a future refactor reintroduces a\n * hand-written list.\n *\n * Exported (not module-private) so {@link isKnownAgentEvent} /\n * {@link partitionAgentEvents} (and the freeze guard) can check against the\n * exact same set without each reaching into zod's discriminated-union\n * internals directly. `z.toJSONSchema`'s output shape here (`.oneOf[].\n * properties.type.const`) is a public, documented zod v4 API — not\n * reaching into `._def`/internal fields — same as the freeze guard already\n * relies on.\n */\nexport const KNOWN_AGENT_EVENT_TYPES: readonly string[] = (\n z.toJSONSchema(AgentEventSchema) as unknown as { oneOf: Array<{ properties: { type: { const: string } } }> }\n).oneOf.map((branch) => branch.properties.type.const);\n\n/**\n * Pre-freeze compatibility widening (the freeze blocker this schema fixes):\n * an unknown-type event — one a future runtime/protocol minor version\n * introduces — parses as an opaque passthrough placeholder instead of\n * hard-failing the entire `task.progress` batch it arrived in. Without this,\n * `TaskProgressPayloadSchema.events: z.array(AgentEventSchema)` would throw\n * on the whole array the moment one event had an unrecognized `type`, which\n * made the wire's \"additive new variants are non-breaking\" promise false for\n * the installed base — and unfixable post-freeze.\n *\n * The `.refine` guard is load-bearing, not decorative: it excludes every\n * KNOWN type literal, so a *malformed* known variant (e.g. `progress`\n * missing `text`) still fails validation instead of silently matching this\n * fallback. Tolerance is only for unknown TYPES, never for malformed known\n * ones — see {@link AgentEventOrUnknownSchema}, which is what actually\n * combines this with {@link AgentEventSchema} for real use.\n *\n * Deliberately asymmetric with envelope-level control/security fields\n * (`instruction` — see `messages.ts`), which stay\n * fail-closed on unknown shapes with no equivalent widening: this tolerance\n * applies only to observability data (agent progress events), never to\n * control/security surfaces. That asymmetry is the freeze rule.\n */\nexport const UnknownAgentEventSchema = z\n .object({ type: z.string() })\n .passthrough()\n .refine(\n (event) => !KNOWN_AGENT_EVENT_TYPES.includes(event.type),\n 'type refers to a known AgentEvent variant; malformed known variants must fail through AgentEventSchema, not fall back to unknown-tolerance',\n );\n\nexport type UnknownAgentEvent = z.infer<typeof UnknownAgentEventSchema>;\n\n/**\n * The actual element schema for `TaskProgressPayloadSchema.events`\n * (`messages.ts`): a known, fully-typed {@link AgentEvent} OR an opaque\n * unknown-type placeholder. `z.union` (not `discriminatedUnion`) is required\n * here because the fallback branch matches on \"not one of the known\n * literals\", which a discriminated union can't express directly.\n */\nexport const AgentEventOrUnknownSchema = z.union([AgentEventSchema, UnknownAgentEventSchema]);\n\nexport type AgentEventOrUnknown = z.infer<typeof AgentEventOrUnknownSchema>;\n\n/**\n * Type guard distinguishing a known, fully-typed {@link AgentEvent} from an\n * {@link UnknownAgentEvent} passthrough placeholder.\n */\nexport function isKnownAgentEvent(event: AgentEventOrUnknown): event is AgentEvent {\n return KNOWN_AGENT_EVENT_TYPES.includes(event.type);\n}\n\n/**\n * Split a `task.progress` events array into known (typed, actionable) and\n * unknown (opaque, safe-to-skip) events. Consumers should process `known`\n * and skip `unknown` rather than throwing on it — that's the point of the\n * pre-freeze tolerance above.\n */\nexport function partitionAgentEvents(events: readonly AgentEventOrUnknown[]): {\n known: AgentEvent[];\n unknown: UnknownAgentEvent[];\n} {\n const known: AgentEvent[] = [];\n const unknown: UnknownAgentEvent[] = [];\n for (const event of events) {\n if (isKnownAgentEvent(event)) {\n known.push(event);\n } else {\n unknown.push(event);\n }\n }\n return { known, unknown };\n}\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema } from './agent-egress';\n\n/** Maximum UTF-8 encoded JSON bytes carried by one projection payload. */\nexport const AGENT_HOME_PROJECTION_MAX_BYTES = 64 * 1024;\n\n/** PostgreSQL BIGINT maximum, kept as decimal text to avoid JavaScript precision loss. */\nexport const AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM = '9223372036854775807' as const;\n\n/**\n * Canonical positive decimal Profile revision for this projection contract.\n *\n * This deliberately stays local to the projection contract: the generic\n * AgentRef used by existing task and egress messages remains opaque. Values\n * cross the JavaScript/PostgreSQL boundary as text and are compared\n * lexically after canonical syntax validation.\n */\nexport const AgentHomeProjectionProfileRevisionSchema = z\n .string()\n .regex(/^[1-9][0-9]{0,18}$/u, 'profileRevision must be a canonical positive decimal string')\n .refine(\n (value) =>\n value.length < AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM.length ||\n value <= AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM,\n `profileRevision must not exceed PostgreSQL BIGINT maximum ${AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM}`,\n );\nexport type AgentHomeProjectionProfileRevision = z.infer<typeof AgentHomeProjectionProfileRevisionSchema>;\n\n/** The projection hash uses the package-wide lowercase SHA-256 transport form. */\nexport const AgentHomeProjectionHashSchema = AgentEgressContentHashSchema;\nexport type AgentHomeProjectionHash = z.infer<typeof AgentHomeProjectionHashSchema>;\n\n/** Terminal local-apply outcome carried by the exact completion request. */\nexport const AgentHomeProjectionOutcomeSchema = z.enum(['applied', 'idempotent', 'stale', 'conflict']);\nexport type AgentHomeProjectionOutcome = z.infer<typeof AgentHomeProjectionOutcomeSchema>;\n\n/**\n * Bounded opaque JSON. The SDK enforces only byte size and does not interpret\n * Salesko or any other product's fields. Credential custody remains outside\n * this protocol surface; this schema intentionally defines no credential\n * fields and is not a DLP scanner.\n */\nexport type AgentHomeProjectionValue =\n | string\n | number\n | boolean\n | null\n | AgentHomeProjectionValue[]\n | { [key: string]: AgentHomeProjectionValue };\n\nexport const AgentHomeProjectionValueSchema: z.ZodType<AgentHomeProjectionValue> = z\n .json()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= AGENT_HOME_PROJECTION_MAX_BYTES,\n `projection must not exceed ${AGENT_HOME_PROJECTION_MAX_BYTES} UTF-8 JSON bytes`,\n );\n","/**\n * Member keys, the member chain and scope key packages as the Host stores\n * them (#654 design §7.2–§7.4, E2c).\n *\n * The Host checks shapes only. It never hashes an entry or verifies a\n * signature: members walk the chain themselves (§7.3), so a Host check adds\n * no trust. `@byok-sdk/core/sealed-payload` creates and verifies these values.\n * Protocol does not depend on core, so this module repeats core's shape\n * rules; a cross-package test in `@byok-sdk/cloud` keeps the two equal.\n */\nimport { z } from 'zod';\n\nimport { CONTENT_HASH_RE } from './blob';\n\n/** The most chain entries one append accepts. */\nexport const E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES = 64;\n/** The largest canonical JSON entry, in UTF-8 bytes. */\nexport const E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES = 65_536;\n/** The most chain entries one read returns. */\nexport const E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES = 256;\n/** The most scope key packages one put accepts. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PUT_MAX = 256;\n/** The most packages one paged device read returns. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX = 16;\n/**\n * The longest scope id, in UTF-16 code units, as for other opaque Host ids.\n * Core sets no maximum, so the scope key package shape (which the parity test\n * compares with core) leaves it out, and the Host checks it on every put and\n * read. The key package notice is Host-built wire, so its schema carries it.\n */\nexport const E2EE_SCOPE_ID_MAX_LENGTH = 512;\n\n// Device-proof operations of the three device write routes. Each route binds\n// one operation, and the proof's `resource` is the route path.\n/** Register the device's member key bundle and its device pairing MAC (§7.2 step 3). */\nexport const E2EE_MEMBER_KEY_REGISTER_OPERATION = 'e2ee-member-key.register' as const;\n/** Append member chain entries. */\nexport const E2EE_MEMBER_CHAIN_APPEND_OPERATION = 'e2ee-member-chain.append' as const;\n/** Put scope key packages. */\nexport const E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION = 'e2ee-scope-key-package.put' as const;\n\n/**\n * Canonical unpadded base64url of exactly `bytes` bytes: the length is fixed,\n * and the unused low bits of the last character are zero, so one value has\n * one text form.\n */\nfunction base64UrlBytes(bytes: number) {\n const length = Math.ceil((bytes * 4) / 3);\n const last = ['[A-Za-z0-9_-]', '[AQgw]', '[AEIMQUYcgkosw048]'][bytes % 3];\n return z.string().regex(new RegExp(`^[A-Za-z0-9_-]{${length - 1}}${last}$`, 'u'));\n}\n\nconst MemberIdSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/u);\nconst PositiveSafeIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);\nconst SignatureSchema = base64UrlBytes(64);\n\nconst P256PublicJwkSchema = z.strictObject({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: base64UrlBytes(32),\n y: base64UrlBytes(32),\n});\n\n/** A member's public key bundle. A device member names its SDK device id; a client member has none. */\nexport const E2eeMemberKeyBundleSchema = z.strictObject({\n v: z.literal(1),\n memberId: MemberIdSchema,\n signingPublicJwk: P256PublicJwkSchema,\n kemPublicJwk: P256PublicJwkSchema,\n kemEpoch: PositiveSafeIntegerSchema,\n kemSig: SignatureSchema,\n deviceId: z.string().min(1).optional(),\n});\nexport type E2eeMemberKeyBundle = z.infer<typeof E2eeMemberKeyBundleSchema>;\n\nexport const E2EE_MEMBER_CHAIN_OPS = ['add', 'remove', 'rotate', 'scope-policy', 'shred'] as const;\n\n/**\n * The subject of a `shred` entry (design §11.2). The Host reads it to delete\n * the scope's key packages (owner batch §50g A), so it checks this one\n * subject strictly. Core's walk refuses any other `shred` subject too. Like\n * core, it sets no maximum length: a scope id the Host never stored has no\n * packages to delete.\n */\nconst E2eeScopeShredSubjectSchema = z.strictObject({ scopeId: z.string().min(1) });\n\n/**\n * The subject of a `rotate` entry. The Host reads `memberId` and `kemEpoch`\n * to raise the member's KEM floor (#654 E5b-2, owner batch §77a), so it\n * checks this subject as strictly as core's walk does.\n */\nconst E2eeMemberRotateSubjectSchema = z.strictObject({\n memberId: MemberIdSchema,\n kemPublicJwk: P256PublicJwkSchema,\n kemEpoch: PositiveSafeIntegerSchema,\n kemSig: SignatureSchema,\n});\n\n/**\n * One signed member chain entry. `subject` must be a JSON object; the Host\n * stores the entry as canonical JSON, which refuses any value outside JSON.\n * A `shred` subject must also be exactly `{ scopeId }`.\n */\nexport const E2eeMemberChainEntrySchema = z\n .strictObject({\n v: z.literal(1),\n tenantId: z.string().min(1),\n seq: PositiveSafeIntegerSchema,\n prev: z.union([z.null(), z.string().regex(CONTENT_HASH_RE)]),\n op: z.enum(E2EE_MEMBER_CHAIN_OPS),\n subject: z.custom<Readonly<Record<string, unknown>>>(\n value => value !== null && typeof value === 'object' && !Array.isArray(value),\n ),\n signer: MemberIdSchema,\n sig: SignatureSchema,\n })\n .refine(entry => (entry.seq === 1) === (entry.prev === null), {\n path: ['prev'],\n message: 'the first entry, and only the first, has no prev',\n })\n .refine(entry => entry.op !== 'shred' || E2eeScopeShredSubjectSchema.safeParse(entry.subject).success, {\n path: ['subject'],\n message: 'a shred subject is exactly { scopeId }',\n })\n .refine(entry => entry.op !== 'rotate' || E2eeMemberRotateSubjectSchema.safeParse(entry.subject).success, {\n path: ['subject'],\n message: 'a rotate subject is exactly { memberId, kemPublicJwk, kemEpoch, kemSig }',\n });\nexport type E2eeMemberChainEntry = z.infer<typeof E2eeMemberChainEntrySchema>;\n\nconst E2eeScopeKeyPackageV1Schema = z.strictObject({\n v: z.literal(1),\n tenantId: z.string().min(1),\n scopeId: z.string().min(1),\n epoch: PositiveSafeIntegerSchema,\n keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u),\n recipient: MemberIdSchema,\n sender: MemberIdSchema,\n enc: base64UrlBytes(65),\n ciphertext: base64UrlBytes(48),\n sig: SignatureSchema,\n});\n\n/** One scope key wrapped to one member's KEM key of `recipientKemEpoch` (§7.4, §77a). A put takes version 2 only. */\nexport const E2eeScopeKeyPackageV2Schema = z.strictObject({\n ...E2eeScopeKeyPackageV1Schema.shape,\n v: z.literal(2),\n recipientKemEpoch: PositiveSafeIntegerSchema,\n});\n\n/** A stored package as a read returns it: version 1 from before `e2ee.member.kem-epoch`, version 2 after. */\nexport const E2eeScopeKeyPackageSchema = z.union([E2eeScopeKeyPackageV1Schema, E2eeScopeKeyPackageV2Schema]);\nexport type E2eeScopeKeyPackage = z.infer<typeof E2eeScopeKeyPackageSchema>;\n\n/** A pairing MAC (§7.2 steps 3 and 4): HMAC-SHA-256 under `pv`, which the Host never holds. */\nexport const E2eePairingMacSchema = base64UrlBytes(32);\n\n/**\n * The device registration body. `member` is the device's own bundle, so it\n * names the device id; `mac` is the device pairing MAC over it under `pv`.\n */\nexport const E2eeMemberKeyRegisterRequestSchema = z.strictObject({\n member: E2eeMemberKeyBundleSchema.refine(member => member.deviceId !== undefined, {\n message: 'a device member names its deviceId',\n }),\n mac: E2eePairingMacSchema,\n});\nexport type E2eeMemberKeyRegisterRequest = z.infer<typeof E2eeMemberKeyRegisterRequestSchema>;\n\n/** What the client relays to the device in pairing step 4. The client member has no device id. */\nexport const E2eeClientPairingMacSchema = z.strictObject({\n mac: E2eePairingMacSchema,\n member: E2eeMemberKeyBundleSchema.refine(member => member.deviceId === undefined, {\n message: 'a client member has no deviceId',\n }),\n chainHead: z.strictObject({ seq: PositiveSafeIntegerSchema, hash: z.string().regex(CONTENT_HASH_RE) }),\n});\nexport type E2eeClientPairingMac = z.infer<typeof E2eeClientPairingMacSchema>;\n\n/**\n * Server -> daemon `e2ee.key_package.available` (E2c-3): the Host stored a\n * scope key package for this device's member. The payload names only the\n * scope epoch; the device fetches the package from its device route (§7.4,\n * notice-and-fetch), so a mailbox row never holds key material. Gated by\n * `sealed-payload-v1`.\n */\nexport const E2eeKeyPackageAvailablePayloadSchema = z.strictObject({\n scopeId: z.string().min(1).max(E2EE_SCOPE_ID_MAX_LENGTH),\n epoch: PositiveSafeIntegerSchema,\n});\nexport type E2eeKeyPackageAvailablePayload = z.infer<typeof E2eeKeyPackageAvailablePayloadSchema>;\n","import { z } from 'zod';\n\n/**\n * #1121: a device -> Host vocabulary a newer device may extend — a failure\n * class, a decline code, a content denial reason. A receiver must not refuse\n * the whole report for a value it does not know: it keeps the known meaning\n * of the values it knows and records any other well-formed token as\n * `unknown`, with the raw token kept beside it (`reported<Field>`). Control\n * vocabularies (message types, decisions, outcomes that select a shape) stay\n * closed.\n */\nconst OPEN_VOCABULARY_TOKEN = /^[a-z][a-z0-9_-]{0,63}$/;\n\n/** Any well-formed open-vocabulary token, without a membership rule. */\nexport function openVocabularyToken(): z.ZodString {\n return z.string().regex(OPEN_VOCABULARY_TOKEN);\n}\n\n/** A well-formed token that is none of `known`: the raw value a receiver keeps as `reported<Field>`. */\nexport function unrecognizedToken(known: readonly string[]): z.ZodString {\n return openVocabularyToken().refine((value) => !known.includes(value), {\n message: 'a recognized value is not reported as unrecognized',\n });\n}\n","import { PreparedAgentMemoryModeSchema } from './input-preparation';\nimport { z } from 'zod';\nimport { RUNTIME_FAILURE_CLASSES, RUNTIME_IDS, RUNTIME_QUOTA_SCOPES, RUNTIME_UNAVAILABLE_CAUSES, TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH, boundFailureReason, type RuntimeUnavailableCause } from './constants';\nimport { BlobRefSchema } from './blob';\nimport {\n SEALED_DECLINE_CODES,\n SealedTaskInputSchema,\n SealedAgentMessageSchema,\n SealedTaskOutputSchema,\n RoutineRefSchema,\n TaskSealingSchema,\n sealedOfferRule,\n} from './sealed-payload';\nimport { AgentEventOrUnknownSchema } from './agent-event';\nimport {\n AgentContentActorSchema,\n AgentContentDecodeAsSchema,\n AgentContentMimeTypeSchema,\n AgentContentReadDenialReasonSchema,\n AgentContentReadSurfaceSchema,\n AgentEgressContentHashSchema,\n AgentEgressPolicyRevisionSchema,\n AgentEgressPolicySchema,\n AgentMessageContractSchema,\n AgentMessageContentTypeSchema,\n AgentMessageEgressRequirementSchema,\n AGENT_MESSAGE_MAX_BYTES,\n AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,\n ContentReadPolicySchema,\n} from './agent-egress';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionProfileRevisionSchema,\n AgentHomeProjectionValueSchema,\n} from './agent-home-projection';\nimport { ProviderProvisioningAvailablePayloadSchema } from './provider-provisioning';\nimport { E2eeKeyPackageAvailablePayloadSchema } from './e2ee-member';\nimport {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\nimport { openVocabularyToken, unrecognizedToken } from './open-vocabulary';\nimport { ProviderProfileBindingSchema } from './provider-profile-binding';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\nimport { canonicalizePlainJson, type PlainJsonCheck } from './plain-json';\n\n/** Max size of an inlined artifact payload, per the delivery-model spec (<=64KB). */\nconst MAX_INLINE_BYTES = 64 * 1024;\n\nfunction isWithinInlineByteLimit(value: string): boolean {\n return new TextEncoder().encode(value).length <= MAX_INLINE_BYTES;\n}\n\n// ---------------------------------------------------------------------------\n// conn.* — connection handshake\n// ---------------------------------------------------------------------------\n\nexport const RuntimeIdSchema = z.enum(RUNTIME_IDS);\nexport type RuntimeId = z.infer<typeof RuntimeIdSchema>;\n\n/**\n * The append-only pre-claim runtime-unavailable cause (#1103 D6). An unknown\n * well-formed token is accepted and kept verbatim, so a newer device can add\n * one without a protocol bump; {@link readRuntimeUnavailableCause} is the\n * typed reading.\n */\nconst RuntimeUnavailableCauseSchema = z.union([\n z.enum(RUNTIME_UNAVAILABLE_CAUSES),\n unrecognizedToken(RUNTIME_UNAVAILABLE_CAUSES),\n]);\n\n/** A runtime-unavailable cause as this version understands it; unknown reads as `unknown` with the raw token kept. */\nexport type RuntimeUnavailableCauseReading =\n | { readonly cause: RuntimeUnavailableCause }\n | { readonly cause: 'unknown'; readonly reportedCause: string };\n\nexport function readRuntimeUnavailableCause(cause: string): RuntimeUnavailableCauseReading {\n return (RUNTIME_UNAVAILABLE_CAUSES as readonly string[]).includes(cause)\n ? { cause: cause as RuntimeUnavailableCause }\n : { cause: 'unknown', reportedCause: cause };\n}\n\n/** Wire-safe protocol version number: bounded before JSON reaches a store or comparison. */\nexport const ProtocolVersionNumberSchema = z\n .number()\n .int()\n .nonnegative()\n .max(2_147_483_647);\n\n/**\n * Per-runtime feature flags reported in `conn.hello.runtimes[].capabilities`\n * (pre-freeze addition). Distinct from the connection-level `CAPABILITY_FLAGS`\n * (`version.ts`) / `conn.hello.capabilities` array: those are protocol-level\n * flags negotiated for the whole connection, while this is what one specific\n * detected runtime (pi/claude/codex) supports. The whole field is optional\n * end-to-end — older daemons omit `capabilities` entirely — and every field\n * inside it is itself optional, since detection can be partial.\n *\n * Unrecognized keys inside `capabilities` itself, by contrast, are silently\n * stripped (zod's default object behavior — same as every other payload\n * schema in this file) rather than passed through: this is a closed, typed\n * shape consumers can rely on, and a genuinely new capability flag gets added\n * here explicitly rather than round-tripped opaquely.\n */\nexport const RuntimeCapabilitiesSchema = z.object({\n steer: z.boolean().optional(),\n resume: z.boolean().optional(),\n approvalInteractive: z.boolean().optional(),\n /** Whether this runtime can project a locally configured MCP toolset into one task. */\n mcpToolsets: z.boolean().optional(),\n messageDraft: z.boolean().optional(),\n /** The capability matrix (#1103): what the runtime's adapter descriptor declares. Discovery data, not a gate. */\n toolAuthorizationAuto: z.boolean().optional(),\n /** The durable worker lane (Pi today). */\n durableLane: z.boolean().optional(),\n preparedLane: z.boolean().optional(),\n isolation: z.object({\n userContext: z.boolean().optional(),\n userMcpServers: z.boolean().optional(),\n sessionPersistence: z.boolean().optional(),\n }).optional(),\n});\nexport type RuntimeCapabilities = z.infer<typeof RuntimeCapabilitiesSchema>;\n\n/**\n * The effective version policy's verdict, projected for discovery (#1103 D8).\n * Only `state` and the policy's qualified token travel: `matched` and the\n * allow/warn/block spec lists stay local. Absence means **unknown**, never\n * `allow`: an older daemon or an adapter without a policy omits the field.\n */\nexport const RuntimeVersionPolicyProjectionSchema = z.object({\n state: z.enum(['allow', 'warn', 'block']),\n qualifiedVersion: z.string().min(1).max(256).optional(),\n});\nexport type RuntimeVersionPolicyProjection = z.infer<typeof RuntimeVersionPolicyProjectionSchema>;\n\n/**\n * Runtime detection info reported in `conn.hello`. Supersedes the M0\n * `agents: unknown` field (M1 gap #4): typed, so the server no longer has to\n * best-effort-normalize an untyped blob.\n */\nexport const RuntimeInfoSchema = z.object({\n id: RuntimeIdSchema,\n version: z.string().optional(),\n authPresent: z.boolean().optional(),\n /** Optional: older daemons omit this entirely (pre-freeze addition). */\n capabilities: RuntimeCapabilitiesSchema.optional(),\n /** #1103 D8: strip-safe discovery projection; absent means unknown. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\nexport type RuntimeInfo = z.infer<typeof RuntimeInfoSchema>;\n\n/** Custom identities are disjoint from the frozen built-in runtime enum. */\nexport const HarnessIdSchema = z.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/)\n .refine(value => !(RUNTIME_IDS as readonly string[]).includes(value), 'built-in runtime must use runtime');\nexport type HarnessId = z.infer<typeof HarnessIdSchema>;\nexport const HarnessInfoSchema = z.object({\n id: HarnessIdSchema,\n version: z.string().min(1).max(128).optional(),\n capabilities: RuntimeCapabilitiesSchema,\n /** #1103 D8: the same version-policy projection a built-in runtime carries. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\nexport type HarnessInfo = z.infer<typeof HarnessInfoSchema>;\nexport const HarnessInventorySchema = z.array(HarnessInfoSchema).max(64)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate harness identity');\n\n/**\n * One non-available runtime or harness in `conn.hello.runtimeUnavailable`\n * (#1103 D8). The id stays in the existing identity domain: a built-in\n * runtime id or a custom harness id. The cause is the append-only\n * vocabulary, and `retryable` carries the same per-cause default a\n * `task.decline` reports. Absence of the whole array means unknown, never\n * \"everything is available\".\n */\nexport const RuntimeUnavailableEntrySchema = z.object({\n id: z.union([RuntimeIdSchema, HarnessIdSchema]),\n cause: RuntimeUnavailableCauseSchema,\n retryable: z.boolean(),\n});\nexport type RuntimeUnavailableEntry = z.infer<typeof RuntimeUnavailableEntrySchema>;\n\n/** Bounded, unique by id: 16 entries are more runtimes than one daemon hosts. */\nconst RuntimeUnavailableListSchema = z.array(RuntimeUnavailableEntrySchema).max(16)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate runtime-unavailable identity');\n\n/** Maximum logical toolsets one daemon may advertise as locally configured. */\nexport const CONFIGURED_TOOLSETS_MAX_ITEMS = 64;\n\n/**\n * Logical, host-owned MCP toolset identifier. A task may request this name,\n * but the executable/server definition behind it exists only in the daemon's\n * local configuration and never crosses the SaaS wire.\n */\nexport const ToolsetIdSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, 'toolset ids must be lowercase logical identifiers');\nexport type ToolsetId = z.infer<typeof ToolsetIdSchema>;\n\n/** Stable Agent identity carried across transport and storage. */\nexport const AGENT_REF_MAX_BYTES = 160;\nconst AGENT_REF_VALUE = z\n .string()\n .min(1)\n .max(AGENT_REF_MAX_BYTES)\n .refine((value) => new TextEncoder().encode(value).byteLength <= AGENT_REF_MAX_BYTES, {\n message: `AgentRef values must not exceed ${AGENT_REF_MAX_BYTES} UTF-8 bytes`,\n })\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, 'AgentRef values must not contain control characters');\n\nconst WINDOWS_RESERVED_AGENT_SEGMENT = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\..*)?$/iu;\n\n/**\n * Agent ids are opaque to the SDK but must remain one safe pathname segment;\n * the SDK owns the deterministic `<hostStorageRoot>/agents/<agentId>` mapping.\n */\nexport const AgentRefSchema = z\n .object({\n agentId: AGENT_REF_VALUE.regex(/^[^\\\\/:<>\"|?*]+$/u, 'agentId must be one portable pathname segment').refine(\n (value) => value !== '.' && value !== '..',\n 'agentId must not be a dot segment',\n ).refine(\n (value) => !/[. ]$/u.test(value) && !WINDOWS_RESERVED_AGENT_SEGMENT.test(value),\n 'agentId must be a portable Windows-safe pathname segment',\n ),\n profileRevision: AGENT_REF_VALUE,\n })\n .strict();\nexport type AgentRef = z.infer<typeof AgentRefSchema>;\n\n/** AgentRef constrained to the canonical Profile revision required by projection control. */\nexport const AgentHomeProjectionAgentRefSchema = AgentRefSchema.extend({\n profileRevision: AgentHomeProjectionProfileRevisionSchema,\n}).strict();\nexport type AgentHomeProjectionAgentRef = z.infer<typeof AgentHomeProjectionAgentRefSchema>;\n\nfunction rejectDuplicateToolsets(\n ids: readonly string[],\n ctx: z.RefinementCtx,\n label: 'configured' | 'required',\n): void {\n const seen = new Set<string>();\n for (const [index, id] of ids.entries()) {\n if (seen.has(id)) {\n ctx.addIssue({ code: 'custom', path: [index], message: `duplicate ${label} toolset: ${id}` });\n }\n seen.add(id);\n }\n}\n\n/**\n * Device-local inventory projected for discovery. IDs only: executable MCP\n * definitions, arguments, environment and credentials never enter this shape.\n * Empty means known-none; omission on the containing message means unknown.\n */\nexport const ConfiguredToolsetsSchema = z\n .array(ToolsetIdSchema)\n .max(CONFIGURED_TOOLSETS_MAX_ITEMS)\n .superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'configured'));\n\n/** daemon -> server: opening handshake. */\nexport const ConnHelloPayloadSchema = z.object({\n protocolVersions: z.array(ProtocolVersionNumberSchema).max(16),\n capabilities: z.array(z.string()),\n deviceId: z.string(),\n productId: z.string(),\n /** U4a Local Agent release identity; this is the sole client-version authority. */\n clientVersion: z.string().min(1).max(128).optional(),\n /** Runtimes detected on this device (M1 gap #4; replaces `agents`). */\n runtimes: z.array(RuntimeInfoSchema).optional(),\n harnesses: HarnessInventorySchema.optional(),\n /** #1103 D8: non-available runtimes and harnesses; strip-safe and absent means unknown. */\n runtimeUnavailable: RuntimeUnavailableListSchema.optional(),\n /** Validated logical IDs configured on this device; definitions and secrets stay local. */\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n /**\n * Last `seq` this device has seen from the server (M1 redelivery cursor).\n * Omitted on a device's first-ever connection. The server replays any\n * server->daemon envelopes with `seq > cursor` it still holds — see\n * docs/protocol.md \"At-least-once delivery\".\n */\n cursor: z.number().int().optional(),\n});\nexport type ConnHelloPayload = z.infer<typeof ConnHelloPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// server -> daemon: task.*\n//\n// Every type in this section carries a *required* envelope `task_id` (M1 gap\n// #1) and a *required* envelope `seq` — a per-device monotonic counter the\n// daemon uses as a redelivery cursor (M1 gap; see `conn.hello.cursor` above\n// and docs/protocol.md \"At-least-once delivery\"). None of these payloads\n// duplicate `taskId` at the payload level (M1 gap #7): the envelope's\n// `task_id` is the single routing key.\n// ---------------------------------------------------------------------------\n\n/**\n * The out-of-band-reference form of an offer's `instruction` (the\n * alternative to an inlined string). `.strict()`: this is control data — it's\n * the task instruction itself,\n * the thing that authorizes what work gets done — so per the freeze rule's\n * observability-vs-control asymmetry (docs/protocol.md \"Freeze rule\") an\n * unrecognized field here must be REJECTED, not silently stripped the way an\n * ordinary payload's unknown field is. Without `.strict()`, a hypothetical\n * future field riding along next to `blobRef` (e.g. a routing/priority\n * override) would be silently discarded instead of failing the parse —\n * exactly the kind of silent reinterpretation the freeze rule forbids for\n * control/security payloads. Consequence: adding a field to this shape\n * post-freeze is a BREAKING change (version bump required), not the usual\n * non-breaking additive-optional-field case.\n */\nconst InstructionBlobRefSchema = z.object({ blobRef: BlobRefSchema }).strict();\n\nconst DispatchTargetIdSchema = z\n .string()\n .min(1)\n .max(160)\n .regex(/^[^\\u0000\\r\\n]+$/u, 'dispatch target ids must not contain control line breaks');\n\n/**\n * The web-selected runtime/model target carried end to end with a task.\n *\n * This is an additive v1 field. The discriminated union makes lane ownership\n * fail closed at decode time: subscription credentials can only belong to the\n * vendor CLIs, while a BYOK provider can only be executed through Pi.\n */\nexport const DispatchSelectionSchema = z.discriminatedUnion('lane', [\n z\n .object({\n lane: z.literal('subscription'),\n runtimeId: z.enum(['claude', 'codex']),\n providerId: z.null(),\n modelId: DispatchTargetIdSchema,\n })\n .strict(),\n z\n .object({\n lane: z.literal('byok'),\n runtimeId: z.literal('pi'),\n providerId: DispatchTargetIdSchema,\n modelId: DispatchTargetIdSchema,\n })\n .strict(),\n z\n .object({\n lane: z.literal('byok-profile'),\n runtimeId: z.literal('pi'),\n providerProfile: ProviderProfileBindingSchema,\n })\n .strict(),\n]);\nexport type DispatchSelection = z.infer<typeof DispatchSelectionSchema>;\n\n/**\n * #654: the plaintext branch of a sealable type refuses the sealed members.\n * Without this, a loose schema would strip them, and sealed content or a\n * sealing policy would pass as plaintext. A strict schema needs it too: its\n * unknown-key check sees only enumerable keys, so a non-enumerable `sealed` or\n * `sealing` would be dropped. A sealed message takes the type's sealed branch.\n */\nconst NO_SEALED_MEMBER = { sealed: z.never().optional(), sealing: z.never().optional() };\n\n/** Every named toolset is required; duplicates are rejected instead of silently de-duplicated. */\nexport const RequiredToolsetsSchema = z\n .array(ToolsetIdSchema)\n .min(1)\n .max(16)\n .superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'required'));\n\n/**\n * How an Agent Attempt uses its Agent home. `memory-reader` runs the Attempt\n * in its own run directory, `<home>/.byok/runs/<taskId>/`, beside other\n * reader Attempts and at most one writer Attempt. The home stays an ancestor\n * of that cwd, so the runtime still finds the persona and memory. Absent means\n * a writer: the Attempt runs in the canonical home, and one home has at most\n * one writer at a time. The SDK does not make memory read-only; a reader\n * terminal reports memory changes in `agentHomeMemoryChange`. A host sends this\n * field only to a device that advertises `agent-home-readers`: the Agent\n * offers are strict, so an older daemon cannot accept it.\n */\nexport const AgentHomeAccessSchema = z.literal('memory-reader');\nexport type AgentHomeAccess = z.infer<typeof AgentHomeAccessSchema>;\n\n/**\n * The `agentMemory` of an ordinary Agent offer: the prepared modes plus\n * `read-if-admitted` and `read-write-if-admitted`. When the daemon admits the\n * memory MCP they run as `read` and `read-write`; when it does not, both run as\n * `none`. A host sends each only to a device that advertises\n * `agent-memory-read-if-admitted` or `agent-memory-read-write-if-admitted`. A\n * `memory-reader` Attempt cannot select `read-write-if-admitted`. Prepared\n * offers refuse both.\n */\nexport const AgentMemorySelectionSchema = z.enum([\n ...PreparedAgentMemoryModeSchema.options, 'read-if-admitted', 'read-write-if-admitted',\n]);\nexport type AgentMemorySelection = z.infer<typeof AgentMemorySelectionSchema>;\n\n/**\n * How a `task.offer` starts its runtime session. `resume` continues the named\n * session; `fresh` lets the selected runtime mint one after start. It is\n * required, so an offer without a resume reference is never read as fresh.\n */\nexport const SessionSelectionSchema = z.discriminatedUnion('mode', [\n z.object({ mode: z.literal('resume'), sessionRef: z.string().min(1).max(512) }).strict(),\n z.object({ mode: z.literal('fresh') }).strict(),\n]);\nexport type SessionSelection = z.infer<typeof SessionSelectionSchema>;\n\n/**\n * The fields both `task.offer` branches carry. Every offer binds a durable\n * host-owned Agent (`agentRef`). Each optional field is gated on its own\n * device flag (`wire-additions.ts`); the offer is strict, so a daemon that does\n * not know a field stops its cursor instead of stripping it.\n *\n * `agentMemory` selects the Agent memory of this one task (see\n * {@link AgentMemorySelectionSchema}); absent keeps the daemon admission.\n * `preparation` names an already-counted prepared Execution (see\n * {@link offerRule}): every value under it is the Host re-presenting what the\n * device already told it, and the device declines non-retryably on any\n * difference from its own record.\n */\nconst OFFER_FIELDS = {\n agentRef: AgentRefSchema,\n session: SessionSelectionSchema,\n preparation: InputPreparationOfferBindingSchema.optional(),\n agentMemory: AgentMemorySelectionSchema.optional(),\n homeAccess: AgentHomeAccessSchema.optional(),\n requiredToolsets: RequiredToolsetsSchema.optional(),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n dispatchSelection: DispatchSelectionSchema.optional(),\n terminalProjection: TerminalProjectionSelectionSchema.optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .strict()\n .optional(),\n egressPolicy: AgentEgressPolicySchema.optional(),\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n};\n\ntype OfferRuleInput = {\n readonly instruction?: unknown;\n readonly session: SessionSelection;\n readonly preparation?: unknown;\n readonly agentMemory?: AgentMemorySelection;\n readonly egressPolicy?: unknown;\n readonly messageEgress?: unknown;\n readonly routineRef?: unknown;\n};\n\n/**\n * The cross-field rules of a `task.offer`, for `superRefine`:\n *\n * - A prepared offer (`preparation`) carries no `instruction`: the user request\n * is already inside the frozen envelope the prepared record retained. It\n * never resumes, and it selects a prepared `agentMemory` mode.\n * - A plaintext offer that is not prepared carries an `instruction`. A sealed\n * offer's instruction is checked by {@link sealedOfferRule}.\n * - A fresh or prepared offer carries an `egressPolicy`; `messageEgress` needs one.\n * - A `routineRef` names an execution, so it needs a fresh session.\n */\nfunction offerRule(payload: OfferRuleInput, ctx: z.RefinementCtx, plaintext: boolean): void {\n const { instruction, session, preparation, agentMemory, egressPolicy, messageEgress, routineRef } = payload;\n if (preparation !== undefined) {\n if (instruction !== undefined) ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'a prepared offer carries no instruction' });\n if (session.mode !== 'fresh') ctx.addIssue({ code: 'custom', path: ['session'], message: 'a prepared offer never resumes' });\n if (!PreparedAgentMemoryModeSchema.safeParse(agentMemory).success) {\n ctx.addIssue({ code: 'custom', path: ['agentMemory'], message: 'a prepared offer selects a prepared agentMemory mode' });\n }\n } else if (plaintext && instruction === undefined) {\n ctx.addIssue({ code: 'custom', path: ['instruction'], message: 'an offer that is not prepared carries an instruction' });\n }\n if ((preparation !== undefined || session.mode === 'fresh') && egressPolicy === undefined) {\n ctx.addIssue({ code: 'custom', path: ['egressPolicy'], message: 'a fresh or prepared offer carries an egressPolicy' });\n }\n if (messageEgress !== undefined && egressPolicy === undefined) {\n ctx.addIssue({ code: 'custom', path: ['messageEgress'], message: 'messageEgress needs an egressPolicy' });\n }\n if (routineRef !== undefined && session.mode !== 'fresh') {\n ctx.addIssue({ code: 'custom', path: ['routineRef'], message: 'a routine occurrence is an execution, so it needs a fresh session' });\n }\n}\n\n/** The plaintext branch of `task.offer`, before its cross-field rules. */\nconst TaskOfferPlainFields = z\n .object({\n ...NO_SEALED_MEMBER,\n routineRef: z.never().optional(),\n instruction: z.union([z.string(), InstructionBlobRefSchema]).optional(),\n ...OFFER_FIELDS,\n })\n .strict();\n\n/**\n * The sealed branch of `task.offer`, before its rules. `sealing` marks it: the\n * task's frozen sealing policy. When the policy includes `task-input`,\n * `instruction` moves into `sealed` (or `sealed` is a routine template named by\n * `routineRef`); otherwise `instruction` stays plaintext and only the output is\n * sealed. A prepared Execution is never sealed (`SEALED_SPLIT_TABLE` forbids\n * `preparation`).\n */\nconst TaskOfferSealedFields = z\n .object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]).optional(),\n sealing: TaskSealingSchema,\n sealed: SealedTaskInputSchema.optional(),\n routineRef: RoutineRefSchema.optional(),\n ...OFFER_FIELDS,\n preparation: z.never().optional(),\n })\n .strict();\n\n/** server -> daemon: a `task.offer` of a task that is not sealed. */\nexport const TaskOfferPlainPayloadSchema = TaskOfferPlainFields.superRefine((payload, ctx) => offerRule(payload, ctx, true));\nexport type TaskOfferPlainPayload = z.infer<typeof TaskOfferPlainPayloadSchema>;\n\n/** server -> daemon: a `task.offer` of a sealed task. */\nexport const TaskOfferSealedPayloadSchema = TaskOfferSealedFields.superRefine((payload, ctx) => {\n offerRule(payload, ctx, false);\n sealedOfferRule(payload, ctx);\n});\nexport type TaskOfferSealedPayload = z.infer<typeof TaskOfferSealedPayloadSchema>;\n\n/**\n * server -> daemon: the one task-opening offer. Both branches are strict, so a\n * field this decoder does not know stops the daemon's cursor (the long-poll\n * treats it like an unknown type) instead of being stripped. The plaintext\n * branch comes first and refuses `sealing`, so a sealed offer always takes the\n * sealed branch; narrow with `payload.sealing !== undefined`.\n */\nexport const TaskOfferPayloadSchema = z.union([\n TaskOfferPlainPayloadSchema as typeof TaskOfferPlainPayloadSchema,\n TaskOfferSealedPayloadSchema as typeof TaskOfferSealedPayloadSchema,\n]);\nexport type TaskOfferPayload = z.infer<typeof TaskOfferPayloadSchema>;\n\nconst EGRESS_SAFE_VALUE = z\n .json()\n .refine(\n (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 256 * 1024,\n 'egress payload exceeds 256KiB',\n );\nconst EGRESS_SESSION_REF = z.string().min(1).max(512);\n\n/** Daemon -> cloud: one durable reliable-lane item, forwarded as the Agent produced it. */\nexport const AgentEgressReliablePayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n policyRevision: AgentEgressPolicyRevisionSchema,\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n payload: EGRESS_SAFE_VALUE,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().nonnegative().max(256 * 1024),\n })\n .strict();\nexport type AgentEgressReliablePayload = z.infer<typeof AgentEgressReliablePayloadSchema>;\n\n/** Cloud -> daemon: exact acknowledgement for one reliable egress record. */\nexport const AgentEgressAckPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n policyRevision: AgentEgressPolicyRevisionSchema,\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n receiptId: z.uuid(),\n })\n .strict();\nexport type AgentEgressAckPayload = z.infer<typeof AgentEgressAckPayloadSchema>;\n\nconst AGENT_MESSAGE_BODY = z.string().min(1).refine(\n (value) => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_MAX_BYTES,\n `Agent message body exceeds ${AGENT_MESSAGE_MAX_BYTES} bytes`,\n);\n\n/** Daemon -> server: one Agent-authored message, independent from task activity. */\n/** Display-only text. Offsets count UTF-8 bytes within one revision. */\nexport const AgentMessageDraftPayloadSchema = z.object({\n agentRef: AgentRefSchema,\n revision: z.number().int().min(1),\n offset: z.number().int().nonnegative(),\n text: z.string().refine(\n value => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,\n `Agent message draft frame exceeds ${AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES} bytes`,\n ),\n overflow: z.literal(true).optional(),\n}).strict();\nexport type AgentMessageDraftPayload = z.infer<typeof AgentMessageDraftPayloadSchema>;\n\n/** The fields of an Agent message that every branch carries in plaintext. */\nconst AGENT_MESSAGE_IDENTITY = {\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n};\n\n/** Daemon -> server: one Agent message in plaintext. */\nexport const AgentMessagePublishPlainPayloadSchema = z\n .object({\n ...AGENT_MESSAGE_IDENTITY,\n contentType: AgentMessageContentTypeSchema,\n body: AGENT_MESSAGE_BODY,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\n ...NO_SEALED_MEMBER,\n })\n .strict()\n .superRefine((value, context) => {\n const actual = new TextEncoder().encode(value.body).byteLength;\n if (actual !== value.byteCount) {\n context.addIssue({ code: 'custom', path: ['byteCount'], message: 'byteCount must equal UTF-8 body bytes' });\n }\n });\nexport type AgentMessagePublishPlainPayload = z.infer<typeof AgentMessagePublishPlainPayloadSchema>;\n\n/**\n * Daemon -> server: one Agent message of a task whose `sealing` lists\n * `agent-message` (#1045 C2). `body` is sealed; `contentHash` and\n * `byteCount` are not carried, and `messageId` and `cursor` name the write in\n * the AAD and the content MAC. Gated on `sealed-payload-v2`.\n */\nexport const AgentMessagePublishSealedPayloadSchema = z\n .object({ ...AGENT_MESSAGE_IDENTITY, contentType: AgentMessageContentTypeSchema, sealed: SealedAgentMessageSchema })\n .strict();\nexport type AgentMessagePublishSealedPayload = z.infer<typeof AgentMessagePublishSealedPayloadSchema>;\n\n/** Narrow with `payload.sealed !== undefined`; the plaintext branch's `sealed` is `never`. */\nexport const AgentMessagePublishPayloadSchema = z.union([\n AgentMessagePublishPlainPayloadSchema as typeof AgentMessagePublishPlainPayloadSchema,\n AgentMessagePublishSealedPayloadSchema as typeof AgentMessagePublishSealedPayloadSchema,\n]);\nexport type AgentMessagePublishPayload = z.infer<typeof AgentMessagePublishPayloadSchema>;\n\nconst AGENT_MESSAGE_DISPOSITION = {\n ...AGENT_MESSAGE_IDENTITY,\n outcome: z.enum(['accepted', 'held', 'refused']),\n receiptId: z.uuid(),\n reasonCode: z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u).optional(),\n};\n\n/** Server -> daemon: the disposition of a plaintext message, naming its `contentHash`. */\nexport const AgentMessageDispositionPlainPayloadSchema = z\n .object({ ...AGENT_MESSAGE_DISPOSITION, contentHash: AgentEgressContentHashSchema, contentMac: z.never().optional() })\n .strict();\nexport type AgentMessageDispositionPlainPayload = z.infer<typeof AgentMessageDispositionPlainPayloadSchema>;\n\n/**\n * Server -> daemon: the disposition of a sealed message (#1045 C2). It names\n * the message by its sealed member's `contentMac`, because the sealed message\n * carries no `contentHash`. Gated on `sealed-payload-v2`.\n */\nexport const AgentMessageDispositionSealedPayloadSchema = z\n .object({\n ...AGENT_MESSAGE_DISPOSITION,\n contentMac: SealedAgentMessageSchema.shape.contentMac,\n contentHash: z.never().optional(),\n })\n .strict();\nexport type AgentMessageDispositionSealedPayload = z.infer<typeof AgentMessageDispositionSealedPayloadSchema>;\n\n/** Narrow with `payload.contentMac !== undefined`. */\nexport const AgentMessageDispositionPayloadSchema = z.union([\n AgentMessageDispositionPlainPayloadSchema as typeof AgentMessageDispositionPlainPayloadSchema,\n AgentMessageDispositionSealedPayloadSchema as typeof AgentMessageDispositionSealedPayloadSchema,\n]);\nexport type AgentMessageDispositionPayload = z.infer<typeof AgentMessageDispositionPayloadSchema>;\n\nconst AGENT_CONTENT_TARGET = z\n .string()\n .min(1)\n .max(1024)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'content target must not contain control characters')\n .refine(\n (value) =>\n !value.startsWith('/') &&\n !value.includes('\\\\') &&\n value.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..'),\n 'content target must be a portable relative path without dot segments',\n );\nconst AGENT_CONTENT_CWD = z\n .string()\n .min(1)\n .max(4096)\n .regex(/^[^\\u0000-\\u001f\\u007f]+$/u, 'cwd must not contain control characters')\n .regex(/^(?:\\/|[A-Za-z]:[\\\\/])/u, 'cwd must be absolute');\n\n/** Server -> daemon: one exact, independently-capability-gated content read. */\nexport const AgentContentReadPayloadSchema = z\n .object({\n requestId: z.uuid(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n policy: ContentReadPolicySchema,\n })\n .strict();\nexport type AgentContentReadPayload = z.infer<typeof AgentContentReadPayloadSchema>;\n\n/** Daemon -> cloud: durable, content-free content-read audit fact. */\nexport const AgentContentReceiptPayloadSchema = z.discriminatedUnion('decision', [\n z\n .object({\n requestId: z.uuid(),\n /** Stable reliable-delivery identity. Content receipts use their requestId. */\n eventId: z.uuid(),\n /** Stable positive cursor allocated by the durable Agent spool. */\n cursor: z.number().int().positive(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n decision: z.literal('allowed'),\n byteCount: z.number().int().nonnegative(),\n contentHash: AgentEgressContentHashSchema,\n blobRef: BlobRefSchema,\n })\n .strict(),\n z\n .object({\n requestId: z.uuid(),\n eventId: z.uuid(),\n cursor: z.number().int().positive(),\n surface: AgentContentReadSurfaceSchema,\n actor: AgentContentActorSchema,\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n runtime: RuntimeIdSchema,\n cwd: AGENT_CONTENT_CWD,\n policyRevision: AgentEgressPolicyRevisionSchema,\n target: AGENT_CONTENT_TARGET,\n mimeType: AgentContentMimeTypeSchema,\n decodeAs: AgentContentDecodeAsSchema,\n decision: z.literal('denied'),\n byteCount: z.literal(0),\n /** Open (#1121): a well-formed reason this version does not know is accepted and kept verbatim. */\n reason: z.union([AgentContentReadDenialReasonSchema, unrecognizedToken(AgentContentReadDenialReasonSchema.options)]),\n })\n .strict(),\n]).superRefine((value, ctx) => {\n if (value.decision !== 'allowed') return;\n if (value.blobRef.size !== value.byteCount) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'size'], message: 'blobRef size must equal byteCount' });\n }\n if (value.blobRef.contentHash !== value.contentHash) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'contentHash'], message: 'blobRef contentHash must equal contentHash' });\n }\n if (value.blobRef.contentType !== value.mimeType) {\n ctx.addIssue({ code: 'custom', path: ['blobRef', 'contentType'], message: 'blobRef contentType must equal mimeType' });\n }\n});\nexport type AgentContentReceiptPayload = z.infer<typeof AgentContentReceiptPayloadSchema>;\n\n/**\n * Server -> daemon: one task-free exact-device Agent-home projection.\n *\n * `agentRef.profileRevision` is the projection contract's canonical comparable\n * revision. It is validated without interpreting the opaque product\n * projection, whose fields are never inspected for product semantics.\n */\nexport const AgentHomeProjectionPayloadSchema = z\n .object({\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n projection: AgentHomeProjectionValueSchema,\n })\n .strict();\nexport type AgentHomeProjectionPayload = z.infer<typeof AgentHomeProjectionPayloadSchema>;\n\n/**\n * Server -> daemon: a Host-approved Agent memory intent is waiting for this\n * device (capability `agent-memory-intent.v1`, see `agent-memory-intent.ts`).\n *\n * `.strict()` and exactly two fields. There is deliberately no path, operation,\n * revision or content: the device fetches the immutable intent from the Host\n * under its own device authentication, so a mailbox row or journal line never\n * holds memory content. `agentRef` routes the home lease and the local ledger\n * and must equal the fetched intent's `agentRef`.\n */\nexport const AgentMemoryIntentAvailablePayloadSchema = z\n .object({\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n })\n .strict();\nexport type AgentMemoryIntentAvailablePayload = z.infer<typeof AgentMemoryIntentAvailablePayloadSchema>;\n\n/**\n * The inlined form of `agent.input.preparation`'s authorized context document.\n *\n * Bounded by the SAME `MAX_INLINE_BYTES` (64 KiB) every other inlined artifact\n * on this wire is bounded by — there is no preparation-specific enlargement.\n * Anything larger uses the blob-ref form below, exactly the way a large task\n * instruction does; it is never implicitly chunked.\n */\nconst InputPreparationInlineContextSchema = z\n .object({\n inline: z\n .string()\n .refine(isWithinInlineByteLimit, `inline context must not exceed ${MAX_INLINE_BYTES} UTF-8 bytes`),\n })\n .strict();\n\n/**\n * The out-of-band form. `contentHash` is stated a second time next to the\n * `BlobRef` on purpose and must equal it: the device verifies the DECODED\n * bytes against this field, so a blob store that serves different bytes under\n * the same id is caught locally rather than compiled.\n */\nconst InputPreparationBlobContextSchema = z\n .object({ blobRef: BlobRefSchema, contentHash: InputPreparationContentHashSchema })\n .strict()\n .superRefine((value, ctx) => {\n if (value.blobRef.contentHash !== value.contentHash) {\n ctx.addIssue({\n code: 'custom',\n path: ['blobRef', 'contentHash'],\n message: 'blobRef contentHash must equal contentHash',\n });\n }\n });\n\n/**\n * Server -> daemon: one task-free, exact-device remote input preparation.\n *\n * Distinct message type rather than an optional field on an existing one, for\n * the same N/N-1 reason the Agent offers are: an optional field could be\n * legally STRIPPED by a daemon that predates this contract, which would then\n * answer as though a preparation it never performed had somehow been handled.\n * An unknown type (`parseMessage` -> `UnknownMessageTypeError`) is not skipped\n * cleanly either: on long-poll it freezes the cursor, so the enqueue capability\n * gate is the compatibility boundary.\n *\n * What is deliberately NOT here (§17 B): `tools`, `toolExecutors`, runtime or\n * compiler identity, `tenantId` and `deviceId`. The first three are local\n * observations; the last two come from the device's own authenticated record,\n * never from the payload — a sender that could name them could redirect a\n * preparation's binding to a device it does not own.\n *\n * `deadlineAt` may only ever be TIGHTENED locally: the device clamps to\n * `min(deadlineAt - now, limits.preparationDeadlineMs)`, so a generous Host\n * deadline cannot enlarge a configured local bound.\n */\nexport const AgentInputPreparationPayloadSchema = z\n .object({\n agentMemory: PreparedAgentMemoryModeSchema,\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n source: InputPreparationSourceSchema,\n selection: InputPreparationSelectionSchema,\n deadlineAt: z.iso.datetime({ offset: true }),\n context: z.union([InputPreparationInlineContextSchema, InputPreparationBlobContextSchema]),\n requiredToolsets: z.array(ToolsetIdSchema).max(16).superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, 'required')),\n /**\n * The Host's accounting ruling for this preparation, carried verbatim onto\n * the receipt's binding. Optional and defaulted NOWHERE: a payload that\n * omits it produces a receipt that says `accounting_policy_missing`, which\n * is the honest answer — the device rules on no residual key by itself.\n */\n accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional(),\n })\n .strict();\nexport type AgentInputPreparationPayload = z.infer<typeof AgentInputPreparationPayloadSchema>;\n\n/**\n * server -> daemon: approve a pending `task.await_approval` request.\n *\n * Semantics (M1 gap #3): the server's own state is authoritative on its own\n * action — calling the server-side `approve()` API moves the task record\n * `AwaitApproval -> Running` immediately. This wire message is a best-effort\n * *notification* telling the daemon to resume the paused runtime session; the\n * daemon does not send a dedicated ack. Its outcome is observable through the\n * task's existing message stream (e.g. `task.progress` resuming, or\n * `task.fail`/`task.cancelled` if resuming turns out to be impossible) — no\n * new ack message type is introduced. See docs/protocol.md \"Approval flow\".\n *\n * `approvalId` (required since v4): the SPECIFIC pending approval this\n * decision resolves. The daemon compares it against its own\n * currently-dispatched approval id (`ActiveTask.pendingApprovalId`,\n * `packages/client`'s `task-runner.ts`) and treats a mismatch as a stale,\n * audit-only no-op, so a late decision never lands on the task's next\n * approval — see `TaskRunner.handleApprove`.\n */\nexport const TaskApprovePayloadSchema = z.object({\n approvalId: z.string().min(1),\n});\nexport type TaskApprovePayload = z.infer<typeof TaskApprovePayloadSchema>;\n\n/**\n * server -> daemon: reject a pending `task.await_approval` request.\n *\n * Same best-effort-notification semantics as `task.approve` (M1 gap #3): the\n * server moves its own record `AwaitApproval -> Failed` immediately; this\n * message just tells the daemon to stop, and the daemon reports the outcome\n * via its existing `task.fail` terminal message.\n *\n * `approvalId` (required since v4): same targeting as\n * `TaskApprovePayloadSchema.approvalId` above, applied to the reject path\n * (`TaskRunner.handleReject`).\n */\nexport const TaskRejectPayloadSchema = z.object({\n reason: z.string().optional(),\n approvalId: z.string().min(1),\n});\nexport type TaskRejectPayload = z.infer<typeof TaskRejectPayloadSchema>;\n\n/**\n * server -> daemon: cancel a task in any non-terminal state.\n *\n * Same best-effort-notification semantics (M1 gap #3): the server moves its\n * own record to `Cancelled` immediately on its own action and does not wait\n * for a daemon ack; this message just tells the daemon to stop local work.\n * The daemon reports the outcome via the explicit `task.cancelled` terminal\n * message (M1 gap #6) — not `task.fail`.\n */\nexport const TaskCancelPayloadSchema = z.object({\n reason: z.string().optional(),\n});\nexport type TaskCancelPayload = z.infer<typeof TaskCancelPayloadSchema>;\n\n/** server -> daemon: inject steering text into a running task. */\nconst TaskSteerPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n text: z.string(),\n});\n\n// ---------------------------------------------------------------------------\n// daemon -> server: task.*\n//\n// Every type in this section carries a *required* envelope `task_id` (M1 gap\n// #1 — these all route by task id). Envelope `seq` (the redelivery cursor)\n// stays optional in this direction: M1 only specifies at-least-once\n// server->daemon redelivery, not a daemon->server one (see\n// docs/protocol.md).\n// ---------------------------------------------------------------------------\n\n/** Maximum offer admission duration, and of each phase in it (seven days). */\nexport const OFFER_ADMISSION_MAX_DURATION_MS = 604_800_000;\nconst OfferAdmissionDurationSchema = z.number().int().nonnegative().max(OFFER_ADMISSION_MAX_DURATION_MS);\n/**\n * #1014: how long this device spent admitting an offer, in milliseconds of its\n * monotonic clock, from receiving the offer to sending the claim or decline\n * that ends admission. A phase is present only when it ran; the time no phase\n * names is `totalMs` minus their sum.\n */\nexport const OfferAdmissionTimingsSchema = z.object({\n totalMs: OfferAdmissionDurationSchema,\n agentHomeWaitMs: OfferAdmissionDurationSchema.optional(),\n messageHelperPreflightMs: OfferAdmissionDurationSchema.optional(),\n resultHelperPreflightMs: OfferAdmissionDurationSchema.optional(),\n toolsetProbeMs: OfferAdmissionDurationSchema.optional(),\n runtimeLaunchMs: OfferAdmissionDurationSchema.optional(),\n}).strict();\nexport type OfferAdmissionTimings = z.infer<typeof OfferAdmissionTimingsSchema>;\n\n/**\n * daemon -> server: claim an offered task (idempotent CAS on the server\n * side). `taskId` used to be duplicated here; it is now carried only by the\n * envelope's `task_id` (M1 gap #7).\n *\n * Claiming no longer implies the task is `Running` (M1 gap #2) — see\n * `task.started`.\n *\n * `runtime` (M5, additive-minor — docs/protocol.md §3.1): the ACTUAL\n * adapter this device selected for the task, distinct from the offer's\n * own `runtime` (the merely REQUESTED one, `TaskOfferPayloadSchema`'s `runtime`\n * above). When an offer names no runtime the daemon auto-selects (pi-first —\n * `TaskRunner.pickAdapter`, `packages/client`'s `task-runner.ts`), and before\n * this field existed the server had no way to learn which adapter actually\n * ran — `TaskSnapshot.runtime` (`packages/server`'s `types.ts`) only ever\n * recorded what was requested. Plain optional property on this already-\n * tolerant `z.object()`: an old server simply never reads it, so this needed\n * no version bump and no emission gating — a new daemon sends it\n * unconditionally, regardless of whether the connected server is new enough\n * to store it.\n *\n * `capabilities` (S0/D-4, additive-minor — docs/protocol.md §2.4): the\n * TASK-level capability authority — what the claiming adapter reported about\n * itself at the moment it took this task, reusing `RuntimeCapabilitiesSchema`\n * (above) rather than introducing a second capability shape. Same source of\n * truth as `conn.hello.runtimes[].capabilities`, different scope: `conn.hello`\n * is CONNECTION-level discovery (\"what could this device run\"), which no\n * server-side task control decision may read, because it describes a device,\n * not the adapter that claimed this task. This field is task-shaped: it shares a lifecycle with\n * the task↔runtime binding the claim itself establishes, so a control gate\n * (`steerTask()`, `packages/server`'s `hub.ts`) can key off it and stay\n * correct across reconnects, adapter-set changes, and transports. Plain\n * optional property on this already-tolerant `z.object()`, exactly like\n * `runtime` above: an old daemon simply omits it, and a consumer that gates on\n * it must fail closed on absence rather than assume a default.\n */\nexport const TaskClaimPayloadSchema = z.object({\n deviceId: z.string(),\n agentId: z.string().optional(),\n agentRef: AgentRefSchema.optional(),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n capabilities: RuntimeCapabilitiesSchema.optional(),\n admission: OfferAdmissionTimingsSchema.optional(),\n});\nexport type TaskClaimPayload = z.infer<typeof TaskClaimPayloadSchema>;\n\n/**\n * daemon -> server: explicit `Claimed -> Running` transition (M1 gap #2).\n * A `task.claim` no longer implies the task started running; the daemon\n * sends this once it has actually started the runtime session for the task.\n */\nexport const TaskStartedPayloadSchema = z.object({});\nexport type TaskStartedPayload = z.infer<typeof TaskStartedPayloadSchema>;\n\n/**\n * daemon -> server: decline an offer *before* claiming it (M1 gap #5) — e.g.\n * no compatible/available runtime. Fail-closed rejections must use this instead of silently\n * dropping the offer.\n *\n * Decision (see docs/protocol.md \"Declined vs. Failed\" for the full\n * writeup): declining does *not* introduce a new `Declined` terminal state.\n * It maps onto the existing `Failed` state via a new `Offered -> Failed`\n * transition. `reason`/`retryable` intentionally mirror `TaskFailPayload`\n * semantics, because a pre-claim decline and a post-claim failure are the same\n * outcome from the dispatcher's point of view (this attempt produced no\n * result; here's whether retrying — e.g. offering to a different device —\n * makes sense), and keeping the state machine minimal avoids forking every\n * terminal-state consumer into \"Failed or Declined, handle both\".\n */\nconst HOME_DECLINE_CODES = ['agent_home_writer_busy', 'agent_home_reader_busy'] as const;\nconst DECLINE_CODES = [...HOME_DECLINE_CODES, ...SEALED_DECLINE_CODES] as const;\nexport type TaskDeclineCode = (typeof DECLINE_CODES)[number];\n/**\n * The decline code is open (#1121): a well-formed code this version does not\n * know is accepted and kept verbatim, so the decline is still recorded.\n * {@link readDeclineCode} is the typed reading.\n */\n/**\n * The typed reason a runtime was unavailable before claim (#1103 D6).\n * Append-only: an unknown well-formed cause is accepted and kept verbatim\n * (#1121), and {@link readRuntimeUnavailableCause} is the typed reading. The\n * login-shell capture code travels only with `environment_unavailable`\n * (#1095); it is an open well-formed token so the protocol never owns the\n * client's closed environment-code list.\n */\nconst RuntimeUnavailableSchema = z.object({\n cause: RuntimeUnavailableCauseSchema,\n code: openVocabularyToken().optional(),\n}).refine((value) => value.code === undefined || value.cause === 'environment_unavailable', {\n message: 'only environment_unavailable carries an environment code',\n});\n\nconst DeclineFields = z.object({\n ...NO_SEALED_MEMBER,\n reason: z.string(),\n retryable: z.boolean().optional(),\n agentRef: AgentRefSchema.optional(),\n code: z.union([z.enum(DECLINE_CODES), unrecognizedToken(DECLINE_CODES)]).optional(),\n runtimeUnavailable: RuntimeUnavailableSchema.optional(),\n admission: OfferAdmissionTimingsSchema.optional(),\n});\n\n/** A decline code as this version understands it: one it does not know reads as `unknown`, its raw token kept. */\nexport type TaskDeclineCodeReading =\n | { readonly code: TaskDeclineCode }\n | { readonly code: 'unknown'; readonly reportedCode: string };\n\nexport function readDeclineCode(code: string): TaskDeclineCodeReading {\n return (DECLINE_CODES as readonly string[]).includes(code)\n ? { code: code as TaskDeclineCode }\n : { code: 'unknown', reportedCode: code };\n}\n/**\n * #654: a sealed decline code names a fixed, non-retryable outcome and\n * carries no content, so its `reason` is the code itself. A free-text reason\n * or `retryable: true` never goes with it.\n */\nconst TaskDeclinePlainPayloadSchema = DeclineFields.refine(\n (p) => !(SEALED_DECLINE_CODES as readonly unknown[]).includes(p.code) || (p.reason === p.code && p.retryable !== true),\n { message: 'a sealed code needs reason === code, not retryable' },\n);\n\n/**\n * daemon -> server: batch of normalized agent events.\n *\n * `events` elements are known-or-unknown (`AgentEventOrUnknownSchema` —\n * `agent-event.ts`), not bare `AgentEventSchema`: pre-freeze, an unrecognized\n * event `type` must not fail the whole batch, since a peer running a newer\n * minor version may have emitted an additive event variant this schema\n * doesn't know about yet. See `agent-event.ts` for the full rationale and\n * `partitionAgentEvents`/`isKnownAgentEvent` for how consumers should skip\n * unknowns instead of choking on them.\n */\nconst TaskProgressPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n seq: z.number().int(),\n events: z.array(AgentEventOrUnknownSchema),\n});\n\n/** daemon -> server: an artifact produced by the task, inline or by blob ref. */\nconst TaskArtifactPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n name: z.string(),\n contentType: z.string(),\n inline: z\n .string()\n .refine(isWithinInlineByteLimit, {\n message: 'inline artifact payload exceeds 64KB limit',\n })\n .optional(),\n blobRef: BlobRefSchema.optional(),\n});\n\n/**\n * daemon -> server: task is blocked on an out-of-band approval.\n *\n * `approvalId` (required since v4): the daemon's own locally-generated\n * identity for THIS SPECIFIC pending approval (`ApprovalRegistry`,\n * `packages/client`'s `approvals.ts`). The server echoes it on the\n * `task.approve`/`task.reject` that decides this approval.\n */\nconst TaskAwaitApprovalPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n summary: z.string(),\n approvalId: z.string().min(1),\n});\n\n/**\n * Hard cap (1 MiB) on a single `task.complete.document` (see\n * {@link TaskCompletePayloadSchema}), measured as the UTF-8 byte length of\n * its canonical JSON encoding — NOT as a node/key count, since a document is\n * schema-neutral and its object shape is unbounded by design.\n *\n * The cap is a REJECT-AT-BOUNDARY limit on both sides: a daemon that\n * produces an over-cap document reports `task.fail` instead of sending it,\n * and a server rejects an over-cap document at schema validation. It is\n * never truncated — a truncated JSON document is not valid JSON, so\n * \"shrinking to fit\" can only hand the consumer garbage.\n *\n * 1 MiB is the conservative ceiling declared by the first real consumer\n * (`docs/researches/2026-08-12-salesko-consumption-evidence.md` §1/§2:\n * smallest real frame 8.4 KiB, typical 48-96 KiB, 512 KiB comfortable).\n * Producers should stay at or under ~512 KiB (docs/protocol.md); the extra\n * headroom exists because raising a protocol cap later is additive while\n * lowering one is breaking. A result too big for this channel belongs in\n * `artifactRefs` (the multi-file/binary/oversized channel), not here.\n */\nexport const RESULT_DOCUMENT_MAX_BYTES = 1_048_576;\n\n/**\n * Outcome of {@link checkResultDocument}.\n *\n * `bytes` is the measured canonical JSON UTF-8 byte length, present on both\n * the accept and the over-cap rejection so a caller can name the actual size\n * in a failure reason. `canonical` is the CANONICAL SNAPSHOT — the value a\n * sender must actually put on the wire; see {@link checkResultDocument}.\n */\nexport type ResultDocumentCheck = PlainJsonCheck;\n\n/**\n * THE single authority for \"is this a legal `task.complete.document`\", and\n * the one place its canonical form is produced. `TaskCompletePayloadSchema`'s\n * own refinement calls it, and the daemon-side pre-send gate\n * (`packages/client`'s `task-runner.ts`) imports and calls the exact same\n * function rather than re-deriving any part of it: a daemon that measured or\n * judged a document even slightly differently from the server that validates\n * it would either reject documents the wire would have accepted, or hand the\n * server a payload it is about to reject after the runtime session already\n * ended.\n *\n * **The contract is: a document must be PLAIN JSON DATA.** Not \"an object\n * that happens to survive `JSON.stringify`\" — that bar is far too low, and\n * two concrete attacks/mistakes live under it:\n *\n * 1. `JSON.stringify` succeeding does not mean the value was preserved. An\n * `undefined`-valued key, a `NaN`, a function-valued property, or a\n * `Date` all serialize \"successfully\" while silently becoming something\n * else (dropped, `null`, or a string). The result is a well-formed,\n * under-cap document that is not what the producer had — a confidently\n * wrong terminal result, the worst outcome this channel has.\n * 2. `toJSON(key)` receives the property key it is being serialized under,\n * so an object can legally answer one way at the root (`key === ''`,\n * where this function measures it) and a completely different way when\n * nested inside the envelope payload (`key === 'document'`, where the\n * codec actually serializes it). A root-only measurement is therefore\n * not a bound on what goes on the wire at all. The same hole exists for\n * any getter that answers differently on a second read.\n *\n * Both die together via the same mechanism. The steps:\n *\n * 1. `JSON.stringify` must succeed and not return `undefined`.\n * 2. Its UTF-8 byte length must be within {@link RESULT_DOCUMENT_MAX_BYTES}.\n * 3. `JSON.parse` that string — the CANONICAL SNAPSHOT. It is pure data:\n * no `toJSON`, no getters, no prototype, nothing left that can answer\n * differently a second time.\n * 4. The original must be structurally equal to the snapshot\n * (`isSameJsonData`, `plain-json.ts`). Any mismatch means the value was not plain\n * JSON data, and it is rejected rather than silently transformed.\n *\n * On success the snapshot is returned as `canonical`, and **every sender\n * must put THAT on the wire, never the original reference** — which is what\n * closes the contextual-`toJSON`/unstable-getter hole for good: pure data\n * serializes identically at the root and nested, so what was measured is\n * necessarily what is sent. The check is idempotent on pure data, so the\n * server re-running it on an already-parsed payload is a no-op that always\n * agrees.\n */\nexport function checkResultDocument(document: unknown): ResultDocumentCheck {\n return canonicalizePlainJson(document, RESULT_DOCUMENT_MAX_BYTES);\n}\n\n/** Maximum provider-reported prompt or completion token count retained in one terminal observation. */\nexport const TERMINAL_INFERENCE_USAGE_MAX_TOKENS = 1_000_000_000;\n/** Maximum device-observed elapsed duration retained in one terminal observation (seven days). */\nexport const TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS = 604_800_000;\nexport const TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH = 160;\nexport const TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH = 128;\n\nconst TerminalInferenceUsageNumberSchema = z\n .number()\n .int()\n .safe()\n .nonnegative()\n .max(TERMINAL_INFERENCE_USAGE_MAX_TOKENS);\n\nconst TerminalInferenceUsageDurationSchema = z\n .number()\n .int()\n .safe()\n .nonnegative()\n .max(TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS);\n\n/** Canonical device observation time: an ISO-8601 UTC instant with milliseconds. */\nconst TerminalInferenceReportedAtSchema = z\n .iso\n .datetime({ offset: true, precision: 3 })\n .refine((value) => value.endsWith('Z'), 'reportedAt must be canonical UTC (Z)');\n\n/**\n * A bounded, non-billing observation associated with one terminal runtime\n * outcome. It is optional on every terminal payload so a pre-U2 daemon remains\n * a legal v1 peer. `promptTokens` and `completionTokens` are values a runtime\n * reported for its final observed turn; they are not a storage-accounting or\n * invoice authority.\n */\nexport const TerminalInferenceUsageSchema = z.object({\n /** The adapter that actually started this task, never a requested fallback. */\n runtime: RuntimeIdSchema,\n /** Omitted unless the adapter itself exposed this provider observation. */\n provider: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH).optional(),\n /** Omitted unless the adapter itself exposed this model observation. */\n model: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),\n /** Direct projection of the runtime's final observed input token count. */\n promptTokens: TerminalInferenceUsageNumberSchema.optional(),\n /** Direct projection of the runtime's final observed output token count. */\n completionTokens: TerminalInferenceUsageNumberSchema.optional(),\n /** Device-observed elapsed duration for the started task. */\n durationMs: TerminalInferenceUsageDurationSchema.optional(),\n /** Process-immutable Local Agent release version, owned outside the protocol. */\n clientVersion: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH),\n /** Device observation time, never server receipt time. */\n reportedAt: TerminalInferenceReportedAtSchema,\n});\nexport type TerminalInferenceUsage = z.infer<typeof TerminalInferenceUsageSchema>;\n\n/**\n * The prepared-only terminal observation: what the runtime reported about the\n * provider calls of ONE prepared Execution, bound to the frozen request it\n * launched.\n *\n * - `requestDigest` — the frozen artifact's own request digest\n * (`InputPreparationArtifactSummarySchema.requestDigest`), so the Host\n * compares these numbers against exactly the D whose `requestBytes` it\n * ruled on.\n * - `initialPromptTokens` — the prompt tokens of the FIRST provider call. It\n * is the only call whose request is D; every later call is an ordinary tool\n * continuation. Prompt tokens are the provider's whole prompt, cache reads\n * and writes included.\n * - `maxPromptTokens` — the largest prompt of any provider call of the\n * Execution, so `maxPromptTokens >= initialPromptTokens`.\n *\n * A separate field, deliberately NOT {@link TerminalInferenceUsageSchema}:\n * that one is telemetry and never task-state authority, while this one is the\n * evidence a Host checks its own budget ruling against. The device performs no\n * budget arithmetic over it. Strict, like every other control shape: an\n * unrecognized field is rejected, not stripped.\n */\nexport const TerminalPreparedObservationSchema = z\n .object({\n requestDigest: InputPreparationArtifactSummarySchema.shape.requestDigest,\n initialPromptTokens: TerminalInferenceUsageNumberSchema,\n maxPromptTokens: TerminalInferenceUsageNumberSchema,\n })\n .strict()\n .refine((value) => value.maxPromptTokens >= value.initialPromptTokens, {\n message: 'maxPromptTokens must not be below initialPromptTokens',\n path: ['maxPromptTokens'],\n });\nexport type TerminalPreparedObservation = z.infer<typeof TerminalPreparedObservationSchema>;\n\n/**\n * The task-free Agent-home projection (`agent.home_projection`) that the\n * device had already applied when an Agent Attempt started. The writer lease\n * keeps a new projection out of the home until the Attempt ends, so this is\n * the persona the Attempt ran with. The SDK does not compare it with the\n * offer's `agentRef.profileRevision`: the host decides whether a mismatch\n * matters. Absent when the task was not Agent-bound, or when the home had no\n * applied projection record.\n */\nexport const TerminalAgentHomeProjectionSchema = z\n .object({\n profileRevision: AgentHomeProjectionProfileRevisionSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n })\n .strict();\nexport type TerminalAgentHomeProjection = z.infer<typeof TerminalAgentHomeProjectionSchema>;\n\n/** Maximum memory files one reader digest covers: `MEMORY.md` plus every entry under `notes/`. */\nexport const AGENT_HOME_MEMORY_DIGEST_MAX_FILES = 256;\n/** Maximum bytes of memory files one reader digest reads. */\nexport const AGENT_HOME_MEMORY_DIGEST_MAX_BYTES = 16 * 1024 * 1024;\n/** Maximum length of one changed memory path, relative to the Agent home. */\nexport const AGENT_HOME_MEMORY_PATH_MAX_LENGTH = 1024;\n\nconst AgentHomeMemoryChangedPathsSchema = z\n .array(z.string().min(1).max(AGENT_HOME_MEMORY_PATH_MAX_LENGTH).regex(/^[^\\u0000]+$/u))\n .min(1)\n // A path can leave one digest and another can enter the other one.\n .max(AGENT_HOME_MEMORY_DIGEST_MAX_FILES * 2);\n\n/**\n * Memory-change evidence of one `memory-reader` Attempt. The device hashes\n * `MEMORY.md` and every file under `notes/` when the reader starts and again\n * at its terminal, and compares the two digests.\n *\n * - `unchanged`: the digests are equal.\n * - `reader-attributed`: the digests differ and no writer Attempt of the home\n * overlapped this reader. A reader Attempt changed memory: this one, or\n * another reader that overlapped it.\n * - `unattributed`: the digests differ and a writer Attempt overlapped this\n * reader, so the change has no single source.\n * - `unmeasured`: the digest bound was exceeded, or a read failed.\n *\n * `paths` lists the changed files relative to the home, with `/` separators.\n * The device sees only Attempts it runs; a host that writes memory files\n * itself while readers run makes the attribution ambiguous. Absent on writer\n * terminals and on a claimed failure before the Attempt became active.\n */\nexport const TerminalAgentHomeMemoryChangeSchema = z.discriminatedUnion('outcome', [\n z.object({ outcome: z.literal('unchanged') }).strict(),\n z.object({ outcome: z.literal('reader-attributed'), paths: AgentHomeMemoryChangedPathsSchema }).strict(),\n z.object({ outcome: z.literal('unattributed'), paths: AgentHomeMemoryChangedPathsSchema }).strict(),\n z.object({ outcome: z.literal('unmeasured') }).strict(),\n]);\nexport type TerminalAgentHomeMemoryChange = z.infer<typeof TerminalAgentHomeMemoryChangeSchema>;\n\n/**\n * daemon -> server: task finished successfully.\n *\n * `document` (docs/protocol.md §7.2): the OPTIONAL\n * structured terminal result of the task — one JSON value the product on the\n * other side consumes as the task's actual output, as opposed to `summary`\n * (human-readable prose) or `artifactRefs` (files). Deliberately\n * `z.unknown()`: this SDK never understands, validates, or transforms the\n * product's own document schema — that validation belongs to the consumer.\n * The only constraints the wire imposes are the ones\n * {@link checkResultDocument} enforces: it must be PLAIN JSON DATA (equal to\n * its own JSON round trip — see that function for why \"stringify succeeded\"\n * is not enough), and its canonical JSON UTF-8 encoding must be at most\n * {@link RESULT_DOCUMENT_MAX_BYTES}. An over-cap document is REJECTED here,\n * never truncated (see that constant's own doc comment). A sender puts the\n * check's `canonical` snapshot on the wire, never the original object.\n *\n * Wire v3: every v3 server keeps this field, so no capability flag gates it\n * (the v2 `result-document` flag is gone). For a\n * `terminalProjection.mode: 'result-document'` offer it carries the outcome\n * the daemon validated against the offer's frozen schema\n * (`validateResultOutcome`, `result-schema.ts`, at most\n * `RESULT_OUTCOME_MAX_BYTES`).\n */\nconst TaskCompletePlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n harnessId: HarnessIdSchema.optional(),\n summary: z.string(),\n /**\n * The runtime's closing reply: the assistant text after the last tool\n * interaction, or the last whole message for a runtime whose `progress`\n * events are whole messages (Codex). `summary` keeps the whole run's text,\n * so a host reads the final answer here without parsing commentary out of\n * it. Absent when the run ended with no closing text. An older server strips\n * this optional field; the host then sees it absent and keeps `summary`.\n */\n finalMessage: z.string().optional(),\n sessionRef: z.string(),\n artifactRefs: z.array(BlobRefSchema).optional(),\n document: z\n .unknown()\n .optional()\n .refine((value) => value === undefined || checkResultDocument(value).ok, {\n message: `task.complete.document must be plain JSON data (equal to its own JSON round trip) and at most ${RESULT_DOCUMENT_MAX_BYTES} bytes as canonical JSON (UTF-8)`,\n }),\n usage: TerminalInferenceUsageSchema.optional(),\n /** Present on a prepared Execution only — see {@link TerminalPreparedObservationSchema}. */\n preparedObservation: TerminalPreparedObservationSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/** A runtime failure class this version knows (#869). `unknown` means the runtime gave no structured evidence. */\nexport const RuntimeFailureClassSchema = z.enum(RUNTIME_FAILURE_CLASSES);\nexport type RuntimeFailureClass = z.infer<typeof RuntimeFailureClassSchema>;\n\n/** Whether a `quota` limit covers the whole account or one model (#1271). */\nexport const RuntimeQuotaScopeSchema = z.enum(RUNTIME_QUOTA_SCOPES);\nexport type RuntimeQuotaScope = z.infer<typeof RuntimeQuotaScopeSchema>;\n\n/**\n * The machine-readable failure of a `task.fail` (#869); `reason` stays display\n * text. `resetsAt` (ISO 8601 UTC) and `scope` exist only on `quota`, and only\n * when the runtime reported them. `scope` is gated on the server's\n * `runtime-quota-scope` flag (#1271).\n *\n * The class is open (#1121): a well-formed class this version does not know,\n * with whatever fields a newer device put beside it, is accepted and kept\n * verbatim, so the terminal is still recorded. {@link readTaskFailure} is the\n * typed reading.\n */\nexport const TaskFailureSchema = z.union([\n z.object({ class: z.literal('quota'), resetsAt: z.iso.datetime().optional(), scope: RuntimeQuotaScopeSchema.optional() }).strict(),\n z.object({ class: RuntimeFailureClassSchema.exclude(['quota']) }).strict(),\n z.looseObject({ class: unrecognizedToken(RUNTIME_FAILURE_CLASSES) }),\n]);\nexport type TaskFailure = z.infer<typeof TaskFailureSchema>;\n\n/** A {@link TaskFailure} as this version understands it: a class it does not know reads as `unknown`, its raw token kept. */\nexport type TaskFailureReading =\n | { readonly class: 'quota'; readonly resetsAt?: string; readonly scope?: RuntimeQuotaScope }\n | { readonly class: Exclude<RuntimeFailureClass, 'quota' | 'unknown'> }\n | { readonly class: 'unknown'; readonly reportedClass?: string };\n\nexport function readTaskFailure(failure: TaskFailure): TaskFailureReading {\n if ((RUNTIME_FAILURE_CLASSES as readonly string[]).includes(failure.class)) return failure as TaskFailureReading;\n return { class: 'unknown', reportedClass: failure.class };\n}\n\n/** daemon -> server: task failed. */\nconst TaskFailPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n /** Local interruption observation bound to the immutable offer; does not assert a cloud claim. */\n recovery: z.object({ kind: z.literal('daemon_interrupted'), offerId: z.uuid() }).strict().optional(),\n harnessId: HarnessIdSchema.optional(),\n /**\n * Display text, bounded by `boundFailureReason` on every parse (#1124):\n * credentials redacted, at most `TASK_FAIL_REASON_MAX_BYTES` UTF-8 bytes.\n * `createEnvelope` and every decode apply it, so one place bounds every\n * sender and receiver. A longer reason is truncated, never refused.\n */\n reason: z.string().transform(boundFailureReason),\n retryable: z.boolean().optional(),\n /** Gated on the server's `runtime-failure-class` flag. Plaintext on the sealed branch too. */\n failure: TaskFailureSchema.optional(),\n usage: TerminalInferenceUsageSchema.optional(),\n /** Present on a prepared Execution that observed provider usage before failing. */\n preparedObservation: TerminalPreparedObservationSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/**\n * daemon -> server: task ended in the `Cancelled` state (M1 gap #6) — either\n * in response to a server-sent `task.cancel`, or a cancellation the daemon\n * observed/decided locally (e.g. a local stop action) that the server didn't\n * initiate. This is the canonical way to report a `Cancelled` outcome; it\n * supersedes the M0 convention of `task.fail({ reason: 'cancelled' })`.\n *\n * This is deliberately its own message rather than folded into `task.fail`\n * (decision: prefer the explicit message — see docs/protocol.md) because\n * `Cancelled` is semantically distinct from `Failed`: one is an intentional\n * stop, the other an error. Overloading `task.fail` with a magic\n * `reason: 'cancelled'` string convention hid that distinction on the wire.\n *\n * Dual-purpose on receipt: if the server already moved its own record to\n * `Cancelled` (it initiated the cancel — M1 gap #3's \"server state is\n * authoritative\" rule), this is an idempotent no-op ack. If the server\n * hasn't yet (a locally-observed cancellation), this is the authoritative\n * trigger that moves `Claimed`/`Running`/`AwaitApproval -> Cancelled`.\n */\nconst TaskCancelledPlainPayloadSchema = z.object({\n ...NO_SEALED_MEMBER,\n harnessId: HarnessIdSchema.optional(),\n reason: z.string().optional(),\n usage: TerminalInferenceUsageSchema.optional(),\n agentRef: AgentRefSchema.optional(),\n agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),\n agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional(),\n});\n\n/**\n * daemon -> server: a pending `task.await_approval` was resolved entirely\n * LOCALLY on the device — the local control-socket `approvals.resolve` RPC,\n * a fail-closed `requestApproval` timeout, or a fail-closed eviction/finish\n * rejection (see `packages/client`'s `task-runner.ts`/`approvals.ts`) —\n * *without* a wire `task.approve`/`task.reject` ever having been exchanged\n * for it. Baseline since v4: the daemon reports every local resolution, and\n * this report is the server's only source for one; the server does not infer\n * a resolution from later task activity.\n *\n * Observability-class tolerance applies (not control/security — see the\n * freeze rule's asymmetry, `docs/protocol.md`): this is a daemon reporting\n * what it already did locally, not a payload that grants/denies anything on\n * its own — the receiving server's own state machine (`TASK_TRANSITIONS`,\n * `task-state.ts`) is still what decides whether the reported resolution is\n * legal to apply. Plain `z.object()` (not `.strict()`), same as every other\n * non-control payload in this file.\n *\n * `resolvedBy` is a single-value enum (`'local'`) rather than a bare string:\n * a later wave could add a DISTINCT value as a gated addition, while the\n * shape stays closed and typed today.\n */\nexport const TaskApprovalResolvedPayloadSchema = z.object({\n approvalId: z.string(),\n decision: z.enum(['approve', 'reject']),\n resolvedBy: z.enum(['local']),\n at: z.iso.datetime({ offset: true }),\n});\nexport type TaskApprovalResolvedPayload = z.infer<typeof TaskApprovalResolvedPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// Sealed payload v1 (#654): the sealed branch of each sealable type\n//\n// A sealable type's payload is a union: the plaintext branch (which refuses\n// `sealed` and `sealing`) and a strict sealed branch. The sealed branch is the\n// plaintext fields without the ones `SEALED_SPLIT_TABLE` moves into the\n// ciphertext or drops, plus `sealed`. The wire `type` stays plaintext. Each\n// sealed branch is gated on `sealed-payload-v1` by its marker field\n// (`wire-additions.ts`). `task.offer`'s branches are above.\n// ---------------------------------------------------------------------------\n\n/**\n * server -> daemon: sealed steering text. `steerId` names this steer in the\n * AAD and the content MAC, so the Host cannot replay an earlier steer of the\n * same task as a new one.\n */\nexport const TaskSteerSealedPayloadSchema = z.object({ steerId: z.uuid(), sealed: SealedTaskInputSchema }).strict();\nexport type TaskSteerSealedPayload = z.infer<typeof TaskSteerSealedPayloadSchema>;\n\n/**\n * daemon -> server: `task.complete` of a sealed task. `summary`,\n * `finalMessage` and `document` are sealed. `artifactRefs` and\n * `preparedObservation` are not carried in v1.\n */\nexport const TaskCompleteSealedPayloadSchema = TaskCompletePlainPayloadSchema.omit({\n summary: true,\n finalMessage: true,\n document: true,\n artifactRefs: true,\n preparedObservation: true,\n})\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskCompleteSealedPayload = z.infer<typeof TaskCompleteSealedPayloadSchema>;\n\n/** daemon -> server: `task.fail` of a sealed task. `reason` is sealed; `preparedObservation` is not carried in v1. */\nexport const TaskFailSealedPayloadSchema = TaskFailPlainPayloadSchema.omit({ reason: true, preparedObservation: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskFailSealedPayload = z.infer<typeof TaskFailSealedPayloadSchema>;\n\n/**\n * daemon -> server: `task.decline` of a sealed task with a sealed `reason`.\n * The sealed decline codes go only on the plaintext branch: a device that\n * cannot open or use the scope key often cannot seal a reply either.\n */\nexport const TaskDeclineSealedPayloadSchema = DeclineFields.omit({ reason: true })\n .extend({\n code: z.union([z.enum(HOME_DECLINE_CODES), unrecognizedToken(DECLINE_CODES)]).optional(),\n sealed: SealedTaskOutputSchema,\n })\n .strict();\nexport type TaskDeclineSealedPayload = z.infer<typeof TaskDeclineSealedPayloadSchema>;\n\n/** daemon -> server: `task.cancelled` of a sealed task. `reason` is sealed. */\nexport const TaskCancelledSealedPayloadSchema = TaskCancelledPlainPayloadSchema.omit({ reason: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskCancelledSealedPayload = z.infer<typeof TaskCancelledSealedPayloadSchema>;\n\n/** daemon -> server: `task.progress` of a sealed task. `events` is sealed; `seq` names the batch. */\nexport const TaskProgressSealedPayloadSchema = TaskProgressPlainPayloadSchema.omit({ events: true })\n .extend({ sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskProgressSealedPayload = z.infer<typeof TaskProgressSealedPayloadSchema>;\n\n/**\n * daemon -> server: an inline artifact of a sealed task. `inline` is sealed; a\n * blob artifact is not carried in v1. `artifactId` names the write in the AAD\n * and the content MAC, because two artifacts of one task may share a `name`.\n */\nexport const TaskArtifactSealedPayloadSchema = TaskArtifactPlainPayloadSchema.omit({ inline: true, blobRef: true })\n .extend({ artifactId: z.uuid(), sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskArtifactSealedPayload = z.infer<typeof TaskArtifactSealedPayloadSchema>;\n\n/** daemon -> server: `task.await_approval` of a sealed task. `summary` is sealed; `approvalId` is required. */\nexport const TaskAwaitApprovalSealedPayloadSchema = TaskAwaitApprovalPlainPayloadSchema.omit({ summary: true })\n .extend({ approvalId: z.string().min(1), sealed: SealedTaskOutputSchema })\n .strict();\nexport type TaskAwaitApprovalSealedPayload = z.infer<typeof TaskAwaitApprovalSealedPayloadSchema>;\n\n// Each sealable payload: the plaintext branch first, then the sealed branch.\n// Narrow with `payload.sealed !== undefined`; the plaintext branch's `sealed` is `never`.\n// Each member is written `X as typeof X` (see `MESSAGE_PAYLOAD_SCHEMAS`).\n\nexport const TaskSteerPayloadSchema = z.union([\n TaskSteerPlainPayloadSchema as typeof TaskSteerPlainPayloadSchema,\n TaskSteerSealedPayloadSchema as typeof TaskSteerSealedPayloadSchema,\n]);\nexport type TaskSteerPayload = z.infer<typeof TaskSteerPayloadSchema>;\n\nexport const TaskDeclinePayloadSchema = z.union([\n TaskDeclinePlainPayloadSchema as typeof TaskDeclinePlainPayloadSchema,\n TaskDeclineSealedPayloadSchema as typeof TaskDeclineSealedPayloadSchema,\n]);\nexport type TaskDeclinePayload = z.infer<typeof TaskDeclinePayloadSchema>;\n\nexport const TaskProgressPayloadSchema = z.union([\n TaskProgressPlainPayloadSchema as typeof TaskProgressPlainPayloadSchema,\n TaskProgressSealedPayloadSchema as typeof TaskProgressSealedPayloadSchema,\n]);\nexport type TaskProgressPayload = z.infer<typeof TaskProgressPayloadSchema>;\n\nexport const TaskArtifactPayloadSchema = z.union([\n TaskArtifactPlainPayloadSchema as typeof TaskArtifactPlainPayloadSchema,\n TaskArtifactSealedPayloadSchema as typeof TaskArtifactSealedPayloadSchema,\n]);\nexport type TaskArtifactPayload = z.infer<typeof TaskArtifactPayloadSchema>;\n\nexport const TaskAwaitApprovalPayloadSchema = z.union([\n TaskAwaitApprovalPlainPayloadSchema as typeof TaskAwaitApprovalPlainPayloadSchema,\n TaskAwaitApprovalSealedPayloadSchema as typeof TaskAwaitApprovalSealedPayloadSchema,\n]);\nexport type TaskAwaitApprovalPayload = z.infer<typeof TaskAwaitApprovalPayloadSchema>;\n\nexport const TaskCompletePayloadSchema = z.union([\n TaskCompletePlainPayloadSchema as typeof TaskCompletePlainPayloadSchema,\n TaskCompleteSealedPayloadSchema as typeof TaskCompleteSealedPayloadSchema,\n]);\nexport type TaskCompletePayload = z.infer<typeof TaskCompletePayloadSchema>;\n\nexport const TaskFailPayloadSchema = z.union([\n TaskFailPlainPayloadSchema as typeof TaskFailPlainPayloadSchema,\n TaskFailSealedPayloadSchema as typeof TaskFailSealedPayloadSchema,\n]);\nexport type TaskFailPayload = z.infer<typeof TaskFailPayloadSchema>;\n\nexport const TaskCancelledPayloadSchema = z.union([\n TaskCancelledPlainPayloadSchema as typeof TaskCancelledPlainPayloadSchema,\n TaskCancelledSealedPayloadSchema as typeof TaskCancelledSealedPayloadSchema,\n]);\nexport type TaskCancelledPayload = z.infer<typeof TaskCancelledPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// registry — single source of truth mapping message type -> payload schema\n// ---------------------------------------------------------------------------\n\n/**\n * Each value is written `X as typeof X`. The assertion is type-only (no\n * runtime code). It makes declaration emit name each schema (`typeof X`)\n * instead of copying its full type, which keeps the published `.d.ts` small.\n * Every new entry follows this rule. Entries are grouped by direction.\n */\nexport const MESSAGE_PAYLOAD_SCHEMAS = {\n 'conn.hello': ConnHelloPayloadSchema as typeof ConnHelloPayloadSchema,\n 'task.offer': TaskOfferPayloadSchema as typeof TaskOfferPayloadSchema,\n 'agent.egress.ack': AgentEgressAckPayloadSchema as typeof AgentEgressAckPayloadSchema,\n 'agent.message.disposition': AgentMessageDispositionPayloadSchema as typeof AgentMessageDispositionPayloadSchema,\n 'agent.content.read': AgentContentReadPayloadSchema as typeof AgentContentReadPayloadSchema,\n 'agent.home.projection': AgentHomeProjectionPayloadSchema as typeof AgentHomeProjectionPayloadSchema,\n 'agent.input.preparation': AgentInputPreparationPayloadSchema as typeof AgentInputPreparationPayloadSchema,\n 'provider.provisioning.available': ProviderProvisioningAvailablePayloadSchema as typeof ProviderProvisioningAvailablePayloadSchema,\n 'agent.memory.intent.available': AgentMemoryIntentAvailablePayloadSchema as typeof AgentMemoryIntentAvailablePayloadSchema,\n 'task.approve': TaskApprovePayloadSchema as typeof TaskApprovePayloadSchema,\n 'task.reject': TaskRejectPayloadSchema as typeof TaskRejectPayloadSchema,\n 'task.cancel': TaskCancelPayloadSchema as typeof TaskCancelPayloadSchema,\n 'task.steer': TaskSteerPayloadSchema as typeof TaskSteerPayloadSchema,\n 'e2ee.key_package.available': E2eeKeyPackageAvailablePayloadSchema as typeof E2eeKeyPackageAvailablePayloadSchema,\n 'task.claim': TaskClaimPayloadSchema as typeof TaskClaimPayloadSchema,\n 'task.started': TaskStartedPayloadSchema as typeof TaskStartedPayloadSchema,\n 'task.decline': TaskDeclinePayloadSchema as typeof TaskDeclinePayloadSchema,\n 'task.progress': TaskProgressPayloadSchema as typeof TaskProgressPayloadSchema,\n 'task.artifact': TaskArtifactPayloadSchema as typeof TaskArtifactPayloadSchema,\n 'task.await_approval': TaskAwaitApprovalPayloadSchema as typeof TaskAwaitApprovalPayloadSchema,\n 'task.complete': TaskCompletePayloadSchema as typeof TaskCompletePayloadSchema,\n 'task.fail': TaskFailPayloadSchema as typeof TaskFailPayloadSchema,\n 'task.cancelled': TaskCancelledPayloadSchema as typeof TaskCancelledPayloadSchema,\n 'task.approval_resolved': TaskApprovalResolvedPayloadSchema as typeof TaskApprovalResolvedPayloadSchema,\n 'agent.egress.reliable': AgentEgressReliablePayloadSchema as typeof AgentEgressReliablePayloadSchema,\n 'agent.message.draft': AgentMessageDraftPayloadSchema as typeof AgentMessageDraftPayloadSchema,\n 'agent.message.publish': AgentMessagePublishPayloadSchema as typeof AgentMessagePublishPayloadSchema,\n 'agent.content.receipt': AgentContentReceiptPayloadSchema as typeof AgentContentReceiptPayloadSchema,\n} as const;\n\nexport type MessageType = keyof typeof MESSAGE_PAYLOAD_SCHEMAS;\n\nexport const MESSAGE_TYPES = Object.keys(MESSAGE_PAYLOAD_SCHEMAS) as MessageType[];\n\n/**\n * Message types the server sends to the daemon. Used by {@link EnvelopeSchema}\n * (`envelope.ts`) to decide which branches require envelope `seq` (M1\n * redelivery cursor).\n */\nexport const SERVER_TO_DAEMON_TYPES = [\n 'task.offer',\n 'agent.egress.ack',\n 'agent.message.disposition',\n 'agent.content.read',\n 'agent.home.projection',\n 'agent.input.preparation',\n 'provider.provisioning.available',\n 'agent.memory.intent.available',\n 'task.approve',\n 'task.reject',\n 'task.cancel',\n 'task.steer',\n 'e2ee.key_package.available',\n] as const satisfies readonly MessageType[];\n\n/**\n * Message types the daemon sends to the server — the flip side of\n * {@link SERVER_TO_DAEMON_TYPES}. `conn.hello` is deliberately excluded: the\n * inbound gate handles a bearer-authenticated `conn.hello` as a capability\n * snapshot on its own, before the type-allow check.\n *\n * Used by `handleInboundEnvelope` (`@byok-sdk/cloud`'s `inbound.ts`) as the\n * type-allow gate for every inbound `POST /byok/messages` envelope (finding\n * P2): a `type` outside this set — a server -> daemon type arriving inbound,\n * or anything unrecognized — is rejected before it's dispatched to any\n * handler or counted `accepted` on the `/byok/messages` wire.\n */\nexport const DAEMON_TO_SERVER_TYPES = [\n 'task.claim',\n 'task.started',\n 'task.decline',\n 'task.progress',\n 'task.artifact',\n 'task.await_approval',\n 'task.complete',\n 'task.fail',\n 'task.cancelled',\n 'task.approval_resolved',\n 'agent.egress.reliable',\n 'agent.message.draft',\n 'agent.message.publish',\n 'agent.content.receipt',\n] as const satisfies readonly MessageType[];\n","import { z } from 'zod';\nimport { AgentHomeProjectionAgentRefSchema } from './messages';\n\n/**\n * Host-approved Agent memory intents — the wire half.\n *\n * A Host (the only approval authority) approves one exact memory operation on\n * one device-local Agent home. The device (the only memory content authority)\n * applies it with its existing sha256 CAS at most once and reports a terminal,\n * content-free completion. This package defines only:\n *\n * - the device capability that gates the task-free server -> daemon notice\n * `agent.memory.intent.available`, whose strict payload is exactly\n * `{ intentId, agentRef }` (see `messages.ts`);\n * - the immutable intent a Host releases over its own device routes;\n * - the fetch request/response a device exchanges with those routes;\n * - the terminal completion a device reports and the durable readback a Host\n * returns for it.\n *\n * Notice-and-fetch is the point: memory content never rides the mailbox or the\n * device journal. The only field that carries content is `content` on a\n * `release` of a `replace` intent.\n *\n * Path authority stays with the device. This schema applies only the syntactic\n * bounds the device ledger relies on (at most 1024 ASCII bytes that need no\n * JSON escaping); the exact memory path rule (`MEMORY.md` or\n * `notes/<safe>/…md`) and the `MEMORY.md` delete ban are evaluated by the\n * device and reported as `path_invalid` / `memory_md_not_deletable`. Host-only\n * path policy is Host vocabulary and stays out of this package, as do\n * audiences, route paths and product names.\n *\n * `operationDigest` is pinned to `@byok-sdk/core`\n * `agentMemoryIntentOperationDigest(...)`, which a device recomputes with its\n * own enrolled tenant and device ids.\n */\n\n/** Maximum UTF-8 byte length of a released `replace` body (one memory file): 256 KiB. */\nexport const AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES = 262_144;\n/** Maximum byte length of an intent `path` (ASCII, so bytes = characters). */\nexport const AGENT_MEMORY_INTENT_PATH_MAX_BYTES = 1024;\n/** Maximum byte length of an opaque `approvalRef` (ASCII, so bytes = characters). */\nexport const AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES = 128;\n\nconst SHA256_REVISION = /^sha256:[0-9a-f]{64}$/u;\n\n/** A memory file revision: `sha256:` over the file bytes (a missing file is the empty-bytes digest). */\nexport const AgentMemoryIntentRevisionSchema = z\n .string()\n .regex(SHA256_REVISION, 'revision must be lowercase sha256:<64 hex>');\nexport type AgentMemoryIntentRevision = z.infer<typeof AgentMemoryIntentRevisionSchema>;\n\n/** The identity-and-operation binding; see `@byok-sdk/core` `agentMemoryIntentOperationDigest`. */\nexport const AgentMemoryIntentOperationDigestSchema = z\n .string()\n .regex(SHA256_REVISION, 'operationDigest must be lowercase sha256:<64 hex>');\nexport type AgentMemoryIntentOperationDigest = z.infer<typeof AgentMemoryIntentOperationDigestSchema>;\n\n/**\n * Syntactic bound only: 1..1024 printable ASCII characters that need no JSON\n * escaping (no `\"`, no `\\`, no control characters). The device applies the\n * exact memory path rule.\n */\nexport const AgentMemoryIntentPathSchema = z\n .string()\n .min(1)\n .max(AGENT_MEMORY_INTENT_PATH_MAX_BYTES)\n .regex(/^[\\x20\\x21\\x23-\\x5b\\x5d-\\x7e]+$/u, 'path must be printable ASCII without quote or backslash');\nexport type AgentMemoryIntentPath = z.infer<typeof AgentMemoryIntentPathSchema>;\n\n/** Opaque audit correlation. The device records it and never evaluates it. */\nexport const AgentMemoryIntentApprovalRefSchema = z\n .string()\n .regex(\n new RegExp(`^[A-Za-z0-9._:-]{1,${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES}}$`, 'u'),\n `approvalRef must be 1..${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES} characters of [A-Za-z0-9._:-]`,\n );\nexport type AgentMemoryIntentApprovalRef = z.infer<typeof AgentMemoryIntentApprovalRefSchema>;\n\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\nconst utf8 = new TextEncoder();\n\n/** A `replace` body: well-formed Unicode whose UTF-8 encoding is at most 256 KiB. */\nexport const AgentMemoryIntentContentSchema = z\n .string()\n .refine((value) => !LONE_SURROGATE.test(value), 'content must be well-formed Unicode (encodable as UTF-8)')\n .refine(\n (value) => utf8.encode(value).byteLength <= AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES,\n `content must not exceed ${AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES} UTF-8 bytes`,\n );\nexport type AgentMemoryIntentContent = z.infer<typeof AgentMemoryIntentContentSchema>;\n\nexport const AGENT_MEMORY_INTENT_OPERATIONS = ['replace', 'delete'] as const;\nexport const AgentMemoryIntentOperationSchema = z.enum(AGENT_MEMORY_INTENT_OPERATIONS);\nexport type AgentMemoryIntentOperation = z.infer<typeof AgentMemoryIntentOperationSchema>;\n\n/**\n * The immutable Host-approved intent.\n *\n * - `replace`: `targetRevision` is the digest of the approved body and must\n * differ from `baseRevision`; `content` appears only inside a `release`.\n * - `delete`: `targetRevision` is `null` and there is never `content`.\n */\nexport const AgentMemoryIntentV1Schema = z\n .object({\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n path: AgentMemoryIntentPathSchema,\n operation: AgentMemoryIntentOperationSchema,\n baseRevision: AgentMemoryIntentRevisionSchema,\n targetRevision: AgentMemoryIntentRevisionSchema.nullable(),\n content: AgentMemoryIntentContentSchema.optional(),\n approvalRef: AgentMemoryIntentApprovalRefSchema,\n operationDigest: AgentMemoryIntentOperationDigestSchema,\n })\n .strict()\n .superRefine((intent, ctx) => {\n if (intent.operation === 'delete') {\n if (intent.targetRevision !== null) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'a delete intent has a null targetRevision' });\n }\n if (intent.content !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['content'], message: 'a delete intent never carries content' });\n }\n return;\n }\n if (intent.targetRevision === null) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'a replace intent requires a targetRevision' });\n } else if (intent.targetRevision === intent.baseRevision) {\n ctx.addIssue({ code: 'custom', path: ['targetRevision'], message: 'targetRevision must differ from baseRevision' });\n }\n });\nexport type AgentMemoryIntentV1 = z.infer<typeof AgentMemoryIntentV1Schema>;\n\n// ---------------------------------------------------------------------------\n// Completion and readback\n// ---------------------------------------------------------------------------\n\n/**\n * Codes a Host decides on its own authority. They are the only `withheld`\n * codes and the only codes a `host_terminal` readback may carry.\n */\nexport const AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES = [\n 'intent_revoked',\n 'intent_expired',\n 'placement_changed',\n 'profile_revision_changed',\n] as const;\nexport const AgentMemoryIntentHostTerminalCodeSchema = z.enum(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES);\nexport type AgentMemoryIntentHostTerminalCode = z.infer<typeof AgentMemoryIntentHostTerminalCodeSchema>;\n\n/**\n * Closed rejection set. A code names the failed check, never a value. Every\n * `rejected` completion means the device wrote no `applying` record and made\n * zero memory writes.\n */\nexport const AGENT_MEMORY_INTENT_REJECTION_CODES = [\n 'intent_invalid',\n 'path_invalid',\n 'memory_md_not_deletable',\n 'content_invalid',\n 'intent_digest_mismatch',\n 'agent_ref_mismatch',\n 'agent_home_unavailable',\n ...AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES,\n] as const;\nexport const AgentMemoryIntentRejectionCodeSchema = z.enum(AGENT_MEMORY_INTENT_REJECTION_CODES);\nexport type AgentMemoryIntentRejectionCode = z.infer<typeof AgentMemoryIntentRejectionCodeSchema>;\n\n/** One device observation of the target file. The observation instant is not on the wire. */\nexport const AgentMemoryIntentFileObservationSchema = z\n .object({\n exists: z.boolean(),\n revision: AgentMemoryIntentRevisionSchema,\n })\n .strict();\nexport type AgentMemoryIntentFileObservation = z.infer<typeof AgentMemoryIntentFileObservationSchema>;\n\nconst completionIdentity = {\n intentId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n path: AgentMemoryIntentPathSchema,\n operation: AgentMemoryIntentOperationSchema,\n operationDigest: AgentMemoryIntentOperationDigestSchema,\n} as const;\n\nconst AppliedCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('applied'), result: AgentMemoryIntentFileObservationSchema })\n .strict();\nconst ConflictCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('conflict'), observed: AgentMemoryIntentFileObservationSchema })\n .strict();\nconst RejectedCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('rejected'), code: AgentMemoryIntentRejectionCodeSchema })\n .strict();\nconst UncertainCompletionSchema = z\n .object({ ...completionIdentity, outcome: z.literal('uncertain'), observed: AgentMemoryIntentFileObservationSchema })\n .strict();\n\n/**\n * The terminal, content-free result of one intent, reported by the device.\n *\n * - `applied`: the live-path CAS returned success; `result` is the file after it.\n * - `conflict`: the live-path CAS refused on revision; this attempt wrote nothing.\n * - `rejected`: no `applying` record was written; zero writes.\n * - `uncertain`: whether this intent wrote is unknown; `observed` is only the\n * current file, never provenance.\n *\n * There is no non-terminal outcome.\n */\nexport const AgentMemoryIntentCompletionSchema = z.discriminatedUnion('outcome', [\n AppliedCompletionSchema,\n ConflictCompletionSchema,\n RejectedCompletionSchema,\n UncertainCompletionSchema,\n]);\nexport type AgentMemoryIntentCompletion = z.infer<typeof AgentMemoryIntentCompletionSchema>;\n\n/**\n * How the Host's durable record relates to the completion it was handed:\n *\n * - `recorded`: this completion became the intent's first terminal fact.\n * - `idempotent`: an identical completion was already recorded.\n * - `conflict`: a different completion is already recorded; it is returned.\n * - `host_terminal`: the Host had already terminated the intent on its own\n * authority ({@link AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES}).\n */\nexport const AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS = ['recorded', 'idempotent', 'conflict', 'host_terminal'] as const;\nexport const AgentMemoryIntentReadbackDispositionSchema = z.enum(AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS);\nexport type AgentMemoryIntentReadbackDisposition = z.infer<typeof AgentMemoryIntentReadbackDispositionSchema>;\n\n/**\n * The Host's durable terminal readback for one intent. `completion` is the\n * terminal fact the Host has STORED; on `host_terminal` it is always a\n * `rejected` completion carrying a Host code. `recordedAt` is the Host record\n * time, never a device observation time.\n */\nexport const AgentMemoryIntentReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n intentId: z.uuid(),\n disposition: AgentMemoryIntentReadbackDispositionSchema,\n completion: AgentMemoryIntentCompletionSchema,\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict()\n .superRefine((readback, ctx) => {\n if (readback.completion.intentId !== readback.intentId) {\n ctx.addIssue({ code: 'custom', path: ['completion', 'intentId'], message: 'completion intentId must equal readback intentId' });\n }\n if (\n readback.disposition === 'host_terminal' &&\n (readback.completion.outcome !== 'rejected' ||\n !(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES as readonly string[]).includes(readback.completion.code))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['completion'],\n message: `a host_terminal readback must carry a rejected completion with one of: ${AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.join(', ')}`,\n });\n }\n });\nexport type AgentMemoryIntentReadback = z.infer<typeof AgentMemoryIntentReadbackSchema>;\n\n// ---------------------------------------------------------------------------\n// Fetch\n// ---------------------------------------------------------------------------\n\n/**\n * `held`: the device reserved a ledger slot and may receive a release.\n * `none`: the device could not reserve; the Host must not change intent state\n * or release content.\n */\nexport const AGENT_MEMORY_INTENT_RESERVATIONS = ['held', 'none'] as const;\nexport const AgentMemoryIntentReservationSchema = z.enum(AGENT_MEMORY_INTENT_RESERVATIONS);\nexport type AgentMemoryIntentReservation = z.infer<typeof AgentMemoryIntentReservationSchema>;\n\n/**\n * The SDK half of a fetch. Device authentication (the tenant and device a Host\n * trusts) is Host transport vocabulary and is not part of this schema.\n */\nexport const AgentMemoryIntentFetchRequestSchema = z\n .object({\n intentId: z.uuid(),\n reservation: AgentMemoryIntentReservationSchema,\n })\n .strict();\nexport type AgentMemoryIntentFetchRequest = z.infer<typeof AgentMemoryIntentFetchRequestSchema>;\n\nexport const AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS = ['release', 'withheld', 'terminal', 'deferred'] as const;\nexport type AgentMemoryIntentFetchDisposition = (typeof AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS)[number];\n\n/** Which fetch dispositions a Host may answer for each request reservation. */\nexport const AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION = {\n held: ['release', 'withheld', 'terminal'],\n none: ['terminal', 'deferred'],\n} as const satisfies Record<AgentMemoryIntentReservation, readonly AgentMemoryIntentFetchDisposition[]>;\n\nfunction requireNoContent(intent: AgentMemoryIntentV1, ctx: z.RefinementCtx, disposition: string): void {\n if (intent.content !== undefined) {\n ctx.addIssue({ code: 'custom', path: ['intent', 'content'], message: `a ${disposition} fetch response never carries content` });\n }\n}\n\nconst ReleaseFetchResponseSchema = z\n .object({ disposition: z.literal('release'), intent: AgentMemoryIntentV1Schema })\n .strict()\n .superRefine((response, ctx) => {\n if (response.intent.operation === 'replace' && response.intent.content === undefined) {\n ctx.addIssue({ code: 'custom', path: ['intent', 'content'], message: 'a replace release must carry content' });\n }\n });\n\nconst WithheldFetchResponseSchema = z\n .object({ disposition: z.literal('withheld'), intent: AgentMemoryIntentV1Schema, code: AgentMemoryIntentHostTerminalCodeSchema })\n .strict()\n .superRefine((response, ctx) => requireNoContent(response.intent, ctx, 'withheld'));\n\nconst TerminalFetchResponseSchema = z\n .object({ disposition: z.literal('terminal'), intent: AgentMemoryIntentV1Schema, readback: AgentMemoryIntentReadbackSchema })\n .strict()\n .superRefine((response, ctx) => {\n requireNoContent(response.intent, ctx, 'terminal');\n const { intent, readback } = response;\n if (readback.intentId !== intent.intentId) {\n ctx.addIssue({ code: 'custom', path: ['readback', 'intentId'], message: 'readback intentId must equal intent intentId' });\n }\n const completion = readback.completion;\n if (\n completion.agentRef.agentId !== intent.agentRef.agentId ||\n completion.agentRef.profileRevision !== intent.agentRef.profileRevision ||\n completion.path !== intent.path ||\n completion.operation !== intent.operation ||\n completion.operationDigest !== intent.operationDigest\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['readback', 'completion'],\n message: 'readback completion identity must equal the intent identity and operationDigest',\n });\n }\n });\n\nconst DeferredFetchResponseSchema = z\n .object({ disposition: z.literal('deferred'), intent: AgentMemoryIntentV1Schema })\n .strict()\n .superRefine((response, ctx) => requireNoContent(response.intent, ctx, 'deferred'));\n\n/**\n * A Host fetch answer, independent of the request reservation. A device must\n * parse with {@link agentMemoryIntentFetchResponseSchemaFor} so a `release` or\n * `withheld` answer to a `none` request (or a `deferred` answer to a `held`\n * request) is refused.\n */\nexport const AgentMemoryIntentFetchResponseSchema = z.discriminatedUnion('disposition', [\n ReleaseFetchResponseSchema,\n WithheldFetchResponseSchema,\n TerminalFetchResponseSchema,\n DeferredFetchResponseSchema,\n]);\nexport type AgentMemoryIntentFetchResponse = z.infer<typeof AgentMemoryIntentFetchResponseSchema>;\n\n/** The fetch answer schema bound to the reservation the device sent. */\nexport function agentMemoryIntentFetchResponseSchemaFor(reservation: AgentMemoryIntentReservation) {\n const allowed: readonly AgentMemoryIntentFetchDisposition[] =\n AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION[AgentMemoryIntentReservationSchema.parse(reservation)];\n return AgentMemoryIntentFetchResponseSchema.superRefine((response, ctx) => {\n if (!allowed.includes(response.disposition)) {\n ctx.addIssue({\n code: 'custom',\n path: ['disposition'],\n message: `a ${reservation} reservation allows only: ${allowed.join(', ')}`,\n });\n }\n });\n}\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema, AgentEgressPolicyRevisionSchema } from './agent-egress';\nimport { AgentRefSchema, RuntimeIdSchema } from './messages';\nimport { SealedMemoryProjectionSchema } from './sealed-payload';\n\n/** One hosted projection is bounded before it enters the redaction or storage seam. */\nexport const AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES = 512 * 1024;\n\n/** PostgreSQL `integer` ceiling shared by writer epochs and source sequences. */\nexport const AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE = 2_147_483_647;\n\nconst OPAQUE_REFERENCE_MAX_BYTES = 512;\nconst opaqueReference = (field: string) => z\n .string()\n .min(1)\n .max(OPAQUE_REFERENCE_MAX_BYTES)\n .refine((value) => new TextEncoder().encode(value).byteLength <= OPAQUE_REFERENCE_MAX_BYTES, {\n message: `${field} must not exceed ${OPAQUE_REFERENCE_MAX_BYTES} UTF-8 bytes`,\n })\n .regex(/^[^\\u0000-\\u001f\\u007f\\r\\n]+$/u, `${field} must not contain control characters`);\n\n/** Opaque, embedder-issued authorization grant. It is never interpreted as a consent boolean. */\nexport const AgentMemoryProjectionGrantRefSchema = opaqueReference('grantRef');\nexport type AgentMemoryProjectionGrantRef = z.infer<typeof AgentMemoryProjectionGrantRefSchema>;\n\n/** Exact local runtime session identity. No cwd or local source path is portable. */\nexport const AgentMemoryProjectionSessionRefSchema = opaqueReference('sessionRef');\nexport type AgentMemoryProjectionSessionRef = z.infer<typeof AgentMemoryProjectionSessionRefSchema>;\n\n/** Positive epoch that changes only when the local single-writer authority changes. */\nexport const AgentMemoryProjectionWriterEpochSchema = z\n .number()\n .int()\n .positive()\n .max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);\nexport type AgentMemoryProjectionWriterEpoch = z.infer<typeof AgentMemoryProjectionWriterEpochSchema>;\n\n/** Positive sequence within one writer epoch. A new epoch starts at one. */\nexport const AgentMemoryProjectionSourceSeqSchema = z\n .number()\n .int()\n .positive()\n .max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);\nexport type AgentMemoryProjectionSourceSeq = z.infer<typeof AgentMemoryProjectionSourceSeqSchema>;\n\n/** Byte length implied by the unpadded base64url transport string. */\nexport function agentMemoryProjectionBase64UrlByteLength(value: string): number | undefined {\n if (!/^[A-Za-z0-9_-]*$/u.test(value) || value.length % 4 === 1) return undefined;\n const complete = Math.floor(value.length / 4) * 3;\n const tail = value.length % 4;\n return complete + (tail === 0 ? 0 : tail - 1);\n}\n\n/**\n * The only body-bearing field in the hosted contract. It is already redacted\n * by the embedder; source bytes, raw-source hashes, cwd, and local paths never\n * cross this boundary. The hosted store re-hashes these bytes before commit.\n */\nexport const AgentMemoryProjectionSnapshotSchema = z\n .object({\n redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n redactedBytes: z.string().max(Math.ceil(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES / 3) * 4),\n })\n .strict()\n .superRefine((snapshot, ctx) => {\n const actual = agentMemoryProjectionBase64UrlByteLength(snapshot.redactedBytes);\n if (actual === undefined) {\n ctx.addIssue({ code: 'custom', path: ['redactedBytes'], message: 'redactedBytes must be unpadded base64url' });\n return;\n }\n if (actual !== snapshot.redactedByteCount) {\n ctx.addIssue({\n code: 'custom',\n path: ['redactedByteCount'],\n message: 'redactedByteCount must equal the decoded redactedBytes length',\n });\n }\n });\nexport type AgentMemoryProjectionSnapshot = z.infer<typeof AgentMemoryProjectionSnapshotSchema>;\n\n/** The plaintext identity and ordering fields of every mutation branch. */\nconst MUTATION_IDENTITY = {\n taskId: z.string().min(1).max(512),\n agentRef: AgentRefSchema,\n sessionRef: AgentMemoryProjectionSessionRefSchema,\n runtimeId: RuntimeIdSchema,\n grantRef: AgentMemoryProjectionGrantRefSchema,\n writerEpoch: AgentMemoryProjectionWriterEpochSchema,\n sourceSeq: AgentMemoryProjectionSourceSeqSchema,\n mutationId: z.uuid(),\n policyRevision: AgentEgressPolicyRevisionSchema,\n};\n\n/**\n * Device -> hosted mutation for one redacted full snapshot. It intentionally\n * contains no tenant/device identity: authenticated transport supplies both.\n * The snapshot is a one-way copy of local `MEMORY.md` plus local `notes/`, not\n * a remote authoring, merge, import, history, or RAG contract.\n */\nexport const AgentMemoryProjectionPlainMutationSchema = z\n .object({ ...MUTATION_IDENTITY, snapshot: AgentMemoryProjectionSnapshotSchema, sealed: z.never().optional() })\n .strict();\nexport type AgentMemoryProjectionPlainMutation = z.infer<typeof AgentMemoryProjectionPlainMutationSchema>;\n\n/**\n * The mutation under a grant that names a sealing scope (#1045 C4). The\n * redacted snapshot is sealed, inline only, under the Agent's memory scope;\n * its plaintext hash and byte count are not carried. The AAD binds\n * `{ agentId, writerEpoch, sourceSeq, mutationId }`, so the Host cannot move\n * a snapshot to another Agent, epoch or position.\n */\nexport const AgentMemoryProjectionSealedMutationSchema = z\n .object({ ...MUTATION_IDENTITY, sealed: SealedMemoryProjectionSchema, snapshot: z.never().optional() })\n .strict();\nexport type AgentMemoryProjectionSealedMutation = z.infer<typeof AgentMemoryProjectionSealedMutationSchema>;\n\n/** Narrow with `mutation.sealed !== undefined`. */\nexport const AgentMemoryProjectionMutationSchema = z.union([\n AgentMemoryProjectionPlainMutationSchema as typeof AgentMemoryProjectionPlainMutationSchema,\n AgentMemoryProjectionSealedMutationSchema as typeof AgentMemoryProjectionSealedMutationSchema,\n]);\nexport type AgentMemoryProjectionMutation = z.infer<typeof AgentMemoryProjectionMutationSchema>;\n\n/** Stable meter receipt for one accepted redacted snapshot; it never carries the snapshot body. */\nexport const AgentMemoryProjectionMeteringReceiptSchema = z\n .object({\n meteringReceiptId: z.uuid(),\n acceptedRedactedBytes: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\nexport type AgentMemoryProjectionMeteringReceipt = z.infer<typeof AgentMemoryProjectionMeteringReceiptSchema>;\n\nconst RECEIPT_IDENTITY = {\n outcome: z.enum(['accepted', 'idempotent']),\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n ...MUTATION_IDENTITY,\n};\n\n/** Immutable commit readback. It repeats identity and redacted metadata, never redacted bytes. */\nexport const AgentMemoryProjectionPlainReceiptSchema = z\n .object({\n ...RECEIPT_IDENTITY,\n redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n metering: AgentMemoryProjectionMeteringReceiptSchema,\n })\n .strict();\nexport type AgentMemoryProjectionPlainReceipt = z.infer<typeof AgentMemoryProjectionPlainReceiptSchema>;\n\n/** Stable meter receipt for one accepted sealed snapshot: the Host meters the padded length it stores. */\nexport const AgentMemoryProjectionSealedMeteringReceiptSchema = z\n .object({\n meteringReceiptId: z.uuid(),\n acceptedPaddedBytes: SealedMemoryProjectionSchema.shape.paddedLength,\n recordedAt: z.iso.datetime({ offset: true }),\n })\n .strict();\nexport type AgentMemoryProjectionSealedMeteringReceipt = z.infer<typeof AgentMemoryProjectionSealedMeteringReceiptSchema>;\n\n/** Immutable commit readback of a sealed snapshot: identity and the sealed member's `contentMac` and padded length. */\nexport const AgentMemoryProjectionSealedReceiptSchema = z\n .object({\n ...RECEIPT_IDENTITY,\n contentMac: SealedMemoryProjectionSchema.shape.contentMac,\n paddedLength: SealedMemoryProjectionSchema.shape.paddedLength,\n metering: AgentMemoryProjectionSealedMeteringReceiptSchema,\n })\n .strict();\nexport type AgentMemoryProjectionSealedReceipt = z.infer<typeof AgentMemoryProjectionSealedReceiptSchema>;\n\nexport const AgentMemoryProjectionReceiptSchema = z.union([\n AgentMemoryProjectionPlainReceiptSchema as typeof AgentMemoryProjectionPlainReceiptSchema,\n AgentMemoryProjectionSealedReceiptSchema as typeof AgentMemoryProjectionSealedReceiptSchema,\n]);\nexport type AgentMemoryProjectionReceipt = z.infer<typeof AgentMemoryProjectionReceiptSchema>;\n\n/**\n * Server-side erase result. The returned epoch is the minimum legal epoch for\n * a later host-issued writer grant; erased source epochs can never re-enter.\n */\nexport const AgentMemoryProjectionEraseResultSchema = z\n .object({ nextWriterEpoch: AgentMemoryProjectionWriterEpochSchema })\n .strict();\nexport type AgentMemoryProjectionEraseResult = z.infer<typeof AgentMemoryProjectionEraseResultSchema>;\n","import { z } from 'zod';\nimport { MESSAGE_PAYLOAD_SCHEMAS, SERVER_TO_DAEMON_TYPES, type MessageType } from './messages';\nimport { PROTOCOL_VERSION } from './version';\n\nconst REQUIRED_TASK_ID = z.string().min(1);\nconst OPTIONAL_TASK_ID = REQUIRED_TASK_ID.optional();\nconst FORBIDDEN_TASK_ID = z.never().optional();\nconst REQUIRED_SEQ = z.number().int();\nconst OPTIONAL_SEQ = REQUIRED_SEQ.optional();\n\n/**\n * The schema `envelopeShape` returns, written out so declaration emit names\n * each branch of `EnvelopeSchema` instead of copying every payload type.\n * Type-only: it must stay equal to the inferred `z.object` type below.\n */\ntype EnvelopeShape<T extends MessageType, TaskId extends z.ZodTypeAny, Seq extends z.ZodTypeAny> = z.ZodObject<{\n v: z.ZodNumber;\n id: z.ZodUUID;\n ts: z.ZodISODateTime;\n type: z.ZodLiteral<T>;\n task_id: TaskId;\n session_ref: z.ZodOptional<z.ZodString>;\n seq: Seq;\n payload: (typeof MESSAGE_PAYLOAD_SCHEMAS)[T];\n}, z.core.$strip>;\n\n/**\n * Build the full envelope schema for one message type. Field order here\n * matches the spec's documented shape (`v, id, ts, type, task_id?,\n * session_ref?, seq?, payload`) so parsed output has predictable key order.\n *\n * `taskId`/`seq` are passed in as concrete schemas (not a boolean flag)\n * so each call site's return type is precisely the required-or-optional\n * shape for that branch — `z.infer<typeof EnvelopeSchema>` then reflects the\n * per-message-type requiredness rather than collapsing it to `string |\n * undefined` for every branch.\n */\nfunction envelopeShape<\n T extends MessageType,\n TaskId extends z.ZodTypeAny,\n Seq extends z.ZodTypeAny,\n>(type: T, taskId: TaskId, seq: Seq): EnvelopeShape<T, TaskId, Seq> {\n return z.object({\n // A known payload shape does not authorize interpreting another wire major\n // as v1. Keep the public number type and all supported v1 bytes unchanged.\n v: z.number().int().refine((version): boolean => version === PROTOCOL_VERSION, {\n message: 'unsupported protocol version',\n }),\n id: z.uuid(),\n ts: z.iso.datetime({ offset: true }),\n type: z.literal(type),\n task_id: taskId,\n session_ref: z.string().optional(),\n seq,\n payload: MESSAGE_PAYLOAD_SCHEMAS[type],\n });\n}\n\n/**\n * The wire envelope: common transport fields plus a `payload` whose shape is\n * determined by `type`. Unknown top-level fields are tolerated (stripped) for\n * forward-compat; unknown `type` values do not match any branch below and are\n * handled explicitly by {@link parseMessage} in `codec.ts`.\n *\n * Two cross-cutting requiredness rules, fixed at M1 (see docs/protocol.md\n * \"M0 -> M1 breaking changes\"):\n *\n * - `task_id` is REQUIRED for every `task.*` type (they all route by task id)\n * and stays optional for `conn.*` (M1 gap #1).\n * - `seq` is REQUIRED for every type the *server* sends to the daemon — a\n * per-device monotonic counter used as a redelivery cursor — and stays\n * optional for daemon -> server types (M1 redelivery cursor; see\n * `conn.hello.cursor` in `messages.ts`).\n */\nexport const EnvelopeSchema = z.discriminatedUnion('type', [\n // conn.hello: task_id stays optional (no task routing); it is\n // daemon -> server, so there is no cursor to satisfy on this leg.\n envelopeShape('conn.hello', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n\n // server -> daemon: seq required (per-device redelivery cursor); task.*\n // also requires task_id (routing key).\n envelopeShape('task.offer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.egress.ack', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.message.disposition', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.content.read', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.home.projection', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.input.preparation', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('provider.provisioning.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('agent.memory.intent.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.approve', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.reject', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.cancel', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.steer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('e2ee.key_package.available', FORBIDDEN_TASK_ID, REQUIRED_SEQ),\n\n // daemon -> server: task.* requires task_id (routing key); envelope-level\n // seq is not required in this direction (no daemon->server redelivery\n // cursor — see docs/protocol.md).\n envelopeShape('task.claim', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.started', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.decline', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.progress', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.artifact', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.await_approval', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.complete', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.fail', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.cancelled', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('task.approval_resolved', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.egress.reliable', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.message.draft', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.message.publish', REQUIRED_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('agent.content.receipt', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n]);\n\nexport type Envelope = z.infer<typeof EnvelopeSchema>;\n\n/** `true` for every message type the server sends to the daemon (envelope `seq` is required for these). */\nexport function isServerToDaemonType(type: MessageType): boolean {\n return (SERVER_TO_DAEMON_TYPES as readonly MessageType[]).includes(type);\n}\n","import type { ZodError } from 'zod';\n\n/** Base class for all protocol decode/validation errors. */\nexport class ProtocolError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ProtocolError';\n }\n}\n\n/** The input was not valid JSON at all (only thrown by `decodeEnvelope`). */\nexport class EnvelopeParseError extends ProtocolError {\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n this.name = 'EnvelopeParseError';\n }\n}\n\n/**\n * The `type` field did not match any known message type. This is distinct\n * from {@link EnvelopeValidationError} on purpose: a daemon/server on an\n * older minor version should catch this specifically and skip the message\n * instead of treating it as a bug, since a newer peer may have introduced an\n * additive message type it doesn't understand yet.\n */\nexport class UnknownMessageTypeError extends ProtocolError {\n public readonly type: unknown;\n\n constructor(type: unknown) {\n super(`Unknown message type: ${String(type)}`);\n this.name = 'UnknownMessageTypeError';\n this.type = type;\n }\n}\n\n/** The `type` field was recognized but the envelope/payload failed schema validation. */\nexport class EnvelopeValidationError extends ProtocolError {\n public readonly issues: ZodError;\n\n constructor(message: string, issues: ZodError) {\n super(message, { cause: issues });\n this.name = 'EnvelopeValidationError';\n this.issues = issues;\n }\n}\n","import type { z } from 'zod';\nimport { EnvelopeSchema, type Envelope } from './envelope';\nimport { MESSAGE_TYPES, MESSAGE_PAYLOAD_SCHEMAS, type MessageType } from './messages';\nimport { PROTOCOL_VERSION } from './version';\nimport { EnvelopeParseError, EnvelopeValidationError, UnknownMessageTypeError } from './errors';\n\nconst MESSAGE_TYPE_SET = new Set<string>(MESSAGE_TYPES);\n\nfunction decodeText(input: string | Uint8Array): string {\n return typeof input === 'string' ? input : new TextDecoder('utf-8').decode(input);\n}\n\n/**\n * Validate an already-parsed JS value as an {@link Envelope}, narrowing\n * `payload` by `type`. Throws {@link UnknownMessageTypeError} when `type`\n * isn't a recognized message type (safe for the caller to skip/ignore), or\n * {@link EnvelopeValidationError} when a recognized type fails schema\n * validation.\n */\nexport function parseMessage(data: unknown): Envelope {\n const result = EnvelopeSchema.safeParse(data);\n if (result.success) {\n return result.data;\n }\n\n const typeValue =\n typeof data === 'object' && data !== null && !Array.isArray(data)\n ? (data as Record<string, unknown>).type\n : undefined;\n\n if (typeof typeValue !== 'string' || !MESSAGE_TYPE_SET.has(typeValue)) {\n throw new UnknownMessageTypeError(typeValue);\n }\n\n throw new EnvelopeValidationError(\n `Envelope failed validation for type \"${typeValue}\"`,\n result.error,\n );\n}\n\n/**\n * Decode a single NDJSON line into a validated {@link Envelope}. Accepts a\n * string or raw bytes (e.g. a binary transport frame) — isomorphic, no\n * stream handling required of the caller.\n */\nexport function decodeEnvelope(line: string | Uint8Array): Envelope {\n const text = decodeText(line).replace(/[\\r\\n]+$/, '');\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (cause) {\n throw new EnvelopeParseError('Envelope line is not valid JSON', cause);\n }\n return parseMessage(json);\n}\n\n/** Encode an {@link Envelope} as a single-line NDJSON string (trailing `\\n` included). */\nexport function encodeEnvelope(env: Envelope): string {\n return `${JSON.stringify(env)}\\n`;\n}\n\n// ---------------------------------------------------------------------------\n// createEnvelope — finding F1: `taskId`/`seq` used to be uniformly optional\n// regardless of `type`, so e.g. `createEnvelope('task.offer', payload)` (no\n// `taskId`, no `seq`) type-checked cleanly and only failed much later, at\n// runtime, wherever the resulting envelope happened to get decoded — often\n// on the *other* side of the wire, several hops from the actual mistake.\n//\n// `EnvelopeShapeOptions` is the per-type source of truth for `taskId`/`seq`\n// requiredness, deliberately parallel to `envelope.ts`'s own\n// `envelopeShape()` calls (which encode the identical rule at the schema\n// level — see docs/protocol.md §1.1/§1.2): every `task.*` type requires\n// `taskId`; every type the *server* sends to the daemon additionally\n// requires `seq`. `createEnvelope`'s `opts` parameter is conditionally\n// required/optional per `T` from this map (`RequiredKeys`/`CreateEnvelopeArgs`\n// below), so a call site missing a required field is a compile error, not a\n// runtime surprise. The constructed envelope is also validated against\n// {@link EnvelopeSchema} before being returned, throwing\n// {@link EnvelopeValidationError} on failure — a second, runtime-level net\n// for whatever the type system can't catch (e.g. a payload widened via `as`).\n// ---------------------------------------------------------------------------\n\ninterface EnvelopeShapeOptions {\n 'conn.hello': { taskId?: string; seq?: number };\n 'task.offer': { taskId: string; seq: number };\n 'agent.egress.ack': { taskId?: string; seq: number };\n 'agent.message.disposition': { taskId: string; seq: number };\n 'agent.content.read': { taskId?: string; seq: number };\n 'agent.home.projection': { taskId?: never; seq: number };\n 'agent.input.preparation': { taskId?: never; seq: number };\n 'provider.provisioning.available': { taskId?: never; seq: number };\n 'agent.memory.intent.available': { taskId?: never; seq: number };\n 'task.approve': { taskId: string; seq: number };\n 'task.reject': { taskId: string; seq: number };\n 'task.cancel': { taskId: string; seq: number };\n 'task.steer': { taskId: string; seq: number };\n 'e2ee.key_package.available': { taskId?: never; seq: number };\n 'task.claim': { taskId: string; seq?: number };\n 'task.started': { taskId: string; seq?: number };\n 'task.decline': { taskId: string; seq?: number };\n 'task.progress': { taskId: string; seq?: number };\n 'task.artifact': { taskId: string; seq?: number };\n 'task.await_approval': { taskId: string; seq?: number };\n 'task.complete': { taskId: string; seq?: number };\n 'task.fail': { taskId: string; seq?: number };\n 'task.cancelled': { taskId: string; seq?: number };\n 'task.approval_resolved': { taskId: string; seq?: number };\n 'agent.egress.reliable': { taskId?: string; seq?: number };\n 'agent.message.draft': { taskId: string; seq?: number };\n 'agent.message.publish': { taskId: string; seq?: number };\n 'agent.content.receipt': { taskId?: string; seq?: number };\n}\n\ninterface EnvelopeCommonOptions {\n id?: string;\n ts?: string;\n v?: number;\n /** Always optional regardless of `type` (docs/protocol.md §1.3). */\n sessionRef?: string;\n}\n\n/** Public options shape for `createEnvelope<T>` — conditionally required `taskId`/`seq` per `EnvelopeShapeOptions[T]`, plus the always-optional common fields. Defaults to the full `MessageType` union (a loose, all-optional-ish shape) when `T` isn't pinned, which is also what `createEnvelope`'s own implementation uses internally to read `opts` without fighting the per-call-site conditional. */\nexport type CreateEnvelopeOptions<T extends MessageType = MessageType> = EnvelopeCommonOptions &\n EnvelopeShapeOptions[T];\n\n/** `never` unless every key of `T` is optional — i.e. whether `createEnvelope`'s `opts` argument can be omitted entirely for a given message type. */\ntype RequiredKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];\n\n/** The rest-parameter shape for `createEnvelope`'s 3rd argument: present-and-optional when `T` needs nothing, present-and-required when it needs `taskId` and/or `seq`. */\ntype CreateEnvelopeArgs<T extends MessageType> = RequiredKeys<EnvelopeShapeOptions[T]> extends never\n ? [opts?: CreateEnvelopeOptions<T>]\n : [opts: CreateEnvelopeOptions<T>];\n\ntype PayloadOf<T extends MessageType> = z.infer<(typeof MESSAGE_PAYLOAD_SCHEMAS)[T]>;\n\n/**\n * Build a well-formed {@link Envelope}, filling `v`/`id`/`ts` with defaults.\n * `opts` (`taskId`/`seq`) is required or optional depending on `type` — see\n * the module doc above — and the constructed envelope is validated against\n * {@link EnvelopeSchema} before being returned, throwing\n * {@link EnvelopeValidationError} if it doesn't satisfy the schema.\n */\nexport function createEnvelope<T extends MessageType>(\n type: T,\n payload: PayloadOf<T>,\n ...rest: CreateEnvelopeArgs<T>\n): Extract<Envelope, { type: T }> {\n // `rest[0]`'s precise per-T type doesn't survive being read back out\n // inside a generic function body (a well-known TS limitation, not a\n // soundness gap: every concrete instantiation of `T` at the call site was\n // already checked against `CreateEnvelopeArgs<T>` above) — `opts` is\n // treated as the loose, common shape here, and the schema validation below\n // is what actually guards this function's output either way.\n const opts = (rest[0] ?? {}) as CreateEnvelopeOptions;\n const envelope = {\n v: opts.v ?? PROTOCOL_VERSION,\n id: opts.id ?? crypto.randomUUID(),\n ts: opts.ts ?? new Date().toISOString(),\n type,\n ...(opts.taskId !== undefined ? { task_id: opts.taskId } : {}),\n ...(opts.sessionRef !== undefined ? { session_ref: opts.sessionRef } : {}),\n ...(opts.seq !== undefined ? { seq: opts.seq } : {}),\n payload,\n };\n\n const result = EnvelopeSchema.safeParse(envelope);\n if (!result.success) {\n throw new EnvelopeValidationError(`createEnvelope built an invalid envelope for type \"${type}\"`, result.error);\n }\n return result.data as Extract<Envelope, { type: T }>;\n}\n","import { z } from 'zod';\nimport { PROTOCOL_VERSION } from './version';\nimport { CONTENT_HASH_RE } from './blob';\nimport {\n AgentRefSchema,\n ConfiguredToolsetsSchema,\n ProtocolVersionNumberSchema,\n RuntimeCapabilitiesSchema,\n RuntimeIdSchema,\n RuntimeUnavailableEntrySchema,\n RuntimeVersionPolicyProjectionSchema,\n AgentHomeProjectionAgentRefSchema,\n} from './messages';\nimport {\n InputPreparationProfileIdSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationReceiptSummarySchema,\n InputPreparationRejectionReasonSchema,\n} from './input-preparation';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionOutcomeSchema,\n} from './agent-home-projection';\nimport {\n AgentMemoryProjectionMutationSchema,\n AgentMemoryProjectionReceiptSchema,\n} from './agent-memory-projection';\n\n/**\n * HTTP-side request/response shapes for the reference server's auth and blob\n * endpoints (M1 Part B). These are plain HTTP bodies, not wire envelopes —\n * kept in a separate module from `envelope.ts`/`messages.ts` because they\n * are HTTP request/response bodies rather than mailbox envelopes. Documented\n * in full in docs/protocol.md (\"Auth flows\", \"Blob flows\", \"Long-poll\").\n *\n * The wire protocol version (`v:1`) is unaffected by any of this: pairing,\n * token renewal, and blob transfer are separate HTTP calls around the\n * long-poll mailbox lifecycle, not envelope types.\n */\n\n// ---------------------------------------------------------------------------\n// POST /byok/pair (v2) — one-time device pairing. An out-of-band pairing\n// code (minted by the SaaS's own auth/device-flow UI) plus a freshly\n// generated Ed25519 device keypair (private key never leaves the device)\n// register the device and mint its first access token.\n// ---------------------------------------------------------------------------\n\nexport const PairRequestSchema = z.object({\n pairingCode: z.string(),\n deviceName: z.string(),\n /** Ed25519 public key, base64url-encoded. Private key stays device-local (OS keychain or 0600 file). */\n devicePublicKey: z.string(),\n /**\n * Optional client-hashed physical machine identity: lowercase hex SHA-256 of\n * the product id and an OS-provided machine identifier, never the raw\n * identifier itself. It names no tenant and no product — those still come\n * only from the redeemed pairing code's claims — so it can only ever\n * supersede the SAME tenant/product's prior active device rows carrying this\n * exact digest. A client that cannot resolve one omits the field entirely.\n */\n machineId: z.string().regex(/^[0-9a-f]{64}$/u).optional(),\n});\nexport type PairRequest = z.infer<typeof PairRequestSchema>;\n\n/**\n * The authenticated tenant projection is opaque to the wire protocol. It is\n * bounded so a malformed control-plane value cannot become an unbounded local\n * key prefix, while deliberately imposing no product-specific format.\n *\n * Keep these runtime checks aligned with `@byok-sdk/core`'s TenantId mint\n * point: trimming or normalizing here would make the response disagree with\n * the authenticated device row that authored it.\n */\nexport const PAIR_RESPONSE_TENANT_ID_MAX_LENGTH = 200;\nexport const PairResponseTenantIdSchema = z\n .string()\n .min(1)\n .max(PAIR_RESPONSE_TENANT_ID_MAX_LENGTH)\n .refine((value) => value.trim() === value, {\n message: 'tenantId must not have leading or trailing whitespace',\n })\n .refine((value) => !value.includes('\\u0000'), {\n message: 'tenantId must not contain a NUL character',\n });\n\nexport const PairResponseSchema = z.object({\n deviceId: z.string(),\n /** JWT, ~1h lifetime. */\n accessToken: z.string(),\n /** Opaque hint for when/how to renew (e.g. an ISO timestamp); not itself a credential. */\n refreshHint: z.string().optional(),\n /**\n * Lifetime of `accessToken` in seconds, relative to when the device receives\n * this response. The device-side lifetime authority (#1114): a device never\n * compares a server timestamp with its own clock. Optional on the wire\n * because published v4 hosts omit it; the client requires it.\n */\n expiresIn: z.number().int().positive().optional(),\n /** Exact opaque, non-secret tenant binding from the authenticated device row. */\n tenantId: PairResponseTenantIdSchema,\n});\nexport type PairResponse = z.infer<typeof PairResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/challenge + POST /byok/token — token renewal without re-pairing.\n// Two-step challenge/response proves possession of the device private key\n// without ever transmitting it: the server hands out a one-time nonce, the\n// client signs it locally with the device key, and trades the signature for\n// a fresh access token.\n// ---------------------------------------------------------------------------\n\nexport const ChallengeRequestSchema = z.object({\n deviceId: z.string(),\n});\nexport type ChallengeRequest = z.infer<typeof ChallengeRequestSchema>;\n\nexport const ChallengeResponseSchema = z.object({\n /** One-time value the client must sign with its device private key. */\n nonce: z.string(),\n});\nexport type ChallengeResponse = z.infer<typeof ChallengeResponseSchema>;\n\nexport const TokenRequestSchema = z.object({\n deviceId: z.string(),\n nonce: z.string(),\n /** Ed25519 signature over `nonce`, base64url-encoded. */\n signature: z.string(),\n});\nexport type TokenRequest = z.infer<typeof TokenRequestSchema>;\n\nexport const TokenResponseSchema = z.object({\n accessToken: z.string(),\n /** Absolute server-clock expiry. Kept for published devices; current devices derive lifetime from `expiresIn`. */\n expiresAt: z.iso.datetime({ offset: true }),\n /**\n * Lifetime of `accessToken` in seconds, relative to when the device receives\n * this response (#1114). Optional on the wire because published v4 hosts\n * omit it; the client requires it.\n */\n expiresIn: z.number().int().positive().optional(),\n});\nexport type TokenResponse = z.infer<typeof TokenResponseSchema>;\n\n/**\n * The one typed `401` body of `/byok/challenge` and `/byok/token`: the device\n * id resolves to no registration (§6.3). Revocation deletes the registration,\n * so an unknown device and a revoked one answer with this same body and stay\n * indistinguishable. Every other `401` on these routes (bad signature, used\n * or expired nonce) stays untyped, and a client must not read it as\n * revocation.\n */\nexport const DEVICE_NOT_REGISTERED_CODE = 'device_not_registered';\nexport const DeviceNotRegisteredResponseSchema = z.object({\n error: z.string(),\n code: z.literal(DEVICE_NOT_REGISTERED_CODE),\n});\nexport type DeviceNotRegisteredResponse = z.infer<typeof DeviceNotRegisteredResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// PUT /byok/presence — first-hop daemon observation. The body carries only\n// facts captured by the daemon's frozen start snapshot; omitted release,\n// runtime, and auth fields remain unknown rather than guessed.\n// ---------------------------------------------------------------------------\n\n/** The hosted default is byte-bounded independently; this caps protocol input before it reaches a handler. */\nexport const PRESENCE_DETAIL_MAX_LENGTH = 512;\nexport const PRESENCE_RUNTIME_VERSION_MAX_LENGTH = 128;\n\n/**\n * Presence is a readiness observation. It retains only the facts the cloud\n * persists and bounds every string/array/numeric input at this public request\n * boundary. `capabilities` is the same capability matrix `conn.hello` reports\n * for the runtime (#1103), so a Host can read it before dispatch.\n */\nconst PresenceRuntimeFactSchema = z.object({\n id: RuntimeIdSchema,\n version: z.string().min(1).max(PRESENCE_RUNTIME_VERSION_MAX_LENGTH).optional(),\n authPresent: z.boolean().optional(),\n capabilities: RuntimeCapabilitiesSchema.optional(),\n /** #1103 D8: strip-safe discovery projection; absent means unknown. */\n versionPolicy: RuntimeVersionPolicyProjectionSchema.optional(),\n});\n\n/**\n * Presence carries the built-in runtime identity domain only (#1103 D8): a\n * custom harness id would fail an older server's whole-body decode, so\n * harness policies and versions travel on `conn.hello.harnesses[]`, never\n * here. The cause vocabulary is the same append-only one.\n */\nconst PresenceRuntimeUnavailableEntrySchema = RuntimeUnavailableEntrySchema.extend({ id: RuntimeIdSchema });\nconst PresenceRuntimeUnavailableSchema = z.array(PresenceRuntimeUnavailableEntrySchema).max(16)\n .refine(values => new Set(values.map(value => value.id)).size === values.length, 'duplicate runtime-unavailable identity');\n\nexport const PresencePublishRequestSchema = z.object({\n level: z.enum(['online', 'thinking', 'working', 'error', 'offline']),\n detail: z.string().max(PRESENCE_DETAIL_MAX_LENGTH).optional(),\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n /** U4a Local Agent release version; never inferred from a host package. */\n clientVersion: z.string().min(1).max(128).optional(),\n protocolVersions: z.array(ProtocolVersionNumberSchema).max(16).optional(),\n /** Runtime version/auth facts from the same real probe as conn.hello. */\n runtimes: z.array(PresenceRuntimeFactSchema).max(16).optional(),\n /** #1103 D8: non-available built-in runtimes; strip-safe and absent means unknown. */\n runtimeUnavailable: PresenceRuntimeUnavailableSchema.optional(),\n});\nexport type PresencePublishRequest = z.infer<typeof PresencePublishRequestSchema>;\n\n/**\n * Revocation is server-side only (dashboard/API call on the SaaS's own\n * device registry) — there is no wire message for it. A revoked device's\n * next `/byok/challenge`, `/byok/token`, or authenticated mailbox call gets a 401;\n * the daemon's only recourse is to re-run `/byok/pair` from scratch.\n */\n\n// ---------------------------------------------------------------------------\n// Blob endpoints — presigned upload/download. Authed (bearer access token).\n// `BlobRef` (`blob.ts`) is unchanged; these are the HTTP calls that produce\n// the presigned URLs a `BlobRef` points at.\n// ---------------------------------------------------------------------------\n\n/** POST /byok/blobs request: declare a blob before uploading it. `contentHash` must be the canonical `sha256:<64 lowercase hex>` form (finding F9) — the server rejects anything else outright, no normalization. */\nexport const CreateBlobRequestSchema = z.object({\n size: z.number().int().nonnegative(),\n contentType: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be \"sha256:<64 lowercase hex>\"'),\n});\nexport type CreateBlobRequest = z.infer<typeof CreateBlobRequestSchema>;\n\n/** POST /byok/blobs response: presigned PUT target for the declared blob. */\nexport const CreateBlobResponseSchema = z.object({\n blobId: z.string(),\n uploadUrl: z.string(),\n});\nexport type CreateBlobResponse = z.infer<typeof CreateBlobResponseSchema>;\n\n/** GET /byok/blobs/:id/url response: presigned GET target for an existing blob. */\nexport const BlobDownloadUrlResponseSchema = z.object({\n downloadUrl: z.string(),\n});\nexport type BlobDownloadUrlResponse = z.infer<typeof BlobDownloadUrlResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// GET /byok/events?cursor=N — the daemon's authenticated receive transport.\n// Holds the request open ~50s waiting for new events and uses the mailbox's\n// at-least-once/cursor semantics (see docs/protocol.md \"At-least-once delivery\").\n// ---------------------------------------------------------------------------\n\nexport const EventsPollQuerySchema = z.object({\n /** Volatile navigation within the advertised read-ahead window; never acknowledges work. */\n afterSeq: z.number().int().nonnegative().optional(),\n /** Last reliably processed seq; the only acknowledgement. Omitted on the first poll. */\n cursor: z.number().int().nonnegative().optional(),\n});\nexport type EventsPollQuery = z.infer<typeof EventsPollQuerySchema>;\n\n/**\n * Deployment-owned activity limits. A v3 responder advertises them on every\n * events page and on every answer whose `conn.hello` it accepted; there is no\n * client-side default.\n */\nexport const ActivityIngressSchema = z.object({\n activityMaxEvents: z.number().int().positive(),\n activityMaxBytes: z.number().int().min(2),\n});\nexport type ActivityIngress = z.infer<typeof ActivityIngressSchema>;\nexport const OUTBOUND_REFUSAL_REASONS = ['payload_invalid', 'not_permitted', 'limit_exceeded', 'state_conflict', 'unsupported'] as const;\n/** `unknown` is an unrecognized wire reason string, kept as an observation. */\nexport type OutboundRefusalReason = typeof OUTBOUND_REFUSAL_REASONS[number] | 'unknown';\nfunction isOutboundRefusalCode(value: string): value is typeof OUTBOUND_REFUSAL_REASONS[number] {\n return (OUTBOUND_REFUSAL_REASONS as readonly string[]).includes(value);\n}\nexport const MessageSendOutcomeSchema = z.object({\n id: z.uuid(),\n outcome: z.enum(['accepted', 'duplicate', 'rejected']),\n /** Decodes to an {@link OutboundRefusalReason}; an unrecognized string becomes `unknown`. */\n reason: z.string().max(64).transform((value): OutboundRefusalReason => (isOutboundRefusalCode(value) ? value : 'unknown')).optional(),\n});\nexport type MessageSendOutcome = z.infer<typeof MessageSendOutcomeSchema>;\n\nexport const EventsPollResponseSchema = z.object({\n /**\n * Not-yet-decoded entries (#386). This schema decodes the page only; each\n * entry is decoded on its own with `parseMessage`, so one unknown or invalid\n * entry stalls its own sequence instead of failing every entry in the page.\n */\n events: z.array(z.unknown()),\n cursor: z.number().int(),\n /**\n * Required: the server capabilities for THIS long-poll response. Each page\n * replaces the daemon's advertisement; an empty list advertises nothing.\n */\n capabilities: z.array(z.string()),\n /** Required in v3: the activity limits that apply to new progress pushes. */\n ingress: ActivityIngressSchema,\n});\nexport type EventsPollResponse = z.infer<typeof EventsPollResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/messages — finding F6: long-poll is now a full transport, not\n// receive-only. While a device is long-polling for S->D traffic (§8), it has\n// no live WS to carry its own D->S envelopes (task.claim, task.progress,\n// task.complete, etc.) — this endpoint is that path: a batch of envelopes,\n// authed the same way as every other bearer-authed route, routed through the\n// identical inbound handling a WS connection's messages get. See\n// docs/protocol.md §8.\n// ---------------------------------------------------------------------------\n\n/**\n * Batch size ceiling for a single `POST /byok/messages` call — generous for\n * normal redelivery-catchup bursts, but bounded so one request can't force\n * the server to process an unbounded batch. Exported (not just a local\n * const) so the client's own outbound drain (`ConnectionManager.drainOutbox`,\n * finding P1) can chunk against the exact same number instead of a\n * hard-coded, driftable copy of it.\n */\nexport const MAX_MESSAGES_PER_BATCH = 256;\n\n/** Request body ceiling for `POST /byok/messages`; the cloud answers 413 above it, so the client chunks its drain by it. */\nexport const MESSAGES_SEND_MAX_BODY_BYTES = 2 * 1024 * 1024;\n\n/**\n * The batch frame only (#1121). Each entry must speak this wire major and\n * carry the UUID its outcome is correlated by; everything else is decoded per\n * entry with `parseMessage`, so one invalid envelope is answered\n * `rejected: payload_invalid` on its own instead of failing every envelope in\n * the batch — the same split as `EventsPollResponseSchema.events` (#386) on\n * the receive side. A different `v` still fails the whole request: the wire\n * major belongs to the sender, which could not read this version's outcomes.\n */\nexport const MessagesSendRequestSchema = z.object({\n messages: z.array(z.looseObject({ v: z.literal(PROTOCOL_VERSION), id: z.uuid() })).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendRequest = z.infer<typeof MessagesSendRequestSchema>;\n\n/**\n * `accepted` counts every envelope the inbound gate (`@byok-sdk/cloud`'s\n * `handleInboundEnvelope`) answered `'accepted'` *or* `'duplicate'` for — a deduped replay is a wire-level\n * success even though the business mutation did not run a second time.\n * `rejected` is omitted when zero. `outcomes` is required and correlates\n * exactly one result with each posted envelope; a rejected outcome carries its\n * reason. `ingress` is required on an answer whose `conn.hello` was accepted\n * (or deduplicated). The client enforces the per-envelope rules against the\n * posted batch and treats a violation as an unusable response.\n *\n * `capabilities` (additive) is the same server capability advertisement a\n * `GET /byok/events` response carries. A server includes it when the batch\n * carries `conn.hello`: the daemon's handshake is a lone `conn.hello` POST,\n * so its answer carries readiness and capabilities in one round trip.\n * Absence means \"no update\" — the daemon keeps the advertisement it already\n * holds — never an empty list.\n */\nexport const MessagesSendResponseSchema = z.object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative().optional(),\n capabilities: z.array(z.string()).optional(),\n ingress: ActivityIngressSchema.optional(),\n outcomes: z.array(MessageSendOutcomeSchema).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendResponse = z.infer<typeof MessagesSendResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// Task-free Agent-home projection completion/readback. These are authenticated\n// HTTP bodies, not daemon/server envelope messages. The completion request is\n// terminal and binds the exact request, AgentRef and projection hash; the\n// readback additionally carries the tenant/device routing identity and allows\n// `pending` before a daemon completion is durably recorded.\n// ---------------------------------------------------------------------------\n\nexport const AgentHomeProjectionCompletionRequestSchema = z\n .object({\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n outcome: AgentHomeProjectionOutcomeSchema,\n })\n .strict();\nexport type AgentHomeProjectionCompletionRequest = z.infer<typeof AgentHomeProjectionCompletionRequestSchema>;\n\nexport const AgentHomeProjectionStatusSchema = z.enum([\n 'pending',\n 'applied',\n 'idempotent',\n 'stale',\n 'conflict',\n]);\nexport type AgentHomeProjectionStatus = z.infer<typeof AgentHomeProjectionStatusSchema>;\n\nexport const AgentHomeProjectionReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n agentRef: AgentHomeProjectionAgentRefSchema,\n projectionHash: AgentHomeProjectionHashSchema,\n status: AgentHomeProjectionStatusSchema,\n completedAt: z.iso.datetime({ offset: true }).optional(),\n })\n .strict();\nexport type AgentHomeProjectionReadback = z.infer<typeof AgentHomeProjectionReadbackSchema>;\n\n// ---------------------------------------------------------------------------\n// Remote input preparation completion/readback. Same shape as the Agent-home\n// pair above and for the same reason: the device -> cloud leg of a task-free\n// control request is a direct AUTHENTICATED HTTP call, not a mailbox envelope,\n// because the daemon may advance its server -> daemon cursor only once the\n// terminal fact is durably recorded — and an outbox envelope gives it nothing\n// to wait on.\n//\n// The completion is a discriminated union rather than an outcome enum plus\n// optional siblings: `prepared` without a receipt, or `rejected` carrying one,\n// must both be unrepresentable rather than merely discouraged.\n// ---------------------------------------------------------------------------\n\nexport const InputPreparationCompletionRequestSchema = z.discriminatedUnion('outcome', [\n z\n .object({\n outcome: z.literal('prepared'),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n receipt: InputPreparationReceiptSummarySchema,\n })\n .strict(),\n z\n .object({\n outcome: z.literal('rejected'),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n reason: InputPreparationRejectionReasonSchema,\n })\n .strict(),\n]);\nexport type InputPreparationCompletionRequest = z.infer<typeof InputPreparationCompletionRequestSchema>;\n\n/** `pending` until the device records a terminal fact; the other two are terminal. */\nexport const InputPreparationStatusSchema = z.enum(['pending', 'prepared', 'rejected']);\nexport type InputPreparationStatus = z.infer<typeof InputPreparationStatusSchema>;\n\n/**\n * Tenant/device/request-bound durable readback. `receipt` and `reason` are\n * present only on their own terminal status, never together and never on\n * `pending`.\n */\nexport const InputPreparationReadbackSchema = z\n .object({\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\n requestId: z.uuid(),\n agentRef: AgentRefSchema,\n profileId: InputPreparationProfileIdSchema,\n policyRevision: InputPreparationPolicyRevisionSchema,\n status: InputPreparationStatusSchema,\n receipt: InputPreparationReceiptSummarySchema.optional(),\n reason: InputPreparationRejectionReasonSchema.optional(),\n completedAt: z.iso.datetime({ offset: true }).optional(),\n })\n .strict()\n .superRefine((value, ctx) => {\n const expectsReceipt = value.status === 'prepared';\n const expectsReason = value.status === 'rejected';\n if (expectsReceipt !== (value.receipt !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['receipt'], message: 'receipt is present exactly when status is \"prepared\"' });\n }\n if (expectsReason !== (value.reason !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['reason'], message: 'reason is present exactly when status is \"rejected\"' });\n }\n if ((value.status !== 'pending') !== (value.completedAt !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['completedAt'], message: 'completedAt is present exactly when the status is terminal' });\n }\n });\nexport type InputPreparationReadback = z.infer<typeof InputPreparationReadbackSchema>;\n\n/**\n * Query identity for the status GET. The request key is\n * `(deviceId, agentRef, requestId)`; `deviceId` comes from bearer auth, the\n * path carries `requestId`, so only the AgentRef halves travel as query\n * parameters.\n */\nexport const InputPreparationStatusQuerySchema = z\n .object({\n agentId: z.string().min(1),\n profileRevision: z.string().min(1),\n })\n .strict();\nexport type InputPreparationStatusQuery = z.infer<typeof InputPreparationStatusQuerySchema>;\n\n// ---------------------------------------------------------------------------\n// POST /byok/agent-memory-projections — optional hosted, redacted, one-way\n// snapshots. Tenant and device identity come only from bearer authentication.\n// ---------------------------------------------------------------------------\n\nexport const AgentMemoryProjectionCommitRequestSchema = AgentMemoryProjectionMutationSchema;\nexport type AgentMemoryProjectionCommitRequest = z.infer<typeof AgentMemoryProjectionCommitRequestSchema>;\n\nexport const AgentMemoryProjectionCommitResponseSchema = AgentMemoryProjectionReceiptSchema;\nexport type AgentMemoryProjectionCommitResponse = z.infer<typeof AgentMemoryProjectionCommitResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// Route paths — the single source of truth for the `/byok/*` HTTP surface.\n//\n// These literals were previously hand-copied across client, cloud, server, and\n// testkit; the doc comments above already named every one of them but exported\n// no constant. They ARE the wire contract (unlike the host-owned, opaque\n// capability vocabulary of ADR-010, which stays out of protocol), so they live\n// here and every package imports them — a route change is now one edit.\n//\n// Two shapes:\n// - Static paths (`BYOK_*_PATH`) — used identically by routers and clients.\n// - Parameterized routes: a router template (`BYOK_*_ROUTE`, with `:param`\n// placeholders) for mounting, plus a builder (`byok*Path(...)`) that fills\n// the params for a client request. Each builder reproduces its call site\n// byte-for-byte, including whether a segment is `encodeURIComponent`-encoded.\n// ---------------------------------------------------------------------------\n\n/** `POST /byok/pair` — one-time device pairing (§6). */\nexport const BYOK_PAIR_PATH = '/byok/pair';\n/** `POST /byok/challenge` — token-renewal challenge (§6.3). */\nexport const BYOK_CHALLENGE_PATH = '/byok/challenge';\n/** `POST /byok/token` — token-renewal exchange (§6.3). */\nexport const BYOK_TOKEN_PATH = '/byok/token';\n\n/** `GET /byok/capabilities` — ADR-010 declaration route. */\nexport const BYOK_CAPABILITIES_PATH = '/byok/capabilities';\n\n/** `GET /byok/events` — long-poll receive (§8). */\nexport const BYOK_EVENTS_PATH = '/byok/events';\n/** `POST /byok/messages` — long-poll batched send (§8.2). */\nexport const BYOK_MESSAGES_PATH = '/byok/messages';\n\n/** `PUT /byok/agent-home-projections/:requestId/completion`. */\nexport const BYOK_AGENT_HOME_PROJECTIONS_PATH = '/byok/agent-home-projections';\nexport const BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE =\n '/byok/agent-home-projections/:requestId/completion';\nexport function byokAgentHomeProjectionCompletionPath(requestId: string): string {\n return `${BYOK_AGENT_HOME_PROJECTIONS_PATH}/${encodeURIComponent(requestId)}/completion`;\n}\n\n/** `PUT /byok/input-preparations/:requestId/completion` and `GET /byok/input-preparations/:requestId`. */\nexport const BYOK_INPUT_PREPARATIONS_PATH = '/byok/input-preparations';\nexport const BYOK_INPUT_PREPARATION_COMPLETION_ROUTE = '/byok/input-preparations/:requestId/completion';\nexport const BYOK_INPUT_PREPARATION_STATUS_ROUTE = '/byok/input-preparations/:requestId';\nexport function byokInputPreparationCompletionPath(requestId: string): string {\n return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}/completion`;\n}\nexport function byokInputPreparationStatusPath(requestId: string): string {\n return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}`;\n}\n\n/** `POST /byok/agent-memory-projections` — optional local-to-hosted redacted snapshot commit. */\nexport const BYOK_AGENT_MEMORY_PROJECTIONS_PATH = '/byok/agent-memory-projections';\n\n/** `PUT /byok/presence` — presence heartbeat. */\nexport const BYOK_PRESENCE_PATH = '/byok/presence';\n\n/** `GET /byok/board` — coordination board list/poll. */\nexport const BYOK_BOARD_PATH = '/byok/board';\n/** `GET /byok/board/stream` — coordination board SSE. */\nexport const BYOK_BOARD_STREAM_PATH = '/byok/board/stream';\n/** Router template — `POST /byok/board/:id/claim`. */\nexport const BYOK_BOARD_CLAIM_ROUTE = '/byok/board/:id/claim';\n/** Router template — `POST /byok/board/:id/unclaim`. */\nexport const BYOK_BOARD_UNCLAIM_ROUTE = '/byok/board/:id/unclaim';\n/** Router template — `POST /byok/board/:id/status`. */\nexport const BYOK_BOARD_STATUS_ROUTE = '/byok/board/:id/status';\n\n/** `GET /byok/records` — truth manifest list (§12.3). */\nexport const BYOK_RECORDS_PATH = '/byok/records';\n/** Router template for a single truth record — `GET`/`PUT /byok/records/:kind/:key`. */\nexport const BYOK_RECORD_ROUTE = '/byok/records/:kind/:key';\n/** Client builder for a truth record path. Mirrors the `:kind/:key` template, each segment URL-encoded. */\nexport function byokRecordPath(kind: string, key: string): string {\n return `/byok/records/${encodeURIComponent(kind)}/${encodeURIComponent(key)}`;\n}\n\n/** `POST /byok/e2ee/member-key` — device proof: register the device's member key bundle and pairing MAC (#654). */\nexport const BYOK_E2EE_MEMBER_KEY_PATH = '/byok/e2ee/member-key';\n/** `POST /byok/e2ee/chain` (device proof: append) and `GET` (device: read) — the member chain. */\nexport const BYOK_E2EE_CHAIN_PATH = '/byok/e2ee/chain';\n/** `POST /byok/e2ee/key-packages` (device proof: put) and `GET` (device: this device's packages). */\nexport const BYOK_E2EE_KEY_PACKAGES_PATH = '/byok/e2ee/key-packages';\n/** `GET /byok/e2ee/pairing-mac` — device: the client pairing MAC relayed to this device. */\nexport const BYOK_E2EE_PAIRING_MAC_PATH = '/byok/e2ee/pairing-mac';\n\n/** `GET /byok/skill-packs` — skill-pack manifest catalogue. */\nexport const BYOK_SKILL_PACKS_PATH = '/byok/skill-packs';\n/** Router template for a skill-pack file — `GET /byok/skill-packs/:name/files/:path`. */\nexport const BYOK_SKILL_PACK_FILE_ROUTE = '/byok/skill-packs/:name/files/:path';\n/** Client builder for a skill-pack file path. Mirrors the `:name`/`:path` template, each segment URL-encoded. */\nexport function byokSkillPackFilePath(name: string, path: string): string {\n return `/byok/skill-packs/${encodeURIComponent(name)}/files/${encodeURIComponent(path)}`;\n}\n\n/** `POST /byok/blobs` — declare a blob upload (§7). */\nexport const BYOK_BLOBS_PATH = '/byok/blobs';\n/** Router template — `POST /byok/blobs/:id/finalize`. */\nexport const BYOK_BLOB_FINALIZE_ROUTE = '/byok/blobs/:id/finalize';\n/** Router template — `GET /byok/blobs/:id/url`. */\nexport const BYOK_BLOB_URL_ROUTE = '/byok/blobs/:id/url';\n/** Router template for the two presigned byte routes — `PUT`/`GET /byok/blobs/:id/content`. */\nexport const BYOK_BLOB_CONTENT_ROUTE = '/byok/blobs/:id/content';\n/** Client builder — `POST /byok/blobs/:id/finalize`, blob id URL-encoded (client-supplied). */\nexport function byokBlobFinalizePath(blobId: string): string {\n return `/byok/blobs/${encodeURIComponent(blobId)}/finalize`;\n}\n/** Client builder — `GET /byok/blobs/:id/url`, blob id URL-encoded (client-supplied). */\nexport function byokBlobUrlPath(blobId: string): string {\n return `/byok/blobs/${encodeURIComponent(blobId)}/url`;\n}\n/**\n * Path portion of a presigned `/byok/blobs/:id/content` URL. The blob id here\n * is a server-minted token (NOT URL-encoded, matching the reference stores that\n * mint these signed URLs); callers append the `?sig=&exp=` query themselves.\n */\nexport function byokBlobContentPath(blobId: string): string {\n return `/byok/blobs/${blobId}/content`;\n}\n","import {\n RESULT_OUTCOME_MAX_BYTES, RESULT_SCHEMA_MAX_BYTES, checkResultSchema, type ResultSchema,\n resultOutcomeMaxBytes,\n} from './result-schema';\n\nexport const BOT_TURN_OUTCOME_CONTRACT = 'bot-turn-outcome.v1';\n\n/** Code-point and item caps for Bot turn outcomes. */\nexport const BOT_TURN_OUTCOME_LIMITS = Object.freeze({\n delegateMaxItems: 2,\n delegateRequestMaxLength: 1_000,\n cancelDelegationMaxItems: 2,\n askUserQuestionMaxLength: 400,\n askUserOptionsMaxItems: 6,\n askUserOptionIdMaxLength: 24,\n askUserOptionLabelMaxLength: 80,\n confirmableActionMaxItems: 1,\n confirmableSummaryMaxLength: 300,\n confirmableDraftMaxBytes: 16_384,\n createRoutineMaxItems: 1,\n updateRoutineMaxItems: 1,\n cancelRoutineMaxItems: 2,\n routinePromptMaxLength: 500,\n postTextMaxLength: 2_730,\n roomCallMembersMaxItems: 4,\n createBotMaxItems: 3,\n updateBotMaxItems: 1,\n deleteBotMaxItems: 1,\n botNameMaxLength: 40,\n botRoleMaxLength: 80,\n botPersonaMaxLength: 300,\n createRoomMaxItems: 1,\n updateRoomMaxItems: 1,\n roomNameMaxLength: 40,\n roomMembersMaxItems: 12,\n roomAnnouncementMaxLength: 300,\n teamNoteMaxLength: 300,\n});\nconst L = BOT_TURN_OUTCOME_LIMITS;\n\nexport type NonEmptyIds = readonly [string, ...string[]];\nconst text = (maxLength: number): ResultSchema =>\n ({ type: 'string', minLength: 1, maxLength });\nconst oneOfIds = (ids: NonEmptyIds): ResultSchema => ({ enum: [...ids] });\nconst closed = (properties: Record<string, ResultSchema>, required: string[]): ResultSchema =>\n ({ type: 'object', additionalProperties: false, required, properties });\nconst list = (items: ResultSchema, maxItems: number): ResultSchema =>\n ({ type: 'array', minItems: 1, maxItems, items });\n\n/** ISO 8601 order, Monday first. Equal to core's list. A server test checks parity. */\nexport const ROUTINE_DAYS_OF_WEEK = Object.freeze(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const);\nexport type RoutineDayOfWeek = (typeof ROUTINE_DAYS_OF_WEEK)[number];\nconst integer = (minimum: number, maximum: number): ResultSchema => ({ type: 'integer', minimum, maximum });\n\nexport type BotTurnOutcomeSchemaErrorCode = 'not-subset' | 'schema-over-budget' | 'over-budget' | 'draft-over-budget';\n\nexport class BotTurnOutcomeSchemaError extends Error {\n constructor(readonly code: BotTurnOutcomeSchemaErrorCode, message: string) {\n super(message); this.name = 'BotTurnOutcomeSchemaError';\n }\n}\n\n/**\n * `checked` (default): field types, ranges and enums sit once in the outer\n * properties; each oneOf branch lists only its allowed names and required\n * fields, with additionalProperties false. An instance matches exactly one\n * branch: daysOfWeek and dayOfMonth never appear together; month needs\n * dayOfMonth. `flat`: the same outer object without the oneOf; the Host then\n * refuses those two combinations at apply time. Use `flat` only under the\n * schema budget rule of composeBotTurnOutcomeSchema. Neither form sees\n * duplicate days, a day the month never has (Apr 31), or Feb 29.\n */\nexport type RoutineScheduleShape = 'checked' | 'flat';\nfunction schedule(timeZones: NonEmptyIds, shape: RoutineScheduleShape): ResultSchema {\n const fields = {\n minute: integer(0, 59), hour: integer(0, 23),\n daysOfWeek: { type: 'array', minItems: 1, maxItems: 7, items: { enum: [...ROUTINE_DAYS_OF_WEEK] } } as ResultSchema,\n dayOfMonth: integer(1, 31), month: integer(1, 12), tz: oneOfIds(timeZones),\n };\n const outer: ResultSchema = {\n description: 'Local time in tz. No day field: every day. daysOfWeek: those days only. dayOfMonth: that day of each month, or of month only.',\n ...closed(fields, ['minute', 'hour', 'tz']),\n };\n if (shape === 'flat') return outer;\n // The outer object already requires minute, hour and tz; a branch adds only its own day field.\n const only = (names: string[], required: string[]): ResultSchema =>\n ({ additionalProperties: false, ...(required.length ? { required } : {}), properties: Object.fromEntries(names.map(n => [n, {}])) });\n return { ...outer, oneOf: [\n only(['minute', 'hour', 'tz'], []),\n only(['minute', 'hour', 'daysOfWeek', 'tz'], ['daysOfWeek']),\n only(['minute', 'hour', 'dayOfMonth', 'month', 'tz'], ['dayOfMonth']),\n ] };\n}\nfunction roomFields(members: NonEmptyIds): Record<string, ResultSchema> {\n return {\n name: text(L.roomNameMaxLength),\n members: { type: 'array', minItems: 1, maxItems: L.roomMembersMaxItems, items: oneOfIds(members) },\n admin: oneOfIds(members), mode: { enum: ['mention', 'admin'] }, announcement: text(L.roomAnnouncementMaxLength),\n };\n}\n\n/**\n * Every id is a Host-filled enum. New objects use Host-offered localId slots\n * (e.g. \"new_bot_1\"), so a same-outcome reference is also an enum member.\n */\nexport const botTurnOutcomeFragments = {\n /** `to` lists this Bot first: delegating to yourself is a continuation. */\n delegate(o: { to: NonEmptyIds }): ResultSchema {\n return list(closed({ to: oneOfIds(o.to), request: text(L.delegateRequestMaxLength) }, ['to', 'request']), L.delegateMaxItems);\n },\n /** Owner-authorized Main Bot turns only. The Host lists open delegations. */\n cancelDelegation(o: { delegationIds: NonEmptyIds }): ResultSchema {\n return list(closed({ delegationId: oneOfIds(o.delegationIds) }, ['delegationId']), L.cancelDelegationMaxItems);\n },\n askUser(): ResultSchema {\n const question = text(L.askUserQuestionMaxLength);\n const option = closed({ id: text(L.askUserOptionIdMaxLength), label: text(L.askUserOptionLabelMaxLength) }, ['id', 'label']);\n return { oneOf: [\n closed({ question, answerKind: { const: 'text' } }, ['question', 'answerKind']),\n closed({ question, answerKind: { const: 'single_choice' },\n options: { type: 'array', minItems: 2, maxItems: L.askUserOptionsMaxItems, items: option } }, ['question', 'answerKind', 'options']),\n ] };\n },\n /** One branch per Host action; each draft needs a finite bound of at most confirmableDraftMaxBytes. */\n confirmableAction(o: { actions: readonly [{ action: string; draft: ResultSchema }, ...{ action: string; draft: ResultSchema }[]] }): ResultSchema {\n for (const { action, draft } of o.actions) {\n const bound = resultOutcomeMaxBytes(draft);\n if (bound === null || bound > L.confirmableDraftMaxBytes) {\n throw new BotTurnOutcomeSchemaError('draft-over-budget', `draft for ${action} is ${bound ?? 'unbounded'}; cap ${L.confirmableDraftMaxBytes}`);\n }\n }\n const branches = o.actions.map(({ action, draft }) =>\n closed({ action: { const: action }, summary: text(L.confirmableSummaryMaxLength), draft }, ['action', 'summary', 'draft']));\n return list(branches.length === 1 ? branches[0]! : { oneOf: branches }, L.confirmableActionMaxItems);\n },\n /** `targets` only for a Main Bot: the Bot itself first, then team Bots. Omitted means the Bot itself. */\n createRoutine(o: { localIds: NonEmptyIds; timeZones: NonEmptyIds; targets?: NonEmptyIds; scheduleShape?: RoutineScheduleShape }): ResultSchema {\n return list(closed({\n localId: oneOfIds(o.localIds), schedule: schedule(o.timeZones, o.scheduleShape ?? 'checked'), prompt: text(L.routinePromptMaxLength),\n ...(o.targets ? { target: oneOfIds(o.targets) } : {}),\n }, ['localId', 'schedule', 'prompt']), L.createRoutineMaxItems);\n },\n updateRoutine(o: { routineIds: NonEmptyIds; timeZones: NonEmptyIds; scheduleShape?: RoutineScheduleShape }): ResultSchema {\n return list(closed({ routineId: oneOfIds(o.routineIds), schedule: schedule(o.timeZones, o.scheduleShape ?? 'checked'), prompt: text(L.routinePromptMaxLength) },\n ['routineId']), L.updateRoutineMaxItems);\n },\n cancelRoutine(o: { routineIds: NonEmptyIds }): ResultSchema {\n return list(closed({ routineId: oneOfIds(o.routineIds) }, ['routineId']), L.cancelRoutineMaxItems);\n },\n /** Room turns only. Exactly one of post or pass. */\n speech(): ResultSchema {\n return { oneOf: [\n closed({ kind: { const: 'post' }, text: text(L.postTextMaxLength) }, ['kind', 'text']),\n closed({ kind: { const: 'pass' } }, ['kind']),\n ] };\n },\n roomCall(o: { members: NonEmptyIds }): ResultSchema {\n return closed({ members: { type: 'array', minItems: 1, maxItems: L.roomCallMembersMaxItems, items: oneOfIds(o.members) } }, ['members']);\n },\n createBot(o: { localIds: NonEmptyIds; models: NonEmptyIds }): ResultSchema {\n return list(closed({\n localId: oneOfIds(o.localIds), name: text(L.botNameMaxLength), role: text(L.botRoleMaxLength),\n persona: text(L.botPersonaMaxLength), model: oneOfIds(o.models),\n }, ['localId', 'name', 'role', 'persona', 'model']), L.createBotMaxItems);\n },\n updateBot(o: { botIds: NonEmptyIds; models: NonEmptyIds }): ResultSchema {\n return list(closed({\n botId: oneOfIds(o.botIds), name: text(L.botNameMaxLength), role: text(L.botRoleMaxLength),\n persona: text(L.botPersonaMaxLength), model: oneOfIds(o.models),\n }, ['botId']), L.updateBotMaxItems);\n },\n deleteBot(o: { botIds: NonEmptyIds }): ResultSchema {\n return list(closed({ botId: oneOfIds(o.botIds) }, ['botId']), L.deleteBotMaxItems);\n },\n /** `members`: team Bot ids plus the create_bot localId slots of this outcome. */\n createRoom(o: { localIds: NonEmptyIds; members: NonEmptyIds }): ResultSchema {\n return list(closed({ localId: oneOfIds(o.localIds), ...roomFields(o.members) }, ['localId', 'name', 'members']), L.createRoomMaxItems);\n },\n updateRoom(o: { roomIds: NonEmptyIds; members: NonEmptyIds }): ResultSchema {\n return list(closed({ roomId: oneOfIds(o.roomIds), ...roomFields(o.members) }, ['roomId']), L.updateRoomMaxItems);\n },\n teamNote(): ResultSchema {\n return closed({ text: text(L.teamNoteMaxLength) }, ['text']);\n },\n};\n\nexport type BotTurnOutcomeKind =\n | 'delegate' | 'cancel_delegation' | 'ask_user' | 'confirmable_action' | 'create_routine' | 'update_routine' | 'cancel_routine'\n | 'speech' | 'room_call' | 'create_bot' | 'update_bot' | 'delete_bot' | 'create_room' | 'update_room' | 'team_note';\n\n/**\n * Host composition: pick fragments, freeze the result in the offer. Refuses a\n * schema outside the K7 subset ('not-subset'), a schema above\n * RESULT_SCHEMA_MAX_BYTES ('schema-over-budget'), or one whose largest\n * instance could exceed RESULT_OUTCOME_MAX_BYTES ('over-budget').\n *\n * Schema budget rule, before the offer is frozen: only 'schema-over-budget'\n * allows the Host to rebuild the routine fragments with scheduleShape 'flat'.\n * If the schema is still over, the Host blocks the turn with a visible reason\n * or runs its defined batch selection. It never drops authorized ids from an\n * enum silently.\n */\nexport function composeBotTurnOutcomeSchema(\n fragments: BotTurnOutcomeFragments,\n required: readonly BotTurnOutcomeKind[] = [],\n): ResultSchema {\n const schema: ResultSchema = {\n type: 'object', additionalProperties: false,\n description: `${BOT_TURN_OUTCOME_CONTRACT}: actions for the Host. Omit a field for no action of that kind; {} means no actions.`,\n ...(required.length ? { required: [...required] } : {}),\n properties: fragments,\n };\n const admitted = checkResultSchema(schema);\n if (!admitted.ok && admitted.reason === 'over-cap') {\n throw new BotTurnOutcomeSchemaError('schema-over-budget', `schema is ${admitted.bytes} bytes; cap ${RESULT_SCHEMA_MAX_BYTES}`);\n }\n if (!admitted.ok) throw new BotTurnOutcomeSchemaError('not-subset', JSON.stringify(admitted.issues));\n const bound = resultOutcomeMaxBytes(admitted.canonical);\n if (bound === null || bound > RESULT_OUTCOME_MAX_BYTES) {\n throw new BotTurnOutcomeSchemaError('over-budget', `largest outcome is ${bound ?? 'unbounded'} bytes; cap ${RESULT_OUTCOME_MAX_BYTES}`);\n }\n return admitted.canonical;\n}\n\nexport type BotTurnOutcomeFragments = Partial<Readonly<Record<BotTurnOutcomeKind, ResultSchema>>>;\n\nexport interface DelegateAction { readonly to: string; readonly request: string }\nexport interface CancelDelegationAction { readonly delegationId: string }\nexport type AskUserAction =\n | { readonly question: string; readonly answerKind: 'text' }\n | { readonly question: string; readonly answerKind: 'single_choice';\n readonly options: readonly { readonly id: string; readonly label: string }[] };\nexport interface ConfirmableAction<Draft = unknown> { readonly action: string; readonly summary: string; readonly draft: Draft }\n/**\n * No day field: every day. daysOfWeek and dayOfMonth never appear together;\n * month needs dayOfMonth. Under the 'flat' shape the schema does not enforce\n * this; the Host narrows to this type only after checkRoutineSchedule passes.\n */\nexport type RoutineScheduleFields =\n | { readonly minute: number; readonly hour: number; readonly tz: string }\n | { readonly minute: number; readonly hour: number; readonly daysOfWeek: readonly RoutineDayOfWeek[]; readonly tz: string }\n | { readonly minute: number; readonly hour: number; readonly dayOfMonth: number; readonly month?: number; readonly tz: string };\nexport interface CreateRoutineAction { readonly localId: string; readonly schedule: RoutineScheduleFields; readonly prompt: string; readonly target?: string }\nexport interface UpdateRoutineAction { readonly routineId: string; readonly schedule?: RoutineScheduleFields; readonly prompt?: string }\nexport interface CancelRoutineAction { readonly routineId: string }\nexport type RoomSpeech = { readonly kind: 'post'; readonly text: string } | { readonly kind: 'pass' };\nexport interface RoomCallAction { readonly members: readonly string[] }\nexport interface CreateBotAction { readonly localId: string; readonly name: string; readonly role: string; readonly persona: string; readonly model: string }\nexport interface UpdateBotAction { readonly botId: string; readonly name?: string; readonly role?: string; readonly persona?: string; readonly model?: string }\nexport interface DeleteBotAction { readonly botId: string }\nexport interface RoomFields {\n readonly name: string; readonly members: readonly string[]; readonly admin?: string;\n readonly mode?: 'mention' | 'admin'; readonly announcement?: string;\n}\nexport interface CreateRoomAction extends RoomFields { readonly localId: string }\nexport interface UpdateRoomAction extends Partial<RoomFields> { readonly roomId: string }\nexport interface TeamNoteAction { readonly text: string }\n\n/** Shape of a document that passed a schema composed from these fragments. */\nexport interface BotTurnOutcome {\n readonly delegate?: readonly DelegateAction[];\n readonly cancel_delegation?: readonly CancelDelegationAction[];\n readonly ask_user?: AskUserAction;\n readonly confirmable_action?: readonly ConfirmableAction[];\n readonly create_routine?: readonly CreateRoutineAction[];\n readonly update_routine?: readonly UpdateRoutineAction[];\n readonly cancel_routine?: readonly CancelRoutineAction[];\n readonly speech?: RoomSpeech;\n readonly room_call?: RoomCallAction;\n readonly create_bot?: readonly CreateBotAction[];\n readonly update_bot?: readonly UpdateBotAction[];\n readonly delete_bot?: readonly DeleteBotAction[];\n readonly create_room?: readonly CreateRoomAction[];\n readonly update_room?: readonly UpdateRoomAction[];\n readonly team_note?: TeamNoteAction;\n}\n"]}