@byok-sdk/protocol 0.21.0 → 0.22.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/http-api.d.ts +6 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +7 -25
- package/dist/index.js.map +1 -1
- package/dist/input-preparation.d.ts +14 -99
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-egress.ts","../src/agent-home-projection.ts","../src/permission.ts","../src/input-preparation.ts","../src/terminal-projection.ts","../src/task-assertion.ts","../src/provider-profile-binding.ts","../src/version.ts","../src/blob.ts","../src/agent-event.ts","../src/messages.ts","../src/agent-memory-projection.ts","../src/task-state.ts","../src/envelope.ts","../src/errors.ts","../src/codec.ts","../src/http-api.ts"],"names":["z"],"mappings":";;;AAGO,IAAM,8BAAA,GAAiC;AACvC,IAAM,oCAAA,GAAuC;AAE7C,IAAM,qCAAA,GAAwC;AAE9C,IAAM,+BAAA,GAAkC;AACxC,IAAM,uCAAA,GAA0C;AAChD,IAAM,wCAAA,GAA2C;AACjD,IAAM,sCAAA,GAAyC;AAStD,IAAM,eAAA,GAAkB,CAAA,CACrB,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,gCAAA,EAAkC,oDAAoD,CAAA;AAE/F,IAAM,cAAA,GAAiB,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,EAAS,CAAE,GAAA,CAAI,UAAa,CAAA;AAC7D,IAAM,0BAA0B,GAAA,GAAM;AACtC,IAAM,0BAAA,GAA6B,CAAA,CACvC,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,iCAAA,EAAmC,wDAAwD;AAC7F,IAAM,gCAAgC,CAAA,CAAE,I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AA,CAAmB,MAAM,CAAC,CAAA,SAAA,CAAA;AAClD;AAEO,SAAS,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":["import { z } from 'zod';\n\n/** Additive daemon capability names. Server/cloud admission consumes these exactly. */\nexport const AGENT_EGRESS_POLICY_CAPABILITY = 'agent-egress-policy' as const;\nexport const AGENT_EGRESS_RELIABLE_ACK_CAPABILITY = 'agent-egress-reliable-ack' as const;\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/** Admits the distinct Agent-authored message lane; activity policy remains independent. */\nexport const AGENT_MESSAGE_EGRESS_CAPABILITY = 'agent-message-egress' as const;\nexport const AGENT_CONTENT_WORKSPACE_READ_CAPABILITY = 'agent-content-workspace-read' as const;\nexport const AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY = 'agent-content-transcript-read' as const;\nexport const AGENT_CONTENT_ARTIFACT_READ_CAPABILITY = 'agent-content-artifact-read' as const;\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_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\nexport const AgentEgressActivityPolicySchema = z.discriminatedUnion('mode', [\n z\n .object({\n mode: z.literal('metadata-status'),\n delivery: z.literal('latest-value'),\n })\n .strict(),\n z\n .object({\n mode: z.literal('contentful-trajectory'),\n delivery: z.literal('latest-value'),\n maxCoalesceMs: POSITIVE_LIMIT,\n maxEventBytes: POSITIVE_LIMIT,\n })\n .strict(),\n]);\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. Missing/unknown policy\n * is intentionally not represented as a default: callers must select a\n * revision and all three content 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 'sanitizer_rejected',\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 { AgentEgressContentHashSchema } from './agent-egress';\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/** 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 { z } from 'zod';\n\nexport const PERMISSION_MODES = ['auto', 'confirm', 'readonly', 'plan'] as const;\n\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\n/**\n * Policy the server proposes for a task. The daemon/runtime adapter maps this\n * onto the concrete runtime's flags; anything that can't be expressed exactly\n * must fail closed (deny) rather than silently widen the grant.\n *\n * `.strict()`: this is control/security data, so per the freeze rule's\n * observability-vs-control asymmetry (docs/protocol.md \"Freeze rule\") an\n * unrecognized field must be REJECTED, not silently stripped-and-ignored the\n * way an ordinary payload's unknown field is (plain `z.object()`'s default\n * behavior). Without `.strict()`, a policy carrying a future constraint this\n * schema doesn't know about yet would parse successfully with that\n * constraint silently discarded — exactly the silent-widening failure mode\n * this type's own doc comment above warns against, since a stripped\n * constraint is indistinguishable from a constraint that was never sent.\n *\n * Consequence: adding a new field to this schema post-freeze is therefore a\n * BREAKING change requiring a `PROTOCOL_VERSION` bump — unlike the general\n * \"a new optional field on an existing payload is non-breaking\" rule the\n * freeze rule grants every other schema. That's intentional: a new\n * security/control constraint must force a conscious version bump so an\n * unupgraded peer can never silently ignore it, rather than being added the\n * same low-friction way a harmless observability field would be.\n */\nexport const PermissionPolicySchema = z\n .object({\n mode: z.enum(PERMISSION_MODES),\n allowTools: z.array(z.string()).optional(),\n denyTools: z.array(z.string()).optional(),\n workspaceRoot: z.string().optional(),\n network: z.boolean().optional(),\n })\n .strict();\n\nexport type PermissionPolicy = z.infer<typeof PermissionPolicySchema>;\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema } from './agent-egress';\nimport { PERMISSION_MODES } from './permission';\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, exactly like `PermissionPolicySchema`.\n */\n\n/**\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 = 6 as const;\n\n/**\n * Capability required before a task-free remote input preparation — or a\n * prepared Execution — is admitted: `agent-input-preparation-v<N>`, where\n * `<N>` is {@link INPUT_PREPARATION_WIRE_VERSION}.\n *\n * The version is IN the token because the relay wire has none. A device\n * declares exactly the one token of the contract it speaks, and a cloud admits\n * exactly the one token of the contract it speaks, so a device and a cloud on\n * different contract versions never exchange a preparation at all: the cloud\n * refuses at enqueue (`agent_capability_missing`, before any receipt or\n * mailbox row) instead of relaying a payload the other side would refuse with\n * a strict-schema 422 and a device would then redeliver forever. There is no\n * dual token and no accepted older one. The retired unversioned token\n * `agent-input-preparation` (versions up to 4) is admitted nowhere.\n *\n * The token gates NEW admissions only. A row enqueued before a version cut is\n * still in flight afterwards, and its completion is accepted only by a cloud\n * on the same version as the device answering it; across the cut it is a 422\n * and a stalled device cursor. Draining in-flight rows and upgrading cloud and\n * devices as a pair is the operator precondition for the cut (`docs/spec.md`,\n * bounded admission); nothing here parses an older receipt.\n */\nexport const AGENT_INPUT_PREPARATION_CAPABILITY =\n `agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}` as const;\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/**\n * The permission mode a preparation is compiled FOR.\n *\n * It is the same closed set every task policy uses (`permission.ts`'s\n * `PERMISSION_MODES`), spelled here as its own schema because a preparation\n * carries a mode without carrying a policy: there is no task, no grant and no\n * approval seam on this wire. The mode selects which tools the device's own\n * observation projects into the counted manifest, and nothing else.\n *\n * Declared by the requester rather than inferred by the device: a device that\n * guessed would be counting a manifest the requester never asked for, and a\n * device that defaulted would silently count the widest one.\n */\nexport const InputPreparationPermissionModeSchema = z.enum(PERMISSION_MODES);\nexport type InputPreparationPermissionMode = z.infer<typeof InputPreparationPermissionModeSchema>;\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/** A path-like value carried verbatim into the native prompt renderer. */\nconst CONTEXT_PATH = z.string().max(4096).regex(/^[^\\u0000]*$/u, 'paths must not contain a NUL character');\n\nexport const InputPreparationContextFileSchema = z\n .object({ path: CONTEXT_PATH, content: z.string() })\n .strict();\n\n/**\n * The three documentation locations the native prompt renderer names.\n *\n * The wire field names are this SDK's own and do not track upstream Pi's\n * (`readme`/`docs`/`examples`): the contract a Host integrates against is this\n * one, and renaming a frozen wire field because a runtime renamed a parameter\n * would be a breaking change to every Host for no gain. The device adapter maps\n * these onto whatever the pinned runtime calls them.\n */\nexport const InputPreparationDocsPathsSchema = z\n .object({ readmePath: CONTEXT_PATH, docsPath: CONTEXT_PATH, examplesPath: CONTEXT_PATH })\n .strict();\n\n/**\n * One skill the system prompt renders, stated as the closed set of fields the\n * renderer actually reads.\n *\n * Not a preformatted string: the native renderer owns the skill block's\n * markup, and a Host-rendered one would be a second renderer that could drift\n * from what a live session emits. Loader bookkeeping the prompt never reads\n * (`baseDir`, source info) is deliberately absent — the Host cannot know it and\n * the device must never invent it.\n */\nexport const InputPreparationSkillSchema = z\n .object({\n name: OPAQUE_ID,\n description: z.string().max(4096),\n filePath: CONTEXT_PATH,\n disableModelInvocation: z.boolean(),\n })\n .strict();\nexport type InputPreparationSkill = z.infer<typeof InputPreparationSkillSchema>;\n\n/**\n * Explicit, already-authorized inputs for the native system prompt renderer.\n *\n * `toolSnippets` is PROMPT TEXT the Host authored — it is not the\n * model-visible tool schemas, which the device observes locally and the Host\n * never states (see this module's rule 1). `toolGuidelines` is the same kind of\n * value one level down: the guideline bullets a tool contributes, keyed by tool\n * name and bounded exactly like `toolSnippets` and `promptGuidelines`.\n *\n * `selectedTools` is deliberately absent for the same reason one level up: the\n * native contract requires that list to equal the model-visible manifest\n * exactly, so a Host stating it would be stating the manifest. The device\n * fills it from its own assembled tool surface.\n */\nexport const InputPreparationPromptSnapshotSchema = z\n .object({\n customPrompt: z.string().optional(),\n appendSystemPrompt: z.string().optional(),\n cwd: CONTEXT_PATH,\n toolSnippets: z.record(z.string(), z.string()),\n toolGuidelines: z.record(z.string(), z.array(z.string()).max(512)),\n promptGuidelines: z.array(z.string()).max(512),\n contextFiles: z.array(InputPreparationContextFileSchema).max(512),\n skills: z.array(InputPreparationSkillSchema).max(512),\n docsPaths: InputPreparationDocsPathsSchema,\n })\n .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, every executor identity is attested, 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 'executor_identity_unproven',\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 upstreamBase: OPAQUE_ID,\n upstreamCommit: OPAQUE_ID,\n forkBuild: z.number().int().nonnegative(),\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 device established about the implementation behind ONE\n * model-visible tool: `attested`, or `unavailable:<reason>` naming which of\n * the SDK's closed unavailable reasons applies.\n *\n * A kind, never the identity itself: an install path, a closure digest or a\n * stat tuple is device-local filesystem detail, and a receipt discloses\n * identity facts, not the machine's layout.\n */\nexport const InputPreparationToolImplementationKindSchema = z\n .string()\n .regex(/^(?:attested|unavailable:[a-z_]{1,64})$/u, 'a tool implementation kind is \"attested\" or \"unavailable:<reason>\"');\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, their executor fingerprints, the launch attestation and the\n * implementation identities — so a launch whose live observation differs is\n * a different manifest, whatever the schemas say.\n * - `toolBindingDigest` binds only the facts that can be re-derived WITHOUT\n * spawning a server: the launch attestation, the toolset definition\n * revisions and the implementation identities. It is what a replay of an\n * already-recorded requestId compares against, because re-probing to detect\n * drift would be the second executor fact the idempotency key exists to\n * prevent.\n * - `toolImplementationKinds` states, per model-visible tool name, whether the\n * implementation behind it was attested. It is the evidence behind\n * `executor_identity_unproven`, so a reader does not have to take that\n * readiness reason on trust.\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 toolImplementationKinds: z.record(OPAQUE_ID, InputPreparationToolImplementationKindSchema),\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 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 /**\n * The mode the counted manifest was filtered for. Recorded on the binding\n * rather than only inside the request digest so a consumer can COMPARE it\n * without re-deriving the digest: an Execution offered under a different\n * mode is an Execution whose registered tool set differs from the one\n * these tokens were counted for.\n */\n permissionMode: InputPreparationPermissionModeSchema,\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 * The device could not prove a non-writable launch directory (or a trusted\n * launcher) for the MCP toolset servers this preparation names, so it\n * refused rather than observing them in a directory the agent's own uid can\n * write. The specific `TrustedLaunchCwdUnavailableReason` travels in the\n * receipt's `detail`; it is not widened into a spawn.\n */\n 'launch_boundary_unavailable',\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, the launch attestation, or an implementation identity that no\n * longer measures the same. 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 declared `permissionMode` is not one this device admits: it exceeds\n * the operator's configured ceiling. The requester's declaration is INTENT,\n * not authorization — it goes through the same merge that admits a task\n * offer's `policy.mode` — and an unadmitted mode refuses rather than being\n * silently narrowed to one the device would allow.\n */\n 'permission_mode_denied',\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';\n\n/** Capability required before an offer may select terminal projection behavior. */\nexport const TERMINAL_PROJECTION_SELECTION_CAPABILITY = 'terminal-projection-selection' as const;\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/** Offer-scoped authority: explicit bypass or one required structured result. */\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 }).strict(),\n]);\nexport type TerminalProjectionSelection = z.infer<typeof TerminalProjectionSelectionSchema>;\n","/**\n * The device-level half of the task lane's capability gate (contract §8.1).\n *\n * Contract §8.1 fixes ONE name, `host-mcp-task-context`, carried on two\n * independent channels that must both be in place before a host may route a\n * tool invocation through the task lane:\n *\n * 1. **Deployment level** — the ADR-010 `CapabilityDeclarationSchema` a\n * deployment serves (`@byok-sdk/cloud`'s `CLOUD_CAPABILITIES`). §8.2(1)\n * governs it: a deployment declares the capability only once it is\n * completely implemented.\n * 2. **Device level** — this constant: a `conn.hello` capability string a host\n * consumes through `declaresCapabilities`. §8.3 governs it: a device whose\n * build cannot serve the lane simply does not advertise it, and the host\n * answers `unavailable` rather than reaching for the device assertion the\n * task lane does not accept.\n *\n * It lives in `@byok-sdk/protocol` for the same reason every other daemon\n * capability flag does: this package is the wire vocabulary both sides compile\n * against, and a name spelled twice is a name that can drift. It is registered\n * in `CAPABILITY_FLAGS` (`./version`), which is what makes it a value a daemon\n * can actually send.\n *\n * The spelling satisfies `@byok-sdk/core`'s `CAPABILITY_NAME_PATTERN`\n * (`/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/`) on purpose: the deployment-level channel\n * carries this exact literal, so a name legal in only one of the two channels\n * would leave them naming different things.\n */\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","import { z } from 'zod';\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/** 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","/** 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. Bump on breaking (non-additive) changes to the envelope\n * or message shapes. Additive changes (new optional fields, new message types)\n * do not require a bump — servers negotiate the highest common version and\n * daemons/servers must ignore unknown fields and unknown message types.\n *\n * FROZEN v1 (end of M2 — see docs/protocol.md \"Freeze rule\"): the pi, claude,\n * and codex runtime adapters have all exercised the wire, and every M1/M2\n * protocol gap has been closed. `PROTOCOL_VERSION` stays `1` from here\n * forward; it does not bump for additive changes (new optional fields, new\n * message types, new `AgentEvent` variants, new capability flags) — only for\n * a breaking one (changing, removing, or retyping anything that already\n * exists).\n *\n * IMPORTANT: changing this constant, or changing/removing/retyping any\n * already-frozen schema in this package, requires a DELIBERATE update to the\n * committed golden fixtures in `src/__tests__/golden/` (`v1.frozen.json`,\n * `v1.envelopes.ndjson`) — see `src/__tests__/freeze-guard.test.ts`, which\n * fails loudly on exactly that kind of drift. A passing freeze-guard run\n * after such a change means either (a) the change was genuinely additive and\n * the golden was regenerated with justification, or (b) this constant was\n * bumped alongside a new golden generation for the new version — never a\n * silent edit to either file to make the test pass.\n */\nexport const PROTOCOL_VERSION = 1;\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 * 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 * `result-document` (additive-minor): a SERVER-advertised flag meaning \"I\n * understand the optional `task.complete.document` field\" (`messages.ts`).\n * Functionally gating, like `approval_resolved` and unlike\n * `approval-targeting`.\n *\n * This is the N/N-1 answer for that new daemon -> server FIELD. An old\n * server's transport advertisement (`conn.ack.capabilities` on WS or\n * `EventsPollResponse.capabilities` on long-poll) never includes it, and\n * its `TaskCompletePayloadSchema` is a tolerant (non-`.strict()`)\n * `z.object()`, so a `document` sent to it would be silently STRIPPED on\n * parse and vanish without a trace. That is exactly why emission is gated\n * here rather than sent unconditionally the way `approvalId` is: `document`\n * carries the task's primary structured RESULT, so losing it silently is\n * data loss, not a missed observability hint. A new daemon talking to an old\n * server therefore never sends `document` at all, and — if its configured\n * extractor did produce one — reports `task.fail` (retryable: false; the\n * same server will strip it on every retry too) instead of completing the\n * task with its main result quietly deleted (`packages/client`'s\n * `task-runner.ts`). A new server talking to an old daemon is unaffected:\n * the field is optional, and an old daemon simply never sets it.\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 'result-document',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\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] as const;\n\nexport type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number];\nimport {\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n} from './agent-egress';\nimport { AGENT_HOME_PROJECTION_CAPABILITY } from './agent-home-projection';\nimport { AGENT_INPUT_PREPARATION_CAPABILITY } from './input-preparation';\nimport { TERMINAL_PROJECTION_SELECTION_CAPABILITY } from './terminal-projection';\nimport { HOST_MCP_TASK_CONTEXT_CAPABILITY } from './task-assertion';\nimport { PROVIDER_PROFILE_BINDING_CAPABILITY } from './provider-profile-binding';\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';\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 }),\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`, `policy` — see `messages.ts`/`permission.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 { BlobRefSchema } from './blob';\nimport { PermissionPolicySchema } from './permission';\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 ContentReadPolicySchema,\n} from './agent-egress';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionProfileRevisionSchema,\n AgentHomeProjectionValueSchema,\n} from './agent-home-projection';\nimport {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPermissionModeSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\nimport { ProviderProfileBindingSchema } from './provider-profile-binding';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\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 * Per-tool allow/deny lists are deliberately NOT included here (noise).\n * `permissionModes` mirrors `PERMISSION_MODES` (`permission.ts`) but is kept\n * as a bare `string[]` rather than `z.enum(PERMISSION_MODES)`: this is a\n * runtime's self-reported observability data, not a control/security field,\n * so — per the freeze rule (tolerate unknown for observability, fail closed\n * for control/security; see `agent-event.ts`'s unknown-variant tolerance for\n * the same asymmetry applied to `task.progress` events) — it stays tolerant\n * of a mode string a newer runtime might report that this schema doesn't\n * enumerate yet, rather than rejecting the whole `conn.hello`.\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 permissionModes: z.array(z.string()).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()`: like `PermissionPolicySchema`\n * (`permission.ts`), this is control data — it's 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 — same as `PermissionPolicySchema`.\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 policy: PermissionPolicySchema,\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 * 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 policy: PermissionPolicySchema,\n agentRef: AgentRefSchema,\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 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 'sanitized egress payload exceeds 256KiB',\n );\nconst EGRESS_SESSION_REF = z.string().min(1).max(512);\n\n/** Daemon -> cloud: one durable reliable-lane item after local sanitization. */\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. */\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 * 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 *\n * `permissionMode` is DECLARED by the requester and validated by the device;\n * the device never infers it. A preparation counts tokens for one concrete\n * tool manifest, and that manifest is the policy-filtered set for exactly one\n * mode (`mcp/projection.ts`'s `filterMcpObservationForPolicy`) — so a\n * preparation whose mode is unstated is a count of a manifest nobody named.\n * The device applies the declared mode to its own observation and records it\n * in the artifact binding; it is not a grant, and it authorizes nothing.\n */\nexport const AgentInputPreparationPayloadSchema = z\n .object({\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: RequiredToolsetsSchema,\n permissionMode: InputPreparationPermissionModeSchema,\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, or the offered policy exceeds this\n * device's ceiling. 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 * exactly, 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});\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 =\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/**\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 * 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 * ({@link isSameJsonData}). 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 let json: string | undefined;\n try {\n json = JSON.stringify(document);\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 > RESULT_DOCUMENT_MAX_BYTES) return { ok: false, reason: 'over-cap', bytes };\n\n const canonical: unknown = JSON.parse(json);\n if (!isSameJsonData(document, canonical)) return { ok: false, reason: 'not-plain-json' };\n\n return { ok: true, bytes, canonical };\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 * daemon -> server: task finished successfully.\n *\n * `document` (additive-minor, docs/protocol.md \"Freeze rule\"): 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 * Unlike `approvalId` on `task.await_approval` above, emitting this field IS\n * gated on a capability flag (`result-document`, `version.ts`): a pre-\n * `result-document` server strips it silently as an unknown key (the\n * tolerant `z.object()` behavior §1 mandates), and silently losing the\n * task's primary structured result is not a tolerable degradation the way\n * losing an observability hint is. So a daemon sends `document` only to a\n * server that advertised the flag, and fails the task loudly otherwise —\n * see `packages/client`'s `task-runner.ts`.\n */\nexport const TaskCompletePayloadSchema = z.object({\n harnessId: HarnessIdSchema.optional(),\n summary: z.string(),\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});\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});\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});\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.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 '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 '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.publish',\n 'agent.content.receipt',\n] as const satisfies readonly MessageType[];\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema, AgentEgressPolicyRevisionSchema } from './agent-egress';\nimport { AgentRefSchema, RuntimeIdSchema } from './messages';\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/** 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","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","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('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.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.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 '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\nexport const EventsPollResponseSchema = z.object({\n events: z.array(EnvelopeSchema),\n cursor: z.number().int(),\n /**\n * Server capabilities for THIS long-poll response. This is the HTTP\n * transport's equivalent of `conn.ack.capabilities`: a new daemon treats\n * absence as no advertised capabilities, so old responders remain\n * fail-closed for gated daemon -> server fields and messages.\n */\n capabilities: z.array(z.string()).optional(),\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 additive and omitted when zero, preserving frozen v1's\n * `{ accepted }` response shape.\n */\nexport const MessagesSendResponseSchema = z.object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative().optional(),\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/agent-egress.ts","../src/agent-home-projection.ts","../src/permission.ts","../src/input-preparation.ts","../src/terminal-projection.ts","../src/task-assertion.ts","../src/provider-profile-binding.ts","../src/version.ts","../src/blob.ts","../src/agent-event.ts","../src/messages.ts","../src/agent-memory-projection.ts","../src/task-state.ts","../src/envelope.ts","../src/errors.ts","../src/codec.ts","../src/http-api.ts"],"names":["z"],"mappings":";;;AAGO,IAAM,8BAAA,GAAiC;AACvC,IAAM,oCAAA,GAAuC;AAE7C,IAAM,qCAAA,GAAwC;AAE9C,IAAM,+BAAA,GAAkC;AACxC,IAAM,uCAAA,GAA0C;AAChD,IAAM,wCAAA,GAA2C;AACjD,IAAM,sCAAA,GAAyC;AAStD,IAAM,eAAA,GAAkB,CAAA,CACrB,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,gCAAA,EAAkC,oDAAoD,CAAA;AAE/F,IAAM,cAAA,GAAiB,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,EAAS,CAAE,GAAA,CAAI,UAAa,CAAA;AAC7D,IAAM,0BAA0B,GAAA,GAAM;AACtC,IAAM,0BAAA,GAA6B,CAAA,CACvC,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,GAAG,CAAA,CACP,KAAA,CAAM,iCAAA,EAAmC,wDAAwD;AAC7F,IAAM,gCAAgC,CAAA,CAAE,IAAA,CAAK,CAAC,YAAA,EAAc,eAAe,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,wBAAA,GAA2B;AAEjC,IAAM,mBAAA,GAAsB;AAE5B,IAAM,uBAAA,GAA0B;AAEhC,SAAS,qBAAqB,MAAA,EAAwB;AAC3D,EAAA,OAAO,CAAA,YAAA,EAAe,kBAAA,CAAmB,MAAM,CAAC,CAAA,SAAA,CAAA;AAClD;AAEO,SAAS,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":["import { z } from 'zod';\n\n/** Additive daemon capability names. Server/cloud admission consumes these exactly. */\nexport const AGENT_EGRESS_POLICY_CAPABILITY = 'agent-egress-policy' as const;\nexport const AGENT_EGRESS_RELIABLE_ACK_CAPABILITY = 'agent-egress-reliable-ack' as const;\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/** Admits the distinct Agent-authored message lane; activity policy remains independent. */\nexport const AGENT_MESSAGE_EGRESS_CAPABILITY = 'agent-message-egress' as const;\nexport const AGENT_CONTENT_WORKSPACE_READ_CAPABILITY = 'agent-content-workspace-read' as const;\nexport const AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY = 'agent-content-transcript-read' as const;\nexport const AGENT_CONTENT_ARTIFACT_READ_CAPABILITY = 'agent-content-artifact-read' as const;\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_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\nexport const AgentEgressActivityPolicySchema = z.discriminatedUnion('mode', [\n z\n .object({\n mode: z.literal('metadata-status'),\n delivery: z.literal('latest-value'),\n })\n .strict(),\n z\n .object({\n mode: z.literal('contentful-trajectory'),\n delivery: z.literal('latest-value'),\n maxCoalesceMs: POSITIVE_LIMIT,\n maxEventBytes: POSITIVE_LIMIT,\n })\n .strict(),\n]);\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. Missing/unknown policy\n * is intentionally not represented as a default: callers must select a\n * revision and all three content 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 'sanitizer_rejected',\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 { AgentEgressContentHashSchema } from './agent-egress';\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/** 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 { z } from 'zod';\n\nexport const PERMISSION_MODES = ['auto', 'confirm', 'readonly', 'plan'] as const;\n\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\n/**\n * Policy the server proposes for a task. The daemon/runtime adapter maps this\n * onto the concrete runtime's flags; anything that can't be expressed exactly\n * must fail closed (deny) rather than silently widen the grant.\n *\n * `.strict()`: this is control/security data, so per the freeze rule's\n * observability-vs-control asymmetry (docs/protocol.md \"Freeze rule\") an\n * unrecognized field must be REJECTED, not silently stripped-and-ignored the\n * way an ordinary payload's unknown field is (plain `z.object()`'s default\n * behavior). Without `.strict()`, a policy carrying a future constraint this\n * schema doesn't know about yet would parse successfully with that\n * constraint silently discarded — exactly the silent-widening failure mode\n * this type's own doc comment above warns against, since a stripped\n * constraint is indistinguishable from a constraint that was never sent.\n *\n * Consequence: adding a new field to this schema post-freeze is therefore a\n * BREAKING change requiring a `PROTOCOL_VERSION` bump — unlike the general\n * \"a new optional field on an existing payload is non-breaking\" rule the\n * freeze rule grants every other schema. That's intentional: a new\n * security/control constraint must force a conscious version bump so an\n * unupgraded peer can never silently ignore it, rather than being added the\n * same low-friction way a harmless observability field would be.\n */\nexport const PermissionPolicySchema = z\n .object({\n mode: z.enum(PERMISSION_MODES),\n allowTools: z.array(z.string()).optional(),\n denyTools: z.array(z.string()).optional(),\n workspaceRoot: z.string().optional(),\n network: z.boolean().optional(),\n })\n .strict();\n\nexport type PermissionPolicy = z.infer<typeof PermissionPolicySchema>;\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema } from './agent-egress';\nimport { PERMISSION_MODES } from './permission';\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, exactly like `PermissionPolicySchema`.\n */\n\n/**\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 = 7 as const;\n\n/**\n * Capability required before a task-free remote input preparation — or a\n * prepared Execution — is admitted: `agent-input-preparation-v<N>`, where\n * `<N>` is {@link INPUT_PREPARATION_WIRE_VERSION}.\n *\n * The version is IN the token because the relay wire has none. A device\n * declares exactly the one token of the contract it speaks, and a cloud admits\n * exactly the one token of the contract it speaks, so a device and a cloud on\n * different contract versions never exchange a preparation at all: the cloud\n * refuses at enqueue (`agent_capability_missing`, before any receipt or\n * mailbox row) instead of relaying a payload the other side would refuse with\n * a strict-schema 422 and a device would then redeliver forever. There is no\n * dual token and no accepted older one. The retired unversioned token\n * `agent-input-preparation` (versions up to 4) is admitted nowhere.\n *\n * The token gates NEW admissions only. A row enqueued before a version cut is\n * still in flight afterwards, and its completion is accepted only by a cloud\n * on the same version as the device answering it; across the cut it is a 422\n * and a stalled device cursor. Draining in-flight rows and upgrading cloud and\n * devices as a pair is the operator precondition for the cut (`docs/spec.md`,\n * bounded admission); nothing here parses an older receipt.\n */\nexport const AGENT_INPUT_PREPARATION_CAPABILITY =\n `agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}` as const;\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/**\n * The permission mode a preparation is compiled FOR.\n *\n * It is the same closed set every task policy uses (`permission.ts`'s\n * `PERMISSION_MODES`), spelled here as its own schema because a preparation\n * carries a mode without carrying a policy: there is no task, no grant and no\n * approval seam on this wire. The mode selects which tools the device's own\n * observation projects into the counted manifest, and nothing else.\n *\n * Declared by the requester rather than inferred by the device: a device that\n * guessed would be counting a manifest the requester never asked for, and a\n * device that defaulted would silently count the widest one.\n */\nexport const InputPreparationPermissionModeSchema = z.enum(PERMISSION_MODES);\nexport type InputPreparationPermissionMode = z.infer<typeof InputPreparationPermissionModeSchema>;\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, every executor identity is attested, 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 'executor_identity_unproven',\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 device established about the implementation behind ONE\n * model-visible tool: `attested`, or `unavailable:<reason>` naming which of\n * the SDK's closed unavailable reasons applies.\n *\n * A kind, never the identity itself: an install path, a closure digest or a\n * stat tuple is device-local filesystem detail, and a receipt discloses\n * identity facts, not the machine's layout.\n */\nexport const InputPreparationToolImplementationKindSchema = z\n .string()\n .regex(/^(?:attested|unavailable:[a-z_]{1,64})$/u, 'a tool implementation kind is \"attested\" or \"unavailable:<reason>\"');\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, their executor fingerprints, the launch attestation and the\n * implementation identities — so a launch whose live observation differs is\n * a different manifest, whatever the schemas say.\n * - `toolBindingDigest` binds only the facts that can be re-derived WITHOUT\n * spawning a server: the launch attestation, the toolset definition\n * revisions and the implementation identities. It is what a replay of an\n * already-recorded requestId compares against, because re-probing to detect\n * drift would be the second executor fact the idempotency key exists to\n * prevent.\n * - `toolImplementationKinds` states, per model-visible tool name, whether the\n * implementation behind it was attested. It is the evidence behind\n * `executor_identity_unproven`, so a reader does not have to take that\n * readiness reason on trust.\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 toolImplementationKinds: z.record(OPAQUE_ID, InputPreparationToolImplementationKindSchema),\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 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 /**\n * The mode the counted manifest was filtered for. Recorded on the binding\n * rather than only inside the request digest so a consumer can COMPARE it\n * without re-deriving the digest: an Execution offered under a different\n * mode is an Execution whose registered tool set differs from the one\n * these tokens were counted for.\n */\n permissionMode: InputPreparationPermissionModeSchema,\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 * The device could not prove a non-writable launch directory (or a trusted\n * launcher) for the MCP toolset servers this preparation names, so it\n * refused rather than observing them in a directory the agent's own uid can\n * write. The specific `TrustedLaunchCwdUnavailableReason` travels in the\n * receipt's `detail`; it is not widened into a spawn.\n */\n 'launch_boundary_unavailable',\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, the launch attestation, or an implementation identity that no\n * longer measures the same. 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 declared `permissionMode` is not one this device admits: it exceeds\n * the operator's configured ceiling. The requester's declaration is INTENT,\n * not authorization — it goes through the same merge that admits a task\n * offer's `policy.mode` — and an unadmitted mode refuses rather than being\n * silently narrowed to one the device would allow.\n */\n 'permission_mode_denied',\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';\n\n/** Capability required before an offer may select terminal projection behavior. */\nexport const TERMINAL_PROJECTION_SELECTION_CAPABILITY = 'terminal-projection-selection' as const;\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/** Offer-scoped authority: explicit bypass or one required structured result. */\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 }).strict(),\n]);\nexport type TerminalProjectionSelection = z.infer<typeof TerminalProjectionSelectionSchema>;\n","/**\n * The device-level half of the task lane's capability gate (contract §8.1).\n *\n * Contract §8.1 fixes ONE name, `host-mcp-task-context`, carried on two\n * independent channels that must both be in place before a host may route a\n * tool invocation through the task lane:\n *\n * 1. **Deployment level** — the ADR-010 `CapabilityDeclarationSchema` a\n * deployment serves (`@byok-sdk/cloud`'s `CLOUD_CAPABILITIES`). §8.2(1)\n * governs it: a deployment declares the capability only once it is\n * completely implemented.\n * 2. **Device level** — this constant: a `conn.hello` capability string a host\n * consumes through `declaresCapabilities`. §8.3 governs it: a device whose\n * build cannot serve the lane simply does not advertise it, and the host\n * answers `unavailable` rather than reaching for the device assertion the\n * task lane does not accept.\n *\n * It lives in `@byok-sdk/protocol` for the same reason every other daemon\n * capability flag does: this package is the wire vocabulary both sides compile\n * against, and a name spelled twice is a name that can drift. It is registered\n * in `CAPABILITY_FLAGS` (`./version`), which is what makes it a value a daemon\n * can actually send.\n *\n * The spelling satisfies `@byok-sdk/core`'s `CAPABILITY_NAME_PATTERN`\n * (`/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/`) on purpose: the deployment-level channel\n * carries this exact literal, so a name legal in only one of the two channels\n * would leave them naming different things.\n */\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","import { z } from 'zod';\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/** 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","/** 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. Bump on breaking (non-additive) changes to the envelope\n * or message shapes. Additive changes (new optional fields, new message types)\n * do not require a bump — servers negotiate the highest common version and\n * daemons/servers must ignore unknown fields and unknown message types.\n *\n * FROZEN v1 (end of M2 — see docs/protocol.md \"Freeze rule\"): the pi, claude,\n * and codex runtime adapters have all exercised the wire, and every M1/M2\n * protocol gap has been closed. `PROTOCOL_VERSION` stays `1` from here\n * forward; it does not bump for additive changes (new optional fields, new\n * message types, new `AgentEvent` variants, new capability flags) — only for\n * a breaking one (changing, removing, or retyping anything that already\n * exists).\n *\n * IMPORTANT: changing this constant, or changing/removing/retyping any\n * already-frozen schema in this package, requires a DELIBERATE update to the\n * committed golden fixtures in `src/__tests__/golden/` (`v1.frozen.json`,\n * `v1.envelopes.ndjson`) — see `src/__tests__/freeze-guard.test.ts`, which\n * fails loudly on exactly that kind of drift. A passing freeze-guard run\n * after such a change means either (a) the change was genuinely additive and\n * the golden was regenerated with justification, or (b) this constant was\n * bumped alongside a new golden generation for the new version — never a\n * silent edit to either file to make the test pass.\n */\nexport const PROTOCOL_VERSION = 1;\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 * 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 * `result-document` (additive-minor): a SERVER-advertised flag meaning \"I\n * understand the optional `task.complete.document` field\" (`messages.ts`).\n * Functionally gating, like `approval_resolved` and unlike\n * `approval-targeting`.\n *\n * This is the N/N-1 answer for that new daemon -> server FIELD. An old\n * server's transport advertisement (`conn.ack.capabilities` on WS or\n * `EventsPollResponse.capabilities` on long-poll) never includes it, and\n * its `TaskCompletePayloadSchema` is a tolerant (non-`.strict()`)\n * `z.object()`, so a `document` sent to it would be silently STRIPPED on\n * parse and vanish without a trace. That is exactly why emission is gated\n * here rather than sent unconditionally the way `approvalId` is: `document`\n * carries the task's primary structured RESULT, so losing it silently is\n * data loss, not a missed observability hint. A new daemon talking to an old\n * server therefore never sends `document` at all, and — if its configured\n * extractor did produce one — reports `task.fail` (retryable: false; the\n * same server will strip it on every retry too) instead of completing the\n * task with its main result quietly deleted (`packages/client`'s\n * `task-runner.ts`). A new server talking to an old daemon is unaffected:\n * the field is optional, and an old daemon simply never sets it.\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 'result-document',\n 'dispatch-selection',\n PROVIDER_PROFILE_BINDING_CAPABILITY,\n 'toolset-selection',\n 'agent-home-contract',\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] as const;\n\nexport type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number];\nimport {\n AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,\n AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,\n AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,\n AGENT_EGRESS_FRESH_SESSION_CAPABILITY,\n AGENT_EGRESS_POLICY_CAPABILITY,\n AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,\n AGENT_MESSAGE_EGRESS_CAPABILITY,\n} from './agent-egress';\nimport { AGENT_HOME_PROJECTION_CAPABILITY } from './agent-home-projection';\nimport { AGENT_INPUT_PREPARATION_CAPABILITY } from './input-preparation';\nimport { TERMINAL_PROJECTION_SELECTION_CAPABILITY } from './terminal-projection';\nimport { HOST_MCP_TASK_CONTEXT_CAPABILITY } from './task-assertion';\nimport { PROVIDER_PROFILE_BINDING_CAPABILITY } from './provider-profile-binding';\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';\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 }),\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`, `policy` — see `messages.ts`/`permission.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 { BlobRefSchema } from './blob';\nimport { PermissionPolicySchema } from './permission';\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 ContentReadPolicySchema,\n} from './agent-egress';\nimport {\n AgentHomeProjectionHashSchema,\n AgentHomeProjectionProfileRevisionSchema,\n AgentHomeProjectionValueSchema,\n} from './agent-home-projection';\nimport {\n InputPreparationAccountingPolicyRefSchema,\n InputPreparationArtifactSummarySchema,\n InputPreparationContentHashSchema,\n InputPreparationOfferBindingSchema,\n InputPreparationPermissionModeSchema,\n InputPreparationPolicyRevisionSchema,\n InputPreparationProfileIdSchema,\n InputPreparationSelectionSchema,\n InputPreparationSourceSchema,\n} from './input-preparation';\nimport { ProviderProfileBindingSchema } from './provider-profile-binding';\nimport { TerminalProjectionSelectionSchema } from './terminal-projection';\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 * Per-tool allow/deny lists are deliberately NOT included here (noise).\n * `permissionModes` mirrors `PERMISSION_MODES` (`permission.ts`) but is kept\n * as a bare `string[]` rather than `z.enum(PERMISSION_MODES)`: this is a\n * runtime's self-reported observability data, not a control/security field,\n * so — per the freeze rule (tolerate unknown for observability, fail closed\n * for control/security; see `agent-event.ts`'s unknown-variant tolerance for\n * the same asymmetry applied to `task.progress` events) — it stays tolerant\n * of a mode string a newer runtime might report that this schema doesn't\n * enumerate yet, rather than rejecting the whole `conn.hello`.\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 permissionModes: z.array(z.string()).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()`: like `PermissionPolicySchema`\n * (`permission.ts`), this is control data — it's 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 — same as `PermissionPolicySchema`.\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 policy: PermissionPolicySchema,\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 * 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 policy: PermissionPolicySchema,\n agentRef: AgentRefSchema,\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 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 'sanitized egress payload exceeds 256KiB',\n );\nconst EGRESS_SESSION_REF = z.string().min(1).max(512);\n\n/** Daemon -> cloud: one durable reliable-lane item after local sanitization. */\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. */\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 * 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 *\n * `permissionMode` is DECLARED by the requester and validated by the device;\n * the device never infers it. A preparation counts tokens for one concrete\n * tool manifest, and that manifest is the policy-filtered set for exactly one\n * mode (`mcp/projection.ts`'s `filterMcpObservationForPolicy`) — so a\n * preparation whose mode is unstated is a count of a manifest nobody named.\n * The device applies the declared mode to its own observation and records it\n * in the artifact binding; it is not a grant, and it authorizes nothing.\n */\nexport const AgentInputPreparationPayloadSchema = z\n .object({\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 permissionMode: InputPreparationPermissionModeSchema,\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, or the offered policy exceeds this\n * device's ceiling. 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 * exactly, 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});\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 =\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/**\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 * 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 * ({@link isSameJsonData}). 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 let json: string | undefined;\n try {\n json = JSON.stringify(document);\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 > RESULT_DOCUMENT_MAX_BYTES) return { ok: false, reason: 'over-cap', bytes };\n\n const canonical: unknown = JSON.parse(json);\n if (!isSameJsonData(document, canonical)) return { ok: false, reason: 'not-plain-json' };\n\n return { ok: true, bytes, canonical };\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 * daemon -> server: task finished successfully.\n *\n * `document` (additive-minor, docs/protocol.md \"Freeze rule\"): 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 * Unlike `approvalId` on `task.await_approval` above, emitting this field IS\n * gated on a capability flag (`result-document`, `version.ts`): a pre-\n * `result-document` server strips it silently as an unknown key (the\n * tolerant `z.object()` behavior §1 mandates), and silently losing the\n * task's primary structured result is not a tolerable degradation the way\n * losing an observability hint is. So a daemon sends `document` only to a\n * server that advertised the flag, and fails the task loudly otherwise —\n * see `packages/client`'s `task-runner.ts`.\n */\nexport const TaskCompletePayloadSchema = z.object({\n harnessId: HarnessIdSchema.optional(),\n summary: z.string(),\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});\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});\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});\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.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 '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 '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.publish',\n 'agent.content.receipt',\n] as const satisfies readonly MessageType[];\n","import { z } from 'zod';\nimport { AgentEgressContentHashSchema, AgentEgressPolicyRevisionSchema } from './agent-egress';\nimport { AgentRefSchema, RuntimeIdSchema } from './messages';\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/** 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","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","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('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.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.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 '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\nexport const EventsPollResponseSchema = z.object({\n events: z.array(EnvelopeSchema),\n cursor: z.number().int(),\n /**\n * Server capabilities for THIS long-poll response. This is the HTTP\n * transport's equivalent of `conn.ack.capabilities`: a new daemon treats\n * absence as no advertised capabilities, so old responders remain\n * fail-closed for gated daemon -> server fields and messages.\n */\n capabilities: z.array(z.string()).optional(),\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 additive and omitted when zero, preserving frozen v1's\n * `{ accepted }` response shape.\n */\nexport const MessagesSendResponseSchema = z.object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative().optional(),\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"]}
|