@byok-sdk/protocol 0.27.0 → 0.28.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/bot-turn-outcome.d.ts +252 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +280 -8
- package/dist/index.js.map +1 -1
- package/dist/result-schema.d.ts +7 -0
- package/dist/wire-additions.d.ts +3 -3
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capability-constants.ts","../src/version.ts","../src/task-state.ts","../src/wire-additions.ts","../src/blob.ts","../src/provider-profile-binding.ts","../src/provider-provisioning.ts","../src/plain-json.ts","../src/result-schema.ts","../src/terminal-projection.ts","../src/agent-egress.ts","../src/input-preparation.ts","../src/agent-event.ts","../src/agent-home-projection.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"],"names":["z","LONE_SURROGATE","completionIdentity","AppliedCompletionSchema","RejectedCompletionSchema"],"mappings":";;;;AAWO,IAAM,8BAAA,GAAiC;AAIvC,IAAM,8BAAA,GAAiC;AAEvC,IAAM,oCAAA,GAAuC;AAG7C,IAAM,qCAAA,GAAwC;AAG9C,IAAM,+BAAA,GAAkC;AAExC,IAAM,uCAAA,GAA0C;AAEhD,IAAM,wCAAA,GAA2C;AAEjD,IAAM,sCAAA,GAAyC;AAG/C,IAAM,gCAAA,GAAmC;AAGzC,IAAM,wCAAA,GAA2C;AAGjD,IAAM,gCAAA,GAAmC;AAGzC,IAAM,mCAAA,GAAsC;AAG5C,IAAM,gCAAA,GAAmC;AAGzC,IAAM,8BAAA,GAAiC;AAGvC,IAAM,kCAAA,GAAqC;AAG3C,IAAM,kCAAA,GACX,4BAA4B,8BAA8B,CAAA;AAGrD,IAAM,2BAAA,GAA8B,CAAC,MAAA,EAAQ,MAAA,EAAQ,YAAY;AAEjE,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gBAAgB,MAAA,EAAwB;AACtD,EAAA,OAAO,CAAA,YAAA,EAAe,kBAAA,CAAmB,MAAM,CAAC,CAAA,IAAA,CAAA;AAClD;AAMO,SAAS,oBAAoB,MAAA,EAAwB;AAC1D,EAAA,OAAO,eAAe,MAAM,CAAA,QAAA,CAAA;AAC9B","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/** 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/** 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 v3 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 v3 release has been published\n * yet, so `src/__tests__/compat.test.ts` has no published v3 decoder to prove\n * additions against; cross-release gates stay unproven until one exists.\n *\n * v3 makes `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 = 3;\n\n/** Host declares that this device accepts only Agent-bound offer variants. */\nexport const STRICT_AGENT_ONLY_CAPABILITY = 'strict-agent-only' as const;\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 exchanged during the connection handshake (`conn.hello` /\n * `conn.ack`). Additional flags may be introduced without a protocol version\n * bump; unrecognized flags must be ignored by both sides.\n *\n * `interactive-approval` is RESERVED as of this addition: it gates the\n * (currently unexercised) approval seam — a server must not route an\n * approval-requiring policy to a daemon that hasn't advertised this flag. No\n * bundled runtime adapter emits it yet; that's expected until interactive\n * approval is actually wired up in a later wave.\n *\n * `approval_resolved` (additive-minor): a SERVER-advertised flag meaning\n * \"I understand the `task.approval_resolved` message\" (`messages.ts`). This\n * is the N/N-1 answer for that new daemon -> server message: an old server's\n * `CAPABILITY_FLAGS`/`conn.ack.capabilities` never includes it, so a new\n * daemon talking to an old server never sends `task.approval_resolved` at\n * all (see `packages/client`'s `task-runner.ts`) and falls back to the\n * pre-existing implicit-resume inference\n * (`ConnectionHub.resumeIfImplicitlyApproved`, `packages/server/src/hub.ts`)\n * unconditionally, exactly as before this flag existed. Unlike\n * `interactive-approval`, this one IS exercised the moment both sides\n * support it — there is no reserved/dormant period for it.\n */\n/**\n * `approval-targeting` (M5, additive-minor): unlike `approval_resolved`\n * above, this flag is purely INFORMATIONAL/semantic, not a functional gate.\n * `task.await_approval`/`task.approve`/`task.reject` all carry their new\n * `approvalId` field UNCONDITIONALLY on both sides once each peer is\n * upgraded -- the wire is tolerant (a plain, non-`.strict()` `z.object()`\n * field, `messages.ts`), so no version/capability negotiation is needed just\n * to send it safely; an older peer that doesn't recognize the field simply\n * never reads it. Receivers decide whether to apply exact-match targeting\n * by FIELD PRESENCE on the specific message at hand (does this particular\n * `task.approve`/`task.reject`/`onApprovalResolved` payload carry an\n * `approvalId`, and does a stored one exist to compare it against?), never\n * by checking this flag -- see `ConnectionHub.approveTask`/`rejectTask`/\n * `onApprovalResolved` and `TaskRunner.handleApprove`/`handleReject`\n * (`packages/client`'s `task-runner.ts`). This flag exists only so each side\n * can advertise, and an embedder/operator can observe (`ConnectionHub.\n * getDeviceCapabilities`), whether the OTHER side is new enough to\n * participate in targeting at all -- the same N/N-1-safe shape as every\n * other flag here, just consumed for observability instead of gating.\n */\n/**\n * `dispatch-selection` (additive-minor) is a correctness gate for the\n * optional `task.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 * a legacy runtime-only offer that could reach a different provider.\n *\n * `toolset-selection` (additive-minor) means the daemon understands\n * `task.offer_with_toolsets` and can resolve its logical ids against local\n * MCP configuration. The distinct message type is also the N/N-1 safety\n * boundary for long-poll: an older daemon skips it as unknown and therefore\n * cannot accidentally execute the instruction without the required tools.\n */\nexport const CUSTOM_HARNESS_CAPABILITY = 'custom-harness' as const;\n\nexport const CAPABILITY_FLAGS = [\n 'steer',\n 'blob-upload',\n 'interactive-approval',\n 'approval_resolved',\n 'approval-targeting',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\n AGENT_HOME_READERS_CAPABILITY,\n STRICT_AGENT_ONLY_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-message-draft',\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_INPUT_PREPARATION_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 one table of receiver-capability gates and wire additions\n * (docs/protocol.md \"Freeze rule\").\n *\n * A v3 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); a type\n * entry applies to every 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. The\n * server-advertised `approval_resolved` gate is kept as the daemon's sending\n * condition for `task.approval_resolved`. No v3 release has been\n * published, so no row is proven against a published v3 decoder yet\n * (`src/__tests__/compat.test.ts`).\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 (types only) so it stays free\n * of zod.\n */\nimport type { MessageType } from './messages';\nimport type { CapabilityFlag } from './version';\n\ntype HttpWireSurface =\n | 'ChallengeRequest' | 'ChallengeResponse' | 'TokenRequest' | 'TokenResponse'\n | 'EventsPollQuery' | 'EventsPollResponse' | 'MessagesSendRequest' | 'MessagesSendResponse';\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 AGENT_OFFER_FIELDS = (surface: MessageType): readonly WireAddition[] => [\n { kind: 'envelope', rule: 'gated', surface, field: 'dispatchSelection', capability: 'dispatch-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'requiredToolsets', capability: 'toolset-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'terminalProjection', capability: 'terminal-projection-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'homeAccess', capability: 'agent-home-readers', advertisedBy: 'device' },\n];\n\nconst EGRESS_OFFER_FIELDS = (surface: MessageType): readonly WireAddition[] => [\n { kind: 'envelope', rule: 'gated', surface, field: 'messageEgress', capability: 'agent-message-egress', advertisedBy: 'device' },\n ...AGENT_OFFER_FIELDS(surface),\n];\n\nexport const WIRE_ADDITIONS: readonly WireAddition[] = Object.freeze([\n // Server to daemon: offers.\n { kind: 'envelope', rule: 'gated', surface: 'task.offer', field: 'harnessId', capability: 'custom-harness', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_with_toolsets', field: 'harnessId', capability: 'custom-harness', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent', capability: 'agent-home-contract', advertisedBy: 'device' },\n ...AGENT_OFFER_FIELDS('task.offer_for_agent'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_for_agent_with_egress'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-fresh-session', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_for_agent_with_egress_fresh'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-input-preparation-v9', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-fresh-session', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_prepared'),\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 // 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 // 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.approval_resolved', capability: 'approval_resolved', advertisedBy: 'server' },\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 = fields[entry.field];\n if (value === undefined) continue;\n if (entry.value !== undefined && 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/** 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): 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 (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","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';\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","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 `task.offer_prepared` 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';\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 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 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('needs_approval'), summary: 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 }),\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","import { PreparedAgentMemoryModeSchema } from './input-preparation';\nimport { z } from 'zod';\nimport { BlobRefSchema } from './blob';\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 {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\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(['pi', 'claude', 'codex']);\nexport type RuntimeId = z.infer<typeof RuntimeIdSchema>;\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});\nexport type RuntimeCapabilities = z.infer<typeof RuntimeCapabilitiesSchema>;\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});\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 => !['pi', 'claude', 'codex'].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});\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/** 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 /** 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/** server -> daemon: handshake acknowledgement. */\nexport const ConnAckPayloadSchema = z.object({\n protocolVersion: z.number().int(),\n capabilities: z.array(z.string()),\n serverTime: z.iso.datetime({ offset: true }),\n});\nexport type ConnAckPayload = z.infer<typeof ConnAckPayloadSchema>;\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 `TaskOfferPayload.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 * server -> daemon: offer a task for a device to claim.\n *\n * `taskId` used to be duplicated here; it is now carried only by the\n * envelope's `task_id` (M1 gap #7 — single source of truth for routing).\n */\nexport const TaskOfferPayloadSchema = z.object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n dispatchSelection: DispatchSelectionSchema.optional(),\n sessionRef: z.string().optional(),\n workspaceHint: z.string().optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .optional(),\n});\nexport type TaskOfferPayload = z.infer<typeof TaskOfferPayloadSchema>;\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 * Additive v1 offer variant for tasks whose semantics require local MCP\n * tools. This is a distinct message type rather than an optional field on\n * `task.offer`, so an older daemon can never strip an unknown optional control\n * field and run the task without its required tools. An unknown type is not\n * silently skipped either: on long-poll it freezes the cursor, so the enqueue\n * capability gate is the real compatibility boundary. The whole payload is\n * strict because every field here affects execution authority.\n */\nexport const TaskOfferWithToolsetsPayloadSchema = TaskOfferPayloadSchema.extend({\n requiredToolsets: RequiredToolsetsSchema,\n}).strict();\nexport type TaskOfferWithToolsetsPayload = z.infer<typeof TaskOfferWithToolsetsPayloadSchema>;\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 * Strict additive offer for a durable host-owned Agent. An older daemon that\n * does not advertise `agent-home-contract` skips this distinct message type\n * instead of stripping identity and applying legacy workspace semantics.\n */\nexport const TaskOfferForAgentPayloadSchema = z\n .object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]),\n agentRef: AgentRefSchema,\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 sessionRef: z.string().optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .optional(),\n })\n .strict();\nexport type TaskOfferForAgentPayload = z.infer<typeof TaskOfferForAgentPayloadSchema>;\n\n/**\n * Strict Agent offer which consumes the typed egress policy. It is a distinct\n * message so an older Agent-home daemon cannot strip control data and proceed\n * with an unconsumed egress declaration.\n */\nexport const TaskOfferForAgentWithEgressPayloadSchema = TaskOfferForAgentPayloadSchema.extend({\n sessionRef: z.string().min(1).max(512),\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n}).strict();\nexport type TaskOfferForAgentWithEgressPayload = z.infer<typeof TaskOfferForAgentWithEgressPayloadSchema>;\n\n/**\n * Strict fresh-session Agent egress offer. It deliberately omits `sessionRef`:\n * the selected runtime is the sole authority that can mint that identity after\n * start. This distinct message prevents a missing resume reference from being\n * interpreted as a fresh execution by an older daemon.\n */\nexport const TaskOfferForAgentWithEgressFreshPayloadSchema = TaskOfferForAgentPayloadSchema.omit({\n sessionRef: true,\n})\n .extend({\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n })\n .strict();\nexport type TaskOfferForAgentWithEgressFreshPayload = z.infer<typeof TaskOfferForAgentWithEgressFreshPayloadSchema>;\n\n/**\n * Strict offer for an already-counted prepared Execution.\n *\n * A DISTINCT message type, not a `preparation` field added to\n * `task.offer_for_agent`, for the same N/N-1 reason the toolset and egress\n * variants are distinct. On long-poll, both an unknown message type and an\n * unknown key on a strict payload freeze the cursor. The enqueue capability\n * gate is the compatibility boundary: v6 requires a drain and paired upgrade,\n * with no dual token or dual read.\n *\n * It carries no `instruction`: the user request is already inside the frozen\n * envelope the referenced record retained, and an offer that carried both would\n * have two answers to what the runtime is about to send. `sessionRef` is absent\n * for the same structural reason the adapter refuses the pair — a prepared\n * Execution never resumes.\n *\n * Every value under `preparation` is the Host RE-PRESENTING what the device\n * already told it. The device compares each one against its own durable record\n * and declines non-retryably on any difference; nothing here is authority.\n */\nexport const TaskOfferPreparedPayloadSchema = TaskOfferForAgentPayloadSchema.omit({\n instruction: true,\n sessionRef: true,\n})\n .extend({\n preparation: InputPreparationOfferBindingSchema,\n agentMemory: PreparedAgentMemoryModeSchema,\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n })\n .strict();\nexport type TaskOfferPreparedPayload = z.infer<typeof TaskOfferPreparedPayloadSchema>;\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\nexport const AgentMessagePublishPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n contentType: AgentMessageContentTypeSchema,\n body: AGENT_MESSAGE_BODY,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\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 AgentMessagePublishPayload = z.infer<typeof AgentMessagePublishPayloadSchema>;\n\nexport const AgentMessageDispositionPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n contentHash: AgentEgressContentHashSchema,\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 .strict();\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 reason: AgentContentReadDenialReasonSchema,\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 `task.offer_with_toolsets` is: 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` (M5, additive-minor — docs/protocol.md §5.3): OPTIONAL target\n * identity for the SPECIFIC pending approval this decision resolves, rather\n * than \"whichever one is currently pending\" (the pre-M5 behavior, and still\n * what happens when this field is absent — a legacy server that never\n * learned an id, or one talking to a legacy daemon). When present, the\n * daemon compares it against its own currently-dispatched approval id\n * (`ActiveTask.pendingApprovalId`, `packages/client`'s `task-runner.ts`) and\n * treats a mismatch as a stale, audit-only no-op instead of resolving\n * whatever happens to be pending right now — see `TaskRunner.handleApprove`.\n */\nexport const TaskApprovePayloadSchema = z.object({\n approvalId: z.string().optional(),\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` (M5, additive-minor — docs/protocol.md §5.3): same optional\n * targeting semantics as `TaskApprovePayloadSchema.approvalId` above, applied\n * to the reject path (`TaskRunner.handleReject`).\n */\nexport const TaskRejectPayloadSchema = z.object({\n reason: z.string().optional(),\n approvalId: z.string().optional(),\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. */\nexport const TaskSteerPayloadSchema = z.object({\n text: z.string(),\n});\nexport type TaskSteerPayload = z.infer<typeof TaskSteerPayloadSchema>;\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/**\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 `task.offer`'s\n * own `runtime` (the merely REQUESTED one, `TaskOfferPayloadSchema.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 (same shape as `approvalId` on\n * `task.await_approval`/`task.approve`/`task.reject`, §5.3) — a new daemon\n * sends it unconditionally, regardless of whether the connected server is\n * new enough 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});\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 */\nexport const TaskDeclinePayloadSchema = z.object({\n reason: z.string(),\n retryable: z.boolean().optional(),\n agentRef: AgentRefSchema.optional(),\n code: z.enum(['agent_home_writer_busy', 'agent_home_reader_busy']).optional(),\n});\nexport type TaskDeclinePayload = z.infer<typeof TaskDeclinePayloadSchema>;\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 */\nexport const TaskProgressPayloadSchema = z.object({\n seq: z.number().int(),\n events: z.array(AgentEventOrUnknownSchema),\n});\nexport type TaskProgressPayload = z.infer<typeof TaskProgressPayloadSchema>;\n\n/** daemon -> server: an artifact produced by the task, inline or by blob ref. */\nexport const TaskArtifactPayloadSchema = z.object({\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});\nexport type TaskArtifactPayload = z.infer<typeof TaskArtifactPayloadSchema>;\n\n/**\n * daemon -> server: task is blocked on an out-of-band approval.\n *\n * `approvalId` (M5, additive-minor — docs/protocol.md §5.3): the daemon's own\n * locally-generated identity for THIS SPECIFIC pending approval\n * (`ApprovalRegistry`, `packages/client`'s `approvals.ts`) — included\n * unconditionally by an M5+ daemon, regardless of whether the connected\n * server has advertised the `approval-targeting` capability flag\n * (`version.ts`; see that flag's own doc comment for why no emission gating\n * is needed here — it's a tolerant `z.object()` field, so an older server\n * simply ignores it). Optional purely for wire tolerance with a pre-M5\n * daemon build that never set it at all: a server that never learns an id\n * for a task's current approval can't target a later `approve`/`reject`\n * decision and falls back to resolving \"whichever approval is currently\n * pending\" — the same behavior every server had before this field existed.\n */\nexport const TaskAwaitApprovalPayloadSchema = z.object({\n summary: z.string(),\n approvalId: z.string().optional(),\n});\nexport type TaskAwaitApprovalPayload = z.infer<typeof TaskAwaitApprovalPayloadSchema>;\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_MODEL_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 */\nexport const TaskCompletePayloadSchema = z.object({\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});\nexport type TaskCompletePayload = z.infer<typeof TaskCompletePayloadSchema>;\n\n/** daemon -> server: task failed. */\nexport const TaskFailPayloadSchema = z.object({\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 reason: z.string(),\n retryable: z.boolean().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});\nexport type TaskFailPayload = z.infer<typeof TaskFailPayloadSchema>;\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 */\nexport const TaskCancelledPayloadSchema = z.object({\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});\nexport type TaskCancelledPayload = z.infer<typeof TaskCancelledPayloadSchema>;\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. This is the additive-minor answer to a gap the M4 Phase 3 approval\n * work left open (see the \"Deferred additive candidate\" note this schema\n * resolves, `docs/protocol.md`): today the server only learns of a local\n * resolution IMPLICITLY, after the fact, once the daemon's next\n * `task.progress`/`task.artifact`/`task.complete` proves the task already\n * moved on (`ConnectionHub.resumeIfImplicitlyApproved`,\n * `packages/server/src/hub.ts`) — a window in which a SaaS-side\n * `TaskHandle.approve()`/`.reject()` can independently decide (and win) the\n * server's own authoritative record before that evidence ever arrives. This\n * message lets the daemon report the local resolution explicitly and\n * immediately, narrowing that window from \"until the next progress message\"\n * down to ordinary network latency; the implicit-inference path stays as-is,\n * unconditionally, as the compatibility fallback for an old server that\n * never advertises the `approval_resolved` capability flag (`version.ts`) or\n * an old daemon that predates this message entirely.\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 * deliberately future-proof (a later wave could add e.g. `'operator-cli'` as\n * a DISTINCT value without a version bump — a new enum member is additive,\n * same as a new message type or capability flag), while still being a closed,\n * typed shape today rather than an open string a typo could silently widen.\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// registry — single source of truth mapping message type -> payload schema\n// ---------------------------------------------------------------------------\n\n/** Protocol-owned task-opening family; the wire registry consumes these same entries. */\nconst TASK_OFFER_PAYLOAD_SCHEMAS = {\n 'task.offer': TaskOfferPayloadSchema,\n 'task.offer_with_toolsets': TaskOfferWithToolsetsPayloadSchema,\n 'task.offer_for_agent': TaskOfferForAgentPayloadSchema,\n 'task.offer_for_agent_with_egress': TaskOfferForAgentWithEgressPayloadSchema,\n 'task.offer_for_agent_with_egress_fresh': TaskOfferForAgentWithEgressFreshPayloadSchema,\n 'task.offer_prepared': TaskOfferPreparedPayloadSchema,\n} as const;\n\nexport type TaskOfferType = keyof typeof TASK_OFFER_PAYLOAD_SCHEMAS;\nexport const TASK_OFFER_TYPES: readonly TaskOfferType[] = Object.freeze(\n Object.keys(TASK_OFFER_PAYLOAD_SCHEMAS) as TaskOfferType[],\n);\n\n/** Classify task-opening offers without duplicating the protocol registry in consumers. */\nexport function isTaskOfferType(type: string): type is TaskOfferType {\n return Object.hasOwn(TASK_OFFER_PAYLOAD_SCHEMAS, type);\n}\n\nexport const MESSAGE_PAYLOAD_SCHEMAS = {\n 'conn.hello': ConnHelloPayloadSchema,\n 'conn.ack': ConnAckPayloadSchema,\n ...TASK_OFFER_PAYLOAD_SCHEMAS,\n 'agent.egress.reliable': AgentEgressReliablePayloadSchema,\n 'agent.egress.ack': AgentEgressAckPayloadSchema,\n 'agent.message.draft': AgentMessageDraftPayloadSchema,\n 'agent.message.publish': AgentMessagePublishPayloadSchema,\n 'agent.message.disposition': AgentMessageDispositionPayloadSchema,\n 'agent.content.read': AgentContentReadPayloadSchema,\n 'agent.content.receipt': AgentContentReceiptPayloadSchema,\n 'agent.home.projection': AgentHomeProjectionPayloadSchema,\n 'agent.input.preparation': AgentInputPreparationPayloadSchema,\n 'provider.provisioning.available': ProviderProvisioningAvailablePayloadSchema,\n 'agent.memory.intent.available': AgentMemoryIntentAvailablePayloadSchema,\n 'task.approve': TaskApprovePayloadSchema,\n 'task.reject': TaskRejectPayloadSchema,\n 'task.cancel': TaskCancelPayloadSchema,\n 'task.steer': TaskSteerPayloadSchema,\n 'task.claim': TaskClaimPayloadSchema,\n 'task.started': TaskStartedPayloadSchema,\n 'task.decline': TaskDeclinePayloadSchema,\n 'task.progress': TaskProgressPayloadSchema,\n 'task.artifact': TaskArtifactPayloadSchema,\n 'task.await_approval': TaskAwaitApprovalPayloadSchema,\n 'task.complete': TaskCompletePayloadSchema,\n 'task.fail': TaskFailPayloadSchema,\n 'task.cancelled': TaskCancelledPayloadSchema,\n 'task.approval_resolved': TaskApprovalResolvedPayloadSchema,\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 'conn.ack',\n 'task.offer',\n 'task.offer_with_toolsets',\n 'task.offer_for_agent',\n 'task.offer_for_agent_with_egress',\n 'task.offer_for_agent_with_egress_fresh',\n 'task.offer_prepared',\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] 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: it's\n * only ever valid as the first frame of a WS handshake (`ws-server.ts`), not\n * as ongoing inbound traffic through `ConnectionHub.handleInbound`.\n *\n * Used by `handleInbound` (`@byok-sdk/server`'s `hub.ts`) as the type-allow gate\n * for every inbound envelope, WS and `POST /byok/messages` alike (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';\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/**\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 AgentMemoryProjectionMutationSchema = z\n .object({\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 snapshot: AgentMemoryProjectionSnapshotSchema,\n })\n .strict();\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\n/** Immutable commit readback. It repeats identity and redacted metadata, never redacted bytes. */\nexport const AgentMemoryProjectionReceiptSchema = z\n .object({\n outcome: z.enum(['accepted', 'idempotent']),\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\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 redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n metering: AgentMemoryProjectionMeteringReceiptSchema,\n })\n .strict();\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 * 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) {\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.* — task_id stays optional (no task routing). conn.hello is\n // daemon -> server (no cursor to satisfy on this leg); conn.ack is\n // server -> daemon and therefore carries the required redelivery `seq`.\n envelopeShape('conn.hello', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('conn.ack', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n\n // task.* server -> daemon: task_id required (routing key) + seq required\n // (per-device redelivery cursor).\n envelopeShape('task.offer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_with_toolsets', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent_with_egress', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent_with_egress_fresh', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_prepared', 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\n // task.* daemon -> server: task_id required (routing key); envelope-level\n // seq is not required in this direction in M1 (no daemon->server\n // redelivery cursor yet — 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 'conn.ack': { taskId?: string; seq: number };\n 'task.offer': { taskId: string; seq: number };\n 'task.offer_with_toolsets': { taskId: string; seq: number };\n 'task.offer_for_agent': { taskId: string; seq: number };\n 'task.offer_for_agent_with_egress': { taskId: string; seq: number };\n 'task.offer_for_agent_with_egress_fresh': { taskId: string; seq: number };\n 'task.offer_prepared': { taskId: string; seq: number };\n 'agent.egress.reliable': { taskId?: string; seq?: number };\n 'agent.egress.ack': { taskId?: string; seq: number };\n 'agent.message.draft': { taskId: string; seq?: number };\n 'agent.message.publish': { 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 'agent.content.receipt': { taskId?: string; 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 '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}\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 { CONTENT_HASH_RE } from './blob';\nimport { EnvelopeSchema } from './envelope';\nimport {\n AgentRefSchema,\n ConfiguredToolsetsSchema,\n ProtocolVersionNumberSchema,\n RuntimeIdSchema,\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 /** 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 expiresAt: z.iso.datetime({ offset: true }),\n});\nexport type TokenResponse = z.infer<typeof TokenResponseSchema>;\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, not a second runtime-capability\n * protocol. It retains only the facts the cloud persists and bounds every\n * string/array/numeric input at this public request boundary.\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});\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});\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 in v3: the server capabilities for THIS long-poll response, the\n * HTTP transport's equivalent of `conn.ack.capabilities`. Each page replaces\n * 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\nexport const MessagesSendRequestSchema = z.object({\n messages: z.array(EnvelopeSchema).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendRequest = z.infer<typeof MessagesSendRequestSchema>;\n\n/**\n * `accepted` counts every envelope `ConnectionHub.handleInbound` returned\n * `'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/** `POST /byok/activity` — activity-tail append. */\nexport const BYOK_ACTIVITY_PATH = '/byok/activity';\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/** `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"]}
|
|
1
|
+
{"version":3,"sources":["../src/capability-constants.ts","../src/version.ts","../src/task-state.ts","../src/wire-additions.ts","../src/blob.ts","../src/provider-profile-binding.ts","../src/provider-provisioning.ts","../src/plain-json.ts","../src/result-schema.ts","../src/terminal-projection.ts","../src/agent-egress.ts","../src/input-preparation.ts","../src/agent-event.ts","../src/agent-home-projection.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":["z","size","LONE_SURROGATE","completionIdentity","AppliedCompletionSchema","RejectedCompletionSchema","text"],"mappings":";;;;AAWO,IAAM,8BAAA,GAAiC;AAIvC,IAAM,8BAAA,GAAiC;AAEvC,IAAM,oCAAA,GAAuC;AAG7C,IAAM,qCAAA,GAAwC;AAG9C,IAAM,+BAAA,GAAkC;AAExC,IAAM,uCAAA,GAA0C;AAEhD,IAAM,wCAAA,GAA2C;AAEjD,IAAM,sCAAA,GAAyC;AAG/C,IAAM,gCAAA,GAAmC;AAGzC,IAAM,wCAAA,GAA2C;AAGjD,IAAM,gCAAA,GAAmC;AAGzC,IAAM,mCAAA,GAAsC;AAG5C,IAAM,gCAAA,GAAmC;AAGzC,IAAM,8BAAA,GAAiC;AAGvC,IAAM,kCAAA,GAAqC;AA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AAe,wBAAwB,CAAA,CAAE,CAAA;AAAA,EACxI;AACA,EAAA,OAAO,QAAA,CAAS,SAAA;AAClB","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/** 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/** 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 v3 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 v3 release has been published\n * yet, so `src/__tests__/compat.test.ts` has no published v3 decoder to prove\n * additions against; cross-release gates stay unproven until one exists.\n *\n * v3 makes `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 = 3;\n\n/** Host declares that this device accepts only Agent-bound offer variants. */\nexport const STRICT_AGENT_ONLY_CAPABILITY = 'strict-agent-only' as const;\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 exchanged during the connection handshake (`conn.hello` /\n * `conn.ack`). Additional flags may be introduced without a protocol version\n * bump; unrecognized flags must be ignored by both sides.\n *\n * `interactive-approval` is RESERVED as of this addition: it gates the\n * (currently unexercised) approval seam — a server must not route an\n * approval-requiring policy to a daemon that hasn't advertised this flag. No\n * bundled runtime adapter emits it yet; that's expected until interactive\n * approval is actually wired up in a later wave.\n *\n * `approval_resolved` (additive-minor): a SERVER-advertised flag meaning\n * \"I understand the `task.approval_resolved` message\" (`messages.ts`). This\n * is the N/N-1 answer for that new daemon -> server message: an old server's\n * `CAPABILITY_FLAGS`/`conn.ack.capabilities` never includes it, so a new\n * daemon talking to an old server never sends `task.approval_resolved` at\n * all (see `packages/client`'s `task-runner.ts`) and falls back to the\n * pre-existing implicit-resume inference\n * (`ConnectionHub.resumeIfImplicitlyApproved`, `packages/server/src/hub.ts`)\n * unconditionally, exactly as before this flag existed. Unlike\n * `interactive-approval`, this one IS exercised the moment both sides\n * support it — there is no reserved/dormant period for it.\n */\n/**\n * `approval-targeting` (M5, additive-minor): unlike `approval_resolved`\n * above, this flag is purely INFORMATIONAL/semantic, not a functional gate.\n * `task.await_approval`/`task.approve`/`task.reject` all carry their new\n * `approvalId` field UNCONDITIONALLY on both sides once each peer is\n * upgraded -- the wire is tolerant (a plain, non-`.strict()` `z.object()`\n * field, `messages.ts`), so no version/capability negotiation is needed just\n * to send it safely; an older peer that doesn't recognize the field simply\n * never reads it. Receivers decide whether to apply exact-match targeting\n * by FIELD PRESENCE on the specific message at hand (does this particular\n * `task.approve`/`task.reject`/`onApprovalResolved` payload carry an\n * `approvalId`, and does a stored one exist to compare it against?), never\n * by checking this flag -- see `ConnectionHub.approveTask`/`rejectTask`/\n * `onApprovalResolved` and `TaskRunner.handleApprove`/`handleReject`\n * (`packages/client`'s `task-runner.ts`). This flag exists only so each side\n * can advertise, and an embedder/operator can observe (`ConnectionHub.\n * getDeviceCapabilities`), whether the OTHER side is new enough to\n * participate in targeting at all -- the same N/N-1-safe shape as every\n * other flag here, just consumed for observability instead of gating.\n */\n/**\n * `dispatch-selection` (additive-minor) is a correctness gate for the\n * optional `task.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 * a legacy runtime-only offer that could reach a different provider.\n *\n * `toolset-selection` (additive-minor) means the daemon understands\n * `task.offer_with_toolsets` and can resolve its logical ids against local\n * MCP configuration. The distinct message type is also the N/N-1 safety\n * boundary for long-poll: an older daemon skips it as unknown and therefore\n * cannot accidentally execute the instruction without the required tools.\n */\nexport const CUSTOM_HARNESS_CAPABILITY = 'custom-harness' as const;\n\nexport const CAPABILITY_FLAGS = [\n 'steer',\n 'blob-upload',\n 'interactive-approval',\n 'approval_resolved',\n 'approval-targeting',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\n AGENT_HOME_READERS_CAPABILITY,\n STRICT_AGENT_ONLY_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-message-draft',\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_INPUT_PREPARATION_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 one table of receiver-capability gates and wire additions\n * (docs/protocol.md \"Freeze rule\").\n *\n * A v3 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); a type\n * entry applies to every 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. The\n * server-advertised `approval_resolved` gate is kept as the daemon's sending\n * condition for `task.approval_resolved`. The first stable v3 decoder is\n * 0.27.0. Cross-release checks use its actual registry tarball\n * (`src/__tests__/published-compat.test.ts`).\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 (types only) so it stays free\n * of zod.\n */\nimport type { MessageType } from './messages';\nimport type { CapabilityFlag } from './version';\n\ntype HttpWireSurface =\n | 'ChallengeRequest' | 'ChallengeResponse' | 'TokenRequest' | 'TokenResponse'\n | 'EventsPollQuery' | 'EventsPollResponse' | 'MessagesSendRequest' | 'MessagesSendResponse';\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 AGENT_OFFER_FIELDS = (surface: MessageType): readonly WireAddition[] => [\n { kind: 'envelope', rule: 'gated', surface, field: 'dispatchSelection', capability: 'dispatch-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'requiredToolsets', capability: 'toolset-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'terminalProjection', capability: 'terminal-projection-selection', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface, field: 'homeAccess', capability: 'agent-home-readers', advertisedBy: 'device' },\n];\n\nconst EGRESS_OFFER_FIELDS = (surface: MessageType): readonly WireAddition[] => [\n { kind: 'envelope', rule: 'gated', surface, field: 'messageEgress', capability: 'agent-message-egress', advertisedBy: 'device' },\n ...AGENT_OFFER_FIELDS(surface),\n];\n\nexport const WIRE_ADDITIONS: readonly WireAddition[] = Object.freeze([\n // Server to daemon: offers.\n { kind: 'envelope', rule: 'gated', surface: 'task.offer', field: 'harnessId', capability: 'custom-harness', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_with_toolsets', field: 'harnessId', capability: 'custom-harness', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent', capability: 'agent-home-contract', advertisedBy: 'device' },\n ...AGENT_OFFER_FIELDS('task.offer_for_agent'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_for_agent_with_egress'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_for_agent_with_egress_fresh', capability: 'agent-egress-fresh-session', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_for_agent_with_egress_fresh'),\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-home-contract', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-input-preparation-v9', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-policy', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-reliable-ack', advertisedBy: 'device' },\n { kind: 'envelope', rule: 'gated', surface: 'task.offer_prepared', capability: 'agent-egress-fresh-session', advertisedBy: 'device' },\n ...EGRESS_OFFER_FIELDS('task.offer_prepared'),\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 // 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 // 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.approval_resolved', capability: 'approval_resolved', advertisedBy: 'server' },\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 = fields[entry.field];\n if (value === undefined) continue;\n if (entry.value !== undefined && 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/** 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';\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","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 `task.offer_prepared` 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';\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 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 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('needs_approval'), summary: 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 }),\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","import { PreparedAgentMemoryModeSchema } from './input-preparation';\nimport { z } from 'zod';\nimport { BlobRefSchema } from './blob';\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 {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\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(['pi', 'claude', 'codex']);\nexport type RuntimeId = z.infer<typeof RuntimeIdSchema>;\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});\nexport type RuntimeCapabilities = z.infer<typeof RuntimeCapabilitiesSchema>;\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});\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 => !['pi', 'claude', 'codex'].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});\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/** 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 /** 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/** server -> daemon: handshake acknowledgement. */\nexport const ConnAckPayloadSchema = z.object({\n protocolVersion: z.number().int(),\n capabilities: z.array(z.string()),\n serverTime: z.iso.datetime({ offset: true }),\n});\nexport type ConnAckPayload = z.infer<typeof ConnAckPayloadSchema>;\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 `TaskOfferPayload.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 * server -> daemon: offer a task for a device to claim.\n *\n * `taskId` used to be duplicated here; it is now carried only by the\n * envelope's `task_id` (M1 gap #7 — single source of truth for routing).\n */\nexport const TaskOfferPayloadSchema = z.object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]),\n runtime: RuntimeIdSchema.optional(),\n harnessId: HarnessIdSchema.optional(),\n dispatchSelection: DispatchSelectionSchema.optional(),\n sessionRef: z.string().optional(),\n workspaceHint: z.string().optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .optional(),\n});\nexport type TaskOfferPayload = z.infer<typeof TaskOfferPayloadSchema>;\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 * Additive v1 offer variant for tasks whose semantics require local MCP\n * tools. This is a distinct message type rather than an optional field on\n * `task.offer`, so an older daemon can never strip an unknown optional control\n * field and run the task without its required tools. An unknown type is not\n * silently skipped either: on long-poll it freezes the cursor, so the enqueue\n * capability gate is the real compatibility boundary. The whole payload is\n * strict because every field here affects execution authority.\n */\nexport const TaskOfferWithToolsetsPayloadSchema = TaskOfferPayloadSchema.extend({\n requiredToolsets: RequiredToolsetsSchema,\n}).strict();\nexport type TaskOfferWithToolsetsPayload = z.infer<typeof TaskOfferWithToolsetsPayloadSchema>;\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 * Strict additive offer for a durable host-owned Agent. An older daemon that\n * does not advertise `agent-home-contract` skips this distinct message type\n * instead of stripping identity and applying legacy workspace semantics.\n */\nexport const TaskOfferForAgentPayloadSchema = z\n .object({\n instruction: z.union([z.string(), InstructionBlobRefSchema]),\n agentRef: AgentRefSchema,\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 sessionRef: z.string().optional(),\n limits: z\n .object({\n maxDurationMs: z.number().int().positive().optional(),\n maxTokens: z.number().int().positive().optional(),\n })\n .optional(),\n })\n .strict();\nexport type TaskOfferForAgentPayload = z.infer<typeof TaskOfferForAgentPayloadSchema>;\n\n/**\n * Strict Agent offer which consumes the typed egress policy. It is a distinct\n * message so an older Agent-home daemon cannot strip control data and proceed\n * with an unconsumed egress declaration.\n */\nexport const TaskOfferForAgentWithEgressPayloadSchema = TaskOfferForAgentPayloadSchema.extend({\n sessionRef: z.string().min(1).max(512),\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n}).strict();\nexport type TaskOfferForAgentWithEgressPayload = z.infer<typeof TaskOfferForAgentWithEgressPayloadSchema>;\n\n/**\n * Strict fresh-session Agent egress offer. It deliberately omits `sessionRef`:\n * the selected runtime is the sole authority that can mint that identity after\n * start. This distinct message prevents a missing resume reference from being\n * interpreted as a fresh execution by an older daemon.\n */\nexport const TaskOfferForAgentWithEgressFreshPayloadSchema = TaskOfferForAgentPayloadSchema.omit({\n sessionRef: true,\n})\n .extend({\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n })\n .strict();\nexport type TaskOfferForAgentWithEgressFreshPayload = z.infer<typeof TaskOfferForAgentWithEgressFreshPayloadSchema>;\n\n/**\n * Strict offer for an already-counted prepared Execution.\n *\n * A DISTINCT message type, not a `preparation` field added to\n * `task.offer_for_agent`, for the same N/N-1 reason the toolset and egress\n * variants are distinct. On long-poll, both an unknown message type and an\n * unknown key on a strict payload freeze the cursor. The enqueue capability\n * gate is the compatibility boundary: v6 requires a drain and paired upgrade,\n * with no dual token or dual read.\n *\n * It carries no `instruction`: the user request is already inside the frozen\n * envelope the referenced record retained, and an offer that carried both would\n * have two answers to what the runtime is about to send. `sessionRef` is absent\n * for the same structural reason the adapter refuses the pair — a prepared\n * Execution never resumes.\n *\n * Every value under `preparation` is the Host RE-PRESENTING what the device\n * already told it. The device compares each one against its own durable record\n * and declines non-retryably on any difference; nothing here is authority.\n */\nexport const TaskOfferPreparedPayloadSchema = TaskOfferForAgentPayloadSchema.omit({\n instruction: true,\n sessionRef: true,\n})\n .extend({\n preparation: InputPreparationOfferBindingSchema,\n agentMemory: PreparedAgentMemoryModeSchema,\n egressPolicy: AgentEgressPolicySchema,\n messageEgress: AgentMessageEgressRequirementSchema.optional(),\n })\n .strict();\nexport type TaskOfferPreparedPayload = z.infer<typeof TaskOfferPreparedPayloadSchema>;\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\nexport const AgentMessagePublishPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n contentType: AgentMessageContentTypeSchema,\n body: AGENT_MESSAGE_BODY,\n contentHash: AgentEgressContentHashSchema,\n byteCount: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES),\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 AgentMessagePublishPayload = z.infer<typeof AgentMessagePublishPayloadSchema>;\n\nexport const AgentMessageDispositionPayloadSchema = z\n .object({\n agentRef: AgentRefSchema,\n sessionRef: EGRESS_SESSION_REF,\n contract: AgentMessageContractSchema,\n messageId: z.uuid(),\n cursor: z.number().int().positive(),\n contentHash: AgentEgressContentHashSchema,\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 .strict();\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 reason: AgentContentReadDenialReasonSchema,\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 `task.offer_with_toolsets` is: 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` (M5, additive-minor — docs/protocol.md §5.3): OPTIONAL target\n * identity for the SPECIFIC pending approval this decision resolves, rather\n * than \"whichever one is currently pending\" (the pre-M5 behavior, and still\n * what happens when this field is absent — a legacy server that never\n * learned an id, or one talking to a legacy daemon). When present, the\n * daemon compares it against its own currently-dispatched approval id\n * (`ActiveTask.pendingApprovalId`, `packages/client`'s `task-runner.ts`) and\n * treats a mismatch as a stale, audit-only no-op instead of resolving\n * whatever happens to be pending right now — see `TaskRunner.handleApprove`.\n */\nexport const TaskApprovePayloadSchema = z.object({\n approvalId: z.string().optional(),\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` (M5, additive-minor — docs/protocol.md §5.3): same optional\n * targeting semantics as `TaskApprovePayloadSchema.approvalId` above, applied\n * to the reject path (`TaskRunner.handleReject`).\n */\nexport const TaskRejectPayloadSchema = z.object({\n reason: z.string().optional(),\n approvalId: z.string().optional(),\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. */\nexport const TaskSteerPayloadSchema = z.object({\n text: z.string(),\n});\nexport type TaskSteerPayload = z.infer<typeof TaskSteerPayloadSchema>;\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/**\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 `task.offer`'s\n * own `runtime` (the merely REQUESTED one, `TaskOfferPayloadSchema.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 (same shape as `approvalId` on\n * `task.await_approval`/`task.approve`/`task.reject`, §5.3) — a new daemon\n * sends it unconditionally, regardless of whether the connected server is\n * new enough 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});\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 */\nexport const TaskDeclinePayloadSchema = z.object({\n reason: z.string(),\n retryable: z.boolean().optional(),\n agentRef: AgentRefSchema.optional(),\n code: z.enum(['agent_home_writer_busy', 'agent_home_reader_busy']).optional(),\n});\nexport type TaskDeclinePayload = z.infer<typeof TaskDeclinePayloadSchema>;\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 */\nexport const TaskProgressPayloadSchema = z.object({\n seq: z.number().int(),\n events: z.array(AgentEventOrUnknownSchema),\n});\nexport type TaskProgressPayload = z.infer<typeof TaskProgressPayloadSchema>;\n\n/** daemon -> server: an artifact produced by the task, inline or by blob ref. */\nexport const TaskArtifactPayloadSchema = z.object({\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});\nexport type TaskArtifactPayload = z.infer<typeof TaskArtifactPayloadSchema>;\n\n/**\n * daemon -> server: task is blocked on an out-of-band approval.\n *\n * `approvalId` (M5, additive-minor — docs/protocol.md §5.3): the daemon's own\n * locally-generated identity for THIS SPECIFIC pending approval\n * (`ApprovalRegistry`, `packages/client`'s `approvals.ts`) — included\n * unconditionally by an M5+ daemon, regardless of whether the connected\n * server has advertised the `approval-targeting` capability flag\n * (`version.ts`; see that flag's own doc comment for why no emission gating\n * is needed here — it's a tolerant `z.object()` field, so an older server\n * simply ignores it). Optional purely for wire tolerance with a pre-M5\n * daemon build that never set it at all: a server that never learns an id\n * for a task's current approval can't target a later `approve`/`reject`\n * decision and falls back to resolving \"whichever approval is currently\n * pending\" — the same behavior every server had before this field existed.\n */\nexport const TaskAwaitApprovalPayloadSchema = z.object({\n summary: z.string(),\n approvalId: z.string().optional(),\n});\nexport type TaskAwaitApprovalPayload = z.infer<typeof TaskAwaitApprovalPayloadSchema>;\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_MODEL_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 */\nexport const TaskCompletePayloadSchema = z.object({\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});\nexport type TaskCompletePayload = z.infer<typeof TaskCompletePayloadSchema>;\n\n/** daemon -> server: task failed. */\nexport const TaskFailPayloadSchema = z.object({\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 reason: z.string(),\n retryable: z.boolean().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});\nexport type TaskFailPayload = z.infer<typeof TaskFailPayloadSchema>;\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 */\nexport const TaskCancelledPayloadSchema = z.object({\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});\nexport type TaskCancelledPayload = z.infer<typeof TaskCancelledPayloadSchema>;\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. This is the additive-minor answer to a gap the M4 Phase 3 approval\n * work left open (see the \"Deferred additive candidate\" note this schema\n * resolves, `docs/protocol.md`): today the server only learns of a local\n * resolution IMPLICITLY, after the fact, once the daemon's next\n * `task.progress`/`task.artifact`/`task.complete` proves the task already\n * moved on (`ConnectionHub.resumeIfImplicitlyApproved`,\n * `packages/server/src/hub.ts`) — a window in which a SaaS-side\n * `TaskHandle.approve()`/`.reject()` can independently decide (and win) the\n * server's own authoritative record before that evidence ever arrives. This\n * message lets the daemon report the local resolution explicitly and\n * immediately, narrowing that window from \"until the next progress message\"\n * down to ordinary network latency; the implicit-inference path stays as-is,\n * unconditionally, as the compatibility fallback for an old server that\n * never advertises the `approval_resolved` capability flag (`version.ts`) or\n * an old daemon that predates this message entirely.\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 * deliberately future-proof (a later wave could add e.g. `'operator-cli'` as\n * a DISTINCT value without a version bump — a new enum member is additive,\n * same as a new message type or capability flag), while still being a closed,\n * typed shape today rather than an open string a typo could silently widen.\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// registry — single source of truth mapping message type -> payload schema\n// ---------------------------------------------------------------------------\n\n/** Protocol-owned task-opening family; the wire registry consumes these same entries. */\nconst TASK_OFFER_PAYLOAD_SCHEMAS = {\n 'task.offer': TaskOfferPayloadSchema,\n 'task.offer_with_toolsets': TaskOfferWithToolsetsPayloadSchema,\n 'task.offer_for_agent': TaskOfferForAgentPayloadSchema,\n 'task.offer_for_agent_with_egress': TaskOfferForAgentWithEgressPayloadSchema,\n 'task.offer_for_agent_with_egress_fresh': TaskOfferForAgentWithEgressFreshPayloadSchema,\n 'task.offer_prepared': TaskOfferPreparedPayloadSchema,\n} as const;\n\nexport type TaskOfferType = keyof typeof TASK_OFFER_PAYLOAD_SCHEMAS;\nexport const TASK_OFFER_TYPES: readonly TaskOfferType[] = Object.freeze(\n Object.keys(TASK_OFFER_PAYLOAD_SCHEMAS) as TaskOfferType[],\n);\n\n/** Classify task-opening offers without duplicating the protocol registry in consumers. */\nexport function isTaskOfferType(type: string): type is TaskOfferType {\n return Object.hasOwn(TASK_OFFER_PAYLOAD_SCHEMAS, type);\n}\n\nexport const MESSAGE_PAYLOAD_SCHEMAS = {\n 'conn.hello': ConnHelloPayloadSchema,\n 'conn.ack': ConnAckPayloadSchema,\n ...TASK_OFFER_PAYLOAD_SCHEMAS,\n 'agent.egress.reliable': AgentEgressReliablePayloadSchema,\n 'agent.egress.ack': AgentEgressAckPayloadSchema,\n 'agent.message.draft': AgentMessageDraftPayloadSchema,\n 'agent.message.publish': AgentMessagePublishPayloadSchema,\n 'agent.message.disposition': AgentMessageDispositionPayloadSchema,\n 'agent.content.read': AgentContentReadPayloadSchema,\n 'agent.content.receipt': AgentContentReceiptPayloadSchema,\n 'agent.home.projection': AgentHomeProjectionPayloadSchema,\n 'agent.input.preparation': AgentInputPreparationPayloadSchema,\n 'provider.provisioning.available': ProviderProvisioningAvailablePayloadSchema,\n 'agent.memory.intent.available': AgentMemoryIntentAvailablePayloadSchema,\n 'task.approve': TaskApprovePayloadSchema,\n 'task.reject': TaskRejectPayloadSchema,\n 'task.cancel': TaskCancelPayloadSchema,\n 'task.steer': TaskSteerPayloadSchema,\n 'task.claim': TaskClaimPayloadSchema,\n 'task.started': TaskStartedPayloadSchema,\n 'task.decline': TaskDeclinePayloadSchema,\n 'task.progress': TaskProgressPayloadSchema,\n 'task.artifact': TaskArtifactPayloadSchema,\n 'task.await_approval': TaskAwaitApprovalPayloadSchema,\n 'task.complete': TaskCompletePayloadSchema,\n 'task.fail': TaskFailPayloadSchema,\n 'task.cancelled': TaskCancelledPayloadSchema,\n 'task.approval_resolved': TaskApprovalResolvedPayloadSchema,\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 'conn.ack',\n 'task.offer',\n 'task.offer_with_toolsets',\n 'task.offer_for_agent',\n 'task.offer_for_agent_with_egress',\n 'task.offer_for_agent_with_egress_fresh',\n 'task.offer_prepared',\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] 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: it's\n * only ever valid as the first frame of a WS handshake (`ws-server.ts`), not\n * as ongoing inbound traffic through `ConnectionHub.handleInbound`.\n *\n * Used by `handleInbound` (`@byok-sdk/server`'s `hub.ts`) as the type-allow gate\n * for every inbound envelope, WS and `POST /byok/messages` alike (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';\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/**\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 AgentMemoryProjectionMutationSchema = z\n .object({\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 snapshot: AgentMemoryProjectionSnapshotSchema,\n })\n .strict();\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\n/** Immutable commit readback. It repeats identity and redacted metadata, never redacted bytes. */\nexport const AgentMemoryProjectionReceiptSchema = z\n .object({\n outcome: z.enum(['accepted', 'idempotent']),\n tenantId: z.string().min(1),\n deviceId: z.string().min(1),\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 redactedHash: AgentEgressContentHashSchema,\n redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),\n metering: AgentMemoryProjectionMeteringReceiptSchema,\n })\n .strict();\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 * 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) {\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.* — task_id stays optional (no task routing). conn.hello is\n // daemon -> server (no cursor to satisfy on this leg); conn.ack is\n // server -> daemon and therefore carries the required redelivery `seq`.\n envelopeShape('conn.hello', OPTIONAL_TASK_ID, OPTIONAL_SEQ),\n envelopeShape('conn.ack', OPTIONAL_TASK_ID, REQUIRED_SEQ),\n\n // task.* server -> daemon: task_id required (routing key) + seq required\n // (per-device redelivery cursor).\n envelopeShape('task.offer', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_with_toolsets', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent_with_egress', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_for_agent_with_egress_fresh', REQUIRED_TASK_ID, REQUIRED_SEQ),\n envelopeShape('task.offer_prepared', 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\n // task.* daemon -> server: task_id required (routing key); envelope-level\n // seq is not required in this direction in M1 (no daemon->server\n // redelivery cursor yet — 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 'conn.ack': { taskId?: string; seq: number };\n 'task.offer': { taskId: string; seq: number };\n 'task.offer_with_toolsets': { taskId: string; seq: number };\n 'task.offer_for_agent': { taskId: string; seq: number };\n 'task.offer_for_agent_with_egress': { taskId: string; seq: number };\n 'task.offer_for_agent_with_egress_fresh': { taskId: string; seq: number };\n 'task.offer_prepared': { taskId: string; seq: number };\n 'agent.egress.reliable': { taskId?: string; seq?: number };\n 'agent.egress.ack': { taskId?: string; seq: number };\n 'agent.message.draft': { taskId: string; seq?: number };\n 'agent.message.publish': { 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 'agent.content.receipt': { taskId?: string; 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 '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}\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 { CONTENT_HASH_RE } from './blob';\nimport { EnvelopeSchema } from './envelope';\nimport {\n AgentRefSchema,\n ConfiguredToolsetsSchema,\n ProtocolVersionNumberSchema,\n RuntimeIdSchema,\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 /** 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 expiresAt: z.iso.datetime({ offset: true }),\n});\nexport type TokenResponse = z.infer<typeof TokenResponseSchema>;\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, not a second runtime-capability\n * protocol. It retains only the facts the cloud persists and bounds every\n * string/array/numeric input at this public request boundary.\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});\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});\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 in v3: the server capabilities for THIS long-poll response, the\n * HTTP transport's equivalent of `conn.ack.capabilities`. Each page replaces\n * 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\nexport const MessagesSendRequestSchema = z.object({\n messages: z.array(EnvelopeSchema).max(MAX_MESSAGES_PER_BATCH),\n});\nexport type MessagesSendRequest = z.infer<typeof MessagesSendRequestSchema>;\n\n/**\n * `accepted` counts every envelope `ConnectionHub.handleInbound` returned\n * `'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/** `POST /byok/activity` — activity-tail append. */\nexport const BYOK_ACTIVITY_PATH = '/byok/activity';\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/** `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"]}
|