@byok-sdk/protocol 0.30.2 → 0.32.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/README.md +1 -1
- package/dist/agent-event.d.ts +2 -6
- package/dist/agent-memory.d.ts +79 -0
- package/dist/agent-memory.js +5 -0
- package/dist/agent-memory.js.map +1 -0
- package/dist/capability-constants.d.ts +9 -0
- package/dist/codec.d.ts +10 -86
- package/dist/constants.d.ts +14 -0
- package/dist/constants.js +2 -114
- package/dist/constants.js.map +1 -1
- package/dist/envelope.d.ts +1 -1
- package/dist/failure-reason.d.ts +23 -0
- package/dist/http-api.d.ts +74 -5
- package/dist/index.d.ts +7 -8
- package/dist/index.js +3 -3053
- package/dist/index.js.map +1 -1
- package/dist/input-preparation.d.ts +1 -1
- package/dist/messages.d.ts +1345 -1369
- package/dist/open-vocabulary.d.ts +5 -0
- package/dist/sealed-payload.d.ts +16 -14
- package/dist/sealed-split-table.d.ts +61 -55
- package/dist/version.d.ts +22 -54
- package/dist/wire-additions.d.ts +11 -7
- package/package.json +7 -4
- package/dist/task-assertion.d.ts +0 -28
package/dist/index.js
CHANGED
|
@@ -1,3059 +1,9 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { Validator } from '@cfworker/json-schema';
|
|
3
3
|
|
|
4
|
-
// src/capability-constants.ts
|
|
5
|
-
var INPUT_PREPARATION_WIRE_VERSION = 9;
|
|
6
|
-
var AGENT_EGRESS_POLICY_CAPABILITY = "agent-egress-policy";
|
|
7
|
-
var AGENT_EGRESS_RELIABLE_ACK_CAPABILITY = "agent-egress-reliable-ack";
|
|
8
|
-
var AGENT_EGRESS_FRESH_SESSION_CAPABILITY = "agent-egress-fresh-session";
|
|
9
|
-
var AGENT_MESSAGE_EGRESS_CAPABILITY = "agent-message-egress";
|
|
10
|
-
var AGENT_CONTENT_WORKSPACE_READ_CAPABILITY = "agent-content-workspace-read";
|
|
11
|
-
var AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY = "agent-content-transcript-read";
|
|
12
|
-
var AGENT_CONTENT_ARTIFACT_READ_CAPABILITY = "agent-content-artifact-read";
|
|
13
|
-
var AGENT_HOME_PROJECTION_CAPABILITY = "agent-home-projection";
|
|
14
|
-
var TERMINAL_PROJECTION_SELECTION_CAPABILITY = "terminal-projection-selection";
|
|
15
|
-
var HOST_MCP_TASK_CONTEXT_CAPABILITY = "host-mcp-task-context";
|
|
16
|
-
var PROVIDER_PROFILE_BINDING_CAPABILITY = "provider-profile-binding";
|
|
17
|
-
var PROVIDER_PROVISIONING_CAPABILITY = "provider-provisioning.v1";
|
|
18
|
-
var AGENT_MEMORY_INTENT_CAPABILITY = "agent-memory-intent.v1";
|
|
19
|
-
var AGENT_MEMORY_PROJECTION_CAPABILITY = "agent.memory.projection";
|
|
20
|
-
var AGENT_MEMORY_SELECTION_CAPABILITY = "agent-memory-selection";
|
|
21
|
-
var AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY = "agent-memory-read-if-admitted";
|
|
22
|
-
var AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY = "agent-memory-read-write-if-admitted";
|
|
23
|
-
var AGENT_INPUT_PREPARATION_CAPABILITY = `agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}`;
|
|
24
|
-
var SEALED_PAYLOAD_CAPABILITY = "sealed-payload-v1";
|
|
25
|
-
var SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY = "sealed-output-ciphertext-ref";
|
|
26
|
-
var RUNTIME_FAILURE_CLASS_CAPABILITY = "runtime-failure-class";
|
|
27
|
-
var RUNTIME_FAILURE_CLASSES = [
|
|
28
|
-
"auth",
|
|
29
|
-
"quota",
|
|
30
|
-
"rate_limited",
|
|
31
|
-
"billing",
|
|
32
|
-
"model_unavailable",
|
|
33
|
-
"input_too_large",
|
|
34
|
-
"invalid_request",
|
|
35
|
-
"overloaded",
|
|
36
|
-
"provider",
|
|
37
|
-
"runtime_exited",
|
|
38
|
-
"limit_reached",
|
|
39
|
-
"output_schema",
|
|
40
|
-
"unknown"
|
|
41
|
-
];
|
|
42
|
-
var PREPARED_AGENT_MEMORY_MODES = ["none", "read", "read-write"];
|
|
43
|
-
function isPreparedAgentMemoryMode(value) {
|
|
44
|
-
return typeof value === "string" && PREPARED_AGENT_MEMORY_MODES.some((mode) => mode === value);
|
|
45
|
-
}
|
|
4
|
+
var INPUT_PREPARATION_WIRE_VERSION=9;var AGENT_EGRESS_POLICY_CAPABILITY="agent-egress-policy";var AGENT_EGRESS_RELIABLE_ACK_CAPABILITY="agent-egress-reliable-ack";var AGENT_EGRESS_FRESH_SESSION_CAPABILITY="agent-egress-fresh-session";var AGENT_MESSAGE_EGRESS_CAPABILITY="agent-message-egress";var AGENT_CONTENT_WORKSPACE_READ_CAPABILITY="agent-content-workspace-read";var AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY="agent-content-transcript-read";var AGENT_CONTENT_ARTIFACT_READ_CAPABILITY="agent-content-artifact-read";var AGENT_HOME_PROJECTION_CAPABILITY="agent-home-projection";var TERMINAL_PROJECTION_SELECTION_CAPABILITY="terminal-projection-selection";var HOST_MCP_TASK_CONTEXT_CAPABILITY="host-mcp-task-context";var PROVIDER_PROFILE_BINDING_CAPABILITY="provider-profile-binding";var PROVIDER_PROVISIONING_CAPABILITY="provider-provisioning.v1";var AGENT_MEMORY_INTENT_CAPABILITY="agent-memory-intent.v1";var AGENT_MEMORY_PROJECTION_CAPABILITY="agent.memory.projection";var AGENT_MEMORY_SELECTION_CAPABILITY="agent-memory-selection";var AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY="agent-memory-read-if-admitted";var AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY="agent-memory-read-write-if-admitted";var AGENT_INPUT_PREPARATION_CAPABILITY=`agent-input-preparation-v${INPUT_PREPARATION_WIRE_VERSION}`;var SEALED_PAYLOAD_CAPABILITY="sealed-payload-v1";var SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY="sealed-output-ciphertext-ref";var RUNTIME_FAILURE_CLASS_CAPABILITY="runtime-failure-class";var RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY="runtime-unavailable-cause";var RUNTIME_FAILURE_CLASSES=["auth","quota","rate_limited","billing","model_unavailable","input_too_large","invalid_request","overloaded","provider","runtime_exited","limit_reached","output_schema","unknown"];var PREPARED_AGENT_MEMORY_MODES=["none","read","read-write"];function isPreparedAgentMemoryMode(value){return typeof value==="string"&&PREPARED_AGENT_MEMORY_MODES.some(mode=>mode===value)}var MAILBOX_READ_AHEAD_MAX_SEQS=4096;var MAILBOX_READ_AHEAD_CAPABILITY="mailbox-read-ahead";var PROTOCOL_VERSION=4;var AGENT_HOME_READERS_CAPABILITY="agent-home-readers";var CUSTOM_HARNESS_CAPABILITY="custom-harness";var CAPABILITY_FLAGS=["steer","blob-upload","dispatch-selection",PROVIDER_PROFILE_BINDING_CAPABILITY,"toolset-selection","agent-home-contract",AGENT_HOME_READERS_CAPABILITY,AGENT_EGRESS_POLICY_CAPABILITY,AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,AGENT_MESSAGE_EGRESS_CAPABILITY,AGENT_EGRESS_FRESH_SESSION_CAPABILITY,AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,AGENT_HOME_PROJECTION_CAPABILITY,AGENT_INPUT_PREPARATION_CAPABILITY,TERMINAL_PROJECTION_SELECTION_CAPABILITY,HOST_MCP_TASK_CONTEXT_CAPABILITY,CUSTOM_HARNESS_CAPABILITY,MAILBOX_READ_AHEAD_CAPABILITY,PROVIDER_PROVISIONING_CAPABILITY,AGENT_MEMORY_INTENT_CAPABILITY,AGENT_MEMORY_SELECTION_CAPABILITY,AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,"agent-message-draft",SEALED_PAYLOAD_CAPABILITY,SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,RUNTIME_FAILURE_CLASS_CAPABILITY,RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY];var TASK_STATES=["Offered","Claimed","Running","AwaitApproval","Complete","Failed","Cancelled"];var TASK_TRANSITIONS={Offered:["Claimed","Cancelled","Failed"],Claimed:["Running","Failed","Cancelled"],Running:["AwaitApproval","Complete","Failed","Cancelled"],AwaitApproval:["Running","Failed","Cancelled"],Complete:[],Failed:[],Cancelled:[]};function canTransition(from,to){return TASK_TRANSITIONS[from].includes(to)}var TASK_FAIL_REASON_MAX_BYTES=2048;var REDACTED="[redacted]";var VALUE=String.raw`(?:"(?:\\[^\n]|[^"\\\n])*(?:\\)?"?|'(?:\\[^\n]|[^'\\\n])*(?:\\)?'?|[^\s"'\[\u2026,;&|][^\s"',;&|]*)`;var GAP="[ \\t]{0,16}";var RULES=[[new RegExp(String.raw`\b((?:proxy-)?authorization)(["']?${GAP}[:=]${GAP})(?:(?:bearer|basic|token|digest)[ \t]{1,16})?${VALUE}`,"gi"),`$1$2${REDACTED}`],[/\b(bearer)[ \t]{1,16}[A-Za-z0-9._~+/=-]{8,}/gi,`$1 ${REDACTED}`],[new RegExp(String.raw`(key|token|secret|passw(?:or)?d[\w.-]{0,64})(["']?${GAP}[:=]${GAP})${VALUE}`,"gi"),`$1$2${REDACTED}`],[/:\/\/[^\s/?#@]{1,256}@/g,`://${REDACTED}@`],[/\bsk-[A-Za-z0-9_-]{16,}/g,REDACTED],[/\bxai-[A-Za-z0-9_-]{16,}/g,REDACTED],[/\bAIza[0-9A-Za-z_-]{30,}/g,REDACTED],[/\bgh[pousr]_[A-Za-z0-9]{20,}/g,REDACTED],[/\bgithub_pat_[A-Za-z0-9_]{20,}/g,REDACTED],[/\bAKIA[0-9A-Z]{16}/g,REDACTED],[/\beyJ[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*){0,2}/g,REDACTED]];var encoder=new TextEncoder;var decoder=new TextDecoder("utf-8");function redact(text2){let out=text2;for(const[pattern,replacement]of RULES)out=out.replace(pattern,replacement);return out}function boundFailureReason(reason){const redacted=redact(reason);const bytes=encoder.encode(redacted);if(bytes.length<=TASK_FAIL_REASON_MAX_BYTES)return redacted;let keep=TASK_FAIL_REASON_MAX_BYTES-encoder.encode(`\u2026[truncated ${bytes.length} bytes]`).length;while(keep>0&&((bytes[keep]??0)&192)===128)keep-=1;return `${decoder.decode(bytes.subarray(0,keep))}\u2026[truncated ${bytes.length-keep} bytes]`}var AGENT_MEMORY_MAX_SNAPSHOT_BYTES=1024*1024;var AGENT_MEMORY_MAX_SNAPSHOT_FILES=128;var RUNTIME_IDS=Object.freeze(["pi","claude","codex"]);var RUNTIME_UNAVAILABLE_CAUSES=Object.freeze(["not_installed","not_executable","probe_timeout","probe_failed","app_server_unavailable","acp_unavailable","platform_unsupported","environment_unavailable","version_blocked","runtime_not_configured","runtime_not_allowed","none_available"]);var TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH=160;var TERMINAL_DIGESTS={"agentRef.profileRevision":"plain","agentHomeProjection.profileRevision":"plain","agentHomeProjection.projectionHash":"plain"};var SEALED_SPLIT_TABLE=Object.freeze({"task.offer":{marker:"sealing",category:"task-input",identity:[],moved:["instruction"],forbidden:["preparation"],digests:{"instruction.blobRef.contentHash":"sealed","agentRef.profileRevision":"plain","dispatchSelection.providerProfile.profileRevision":"plain","dispatchSelection.providerProfile.profileHash":"plain","egressPolicy.policyRevision":"plain","preparation.requestDigest":"forbidden","preparation.artifactDigest":"forbidden"}},"task.steer":{marker:"sealed",category:"task-input",identity:["steerId"],moved:["text"],forbidden:[],digests:{}},"task.complete":{marker:"sealed",category:"task-output",identity:[],moved:["summary","finalMessage","document"],forbidden:["artifactRefs","preparedObservation"],digests:{...TERMINAL_DIGESTS,"artifactRefs[].contentHash":"forbidden","preparedObservation.requestDigest":"forbidden"}},"task.fail":{marker:"sealed",category:"task-output",identity:[],moved:["reason"],forbidden:["preparedObservation"],digests:{...TERMINAL_DIGESTS,"preparedObservation.requestDigest":"forbidden"}},"task.decline":{marker:"sealed",category:"task-output",identity:[],moved:["reason"],forbidden:[],digests:{"agentRef.profileRevision":"plain"}},"task.cancelled":{marker:"sealed",category:"task-output",identity:[],moved:["reason"],forbidden:[],digests:TERMINAL_DIGESTS},"task.progress":{marker:"sealed",category:"task-output",identity:["seq"],moved:["events"],forbidden:[],digests:{"events[].spill.blob.contentHash":"sealed"},inlineOnly:true},"task.artifact":{marker:"sealed",category:"task-output",identity:["artifactId"],moved:["inline"],forbidden:["blobRef"],digests:{"blobRef.contentHash":"forbidden"},limits:{inline:2*1024*1024}},"task.await_approval":{marker:"sealed",category:"task-output",identity:["approvalId"],moved:["summary"],forbidden:[],digests:{},inlineOnly:true}});function isSealableMessageType(type){return Object.hasOwn(SEALED_SPLIT_TABLE,type)}function isSealedPayload(type,payload){return isSealableMessageType(type)&&payload!==null&&typeof payload==="object"&&payload[SEALED_SPLIT_TABLE[type].marker]!==void 0}var MATRIX_FIELDS=["toolAuthorizationAuto","durablePi","preparedLane","isolation"];var offerRow=(field,capability,value)=>({kind:"envelope",rule:"gated",surface:"task.offer",...field===void 0?{}:{field},...value===void 0?{}:{value},capability,advertisedBy:"device"});function sealedRows(){return Object.keys(SEALED_SPLIT_TABLE).flatMap(surface=>{const entry=SEALED_SPLIT_TABLE[surface];const advertisedBy=entry.category==="task-input"?"device":"server";const byReference=advertisedBy==="server"&&entry.inlineOnly!==true?[{kind:"envelope",rule:"gated",surface,field:"sealed.ciphertextRef",capability:"sealed-output-ciphertext-ref",advertisedBy}]:[];return [{kind:"envelope",rule:"gated",surface,field:entry.marker,capability:"sealed-payload-v1",advertisedBy},...byReference]})}var SEALED_DECLINE_CODE=value=>({kind:"envelope",rule:"gated",surface:"task.decline",field:"code",value,capability:"sealed-payload-v1",advertisedBy:"server"});var PLAIN_ROWS=[offerRow(void 0,"agent-home-contract"),offerRow("dispatchSelection","dispatch-selection"),offerRow("requiredToolsets","toolset-selection"),offerRow("terminalProjection","terminal-projection-selection"),offerRow("homeAccess","agent-home-readers"),offerRow("harnessId","custom-harness"),offerRow("agentMemory","agent-memory-selection"),offerRow("agentMemory","agent-memory-read-if-admitted","read-if-admitted"),offerRow("agentMemory","agent-memory-read-write-if-admitted","read-write-if-admitted"),offerRow("egressPolicy","agent-egress-policy"),offerRow("egressPolicy","agent-egress-reliable-ack"),offerRow("messageEgress","agent-message-egress"),offerRow("session.mode","agent-egress-fresh-session","fresh"),offerRow("preparation","agent-input-preparation-v9"),{kind:"envelope",rule:"gated",surface:"agent.content.read",capability:"agent-home-contract",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.content.read",capability:"agent-egress-policy",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.content.read",capability:"agent-egress-reliable-ack",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.content.read",field:"surface",value:"workspace",capability:"agent-content-workspace-read",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.content.read",field:"surface",value:"transcript",capability:"agent-content-transcript-read",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.content.read",field:"surface",value:"artifact",capability:"agent-content-artifact-read",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.home.projection",capability:"agent-home-contract",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.home.projection",capability:"agent-home-projection",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.input.preparation",capability:"agent-home-contract",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.input.preparation",capability:"agent-input-preparation-v9",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"provider.provisioning.available",capability:"provider-provisioning.v1",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"agent.memory.intent.available",capability:"agent-memory-intent.v1",advertisedBy:"device"},{kind:"envelope",rule:"gated",surface:"e2ee.key_package.available",capability:"sealed-payload-v1",advertisedBy:"device"},{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:"runtimes[].capabilities.messageDraft"},{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:"harnesses[].capabilities.messageDraft"},{kind:"envelope",rule:"strip-safe",surface:"task.claim",field:"capabilities.messageDraft"},...MATRIX_FIELDS.flatMap(field=>[{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:`runtimes[].capabilities.${field}`},{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:`harnesses[].capabilities.${field}`},{kind:"envelope",rule:"strip-safe",surface:"task.claim",field:`capabilities.${field}`}]),{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:"runtimes[].versionPolicy"},{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:"harnesses[].versionPolicy"},{kind:"envelope",rule:"strip-safe",surface:"conn.hello",field:"runtimeUnavailable"},{kind:"http",rule:"strip-safe",surface:"PresencePublishRequest",field:"runtimes[].versionPolicy"},{kind:"http",rule:"strip-safe",surface:"PresencePublishRequest",field:"runtimeUnavailable"},{kind:"http",rule:"strip-safe",surface:"PresencePublishRequest",field:"runtimes[].capabilities"},{kind:"envelope",rule:"strip-safe",surface:"task.progress",field:"events[].mcp"},{kind:"envelope",rule:"gated",surface:"agent.message.draft",capability:"agent-message-draft",advertisedBy:"server"},{kind:"envelope",rule:"gated",surface:"task.fail",field:"failure",capability:"runtime-failure-class",advertisedBy:"server"},{kind:"envelope",rule:"strip-safe",surface:"task.decline",field:"runtimeUnavailable"},{kind:"http",rule:"strip-safe",surface:"TokenResponse",field:"expiresIn"},{kind:"http",rule:"strip-safe",surface:"PairResponse",field:"expiresIn"}];var WIRE_ADDITIONS=Object.freeze([...PLAIN_ROWS,...sealedRows(),SEALED_DECLINE_CODE("sealed_key_unavailable"),SEALED_DECLINE_CODE("sealed_open_failed"),SEALED_DECLINE_CODE("sealed_content_mac_mismatch"),SEALED_DECLINE_CODE("sealing_policy_mismatch")]);function requiredReceiverCapabilities(type,payload){const fields=payload!==null&&typeof payload==="object"?payload:{};const required=[];for(const entry of WIRE_ADDITIONS){if(entry.kind!=="envelope"||entry.rule!=="gated"||entry.surface!==type)continue;if(entry.field!==void 0){const value=entry.field.split(".").reduce((parent,segment)=>parent!==null&&typeof parent==="object"?parent[segment]:void 0,fields);if(value===void 0)continue;if(entry.value!==void 0&&value!==entry.value)continue}if(!required.includes(entry.capability))required.push(entry.capability);}return required}var CONTENT_HASH_RE=/^sha256:[0-9a-f]{64}$/;var BlobRefSchema=z.object({blobId:z.string(),contentHash:z.string().regex(CONTENT_HASH_RE,'contentHash must be "sha256:<64 lowercase hex>"'),size:z.number().int().nonnegative(),contentType:z.string(),url:z.string().optional()});var SEALED_PAYLOAD_VERSION=1;var SEALED_PAYLOAD_SUITE="byok-sealed-v1.hkdf-sha256.aes-256-gcm";var SEALED_PAYLOAD_CATEGORIES=["task-input","agent-message","task-output","memory-projection"];var SEALED_PAYLOAD_V1_CATEGORIES=["task-input","task-output"];var SEALED_DECLINE_CODES=["sealed_key_unavailable","sealed_open_failed","sealed_content_mac_mismatch","sealing_policy_mismatch"];var SEALED_TASK_PLAIN_CODES=Object.freeze({"task.fail":{reason:["daemon_interrupted","sealed_key_unavailable"]},"task.decline":{reason:SEALED_DECLINE_CODES},"task.cancelled":{reason:[]}});function isSealedTaskPlainOutput(type,payload){const codes=Object.hasOwn(SEALED_TASK_PLAIN_CODES,type)?SEALED_TASK_PLAIN_CODES[type]:{};const entry=isSealableMessageType(type)?SEALED_SPLIT_TABLE[type]:void 0;const fields=entry?.category==="task-output"?[...entry.moved,...entry.forbidden]:[];if(fields.length>0&&!Object.hasOwn(SEALED_TASK_PLAIN_CODES,type))return false;const record=payload;for(const field of fields){const value=record[field];if(value!==void 0&&!(typeof value==="string"&&(codes[field]??[]).includes(value)))return false}return type!=="task.decline"||record.reason===void 0||record.code===record.reason}var SEALED_INLINE_MAX_PADDED_LENGTH=256*1024;var SEALED_PAYLOAD_MAX_CONTENT_LENGTH=2*1024*1024;var AEAD_TAG_BYTES=16;var FRAME_HEADER_BYTES=4;var ALIGNED_FRAME_LIMIT=16*1024;var FRAME_ALIGNMENT=256;var SALT_BYTES=32;var NONCE_BYTES=12;function floorLog2(value){let exponent=0;for(let remaining=value;remaining>=2;remaining=Math.floor(remaining/2))exponent+=1;return exponent}function sealedPayloadPaddedLength(frameLength){if(!Number.isSafeInteger(frameLength)||frameLength<FRAME_HEADER_BYTES){throw new RangeError("Sealed frame length must be a safe integer of at least 4")}if(frameLength<=ALIGNED_FRAME_LIMIT)return Math.ceil(frameLength/FRAME_ALIGNMENT)*FRAME_ALIGNMENT;const exponent=floorLog2(frameLength);const step=2**(exponent-(floorLog2(exponent)+1));return Math.ceil(frameLength/step)*step}var SEALED_PAYLOAD_MAX_PADDED_LENGTH=sealedPayloadPaddedLength(FRAME_HEADER_BYTES+SEALED_PAYLOAD_MAX_CONTENT_LENGTH);function isLegalPaddedLength(value){return Number.isSafeInteger(value)&&value>=FRAME_ALIGNMENT&&value<=SEALED_PAYLOAD_MAX_PADDED_LENGTH&&sealedPayloadPaddedLength(value)===value}var BASE64URL_VALUE=/^[A-Za-z0-9_-]*$/u;var BASE64URL_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function sealedBase64UrlByteLength(value){if(!BASE64URL_VALUE.test(value))return void 0;const tail=value.length%4;if(tail===1)return void 0;if(tail!==0){const last=BASE64URL_ALPHABET.indexOf(value[value.length-1]);const unusedBits=tail===2?15:3;if((last&unusedBits)!==0)return void 0}return Math.floor(value.length/4)*3+(tail===0?0:tail-1)}function base64UrlOf(bytes){return z.string().refine(value=>sealedBase64UrlByteLength(value)===bytes,`must be canonical unpadded base64url of ${bytes} bytes`)}var PositiveIntegerSchema=z.number().int().positive().max(Number.MAX_SAFE_INTEGER);function sealedPayloadSchema(category){return z.object({v:z.literal(SEALED_PAYLOAD_VERSION),suite:z.literal(SEALED_PAYLOAD_SUITE),category,scope:z.object({id:z.string().min(1),epoch:PositiveIntegerSchema,keyId:z.string().regex(/^[A-Za-z0-9_-]{22}$/u)}).strict(),chainHead:z.object({seq:PositiveIntegerSchema,hash:z.string().regex(CONTENT_HASH_RE)}).strict(),sender:z.string().regex(/^[A-Za-z0-9_-]{43}$/u),salt:base64UrlOf(SALT_BYTES),nonce:base64UrlOf(NONCE_BYTES),paddedLength:PositiveIntegerSchema.refine(isLegalPaddedLength,"must be a legal padded frame length within the v1 limit"),contentMac:z.string().regex(/^hmac-sha256:[0-9a-f]{64}$/u),ciphertext:z.string().optional(),ciphertextRef:BlobRefSchema.omit({url:true}).strict().optional()}).strict().superRefine((sealed,ctx)=>{const ciphertextLength=sealed.paddedLength+AEAD_TAG_BYTES;const inline=sealed.paddedLength<=SEALED_INLINE_MAX_PADDED_LENGTH;if(inline){if(sealed.ciphertextRef!==void 0||sealed.ciphertext===void 0){ctx.addIssue({code:"custom",path:["ciphertext"],message:`a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH} carries inline ciphertext only`});}else if(sealedBase64UrlByteLength(sealed.ciphertext)!==ciphertextLength){ctx.addIssue({code:"custom",path:["ciphertext"],message:"ciphertext must be canonical base64url of paddedLength + 16 bytes"});}return}if(sealed.ciphertext!==void 0||sealed.ciphertextRef===void 0){ctx.addIssue({code:"custom",path:["ciphertextRef"],message:`a padded length above ${SEALED_INLINE_MAX_PADDED_LENGTH} carries ciphertextRef only`});}else if(sealed.ciphertextRef.size!==ciphertextLength){ctx.addIssue({code:"custom",path:["ciphertextRef","size"],message:"ciphertextRef size must equal paddedLength + 16"});}})}var SealedPayloadSchema=sealedPayloadSchema(z.enum(SEALED_PAYLOAD_V1_CATEGORIES));var SealedTaskInputSchema=sealedPayloadSchema(z.literal("task-input"));var SealedTaskOutputSchema=sealedPayloadSchema(z.literal("task-output"));function isCanonicalCategoryList(categories){return categories.every((category,index)=>index===0||SEALED_PAYLOAD_CATEGORIES.indexOf(categories[index-1])<SEALED_PAYLOAD_CATEGORIES.indexOf(category))}var TaskSealingSchema=z.object({scopeId:z.string().min(1),epoch:PositiveIntegerSchema,categories:z.array(z.enum(SEALED_PAYLOAD_V1_CATEGORIES)).min(1).refine(isCanonicalCategoryList,"categories must be unique and in canonical order")}).strict();var CanonicalInstantSchema=z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u).refine(value=>{const instant=Date.parse(value);return Number.isFinite(instant)&&new Date(instant).toISOString()===value},"must be a canonical UTC instant");var RoutineRefSchema=z.object({routineId:z.string().min(1),definitionVersion:z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),notAfter:CanonicalInstantSchema}).strict();function sealedOfferRule(payload,ctx){const{instruction,sealing,sealed,routineRef}=payload;if(!sealing.categories.includes("task-input")){if(routineRef!==void 0)ctx.addIssue({code:"custom",path:["routineRef"],message:"a routine template is sealed task input, so routineRef needs a task that seals task-input"});if(sealed!==void 0)ctx.addIssue({code:"custom",path:["sealed"],message:"a task that does not seal task-input carries no sealed member"});if(instruction===void 0)ctx.addIssue({code:"custom",path:["instruction"],message:"a task that does not seal task-input carries a plaintext instruction"});return}if(sealed===void 0){ctx.addIssue({code:"custom",path:["sealed"],message:"a task that seals task-input carries the sealed instruction"});return}if(instruction!==void 0)ctx.addIssue({code:"custom",path:["instruction"],message:"a sealed instruction never travels in plaintext too"});if(sealed.scope.id!==sealing.scopeId||sealed.scope.epoch!==sealing.epoch){ctx.addIssue({code:"custom",path:["sealed","scope"],message:"the offer task-input must be sealed under the task scope at the task epoch"});}}var ProviderProfileRefSchema=z.string().min(1).max(64).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u,"provider profile refs must be lowercase portable identifiers");var ProviderProfileRevisionSchema=z.string().regex(/^(?:0|[1-9][0-9]{0,19})$/u,"provider profile revision must be canonical decimal");var ProviderProfileHashSchema=z.string().regex(/^sha256:[0-9a-f]{64}$/u,"provider profile hash must be lowercase sha256");var PROVIDER_MODEL_CAPABILITIES=["image-input"];var ProviderModelCapabilitySchema=z.enum(PROVIDER_MODEL_CAPABILITIES);var ProviderProfileBindingSchema=z.object({profileRef:ProviderProfileRefSchema,profileRevision:ProviderProfileRevisionSchema,profileHash:ProviderProfileHashSchema,modelId:z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u),requiredCapabilities:z.array(ProviderModelCapabilitySchema).max(8)}).strict().superRefine((binding,ctx)=>{if(new Set(binding.requiredCapabilities).size!==binding.requiredCapabilities.length){ctx.addIssue({code:"custom",path:["requiredCapabilities"],message:"duplicate provider capability"});}});var PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION="provider-secret-sealing-key.register";var ProviderProvisioningAvailablePayloadSchema=z.object({requestId:z.uuid()}).strict();var PROVIDER_PROVISIONING_OPERATIONS=["configure","update_model","replace_secret","delete"];var ProviderProvisioningOperationSchema=z.enum(PROVIDER_PROVISIONING_OPERATIONS);var PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM="9223372036854775807";var ProviderProvisioningOperationGenerationSchema=z.string().regex(/^[1-9][0-9]{0,18}$/u,"operationGeneration must be a canonical positive decimal string").refine(value=>value.length<PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM.length||value<=PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM,`operationGeneration must not exceed ${PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM}`);var ProviderProvisioningOperationDigestSchema=z.string().regex(/^sha256:[0-9a-f]{64}$/u,"operationDigest must be lowercase sha256");var PROVIDER_PROVISIONING_REJECTION_CODES=["request_invalid","request_conflict","request_expired","request_not_yet_valid","request_window_invalid","sealing_key_rotated","enrollment_mismatch","agent_not_placed","config_digest_mismatch","operation_generation_stale","profile_changed","profile_not_found","credential_scope_mismatch","provider_kind_unsupported","pi_model_invalid","capabilities_invalid","seal_open_failed","secret_invalid","local_commit_interrupted","secret_store_unavailable"];var ProviderProvisioningRejectionCodeSchema=z.enum(PROVIDER_PROVISIONING_REJECTION_CODES);var PROVIDER_PROVISIONING_HOST_TERMINAL_CODES=["request_expired","sealing_key_rotated"];var ProviderProvisioningProviderStatusSchema=z.object({profileRef:ProviderProfileRefSchema,providerKind:z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,"providerKind must be a lowercase portable identifier"),modelId:z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u),capabilities:z.array(ProviderModelCapabilitySchema).max(8),secretConfigured:z.boolean()}).strict().superRefine((status,ctx)=>{if(new Set(status.capabilities).size!==status.capabilities.length){ctx.addIssue({code:"custom",path:["capabilities"],message:"duplicate provider capability"});}});var PROVIDER_PROVISIONING_KEY_CHECK_RESULTS=["ok","credential_rejected","rate_limited","quota_or_billing","model_not_permitted","provider_error","unreachable","timeout","not_run"];var ProviderProvisioningKeyCheckResultSchema=z.enum(PROVIDER_PROVISIONING_KEY_CHECK_RESULTS);var ProviderProvisioningKeyCheckSchema=z.object({result:ProviderProvisioningKeyCheckResultSchema}).strict();var completionIdentity={requestId:z.uuid(),operation:ProviderProvisioningOperationSchema,operationGeneration:ProviderProvisioningOperationGenerationSchema,operationDigest:ProviderProvisioningOperationDigestSchema};var AppliedCompletionSchema=z.object({outcome:z.literal("applied"),...completionIdentity,providerStatus:ProviderProvisioningProviderStatusSchema.nullable(),binding:ProviderProfileBindingSchema.nullable(),keyCheck:ProviderProvisioningKeyCheckSchema}).strict();var RejectedCompletionSchema=z.object({outcome:z.literal("rejected"),...completionIdentity,code:ProviderProvisioningRejectionCodeSchema}).strict();var ProviderProvisioningCompletionSchema=z.discriminatedUnion("outcome",[AppliedCompletionSchema,RejectedCompletionSchema]).superRefine((completion,ctx)=>{if(completion.outcome!=="applied")return;const{operation,providerStatus,binding}=completion;if(operation==="delete"){if(completion.keyCheck.result!=="not_run"){ctx.addIssue({code:"custom",path:["keyCheck","result"],message:"an applied delete must report keyCheck not_run"});}if(providerStatus!==null){ctx.addIssue({code:"custom",path:["providerStatus"],message:"an applied delete reports no provider status"});}if(binding!==null){ctx.addIssue({code:"custom",path:["binding"],message:"an applied delete reports no binding"});}return}if(providerStatus===null){ctx.addIssue({code:"custom",path:["providerStatus"],message:`an applied ${operation} must report provider status`});}if(binding===null){ctx.addIssue({code:"custom",path:["binding"],message:`an applied ${operation} must report its exact binding`});}if(providerStatus===null||binding===null)return;if(providerStatus.profileRef!==binding.profileRef){ctx.addIssue({code:"custom",path:["binding","profileRef"],message:"binding profileRef must equal providerStatus profileRef"});}if(providerStatus.modelId!==binding.modelId){ctx.addIssue({code:"custom",path:["binding","modelId"],message:"binding modelId must equal providerStatus modelId"});}if((operation==="configure"||operation==="replace_secret")&&!providerStatus.secretConfigured){ctx.addIssue({code:"custom",path:["providerStatus","secretConfigured"],message:`an applied ${operation} must report a configured secret`});}});var PROVIDER_PROVISIONING_DISPOSITIONS=["recorded","idempotent","conflict","host_terminal"];var ProviderProvisioningDispositionSchema=z.enum(PROVIDER_PROVISIONING_DISPOSITIONS);var ProviderProvisioningReadbackSchema=z.object({tenantId:z.string().min(1),deviceId:z.string().min(1),requestId:z.uuid(),disposition:ProviderProvisioningDispositionSchema,completion:ProviderProvisioningCompletionSchema,completedAt:z.iso.datetime({offset:true})}).strict().superRefine((readback,ctx)=>{if(readback.completion.requestId!==readback.requestId){ctx.addIssue({code:"custom",path:["completion","requestId"],message:"completion requestId must equal readback requestId"});}if(readback.disposition==="host_terminal"&&(readback.completion.outcome!=="rejected"||!PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.includes(readback.completion.code))){ctx.addIssue({code:"custom",path:["completion"],message:`a host_terminal readback must carry a rejected completion with one of: ${PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.join(", ")}`});}});function isSameJsonData(a,b){if(a===null||b===null)return a===b;const typeOfA=typeof a;if(typeOfA!==typeof b)return false;if(typeOfA!=="object"){return a===b}const aIsArray=Array.isArray(a);if(aIsArray!==Array.isArray(b))return false;if(aIsArray){const arrayA=a;const arrayB=b;if(arrayA.length!==arrayB.length)return false;for(let index=0;index<arrayA.length;index+=1){if(!isSameJsonData(arrayA[index],arrayB[index]))return false}return true}const objectA=a;const objectB=b;const keysA=Object.keys(objectA);const keysB=Object.keys(objectB);if(keysA.length===0){const prototypeA=Object.getPrototypeOf(objectA);if(prototypeA!==Object.prototype&&prototypeA!==null)return false}if(keysA.length!==keysB.length)return false;for(const key of keysA){if(!Object.prototype.hasOwnProperty.call(objectB,key))return false;if(!isSameJsonData(objectA[key],objectB[key]))return false}return true}function jsonDepthExceeds(value,limit){const stack=[{node:value,depth:0}];while(stack.length>0){const{node,depth}=stack.pop();if(node===null||typeof node!=="object")continue;const next=depth+1;if(next>limit)return true;const children=Array.isArray(node)?node:Object.values(node);for(const child of children)stack.push({node:child,depth:next});}return false}function canonicalizePlainJson(value,maxBytes,maxDepth){let json;try{json=JSON.stringify(value);}catch{return {ok:false,reason:"not-serializable"}}if(json===void 0)return {ok:false,reason:"not-serializable"};const bytes=new TextEncoder().encode(json).length;if(bytes>maxBytes)return {ok:false,reason:"over-cap",bytes};const canonical=JSON.parse(json);if(maxDepth!==void 0&&jsonDepthExceeds(canonical,maxDepth))return {ok:false,reason:"too-deep",bytes};if(!isSameJsonData(value,canonical))return {ok:false,reason:"not-plain-json"};return {ok:true,bytes,canonical}}var RESULT_SCHEMA_MAX_BYTES=16384;var RESULT_OUTCOME_MAX_BYTES=65536;var RESULT_SCHEMA_MAX_DEPTH=32;var RESULT_JSON_MAX_DEPTH=128;var RESULT_ISSUES_MAX_COUNT=20;var RESULT_ISSUES_MAX_BYTES=4096;var ISSUE_STRING_MAX_LENGTH=128;var RESULT_SCHEMA_KEYWORDS=Object.freeze(["type","properties","required","additionalProperties","items","enum","const","oneOf","minLength","maxLength","minItems","maxItems","minimum","maximum","description"]);var RESULT_SCHEMA_INSTANCE_TYPES=Object.freeze(["object","array","string","number","integer","boolean","null"]);var KEYWORDS=new Set(RESULT_SCHEMA_KEYWORDS);var INSTANCE_TYPES=new Set(RESULT_SCHEMA_INSTANCE_TYPES);var encoder2=new TextEncoder;function cut(value){return value.length<=ISSUE_STRING_MAX_LENGTH?value:`${value.slice(0,ISSUE_STRING_MAX_LENGTH-1)}\u2026`}var IssueSink=class{issues=[];truncated=false;bytes=2;add(pointer,keyword,message){const issue={pointer:cut(pointer),keyword:cut(keyword),message:cut(message)};const size2=encoder2.encode(JSON.stringify(issue)).length+(this.issues.length===0?0:1);if(this.issues.length>=RESULT_ISSUES_MAX_COUNT||this.bytes+size2>RESULT_ISSUES_MAX_BYTES){this.truncated=true;return}this.issues.push(issue);this.bytes+=size2;}get empty(){return this.issues.length===0&&!this.truncated}};function pointerTo(base,token){return `${base}/${String(token).replace(/~/g,"~0").replace(/\//g,"~1")}`}function isObject(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function isNonNegativeInteger(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>=0}var LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function hasLoneSurrogate(value){const stack=[value];while(stack.length>0){const node=stack.pop();if(typeof node==="string"){if(LONE_SURROGATE.test(node))return true}else if(Array.isArray(node)){for(const member of node)stack.push(member);}else if(node!==null&&typeof node==="object"){for(const[key,member]of Object.entries(node)){if(LONE_SURROGATE.test(key))return true;stack.push(member);}}}return false}function canonicalDocument(value,maxBytes){const check=canonicalizePlainJson(value,maxBytes,RESULT_JSON_MAX_DEPTH);if(check.ok&&hasLoneSurrogate(check.canonical))return {ok:false,reason:"not-plain-json"};return check}function documentFailure(check,what,maxBytes){const sink=new IssueSink;switch(check.reason){case "not-serializable":sink.add("",check.reason,`${what} is not JSON-serializable`);return {ok:false,reason:check.reason,issues:sink.issues,truncated:false};case "not-plain-json":sink.add("",check.reason,`${what} is not plain JSON data in well-formed Unicode`);return {ok:false,reason:check.reason,issues:sink.issues,truncated:false};case "over-cap":sink.add("",check.reason,`${what} is ${check.bytes} bytes as canonical JSON (UTF-8); the cap is ${maxBytes}`);return {ok:false,reason:check.reason,bytes:check.bytes,issues:sink.issues,truncated:false};case "too-deep":sink.add("",check.reason,`${what} nests JSON containers deeper than ${RESULT_JSON_MAX_DEPTH}`);return {ok:false,reason:check.reason,bytes:check.bytes,issues:sink.issues,truncated:false}}}function checkSubschema(node,pointer,depth,sink,requireObjectRoot=true){if(!isObject(node)){sink.add(pointer,"schema","a subschema must be a JSON object");return}if(depth>RESULT_SCHEMA_MAX_DEPTH){sink.add(pointer,"depth",`subschemas nest deeper than ${RESULT_SCHEMA_MAX_DEPTH} levels`);return}for(const key of Object.keys(node)){if(!KEYWORDS.has(key))sink.add(pointerTo(pointer,key),key,"keyword is outside the result schema subset");}if(requireObjectRoot&&depth===0&&node.type!=="object"){sink.add(pointerTo(pointer,"type"),"type","the root schema must declare type: 'object'");}if(Object.hasOwn(node,"type")){const type=node.type;const valid=typeof type==="string"?INSTANCE_TYPES.has(type):Array.isArray(type)&&type.length>0&&type.every(member=>typeof member==="string"&&INSTANCE_TYPES.has(member))&&new Set(type).size===type.length;if(!valid)sink.add(pointerTo(pointer,"type"),"type","must be a JSON type name or a non-empty array of unique type names");}if(Object.hasOwn(node,"properties")){const properties=node.properties;const at=pointerTo(pointer,"properties");if(!isObject(properties))sink.add(at,"properties","must be an object of subschemas");else for(const[name,subschema]of Object.entries(properties))checkSubschema(subschema,pointerTo(at,name),depth+1,sink);}if(Object.hasOwn(node,"required")){const required=node.required;if(!Array.isArray(required)||!required.every(name=>typeof name==="string")||new Set(required).size!==required.length){sink.add(pointerTo(pointer,"required"),"required","must be an array of unique property names");}}if(Object.hasOwn(node,"additionalProperties")&&node.additionalProperties!==false){sink.add(pointerTo(pointer,"additionalProperties"),"additionalProperties","only additionalProperties: false is allowed");}if(Object.hasOwn(node,"items")){if(!isObject(node.items))sink.add(pointerTo(pointer,"items"),"items","must be one subschema object");else checkSubschema(node.items,pointerTo(pointer,"items"),depth+1,sink);}if(Object.hasOwn(node,"enum")&&(!Array.isArray(node.enum)||node.enum.length===0)){sink.add(pointerTo(pointer,"enum"),"enum","must be a non-empty array");}if(Object.hasOwn(node,"oneOf")){const oneOf=node.oneOf;const at=pointerTo(pointer,"oneOf");if(!Array.isArray(oneOf)||oneOf.length===0)sink.add(at,"oneOf","must be a non-empty array of subschemas");else oneOf.forEach((subschema,index)=>checkSubschema(subschema,pointerTo(at,index),depth+1,sink));}for(const keyword of ["minLength","maxLength","minItems","maxItems"]){if(Object.hasOwn(node,keyword)&&!isNonNegativeInteger(node[keyword])){sink.add(pointerTo(pointer,keyword),keyword,"must be a non-negative integer");}}for(const keyword of ["minimum","maximum"]){if(Object.hasOwn(node,keyword)&&typeof node[keyword]!=="number"){sink.add(pointerTo(pointer,keyword),keyword,"must be a number");}}if(Object.hasOwn(node,"description")&&typeof node.description!=="string"){sink.add(pointerTo(pointer,"description"),"description","must be a string");}}function checkResultSchema(schema){const document=canonicalDocument(schema,RESULT_SCHEMA_MAX_BYTES);if(!document.ok)return documentFailure(document,"the result schema",RESULT_SCHEMA_MAX_BYTES);const sink=new IssueSink;checkSubschema(document.canonical,"",0,sink);if(!sink.empty)return {ok:false,reason:"not-subset",bytes:document.bytes,issues:sink.issues,truncated:sink.truncated};return {ok:true,bytes:document.bytes,canonical:document.canonical}}function withoutPrototypes(value){if(value===null||typeof value!=="object")return value;if(Array.isArray(value))return value.map(withoutPrototypes);const copy=Object.create(null);for(const[key,member]of Object.entries(value)){Object.defineProperty(copy,key,{value:withoutPrototypes(member),enumerable:true,writable:true,configurable:true});}return copy}function fragmentToPointer(location){return decodeURI(location.startsWith("#")?location.slice(1):location)}function validateResultOutcome(schema,outcome){const admitted=checkResultSchema(schema);if(!admitted.ok){return {ok:false,reason:"schema-not-admitted",bytes:admitted.bytes,issues:admitted.issues,truncated:admitted.truncated}}const document=canonicalDocument(outcome,RESULT_OUTCOME_MAX_BYTES);if(!document.ok)return documentFailure(document,"the outcome",RESULT_OUTCOME_MAX_BYTES);const validator=new Validator(withoutPrototypes(admitted.canonical),"2020-12",true);const result=validator.validate(withoutPrototypes(document.canonical));if(result.valid)return {ok:true,bytes:document.bytes,canonical:document.canonical};const sink=new IssueSink;for(const unit of result.errors)sink.add(fragmentToPointer(unit.instanceLocation),unit.keyword,unit.error);return {ok:false,reason:"schema-mismatch",bytes:document.bytes,issues:sink.issues,truncated:sink.truncated}}var MAX_BYTES_PER_CODE_POINT=6;var MAX_NUMBER_BYTES=25;var MAX_INTEGER_BYTES=24;var DECIMAL_LIMIT=1e21;var enc=new TextEncoder;var size=v=>enc.encode(JSON.stringify(v)).length;function typeBound(node,type){switch(type){case "null":return 4;case "boolean":return 5;case "integer":{const lo=typeof node.minimum==="number"?Math.ceil(node.minimum):void 0;const hi=typeof node.maximum==="number"?Math.floor(node.maximum):void 0;if(lo===void 0||hi===void 0||!(Math.abs(lo)<DECIMAL_LIMIT)||!(Math.abs(hi)<DECIMAL_LIMIT))return MAX_INTEGER_BYTES;return Math.min(MAX_INTEGER_BYTES,Math.max(String(lo).length,String(hi).length))}case "number":return MAX_NUMBER_BYTES;case "string":return typeof node.maxLength==="number"?2+MAX_BYTES_PER_CODE_POINT*node.maxLength:null;case "array":{if(node.maxItems===0)return 2;if(typeof node.maxItems!=="number"||node.items===void 0)return null;const item=outcomeBound(node.items);return item===null?null:2+node.maxItems*item+Math.max(0,node.maxItems-1)}case "object":{if(node.additionalProperties!==false)return null;const entries=Object.entries(node.properties??{});let total=2+Math.max(0,entries.length-1);for(const[name,sub]of entries){const b=outcomeBound(sub);if(b===null)return null;total+=size(name)+1+b;}return total}default:return null}}function outcomeBound(schema){const node=schema;const bounds=[];if(Object.hasOwn(node,"const"))bounds.push(size(node.const));if(Array.isArray(node.enum))bounds.push(Math.max(...node.enum.map(size)));if(Array.isArray(node.oneOf)){const branches=node.oneOf.map(outcomeBound);if(branches.every(b=>b!==null))bounds.push(Math.max(...branches));}if(node.type!==void 0){const types=Array.isArray(node.type)?node.type:[node.type];const each=types.map(t=>typeBound(node,t));if(each.every(b=>b!==null))bounds.push(Math.max(...each));}return bounds.length===0?null:Math.min(...bounds)}function resultOutcomeMaxBytes(schema){const pending=[schema];const seen=new Set;while(pending.length>0){const value=pending.pop();if(typeof value==="function")return null;if(value===null||typeof value!=="object"||seen.has(value))continue;seen.add(value);const prototype=Object.getPrototypeOf(value);if(prototype!==null&&prototype!==Object.prototype&&prototype!==Array.prototype)return null;for(const[name,descriptor]of Object.entries(Object.getOwnPropertyDescriptors(value))){if(name==="toJSON"&&(!Object.hasOwn(descriptor,"value")||typeof descriptor.value==="function"))return null;if(!descriptor.enumerable)continue;if(!Object.hasOwn(descriptor,"value"))return null;pending.push(descriptor.value);}}const document=canonicalDocument(schema,RESULT_SCHEMA_MAX_BYTES);if(!document.ok)return null;const sink=new IssueSink;checkSubschema(document.canonical,"",0,sink,false);if(!sink.empty)return null;return outcomeBound(document.canonical)}var TerminalProjectionContractSchema=z.string().min(1).max(128).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u,"terminal projection contracts must be opaque lowercase ids");var ResultDocumentSchemaSchema=z.custom().superRefine((value,ctx)=>{const check=checkResultSchema(value);if(check.ok)return;for(const issue of check.issues){ctx.addIssue({code:"custom",message:`result schema ${check.reason} at '${issue.pointer}' (${issue.keyword}): ${issue.message}`,params:{reason:check.reason,pointer:issue.pointer,keyword:issue.keyword}});}if(check.truncated){ctx.addIssue({code:"custom",message:"result schema issues truncated",params:{reason:check.reason,truncated:true}});}});var TerminalProjectionSelectionSchema=z.discriminatedUnion("mode",[z.object({mode:z.literal("none")}).strict(),z.object({mode:z.literal("result-document"),contract:TerminalProjectionContractSchema,schema:ResultDocumentSchemaSchema}).strict()]);var POLICY_REVISION=z.string().min(1).max(160).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u,"policyRevision must not contain control characters");var POSITIVE_LIMIT=z.number().int().positive().max(2147483647);var AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES=16*1024;var AGENT_MESSAGE_MAX_BYTES=256*1024;var AgentMessageContractSchema=z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u,"message contract must be an opaque portable identifier");var AgentMessageContentTypeSchema=z.enum(["text/plain","text/markdown"]);var AgentMessageDestinationBindingSchema=z.string().min(1).max(2048).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u,"destination binding must not contain control characters");var AgentMessageFreshnessCursorSchema=z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u,"freshness cursor must not contain control characters");var AgentMessageServerContextSchema=z.object({destinationBinding:AgentMessageDestinationBindingSchema,freshnessCursor:AgentMessageFreshnessCursorSchema.optional()}).strict();var AgentMessageEgressRequirementSchema=z.object({mode:z.literal("required"),contract:AgentMessageContractSchema,contentType:AgentMessageContentTypeSchema,maxBytes:z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES)}).strict();var AgentContentMimeTypeSchema=z.string().min(3).max(255).regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/iu,"MIME types must be explicit type/subtype values");var ContentReadPolicySchema=z.object({maxBytes:POSITIVE_LIMIT,allowedMimeTypes:z.array(AgentContentMimeTypeSchema).min(1).max(32)}).strict();var AgentEgressActivityPolicySchema=z.object({delivery:z.literal("latest-value"),maxCoalesceMs:POSITIVE_LIMIT,maxEventBytes:POSITIVE_LIMIT}).strict();var AgentReliableQuotaPolicySchema=z.object({maxPendingEventsPerAgent:POSITIVE_LIMIT,maxPendingBytesPerAgent:POSITIVE_LIMIT,maxPendingBytesPerTenant:POSITIVE_LIMIT}).strict();var AgentEgressPolicySchema=z.object({policyRevision:POLICY_REVISION,activity:AgentEgressActivityPolicySchema,reliable:AgentReliableQuotaPolicySchema,transfers:z.object({workspace:z.union([z.literal("disabled"),ContentReadPolicySchema]),transcript:z.union([z.literal("disabled"),ContentReadPolicySchema]),artifact:z.union([z.literal("disabled"),ContentReadPolicySchema])}).strict()}).strict();var AgentEgressLaneSchema=z.enum(["reliable","latest-value"]);var AgentEgressDropReasonSchema=z.enum(["policy_denied","capability_missing","quota_exceeded","backpressure","coalesced","disconnected","invalid_envelope","ack_mismatch"]);var AgentContentReadSurfaceSchema=z.enum(["workspace","transcript","artifact"]);var AgentContentActorKindSchema=z.enum(["user","agent","system"]);var AgentContentActorSchema=z.object({kind:AgentContentActorKindSchema,id:z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f]+$/u,"actor id must not contain control characters")}).strict();var AgentContentDecodeAsSchema=z.enum(["bytes","utf8"]);var AgentContentReadDecisionSchema=z.enum(["allowed","denied"]);var AgentContentReadDenialReasonSchema=z.enum(["invalid-request","policy-disabled","capability-missing","policy-revision-mismatch","absolute-target","non-relative-target","dot-segment","sensitive-name","root-not-allowlisted","root-invalid","path-escape","target-missing","symlink","not-regular-file","byte-limit","mime-not-allowlisted","text-not-allowlisted","text-decode-failed","identity-mismatch"]);var AgentEgressContentHashSchema=z.string().regex(/^sha256:[a-f0-9]{64}$/u,"contentHash must be a lowercase SHA-256 digest");var AgentEgressPolicyRevisionSchema=POLICY_REVISION;var InputPreparationContentHashSchema=AgentEgressContentHashSchema;var OPAQUE_ID=z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f]+$/u,"control identifiers must not contain control characters");var OPAQUE_TEXT=z.string().min(1).max(2048).regex(/^[^\u0000-\u001f\u007f]+$/u,"control text must not contain control characters");var InputPreparationPolicyRevisionSchema=OPAQUE_ID;var InputPreparationProfileIdSchema=OPAQUE_ID;var PreparedAgentMemoryModeSchema=z.enum(PREPARED_AGENT_MEMORY_MODES);var InputPreparationSourceSchema=z.object({revision:OPAQUE_ID,digest:OPAQUE_ID}).strict();var InputPreparationModelCostSchema=z.object({input:z.number().finite(),output:z.number().finite(),cacheRead:z.number().finite(),cacheWrite:z.number().finite()}).strict();var THINKING_EFFORT=z.string().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/u).nullable();var InputPreparationThinkingLevelMapSchema=z.object({off:THINKING_EFFORT,minimal:THINKING_EFFORT,low:THINKING_EFFORT,medium:THINKING_EFFORT,high:THINKING_EFFORT,xhigh:THINKING_EFFORT,max:THINKING_EFFORT}).strict();var InputPreparationModelCompatSchema=z.object({supportsStore:z.boolean().optional(),supportsDeveloperRole:z.boolean().optional(),supportsReasoningEffort:z.boolean().optional(),supportsUsageInStreaming:z.boolean().optional(),maxTokensField:z.enum(["max_completion_tokens","max_tokens"]).optional(),thinkingFormat:z.enum(["openai","openrouter","deepseek","together","baseten","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling"]).optional(),zaiToolStream:z.boolean().optional()}).strict();var InputPreparationModelSchema=z.object({id:OPAQUE_ID,name:OPAQUE_ID,api:z.literal("openai-completions"),provider:OPAQUE_ID,baseUrl:OPAQUE_TEXT,reasoning:z.boolean(),input:z.array(z.enum(["text","image"])).min(1).max(8),cost:InputPreparationModelCostSchema,contextWindow:z.number().int().positive(),maxTokens:z.number().int().positive(),thinkingLevelMap:InputPreparationThinkingLevelMapSchema.optional(),compat:InputPreparationModelCompatSchema.optional()}).strict();var InputPreparationOptionsSchema=z.object({cacheRetention:z.enum(["none","short","long"]),maxTokens:z.number().int().positive(),temperature:z.number().finite().optional(),toolChoice:z.enum(["auto","none"]).optional(),reasoningEffort:z.enum(["minimal","low","medium","high","xhigh","max"]).optional()}).strict();var InputPreparationSelectionSchema=z.object({model:InputPreparationModelSchema,options:InputPreparationOptionsSchema}).strict();var InputPreparationPromptSnapshotSchema=z.object({systemPrompt:z.string()}).strict();var InputPreparationUserMessageSchema=z.object({role:z.literal("user"),content:z.string(),timestamp:z.number().int()}).strict();var InputPreparationHostCanonicalAssistantMessageSchema=z.object({role:z.literal("assistant"),origin:z.literal("host_canonical"),content:z.string(),timestamp:z.number().int()}).strict();var InputPreparationMessageSchema=z.discriminatedUnion("role",[InputPreparationUserMessageSchema,InputPreparationHostCanonicalAssistantMessageSchema]);var InputPreparationContextDocumentSchema=z.object({prompt:InputPreparationPromptSnapshotSchema,messages:z.array(InputPreparationMessageSchema).max(4096)}).strict();var InputPreparationStateSchema=z.enum(["reserved","counting","prepared","cancelled","failed","counter_interrupted"]);var InputPreparationReadinessReasonSchema=z.enum(["not_prepared","counter_interrupted","cancelled","failed","artifact_expired","counter_authority_not_production","counter_coverage_incomplete","request_content_not_text","projection_unknown","residual_not_ruled","accounting_policy_missing","accounting_policy_inapplicable","runtime_contract_superseded"]);var InputPreparationRuntimeIdentitySchema=z.object({packageName:OPAQUE_ID,packageVersion:OPAQUE_ID,tarballIntegrity:z.string().regex(/^sha512-[A-Za-z0-9+/]+={0,2}$/u),provenanceDigest:z.string().regex(/^[0-9a-f]{64}$/u),closureDigest:z.string().regex(/^[0-9a-f]{64}$/u),upstreamCommit:OPAQUE_ID,envelopeFormat:OPAQUE_ID,requestFormat:OPAQUE_ID,compilerVersion:z.number().int().nonnegative()}).strict();var InputPreparationCounterTargetSchema=z.object({endpoint:OPAQUE_TEXT,modelId:OPAQUE_ID}).strict();var InputPreparationAccountingPolicyRefSchema=z.object({revision:OPAQUE_ID,ruledRuntime:OPAQUE_ID,ruledTarget:InputPreparationCounterTargetSchema,ruledResidualKeys:z.array(OPAQUE_ID).max(64)}).strict();var InputPreparationCounterProviderEvidenceSchema=z.object({projectionDigest:z.string().regex(/^[0-9a-f]{64}$/u,"a projection digest is lowercase sha-256 hex"),endpoint:OPAQUE_TEXT,modelId:OPAQUE_ID,asserted:z.object({httpStatus:z.number().int(),usageFields:z.record(OPAQUE_ID,z.number().finite()),responseDigest:OPAQUE_ID}).strict()}).strict();var InputPreparationCounterEvidenceSchema=z.object({method:OPAQUE_ID,methodVersion:OPAQUE_ID,authority:z.enum(["provider","test_fixture"]),value:z.number().int().nonnegative(),coverage:z.object({covered:z.boolean(),reason:z.string().max(512).optional()}).strict(),providerEvidence:InputPreparationCounterProviderEvidenceSchema,target:InputPreparationCounterTargetSchema,calledAt:z.iso.datetime({offset:true}),completedAt:z.iso.datetime({offset:true})}).strict();var InputPreparationResidualValueClassSchema=z.enum(["constant","boolean","bounded_integer","bounded_number","finite_number","closed_enum","nonempty_string","object_shape"]);var InputPreparationResidualKeySchema=z.object({key:OPAQUE_ID,valueClass:InputPreparationResidualValueClassSchema}).strict();var InputPreparationProjectionSchema=z.object({version:z.literal(3),kind:z.enum(["content_complete","unknown"]),digest:z.string().regex(/^[0-9a-f]{64}$/u,"a projection digest is lowercase sha-256 hex")}).strict();var InputPreparationArtifactSummarySchema=z.object({requestDigest:OPAQUE_ID,envelopeDigest:OPAQUE_ID,toolManifestDigest:OPAQUE_ID,requestBytes:z.number().int().nonnegative(),projectionBytes:z.number().int().nonnegative(),projection:InputPreparationProjectionSchema,residual:z.array(InputPreparationResidualKeySchema).max(64),observationDigest:OPAQUE_ID,toolBindingDigest:OPAQUE_ID,toolNames:z.array(OPAQUE_ID)}).strict();var InputPreparationBindingSchema=z.object({terminalProjection:TerminalProjectionSelectionSchema.optional(),agentMemory:PreparedAgentMemoryModeSchema,scopeId:OPAQUE_ID,deviceId:OPAQUE_ID,agentRef:OPAQUE_ID,profileId:OPAQUE_ID,profileRevision:OPAQUE_ID,source:InputPreparationSourceSchema,target:InputPreparationCounterTargetSchema,policyRevision:OPAQUE_ID,runtime:InputPreparationRuntimeIdentitySchema,requestDigest:OPAQUE_ID,accountingPolicyRef:InputPreparationAccountingPolicyRefSchema.optional()}).strict();var InputPreparationReceiptSummarySchema=z.object({reference:OPAQUE_ID,state:InputPreparationStateSchema,binding:InputPreparationBindingSchema,artifact:InputPreparationArtifactSummarySchema.optional(),counter:InputPreparationCounterEvidenceSchema.optional(),ready:z.boolean(),readinessReasons:z.array(InputPreparationReadinessReasonSchema).max(16),detail:OPAQUE_ID.optional(),artifactExpiresAt:z.iso.datetime({offset:true})}).strict().superRefine((value,ctx)=>{if(value.ready!==(value.readinessReasons.length===0)){ctx.addIssue({code:"custom",path:["ready"],message:"ready must be true exactly when readinessReasons is empty"});}});var InputPreparationReferenceSchema=OPAQUE_ID;var InputPreparationOfferBindingSchema=z.object({reference:InputPreparationReferenceSchema,requestDigest:OPAQUE_ID,artifactDigest:OPAQUE_ID.optional()}).strict();var InputPreparationRejectionReasonSchema=z.enum(["input_preparation_unconfigured","bad_request","authority_unavailable","scope_denied","policy_revision_mismatch","runtime_identity_unavailable","unsupported_input","limit_exceeded","request_conflict","not_found","counter_unavailable","counter_interrupted","durable_write_failed","cancelled","context_unresolvable","context_hash_mismatch","toolsets_unobservable","deadline_elapsed","observation_drift","rpc_frame_too_large","input_preparation_record_log_unsupported"]);var AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH=512;var AgentEventSpillSchema=z.object({field:z.enum(["input","output"]),totalBytes:z.number().int().nonnegative(),omittedBytes:z.number().int().nonnegative(),contentType:z.literal("application/json"),blob:BlobRefSchema.optional(),unstoredReason:z.string().min(1).max(AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH).optional()}).strict().refine(spill=>spill.blob===void 0!==(spill.unstoredReason===void 0),"spill must carry exactly one of blob (the omitted bytes are readable) or unstoredReason (they are not)");var AgentEventSchema=z.discriminatedUnion("type",[z.object({type:z.literal("progress"),text:z.string()}),z.object({type:z.literal("tool_use"),tool:z.string(),mcp:z.object({server:z.string().min(1),tool:z.string().min(1)}).strict().optional(),input:z.unknown().optional(),toolCallId:z.string().regex(/\S/,"toolCallId must contain a non-whitespace character").optional(),spill:AgentEventSpillSchema.optional()}),z.object({type:z.literal("tool_result"),tool:z.string(),mcp:z.object({server:z.string().min(1),tool:z.string().min(1)}).strict().optional(),output:z.unknown().optional(),toolCallId:z.string().regex(/\S/,"toolCallId must contain a non-whitespace character").optional(),isError:z.boolean().optional(),spill:AgentEventSpillSchema.optional()}),z.object({type:z.literal("artifact"),name:z.string(),contentType:z.string()}),z.object({type:z.literal("turn_end")}),z.object({type:z.literal("error"),message:z.string()}),z.object({type:z.literal("usage"),inputTokens:z.number().int().nonnegative().optional(),cachedInputTokens:z.number().int().nonnegative().optional(),outputTokens:z.number().int().nonnegative().optional(),reasoningTokens:z.number().int().nonnegative().optional(),totalTokens:z.number().int().nonnegative().optional(),contextTokens:z.number().int().nonnegative().optional(),contextWindow:z.number().int().positive().optional(),contextSource:z.enum(["provider","estimate"]).optional(),model:z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional()})]);var KNOWN_AGENT_EVENT_TYPES=z.toJSONSchema(AgentEventSchema).oneOf.map(branch=>branch.properties.type.const);var UnknownAgentEventSchema=z.object({type:z.string()}).passthrough().refine(event=>!KNOWN_AGENT_EVENT_TYPES.includes(event.type),"type refers to a known AgentEvent variant; malformed known variants must fail through AgentEventSchema, not fall back to unknown-tolerance");var AgentEventOrUnknownSchema=z.union([AgentEventSchema,UnknownAgentEventSchema]);function isKnownAgentEvent(event){return KNOWN_AGENT_EVENT_TYPES.includes(event.type)}function partitionAgentEvents(events){const known=[];const unknown=[];for(const event of events){if(isKnownAgentEvent(event)){known.push(event);}else {unknown.push(event);}}return {known,unknown}}var AGENT_HOME_PROJECTION_MAX_BYTES=64*1024;var AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM="9223372036854775807";var AgentHomeProjectionProfileRevisionSchema=z.string().regex(/^[1-9][0-9]{0,18}$/u,"profileRevision must be a canonical positive decimal string").refine(value=>value.length<AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM.length||value<=AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM,`profileRevision must not exceed PostgreSQL BIGINT maximum ${AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM}`);var AgentHomeProjectionHashSchema=AgentEgressContentHashSchema;var AgentHomeProjectionOutcomeSchema=z.enum(["applied","idempotent","stale","conflict"]);var AgentHomeProjectionValueSchema=z.json().refine(value=>new TextEncoder().encode(JSON.stringify(value)).byteLength<=AGENT_HOME_PROJECTION_MAX_BYTES,`projection must not exceed ${AGENT_HOME_PROJECTION_MAX_BYTES} UTF-8 JSON bytes`);var E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES=64;var E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES=65536;var E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES=256;var E2EE_SCOPE_KEY_PACKAGE_PUT_MAX=256;var E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX=16;var E2EE_SCOPE_ID_MAX_LENGTH=512;var E2EE_MEMBER_KEY_REGISTER_OPERATION="e2ee-member-key.register";var E2EE_MEMBER_CHAIN_APPEND_OPERATION="e2ee-member-chain.append";var E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION="e2ee-scope-key-package.put";function base64UrlBytes(bytes){const length=Math.ceil(bytes*4/3);const last=["[A-Za-z0-9_-]","[AQgw]","[AEIMQUYcgkosw048]"][bytes%3];return z.string().regex(new RegExp(`^[A-Za-z0-9_-]{${length-1}}${last}$`,"u"))}var MemberIdSchema=z.string().regex(/^[A-Za-z0-9_-]{43}$/u);var PositiveSafeIntegerSchema=z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var SignatureSchema=base64UrlBytes(64);var P256PublicJwkSchema=z.strictObject({kty:z.literal("EC"),crv:z.literal("P-256"),x:base64UrlBytes(32),y:base64UrlBytes(32)});var E2eeMemberKeyBundleSchema=z.strictObject({v:z.literal(1),memberId:MemberIdSchema,signingPublicJwk:P256PublicJwkSchema,kemPublicJwk:P256PublicJwkSchema,kemEpoch:PositiveSafeIntegerSchema,kemSig:SignatureSchema,deviceId:z.string().min(1).optional()});var E2EE_MEMBER_CHAIN_OPS=["add","remove","rotate","scope-policy","shred"];var E2eeScopeShredSubjectSchema=z.strictObject({scopeId:z.string().min(1)});var E2eeMemberRotateSubjectSchema=z.strictObject({memberId:MemberIdSchema,kemPublicJwk:P256PublicJwkSchema,kemEpoch:PositiveSafeIntegerSchema,kemSig:SignatureSchema});var E2eeMemberChainEntrySchema=z.strictObject({v:z.literal(1),tenantId:z.string().min(1),seq:PositiveSafeIntegerSchema,prev:z.union([z.null(),z.string().regex(CONTENT_HASH_RE)]),op:z.enum(E2EE_MEMBER_CHAIN_OPS),subject:z.custom(value=>value!==null&&typeof value==="object"&&!Array.isArray(value)),signer:MemberIdSchema,sig:SignatureSchema}).refine(entry=>entry.seq===1===(entry.prev===null),{path:["prev"],message:"the first entry, and only the first, has no prev"}).refine(entry=>entry.op!=="shred"||E2eeScopeShredSubjectSchema.safeParse(entry.subject).success,{path:["subject"],message:"a shred subject is exactly { scopeId }"}).refine(entry=>entry.op!=="rotate"||E2eeMemberRotateSubjectSchema.safeParse(entry.subject).success,{path:["subject"],message:"a rotate subject is exactly { memberId, kemPublicJwk, kemEpoch, kemSig }"});var E2eeScopeKeyPackageV1Schema=z.strictObject({v:z.literal(1),tenantId:z.string().min(1),scopeId:z.string().min(1),epoch:PositiveSafeIntegerSchema,keyId:z.string().regex(/^[A-Za-z0-9_-]{22}$/u),recipient:MemberIdSchema,sender:MemberIdSchema,enc:base64UrlBytes(65),ciphertext:base64UrlBytes(48),sig:SignatureSchema});var E2eeScopeKeyPackageV2Schema=z.strictObject({...E2eeScopeKeyPackageV1Schema.shape,v:z.literal(2),recipientKemEpoch:PositiveSafeIntegerSchema});var E2eeScopeKeyPackageSchema=z.union([E2eeScopeKeyPackageV1Schema,E2eeScopeKeyPackageV2Schema]);var E2eePairingMacSchema=base64UrlBytes(32);var E2eeMemberKeyRegisterRequestSchema=z.strictObject({member:E2eeMemberKeyBundleSchema.refine(member=>member.deviceId!==void 0,{message:"a device member names its deviceId"}),mac:E2eePairingMacSchema});var E2eeClientPairingMacSchema=z.strictObject({mac:E2eePairingMacSchema,member:E2eeMemberKeyBundleSchema.refine(member=>member.deviceId===void 0,{message:"a client member has no deviceId"}),chainHead:z.strictObject({seq:PositiveSafeIntegerSchema,hash:z.string().regex(CONTENT_HASH_RE)})});var E2eeKeyPackageAvailablePayloadSchema=z.strictObject({scopeId:z.string().min(1).max(E2EE_SCOPE_ID_MAX_LENGTH),epoch:PositiveSafeIntegerSchema});var OPEN_VOCABULARY_TOKEN=/^[a-z][a-z0-9_-]{0,63}$/;function openVocabularyToken(){return z.string().regex(OPEN_VOCABULARY_TOKEN)}function unrecognizedToken(known){return openVocabularyToken().refine(value=>!known.includes(value),{message:"a recognized value is not reported as unrecognized"})}var MAX_INLINE_BYTES=64*1024;function isWithinInlineByteLimit(value){return new TextEncoder().encode(value).length<=MAX_INLINE_BYTES}var RuntimeIdSchema=z.enum(RUNTIME_IDS);var RuntimeUnavailableCauseSchema=z.union([z.enum(RUNTIME_UNAVAILABLE_CAUSES),unrecognizedToken(RUNTIME_UNAVAILABLE_CAUSES)]);function readRuntimeUnavailableCause(cause){return RUNTIME_UNAVAILABLE_CAUSES.includes(cause)?{cause}:{cause:"unknown",reportedCause:cause}}var ProtocolVersionNumberSchema=z.number().int().nonnegative().max(2147483647);var RuntimeCapabilitiesSchema=z.object({steer:z.boolean().optional(),resume:z.boolean().optional(),approvalInteractive:z.boolean().optional(),mcpToolsets:z.boolean().optional(),messageDraft:z.boolean().optional(),toolAuthorizationAuto:z.boolean().optional(),durablePi:z.boolean().optional(),preparedLane:z.boolean().optional(),isolation:z.object({userContext:z.boolean().optional(),userMcpServers:z.boolean().optional(),sessionPersistence:z.boolean().optional()}).optional()});var RuntimeVersionPolicyProjectionSchema=z.object({state:z.enum(["allow","warn","block"]),qualifiedVersion:z.string().min(1).max(256).optional()});var RuntimeInfoSchema=z.object({id:RuntimeIdSchema,version:z.string().optional(),authPresent:z.boolean().optional(),capabilities:RuntimeCapabilitiesSchema.optional(),versionPolicy:RuntimeVersionPolicyProjectionSchema.optional()});var HarnessIdSchema=z.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/).refine(value=>!RUNTIME_IDS.includes(value),"built-in runtime must use runtime");var HarnessInfoSchema=z.object({id:HarnessIdSchema,version:z.string().min(1).max(128).optional(),capabilities:RuntimeCapabilitiesSchema,versionPolicy:RuntimeVersionPolicyProjectionSchema.optional()});var HarnessInventorySchema=z.array(HarnessInfoSchema).max(64).refine(values=>new Set(values.map(value=>value.id)).size===values.length,"duplicate harness identity");var RuntimeUnavailableEntrySchema=z.object({id:z.union([RuntimeIdSchema,HarnessIdSchema]),cause:RuntimeUnavailableCauseSchema,retryable:z.boolean()});var RuntimeUnavailableListSchema=z.array(RuntimeUnavailableEntrySchema).max(16).refine(values=>new Set(values.map(value=>value.id)).size===values.length,"duplicate runtime-unavailable identity");var CONFIGURED_TOOLSETS_MAX_ITEMS=64;var ToolsetIdSchema=z.string().min(1).max(128).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u,"toolset ids must be lowercase logical identifiers");var AGENT_REF_MAX_BYTES=160;var AGENT_REF_VALUE=z.string().min(1).max(AGENT_REF_MAX_BYTES).refine(value=>new TextEncoder().encode(value).byteLength<=AGENT_REF_MAX_BYTES,{message:`AgentRef values must not exceed ${AGENT_REF_MAX_BYTES} UTF-8 bytes`}).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u,"AgentRef values must not contain control characters");var WINDOWS_RESERVED_AGENT_SEGMENT=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;var AgentRefSchema=z.object({agentId:AGENT_REF_VALUE.regex(/^[^\\/:<>"|?*]+$/u,"agentId must be one portable pathname segment").refine(value=>value!=="."&&value!=="..","agentId must not be a dot segment").refine(value=>!/[. ]$/u.test(value)&&!WINDOWS_RESERVED_AGENT_SEGMENT.test(value),"agentId must be a portable Windows-safe pathname segment"),profileRevision:AGENT_REF_VALUE}).strict();var AgentHomeProjectionAgentRefSchema=AgentRefSchema.extend({profileRevision:AgentHomeProjectionProfileRevisionSchema}).strict();function rejectDuplicateToolsets(ids,ctx,label){const seen=new Set;for(const[index,id]of ids.entries()){if(seen.has(id)){ctx.addIssue({code:"custom",path:[index],message:`duplicate ${label} toolset: ${id}`});}seen.add(id);}}var ConfiguredToolsetsSchema=z.array(ToolsetIdSchema).max(CONFIGURED_TOOLSETS_MAX_ITEMS).superRefine((ids,ctx)=>rejectDuplicateToolsets(ids,ctx,"configured"));var ConnHelloPayloadSchema=z.object({protocolVersions:z.array(ProtocolVersionNumberSchema).max(16),capabilities:z.array(z.string()),deviceId:z.string(),productId:z.string(),clientVersion:z.string().min(1).max(128).optional(),runtimes:z.array(RuntimeInfoSchema).optional(),harnesses:HarnessInventorySchema.optional(),runtimeUnavailable:RuntimeUnavailableListSchema.optional(),configuredToolsets:ConfiguredToolsetsSchema.optional(),cursor:z.number().int().optional()});var InstructionBlobRefSchema=z.object({blobRef:BlobRefSchema}).strict();var DispatchTargetIdSchema=z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u,"dispatch target ids must not contain control line breaks");var DispatchSelectionSchema=z.discriminatedUnion("lane",[z.object({lane:z.literal("subscription"),runtimeId:z.enum(["claude","codex"]),providerId:z.null(),modelId:DispatchTargetIdSchema}).strict(),z.object({lane:z.literal("byok"),runtimeId:z.literal("pi"),providerId:DispatchTargetIdSchema,modelId:DispatchTargetIdSchema}).strict(),z.object({lane:z.literal("byok-profile"),runtimeId:z.literal("pi"),providerProfile:ProviderProfileBindingSchema}).strict()]);var NO_SEALED_MEMBER={sealed:z.never().optional(),sealing:z.never().optional()};var RequiredToolsetsSchema=z.array(ToolsetIdSchema).min(1).max(16).superRefine((ids,ctx)=>rejectDuplicateToolsets(ids,ctx,"required"));var AgentHomeAccessSchema=z.literal("memory-reader");var AgentMemorySelectionSchema=z.enum([...PreparedAgentMemoryModeSchema.options,"read-if-admitted","read-write-if-admitted"]);var SessionSelectionSchema=z.discriminatedUnion("mode",[z.object({mode:z.literal("resume"),sessionRef:z.string().min(1).max(512)}).strict(),z.object({mode:z.literal("fresh")}).strict()]);var OFFER_FIELDS={agentRef:AgentRefSchema,session:SessionSelectionSchema,preparation:InputPreparationOfferBindingSchema.optional(),agentMemory:AgentMemorySelectionSchema.optional(),homeAccess:AgentHomeAccessSchema.optional(),requiredToolsets:RequiredToolsetsSchema.optional(),runtime:RuntimeIdSchema.optional(),harnessId:HarnessIdSchema.optional(),dispatchSelection:DispatchSelectionSchema.optional(),terminalProjection:TerminalProjectionSelectionSchema.optional(),limits:z.object({maxDurationMs:z.number().int().positive().optional(),maxTokens:z.number().int().positive().optional()}).strict().optional(),egressPolicy:AgentEgressPolicySchema.optional(),messageEgress:AgentMessageEgressRequirementSchema.optional()};function offerRule(payload,ctx,plaintext){const{instruction,session,preparation,agentMemory,egressPolicy,messageEgress,routineRef}=payload;if(preparation!==void 0){if(instruction!==void 0)ctx.addIssue({code:"custom",path:["instruction"],message:"a prepared offer carries no instruction"});if(session.mode!=="fresh")ctx.addIssue({code:"custom",path:["session"],message:"a prepared offer never resumes"});if(!PreparedAgentMemoryModeSchema.safeParse(agentMemory).success){ctx.addIssue({code:"custom",path:["agentMemory"],message:"a prepared offer selects a prepared agentMemory mode"});}}else if(plaintext&&instruction===void 0){ctx.addIssue({code:"custom",path:["instruction"],message:"an offer that is not prepared carries an instruction"});}if((preparation!==void 0||session.mode==="fresh")&&egressPolicy===void 0){ctx.addIssue({code:"custom",path:["egressPolicy"],message:"a fresh or prepared offer carries an egressPolicy"});}if(messageEgress!==void 0&&egressPolicy===void 0){ctx.addIssue({code:"custom",path:["messageEgress"],message:"messageEgress needs an egressPolicy"});}if(routineRef!==void 0&&session.mode!=="fresh"){ctx.addIssue({code:"custom",path:["routineRef"],message:"a routine occurrence is an execution, so it needs a fresh session"});}}var TaskOfferPlainFields=z.object({...NO_SEALED_MEMBER,routineRef:z.never().optional(),instruction:z.union([z.string(),InstructionBlobRefSchema]).optional(),...OFFER_FIELDS}).strict();var TaskOfferSealedFields=z.object({instruction:z.union([z.string(),InstructionBlobRefSchema]).optional(),sealing:TaskSealingSchema,sealed:SealedTaskInputSchema.optional(),routineRef:RoutineRefSchema.optional(),...OFFER_FIELDS,preparation:z.never().optional()}).strict();var TaskOfferPlainPayloadSchema=TaskOfferPlainFields.superRefine((payload,ctx)=>offerRule(payload,ctx,true));var TaskOfferSealedPayloadSchema=TaskOfferSealedFields.superRefine((payload,ctx)=>{offerRule(payload,ctx,false);sealedOfferRule(payload,ctx);});var TaskOfferPayloadSchema=z.union([TaskOfferPlainPayloadSchema,TaskOfferSealedPayloadSchema]);var EGRESS_SAFE_VALUE=z.json().refine(value=>new TextEncoder().encode(JSON.stringify(value)).byteLength<=256*1024,"egress payload exceeds 256KiB");var EGRESS_SESSION_REF=z.string().min(1).max(512);var AgentEgressReliablePayloadSchema=z.object({agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,policyRevision:AgentEgressPolicyRevisionSchema,eventId:z.uuid(),cursor:z.number().int().positive(),payload:EGRESS_SAFE_VALUE,contentHash:AgentEgressContentHashSchema,byteCount:z.number().int().nonnegative().max(256*1024)}).strict();var AgentEgressAckPayloadSchema=z.object({agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,policyRevision:AgentEgressPolicyRevisionSchema,eventId:z.uuid(),cursor:z.number().int().positive(),receiptId:z.uuid()}).strict();var AGENT_MESSAGE_BODY=z.string().min(1).refine(value=>new TextEncoder().encode(value).byteLength<=AGENT_MESSAGE_MAX_BYTES,`Agent message body exceeds ${AGENT_MESSAGE_MAX_BYTES} bytes`);var AgentMessageDraftPayloadSchema=z.object({agentRef:AgentRefSchema,revision:z.number().int().min(1),offset:z.number().int().nonnegative(),text:z.string().refine(value=>new TextEncoder().encode(value).byteLength<=AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,`Agent message draft frame exceeds ${AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES} bytes`),overflow:z.literal(true).optional()}).strict();var AgentMessagePublishPayloadSchema=z.object({agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,contract:AgentMessageContractSchema,messageId:z.uuid(),cursor:z.number().int().positive(),contentType:AgentMessageContentTypeSchema,body:AGENT_MESSAGE_BODY,contentHash:AgentEgressContentHashSchema,byteCount:z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES)}).strict().superRefine((value,context)=>{const actual=new TextEncoder().encode(value.body).byteLength;if(actual!==value.byteCount){context.addIssue({code:"custom",path:["byteCount"],message:"byteCount must equal UTF-8 body bytes"});}});var AgentMessageDispositionPayloadSchema=z.object({agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,contract:AgentMessageContractSchema,messageId:z.uuid(),cursor:z.number().int().positive(),contentHash:AgentEgressContentHashSchema,outcome:z.enum(["accepted","held","refused"]),receiptId:z.uuid(),reasonCode:z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u).optional()}).strict();var AGENT_CONTENT_TARGET=z.string().min(1).max(1024).regex(/^[^\u0000-\u001f\u007f]+$/u,"content target must not contain control characters").refine(value=>!value.startsWith("/")&&!value.includes("\\")&&value.split("/").every(segment=>segment.length>0&&segment!=="."&&segment!==".."),"content target must be a portable relative path without dot segments");var AGENT_CONTENT_CWD=z.string().min(1).max(4096).regex(/^[^\u0000-\u001f\u007f]+$/u,"cwd must not contain control characters").regex(/^(?:\/|[A-Za-z]:[\\/])/u,"cwd must be absolute");var AgentContentReadPayloadSchema=z.object({requestId:z.uuid(),surface:AgentContentReadSurfaceSchema,actor:AgentContentActorSchema,agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,runtime:RuntimeIdSchema,cwd:AGENT_CONTENT_CWD,policyRevision:AgentEgressPolicyRevisionSchema,target:AGENT_CONTENT_TARGET,mimeType:AgentContentMimeTypeSchema,decodeAs:AgentContentDecodeAsSchema,policy:ContentReadPolicySchema}).strict();var AgentContentReceiptPayloadSchema=z.discriminatedUnion("decision",[z.object({requestId:z.uuid(),eventId:z.uuid(),cursor:z.number().int().positive(),surface:AgentContentReadSurfaceSchema,actor:AgentContentActorSchema,agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,runtime:RuntimeIdSchema,cwd:AGENT_CONTENT_CWD,policyRevision:AgentEgressPolicyRevisionSchema,target:AGENT_CONTENT_TARGET,mimeType:AgentContentMimeTypeSchema,decodeAs:AgentContentDecodeAsSchema,decision:z.literal("allowed"),byteCount:z.number().int().nonnegative(),contentHash:AgentEgressContentHashSchema,blobRef:BlobRefSchema}).strict(),z.object({requestId:z.uuid(),eventId:z.uuid(),cursor:z.number().int().positive(),surface:AgentContentReadSurfaceSchema,actor:AgentContentActorSchema,agentRef:AgentRefSchema,sessionRef:EGRESS_SESSION_REF,runtime:RuntimeIdSchema,cwd:AGENT_CONTENT_CWD,policyRevision:AgentEgressPolicyRevisionSchema,target:AGENT_CONTENT_TARGET,mimeType:AgentContentMimeTypeSchema,decodeAs:AgentContentDecodeAsSchema,decision:z.literal("denied"),byteCount:z.literal(0),reason:z.union([AgentContentReadDenialReasonSchema,unrecognizedToken(AgentContentReadDenialReasonSchema.options)])}).strict()]).superRefine((value,ctx)=>{if(value.decision!=="allowed")return;if(value.blobRef.size!==value.byteCount){ctx.addIssue({code:"custom",path:["blobRef","size"],message:"blobRef size must equal byteCount"});}if(value.blobRef.contentHash!==value.contentHash){ctx.addIssue({code:"custom",path:["blobRef","contentHash"],message:"blobRef contentHash must equal contentHash"});}if(value.blobRef.contentType!==value.mimeType){ctx.addIssue({code:"custom",path:["blobRef","contentType"],message:"blobRef contentType must equal mimeType"});}});var AgentHomeProjectionPayloadSchema=z.object({requestId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema,projectionHash:AgentHomeProjectionHashSchema,projection:AgentHomeProjectionValueSchema}).strict();var AgentMemoryIntentAvailablePayloadSchema=z.object({intentId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema}).strict();var InputPreparationInlineContextSchema=z.object({inline:z.string().refine(isWithinInlineByteLimit,`inline context must not exceed ${MAX_INLINE_BYTES} UTF-8 bytes`)}).strict();var InputPreparationBlobContextSchema=z.object({blobRef:BlobRefSchema,contentHash:InputPreparationContentHashSchema}).strict().superRefine((value,ctx)=>{if(value.blobRef.contentHash!==value.contentHash){ctx.addIssue({code:"custom",path:["blobRef","contentHash"],message:"blobRef contentHash must equal contentHash"});}});var AgentInputPreparationPayloadSchema=z.object({agentMemory:PreparedAgentMemoryModeSchema,requestId:z.uuid(),agentRef:AgentRefSchema,profileId:InputPreparationProfileIdSchema,policyRevision:InputPreparationPolicyRevisionSchema,source:InputPreparationSourceSchema,selection:InputPreparationSelectionSchema,deadlineAt:z.iso.datetime({offset:true}),context:z.union([InputPreparationInlineContextSchema,InputPreparationBlobContextSchema]),requiredToolsets:z.array(ToolsetIdSchema).max(16).superRefine((ids,ctx)=>rejectDuplicateToolsets(ids,ctx,"required")),accountingPolicyRef:InputPreparationAccountingPolicyRefSchema.optional()}).strict();var TaskApprovePayloadSchema=z.object({approvalId:z.string().min(1)});var TaskRejectPayloadSchema=z.object({reason:z.string().optional(),approvalId:z.string().min(1)});var TaskCancelPayloadSchema=z.object({reason:z.string().optional()});var TaskSteerPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,text:z.string()});var OFFER_ADMISSION_MAX_DURATION_MS=6048e5;var OfferAdmissionDurationSchema=z.number().int().nonnegative().max(OFFER_ADMISSION_MAX_DURATION_MS);var OfferAdmissionTimingsSchema=z.object({totalMs:OfferAdmissionDurationSchema,agentHomeWaitMs:OfferAdmissionDurationSchema.optional(),messageHelperPreflightMs:OfferAdmissionDurationSchema.optional(),resultHelperPreflightMs:OfferAdmissionDurationSchema.optional(),toolsetProbeMs:OfferAdmissionDurationSchema.optional(),runtimeLaunchMs:OfferAdmissionDurationSchema.optional()}).strict();var TaskClaimPayloadSchema=z.object({deviceId:z.string(),agentId:z.string().optional(),agentRef:AgentRefSchema.optional(),runtime:RuntimeIdSchema.optional(),harnessId:HarnessIdSchema.optional(),capabilities:RuntimeCapabilitiesSchema.optional(),admission:OfferAdmissionTimingsSchema.optional()});var TaskStartedPayloadSchema=z.object({});var HOME_DECLINE_CODES=["agent_home_writer_busy","agent_home_reader_busy"];var DECLINE_CODES=[...HOME_DECLINE_CODES,...SEALED_DECLINE_CODES];var RuntimeUnavailableSchema=z.object({cause:RuntimeUnavailableCauseSchema,code:openVocabularyToken().optional()}).refine(value=>value.code===void 0||value.cause==="environment_unavailable",{message:"only environment_unavailable carries an environment code"});var DeclineFields=z.object({...NO_SEALED_MEMBER,reason:z.string(),retryable:z.boolean().optional(),agentRef:AgentRefSchema.optional(),code:z.union([z.enum(DECLINE_CODES),unrecognizedToken(DECLINE_CODES)]).optional(),runtimeUnavailable:RuntimeUnavailableSchema.optional(),admission:OfferAdmissionTimingsSchema.optional()});function readDeclineCode(code){return DECLINE_CODES.includes(code)?{code}:{code:"unknown",reportedCode:code}}var TaskDeclinePlainPayloadSchema=DeclineFields.refine(p=>!SEALED_DECLINE_CODES.includes(p.code)||p.reason===p.code&&p.retryable!==true,{message:"a sealed code needs reason === code, not retryable"});var TaskProgressPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,seq:z.number().int(),events:z.array(AgentEventOrUnknownSchema)});var TaskArtifactPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,name:z.string(),contentType:z.string(),inline:z.string().refine(isWithinInlineByteLimit,{message:"inline artifact payload exceeds 64KB limit"}).optional(),blobRef:BlobRefSchema.optional()});var TaskAwaitApprovalPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,summary:z.string(),approvalId:z.string().min(1)});var RESULT_DOCUMENT_MAX_BYTES=1048576;function checkResultDocument(document){return canonicalizePlainJson(document,RESULT_DOCUMENT_MAX_BYTES)}var TERMINAL_INFERENCE_USAGE_MAX_TOKENS=1e9;var TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS=6048e5;var TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH=160;var TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH=128;var TerminalInferenceUsageNumberSchema=z.number().int().safe().nonnegative().max(TERMINAL_INFERENCE_USAGE_MAX_TOKENS);var TerminalInferenceUsageDurationSchema=z.number().int().safe().nonnegative().max(TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS);var TerminalInferenceReportedAtSchema=z.iso.datetime({offset:true,precision:3}).refine(value=>value.endsWith("Z"),"reportedAt must be canonical UTC (Z)");var TerminalInferenceUsageSchema=z.object({runtime:RuntimeIdSchema,provider:z.string().min(1).max(TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH).optional(),model:z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),promptTokens:TerminalInferenceUsageNumberSchema.optional(),completionTokens:TerminalInferenceUsageNumberSchema.optional(),durationMs:TerminalInferenceUsageDurationSchema.optional(),clientVersion:z.string().min(1).max(TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH),reportedAt:TerminalInferenceReportedAtSchema});var TerminalPreparedObservationSchema=z.object({requestDigest:InputPreparationArtifactSummarySchema.shape.requestDigest,initialPromptTokens:TerminalInferenceUsageNumberSchema,maxPromptTokens:TerminalInferenceUsageNumberSchema}).strict().refine(value=>value.maxPromptTokens>=value.initialPromptTokens,{message:"maxPromptTokens must not be below initialPromptTokens",path:["maxPromptTokens"]});var TerminalAgentHomeProjectionSchema=z.object({profileRevision:AgentHomeProjectionProfileRevisionSchema,projectionHash:AgentHomeProjectionHashSchema}).strict();var AGENT_HOME_MEMORY_DIGEST_MAX_FILES=256;var AGENT_HOME_MEMORY_DIGEST_MAX_BYTES=16*1024*1024;var AGENT_HOME_MEMORY_PATH_MAX_LENGTH=1024;var AgentHomeMemoryChangedPathsSchema=z.array(z.string().min(1).max(AGENT_HOME_MEMORY_PATH_MAX_LENGTH).regex(/^[^\u0000]+$/u)).min(1).max(AGENT_HOME_MEMORY_DIGEST_MAX_FILES*2);var TerminalAgentHomeMemoryChangeSchema=z.discriminatedUnion("outcome",[z.object({outcome:z.literal("unchanged")}).strict(),z.object({outcome:z.literal("reader-attributed"),paths:AgentHomeMemoryChangedPathsSchema}).strict(),z.object({outcome:z.literal("unattributed"),paths:AgentHomeMemoryChangedPathsSchema}).strict(),z.object({outcome:z.literal("unmeasured")}).strict()]);var TaskCompletePlainPayloadSchema=z.object({...NO_SEALED_MEMBER,harnessId:HarnessIdSchema.optional(),summary:z.string(),finalMessage:z.string().optional(),sessionRef:z.string(),artifactRefs:z.array(BlobRefSchema).optional(),document:z.unknown().optional().refine(value=>value===void 0||checkResultDocument(value).ok,{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)`}),usage:TerminalInferenceUsageSchema.optional(),preparedObservation:TerminalPreparedObservationSchema.optional(),agentRef:AgentRefSchema.optional(),agentHomeProjection:TerminalAgentHomeProjectionSchema.optional(),agentHomeMemoryChange:TerminalAgentHomeMemoryChangeSchema.optional()});var RuntimeFailureClassSchema=z.enum(RUNTIME_FAILURE_CLASSES);var TaskFailureSchema=z.union([z.object({class:z.literal("quota"),resetsAt:z.iso.datetime().optional()}).strict(),z.object({class:RuntimeFailureClassSchema.exclude(["quota"])}).strict(),z.looseObject({class:unrecognizedToken(RUNTIME_FAILURE_CLASSES)})]);function readTaskFailure(failure){if(RUNTIME_FAILURE_CLASSES.includes(failure.class))return failure;return {class:"unknown",reportedClass:failure.class}}var TaskFailPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,recovery:z.object({kind:z.literal("daemon_interrupted"),offerId:z.uuid()}).strict().optional(),harnessId:HarnessIdSchema.optional(),reason:z.string().transform(boundFailureReason),retryable:z.boolean().optional(),failure:TaskFailureSchema.optional(),usage:TerminalInferenceUsageSchema.optional(),preparedObservation:TerminalPreparedObservationSchema.optional(),agentRef:AgentRefSchema.optional(),agentHomeProjection:TerminalAgentHomeProjectionSchema.optional(),agentHomeMemoryChange:TerminalAgentHomeMemoryChangeSchema.optional()});var TaskCancelledPlainPayloadSchema=z.object({...NO_SEALED_MEMBER,harnessId:HarnessIdSchema.optional(),reason:z.string().optional(),usage:TerminalInferenceUsageSchema.optional(),agentRef:AgentRefSchema.optional(),agentHomeProjection:TerminalAgentHomeProjectionSchema.optional(),agentHomeMemoryChange:TerminalAgentHomeMemoryChangeSchema.optional()});var TaskApprovalResolvedPayloadSchema=z.object({approvalId:z.string(),decision:z.enum(["approve","reject"]),resolvedBy:z.enum(["local"]),at:z.iso.datetime({offset:true})});var TaskSteerSealedPayloadSchema=z.object({steerId:z.uuid(),sealed:SealedTaskInputSchema}).strict();var TaskCompleteSealedPayloadSchema=TaskCompletePlainPayloadSchema.omit({summary:true,finalMessage:true,document:true,artifactRefs:true,preparedObservation:true}).extend({sealed:SealedTaskOutputSchema}).strict();var TaskFailSealedPayloadSchema=TaskFailPlainPayloadSchema.omit({reason:true,preparedObservation:true}).extend({sealed:SealedTaskOutputSchema}).strict();var TaskDeclineSealedPayloadSchema=DeclineFields.omit({reason:true}).extend({code:z.union([z.enum(HOME_DECLINE_CODES),unrecognizedToken(DECLINE_CODES)]).optional(),sealed:SealedTaskOutputSchema}).strict();var TaskCancelledSealedPayloadSchema=TaskCancelledPlainPayloadSchema.omit({reason:true}).extend({sealed:SealedTaskOutputSchema}).strict();var TaskProgressSealedPayloadSchema=TaskProgressPlainPayloadSchema.omit({events:true}).extend({sealed:SealedTaskOutputSchema}).strict();var TaskArtifactSealedPayloadSchema=TaskArtifactPlainPayloadSchema.omit({inline:true,blobRef:true}).extend({artifactId:z.uuid(),sealed:SealedTaskOutputSchema}).strict();var TaskAwaitApprovalSealedPayloadSchema=TaskAwaitApprovalPlainPayloadSchema.omit({summary:true}).extend({approvalId:z.string().min(1),sealed:SealedTaskOutputSchema}).strict();var TaskSteerPayloadSchema=z.union([TaskSteerPlainPayloadSchema,TaskSteerSealedPayloadSchema]);var TaskDeclinePayloadSchema=z.union([TaskDeclinePlainPayloadSchema,TaskDeclineSealedPayloadSchema]);var TaskProgressPayloadSchema=z.union([TaskProgressPlainPayloadSchema,TaskProgressSealedPayloadSchema]);var TaskArtifactPayloadSchema=z.union([TaskArtifactPlainPayloadSchema,TaskArtifactSealedPayloadSchema]);var TaskAwaitApprovalPayloadSchema=z.union([TaskAwaitApprovalPlainPayloadSchema,TaskAwaitApprovalSealedPayloadSchema]);var TaskCompletePayloadSchema=z.union([TaskCompletePlainPayloadSchema,TaskCompleteSealedPayloadSchema]);var TaskFailPayloadSchema=z.union([TaskFailPlainPayloadSchema,TaskFailSealedPayloadSchema]);var TaskCancelledPayloadSchema=z.union([TaskCancelledPlainPayloadSchema,TaskCancelledSealedPayloadSchema]);var MESSAGE_PAYLOAD_SCHEMAS={"conn.hello":ConnHelloPayloadSchema,"task.offer":TaskOfferPayloadSchema,"agent.egress.ack":AgentEgressAckPayloadSchema,"agent.message.disposition":AgentMessageDispositionPayloadSchema,"agent.content.read":AgentContentReadPayloadSchema,"agent.home.projection":AgentHomeProjectionPayloadSchema,"agent.input.preparation":AgentInputPreparationPayloadSchema,"provider.provisioning.available":ProviderProvisioningAvailablePayloadSchema,"agent.memory.intent.available":AgentMemoryIntentAvailablePayloadSchema,"task.approve":TaskApprovePayloadSchema,"task.reject":TaskRejectPayloadSchema,"task.cancel":TaskCancelPayloadSchema,"task.steer":TaskSteerPayloadSchema,"e2ee.key_package.available":E2eeKeyPackageAvailablePayloadSchema,"task.claim":TaskClaimPayloadSchema,"task.started":TaskStartedPayloadSchema,"task.decline":TaskDeclinePayloadSchema,"task.progress":TaskProgressPayloadSchema,"task.artifact":TaskArtifactPayloadSchema,"task.await_approval":TaskAwaitApprovalPayloadSchema,"task.complete":TaskCompletePayloadSchema,"task.fail":TaskFailPayloadSchema,"task.cancelled":TaskCancelledPayloadSchema,"task.approval_resolved":TaskApprovalResolvedPayloadSchema,"agent.egress.reliable":AgentEgressReliablePayloadSchema,"agent.message.draft":AgentMessageDraftPayloadSchema,"agent.message.publish":AgentMessagePublishPayloadSchema,"agent.content.receipt":AgentContentReceiptPayloadSchema};var MESSAGE_TYPES=Object.keys(MESSAGE_PAYLOAD_SCHEMAS);var SERVER_TO_DAEMON_TYPES=["task.offer","agent.egress.ack","agent.message.disposition","agent.content.read","agent.home.projection","agent.input.preparation","provider.provisioning.available","agent.memory.intent.available","task.approve","task.reject","task.cancel","task.steer","e2ee.key_package.available"];var DAEMON_TO_SERVER_TYPES=["task.claim","task.started","task.decline","task.progress","task.artifact","task.await_approval","task.complete","task.fail","task.cancelled","task.approval_resolved","agent.egress.reliable","agent.message.draft","agent.message.publish","agent.content.receipt"];var AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES=262144;var AGENT_MEMORY_INTENT_PATH_MAX_BYTES=1024;var AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES=128;var SHA256_REVISION=/^sha256:[0-9a-f]{64}$/u;var AgentMemoryIntentRevisionSchema=z.string().regex(SHA256_REVISION,"revision must be lowercase sha256:<64 hex>");var AgentMemoryIntentOperationDigestSchema=z.string().regex(SHA256_REVISION,"operationDigest must be lowercase sha256:<64 hex>");var AgentMemoryIntentPathSchema=z.string().min(1).max(AGENT_MEMORY_INTENT_PATH_MAX_BYTES).regex(/^[\x20\x21\x23-\x5b\x5d-\x7e]+$/u,"path must be printable ASCII without quote or backslash");var AgentMemoryIntentApprovalRefSchema=z.string().regex(new RegExp(`^[A-Za-z0-9._:-]{1,${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES}}$`,"u"),`approvalRef must be 1..${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES} characters of [A-Za-z0-9._:-]`);var LONE_SURROGATE2=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;var utf8=new TextEncoder;var AgentMemoryIntentContentSchema=z.string().refine(value=>!LONE_SURROGATE2.test(value),"content must be well-formed Unicode (encodable as UTF-8)").refine(value=>utf8.encode(value).byteLength<=AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES,`content must not exceed ${AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES} UTF-8 bytes`);var AGENT_MEMORY_INTENT_OPERATIONS=["replace","delete"];var AgentMemoryIntentOperationSchema=z.enum(AGENT_MEMORY_INTENT_OPERATIONS);var AgentMemoryIntentV1Schema=z.object({intentId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema,path:AgentMemoryIntentPathSchema,operation:AgentMemoryIntentOperationSchema,baseRevision:AgentMemoryIntentRevisionSchema,targetRevision:AgentMemoryIntentRevisionSchema.nullable(),content:AgentMemoryIntentContentSchema.optional(),approvalRef:AgentMemoryIntentApprovalRefSchema,operationDigest:AgentMemoryIntentOperationDigestSchema}).strict().superRefine((intent,ctx)=>{if(intent.operation==="delete"){if(intent.targetRevision!==null){ctx.addIssue({code:"custom",path:["targetRevision"],message:"a delete intent has a null targetRevision"});}if(intent.content!==void 0){ctx.addIssue({code:"custom",path:["content"],message:"a delete intent never carries content"});}return}if(intent.targetRevision===null){ctx.addIssue({code:"custom",path:["targetRevision"],message:"a replace intent requires a targetRevision"});}else if(intent.targetRevision===intent.baseRevision){ctx.addIssue({code:"custom",path:["targetRevision"],message:"targetRevision must differ from baseRevision"});}});var AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES=["intent_revoked","intent_expired","placement_changed","profile_revision_changed"];var AgentMemoryIntentHostTerminalCodeSchema=z.enum(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES);var AGENT_MEMORY_INTENT_REJECTION_CODES=["intent_invalid","path_invalid","memory_md_not_deletable","content_invalid","intent_digest_mismatch","agent_ref_mismatch","agent_home_unavailable",...AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES];var AgentMemoryIntentRejectionCodeSchema=z.enum(AGENT_MEMORY_INTENT_REJECTION_CODES);var AgentMemoryIntentFileObservationSchema=z.object({exists:z.boolean(),revision:AgentMemoryIntentRevisionSchema}).strict();var completionIdentity2={intentId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema,path:AgentMemoryIntentPathSchema,operation:AgentMemoryIntentOperationSchema,operationDigest:AgentMemoryIntentOperationDigestSchema};var AppliedCompletionSchema2=z.object({...completionIdentity2,outcome:z.literal("applied"),result:AgentMemoryIntentFileObservationSchema}).strict();var ConflictCompletionSchema=z.object({...completionIdentity2,outcome:z.literal("conflict"),observed:AgentMemoryIntentFileObservationSchema}).strict();var RejectedCompletionSchema2=z.object({...completionIdentity2,outcome:z.literal("rejected"),code:AgentMemoryIntentRejectionCodeSchema}).strict();var UncertainCompletionSchema=z.object({...completionIdentity2,outcome:z.literal("uncertain"),observed:AgentMemoryIntentFileObservationSchema}).strict();var AgentMemoryIntentCompletionSchema=z.discriminatedUnion("outcome",[AppliedCompletionSchema2,ConflictCompletionSchema,RejectedCompletionSchema2,UncertainCompletionSchema]);var AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS=["recorded","idempotent","conflict","host_terminal"];var AgentMemoryIntentReadbackDispositionSchema=z.enum(AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS);var AgentMemoryIntentReadbackSchema=z.object({tenantId:z.string().min(1),deviceId:z.string().min(1),intentId:z.uuid(),disposition:AgentMemoryIntentReadbackDispositionSchema,completion:AgentMemoryIntentCompletionSchema,recordedAt:z.iso.datetime({offset:true})}).strict().superRefine((readback,ctx)=>{if(readback.completion.intentId!==readback.intentId){ctx.addIssue({code:"custom",path:["completion","intentId"],message:"completion intentId must equal readback intentId"});}if(readback.disposition==="host_terminal"&&(readback.completion.outcome!=="rejected"||!AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.includes(readback.completion.code))){ctx.addIssue({code:"custom",path:["completion"],message:`a host_terminal readback must carry a rejected completion with one of: ${AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.join(", ")}`});}});var AGENT_MEMORY_INTENT_RESERVATIONS=["held","none"];var AgentMemoryIntentReservationSchema=z.enum(AGENT_MEMORY_INTENT_RESERVATIONS);var AgentMemoryIntentFetchRequestSchema=z.object({intentId:z.uuid(),reservation:AgentMemoryIntentReservationSchema}).strict();var AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS=["release","withheld","terminal","deferred"];var AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION={held:["release","withheld","terminal"],none:["terminal","deferred"]};function requireNoContent(intent,ctx,disposition){if(intent.content!==void 0){ctx.addIssue({code:"custom",path:["intent","content"],message:`a ${disposition} fetch response never carries content`});}}var ReleaseFetchResponseSchema=z.object({disposition:z.literal("release"),intent:AgentMemoryIntentV1Schema}).strict().superRefine((response,ctx)=>{if(response.intent.operation==="replace"&&response.intent.content===void 0){ctx.addIssue({code:"custom",path:["intent","content"],message:"a replace release must carry content"});}});var WithheldFetchResponseSchema=z.object({disposition:z.literal("withheld"),intent:AgentMemoryIntentV1Schema,code:AgentMemoryIntentHostTerminalCodeSchema}).strict().superRefine((response,ctx)=>requireNoContent(response.intent,ctx,"withheld"));var TerminalFetchResponseSchema=z.object({disposition:z.literal("terminal"),intent:AgentMemoryIntentV1Schema,readback:AgentMemoryIntentReadbackSchema}).strict().superRefine((response,ctx)=>{requireNoContent(response.intent,ctx,"terminal");const{intent,readback}=response;if(readback.intentId!==intent.intentId){ctx.addIssue({code:"custom",path:["readback","intentId"],message:"readback intentId must equal intent intentId"});}const completion=readback.completion;if(completion.agentRef.agentId!==intent.agentRef.agentId||completion.agentRef.profileRevision!==intent.agentRef.profileRevision||completion.path!==intent.path||completion.operation!==intent.operation||completion.operationDigest!==intent.operationDigest){ctx.addIssue({code:"custom",path:["readback","completion"],message:"readback completion identity must equal the intent identity and operationDigest"});}});var DeferredFetchResponseSchema=z.object({disposition:z.literal("deferred"),intent:AgentMemoryIntentV1Schema}).strict().superRefine((response,ctx)=>requireNoContent(response.intent,ctx,"deferred"));var AgentMemoryIntentFetchResponseSchema=z.discriminatedUnion("disposition",[ReleaseFetchResponseSchema,WithheldFetchResponseSchema,TerminalFetchResponseSchema,DeferredFetchResponseSchema]);function agentMemoryIntentFetchResponseSchemaFor(reservation){const allowed=AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION[AgentMemoryIntentReservationSchema.parse(reservation)];return AgentMemoryIntentFetchResponseSchema.superRefine((response,ctx)=>{if(!allowed.includes(response.disposition)){ctx.addIssue({code:"custom",path:["disposition"],message:`a ${reservation} reservation allows only: ${allowed.join(", ")}`});}})}var AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES=512*1024;var AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE=2147483647;var OPAQUE_REFERENCE_MAX_BYTES=512;var opaqueReference=field=>z.string().min(1).max(OPAQUE_REFERENCE_MAX_BYTES).refine(value=>new TextEncoder().encode(value).byteLength<=OPAQUE_REFERENCE_MAX_BYTES,{message:`${field} must not exceed ${OPAQUE_REFERENCE_MAX_BYTES} UTF-8 bytes`}).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u,`${field} must not contain control characters`);var AgentMemoryProjectionGrantRefSchema=opaqueReference("grantRef");var AgentMemoryProjectionSessionRefSchema=opaqueReference("sessionRef");var AgentMemoryProjectionWriterEpochSchema=z.number().int().positive().max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);var AgentMemoryProjectionSourceSeqSchema=z.number().int().positive().max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);function agentMemoryProjectionBase64UrlByteLength(value){if(!/^[A-Za-z0-9_-]*$/u.test(value)||value.length%4===1)return void 0;const complete=Math.floor(value.length/4)*3;const tail=value.length%4;return complete+(tail===0?0:tail-1)}var AgentMemoryProjectionSnapshotSchema=z.object({redactedHash:AgentEgressContentHashSchema,redactedByteCount:z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),redactedBytes:z.string().max(Math.ceil(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES/3)*4)}).strict().superRefine((snapshot,ctx)=>{const actual=agentMemoryProjectionBase64UrlByteLength(snapshot.redactedBytes);if(actual===void 0){ctx.addIssue({code:"custom",path:["redactedBytes"],message:"redactedBytes must be unpadded base64url"});return}if(actual!==snapshot.redactedByteCount){ctx.addIssue({code:"custom",path:["redactedByteCount"],message:"redactedByteCount must equal the decoded redactedBytes length"});}});var AgentMemoryProjectionMutationSchema=z.object({taskId:z.string().min(1).max(512),agentRef:AgentRefSchema,sessionRef:AgentMemoryProjectionSessionRefSchema,runtimeId:RuntimeIdSchema,grantRef:AgentMemoryProjectionGrantRefSchema,writerEpoch:AgentMemoryProjectionWriterEpochSchema,sourceSeq:AgentMemoryProjectionSourceSeqSchema,mutationId:z.uuid(),policyRevision:AgentEgressPolicyRevisionSchema,snapshot:AgentMemoryProjectionSnapshotSchema}).strict();var AgentMemoryProjectionMeteringReceiptSchema=z.object({meteringReceiptId:z.uuid(),acceptedRedactedBytes:z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),recordedAt:z.iso.datetime({offset:true})}).strict();var AgentMemoryProjectionReceiptSchema=z.object({outcome:z.enum(["accepted","idempotent"]),tenantId:z.string().min(1),deviceId:z.string().min(1),taskId:z.string().min(1).max(512),agentRef:AgentRefSchema,sessionRef:AgentMemoryProjectionSessionRefSchema,runtimeId:RuntimeIdSchema,grantRef:AgentMemoryProjectionGrantRefSchema,writerEpoch:AgentMemoryProjectionWriterEpochSchema,sourceSeq:AgentMemoryProjectionSourceSeqSchema,mutationId:z.uuid(),policyRevision:AgentEgressPolicyRevisionSchema,redactedHash:AgentEgressContentHashSchema,redactedByteCount:z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),metering:AgentMemoryProjectionMeteringReceiptSchema}).strict();var AgentMemoryProjectionEraseResultSchema=z.object({nextWriterEpoch:AgentMemoryProjectionWriterEpochSchema}).strict();var REQUIRED_TASK_ID=z.string().min(1);var OPTIONAL_TASK_ID=REQUIRED_TASK_ID.optional();var FORBIDDEN_TASK_ID=z.never().optional();var REQUIRED_SEQ=z.number().int();var OPTIONAL_SEQ=REQUIRED_SEQ.optional();function envelopeShape(type,taskId,seq){return z.object({v:z.number().int().refine(version=>version===PROTOCOL_VERSION,{message:"unsupported protocol version"}),id:z.uuid(),ts:z.iso.datetime({offset:true}),type:z.literal(type),task_id:taskId,session_ref:z.string().optional(),seq,payload:MESSAGE_PAYLOAD_SCHEMAS[type]})}var EnvelopeSchema=z.discriminatedUnion("type",[envelopeShape("conn.hello",OPTIONAL_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.offer",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.egress.ack",OPTIONAL_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.message.disposition",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.content.read",OPTIONAL_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.home.projection",FORBIDDEN_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.input.preparation",FORBIDDEN_TASK_ID,REQUIRED_SEQ),envelopeShape("provider.provisioning.available",FORBIDDEN_TASK_ID,REQUIRED_SEQ),envelopeShape("agent.memory.intent.available",FORBIDDEN_TASK_ID,REQUIRED_SEQ),envelopeShape("task.approve",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("task.reject",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("task.cancel",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("task.steer",REQUIRED_TASK_ID,REQUIRED_SEQ),envelopeShape("e2ee.key_package.available",FORBIDDEN_TASK_ID,REQUIRED_SEQ),envelopeShape("task.claim",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.started",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.decline",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.progress",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.artifact",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.await_approval",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.complete",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.fail",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.cancelled",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("task.approval_resolved",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("agent.egress.reliable",OPTIONAL_TASK_ID,OPTIONAL_SEQ),envelopeShape("agent.message.draft",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("agent.message.publish",REQUIRED_TASK_ID,OPTIONAL_SEQ),envelopeShape("agent.content.receipt",OPTIONAL_TASK_ID,OPTIONAL_SEQ)]);function isServerToDaemonType(type){return SERVER_TO_DAEMON_TYPES.includes(type)}var ProtocolError=class extends Error{constructor(message,options){super(message,options);this.name="ProtocolError";}};var EnvelopeParseError=class extends ProtocolError{constructor(message,cause){super(message,{cause});this.name="EnvelopeParseError";}};var UnknownMessageTypeError=class extends ProtocolError{type;constructor(type){super(`Unknown message type: ${String(type)}`);this.name="UnknownMessageTypeError";this.type=type;}};var EnvelopeValidationError=class extends ProtocolError{issues;constructor(message,issues){super(message,{cause:issues});this.name="EnvelopeValidationError";this.issues=issues;}};var MESSAGE_TYPE_SET=new Set(MESSAGE_TYPES);function decodeText(input){return typeof input==="string"?input:new TextDecoder("utf-8").decode(input)}function parseMessage(data){const result=EnvelopeSchema.safeParse(data);if(result.success){return result.data}const typeValue=typeof data==="object"&&data!==null&&!Array.isArray(data)?data.type:void 0;if(typeof typeValue!=="string"||!MESSAGE_TYPE_SET.has(typeValue)){throw new UnknownMessageTypeError(typeValue)}throw new EnvelopeValidationError(`Envelope failed validation for type "${typeValue}"`,result.error)}function decodeEnvelope(line){const text2=decodeText(line).replace(/[\r\n]+$/,"");let json;try{json=JSON.parse(text2);}catch(cause){throw new EnvelopeParseError("Envelope line is not valid JSON",cause)}return parseMessage(json)}function encodeEnvelope(env){return `${JSON.stringify(env)}
|
|
5
|
+
`}function createEnvelope(type,payload,...rest){const opts=rest[0]??{};const envelope={v:opts.v??PROTOCOL_VERSION,id:opts.id??crypto.randomUUID(),ts:opts.ts??new Date().toISOString(),type,...opts.taskId!==void 0?{task_id:opts.taskId}:{},...opts.sessionRef!==void 0?{session_ref:opts.sessionRef}:{},...opts.seq!==void 0?{seq:opts.seq}:{},payload};const result=EnvelopeSchema.safeParse(envelope);if(!result.success){throw new EnvelopeValidationError(`createEnvelope built an invalid envelope for type "${type}"`,result.error)}return result.data}var PairRequestSchema=z.object({pairingCode:z.string(),deviceName:z.string(),devicePublicKey:z.string(),machineId:z.string().regex(/^[0-9a-f]{64}$/u).optional()});var PAIR_RESPONSE_TENANT_ID_MAX_LENGTH=200;var PairResponseTenantIdSchema=z.string().min(1).max(PAIR_RESPONSE_TENANT_ID_MAX_LENGTH).refine(value=>value.trim()===value,{message:"tenantId must not have leading or trailing whitespace"}).refine(value=>!value.includes("\0"),{message:"tenantId must not contain a NUL character"});var PairResponseSchema=z.object({deviceId:z.string(),accessToken:z.string(),refreshHint:z.string().optional(),expiresIn:z.number().int().positive().optional(),tenantId:PairResponseTenantIdSchema});var ChallengeRequestSchema=z.object({deviceId:z.string()});var ChallengeResponseSchema=z.object({nonce:z.string()});var TokenRequestSchema=z.object({deviceId:z.string(),nonce:z.string(),signature:z.string()});var TokenResponseSchema=z.object({accessToken:z.string(),expiresAt:z.iso.datetime({offset:true}),expiresIn:z.number().int().positive().optional()});var DEVICE_NOT_REGISTERED_CODE="device_not_registered";var DeviceNotRegisteredResponseSchema=z.object({error:z.string(),code:z.literal(DEVICE_NOT_REGISTERED_CODE)});var PRESENCE_DETAIL_MAX_LENGTH=512;var PRESENCE_RUNTIME_VERSION_MAX_LENGTH=128;var PresenceRuntimeFactSchema=z.object({id:RuntimeIdSchema,version:z.string().min(1).max(PRESENCE_RUNTIME_VERSION_MAX_LENGTH).optional(),authPresent:z.boolean().optional(),capabilities:RuntimeCapabilitiesSchema.optional(),versionPolicy:RuntimeVersionPolicyProjectionSchema.optional()});var PresenceRuntimeUnavailableEntrySchema=RuntimeUnavailableEntrySchema.extend({id:RuntimeIdSchema});var PresenceRuntimeUnavailableSchema=z.array(PresenceRuntimeUnavailableEntrySchema).max(16).refine(values=>new Set(values.map(value=>value.id)).size===values.length,"duplicate runtime-unavailable identity");var PresencePublishRequestSchema=z.object({level:z.enum(["online","thinking","working","error","offline"]),detail:z.string().max(PRESENCE_DETAIL_MAX_LENGTH).optional(),configuredToolsets:ConfiguredToolsetsSchema.optional(),clientVersion:z.string().min(1).max(128).optional(),protocolVersions:z.array(ProtocolVersionNumberSchema).max(16).optional(),runtimes:z.array(PresenceRuntimeFactSchema).max(16).optional(),runtimeUnavailable:PresenceRuntimeUnavailableSchema.optional()});var CreateBlobRequestSchema=z.object({size:z.number().int().nonnegative(),contentType:z.string(),contentHash:z.string().regex(CONTENT_HASH_RE,'contentHash must be "sha256:<64 lowercase hex>"')});var CreateBlobResponseSchema=z.object({blobId:z.string(),uploadUrl:z.string()});var BlobDownloadUrlResponseSchema=z.object({downloadUrl:z.string()});var EventsPollQuerySchema=z.object({afterSeq:z.number().int().nonnegative().optional(),cursor:z.number().int().nonnegative().optional()});var ActivityIngressSchema=z.object({activityMaxEvents:z.number().int().positive(),activityMaxBytes:z.number().int().min(2)});var OUTBOUND_REFUSAL_REASONS=["payload_invalid","not_permitted","limit_exceeded","state_conflict","unsupported"];function isOutboundRefusalCode(value){return OUTBOUND_REFUSAL_REASONS.includes(value)}var MessageSendOutcomeSchema=z.object({id:z.uuid(),outcome:z.enum(["accepted","duplicate","rejected"]),reason:z.string().max(64).transform(value=>isOutboundRefusalCode(value)?value:"unknown").optional()});var EventsPollResponseSchema=z.object({events:z.array(z.unknown()),cursor:z.number().int(),capabilities:z.array(z.string()),ingress:ActivityIngressSchema});var MAX_MESSAGES_PER_BATCH=256;var MESSAGES_SEND_MAX_BODY_BYTES=2*1024*1024;var MessagesSendRequestSchema=z.object({messages:z.array(z.looseObject({v:z.literal(PROTOCOL_VERSION),id:z.uuid()})).max(MAX_MESSAGES_PER_BATCH)});var MessagesSendResponseSchema=z.object({accepted:z.number().int().nonnegative(),rejected:z.number().int().nonnegative().optional(),capabilities:z.array(z.string()).optional(),ingress:ActivityIngressSchema.optional(),outcomes:z.array(MessageSendOutcomeSchema).max(MAX_MESSAGES_PER_BATCH)});var AgentHomeProjectionCompletionRequestSchema=z.object({requestId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema,projectionHash:AgentHomeProjectionHashSchema,outcome:AgentHomeProjectionOutcomeSchema}).strict();var AgentHomeProjectionStatusSchema=z.enum(["pending","applied","idempotent","stale","conflict"]);var AgentHomeProjectionReadbackSchema=z.object({tenantId:z.string().min(1),deviceId:z.string().min(1),requestId:z.uuid(),agentRef:AgentHomeProjectionAgentRefSchema,projectionHash:AgentHomeProjectionHashSchema,status:AgentHomeProjectionStatusSchema,completedAt:z.iso.datetime({offset:true}).optional()}).strict();var InputPreparationCompletionRequestSchema=z.discriminatedUnion("outcome",[z.object({outcome:z.literal("prepared"),requestId:z.uuid(),agentRef:AgentRefSchema,profileId:InputPreparationProfileIdSchema,policyRevision:InputPreparationPolicyRevisionSchema,receipt:InputPreparationReceiptSummarySchema}).strict(),z.object({outcome:z.literal("rejected"),requestId:z.uuid(),agentRef:AgentRefSchema,profileId:InputPreparationProfileIdSchema,policyRevision:InputPreparationPolicyRevisionSchema,reason:InputPreparationRejectionReasonSchema}).strict()]);var InputPreparationStatusSchema=z.enum(["pending","prepared","rejected"]);var InputPreparationReadbackSchema=z.object({tenantId:z.string().min(1),deviceId:z.string().min(1),requestId:z.uuid(),agentRef:AgentRefSchema,profileId:InputPreparationProfileIdSchema,policyRevision:InputPreparationPolicyRevisionSchema,status:InputPreparationStatusSchema,receipt:InputPreparationReceiptSummarySchema.optional(),reason:InputPreparationRejectionReasonSchema.optional(),completedAt:z.iso.datetime({offset:true}).optional()}).strict().superRefine((value,ctx)=>{const expectsReceipt=value.status==="prepared";const expectsReason=value.status==="rejected";if(expectsReceipt!==(value.receipt!==void 0)){ctx.addIssue({code:"custom",path:["receipt"],message:'receipt is present exactly when status is "prepared"'});}if(expectsReason!==(value.reason!==void 0)){ctx.addIssue({code:"custom",path:["reason"],message:'reason is present exactly when status is "rejected"'});}if(value.status!=="pending"!==(value.completedAt!==void 0)){ctx.addIssue({code:"custom",path:["completedAt"],message:"completedAt is present exactly when the status is terminal"});}});var InputPreparationStatusQuerySchema=z.object({agentId:z.string().min(1),profileRevision:z.string().min(1)}).strict();var AgentMemoryProjectionCommitRequestSchema=AgentMemoryProjectionMutationSchema;var AgentMemoryProjectionCommitResponseSchema=AgentMemoryProjectionReceiptSchema;var BYOK_PAIR_PATH="/byok/pair";var BYOK_CHALLENGE_PATH="/byok/challenge";var BYOK_TOKEN_PATH="/byok/token";var BYOK_CAPABILITIES_PATH="/byok/capabilities";var BYOK_EVENTS_PATH="/byok/events";var BYOK_MESSAGES_PATH="/byok/messages";var BYOK_AGENT_HOME_PROJECTIONS_PATH="/byok/agent-home-projections";var BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE="/byok/agent-home-projections/:requestId/completion";function byokAgentHomeProjectionCompletionPath(requestId){return `${BYOK_AGENT_HOME_PROJECTIONS_PATH}/${encodeURIComponent(requestId)}/completion`}var BYOK_INPUT_PREPARATIONS_PATH="/byok/input-preparations";var BYOK_INPUT_PREPARATION_COMPLETION_ROUTE="/byok/input-preparations/:requestId/completion";var BYOK_INPUT_PREPARATION_STATUS_ROUTE="/byok/input-preparations/:requestId";function byokInputPreparationCompletionPath(requestId){return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}/completion`}function byokInputPreparationStatusPath(requestId){return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}`}var BYOK_AGENT_MEMORY_PROJECTIONS_PATH="/byok/agent-memory-projections";var BYOK_PRESENCE_PATH="/byok/presence";var BYOK_BOARD_PATH="/byok/board";var BYOK_BOARD_STREAM_PATH="/byok/board/stream";var BYOK_BOARD_CLAIM_ROUTE="/byok/board/:id/claim";var BYOK_BOARD_UNCLAIM_ROUTE="/byok/board/:id/unclaim";var BYOK_BOARD_STATUS_ROUTE="/byok/board/:id/status";var BYOK_RECORDS_PATH="/byok/records";var BYOK_RECORD_ROUTE="/byok/records/:kind/:key";function byokRecordPath(kind,key){return `/byok/records/${encodeURIComponent(kind)}/${encodeURIComponent(key)}`}var BYOK_E2EE_MEMBER_KEY_PATH="/byok/e2ee/member-key";var BYOK_E2EE_CHAIN_PATH="/byok/e2ee/chain";var BYOK_E2EE_KEY_PACKAGES_PATH="/byok/e2ee/key-packages";var BYOK_E2EE_PAIRING_MAC_PATH="/byok/e2ee/pairing-mac";var BYOK_SKILL_PACKS_PATH="/byok/skill-packs";var BYOK_SKILL_PACK_FILE_ROUTE="/byok/skill-packs/:name/files/:path";function byokSkillPackFilePath(name,path){return `/byok/skill-packs/${encodeURIComponent(name)}/files/${encodeURIComponent(path)}`}var BYOK_BLOBS_PATH="/byok/blobs";var BYOK_BLOB_FINALIZE_ROUTE="/byok/blobs/:id/finalize";var BYOK_BLOB_URL_ROUTE="/byok/blobs/:id/url";var BYOK_BLOB_CONTENT_ROUTE="/byok/blobs/:id/content";function byokBlobFinalizePath(blobId){return `/byok/blobs/${encodeURIComponent(blobId)}/finalize`}function byokBlobUrlPath(blobId){return `/byok/blobs/${encodeURIComponent(blobId)}/url`}function byokBlobContentPath(blobId){return `/byok/blobs/${blobId}/content`}var BOT_TURN_OUTCOME_CONTRACT="bot-turn-outcome.v1";var BOT_TURN_OUTCOME_LIMITS=Object.freeze({delegateMaxItems:2,delegateRequestMaxLength:1e3,cancelDelegationMaxItems:2,askUserQuestionMaxLength:400,askUserOptionsMaxItems:6,askUserOptionIdMaxLength:24,askUserOptionLabelMaxLength:80,confirmableActionMaxItems:1,confirmableSummaryMaxLength:300,confirmableDraftMaxBytes:16384,createRoutineMaxItems:1,updateRoutineMaxItems:1,cancelRoutineMaxItems:2,routinePromptMaxLength:500,postTextMaxLength:2730,roomCallMembersMaxItems:4,createBotMaxItems:3,updateBotMaxItems:1,deleteBotMaxItems:1,botNameMaxLength:40,botRoleMaxLength:80,botPersonaMaxLength:300,createRoomMaxItems:1,updateRoomMaxItems:1,roomNameMaxLength:40,roomMembersMaxItems:12,roomAnnouncementMaxLength:300,teamNoteMaxLength:300});var L=BOT_TURN_OUTCOME_LIMITS;var text=maxLength=>({type:"string",minLength:1,maxLength});var oneOfIds=ids=>({enum:[...ids]});var closed=(properties,required)=>({type:"object",additionalProperties:false,required,properties});var list=(items,maxItems)=>({type:"array",minItems:1,maxItems,items});var ROUTINE_DAYS_OF_WEEK=Object.freeze(["mon","tue","wed","thu","fri","sat","sun"]);var integer=(minimum,maximum)=>({type:"integer",minimum,maximum});var BotTurnOutcomeSchemaError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="BotTurnOutcomeSchemaError";}code};function schedule(timeZones,shape){const fields={minute:integer(0,59),hour:integer(0,23),daysOfWeek:{type:"array",minItems:1,maxItems:7,items:{enum:[...ROUTINE_DAYS_OF_WEEK]}},dayOfMonth:integer(1,31),month:integer(1,12),tz:oneOfIds(timeZones)};const outer={description:"Local time in tz. No day field: every day. daysOfWeek: those days only. dayOfMonth: that day of each month, or of month only.",...closed(fields,["minute","hour","tz"])};if(shape==="flat")return outer;const only=(names,required)=>({additionalProperties:false,...required.length?{required}:{},properties:Object.fromEntries(names.map(n=>[n,{}]))});return {...outer,oneOf:[only(["minute","hour","tz"],[]),only(["minute","hour","daysOfWeek","tz"],["daysOfWeek"]),only(["minute","hour","dayOfMonth","month","tz"],["dayOfMonth"])]}}function roomFields(members){return {name:text(L.roomNameMaxLength),members:{type:"array",minItems:1,maxItems:L.roomMembersMaxItems,items:oneOfIds(members)},admin:oneOfIds(members),mode:{enum:["mention","admin"]},announcement:text(L.roomAnnouncementMaxLength)}}var botTurnOutcomeFragments={delegate(o){return list(closed({to:oneOfIds(o.to),request:text(L.delegateRequestMaxLength)},["to","request"]),L.delegateMaxItems)},cancelDelegation(o){return list(closed({delegationId:oneOfIds(o.delegationIds)},["delegationId"]),L.cancelDelegationMaxItems)},askUser(){const question=text(L.askUserQuestionMaxLength);const option=closed({id:text(L.askUserOptionIdMaxLength),label:text(L.askUserOptionLabelMaxLength)},["id","label"]);return {oneOf:[closed({question,answerKind:{const:"text"}},["question","answerKind"]),closed({question,answerKind:{const:"single_choice"},options:{type:"array",minItems:2,maxItems:L.askUserOptionsMaxItems,items:option}},["question","answerKind","options"])]}},confirmableAction(o){for(const{action,draft}of o.actions){const bound=resultOutcomeMaxBytes(draft);if(bound===null||bound>L.confirmableDraftMaxBytes){throw new BotTurnOutcomeSchemaError("draft-over-budget",`draft for ${action} is ${bound??"unbounded"}; cap ${L.confirmableDraftMaxBytes}`)}}const branches=o.actions.map(({action,draft})=>closed({action:{const:action},summary:text(L.confirmableSummaryMaxLength),draft},["action","summary","draft"]));return list(branches.length===1?branches[0]:{oneOf:branches},L.confirmableActionMaxItems)},createRoutine(o){return list(closed({localId:oneOfIds(o.localIds),schedule:schedule(o.timeZones,o.scheduleShape??"checked"),prompt:text(L.routinePromptMaxLength),...o.targets?{target:oneOfIds(o.targets)}:{}},["localId","schedule","prompt"]),L.createRoutineMaxItems)},updateRoutine(o){return list(closed({routineId:oneOfIds(o.routineIds),schedule:schedule(o.timeZones,o.scheduleShape??"checked"),prompt:text(L.routinePromptMaxLength)},["routineId"]),L.updateRoutineMaxItems)},cancelRoutine(o){return list(closed({routineId:oneOfIds(o.routineIds)},["routineId"]),L.cancelRoutineMaxItems)},speech(){return {oneOf:[closed({kind:{const:"post"},text:text(L.postTextMaxLength)},["kind","text"]),closed({kind:{const:"pass"}},["kind"])]}},roomCall(o){return closed({members:{type:"array",minItems:1,maxItems:L.roomCallMembersMaxItems,items:oneOfIds(o.members)}},["members"])},createBot(o){return list(closed({localId:oneOfIds(o.localIds),name:text(L.botNameMaxLength),role:text(L.botRoleMaxLength),persona:text(L.botPersonaMaxLength),model:oneOfIds(o.models)},["localId","name","role","persona","model"]),L.createBotMaxItems)},updateBot(o){return list(closed({botId:oneOfIds(o.botIds),name:text(L.botNameMaxLength),role:text(L.botRoleMaxLength),persona:text(L.botPersonaMaxLength),model:oneOfIds(o.models)},["botId"]),L.updateBotMaxItems)},deleteBot(o){return list(closed({botId:oneOfIds(o.botIds)},["botId"]),L.deleteBotMaxItems)},createRoom(o){return list(closed({localId:oneOfIds(o.localIds),...roomFields(o.members)},["localId","name","members"]),L.createRoomMaxItems)},updateRoom(o){return list(closed({roomId:oneOfIds(o.roomIds),...roomFields(o.members)},["roomId"]),L.updateRoomMaxItems)},teamNote(){return closed({text:text(L.teamNoteMaxLength)},["text"])}};function composeBotTurnOutcomeSchema(fragments,required=[]){const schema={type:"object",additionalProperties:false,description:`${BOT_TURN_OUTCOME_CONTRACT}: actions for the Host. Omit a field for no action of that kind; {} means no actions.`,...required.length?{required:[...required]}:{},properties:fragments};const admitted=checkResultSchema(schema);if(!admitted.ok&&admitted.reason==="over-cap"){throw new BotTurnOutcomeSchemaError("schema-over-budget",`schema is ${admitted.bytes} bytes; cap ${RESULT_SCHEMA_MAX_BYTES}`)}if(!admitted.ok)throw new BotTurnOutcomeSchemaError("not-subset",JSON.stringify(admitted.issues));const bound=resultOutcomeMaxBytes(admitted.canonical);if(bound===null||bound>RESULT_OUTCOME_MAX_BYTES){throw new BotTurnOutcomeSchemaError("over-budget",`largest outcome is ${bound??"unbounded"} bytes; cap ${RESULT_OUTCOME_MAX_BYTES}`)}return admitted.canonical}
|
|
46
6
|
|
|
47
|
-
// src/version.ts
|
|
48
|
-
var MAILBOX_READ_AHEAD_MAX_SEQS = 4096;
|
|
49
|
-
var MAILBOX_READ_AHEAD_CAPABILITY = "mailbox-read-ahead";
|
|
50
|
-
var PROTOCOL_VERSION = 3;
|
|
51
|
-
var STRICT_AGENT_ONLY_CAPABILITY = "strict-agent-only";
|
|
52
|
-
var AGENT_HOME_READERS_CAPABILITY = "agent-home-readers";
|
|
53
|
-
var CUSTOM_HARNESS_CAPABILITY = "custom-harness";
|
|
54
|
-
var CAPABILITY_FLAGS = [
|
|
55
|
-
"steer",
|
|
56
|
-
"blob-upload",
|
|
57
|
-
"interactive-approval",
|
|
58
|
-
"approval_resolved",
|
|
59
|
-
"approval-targeting",
|
|
60
|
-
"dispatch-selection",
|
|
61
|
-
PROVIDER_PROFILE_BINDING_CAPABILITY,
|
|
62
|
-
"toolset-selection",
|
|
63
|
-
"agent-home-contract",
|
|
64
|
-
AGENT_HOME_READERS_CAPABILITY,
|
|
65
|
-
STRICT_AGENT_ONLY_CAPABILITY,
|
|
66
|
-
AGENT_EGRESS_POLICY_CAPABILITY,
|
|
67
|
-
AGENT_EGRESS_RELIABLE_ACK_CAPABILITY,
|
|
68
|
-
AGENT_MESSAGE_EGRESS_CAPABILITY,
|
|
69
|
-
AGENT_EGRESS_FRESH_SESSION_CAPABILITY,
|
|
70
|
-
AGENT_CONTENT_WORKSPACE_READ_CAPABILITY,
|
|
71
|
-
AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY,
|
|
72
|
-
AGENT_CONTENT_ARTIFACT_READ_CAPABILITY,
|
|
73
|
-
AGENT_HOME_PROJECTION_CAPABILITY,
|
|
74
|
-
AGENT_INPUT_PREPARATION_CAPABILITY,
|
|
75
|
-
TERMINAL_PROJECTION_SELECTION_CAPABILITY,
|
|
76
|
-
HOST_MCP_TASK_CONTEXT_CAPABILITY,
|
|
77
|
-
CUSTOM_HARNESS_CAPABILITY,
|
|
78
|
-
MAILBOX_READ_AHEAD_CAPABILITY,
|
|
79
|
-
PROVIDER_PROVISIONING_CAPABILITY,
|
|
80
|
-
AGENT_MEMORY_INTENT_CAPABILITY,
|
|
81
|
-
AGENT_MEMORY_SELECTION_CAPABILITY,
|
|
82
|
-
AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY,
|
|
83
|
-
AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY,
|
|
84
|
-
"agent-message-draft",
|
|
85
|
-
SEALED_PAYLOAD_CAPABILITY,
|
|
86
|
-
SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY,
|
|
87
|
-
RUNTIME_FAILURE_CLASS_CAPABILITY
|
|
88
|
-
];
|
|
89
|
-
|
|
90
|
-
// src/task-state.ts
|
|
91
|
-
var TASK_STATES = [
|
|
92
|
-
"Offered",
|
|
93
|
-
"Claimed",
|
|
94
|
-
"Running",
|
|
95
|
-
"AwaitApproval",
|
|
96
|
-
"Complete",
|
|
97
|
-
"Failed",
|
|
98
|
-
"Cancelled"
|
|
99
|
-
];
|
|
100
|
-
var TASK_TRANSITIONS = {
|
|
101
|
-
Offered: ["Claimed", "Cancelled", "Failed"],
|
|
102
|
-
Claimed: ["Running", "Failed", "Cancelled"],
|
|
103
|
-
Running: ["AwaitApproval", "Complete", "Failed", "Cancelled"],
|
|
104
|
-
AwaitApproval: ["Running", "Failed", "Cancelled"],
|
|
105
|
-
Complete: [],
|
|
106
|
-
Failed: [],
|
|
107
|
-
Cancelled: []
|
|
108
|
-
};
|
|
109
|
-
function canTransition(from, to) {
|
|
110
|
-
return TASK_TRANSITIONS[from].includes(to);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// src/constants.ts
|
|
114
|
-
var AGENT_MEMORY_MAX_SNAPSHOT_BYTES = 1024 * 1024;
|
|
115
|
-
var AGENT_MEMORY_MAX_SNAPSHOT_FILES = 128;
|
|
116
|
-
var RUNTIME_IDS = Object.freeze(["pi", "claude", "codex"]);
|
|
117
|
-
|
|
118
|
-
// src/sealed-split-table.ts
|
|
119
|
-
var OFFER_DIGESTS = {
|
|
120
|
-
"instruction.blobRef.contentHash": "sealed",
|
|
121
|
-
"dispatchSelection.providerProfile.profileRevision": "plain",
|
|
122
|
-
"dispatchSelection.providerProfile.profileHash": "plain"
|
|
123
|
-
};
|
|
124
|
-
var AGENT_OFFER_DIGESTS = { ...OFFER_DIGESTS, "agentRef.profileRevision": "plain" };
|
|
125
|
-
var EGRESS_OFFER_DIGESTS = { ...AGENT_OFFER_DIGESTS, "egressPolicy.policyRevision": "plain" };
|
|
126
|
-
var TERMINAL_DIGESTS = {
|
|
127
|
-
"agentRef.profileRevision": "plain",
|
|
128
|
-
"agentHomeProjection.profileRevision": "plain",
|
|
129
|
-
"agentHomeProjection.projectionHash": "plain"
|
|
130
|
-
};
|
|
131
|
-
var sealedOffer = (plainType, digests) => ({ plainType, category: "task-input", identity: [], moved: ["instruction"], forbidden: [], digests });
|
|
132
|
-
var SEALED_SPLIT_TABLE = Object.freeze({
|
|
133
|
-
"task.offer_sealed": sealedOffer("task.offer", OFFER_DIGESTS),
|
|
134
|
-
"task.offer_with_toolsets_sealed": sealedOffer("task.offer_with_toolsets", OFFER_DIGESTS),
|
|
135
|
-
"task.offer_for_agent_sealed": sealedOffer("task.offer_for_agent", AGENT_OFFER_DIGESTS),
|
|
136
|
-
"task.offer_for_agent_with_egress_sealed": sealedOffer("task.offer_for_agent_with_egress", EGRESS_OFFER_DIGESTS),
|
|
137
|
-
"task.offer_for_agent_with_egress_fresh_sealed": sealedOffer("task.offer_for_agent_with_egress_fresh", EGRESS_OFFER_DIGESTS),
|
|
138
|
-
"task.steer_sealed": { plainType: "task.steer", category: "task-input", identity: ["steerId"], moved: ["text"], forbidden: [], digests: {} },
|
|
139
|
-
"task.complete_sealed": {
|
|
140
|
-
plainType: "task.complete",
|
|
141
|
-
category: "task-output",
|
|
142
|
-
identity: [],
|
|
143
|
-
moved: ["summary", "finalMessage", "document"],
|
|
144
|
-
forbidden: ["artifactRefs", "preparedObservation"],
|
|
145
|
-
digests: {
|
|
146
|
-
...TERMINAL_DIGESTS,
|
|
147
|
-
"artifactRefs[].contentHash": "forbidden",
|
|
148
|
-
"preparedObservation.requestDigest": "forbidden"
|
|
149
|
-
}
|
|
150
|
-
},
|
|
151
|
-
"task.fail_sealed": {
|
|
152
|
-
plainType: "task.fail",
|
|
153
|
-
category: "task-output",
|
|
154
|
-
identity: [],
|
|
155
|
-
moved: ["reason"],
|
|
156
|
-
forbidden: ["preparedObservation"],
|
|
157
|
-
digests: { ...TERMINAL_DIGESTS, "preparedObservation.requestDigest": "forbidden" }
|
|
158
|
-
},
|
|
159
|
-
"task.decline_sealed": {
|
|
160
|
-
plainType: "task.decline",
|
|
161
|
-
category: "task-output",
|
|
162
|
-
identity: [],
|
|
163
|
-
moved: ["reason"],
|
|
164
|
-
forbidden: [],
|
|
165
|
-
digests: { "agentRef.profileRevision": "plain" }
|
|
166
|
-
},
|
|
167
|
-
"task.cancelled_sealed": {
|
|
168
|
-
plainType: "task.cancelled",
|
|
169
|
-
category: "task-output",
|
|
170
|
-
identity: [],
|
|
171
|
-
moved: ["reason"],
|
|
172
|
-
forbidden: [],
|
|
173
|
-
digests: TERMINAL_DIGESTS
|
|
174
|
-
},
|
|
175
|
-
"task.progress_sealed": {
|
|
176
|
-
plainType: "task.progress",
|
|
177
|
-
category: "task-output",
|
|
178
|
-
identity: ["seq"],
|
|
179
|
-
moved: ["events"],
|
|
180
|
-
forbidden: [],
|
|
181
|
-
digests: { "events[].spill.blob.contentHash": "sealed" },
|
|
182
|
-
inlineOnly: true
|
|
183
|
-
},
|
|
184
|
-
"task.artifact_sealed": {
|
|
185
|
-
plainType: "task.artifact",
|
|
186
|
-
category: "task-output",
|
|
187
|
-
identity: ["artifactId"],
|
|
188
|
-
moved: ["inline"],
|
|
189
|
-
forbidden: ["blobRef"],
|
|
190
|
-
digests: { "blobRef.contentHash": "forbidden" },
|
|
191
|
-
limits: { inline: 2 * 1024 * 1024 }
|
|
192
|
-
},
|
|
193
|
-
"task.await_approval_sealed": {
|
|
194
|
-
plainType: "task.await_approval",
|
|
195
|
-
category: "task-output",
|
|
196
|
-
identity: ["approvalId"],
|
|
197
|
-
moved: ["summary"],
|
|
198
|
-
forbidden: [],
|
|
199
|
-
digests: {},
|
|
200
|
-
inlineOnly: true
|
|
201
|
-
}
|
|
202
|
-
});
|
|
203
|
-
function isSealedMessageType(type) {
|
|
204
|
-
return Object.hasOwn(SEALED_SPLIT_TABLE, type);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// src/wire-additions.ts
|
|
208
|
-
var AGENT_OFFER_FIELDS = (surface) => [
|
|
209
|
-
{ kind: "envelope", rule: "gated", surface, field: "dispatchSelection", capability: "dispatch-selection", advertisedBy: "device" },
|
|
210
|
-
{ kind: "envelope", rule: "gated", surface, field: "requiredToolsets", capability: "toolset-selection", advertisedBy: "device" },
|
|
211
|
-
{ kind: "envelope", rule: "gated", surface, field: "terminalProjection", capability: "terminal-projection-selection", advertisedBy: "device" },
|
|
212
|
-
{ kind: "envelope", rule: "gated", surface, field: "homeAccess", capability: "agent-home-readers", advertisedBy: "device" }
|
|
213
|
-
];
|
|
214
|
-
var EGRESS_OFFER_FIELDS = (surface) => [
|
|
215
|
-
{ kind: "envelope", rule: "gated", surface, field: "messageEgress", capability: "agent-message-egress", advertisedBy: "device" },
|
|
216
|
-
...AGENT_OFFER_FIELDS(surface)
|
|
217
|
-
];
|
|
218
|
-
function sealedRows(plainRows) {
|
|
219
|
-
return Object.keys(SEALED_SPLIT_TABLE).flatMap((surface) => {
|
|
220
|
-
const { plainType, moved, forbidden } = SEALED_SPLIT_TABLE[surface];
|
|
221
|
-
const dropped = [...moved, ...forbidden];
|
|
222
|
-
const advertisedBy = SEALED_SPLIT_TABLE[surface].category === "task-input" ? "device" : "server";
|
|
223
|
-
const inherited = plainRows.flatMap((row) => {
|
|
224
|
-
if (row.kind !== "envelope" || row.surface !== plainType) return [];
|
|
225
|
-
if (row.field !== void 0 && dropped.includes(row.field.split(/[.[]/u)[0])) return [];
|
|
226
|
-
return [{ ...row, surface }];
|
|
227
|
-
});
|
|
228
|
-
const entry = SEALED_SPLIT_TABLE[surface];
|
|
229
|
-
const byReference = advertisedBy === "server" && entry.inlineOnly !== true ? [{ kind: "envelope", rule: "gated", surface, field: "sealed.ciphertextRef", capability: "sealed-output-ciphertext-ref", advertisedBy }] : [];
|
|
230
|
-
return [{ kind: "envelope", rule: "gated", surface, capability: "sealed-payload-v1", advertisedBy }, ...inherited, ...byReference];
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
var SEALED_DECLINE_CODE = (value) => ({ kind: "envelope", rule: "gated", surface: "task.decline", field: "code", value, capability: "sealed-payload-v1", advertisedBy: "server" });
|
|
234
|
-
var PLAIN_ROWS = [
|
|
235
|
-
// Server to daemon: offers.
|
|
236
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer", field: "harnessId", capability: "custom-harness", advertisedBy: "device" },
|
|
237
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_with_toolsets", field: "harnessId", capability: "custom-harness", advertisedBy: "device" },
|
|
238
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent", capability: "agent-home-contract", advertisedBy: "device" },
|
|
239
|
-
...AGENT_OFFER_FIELDS("task.offer_for_agent"),
|
|
240
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent", field: "agentMemory", capability: "agent-memory-selection", advertisedBy: "device" },
|
|
241
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent", field: "agentMemory", value: "read-if-admitted", capability: "agent-memory-read-if-admitted", advertisedBy: "device" },
|
|
242
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent", field: "agentMemory", value: "read-write-if-admitted", capability: "agent-memory-read-write-if-admitted", advertisedBy: "device" },
|
|
243
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", capability: "agent-home-contract", advertisedBy: "device" },
|
|
244
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", capability: "agent-egress-policy", advertisedBy: "device" },
|
|
245
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", capability: "agent-egress-reliable-ack", advertisedBy: "device" },
|
|
246
|
-
...EGRESS_OFFER_FIELDS("task.offer_for_agent_with_egress"),
|
|
247
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", field: "agentMemory", capability: "agent-memory-selection", advertisedBy: "device" },
|
|
248
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", field: "agentMemory", value: "read-if-admitted", capability: "agent-memory-read-if-admitted", advertisedBy: "device" },
|
|
249
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress", field: "agentMemory", value: "read-write-if-admitted", capability: "agent-memory-read-write-if-admitted", advertisedBy: "device" },
|
|
250
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", capability: "agent-home-contract", advertisedBy: "device" },
|
|
251
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", capability: "agent-egress-policy", advertisedBy: "device" },
|
|
252
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", capability: "agent-egress-reliable-ack", advertisedBy: "device" },
|
|
253
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", capability: "agent-egress-fresh-session", advertisedBy: "device" },
|
|
254
|
-
...EGRESS_OFFER_FIELDS("task.offer_for_agent_with_egress_fresh"),
|
|
255
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", field: "agentMemory", capability: "agent-memory-selection", advertisedBy: "device" },
|
|
256
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", field: "agentMemory", value: "read-if-admitted", capability: "agent-memory-read-if-admitted", advertisedBy: "device" },
|
|
257
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_for_agent_with_egress_fresh", field: "agentMemory", value: "read-write-if-admitted", capability: "agent-memory-read-write-if-admitted", advertisedBy: "device" },
|
|
258
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_prepared", capability: "agent-home-contract", advertisedBy: "device" },
|
|
259
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_prepared", capability: "agent-input-preparation-v9", advertisedBy: "device" },
|
|
260
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_prepared", capability: "agent-egress-policy", advertisedBy: "device" },
|
|
261
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_prepared", capability: "agent-egress-reliable-ack", advertisedBy: "device" },
|
|
262
|
-
{ kind: "envelope", rule: "gated", surface: "task.offer_prepared", capability: "agent-egress-fresh-session", advertisedBy: "device" },
|
|
263
|
-
...EGRESS_OFFER_FIELDS("task.offer_prepared"),
|
|
264
|
-
// Server to daemon: Agent control messages.
|
|
265
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", capability: "agent-home-contract", advertisedBy: "device" },
|
|
266
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", capability: "agent-egress-policy", advertisedBy: "device" },
|
|
267
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", capability: "agent-egress-reliable-ack", advertisedBy: "device" },
|
|
268
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", field: "surface", value: "workspace", capability: "agent-content-workspace-read", advertisedBy: "device" },
|
|
269
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", field: "surface", value: "transcript", capability: "agent-content-transcript-read", advertisedBy: "device" },
|
|
270
|
-
{ kind: "envelope", rule: "gated", surface: "agent.content.read", field: "surface", value: "artifact", capability: "agent-content-artifact-read", advertisedBy: "device" },
|
|
271
|
-
{ kind: "envelope", rule: "gated", surface: "agent.home.projection", capability: "agent-home-contract", advertisedBy: "device" },
|
|
272
|
-
{ kind: "envelope", rule: "gated", surface: "agent.home.projection", capability: "agent-home-projection", advertisedBy: "device" },
|
|
273
|
-
{ kind: "envelope", rule: "gated", surface: "agent.input.preparation", capability: "agent-home-contract", advertisedBy: "device" },
|
|
274
|
-
{ kind: "envelope", rule: "gated", surface: "agent.input.preparation", capability: "agent-input-preparation-v9", advertisedBy: "device" },
|
|
275
|
-
{ kind: "envelope", rule: "gated", surface: "provider.provisioning.available", capability: "provider-provisioning.v1", advertisedBy: "device" },
|
|
276
|
-
{ kind: "envelope", rule: "gated", surface: "agent.memory.intent.available", capability: "agent-memory-intent.v1", advertisedBy: "device" },
|
|
277
|
-
{ kind: "envelope", rule: "gated", surface: "e2ee.key_package.available", capability: "sealed-payload-v1", advertisedBy: "device" },
|
|
278
|
-
// One optional runtime capability, shared by discovery and the claim snapshot.
|
|
279
|
-
{ kind: "envelope", rule: "strip-safe", surface: "conn.hello", field: "runtimes[].capabilities.messageDraft" },
|
|
280
|
-
{ kind: "envelope", rule: "strip-safe", surface: "conn.hello", field: "harnesses[].capabilities.messageDraft" },
|
|
281
|
-
{ kind: "envelope", rule: "strip-safe", surface: "task.claim", field: "capabilities.messageDraft" },
|
|
282
|
-
// Optional MCP event identity is observability only; older receivers may omit it.
|
|
283
|
-
{ kind: "envelope", rule: "strip-safe", surface: "task.progress", field: "events[].mcp" },
|
|
284
|
-
// Daemon to server.
|
|
285
|
-
{ kind: "envelope", rule: "gated", surface: "agent.message.draft", capability: "agent-message-draft", advertisedBy: "server" },
|
|
286
|
-
{ kind: "envelope", rule: "gated", surface: "task.approval_resolved", capability: "approval_resolved", advertisedBy: "server" },
|
|
287
|
-
{ kind: "envelope", rule: "gated", surface: "task.fail", field: "failure", capability: "runtime-failure-class", advertisedBy: "server" }
|
|
288
|
-
];
|
|
289
|
-
var WIRE_ADDITIONS = Object.freeze([
|
|
290
|
-
...PLAIN_ROWS,
|
|
291
|
-
...sealedRows(PLAIN_ROWS),
|
|
292
|
-
SEALED_DECLINE_CODE("sealed_key_unavailable"),
|
|
293
|
-
SEALED_DECLINE_CODE("sealed_open_failed"),
|
|
294
|
-
SEALED_DECLINE_CODE("sealed_content_mac_mismatch"),
|
|
295
|
-
SEALED_DECLINE_CODE("sealing_policy_mismatch")
|
|
296
|
-
]);
|
|
297
|
-
function requiredReceiverCapabilities(type, payload) {
|
|
298
|
-
const fields = payload !== null && typeof payload === "object" ? payload : {};
|
|
299
|
-
const required = [];
|
|
300
|
-
for (const entry of WIRE_ADDITIONS) {
|
|
301
|
-
if (entry.kind !== "envelope" || entry.rule !== "gated" || entry.surface !== type) continue;
|
|
302
|
-
if (entry.field !== void 0) {
|
|
303
|
-
const value = entry.field.split(".").reduce(
|
|
304
|
-
(parent, segment) => parent !== null && typeof parent === "object" ? parent[segment] : void 0,
|
|
305
|
-
fields
|
|
306
|
-
);
|
|
307
|
-
if (value === void 0) continue;
|
|
308
|
-
if (entry.value !== void 0 && value !== entry.value) continue;
|
|
309
|
-
}
|
|
310
|
-
if (!required.includes(entry.capability)) required.push(entry.capability);
|
|
311
|
-
}
|
|
312
|
-
return required;
|
|
313
|
-
}
|
|
314
|
-
var CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;
|
|
315
|
-
var BlobRefSchema = z.object({
|
|
316
|
-
blobId: z.string(),
|
|
317
|
-
contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be "sha256:<64 lowercase hex>"'),
|
|
318
|
-
size: z.number().int().nonnegative(),
|
|
319
|
-
contentType: z.string(),
|
|
320
|
-
url: z.string().optional()
|
|
321
|
-
});
|
|
322
|
-
var SEALED_PAYLOAD_VERSION = 1;
|
|
323
|
-
var SEALED_PAYLOAD_SUITE = "byok-sealed-v1.hkdf-sha256.aes-256-gcm";
|
|
324
|
-
var SEALED_PAYLOAD_CATEGORIES = ["task-input", "agent-message", "task-output", "memory-projection"];
|
|
325
|
-
var SEALED_PAYLOAD_V1_CATEGORIES = ["task-input", "task-output"];
|
|
326
|
-
var SEALED_DECLINE_CODES = [
|
|
327
|
-
"sealed_key_unavailable",
|
|
328
|
-
"sealed_open_failed",
|
|
329
|
-
"sealed_content_mac_mismatch",
|
|
330
|
-
"sealing_policy_mismatch"
|
|
331
|
-
];
|
|
332
|
-
var SEALED_TASK_PLAIN_CODES = Object.freeze({
|
|
333
|
-
"task.fail": { reason: ["daemon_interrupted", "sealed_key_unavailable"] },
|
|
334
|
-
"task.decline": { reason: SEALED_DECLINE_CODES },
|
|
335
|
-
"task.cancelled": { reason: [] }
|
|
336
|
-
});
|
|
337
|
-
function isSealedTaskPlainOutput(type, payload) {
|
|
338
|
-
const codes = Object.hasOwn(SEALED_TASK_PLAIN_CODES, type) ? SEALED_TASK_PLAIN_CODES[type] : {};
|
|
339
|
-
const fields = Object.values(SEALED_SPLIT_TABLE).filter((entry) => entry.category === "task-output" && entry.plainType === type).flatMap((entry) => [...entry.moved, ...entry.forbidden]);
|
|
340
|
-
if (fields.length > 0 && !Object.hasOwn(SEALED_TASK_PLAIN_CODES, type)) return false;
|
|
341
|
-
const record = payload;
|
|
342
|
-
for (const field of fields) {
|
|
343
|
-
const value = record[field];
|
|
344
|
-
if (value !== void 0 && !(typeof value === "string" && (codes[field] ?? []).includes(value))) return false;
|
|
345
|
-
}
|
|
346
|
-
return type !== "task.decline" || record.reason === void 0 || record.code === record.reason;
|
|
347
|
-
}
|
|
348
|
-
var SEALED_INLINE_MAX_PADDED_LENGTH = 256 * 1024;
|
|
349
|
-
var SEALED_PAYLOAD_MAX_CONTENT_LENGTH = 2 * 1024 * 1024;
|
|
350
|
-
var AEAD_TAG_BYTES = 16;
|
|
351
|
-
var FRAME_HEADER_BYTES = 4;
|
|
352
|
-
var ALIGNED_FRAME_LIMIT = 16 * 1024;
|
|
353
|
-
var FRAME_ALIGNMENT = 256;
|
|
354
|
-
var SALT_BYTES = 32;
|
|
355
|
-
var NONCE_BYTES = 12;
|
|
356
|
-
function floorLog2(value) {
|
|
357
|
-
let exponent = 0;
|
|
358
|
-
for (let remaining = value; remaining >= 2; remaining = Math.floor(remaining / 2)) exponent += 1;
|
|
359
|
-
return exponent;
|
|
360
|
-
}
|
|
361
|
-
function sealedPayloadPaddedLength(frameLength) {
|
|
362
|
-
if (!Number.isSafeInteger(frameLength) || frameLength < FRAME_HEADER_BYTES) {
|
|
363
|
-
throw new RangeError("Sealed frame length must be a safe integer of at least 4");
|
|
364
|
-
}
|
|
365
|
-
if (frameLength <= ALIGNED_FRAME_LIMIT) return Math.ceil(frameLength / FRAME_ALIGNMENT) * FRAME_ALIGNMENT;
|
|
366
|
-
const exponent = floorLog2(frameLength);
|
|
367
|
-
const step = 2 ** (exponent - (floorLog2(exponent) + 1));
|
|
368
|
-
return Math.ceil(frameLength / step) * step;
|
|
369
|
-
}
|
|
370
|
-
var SEALED_PAYLOAD_MAX_PADDED_LENGTH = sealedPayloadPaddedLength(
|
|
371
|
-
FRAME_HEADER_BYTES + SEALED_PAYLOAD_MAX_CONTENT_LENGTH
|
|
372
|
-
);
|
|
373
|
-
function isLegalPaddedLength(value) {
|
|
374
|
-
return Number.isSafeInteger(value) && value >= FRAME_ALIGNMENT && value <= SEALED_PAYLOAD_MAX_PADDED_LENGTH && sealedPayloadPaddedLength(value) === value;
|
|
375
|
-
}
|
|
376
|
-
var BASE64URL_VALUE = /^[A-Za-z0-9_-]*$/u;
|
|
377
|
-
var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
378
|
-
function sealedBase64UrlByteLength(value) {
|
|
379
|
-
if (!BASE64URL_VALUE.test(value)) return void 0;
|
|
380
|
-
const tail = value.length % 4;
|
|
381
|
-
if (tail === 1) return void 0;
|
|
382
|
-
if (tail !== 0) {
|
|
383
|
-
const last = BASE64URL_ALPHABET.indexOf(value[value.length - 1]);
|
|
384
|
-
const unusedBits = tail === 2 ? 15 : 3;
|
|
385
|
-
if ((last & unusedBits) !== 0) return void 0;
|
|
386
|
-
}
|
|
387
|
-
return Math.floor(value.length / 4) * 3 + (tail === 0 ? 0 : tail - 1);
|
|
388
|
-
}
|
|
389
|
-
function base64UrlOf(bytes) {
|
|
390
|
-
return z.string().refine((value) => sealedBase64UrlByteLength(value) === bytes, `must be canonical unpadded base64url of ${bytes} bytes`);
|
|
391
|
-
}
|
|
392
|
-
var PositiveIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
|
|
393
|
-
function sealedPayloadSchema(category) {
|
|
394
|
-
return z.object({
|
|
395
|
-
v: z.literal(SEALED_PAYLOAD_VERSION),
|
|
396
|
-
suite: z.literal(SEALED_PAYLOAD_SUITE),
|
|
397
|
-
category,
|
|
398
|
-
scope: z.object({
|
|
399
|
-
id: z.string().min(1),
|
|
400
|
-
epoch: PositiveIntegerSchema,
|
|
401
|
-
keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u)
|
|
402
|
-
}).strict(),
|
|
403
|
-
chainHead: z.object({
|
|
404
|
-
seq: PositiveIntegerSchema,
|
|
405
|
-
hash: z.string().regex(CONTENT_HASH_RE)
|
|
406
|
-
}).strict(),
|
|
407
|
-
sender: z.string().regex(/^[A-Za-z0-9_-]{43}$/u),
|
|
408
|
-
salt: base64UrlOf(SALT_BYTES),
|
|
409
|
-
nonce: base64UrlOf(NONCE_BYTES),
|
|
410
|
-
paddedLength: PositiveIntegerSchema.refine(isLegalPaddedLength, "must be a legal padded frame length within the v1 limit"),
|
|
411
|
-
contentMac: z.string().regex(/^hmac-sha256:[0-9a-f]{64}$/u),
|
|
412
|
-
ciphertext: z.string().optional(),
|
|
413
|
-
/** The ciphertext blob. A presigned `url` is transport detail and never part of a sealed member. */
|
|
414
|
-
ciphertextRef: BlobRefSchema.omit({ url: true }).strict().optional()
|
|
415
|
-
}).strict().superRefine((sealed, ctx) => {
|
|
416
|
-
const ciphertextLength = sealed.paddedLength + AEAD_TAG_BYTES;
|
|
417
|
-
const inline = sealed.paddedLength <= SEALED_INLINE_MAX_PADDED_LENGTH;
|
|
418
|
-
if (inline) {
|
|
419
|
-
if (sealed.ciphertextRef !== void 0 || sealed.ciphertext === void 0) {
|
|
420
|
-
ctx.addIssue({ code: "custom", path: ["ciphertext"], message: `a padded length up to ${SEALED_INLINE_MAX_PADDED_LENGTH} carries inline ciphertext only` });
|
|
421
|
-
} else if (sealedBase64UrlByteLength(sealed.ciphertext) !== ciphertextLength) {
|
|
422
|
-
ctx.addIssue({ code: "custom", path: ["ciphertext"], message: "ciphertext must be canonical base64url of paddedLength + 16 bytes" });
|
|
423
|
-
}
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
if (sealed.ciphertext !== void 0 || sealed.ciphertextRef === void 0) {
|
|
427
|
-
ctx.addIssue({ code: "custom", path: ["ciphertextRef"], message: `a padded length above ${SEALED_INLINE_MAX_PADDED_LENGTH} carries ciphertextRef only` });
|
|
428
|
-
} else if (sealed.ciphertextRef.size !== ciphertextLength) {
|
|
429
|
-
ctx.addIssue({ code: "custom", path: ["ciphertextRef", "size"], message: "ciphertextRef size must equal paddedLength + 16" });
|
|
430
|
-
}
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
var SealedPayloadSchema = sealedPayloadSchema(z.enum(SEALED_PAYLOAD_V1_CATEGORIES));
|
|
434
|
-
var SealedTaskInputSchema = sealedPayloadSchema(z.literal("task-input"));
|
|
435
|
-
var SealedTaskOutputSchema = sealedPayloadSchema(z.literal("task-output"));
|
|
436
|
-
function isCanonicalCategoryList(categories) {
|
|
437
|
-
return categories.every((category, index) => index === 0 || SEALED_PAYLOAD_CATEGORIES.indexOf(categories[index - 1]) < SEALED_PAYLOAD_CATEGORIES.indexOf(category));
|
|
438
|
-
}
|
|
439
|
-
var TaskSealingSchema = z.object({
|
|
440
|
-
scopeId: z.string().min(1),
|
|
441
|
-
epoch: PositiveIntegerSchema,
|
|
442
|
-
categories: z.array(z.enum(SEALED_PAYLOAD_V1_CATEGORIES)).min(1).refine(isCanonicalCategoryList, "categories must be unique and in canonical order")
|
|
443
|
-
}).strict();
|
|
444
|
-
var CanonicalInstantSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u).refine((value) => {
|
|
445
|
-
const instant = Date.parse(value);
|
|
446
|
-
return Number.isFinite(instant) && new Date(instant).toISOString() === value;
|
|
447
|
-
}, "must be a canonical UTC instant");
|
|
448
|
-
var RoutineRefSchema = z.object({
|
|
449
|
-
routineId: z.string().min(1),
|
|
450
|
-
definitionVersion: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
451
|
-
notAfter: CanonicalInstantSchema
|
|
452
|
-
}).strict();
|
|
453
|
-
function sealedOfferRule(payload, ctx) {
|
|
454
|
-
const { instruction, sealing, sealed, routineRef } = payload;
|
|
455
|
-
if (!sealing.categories.includes("task-input")) {
|
|
456
|
-
if (routineRef !== void 0) ctx.addIssue({ code: "custom", path: ["routineRef"], message: "a routine template is sealed task input, so routineRef needs a task that seals task-input" });
|
|
457
|
-
if (sealed !== void 0) ctx.addIssue({ code: "custom", path: ["sealed"], message: "a task that does not seal task-input carries no sealed member" });
|
|
458
|
-
if (instruction === void 0) ctx.addIssue({ code: "custom", path: ["instruction"], message: "a task that does not seal task-input carries a plaintext instruction" });
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
if (sealed === void 0) {
|
|
462
|
-
ctx.addIssue({ code: "custom", path: ["sealed"], message: "a task that seals task-input carries the sealed instruction" });
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
if (instruction !== void 0) ctx.addIssue({ code: "custom", path: ["instruction"], message: "a sealed instruction never travels in plaintext too" });
|
|
466
|
-
if (sealed.scope.id !== sealing.scopeId || sealed.scope.epoch !== sealing.epoch) {
|
|
467
|
-
ctx.addIssue({ code: "custom", path: ["sealed", "scope"], message: "the offer task-input must be sealed under the task scope at the task epoch" });
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
var ProviderProfileRefSchema = z.string().min(1).max(64).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u, "provider profile refs must be lowercase portable identifiers");
|
|
471
|
-
var ProviderProfileRevisionSchema = z.string().regex(/^(?:0|[1-9][0-9]{0,19})$/u, "provider profile revision must be canonical decimal");
|
|
472
|
-
var ProviderProfileHashSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/u, "provider profile hash must be lowercase sha256");
|
|
473
|
-
var PROVIDER_MODEL_CAPABILITIES = ["image-input"];
|
|
474
|
-
var ProviderModelCapabilitySchema = z.enum(PROVIDER_MODEL_CAPABILITIES);
|
|
475
|
-
var ProviderProfileBindingSchema = z.object({
|
|
476
|
-
profileRef: ProviderProfileRefSchema,
|
|
477
|
-
profileRevision: ProviderProfileRevisionSchema,
|
|
478
|
-
profileHash: ProviderProfileHashSchema,
|
|
479
|
-
modelId: z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u),
|
|
480
|
-
requiredCapabilities: z.array(ProviderModelCapabilitySchema).max(8)
|
|
481
|
-
}).strict().superRefine((binding, ctx) => {
|
|
482
|
-
if (new Set(binding.requiredCapabilities).size !== binding.requiredCapabilities.length) {
|
|
483
|
-
ctx.addIssue({ code: "custom", path: ["requiredCapabilities"], message: "duplicate provider capability" });
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
var PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION = "provider-secret-sealing-key.register";
|
|
487
|
-
var ProviderProvisioningAvailablePayloadSchema = z.object({
|
|
488
|
-
requestId: z.uuid()
|
|
489
|
-
}).strict();
|
|
490
|
-
var PROVIDER_PROVISIONING_OPERATIONS = ["configure", "update_model", "replace_secret", "delete"];
|
|
491
|
-
var ProviderProvisioningOperationSchema = z.enum(PROVIDER_PROVISIONING_OPERATIONS);
|
|
492
|
-
var PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM = "9223372036854775807";
|
|
493
|
-
var ProviderProvisioningOperationGenerationSchema = z.string().regex(/^[1-9][0-9]{0,18}$/u, "operationGeneration must be a canonical positive decimal string").refine(
|
|
494
|
-
(value) => value.length < PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM.length || value <= PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM,
|
|
495
|
-
`operationGeneration must not exceed ${PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM}`
|
|
496
|
-
);
|
|
497
|
-
var ProviderProvisioningOperationDigestSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/u, "operationDigest must be lowercase sha256");
|
|
498
|
-
var PROVIDER_PROVISIONING_REJECTION_CODES = [
|
|
499
|
-
"request_invalid",
|
|
500
|
-
"request_conflict",
|
|
501
|
-
"request_expired",
|
|
502
|
-
"request_not_yet_valid",
|
|
503
|
-
"request_window_invalid",
|
|
504
|
-
"sealing_key_rotated",
|
|
505
|
-
"enrollment_mismatch",
|
|
506
|
-
"agent_not_placed",
|
|
507
|
-
"config_digest_mismatch",
|
|
508
|
-
"operation_generation_stale",
|
|
509
|
-
"profile_changed",
|
|
510
|
-
"profile_not_found",
|
|
511
|
-
"credential_scope_mismatch",
|
|
512
|
-
"provider_kind_unsupported",
|
|
513
|
-
"pi_model_invalid",
|
|
514
|
-
"capabilities_invalid",
|
|
515
|
-
"seal_open_failed",
|
|
516
|
-
"secret_invalid",
|
|
517
|
-
"local_commit_interrupted",
|
|
518
|
-
"secret_store_unavailable"
|
|
519
|
-
];
|
|
520
|
-
var ProviderProvisioningRejectionCodeSchema = z.enum(PROVIDER_PROVISIONING_REJECTION_CODES);
|
|
521
|
-
var PROVIDER_PROVISIONING_HOST_TERMINAL_CODES = ["request_expired", "sealing_key_rotated"];
|
|
522
|
-
var ProviderProvisioningProviderStatusSchema = z.object({
|
|
523
|
-
profileRef: ProviderProfileRefSchema,
|
|
524
|
-
providerKind: z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u, "providerKind must be a lowercase portable identifier"),
|
|
525
|
-
modelId: z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u),
|
|
526
|
-
capabilities: z.array(ProviderModelCapabilitySchema).max(8),
|
|
527
|
-
secretConfigured: z.boolean()
|
|
528
|
-
}).strict().superRefine((status, ctx) => {
|
|
529
|
-
if (new Set(status.capabilities).size !== status.capabilities.length) {
|
|
530
|
-
ctx.addIssue({ code: "custom", path: ["capabilities"], message: "duplicate provider capability" });
|
|
531
|
-
}
|
|
532
|
-
});
|
|
533
|
-
var PROVIDER_PROVISIONING_KEY_CHECK_RESULTS = [
|
|
534
|
-
"ok",
|
|
535
|
-
"credential_rejected",
|
|
536
|
-
"rate_limited",
|
|
537
|
-
"quota_or_billing",
|
|
538
|
-
"model_not_permitted",
|
|
539
|
-
"provider_error",
|
|
540
|
-
"unreachable",
|
|
541
|
-
"timeout",
|
|
542
|
-
"not_run"
|
|
543
|
-
];
|
|
544
|
-
var ProviderProvisioningKeyCheckResultSchema = z.enum(PROVIDER_PROVISIONING_KEY_CHECK_RESULTS);
|
|
545
|
-
var ProviderProvisioningKeyCheckSchema = z.object({
|
|
546
|
-
result: ProviderProvisioningKeyCheckResultSchema
|
|
547
|
-
}).strict();
|
|
548
|
-
var completionIdentity = {
|
|
549
|
-
requestId: z.uuid(),
|
|
550
|
-
operation: ProviderProvisioningOperationSchema,
|
|
551
|
-
operationGeneration: ProviderProvisioningOperationGenerationSchema,
|
|
552
|
-
operationDigest: ProviderProvisioningOperationDigestSchema
|
|
553
|
-
};
|
|
554
|
-
var AppliedCompletionSchema = z.object({
|
|
555
|
-
outcome: z.literal("applied"),
|
|
556
|
-
...completionIdentity,
|
|
557
|
-
providerStatus: ProviderProvisioningProviderStatusSchema.nullable(),
|
|
558
|
-
binding: ProviderProfileBindingSchema.nullable(),
|
|
559
|
-
keyCheck: ProviderProvisioningKeyCheckSchema
|
|
560
|
-
}).strict();
|
|
561
|
-
var RejectedCompletionSchema = z.object({
|
|
562
|
-
outcome: z.literal("rejected"),
|
|
563
|
-
...completionIdentity,
|
|
564
|
-
code: ProviderProvisioningRejectionCodeSchema
|
|
565
|
-
}).strict();
|
|
566
|
-
var ProviderProvisioningCompletionSchema = z.discriminatedUnion("outcome", [AppliedCompletionSchema, RejectedCompletionSchema]).superRefine((completion, ctx) => {
|
|
567
|
-
if (completion.outcome !== "applied") return;
|
|
568
|
-
const { operation, providerStatus, binding } = completion;
|
|
569
|
-
if (operation === "delete") {
|
|
570
|
-
if (completion.keyCheck.result !== "not_run") {
|
|
571
|
-
ctx.addIssue({ code: "custom", path: ["keyCheck", "result"], message: "an applied delete must report keyCheck not_run" });
|
|
572
|
-
}
|
|
573
|
-
if (providerStatus !== null) {
|
|
574
|
-
ctx.addIssue({ code: "custom", path: ["providerStatus"], message: "an applied delete reports no provider status" });
|
|
575
|
-
}
|
|
576
|
-
if (binding !== null) {
|
|
577
|
-
ctx.addIssue({ code: "custom", path: ["binding"], message: "an applied delete reports no binding" });
|
|
578
|
-
}
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
if (providerStatus === null) {
|
|
582
|
-
ctx.addIssue({ code: "custom", path: ["providerStatus"], message: `an applied ${operation} must report provider status` });
|
|
583
|
-
}
|
|
584
|
-
if (binding === null) {
|
|
585
|
-
ctx.addIssue({ code: "custom", path: ["binding"], message: `an applied ${operation} must report its exact binding` });
|
|
586
|
-
}
|
|
587
|
-
if (providerStatus === null || binding === null) return;
|
|
588
|
-
if (providerStatus.profileRef !== binding.profileRef) {
|
|
589
|
-
ctx.addIssue({ code: "custom", path: ["binding", "profileRef"], message: "binding profileRef must equal providerStatus profileRef" });
|
|
590
|
-
}
|
|
591
|
-
if (providerStatus.modelId !== binding.modelId) {
|
|
592
|
-
ctx.addIssue({ code: "custom", path: ["binding", "modelId"], message: "binding modelId must equal providerStatus modelId" });
|
|
593
|
-
}
|
|
594
|
-
if ((operation === "configure" || operation === "replace_secret") && !providerStatus.secretConfigured) {
|
|
595
|
-
ctx.addIssue({
|
|
596
|
-
code: "custom",
|
|
597
|
-
path: ["providerStatus", "secretConfigured"],
|
|
598
|
-
message: `an applied ${operation} must report a configured secret`
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
});
|
|
602
|
-
var PROVIDER_PROVISIONING_DISPOSITIONS = ["recorded", "idempotent", "conflict", "host_terminal"];
|
|
603
|
-
var ProviderProvisioningDispositionSchema = z.enum(PROVIDER_PROVISIONING_DISPOSITIONS);
|
|
604
|
-
var ProviderProvisioningReadbackSchema = z.object({
|
|
605
|
-
tenantId: z.string().min(1),
|
|
606
|
-
deviceId: z.string().min(1),
|
|
607
|
-
requestId: z.uuid(),
|
|
608
|
-
disposition: ProviderProvisioningDispositionSchema,
|
|
609
|
-
completion: ProviderProvisioningCompletionSchema,
|
|
610
|
-
completedAt: z.iso.datetime({ offset: true })
|
|
611
|
-
}).strict().superRefine((readback, ctx) => {
|
|
612
|
-
if (readback.completion.requestId !== readback.requestId) {
|
|
613
|
-
ctx.addIssue({ code: "custom", path: ["completion", "requestId"], message: "completion requestId must equal readback requestId" });
|
|
614
|
-
}
|
|
615
|
-
if (readback.disposition === "host_terminal" && (readback.completion.outcome !== "rejected" || !PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.includes(readback.completion.code))) {
|
|
616
|
-
ctx.addIssue({
|
|
617
|
-
code: "custom",
|
|
618
|
-
path: ["completion"],
|
|
619
|
-
message: `a host_terminal readback must carry a rejected completion with one of: ${PROVIDER_PROVISIONING_HOST_TERMINAL_CODES.join(", ")}`
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
});
|
|
623
|
-
|
|
624
|
-
// src/plain-json.ts
|
|
625
|
-
function isSameJsonData(a, b) {
|
|
626
|
-
if (a === null || b === null) return a === b;
|
|
627
|
-
const typeOfA = typeof a;
|
|
628
|
-
if (typeOfA !== typeof b) return false;
|
|
629
|
-
if (typeOfA !== "object") {
|
|
630
|
-
return a === b;
|
|
631
|
-
}
|
|
632
|
-
const aIsArray = Array.isArray(a);
|
|
633
|
-
if (aIsArray !== Array.isArray(b)) return false;
|
|
634
|
-
if (aIsArray) {
|
|
635
|
-
const arrayA = a;
|
|
636
|
-
const arrayB = b;
|
|
637
|
-
if (arrayA.length !== arrayB.length) return false;
|
|
638
|
-
for (let index = 0; index < arrayA.length; index += 1) {
|
|
639
|
-
if (!isSameJsonData(arrayA[index], arrayB[index])) return false;
|
|
640
|
-
}
|
|
641
|
-
return true;
|
|
642
|
-
}
|
|
643
|
-
const objectA = a;
|
|
644
|
-
const objectB = b;
|
|
645
|
-
const keysA = Object.keys(objectA);
|
|
646
|
-
const keysB = Object.keys(objectB);
|
|
647
|
-
if (keysA.length === 0) {
|
|
648
|
-
const prototypeA = Object.getPrototypeOf(objectA);
|
|
649
|
-
if (prototypeA !== Object.prototype && prototypeA !== null) return false;
|
|
650
|
-
}
|
|
651
|
-
if (keysA.length !== keysB.length) return false;
|
|
652
|
-
for (const key of keysA) {
|
|
653
|
-
if (!Object.prototype.hasOwnProperty.call(objectB, key)) return false;
|
|
654
|
-
if (!isSameJsonData(objectA[key], objectB[key])) return false;
|
|
655
|
-
}
|
|
656
|
-
return true;
|
|
657
|
-
}
|
|
658
|
-
function jsonDepthExceeds(value, limit) {
|
|
659
|
-
const stack = [{ node: value, depth: 0 }];
|
|
660
|
-
while (stack.length > 0) {
|
|
661
|
-
const { node, depth } = stack.pop();
|
|
662
|
-
if (node === null || typeof node !== "object") continue;
|
|
663
|
-
const next = depth + 1;
|
|
664
|
-
if (next > limit) return true;
|
|
665
|
-
const children = Array.isArray(node) ? node : Object.values(node);
|
|
666
|
-
for (const child of children) stack.push({ node: child, depth: next });
|
|
667
|
-
}
|
|
668
|
-
return false;
|
|
669
|
-
}
|
|
670
|
-
function canonicalizePlainJson(value, maxBytes, maxDepth) {
|
|
671
|
-
let json;
|
|
672
|
-
try {
|
|
673
|
-
json = JSON.stringify(value);
|
|
674
|
-
} catch {
|
|
675
|
-
return { ok: false, reason: "not-serializable" };
|
|
676
|
-
}
|
|
677
|
-
if (json === void 0) return { ok: false, reason: "not-serializable" };
|
|
678
|
-
const bytes = new TextEncoder().encode(json).length;
|
|
679
|
-
if (bytes > maxBytes) return { ok: false, reason: "over-cap", bytes };
|
|
680
|
-
const canonical = JSON.parse(json);
|
|
681
|
-
if (maxDepth !== void 0 && jsonDepthExceeds(canonical, maxDepth)) return { ok: false, reason: "too-deep", bytes };
|
|
682
|
-
if (!isSameJsonData(value, canonical)) return { ok: false, reason: "not-plain-json" };
|
|
683
|
-
return { ok: true, bytes, canonical };
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
// src/result-schema.ts
|
|
687
|
-
var RESULT_SCHEMA_MAX_BYTES = 16384;
|
|
688
|
-
var RESULT_OUTCOME_MAX_BYTES = 65536;
|
|
689
|
-
var RESULT_SCHEMA_MAX_DEPTH = 32;
|
|
690
|
-
var RESULT_JSON_MAX_DEPTH = 128;
|
|
691
|
-
var RESULT_ISSUES_MAX_COUNT = 20;
|
|
692
|
-
var RESULT_ISSUES_MAX_BYTES = 4096;
|
|
693
|
-
var ISSUE_STRING_MAX_LENGTH = 128;
|
|
694
|
-
var RESULT_SCHEMA_KEYWORDS = Object.freeze([
|
|
695
|
-
"type",
|
|
696
|
-
"properties",
|
|
697
|
-
"required",
|
|
698
|
-
"additionalProperties",
|
|
699
|
-
"items",
|
|
700
|
-
"enum",
|
|
701
|
-
"const",
|
|
702
|
-
"oneOf",
|
|
703
|
-
"minLength",
|
|
704
|
-
"maxLength",
|
|
705
|
-
"minItems",
|
|
706
|
-
"maxItems",
|
|
707
|
-
"minimum",
|
|
708
|
-
"maximum",
|
|
709
|
-
"description"
|
|
710
|
-
]);
|
|
711
|
-
var RESULT_SCHEMA_INSTANCE_TYPES = Object.freeze([
|
|
712
|
-
"object",
|
|
713
|
-
"array",
|
|
714
|
-
"string",
|
|
715
|
-
"number",
|
|
716
|
-
"integer",
|
|
717
|
-
"boolean",
|
|
718
|
-
"null"
|
|
719
|
-
]);
|
|
720
|
-
var KEYWORDS = new Set(RESULT_SCHEMA_KEYWORDS);
|
|
721
|
-
var INSTANCE_TYPES = new Set(RESULT_SCHEMA_INSTANCE_TYPES);
|
|
722
|
-
var encoder = new TextEncoder();
|
|
723
|
-
function cut(value) {
|
|
724
|
-
return value.length <= ISSUE_STRING_MAX_LENGTH ? value : `${value.slice(0, ISSUE_STRING_MAX_LENGTH - 1)}\u2026`;
|
|
725
|
-
}
|
|
726
|
-
var IssueSink = class {
|
|
727
|
-
issues = [];
|
|
728
|
-
truncated = false;
|
|
729
|
-
bytes = 2;
|
|
730
|
-
// "[]"
|
|
731
|
-
add(pointer, keyword, message) {
|
|
732
|
-
const issue = { pointer: cut(pointer), keyword: cut(keyword), message: cut(message) };
|
|
733
|
-
const size2 = encoder.encode(JSON.stringify(issue)).length + (this.issues.length === 0 ? 0 : 1);
|
|
734
|
-
if (this.issues.length >= RESULT_ISSUES_MAX_COUNT || this.bytes + size2 > RESULT_ISSUES_MAX_BYTES) {
|
|
735
|
-
this.truncated = true;
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
this.issues.push(issue);
|
|
739
|
-
this.bytes += size2;
|
|
740
|
-
}
|
|
741
|
-
get empty() {
|
|
742
|
-
return this.issues.length === 0 && !this.truncated;
|
|
743
|
-
}
|
|
744
|
-
};
|
|
745
|
-
function pointerTo(base, token) {
|
|
746
|
-
return `${base}/${String(token).replace(/~/g, "~0").replace(/\//g, "~1")}`;
|
|
747
|
-
}
|
|
748
|
-
function isObject(value) {
|
|
749
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
750
|
-
}
|
|
751
|
-
function isNonNegativeInteger(value) {
|
|
752
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
753
|
-
}
|
|
754
|
-
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
|
|
755
|
-
function hasLoneSurrogate(value) {
|
|
756
|
-
const stack = [value];
|
|
757
|
-
while (stack.length > 0) {
|
|
758
|
-
const node = stack.pop();
|
|
759
|
-
if (typeof node === "string") {
|
|
760
|
-
if (LONE_SURROGATE.test(node)) return true;
|
|
761
|
-
} else if (Array.isArray(node)) {
|
|
762
|
-
for (const member of node) stack.push(member);
|
|
763
|
-
} else if (node !== null && typeof node === "object") {
|
|
764
|
-
for (const [key, member] of Object.entries(node)) {
|
|
765
|
-
if (LONE_SURROGATE.test(key)) return true;
|
|
766
|
-
stack.push(member);
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
return false;
|
|
771
|
-
}
|
|
772
|
-
function canonicalDocument(value, maxBytes) {
|
|
773
|
-
const check = canonicalizePlainJson(value, maxBytes, RESULT_JSON_MAX_DEPTH);
|
|
774
|
-
if (check.ok && hasLoneSurrogate(check.canonical)) return { ok: false, reason: "not-plain-json" };
|
|
775
|
-
return check;
|
|
776
|
-
}
|
|
777
|
-
function documentFailure(check, what, maxBytes) {
|
|
778
|
-
const sink = new IssueSink();
|
|
779
|
-
switch (check.reason) {
|
|
780
|
-
case "not-serializable":
|
|
781
|
-
sink.add("", check.reason, `${what} is not JSON-serializable`);
|
|
782
|
-
return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };
|
|
783
|
-
case "not-plain-json":
|
|
784
|
-
sink.add("", check.reason, `${what} is not plain JSON data in well-formed Unicode`);
|
|
785
|
-
return { ok: false, reason: check.reason, issues: sink.issues, truncated: false };
|
|
786
|
-
case "over-cap":
|
|
787
|
-
sink.add("", check.reason, `${what} is ${check.bytes} bytes as canonical JSON (UTF-8); the cap is ${maxBytes}`);
|
|
788
|
-
return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };
|
|
789
|
-
case "too-deep":
|
|
790
|
-
sink.add("", check.reason, `${what} nests JSON containers deeper than ${RESULT_JSON_MAX_DEPTH}`);
|
|
791
|
-
return { ok: false, reason: check.reason, bytes: check.bytes, issues: sink.issues, truncated: false };
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
function checkSubschema(node, pointer, depth, sink, requireObjectRoot = true) {
|
|
795
|
-
if (!isObject(node)) {
|
|
796
|
-
sink.add(pointer, "schema", "a subschema must be a JSON object");
|
|
797
|
-
return;
|
|
798
|
-
}
|
|
799
|
-
if (depth > RESULT_SCHEMA_MAX_DEPTH) {
|
|
800
|
-
sink.add(pointer, "depth", `subschemas nest deeper than ${RESULT_SCHEMA_MAX_DEPTH} levels`);
|
|
801
|
-
return;
|
|
802
|
-
}
|
|
803
|
-
for (const key of Object.keys(node)) {
|
|
804
|
-
if (!KEYWORDS.has(key)) sink.add(pointerTo(pointer, key), key, "keyword is outside the result schema subset");
|
|
805
|
-
}
|
|
806
|
-
if (requireObjectRoot && depth === 0 && node.type !== "object") {
|
|
807
|
-
sink.add(pointerTo(pointer, "type"), "type", "the root schema must declare type: 'object'");
|
|
808
|
-
}
|
|
809
|
-
if (Object.hasOwn(node, "type")) {
|
|
810
|
-
const type = node.type;
|
|
811
|
-
const valid = typeof type === "string" ? INSTANCE_TYPES.has(type) : Array.isArray(type) && type.length > 0 && type.every((member) => typeof member === "string" && INSTANCE_TYPES.has(member)) && new Set(type).size === type.length;
|
|
812
|
-
if (!valid) sink.add(pointerTo(pointer, "type"), "type", "must be a JSON type name or a non-empty array of unique type names");
|
|
813
|
-
}
|
|
814
|
-
if (Object.hasOwn(node, "properties")) {
|
|
815
|
-
const properties = node.properties;
|
|
816
|
-
const at = pointerTo(pointer, "properties");
|
|
817
|
-
if (!isObject(properties)) sink.add(at, "properties", "must be an object of subschemas");
|
|
818
|
-
else for (const [name, subschema] of Object.entries(properties)) checkSubschema(subschema, pointerTo(at, name), depth + 1, sink);
|
|
819
|
-
}
|
|
820
|
-
if (Object.hasOwn(node, "required")) {
|
|
821
|
-
const required = node.required;
|
|
822
|
-
if (!Array.isArray(required) || !required.every((name) => typeof name === "string") || new Set(required).size !== required.length) {
|
|
823
|
-
sink.add(pointerTo(pointer, "required"), "required", "must be an array of unique property names");
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
if (Object.hasOwn(node, "additionalProperties") && node.additionalProperties !== false) {
|
|
827
|
-
sink.add(pointerTo(pointer, "additionalProperties"), "additionalProperties", "only additionalProperties: false is allowed");
|
|
828
|
-
}
|
|
829
|
-
if (Object.hasOwn(node, "items")) {
|
|
830
|
-
if (!isObject(node.items)) sink.add(pointerTo(pointer, "items"), "items", "must be one subschema object");
|
|
831
|
-
else checkSubschema(node.items, pointerTo(pointer, "items"), depth + 1, sink);
|
|
832
|
-
}
|
|
833
|
-
if (Object.hasOwn(node, "enum") && (!Array.isArray(node.enum) || node.enum.length === 0)) {
|
|
834
|
-
sink.add(pointerTo(pointer, "enum"), "enum", "must be a non-empty array");
|
|
835
|
-
}
|
|
836
|
-
if (Object.hasOwn(node, "oneOf")) {
|
|
837
|
-
const oneOf = node.oneOf;
|
|
838
|
-
const at = pointerTo(pointer, "oneOf");
|
|
839
|
-
if (!Array.isArray(oneOf) || oneOf.length === 0) sink.add(at, "oneOf", "must be a non-empty array of subschemas");
|
|
840
|
-
else oneOf.forEach((subschema, index) => checkSubschema(subschema, pointerTo(at, index), depth + 1, sink));
|
|
841
|
-
}
|
|
842
|
-
for (const keyword of ["minLength", "maxLength", "minItems", "maxItems"]) {
|
|
843
|
-
if (Object.hasOwn(node, keyword) && !isNonNegativeInteger(node[keyword])) {
|
|
844
|
-
sink.add(pointerTo(pointer, keyword), keyword, "must be a non-negative integer");
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
for (const keyword of ["minimum", "maximum"]) {
|
|
848
|
-
if (Object.hasOwn(node, keyword) && typeof node[keyword] !== "number") {
|
|
849
|
-
sink.add(pointerTo(pointer, keyword), keyword, "must be a number");
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
if (Object.hasOwn(node, "description") && typeof node.description !== "string") {
|
|
853
|
-
sink.add(pointerTo(pointer, "description"), "description", "must be a string");
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
function checkResultSchema(schema) {
|
|
857
|
-
const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);
|
|
858
|
-
if (!document.ok) return documentFailure(document, "the result schema", RESULT_SCHEMA_MAX_BYTES);
|
|
859
|
-
const sink = new IssueSink();
|
|
860
|
-
checkSubschema(document.canonical, "", 0, sink);
|
|
861
|
-
if (!sink.empty) return { ok: false, reason: "not-subset", bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };
|
|
862
|
-
return { ok: true, bytes: document.bytes, canonical: document.canonical };
|
|
863
|
-
}
|
|
864
|
-
function withoutPrototypes(value) {
|
|
865
|
-
if (value === null || typeof value !== "object") return value;
|
|
866
|
-
if (Array.isArray(value)) return value.map(withoutPrototypes);
|
|
867
|
-
const copy = /* @__PURE__ */ Object.create(null);
|
|
868
|
-
for (const [key, member] of Object.entries(value)) {
|
|
869
|
-
Object.defineProperty(copy, key, { value: withoutPrototypes(member), enumerable: true, writable: true, configurable: true });
|
|
870
|
-
}
|
|
871
|
-
return copy;
|
|
872
|
-
}
|
|
873
|
-
function fragmentToPointer(location) {
|
|
874
|
-
return decodeURI(location.startsWith("#") ? location.slice(1) : location);
|
|
875
|
-
}
|
|
876
|
-
function validateResultOutcome(schema, outcome) {
|
|
877
|
-
const admitted = checkResultSchema(schema);
|
|
878
|
-
if (!admitted.ok) {
|
|
879
|
-
return { ok: false, reason: "schema-not-admitted", bytes: admitted.bytes, issues: admitted.issues, truncated: admitted.truncated };
|
|
880
|
-
}
|
|
881
|
-
const document = canonicalDocument(outcome, RESULT_OUTCOME_MAX_BYTES);
|
|
882
|
-
if (!document.ok) return documentFailure(document, "the outcome", RESULT_OUTCOME_MAX_BYTES);
|
|
883
|
-
const validator = new Validator(withoutPrototypes(admitted.canonical), "2020-12", true);
|
|
884
|
-
const result = validator.validate(withoutPrototypes(document.canonical));
|
|
885
|
-
if (result.valid) return { ok: true, bytes: document.bytes, canonical: document.canonical };
|
|
886
|
-
const sink = new IssueSink();
|
|
887
|
-
for (const unit of result.errors) sink.add(fragmentToPointer(unit.instanceLocation), unit.keyword, unit.error);
|
|
888
|
-
return { ok: false, reason: "schema-mismatch", bytes: document.bytes, issues: sink.issues, truncated: sink.truncated };
|
|
889
|
-
}
|
|
890
|
-
var MAX_BYTES_PER_CODE_POINT = 6;
|
|
891
|
-
var MAX_NUMBER_BYTES = 25;
|
|
892
|
-
var MAX_INTEGER_BYTES = 24;
|
|
893
|
-
var DECIMAL_LIMIT = 1e21;
|
|
894
|
-
var enc = new TextEncoder();
|
|
895
|
-
var size = (v) => enc.encode(JSON.stringify(v)).length;
|
|
896
|
-
function typeBound(node, type) {
|
|
897
|
-
switch (type) {
|
|
898
|
-
case "null":
|
|
899
|
-
return 4;
|
|
900
|
-
case "boolean":
|
|
901
|
-
return 5;
|
|
902
|
-
case "integer": {
|
|
903
|
-
const lo = typeof node.minimum === "number" ? Math.ceil(node.minimum) : void 0;
|
|
904
|
-
const hi = typeof node.maximum === "number" ? Math.floor(node.maximum) : void 0;
|
|
905
|
-
if (lo === void 0 || hi === void 0 || !(Math.abs(lo) < DECIMAL_LIMIT) || !(Math.abs(hi) < DECIMAL_LIMIT)) return MAX_INTEGER_BYTES;
|
|
906
|
-
return Math.min(MAX_INTEGER_BYTES, Math.max(String(lo).length, String(hi).length));
|
|
907
|
-
}
|
|
908
|
-
case "number":
|
|
909
|
-
return MAX_NUMBER_BYTES;
|
|
910
|
-
case "string":
|
|
911
|
-
return typeof node.maxLength === "number" ? 2 + MAX_BYTES_PER_CODE_POINT * node.maxLength : null;
|
|
912
|
-
case "array": {
|
|
913
|
-
if (node.maxItems === 0) return 2;
|
|
914
|
-
if (typeof node.maxItems !== "number" || node.items === void 0) return null;
|
|
915
|
-
const item = outcomeBound(node.items);
|
|
916
|
-
return item === null ? null : 2 + node.maxItems * item + Math.max(0, node.maxItems - 1);
|
|
917
|
-
}
|
|
918
|
-
case "object": {
|
|
919
|
-
if (node.additionalProperties !== false) return null;
|
|
920
|
-
const entries = Object.entries(node.properties ?? {});
|
|
921
|
-
let total = 2 + Math.max(0, entries.length - 1);
|
|
922
|
-
for (const [name, sub] of entries) {
|
|
923
|
-
const b = outcomeBound(sub);
|
|
924
|
-
if (b === null) return null;
|
|
925
|
-
total += size(name) + 1 + b;
|
|
926
|
-
}
|
|
927
|
-
return total;
|
|
928
|
-
}
|
|
929
|
-
default:
|
|
930
|
-
return null;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
function outcomeBound(schema) {
|
|
934
|
-
const node = schema;
|
|
935
|
-
const bounds = [];
|
|
936
|
-
if (Object.hasOwn(node, "const")) bounds.push(size(node.const));
|
|
937
|
-
if (Array.isArray(node.enum)) bounds.push(Math.max(...node.enum.map(size)));
|
|
938
|
-
if (Array.isArray(node.oneOf)) {
|
|
939
|
-
const branches = node.oneOf.map(outcomeBound);
|
|
940
|
-
if (branches.every((b) => b !== null)) bounds.push(Math.max(...branches));
|
|
941
|
-
}
|
|
942
|
-
if (node.type !== void 0) {
|
|
943
|
-
const types = Array.isArray(node.type) ? node.type : [node.type];
|
|
944
|
-
const each = types.map((t) => typeBound(node, t));
|
|
945
|
-
if (each.every((b) => b !== null)) bounds.push(Math.max(...each));
|
|
946
|
-
}
|
|
947
|
-
return bounds.length === 0 ? null : Math.min(...bounds);
|
|
948
|
-
}
|
|
949
|
-
function resultOutcomeMaxBytes(schema) {
|
|
950
|
-
const pending = [schema];
|
|
951
|
-
const seen = /* @__PURE__ */ new Set();
|
|
952
|
-
while (pending.length > 0) {
|
|
953
|
-
const value = pending.pop();
|
|
954
|
-
if (typeof value === "function") return null;
|
|
955
|
-
if (value === null || typeof value !== "object" || seen.has(value)) continue;
|
|
956
|
-
seen.add(value);
|
|
957
|
-
const prototype = Object.getPrototypeOf(value);
|
|
958
|
-
if (prototype !== null && prototype !== Object.prototype && prototype !== Array.prototype) return null;
|
|
959
|
-
for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
|
|
960
|
-
if (name === "toJSON" && (!Object.hasOwn(descriptor, "value") || typeof descriptor.value === "function")) return null;
|
|
961
|
-
if (!descriptor.enumerable) continue;
|
|
962
|
-
if (!Object.hasOwn(descriptor, "value")) return null;
|
|
963
|
-
pending.push(descriptor.value);
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
const document = canonicalDocument(schema, RESULT_SCHEMA_MAX_BYTES);
|
|
967
|
-
if (!document.ok) return null;
|
|
968
|
-
const sink = new IssueSink();
|
|
969
|
-
checkSubschema(document.canonical, "", 0, sink, false);
|
|
970
|
-
if (!sink.empty) return null;
|
|
971
|
-
return outcomeBound(document.canonical);
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
// src/terminal-projection.ts
|
|
975
|
-
var TerminalProjectionContractSchema = z.string().min(1).max(128).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, "terminal projection contracts must be opaque lowercase ids");
|
|
976
|
-
var ResultDocumentSchemaSchema = z.custom().superRefine((value, ctx) => {
|
|
977
|
-
const check = checkResultSchema(value);
|
|
978
|
-
if (check.ok) return;
|
|
979
|
-
for (const issue of check.issues) {
|
|
980
|
-
ctx.addIssue({
|
|
981
|
-
code: "custom",
|
|
982
|
-
message: `result schema ${check.reason} at '${issue.pointer}' (${issue.keyword}): ${issue.message}`,
|
|
983
|
-
params: { reason: check.reason, pointer: issue.pointer, keyword: issue.keyword }
|
|
984
|
-
});
|
|
985
|
-
}
|
|
986
|
-
if (check.truncated) {
|
|
987
|
-
ctx.addIssue({ code: "custom", message: "result schema issues truncated", params: { reason: check.reason, truncated: true } });
|
|
988
|
-
}
|
|
989
|
-
});
|
|
990
|
-
var TerminalProjectionSelectionSchema = z.discriminatedUnion("mode", [
|
|
991
|
-
z.object({ mode: z.literal("none") }).strict(),
|
|
992
|
-
z.object({
|
|
993
|
-
mode: z.literal("result-document"),
|
|
994
|
-
contract: TerminalProjectionContractSchema,
|
|
995
|
-
schema: ResultDocumentSchemaSchema
|
|
996
|
-
}).strict()
|
|
997
|
-
]);
|
|
998
|
-
var POLICY_REVISION = z.string().min(1).max(160).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u, "policyRevision must not contain control characters");
|
|
999
|
-
var POSITIVE_LIMIT = z.number().int().positive().max(2147483647);
|
|
1000
|
-
var AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES = 16 * 1024;
|
|
1001
|
-
var AGENT_MESSAGE_MAX_BYTES = 256 * 1024;
|
|
1002
|
-
var AgentMessageContractSchema = z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u, "message contract must be an opaque portable identifier");
|
|
1003
|
-
var AgentMessageContentTypeSchema = z.enum(["text/plain", "text/markdown"]);
|
|
1004
|
-
var AgentMessageDestinationBindingSchema = z.string().min(1).max(2048).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u, "destination binding must not contain control characters");
|
|
1005
|
-
var AgentMessageFreshnessCursorSchema = z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u, "freshness cursor must not contain control characters");
|
|
1006
|
-
var AgentMessageServerContextSchema = z.object({
|
|
1007
|
-
destinationBinding: AgentMessageDestinationBindingSchema,
|
|
1008
|
-
freshnessCursor: AgentMessageFreshnessCursorSchema.optional()
|
|
1009
|
-
}).strict();
|
|
1010
|
-
var AgentMessageEgressRequirementSchema = z.object({
|
|
1011
|
-
mode: z.literal("required"),
|
|
1012
|
-
contract: AgentMessageContractSchema,
|
|
1013
|
-
contentType: AgentMessageContentTypeSchema,
|
|
1014
|
-
maxBytes: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES)
|
|
1015
|
-
}).strict();
|
|
1016
|
-
var AgentContentMimeTypeSchema = z.string().min(3).max(255).regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/iu, "MIME types must be explicit type/subtype values");
|
|
1017
|
-
var ContentReadPolicySchema = z.object({
|
|
1018
|
-
maxBytes: POSITIVE_LIMIT,
|
|
1019
|
-
allowedMimeTypes: z.array(AgentContentMimeTypeSchema).min(1).max(32)
|
|
1020
|
-
}).strict();
|
|
1021
|
-
var AgentEgressActivityPolicySchema = z.object({
|
|
1022
|
-
delivery: z.literal("latest-value"),
|
|
1023
|
-
maxCoalesceMs: POSITIVE_LIMIT,
|
|
1024
|
-
maxEventBytes: POSITIVE_LIMIT
|
|
1025
|
-
}).strict();
|
|
1026
|
-
var AgentReliableQuotaPolicySchema = z.object({
|
|
1027
|
-
maxPendingEventsPerAgent: POSITIVE_LIMIT,
|
|
1028
|
-
maxPendingBytesPerAgent: POSITIVE_LIMIT,
|
|
1029
|
-
maxPendingBytesPerTenant: POSITIVE_LIMIT
|
|
1030
|
-
}).strict();
|
|
1031
|
-
var AgentEgressPolicySchema = z.object({
|
|
1032
|
-
policyRevision: POLICY_REVISION,
|
|
1033
|
-
activity: AgentEgressActivityPolicySchema,
|
|
1034
|
-
reliable: AgentReliableQuotaPolicySchema,
|
|
1035
|
-
transfers: z.object({
|
|
1036
|
-
workspace: z.union([z.literal("disabled"), ContentReadPolicySchema]),
|
|
1037
|
-
transcript: z.union([z.literal("disabled"), ContentReadPolicySchema]),
|
|
1038
|
-
artifact: z.union([z.literal("disabled"), ContentReadPolicySchema])
|
|
1039
|
-
}).strict()
|
|
1040
|
-
}).strict();
|
|
1041
|
-
var AgentEgressLaneSchema = z.enum(["reliable", "latest-value"]);
|
|
1042
|
-
var AgentEgressDropReasonSchema = z.enum([
|
|
1043
|
-
"policy_denied",
|
|
1044
|
-
"capability_missing",
|
|
1045
|
-
"quota_exceeded",
|
|
1046
|
-
"backpressure",
|
|
1047
|
-
"coalesced",
|
|
1048
|
-
"disconnected",
|
|
1049
|
-
"invalid_envelope",
|
|
1050
|
-
"ack_mismatch"
|
|
1051
|
-
]);
|
|
1052
|
-
var AgentContentReadSurfaceSchema = z.enum(["workspace", "transcript", "artifact"]);
|
|
1053
|
-
var AgentContentActorKindSchema = z.enum(["user", "agent", "system"]);
|
|
1054
|
-
var AgentContentActorSchema = z.object({
|
|
1055
|
-
kind: AgentContentActorKindSchema,
|
|
1056
|
-
id: z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f]+$/u, "actor id must not contain control characters")
|
|
1057
|
-
}).strict();
|
|
1058
|
-
var AgentContentDecodeAsSchema = z.enum(["bytes", "utf8"]);
|
|
1059
|
-
var AgentContentReadDecisionSchema = z.enum(["allowed", "denied"]);
|
|
1060
|
-
var AgentContentReadDenialReasonSchema = z.enum([
|
|
1061
|
-
"invalid-request",
|
|
1062
|
-
"policy-disabled",
|
|
1063
|
-
"capability-missing",
|
|
1064
|
-
"policy-revision-mismatch",
|
|
1065
|
-
"absolute-target",
|
|
1066
|
-
"non-relative-target",
|
|
1067
|
-
"dot-segment",
|
|
1068
|
-
"sensitive-name",
|
|
1069
|
-
"root-not-allowlisted",
|
|
1070
|
-
"root-invalid",
|
|
1071
|
-
"path-escape",
|
|
1072
|
-
"target-missing",
|
|
1073
|
-
"symlink",
|
|
1074
|
-
"not-regular-file",
|
|
1075
|
-
"byte-limit",
|
|
1076
|
-
"mime-not-allowlisted",
|
|
1077
|
-
"text-not-allowlisted",
|
|
1078
|
-
"text-decode-failed",
|
|
1079
|
-
"identity-mismatch"
|
|
1080
|
-
]);
|
|
1081
|
-
var AgentEgressContentHashSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/u, "contentHash must be a lowercase SHA-256 digest");
|
|
1082
|
-
var AgentEgressPolicyRevisionSchema = POLICY_REVISION;
|
|
1083
|
-
|
|
1084
|
-
// src/input-preparation.ts
|
|
1085
|
-
var InputPreparationContentHashSchema = AgentEgressContentHashSchema;
|
|
1086
|
-
var OPAQUE_ID = z.string().min(1).max(512).regex(/^[^\u0000-\u001f\u007f]+$/u, "control identifiers must not contain control characters");
|
|
1087
|
-
var OPAQUE_TEXT = z.string().min(1).max(2048).regex(/^[^\u0000-\u001f\u007f]+$/u, "control text must not contain control characters");
|
|
1088
|
-
var InputPreparationPolicyRevisionSchema = OPAQUE_ID;
|
|
1089
|
-
var InputPreparationProfileIdSchema = OPAQUE_ID;
|
|
1090
|
-
var PreparedAgentMemoryModeSchema = z.enum(PREPARED_AGENT_MEMORY_MODES);
|
|
1091
|
-
var InputPreparationSourceSchema = z.object({ revision: OPAQUE_ID, digest: OPAQUE_ID }).strict();
|
|
1092
|
-
var InputPreparationModelCostSchema = z.object({
|
|
1093
|
-
input: z.number().finite(),
|
|
1094
|
-
output: z.number().finite(),
|
|
1095
|
-
cacheRead: z.number().finite(),
|
|
1096
|
-
cacheWrite: z.number().finite()
|
|
1097
|
-
}).strict();
|
|
1098
|
-
var THINKING_EFFORT = z.string().min(1).max(64).regex(/^[a-zA-Z0-9_-]+$/u).nullable();
|
|
1099
|
-
var InputPreparationThinkingLevelMapSchema = z.object({
|
|
1100
|
-
off: THINKING_EFFORT,
|
|
1101
|
-
minimal: THINKING_EFFORT,
|
|
1102
|
-
low: THINKING_EFFORT,
|
|
1103
|
-
medium: THINKING_EFFORT,
|
|
1104
|
-
high: THINKING_EFFORT,
|
|
1105
|
-
xhigh: THINKING_EFFORT,
|
|
1106
|
-
max: THINKING_EFFORT
|
|
1107
|
-
}).strict();
|
|
1108
|
-
var InputPreparationModelCompatSchema = z.object({
|
|
1109
|
-
supportsStore: z.boolean().optional(),
|
|
1110
|
-
supportsDeveloperRole: z.boolean().optional(),
|
|
1111
|
-
supportsReasoningEffort: z.boolean().optional(),
|
|
1112
|
-
supportsUsageInStreaming: z.boolean().optional(),
|
|
1113
|
-
maxTokensField: z.enum(["max_completion_tokens", "max_tokens"]).optional(),
|
|
1114
|
-
thinkingFormat: z.enum([
|
|
1115
|
-
"openai",
|
|
1116
|
-
"openrouter",
|
|
1117
|
-
"deepseek",
|
|
1118
|
-
"together",
|
|
1119
|
-
"baseten",
|
|
1120
|
-
"zai",
|
|
1121
|
-
"qwen",
|
|
1122
|
-
"chat-template",
|
|
1123
|
-
"qwen-chat-template",
|
|
1124
|
-
"string-thinking",
|
|
1125
|
-
"ant-ling"
|
|
1126
|
-
]).optional(),
|
|
1127
|
-
zaiToolStream: z.boolean().optional()
|
|
1128
|
-
}).strict();
|
|
1129
|
-
var InputPreparationModelSchema = z.object({
|
|
1130
|
-
id: OPAQUE_ID,
|
|
1131
|
-
name: OPAQUE_ID,
|
|
1132
|
-
api: z.literal("openai-completions"),
|
|
1133
|
-
provider: OPAQUE_ID,
|
|
1134
|
-
baseUrl: OPAQUE_TEXT,
|
|
1135
|
-
reasoning: z.boolean(),
|
|
1136
|
-
input: z.array(z.enum(["text", "image"])).min(1).max(8),
|
|
1137
|
-
cost: InputPreparationModelCostSchema,
|
|
1138
|
-
contextWindow: z.number().int().positive(),
|
|
1139
|
-
maxTokens: z.number().int().positive(),
|
|
1140
|
-
thinkingLevelMap: InputPreparationThinkingLevelMapSchema.optional(),
|
|
1141
|
-
compat: InputPreparationModelCompatSchema.optional()
|
|
1142
|
-
}).strict();
|
|
1143
|
-
var InputPreparationOptionsSchema = z.object({
|
|
1144
|
-
cacheRetention: z.enum(["none", "short", "long"]),
|
|
1145
|
-
maxTokens: z.number().int().positive(),
|
|
1146
|
-
temperature: z.number().finite().optional(),
|
|
1147
|
-
toolChoice: z.enum(["auto", "none"]).optional(),
|
|
1148
|
-
reasoningEffort: z.enum(["minimal", "low", "medium", "high", "xhigh", "max"]).optional()
|
|
1149
|
-
}).strict();
|
|
1150
|
-
var InputPreparationSelectionSchema = z.object({ model: InputPreparationModelSchema, options: InputPreparationOptionsSchema }).strict();
|
|
1151
|
-
var InputPreparationPromptSnapshotSchema = z.object({ systemPrompt: z.string() }).strict();
|
|
1152
|
-
var InputPreparationUserMessageSchema = z.object({
|
|
1153
|
-
role: z.literal("user"),
|
|
1154
|
-
content: z.string(),
|
|
1155
|
-
timestamp: z.number().int()
|
|
1156
|
-
}).strict();
|
|
1157
|
-
var InputPreparationHostCanonicalAssistantMessageSchema = z.object({
|
|
1158
|
-
role: z.literal("assistant"),
|
|
1159
|
-
origin: z.literal("host_canonical"),
|
|
1160
|
-
content: z.string(),
|
|
1161
|
-
timestamp: z.number().int()
|
|
1162
|
-
}).strict();
|
|
1163
|
-
var InputPreparationMessageSchema = z.discriminatedUnion("role", [
|
|
1164
|
-
InputPreparationUserMessageSchema,
|
|
1165
|
-
InputPreparationHostCanonicalAssistantMessageSchema
|
|
1166
|
-
]);
|
|
1167
|
-
var InputPreparationContextDocumentSchema = z.object({
|
|
1168
|
-
prompt: InputPreparationPromptSnapshotSchema,
|
|
1169
|
-
messages: z.array(InputPreparationMessageSchema).max(4096)
|
|
1170
|
-
}).strict();
|
|
1171
|
-
var InputPreparationStateSchema = z.enum([
|
|
1172
|
-
"reserved",
|
|
1173
|
-
"counting",
|
|
1174
|
-
"prepared",
|
|
1175
|
-
"cancelled",
|
|
1176
|
-
"failed",
|
|
1177
|
-
"counter_interrupted"
|
|
1178
|
-
]);
|
|
1179
|
-
var InputPreparationReadinessReasonSchema = z.enum([
|
|
1180
|
-
/** The record has not reached `prepared` (it is `reserved` or `counting`). */
|
|
1181
|
-
"not_prepared",
|
|
1182
|
-
"counter_interrupted",
|
|
1183
|
-
"cancelled",
|
|
1184
|
-
"failed",
|
|
1185
|
-
"artifact_expired",
|
|
1186
|
-
/** A counter IS present and its authority is not `provider` (a fixture never reaches ready). */
|
|
1187
|
-
"counter_authority_not_production",
|
|
1188
|
-
/** A counter IS present and it reported its projection as not covered. */
|
|
1189
|
-
"counter_coverage_incomplete",
|
|
1190
|
-
/**
|
|
1191
|
-
* D, the frozen provider request, carries a message content part whose
|
|
1192
|
-
* `type` is not `text`. The first release admits text-only D; a multimodal
|
|
1193
|
-
* part is not sized by `requestBytes` in any way the Host's ruling covers.
|
|
1194
|
-
*/
|
|
1195
|
-
"request_content_not_text",
|
|
1196
|
-
/** The native compiler's projection kind is not `content_complete`. */
|
|
1197
|
-
"projection_unknown",
|
|
1198
|
-
/** The artifact carries a residual key the accounting policy does not rule on. */
|
|
1199
|
-
"residual_not_ruled",
|
|
1200
|
-
/** The request named no accounting policy. There is no default. */
|
|
1201
|
-
"accounting_policy_missing",
|
|
1202
|
-
/** The named policy was ruled for a different runtime, endpoint or model. */
|
|
1203
|
-
"accounting_policy_inapplicable",
|
|
1204
|
-
/**
|
|
1205
|
-
* The record was prepared against a runtime contract this build no longer
|
|
1206
|
-
* speaks: its binding declares a prepared-compiler version other than the one
|
|
1207
|
-
* this build prepares and consumes against. The artifact is not re-read
|
|
1208
|
-
* through the current contract and is not translated — a projection frozen
|
|
1209
|
-
* under another compiler's classification table is evidence about a request
|
|
1210
|
-
* this build cannot re-derive.
|
|
1211
|
-
*/
|
|
1212
|
-
"runtime_contract_superseded"
|
|
1213
|
-
]);
|
|
1214
|
-
var InputPreparationRuntimeIdentitySchema = z.object({
|
|
1215
|
-
packageName: OPAQUE_ID,
|
|
1216
|
-
packageVersion: OPAQUE_ID,
|
|
1217
|
-
tarballIntegrity: z.string().regex(/^sha512-[A-Za-z0-9+/]+={0,2}$/u),
|
|
1218
|
-
provenanceDigest: z.string().regex(/^[0-9a-f]{64}$/u),
|
|
1219
|
-
closureDigest: z.string().regex(/^[0-9a-f]{64}$/u),
|
|
1220
|
-
upstreamCommit: OPAQUE_ID,
|
|
1221
|
-
envelopeFormat: OPAQUE_ID,
|
|
1222
|
-
requestFormat: OPAQUE_ID,
|
|
1223
|
-
compilerVersion: z.number().int().nonnegative()
|
|
1224
|
-
}).strict();
|
|
1225
|
-
var InputPreparationCounterTargetSchema = z.object({ endpoint: OPAQUE_TEXT, modelId: OPAQUE_ID }).strict();
|
|
1226
|
-
var InputPreparationAccountingPolicyRefSchema = z.object({
|
|
1227
|
-
revision: OPAQUE_ID,
|
|
1228
|
-
/** The runtime identity string this ruling was made for. */
|
|
1229
|
-
ruledRuntime: OPAQUE_ID,
|
|
1230
|
-
/** The endpoint/model this ruling was made for. */
|
|
1231
|
-
ruledTarget: InputPreparationCounterTargetSchema,
|
|
1232
|
-
/** Every residual key the Host's accounting already accounts for. */
|
|
1233
|
-
ruledResidualKeys: z.array(OPAQUE_ID).max(64)
|
|
1234
|
-
}).strict();
|
|
1235
|
-
var InputPreparationCounterProviderEvidenceSchema = z.object({
|
|
1236
|
-
projectionDigest: z.string().regex(/^[0-9a-f]{64}$/u, "a projection digest is lowercase sha-256 hex"),
|
|
1237
|
-
endpoint: OPAQUE_TEXT,
|
|
1238
|
-
modelId: OPAQUE_ID,
|
|
1239
|
-
asserted: z.object({
|
|
1240
|
-
httpStatus: z.number().int(),
|
|
1241
|
-
usageFields: z.record(OPAQUE_ID, z.number().finite()),
|
|
1242
|
-
responseDigest: OPAQUE_ID
|
|
1243
|
-
}).strict()
|
|
1244
|
-
}).strict();
|
|
1245
|
-
var InputPreparationCounterEvidenceSchema = z.object({
|
|
1246
|
-
method: OPAQUE_ID,
|
|
1247
|
-
methodVersion: OPAQUE_ID,
|
|
1248
|
-
authority: z.enum(["provider", "test_fixture"]),
|
|
1249
|
-
value: z.number().int().nonnegative(),
|
|
1250
|
-
coverage: z.object({ covered: z.boolean(), reason: z.string().max(512).optional() }).strict(),
|
|
1251
|
-
providerEvidence: InputPreparationCounterProviderEvidenceSchema,
|
|
1252
|
-
target: InputPreparationCounterTargetSchema,
|
|
1253
|
-
calledAt: z.iso.datetime({ offset: true }),
|
|
1254
|
-
completedAt: z.iso.datetime({ offset: true })
|
|
1255
|
-
}).strict();
|
|
1256
|
-
var InputPreparationResidualValueClassSchema = z.enum([
|
|
1257
|
-
"constant",
|
|
1258
|
-
"boolean",
|
|
1259
|
-
"bounded_integer",
|
|
1260
|
-
"bounded_number",
|
|
1261
|
-
"finite_number",
|
|
1262
|
-
"closed_enum",
|
|
1263
|
-
"nonempty_string",
|
|
1264
|
-
"object_shape"
|
|
1265
|
-
]);
|
|
1266
|
-
var InputPreparationResidualKeySchema = z.object({ key: OPAQUE_ID, valueClass: InputPreparationResidualValueClassSchema }).strict();
|
|
1267
|
-
var InputPreparationProjectionSchema = z.object({
|
|
1268
|
-
version: z.literal(3),
|
|
1269
|
-
kind: z.enum(["content_complete", "unknown"]),
|
|
1270
|
-
digest: z.string().regex(/^[0-9a-f]{64}$/u, "a projection digest is lowercase sha-256 hex")
|
|
1271
|
-
}).strict();
|
|
1272
|
-
var InputPreparationArtifactSummarySchema = z.object({
|
|
1273
|
-
requestDigest: OPAQUE_ID,
|
|
1274
|
-
envelopeDigest: OPAQUE_ID,
|
|
1275
|
-
toolManifestDigest: OPAQUE_ID,
|
|
1276
|
-
/**
|
|
1277
|
-
* The exact UTF-8 byte length of the frozen provider request D, measured
|
|
1278
|
-
* by the device's own compiler. The ONE size evidence a receipt carries:
|
|
1279
|
-
* the Host rules the budget (`requestBytes + C + max_tokens <= window`)
|
|
1280
|
-
* against it. Never a token count and never an estimate.
|
|
1281
|
-
*/
|
|
1282
|
-
requestBytes: z.number().int().nonnegative(),
|
|
1283
|
-
projectionBytes: z.number().int().nonnegative(),
|
|
1284
|
-
projection: InputPreparationProjectionSchema,
|
|
1285
|
-
residual: z.array(InputPreparationResidualKeySchema).max(64),
|
|
1286
|
-
observationDigest: OPAQUE_ID,
|
|
1287
|
-
toolBindingDigest: OPAQUE_ID,
|
|
1288
|
-
toolNames: z.array(OPAQUE_ID)
|
|
1289
|
-
}).strict();
|
|
1290
|
-
var InputPreparationBindingSchema = z.object({
|
|
1291
|
-
terminalProjection: TerminalProjectionSelectionSchema.optional(),
|
|
1292
|
-
agentMemory: PreparedAgentMemoryModeSchema,
|
|
1293
|
-
scopeId: OPAQUE_ID,
|
|
1294
|
-
deviceId: OPAQUE_ID,
|
|
1295
|
-
agentRef: OPAQUE_ID,
|
|
1296
|
-
profileId: OPAQUE_ID,
|
|
1297
|
-
profileRevision: OPAQUE_ID,
|
|
1298
|
-
source: InputPreparationSourceSchema,
|
|
1299
|
-
target: InputPreparationCounterTargetSchema,
|
|
1300
|
-
policyRevision: OPAQUE_ID,
|
|
1301
|
-
runtime: InputPreparationRuntimeIdentitySchema,
|
|
1302
|
-
requestDigest: OPAQUE_ID,
|
|
1303
|
-
/**
|
|
1304
|
-
* The Host's accounting ruling this preparation was requested under,
|
|
1305
|
-
* copied verbatim. Absent when the request named none — never filled in,
|
|
1306
|
-
* and never narrowed to one the device would have chosen.
|
|
1307
|
-
*/
|
|
1308
|
-
accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional()
|
|
1309
|
-
}).strict();
|
|
1310
|
-
var InputPreparationReceiptSummarySchema = z.object({
|
|
1311
|
-
reference: OPAQUE_ID,
|
|
1312
|
-
state: InputPreparationStateSchema,
|
|
1313
|
-
binding: InputPreparationBindingSchema,
|
|
1314
|
-
artifact: InputPreparationArtifactSummarySchema.optional(),
|
|
1315
|
-
counter: InputPreparationCounterEvidenceSchema.optional(),
|
|
1316
|
-
ready: z.boolean(),
|
|
1317
|
-
readinessReasons: z.array(InputPreparationReadinessReasonSchema).max(16),
|
|
1318
|
-
detail: OPAQUE_ID.optional(),
|
|
1319
|
-
artifactExpiresAt: z.iso.datetime({ offset: true })
|
|
1320
|
-
}).strict().superRefine((value, ctx) => {
|
|
1321
|
-
if (value.ready !== (value.readinessReasons.length === 0)) {
|
|
1322
|
-
ctx.addIssue({
|
|
1323
|
-
code: "custom",
|
|
1324
|
-
path: ["ready"],
|
|
1325
|
-
message: "ready must be true exactly when readinessReasons is empty"
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
});
|
|
1329
|
-
var InputPreparationReferenceSchema = OPAQUE_ID;
|
|
1330
|
-
var InputPreparationOfferBindingSchema = z.object({
|
|
1331
|
-
reference: InputPreparationReferenceSchema,
|
|
1332
|
-
/** `InputPreparationBindingSchema.requestDigest`, as the receipt reported it. */
|
|
1333
|
-
requestDigest: OPAQUE_ID,
|
|
1334
|
-
/** `InputPreparationArtifactSummarySchema.envelopeDigest`, when the receipt carried one. */
|
|
1335
|
-
artifactDigest: OPAQUE_ID.optional()
|
|
1336
|
-
}).strict();
|
|
1337
|
-
var InputPreparationRejectionReasonSchema = z.enum([
|
|
1338
|
-
"input_preparation_unconfigured",
|
|
1339
|
-
"bad_request",
|
|
1340
|
-
"authority_unavailable",
|
|
1341
|
-
"scope_denied",
|
|
1342
|
-
"policy_revision_mismatch",
|
|
1343
|
-
"runtime_identity_unavailable",
|
|
1344
|
-
"unsupported_input",
|
|
1345
|
-
"limit_exceeded",
|
|
1346
|
-
"request_conflict",
|
|
1347
|
-
"not_found",
|
|
1348
|
-
"counter_unavailable",
|
|
1349
|
-
"counter_interrupted",
|
|
1350
|
-
"durable_write_failed",
|
|
1351
|
-
"cancelled",
|
|
1352
|
-
"context_unresolvable",
|
|
1353
|
-
"context_hash_mismatch",
|
|
1354
|
-
"toolsets_unobservable",
|
|
1355
|
-
"deadline_elapsed",
|
|
1356
|
-
/**
|
|
1357
|
-
* A repeat of an already-recorded `requestId` arrived after the facts its
|
|
1358
|
-
* executor fingerprints were frozen against changed — a toolset definition
|
|
1359
|
-
* revision or a configured server argv. The recorded receipt is not re-derived and no
|
|
1360
|
-
* server is re-probed; the repeat is refused so the caller mints a new
|
|
1361
|
-
* preparation instead of silently receiving one bound to stale evidence.
|
|
1362
|
-
*/
|
|
1363
|
-
"observation_drift",
|
|
1364
|
-
/**
|
|
1365
|
-
* The device compiled the input, then found that the `prompt_prepared` frame
|
|
1366
|
-
* the runtime would have to be handed exceeds the single-frame byte cap that
|
|
1367
|
-
* runtime enforces. The bound belongs to the runtime, not to the operator's
|
|
1368
|
-
* retention policy, so it is decided first and nothing is retained: a
|
|
1369
|
-
* preparation that could never be delivered is not a smaller preparation.
|
|
1370
|
-
*/
|
|
1371
|
-
"rpc_frame_too_large",
|
|
1372
|
-
/**
|
|
1373
|
-
* The device's input-preparation lane is off because its durable record log
|
|
1374
|
-
* holds a record from an older record schema version. The rest of the
|
|
1375
|
-
* device runs; this lane refuses until an operator archives that log. No
|
|
1376
|
-
* record is migrated, read forward or deleted.
|
|
1377
|
-
*/
|
|
1378
|
-
"input_preparation_record_log_unsupported"
|
|
1379
|
-
]);
|
|
1380
|
-
var AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH = 512;
|
|
1381
|
-
var AgentEventSpillSchema = z.object({
|
|
1382
|
-
/** Which field of the event was replaced by a preview. */
|
|
1383
|
-
field: z.enum(["input", "output"]),
|
|
1384
|
-
/** UTF-8 byte length of the full `JSON.stringify(<field>)` that was spilled. */
|
|
1385
|
-
totalBytes: z.number().int().nonnegative(),
|
|
1386
|
-
/** `totalBytes` minus the UTF-8 bytes of the retained preview head + tail. */
|
|
1387
|
-
omittedBytes: z.number().int().nonnegative(),
|
|
1388
|
-
/** Always the JSON serialization of the field — never the tool's own notion of a content type. */
|
|
1389
|
-
contentType: z.literal("application/json"),
|
|
1390
|
-
/** Where the omitted bytes are readable. Mutually exclusive with `unstoredReason`. */
|
|
1391
|
-
blob: BlobRefSchema.optional(),
|
|
1392
|
-
/** Why the omitted bytes are NOT readable. Mutually exclusive with `blob`. */
|
|
1393
|
-
unstoredReason: z.string().min(1).max(AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH).optional()
|
|
1394
|
-
}).strict().refine(
|
|
1395
|
-
(spill) => spill.blob === void 0 !== (spill.unstoredReason === void 0),
|
|
1396
|
-
"spill must carry exactly one of blob (the omitted bytes are readable) or unstoredReason (they are not)"
|
|
1397
|
-
);
|
|
1398
|
-
var AgentEventSchema = z.discriminatedUnion("type", [
|
|
1399
|
-
z.object({ type: z.literal("progress"), text: z.string() }),
|
|
1400
|
-
z.object({
|
|
1401
|
-
type: z.literal("tool_use"),
|
|
1402
|
-
tool: z.string(),
|
|
1403
|
-
/** Authoritative MCP identity, absent when the adapter cannot resolve it. */
|
|
1404
|
-
mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),
|
|
1405
|
-
input: z.unknown().optional(),
|
|
1406
|
-
toolCallId: z.string().regex(/\S/, "toolCallId must contain a non-whitespace character").optional(),
|
|
1407
|
-
/** Present only when `input` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */
|
|
1408
|
-
spill: AgentEventSpillSchema.optional()
|
|
1409
|
-
}),
|
|
1410
|
-
z.object({
|
|
1411
|
-
type: z.literal("tool_result"),
|
|
1412
|
-
tool: z.string(),
|
|
1413
|
-
/** Authoritative MCP identity, absent when the adapter cannot resolve it. */
|
|
1414
|
-
mcp: z.object({ server: z.string().min(1), tool: z.string().min(1) }).strict().optional(),
|
|
1415
|
-
output: z.unknown().optional(),
|
|
1416
|
-
toolCallId: z.string().regex(/\S/, "toolCallId must contain a non-whitespace character").optional(),
|
|
1417
|
-
isError: z.boolean().optional(),
|
|
1418
|
-
/** Present only when `output` is a preview of a spilled value — see {@link AgentEventSpillSchema}. */
|
|
1419
|
-
spill: AgentEventSpillSchema.optional()
|
|
1420
|
-
}),
|
|
1421
|
-
z.object({ type: z.literal("artifact"), name: z.string(), contentType: z.string() }),
|
|
1422
|
-
z.object({ type: z.literal("needs_approval"), summary: z.string() }),
|
|
1423
|
-
z.object({ type: z.literal("turn_end") }),
|
|
1424
|
-
z.object({ type: z.literal("error"), message: z.string() }),
|
|
1425
|
-
/**
|
|
1426
|
-
* Token usage reported by a runtime turn — maps from codex
|
|
1427
|
-
* `turn.completed.usage` and claude `result` usage (adapters wired up in a
|
|
1428
|
-
* later wave; this is just the variant + schema). All fields optional
|
|
1429
|
-
* because runtimes report different subsets.
|
|
1430
|
-
*/
|
|
1431
|
-
z.object({
|
|
1432
|
-
type: z.literal("usage"),
|
|
1433
|
-
inputTokens: z.number().int().nonnegative().optional(),
|
|
1434
|
-
cachedInputTokens: z.number().int().nonnegative().optional(),
|
|
1435
|
-
outputTokens: z.number().int().nonnegative().optional(),
|
|
1436
|
-
reasoningTokens: z.number().int().nonnegative().optional(),
|
|
1437
|
-
totalTokens: z.number().int().nonnegative().optional(),
|
|
1438
|
-
// Context occupancy is independent of provider cost counters. Unknown stays absent.
|
|
1439
|
-
contextTokens: z.number().int().nonnegative().optional(),
|
|
1440
|
-
contextWindow: z.number().int().positive().optional(),
|
|
1441
|
-
contextSource: z.enum(["provider", "estimate"]).optional()
|
|
1442
|
-
})
|
|
1443
|
-
]);
|
|
1444
|
-
var KNOWN_AGENT_EVENT_TYPES = z.toJSONSchema(AgentEventSchema).oneOf.map((branch) => branch.properties.type.const);
|
|
1445
|
-
var UnknownAgentEventSchema = z.object({ type: z.string() }).passthrough().refine(
|
|
1446
|
-
(event) => !KNOWN_AGENT_EVENT_TYPES.includes(event.type),
|
|
1447
|
-
"type refers to a known AgentEvent variant; malformed known variants must fail through AgentEventSchema, not fall back to unknown-tolerance"
|
|
1448
|
-
);
|
|
1449
|
-
var AgentEventOrUnknownSchema = z.union([AgentEventSchema, UnknownAgentEventSchema]);
|
|
1450
|
-
function isKnownAgentEvent(event) {
|
|
1451
|
-
return KNOWN_AGENT_EVENT_TYPES.includes(event.type);
|
|
1452
|
-
}
|
|
1453
|
-
function partitionAgentEvents(events) {
|
|
1454
|
-
const known = [];
|
|
1455
|
-
const unknown = [];
|
|
1456
|
-
for (const event of events) {
|
|
1457
|
-
if (isKnownAgentEvent(event)) {
|
|
1458
|
-
known.push(event);
|
|
1459
|
-
} else {
|
|
1460
|
-
unknown.push(event);
|
|
1461
|
-
}
|
|
1462
|
-
}
|
|
1463
|
-
return { known, unknown };
|
|
1464
|
-
}
|
|
1465
|
-
var AGENT_HOME_PROJECTION_MAX_BYTES = 64 * 1024;
|
|
1466
|
-
var AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM = "9223372036854775807";
|
|
1467
|
-
var AgentHomeProjectionProfileRevisionSchema = z.string().regex(/^[1-9][0-9]{0,18}$/u, "profileRevision must be a canonical positive decimal string").refine(
|
|
1468
|
-
(value) => value.length < AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM.length || value <= AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM,
|
|
1469
|
-
`profileRevision must not exceed PostgreSQL BIGINT maximum ${AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM}`
|
|
1470
|
-
);
|
|
1471
|
-
var AgentHomeProjectionHashSchema = AgentEgressContentHashSchema;
|
|
1472
|
-
var AgentHomeProjectionOutcomeSchema = z.enum(["applied", "idempotent", "stale", "conflict"]);
|
|
1473
|
-
var AgentHomeProjectionValueSchema = z.json().refine(
|
|
1474
|
-
(value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= AGENT_HOME_PROJECTION_MAX_BYTES,
|
|
1475
|
-
`projection must not exceed ${AGENT_HOME_PROJECTION_MAX_BYTES} UTF-8 JSON bytes`
|
|
1476
|
-
);
|
|
1477
|
-
var E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES = 64;
|
|
1478
|
-
var E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES = 65536;
|
|
1479
|
-
var E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES = 256;
|
|
1480
|
-
var E2EE_SCOPE_KEY_PACKAGE_PUT_MAX = 256;
|
|
1481
|
-
var E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX = 16;
|
|
1482
|
-
var E2EE_SCOPE_ID_MAX_LENGTH = 512;
|
|
1483
|
-
var E2EE_MEMBER_KEY_REGISTER_OPERATION = "e2ee-member-key.register";
|
|
1484
|
-
var E2EE_MEMBER_CHAIN_APPEND_OPERATION = "e2ee-member-chain.append";
|
|
1485
|
-
var E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION = "e2ee-scope-key-package.put";
|
|
1486
|
-
function base64UrlBytes(bytes) {
|
|
1487
|
-
const length = Math.ceil(bytes * 4 / 3);
|
|
1488
|
-
const last = ["[A-Za-z0-9_-]", "[AQgw]", "[AEIMQUYcgkosw048]"][bytes % 3];
|
|
1489
|
-
return z.string().regex(new RegExp(`^[A-Za-z0-9_-]{${length - 1}}${last}$`, "u"));
|
|
1490
|
-
}
|
|
1491
|
-
var MemberIdSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/u);
|
|
1492
|
-
var PositiveSafeIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
|
|
1493
|
-
var SignatureSchema = base64UrlBytes(64);
|
|
1494
|
-
var P256PublicJwkSchema = z.strictObject({
|
|
1495
|
-
kty: z.literal("EC"),
|
|
1496
|
-
crv: z.literal("P-256"),
|
|
1497
|
-
x: base64UrlBytes(32),
|
|
1498
|
-
y: base64UrlBytes(32)
|
|
1499
|
-
});
|
|
1500
|
-
var E2eeMemberKeyBundleSchema = z.strictObject({
|
|
1501
|
-
v: z.literal(1),
|
|
1502
|
-
memberId: MemberIdSchema,
|
|
1503
|
-
signingPublicJwk: P256PublicJwkSchema,
|
|
1504
|
-
kemPublicJwk: P256PublicJwkSchema,
|
|
1505
|
-
kemEpoch: PositiveSafeIntegerSchema,
|
|
1506
|
-
kemSig: SignatureSchema,
|
|
1507
|
-
deviceId: z.string().min(1).optional()
|
|
1508
|
-
});
|
|
1509
|
-
var E2EE_MEMBER_CHAIN_OPS = ["add", "remove", "rotate", "scope-policy", "shred"];
|
|
1510
|
-
var E2eeScopeShredSubjectSchema = z.strictObject({ scopeId: z.string().min(1) });
|
|
1511
|
-
var E2eeMemberRotateSubjectSchema = z.strictObject({
|
|
1512
|
-
memberId: MemberIdSchema,
|
|
1513
|
-
kemPublicJwk: P256PublicJwkSchema,
|
|
1514
|
-
kemEpoch: PositiveSafeIntegerSchema,
|
|
1515
|
-
kemSig: SignatureSchema
|
|
1516
|
-
});
|
|
1517
|
-
var E2eeMemberChainEntrySchema = z.strictObject({
|
|
1518
|
-
v: z.literal(1),
|
|
1519
|
-
tenantId: z.string().min(1),
|
|
1520
|
-
seq: PositiveSafeIntegerSchema,
|
|
1521
|
-
prev: z.union([z.null(), z.string().regex(CONTENT_HASH_RE)]),
|
|
1522
|
-
op: z.enum(E2EE_MEMBER_CHAIN_OPS),
|
|
1523
|
-
subject: z.custom(
|
|
1524
|
-
(value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
1525
|
-
),
|
|
1526
|
-
signer: MemberIdSchema,
|
|
1527
|
-
sig: SignatureSchema
|
|
1528
|
-
}).refine((entry) => entry.seq === 1 === (entry.prev === null), {
|
|
1529
|
-
path: ["prev"],
|
|
1530
|
-
message: "the first entry, and only the first, has no prev"
|
|
1531
|
-
}).refine((entry) => entry.op !== "shred" || E2eeScopeShredSubjectSchema.safeParse(entry.subject).success, {
|
|
1532
|
-
path: ["subject"],
|
|
1533
|
-
message: "a shred subject is exactly { scopeId }"
|
|
1534
|
-
}).refine((entry) => entry.op !== "rotate" || E2eeMemberRotateSubjectSchema.safeParse(entry.subject).success, {
|
|
1535
|
-
path: ["subject"],
|
|
1536
|
-
message: "a rotate subject is exactly { memberId, kemPublicJwk, kemEpoch, kemSig }"
|
|
1537
|
-
});
|
|
1538
|
-
var E2eeScopeKeyPackageV1Schema = z.strictObject({
|
|
1539
|
-
v: z.literal(1),
|
|
1540
|
-
tenantId: z.string().min(1),
|
|
1541
|
-
scopeId: z.string().min(1),
|
|
1542
|
-
epoch: PositiveSafeIntegerSchema,
|
|
1543
|
-
keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/u),
|
|
1544
|
-
recipient: MemberIdSchema,
|
|
1545
|
-
sender: MemberIdSchema,
|
|
1546
|
-
enc: base64UrlBytes(65),
|
|
1547
|
-
ciphertext: base64UrlBytes(48),
|
|
1548
|
-
sig: SignatureSchema
|
|
1549
|
-
});
|
|
1550
|
-
var E2eeScopeKeyPackageV2Schema = z.strictObject({
|
|
1551
|
-
...E2eeScopeKeyPackageV1Schema.shape,
|
|
1552
|
-
v: z.literal(2),
|
|
1553
|
-
recipientKemEpoch: PositiveSafeIntegerSchema
|
|
1554
|
-
});
|
|
1555
|
-
var E2eeScopeKeyPackageSchema = z.union([E2eeScopeKeyPackageV1Schema, E2eeScopeKeyPackageV2Schema]);
|
|
1556
|
-
var E2eePairingMacSchema = base64UrlBytes(32);
|
|
1557
|
-
var E2eeMemberKeyRegisterRequestSchema = z.strictObject({
|
|
1558
|
-
member: E2eeMemberKeyBundleSchema.refine((member) => member.deviceId !== void 0, {
|
|
1559
|
-
message: "a device member names its deviceId"
|
|
1560
|
-
}),
|
|
1561
|
-
mac: E2eePairingMacSchema
|
|
1562
|
-
});
|
|
1563
|
-
var E2eeClientPairingMacSchema = z.strictObject({
|
|
1564
|
-
mac: E2eePairingMacSchema,
|
|
1565
|
-
member: E2eeMemberKeyBundleSchema.refine((member) => member.deviceId === void 0, {
|
|
1566
|
-
message: "a client member has no deviceId"
|
|
1567
|
-
}),
|
|
1568
|
-
chainHead: z.strictObject({ seq: PositiveSafeIntegerSchema, hash: z.string().regex(CONTENT_HASH_RE) })
|
|
1569
|
-
});
|
|
1570
|
-
var E2eeKeyPackageAvailablePayloadSchema = z.strictObject({
|
|
1571
|
-
scopeId: z.string().min(1).max(E2EE_SCOPE_ID_MAX_LENGTH),
|
|
1572
|
-
epoch: PositiveSafeIntegerSchema
|
|
1573
|
-
});
|
|
1574
|
-
|
|
1575
|
-
// src/messages.ts
|
|
1576
|
-
var MAX_INLINE_BYTES = 64 * 1024;
|
|
1577
|
-
function isWithinInlineByteLimit(value) {
|
|
1578
|
-
return new TextEncoder().encode(value).length <= MAX_INLINE_BYTES;
|
|
1579
|
-
}
|
|
1580
|
-
var RuntimeIdSchema = z.enum(RUNTIME_IDS);
|
|
1581
|
-
var ProtocolVersionNumberSchema = z.number().int().nonnegative().max(2147483647);
|
|
1582
|
-
var RuntimeCapabilitiesSchema = z.object({
|
|
1583
|
-
steer: z.boolean().optional(),
|
|
1584
|
-
resume: z.boolean().optional(),
|
|
1585
|
-
approvalInteractive: z.boolean().optional(),
|
|
1586
|
-
/** Whether this runtime can project a locally configured MCP toolset into one task. */
|
|
1587
|
-
mcpToolsets: z.boolean().optional(),
|
|
1588
|
-
messageDraft: z.boolean().optional()
|
|
1589
|
-
});
|
|
1590
|
-
var RuntimeInfoSchema = z.object({
|
|
1591
|
-
id: RuntimeIdSchema,
|
|
1592
|
-
version: z.string().optional(),
|
|
1593
|
-
authPresent: z.boolean().optional(),
|
|
1594
|
-
/** Optional: older daemons omit this entirely (pre-freeze addition). */
|
|
1595
|
-
capabilities: RuntimeCapabilitiesSchema.optional()
|
|
1596
|
-
});
|
|
1597
|
-
var HarnessIdSchema = z.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/).refine((value) => !RUNTIME_IDS.includes(value), "built-in runtime must use runtime");
|
|
1598
|
-
var HarnessInfoSchema = z.object({
|
|
1599
|
-
id: HarnessIdSchema,
|
|
1600
|
-
version: z.string().min(1).max(128).optional(),
|
|
1601
|
-
capabilities: RuntimeCapabilitiesSchema
|
|
1602
|
-
});
|
|
1603
|
-
var HarnessInventorySchema = z.array(HarnessInfoSchema).max(64).refine((values) => new Set(values.map((value) => value.id)).size === values.length, "duplicate harness identity");
|
|
1604
|
-
var CONFIGURED_TOOLSETS_MAX_ITEMS = 64;
|
|
1605
|
-
var ToolsetIdSchema = z.string().min(1).max(128).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/u, "toolset ids must be lowercase logical identifiers");
|
|
1606
|
-
var AGENT_REF_MAX_BYTES = 160;
|
|
1607
|
-
var AGENT_REF_VALUE = z.string().min(1).max(AGENT_REF_MAX_BYTES).refine((value) => new TextEncoder().encode(value).byteLength <= AGENT_REF_MAX_BYTES, {
|
|
1608
|
-
message: `AgentRef values must not exceed ${AGENT_REF_MAX_BYTES} UTF-8 bytes`
|
|
1609
|
-
}).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u, "AgentRef values must not contain control characters");
|
|
1610
|
-
var WINDOWS_RESERVED_AGENT_SEGMENT = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;
|
|
1611
|
-
var AgentRefSchema = z.object({
|
|
1612
|
-
agentId: AGENT_REF_VALUE.regex(/^[^\\/:<>"|?*]+$/u, "agentId must be one portable pathname segment").refine(
|
|
1613
|
-
(value) => value !== "." && value !== "..",
|
|
1614
|
-
"agentId must not be a dot segment"
|
|
1615
|
-
).refine(
|
|
1616
|
-
(value) => !/[. ]$/u.test(value) && !WINDOWS_RESERVED_AGENT_SEGMENT.test(value),
|
|
1617
|
-
"agentId must be a portable Windows-safe pathname segment"
|
|
1618
|
-
),
|
|
1619
|
-
profileRevision: AGENT_REF_VALUE
|
|
1620
|
-
}).strict();
|
|
1621
|
-
var AgentHomeProjectionAgentRefSchema = AgentRefSchema.extend({
|
|
1622
|
-
profileRevision: AgentHomeProjectionProfileRevisionSchema
|
|
1623
|
-
}).strict();
|
|
1624
|
-
function rejectDuplicateToolsets(ids, ctx, label) {
|
|
1625
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1626
|
-
for (const [index, id] of ids.entries()) {
|
|
1627
|
-
if (seen.has(id)) {
|
|
1628
|
-
ctx.addIssue({ code: "custom", path: [index], message: `duplicate ${label} toolset: ${id}` });
|
|
1629
|
-
}
|
|
1630
|
-
seen.add(id);
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
var ConfiguredToolsetsSchema = z.array(ToolsetIdSchema).max(CONFIGURED_TOOLSETS_MAX_ITEMS).superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, "configured"));
|
|
1634
|
-
var ConnHelloPayloadSchema = z.object({
|
|
1635
|
-
protocolVersions: z.array(ProtocolVersionNumberSchema).max(16),
|
|
1636
|
-
capabilities: z.array(z.string()),
|
|
1637
|
-
deviceId: z.string(),
|
|
1638
|
-
productId: z.string(),
|
|
1639
|
-
/** U4a Local Agent release identity; this is the sole client-version authority. */
|
|
1640
|
-
clientVersion: z.string().min(1).max(128).optional(),
|
|
1641
|
-
/** Runtimes detected on this device (M1 gap #4; replaces `agents`). */
|
|
1642
|
-
runtimes: z.array(RuntimeInfoSchema).optional(),
|
|
1643
|
-
harnesses: HarnessInventorySchema.optional(),
|
|
1644
|
-
/** Validated logical IDs configured on this device; definitions and secrets stay local. */
|
|
1645
|
-
configuredToolsets: ConfiguredToolsetsSchema.optional(),
|
|
1646
|
-
/**
|
|
1647
|
-
* Last `seq` this device has seen from the server (M1 redelivery cursor).
|
|
1648
|
-
* Omitted on a device's first-ever connection. The server replays any
|
|
1649
|
-
* server->daemon envelopes with `seq > cursor` it still holds — see
|
|
1650
|
-
* docs/protocol.md "At-least-once delivery".
|
|
1651
|
-
*/
|
|
1652
|
-
cursor: z.number().int().optional()
|
|
1653
|
-
});
|
|
1654
|
-
var ConnAckPayloadSchema = z.object({
|
|
1655
|
-
protocolVersion: z.number().int(),
|
|
1656
|
-
capabilities: z.array(z.string()),
|
|
1657
|
-
serverTime: z.iso.datetime({ offset: true })
|
|
1658
|
-
});
|
|
1659
|
-
var InstructionBlobRefSchema = z.object({ blobRef: BlobRefSchema }).strict();
|
|
1660
|
-
var DispatchTargetIdSchema = z.string().min(1).max(160).regex(/^[^\u0000\r\n]+$/u, "dispatch target ids must not contain control line breaks");
|
|
1661
|
-
var DispatchSelectionSchema = z.discriminatedUnion("lane", [
|
|
1662
|
-
z.object({
|
|
1663
|
-
lane: z.literal("subscription"),
|
|
1664
|
-
runtimeId: z.enum(["claude", "codex"]),
|
|
1665
|
-
providerId: z.null(),
|
|
1666
|
-
modelId: DispatchTargetIdSchema
|
|
1667
|
-
}).strict(),
|
|
1668
|
-
z.object({
|
|
1669
|
-
lane: z.literal("byok"),
|
|
1670
|
-
runtimeId: z.literal("pi"),
|
|
1671
|
-
providerId: DispatchTargetIdSchema,
|
|
1672
|
-
modelId: DispatchTargetIdSchema
|
|
1673
|
-
}).strict(),
|
|
1674
|
-
z.object({
|
|
1675
|
-
lane: z.literal("byok-profile"),
|
|
1676
|
-
runtimeId: z.literal("pi"),
|
|
1677
|
-
providerProfile: ProviderProfileBindingSchema
|
|
1678
|
-
}).strict()
|
|
1679
|
-
]);
|
|
1680
|
-
var NO_SEALED_MEMBER = { sealed: z.never().optional(), sealing: z.never().optional() };
|
|
1681
|
-
var TaskOfferPayloadSchema = z.object({
|
|
1682
|
-
...NO_SEALED_MEMBER,
|
|
1683
|
-
instruction: z.union([z.string(), InstructionBlobRefSchema]),
|
|
1684
|
-
runtime: RuntimeIdSchema.optional(),
|
|
1685
|
-
harnessId: HarnessIdSchema.optional(),
|
|
1686
|
-
dispatchSelection: DispatchSelectionSchema.optional(),
|
|
1687
|
-
sessionRef: z.string().optional(),
|
|
1688
|
-
workspaceHint: z.string().optional(),
|
|
1689
|
-
limits: z.object({
|
|
1690
|
-
maxDurationMs: z.number().int().positive().optional(),
|
|
1691
|
-
maxTokens: z.number().int().positive().optional()
|
|
1692
|
-
}).optional()
|
|
1693
|
-
});
|
|
1694
|
-
var RequiredToolsetsSchema = z.array(ToolsetIdSchema).min(1).max(16).superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, "required"));
|
|
1695
|
-
var TaskOfferWithToolsetsPayloadSchema = TaskOfferPayloadSchema.extend({
|
|
1696
|
-
requiredToolsets: RequiredToolsetsSchema
|
|
1697
|
-
}).strict();
|
|
1698
|
-
var AgentHomeAccessSchema = z.literal("memory-reader");
|
|
1699
|
-
var AgentMemorySelectionSchema = z.enum([
|
|
1700
|
-
...PreparedAgentMemoryModeSchema.options,
|
|
1701
|
-
"read-if-admitted",
|
|
1702
|
-
"read-write-if-admitted"
|
|
1703
|
-
]);
|
|
1704
|
-
var TaskOfferForAgentPayloadSchema = z.object({
|
|
1705
|
-
...NO_SEALED_MEMBER,
|
|
1706
|
-
instruction: z.union([z.string(), InstructionBlobRefSchema]),
|
|
1707
|
-
agentRef: AgentRefSchema,
|
|
1708
|
-
homeAccess: AgentHomeAccessSchema.optional(),
|
|
1709
|
-
agentMemory: AgentMemorySelectionSchema.optional(),
|
|
1710
|
-
requiredToolsets: RequiredToolsetsSchema.optional(),
|
|
1711
|
-
runtime: RuntimeIdSchema.optional(),
|
|
1712
|
-
harnessId: HarnessIdSchema.optional(),
|
|
1713
|
-
dispatchSelection: DispatchSelectionSchema.optional(),
|
|
1714
|
-
terminalProjection: TerminalProjectionSelectionSchema.optional(),
|
|
1715
|
-
sessionRef: z.string().optional(),
|
|
1716
|
-
limits: z.object({
|
|
1717
|
-
maxDurationMs: z.number().int().positive().optional(),
|
|
1718
|
-
maxTokens: z.number().int().positive().optional()
|
|
1719
|
-
}).optional()
|
|
1720
|
-
}).strict();
|
|
1721
|
-
var TaskOfferForAgentWithEgressPayloadSchema = TaskOfferForAgentPayloadSchema.extend({
|
|
1722
|
-
sessionRef: z.string().min(1).max(512),
|
|
1723
|
-
egressPolicy: AgentEgressPolicySchema,
|
|
1724
|
-
messageEgress: AgentMessageEgressRequirementSchema.optional()
|
|
1725
|
-
}).strict();
|
|
1726
|
-
var TaskOfferForAgentWithEgressFreshPayloadSchema = TaskOfferForAgentPayloadSchema.omit({
|
|
1727
|
-
sessionRef: true
|
|
1728
|
-
}).extend({
|
|
1729
|
-
egressPolicy: AgentEgressPolicySchema,
|
|
1730
|
-
messageEgress: AgentMessageEgressRequirementSchema.optional()
|
|
1731
|
-
}).strict();
|
|
1732
|
-
var TaskOfferPreparedPayloadSchema = TaskOfferForAgentPayloadSchema.omit({
|
|
1733
|
-
instruction: true,
|
|
1734
|
-
sessionRef: true,
|
|
1735
|
-
agentMemory: true
|
|
1736
|
-
}).extend({
|
|
1737
|
-
preparation: InputPreparationOfferBindingSchema,
|
|
1738
|
-
agentMemory: PreparedAgentMemoryModeSchema,
|
|
1739
|
-
egressPolicy: AgentEgressPolicySchema,
|
|
1740
|
-
messageEgress: AgentMessageEgressRequirementSchema.optional()
|
|
1741
|
-
}).strict();
|
|
1742
|
-
var EGRESS_SAFE_VALUE = z.json().refine(
|
|
1743
|
-
(value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 256 * 1024,
|
|
1744
|
-
"egress payload exceeds 256KiB"
|
|
1745
|
-
);
|
|
1746
|
-
var EGRESS_SESSION_REF = z.string().min(1).max(512);
|
|
1747
|
-
var AgentEgressReliablePayloadSchema = z.object({
|
|
1748
|
-
agentRef: AgentRefSchema,
|
|
1749
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1750
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
1751
|
-
eventId: z.uuid(),
|
|
1752
|
-
cursor: z.number().int().positive(),
|
|
1753
|
-
payload: EGRESS_SAFE_VALUE,
|
|
1754
|
-
contentHash: AgentEgressContentHashSchema,
|
|
1755
|
-
byteCount: z.number().int().nonnegative().max(256 * 1024)
|
|
1756
|
-
}).strict();
|
|
1757
|
-
var AgentEgressAckPayloadSchema = z.object({
|
|
1758
|
-
agentRef: AgentRefSchema,
|
|
1759
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1760
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
1761
|
-
eventId: z.uuid(),
|
|
1762
|
-
cursor: z.number().int().positive(),
|
|
1763
|
-
receiptId: z.uuid()
|
|
1764
|
-
}).strict();
|
|
1765
|
-
var AGENT_MESSAGE_BODY = z.string().min(1).refine(
|
|
1766
|
-
(value) => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_MAX_BYTES,
|
|
1767
|
-
`Agent message body exceeds ${AGENT_MESSAGE_MAX_BYTES} bytes`
|
|
1768
|
-
);
|
|
1769
|
-
var AgentMessageDraftPayloadSchema = z.object({
|
|
1770
|
-
agentRef: AgentRefSchema,
|
|
1771
|
-
revision: z.number().int().min(1),
|
|
1772
|
-
offset: z.number().int().nonnegative(),
|
|
1773
|
-
text: z.string().refine(
|
|
1774
|
-
(value) => new TextEncoder().encode(value).byteLength <= AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES,
|
|
1775
|
-
`Agent message draft frame exceeds ${AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES} bytes`
|
|
1776
|
-
),
|
|
1777
|
-
overflow: z.literal(true).optional()
|
|
1778
|
-
}).strict();
|
|
1779
|
-
var AgentMessagePublishPayloadSchema = z.object({
|
|
1780
|
-
agentRef: AgentRefSchema,
|
|
1781
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1782
|
-
contract: AgentMessageContractSchema,
|
|
1783
|
-
messageId: z.uuid(),
|
|
1784
|
-
cursor: z.number().int().positive(),
|
|
1785
|
-
contentType: AgentMessageContentTypeSchema,
|
|
1786
|
-
body: AGENT_MESSAGE_BODY,
|
|
1787
|
-
contentHash: AgentEgressContentHashSchema,
|
|
1788
|
-
byteCount: z.number().int().positive().max(AGENT_MESSAGE_MAX_BYTES)
|
|
1789
|
-
}).strict().superRefine((value, context) => {
|
|
1790
|
-
const actual = new TextEncoder().encode(value.body).byteLength;
|
|
1791
|
-
if (actual !== value.byteCount) {
|
|
1792
|
-
context.addIssue({ code: "custom", path: ["byteCount"], message: "byteCount must equal UTF-8 body bytes" });
|
|
1793
|
-
}
|
|
1794
|
-
});
|
|
1795
|
-
var AgentMessageDispositionPayloadSchema = z.object({
|
|
1796
|
-
agentRef: AgentRefSchema,
|
|
1797
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1798
|
-
contract: AgentMessageContractSchema,
|
|
1799
|
-
messageId: z.uuid(),
|
|
1800
|
-
cursor: z.number().int().positive(),
|
|
1801
|
-
contentHash: AgentEgressContentHashSchema,
|
|
1802
|
-
outcome: z.enum(["accepted", "held", "refused"]),
|
|
1803
|
-
receiptId: z.uuid(),
|
|
1804
|
-
reasonCode: z.string().min(1).max(160).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u).optional()
|
|
1805
|
-
}).strict();
|
|
1806
|
-
var AGENT_CONTENT_TARGET = z.string().min(1).max(1024).regex(/^[^\u0000-\u001f\u007f]+$/u, "content target must not contain control characters").refine(
|
|
1807
|
-
(value) => !value.startsWith("/") && !value.includes("\\") && value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."),
|
|
1808
|
-
"content target must be a portable relative path without dot segments"
|
|
1809
|
-
);
|
|
1810
|
-
var AGENT_CONTENT_CWD = z.string().min(1).max(4096).regex(/^[^\u0000-\u001f\u007f]+$/u, "cwd must not contain control characters").regex(/^(?:\/|[A-Za-z]:[\\/])/u, "cwd must be absolute");
|
|
1811
|
-
var AgentContentReadPayloadSchema = z.object({
|
|
1812
|
-
requestId: z.uuid(),
|
|
1813
|
-
surface: AgentContentReadSurfaceSchema,
|
|
1814
|
-
actor: AgentContentActorSchema,
|
|
1815
|
-
agentRef: AgentRefSchema,
|
|
1816
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1817
|
-
runtime: RuntimeIdSchema,
|
|
1818
|
-
cwd: AGENT_CONTENT_CWD,
|
|
1819
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
1820
|
-
target: AGENT_CONTENT_TARGET,
|
|
1821
|
-
mimeType: AgentContentMimeTypeSchema,
|
|
1822
|
-
decodeAs: AgentContentDecodeAsSchema,
|
|
1823
|
-
policy: ContentReadPolicySchema
|
|
1824
|
-
}).strict();
|
|
1825
|
-
var AgentContentReceiptPayloadSchema = z.discriminatedUnion("decision", [
|
|
1826
|
-
z.object({
|
|
1827
|
-
requestId: z.uuid(),
|
|
1828
|
-
/** Stable reliable-delivery identity. Content receipts use their requestId. */
|
|
1829
|
-
eventId: z.uuid(),
|
|
1830
|
-
/** Stable positive cursor allocated by the durable Agent spool. */
|
|
1831
|
-
cursor: z.number().int().positive(),
|
|
1832
|
-
surface: AgentContentReadSurfaceSchema,
|
|
1833
|
-
actor: AgentContentActorSchema,
|
|
1834
|
-
agentRef: AgentRefSchema,
|
|
1835
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1836
|
-
runtime: RuntimeIdSchema,
|
|
1837
|
-
cwd: AGENT_CONTENT_CWD,
|
|
1838
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
1839
|
-
target: AGENT_CONTENT_TARGET,
|
|
1840
|
-
mimeType: AgentContentMimeTypeSchema,
|
|
1841
|
-
decodeAs: AgentContentDecodeAsSchema,
|
|
1842
|
-
decision: z.literal("allowed"),
|
|
1843
|
-
byteCount: z.number().int().nonnegative(),
|
|
1844
|
-
contentHash: AgentEgressContentHashSchema,
|
|
1845
|
-
blobRef: BlobRefSchema
|
|
1846
|
-
}).strict(),
|
|
1847
|
-
z.object({
|
|
1848
|
-
requestId: z.uuid(),
|
|
1849
|
-
eventId: z.uuid(),
|
|
1850
|
-
cursor: z.number().int().positive(),
|
|
1851
|
-
surface: AgentContentReadSurfaceSchema,
|
|
1852
|
-
actor: AgentContentActorSchema,
|
|
1853
|
-
agentRef: AgentRefSchema,
|
|
1854
|
-
sessionRef: EGRESS_SESSION_REF,
|
|
1855
|
-
runtime: RuntimeIdSchema,
|
|
1856
|
-
cwd: AGENT_CONTENT_CWD,
|
|
1857
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
1858
|
-
target: AGENT_CONTENT_TARGET,
|
|
1859
|
-
mimeType: AgentContentMimeTypeSchema,
|
|
1860
|
-
decodeAs: AgentContentDecodeAsSchema,
|
|
1861
|
-
decision: z.literal("denied"),
|
|
1862
|
-
byteCount: z.literal(0),
|
|
1863
|
-
reason: AgentContentReadDenialReasonSchema
|
|
1864
|
-
}).strict()
|
|
1865
|
-
]).superRefine((value, ctx) => {
|
|
1866
|
-
if (value.decision !== "allowed") return;
|
|
1867
|
-
if (value.blobRef.size !== value.byteCount) {
|
|
1868
|
-
ctx.addIssue({ code: "custom", path: ["blobRef", "size"], message: "blobRef size must equal byteCount" });
|
|
1869
|
-
}
|
|
1870
|
-
if (value.blobRef.contentHash !== value.contentHash) {
|
|
1871
|
-
ctx.addIssue({ code: "custom", path: ["blobRef", "contentHash"], message: "blobRef contentHash must equal contentHash" });
|
|
1872
|
-
}
|
|
1873
|
-
if (value.blobRef.contentType !== value.mimeType) {
|
|
1874
|
-
ctx.addIssue({ code: "custom", path: ["blobRef", "contentType"], message: "blobRef contentType must equal mimeType" });
|
|
1875
|
-
}
|
|
1876
|
-
});
|
|
1877
|
-
var AgentHomeProjectionPayloadSchema = z.object({
|
|
1878
|
-
requestId: z.uuid(),
|
|
1879
|
-
agentRef: AgentHomeProjectionAgentRefSchema,
|
|
1880
|
-
projectionHash: AgentHomeProjectionHashSchema,
|
|
1881
|
-
projection: AgentHomeProjectionValueSchema
|
|
1882
|
-
}).strict();
|
|
1883
|
-
var AgentMemoryIntentAvailablePayloadSchema = z.object({
|
|
1884
|
-
intentId: z.uuid(),
|
|
1885
|
-
agentRef: AgentHomeProjectionAgentRefSchema
|
|
1886
|
-
}).strict();
|
|
1887
|
-
var InputPreparationInlineContextSchema = z.object({
|
|
1888
|
-
inline: z.string().refine(isWithinInlineByteLimit, `inline context must not exceed ${MAX_INLINE_BYTES} UTF-8 bytes`)
|
|
1889
|
-
}).strict();
|
|
1890
|
-
var InputPreparationBlobContextSchema = z.object({ blobRef: BlobRefSchema, contentHash: InputPreparationContentHashSchema }).strict().superRefine((value, ctx) => {
|
|
1891
|
-
if (value.blobRef.contentHash !== value.contentHash) {
|
|
1892
|
-
ctx.addIssue({
|
|
1893
|
-
code: "custom",
|
|
1894
|
-
path: ["blobRef", "contentHash"],
|
|
1895
|
-
message: "blobRef contentHash must equal contentHash"
|
|
1896
|
-
});
|
|
1897
|
-
}
|
|
1898
|
-
});
|
|
1899
|
-
var AgentInputPreparationPayloadSchema = z.object({
|
|
1900
|
-
agentMemory: PreparedAgentMemoryModeSchema,
|
|
1901
|
-
requestId: z.uuid(),
|
|
1902
|
-
agentRef: AgentRefSchema,
|
|
1903
|
-
profileId: InputPreparationProfileIdSchema,
|
|
1904
|
-
policyRevision: InputPreparationPolicyRevisionSchema,
|
|
1905
|
-
source: InputPreparationSourceSchema,
|
|
1906
|
-
selection: InputPreparationSelectionSchema,
|
|
1907
|
-
deadlineAt: z.iso.datetime({ offset: true }),
|
|
1908
|
-
context: z.union([InputPreparationInlineContextSchema, InputPreparationBlobContextSchema]),
|
|
1909
|
-
requiredToolsets: z.array(ToolsetIdSchema).max(16).superRefine((ids, ctx) => rejectDuplicateToolsets(ids, ctx, "required")),
|
|
1910
|
-
/**
|
|
1911
|
-
* The Host's accounting ruling for this preparation, carried verbatim onto
|
|
1912
|
-
* the receipt's binding. Optional and defaulted NOWHERE: a payload that
|
|
1913
|
-
* omits it produces a receipt that says `accounting_policy_missing`, which
|
|
1914
|
-
* is the honest answer — the device rules on no residual key by itself.
|
|
1915
|
-
*/
|
|
1916
|
-
accountingPolicyRef: InputPreparationAccountingPolicyRefSchema.optional()
|
|
1917
|
-
}).strict();
|
|
1918
|
-
var TaskApprovePayloadSchema = z.object({
|
|
1919
|
-
approvalId: z.string().optional()
|
|
1920
|
-
});
|
|
1921
|
-
var TaskRejectPayloadSchema = z.object({
|
|
1922
|
-
reason: z.string().optional(),
|
|
1923
|
-
approvalId: z.string().optional()
|
|
1924
|
-
});
|
|
1925
|
-
var TaskCancelPayloadSchema = z.object({
|
|
1926
|
-
reason: z.string().optional()
|
|
1927
|
-
});
|
|
1928
|
-
var TaskSteerPayloadSchema = z.object({
|
|
1929
|
-
...NO_SEALED_MEMBER,
|
|
1930
|
-
text: z.string()
|
|
1931
|
-
});
|
|
1932
|
-
var TaskClaimPayloadSchema = z.object({
|
|
1933
|
-
deviceId: z.string(),
|
|
1934
|
-
agentId: z.string().optional(),
|
|
1935
|
-
agentRef: AgentRefSchema.optional(),
|
|
1936
|
-
runtime: RuntimeIdSchema.optional(),
|
|
1937
|
-
harnessId: HarnessIdSchema.optional(),
|
|
1938
|
-
capabilities: RuntimeCapabilitiesSchema.optional()
|
|
1939
|
-
});
|
|
1940
|
-
var TaskStartedPayloadSchema = z.object({});
|
|
1941
|
-
var HOME_DECLINE_CODES = ["agent_home_writer_busy", "agent_home_reader_busy"];
|
|
1942
|
-
var DeclineFields = z.object({
|
|
1943
|
-
...NO_SEALED_MEMBER,
|
|
1944
|
-
reason: z.string(),
|
|
1945
|
-
retryable: z.boolean().optional(),
|
|
1946
|
-
agentRef: AgentRefSchema.optional(),
|
|
1947
|
-
code: z.enum([...HOME_DECLINE_CODES, ...SEALED_DECLINE_CODES]).optional()
|
|
1948
|
-
});
|
|
1949
|
-
var TaskDeclinePayloadSchema = DeclineFields.refine(
|
|
1950
|
-
(p) => !SEALED_DECLINE_CODES.includes(p.code) || p.reason === p.code && p.retryable !== true,
|
|
1951
|
-
{ message: "a sealed code needs reason === code, not retryable" }
|
|
1952
|
-
);
|
|
1953
|
-
var TaskProgressPayloadSchema = z.object({
|
|
1954
|
-
...NO_SEALED_MEMBER,
|
|
1955
|
-
seq: z.number().int(),
|
|
1956
|
-
events: z.array(AgentEventOrUnknownSchema)
|
|
1957
|
-
});
|
|
1958
|
-
var TaskArtifactPayloadSchema = z.object({
|
|
1959
|
-
...NO_SEALED_MEMBER,
|
|
1960
|
-
name: z.string(),
|
|
1961
|
-
contentType: z.string(),
|
|
1962
|
-
inline: z.string().refine(isWithinInlineByteLimit, {
|
|
1963
|
-
message: "inline artifact payload exceeds 64KB limit"
|
|
1964
|
-
}).optional(),
|
|
1965
|
-
blobRef: BlobRefSchema.optional()
|
|
1966
|
-
});
|
|
1967
|
-
var TaskAwaitApprovalPayloadSchema = z.object({
|
|
1968
|
-
...NO_SEALED_MEMBER,
|
|
1969
|
-
summary: z.string(),
|
|
1970
|
-
approvalId: z.string().optional()
|
|
1971
|
-
});
|
|
1972
|
-
var RESULT_DOCUMENT_MAX_BYTES = 1048576;
|
|
1973
|
-
function checkResultDocument(document) {
|
|
1974
|
-
return canonicalizePlainJson(document, RESULT_DOCUMENT_MAX_BYTES);
|
|
1975
|
-
}
|
|
1976
|
-
var TERMINAL_INFERENCE_USAGE_MAX_TOKENS = 1e9;
|
|
1977
|
-
var TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS = 6048e5;
|
|
1978
|
-
var TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH = 160;
|
|
1979
|
-
var TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH = 160;
|
|
1980
|
-
var TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH = 128;
|
|
1981
|
-
var TerminalInferenceUsageNumberSchema = z.number().int().safe().nonnegative().max(TERMINAL_INFERENCE_USAGE_MAX_TOKENS);
|
|
1982
|
-
var TerminalInferenceUsageDurationSchema = z.number().int().safe().nonnegative().max(TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS);
|
|
1983
|
-
var TerminalInferenceReportedAtSchema = z.iso.datetime({ offset: true, precision: 3 }).refine((value) => value.endsWith("Z"), "reportedAt must be canonical UTC (Z)");
|
|
1984
|
-
var TerminalInferenceUsageSchema = z.object({
|
|
1985
|
-
/** The adapter that actually started this task, never a requested fallback. */
|
|
1986
|
-
runtime: RuntimeIdSchema,
|
|
1987
|
-
/** Omitted unless the adapter itself exposed this provider observation. */
|
|
1988
|
-
provider: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH).optional(),
|
|
1989
|
-
/** Omitted unless the adapter itself exposed this model observation. */
|
|
1990
|
-
model: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH).optional(),
|
|
1991
|
-
/** Direct projection of the runtime's final observed input token count. */
|
|
1992
|
-
promptTokens: TerminalInferenceUsageNumberSchema.optional(),
|
|
1993
|
-
/** Direct projection of the runtime's final observed output token count. */
|
|
1994
|
-
completionTokens: TerminalInferenceUsageNumberSchema.optional(),
|
|
1995
|
-
/** Device-observed elapsed duration for the started task. */
|
|
1996
|
-
durationMs: TerminalInferenceUsageDurationSchema.optional(),
|
|
1997
|
-
/** Process-immutable Local Agent release version, owned outside the protocol. */
|
|
1998
|
-
clientVersion: z.string().min(1).max(TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH),
|
|
1999
|
-
/** Device observation time, never server receipt time. */
|
|
2000
|
-
reportedAt: TerminalInferenceReportedAtSchema
|
|
2001
|
-
});
|
|
2002
|
-
var TerminalPreparedObservationSchema = z.object({
|
|
2003
|
-
requestDigest: InputPreparationArtifactSummarySchema.shape.requestDigest,
|
|
2004
|
-
initialPromptTokens: TerminalInferenceUsageNumberSchema,
|
|
2005
|
-
maxPromptTokens: TerminalInferenceUsageNumberSchema
|
|
2006
|
-
}).strict().refine((value) => value.maxPromptTokens >= value.initialPromptTokens, {
|
|
2007
|
-
message: "maxPromptTokens must not be below initialPromptTokens",
|
|
2008
|
-
path: ["maxPromptTokens"]
|
|
2009
|
-
});
|
|
2010
|
-
var TerminalAgentHomeProjectionSchema = z.object({
|
|
2011
|
-
profileRevision: AgentHomeProjectionProfileRevisionSchema,
|
|
2012
|
-
projectionHash: AgentHomeProjectionHashSchema
|
|
2013
|
-
}).strict();
|
|
2014
|
-
var AGENT_HOME_MEMORY_DIGEST_MAX_FILES = 256;
|
|
2015
|
-
var AGENT_HOME_MEMORY_DIGEST_MAX_BYTES = 16 * 1024 * 1024;
|
|
2016
|
-
var AGENT_HOME_MEMORY_PATH_MAX_LENGTH = 1024;
|
|
2017
|
-
var AgentHomeMemoryChangedPathsSchema = z.array(z.string().min(1).max(AGENT_HOME_MEMORY_PATH_MAX_LENGTH).regex(/^[^\u0000]+$/u)).min(1).max(AGENT_HOME_MEMORY_DIGEST_MAX_FILES * 2);
|
|
2018
|
-
var TerminalAgentHomeMemoryChangeSchema = z.discriminatedUnion("outcome", [
|
|
2019
|
-
z.object({ outcome: z.literal("unchanged") }).strict(),
|
|
2020
|
-
z.object({ outcome: z.literal("reader-attributed"), paths: AgentHomeMemoryChangedPathsSchema }).strict(),
|
|
2021
|
-
z.object({ outcome: z.literal("unattributed"), paths: AgentHomeMemoryChangedPathsSchema }).strict(),
|
|
2022
|
-
z.object({ outcome: z.literal("unmeasured") }).strict()
|
|
2023
|
-
]);
|
|
2024
|
-
var TaskCompletePayloadSchema = z.object({
|
|
2025
|
-
...NO_SEALED_MEMBER,
|
|
2026
|
-
harnessId: HarnessIdSchema.optional(),
|
|
2027
|
-
summary: z.string(),
|
|
2028
|
-
/**
|
|
2029
|
-
* The runtime's closing reply: the assistant text after the last tool
|
|
2030
|
-
* interaction, or the last whole message for a runtime whose `progress`
|
|
2031
|
-
* events are whole messages (Codex). `summary` keeps the whole run's text,
|
|
2032
|
-
* so a host reads the final answer here without parsing commentary out of
|
|
2033
|
-
* it. Absent when the run ended with no closing text. An older server strips
|
|
2034
|
-
* this optional field; the host then sees it absent and keeps `summary`.
|
|
2035
|
-
*/
|
|
2036
|
-
finalMessage: z.string().optional(),
|
|
2037
|
-
sessionRef: z.string(),
|
|
2038
|
-
artifactRefs: z.array(BlobRefSchema).optional(),
|
|
2039
|
-
document: z.unknown().optional().refine((value) => value === void 0 || checkResultDocument(value).ok, {
|
|
2040
|
-
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)`
|
|
2041
|
-
}),
|
|
2042
|
-
usage: TerminalInferenceUsageSchema.optional(),
|
|
2043
|
-
/** Present on a prepared Execution only — see {@link TerminalPreparedObservationSchema}. */
|
|
2044
|
-
preparedObservation: TerminalPreparedObservationSchema.optional(),
|
|
2045
|
-
agentRef: AgentRefSchema.optional(),
|
|
2046
|
-
agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),
|
|
2047
|
-
agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional()
|
|
2048
|
-
});
|
|
2049
|
-
var RuntimeFailureClassSchema = z.enum(RUNTIME_FAILURE_CLASSES);
|
|
2050
|
-
var TaskFailureSchema = z.union([
|
|
2051
|
-
z.object({ class: z.literal("quota"), resetsAt: z.iso.datetime().optional() }).strict(),
|
|
2052
|
-
z.object({ class: RuntimeFailureClassSchema.exclude(["quota"]) }).strict()
|
|
2053
|
-
]);
|
|
2054
|
-
var TaskFailPayloadSchema = z.object({
|
|
2055
|
-
...NO_SEALED_MEMBER,
|
|
2056
|
-
/** Local interruption observation bound to the immutable offer; does not assert a cloud claim. */
|
|
2057
|
-
recovery: z.object({ kind: z.literal("daemon_interrupted"), offerId: z.uuid() }).strict().optional(),
|
|
2058
|
-
harnessId: HarnessIdSchema.optional(),
|
|
2059
|
-
reason: z.string(),
|
|
2060
|
-
retryable: z.boolean().optional(),
|
|
2061
|
-
/** Gated on the server's `runtime-failure-class` flag. Plaintext on `task.fail_sealed`. */
|
|
2062
|
-
failure: TaskFailureSchema.optional(),
|
|
2063
|
-
usage: TerminalInferenceUsageSchema.optional(),
|
|
2064
|
-
/** Present on a prepared Execution that observed provider usage before failing. */
|
|
2065
|
-
preparedObservation: TerminalPreparedObservationSchema.optional(),
|
|
2066
|
-
agentRef: AgentRefSchema.optional(),
|
|
2067
|
-
agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),
|
|
2068
|
-
agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional()
|
|
2069
|
-
});
|
|
2070
|
-
var TaskCancelledPayloadSchema = z.object({
|
|
2071
|
-
...NO_SEALED_MEMBER,
|
|
2072
|
-
harnessId: HarnessIdSchema.optional(),
|
|
2073
|
-
reason: z.string().optional(),
|
|
2074
|
-
usage: TerminalInferenceUsageSchema.optional(),
|
|
2075
|
-
agentRef: AgentRefSchema.optional(),
|
|
2076
|
-
agentHomeProjection: TerminalAgentHomeProjectionSchema.optional(),
|
|
2077
|
-
agentHomeMemoryChange: TerminalAgentHomeMemoryChangeSchema.optional()
|
|
2078
|
-
});
|
|
2079
|
-
var TaskApprovalResolvedPayloadSchema = z.object({
|
|
2080
|
-
approvalId: z.string(),
|
|
2081
|
-
decision: z.enum(["approve", "reject"]),
|
|
2082
|
-
resolvedBy: z.enum(["local"]),
|
|
2083
|
-
at: z.iso.datetime({ offset: true })
|
|
2084
|
-
});
|
|
2085
|
-
var SEALED_OFFER_FIELDS = {
|
|
2086
|
-
instruction: z.union([z.string(), InstructionBlobRefSchema]).optional(),
|
|
2087
|
-
sealing: TaskSealingSchema,
|
|
2088
|
-
sealed: SealedTaskInputSchema.optional()
|
|
2089
|
-
};
|
|
2090
|
-
var TaskOfferSealedPayloadSchema = TaskOfferPayloadSchema.extend(SEALED_OFFER_FIELDS).strict().superRefine(sealedOfferRule);
|
|
2091
|
-
var TaskOfferWithToolsetsSealedPayloadSchema = TaskOfferWithToolsetsPayloadSchema.extend(SEALED_OFFER_FIELDS).strict().superRefine(sealedOfferRule);
|
|
2092
|
-
var TaskOfferForAgentSealedPayloadSchema = TaskOfferForAgentPayloadSchema.extend(SEALED_OFFER_FIELDS).strict().superRefine(sealedOfferRule);
|
|
2093
|
-
var TaskOfferForAgentWithEgressSealedPayloadSchema = TaskOfferForAgentWithEgressPayloadSchema.extend(SEALED_OFFER_FIELDS).strict().superRefine(sealedOfferRule);
|
|
2094
|
-
var TaskOfferForAgentWithEgressFreshSealedPayloadSchema = TaskOfferForAgentWithEgressFreshPayloadSchema.extend({ ...SEALED_OFFER_FIELDS, routineRef: RoutineRefSchema.optional() }).strict().superRefine(sealedOfferRule);
|
|
2095
|
-
var TaskSteerSealedPayloadSchema = z.object({ steerId: z.uuid(), sealed: SealedTaskInputSchema }).strict();
|
|
2096
|
-
var TaskCompleteSealedPayloadSchema = TaskCompletePayloadSchema.omit({
|
|
2097
|
-
summary: true,
|
|
2098
|
-
finalMessage: true,
|
|
2099
|
-
document: true,
|
|
2100
|
-
artifactRefs: true,
|
|
2101
|
-
preparedObservation: true
|
|
2102
|
-
}).extend({ sealed: SealedTaskOutputSchema }).strict();
|
|
2103
|
-
var TaskFailSealedPayloadSchema = TaskFailPayloadSchema.omit({ reason: true, preparedObservation: true }).extend({ sealed: SealedTaskOutputSchema }).strict();
|
|
2104
|
-
var TaskDeclineSealedPayloadSchema = DeclineFields.omit({ reason: true }).extend({ code: z.enum(HOME_DECLINE_CODES).optional(), sealed: SealedTaskOutputSchema }).strict();
|
|
2105
|
-
var TaskCancelledSealedPayloadSchema = TaskCancelledPayloadSchema.omit({ reason: true }).extend({ sealed: SealedTaskOutputSchema }).strict();
|
|
2106
|
-
var TaskProgressSealedPayloadSchema = TaskProgressPayloadSchema.omit({ events: true }).extend({ sealed: SealedTaskOutputSchema }).strict();
|
|
2107
|
-
var TaskArtifactSealedPayloadSchema = TaskArtifactPayloadSchema.omit({ inline: true, blobRef: true }).extend({ artifactId: z.uuid(), sealed: SealedTaskOutputSchema }).strict();
|
|
2108
|
-
var TaskAwaitApprovalSealedPayloadSchema = TaskAwaitApprovalPayloadSchema.omit({ summary: true }).extend({ approvalId: z.string().min(1), sealed: SealedTaskOutputSchema }).strict();
|
|
2109
|
-
var TASK_OFFER_PAYLOAD_SCHEMAS = {
|
|
2110
|
-
"task.offer": TaskOfferPayloadSchema,
|
|
2111
|
-
"task.offer_with_toolsets": TaskOfferWithToolsetsPayloadSchema,
|
|
2112
|
-
"task.offer_for_agent": TaskOfferForAgentPayloadSchema,
|
|
2113
|
-
"task.offer_for_agent_with_egress": TaskOfferForAgentWithEgressPayloadSchema,
|
|
2114
|
-
"task.offer_for_agent_with_egress_fresh": TaskOfferForAgentWithEgressFreshPayloadSchema,
|
|
2115
|
-
"task.offer_prepared": TaskOfferPreparedPayloadSchema,
|
|
2116
|
-
"task.offer_sealed": TaskOfferSealedPayloadSchema,
|
|
2117
|
-
"task.offer_with_toolsets_sealed": TaskOfferWithToolsetsSealedPayloadSchema,
|
|
2118
|
-
"task.offer_for_agent_sealed": TaskOfferForAgentSealedPayloadSchema,
|
|
2119
|
-
"task.offer_for_agent_with_egress_sealed": TaskOfferForAgentWithEgressSealedPayloadSchema,
|
|
2120
|
-
"task.offer_for_agent_with_egress_fresh_sealed": TaskOfferForAgentWithEgressFreshSealedPayloadSchema
|
|
2121
|
-
};
|
|
2122
|
-
var TASK_OFFER_TYPES = Object.freeze(
|
|
2123
|
-
Object.keys(TASK_OFFER_PAYLOAD_SCHEMAS)
|
|
2124
|
-
);
|
|
2125
|
-
function isTaskOfferType(type) {
|
|
2126
|
-
return Object.hasOwn(TASK_OFFER_PAYLOAD_SCHEMAS, type);
|
|
2127
|
-
}
|
|
2128
|
-
var MESSAGE_PAYLOAD_SCHEMAS = {
|
|
2129
|
-
"conn.hello": ConnHelloPayloadSchema,
|
|
2130
|
-
"conn.ack": ConnAckPayloadSchema,
|
|
2131
|
-
...TASK_OFFER_PAYLOAD_SCHEMAS,
|
|
2132
|
-
"agent.egress.reliable": AgentEgressReliablePayloadSchema,
|
|
2133
|
-
"agent.egress.ack": AgentEgressAckPayloadSchema,
|
|
2134
|
-
"agent.message.draft": AgentMessageDraftPayloadSchema,
|
|
2135
|
-
"agent.message.publish": AgentMessagePublishPayloadSchema,
|
|
2136
|
-
"agent.message.disposition": AgentMessageDispositionPayloadSchema,
|
|
2137
|
-
"agent.content.read": AgentContentReadPayloadSchema,
|
|
2138
|
-
"agent.content.receipt": AgentContentReceiptPayloadSchema,
|
|
2139
|
-
"agent.home.projection": AgentHomeProjectionPayloadSchema,
|
|
2140
|
-
"agent.input.preparation": AgentInputPreparationPayloadSchema,
|
|
2141
|
-
"provider.provisioning.available": ProviderProvisioningAvailablePayloadSchema,
|
|
2142
|
-
"agent.memory.intent.available": AgentMemoryIntentAvailablePayloadSchema,
|
|
2143
|
-
"task.approve": TaskApprovePayloadSchema,
|
|
2144
|
-
"task.reject": TaskRejectPayloadSchema,
|
|
2145
|
-
"task.cancel": TaskCancelPayloadSchema,
|
|
2146
|
-
"task.steer": TaskSteerPayloadSchema,
|
|
2147
|
-
"task.claim": TaskClaimPayloadSchema,
|
|
2148
|
-
"task.started": TaskStartedPayloadSchema,
|
|
2149
|
-
"task.decline": TaskDeclinePayloadSchema,
|
|
2150
|
-
"task.progress": TaskProgressPayloadSchema,
|
|
2151
|
-
"task.artifact": TaskArtifactPayloadSchema,
|
|
2152
|
-
"task.await_approval": TaskAwaitApprovalPayloadSchema,
|
|
2153
|
-
"task.complete": TaskCompletePayloadSchema,
|
|
2154
|
-
"task.fail": TaskFailPayloadSchema,
|
|
2155
|
-
"task.cancelled": TaskCancelledPayloadSchema,
|
|
2156
|
-
"task.approval_resolved": TaskApprovalResolvedPayloadSchema,
|
|
2157
|
-
"task.steer_sealed": TaskSteerSealedPayloadSchema,
|
|
2158
|
-
"task.complete_sealed": TaskCompleteSealedPayloadSchema,
|
|
2159
|
-
"task.fail_sealed": TaskFailSealedPayloadSchema,
|
|
2160
|
-
"task.decline_sealed": TaskDeclineSealedPayloadSchema,
|
|
2161
|
-
"task.cancelled_sealed": TaskCancelledSealedPayloadSchema,
|
|
2162
|
-
"task.progress_sealed": TaskProgressSealedPayloadSchema,
|
|
2163
|
-
"task.artifact_sealed": TaskArtifactSealedPayloadSchema,
|
|
2164
|
-
"task.await_approval_sealed": TaskAwaitApprovalSealedPayloadSchema,
|
|
2165
|
-
"e2ee.key_package.available": E2eeKeyPackageAvailablePayloadSchema
|
|
2166
|
-
};
|
|
2167
|
-
var MESSAGE_TYPES = Object.keys(MESSAGE_PAYLOAD_SCHEMAS);
|
|
2168
|
-
var SERVER_TO_DAEMON_TYPES = [
|
|
2169
|
-
"conn.ack",
|
|
2170
|
-
"task.offer",
|
|
2171
|
-
"task.offer_with_toolsets",
|
|
2172
|
-
"task.offer_for_agent",
|
|
2173
|
-
"task.offer_for_agent_with_egress",
|
|
2174
|
-
"task.offer_for_agent_with_egress_fresh",
|
|
2175
|
-
"task.offer_prepared",
|
|
2176
|
-
"agent.egress.ack",
|
|
2177
|
-
"agent.message.disposition",
|
|
2178
|
-
"agent.content.read",
|
|
2179
|
-
"agent.home.projection",
|
|
2180
|
-
"agent.input.preparation",
|
|
2181
|
-
"provider.provisioning.available",
|
|
2182
|
-
"agent.memory.intent.available",
|
|
2183
|
-
"task.approve",
|
|
2184
|
-
"task.reject",
|
|
2185
|
-
"task.cancel",
|
|
2186
|
-
"task.steer",
|
|
2187
|
-
"task.offer_sealed",
|
|
2188
|
-
"task.offer_with_toolsets_sealed",
|
|
2189
|
-
"task.offer_for_agent_sealed",
|
|
2190
|
-
"task.offer_for_agent_with_egress_sealed",
|
|
2191
|
-
"task.offer_for_agent_with_egress_fresh_sealed",
|
|
2192
|
-
"task.steer_sealed",
|
|
2193
|
-
"e2ee.key_package.available"
|
|
2194
|
-
];
|
|
2195
|
-
var DAEMON_TO_SERVER_TYPES = [
|
|
2196
|
-
"task.claim",
|
|
2197
|
-
"task.started",
|
|
2198
|
-
"task.decline",
|
|
2199
|
-
"task.progress",
|
|
2200
|
-
"task.artifact",
|
|
2201
|
-
"task.await_approval",
|
|
2202
|
-
"task.complete",
|
|
2203
|
-
"task.fail",
|
|
2204
|
-
"task.cancelled",
|
|
2205
|
-
"task.approval_resolved",
|
|
2206
|
-
"agent.egress.reliable",
|
|
2207
|
-
"agent.message.draft",
|
|
2208
|
-
"agent.message.publish",
|
|
2209
|
-
"agent.content.receipt",
|
|
2210
|
-
"task.complete_sealed",
|
|
2211
|
-
"task.fail_sealed",
|
|
2212
|
-
"task.decline_sealed",
|
|
2213
|
-
"task.cancelled_sealed",
|
|
2214
|
-
"task.progress_sealed",
|
|
2215
|
-
"task.artifact_sealed",
|
|
2216
|
-
"task.await_approval_sealed"
|
|
2217
|
-
];
|
|
2218
|
-
|
|
2219
|
-
// src/agent-memory-intent.ts
|
|
2220
|
-
var AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES = 262144;
|
|
2221
|
-
var AGENT_MEMORY_INTENT_PATH_MAX_BYTES = 1024;
|
|
2222
|
-
var AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES = 128;
|
|
2223
|
-
var SHA256_REVISION = /^sha256:[0-9a-f]{64}$/u;
|
|
2224
|
-
var AgentMemoryIntentRevisionSchema = z.string().regex(SHA256_REVISION, "revision must be lowercase sha256:<64 hex>");
|
|
2225
|
-
var AgentMemoryIntentOperationDigestSchema = z.string().regex(SHA256_REVISION, "operationDigest must be lowercase sha256:<64 hex>");
|
|
2226
|
-
var AgentMemoryIntentPathSchema = z.string().min(1).max(AGENT_MEMORY_INTENT_PATH_MAX_BYTES).regex(/^[\x20\x21\x23-\x5b\x5d-\x7e]+$/u, "path must be printable ASCII without quote or backslash");
|
|
2227
|
-
var AgentMemoryIntentApprovalRefSchema = z.string().regex(
|
|
2228
|
-
new RegExp(`^[A-Za-z0-9._:-]{1,${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES}}$`, "u"),
|
|
2229
|
-
`approvalRef must be 1..${AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES} characters of [A-Za-z0-9._:-]`
|
|
2230
|
-
);
|
|
2231
|
-
var LONE_SURROGATE2 = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
|
|
2232
|
-
var utf8 = new TextEncoder();
|
|
2233
|
-
var AgentMemoryIntentContentSchema = z.string().refine((value) => !LONE_SURROGATE2.test(value), "content must be well-formed Unicode (encodable as UTF-8)").refine(
|
|
2234
|
-
(value) => utf8.encode(value).byteLength <= AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES,
|
|
2235
|
-
`content must not exceed ${AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES} UTF-8 bytes`
|
|
2236
|
-
);
|
|
2237
|
-
var AGENT_MEMORY_INTENT_OPERATIONS = ["replace", "delete"];
|
|
2238
|
-
var AgentMemoryIntentOperationSchema = z.enum(AGENT_MEMORY_INTENT_OPERATIONS);
|
|
2239
|
-
var AgentMemoryIntentV1Schema = z.object({
|
|
2240
|
-
intentId: z.uuid(),
|
|
2241
|
-
agentRef: AgentHomeProjectionAgentRefSchema,
|
|
2242
|
-
path: AgentMemoryIntentPathSchema,
|
|
2243
|
-
operation: AgentMemoryIntentOperationSchema,
|
|
2244
|
-
baseRevision: AgentMemoryIntentRevisionSchema,
|
|
2245
|
-
targetRevision: AgentMemoryIntentRevisionSchema.nullable(),
|
|
2246
|
-
content: AgentMemoryIntentContentSchema.optional(),
|
|
2247
|
-
approvalRef: AgentMemoryIntentApprovalRefSchema,
|
|
2248
|
-
operationDigest: AgentMemoryIntentOperationDigestSchema
|
|
2249
|
-
}).strict().superRefine((intent, ctx) => {
|
|
2250
|
-
if (intent.operation === "delete") {
|
|
2251
|
-
if (intent.targetRevision !== null) {
|
|
2252
|
-
ctx.addIssue({ code: "custom", path: ["targetRevision"], message: "a delete intent has a null targetRevision" });
|
|
2253
|
-
}
|
|
2254
|
-
if (intent.content !== void 0) {
|
|
2255
|
-
ctx.addIssue({ code: "custom", path: ["content"], message: "a delete intent never carries content" });
|
|
2256
|
-
}
|
|
2257
|
-
return;
|
|
2258
|
-
}
|
|
2259
|
-
if (intent.targetRevision === null) {
|
|
2260
|
-
ctx.addIssue({ code: "custom", path: ["targetRevision"], message: "a replace intent requires a targetRevision" });
|
|
2261
|
-
} else if (intent.targetRevision === intent.baseRevision) {
|
|
2262
|
-
ctx.addIssue({ code: "custom", path: ["targetRevision"], message: "targetRevision must differ from baseRevision" });
|
|
2263
|
-
}
|
|
2264
|
-
});
|
|
2265
|
-
var AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES = [
|
|
2266
|
-
"intent_revoked",
|
|
2267
|
-
"intent_expired",
|
|
2268
|
-
"placement_changed",
|
|
2269
|
-
"profile_revision_changed"
|
|
2270
|
-
];
|
|
2271
|
-
var AgentMemoryIntentHostTerminalCodeSchema = z.enum(AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES);
|
|
2272
|
-
var AGENT_MEMORY_INTENT_REJECTION_CODES = [
|
|
2273
|
-
"intent_invalid",
|
|
2274
|
-
"path_invalid",
|
|
2275
|
-
"memory_md_not_deletable",
|
|
2276
|
-
"content_invalid",
|
|
2277
|
-
"intent_digest_mismatch",
|
|
2278
|
-
"agent_ref_mismatch",
|
|
2279
|
-
"agent_home_unavailable",
|
|
2280
|
-
...AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES
|
|
2281
|
-
];
|
|
2282
|
-
var AgentMemoryIntentRejectionCodeSchema = z.enum(AGENT_MEMORY_INTENT_REJECTION_CODES);
|
|
2283
|
-
var AgentMemoryIntentFileObservationSchema = z.object({
|
|
2284
|
-
exists: z.boolean(),
|
|
2285
|
-
revision: AgentMemoryIntentRevisionSchema
|
|
2286
|
-
}).strict();
|
|
2287
|
-
var completionIdentity2 = {
|
|
2288
|
-
intentId: z.uuid(),
|
|
2289
|
-
agentRef: AgentHomeProjectionAgentRefSchema,
|
|
2290
|
-
path: AgentMemoryIntentPathSchema,
|
|
2291
|
-
operation: AgentMemoryIntentOperationSchema,
|
|
2292
|
-
operationDigest: AgentMemoryIntentOperationDigestSchema
|
|
2293
|
-
};
|
|
2294
|
-
var AppliedCompletionSchema2 = z.object({ ...completionIdentity2, outcome: z.literal("applied"), result: AgentMemoryIntentFileObservationSchema }).strict();
|
|
2295
|
-
var ConflictCompletionSchema = z.object({ ...completionIdentity2, outcome: z.literal("conflict"), observed: AgentMemoryIntentFileObservationSchema }).strict();
|
|
2296
|
-
var RejectedCompletionSchema2 = z.object({ ...completionIdentity2, outcome: z.literal("rejected"), code: AgentMemoryIntentRejectionCodeSchema }).strict();
|
|
2297
|
-
var UncertainCompletionSchema = z.object({ ...completionIdentity2, outcome: z.literal("uncertain"), observed: AgentMemoryIntentFileObservationSchema }).strict();
|
|
2298
|
-
var AgentMemoryIntentCompletionSchema = z.discriminatedUnion("outcome", [
|
|
2299
|
-
AppliedCompletionSchema2,
|
|
2300
|
-
ConflictCompletionSchema,
|
|
2301
|
-
RejectedCompletionSchema2,
|
|
2302
|
-
UncertainCompletionSchema
|
|
2303
|
-
]);
|
|
2304
|
-
var AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS = ["recorded", "idempotent", "conflict", "host_terminal"];
|
|
2305
|
-
var AgentMemoryIntentReadbackDispositionSchema = z.enum(AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS);
|
|
2306
|
-
var AgentMemoryIntentReadbackSchema = z.object({
|
|
2307
|
-
tenantId: z.string().min(1),
|
|
2308
|
-
deviceId: z.string().min(1),
|
|
2309
|
-
intentId: z.uuid(),
|
|
2310
|
-
disposition: AgentMemoryIntentReadbackDispositionSchema,
|
|
2311
|
-
completion: AgentMemoryIntentCompletionSchema,
|
|
2312
|
-
recordedAt: z.iso.datetime({ offset: true })
|
|
2313
|
-
}).strict().superRefine((readback, ctx) => {
|
|
2314
|
-
if (readback.completion.intentId !== readback.intentId) {
|
|
2315
|
-
ctx.addIssue({ code: "custom", path: ["completion", "intentId"], message: "completion intentId must equal readback intentId" });
|
|
2316
|
-
}
|
|
2317
|
-
if (readback.disposition === "host_terminal" && (readback.completion.outcome !== "rejected" || !AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.includes(readback.completion.code))) {
|
|
2318
|
-
ctx.addIssue({
|
|
2319
|
-
code: "custom",
|
|
2320
|
-
path: ["completion"],
|
|
2321
|
-
message: `a host_terminal readback must carry a rejected completion with one of: ${AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES.join(", ")}`
|
|
2322
|
-
});
|
|
2323
|
-
}
|
|
2324
|
-
});
|
|
2325
|
-
var AGENT_MEMORY_INTENT_RESERVATIONS = ["held", "none"];
|
|
2326
|
-
var AgentMemoryIntentReservationSchema = z.enum(AGENT_MEMORY_INTENT_RESERVATIONS);
|
|
2327
|
-
var AgentMemoryIntentFetchRequestSchema = z.object({
|
|
2328
|
-
intentId: z.uuid(),
|
|
2329
|
-
reservation: AgentMemoryIntentReservationSchema
|
|
2330
|
-
}).strict();
|
|
2331
|
-
var AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS = ["release", "withheld", "terminal", "deferred"];
|
|
2332
|
-
var AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION = {
|
|
2333
|
-
held: ["release", "withheld", "terminal"],
|
|
2334
|
-
none: ["terminal", "deferred"]
|
|
2335
|
-
};
|
|
2336
|
-
function requireNoContent(intent, ctx, disposition) {
|
|
2337
|
-
if (intent.content !== void 0) {
|
|
2338
|
-
ctx.addIssue({ code: "custom", path: ["intent", "content"], message: `a ${disposition} fetch response never carries content` });
|
|
2339
|
-
}
|
|
2340
|
-
}
|
|
2341
|
-
var ReleaseFetchResponseSchema = z.object({ disposition: z.literal("release"), intent: AgentMemoryIntentV1Schema }).strict().superRefine((response, ctx) => {
|
|
2342
|
-
if (response.intent.operation === "replace" && response.intent.content === void 0) {
|
|
2343
|
-
ctx.addIssue({ code: "custom", path: ["intent", "content"], message: "a replace release must carry content" });
|
|
2344
|
-
}
|
|
2345
|
-
});
|
|
2346
|
-
var WithheldFetchResponseSchema = z.object({ disposition: z.literal("withheld"), intent: AgentMemoryIntentV1Schema, code: AgentMemoryIntentHostTerminalCodeSchema }).strict().superRefine((response, ctx) => requireNoContent(response.intent, ctx, "withheld"));
|
|
2347
|
-
var TerminalFetchResponseSchema = z.object({ disposition: z.literal("terminal"), intent: AgentMemoryIntentV1Schema, readback: AgentMemoryIntentReadbackSchema }).strict().superRefine((response, ctx) => {
|
|
2348
|
-
requireNoContent(response.intent, ctx, "terminal");
|
|
2349
|
-
const { intent, readback } = response;
|
|
2350
|
-
if (readback.intentId !== intent.intentId) {
|
|
2351
|
-
ctx.addIssue({ code: "custom", path: ["readback", "intentId"], message: "readback intentId must equal intent intentId" });
|
|
2352
|
-
}
|
|
2353
|
-
const completion = readback.completion;
|
|
2354
|
-
if (completion.agentRef.agentId !== intent.agentRef.agentId || completion.agentRef.profileRevision !== intent.agentRef.profileRevision || completion.path !== intent.path || completion.operation !== intent.operation || completion.operationDigest !== intent.operationDigest) {
|
|
2355
|
-
ctx.addIssue({
|
|
2356
|
-
code: "custom",
|
|
2357
|
-
path: ["readback", "completion"],
|
|
2358
|
-
message: "readback completion identity must equal the intent identity and operationDigest"
|
|
2359
|
-
});
|
|
2360
|
-
}
|
|
2361
|
-
});
|
|
2362
|
-
var DeferredFetchResponseSchema = z.object({ disposition: z.literal("deferred"), intent: AgentMemoryIntentV1Schema }).strict().superRefine((response, ctx) => requireNoContent(response.intent, ctx, "deferred"));
|
|
2363
|
-
var AgentMemoryIntentFetchResponseSchema = z.discriminatedUnion("disposition", [
|
|
2364
|
-
ReleaseFetchResponseSchema,
|
|
2365
|
-
WithheldFetchResponseSchema,
|
|
2366
|
-
TerminalFetchResponseSchema,
|
|
2367
|
-
DeferredFetchResponseSchema
|
|
2368
|
-
]);
|
|
2369
|
-
function agentMemoryIntentFetchResponseSchemaFor(reservation) {
|
|
2370
|
-
const allowed = AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION[AgentMemoryIntentReservationSchema.parse(reservation)];
|
|
2371
|
-
return AgentMemoryIntentFetchResponseSchema.superRefine((response, ctx) => {
|
|
2372
|
-
if (!allowed.includes(response.disposition)) {
|
|
2373
|
-
ctx.addIssue({
|
|
2374
|
-
code: "custom",
|
|
2375
|
-
path: ["disposition"],
|
|
2376
|
-
message: `a ${reservation} reservation allows only: ${allowed.join(", ")}`
|
|
2377
|
-
});
|
|
2378
|
-
}
|
|
2379
|
-
});
|
|
2380
|
-
}
|
|
2381
|
-
var AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES = 512 * 1024;
|
|
2382
|
-
var AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE = 2147483647;
|
|
2383
|
-
var OPAQUE_REFERENCE_MAX_BYTES = 512;
|
|
2384
|
-
var opaqueReference = (field) => z.string().min(1).max(OPAQUE_REFERENCE_MAX_BYTES).refine((value) => new TextEncoder().encode(value).byteLength <= OPAQUE_REFERENCE_MAX_BYTES, {
|
|
2385
|
-
message: `${field} must not exceed ${OPAQUE_REFERENCE_MAX_BYTES} UTF-8 bytes`
|
|
2386
|
-
}).regex(/^[^\u0000-\u001f\u007f\r\n]+$/u, `${field} must not contain control characters`);
|
|
2387
|
-
var AgentMemoryProjectionGrantRefSchema = opaqueReference("grantRef");
|
|
2388
|
-
var AgentMemoryProjectionSessionRefSchema = opaqueReference("sessionRef");
|
|
2389
|
-
var AgentMemoryProjectionWriterEpochSchema = z.number().int().positive().max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);
|
|
2390
|
-
var AgentMemoryProjectionSourceSeqSchema = z.number().int().positive().max(AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE);
|
|
2391
|
-
function agentMemoryProjectionBase64UrlByteLength(value) {
|
|
2392
|
-
if (!/^[A-Za-z0-9_-]*$/u.test(value) || value.length % 4 === 1) return void 0;
|
|
2393
|
-
const complete = Math.floor(value.length / 4) * 3;
|
|
2394
|
-
const tail = value.length % 4;
|
|
2395
|
-
return complete + (tail === 0 ? 0 : tail - 1);
|
|
2396
|
-
}
|
|
2397
|
-
var AgentMemoryProjectionSnapshotSchema = z.object({
|
|
2398
|
-
redactedHash: AgentEgressContentHashSchema,
|
|
2399
|
-
redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),
|
|
2400
|
-
redactedBytes: z.string().max(Math.ceil(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES / 3) * 4)
|
|
2401
|
-
}).strict().superRefine((snapshot, ctx) => {
|
|
2402
|
-
const actual = agentMemoryProjectionBase64UrlByteLength(snapshot.redactedBytes);
|
|
2403
|
-
if (actual === void 0) {
|
|
2404
|
-
ctx.addIssue({ code: "custom", path: ["redactedBytes"], message: "redactedBytes must be unpadded base64url" });
|
|
2405
|
-
return;
|
|
2406
|
-
}
|
|
2407
|
-
if (actual !== snapshot.redactedByteCount) {
|
|
2408
|
-
ctx.addIssue({
|
|
2409
|
-
code: "custom",
|
|
2410
|
-
path: ["redactedByteCount"],
|
|
2411
|
-
message: "redactedByteCount must equal the decoded redactedBytes length"
|
|
2412
|
-
});
|
|
2413
|
-
}
|
|
2414
|
-
});
|
|
2415
|
-
var AgentMemoryProjectionMutationSchema = z.object({
|
|
2416
|
-
taskId: z.string().min(1).max(512),
|
|
2417
|
-
agentRef: AgentRefSchema,
|
|
2418
|
-
sessionRef: AgentMemoryProjectionSessionRefSchema,
|
|
2419
|
-
runtimeId: RuntimeIdSchema,
|
|
2420
|
-
grantRef: AgentMemoryProjectionGrantRefSchema,
|
|
2421
|
-
writerEpoch: AgentMemoryProjectionWriterEpochSchema,
|
|
2422
|
-
sourceSeq: AgentMemoryProjectionSourceSeqSchema,
|
|
2423
|
-
mutationId: z.uuid(),
|
|
2424
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
2425
|
-
snapshot: AgentMemoryProjectionSnapshotSchema
|
|
2426
|
-
}).strict();
|
|
2427
|
-
var AgentMemoryProjectionMeteringReceiptSchema = z.object({
|
|
2428
|
-
meteringReceiptId: z.uuid(),
|
|
2429
|
-
acceptedRedactedBytes: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),
|
|
2430
|
-
recordedAt: z.iso.datetime({ offset: true })
|
|
2431
|
-
}).strict();
|
|
2432
|
-
var AgentMemoryProjectionReceiptSchema = z.object({
|
|
2433
|
-
outcome: z.enum(["accepted", "idempotent"]),
|
|
2434
|
-
tenantId: z.string().min(1),
|
|
2435
|
-
deviceId: z.string().min(1),
|
|
2436
|
-
taskId: z.string().min(1).max(512),
|
|
2437
|
-
agentRef: AgentRefSchema,
|
|
2438
|
-
sessionRef: AgentMemoryProjectionSessionRefSchema,
|
|
2439
|
-
runtimeId: RuntimeIdSchema,
|
|
2440
|
-
grantRef: AgentMemoryProjectionGrantRefSchema,
|
|
2441
|
-
writerEpoch: AgentMemoryProjectionWriterEpochSchema,
|
|
2442
|
-
sourceSeq: AgentMemoryProjectionSourceSeqSchema,
|
|
2443
|
-
mutationId: z.uuid(),
|
|
2444
|
-
policyRevision: AgentEgressPolicyRevisionSchema,
|
|
2445
|
-
redactedHash: AgentEgressContentHashSchema,
|
|
2446
|
-
redactedByteCount: z.number().int().nonnegative().max(AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES),
|
|
2447
|
-
metering: AgentMemoryProjectionMeteringReceiptSchema
|
|
2448
|
-
}).strict();
|
|
2449
|
-
var AgentMemoryProjectionEraseResultSchema = z.object({ nextWriterEpoch: AgentMemoryProjectionWriterEpochSchema }).strict();
|
|
2450
|
-
var REQUIRED_TASK_ID = z.string().min(1);
|
|
2451
|
-
var OPTIONAL_TASK_ID = REQUIRED_TASK_ID.optional();
|
|
2452
|
-
var FORBIDDEN_TASK_ID = z.never().optional();
|
|
2453
|
-
var REQUIRED_SEQ = z.number().int();
|
|
2454
|
-
var OPTIONAL_SEQ = REQUIRED_SEQ.optional();
|
|
2455
|
-
function envelopeShape(type, taskId, seq) {
|
|
2456
|
-
return z.object({
|
|
2457
|
-
// A known payload shape does not authorize interpreting another wire major
|
|
2458
|
-
// as v1. Keep the public number type and all supported v1 bytes unchanged.
|
|
2459
|
-
v: z.number().int().refine((version) => version === PROTOCOL_VERSION, {
|
|
2460
|
-
message: "unsupported protocol version"
|
|
2461
|
-
}),
|
|
2462
|
-
id: z.uuid(),
|
|
2463
|
-
ts: z.iso.datetime({ offset: true }),
|
|
2464
|
-
type: z.literal(type),
|
|
2465
|
-
task_id: taskId,
|
|
2466
|
-
session_ref: z.string().optional(),
|
|
2467
|
-
seq,
|
|
2468
|
-
payload: MESSAGE_PAYLOAD_SCHEMAS[type]
|
|
2469
|
-
});
|
|
2470
|
-
}
|
|
2471
|
-
var EnvelopeSchema = z.discriminatedUnion("type", [
|
|
2472
|
-
// conn.* — task_id stays optional (no task routing). conn.hello is
|
|
2473
|
-
// daemon -> server (no cursor to satisfy on this leg); conn.ack is
|
|
2474
|
-
// server -> daemon and therefore carries the required redelivery `seq`.
|
|
2475
|
-
envelopeShape("conn.hello", OPTIONAL_TASK_ID, OPTIONAL_SEQ),
|
|
2476
|
-
envelopeShape("conn.ack", OPTIONAL_TASK_ID, REQUIRED_SEQ),
|
|
2477
|
-
// task.* server -> daemon: task_id required (routing key) + seq required
|
|
2478
|
-
// (per-device redelivery cursor).
|
|
2479
|
-
envelopeShape("task.offer", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2480
|
-
envelopeShape("task.offer_with_toolsets", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2481
|
-
envelopeShape("task.offer_for_agent", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2482
|
-
envelopeShape("task.offer_for_agent_with_egress", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2483
|
-
envelopeShape("task.offer_for_agent_with_egress_fresh", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2484
|
-
envelopeShape("task.offer_prepared", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2485
|
-
envelopeShape("agent.egress.ack", OPTIONAL_TASK_ID, REQUIRED_SEQ),
|
|
2486
|
-
envelopeShape("agent.message.disposition", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2487
|
-
envelopeShape("agent.content.read", OPTIONAL_TASK_ID, REQUIRED_SEQ),
|
|
2488
|
-
envelopeShape("agent.home.projection", FORBIDDEN_TASK_ID, REQUIRED_SEQ),
|
|
2489
|
-
envelopeShape("agent.input.preparation", FORBIDDEN_TASK_ID, REQUIRED_SEQ),
|
|
2490
|
-
envelopeShape("provider.provisioning.available", FORBIDDEN_TASK_ID, REQUIRED_SEQ),
|
|
2491
|
-
envelopeShape("agent.memory.intent.available", FORBIDDEN_TASK_ID, REQUIRED_SEQ),
|
|
2492
|
-
envelopeShape("task.approve", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2493
|
-
envelopeShape("task.reject", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2494
|
-
envelopeShape("task.cancel", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2495
|
-
envelopeShape("task.steer", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2496
|
-
// task.* daemon -> server: task_id required (routing key); envelope-level
|
|
2497
|
-
// seq is not required in this direction in M1 (no daemon->server
|
|
2498
|
-
// redelivery cursor yet — see docs/protocol.md).
|
|
2499
|
-
envelopeShape("task.claim", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2500
|
-
envelopeShape("task.started", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2501
|
-
envelopeShape("task.decline", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2502
|
-
envelopeShape("task.progress", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2503
|
-
envelopeShape("task.artifact", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2504
|
-
envelopeShape("task.await_approval", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2505
|
-
envelopeShape("task.complete", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2506
|
-
envelopeShape("task.fail", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2507
|
-
envelopeShape("task.cancelled", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2508
|
-
envelopeShape("task.approval_resolved", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2509
|
-
envelopeShape("agent.egress.reliable", OPTIONAL_TASK_ID, OPTIONAL_SEQ),
|
|
2510
|
-
envelopeShape("agent.message.draft", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2511
|
-
envelopeShape("agent.message.publish", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2512
|
-
envelopeShape("agent.content.receipt", OPTIONAL_TASK_ID, OPTIONAL_SEQ),
|
|
2513
|
-
// Sealed payload v1 (#654). Appended last, so every released branch keeps
|
|
2514
|
-
// its position in the union.
|
|
2515
|
-
envelopeShape("task.offer_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2516
|
-
envelopeShape("task.offer_with_toolsets_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2517
|
-
envelopeShape("task.offer_for_agent_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2518
|
-
envelopeShape("task.offer_for_agent_with_egress_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2519
|
-
envelopeShape("task.offer_for_agent_with_egress_fresh_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2520
|
-
envelopeShape("task.steer_sealed", REQUIRED_TASK_ID, REQUIRED_SEQ),
|
|
2521
|
-
envelopeShape("task.complete_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2522
|
-
envelopeShape("task.fail_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2523
|
-
envelopeShape("task.decline_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2524
|
-
envelopeShape("task.cancelled_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2525
|
-
envelopeShape("task.progress_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2526
|
-
envelopeShape("task.artifact_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2527
|
-
envelopeShape("task.await_approval_sealed", REQUIRED_TASK_ID, OPTIONAL_SEQ),
|
|
2528
|
-
// E2EE key package notice (#654 E2c-3), appended for the same reason.
|
|
2529
|
-
envelopeShape("e2ee.key_package.available", FORBIDDEN_TASK_ID, REQUIRED_SEQ)
|
|
2530
|
-
]);
|
|
2531
|
-
function isServerToDaemonType(type) {
|
|
2532
|
-
return SERVER_TO_DAEMON_TYPES.includes(type);
|
|
2533
|
-
}
|
|
2534
|
-
|
|
2535
|
-
// src/errors.ts
|
|
2536
|
-
var ProtocolError = class extends Error {
|
|
2537
|
-
constructor(message, options) {
|
|
2538
|
-
super(message, options);
|
|
2539
|
-
this.name = "ProtocolError";
|
|
2540
|
-
}
|
|
2541
|
-
};
|
|
2542
|
-
var EnvelopeParseError = class extends ProtocolError {
|
|
2543
|
-
constructor(message, cause) {
|
|
2544
|
-
super(message, { cause });
|
|
2545
|
-
this.name = "EnvelopeParseError";
|
|
2546
|
-
}
|
|
2547
|
-
};
|
|
2548
|
-
var UnknownMessageTypeError = class extends ProtocolError {
|
|
2549
|
-
type;
|
|
2550
|
-
constructor(type) {
|
|
2551
|
-
super(`Unknown message type: ${String(type)}`);
|
|
2552
|
-
this.name = "UnknownMessageTypeError";
|
|
2553
|
-
this.type = type;
|
|
2554
|
-
}
|
|
2555
|
-
};
|
|
2556
|
-
var EnvelopeValidationError = class extends ProtocolError {
|
|
2557
|
-
issues;
|
|
2558
|
-
constructor(message, issues) {
|
|
2559
|
-
super(message, { cause: issues });
|
|
2560
|
-
this.name = "EnvelopeValidationError";
|
|
2561
|
-
this.issues = issues;
|
|
2562
|
-
}
|
|
2563
|
-
};
|
|
2564
|
-
|
|
2565
|
-
// src/codec.ts
|
|
2566
|
-
var MESSAGE_TYPE_SET = new Set(MESSAGE_TYPES);
|
|
2567
|
-
function decodeText(input) {
|
|
2568
|
-
return typeof input === "string" ? input : new TextDecoder("utf-8").decode(input);
|
|
2569
|
-
}
|
|
2570
|
-
function parseMessage(data) {
|
|
2571
|
-
const result = EnvelopeSchema.safeParse(data);
|
|
2572
|
-
if (result.success) {
|
|
2573
|
-
return result.data;
|
|
2574
|
-
}
|
|
2575
|
-
const typeValue = typeof data === "object" && data !== null && !Array.isArray(data) ? data.type : void 0;
|
|
2576
|
-
if (typeof typeValue !== "string" || !MESSAGE_TYPE_SET.has(typeValue)) {
|
|
2577
|
-
throw new UnknownMessageTypeError(typeValue);
|
|
2578
|
-
}
|
|
2579
|
-
throw new EnvelopeValidationError(
|
|
2580
|
-
`Envelope failed validation for type "${typeValue}"`,
|
|
2581
|
-
result.error
|
|
2582
|
-
);
|
|
2583
|
-
}
|
|
2584
|
-
function decodeEnvelope(line) {
|
|
2585
|
-
const text2 = decodeText(line).replace(/[\r\n]+$/, "");
|
|
2586
|
-
let json;
|
|
2587
|
-
try {
|
|
2588
|
-
json = JSON.parse(text2);
|
|
2589
|
-
} catch (cause) {
|
|
2590
|
-
throw new EnvelopeParseError("Envelope line is not valid JSON", cause);
|
|
2591
|
-
}
|
|
2592
|
-
return parseMessage(json);
|
|
2593
|
-
}
|
|
2594
|
-
function encodeEnvelope(env) {
|
|
2595
|
-
return `${JSON.stringify(env)}
|
|
2596
|
-
`;
|
|
2597
|
-
}
|
|
2598
|
-
function createEnvelope(type, payload, ...rest) {
|
|
2599
|
-
const opts = rest[0] ?? {};
|
|
2600
|
-
const envelope = {
|
|
2601
|
-
v: opts.v ?? PROTOCOL_VERSION,
|
|
2602
|
-
id: opts.id ?? crypto.randomUUID(),
|
|
2603
|
-
ts: opts.ts ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2604
|
-
type,
|
|
2605
|
-
...opts.taskId !== void 0 ? { task_id: opts.taskId } : {},
|
|
2606
|
-
...opts.sessionRef !== void 0 ? { session_ref: opts.sessionRef } : {},
|
|
2607
|
-
...opts.seq !== void 0 ? { seq: opts.seq } : {},
|
|
2608
|
-
payload
|
|
2609
|
-
};
|
|
2610
|
-
const result = EnvelopeSchema.safeParse(envelope);
|
|
2611
|
-
if (!result.success) {
|
|
2612
|
-
throw new EnvelopeValidationError(`createEnvelope built an invalid envelope for type "${type}"`, result.error);
|
|
2613
|
-
}
|
|
2614
|
-
return result.data;
|
|
2615
|
-
}
|
|
2616
|
-
var PairRequestSchema = z.object({
|
|
2617
|
-
pairingCode: z.string(),
|
|
2618
|
-
deviceName: z.string(),
|
|
2619
|
-
/** Ed25519 public key, base64url-encoded. Private key stays device-local (OS keychain or 0600 file). */
|
|
2620
|
-
devicePublicKey: z.string(),
|
|
2621
|
-
/**
|
|
2622
|
-
* Optional client-hashed physical machine identity: lowercase hex SHA-256 of
|
|
2623
|
-
* the product id and an OS-provided machine identifier, never the raw
|
|
2624
|
-
* identifier itself. It names no tenant and no product — those still come
|
|
2625
|
-
* only from the redeemed pairing code's claims — so it can only ever
|
|
2626
|
-
* supersede the SAME tenant/product's prior active device rows carrying this
|
|
2627
|
-
* exact digest. A client that cannot resolve one omits the field entirely.
|
|
2628
|
-
*/
|
|
2629
|
-
machineId: z.string().regex(/^[0-9a-f]{64}$/u).optional()
|
|
2630
|
-
});
|
|
2631
|
-
var PAIR_RESPONSE_TENANT_ID_MAX_LENGTH = 200;
|
|
2632
|
-
var PairResponseTenantIdSchema = z.string().min(1).max(PAIR_RESPONSE_TENANT_ID_MAX_LENGTH).refine((value) => value.trim() === value, {
|
|
2633
|
-
message: "tenantId must not have leading or trailing whitespace"
|
|
2634
|
-
}).refine((value) => !value.includes("\0"), {
|
|
2635
|
-
message: "tenantId must not contain a NUL character"
|
|
2636
|
-
});
|
|
2637
|
-
var PairResponseSchema = z.object({
|
|
2638
|
-
deviceId: z.string(),
|
|
2639
|
-
/** JWT, ~1h lifetime. */
|
|
2640
|
-
accessToken: z.string(),
|
|
2641
|
-
/** Opaque hint for when/how to renew (e.g. an ISO timestamp); not itself a credential. */
|
|
2642
|
-
refreshHint: z.string().optional(),
|
|
2643
|
-
/** Exact opaque, non-secret tenant binding from the authenticated device row. */
|
|
2644
|
-
tenantId: PairResponseTenantIdSchema
|
|
2645
|
-
});
|
|
2646
|
-
var ChallengeRequestSchema = z.object({
|
|
2647
|
-
deviceId: z.string()
|
|
2648
|
-
});
|
|
2649
|
-
var ChallengeResponseSchema = z.object({
|
|
2650
|
-
/** One-time value the client must sign with its device private key. */
|
|
2651
|
-
nonce: z.string()
|
|
2652
|
-
});
|
|
2653
|
-
var TokenRequestSchema = z.object({
|
|
2654
|
-
deviceId: z.string(),
|
|
2655
|
-
nonce: z.string(),
|
|
2656
|
-
/** Ed25519 signature over `nonce`, base64url-encoded. */
|
|
2657
|
-
signature: z.string()
|
|
2658
|
-
});
|
|
2659
|
-
var TokenResponseSchema = z.object({
|
|
2660
|
-
accessToken: z.string(),
|
|
2661
|
-
expiresAt: z.iso.datetime({ offset: true })
|
|
2662
|
-
});
|
|
2663
|
-
var PRESENCE_DETAIL_MAX_LENGTH = 512;
|
|
2664
|
-
var PRESENCE_RUNTIME_VERSION_MAX_LENGTH = 128;
|
|
2665
|
-
var PresenceRuntimeFactSchema = z.object({
|
|
2666
|
-
id: RuntimeIdSchema,
|
|
2667
|
-
version: z.string().min(1).max(PRESENCE_RUNTIME_VERSION_MAX_LENGTH).optional(),
|
|
2668
|
-
authPresent: z.boolean().optional()
|
|
2669
|
-
});
|
|
2670
|
-
var PresencePublishRequestSchema = z.object({
|
|
2671
|
-
level: z.enum(["online", "thinking", "working", "error", "offline"]),
|
|
2672
|
-
detail: z.string().max(PRESENCE_DETAIL_MAX_LENGTH).optional(),
|
|
2673
|
-
configuredToolsets: ConfiguredToolsetsSchema.optional(),
|
|
2674
|
-
/** U4a Local Agent release version; never inferred from a host package. */
|
|
2675
|
-
clientVersion: z.string().min(1).max(128).optional(),
|
|
2676
|
-
protocolVersions: z.array(ProtocolVersionNumberSchema).max(16).optional(),
|
|
2677
|
-
/** Runtime version/auth facts from the same real probe as conn.hello. */
|
|
2678
|
-
runtimes: z.array(PresenceRuntimeFactSchema).max(16).optional()
|
|
2679
|
-
});
|
|
2680
|
-
var CreateBlobRequestSchema = z.object({
|
|
2681
|
-
size: z.number().int().nonnegative(),
|
|
2682
|
-
contentType: z.string(),
|
|
2683
|
-
contentHash: z.string().regex(CONTENT_HASH_RE, 'contentHash must be "sha256:<64 lowercase hex>"')
|
|
2684
|
-
});
|
|
2685
|
-
var CreateBlobResponseSchema = z.object({
|
|
2686
|
-
blobId: z.string(),
|
|
2687
|
-
uploadUrl: z.string()
|
|
2688
|
-
});
|
|
2689
|
-
var BlobDownloadUrlResponseSchema = z.object({
|
|
2690
|
-
downloadUrl: z.string()
|
|
2691
|
-
});
|
|
2692
|
-
var EventsPollQuerySchema = z.object({
|
|
2693
|
-
/** Volatile navigation within the advertised read-ahead window; never acknowledges work. */
|
|
2694
|
-
afterSeq: z.number().int().nonnegative().optional(),
|
|
2695
|
-
/** Last reliably processed seq; the only acknowledgement. Omitted on the first poll. */
|
|
2696
|
-
cursor: z.number().int().nonnegative().optional()
|
|
2697
|
-
});
|
|
2698
|
-
var ActivityIngressSchema = z.object({
|
|
2699
|
-
activityMaxEvents: z.number().int().positive(),
|
|
2700
|
-
activityMaxBytes: z.number().int().min(2)
|
|
2701
|
-
});
|
|
2702
|
-
var OUTBOUND_REFUSAL_REASONS = ["payload_invalid", "not_permitted", "limit_exceeded", "state_conflict", "unsupported"];
|
|
2703
|
-
function isOutboundRefusalCode(value) {
|
|
2704
|
-
return OUTBOUND_REFUSAL_REASONS.includes(value);
|
|
2705
|
-
}
|
|
2706
|
-
var MessageSendOutcomeSchema = z.object({
|
|
2707
|
-
id: z.uuid(),
|
|
2708
|
-
outcome: z.enum(["accepted", "duplicate", "rejected"]),
|
|
2709
|
-
/** Decodes to an {@link OutboundRefusalReason}; an unrecognized string becomes `unknown`. */
|
|
2710
|
-
reason: z.string().max(64).transform((value) => isOutboundRefusalCode(value) ? value : "unknown").optional()
|
|
2711
|
-
});
|
|
2712
|
-
var EventsPollResponseSchema = z.object({
|
|
2713
|
-
/**
|
|
2714
|
-
* Not-yet-decoded entries (#386). This schema decodes the page only; each
|
|
2715
|
-
* entry is decoded on its own with `parseMessage`, so one unknown or invalid
|
|
2716
|
-
* entry stalls its own sequence instead of failing every entry in the page.
|
|
2717
|
-
*/
|
|
2718
|
-
events: z.array(z.unknown()),
|
|
2719
|
-
cursor: z.number().int(),
|
|
2720
|
-
/**
|
|
2721
|
-
* Required in v3: the server capabilities for THIS long-poll response, the
|
|
2722
|
-
* HTTP transport's equivalent of `conn.ack.capabilities`. Each page replaces
|
|
2723
|
-
* the daemon's advertisement; an empty list advertises nothing.
|
|
2724
|
-
*/
|
|
2725
|
-
capabilities: z.array(z.string()),
|
|
2726
|
-
/** Required in v3: the activity limits that apply to new progress pushes. */
|
|
2727
|
-
ingress: ActivityIngressSchema
|
|
2728
|
-
});
|
|
2729
|
-
var MAX_MESSAGES_PER_BATCH = 256;
|
|
2730
|
-
var MESSAGES_SEND_MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
2731
|
-
var MessagesSendRequestSchema = z.object({
|
|
2732
|
-
messages: z.array(EnvelopeSchema).max(MAX_MESSAGES_PER_BATCH)
|
|
2733
|
-
});
|
|
2734
|
-
var MessagesSendResponseSchema = z.object({
|
|
2735
|
-
accepted: z.number().int().nonnegative(),
|
|
2736
|
-
rejected: z.number().int().nonnegative().optional(),
|
|
2737
|
-
capabilities: z.array(z.string()).optional(),
|
|
2738
|
-
ingress: ActivityIngressSchema.optional(),
|
|
2739
|
-
outcomes: z.array(MessageSendOutcomeSchema).max(MAX_MESSAGES_PER_BATCH)
|
|
2740
|
-
});
|
|
2741
|
-
var AgentHomeProjectionCompletionRequestSchema = z.object({
|
|
2742
|
-
requestId: z.uuid(),
|
|
2743
|
-
agentRef: AgentHomeProjectionAgentRefSchema,
|
|
2744
|
-
projectionHash: AgentHomeProjectionHashSchema,
|
|
2745
|
-
outcome: AgentHomeProjectionOutcomeSchema
|
|
2746
|
-
}).strict();
|
|
2747
|
-
var AgentHomeProjectionStatusSchema = z.enum([
|
|
2748
|
-
"pending",
|
|
2749
|
-
"applied",
|
|
2750
|
-
"idempotent",
|
|
2751
|
-
"stale",
|
|
2752
|
-
"conflict"
|
|
2753
|
-
]);
|
|
2754
|
-
var AgentHomeProjectionReadbackSchema = z.object({
|
|
2755
|
-
tenantId: z.string().min(1),
|
|
2756
|
-
deviceId: z.string().min(1),
|
|
2757
|
-
requestId: z.uuid(),
|
|
2758
|
-
agentRef: AgentHomeProjectionAgentRefSchema,
|
|
2759
|
-
projectionHash: AgentHomeProjectionHashSchema,
|
|
2760
|
-
status: AgentHomeProjectionStatusSchema,
|
|
2761
|
-
completedAt: z.iso.datetime({ offset: true }).optional()
|
|
2762
|
-
}).strict();
|
|
2763
|
-
var InputPreparationCompletionRequestSchema = z.discriminatedUnion("outcome", [
|
|
2764
|
-
z.object({
|
|
2765
|
-
outcome: z.literal("prepared"),
|
|
2766
|
-
requestId: z.uuid(),
|
|
2767
|
-
agentRef: AgentRefSchema,
|
|
2768
|
-
profileId: InputPreparationProfileIdSchema,
|
|
2769
|
-
policyRevision: InputPreparationPolicyRevisionSchema,
|
|
2770
|
-
receipt: InputPreparationReceiptSummarySchema
|
|
2771
|
-
}).strict(),
|
|
2772
|
-
z.object({
|
|
2773
|
-
outcome: z.literal("rejected"),
|
|
2774
|
-
requestId: z.uuid(),
|
|
2775
|
-
agentRef: AgentRefSchema,
|
|
2776
|
-
profileId: InputPreparationProfileIdSchema,
|
|
2777
|
-
policyRevision: InputPreparationPolicyRevisionSchema,
|
|
2778
|
-
reason: InputPreparationRejectionReasonSchema
|
|
2779
|
-
}).strict()
|
|
2780
|
-
]);
|
|
2781
|
-
var InputPreparationStatusSchema = z.enum(["pending", "prepared", "rejected"]);
|
|
2782
|
-
var InputPreparationReadbackSchema = z.object({
|
|
2783
|
-
tenantId: z.string().min(1),
|
|
2784
|
-
deviceId: z.string().min(1),
|
|
2785
|
-
requestId: z.uuid(),
|
|
2786
|
-
agentRef: AgentRefSchema,
|
|
2787
|
-
profileId: InputPreparationProfileIdSchema,
|
|
2788
|
-
policyRevision: InputPreparationPolicyRevisionSchema,
|
|
2789
|
-
status: InputPreparationStatusSchema,
|
|
2790
|
-
receipt: InputPreparationReceiptSummarySchema.optional(),
|
|
2791
|
-
reason: InputPreparationRejectionReasonSchema.optional(),
|
|
2792
|
-
completedAt: z.iso.datetime({ offset: true }).optional()
|
|
2793
|
-
}).strict().superRefine((value, ctx) => {
|
|
2794
|
-
const expectsReceipt = value.status === "prepared";
|
|
2795
|
-
const expectsReason = value.status === "rejected";
|
|
2796
|
-
if (expectsReceipt !== (value.receipt !== void 0)) {
|
|
2797
|
-
ctx.addIssue({ code: "custom", path: ["receipt"], message: 'receipt is present exactly when status is "prepared"' });
|
|
2798
|
-
}
|
|
2799
|
-
if (expectsReason !== (value.reason !== void 0)) {
|
|
2800
|
-
ctx.addIssue({ code: "custom", path: ["reason"], message: 'reason is present exactly when status is "rejected"' });
|
|
2801
|
-
}
|
|
2802
|
-
if (value.status !== "pending" !== (value.completedAt !== void 0)) {
|
|
2803
|
-
ctx.addIssue({ code: "custom", path: ["completedAt"], message: "completedAt is present exactly when the status is terminal" });
|
|
2804
|
-
}
|
|
2805
|
-
});
|
|
2806
|
-
var InputPreparationStatusQuerySchema = z.object({
|
|
2807
|
-
agentId: z.string().min(1),
|
|
2808
|
-
profileRevision: z.string().min(1)
|
|
2809
|
-
}).strict();
|
|
2810
|
-
var AgentMemoryProjectionCommitRequestSchema = AgentMemoryProjectionMutationSchema;
|
|
2811
|
-
var AgentMemoryProjectionCommitResponseSchema = AgentMemoryProjectionReceiptSchema;
|
|
2812
|
-
var BYOK_PAIR_PATH = "/byok/pair";
|
|
2813
|
-
var BYOK_CHALLENGE_PATH = "/byok/challenge";
|
|
2814
|
-
var BYOK_TOKEN_PATH = "/byok/token";
|
|
2815
|
-
var BYOK_CAPABILITIES_PATH = "/byok/capabilities";
|
|
2816
|
-
var BYOK_EVENTS_PATH = "/byok/events";
|
|
2817
|
-
var BYOK_MESSAGES_PATH = "/byok/messages";
|
|
2818
|
-
var BYOK_AGENT_HOME_PROJECTIONS_PATH = "/byok/agent-home-projections";
|
|
2819
|
-
var BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE = "/byok/agent-home-projections/:requestId/completion";
|
|
2820
|
-
function byokAgentHomeProjectionCompletionPath(requestId) {
|
|
2821
|
-
return `${BYOK_AGENT_HOME_PROJECTIONS_PATH}/${encodeURIComponent(requestId)}/completion`;
|
|
2822
|
-
}
|
|
2823
|
-
var BYOK_INPUT_PREPARATIONS_PATH = "/byok/input-preparations";
|
|
2824
|
-
var BYOK_INPUT_PREPARATION_COMPLETION_ROUTE = "/byok/input-preparations/:requestId/completion";
|
|
2825
|
-
var BYOK_INPUT_PREPARATION_STATUS_ROUTE = "/byok/input-preparations/:requestId";
|
|
2826
|
-
function byokInputPreparationCompletionPath(requestId) {
|
|
2827
|
-
return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}/completion`;
|
|
2828
|
-
}
|
|
2829
|
-
function byokInputPreparationStatusPath(requestId) {
|
|
2830
|
-
return `${BYOK_INPUT_PREPARATIONS_PATH}/${encodeURIComponent(requestId)}`;
|
|
2831
|
-
}
|
|
2832
|
-
var BYOK_AGENT_MEMORY_PROJECTIONS_PATH = "/byok/agent-memory-projections";
|
|
2833
|
-
var BYOK_PRESENCE_PATH = "/byok/presence";
|
|
2834
|
-
var BYOK_ACTIVITY_PATH = "/byok/activity";
|
|
2835
|
-
var BYOK_BOARD_PATH = "/byok/board";
|
|
2836
|
-
var BYOK_BOARD_STREAM_PATH = "/byok/board/stream";
|
|
2837
|
-
var BYOK_BOARD_CLAIM_ROUTE = "/byok/board/:id/claim";
|
|
2838
|
-
var BYOK_BOARD_UNCLAIM_ROUTE = "/byok/board/:id/unclaim";
|
|
2839
|
-
var BYOK_BOARD_STATUS_ROUTE = "/byok/board/:id/status";
|
|
2840
|
-
var BYOK_RECORDS_PATH = "/byok/records";
|
|
2841
|
-
var BYOK_RECORD_ROUTE = "/byok/records/:kind/:key";
|
|
2842
|
-
function byokRecordPath(kind, key) {
|
|
2843
|
-
return `/byok/records/${encodeURIComponent(kind)}/${encodeURIComponent(key)}`;
|
|
2844
|
-
}
|
|
2845
|
-
var BYOK_E2EE_MEMBER_KEY_PATH = "/byok/e2ee/member-key";
|
|
2846
|
-
var BYOK_E2EE_CHAIN_PATH = "/byok/e2ee/chain";
|
|
2847
|
-
var BYOK_E2EE_KEY_PACKAGES_PATH = "/byok/e2ee/key-packages";
|
|
2848
|
-
var BYOK_E2EE_PAIRING_MAC_PATH = "/byok/e2ee/pairing-mac";
|
|
2849
|
-
var BYOK_SKILL_PACKS_PATH = "/byok/skill-packs";
|
|
2850
|
-
var BYOK_SKILL_PACK_FILE_ROUTE = "/byok/skill-packs/:name/files/:path";
|
|
2851
|
-
function byokSkillPackFilePath(name, path) {
|
|
2852
|
-
return `/byok/skill-packs/${encodeURIComponent(name)}/files/${encodeURIComponent(path)}`;
|
|
2853
|
-
}
|
|
2854
|
-
var BYOK_BLOBS_PATH = "/byok/blobs";
|
|
2855
|
-
var BYOK_BLOB_FINALIZE_ROUTE = "/byok/blobs/:id/finalize";
|
|
2856
|
-
var BYOK_BLOB_URL_ROUTE = "/byok/blobs/:id/url";
|
|
2857
|
-
var BYOK_BLOB_CONTENT_ROUTE = "/byok/blobs/:id/content";
|
|
2858
|
-
function byokBlobFinalizePath(blobId) {
|
|
2859
|
-
return `/byok/blobs/${encodeURIComponent(blobId)}/finalize`;
|
|
2860
|
-
}
|
|
2861
|
-
function byokBlobUrlPath(blobId) {
|
|
2862
|
-
return `/byok/blobs/${encodeURIComponent(blobId)}/url`;
|
|
2863
|
-
}
|
|
2864
|
-
function byokBlobContentPath(blobId) {
|
|
2865
|
-
return `/byok/blobs/${blobId}/content`;
|
|
2866
|
-
}
|
|
2867
|
-
|
|
2868
|
-
// src/bot-turn-outcome.ts
|
|
2869
|
-
var BOT_TURN_OUTCOME_CONTRACT = "bot-turn-outcome.v1";
|
|
2870
|
-
var BOT_TURN_OUTCOME_LIMITS = Object.freeze({
|
|
2871
|
-
delegateMaxItems: 2,
|
|
2872
|
-
delegateRequestMaxLength: 1e3,
|
|
2873
|
-
cancelDelegationMaxItems: 2,
|
|
2874
|
-
askUserQuestionMaxLength: 400,
|
|
2875
|
-
askUserOptionsMaxItems: 6,
|
|
2876
|
-
askUserOptionIdMaxLength: 24,
|
|
2877
|
-
askUserOptionLabelMaxLength: 80,
|
|
2878
|
-
confirmableActionMaxItems: 1,
|
|
2879
|
-
confirmableSummaryMaxLength: 300,
|
|
2880
|
-
confirmableDraftMaxBytes: 16384,
|
|
2881
|
-
createRoutineMaxItems: 1,
|
|
2882
|
-
updateRoutineMaxItems: 1,
|
|
2883
|
-
cancelRoutineMaxItems: 2,
|
|
2884
|
-
routinePromptMaxLength: 500,
|
|
2885
|
-
postTextMaxLength: 2730,
|
|
2886
|
-
roomCallMembersMaxItems: 4,
|
|
2887
|
-
createBotMaxItems: 3,
|
|
2888
|
-
updateBotMaxItems: 1,
|
|
2889
|
-
deleteBotMaxItems: 1,
|
|
2890
|
-
botNameMaxLength: 40,
|
|
2891
|
-
botRoleMaxLength: 80,
|
|
2892
|
-
botPersonaMaxLength: 300,
|
|
2893
|
-
createRoomMaxItems: 1,
|
|
2894
|
-
updateRoomMaxItems: 1,
|
|
2895
|
-
roomNameMaxLength: 40,
|
|
2896
|
-
roomMembersMaxItems: 12,
|
|
2897
|
-
roomAnnouncementMaxLength: 300,
|
|
2898
|
-
teamNoteMaxLength: 300
|
|
2899
|
-
});
|
|
2900
|
-
var L = BOT_TURN_OUTCOME_LIMITS;
|
|
2901
|
-
var text = (maxLength) => ({ type: "string", minLength: 1, maxLength });
|
|
2902
|
-
var oneOfIds = (ids) => ({ enum: [...ids] });
|
|
2903
|
-
var closed = (properties, required) => ({ type: "object", additionalProperties: false, required, properties });
|
|
2904
|
-
var list = (items, maxItems) => ({ type: "array", minItems: 1, maxItems, items });
|
|
2905
|
-
var ROUTINE_DAYS_OF_WEEK = Object.freeze(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]);
|
|
2906
|
-
var integer = (minimum, maximum) => ({ type: "integer", minimum, maximum });
|
|
2907
|
-
var BotTurnOutcomeSchemaError = class extends Error {
|
|
2908
|
-
constructor(code, message) {
|
|
2909
|
-
super(message);
|
|
2910
|
-
this.code = code;
|
|
2911
|
-
this.name = "BotTurnOutcomeSchemaError";
|
|
2912
|
-
}
|
|
2913
|
-
code;
|
|
2914
|
-
};
|
|
2915
|
-
function schedule(timeZones, shape) {
|
|
2916
|
-
const fields = {
|
|
2917
|
-
minute: integer(0, 59),
|
|
2918
|
-
hour: integer(0, 23),
|
|
2919
|
-
daysOfWeek: { type: "array", minItems: 1, maxItems: 7, items: { enum: [...ROUTINE_DAYS_OF_WEEK] } },
|
|
2920
|
-
dayOfMonth: integer(1, 31),
|
|
2921
|
-
month: integer(1, 12),
|
|
2922
|
-
tz: oneOfIds(timeZones)
|
|
2923
|
-
};
|
|
2924
|
-
const outer = {
|
|
2925
|
-
description: "Local time in tz. No day field: every day. daysOfWeek: those days only. dayOfMonth: that day of each month, or of month only.",
|
|
2926
|
-
...closed(fields, ["minute", "hour", "tz"])
|
|
2927
|
-
};
|
|
2928
|
-
if (shape === "flat") return outer;
|
|
2929
|
-
const only = (names, required) => ({ additionalProperties: false, ...required.length ? { required } : {}, properties: Object.fromEntries(names.map((n) => [n, {}])) });
|
|
2930
|
-
return { ...outer, oneOf: [
|
|
2931
|
-
only(["minute", "hour", "tz"], []),
|
|
2932
|
-
only(["minute", "hour", "daysOfWeek", "tz"], ["daysOfWeek"]),
|
|
2933
|
-
only(["minute", "hour", "dayOfMonth", "month", "tz"], ["dayOfMonth"])
|
|
2934
|
-
] };
|
|
2935
|
-
}
|
|
2936
|
-
function roomFields(members) {
|
|
2937
|
-
return {
|
|
2938
|
-
name: text(L.roomNameMaxLength),
|
|
2939
|
-
members: { type: "array", minItems: 1, maxItems: L.roomMembersMaxItems, items: oneOfIds(members) },
|
|
2940
|
-
admin: oneOfIds(members),
|
|
2941
|
-
mode: { enum: ["mention", "admin"] },
|
|
2942
|
-
announcement: text(L.roomAnnouncementMaxLength)
|
|
2943
|
-
};
|
|
2944
|
-
}
|
|
2945
|
-
var botTurnOutcomeFragments = {
|
|
2946
|
-
/** `to` lists this Bot first: delegating to yourself is a continuation. */
|
|
2947
|
-
delegate(o) {
|
|
2948
|
-
return list(closed({ to: oneOfIds(o.to), request: text(L.delegateRequestMaxLength) }, ["to", "request"]), L.delegateMaxItems);
|
|
2949
|
-
},
|
|
2950
|
-
/** Owner-authorized Main Bot turns only. The Host lists open delegations. */
|
|
2951
|
-
cancelDelegation(o) {
|
|
2952
|
-
return list(closed({ delegationId: oneOfIds(o.delegationIds) }, ["delegationId"]), L.cancelDelegationMaxItems);
|
|
2953
|
-
},
|
|
2954
|
-
askUser() {
|
|
2955
|
-
const question = text(L.askUserQuestionMaxLength);
|
|
2956
|
-
const option = closed({ id: text(L.askUserOptionIdMaxLength), label: text(L.askUserOptionLabelMaxLength) }, ["id", "label"]);
|
|
2957
|
-
return { oneOf: [
|
|
2958
|
-
closed({ question, answerKind: { const: "text" } }, ["question", "answerKind"]),
|
|
2959
|
-
closed({
|
|
2960
|
-
question,
|
|
2961
|
-
answerKind: { const: "single_choice" },
|
|
2962
|
-
options: { type: "array", minItems: 2, maxItems: L.askUserOptionsMaxItems, items: option }
|
|
2963
|
-
}, ["question", "answerKind", "options"])
|
|
2964
|
-
] };
|
|
2965
|
-
},
|
|
2966
|
-
/** One branch per Host action; each draft needs a finite bound of at most confirmableDraftMaxBytes. */
|
|
2967
|
-
confirmableAction(o) {
|
|
2968
|
-
for (const { action, draft } of o.actions) {
|
|
2969
|
-
const bound = resultOutcomeMaxBytes(draft);
|
|
2970
|
-
if (bound === null || bound > L.confirmableDraftMaxBytes) {
|
|
2971
|
-
throw new BotTurnOutcomeSchemaError("draft-over-budget", `draft for ${action} is ${bound ?? "unbounded"}; cap ${L.confirmableDraftMaxBytes}`);
|
|
2972
|
-
}
|
|
2973
|
-
}
|
|
2974
|
-
const branches = o.actions.map(({ action, draft }) => closed({ action: { const: action }, summary: text(L.confirmableSummaryMaxLength), draft }, ["action", "summary", "draft"]));
|
|
2975
|
-
return list(branches.length === 1 ? branches[0] : { oneOf: branches }, L.confirmableActionMaxItems);
|
|
2976
|
-
},
|
|
2977
|
-
/** `targets` only for a Main Bot: the Bot itself first, then team Bots. Omitted means the Bot itself. */
|
|
2978
|
-
createRoutine(o) {
|
|
2979
|
-
return list(closed({
|
|
2980
|
-
localId: oneOfIds(o.localIds),
|
|
2981
|
-
schedule: schedule(o.timeZones, o.scheduleShape ?? "checked"),
|
|
2982
|
-
prompt: text(L.routinePromptMaxLength),
|
|
2983
|
-
...o.targets ? { target: oneOfIds(o.targets) } : {}
|
|
2984
|
-
}, ["localId", "schedule", "prompt"]), L.createRoutineMaxItems);
|
|
2985
|
-
},
|
|
2986
|
-
updateRoutine(o) {
|
|
2987
|
-
return list(closed(
|
|
2988
|
-
{ routineId: oneOfIds(o.routineIds), schedule: schedule(o.timeZones, o.scheduleShape ?? "checked"), prompt: text(L.routinePromptMaxLength) },
|
|
2989
|
-
["routineId"]
|
|
2990
|
-
), L.updateRoutineMaxItems);
|
|
2991
|
-
},
|
|
2992
|
-
cancelRoutine(o) {
|
|
2993
|
-
return list(closed({ routineId: oneOfIds(o.routineIds) }, ["routineId"]), L.cancelRoutineMaxItems);
|
|
2994
|
-
},
|
|
2995
|
-
/** Room turns only. Exactly one of post or pass. */
|
|
2996
|
-
speech() {
|
|
2997
|
-
return { oneOf: [
|
|
2998
|
-
closed({ kind: { const: "post" }, text: text(L.postTextMaxLength) }, ["kind", "text"]),
|
|
2999
|
-
closed({ kind: { const: "pass" } }, ["kind"])
|
|
3000
|
-
] };
|
|
3001
|
-
},
|
|
3002
|
-
roomCall(o) {
|
|
3003
|
-
return closed({ members: { type: "array", minItems: 1, maxItems: L.roomCallMembersMaxItems, items: oneOfIds(o.members) } }, ["members"]);
|
|
3004
|
-
},
|
|
3005
|
-
createBot(o) {
|
|
3006
|
-
return list(closed({
|
|
3007
|
-
localId: oneOfIds(o.localIds),
|
|
3008
|
-
name: text(L.botNameMaxLength),
|
|
3009
|
-
role: text(L.botRoleMaxLength),
|
|
3010
|
-
persona: text(L.botPersonaMaxLength),
|
|
3011
|
-
model: oneOfIds(o.models)
|
|
3012
|
-
}, ["localId", "name", "role", "persona", "model"]), L.createBotMaxItems);
|
|
3013
|
-
},
|
|
3014
|
-
updateBot(o) {
|
|
3015
|
-
return list(closed({
|
|
3016
|
-
botId: oneOfIds(o.botIds),
|
|
3017
|
-
name: text(L.botNameMaxLength),
|
|
3018
|
-
role: text(L.botRoleMaxLength),
|
|
3019
|
-
persona: text(L.botPersonaMaxLength),
|
|
3020
|
-
model: oneOfIds(o.models)
|
|
3021
|
-
}, ["botId"]), L.updateBotMaxItems);
|
|
3022
|
-
},
|
|
3023
|
-
deleteBot(o) {
|
|
3024
|
-
return list(closed({ botId: oneOfIds(o.botIds) }, ["botId"]), L.deleteBotMaxItems);
|
|
3025
|
-
},
|
|
3026
|
-
/** `members`: team Bot ids plus the create_bot localId slots of this outcome. */
|
|
3027
|
-
createRoom(o) {
|
|
3028
|
-
return list(closed({ localId: oneOfIds(o.localIds), ...roomFields(o.members) }, ["localId", "name", "members"]), L.createRoomMaxItems);
|
|
3029
|
-
},
|
|
3030
|
-
updateRoom(o) {
|
|
3031
|
-
return list(closed({ roomId: oneOfIds(o.roomIds), ...roomFields(o.members) }, ["roomId"]), L.updateRoomMaxItems);
|
|
3032
|
-
},
|
|
3033
|
-
teamNote() {
|
|
3034
|
-
return closed({ text: text(L.teamNoteMaxLength) }, ["text"]);
|
|
3035
|
-
}
|
|
3036
|
-
};
|
|
3037
|
-
function composeBotTurnOutcomeSchema(fragments, required = []) {
|
|
3038
|
-
const schema = {
|
|
3039
|
-
type: "object",
|
|
3040
|
-
additionalProperties: false,
|
|
3041
|
-
description: `${BOT_TURN_OUTCOME_CONTRACT}: actions for the Host. Omit a field for no action of that kind; {} means no actions.`,
|
|
3042
|
-
...required.length ? { required: [...required] } : {},
|
|
3043
|
-
properties: fragments
|
|
3044
|
-
};
|
|
3045
|
-
const admitted = checkResultSchema(schema);
|
|
3046
|
-
if (!admitted.ok && admitted.reason === "over-cap") {
|
|
3047
|
-
throw new BotTurnOutcomeSchemaError("schema-over-budget", `schema is ${admitted.bytes} bytes; cap ${RESULT_SCHEMA_MAX_BYTES}`);
|
|
3048
|
-
}
|
|
3049
|
-
if (!admitted.ok) throw new BotTurnOutcomeSchemaError("not-subset", JSON.stringify(admitted.issues));
|
|
3050
|
-
const bound = resultOutcomeMaxBytes(admitted.canonical);
|
|
3051
|
-
if (bound === null || bound > RESULT_OUTCOME_MAX_BYTES) {
|
|
3052
|
-
throw new BotTurnOutcomeSchemaError("over-budget", `largest outcome is ${bound ?? "unbounded"} bytes; cap ${RESULT_OUTCOME_MAX_BYTES}`);
|
|
3053
|
-
}
|
|
3054
|
-
return admitted.canonical;
|
|
3055
|
-
}
|
|
3056
|
-
|
|
3057
|
-
export { AGENT_CONTENT_ARTIFACT_READ_CAPABILITY, AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY, AGENT_CONTENT_WORKSPACE_READ_CAPABILITY, AGENT_EGRESS_FRESH_SESSION_CAPABILITY, AGENT_EGRESS_POLICY_CAPABILITY, AGENT_EGRESS_RELIABLE_ACK_CAPABILITY, AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH, AGENT_HOME_MEMORY_DIGEST_MAX_BYTES, AGENT_HOME_MEMORY_DIGEST_MAX_FILES, AGENT_HOME_MEMORY_PATH_MAX_LENGTH, AGENT_HOME_PROJECTION_CAPABILITY, AGENT_HOME_PROJECTION_MAX_BYTES, AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM, AGENT_HOME_READERS_CAPABILITY, AGENT_INPUT_PREPARATION_CAPABILITY, AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES, AGENT_MEMORY_INTENT_CAPABILITY, AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES, AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS, AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION, AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES, AGENT_MEMORY_INTENT_OPERATIONS, AGENT_MEMORY_INTENT_PATH_MAX_BYTES, AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS, AGENT_MEMORY_INTENT_REJECTION_CODES, AGENT_MEMORY_INTENT_RESERVATIONS, AGENT_MEMORY_MAX_SNAPSHOT_BYTES, AGENT_MEMORY_MAX_SNAPSHOT_FILES, AGENT_MEMORY_PROJECTION_CAPABILITY, AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE, AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES, AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY, AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY, AGENT_MEMORY_SELECTION_CAPABILITY, AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES, AGENT_MESSAGE_EGRESS_CAPABILITY, AGENT_MESSAGE_MAX_BYTES, AGENT_REF_MAX_BYTES, ActivityIngressSchema, AgentContentActorKindSchema, AgentContentActorSchema, AgentContentDecodeAsSchema, AgentContentMimeTypeSchema, AgentContentReadDecisionSchema, AgentContentReadDenialReasonSchema, AgentContentReadPayloadSchema, AgentContentReadSurfaceSchema, AgentContentReceiptPayloadSchema, AgentEgressAckPayloadSchema, AgentEgressActivityPolicySchema, AgentEgressContentHashSchema, AgentEgressDropReasonSchema, AgentEgressLaneSchema, AgentEgressPolicyRevisionSchema, AgentEgressPolicySchema, AgentEgressReliablePayloadSchema, AgentEventOrUnknownSchema, AgentEventSchema, AgentEventSpillSchema, AgentHomeAccessSchema, AgentHomeProjectionAgentRefSchema, AgentHomeProjectionCompletionRequestSchema, AgentHomeProjectionHashSchema, AgentHomeProjectionOutcomeSchema, AgentHomeProjectionPayloadSchema, AgentHomeProjectionProfileRevisionSchema, AgentHomeProjectionReadbackSchema, AgentHomeProjectionStatusSchema, AgentHomeProjectionValueSchema, AgentInputPreparationPayloadSchema, AgentMemoryIntentApprovalRefSchema, AgentMemoryIntentAvailablePayloadSchema, AgentMemoryIntentCompletionSchema, AgentMemoryIntentContentSchema, AgentMemoryIntentFetchRequestSchema, AgentMemoryIntentFetchResponseSchema, AgentMemoryIntentFileObservationSchema, AgentMemoryIntentHostTerminalCodeSchema, AgentMemoryIntentOperationDigestSchema, AgentMemoryIntentOperationSchema, AgentMemoryIntentPathSchema, AgentMemoryIntentReadbackDispositionSchema, AgentMemoryIntentReadbackSchema, AgentMemoryIntentRejectionCodeSchema, AgentMemoryIntentReservationSchema, AgentMemoryIntentRevisionSchema, AgentMemoryIntentV1Schema, AgentMemoryProjectionCommitRequestSchema, AgentMemoryProjectionCommitResponseSchema, AgentMemoryProjectionEraseResultSchema, AgentMemoryProjectionGrantRefSchema, AgentMemoryProjectionMeteringReceiptSchema, AgentMemoryProjectionMutationSchema, AgentMemoryProjectionReceiptSchema, AgentMemoryProjectionSessionRefSchema, AgentMemoryProjectionSnapshotSchema, AgentMemoryProjectionSourceSeqSchema, AgentMemoryProjectionWriterEpochSchema, AgentMemorySelectionSchema, AgentMessageContentTypeSchema, AgentMessageContractSchema, AgentMessageDestinationBindingSchema, AgentMessageDispositionPayloadSchema, AgentMessageDraftPayloadSchema, AgentMessageEgressRequirementSchema, AgentMessageFreshnessCursorSchema, AgentMessagePublishPayloadSchema, AgentMessageServerContextSchema, AgentRefSchema, AgentReliableQuotaPolicySchema, BOT_TURN_OUTCOME_CONTRACT, BOT_TURN_OUTCOME_LIMITS, BYOK_ACTIVITY_PATH, BYOK_AGENT_HOME_PROJECTIONS_PATH, BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE, BYOK_AGENT_MEMORY_PROJECTIONS_PATH, BYOK_BLOBS_PATH, BYOK_BLOB_CONTENT_ROUTE, BYOK_BLOB_FINALIZE_ROUTE, BYOK_BLOB_URL_ROUTE, BYOK_BOARD_CLAIM_ROUTE, BYOK_BOARD_PATH, BYOK_BOARD_STATUS_ROUTE, BYOK_BOARD_STREAM_PATH, BYOK_BOARD_UNCLAIM_ROUTE, BYOK_CAPABILITIES_PATH, BYOK_CHALLENGE_PATH, BYOK_E2EE_CHAIN_PATH, BYOK_E2EE_KEY_PACKAGES_PATH, BYOK_E2EE_MEMBER_KEY_PATH, BYOK_E2EE_PAIRING_MAC_PATH, BYOK_EVENTS_PATH, BYOK_INPUT_PREPARATIONS_PATH, BYOK_INPUT_PREPARATION_COMPLETION_ROUTE, BYOK_INPUT_PREPARATION_STATUS_ROUTE, BYOK_MESSAGES_PATH, BYOK_PAIR_PATH, BYOK_PRESENCE_PATH, BYOK_RECORDS_PATH, BYOK_RECORD_ROUTE, BYOK_SKILL_PACKS_PATH, BYOK_SKILL_PACK_FILE_ROUTE, BYOK_TOKEN_PATH, BlobDownloadUrlResponseSchema, BlobRefSchema, BotTurnOutcomeSchemaError, CAPABILITY_FLAGS, CONFIGURED_TOOLSETS_MAX_ITEMS, CONTENT_HASH_RE, CUSTOM_HARNESS_CAPABILITY, ChallengeRequestSchema, ChallengeResponseSchema, ConfiguredToolsetsSchema, ConnAckPayloadSchema, ConnHelloPayloadSchema, ContentReadPolicySchema, CreateBlobRequestSchema, CreateBlobResponseSchema, DAEMON_TO_SERVER_TYPES, DispatchSelectionSchema, E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES, E2EE_MEMBER_CHAIN_APPEND_OPERATION, E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES, E2EE_MEMBER_CHAIN_OPS, E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES, E2EE_MEMBER_KEY_REGISTER_OPERATION, E2EE_SCOPE_ID_MAX_LENGTH, E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX, E2EE_SCOPE_KEY_PACKAGE_PUT_MAX, E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION, E2eeClientPairingMacSchema, E2eeKeyPackageAvailablePayloadSchema, E2eeMemberChainEntrySchema, E2eeMemberKeyBundleSchema, E2eeMemberKeyRegisterRequestSchema, E2eePairingMacSchema, E2eeScopeKeyPackageSchema, E2eeScopeKeyPackageV2Schema, EnvelopeParseError, EnvelopeSchema, EnvelopeValidationError, EventsPollQuerySchema, EventsPollResponseSchema, HOST_MCP_TASK_CONTEXT_CAPABILITY, HarnessIdSchema, HarnessInfoSchema, HarnessInventorySchema, INPUT_PREPARATION_WIRE_VERSION, InputPreparationAccountingPolicyRefSchema, InputPreparationArtifactSummarySchema, InputPreparationBindingSchema, InputPreparationCompletionRequestSchema, InputPreparationContentHashSchema, InputPreparationContextDocumentSchema, InputPreparationCounterEvidenceSchema, InputPreparationCounterProviderEvidenceSchema, InputPreparationCounterTargetSchema, InputPreparationHostCanonicalAssistantMessageSchema, InputPreparationMessageSchema, InputPreparationModelCostSchema, InputPreparationModelSchema, InputPreparationOfferBindingSchema, InputPreparationOptionsSchema, InputPreparationPolicyRevisionSchema, InputPreparationProfileIdSchema, InputPreparationProjectionSchema, InputPreparationPromptSnapshotSchema, InputPreparationReadbackSchema, InputPreparationReadinessReasonSchema, InputPreparationReceiptSummarySchema, InputPreparationReferenceSchema, InputPreparationRejectionReasonSchema, InputPreparationResidualKeySchema, InputPreparationResidualValueClassSchema, InputPreparationRuntimeIdentitySchema, InputPreparationSelectionSchema, InputPreparationSourceSchema, InputPreparationStateSchema, InputPreparationStatusQuerySchema, InputPreparationStatusSchema, InputPreparationUserMessageSchema, KNOWN_AGENT_EVENT_TYPES, MAILBOX_READ_AHEAD_CAPABILITY, MAILBOX_READ_AHEAD_MAX_SEQS, MAX_MESSAGES_PER_BATCH, MESSAGES_SEND_MAX_BODY_BYTES, MESSAGE_PAYLOAD_SCHEMAS, MESSAGE_TYPES, MessageSendOutcomeSchema, MessagesSendRequestSchema, MessagesSendResponseSchema, OUTBOUND_REFUSAL_REASONS, PAIR_RESPONSE_TENANT_ID_MAX_LENGTH, PREPARED_AGENT_MEMORY_MODES, PROTOCOL_VERSION, PROVIDER_MODEL_CAPABILITIES, PROVIDER_PROFILE_BINDING_CAPABILITY, PROVIDER_PROVISIONING_CAPABILITY, PROVIDER_PROVISIONING_DISPOSITIONS, PROVIDER_PROVISIONING_HOST_TERMINAL_CODES, PROVIDER_PROVISIONING_KEY_CHECK_RESULTS, PROVIDER_PROVISIONING_OPERATIONS, PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM, PROVIDER_PROVISIONING_REJECTION_CODES, PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION, PairRequestSchema, PairResponseSchema, PairResponseTenantIdSchema, PreparedAgentMemoryModeSchema, PresencePublishRequestSchema, ProtocolError, ProtocolVersionNumberSchema, ProviderModelCapabilitySchema, ProviderProfileBindingSchema, ProviderProfileHashSchema, ProviderProfileRefSchema, ProviderProfileRevisionSchema, ProviderProvisioningAvailablePayloadSchema, ProviderProvisioningCompletionSchema, ProviderProvisioningDispositionSchema, ProviderProvisioningKeyCheckResultSchema, ProviderProvisioningKeyCheckSchema, ProviderProvisioningOperationDigestSchema, ProviderProvisioningOperationGenerationSchema, ProviderProvisioningOperationSchema, ProviderProvisioningProviderStatusSchema, ProviderProvisioningReadbackSchema, ProviderProvisioningRejectionCodeSchema, RESULT_DOCUMENT_MAX_BYTES, RESULT_ISSUES_MAX_BYTES, RESULT_ISSUES_MAX_COUNT, RESULT_JSON_MAX_DEPTH, RESULT_OUTCOME_MAX_BYTES, RESULT_SCHEMA_INSTANCE_TYPES, RESULT_SCHEMA_KEYWORDS, RESULT_SCHEMA_MAX_BYTES, RESULT_SCHEMA_MAX_DEPTH, ROUTINE_DAYS_OF_WEEK, RUNTIME_FAILURE_CLASSES, RUNTIME_FAILURE_CLASS_CAPABILITY, RUNTIME_IDS, RequiredToolsetsSchema, ResultDocumentSchemaSchema, RuntimeCapabilitiesSchema, RuntimeFailureClassSchema, RuntimeIdSchema, RuntimeInfoSchema, SEALED_DECLINE_CODES, SEALED_INLINE_MAX_PADDED_LENGTH, SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY, SEALED_PAYLOAD_CAPABILITY, SEALED_PAYLOAD_CATEGORIES, SEALED_PAYLOAD_MAX_CONTENT_LENGTH, SEALED_PAYLOAD_MAX_PADDED_LENGTH, SEALED_PAYLOAD_SUITE, SEALED_PAYLOAD_V1_CATEGORIES, SEALED_PAYLOAD_VERSION, SEALED_SPLIT_TABLE, SEALED_TASK_PLAIN_CODES, SERVER_TO_DAEMON_TYPES, STRICT_AGENT_ONLY_CAPABILITY, SealedPayloadSchema, SealedTaskInputSchema, SealedTaskOutputSchema, TASK_OFFER_TYPES, TASK_STATES, TASK_TRANSITIONS, TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH, TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS, TERMINAL_INFERENCE_USAGE_MAX_TOKENS, TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH, TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH, TERMINAL_PROJECTION_SELECTION_CAPABILITY, TaskApprovalResolvedPayloadSchema, TaskApprovePayloadSchema, TaskArtifactPayloadSchema, TaskAwaitApprovalPayloadSchema, TaskCancelPayloadSchema, TaskCancelledPayloadSchema, TaskClaimPayloadSchema, TaskCompletePayloadSchema, TaskDeclinePayloadSchema, TaskFailPayloadSchema, TaskFailureSchema, TaskOfferForAgentPayloadSchema, TaskOfferForAgentWithEgressFreshPayloadSchema, TaskOfferForAgentWithEgressPayloadSchema, TaskOfferPayloadSchema, TaskOfferPreparedPayloadSchema, TaskOfferWithToolsetsPayloadSchema, TaskProgressPayloadSchema, TaskRejectPayloadSchema, TaskSealingSchema, TaskStartedPayloadSchema, TaskSteerPayloadSchema, TerminalAgentHomeMemoryChangeSchema, TerminalAgentHomeProjectionSchema, TerminalInferenceUsageSchema, TerminalPreparedObservationSchema, TerminalProjectionContractSchema, TerminalProjectionSelectionSchema, TokenRequestSchema, TokenResponseSchema, ToolsetIdSchema, UnknownAgentEventSchema, UnknownMessageTypeError, WIRE_ADDITIONS, agentMemoryIntentFetchResponseSchemaFor, agentMemoryProjectionBase64UrlByteLength, botTurnOutcomeFragments, byokAgentHomeProjectionCompletionPath, byokBlobContentPath, byokBlobFinalizePath, byokBlobUrlPath, byokInputPreparationCompletionPath, byokInputPreparationStatusPath, byokRecordPath, byokSkillPackFilePath, canTransition, checkResultDocument, checkResultSchema, composeBotTurnOutcomeSchema, createEnvelope, decodeEnvelope, encodeEnvelope, isKnownAgentEvent, isPreparedAgentMemoryMode, isSealedMessageType, isSealedTaskPlainOutput, isServerToDaemonType, isTaskOfferType, parseMessage, partitionAgentEvents, requiredReceiverCapabilities, resultOutcomeMaxBytes, sealedBase64UrlByteLength, sealedPayloadPaddedLength, validateResultOutcome };
|
|
7
|
+
export { AGENT_CONTENT_ARTIFACT_READ_CAPABILITY, AGENT_CONTENT_TRANSCRIPT_READ_CAPABILITY, AGENT_CONTENT_WORKSPACE_READ_CAPABILITY, AGENT_EGRESS_FRESH_SESSION_CAPABILITY, AGENT_EGRESS_POLICY_CAPABILITY, AGENT_EGRESS_RELIABLE_ACK_CAPABILITY, AGENT_EVENT_SPILL_UNSTORED_REASON_MAX_LENGTH, AGENT_HOME_MEMORY_DIGEST_MAX_BYTES, AGENT_HOME_MEMORY_DIGEST_MAX_FILES, AGENT_HOME_MEMORY_PATH_MAX_LENGTH, AGENT_HOME_PROJECTION_CAPABILITY, AGENT_HOME_PROJECTION_MAX_BYTES, AGENT_HOME_PROJECTION_PROFILE_REVISION_MAXIMUM, AGENT_HOME_READERS_CAPABILITY, AGENT_INPUT_PREPARATION_CAPABILITY, AGENT_MEMORY_INTENT_APPROVAL_REF_MAX_BYTES, AGENT_MEMORY_INTENT_CAPABILITY, AGENT_MEMORY_INTENT_CONTENT_MAX_BYTES, AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS, AGENT_MEMORY_INTENT_FETCH_DISPOSITIONS_BY_RESERVATION, AGENT_MEMORY_INTENT_HOST_TERMINAL_CODES, AGENT_MEMORY_INTENT_OPERATIONS, AGENT_MEMORY_INTENT_PATH_MAX_BYTES, AGENT_MEMORY_INTENT_READBACK_DISPOSITIONS, AGENT_MEMORY_INTENT_REJECTION_CODES, AGENT_MEMORY_INTENT_RESERVATIONS, AGENT_MEMORY_MAX_SNAPSHOT_BYTES, AGENT_MEMORY_MAX_SNAPSHOT_FILES, AGENT_MEMORY_PROJECTION_CAPABILITY, AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE, AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES, AGENT_MEMORY_READ_IF_ADMITTED_CAPABILITY, AGENT_MEMORY_READ_WRITE_IF_ADMITTED_CAPABILITY, AGENT_MEMORY_SELECTION_CAPABILITY, AGENT_MESSAGE_DRAFT_FRAME_MAX_BYTES, AGENT_MESSAGE_EGRESS_CAPABILITY, AGENT_MESSAGE_MAX_BYTES, AGENT_REF_MAX_BYTES, ActivityIngressSchema, AgentContentActorKindSchema, AgentContentActorSchema, AgentContentDecodeAsSchema, AgentContentMimeTypeSchema, AgentContentReadDecisionSchema, AgentContentReadDenialReasonSchema, AgentContentReadPayloadSchema, AgentContentReadSurfaceSchema, AgentContentReceiptPayloadSchema, AgentEgressAckPayloadSchema, AgentEgressActivityPolicySchema, AgentEgressContentHashSchema, AgentEgressDropReasonSchema, AgentEgressLaneSchema, AgentEgressPolicyRevisionSchema, AgentEgressPolicySchema, AgentEgressReliablePayloadSchema, AgentEventOrUnknownSchema, AgentEventSchema, AgentEventSpillSchema, AgentHomeAccessSchema, AgentHomeProjectionAgentRefSchema, AgentHomeProjectionCompletionRequestSchema, AgentHomeProjectionHashSchema, AgentHomeProjectionOutcomeSchema, AgentHomeProjectionPayloadSchema, AgentHomeProjectionProfileRevisionSchema, AgentHomeProjectionReadbackSchema, AgentHomeProjectionStatusSchema, AgentHomeProjectionValueSchema, AgentInputPreparationPayloadSchema, AgentMemoryIntentApprovalRefSchema, AgentMemoryIntentAvailablePayloadSchema, AgentMemoryIntentCompletionSchema, AgentMemoryIntentContentSchema, AgentMemoryIntentFetchRequestSchema, AgentMemoryIntentFetchResponseSchema, AgentMemoryIntentFileObservationSchema, AgentMemoryIntentHostTerminalCodeSchema, AgentMemoryIntentOperationDigestSchema, AgentMemoryIntentOperationSchema, AgentMemoryIntentPathSchema, AgentMemoryIntentReadbackDispositionSchema, AgentMemoryIntentReadbackSchema, AgentMemoryIntentRejectionCodeSchema, AgentMemoryIntentReservationSchema, AgentMemoryIntentRevisionSchema, AgentMemoryIntentV1Schema, AgentMemoryProjectionCommitRequestSchema, AgentMemoryProjectionCommitResponseSchema, AgentMemoryProjectionEraseResultSchema, AgentMemoryProjectionGrantRefSchema, AgentMemoryProjectionMeteringReceiptSchema, AgentMemoryProjectionMutationSchema, AgentMemoryProjectionReceiptSchema, AgentMemoryProjectionSessionRefSchema, AgentMemoryProjectionSnapshotSchema, AgentMemoryProjectionSourceSeqSchema, AgentMemoryProjectionWriterEpochSchema, AgentMemorySelectionSchema, AgentMessageContentTypeSchema, AgentMessageContractSchema, AgentMessageDestinationBindingSchema, AgentMessageDispositionPayloadSchema, AgentMessageDraftPayloadSchema, AgentMessageEgressRequirementSchema, AgentMessageFreshnessCursorSchema, AgentMessagePublishPayloadSchema, AgentMessageServerContextSchema, AgentRefSchema, AgentReliableQuotaPolicySchema, BOT_TURN_OUTCOME_CONTRACT, BOT_TURN_OUTCOME_LIMITS, BYOK_AGENT_HOME_PROJECTIONS_PATH, BYOK_AGENT_HOME_PROJECTION_COMPLETION_ROUTE, BYOK_AGENT_MEMORY_PROJECTIONS_PATH, BYOK_BLOBS_PATH, BYOK_BLOB_CONTENT_ROUTE, BYOK_BLOB_FINALIZE_ROUTE, BYOK_BLOB_URL_ROUTE, BYOK_BOARD_CLAIM_ROUTE, BYOK_BOARD_PATH, BYOK_BOARD_STATUS_ROUTE, BYOK_BOARD_STREAM_PATH, BYOK_BOARD_UNCLAIM_ROUTE, BYOK_CAPABILITIES_PATH, BYOK_CHALLENGE_PATH, BYOK_E2EE_CHAIN_PATH, BYOK_E2EE_KEY_PACKAGES_PATH, BYOK_E2EE_MEMBER_KEY_PATH, BYOK_E2EE_PAIRING_MAC_PATH, BYOK_EVENTS_PATH, BYOK_INPUT_PREPARATIONS_PATH, BYOK_INPUT_PREPARATION_COMPLETION_ROUTE, BYOK_INPUT_PREPARATION_STATUS_ROUTE, BYOK_MESSAGES_PATH, BYOK_PAIR_PATH, BYOK_PRESENCE_PATH, BYOK_RECORDS_PATH, BYOK_RECORD_ROUTE, BYOK_SKILL_PACKS_PATH, BYOK_SKILL_PACK_FILE_ROUTE, BYOK_TOKEN_PATH, BlobDownloadUrlResponseSchema, BlobRefSchema, BotTurnOutcomeSchemaError, CAPABILITY_FLAGS, CONFIGURED_TOOLSETS_MAX_ITEMS, CONTENT_HASH_RE, CUSTOM_HARNESS_CAPABILITY, ChallengeRequestSchema, ChallengeResponseSchema, ConfiguredToolsetsSchema, ConnHelloPayloadSchema, ContentReadPolicySchema, CreateBlobRequestSchema, CreateBlobResponseSchema, DAEMON_TO_SERVER_TYPES, DEVICE_NOT_REGISTERED_CODE, DeviceNotRegisteredResponseSchema, DispatchSelectionSchema, E2EE_MEMBER_CHAIN_APPEND_MAX_ENTRIES, E2EE_MEMBER_CHAIN_APPEND_OPERATION, E2EE_MEMBER_CHAIN_ENTRY_MAX_BYTES, E2EE_MEMBER_CHAIN_OPS, E2EE_MEMBER_CHAIN_READ_MAX_ENTRIES, E2EE_MEMBER_KEY_REGISTER_OPERATION, E2EE_SCOPE_ID_MAX_LENGTH, E2EE_SCOPE_KEY_PACKAGE_PAGE_MAX, E2EE_SCOPE_KEY_PACKAGE_PUT_MAX, E2EE_SCOPE_KEY_PACKAGE_PUT_OPERATION, E2eeClientPairingMacSchema, E2eeKeyPackageAvailablePayloadSchema, E2eeMemberChainEntrySchema, E2eeMemberKeyBundleSchema, E2eeMemberKeyRegisterRequestSchema, E2eePairingMacSchema, E2eeScopeKeyPackageSchema, E2eeScopeKeyPackageV2Schema, EnvelopeParseError, EnvelopeSchema, EnvelopeValidationError, EventsPollQuerySchema, EventsPollResponseSchema, HOST_MCP_TASK_CONTEXT_CAPABILITY, HarnessIdSchema, HarnessInfoSchema, HarnessInventorySchema, INPUT_PREPARATION_WIRE_VERSION, InputPreparationAccountingPolicyRefSchema, InputPreparationArtifactSummarySchema, InputPreparationBindingSchema, InputPreparationCompletionRequestSchema, InputPreparationContentHashSchema, InputPreparationContextDocumentSchema, InputPreparationCounterEvidenceSchema, InputPreparationCounterProviderEvidenceSchema, InputPreparationCounterTargetSchema, InputPreparationHostCanonicalAssistantMessageSchema, InputPreparationMessageSchema, InputPreparationModelCostSchema, InputPreparationModelSchema, InputPreparationOfferBindingSchema, InputPreparationOptionsSchema, InputPreparationPolicyRevisionSchema, InputPreparationProfileIdSchema, InputPreparationProjectionSchema, InputPreparationPromptSnapshotSchema, InputPreparationReadbackSchema, InputPreparationReadinessReasonSchema, InputPreparationReceiptSummarySchema, InputPreparationReferenceSchema, InputPreparationRejectionReasonSchema, InputPreparationResidualKeySchema, InputPreparationResidualValueClassSchema, InputPreparationRuntimeIdentitySchema, InputPreparationSelectionSchema, InputPreparationSourceSchema, InputPreparationStateSchema, InputPreparationStatusQuerySchema, InputPreparationStatusSchema, InputPreparationUserMessageSchema, KNOWN_AGENT_EVENT_TYPES, MAILBOX_READ_AHEAD_CAPABILITY, MAILBOX_READ_AHEAD_MAX_SEQS, MAX_MESSAGES_PER_BATCH, MESSAGES_SEND_MAX_BODY_BYTES, MESSAGE_PAYLOAD_SCHEMAS, MESSAGE_TYPES, MessageSendOutcomeSchema, MessagesSendRequestSchema, MessagesSendResponseSchema, OFFER_ADMISSION_MAX_DURATION_MS, OUTBOUND_REFUSAL_REASONS, OfferAdmissionTimingsSchema, PAIR_RESPONSE_TENANT_ID_MAX_LENGTH, PREPARED_AGENT_MEMORY_MODES, PROTOCOL_VERSION, PROVIDER_MODEL_CAPABILITIES, PROVIDER_PROFILE_BINDING_CAPABILITY, PROVIDER_PROVISIONING_CAPABILITY, PROVIDER_PROVISIONING_DISPOSITIONS, PROVIDER_PROVISIONING_HOST_TERMINAL_CODES, PROVIDER_PROVISIONING_KEY_CHECK_RESULTS, PROVIDER_PROVISIONING_OPERATIONS, PROVIDER_PROVISIONING_OPERATION_GENERATION_MAXIMUM, PROVIDER_PROVISIONING_REJECTION_CODES, PROVIDER_SECRET_SEALING_KEY_REGISTER_OPERATION, PairRequestSchema, PairResponseSchema, PairResponseTenantIdSchema, PreparedAgentMemoryModeSchema, PresencePublishRequestSchema, ProtocolError, ProtocolVersionNumberSchema, ProviderModelCapabilitySchema, ProviderProfileBindingSchema, ProviderProfileHashSchema, ProviderProfileRefSchema, ProviderProfileRevisionSchema, ProviderProvisioningAvailablePayloadSchema, ProviderProvisioningCompletionSchema, ProviderProvisioningDispositionSchema, ProviderProvisioningKeyCheckResultSchema, ProviderProvisioningKeyCheckSchema, ProviderProvisioningOperationDigestSchema, ProviderProvisioningOperationGenerationSchema, ProviderProvisioningOperationSchema, ProviderProvisioningProviderStatusSchema, ProviderProvisioningReadbackSchema, ProviderProvisioningRejectionCodeSchema, RESULT_DOCUMENT_MAX_BYTES, RESULT_ISSUES_MAX_BYTES, RESULT_ISSUES_MAX_COUNT, RESULT_JSON_MAX_DEPTH, RESULT_OUTCOME_MAX_BYTES, RESULT_SCHEMA_INSTANCE_TYPES, RESULT_SCHEMA_KEYWORDS, RESULT_SCHEMA_MAX_BYTES, RESULT_SCHEMA_MAX_DEPTH, ROUTINE_DAYS_OF_WEEK, RUNTIME_FAILURE_CLASSES, RUNTIME_FAILURE_CLASS_CAPABILITY, RUNTIME_IDS, RUNTIME_UNAVAILABLE_CAUSES, RUNTIME_UNAVAILABLE_CAUSE_CAPABILITY, RequiredToolsetsSchema, ResultDocumentSchemaSchema, RuntimeCapabilitiesSchema, RuntimeFailureClassSchema, RuntimeIdSchema, RuntimeInfoSchema, RuntimeUnavailableEntrySchema, RuntimeVersionPolicyProjectionSchema, SEALED_DECLINE_CODES, SEALED_INLINE_MAX_PADDED_LENGTH, SEALED_OUTPUT_CIPHERTEXT_REF_CAPABILITY, SEALED_PAYLOAD_CAPABILITY, SEALED_PAYLOAD_CATEGORIES, SEALED_PAYLOAD_MAX_CONTENT_LENGTH, SEALED_PAYLOAD_MAX_PADDED_LENGTH, SEALED_PAYLOAD_SUITE, SEALED_PAYLOAD_V1_CATEGORIES, SEALED_PAYLOAD_VERSION, SEALED_SPLIT_TABLE, SEALED_TASK_PLAIN_CODES, SERVER_TO_DAEMON_TYPES, SealedPayloadSchema, SealedTaskInputSchema, SealedTaskOutputSchema, SessionSelectionSchema, TASK_FAIL_REASON_MAX_BYTES, TASK_STATES, TASK_TRANSITIONS, TERMINAL_INFERENCE_USAGE_CLIENT_VERSION_MAX_LENGTH, TERMINAL_INFERENCE_USAGE_MAX_DURATION_MS, TERMINAL_INFERENCE_USAGE_MAX_TOKENS, TERMINAL_INFERENCE_USAGE_MODEL_MAX_LENGTH, TERMINAL_INFERENCE_USAGE_PROVIDER_MAX_LENGTH, TERMINAL_PROJECTION_SELECTION_CAPABILITY, TaskApprovalResolvedPayloadSchema, TaskApprovePayloadSchema, TaskArtifactPayloadSchema, TaskAwaitApprovalPayloadSchema, TaskCancelPayloadSchema, TaskCancelledPayloadSchema, TaskClaimPayloadSchema, TaskCompletePayloadSchema, TaskDeclinePayloadSchema, TaskFailPayloadSchema, TaskFailureSchema, TaskOfferPayloadSchema, TaskOfferPlainPayloadSchema, TaskOfferSealedPayloadSchema, TaskProgressPayloadSchema, TaskRejectPayloadSchema, TaskSealingSchema, TaskStartedPayloadSchema, TaskSteerPayloadSchema, TaskSteerSealedPayloadSchema, TerminalAgentHomeMemoryChangeSchema, TerminalAgentHomeProjectionSchema, TerminalInferenceUsageSchema, TerminalPreparedObservationSchema, TerminalProjectionContractSchema, TerminalProjectionSelectionSchema, TokenRequestSchema, TokenResponseSchema, ToolsetIdSchema, UnknownAgentEventSchema, UnknownMessageTypeError, WIRE_ADDITIONS, agentMemoryIntentFetchResponseSchemaFor, agentMemoryProjectionBase64UrlByteLength, botTurnOutcomeFragments, boundFailureReason, byokAgentHomeProjectionCompletionPath, byokBlobContentPath, byokBlobFinalizePath, byokBlobUrlPath, byokInputPreparationCompletionPath, byokInputPreparationStatusPath, byokRecordPath, byokSkillPackFilePath, canTransition, checkResultDocument, checkResultSchema, composeBotTurnOutcomeSchema, createEnvelope, decodeEnvelope, encodeEnvelope, isKnownAgentEvent, isPreparedAgentMemoryMode, isSealableMessageType, isSealedPayload, isSealedTaskPlainOutput, isServerToDaemonType, parseMessage, partitionAgentEvents, readDeclineCode, readRuntimeUnavailableCause, readTaskFailure, requiredReceiverCapabilities, resultOutcomeMaxBytes, sealedBase64UrlByteLength, sealedPayloadPaddedLength, validateResultOutcome };
|
|
3058
8
|
//# sourceMappingURL=index.js.map
|
|
3059
9
|
//# sourceMappingURL=index.js.map
|