@cotal-ai/connector-opencode 0.193.0 → 0.193.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -117,7 +117,7 @@ ${serve.endpoint}`;if(this.principalServers.has(serverKey))throw new Error(`anot
117
117
  ${context}
118
118
  (This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze5({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),modes:{type:"object",minProperties:1,maxProperties:32,propertyNames:{minLength:1,maxLength:128},additionalProperties:{anyOf:[{type:"boolean"},{type:"string",minLength:1,maxLength:256}]}},launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},askPermissions:{type:"boolean"},reasoningEvents:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),firstCommand:AGENT_COMMAND_INPUT_SCHEMA,autoName:{type:"boolean"},persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},firstCommand:{type:"object",additionalProperties:false,required:["id"],properties:{id:{type:"string",pattern:"^[a-z2-7]{26}$"}}},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze5({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze5(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze5(child);Object.freeze(v3)}return v3}var import_nkeys12=__toESM(require_mod2(),1);var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze6(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze6(child);Object.freeze(value)}return value}var text3={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint2={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed5=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed5({owner,actor,lifecycleUid:uid});var pair={threadId:text3,toolCallId:text3};var status=(state,fields={})=>closed5({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze6(closed5({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed5({owner,actor}),iat:uint2,exp:uint2,issuer:closed5({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze6(closed5({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint2}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze6(closed5({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed5({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint2,registrationRevision:{...uint2,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed5({t0:uint2,watermark:uint2,watermarkTakenAt:uint2,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint2}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze6(closed5(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze6({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint2,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint2}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze6({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze6(closed5({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze6(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze6(closed5({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze6({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze6({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze6([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze6({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row2=>({name:row2.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row2.capability,inputDigest:singleDocumentClosure(row2.input).closureDigest,outputDigest:singleDocumentClosure(row2.output).closureDigest}))});var import_nkeys13=__toESM(require_mod2(),1);var LANG_PROBLEM_DETAIL_KIND="ai.cotal.lang.problem";var RUN_ACTIVATION_WAIT_MS=15e3;var RUN_LAUNCH_DEADLINE_MS=RUN_ACTIVATION_WAIT_MS+1e4;var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin","artifacts"]);var import_jetstream36=__toESM(require_mod6(),1);var import_transport_node36=__toESM(require_transport_node(),1);var import_jetstream37=__toESM(require_mod6(),1);var import_kv18=__toESM(require_mod5(),1);import{readFileSync as readFileSync4}from"node:fs";import{userInfo as userInfo2}from"node:os";var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_KEY","COTAL_CONTROL_VERSION","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path2=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path2)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k2=>env[k2]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path2)}function controlFromEnv(env=process.env){if(env.COTAL_CONTROL_TOKEN?.trim())throw new Error("COTAL config: COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange. Set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead; this build refuses the old name rather than guess which protocol it meant.");const path2=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token3=material?material.controlKey:directControlKey(env);if(path2&&token3){const direct=env.COTAL_CONTROL_VERSION;const version2=material?material.controlVersion:direct?.trim()?/^(0|[1-9][0-9]*)$/.test(direct)?Number(direct):direct:void 0;assertControlVersion(version2,material?"this launch's material":"COTAL_CONTROL_VERSION");return{path:path2,token:token3,version:version2}}if(!path2&&!token3)return void 0;if(path2)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control key could be resolved - neither the launch material nor COTAL_CONTROL_KEY carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control key was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function directControlKey(env){const key=env.COTAL_CONTROL_KEY;if(!key?.trim()){if(env.COTAL_CONTROL_VERSION?.trim())throw new Error("COTAL config: COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY. The version travels with the key; set both or neither.");return void 0}if(key!==key.trim())throw new Error("COTAL config: COTAL_CONTROL_KEY has whitespace around it. A key is used as given, never trimmed; remove the whitespace.");return key}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var FEEDBACK_URL="https://broker.cotal.ai/v1/feedback";var PUBLIC_FEEDBACK_URL="https://cotal.ai/v1/feedback";function isAuthed(config2){return Boolean(config2.creds)||Boolean(config2.userAuth)}function splitList(v3){if(!v3)return[];return v3.split(",").map(s3=>s3.trim()).filter(Boolean)}function endpointsEnv(v3){let raw;try{raw=JSON.parse(v3)}catch{raw=void 0}if(!Array.isArray(raw))throw new Error("COTAL_ENDPOINTS: expected the JSON list the launcher writes");return parsePersonaEndpoints(raw,"COTAL_ENDPOINTS")}function envList(v3){return v3===void 0?void 0:splitList(v3)}var EnvFlagError=class extends Error{};function envFlag(env,name2){const value=env[name2]?.trim();if(!value)return void 0;if(/^(1|true|yes|on)$/i.test(value))return true;if(/^(0|false|no|off)$/i.test(value))return false;throw new EnvFlagError(`COTAL config: ${name2} must be 1/true/yes/on or 0/false/no/off, got "${env[name2]}"`)}function scrubLaunchMaterial(env=process.env){const path2=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path2)discardLaunchMaterial(path2)}function backfillFloorFromEnv(env){const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n2=Number(backfillFloorRaw);if(!Number.isInteger(n2)||n2<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n2}return backfillFloor}function configFromEnv(env=process.env){const link=env.COTAL_LINK?.trim()?parseJoinLink(env.COTAL_LINK.trim()):void 0;const def=env.COTAL_AGENT_FILE?.trim()?loadAgentFile(env.COTAL_AGENT_FILE.trim()):void 0;const name2=env.COTAL_NAME?.trim()||def?.name||(link?userInfo2().username:void 0);if(!name2)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const displayName=env.COTAL_DISPLAY_NAME||void 0;if(displayName!==void 0){try{assertValidName(displayName)}catch(e3){throw new Error(`COTAL config: COTAL_DISPLAY_NAME: ${e3.message}`)}}const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e3){throw new Error(`COTAL config: ${e3.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c3=>resolvedMuted.includes(c3));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync4(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloor=backfillFloorFromEnv(env);const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a3=>typeof a3==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync4(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync4(credsPath,"utf8"):initialCreds,userAuth,name:name2,...displayName!==void 0&&displayName!==name2?{displayName}:{},...envFlag(env,"COTAL_AUTO_NAME")===true&&displayName===void 0?{autoName:true}:{},role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,modelPolicy:env[MODEL_POLICY_ENV]||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,eventPayloadsWithheld:material?.eventPayloadsWithheld===true||envFlag(env,"COTAL_EVENT_PAYLOADS")===false,askPermissions:material?.askPermissions===true,reasoningEvents:material?.reasoningEvents===true,...material?.fixedOptions!==void 0?{fixedOptions:material.fixedOptions}:{},quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}import{EventEmitter as EventEmitter2}from"node:events";import{createHash as createHash8,randomUUID as randomUUID11}from"node:crypto";import{open as open3,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname7,join as join7}from"node:path";import{createHash as createHash7,randomUUID as randomUUID10}from"node:crypto";import{constants as constants4}from"node:fs";import{lstat as lstat2,open as open2,readFile,readdir as readdir2,rename,unlink}from"node:fs/promises";import{dirname as dirname6,join as join6}from"node:path";var EVENT_WAL_VERSION=4;var WalCorruptError=class extends Error{path;invariant;constructor(path2,invariant,detail){super(`event WAL at ${path2} is unusable (${invariant}): ${detail}`);this.path=path2;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path2,expectedGen,foundGen){super(`event WAL at ${path2} was written by another handle since this one read it (this handle expects generation ${expectedGen}, the file is at ${foundGen===void 0?"no file at all":`generation ${foundGen}`}) \u2014 refusing to overwrite it. A second emitter or a stale handle is writing this principal's log.`);this.path=path2;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n2=>Number.isSafeInteger(n2)&&n2>=0;function docGeneration(path2,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path2,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path2){return open2(path2,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path2,p2,f2){if(p2.E<f2.lastSubjectSeq)throw new WalCorruptError(path2,"pending.E >= frontier.lastSubjectSeq",`pending.E=${p2.E} is behind this thread's last acknowledgement at ${f2.lastSubjectSeq}`);if(p2.seq!==f2.seq+1)throw new WalCorruptError(path2,"pending.seq === frontier.seq + 1",`pending.seq=${p2.seq} frontier.seq=${f2.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p2.state==="sent_unacked"){if(p2.ackSeq!==void 0)throw new WalCorruptError(path2,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p2.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt2(p2.ackSeq))throw new WalCorruptError(path2,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p2.ackSeq)}`);if(p2.ackSeq<=p2.E)throw new WalCorruptError(path2,"acked.ackSeq > pending.E",`ackSeq=${p2.ackSeq} did not advance the frozen subject tip ${p2.E}`)}function parseBrackets(path2,field,v3,nullable2){if(v3===null&&nullable2)return null;if(typeof v3!=="object"||v3===null)throw new WalCorruptError(path2,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v3));const b3=v3;if(b3.run!==void 0&&typeof b3.run!=="string")throw new WalCorruptError(path2,`${field}.run is a string or absent`,JSON.stringify(b3.run));const lists={text:b3.text,reasoning:b3.reasoning,tools:b3.tools};for(const[k2,list2]of Object.entries(lists)){if(!Array.isArray(list2)||list2.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path2,`${field}.${k2} is an array of strings`,JSON.stringify(list2))}if(b3.run===void 0&&b3.text.concat(b3.reasoning,b3.tools).length>0)throw new WalCorruptError(path2,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b3));return{run:b3.run,text:b3.text,reasoning:b3.reasoning,tools:b3.tools}}function parsePayloadCalls(path2,value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>4096||Object.entries(value).some(([id2,allowed])=>!id2||typeof allowed!=="boolean"))throw new WalCorruptError(path2,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path2,raw,space2,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(path2,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path2,"document is an object",typeof d2);const doc=d2;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path2,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path2,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path2,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path2,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path2,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path2,"epoch is a non-empty string",String(doc.epoch));const f2=doc.frontier;if(!f2||!isSafeNonNegInt2(f2.seq)||!isSafeNonNegInt2(f2.lastSubjectSeq))throw new WalCorruptError(path2,"frontier is well-formed",JSON.stringify(doc.frontier));if(f2.sourceCursor!==void 0&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path2,"frontier.sourceCursor is a string or absent",typeof f2.sourceCursor);if(f2.seq===0!==(f2.lastSubjectSeq===0))throw new WalCorruptError(path2,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f2));if((f2.seq>0||f2.lastSubjectSeq>0)&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path2,"a nonzero frontier carries its sourceCursor",JSON.stringify(f2));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path2,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p2=doc.pending;if(p2.state!=="sent_unacked"&&p2.state!=="acked")throw new WalCorruptError(path2,"pending.state is a known tag",String(p2.state));if(typeof p2.id!=="string"||p2.id.length===0)throw new WalCorruptError(path2,"pending.id is a non-empty string",String(p2.id));try{assertIdToken(p2.id,"event WAL pending.id")}catch(e3){throw new WalCorruptError(path2,"pending.id satisfies the wire id grammar",e3.message)}if(!isSafeNonNegInt2(p2.E)||!isSafeNonNegInt2(p2.seq))throw new WalCorruptError(path2,"pending E/seq are safe non-negative integers",JSON.stringify(p2));if(typeof p2.sourceCursor!=="string")throw new WalCorruptError(path2,"pending.sourceCursor is a string",typeof p2.sourceCursor);if(!Array.isArray(p2.body)||p2.body.length===0)throw new WalCorruptError(path2,"pending.body is a non-empty array of parts",JSON.stringify(p2.body));if(doc.v===1)throw new WalCorruptError(path2,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p2.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p2.brackets=parseBrackets(path2,"pending.brackets",p2.brackets,false);if(p2.payload!==void 0){const payload=p2.payload;if(doc.v<4||!payload||typeof payload!=="object"||!Array.isArray(payload.body)||payload.body.length===0||!isSafeNonNegInt2(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt2(payload.ackSeq)||payload.ackSeq<=payload.E))throw new WalCorruptError(path2,"pending payload is a v4 frozen publication",JSON.stringify(payload));try{assertIdToken(payload.id,"event WAL payload id")}catch(e3){throw new WalCorruptError(path2,"pending payload id satisfies the wire id grammar",e3.message)}}p2.payloadCalls=parsePayloadCalls(path2,p2.payloadCalls);pending=p2;assertPendingVintage(path2,pending,f2)}const brackets=doc.v===1?null:parseBrackets(path2,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path2,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f2,pending,payloadCalls:parsePayloadCalls(path2,doc.payloadCalls),brackets}}var EventWal=class _EventWal{path;doc;chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}constructor(path2,doc){this.path=path2;this.doc=doc}get payloadCalls(){return{...this.doc.pending?.payloadCalls??this.doc.payloadCalls??{}}}get epoch(){return this.doc.epoch}get space(){return this.doc.space}get principal(){return this.doc.principal}get threadId(){return this.doc.threadId}get brackets(){return this.doc.brackets}get frontier(){return{...this.doc.frontier}}get pending(){return this.doc.pending?{...this.doc.pending}:null}async pendingSiblings(){const threadDir=createHash7("sha256").update(this.threadId).digest("hex").slice(0,16);if(dirname6(this.path).split(/[\\/]/).pop()!==threadDir)return[];const parent=dirname6(dirname6(this.path));const siblings=[];for(const entry of await readdir2(parent,{withFileTypes:true})){if(!/^[a-f0-9]{16}$/.test(entry.name))continue;const path2=join6(parent,entry.name,"wal.json");if(path2===this.path)continue;if(entry.isSymbolicLink())throw new WalCorruptError(path2,"a real thread directory","found a symlink");if(!entry.isDirectory())continue;let bytes;try{const st2=await lstat2(path2);if(!st2.isFile()||st2.nlink!==1)throw new WalCorruptError(path2,"a real thread log with one name","refusing linked or non-file state");const file2=await open2(path2,constants4.O_RDONLY|(constants4.O_NOFOLLOW??0));try{bytes=await file2.readFile()}finally{await file2.close()}}catch(e3){if(e3.code==="ENOENT")continue;throw e3}let raw;let doc;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes);doc=JSON.parse(raw)}catch{process.stderr.write(`[cotal-connector] Skipping sibling event WAL at ${path2}: unreadable UTF-8 JSON. The file is unchanged.
119
119
  `);continue}if(doc?.pending?.state!=="sent_unacked")continue;const threadId=doc.threadId;try{if(typeof threadId!=="string"||createHash7("sha256").update(threadId).digest("hex").slice(0,16)!==entry.name)throw new WalCorruptError(path2,"thread id matches its directory","refusing misplaced state");const sibling=new _EventWal(path2,parseDoc(path2,raw,this.space,threadId,this.principal));if(sibling.pending)siblings.push(sibling)}catch(e3){if(!(e3 instanceof WalCorruptError))throw e3;process.stderr.write(`[cotal-connector] Skipping sibling event WAL at ${path2}: ${e3.invariant}. The file is unchanged.
120
- `)}}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path2,opts){let raw;let bytes;try{bytes=await readFile(path2)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path2,"the file is valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}}if(raw===void 0){if(opts.subjectMayExist)throw new WalCorruptError(path2,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path2,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path2,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path2,parseDoc(path2,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID10(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.E<this.doc.frontier.lastSubjectSeq)throw new Error(`event WAL ${this.path}: E=${frame.E} is behind this thread's last acknowledgement`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2?.payload||p2.state!=="sent_unacked"||p2.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p2.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p2,payload:{...p2.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p2.payload&&p2.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);const tip=Math.max(this.expectedTip,p2.E);if(ackSeq<=tip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject tip ${tip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p2,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="acked"||p2.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p2.seq,lastSubjectSeq:p2.ackSeq,sourceCursor:p2.sourceCursor},pending:null,brackets:p2.brackets,payloadCalls:p2.payloadCalls??this.doc.payloadCalls})})}async advanceCursorOnly(rangeEnd){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: cannot advance the cursor while a frame is pending`);await this.write({...this.doc,frontier:{...this.doc.frontier,sourceCursor:rangeEnd}})})}async abandon(){return this.serialize(async()=>{await this.assertNotClobbering();if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so an abandonment here would clear this log and leave the principal's shared tip standing, which is the partial abandonment this method refuses to produce; bind the principal's record with bindSubjectFrontier first.`);await this.subject.reset();await this.write({...this.doc,epoch:randomUUID10(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname6(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID10().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await rename(tmp,this.path)}catch(e3){await unlink(tmp).catch(()=>{});throw e3}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes===void 0){if(this.doc.gen!==0)throw new WalStaleWriterError(this.path,this.doc.gen,void 0);return}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(this.path,"the file is valid UTF-8","invalid UTF-8 bytes on the file about to be replaced; refusing rather than substituting U+FFFD")}let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(this.path,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(this.path,"document is an object",typeof d2);const onDisk=docGeneration(this.path,d2);if(onDisk!==this.doc.gen)throw new WalStaleWriterError(this.path,this.doc.gen,onDisk)}};var EventsStateRootMissing=class extends Error{constructor(message2){super(message2);this.name="EventsStateRootMissing"}};function resolveEventsStateRoot(env){const root=env.COTAL_WORKSPACE_ROOT;if(typeof root!=="string"||root.trim()==="")throw new EventsStateRootMissing("events are enabled for this session but COTAL_WORKSPACE_ROOT is not set, so there is nowhere to put the event write-ahead log. The launcher forwards it from LaunchOpts.workspaceRoot; a session started outside a manager has no workspace root and must not publish events. Refusing rather than defaulting to the working directory, which would put the WAL somewhere no later start looks.");return root}function h2(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h2(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json"),deltaJournalPath:join7(threadDir,"deltas.jsonl")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path2,invariant,detail){super(`event WAL principal lock at ${path2} (${invariant}): ${detail}`);this.path=path2;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e3){return e3.code!=="ESRCH"}}async function createLockFile(path2){try{return await openExclusiveNoFollow(path2)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path2){let raw;try{raw=await readFile2(path2,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record3;try{record3=JSON.parse(raw)}catch{throw new PrincipalLockError(path2,"the lock names its owner","the file is not readable JSON, so its owner cannot be checked; refusing rather than reclaiming a lock that may be held")}const r2=record3;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path2,"the lock names its owner",`the record carries pid=${String(r2.pid)} host=${String(r2.host)}, which names nobody checkable`);const here=hostname();if(r2.host!==here)throw new PrincipalLockError(path2,"the recorded owner is on THIS host",`held by pid ${r2.pid} on ${r2.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r2.pid))throw new PrincipalLockError(path2,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path2).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}async function acquirePrincipalLock(lockPath){const already=held.get(lockPath);if(already)return already;let fh=await createLockFile(lockPath);if(fh===void 0){await reclaimIfOwnerIsGone(lockPath);fh=await createLockFile(lockPath);if(fh===void 0)throw new PrincipalLockError(lockPath,"the reclaimed lock is free when this process takes it","another process created the lock between the reclaim and this open, and now holds this principal")}const record3=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID11(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record3,"utf8");await fh.sync()}catch(e3){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e3}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e3){const code=e3.code;if(code==="EPERM"||code==="EACCES")return;throw e3}try{await fh.sync()}catch(e3){const code=e3.code;if(code!=="EBADF"&&code!=="EINVAL"&&code!=="EPERM"&&code!=="EISDIR")throw e3}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h2(opts.space),h2(opts.principal),h2(opts.threadId));for(let dir=loc.threadDir;;dir=dirname7(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname7(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){const workspaceRoot=resolveEventsStateRoot(env);try{await checkEventStartup({workspaceRoot,space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}catch(error51){if(!(error51 instanceof EventStateConflictError))throw error51;const principal=principalKey(ep.principal.owner,ep.principal.actor).key;const threadId="startup-pending-inspection";const{walPath}=eventWalLocation({workspaceRoot,space:ep.space,principal,threadId});const inspection=await EventWal.open(walPath,{space:ep.space,principal,threadId,subjectMayExist:false});if((await inspection.pendingSiblings()).length===0)throw error51}}var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY2=Symbol.for("cotal.once-handoff");function proc(){const g2=globalThis;return g2[KEY2]??={handoffs:new Map}}var keyOf=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p2=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer2=setTimeout(()=>p2.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer2.unref?.();p2.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer:timer2})}return true}function confirmOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="sealed")return false;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed")return false;if(h3.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="confirmed"||h3?.state==="sealed")return;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed"||h3.timer===void 0)return;clearTimeout(h3.timer);h3.timer=void 0}function onOnceHandoffTimeout(fn2){proc().timedOut=fn2}function registerOnceExit(fn2){proc().exit=fn2}function exitOnceSeat(){const p2=proc();if(p2.exiting)return p2.exiting;const exiting=askOnceExit(p2.exit).then(ending=>{if(!ending){p2.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p2.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}var CONNECTOR_VERSION="0.193.0";function managerBearerArgv(argv,instanceId){return[...argv,"--manager-call",...instanceId?["--manager-instance",instanceId]:[]]}var MANAGER_BEARER_MARGIN_MS=12e4;function compareRelease(a3,b3){const[x2,y3]=[a3,b3].map(v3=>v3.split(/[-+]/)[0].split(".").map(Number));for(let i2=0;i2<3;i2++)if(x2[i2]!==y3[i2])return(x2[i2]??0)-(y3[i2]??0);return 0}function bearerExpiryMs2(token3){try{const exp=JSON.parse(Buffer.from(token3.split(".")[1]??"","base64url").toString("utf8")).exp;return typeof exp==="number"&&Number.isFinite(exp)?exp*1e3:void 0}catch{return void 0}}function abortable(p2,signal){if(!signal)return p2;if(signal.aborted){void p2.catch(()=>{});return Promise.reject(signal.reason)}return new Promise((resolve3,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve3(v3)},e3=>{signal.removeEventListener("abort",onAbort);reject(e3)})})}var AgentManagerCalls=class{getConfig;getEndpoint;getLaunchEnv;invokeEndpoint;constructor(getConfig,getEndpoint,getLaunchEnv,invokeEndpoint){this.getConfig=getConfig;this.getEndpoint=getEndpoint;this.getLaunchEnv=getLaunchEnv;this.invokeEndpoint=invokeEndpoint}get config(){return this.getConfig()}get ep(){return this.getEndpoint()}get launchEnv(){return this.getLaunchEnv()}clear(){this.managerBearers.clear()}managerCredential(instanceId){const user=this.config.userAuth;if(user?.bearerCmd){const argv=managerBearerArgv(user.bearerCmd,instanceId);return{bearer:signal=>this.managerCallBearer(argv,signal),drop:()=>{this.managerBearers.delete(JSON.stringify(argv))}}}if(user?.managerBearer)return{bearer:signal=>this.freshManagerBearer(user,instanceId,signal)};return void 0}async freshManagerBearer(user,managerInstanceId,signal,timeoutMs=3e4){if(user.bearerCmd)return this.execBearerCmd(managerBearerArgv(user.bearerCmd,managerInstanceId),signal,timeoutMs);const timeout=AbortSignal.timeout(timeoutMs);const bounded=signal?AbortSignal.any([signal,timeout]):timeout;try{bounded.throwIfAborted();const exchange2=user.managerBearer({managerInstanceId,signal:bounded});return await abortable(exchange2,bounded)}catch(e3){if(signal?.aborted)throw e3;const message2=(e3 instanceof Error?e3.message:String(e3)).replace("--manager-instance <instanceId>","the instance argument");throw new EpEnvelopeError(e3 instanceof EpEnvelopeError?e3.code:"unavailable",message2,void 0,"not-executed")}}async listManagerEndpoints(input,instance){const user=this.config.userAuth;if(!user)return{none:"manager calls ride this session's own credential on this mesh, so the session view covers them"};const managerInstanceId=instance??this.config.managerInstanceId;const credential=this.managerCredential(managerInstanceId);if(!credential)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const token3=await credential.bearer().catch(e3=>{throw user.bearerCmd&&e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token3);return withUserManagerListing({...this.config,managerInstanceId},token3,exp===void 0?void 0:exp/1e3,async(nc,listing)=>listing===void 0?{unbound:true}:this.ep.listEndpointsOver(nc,listing,input))}managerBearers=new Map;managerCallBearer(argv,signal){const key=JSON.stringify(argv);const held2=this.managerBearers.get(key);if(held2&&(held2.refreshAt===void 0||Date.now()<held2.refreshAt))return abortable(held2.flight,signal);const entry={flight:this.execBearerCmd(argv)};this.managerBearers.set(key,entry);entry.flight.then(token3=>{const exp=bearerExpiryMs2(token3);if(exp===void 0||exp-MANAGER_BEARER_MARGIN_MS<=Date.now()){if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)}else entry.refreshAt=exp-MANAGER_BEARER_MARGIN_MS},()=>{if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)});return abortable(entry.flight,signal)}async execBearerCmd(argv,signal,timeoutMs){const bearer=await runAgentBearer(argv,{env:this.launchEnv,signal,timeoutMs});if(!bearer)throw new Error(`bearer command printed nothing (${argv[0]})`);return bearer}async managerInvoke(command,args,opts={}){const clean=args===void 0?void 0:Object.fromEntries(Object.entries(args).filter(([,v3])=>v3!==void 0));let r2;let dropBearer;try{const input=clean&&Object.keys(clean).length?clean:void 0;const user=this.config.userAuth;if(user){const managerInstanceId=opts.instanceId??this.config.managerInstanceId;const credential=this.managerCredential(managerInstanceId);if(!credential)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearer=signal=>credential.bearer(signal).catch(e3=>{if(signal?.aborted||!(e3 instanceof Error)||e3 instanceof EpEnvelopeError)throw e3;const message2=e3.message.replace("--manager-instance <instanceId>","the instance argument");if(typeof e3.retryAfterSeconds==="number")throw new EpEnvelopeError("resource-exhausted",message2,void 0,"not-executed");if(e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",message2,void 0,"not-executed");throw new Error(message2)});dropBearer=credential.drop;r2=await invokeUserManager({...this.config,managerInstanceId},bearer,command,input,{...invokeOpts,follow:follow?(submit,prepare)=>this.ep.followServiceGoal(BASELINE_LIFECYCLE_ENDPOINT,submit,opts.deadlineMs,{prepare,reconcile:async(goalId,attributed,context)=>{const instanceId=attributed.responder?.instanceId;if(!instanceId)throw new Error("accepted goal has no broker-attributed manager instance");const bearer2=signal=>this.freshManagerBearer(user,instanceId,signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...user,owner:context.caller.owner,actor:context.caller.actor}};const queryRes=await invokeUserManager(config2,bearer2,"goal-result",{goalId},{signal:context.signal,deadlineMs:Math.min(invokeOpts.deadlineMs??1e4,context.deadlineMs)});if(queryRes.reply.ok!==true)throw new Error(queryRes.reply.error?.message??"goal-result query refused");return queryRes.reply.data}}):void 0})}else{const launchLocal=command==="stop"||command==="spawn"||command==="define-persona";const classInstanceId=this.config.creds&&launchLocal&&opts.instanceId===void 0?this.config.managerInstanceId:void 0;r2=await this.invokeEndpoint(BASELINE_LIFECYCLE_ENDPOINT,command,input,{...opts,...classInstanceId!==void 0?{classInstanceId}:{}})}}catch(e3){dropBearer?.();if(e3 instanceof EpEnvelopeError){const submitted=command==="spawn"&&e3.outcome==="unknown"?e3.details?.find(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command&&typeof d2.requestId==="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(d2.requestId)):void 0;if(submitted)return{...controlReplyFromThrown(e3,`${e3.code}: ${e3.message}`),outcome:"unknown",data:{goalId:submitted.requestId,submissionUnknown:true}};const undeclared=undeclaredArg(e3);if(undeclared!==void 0&&command!=="status")return{...controlReplyFromThrown(e3,await this.undeclaredArgMessage(command,e3,undeclared)),...e3.outcome?{outcome:e3.outcome}:{}};const unknownDefinition=command==="define-persona"&&e3.outcome!=="not-executed"&&e3.code==="deadline-exceeded"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.command===command);const unknownYield=command==="turn-yield"&&e3.code==="deadline-exceeded"&&e3.outcome==="unknown"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command);const message2=unknownYield?`${e3.code}: ${e3.message}. The yield may already have been recorded. After reconnecting, retry cotal_yield with the same turn id and intended status. An already-settled reply confirms the turn is terminal, not which attempt settled it. A successful reply records the yield if it is still active. This retry is not a read-only check.`:unknownDefinition?`${e3.code}: ${e3.message}`:unansweredRequest(e3)?`${e3.message} (no responder answered - a manager may be down, or this credential holds no "${command}" capability and the broker denied the request)`:`${e3.code}: ${e3.message}`;return{...controlReplyFromThrown(e3,message2),...e3.outcome?{outcome:e3.outcome}:{}}}return{ok:false,error:e3.message}}if(r2.reply.ok!==true)dropBearer?.();return{...controlReplyFrom(r2.reply),instanceId:r2.responder?.instanceId,...r2.reply.error?.outcome?{outcome:r2.reply.error.outcome}:{}}}async undeclaredArgMessage(command,e3,key){const head=`${e3.code}: ${e3.message}. The manager's ${command} does not take "${key}", which this connector at Cotal ${CONNECTOR_VERSION} sends`;const instanceId=undeclaredArgInstance(e3);const answer2=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer2?.ok===true&&answer2.instanceId===instanceId?answer2.data?.version:void 0;const manager=typeof reported==="string"&&/^\d+\.\d+\.\d+/.test(reported)?reported:void 0;const updateManager=`on the manager's host run \`cotal update --self\`, then \`cotal manager restart\`, or, if you set "${key}", call again without it`;if(manager===void 0)return`${head}, so the manager most likely runs an older Cotal: ${updateManager}`;const order2=compareRelease(CONNECTOR_VERSION,manager);if(order2>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order2<0)return`${head}. The manager runs Cotal ${manager}, so this connector is the older side: run \`cotal update --self\` here and start a new session`;return`${head}. The manager also reports Cotal ${manager}, so one side is another build of that version: reinstall that side`}};var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token3,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token3,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token3;const connectOpts=standaloneConnectOpts({bearer:token3,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller2=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller2}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller2=skipped?void 0:await issued();const listing=caller2??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller2;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve3=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller2,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve3(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller2=await issuedUserCaller(nc,config2.space,connId,caller2);legacyRail.delete(key);return resolve3(signal,remaining())}};const connect4=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token3=await bearer(signal);let credentialId;try{({caller:caller2,instanceId,credentialId}=managerCallerBinding(token3,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}))}catch{throw new EpEnvelopeError("failed-precondition","the manager control bearer is not bound to the expected caller and manager instance",void 0,"not-executed")}const connectOpts=standaloneConnectOpts({bearer:token3,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");try{nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left})}catch(error51){signal?.throwIfAborted();if(error51 instanceof EpEnvelopeError)throw error51;throw new EpEnvelopeError(isAuthRejection(error51)?"permission-denied":"unavailable",error51 instanceof Error?error51.message:String(error51),void 0,"not-executed")}if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token3;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller2=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller2)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect4(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve3(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect4();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}import{randomBytes as randomBytes4}from"node:crypto";var COMMAND_LIST_MS=1e4;var MAX_QUEUED_COMMANDS=8;var ENDED_COMMANDS_KEPT=32;var FIRST_COMMAND_READY_MS=6e4;var FIRST_COMMAND_POLL_MS=250;var CommandRefused=class extends Error{code;constructor(code,message2){super(message2);this.code=code;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code,message2)=>new EpEnvelopeError(code,message2,void 0,"not-executed");var what=e3=>"turn"in e3.job?"the turn":`the ${e3.job.command.target} "${e3.job.command.name}"`;function cut2(text5,max){const chars=[...text5];return chars.length<=max?text5:`${chars.slice(0,max-1).join("")}\u2026`}async function runEntry(e3,dispatcher,end2,taken,answered=()=>{}){if(!e3)return"empty";taken(e3);try{if("turn"in e3.job)await dispatcher.turn({...e3.job.turn,id:e3.id});else{const out=await dispatcher.dispatch(e3.job.command);if(out&&typeof out.output==="string"&&out.output!=="")answered(e3,out.output)}end2(e3,{kind:"started"});return"dispatched"}catch(err3){const message2=String(err3?.message??err3);end2(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut2(message2,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut2(`the harness failed, so ${what(e3)} may have started: ${message2}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}}function takeGate(queuedCount,take,closed6){let inFlight;let closedNow=false;void closed6.then(()=>{closedNow=true});return async()=>{if(inFlight){const atSettlement=await Promise.race([inFlight,closed6.then(()=>0)]);return closedNow||atSettlement===0?"empty":"busy"}if(queuedCount()===0)return"empty";let settle;inFlight=new Promise(resolve3=>{settle=resolve3});try{return await take()}finally{inFlight=void 0;settle(queuedCount())}}}function within(work,ms){let timer2;const late2=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms/1e3} s`)),ms)});return Promise.race([Promise.resolve().then(work),late2]).finally(()=>clearTimeout(timer2))}function servedCommands(dispatcher){const now=dispatcher!==void 0&&dispatcher.unsupported?.()===void 0;const turn=now&&typeof dispatcher.turn==="function";return{interrupt:now&&typeof dispatcher.interrupt==="function",turn,images:turn&&dispatcher.images===true,usage:now&&typeof dispatcher.usage==="function",setModel:now&&typeof dispatcher.setModel==="function"}}function notSelf(ctx,what2){if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused("permission-denied",`an agent never ${what2}`)}async function listCommands(dispatcher){if(!dispatcher||dispatcher.targets.size===0||dispatcher.unsupported?.()!==void 0)return{supported:false};let listed;try{listed=await within(()=>dispatcher.list(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not list its commands: ${e3.message}`)}return{supported:true,commands:fitCommandEntries(listed,dispatcher.targets)}}async function readUsage(dispatcher){if(!dispatcher?.usage||dispatcher.unsupported?.()!==void 0)return{supported:false};let got;try{got=await within(()=>dispatcher.usage(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not report its usage: ${e3.message}`)}return{supported:true,...got?.context?{context:got.context}:{},...got?.cost?{cost:got.cost}:{}}}function createCommandLane(dispatcher,onQueued,first,observer){const entries=new Map;const ended=[];let closed6=false;let held2;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued"&&e3!==held2);const waiting=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued").length;const known=id2=>{const e3=entries.get(id2);if(!e3)throw refused("not-found",`command ${id2} is not known to this agent`);return e3};function end2(e3,state){e3.state=state;observer?.state(e3.id,state);ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}function taken(e3){e3.state={kind:"taken"};observer?.state(e3.id,e3.state)}const admission=(id2,job)=>"turn"in job?{kind:"turn",id:id2,text:job.turn.text,images:job.turn.images.length,published:dispatcher?.publishesTurns===true}:{kind:"command",id:id2,target:job.command.target,name:job.command.name,args:job.command.args};function seed(f2){const e3={id:f2.id,job:{command:{target:f2.target,name:f2.name,args:f2.args??""}},state:{kind:"queued"}};entries.set(e3.id,e3);observer?.admit(admission(e3.id,e3.job));const refuse4=message2=>end2(e3,{kind:"refused",code:"failed-precondition",message:cut2(message2,AGENT_COMMAND_MESSAGE_MAX)});if(!dispatcher||dispatcher.targets.size===0)return refuse4("this agent's connector runs no commands or skills");if(!dispatcher.targets.has(f2.target))return refuse4(`this agent's connector runs no ${f2.target}s`);if(dispatcher.unsupported?.()===void 0)return;held2=e3;const deadline=Date.now()+FIRST_COMMAND_READY_MS;const timer2=setInterval(()=>{const cause=e3.state.kind==="queued"?dispatcher.unsupported?.():void 0;if(cause!==void 0&&Date.now()<deadline)return;clearInterval(timer2);held2=void 0;if(e3.state.kind!=="queued")return;if(cause===void 0)onQueued();else refuse4(`the harness ran no commands within ${FIRST_COMMAND_READY_MS/1e3} s: ${cause}`)},FIRST_COMMAND_POLL_MS);timer2.unref?.()}if(first)seed(first);function enqueue(job){if(closed6)throw refused("unavailable","this agent is stopping");if(waiting()>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands and turns are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));if(observer&&!observer.admit(admission(id2,job)))throw refused("resource-exhausted","this agent's read-back store has used its sequence numbers; it takes nothing more until it restarts");entries.set(id2,{id:id2,job,state:{kind:"queued"}});onQueued();return{id:id2}}function run(ctx){notSelf(ctx,"runs a command on itself");const input=ctx.request.args;if(!dispatcher||dispatcher.targets.size===0)throw refused("unimplemented","this agent's connector runs no commands or skills");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector runs no commands now: ${cause}`);if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);return enqueue({command:{target:input.target,name:input.name,args:input.args??""}})}function turn(ctx){notSelf(ctx,"gives itself a turn");const input=ctx.request.args;if(!dispatcher?.turn)throw refused("unimplemented","this agent's connector takes no turn from its owner");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector takes no turn now: ${cause}`);const images=input.images??[];if(images.length&&!dispatcher.images)throw refused("unimplemented","this agent's harness takes no images");if(input.text===""&&!images.length)throw refused("bad-request","a turn needs text or an image");return enqueue({turn:{text:input.text,images}})}async function interrupt(ctx){notSelf(ctx,"interrupts its own turn");if(!dispatcher?.interrupt)throw refused("unimplemented","this agent's connector cannot interrupt a turn");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector cannot interrupt a turn now: ${cause}`);if(closed6)throw refused("unavailable","this agent is stopping");try{return{state:await dispatcher.interrupt()}}catch(e3){throw new EpEnvelopeError("internal",`the harness failed, so the turn may have been interrupted: ${String(e3?.message??e3)}`,void 0,"unknown")}}const take=()=>runEntry(queued()[0],dispatcher,end2,taken,(e3,output)=>observer?.output?.(e3.id,output));let closing;const closed$=new Promise(resolve3=>{closing=resolve3});const gate=takeGate(()=>queued().length,take,closed$);function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end2(e3,{kind:"cancelled"});else if(e3.state.kind!=="cancelled")throw new EpEnvelopeError("conflict",`command ${id2} is ${e3.state.kind}, so it can no longer be cancelled`,[{kind:AGENT_COMMAND_STATE_DETAIL,state:e3.state}],"not-executed");return{state:e3.state}}return{handlers:[{command:"commands",contract:AGENT_CONTRACTS.commands,handler:()=>listCommands(dispatcher)},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx)},{command:"command-cancel",contract:AGENT_CONTRACTS["command-cancel"],handler:ctx=>cancel(ctx.request.args)},{command:"command-state",contract:AGENT_CONTRACTS["command-state"],handler:ctx=>({state:known(ctx.request.args.id).state})},{command:"turn",contract:AGENT_CONTRACTS.turn,handler:ctx=>turn(ctx)},{command:"interrupt",contract:AGENT_CONTRACTS.interrupt,handler:ctx=>interrupt(ctx)},{command:"usage",contract:AGENT_CONTRACTS.usage,handler:()=>readUsage(dispatcher)}],get queued(){return queued().length},dispatchNext:gate,close(){closed6=true;for(const e3 of entries.values())if(e3.state.kind==="queued")end2(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3)} started`});closing()}}}var refused2=(code,message2)=>new EpEnvelopeError(code,message2,void 0,"not-executed");var MODEL_LIST_MS=8500;function matchingChoices(choices,query){const needle=query.toLowerCase();const matches=choices.filter(({model})=>model.toLowerCase().includes(needle));matches.sort((a3,b3)=>a3.model===b3.model?0:a3.model===query?-1:b3.model===query?1:a3.model<b3.model?-1:1);return{items:matches.slice(0,AGENT_MODEL_CHOICES_MAX).map(({model,variants})=>({model,variants:[...variants].sort()})),more:matches.length>AGENT_MODEL_CHOICES_MAX}}function createModelLane(dispatcher,o3){let closed6=false;let tail=Promise.resolve();async function switchTo({model,variant}){if(!dispatcher?.setModel)throw refused2("unimplemented","this agent's harness cannot switch the model it runs");if(o3.policed!==void 0)throw refused2("failed-precondition",`this agent launched under modelPolicy.${o3.policed} in the Cotal configuration, which judges its model at launch only. Start a new agent on a model the policy allows.`);const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused2("unimplemented",`this agent's connector cannot switch its model now: ${cause}`);if(closed6)throw refused2("unavailable","this agent is stopping");let runs;try{runs=await dispatcher.setModel(model,variant)}catch(e3){const message2=String(e3?.message??e3);if(e3 instanceof CommandRefused)throw refused2(e3.code,`the harness refused the switch: ${message2}`);throw new EpEnvelopeError("internal",`the harness failed, so the model it runs is not known: ${message2}`,void 0,"unknown")}const switched={model:runs.model,...runs.variant!==void 0?{variant:runs.variant}:{}};try{await o3.show(switched)}catch(e3){o3.warn(`set-model: presence does not show ${switched.model} yet: ${e3.message}`)}return switched}async function list2(ctx){notSelf(ctx,"lists its own model choices");if(!o3.authed||!dispatcher?.setModel||!dispatcher.listModelChoices||dispatcher.unsupported?.()!==void 0)throw refused2("unimplemented","this agent does not serve live model choices");if(o3.policed!==void 0)throw refused2("failed-precondition","this agent's launch policy locks its model");if(closed6)throw refused2("unavailable","this agent is stopping");const{query}=ctx.request.args;const remaining=(ctx.request.deadlineMs??3e4)-(performance.now()-ctx.receivedAtMonotonicMs);if(remaining<=0)throw refused2("unavailable","the model choices request expired");const signal=AbortSignal.any([ctx.signal,AbortSignal.timeout(Math.ceil(Math.min(MODEL_LIST_MS,remaining)))]);let matches;try{matches=matchingChoices(await dispatcher.listModelChoices(signal),query?.trim()??"")}catch{throw refused2("unavailable","the harness could not list this session's model choices")}if(closed6||signal.aborted)throw refused2("unavailable","the model choices read ended before it could reply");const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};const answer2={runtime,...matches};if(matches.items.some(({variants})=>variants.length>AGENT_MODEL_CHOICE_VARIANTS_MAX))throw refused2("resource-exhausted","a model has too many variants to list");if(!ctx.replyFits(answer2,AGENT_MODEL_CHOICES_REPLY_MAX_BYTES))throw refused2("resource-exhausted","the model choices reply is too large; refine the search");return answer2}return{handler:{command:"set-model",contract:AGENT_CONTRACTS["set-model"],handler:ctx=>{notSelf(ctx,"switches its own model");const args=ctx.request.args;if(o3.exclusive)return o3.exclusive(()=>switchTo(args));const run=tail.then(()=>switchTo(args));tail=run.catch(()=>{});return run}},choices:{command:"model-choices",contract:AGENT_CONTRACTS["model-choices"],handler:list2},close(){closed6=true}}}var refused3=(code,message2,reason)=>new EpEnvelopeError(code,message2,reason?[{kind:AGENT_NAME_REFUSED_DETAIL,reason}]:void 0,"not-executed");function createNameLane(ep,warn,onNamed){let closed6=false;let tail=Promise.resolve();async function takenBy(name2){let roster;try{roster=await ep.readPresence()}catch(e3){throw refused3("unavailable",`the agent could not read who is present, so it cannot tell whether the name is free: ${e3.message}`)}const want=name2.toLowerCase();return roster.find(p2=>p2.status!=="offline"&&p2.card.id!==ep.card.id&&p2.card.name.toLowerCase()===want)?.card.id}async function setName(name2){try{assertValidName(name2)}catch(e3){throw refused3("bad-request",e3.message,"name-invalid")}if(closed6)throw refused3("unavailable","this agent is stopping");if(ep.card.name!==name2){const holder=await takenBy(name2);if(holder!==void 0)throw refused3("already-exists",`the live agent ${holder} is named ${JSON.stringify(name2)}`,"name-taken")}onNamed?.();if(ep.card.name===name2&&ep.card.meta?.[AGENT_LABEL_META_KEY]===void 0)return{name:name2};try{await ep.setCardName(name2,{[AGENT_LABEL_META_KEY]:void 0})}catch(e3){warn(`set-name: presence did not take "${name2}" yet: ${e3.message}`)}return{name:ep.card.name}}async function setLabel(label){try{assertValidLabel(label)}catch(e3){throw refused3("bad-request",e3.message)}if(closed6)throw refused3("unavailable","this agent is stopping");onNamed?.();try{await ep.setCardMeta({[AGENT_LABEL_META_KEY]:label})}catch(e3){warn(`set-label: presence did not take "${label}" yet: ${e3.message}`)}return{label}}const inTurn=run=>{const next=tail.then(run);tail=next.catch(()=>{});return next};return{handlers:[{command:"set-name",contract:AGENT_CONTRACTS["set-name"],handler:ctx=>inTurn(()=>setName(ctx.request.args.name))},{command:"set-label",contract:AGENT_CONTRACTS["set-label"],handler:ctx=>inTurn(()=>setLabel(ctx.request.args.label))}],close(){closed6=true}}}import{randomBytes as randomBytes5}from"node:crypto";var PROMPT_DESK_MIN_MAX_PAYLOAD=524288;var PROMPT_SUMMARY_MAX_BYTES=4096;var PROMPT_ANSWER_REPLY_MS=1e4;var PROMPT_OPEN_MS=Object.freeze({min:1e3,max:7*24*60*60*1e3});var PROMPT_SETTLE_MS=Object.freeze({min:1e3,max:24*60*60*1e3});var PromptRefused=class extends Error{reason;constructor(reason,message2){super(message2);this.reason=reason;this.name="PromptRefused"}};var NONE={tie:"none"};function stepPrompt(state,event,at2){const close=(outcome,attempted)=>({kind:"move",next:{kind:"closed",at:at2,outcome},end:{attempted}});if(state.kind==="open"){switch(event.kind){case"accept":return{kind:"move",next:{kind:"sent",answer:event.answer,delivery:"unconfirmed"},deliver:true};case"settle":{const e3=event.evidence;if(e3.kind==="local")return close({kind:"local",seen:e3.seen},false);if(e3.kind==="observed")return close(e3.seen.tie==="prompt"?{kind:"local",seen:e3.seen}:{kind:"withdrawn",seen:e3.seen},false);if(e3.kind==="withdrawn")return close({kind:"withdrawn",seen:NONE},false);return{kind:"stay",warn:"a confirmation came for a prompt with no accepted answer"}}case"expiry":return close({kind:"expired"},false);case"close":return close({kind:"withdrawn",seen:NONE},false);case"delivery":return{kind:"stay",warn:"a delivery result came for a prompt with no deliver call"};case"settle-time":return{kind:"cannot-happen",why:"the settle time starts at the accepted answer"}}}if(state.kind==="sent"){const answer2=state.answer;switch(event.kind){case"accept":return{kind:"never-reached",why:"an answer to a sent prompt meets check 3 or 4"};case"delivery":if(state.delivery==="delivered")return{kind:"cannot-happen",why:"deliver has one result"};if(event.result==="delivered")return{kind:"move",next:{kind:"sent",answer:answer2,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer:answer2},true);if(event.result==="gone")return close({kind:"undelivered",answer:answer2},true);return{kind:"stay",warn:"deliver failed, which proves nothing about the hand-over"};case"settle":{const e3=event.evidence;if(e3.kind==="confirmed")return close({kind:"answered",answer:answer2},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer2},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer:answer2,seen:e3.seen},true);return close({kind:"unconfirmed",answer:answer2,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer:answer2,seen:NONE},true)}}if(event.kind==="accept")return{kind:"never-reached",why:"an answer to a closed prompt meets check 3 or 4"};if(event.kind==="settle")return{kind:"stay",warn:"a report came for a closed prompt",report:true};return{kind:"stay"}}var iso=ms=>new Date(ms).toISOString();function describe(v3){try{if(v3 instanceof Error)return v3.message;const json2=JSON.stringify(v3);if(json2!==void 0)return json2.length>200?`${json2.slice(0,200)}...`:json2}catch{}try{return typeof v3==="bigint"?`${v3}n`:String(v3)}catch{return`a ${typeof v3} with no text form`}}function ignoreRejection(v3){try{const then=v3?.then;if(typeof then!=="function")return false;then.call(v3,void 0,()=>{})}catch{}return true}function deliveryKind(d2){try{return d2?.kind}catch{return void 0}}var B322="abcdefghijklmnopqrstuvwxyz234567";var EFFECTS=new Set(["proceed","refuse","cancel"]);function deepFreeze7(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze7(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused4(code,message2,details){return new EpEnvelopeError(code,message2,details,"not-executed")}function parseSeen(s3){const o3=s3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if(o3.tie==="none"&&keys===1)return{tie:"none"};if((o3.tie==="prompt"||o3.tie==="subject")&&keys===2&&EFFECTS.has(o3.effect))return{tie:o3.tie,effect:o3.effect}}throw new TypeError(`settle: ${describe(s3)} is not a sighting ({ tie: "prompt" | "subject", effect } or { tie: "none" })`)}function parseEvidence(e3){const o3=e3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if((o3.kind==="confirmed"||o3.kind==="withdrawn")&&keys===1)return{kind:o3.kind};if((o3.kind==="local"||o3.kind==="observed")&&keys===2)return{kind:o3.kind,seen:parseSeen(o3.seen)}}throw new TypeError(`settle: ${describe(e3)} is not an Evidence`)}var LONGEST_BY=Object.freeze({id:`${"w".repeat(64)}.${"w".repeat(64)}`,uid:"w".repeat(32),authority:"owner"});var ANY_AT="2000-01-01T00:00:00.000Z";var LONGEST_SEEN=Object.freeze({tie:"subject",effect:"proceed"});function largestSummaryBytes(base,options){let max=0;const measure=state=>{max=Math.max(max,Buffer.byteLength(JSON.stringify({...base,state})))};const closed6=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed6({kind:"expired"}));measure(closed6({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed6({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer2={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer:answer2,delivery:"unconfirmed"});measure({kind:"sent",answer:answer2,delivery:"delivered"});measure(closed6({kind:"answered",answer:answer2}));measure(closed6({kind:"unconfirmed",answer:answer2,seen:LONGEST_SEEN}));measure(closed6({kind:"undelivered",answer:answer2}));measure(closed6({kind:"local",seen:LONGEST_SEEN,late:answer2}))}return max}var Desk=class{ep;held=new Map;closedOrder=[];live=0;seq=0;stepping=false;later=[];presenceOwed=false;serving=false;closed=false;warn;constructor(ep,warn){this.ep=ep;this.warn=msg=>{try{warn(msg)}catch{}}}get waiting(){return this.live}handlers(){return[{command:"prompts",contract:AGENT_CONTRACTS.prompts,handler:ctx=>this.list(ctx)},{command:"prompt",contract:AGENT_CONTRACTS.prompt,handler:ctx=>this.read(ctx)},{command:"prompt-answer",contract:AGENT_CONTRACTS["prompt-answer"],handler:ctx=>this.answer(ctx)}]}served(ready){this.seq=this.ep.nextPromptsSeq();this.serving=true;ready.then(()=>{this.presenceOwed=true;this.flushPresence()},()=>{})}close(){if(this.closed)return;this.closed=true;this.defer(()=>{for(const h3 of[...this.held.values()])if(h3.state.kind!=="closed")this.apply(h3,{kind:"close"})})}open(spec,hooks){if(this.closed)throw new PromptRefused("closed","the prompt desk has closed; the harness answers this dialog");const invalid2=why=>new PromptRefused("invalid",why);if(!spec||typeof spec!=="object")throw invalid2("a prompt spec is an object");if(!hooks||typeof hooks.deliver!=="function"||typeof hooks.end!=="function"||hooks.check!==void 0&&typeof hooks.check!=="function")throw invalid2("hooks need deliver and end, and check when given, as functions");for(const[name2,value,range]of[["openMs",spec.openMs,PROMPT_OPEN_MS],["settleMs",spec.settleMs,PROMPT_SETTLE_MS]])if(!Number.isSafeInteger(value)||value<range.min||value>range.max)throw invalid2(`${name2} must be an integer from ${range.min} to ${range.max} ms, not ${String(value)}`);let canonical;try{canonical=canonicalJson(spec.content)}catch(e3){throw invalid2(`the content is not interchangeable JSON: ${describe(e3)}`)}const contentBytes=Buffer.byteLength(canonical);if(contentBytes>AGENT_PROMPT_CONTENT_MAX_BYTES)throw new PromptRefused("too-large",`the canonical content is ${contentBytes} bytes, over ${AGENT_PROMPT_CONTENT_MAX_BYTES}`);const content2=deepFreeze7(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content2);const now=Date.now();const openedAt=iso(now),expiresAtMs=now+spec.openMs,expiresAt=iso(expiresAtMs);const validate2=AGENT_CONTRACTS.prompt.output.validate;if(!validate2({prompt:{id:id2,digest,openedAt,expiresAt,state:{kind:"open"},content:content2}})){const first=validate2.errors?.[0];throw invalid2(`the content does not match the prompt schema: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const options=new Map;for(const o3 of content2.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content2.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content2.form!==void 0&&!content2.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content2.subject?.type==="tool"?content2.subject.input:void 0;if(input?.kind==="omitted"&&content2.options.some(o3=>o3.effect==="proceed"))throw invalid2("a tool input that is omitted can be refused remotely, never approved: no option may proceed");let form;if(content2.form!==void 0){const schema=content2.form.schema;for(const name2 of schema.required??[])if(!Object.hasOwn(schema.properties,name2))throw invalid2(`form.schema.required names "${name2}", which is not a property`);try{form=compileContractSchema({root:{...schema,additionalProperties:false}})}catch(e3){throw invalid2(`form.schema does not compile: ${describe(e3)}`)}}const base={id:id2,digest,openedAt,expiresAt,kind:content2.kind,title:content2.title,contentBytes,...content2.source!==void 0?{source:content2.source}:{}};const largest=largestSummaryBytes(base,content2.options);if(largest>PROMPT_SUMMARY_MAX_BYTES)throw new PromptRefused("too-large",`the summary encodes to ${largest} bytes in its largest state, over ${PROMPT_SUMMARY_MAX_BYTES}`);if(this.live>=AGENT_PROMPT_LIST_MAX)throw new PromptRefused("full",`${AGENT_PROMPT_LIST_MAX} prompts are open or sent`);const h3={id:id2,hooks,settleMs:spec.settleMs,expiresAtMs,base:deepFreeze7(base),live:{content:content2,options,...form?{form}:{}},state:deepFreeze7({kind:"open"}),reports:0,ended:false,waiters:new Set};this.held.set(id2,h3);this.live++;this.bump();h3.expiry=timer(Math.max(0,expiresAtMs-Date.now()),()=>this.expire(h3));if(!this.stepping)this.flushPresence();return Object.freeze({id:id2,settle:evidence=>{const e3=parseEvidence(evidence);this.defer(()=>this.apply(h3,{kind:"settle",evidence:e3}))}})}expire(h3){const left=h3.expiresAtMs-Date.now();if(left>0){h3.expiry=timer(left,()=>this.expire(h3));return}this.defer(()=>this.apply(h3,{kind:"expiry"}))}settleTime(h3){const left=h3.settleAtMs-Date.now();if(left>0){h3.settle=timer(left,()=>this.settleTime(h3));return}this.defer(()=>this.apply(h3,{kind:"settle-time"}))}run(fn2){if(this.stepping)throw new Error("prompt desk: a step started inside another step");this.stepping=true;try{return fn2()}finally{try{for(let next=this.later.shift();next;next=this.later.shift())next()}finally{this.stepping=false;this.flushPresence()}}}defer(fn2){if(this.stepping)this.later.push(fn2);else this.run(fn2)}apply(h3,event,why){const step=stepPrompt(h3.state,event,iso(Date.now()));if(step.kind==="cannot-happen"||step.kind==="never-reached"){this.warn(`prompt desk bug: event ${event.kind} met prompt ${h3.id} in state ${h3.state.kind}, a row that ${step.kind==="cannot-happen"?"cannot happen":"is never reached"}: ${step.why}`);return}if(step.kind==="stay"){if(step.report)this.warn(`prompt ${h3.id} is closed, so a "${event.evidence.kind}" report is ignored (${++h3.reports} so far)`);else if(step.warn)this.warn(`prompt ${h3.id}: ${step.warn}${why?`: ${why}`:""}`);if(event.kind==="delivery"&&event.result==="failed")this.answerWaiters(h3);return}h3.state=deepFreeze7(step.next);this.bump();if(h3.state.kind==="closed")this.retire(h3);if(!(h3.state.kind==="sent"&&h3.state.delivery==="unconfirmed"))this.answerWaiters(h3);if(step.end)this.end(h3,step.end.attempted)}answerWaiters(h3){for(const w2 of h3.waiters){clearTimeout(w2.timer);w2.resolve(h3.state)}h3.waiters.clear()}retire(h3){clearTimeout(h3.expiry);clearTimeout(h3.settle);h3.live=void 0;this.live--;this.closedOrder.push(h3.id);while(this.closedOrder.length>AGENT_PROMPT_LIST_MAX)this.held.delete(this.closedOrder.shift())}end(h3,attempted){if(h3.ended){this.warn(`prompt desk bug: prompt ${h3.id} ended twice`);return}h3.ended=true;const hooks=h3.hooks;h3.hooks=void 0;try{ignoreRejection(hooks.end({attempted}))}catch(e3){this.warn(`prompt ${h3.id}: the adapter's end threw: ${describe(e3)}`)}}bump(){this.seq=this.ep.nextPromptsSeq();this.presenceOwed=true}flushPresence(){if(!this.presenceOwed||this.closed||!this.serving)return;this.presenceOwed=false;this.ep.setPromptsPresence({open:this.live,seq:this.seq}).catch(e3=>{if(!this.closed)this.warn(`the prompts presence field was not written: ${describe(e3)}`)})}fit(ctx,data){if(ctx.replyFits(data,Number.MAX_SAFE_INTEGER))return data;const bytes=Buffer.byteLength(JSON.stringify({v:1,id:ctx.request.id,ok:true,data}));const limit=this.ep.maxPayload;throw refused4("resource-exhausted",`the reply is ${bytes} bytes, over this connection's max_payload of ${limit}`,[{kind:AGENT_PROMPT_SIZE_DETAIL,bytes,limit}])}summary(h3){return{...h3.base,state:h3.state}}list(ctx){const open7=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open7.push(this.summary(h3));const closed6=this.closedOrder.map(id2=>this.summary(this.held.get(id2)));const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};return this.fit(ctx,{runtime,seq:this.seq,open:open7,closed:closed6})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused4("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused4("failed-precondition",`prompt ${id2} is closed`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);const{digest,openedAt,expiresAt}=h3.base;return this.fit(ctx,{prompt:{id:id2,digest,openedAt,expiresAt,state:h3.state,content:h3.live.content}})}answer(ctx){const got=this.run(()=>this.decide(ctx));return got instanceof Promise?got.then(state=>({state})):{state:got}}decide(ctx){const a3=ctx.request.args;try{canonicalJson(a3)}catch(e3){throw refused4("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused4("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused4("not-found",`prompt ${a3.id} is not known to this runtime`);const fingerprint=answerFingerprint(a3,ctx.caller);if(h3.fingerprint===fingerprint)return h3.state;if(h3.state.kind!=="open"||h3.live===void 0)throw refused4("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused4("failed-precondition",`the digest is not prompt ${a3.id}'s`,[{kind:AGENT_PROMPT_DIGEST_DETAIL,digest:h3.base.digest}]);const option=h3.live.options.get(a3.option);if(option===void 0)throw refused4("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused4("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused4("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused4("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused4("bad-request",`option "${option.id}" takes no values`);if(a3.values!==void 0&&!h3.live.form(a3.values)){const first=h3.live.form.errors?.[0];throw refused4("bad-request",`the values do not match the form: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const by={id:`${ctx.caller.owner}.${ctx.caller.actor}`,uid:ctx.caller.uid,authority:ctx.authority};const verdict=deepFreeze7({option:option.id,...a3.note!==void 0?{note:a3.note}:{},...a3.values!==void 0?{values:structuredClone(a3.values)}:{},by});let refusal;try{refusal=h3.hooks.check?.(verdict)}catch(e3){this.warn(`prompt ${h3.id}: the adapter's check threw: ${describe(e3)}`);throw refused4("internal",`the agent could not check this answer: ${describe(e3)}`)}if(refusal!==void 0){if(typeof refusal!=="string"){this.warn(`prompt ${h3.id}: the adapter's check returned ${ignoreRejection(refusal)?"a promise, and check is synchronous":`${typeof refusal}, not a message or undefined`}`);throw refused4("internal","the agent could not check this answer")}throw refused4("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused4("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer2={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer:answer2},answer2.at);if(step.kind!=="move"||!step.deliver)throw refused4("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze7(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve3=>{const w2={resolve:resolve3,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve3(h3.state)}))};h3.waiters.add(w2)});this.deliver(h3,verdict);return wait}deliver(h3,verdict){let result;try{result=Promise.resolve(h3.hooks.deliver(verdict))}catch(e3){result=Promise.reject(e3)}const failed=why=>this.defer(()=>this.apply(h3,{kind:"delivery",result:"failed"},why));result.then(d2=>{const kind=deliveryKind(d2);if(kind==="confirmed"||kind==="delivered"||kind==="gone")this.defer(()=>this.apply(h3,{kind:"delivery",result:kind}));else failed(`deliver resolved with ${describe(d2)}, which is not a Delivery`)},e3=>failed(describe(e3))).catch(e3=>this.warn(`prompt desk bug: applying prompt ${h3.id}'s delivery result threw: ${describe(e3)}`))}};function answerFingerprint(a3,caller2){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller2.owner}.${caller2.actor}.${caller2.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}import{createHash as createHash9}from"node:crypto";var STEER_HANDOVER_MS=1e4;var STEER_MIN_BUDGET_MS=11e3;var STEER_KEY_TAIL_MS=6e4;var STEER_KEYS_MAX=256;var STEER_MESSAGE_MAX_BYTES=512;var STEER_STATE_DETAIL="ai.cotal.agent.steer-state";var STEER_KEY_CONFLICT_DETAIL="ai.cotal.agent.steer-key-conflict";var SteerRefused=class extends Error{name="SteerRefused"};var B323="abcdefghijklmnopqrstuvwxyz234567";var runKey=r2=>`${r2.threadId}\0${r2.runId}`;var sha=text5=>createHash9("sha256").update(text5,"utf8").digest("hex");function mintSteerId(){const bytes=new Uint8Array(26);crypto.getRandomValues(bytes);let id2="";for(const b3 of bytes)id2+=B323[b3&31];return id2}function steerMessage(message2){const enc10=new TextEncoder;if(enc10.encode(message2).byteLength<=STEER_MESSAGE_MAX_BYTES)return message2;let out="";for(const ch of message2){if(enc10.encode(out+ch+"\u2026").byteLength>STEER_MESSAGE_MAX_BYTES)break;out+=ch}return`${out}\u2026`}var refuse2=(code,message2,detail,outcome="not-executed")=>({ok:false,code,outcome,message:steerMessage(message2),...detail?{detail}:{}});var servesSteer=d2=>d2!==void 0&&typeof d2.steerTarget==="function"&&typeof d2.steer==="function"&&d2.unsupported?.()===void 0;var SteerLane=class{opts;now;mintId;keys=new Map;refusals=new Map;attachments=new Set;withHarness;constructor(opts={}){this.opts=opts;this.now=opts.now??(()=>performance.now());this.mintId=opts.mintId??mintSteerId}attach(dispatcher){const a3={dispatcher,open:true};this.attachments.add(a3);return{served:()=>a3.open&&servesSteer(dispatcher),steer:(req,budget3,signal)=>this.steer(a3,req,budget3,signal),detach:()=>{a3.open=false;this.attachments.delete(a3)}}}get held(){this.expire();return this.keys.size+this.refusals.size+this.laterReplies}laterReplies=0;get busy(){return this.withHarness!==void 0}steer(a3,req,budget3,signal){if(req.self)return Promise.resolve(refuse2("permission-denied","an agent never steers its own turn"));if(!isWellFormedUnicode(req.text))return Promise.resolve(refuse2("bad-request","the text is not well-formed Unicode"));this.expire();const deadlineAt=budget3.receivedAt+budget3.deadlineMs;const kept=this.refusals.get(req.envelopeId);if(kept)return Promise.resolve(kept.answer);const bound=this.keys.get(req.key);if(bound)return this.repeat(bound,req,deadlineAt);return Promise.resolve(this.admit(a3,req,budget3,deadlineAt,signal))}repeat(bound,req,deadlineAt){bound.heldUntil=Math.max(bound.heldUntil,deadlineAt);if(req.envelopeId===bound.firstEnvelope)return bound.first;const earlier=bound.replies.get(req.envelopeId);if(earlier)return Promise.resolve(earlier);let answer2;if(bound.digest!==sha(req.text)||bound.run!==runKey(req.run)){answer2=refuse2("bad-request","this key already names another steer; mint a new key for every steer",{kind:STEER_KEY_CONFLICT_DETAIL,heldId:bound.id,heldState:bound.state})}else{const detail=(state,code)=>({kind:STEER_STATE_DETAIL,id:bound.id,state,...code?{code}:{}});switch(bound.state){case"delivered":answer2={ok:true,id:bound.id,delivered:"running-turn"};break;case"refused":answer2=refuse2("failed-precondition","the harness refused this steer; nothing was delivered",detail("refused","failed-precondition"));break;case"unknown":answer2=refuse2("internal","this steer's outcome is not known; it may have been delivered",detail("unknown"));break;default:answer2=refuse2("unavailable","this steer is still with the harness; ask again with the same key once it settles",detail("handed-over"))}}if(this.held<STEER_KEYS_MAX){bound.replies.set(req.envelopeId,answer2);this.laterReplies++}return Promise.resolve(answer2)}admit(a3,req,budget3,deadlineAt,signal){const atCap=this.held>=STEER_KEYS_MAX;const preRefuse=(code,message2)=>{const answer2=refuse2(code,message2);if(!atCap)this.refusals.set(req.envelopeId,{answer:answer2,heldUntil:deadlineAt});return answer2};const d2=a3.dispatcher;if(!servesSteer(d2)||d2===void 0){const cause=d2?.unsupported?.();return preRefuse("unimplemented",cause===void 0?"this agent's connector cannot steer a turn":`this agent's connector cannot steer a turn now: ${cause}`)}if(!a3.open||signal?.aborted)return preRefuse("unavailable","this agent's endpoint is closing");if(atCap)return refuse2("resource-exhausted","this agent holds too many steer keys now; try again shortly",void 0,"unknown");let handle;try{handle=d2.steerTarget(req.run)}catch(e3){if(e3 instanceof SteerRefused)return preRefuse("failed-precondition",`that run is not the one running: ${e3.message}`);this.opts.warn?.(`steerTarget failed: ${String(e3?.message??e3)}`);return preRefuse("failed-precondition","the connector could not resolve that run")}if(!a3.open||signal?.aborted)return preRefuse("unavailable","this agent's endpoint is closing");if(this.withHarness)return preRefuse("unavailable","another steer is still with the harness; once it settles, send these words again under a new key");const remaining=budget3.deadlineMs-(this.now()-budget3.receivedAt);if(remaining<STEER_MIN_BUDGET_MS)return preRefuse("unavailable","too little of the request's time is left to hand the steer over");return this.handOver(req,deadlineAt,d2,handle)}handOver(req,deadlineAt,d2,handle){const id2=this.mintId();let resolve3;const first=new Promise(r2=>resolve3=r2);const bound={key:req.key,id:id2,digest:sha(req.text),run:runKey(req.run),state:"handed-over",firstEnvelope:req.envelopeId,first,replies:new Map,heldUntil:deadlineAt};this.keys.set(req.key,bound);this.withHarness=bound;const detail=(state,code)=>({kind:STEER_STATE_DETAIL,id:id2,state,...code?{code}:{}});let replied=false;const reply3=(state,answer2)=>{if(replied)return;replied=true;bound.state=state;clearTimeout(timer2);resolve3(answer2)};const native=(state,answer2)=>{bound.nativeAt=this.now();if(this.withHarness===bound)this.withHarness=void 0;if(replied){if(bound.state!==state)this.opts.warn?.(`steer ${id2}: the harness answered ${state} after the lane replied ${bound.state}; the key keeps ${bound.state}`);return}reply3(state,answer2)};const timer2=setTimeout(()=>reply3("unknown",refuse2("internal","the harness did not answer in time; the steer may have been delivered",detail("unknown"),"unknown")),STEER_HANDOVER_MS);timer2.unref?.();let call;try{call=d2.steer(handle,{id:id2,text:req.text})}catch(e3){call=Promise.reject(e3)}call.then(()=>native("delivered",{ok:true,id:id2,delivered:"running-turn"}),e3=>{if(e3 instanceof SteerRefused)native("refused",refuse2("failed-precondition","the harness refused this steer; nothing was delivered",detail("refused","failed-precondition")));else{this.opts.warn?.(`steer ${id2}: the harness failed: ${String(e3?.message??e3)}`);native("unknown",refuse2("internal","the harness failed; the steer may have been delivered",detail("unknown"),"unknown"))}});return first}expire(){const now=this.now();for(const[k2,b3]of this.keys){if(b3.nativeAt===void 0)continue;if(Math.max(b3.heldUntil,b3.nativeAt)+STEER_KEY_TAIL_MS>now)continue;this.laterReplies-=b3.replies.size;this.keys.delete(k2)}for(const[env,r2]of this.refusals)if(r2.heldUntil+STEER_KEY_TAIL_MS<=now)this.refusals.delete(env)}};var lanes=new Map;function steerLaneFor(runtimeId,warn){let lane=lanes.get(runtimeId);if(!lane){lane=new SteerLane({warn});lanes.set(runtimeId,lane)}return lane}function steerHandler(steer){return{command:"steer",contract:AGENT_CONTRACTS.steer,handler:async ctx=>{const args=ctx.request.args;const self3=ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor;const answer2=await steer.steer({text:args.text,run:args.run,key:args.key,envelopeId:ctx.request.id,self:self3},{deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs},ctx.signal);if(answer2.ok)return{id:answer2.id,delivered:answer2.delivered};throw new EpEnvelopeError(answer2.code,answer2.message,answer2.detail?[answer2.detail]:void 0,answer2.outcome)}}}var OPTION_WRITE_MS=1e4;var OPTION_READ_MS=5e3;var OPTION_REPLY_RESERVE_MS=1e3;var OPTION_WRITE_MIN_BUDGET_MS=OPTION_WRITE_MS+OPTION_REPLY_RESERVE_MS;var OPTION_UNSETTLED_DETAIL="ai.cotal.agent.option-unsettled";var OPTIONS_MAX=16;var CHOICES_MAX=16;var OPTION_RECORDS_MAX=16;var OptionRefused=class extends Error{code;name="OptionRefused";constructor(message2,code="failed-precondition"){super(message2);this.code=code}};function optionFlags(d2){const now=d2!==void 0&&d2.unsupported?.()===void 0;const options=now&&typeof d2.options==="function";const wantsWrite=d2!==void 0&&typeof d2.setOption==="function";const setOption=options&&wantsWrite&&typeof d2.watchOptions==="function";const fault=wantsWrite&&(typeof d2.options!=="function"||typeof d2.watchOptions!=="function")?"the connector offers setOption without options and watchOptions, so set-option is not served":void 0;return{options,setOption,...fault?{fault}:{}}}var ID2=/^[a-z0-9-]{1,64}$/;var text4=n2=>new RegExp(`^[^\\p{Cc}\\p{Cs}\\p{Co}\\p{Cn}\\u2028\\u2029]{1,${n2}}$`,"u");var NAME3=text4(80);var LONG=text4(200);var TOKEN2=/^[^\s\p{C}]{1,64}$/u;var REVERSE_DNS2=/^[a-z0-9-]{1,63}\.[a-z0-9.-]{1,63}$/;var SELECT_KEYS=new Set(["id","name","description","category","type","applies","value","pending","choices","locked"]);var BOOLEAN_KEYS=new Set(["id","name","description","category","type","applies","value","pending","locked"]);var CHOICE_KEYS=new Set(["value","name","description"]);function optionFault(o3){if(typeof o3!=="object"||o3===null||Array.isArray(o3))return"an option is not an object";const r2=o3;const at2=typeof r2.id==="string"?`option ${JSON.stringify(r2.id)}`:"an option";if(typeof r2.id!=="string"||!ID2.test(r2.id))return`${at2}: id does not match ${ID2.source}`;const keys=r2.type==="select"?SELECT_KEYS:r2.type==="boolean"?BOOLEAN_KEYS:void 0;if(!keys)return`${at2}: type is neither select nor boolean`;const extra=Object.keys(r2).find(k2=>!keys.has(k2));if(extra!==void 0)return`${at2}: ${extra==="unsettled"?"unsettled is the lane's to write":`unknown field ${extra}`}`;if(typeof r2.name!=="string"||!NAME3.test(r2.name))return`${at2}: name is not one line of 1 to 80 code points`;for(const f2 of["description","locked"])if(r2[f2]!==void 0&&(typeof r2[f2]!=="string"||!LONG.test(r2[f2])))return`${at2}: ${f2} is not one line of 1 to 200 code points`;if(r2.category!==void 0&&(typeof r2.category!=="string"||r2.category!=="mode"&&!(r2.category.length<=64&&REVERSE_DNS2.test(r2.category))))return`${at2}: category is neither mode nor a name in the Cotal namespace grammar`;if(r2.applies!=="now"&&r2.applies!=="next-turn")return`${at2}: applies is neither now nor next-turn`;if(r2.applies==="now"&&r2.pending!==void 0)return`${at2}: pending with applies now`;const valueOk=v3=>r2.type==="select"?typeof v3==="string"&&TOKEN2.test(v3):typeof v3==="boolean";if(!valueOk(r2.value))return`${at2}: value is not a ${r2.type==="select"?"token":"boolean"}`;if(r2.pending!==void 0&&!valueOk(r2.pending))return`${at2}: pending is not a ${r2.type==="select"?"token":"boolean"}`;if(r2.type==="select"){if(!Array.isArray(r2.choices)||r2.choices.length<1||r2.choices.length>CHOICES_MAX)return`${at2}: choices is not 1 to ${CHOICES_MAX} entries`;const seen=new Set;for(const c3 of r2.choices){if(typeof c3!=="object"||c3===null||Array.isArray(c3))return`${at2}: a choice is not an object`;const cr2=c3;const cx=Object.keys(cr2).find(k2=>!CHOICE_KEYS.has(k2));if(cx!==void 0)return`${at2}: a choice has unknown field ${cx}`;if(typeof cr2.value!=="string"||!TOKEN2.test(cr2.value))return`${at2}: a choice value is not a token`;if(typeof cr2.name!=="string"||!NAME3.test(cr2.name))return`${at2}: choice ${JSON.stringify(cr2.value)} name is not one line of 1 to 80 code points`;if(cr2.description!==void 0&&(typeof cr2.description!=="string"||!LONG.test(cr2.description)))return`${at2}: choice ${JSON.stringify(cr2.value)} description is not one line of 1 to 200 code points`;if(seen.has(cr2.value))return`${at2}: choice value ${JSON.stringify(cr2.value)} repeats`;seen.add(cr2.value)}}return void 0}function listFault(list2){if(!Array.isArray(list2))return"the list is not an array";if(list2.length>OPTIONS_MAX)return`the list has ${list2.length} options, over ${OPTIONS_MAX}`;const ids=new Set;for(const o3 of list2){const f2=optionFault(o3);if(f2)return f2;const id2=o3.id;if(ids.has(id2))return`option id ${JSON.stringify(id2)} repeats`;ids.add(id2)}return void 0}var fail3=(code,message2,outcome="not-executed",detail)=>({ok:false,code,outcome,message:message2,...detail?{detail}:{}});var OptionLane=class{opts;now;seqValue=0;records=new Map;fifo=[];busy=false;attached=0;watched;watching=false;runtime;dispatcher;seqListeners=new Set;constructor(opts){this.opts=opts;this.now=opts.now??(()=>performance.now());this.runtime=opts.runtime}bindRuntime(runtime){this.runtime??={id:runtime.id,startedAt:runtime.startedAt}}get seq(){return this.seqValue}get open(){return this.attached>0}flags(){const{options,setOption}=optionFlags(this.dispatcher);return{options,setOption}}attach(dispatcher,onSeq){this.attached++;this.dispatcher=dispatcher;if(onSeq)this.seqListeners.add(onSeq);const d2=this.dispatcher;if(!this.watching||this.watched!==d2){this.watching=true;this.watched=d2;const f2=optionFlags(d2);if(f2.fault)this.opts.warn?.(f2.fault);d2?.watchOptions?.(()=>{if(this.watched===d2)this.bump()})}this.bump();let done=false;return()=>{if(done)return;done=true;this.attached--;if(onSeq)this.seqListeners.delete(onSeq);if(this.attached===0)for(const j2 of this.fifo.splice(0)){clearTimeout(j2.timer);j2.refuse()}}}bump(){this.seqValue++;this.opts.onSeq?.(this.seqValue);for(const f2 of this.seqListeners)f2(this.seqValue)}remaining(b3){return b3.deadlineMs-(this.now()-b3.receivedAt)}enqueue(job,need){job.timer=setTimeout(()=>{const i2=this.fifo.indexOf(job);if(i2<0)return;this.fifo.splice(i2,1);job.refuse()},Math.max(0,this.remaining(job.budget)-need));job.timer.unref?.();this.fifo.push(job);this.next()}next(){while(!this.busy&&this.fifo.length>0){const job=this.fifo.shift();clearTimeout(job.timer);const need=job.kind==="write"?OPTION_WRITE_MIN_BUDGET_MS:job.kind==="read"?OPTION_REPLY_RESERVE_MS:0;if(job.kind!=="model"&&this.remaining(job.budget)<need){job.refuse();continue}this.busy=true;let released=false;job.start(()=>{if(released)return;released=true;this.busy=false;this.next()})}}runExclusive(fn2){return new Promise((resolve3,reject)=>{this.fifo.push({kind:"model",budget:{deadlineMs:Number.MAX_SAFE_INTEGER,receivedAt:this.now()},start:release=>{const bound=setTimeout(()=>{this.opts.warn?.(`set-model: the harness did not answer within ${OPTION_WRITE_MS} ms; the lane goes on`);release()},OPTION_WRITE_MS);bound.unref?.();let run;try{run=fn2()}catch(e3){run=Promise.reject(e3)}run.then(resolve3,reject).finally(()=>{clearTimeout(bound);release()})},refuse:()=>reject(new EpEnvelopeError("unavailable","this agent is stopping",void 0,"not-executed"))});this.next()})}overlayState(){const unsettled=new Map;for(const r2 of this.records.values())if(r2.phase==="unsettled")unsettled.set(r2.id,r2.value);return unsettled}async snapshot(d2,bound){for(let attempt=0;;attempt++){const before=this.seqValue;const read=await withBound(d2.options(),Math.max(1,bound()));if(this.seqValue===before||attempt===2){return{read,seq:this.seqValue,unsettled:this.overlayState()}}}}overlay(read,s3){const listed=new Set;const options=read.supported?read.options.map(o3=>{const u2=s3.unsettled.get(o3.id);if(u2===void 0||typeof u2!==typeof o3.value)return o3;listed.add(o3.id);return{...o3,unsettled:u2}}):[];const unlisted=[...s3.unsettled].filter(([id2])=>!listed.has(id2)).map(([id2,value])=>({id:id2,value}));const base={runtime:this.runtime??{id:"unbound",startedAt:0},seq:s3.seq,...unlisted.length?{unlisted}:{}};return read.supported?{supported:true,...base,options}:{supported:false,...base}}readFault(read){if(typeof read!=="object"||read===null||Array.isArray(read))return"the read is not an object";const r2=read;if(r2.supported!==true&&r2.supported!==false)return"the read is neither supported nor unsupported";const extra=Object.keys(r2).find(k2=>k2!=="supported"&&!(k2==="options"&&r2.supported===true));if(extra!==void 0)return`the read carries ${extra==="unlisted"?"unlisted, which is the lane's to write":`unknown field ${extra}`}`;if(r2.supported)return listFault(r2.options);return void 0}async readOnce(bound){const d2=this.dispatcher;if(bound<=0)return fail3("unavailable","too little of the request's time is left to read the settings");const started=this.now();let s3;try{s3=await this.snapshot(d2,()=>bound-(this.now()-started))}catch(e3){return fail3("unavailable",`the harness did not answer the read: ${String(e3?.message??e3)}`)}const f2=this.readFault(s3.read);if(f2)return this.fault(f2);return{ok:true,data:this.overlay(s3.read,s3)}}fault(why){this.opts.warn?.(`options: the connector's read was refused: ${why}`);return fail3("internal",`the connector's read broke the settings contract: ${why}`)}refusalBefore(self3,what2){if(self3)return fail3("permission-denied",`an agent never ${what2} its own settings`);return this.refusalNow()}refusalNow(signal){const d2=this.dispatcher;const cause=d2?.unsupported?.();if(cause!==void 0)return fail3("unimplemented",`this agent's connector cannot read or write its settings now: ${cause}`);if(d2===void 0||typeof d2.options!=="function")return fail3("unimplemented","this agent's connector does not serve settings");if(this.attached===0||signal?.aborted)return fail3("unavailable","this agent is stopping");return void 0}options(budget3,self3,signal){const early=this.refusalBefore(self3,"reads")??(signal?.aborted?fail3("unavailable","this agent is stopping"):void 0);if(early)return Promise.resolve(early);if(this.remaining(budget3)-OPTION_REPLY_RESERVE_MS<=0)return Promise.resolve(fail3("unavailable","too little of the request's time is left to read the settings"));return new Promise(resolve3=>{this.enqueue({kind:"read",budget:budget3,start:release=>{const now=this.refusalNow(signal);if(now){release();resolve3(now);return}const bound=Math.min(OPTION_READ_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS);void this.readOnce(bound).then(a3=>{release();resolve3(a3)})},refuse:()=>resolve3(fail3("unavailable","the settings were not read in time"))},OPTION_REPLY_RESERVE_MS)})}setOption(id2,value,budget3,self3,signal){const early=this.refusalBefore(self3,"writes")??(signal?.aborted?fail3("unavailable","this agent is stopping"):void 0);if(early)return Promise.resolve(early);const d2=this.dispatcher;if(!optionFlags(d2).setOption)return Promise.resolve(fail3("unimplemented","this agent's connector reads its settings but does not write them"));const held2=this.records.get(id2);if(held2)return Promise.resolve(fail3("failed-precondition","an earlier write to this option is not settled yet","not-executed",{kind:OPTION_UNSETTLED_DETAIL,id:id2,value:held2.value}));if(this.records.size>=OPTION_RECORDS_MAX)return Promise.resolve(fail3("resource-exhausted",`this agent holds ${OPTION_RECORDS_MAX} writes not yet settled`));if(this.remaining(budget3)<OPTION_WRITE_MIN_BUDGET_MS)return Promise.resolve(fail3("unavailable","too little of the request's time is left to write the setting"));const record3={id:id2,value,phase:"reserved"};this.records.set(id2,record3);return new Promise(resolve3=>{const drop=()=>{if(this.records.get(id2)===record3){this.records.delete(id2)}};this.enqueue({kind:"write",budget:budget3,start:release=>this.take(record3,budget3,release,resolve3,signal),refuse:()=>{drop();resolve3(fail3("unavailable","the write did not get its turn in time"))}},OPTION_WRITE_MIN_BUDGET_MS)})}take(record3,budget3,release,resolve3,signal){const now=this.refusalNow(signal)??(optionFlags(this.dispatcher).setOption?void 0:fail3("unimplemented","this agent's connector does not write its settings now"));if(now){if(this.records.get(record3.id)===record3)this.records.delete(record3.id);release();resolve3(now);return}const d2=this.dispatcher;record3.phase="active";let replied=false;const end2=()=>{if(this.records.get(record3.id)===record3){this.records.delete(record3.id);this.bump()}};const leaveUnknown=why=>{if(replied)return;replied=true;if(record3.phase==="active"){record3.phase="unsettled";this.bump()}release();resolve3(fail3("internal",`${why}; the setting may change later`,"unknown"))};const timer2=setTimeout(()=>leaveUnknown("the harness did not confirm the write in time"),Math.min(OPTION_WRITE_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS));timer2.unref?.();let call;try{call=d2.setOption(record3.id,record3.value)}catch(e3){call=Promise.reject(e3)}call.then(async()=>{clearTimeout(timer2);if(replied){this.opts.warn?.(`set-option ${record3.id}: a late confirmation ended its record`);end2();return}replied=true;end2();const confirmedButUnread=()=>fail3("internal","the harness confirmed the write, but the settings could not be read back","executed");try{const s3=await this.snapshot(d2,()=>Math.min(OPTION_READ_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS));release();const read=s3.read;if(this.readFault(s3.read)!==void 0||!read.supported||!read.options.some(o3=>o3.id===record3.id)){resolve3(confirmedButUnread());return}const out=this.overlay(read,s3);resolve3({ok:true,data:{runtime:out.runtime,seq:out.seq,written:record3.id,options:out.options,...out.unlisted?{unlisted:out.unlisted}:{}}})}catch{release();resolve3(confirmedButUnread())}},e3=>{clearTimeout(timer2);if(e3 instanceof OptionRefused){if(replied){this.opts.warn?.(`set-option ${record3.id}: a late refusal ended its record`);end2();return}replied=true;end2();release();resolve3(fail3(e3.code,`the harness refused the write: ${e3.message}`));return}this.opts.warn?.(`set-option ${record3.id}: the harness failed: ${String(e3?.message??e3)}`);leaveUnknown("the harness failed")}).catch(e3=>this.opts.warn?.(`set-option ${record3.id}: ${String(e3?.message??e3)}`))}};function withBound(p2,ms){let timer2;const late2=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms} ms`)),ms);timer2.unref?.()});return Promise.race([p2,late2]).finally(()=>clearTimeout(timer2))}var lanes2=new Map;function optionLaneFor(runtimeId,o3){let lane=lanes2.get(runtimeId);if(!lane){lane=new OptionLane({warn:o3.warn});lanes2.set(runtimeId,lane)}return lane}var self2=ctx=>ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor;var budget=ctx=>({deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs});var bind=(lane,ctx)=>lane.bindRuntime({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function reply(a3){if(a3.ok)return a3.data;throw new EpEnvelopeError(a3.code,a3.message,a3.detail?[a3.detail]:void 0,a3.outcome)}function optionHandlers(lane){return[{command:"options",contract:AGENT_CONTRACTS.options,handler:async ctx=>{bind(lane,ctx);return reply(await lane.options(budget(ctx),self2(ctx),ctx.signal))}},{command:"set-option",contract:AGENT_CONTRACTS["set-option"],handler:async ctx=>{bind(lane,ctx);const{id:id2,value}=ctx.request.args;return reply(await lane.setOption(id2,value,budget(ctx),self2(ctx),ctx.signal))}}]}import{createHmac as createHmac2,randomBytes as randomBytes6}from"node:crypto";var NATIVE_HARNESS_MS=1e4;var NATIVE_REPLY_RESERVE_MS=1e3;var NATIVE_CURSORS_MAX=64;var NATIVE_ROWS_KEPT=4096;var NativeRefused=class extends Error{code;name="NativeRefused";constructor(message2,code="failed-precondition"){super(message2);this.code=code}};function nativeFlags(d2,authed){const nativeControls=authed&&d2!==void 0&&d2.unsupported?.()===void 0&&d2.kinds.size>0&&typeof d2.read==="function";const nativeActions=nativeControls&&typeof d2.act==="function"&&(d2.actions?.size??0)>0;return{nativeControls,nativeActions}}var fail4=(code,message2,outcome="not-executed")=>({ok:false,code,outcome,message:message2});var utf82=s3=>new TextEncoder().encode(s3).length;var keyOf2=(n2=24)=>randomBytes6(n2).toString("base64url");var SIGN_IN_URL=new RegExp(AGENT_NATIVE_SIGN_IN_URL_PATTERN);var LATEST_MS=Date.UTC(9999,11,31,23,59,59,999);var validMs=v3=>typeof v3==="number"&&Number.isFinite(v3)&&v3>=0&&v3<=LATEST_MS?v3:void 0;var iso2=ms=>new Date(ms).toISOString();var NativeLane=class{opts;now;wall;salt=randomBytes6(32);seqValue=0;attached=0;authed=false;generation=0;dispatcher;watched;runtime;views=new Map;viewTicket=new Map;ticket=0;cursors=new Map;records=new Map;slot;listeners=new Set;constructor(opts={}){this.opts=opts;this.now=opts.now??(()=>performance.now());this.wall=opts.wall??(()=>Date.now())}get seq(){return this.seqValue}flags(){return nativeFlags(this.dispatcher,this.authed)}bindRuntime(runtime){this.runtime??={id:runtime.id,startedAt:runtime.startedAt}}attach(dispatcher,authed,onSeq){this.attached++;this.dispatcher=dispatcher;this.authed=authed;if(onSeq)this.listeners.add(onSeq);if(dispatcher&&this.watched!==dispatcher){this.watched=dispatcher;dispatcher.watchNative?.(()=>{if(this.watched===dispatcher)this.changed()})}this.changed();let done=false;return()=>{if(done)return;done=true;this.attached--;if(onSeq)this.listeners.delete(onSeq);this.generation++}}changed(){this.generation++;this.views.clear();this.viewTicket.clear();this.cursors.clear();this.bump()}bump(){this.seqValue++;for(const f2 of this.listeners)f2(this.seqValue)}remaining(b3){return b3.deadlineMs-(this.now()-b3.receivedAt)}warn(message2){this.opts.warn?.(message2)}gate(c3,runtimeId,what2){if(c3.self)return fail4("permission-denied",`an agent never ${what2} its own native controls`);if(runtimeId!==c3.runtimeId)return fail4("failed-precondition","the runtime named is not the one serving this request; read presence and ask the current runtime");const d2=this.dispatcher;if(!this.authed)return fail4("unimplemented","native controls are served only where the mesh authenticates the agent's owner");if(d2?.unsupported?.()!==void 0)return fail4("unimplemented","this agent's connector serves no native controls now");if(!this.flags().nativeControls)return fail4("unimplemented","this agent's connector serves no native controls");if(this.attached===0)return fail4("unavailable","this agent is stopping");return void 0}revisionOf(scope,snapshot,generation){return createHmac2("sha256",this.salt).update(`${generation}\0${scope}\0${snapshot}`).digest("base64url").slice(0,32)}fault(why){this.warn(`native-controls: the connector's read was refused: ${why}`);return fail4("internal",`the connector's read broke the native controls contract: ${why}`)}async read(input,budget3,c3){const early=this.gate(c3,input.runtimeId,"reads");if(early)return early;const d2=this.dispatcher;const runtime=this.runtime??{id:c3.runtimeId,startedAt:0};const generation=this.generation;if(input.kind==="catalog"){const items2=AGENT_NATIVE_KINDS.filter(k2=>d2.kinds.has(k2)).map(kind2=>({kind:kind2,writable:this.writable(kind2)}));return{ok:true,data:{runtime,kind:"catalog",revision:this.revisionOf("catalog",JSON.stringify(items2),generation),items:items2}}}const kind=input.kind;if(!d2.kinds.has(kind))return fail4("unimplemented","this agent's connector does not read that kind");const resourceId="resourceId"in input?input.resourceId:void 0;const parent=resourceId===void 0?void 0:this.views.get("sessions");if(resourceId!==void 0&&!parent?.rows.has(resourceId))return fail4("not-found","the latest sessions view has no such session; read sessions again");let position;let limit=input.limit??20;let held2;if(input.cursor!==void 0){held2=this.cursors.get(input.cursor);if(!held2||held2.generation!==generation||this.wall()-held2.issuedAt>AGENT_NATIVE_CURSOR_TTL_MS||held2.parent!==void 0&&held2.parent!==parent?.revision){this.cursors.delete(input.cursor);return fail4("not-found","the cursor expired or the view changed; read from the first page")}if(held2.kind!==kind||held2.resourceId!==resourceId||input.limit!==void 0&&input.limit!==held2.limit)return fail4("bad-request","the cursor belongs to another kind, resource or page size");position=held2.position;limit=held2.limit}const bound=Math.min(NATIVE_HARNESS_MS,this.remaining(budget3)-NATIVE_REPLY_RESERVE_MS);if(bound<=0)return fail4("unavailable","too little of the request's time is left to read the harness");const ticket=++this.ticket;let page2;try{page2=await withBound2(d2.read({kind,...resourceId?{resourceId}:{},...position!==void 0?{position}:{},limit}),bound)}catch{return fail4("unavailable","the harness did not answer the read")}if(generation!==this.generation)return fail4("failed-precondition","the view changed while it was read; read from the first page");if(this.attached===0)return fail4("unavailable","this agent is stopping");if(resourceId!==void 0&&this.views.get("sessions")!==parent)return fail4("failed-precondition","the sessions view changed while the history was read; read sessions again");const shaped=this.pageFault(kind,page2,limit);if(shaped)return this.fault(shaped);if(held2&&page2.snapshot!==held2.snapshot)return fail4("failed-precondition","the view changed since the first page; read from the first page");const revision=held2?.revision??this.revisionOf(`${kind}\0${resourceId??""}\0${parent?.revision??""}`,page2.snapshot,generation);const items=structuredClone([...page2.items]);const body={runtime,kind,revision,items};if(!AGENT_CONTRACTS["native-controls"].output.validate(body))return this.fault("the page does not match the row schema of its kind");const rules2=this.rulesFault(kind,items);if(rules2)return this.fault(rules2);const sized=page2.next!==void 0?{...body,nextCursor:"c".repeat(96)}:body;if(c3.fits&&!c3.fits(sized))return fail4("resource-exhausted","the page does not fit one reply; read it with a smaller limit");if(kind!=="history"&&!this.remember(kind,revision,items,held2===void 0,ticket)){return fail4("failed-precondition","a newer view of this kind was read meanwhile; read from the first page")}const out=page2.next===void 0?body:{...body,nextCursor:this.mintCursor({kind,resourceId,limit,revision,snapshot:page2.snapshot,position:page2.next,generation,...parent?{parent:parent.revision}:{}})};return{ok:true,data:out}}writable(kind){const d2=this.dispatcher;if(typeof d2?.act!=="function")return false;return[...d2.actions??[]].some(a3=>AGENT_NATIVE_ACTION_KINDS[a3]===kind&&a3!==AGENT_NATIVE_PREVIEW_ACTION)}pageFault(kind,page2,limit){if(typeof page2!=="object"||page2===null||!Array.isArray(page2.items))return"the page is not an object with items";if(typeof page2.snapshot!=="string"||page2.snapshot.length===0)return"the page names no snapshot";if(page2.next!==void 0&&(typeof page2.next!=="string"||page2.next.length===0))return"the page's next position is not a string";if(page2.items.length>limit)return`the page carries ${page2.items.length} rows, over the limit ${limit}`;for(const row2 of page2.items){let bytes;try{bytes=utf82(JSON.stringify(row2))}catch{return"a row does not serialize"}if(bytes>AGENT_NATIVE_ROW_MAX_BYTES)return`a ${kind} row is over ${AGENT_NATIVE_ROW_MAX_BYTES} bytes`}return void 0}rulesFault(kind,items){const ids=new Set;for(const row2 of items){if(ids.has(row2.id))return"a row id is listed twice";ids.add(row2.id);const defect=nativeRowDefect(kind,row2);if(defect)return defect;for(const o3 of row2.actions){if(!this.dispatcher?.actions?.has(o3.action)||typeof this.dispatcher.act!=="function")return`a row offers ${o3.action}, which the connector does not carry out`}}return void 0}mintCursor(c3){const token3=keyOf2(24);this.cursors.set(token3,{...c3,issuedAt:this.wall()});while(this.cursors.size>NATIVE_CURSORS_MAX)this.cursors.delete(this.cursors.keys().next().value);return token3}remember(kind,revision,rows,first,ticket){let view=this.views.get(kind);if(!view||view.revision!==revision){if(!first||ticket<(this.viewTicket.get(kind)??0))return false;view={revision,rows:new Map};this.views.set(kind,view);this.viewTicket.set(kind,ticket)}for(const row2 of rows){view.rows.delete(row2.id);view.rows.set(row2.id,admitted(row2))}while(view.rows.size>NATIVE_ROWS_KEPT)view.rows.delete(view.rows.keys().next().value);return true}state(input,c3){const early=this.gate(c3,input.runtimeId,"reads");if(early&&!(early.code==="unavailable"&&this.records.has(input.key)))return early;const r2=this.records.get(input.key);if(!r2)return fail4("not-found","this runtime holds no action under that key");return{ok:true,data:this.output(r2)}}output(r2){return{runtime:this.runtime??{id:"unbound",startedAt:0},key:r2.key,state:r2.state}}async act(input,budget3,c3){const early=this.gate(c3,input.runtimeId,"acts on");if(early)return early;const coords=JSON.stringify([input.action,input.resourceId,input.revision,input.args]);const held2=this.records.get(input.key);if(held2){if(held2.coords!==coords)return fail4("bad-request","this key names an earlier action with other coordinates");if(held2.caller===c3.caller&&held2.envelope===c3.envelopeId)return{ok:true,data:this.output(held2)};return fail4("failed-precondition","this key names an earlier action; read its state with native-action-state")}const refused5=this.admit(input,budget3);if(refused5)return refused5;return this.handOver(input,budget3,c3,coords)}admit(input,budget3){const d2=this.dispatcher;const kind=AGENT_NATIVE_ACTION_KINDS[input.action];if(!this.flags().nativeActions||!d2.actions?.has(input.action))return fail4("unimplemented",`this agent's connector does not carry out ${input.action}`);if(this.records.size>=AGENT_NATIVE_RECORDS_MAX)return fail4("resource-exhausted",`this runtime holds ${AGENT_NATIVE_RECORDS_MAX} action records`);const view=this.views.get(kind);if(!view||view.revision!==input.revision)return fail4("failed-precondition",`that revision is not the latest view of ${kind}; read it again`);const row2=view.rows.get(input.resourceId);if(!row2)return fail4("not-found",`the latest view of ${kind} has no such row`);const offer=row2.offers.get(input.action);if(!offer)return fail4("failed-precondition",`the row does not offer ${input.action}`);if(offer.locked)return fail4("failed-precondition",`${input.action} is locked on this row`);const args=this.argsRefusal(input,row2);if(args)return args;if(this.slot)return fail4("unavailable","another native action is still with the harness; read its state and try again once it settled");if(this.remaining(budget3)<NATIVE_HARNESS_MS+NATIVE_REPLY_RESERVE_MS)return fail4("unavailable","too little of the request's time is left to hand the action over");return void 0}argsRefusal(input,row2){const args=input.args;if(input.action==="setting-set"&&!row2.choices?.includes(args.value))return fail4("bad-request","the value is not one of the setting's choices");if(input.action==="checkpoint-restore"){const p2=this.records.get(args.previewKey);const ok3=p2&&p2.action===AGENT_NATIVE_PREVIEW_ACTION&&p2.resourceId===input.resourceId&&p2.state.status==="preview"&&p2.state.restorable&&p2.expiresAt!==void 0&&this.wall()<p2.expiresAt;if(!ok3)return fail4("failed-precondition","previewKey names no live, restorable preview of this checkpoint; preview it again")}return void 0}handOver(input,budget3,c3,coords){const record3={key:input.key,coords,caller:c3.caller,envelope:c3.envelopeId,action:input.action,resourceId:input.resourceId,state:{status:"applying"},answered:false,settled:false};this.records.set(input.key,record3);this.slot=record3;this.bump();const d2=this.dispatcher;const request2=Object.freeze({action:input.action,kind:AGENT_NATIVE_ACTION_KINDS[input.action],resourceId:input.resourceId,args:structuredClone(input.args),key:input.key});const settle=o3=>this.settle(record3,o3);let call;try{call=d2.act(request2,settle)}catch(e3){call=Promise.reject(e3)}const bound=Math.min(NATIVE_HARNESS_MS,this.remaining(budget3)-NATIVE_REPLY_RESERVE_MS);return new Promise(resolve3=>{let replied=false;const reply3=()=>{if(replied)return;replied=true;clearTimeout(timer2);resolve3({ok:true,data:this.output(record3)})};const timer2=setTimeout(()=>{record3.answered=true;if(!record3.settled)this.mark(record3,{status:"unknown"});reply3()},Math.max(0,bound));timer2.unref?.();const after=step=>{try{step()}catch{this.warn(`native-action ${record3.action}: the connector's answer could not be applied`);if(!record3.settled&&!record3.answered){record3.answered=true;this.mark(record3,{status:"unknown"})}}reply3()};call.then(r2=>after(()=>this.took(record3,r2)),e3=>after(()=>this.failed(record3,e3)))})}took(r2,result){if(r2.answered||r2.settled)return;r2.answered=true;const s3=result?.status;if(s3==="applied")return this.end(r2,{status:"applied"});if(s3==="applying")return;if(s3==="authorizing"&&AGENT_NATIVE_SIGN_IN_ACTIONS.includes(r2.action)){const res=result;const why=urlFault(res.url);const until=validMs(res.expiresAt);if(why||until===void 0){this.warn(`native-action ${r2.action}: the sign-in answer was refused: ${why??"its expiry is not a time"}`);return this.mark(r2,{status:"unknown"})}const at2=Math.min(until,this.wall()+AGENT_NATIVE_SIGN_IN_TTL_MS);if(at2<=this.wall())return this.mark(r2,{status:"unknown"});r2.expiresAt=at2;this.mark(r2,{status:"authorizing",url:res.url,expiresAt:iso2(at2)});this.expireAt(r2,at2);return}if(s3==="preview"&&r2.action===AGENT_NATIVE_PREVIEW_ACTION){const res=result;const until=res.expiresAt===void 0?Infinity:validMs(res.expiresAt);const at2=until===void 0?void 0:Math.min(until,this.wall()+AGENT_NATIVE_PREVIEW_TTL_MS);const state=at2===void 0||typeof res.restorable!=="boolean"?void 0:{status:"preview",restorable:res.restorable,expiresAt:iso2(at2),...res.filesAffected!==void 0?{filesAffected:res.filesAffected}:{},...res.reason!==void 0?{reason:res.reason}:{}};if(!state||!AGENT_CONTRACTS["native-action-state"].output.validate({runtime:{id:"x",startedAt:0},key:r2.key,state})){this.warn(`native-action ${r2.action}: the preview answer breaks the state schema`);return this.mark(r2,{status:"unknown"})}r2.expiresAt=at2;return this.end(r2,state)}this.warn(`native-action ${r2.action}: the connector's answer is not one this action takes`);this.mark(r2,{status:"unknown"})}failed(r2,e3){if(r2.answered||r2.settled)return;r2.answered=true;if(e3 instanceof NativeRefused&&AGENT_NATIVE_REFUSAL_CODES.includes(e3.code))return this.end(r2,{status:"refused",code:e3.code,reason:REFUSED_REASON});this.warn(`native-action ${r2.action}: the harness failed`);this.mark(r2,{status:"unknown"})}expireAt(r2,at2){clearTimeout(r2.expiry);r2.expiry=setTimeout(()=>{if(!r2.settled&&r2.state.status==="authorizing")this.mark(r2,{status:"unknown"})},Math.max(0,at2-this.wall()));r2.expiry.unref?.()}settle(r2,o3){if(r2.settled)return;if(o3?.status==="applied")return this.end(r2,{status:"applied"});if(o3?.status==="refused"&&AGENT_NATIVE_REFUSAL_CODES.includes(o3.code))return this.end(r2,{status:"refused",code:o3.code,reason:REFUSED_REASON});this.warn(`native-action ${r2.action}: a settlement that is neither applied nor a typed refusal was ignored`)}mark(r2,state){r2.state=state;if(state.status!=="authorizing"){clearTimeout(r2.expiry);r2.expiry=void 0}this.bump()}end(r2,state){r2.settled=true;r2.answered=true;if(state.status!=="preview")r2.expiresAt=void 0;if(this.slot===r2)this.slot=void 0;this.mark(r2,state)}};var REFUSED_REASON="the harness refused the action and nothing changed";function admitted(row2){const offers2=new Map;for(const o3 of row2.actions)offers2.set(o3.action,Object.freeze(o3.availability==="locked"?{locked:true,reason:o3.reason}:{locked:false}));const choices=row2.choices;return Object.freeze({offers:offers2,...choices?{choices:Object.freeze([...choices])}:{}})}function urlFault(url2){if(typeof url2!=="string")return"it is not a string";if(utf82(url2)>AGENT_NATIVE_URL_MAX_BYTES)return`it is over ${AGENT_NATIVE_URL_MAX_BYTES} bytes`;if(!SIGN_IN_URL.test(url2))return"it is not an https link with a plain host and no user info or fragment";try{if(new URL(url2).protocol!=="https:")return"it is not https"}catch{return"it does not parse"}return void 0}function withBound2(p2,ms){return new Promise((resolve3,reject)=>{const t2=setTimeout(()=>reject(new Error(`no answer within ${Math.round(ms)} ms`)),ms);t2.unref?.();p2.then(v3=>{clearTimeout(t2);resolve3(v3)},e3=>{clearTimeout(t2);reject(e3)})})}var lanes3=new Map;function nativeLaneFor(runtimeId,o3){let lane=lanes3.get(runtimeId);if(!lane){lane=new NativeLane({warn:o3.warn});lanes3.set(runtimeId,lane)}return lane}var caller=ctx=>({self:ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor,caller:`${ctx.caller.owner}.${ctx.caller.actor}.${ctx.caller.uid}`,envelopeId:ctx.request.id,runtimeId:ctx.principal.runtimeId,fits:data=>ctx.replyFits(data,AGENT_NATIVE_REPLY_MAX_BYTES)});var budget2=ctx=>({deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs});var bind2=(lane,ctx)=>lane.bindRuntime({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function reply2(a3){if(a3.ok)return a3.data;throw new EpEnvelopeError(a3.code,a3.message,void 0,a3.outcome)}function nativeHandlers(lane){return[{command:"native-controls",contract:AGENT_CONTRACTS["native-controls"],handler:async ctx=>{bind2(lane,ctx);return reply2(await lane.read(ctx.request.args,budget2(ctx),caller(ctx)))}},{command:"native-action",contract:AGENT_CONTRACTS["native-action"],handler:async ctx=>{bind2(lane,ctx);return reply2(await lane.act(ctx.request.args,budget2(ctx),caller(ctx)))}},{command:"native-action-state",contract:AGENT_CONTRACTS["native-action-state"],handler:ctx=>{bind2(lane,ctx);return reply2(lane.state(ctx.request.args,caller(ctx)))}}]}var SENT_ITEM_REPLY_CEILING=524288;var SENT_SEQ_RESERVE=9*2+AGENT_SENT_ITEMS_MAX*2+5*2;var enc8=new TextEncoder;var utf83=s3=>enc8.encode(s3).length;function normalise(s3){return s3.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}function cutToBytes(s3,max){if(max<=0)return"";if(utf83(s3)<=max)return s3;let out="";let used=0;for(const cp of s3){const b3=utf83(cp);if(used+b3>max)break;out+=cp;used+=b3}return out}function previewOf(text5){if(text5==="")return void 0;return Array.from(text5).slice(0,AGENT_SENT_PREVIEW_MAX).join("")}var isRunToken=s3=>typeof s3==="string"&&/^[^\s\p{C}]+$/u.test(s3)&&Array.from(s3).length<=AGENT_SENT_RUN_ID_MAX;function createSentStore(o3){const rows=new Map;const seqMax=o3.seqMax??Number.MAX_SAFE_INTEGER;const now=o3.now??(()=>new Date);let seq=o3.seqStart??0;let accepted=0;let dropped=0;let bodyBytes=0;const inReserve=()=>seqMax-seq<=SENT_SEQ_RESERVE;const waiting=()=>[...rows.values()].filter(r2=>r2.state.kind==="queued").length;const presence=()=>({waiting:waiting(),seq});function step(apply){if(seq>=seqMax)return false;apply();seq++;o3.changed?.(presence());return true}const unfinished=r2=>r2.state.kind==="queued"||r2.state.kind==="taken";const bytesOf=r2=>(r2.text?.bytes??0)+(r2.output?.bytes??0);function makeRoom(rowsNeeded,bytesNeeded,keep){for(const r2 of[...rows.values()].sort((a3,b3)=>a3.n-b3.n)){if(AGENT_SENT_ITEMS_MAX-rows.size>=rowsNeeded&&AGENT_SENT_BODY_BYTES_MAX-bodyBytes>=bytesNeeded)return;if(unfinished(r2)||r2.id===keep)continue;rows.delete(r2.id);bodyBytes-=bytesOf(r2);dropped++}}function store(raw,keep){const text5=normalise(raw);const of=utf83(text5);makeRoom(0,of,keep);const kept=cutToBytes(text5,AGENT_SENT_BODY_BYTES_MAX-bodyBytes);const bytes=utf83(kept);bodyBytes+=bytes;return{text:kept,bytes,of,normalised:text5}}function admit(item){if(!o3.authed)return true;if(inReserve()||seq+1+SENT_SEQ_RESERVE>seqMax)return false;return step(()=>{makeRoom(1,0);const raw=item.kind==="turn"?item.text:item.args;const stored=raw!==""?store(raw):void 0;const row2={id:item.id,n:++accepted,at:now().toISOString(),kind:item.kind,state:{kind:"queued"},lateAfterStop:0,...stored?{text:{text:stored.text,bytes:stored.bytes,of:stored.of}}:{}};if(item.kind==="turn")row2.turn={...stored?{preview:previewOf(stored.normalised)}:{},images:item.images,published:item.published};else row2.command={target:item.target,name:item.name,args:raw!==""};rows.set(row2.id,row2)})}function state(id2,next){const r2=rows.get(id2);if(!r2)return;step(()=>{r2.state=next})}function late2(id2,apply){const r2=rows.get(id2);if(!r2)return;const reserved=inReserve();if(reserved&&r2.lateAfterStop>=2)return;if(step(()=>apply(r2))&&reserved)r2.lateAfterStop++}const reports={run(id2,run){if(!isRunToken(run?.threadId)||!isRunToken(run?.runId)||run.messageId!==void 0&&!isRunToken(run.messageId))return;late2(id2,r2=>{r2.run={threadId:run.threadId,runId:run.runId,...run.messageId!==void 0?{messageId:run.messageId}:{}}})},output(id2,output){const r2=rows.get(id2);if(!r2||r2.kind!=="command"||typeof output!=="string")return;late2(id2,row2=>{if(row2.output)bodyBytes-=row2.output.bytes;row2.output=void 0;const{text:text5,bytes,of}=store(output,row2.id);row2.output={text:text5,bytes,of}})}};function itemOf(r2){const code=r2.state.kind==="refused"||r2.state.kind==="unknown"?{code:r2.state.code}:{};const base={id:r2.id,n:r2.n,status:r2.state.kind,...code,at:r2.at,...r2.run?{run:r2.run}:{}};if(r2.kind==="turn"){const t2=r2.turn;return{...base,kind:"turn",...t2.preview!==void 0?{preview:t2.preview}:{},...t2.images>0?{images:t2.images}:{},...t2.published?{published:true}:{}}}const c3=r2.command;return{...base,kind:"command",target:c3.target,name:c3.name,...c3.args?{args:true}:{},...r2.output?{output:{bytes:r2.output.of}}:{}}}const runtimeOf=ctx=>({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function sent(ctx){const out={runtime:runtimeOf(ctx),seq,accepted,dropped,items:[...rows.values()].sort((a3,b3)=>a3.n-b3.n).map(itemOf)};const defect=sentListDefect(out);if(defect)throw new EpEnvelopeError("internal",`this agent's read-back list failed its own check: ${defect}`,void 0,"not-executed");return out}function sentItem(ctx){const{id:id2}=ctx.request.args;const r2=rows.get(id2);if(!r2)throw new EpEnvelopeError("not-found",`this agent keeps no sent item ${id2}`,void 0,"not-executed");const out=fitDetail({runtime:runtimeOf(ctx),seq,id:id2,state:r2.state},{output:r2.output,text:r2.text},data=>ctx.replyFits(data,SENT_ITEM_REPLY_CEILING));const defect=sentItemDefect(out,id2,r2.turn?.preview);if(defect)throw new EpEnvelopeError("internal",`this agent's read-back item failed its own check: ${defect}`,void 0,"not-executed");return out}const unimplemented=()=>{throw new EpEnvelopeError("unimplemented","this agent keeps no read-back copy: its mesh does not authenticate its owner",void 0,"not-executed")};const handlers=[{command:"sent",contract:AGENT_CONTRACTS.sent,handler:ctx=>o3.authed?sent(ctx):unimplemented()},{command:"sent-item",contract:AGENT_CONTRACTS["sent-item"],handler:ctx=>o3.authed?sentItem(ctx):unimplemented()}];return{serves:o3.authed,admit,state,presence,handlers,...reports}}function fitDetail(head,bodies,fits){const order2=["output","text"].filter(f2=>bodies[f2]!==void 0);const chosen={};const build=c3=>{const out={...head};const cut3={};for(const f2 of order2){const v3=c3[f2];out[f2]=v3;const kept=utf83(v3);if(kept<bodies[f2].of)cut3[f2]={of:bodies[f2].of,kept}}if(cut3.text||cut3.output)out.cut=cut3;return out};for(const[i2,f2]of order2.entries()){const later=order2.slice(i2+1);const combos=later.reduce((acc,l2)=>acc.flatMap(x2=>[{...x2,[l2]:bodies[l2].text},{...x2,[l2]:""}]),[{}]);const fitsWith=v3=>combos.some(cmb=>fits(build({...chosen,[f2]:v3,...cmb})));const stored=bodies[f2].text;if(fitsWith(stored)){chosen[f2]=stored;continue}const cps=Array.from(stored);let lo=0;let hi2=cps.length-1;while(lo<hi2){const mid=Math.ceil((lo+hi2)/2);if(fitsWith(cps.slice(0,mid).join("")))lo=mid;else hi2=mid-1}chosen[f2]=cps.slice(0,lo).join("")}return build(chosen)}async function openAgentEndpoint(ep,opts){if(typeof opts?.warn!=="function")throw new TypeError("openAgentEndpoint needs opts.warn");const max=ep.maxPayload;if(max<PROMPT_DESK_MIN_MAX_PAYLOAD)throw new Error(`the agent endpoint needs a connection whose max_payload is at least ${PROMPT_DESK_MIN_MAX_PAYLOAD} bytes, and this one is ${max}`);const warn=msg=>{try{opts.warn(msg)}catch{}};const desk=createPromptDesk(ep,warn);let showSent=()=>{};const authed=opts.authed===true;const store=createSentStore({authed,...authed?{seqStart:ep.nextSentSeqStart()}:{},changed:now=>{ep.noteSentSeq(now.seq);showSent()}});const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}),opts.first,store.serves?store:void 0);const naming=createNameLane(ep,warn,opts.onNamed);let showOptions=()=>{};const options=optionLaneFor(ep.runtimeId,{warn});const model=createModelLane(opts.dispatcher,{show:opts.showModel??(s3=>ep.setCardModel(s3.model,s3.variant)),warn,policed:opts.policed,authed,exclusive:fn2=>options.runExclusive(fn2)});const steerLane=steerLaneFor(ep.runtimeId,warn);let onNative=()=>{};const native=nativeLaneFor(ep.runtimeId,{warn});let steer;const steerFor={served:()=>steer?.served()??false,steer:(req,budget3,signal)=>steer.steer(req,budget3,signal),detach:()=>steer?.detach()};const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers,...naming.handlers,model.handler,model.choices,...store.handlers,steerHandler(steerFor),...optionHandlers(options),...nativeHandlers(native)]});steer=steerLane.attach(opts.dispatcher?.steer);const detachOptions=options.attach(opts.dispatcher?.options,()=>showOptions());const detachNative=native.attach(opts.dispatcher?.native,authed,()=>onNative());desk.served(serve.ready);let closing;const showServed=()=>{if(closing)return;const nativeFlagsNow=native.flags();ep.setAgentEndpointPresence({...servedCommands(opts.dispatcher),sent:store.serves,steer:steerFor.served(),...options.flags(),...nativeFlagsNow},nativeFlagsNow.nativeControls?{seq:native.seq}:null).catch(e3=>warn(`presence does not show what the agent endpoint serves: ${e3.message}`));showOptions()};showOptions=()=>{if(closing)return;const cursor=options.flags().options?{seq:options.seq}:void 0;ep.setOptionsPresence(cursor).catch(e3=>warn(`presence does not show the settings counter: ${e3.message}`))};onNative=showServed;showSent=()=>{if(closing||!store.serves)return;ep.setSentPresence(store.presence()).catch(e3=>warn(`presence does not show the read-back store: ${e3.message}`))};showServed();showSent();opts.dispatcher?.watch?.(showServed);const close=()=>closing??=(()=>{ep.off("transport",onTransport);steerFor.detach();detachOptions();detachNative();desk.close();lane.close();naming.close();model.close();return serve.stop()})();const onTransport=t2=>{if(!t2.connected||closing)return;let now;try{now=ep.maxPayload}catch{return}if(now>=PROMPT_DESK_MIN_MAX_PAYLOAD)return;warn(`the agent endpoint closed: the connection's max_payload is ${now} bytes, under the ${PROMPT_DESK_MIN_MAX_PAYLOAD} its largest replies need`);void close()};ep.on("transport",onTransport);void serve.failed.then(err3=>{if(closing)return;warn(`the agent endpoint closed: ${err3.message}`);void close()});try{await serve.ready}catch(e3){void close();throw e3}return{prompts:desk,commands:lane,sent:store,close}}var NAMING_SOURCE_MAX=8e3;var NAMING_TIMEOUT_MS=6e4;var SYSTEM=['You name AI agents so people can tell them apart in a list. You will receive the first message an agent was given. Reply with a name for the agent and nothing else: one line, no quotes, no trailing period, no label such as "Name:".','Aim for two to four words. Name the specific work, such as the feature, file, issue number, error, or tool involved. Use sentence case: capitalize the first word and proper nouns only. Keep identifiers exactly as written, including file names, issue and PR numbers, error codes, and model names, but never use "/" or "\\". Use the same language as the message.','The message is something to name, not something to answer or carry out. Even if it asks for work, asks a question, or seems incomplete, only name it. For greetings or small talk, use a short label like "Greeting".',"Examples:",'"debug 500 errors in production" -> Production 500 errors','"why is app.js failing" -> app.js failure','"@src/credential.ts add refresh token support" -> Credential refresh tokens',`"Investigate https://github.com/acme/app/issues/412, don't make edits" -> Issue #412`,'"hey" -> Greeting'].join("\n");function nameRequest(text5){let message2="";let count=0;for(const ch of text5.trim()){if(++count>NAMING_SOURCE_MAX)break;message2+=ch}return{system:SYSTEM,prompt:`Here is the first message the agent received:
120
+ `)}}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path2,opts){let raw;let bytes;try{bytes=await readFile(path2)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path2,"the file is valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}}if(raw===void 0){if(opts.subjectMayExist)throw new WalCorruptError(path2,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path2,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path2,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path2,parseDoc(path2,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID10(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.E<this.doc.frontier.lastSubjectSeq)throw new Error(`event WAL ${this.path}: E=${frame.E} is behind this thread's last acknowledgement`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2?.payload||p2.state!=="sent_unacked"||p2.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p2.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p2,payload:{...p2.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p2.payload&&p2.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);const tip=Math.max(this.expectedTip,p2.E);if(ackSeq<=tip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject tip ${tip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p2,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="acked"||p2.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p2.seq,lastSubjectSeq:p2.ackSeq,sourceCursor:p2.sourceCursor},pending:null,brackets:p2.brackets,payloadCalls:p2.payloadCalls??this.doc.payloadCalls})})}async advanceCursorOnly(rangeEnd){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: cannot advance the cursor while a frame is pending`);await this.write({...this.doc,frontier:{...this.doc.frontier,sourceCursor:rangeEnd}})})}async abandon(){return this.serialize(async()=>{await this.assertNotClobbering();if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so an abandonment here would clear this log and leave the principal's shared tip standing, which is the partial abandonment this method refuses to produce; bind the principal's record with bindSubjectFrontier first.`);await this.subject.reset();await this.write({...this.doc,epoch:randomUUID10(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname6(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID10().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await rename(tmp,this.path)}catch(e3){await unlink(tmp).catch(()=>{});throw e3}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes===void 0){if(this.doc.gen!==0)throw new WalStaleWriterError(this.path,this.doc.gen,void 0);return}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(this.path,"the file is valid UTF-8","invalid UTF-8 bytes on the file about to be replaced; refusing rather than substituting U+FFFD")}let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(this.path,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(this.path,"document is an object",typeof d2);const onDisk=docGeneration(this.path,d2);if(onDisk!==this.doc.gen)throw new WalStaleWriterError(this.path,this.doc.gen,onDisk)}};var EventsStateRootMissing=class extends Error{constructor(message2){super(message2);this.name="EventsStateRootMissing"}};function resolveEventsStateRoot(env){const root=env.COTAL_WORKSPACE_ROOT;if(typeof root!=="string"||root.trim()==="")throw new EventsStateRootMissing("events are enabled for this session but COTAL_WORKSPACE_ROOT is not set, so there is nowhere to put the event write-ahead log. The launcher forwards it from LaunchOpts.workspaceRoot; a session started outside a manager has no workspace root and must not publish events. Refusing rather than defaulting to the working directory, which would put the WAL somewhere no later start looks.");return root}function h2(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h2(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json"),deltaJournalPath:join7(threadDir,"deltas.jsonl")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path2,invariant,detail){super(`event WAL principal lock at ${path2} (${invariant}): ${detail}`);this.path=path2;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e3){return e3.code!=="ESRCH"}}async function createLockFile(path2){try{return await openExclusiveNoFollow(path2)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path2){let raw;try{raw=await readFile2(path2,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record3;try{record3=JSON.parse(raw)}catch{throw new PrincipalLockError(path2,"the lock names its owner","the file is not readable JSON, so its owner cannot be checked; refusing rather than reclaiming a lock that may be held")}const r2=record3;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path2,"the lock names its owner",`the record carries pid=${String(r2.pid)} host=${String(r2.host)}, which names nobody checkable`);const here=hostname();if(r2.host!==here)throw new PrincipalLockError(path2,"the recorded owner is on THIS host",`held by pid ${r2.pid} on ${r2.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r2.pid))throw new PrincipalLockError(path2,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path2).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}async function acquirePrincipalLock(lockPath){const already=held.get(lockPath);if(already)return already;let fh=await createLockFile(lockPath);if(fh===void 0){await reclaimIfOwnerIsGone(lockPath);fh=await createLockFile(lockPath);if(fh===void 0)throw new PrincipalLockError(lockPath,"the reclaimed lock is free when this process takes it","another process created the lock between the reclaim and this open, and now holds this principal")}const record3=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID11(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record3,"utf8");await fh.sync()}catch(e3){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e3}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e3){const code=e3.code;if(code==="EPERM"||code==="EACCES")return;throw e3}try{await fh.sync()}catch(e3){const code=e3.code;if(code!=="EBADF"&&code!=="EINVAL"&&code!=="EPERM"&&code!=="EISDIR")throw e3}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h2(opts.space),h2(opts.principal),h2(opts.threadId));for(let dir=loc.threadDir;;dir=dirname7(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname7(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){const workspaceRoot=resolveEventsStateRoot(env);try{await checkEventStartup({workspaceRoot,space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}catch(error51){if(!(error51 instanceof EventStateConflictError))throw error51;const principal=principalKey(ep.principal.owner,ep.principal.actor).key;const threadId="startup-pending-inspection";const{walPath}=eventWalLocation({workspaceRoot,space:ep.space,principal,threadId});const inspection=await EventWal.open(walPath,{space:ep.space,principal,threadId,subjectMayExist:false});if((await inspection.pendingSiblings()).length===0)throw error51}}var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY2=Symbol.for("cotal.once-handoff");function proc(){const g2=globalThis;return g2[KEY2]??={handoffs:new Map}}var keyOf=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p2=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer2=setTimeout(()=>p2.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer2.unref?.();p2.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer:timer2})}return true}function confirmOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="sealed")return false;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed")return false;if(h3.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="confirmed"||h3?.state==="sealed")return;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed"||h3.timer===void 0)return;clearTimeout(h3.timer);h3.timer=void 0}function onOnceHandoffTimeout(fn2){proc().timedOut=fn2}function registerOnceExit(fn2){proc().exit=fn2}function exitOnceSeat(){const p2=proc();if(p2.exiting)return p2.exiting;const exiting=askOnceExit(p2.exit).then(ending=>{if(!ending){p2.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p2.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}var CONNECTOR_VERSION="0.193.1";function managerBearerArgv(argv,instanceId){return[...argv,"--manager-call",...instanceId?["--manager-instance",instanceId]:[]]}var MANAGER_BEARER_MARGIN_MS=12e4;function compareRelease(a3,b3){const[x2,y3]=[a3,b3].map(v3=>v3.split(/[-+]/)[0].split(".").map(Number));for(let i2=0;i2<3;i2++)if(x2[i2]!==y3[i2])return(x2[i2]??0)-(y3[i2]??0);return 0}function bearerExpiryMs2(token3){try{const exp=JSON.parse(Buffer.from(token3.split(".")[1]??"","base64url").toString("utf8")).exp;return typeof exp==="number"&&Number.isFinite(exp)?exp*1e3:void 0}catch{return void 0}}function abortable(p2,signal){if(!signal)return p2;if(signal.aborted){void p2.catch(()=>{});return Promise.reject(signal.reason)}return new Promise((resolve3,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve3(v3)},e3=>{signal.removeEventListener("abort",onAbort);reject(e3)})})}var AgentManagerCalls=class{getConfig;getEndpoint;getLaunchEnv;invokeEndpoint;constructor(getConfig,getEndpoint,getLaunchEnv,invokeEndpoint){this.getConfig=getConfig;this.getEndpoint=getEndpoint;this.getLaunchEnv=getLaunchEnv;this.invokeEndpoint=invokeEndpoint}get config(){return this.getConfig()}get ep(){return this.getEndpoint()}get launchEnv(){return this.getLaunchEnv()}clear(){this.managerBearers.clear()}managerCredential(instanceId){const user=this.config.userAuth;if(user?.bearerCmd){const argv=managerBearerArgv(user.bearerCmd,instanceId);return{bearer:signal=>this.managerCallBearer(argv,signal),drop:()=>{this.managerBearers.delete(JSON.stringify(argv))}}}if(user?.managerBearer)return{bearer:signal=>this.freshManagerBearer(user,instanceId,signal)};return void 0}async freshManagerBearer(user,managerInstanceId,signal,timeoutMs=3e4){if(user.bearerCmd)return this.execBearerCmd(managerBearerArgv(user.bearerCmd,managerInstanceId),signal,timeoutMs);const timeout=AbortSignal.timeout(timeoutMs);const bounded=signal?AbortSignal.any([signal,timeout]):timeout;try{bounded.throwIfAborted();const exchange2=user.managerBearer({managerInstanceId,signal:bounded});return await abortable(exchange2,bounded)}catch(e3){if(signal?.aborted)throw e3;const message2=(e3 instanceof Error?e3.message:String(e3)).replace("--manager-instance <instanceId>","the instance argument");throw new EpEnvelopeError(e3 instanceof EpEnvelopeError?e3.code:"unavailable",message2,void 0,"not-executed")}}async listManagerEndpoints(input,instance){const user=this.config.userAuth;if(!user)return{none:"manager calls ride this session's own credential on this mesh, so the session view covers them"};const managerInstanceId=instance??this.config.managerInstanceId;const credential=this.managerCredential(managerInstanceId);if(!credential)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const token3=await credential.bearer().catch(e3=>{throw user.bearerCmd&&e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token3);return withUserManagerListing({...this.config,managerInstanceId},token3,exp===void 0?void 0:exp/1e3,async(nc,listing)=>listing===void 0?{unbound:true}:this.ep.listEndpointsOver(nc,listing,input))}managerBearers=new Map;managerCallBearer(argv,signal){const key=JSON.stringify(argv);const held2=this.managerBearers.get(key);if(held2&&(held2.refreshAt===void 0||Date.now()<held2.refreshAt))return abortable(held2.flight,signal);const entry={flight:this.execBearerCmd(argv)};this.managerBearers.set(key,entry);entry.flight.then(token3=>{const exp=bearerExpiryMs2(token3);if(exp===void 0||exp-MANAGER_BEARER_MARGIN_MS<=Date.now()){if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)}else entry.refreshAt=exp-MANAGER_BEARER_MARGIN_MS},()=>{if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)});return abortable(entry.flight,signal)}async execBearerCmd(argv,signal,timeoutMs){const bearer=await runAgentBearer(argv,{env:this.launchEnv,signal,timeoutMs});if(!bearer)throw new Error(`bearer command printed nothing (${argv[0]})`);return bearer}async managerInvoke(command,args,opts={}){const clean=args===void 0?void 0:Object.fromEntries(Object.entries(args).filter(([,v3])=>v3!==void 0));let r2;let dropBearer;try{const input=clean&&Object.keys(clean).length?clean:void 0;const user=this.config.userAuth;if(user){const managerInstanceId=opts.instanceId??this.config.managerInstanceId;const credential=this.managerCredential(managerInstanceId);if(!credential)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearer=signal=>credential.bearer(signal).catch(e3=>{if(signal?.aborted||!(e3 instanceof Error)||e3 instanceof EpEnvelopeError)throw e3;const message2=e3.message.replace("--manager-instance <instanceId>","the instance argument");if(typeof e3.retryAfterSeconds==="number")throw new EpEnvelopeError("resource-exhausted",message2,void 0,"not-executed");if(e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",message2,void 0,"not-executed");throw new Error(message2)});dropBearer=credential.drop;r2=await invokeUserManager({...this.config,managerInstanceId},bearer,command,input,{...invokeOpts,follow:follow?(submit,prepare)=>this.ep.followServiceGoal(BASELINE_LIFECYCLE_ENDPOINT,submit,opts.deadlineMs,{prepare,reconcile:async(goalId,attributed,context)=>{const instanceId=attributed.responder?.instanceId;if(!instanceId)throw new Error("accepted goal has no broker-attributed manager instance");const bearer2=signal=>this.freshManagerBearer(user,instanceId,signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...user,owner:context.caller.owner,actor:context.caller.actor}};const queryRes=await invokeUserManager(config2,bearer2,"goal-result",{goalId},{signal:context.signal,deadlineMs:Math.min(invokeOpts.deadlineMs??1e4,context.deadlineMs)});if(queryRes.reply.ok!==true)throw new Error(queryRes.reply.error?.message??"goal-result query refused");return queryRes.reply.data}}):void 0})}else{const launchLocal=command==="stop"||command==="spawn"||command==="define-persona";const classInstanceId=this.config.creds&&launchLocal&&opts.instanceId===void 0?this.config.managerInstanceId:void 0;r2=await this.invokeEndpoint(BASELINE_LIFECYCLE_ENDPOINT,command,input,{...opts,...classInstanceId!==void 0?{classInstanceId}:{}})}}catch(e3){dropBearer?.();if(e3 instanceof EpEnvelopeError){const submitted=command==="spawn"&&e3.outcome==="unknown"?e3.details?.find(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command&&typeof d2.requestId==="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(d2.requestId)):void 0;if(submitted)return{...controlReplyFromThrown(e3,`${e3.code}: ${e3.message}`),outcome:"unknown",data:{goalId:submitted.requestId,submissionUnknown:true}};const undeclared=undeclaredArg(e3);if(undeclared!==void 0&&command!=="status")return{...controlReplyFromThrown(e3,await this.undeclaredArgMessage(command,e3,undeclared)),...e3.outcome?{outcome:e3.outcome}:{}};const unknownDefinition=command==="define-persona"&&e3.outcome!=="not-executed"&&e3.code==="deadline-exceeded"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.command===command);const unknownYield=command==="turn-yield"&&e3.code==="deadline-exceeded"&&e3.outcome==="unknown"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command);const message2=unknownYield?`${e3.code}: ${e3.message}. The yield may already have been recorded. After reconnecting, retry cotal_yield with the same turn id and intended status. An already-settled reply confirms the turn is terminal, not which attempt settled it. A successful reply records the yield if it is still active. This retry is not a read-only check.`:unknownDefinition?`${e3.code}: ${e3.message}`:unansweredRequest(e3)?`${e3.message} (no responder answered - a manager may be down, or this credential holds no "${command}" capability and the broker denied the request)`:`${e3.code}: ${e3.message}`;return{...controlReplyFromThrown(e3,message2),...e3.outcome?{outcome:e3.outcome}:{}}}return{ok:false,error:e3.message}}if(r2.reply.ok!==true)dropBearer?.();return{...controlReplyFrom(r2.reply),instanceId:r2.responder?.instanceId,...r2.reply.error?.outcome?{outcome:r2.reply.error.outcome}:{}}}async undeclaredArgMessage(command,e3,key){const head=`${e3.code}: ${e3.message}. The manager's ${command} does not take "${key}", which this connector at Cotal ${CONNECTOR_VERSION} sends`;const instanceId=undeclaredArgInstance(e3);const answer2=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer2?.ok===true&&answer2.instanceId===instanceId?answer2.data?.version:void 0;const manager=typeof reported==="string"&&/^\d+\.\d+\.\d+/.test(reported)?reported:void 0;const updateManager=`on the manager's host run \`cotal update --self\`, then \`cotal manager restart\`, or, if you set "${key}", call again without it`;if(manager===void 0)return`${head}, so the manager most likely runs an older Cotal: ${updateManager}`;const order2=compareRelease(CONNECTOR_VERSION,manager);if(order2>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order2<0)return`${head}. The manager runs Cotal ${manager}, so this connector is the older side: run \`cotal update --self\` here and start a new session`;return`${head}. The manager also reports Cotal ${manager}, so one side is another build of that version: reinstall that side`}};var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token3,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token3,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token3;const connectOpts=standaloneConnectOpts({bearer:token3,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller2=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller2}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller2=skipped?void 0:await issued();const listing=caller2??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller2;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve3=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller2,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve3(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller2=await issuedUserCaller(nc,config2.space,connId,caller2);legacyRail.delete(key);return resolve3(signal,remaining())}};const connect4=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token3=await bearer(signal);let credentialId;try{({caller:caller2,instanceId,credentialId}=managerCallerBinding(token3,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}))}catch{throw new EpEnvelopeError("failed-precondition","the manager control bearer is not bound to the expected caller and manager instance",void 0,"not-executed")}const connectOpts=standaloneConnectOpts({bearer:token3,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");try{nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left})}catch(error51){signal?.throwIfAborted();if(error51 instanceof EpEnvelopeError)throw error51;throw new EpEnvelopeError(isAuthRejection(error51)?"permission-denied":"unavailable",error51 instanceof Error?error51.message:String(error51),void 0,"not-executed")}if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token3;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller2=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller2)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect4(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve3(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect4();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}import{randomBytes as randomBytes4}from"node:crypto";var COMMAND_LIST_MS=1e4;var MAX_QUEUED_COMMANDS=8;var ENDED_COMMANDS_KEPT=32;var FIRST_COMMAND_READY_MS=6e4;var FIRST_COMMAND_POLL_MS=250;var CommandRefused=class extends Error{code;constructor(code,message2){super(message2);this.code=code;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code,message2)=>new EpEnvelopeError(code,message2,void 0,"not-executed");var what=e3=>"turn"in e3.job?"the turn":`the ${e3.job.command.target} "${e3.job.command.name}"`;function cut2(text5,max){const chars=[...text5];return chars.length<=max?text5:`${chars.slice(0,max-1).join("")}\u2026`}async function runEntry(e3,dispatcher,end2,taken,answered=()=>{}){if(!e3)return"empty";taken(e3);try{if("turn"in e3.job)await dispatcher.turn({...e3.job.turn,id:e3.id});else{const out=await dispatcher.dispatch(e3.job.command);if(out&&typeof out.output==="string"&&out.output!=="")answered(e3,out.output)}end2(e3,{kind:"started"});return"dispatched"}catch(err3){const message2=String(err3?.message??err3);end2(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut2(message2,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut2(`the harness failed, so ${what(e3)} may have started: ${message2}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}}function takeGate(queuedCount,take,closed6){let inFlight;let closedNow=false;void closed6.then(()=>{closedNow=true});return async()=>{if(inFlight){const atSettlement=await Promise.race([inFlight,closed6.then(()=>0)]);return closedNow||atSettlement===0?"empty":"busy"}if(queuedCount()===0)return"empty";let settle;inFlight=new Promise(resolve3=>{settle=resolve3});try{return await take()}finally{inFlight=void 0;settle(queuedCount())}}}function within(work,ms){let timer2;const late2=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms/1e3} s`)),ms)});return Promise.race([Promise.resolve().then(work),late2]).finally(()=>clearTimeout(timer2))}function servedCommands(dispatcher){const now=dispatcher!==void 0&&dispatcher.unsupported?.()===void 0;const turn=now&&typeof dispatcher.turn==="function";return{interrupt:now&&typeof dispatcher.interrupt==="function",turn,images:turn&&dispatcher.images===true,usage:now&&typeof dispatcher.usage==="function",setModel:now&&typeof dispatcher.setModel==="function"}}function notSelf(ctx,what2){if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused("permission-denied",`an agent never ${what2}`)}async function listCommands(dispatcher){if(!dispatcher||dispatcher.targets.size===0||dispatcher.unsupported?.()!==void 0)return{supported:false};let listed;try{listed=await within(()=>dispatcher.list(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not list its commands: ${e3.message}`)}return{supported:true,commands:fitCommandEntries(listed,dispatcher.targets)}}async function readUsage(dispatcher){if(!dispatcher?.usage||dispatcher.unsupported?.()!==void 0)return{supported:false};let got;try{got=await within(()=>dispatcher.usage(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not report its usage: ${e3.message}`)}return{supported:true,...got?.context?{context:got.context}:{},...got?.cost?{cost:got.cost}:{}}}function createCommandLane(dispatcher,onQueued,first,observer){const entries=new Map;const ended=[];let closed6=false;let held2;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued"&&e3!==held2);const waiting=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued").length;const known=id2=>{const e3=entries.get(id2);if(!e3)throw refused("not-found",`command ${id2} is not known to this agent`);return e3};function end2(e3,state){e3.state=state;observer?.state(e3.id,state);ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}function taken(e3){e3.state={kind:"taken"};observer?.state(e3.id,e3.state)}const admission=(id2,job)=>"turn"in job?{kind:"turn",id:id2,text:job.turn.text,images:job.turn.images.length,published:dispatcher?.publishesTurns===true}:{kind:"command",id:id2,target:job.command.target,name:job.command.name,args:job.command.args};function seed(f2){const e3={id:f2.id,job:{command:{target:f2.target,name:f2.name,args:f2.args??""}},state:{kind:"queued"}};entries.set(e3.id,e3);observer?.admit(admission(e3.id,e3.job));const refuse4=message2=>end2(e3,{kind:"refused",code:"failed-precondition",message:cut2(message2,AGENT_COMMAND_MESSAGE_MAX)});if(!dispatcher||dispatcher.targets.size===0)return refuse4("this agent's connector runs no commands or skills");if(!dispatcher.targets.has(f2.target))return refuse4(`this agent's connector runs no ${f2.target}s`);if(dispatcher.unsupported?.()===void 0)return;held2=e3;const deadline=Date.now()+FIRST_COMMAND_READY_MS;const timer2=setInterval(()=>{const cause=e3.state.kind==="queued"?dispatcher.unsupported?.():void 0;if(cause!==void 0&&Date.now()<deadline)return;clearInterval(timer2);held2=void 0;if(e3.state.kind!=="queued")return;if(cause===void 0)onQueued();else refuse4(`the harness ran no commands within ${FIRST_COMMAND_READY_MS/1e3} s: ${cause}`)},FIRST_COMMAND_POLL_MS);timer2.unref?.()}if(first)seed(first);function enqueue(job){if(closed6)throw refused("unavailable","this agent is stopping");if(waiting()>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands and turns are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));if(observer&&!observer.admit(admission(id2,job)))throw refused("resource-exhausted","this agent's read-back store has used its sequence numbers; it takes nothing more until it restarts");entries.set(id2,{id:id2,job,state:{kind:"queued"}});onQueued();return{id:id2}}function run(ctx){notSelf(ctx,"runs a command on itself");const input=ctx.request.args;if(!dispatcher||dispatcher.targets.size===0)throw refused("unimplemented","this agent's connector runs no commands or skills");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector runs no commands now: ${cause}`);if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);return enqueue({command:{target:input.target,name:input.name,args:input.args??""}})}function turn(ctx){notSelf(ctx,"gives itself a turn");const input=ctx.request.args;if(!dispatcher?.turn)throw refused("unimplemented","this agent's connector takes no turn from its owner");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector takes no turn now: ${cause}`);const images=input.images??[];if(images.length&&!dispatcher.images)throw refused("unimplemented","this agent's harness takes no images");if(input.text===""&&!images.length)throw refused("bad-request","a turn needs text or an image");return enqueue({turn:{text:input.text,images}})}async function interrupt(ctx){notSelf(ctx,"interrupts its own turn");if(!dispatcher?.interrupt)throw refused("unimplemented","this agent's connector cannot interrupt a turn");const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused("unimplemented",`this agent's connector cannot interrupt a turn now: ${cause}`);if(closed6)throw refused("unavailable","this agent is stopping");try{return{state:await dispatcher.interrupt()}}catch(e3){throw new EpEnvelopeError("internal",`the harness failed, so the turn may have been interrupted: ${String(e3?.message??e3)}`,void 0,"unknown")}}const take=()=>runEntry(queued()[0],dispatcher,end2,taken,(e3,output)=>observer?.output?.(e3.id,output));let closing;const closed$=new Promise(resolve3=>{closing=resolve3});const gate=takeGate(()=>queued().length,take,closed$);function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end2(e3,{kind:"cancelled"});else if(e3.state.kind!=="cancelled")throw new EpEnvelopeError("conflict",`command ${id2} is ${e3.state.kind}, so it can no longer be cancelled`,[{kind:AGENT_COMMAND_STATE_DETAIL,state:e3.state}],"not-executed");return{state:e3.state}}return{handlers:[{command:"commands",contract:AGENT_CONTRACTS.commands,handler:()=>listCommands(dispatcher)},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx)},{command:"command-cancel",contract:AGENT_CONTRACTS["command-cancel"],handler:ctx=>cancel(ctx.request.args)},{command:"command-state",contract:AGENT_CONTRACTS["command-state"],handler:ctx=>({state:known(ctx.request.args.id).state})},{command:"turn",contract:AGENT_CONTRACTS.turn,handler:ctx=>turn(ctx)},{command:"interrupt",contract:AGENT_CONTRACTS.interrupt,handler:ctx=>interrupt(ctx)},{command:"usage",contract:AGENT_CONTRACTS.usage,handler:()=>readUsage(dispatcher)}],get queued(){return queued().length},dispatchNext:gate,close(){closed6=true;for(const e3 of entries.values())if(e3.state.kind==="queued")end2(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3)} started`});closing()}}}var refused2=(code,message2)=>new EpEnvelopeError(code,message2,void 0,"not-executed");var MODEL_LIST_MS=8500;function matchingChoices(choices,query){const needle=query.toLowerCase();const matches=choices.filter(({model})=>model.toLowerCase().includes(needle));matches.sort((a3,b3)=>a3.model===b3.model?0:a3.model===query?-1:b3.model===query?1:a3.model<b3.model?-1:1);return{items:matches.slice(0,AGENT_MODEL_CHOICES_MAX).map(({model,variants})=>({model,variants:[...variants].sort()})),more:matches.length>AGENT_MODEL_CHOICES_MAX}}function createModelLane(dispatcher,o3){let closed6=false;let tail=Promise.resolve();async function switchTo({model,variant}){if(!dispatcher?.setModel)throw refused2("unimplemented","this agent's harness cannot switch the model it runs");if(o3.policed!==void 0)throw refused2("failed-precondition",`this agent launched under modelPolicy.${o3.policed} in the Cotal configuration, which judges its model at launch only. Start a new agent on a model the policy allows.`);const cause=dispatcher.unsupported?.();if(cause!==void 0)throw refused2("unimplemented",`this agent's connector cannot switch its model now: ${cause}`);if(closed6)throw refused2("unavailable","this agent is stopping");let runs;try{runs=await dispatcher.setModel(model,variant)}catch(e3){const message2=String(e3?.message??e3);if(e3 instanceof CommandRefused)throw refused2(e3.code,`the harness refused the switch: ${message2}`);throw new EpEnvelopeError("internal",`the harness failed, so the model it runs is not known: ${message2}`,void 0,"unknown")}const switched={model:runs.model,...runs.variant!==void 0?{variant:runs.variant}:{}};try{await o3.show(switched)}catch(e3){o3.warn(`set-model: presence does not show ${switched.model} yet: ${e3.message}`)}return switched}async function list2(ctx){notSelf(ctx,"lists its own model choices");if(!o3.authed||!dispatcher?.setModel||!dispatcher.listModelChoices||dispatcher.unsupported?.()!==void 0)throw refused2("unimplemented","this agent does not serve live model choices");if(o3.policed!==void 0)throw refused2("failed-precondition","this agent's launch policy locks its model");if(closed6)throw refused2("unavailable","this agent is stopping");const{query}=ctx.request.args;const remaining=(ctx.request.deadlineMs??3e4)-(performance.now()-ctx.receivedAtMonotonicMs);if(remaining<=0)throw refused2("unavailable","the model choices request expired");const signal=AbortSignal.any([ctx.signal,AbortSignal.timeout(Math.ceil(Math.min(MODEL_LIST_MS,remaining)))]);let matches;try{matches=matchingChoices(await dispatcher.listModelChoices(signal),query?.trim()??"")}catch{throw refused2("unavailable","the harness could not list this session's model choices")}if(closed6||signal.aborted)throw refused2("unavailable","the model choices read ended before it could reply");const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};const answer2={runtime,...matches};if(matches.items.some(({variants})=>variants.length>AGENT_MODEL_CHOICE_VARIANTS_MAX))throw refused2("resource-exhausted","a model has too many variants to list");if(!ctx.replyFits(answer2,AGENT_MODEL_CHOICES_REPLY_MAX_BYTES))throw refused2("resource-exhausted","the model choices reply is too large; refine the search");return answer2}return{handler:{command:"set-model",contract:AGENT_CONTRACTS["set-model"],handler:ctx=>{notSelf(ctx,"switches its own model");const args=ctx.request.args;if(o3.exclusive)return o3.exclusive(()=>switchTo(args));const run=tail.then(()=>switchTo(args));tail=run.catch(()=>{});return run}},choices:{command:"model-choices",contract:AGENT_CONTRACTS["model-choices"],handler:list2},close(){closed6=true}}}var refused3=(code,message2,reason)=>new EpEnvelopeError(code,message2,reason?[{kind:AGENT_NAME_REFUSED_DETAIL,reason}]:void 0,"not-executed");function createNameLane(ep,warn,onNamed){let closed6=false;let tail=Promise.resolve();async function takenBy(name2){let roster;try{roster=await ep.readPresence()}catch(e3){throw refused3("unavailable",`the agent could not read who is present, so it cannot tell whether the name is free: ${e3.message}`)}const want=name2.toLowerCase();return roster.find(p2=>p2.status!=="offline"&&p2.card.id!==ep.card.id&&p2.card.name.toLowerCase()===want)?.card.id}async function setName(name2){try{assertValidName(name2)}catch(e3){throw refused3("bad-request",e3.message,"name-invalid")}if(closed6)throw refused3("unavailable","this agent is stopping");if(ep.card.name!==name2){const holder=await takenBy(name2);if(holder!==void 0)throw refused3("already-exists",`the live agent ${holder} is named ${JSON.stringify(name2)}`,"name-taken")}onNamed?.();if(ep.card.name===name2&&ep.card.meta?.[AGENT_LABEL_META_KEY]===void 0)return{name:name2};try{await ep.setCardName(name2,{[AGENT_LABEL_META_KEY]:void 0})}catch(e3){warn(`set-name: presence did not take "${name2}" yet: ${e3.message}`)}return{name:ep.card.name}}async function setLabel(label){try{assertValidLabel(label)}catch(e3){throw refused3("bad-request",e3.message)}if(closed6)throw refused3("unavailable","this agent is stopping");onNamed?.();try{await ep.setCardMeta({[AGENT_LABEL_META_KEY]:label})}catch(e3){warn(`set-label: presence did not take "${label}" yet: ${e3.message}`)}return{label}}const inTurn=run=>{const next=tail.then(run);tail=next.catch(()=>{});return next};return{handlers:[{command:"set-name",contract:AGENT_CONTRACTS["set-name"],handler:ctx=>inTurn(()=>setName(ctx.request.args.name))},{command:"set-label",contract:AGENT_CONTRACTS["set-label"],handler:ctx=>inTurn(()=>setLabel(ctx.request.args.label))}],close(){closed6=true}}}import{randomBytes as randomBytes5}from"node:crypto";var PROMPT_DESK_MIN_MAX_PAYLOAD=524288;var PROMPT_SUMMARY_MAX_BYTES=4096;var PROMPT_ANSWER_REPLY_MS=1e4;var PROMPT_OPEN_MS=Object.freeze({min:1e3,max:7*24*60*60*1e3});var PROMPT_SETTLE_MS=Object.freeze({min:1e3,max:24*60*60*1e3});var PromptRefused=class extends Error{reason;constructor(reason,message2){super(message2);this.reason=reason;this.name="PromptRefused"}};var NONE={tie:"none"};function stepPrompt(state,event,at2){const close=(outcome,attempted)=>({kind:"move",next:{kind:"closed",at:at2,outcome},end:{attempted}});if(state.kind==="open"){switch(event.kind){case"accept":return{kind:"move",next:{kind:"sent",answer:event.answer,delivery:"unconfirmed"},deliver:true};case"settle":{const e3=event.evidence;if(e3.kind==="local")return close({kind:"local",seen:e3.seen},false);if(e3.kind==="observed")return close(e3.seen.tie==="prompt"?{kind:"local",seen:e3.seen}:{kind:"withdrawn",seen:e3.seen},false);if(e3.kind==="withdrawn")return close({kind:"withdrawn",seen:NONE},false);return{kind:"stay",warn:"a confirmation came for a prompt with no accepted answer"}}case"expiry":return close({kind:"expired"},false);case"close":return close({kind:"withdrawn",seen:NONE},false);case"delivery":return{kind:"stay",warn:"a delivery result came for a prompt with no deliver call"};case"settle-time":return{kind:"cannot-happen",why:"the settle time starts at the accepted answer"}}}if(state.kind==="sent"){const answer2=state.answer;switch(event.kind){case"accept":return{kind:"never-reached",why:"an answer to a sent prompt meets check 3 or 4"};case"delivery":if(state.delivery==="delivered")return{kind:"cannot-happen",why:"deliver has one result"};if(event.result==="delivered")return{kind:"move",next:{kind:"sent",answer:answer2,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer:answer2},true);if(event.result==="gone")return close({kind:"undelivered",answer:answer2},true);return{kind:"stay",warn:"deliver failed, which proves nothing about the hand-over"};case"settle":{const e3=event.evidence;if(e3.kind==="confirmed")return close({kind:"answered",answer:answer2},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer2},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer:answer2,seen:e3.seen},true);return close({kind:"unconfirmed",answer:answer2,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer:answer2,seen:NONE},true)}}if(event.kind==="accept")return{kind:"never-reached",why:"an answer to a closed prompt meets check 3 or 4"};if(event.kind==="settle")return{kind:"stay",warn:"a report came for a closed prompt",report:true};return{kind:"stay"}}var iso=ms=>new Date(ms).toISOString();function describe(v3){try{if(v3 instanceof Error)return v3.message;const json2=JSON.stringify(v3);if(json2!==void 0)return json2.length>200?`${json2.slice(0,200)}...`:json2}catch{}try{return typeof v3==="bigint"?`${v3}n`:String(v3)}catch{return`a ${typeof v3} with no text form`}}function ignoreRejection(v3){try{const then=v3?.then;if(typeof then!=="function")return false;then.call(v3,void 0,()=>{})}catch{}return true}function deliveryKind(d2){try{return d2?.kind}catch{return void 0}}var B322="abcdefghijklmnopqrstuvwxyz234567";var EFFECTS=new Set(["proceed","refuse","cancel"]);function deepFreeze7(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze7(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused4(code,message2,details){return new EpEnvelopeError(code,message2,details,"not-executed")}function parseSeen(s3){const o3=s3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if(o3.tie==="none"&&keys===1)return{tie:"none"};if((o3.tie==="prompt"||o3.tie==="subject")&&keys===2&&EFFECTS.has(o3.effect))return{tie:o3.tie,effect:o3.effect}}throw new TypeError(`settle: ${describe(s3)} is not a sighting ({ tie: "prompt" | "subject", effect } or { tie: "none" })`)}function parseEvidence(e3){const o3=e3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if((o3.kind==="confirmed"||o3.kind==="withdrawn")&&keys===1)return{kind:o3.kind};if((o3.kind==="local"||o3.kind==="observed")&&keys===2)return{kind:o3.kind,seen:parseSeen(o3.seen)}}throw new TypeError(`settle: ${describe(e3)} is not an Evidence`)}var LONGEST_BY=Object.freeze({id:`${"w".repeat(64)}.${"w".repeat(64)}`,uid:"w".repeat(32),authority:"owner"});var ANY_AT="2000-01-01T00:00:00.000Z";var LONGEST_SEEN=Object.freeze({tie:"subject",effect:"proceed"});function largestSummaryBytes(base,options){let max=0;const measure=state=>{max=Math.max(max,Buffer.byteLength(JSON.stringify({...base,state})))};const closed6=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed6({kind:"expired"}));measure(closed6({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed6({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer2={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer:answer2,delivery:"unconfirmed"});measure({kind:"sent",answer:answer2,delivery:"delivered"});measure(closed6({kind:"answered",answer:answer2}));measure(closed6({kind:"unconfirmed",answer:answer2,seen:LONGEST_SEEN}));measure(closed6({kind:"undelivered",answer:answer2}));measure(closed6({kind:"local",seen:LONGEST_SEEN,late:answer2}))}return max}var Desk=class{ep;held=new Map;closedOrder=[];live=0;seq=0;stepping=false;later=[];presenceOwed=false;serving=false;closed=false;warn;constructor(ep,warn){this.ep=ep;this.warn=msg=>{try{warn(msg)}catch{}}}get waiting(){return this.live}handlers(){return[{command:"prompts",contract:AGENT_CONTRACTS.prompts,handler:ctx=>this.list(ctx)},{command:"prompt",contract:AGENT_CONTRACTS.prompt,handler:ctx=>this.read(ctx)},{command:"prompt-answer",contract:AGENT_CONTRACTS["prompt-answer"],handler:ctx=>this.answer(ctx)}]}served(ready){this.seq=this.ep.nextPromptsSeq();this.serving=true;ready.then(()=>{this.presenceOwed=true;this.flushPresence()},()=>{})}close(){if(this.closed)return;this.closed=true;this.defer(()=>{for(const h3 of[...this.held.values()])if(h3.state.kind!=="closed")this.apply(h3,{kind:"close"})})}open(spec,hooks){if(this.closed)throw new PromptRefused("closed","the prompt desk has closed; the harness answers this dialog");const invalid2=why=>new PromptRefused("invalid",why);if(!spec||typeof spec!=="object")throw invalid2("a prompt spec is an object");if(!hooks||typeof hooks.deliver!=="function"||typeof hooks.end!=="function"||hooks.check!==void 0&&typeof hooks.check!=="function")throw invalid2("hooks need deliver and end, and check when given, as functions");for(const[name2,value,range]of[["openMs",spec.openMs,PROMPT_OPEN_MS],["settleMs",spec.settleMs,PROMPT_SETTLE_MS]])if(!Number.isSafeInteger(value)||value<range.min||value>range.max)throw invalid2(`${name2} must be an integer from ${range.min} to ${range.max} ms, not ${String(value)}`);let canonical;try{canonical=canonicalJson(spec.content)}catch(e3){throw invalid2(`the content is not interchangeable JSON: ${describe(e3)}`)}const contentBytes=Buffer.byteLength(canonical);if(contentBytes>AGENT_PROMPT_CONTENT_MAX_BYTES)throw new PromptRefused("too-large",`the canonical content is ${contentBytes} bytes, over ${AGENT_PROMPT_CONTENT_MAX_BYTES}`);const content2=deepFreeze7(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content2);const now=Date.now();const openedAt=iso(now),expiresAtMs=now+spec.openMs,expiresAt=iso(expiresAtMs);const validate2=AGENT_CONTRACTS.prompt.output.validate;if(!validate2({prompt:{id:id2,digest,openedAt,expiresAt,state:{kind:"open"},content:content2}})){const first=validate2.errors?.[0];throw invalid2(`the content does not match the prompt schema: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const options=new Map;for(const o3 of content2.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content2.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content2.form!==void 0&&!content2.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content2.subject?.type==="tool"?content2.subject.input:void 0;if(input?.kind==="omitted"&&content2.options.some(o3=>o3.effect==="proceed"))throw invalid2("a tool input that is omitted can be refused remotely, never approved: no option may proceed");let form;if(content2.form!==void 0){const schema=content2.form.schema;for(const name2 of schema.required??[])if(!Object.hasOwn(schema.properties,name2))throw invalid2(`form.schema.required names "${name2}", which is not a property`);try{form=compileContractSchema({root:{...schema,additionalProperties:false}})}catch(e3){throw invalid2(`form.schema does not compile: ${describe(e3)}`)}}const base={id:id2,digest,openedAt,expiresAt,kind:content2.kind,title:content2.title,contentBytes,...content2.source!==void 0?{source:content2.source}:{}};const largest=largestSummaryBytes(base,content2.options);if(largest>PROMPT_SUMMARY_MAX_BYTES)throw new PromptRefused("too-large",`the summary encodes to ${largest} bytes in its largest state, over ${PROMPT_SUMMARY_MAX_BYTES}`);if(this.live>=AGENT_PROMPT_LIST_MAX)throw new PromptRefused("full",`${AGENT_PROMPT_LIST_MAX} prompts are open or sent`);const h3={id:id2,hooks,settleMs:spec.settleMs,expiresAtMs,base:deepFreeze7(base),live:{content:content2,options,...form?{form}:{}},state:deepFreeze7({kind:"open"}),reports:0,ended:false,waiters:new Set};this.held.set(id2,h3);this.live++;this.bump();h3.expiry=timer(Math.max(0,expiresAtMs-Date.now()),()=>this.expire(h3));if(!this.stepping)this.flushPresence();return Object.freeze({id:id2,settle:evidence=>{const e3=parseEvidence(evidence);this.defer(()=>this.apply(h3,{kind:"settle",evidence:e3}))}})}expire(h3){const left=h3.expiresAtMs-Date.now();if(left>0){h3.expiry=timer(left,()=>this.expire(h3));return}this.defer(()=>this.apply(h3,{kind:"expiry"}))}settleTime(h3){const left=h3.settleAtMs-Date.now();if(left>0){h3.settle=timer(left,()=>this.settleTime(h3));return}this.defer(()=>this.apply(h3,{kind:"settle-time"}))}run(fn2){if(this.stepping)throw new Error("prompt desk: a step started inside another step");this.stepping=true;try{return fn2()}finally{try{for(let next=this.later.shift();next;next=this.later.shift())next()}finally{this.stepping=false;this.flushPresence()}}}defer(fn2){if(this.stepping)this.later.push(fn2);else this.run(fn2)}apply(h3,event,why){const step=stepPrompt(h3.state,event,iso(Date.now()));if(step.kind==="cannot-happen"||step.kind==="never-reached"){this.warn(`prompt desk bug: event ${event.kind} met prompt ${h3.id} in state ${h3.state.kind}, a row that ${step.kind==="cannot-happen"?"cannot happen":"is never reached"}: ${step.why}`);return}if(step.kind==="stay"){if(step.report)this.warn(`prompt ${h3.id} is closed, so a "${event.evidence.kind}" report is ignored (${++h3.reports} so far)`);else if(step.warn)this.warn(`prompt ${h3.id}: ${step.warn}${why?`: ${why}`:""}`);if(event.kind==="delivery"&&event.result==="failed")this.answerWaiters(h3);return}h3.state=deepFreeze7(step.next);this.bump();if(h3.state.kind==="closed")this.retire(h3);if(!(h3.state.kind==="sent"&&h3.state.delivery==="unconfirmed"))this.answerWaiters(h3);if(step.end)this.end(h3,step.end.attempted)}answerWaiters(h3){for(const w2 of h3.waiters){clearTimeout(w2.timer);w2.resolve(h3.state)}h3.waiters.clear()}retire(h3){clearTimeout(h3.expiry);clearTimeout(h3.settle);h3.live=void 0;this.live--;this.closedOrder.push(h3.id);while(this.closedOrder.length>AGENT_PROMPT_LIST_MAX)this.held.delete(this.closedOrder.shift())}end(h3,attempted){if(h3.ended){this.warn(`prompt desk bug: prompt ${h3.id} ended twice`);return}h3.ended=true;const hooks=h3.hooks;h3.hooks=void 0;try{ignoreRejection(hooks.end({attempted}))}catch(e3){this.warn(`prompt ${h3.id}: the adapter's end threw: ${describe(e3)}`)}}bump(){this.seq=this.ep.nextPromptsSeq();this.presenceOwed=true}flushPresence(){if(!this.presenceOwed||this.closed||!this.serving)return;this.presenceOwed=false;this.ep.setPromptsPresence({open:this.live,seq:this.seq}).catch(e3=>{if(!this.closed)this.warn(`the prompts presence field was not written: ${describe(e3)}`)})}fit(ctx,data){if(ctx.replyFits(data,Number.MAX_SAFE_INTEGER))return data;const bytes=Buffer.byteLength(JSON.stringify({v:1,id:ctx.request.id,ok:true,data}));const limit=this.ep.maxPayload;throw refused4("resource-exhausted",`the reply is ${bytes} bytes, over this connection's max_payload of ${limit}`,[{kind:AGENT_PROMPT_SIZE_DETAIL,bytes,limit}])}summary(h3){return{...h3.base,state:h3.state}}list(ctx){const open7=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open7.push(this.summary(h3));const closed6=this.closedOrder.map(id2=>this.summary(this.held.get(id2)));const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};return this.fit(ctx,{runtime,seq:this.seq,open:open7,closed:closed6})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused4("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused4("failed-precondition",`prompt ${id2} is closed`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);const{digest,openedAt,expiresAt}=h3.base;return this.fit(ctx,{prompt:{id:id2,digest,openedAt,expiresAt,state:h3.state,content:h3.live.content}})}answer(ctx){const got=this.run(()=>this.decide(ctx));return got instanceof Promise?got.then(state=>({state})):{state:got}}decide(ctx){const a3=ctx.request.args;try{canonicalJson(a3)}catch(e3){throw refused4("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused4("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused4("not-found",`prompt ${a3.id} is not known to this runtime`);const fingerprint=answerFingerprint(a3,ctx.caller);if(h3.fingerprint===fingerprint)return h3.state;if(h3.state.kind!=="open"||h3.live===void 0)throw refused4("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused4("failed-precondition",`the digest is not prompt ${a3.id}'s`,[{kind:AGENT_PROMPT_DIGEST_DETAIL,digest:h3.base.digest}]);const option=h3.live.options.get(a3.option);if(option===void 0)throw refused4("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused4("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused4("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused4("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused4("bad-request",`option "${option.id}" takes no values`);if(a3.values!==void 0&&!h3.live.form(a3.values)){const first=h3.live.form.errors?.[0];throw refused4("bad-request",`the values do not match the form: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const by={id:`${ctx.caller.owner}.${ctx.caller.actor}`,uid:ctx.caller.uid,authority:ctx.authority};const verdict=deepFreeze7({option:option.id,...a3.note!==void 0?{note:a3.note}:{},...a3.values!==void 0?{values:structuredClone(a3.values)}:{},by});let refusal;try{refusal=h3.hooks.check?.(verdict)}catch(e3){this.warn(`prompt ${h3.id}: the adapter's check threw: ${describe(e3)}`);throw refused4("internal",`the agent could not check this answer: ${describe(e3)}`)}if(refusal!==void 0){if(typeof refusal!=="string"){this.warn(`prompt ${h3.id}: the adapter's check returned ${ignoreRejection(refusal)?"a promise, and check is synchronous":`${typeof refusal}, not a message or undefined`}`);throw refused4("internal","the agent could not check this answer")}throw refused4("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused4("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer2={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer:answer2},answer2.at);if(step.kind!=="move"||!step.deliver)throw refused4("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze7(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve3=>{const w2={resolve:resolve3,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve3(h3.state)}))};h3.waiters.add(w2)});this.deliver(h3,verdict);return wait}deliver(h3,verdict){let result;try{result=Promise.resolve(h3.hooks.deliver(verdict))}catch(e3){result=Promise.reject(e3)}const failed=why=>this.defer(()=>this.apply(h3,{kind:"delivery",result:"failed"},why));result.then(d2=>{const kind=deliveryKind(d2);if(kind==="confirmed"||kind==="delivered"||kind==="gone")this.defer(()=>this.apply(h3,{kind:"delivery",result:kind}));else failed(`deliver resolved with ${describe(d2)}, which is not a Delivery`)},e3=>failed(describe(e3))).catch(e3=>this.warn(`prompt desk bug: applying prompt ${h3.id}'s delivery result threw: ${describe(e3)}`))}};function answerFingerprint(a3,caller2){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller2.owner}.${caller2.actor}.${caller2.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}import{createHash as createHash9}from"node:crypto";var STEER_HANDOVER_MS=1e4;var STEER_MIN_BUDGET_MS=11e3;var STEER_KEY_TAIL_MS=6e4;var STEER_KEYS_MAX=256;var STEER_MESSAGE_MAX_BYTES=512;var STEER_STATE_DETAIL="ai.cotal.agent.steer-state";var STEER_KEY_CONFLICT_DETAIL="ai.cotal.agent.steer-key-conflict";var SteerRefused=class extends Error{name="SteerRefused"};var B323="abcdefghijklmnopqrstuvwxyz234567";var runKey=r2=>`${r2.threadId}\0${r2.runId}`;var sha=text5=>createHash9("sha256").update(text5,"utf8").digest("hex");function mintSteerId(){const bytes=new Uint8Array(26);crypto.getRandomValues(bytes);let id2="";for(const b3 of bytes)id2+=B323[b3&31];return id2}function steerMessage(message2){const enc10=new TextEncoder;if(enc10.encode(message2).byteLength<=STEER_MESSAGE_MAX_BYTES)return message2;let out="";for(const ch of message2){if(enc10.encode(out+ch+"\u2026").byteLength>STEER_MESSAGE_MAX_BYTES)break;out+=ch}return`${out}\u2026`}var refuse2=(code,message2,detail,outcome="not-executed")=>({ok:false,code,outcome,message:steerMessage(message2),...detail?{detail}:{}});var servesSteer=d2=>d2!==void 0&&typeof d2.steerTarget==="function"&&typeof d2.steer==="function"&&d2.unsupported?.()===void 0;var SteerLane=class{opts;now;mintId;keys=new Map;refusals=new Map;attachments=new Set;withHarness;constructor(opts={}){this.opts=opts;this.now=opts.now??(()=>performance.now());this.mintId=opts.mintId??mintSteerId}attach(dispatcher){const a3={dispatcher,open:true};this.attachments.add(a3);return{served:()=>a3.open&&servesSteer(dispatcher),steer:(req,budget3,signal)=>this.steer(a3,req,budget3,signal),detach:()=>{a3.open=false;this.attachments.delete(a3)}}}get held(){this.expire();return this.keys.size+this.refusals.size+this.laterReplies}laterReplies=0;get busy(){return this.withHarness!==void 0}steer(a3,req,budget3,signal){if(req.self)return Promise.resolve(refuse2("permission-denied","an agent never steers its own turn"));if(!isWellFormedUnicode(req.text))return Promise.resolve(refuse2("bad-request","the text is not well-formed Unicode"));this.expire();const deadlineAt=budget3.receivedAt+budget3.deadlineMs;const kept=this.refusals.get(req.envelopeId);if(kept)return Promise.resolve(kept.answer);const bound=this.keys.get(req.key);if(bound)return this.repeat(bound,req,deadlineAt);return Promise.resolve(this.admit(a3,req,budget3,deadlineAt,signal))}repeat(bound,req,deadlineAt){bound.heldUntil=Math.max(bound.heldUntil,deadlineAt);if(req.envelopeId===bound.firstEnvelope)return bound.first;const earlier=bound.replies.get(req.envelopeId);if(earlier)return Promise.resolve(earlier);let answer2;if(bound.digest!==sha(req.text)||bound.run!==runKey(req.run)){answer2=refuse2("bad-request","this key already names another steer; mint a new key for every steer",{kind:STEER_KEY_CONFLICT_DETAIL,heldId:bound.id,heldState:bound.state})}else{const detail=(state,code)=>({kind:STEER_STATE_DETAIL,id:bound.id,state,...code?{code}:{}});switch(bound.state){case"delivered":answer2={ok:true,id:bound.id,delivered:"running-turn"};break;case"refused":answer2=refuse2("failed-precondition","the harness refused this steer; nothing was delivered",detail("refused","failed-precondition"));break;case"unknown":answer2=refuse2("internal","this steer's outcome is not known; it may have been delivered",detail("unknown"));break;default:answer2=refuse2("unavailable","this steer is still with the harness; ask again with the same key once it settles",detail("handed-over"))}}if(this.held<STEER_KEYS_MAX){bound.replies.set(req.envelopeId,answer2);this.laterReplies++}return Promise.resolve(answer2)}admit(a3,req,budget3,deadlineAt,signal){const atCap=this.held>=STEER_KEYS_MAX;const preRefuse=(code,message2)=>{const answer2=refuse2(code,message2);if(!atCap)this.refusals.set(req.envelopeId,{answer:answer2,heldUntil:deadlineAt});return answer2};const d2=a3.dispatcher;if(!servesSteer(d2)||d2===void 0){const cause=d2?.unsupported?.();return preRefuse("unimplemented",cause===void 0?"this agent's connector cannot steer a turn":`this agent's connector cannot steer a turn now: ${cause}`)}if(!a3.open||signal?.aborted)return preRefuse("unavailable","this agent's endpoint is closing");if(atCap)return refuse2("resource-exhausted","this agent holds too many steer keys now; try again shortly",void 0,"unknown");let handle;try{handle=d2.steerTarget(req.run)}catch(e3){if(e3 instanceof SteerRefused)return preRefuse("failed-precondition",`that run is not the one running: ${e3.message}`);this.opts.warn?.(`steerTarget failed: ${String(e3?.message??e3)}`);return preRefuse("failed-precondition","the connector could not resolve that run")}if(!a3.open||signal?.aborted)return preRefuse("unavailable","this agent's endpoint is closing");if(this.withHarness)return preRefuse("unavailable","another steer is still with the harness; once it settles, send these words again under a new key");const remaining=budget3.deadlineMs-(this.now()-budget3.receivedAt);if(remaining<STEER_MIN_BUDGET_MS)return preRefuse("unavailable","too little of the request's time is left to hand the steer over");return this.handOver(req,deadlineAt,d2,handle)}handOver(req,deadlineAt,d2,handle){const id2=this.mintId();let resolve3;const first=new Promise(r2=>resolve3=r2);const bound={key:req.key,id:id2,digest:sha(req.text),run:runKey(req.run),state:"handed-over",firstEnvelope:req.envelopeId,first,replies:new Map,heldUntil:deadlineAt};this.keys.set(req.key,bound);this.withHarness=bound;const detail=(state,code)=>({kind:STEER_STATE_DETAIL,id:id2,state,...code?{code}:{}});let replied=false;const reply3=(state,answer2)=>{if(replied)return;replied=true;bound.state=state;clearTimeout(timer2);resolve3(answer2)};const native=(state,answer2)=>{bound.nativeAt=this.now();if(this.withHarness===bound)this.withHarness=void 0;if(replied){if(bound.state!==state)this.opts.warn?.(`steer ${id2}: the harness answered ${state} after the lane replied ${bound.state}; the key keeps ${bound.state}`);return}reply3(state,answer2)};const timer2=setTimeout(()=>reply3("unknown",refuse2("internal","the harness did not answer in time; the steer may have been delivered",detail("unknown"),"unknown")),STEER_HANDOVER_MS);timer2.unref?.();let call;try{call=d2.steer(handle,{id:id2,text:req.text})}catch(e3){call=Promise.reject(e3)}call.then(()=>native("delivered",{ok:true,id:id2,delivered:"running-turn"}),e3=>{if(e3 instanceof SteerRefused)native("refused",refuse2("failed-precondition","the harness refused this steer; nothing was delivered",detail("refused","failed-precondition")));else{this.opts.warn?.(`steer ${id2}: the harness failed: ${String(e3?.message??e3)}`);native("unknown",refuse2("internal","the harness failed; the steer may have been delivered",detail("unknown"),"unknown"))}});return first}expire(){const now=this.now();for(const[k2,b3]of this.keys){if(b3.nativeAt===void 0)continue;if(Math.max(b3.heldUntil,b3.nativeAt)+STEER_KEY_TAIL_MS>now)continue;this.laterReplies-=b3.replies.size;this.keys.delete(k2)}for(const[env,r2]of this.refusals)if(r2.heldUntil+STEER_KEY_TAIL_MS<=now)this.refusals.delete(env)}};var lanes=new Map;function steerLaneFor(runtimeId,warn){let lane=lanes.get(runtimeId);if(!lane){lane=new SteerLane({warn});lanes.set(runtimeId,lane)}return lane}function steerHandler(steer){return{command:"steer",contract:AGENT_CONTRACTS.steer,handler:async ctx=>{const args=ctx.request.args;const self3=ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor;const answer2=await steer.steer({text:args.text,run:args.run,key:args.key,envelopeId:ctx.request.id,self:self3},{deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs},ctx.signal);if(answer2.ok)return{id:answer2.id,delivered:answer2.delivered};throw new EpEnvelopeError(answer2.code,answer2.message,answer2.detail?[answer2.detail]:void 0,answer2.outcome)}}}var OPTION_WRITE_MS=1e4;var OPTION_READ_MS=5e3;var OPTION_REPLY_RESERVE_MS=1e3;var OPTION_WRITE_MIN_BUDGET_MS=OPTION_WRITE_MS+OPTION_REPLY_RESERVE_MS;var OPTION_UNSETTLED_DETAIL="ai.cotal.agent.option-unsettled";var OPTIONS_MAX=16;var CHOICES_MAX=16;var OPTION_RECORDS_MAX=16;var OptionRefused=class extends Error{code;name="OptionRefused";constructor(message2,code="failed-precondition"){super(message2);this.code=code}};function optionFlags(d2){const now=d2!==void 0&&d2.unsupported?.()===void 0;const options=now&&typeof d2.options==="function";const wantsWrite=d2!==void 0&&typeof d2.setOption==="function";const setOption=options&&wantsWrite&&typeof d2.watchOptions==="function";const fault=wantsWrite&&(typeof d2.options!=="function"||typeof d2.watchOptions!=="function")?"the connector offers setOption without options and watchOptions, so set-option is not served":void 0;return{options,setOption,...fault?{fault}:{}}}var ID2=/^[a-z0-9-]{1,64}$/;var text4=n2=>new RegExp(`^[^\\p{Cc}\\p{Cs}\\p{Co}\\p{Cn}\\u2028\\u2029]{1,${n2}}$`,"u");var NAME3=text4(80);var LONG=text4(200);var TOKEN2=/^[^\s\p{C}]{1,64}$/u;var REVERSE_DNS2=/^[a-z0-9-]{1,63}\.[a-z0-9.-]{1,63}$/;var SELECT_KEYS=new Set(["id","name","description","category","type","applies","value","pending","choices","locked"]);var BOOLEAN_KEYS=new Set(["id","name","description","category","type","applies","value","pending","locked"]);var CHOICE_KEYS=new Set(["value","name","description"]);function optionFault(o3){if(typeof o3!=="object"||o3===null||Array.isArray(o3))return"an option is not an object";const r2=o3;const at2=typeof r2.id==="string"?`option ${JSON.stringify(r2.id)}`:"an option";if(typeof r2.id!=="string"||!ID2.test(r2.id))return`${at2}: id does not match ${ID2.source}`;const keys=r2.type==="select"?SELECT_KEYS:r2.type==="boolean"?BOOLEAN_KEYS:void 0;if(!keys)return`${at2}: type is neither select nor boolean`;const extra=Object.keys(r2).find(k2=>!keys.has(k2));if(extra!==void 0)return`${at2}: ${extra==="unsettled"?"unsettled is the lane's to write":`unknown field ${extra}`}`;if(typeof r2.name!=="string"||!NAME3.test(r2.name))return`${at2}: name is not one line of 1 to 80 code points`;for(const f2 of["description","locked"])if(r2[f2]!==void 0&&(typeof r2[f2]!=="string"||!LONG.test(r2[f2])))return`${at2}: ${f2} is not one line of 1 to 200 code points`;if(r2.category!==void 0&&(typeof r2.category!=="string"||r2.category!=="mode"&&!(r2.category.length<=64&&REVERSE_DNS2.test(r2.category))))return`${at2}: category is neither mode nor a name in the Cotal namespace grammar`;if(r2.applies!=="now"&&r2.applies!=="next-turn")return`${at2}: applies is neither now nor next-turn`;if(r2.applies==="now"&&r2.pending!==void 0)return`${at2}: pending with applies now`;const valueOk=v3=>r2.type==="select"?typeof v3==="string"&&TOKEN2.test(v3):typeof v3==="boolean";if(!valueOk(r2.value))return`${at2}: value is not a ${r2.type==="select"?"token":"boolean"}`;if(r2.pending!==void 0&&!valueOk(r2.pending))return`${at2}: pending is not a ${r2.type==="select"?"token":"boolean"}`;if(r2.type==="select"){if(!Array.isArray(r2.choices)||r2.choices.length<1||r2.choices.length>CHOICES_MAX)return`${at2}: choices is not 1 to ${CHOICES_MAX} entries`;const seen=new Set;for(const c3 of r2.choices){if(typeof c3!=="object"||c3===null||Array.isArray(c3))return`${at2}: a choice is not an object`;const cr2=c3;const cx=Object.keys(cr2).find(k2=>!CHOICE_KEYS.has(k2));if(cx!==void 0)return`${at2}: a choice has unknown field ${cx}`;if(typeof cr2.value!=="string"||!TOKEN2.test(cr2.value))return`${at2}: a choice value is not a token`;if(typeof cr2.name!=="string"||!NAME3.test(cr2.name))return`${at2}: choice ${JSON.stringify(cr2.value)} name is not one line of 1 to 80 code points`;if(cr2.description!==void 0&&(typeof cr2.description!=="string"||!LONG.test(cr2.description)))return`${at2}: choice ${JSON.stringify(cr2.value)} description is not one line of 1 to 200 code points`;if(seen.has(cr2.value))return`${at2}: choice value ${JSON.stringify(cr2.value)} repeats`;seen.add(cr2.value)}}return void 0}function listFault(list2){if(!Array.isArray(list2))return"the list is not an array";if(list2.length>OPTIONS_MAX)return`the list has ${list2.length} options, over ${OPTIONS_MAX}`;const ids=new Set;for(const o3 of list2){const f2=optionFault(o3);if(f2)return f2;const id2=o3.id;if(ids.has(id2))return`option id ${JSON.stringify(id2)} repeats`;ids.add(id2)}return void 0}var fail3=(code,message2,outcome="not-executed",detail)=>({ok:false,code,outcome,message:message2,...detail?{detail}:{}});var OptionLane=class{opts;now;seqValue=0;records=new Map;fifo=[];busy=false;attached=0;watched;watching=false;runtime;dispatcher;seqListeners=new Set;constructor(opts){this.opts=opts;this.now=opts.now??(()=>performance.now());this.runtime=opts.runtime}bindRuntime(runtime){this.runtime??={id:runtime.id,startedAt:runtime.startedAt}}get seq(){return this.seqValue}get open(){return this.attached>0}flags(){const{options,setOption}=optionFlags(this.dispatcher);return{options,setOption}}attach(dispatcher,onSeq){this.attached++;this.dispatcher=dispatcher;if(onSeq)this.seqListeners.add(onSeq);const d2=this.dispatcher;if(!this.watching||this.watched!==d2){this.watching=true;this.watched=d2;const f2=optionFlags(d2);if(f2.fault)this.opts.warn?.(f2.fault);d2?.watchOptions?.(()=>{if(this.watched===d2)this.bump()})}this.bump();let done=false;return()=>{if(done)return;done=true;this.attached--;if(onSeq)this.seqListeners.delete(onSeq);if(this.attached===0)for(const j2 of this.fifo.splice(0)){clearTimeout(j2.timer);j2.refuse()}}}bump(){this.seqValue++;this.opts.onSeq?.(this.seqValue);for(const f2 of this.seqListeners)f2(this.seqValue)}remaining(b3){return b3.deadlineMs-(this.now()-b3.receivedAt)}enqueue(job,need){job.timer=setTimeout(()=>{const i2=this.fifo.indexOf(job);if(i2<0)return;this.fifo.splice(i2,1);job.refuse()},Math.max(0,this.remaining(job.budget)-need));job.timer.unref?.();this.fifo.push(job);this.next()}next(){while(!this.busy&&this.fifo.length>0){const job=this.fifo.shift();clearTimeout(job.timer);const need=job.kind==="write"?OPTION_WRITE_MIN_BUDGET_MS:job.kind==="read"?OPTION_REPLY_RESERVE_MS:0;if(job.kind!=="model"&&this.remaining(job.budget)<need){job.refuse();continue}this.busy=true;let released=false;job.start(()=>{if(released)return;released=true;this.busy=false;this.next()})}}runExclusive(fn2){return new Promise((resolve3,reject)=>{this.fifo.push({kind:"model",budget:{deadlineMs:Number.MAX_SAFE_INTEGER,receivedAt:this.now()},start:release=>{const bound=setTimeout(()=>{this.opts.warn?.(`set-model: the harness did not answer within ${OPTION_WRITE_MS} ms; the lane goes on`);release()},OPTION_WRITE_MS);bound.unref?.();let run;try{run=fn2()}catch(e3){run=Promise.reject(e3)}run.then(resolve3,reject).finally(()=>{clearTimeout(bound);release()})},refuse:()=>reject(new EpEnvelopeError("unavailable","this agent is stopping",void 0,"not-executed"))});this.next()})}overlayState(){const unsettled=new Map;for(const r2 of this.records.values())if(r2.phase==="unsettled")unsettled.set(r2.id,r2.value);return unsettled}async snapshot(d2,bound){for(let attempt=0;;attempt++){const before=this.seqValue;const read=await withBound(d2.options(),Math.max(1,bound()));if(this.seqValue===before||attempt===2){return{read,seq:this.seqValue,unsettled:this.overlayState()}}}}overlay(read,s3){const listed=new Set;const options=read.supported?read.options.map(o3=>{const u2=s3.unsettled.get(o3.id);if(u2===void 0||typeof u2!==typeof o3.value)return o3;listed.add(o3.id);return{...o3,unsettled:u2}}):[];const unlisted=[...s3.unsettled].filter(([id2])=>!listed.has(id2)).map(([id2,value])=>({id:id2,value}));const base={runtime:this.runtime??{id:"unbound",startedAt:0},seq:s3.seq,...unlisted.length?{unlisted}:{}};return read.supported?{supported:true,...base,options}:{supported:false,...base}}readFault(read){if(typeof read!=="object"||read===null||Array.isArray(read))return"the read is not an object";const r2=read;if(r2.supported!==true&&r2.supported!==false)return"the read is neither supported nor unsupported";const extra=Object.keys(r2).find(k2=>k2!=="supported"&&!(k2==="options"&&r2.supported===true));if(extra!==void 0)return`the read carries ${extra==="unlisted"?"unlisted, which is the lane's to write":`unknown field ${extra}`}`;if(r2.supported)return listFault(r2.options);return void 0}async readOnce(bound){const d2=this.dispatcher;if(bound<=0)return fail3("unavailable","too little of the request's time is left to read the settings");const started=this.now();let s3;try{s3=await this.snapshot(d2,()=>bound-(this.now()-started))}catch(e3){return fail3("unavailable",`the harness did not answer the read: ${String(e3?.message??e3)}`)}const f2=this.readFault(s3.read);if(f2)return this.fault(f2);return{ok:true,data:this.overlay(s3.read,s3)}}fault(why){this.opts.warn?.(`options: the connector's read was refused: ${why}`);return fail3("internal",`the connector's read broke the settings contract: ${why}`)}refusalBefore(self3,what2){if(self3)return fail3("permission-denied",`an agent never ${what2} its own settings`);return this.refusalNow()}refusalNow(signal){const d2=this.dispatcher;const cause=d2?.unsupported?.();if(cause!==void 0)return fail3("unimplemented",`this agent's connector cannot read or write its settings now: ${cause}`);if(d2===void 0||typeof d2.options!=="function")return fail3("unimplemented","this agent's connector does not serve settings");if(this.attached===0||signal?.aborted)return fail3("unavailable","this agent is stopping");return void 0}options(budget3,self3,signal){const early=this.refusalBefore(self3,"reads")??(signal?.aborted?fail3("unavailable","this agent is stopping"):void 0);if(early)return Promise.resolve(early);if(this.remaining(budget3)-OPTION_REPLY_RESERVE_MS<=0)return Promise.resolve(fail3("unavailable","too little of the request's time is left to read the settings"));return new Promise(resolve3=>{this.enqueue({kind:"read",budget:budget3,start:release=>{const now=this.refusalNow(signal);if(now){release();resolve3(now);return}const bound=Math.min(OPTION_READ_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS);void this.readOnce(bound).then(a3=>{release();resolve3(a3)})},refuse:()=>resolve3(fail3("unavailable","the settings were not read in time"))},OPTION_REPLY_RESERVE_MS)})}setOption(id2,value,budget3,self3,signal){const early=this.refusalBefore(self3,"writes")??(signal?.aborted?fail3("unavailable","this agent is stopping"):void 0);if(early)return Promise.resolve(early);const d2=this.dispatcher;if(!optionFlags(d2).setOption)return Promise.resolve(fail3("unimplemented","this agent's connector reads its settings but does not write them"));const held2=this.records.get(id2);if(held2)return Promise.resolve(fail3("failed-precondition","an earlier write to this option is not settled yet","not-executed",{kind:OPTION_UNSETTLED_DETAIL,id:id2,value:held2.value}));if(this.records.size>=OPTION_RECORDS_MAX)return Promise.resolve(fail3("resource-exhausted",`this agent holds ${OPTION_RECORDS_MAX} writes not yet settled`));if(this.remaining(budget3)<OPTION_WRITE_MIN_BUDGET_MS)return Promise.resolve(fail3("unavailable","too little of the request's time is left to write the setting"));const record3={id:id2,value,phase:"reserved"};this.records.set(id2,record3);return new Promise(resolve3=>{const drop=()=>{if(this.records.get(id2)===record3){this.records.delete(id2)}};this.enqueue({kind:"write",budget:budget3,start:release=>this.take(record3,budget3,release,resolve3,signal),refuse:()=>{drop();resolve3(fail3("unavailable","the write did not get its turn in time"))}},OPTION_WRITE_MIN_BUDGET_MS)})}take(record3,budget3,release,resolve3,signal){const now=this.refusalNow(signal)??(optionFlags(this.dispatcher).setOption?void 0:fail3("unimplemented","this agent's connector does not write its settings now"));if(now){if(this.records.get(record3.id)===record3)this.records.delete(record3.id);release();resolve3(now);return}const d2=this.dispatcher;record3.phase="active";let replied=false;const end2=()=>{if(this.records.get(record3.id)===record3){this.records.delete(record3.id);this.bump()}};const leaveUnknown=why=>{if(replied)return;replied=true;if(record3.phase==="active"){record3.phase="unsettled";this.bump()}release();resolve3(fail3("internal",`${why}; the setting may change later`,"unknown"))};const timer2=setTimeout(()=>leaveUnknown("the harness did not confirm the write in time"),Math.min(OPTION_WRITE_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS));timer2.unref?.();let call;try{call=d2.setOption(record3.id,record3.value)}catch(e3){call=Promise.reject(e3)}call.then(async()=>{clearTimeout(timer2);if(replied){this.opts.warn?.(`set-option ${record3.id}: a late confirmation ended its record`);end2();return}replied=true;end2();const confirmedButUnread=()=>fail3("internal","the harness confirmed the write, but the settings could not be read back","executed");try{const s3=await this.snapshot(d2,()=>Math.min(OPTION_READ_MS,this.remaining(budget3)-OPTION_REPLY_RESERVE_MS));release();const read=s3.read;if(this.readFault(s3.read)!==void 0||!read.supported||!read.options.some(o3=>o3.id===record3.id)){resolve3(confirmedButUnread());return}const out=this.overlay(read,s3);resolve3({ok:true,data:{runtime:out.runtime,seq:out.seq,written:record3.id,options:out.options,...out.unlisted?{unlisted:out.unlisted}:{}}})}catch{release();resolve3(confirmedButUnread())}},e3=>{clearTimeout(timer2);if(e3 instanceof OptionRefused){if(replied){this.opts.warn?.(`set-option ${record3.id}: a late refusal ended its record`);end2();return}replied=true;end2();release();resolve3(fail3(e3.code,`the harness refused the write: ${e3.message}`));return}this.opts.warn?.(`set-option ${record3.id}: the harness failed: ${String(e3?.message??e3)}`);leaveUnknown("the harness failed")}).catch(e3=>this.opts.warn?.(`set-option ${record3.id}: ${String(e3?.message??e3)}`))}};function withBound(p2,ms){let timer2;const late2=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms} ms`)),ms);timer2.unref?.()});return Promise.race([p2,late2]).finally(()=>clearTimeout(timer2))}var lanes2=new Map;function optionLaneFor(runtimeId,o3){let lane=lanes2.get(runtimeId);if(!lane){lane=new OptionLane({warn:o3.warn});lanes2.set(runtimeId,lane)}return lane}var self2=ctx=>ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor;var budget=ctx=>({deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs});var bind=(lane,ctx)=>lane.bindRuntime({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function reply(a3){if(a3.ok)return a3.data;throw new EpEnvelopeError(a3.code,a3.message,a3.detail?[a3.detail]:void 0,a3.outcome)}function optionHandlers(lane){return[{command:"options",contract:AGENT_CONTRACTS.options,handler:async ctx=>{bind(lane,ctx);return reply(await lane.options(budget(ctx),self2(ctx),ctx.signal))}},{command:"set-option",contract:AGENT_CONTRACTS["set-option"],handler:async ctx=>{bind(lane,ctx);const{id:id2,value}=ctx.request.args;return reply(await lane.setOption(id2,value,budget(ctx),self2(ctx),ctx.signal))}}]}import{createHmac as createHmac2,randomBytes as randomBytes6}from"node:crypto";var NATIVE_HARNESS_MS=1e4;var NATIVE_REPLY_RESERVE_MS=1e3;var NATIVE_CURSORS_MAX=64;var NATIVE_ROWS_KEPT=4096;var NativeRefused=class extends Error{code;name="NativeRefused";constructor(message2,code="failed-precondition"){super(message2);this.code=code}};function nativeFlags(d2,authed){const nativeControls=authed&&d2!==void 0&&d2.unsupported?.()===void 0&&d2.kinds.size>0&&typeof d2.read==="function";const nativeActions=nativeControls&&typeof d2.act==="function"&&(d2.actions?.size??0)>0;return{nativeControls,nativeActions}}var fail4=(code,message2,outcome="not-executed")=>({ok:false,code,outcome,message:message2});var utf82=s3=>new TextEncoder().encode(s3).length;var keyOf2=(n2=24)=>randomBytes6(n2).toString("base64url");var SIGN_IN_URL=new RegExp(AGENT_NATIVE_SIGN_IN_URL_PATTERN);var LATEST_MS=Date.UTC(9999,11,31,23,59,59,999);var validMs=v3=>typeof v3==="number"&&Number.isFinite(v3)&&v3>=0&&v3<=LATEST_MS?v3:void 0;var iso2=ms=>new Date(ms).toISOString();var NativeLane=class{opts;now;wall;salt=randomBytes6(32);seqValue=0;attached=0;authed=false;generation=0;dispatcher;watched;runtime;views=new Map;viewTicket=new Map;ticket=0;cursors=new Map;records=new Map;slot;listeners=new Set;constructor(opts={}){this.opts=opts;this.now=opts.now??(()=>performance.now());this.wall=opts.wall??(()=>Date.now())}get seq(){return this.seqValue}flags(){return nativeFlags(this.dispatcher,this.authed)}bindRuntime(runtime){this.runtime??={id:runtime.id,startedAt:runtime.startedAt}}attach(dispatcher,authed,onSeq){this.attached++;this.dispatcher=dispatcher;this.authed=authed;if(onSeq)this.listeners.add(onSeq);if(dispatcher&&this.watched!==dispatcher){this.watched=dispatcher;dispatcher.watchNative?.(()=>{if(this.watched===dispatcher)this.changed()})}this.changed();let done=false;return()=>{if(done)return;done=true;this.attached--;if(onSeq)this.listeners.delete(onSeq);this.generation++}}changed(){this.generation++;this.views.clear();this.viewTicket.clear();this.cursors.clear();this.bump()}bump(){this.seqValue++;for(const f2 of this.listeners)f2(this.seqValue)}remaining(b3){return b3.deadlineMs-(this.now()-b3.receivedAt)}warn(message2){this.opts.warn?.(message2)}gate(c3,runtimeId,what2){if(c3.self)return fail4("permission-denied",`an agent never ${what2} its own native controls`);if(runtimeId!==c3.runtimeId)return fail4("failed-precondition","the runtime named is not the one serving this request; read presence and ask the current runtime");const d2=this.dispatcher;if(!this.authed)return fail4("unimplemented","native controls are served only where the mesh authenticates the agent's owner");if(d2?.unsupported?.()!==void 0)return fail4("unimplemented","this agent's connector serves no native controls now");if(!this.flags().nativeControls)return fail4("unimplemented","this agent's connector serves no native controls");if(this.attached===0)return fail4("unavailable","this agent is stopping");return void 0}revisionOf(scope,snapshot,generation){return createHmac2("sha256",this.salt).update(`${generation}\0${scope}\0${snapshot}`).digest("base64url").slice(0,32)}fault(why){this.warn(`native-controls: the connector's read was refused: ${why}`);return fail4("internal",`the connector's read broke the native controls contract: ${why}`)}async read(input,budget3,c3){const early=this.gate(c3,input.runtimeId,"reads");if(early)return early;const d2=this.dispatcher;const runtime=this.runtime??{id:c3.runtimeId,startedAt:0};const generation=this.generation;if(input.kind==="catalog"){const items2=AGENT_NATIVE_KINDS.filter(k2=>d2.kinds.has(k2)).map(kind2=>({kind:kind2,writable:this.writable(kind2)}));return{ok:true,data:{runtime,kind:"catalog",revision:this.revisionOf("catalog",JSON.stringify(items2),generation),items:items2}}}const kind=input.kind;if(!d2.kinds.has(kind))return fail4("unimplemented","this agent's connector does not read that kind");const resourceId="resourceId"in input?input.resourceId:void 0;const parent=resourceId===void 0?void 0:this.views.get("sessions");if(resourceId!==void 0&&!parent?.rows.has(resourceId))return fail4("not-found","the latest sessions view has no such session; read sessions again");let position;let limit=input.limit??20;let held2;if(input.cursor!==void 0){held2=this.cursors.get(input.cursor);if(!held2||held2.generation!==generation||this.wall()-held2.issuedAt>AGENT_NATIVE_CURSOR_TTL_MS||held2.parent!==void 0&&held2.parent!==parent?.revision){this.cursors.delete(input.cursor);return fail4("not-found","the cursor expired or the view changed; read from the first page")}if(held2.kind!==kind||held2.resourceId!==resourceId||input.limit!==void 0&&input.limit!==held2.limit)return fail4("bad-request","the cursor belongs to another kind, resource or page size");position=held2.position;limit=held2.limit}const bound=Math.min(NATIVE_HARNESS_MS,this.remaining(budget3)-NATIVE_REPLY_RESERVE_MS);if(bound<=0)return fail4("unavailable","too little of the request's time is left to read the harness");const ticket=++this.ticket;let page2;try{page2=await withBound2(d2.read({kind,...resourceId?{resourceId}:{},...position!==void 0?{position}:{},limit}),bound)}catch{return fail4("unavailable","the harness did not answer the read")}if(generation!==this.generation)return fail4("failed-precondition","the view changed while it was read; read from the first page");if(this.attached===0)return fail4("unavailable","this agent is stopping");if(resourceId!==void 0&&this.views.get("sessions")!==parent)return fail4("failed-precondition","the sessions view changed while the history was read; read sessions again");const shaped=this.pageFault(kind,page2,limit);if(shaped)return this.fault(shaped);if(held2&&page2.snapshot!==held2.snapshot)return fail4("failed-precondition","the view changed since the first page; read from the first page");const revision=held2?.revision??this.revisionOf(`${kind}\0${resourceId??""}\0${parent?.revision??""}`,page2.snapshot,generation);const items=structuredClone([...page2.items]);const body={runtime,kind,revision,items};if(!AGENT_CONTRACTS["native-controls"].output.validate(body))return this.fault("the page does not match the row schema of its kind");const rules2=this.rulesFault(kind,items);if(rules2)return this.fault(rules2);const sized=page2.next!==void 0?{...body,nextCursor:"c".repeat(96)}:body;if(c3.fits&&!c3.fits(sized))return fail4("resource-exhausted","the page does not fit one reply; read it with a smaller limit");if(kind!=="history"&&!this.remember(kind,revision,items,held2===void 0,ticket)){return fail4("failed-precondition","a newer view of this kind was read meanwhile; read from the first page")}const out=page2.next===void 0?body:{...body,nextCursor:this.mintCursor({kind,resourceId,limit,revision,snapshot:page2.snapshot,position:page2.next,generation,...parent?{parent:parent.revision}:{}})};return{ok:true,data:out}}writable(kind){const d2=this.dispatcher;if(typeof d2?.act!=="function")return false;return[...d2.actions??[]].some(a3=>AGENT_NATIVE_ACTION_KINDS[a3]===kind&&a3!==AGENT_NATIVE_PREVIEW_ACTION)}pageFault(kind,page2,limit){if(typeof page2!=="object"||page2===null||!Array.isArray(page2.items))return"the page is not an object with items";if(typeof page2.snapshot!=="string"||page2.snapshot.length===0)return"the page names no snapshot";if(page2.next!==void 0&&(typeof page2.next!=="string"||page2.next.length===0))return"the page's next position is not a string";if(page2.items.length>limit)return`the page carries ${page2.items.length} rows, over the limit ${limit}`;for(const row2 of page2.items){let bytes;try{bytes=utf82(JSON.stringify(row2))}catch{return"a row does not serialize"}if(bytes>AGENT_NATIVE_ROW_MAX_BYTES)return`a ${kind} row is over ${AGENT_NATIVE_ROW_MAX_BYTES} bytes`}return void 0}rulesFault(kind,items){const ids=new Set;for(const row2 of items){if(ids.has(row2.id))return"a row id is listed twice";ids.add(row2.id);const defect=nativeRowDefect(kind,row2);if(defect)return defect;for(const o3 of row2.actions){if(!this.dispatcher?.actions?.has(o3.action)||typeof this.dispatcher.act!=="function")return`a row offers ${o3.action}, which the connector does not carry out`}}return void 0}mintCursor(c3){const token3=keyOf2(24);this.cursors.set(token3,{...c3,issuedAt:this.wall()});while(this.cursors.size>NATIVE_CURSORS_MAX)this.cursors.delete(this.cursors.keys().next().value);return token3}remember(kind,revision,rows,first,ticket){let view=this.views.get(kind);if(!view||view.revision!==revision){if(!first||ticket<(this.viewTicket.get(kind)??0))return false;view={revision,rows:new Map};this.views.set(kind,view);this.viewTicket.set(kind,ticket)}for(const row2 of rows){view.rows.delete(row2.id);view.rows.set(row2.id,admitted(row2))}while(view.rows.size>NATIVE_ROWS_KEPT)view.rows.delete(view.rows.keys().next().value);return true}state(input,c3){const early=this.gate(c3,input.runtimeId,"reads");if(early&&!(early.code==="unavailable"&&this.records.has(input.key)))return early;const r2=this.records.get(input.key);if(!r2)return fail4("not-found","this runtime holds no action under that key");return{ok:true,data:this.output(r2)}}output(r2){return{runtime:this.runtime??{id:"unbound",startedAt:0},key:r2.key,state:r2.state}}async act(input,budget3,c3){const early=this.gate(c3,input.runtimeId,"acts on");if(early)return early;const coords=JSON.stringify([input.action,input.resourceId,input.revision,input.args]);const held2=this.records.get(input.key);if(held2){if(held2.coords!==coords)return fail4("bad-request","this key names an earlier action with other coordinates");if(held2.caller===c3.caller&&held2.envelope===c3.envelopeId)return{ok:true,data:this.output(held2)};return fail4("failed-precondition","this key names an earlier action; read its state with native-action-state")}const refused5=this.admit(input,budget3);if(refused5)return refused5;return this.handOver(input,budget3,c3,coords)}admit(input,budget3){const d2=this.dispatcher;const kind=AGENT_NATIVE_ACTION_KINDS[input.action];if(!this.flags().nativeActions||!d2.actions?.has(input.action))return fail4("unimplemented",`this agent's connector does not carry out ${input.action}`);if(this.records.size>=AGENT_NATIVE_RECORDS_MAX)return fail4("resource-exhausted",`this runtime holds ${AGENT_NATIVE_RECORDS_MAX} action records`);const view=this.views.get(kind);if(!view||view.revision!==input.revision)return fail4("failed-precondition",`that revision is not the latest view of ${kind}; read it again`);const row2=view.rows.get(input.resourceId);if(!row2)return fail4("not-found",`the latest view of ${kind} has no such row`);const offer=row2.offers.get(input.action);if(!offer)return fail4("failed-precondition",`the row does not offer ${input.action}`);if(offer.locked)return fail4("failed-precondition",`${input.action} is locked on this row`);const args=this.argsRefusal(input,row2);if(args)return args;if(this.slot)return fail4("unavailable","another native action is still with the harness; read its state and try again once it settled");if(this.remaining(budget3)<NATIVE_HARNESS_MS+NATIVE_REPLY_RESERVE_MS)return fail4("unavailable","too little of the request's time is left to hand the action over");return void 0}argsRefusal(input,row2){const args=input.args;if(input.action==="setting-set"&&!row2.choices?.includes(args.value))return fail4("bad-request","the value is not one of the setting's choices");if(input.action==="checkpoint-restore"){const p2=this.records.get(args.previewKey);const ok3=p2&&p2.action===AGENT_NATIVE_PREVIEW_ACTION&&p2.resourceId===input.resourceId&&p2.state.status==="preview"&&p2.state.restorable&&p2.expiresAt!==void 0&&this.wall()<p2.expiresAt;if(!ok3)return fail4("failed-precondition","previewKey names no live, restorable preview of this checkpoint; preview it again")}return void 0}handOver(input,budget3,c3,coords){const record3={key:input.key,coords,caller:c3.caller,envelope:c3.envelopeId,action:input.action,resourceId:input.resourceId,state:{status:"applying"},answered:false,settled:false};this.records.set(input.key,record3);this.slot=record3;this.bump();const d2=this.dispatcher;const request2=Object.freeze({action:input.action,kind:AGENT_NATIVE_ACTION_KINDS[input.action],resourceId:input.resourceId,args:structuredClone(input.args),key:input.key});const settle=o3=>this.settle(record3,o3);let call;try{call=d2.act(request2,settle)}catch(e3){call=Promise.reject(e3)}const bound=Math.min(NATIVE_HARNESS_MS,this.remaining(budget3)-NATIVE_REPLY_RESERVE_MS);return new Promise(resolve3=>{let replied=false;const reply3=()=>{if(replied)return;replied=true;clearTimeout(timer2);resolve3({ok:true,data:this.output(record3)})};const timer2=setTimeout(()=>{record3.answered=true;if(!record3.settled)this.mark(record3,{status:"unknown"});reply3()},Math.max(0,bound));timer2.unref?.();const after=step=>{try{step()}catch{this.warn(`native-action ${record3.action}: the connector's answer could not be applied`);if(!record3.settled&&!record3.answered){record3.answered=true;this.mark(record3,{status:"unknown"})}}reply3()};call.then(r2=>after(()=>this.took(record3,r2)),e3=>after(()=>this.failed(record3,e3)))})}took(r2,result){if(r2.answered||r2.settled)return;r2.answered=true;const s3=result?.status;if(s3==="applied")return this.end(r2,{status:"applied"});if(s3==="applying")return;if(s3==="authorizing"&&AGENT_NATIVE_SIGN_IN_ACTIONS.includes(r2.action)){const res=result;const why=urlFault(res.url);const until=validMs(res.expiresAt);if(why||until===void 0){this.warn(`native-action ${r2.action}: the sign-in answer was refused: ${why??"its expiry is not a time"}`);return this.mark(r2,{status:"unknown"})}const at2=Math.min(until,this.wall()+AGENT_NATIVE_SIGN_IN_TTL_MS);if(at2<=this.wall())return this.mark(r2,{status:"unknown"});r2.expiresAt=at2;this.mark(r2,{status:"authorizing",url:res.url,expiresAt:iso2(at2)});this.expireAt(r2,at2);return}if(s3==="preview"&&r2.action===AGENT_NATIVE_PREVIEW_ACTION){const res=result;const until=res.expiresAt===void 0?Infinity:validMs(res.expiresAt);const at2=until===void 0?void 0:Math.min(until,this.wall()+AGENT_NATIVE_PREVIEW_TTL_MS);const state=at2===void 0||typeof res.restorable!=="boolean"?void 0:{status:"preview",restorable:res.restorable,expiresAt:iso2(at2),...res.filesAffected!==void 0?{filesAffected:res.filesAffected}:{},...res.reason!==void 0?{reason:res.reason}:{}};if(!state||!AGENT_CONTRACTS["native-action-state"].output.validate({runtime:{id:"x",startedAt:0},key:r2.key,state})){this.warn(`native-action ${r2.action}: the preview answer breaks the state schema`);return this.mark(r2,{status:"unknown"})}r2.expiresAt=at2;return this.end(r2,state)}this.warn(`native-action ${r2.action}: the connector's answer is not one this action takes`);this.mark(r2,{status:"unknown"})}failed(r2,e3){if(r2.answered||r2.settled)return;r2.answered=true;if(e3 instanceof NativeRefused&&AGENT_NATIVE_REFUSAL_CODES.includes(e3.code))return this.end(r2,{status:"refused",code:e3.code,reason:REFUSED_REASON});this.warn(`native-action ${r2.action}: the harness failed`);this.mark(r2,{status:"unknown"})}expireAt(r2,at2){clearTimeout(r2.expiry);r2.expiry=setTimeout(()=>{if(!r2.settled&&r2.state.status==="authorizing")this.mark(r2,{status:"unknown"})},Math.max(0,at2-this.wall()));r2.expiry.unref?.()}settle(r2,o3){if(r2.settled)return;if(o3?.status==="applied")return this.end(r2,{status:"applied"});if(o3?.status==="refused"&&AGENT_NATIVE_REFUSAL_CODES.includes(o3.code))return this.end(r2,{status:"refused",code:o3.code,reason:REFUSED_REASON});this.warn(`native-action ${r2.action}: a settlement that is neither applied nor a typed refusal was ignored`)}mark(r2,state){r2.state=state;if(state.status!=="authorizing"){clearTimeout(r2.expiry);r2.expiry=void 0}this.bump()}end(r2,state){r2.settled=true;r2.answered=true;if(state.status!=="preview")r2.expiresAt=void 0;if(this.slot===r2)this.slot=void 0;this.mark(r2,state)}};var REFUSED_REASON="the harness refused the action and nothing changed";function admitted(row2){const offers2=new Map;for(const o3 of row2.actions)offers2.set(o3.action,Object.freeze(o3.availability==="locked"?{locked:true,reason:o3.reason}:{locked:false}));const choices=row2.choices;return Object.freeze({offers:offers2,...choices?{choices:Object.freeze([...choices])}:{}})}function urlFault(url2){if(typeof url2!=="string")return"it is not a string";if(utf82(url2)>AGENT_NATIVE_URL_MAX_BYTES)return`it is over ${AGENT_NATIVE_URL_MAX_BYTES} bytes`;if(!SIGN_IN_URL.test(url2))return"it is not an https link with a plain host and no user info or fragment";try{if(new URL(url2).protocol!=="https:")return"it is not https"}catch{return"it does not parse"}return void 0}function withBound2(p2,ms){return new Promise((resolve3,reject)=>{const t2=setTimeout(()=>reject(new Error(`no answer within ${Math.round(ms)} ms`)),ms);t2.unref?.();p2.then(v3=>{clearTimeout(t2);resolve3(v3)},e3=>{clearTimeout(t2);reject(e3)})})}var lanes3=new Map;function nativeLaneFor(runtimeId,o3){let lane=lanes3.get(runtimeId);if(!lane){lane=new NativeLane({warn:o3.warn});lanes3.set(runtimeId,lane)}return lane}var caller=ctx=>({self:ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor,caller:`${ctx.caller.owner}.${ctx.caller.actor}.${ctx.caller.uid}`,envelopeId:ctx.request.id,runtimeId:ctx.principal.runtimeId,fits:data=>ctx.replyFits(data,AGENT_NATIVE_REPLY_MAX_BYTES)});var budget2=ctx=>({deadlineMs:ctx.request.deadlineMs??3e4,receivedAt:ctx.receivedAtMonotonicMs});var bind2=(lane,ctx)=>lane.bindRuntime({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function reply2(a3){if(a3.ok)return a3.data;throw new EpEnvelopeError(a3.code,a3.message,void 0,a3.outcome)}function nativeHandlers(lane){return[{command:"native-controls",contract:AGENT_CONTRACTS["native-controls"],handler:async ctx=>{bind2(lane,ctx);return reply2(await lane.read(ctx.request.args,budget2(ctx),caller(ctx)))}},{command:"native-action",contract:AGENT_CONTRACTS["native-action"],handler:async ctx=>{bind2(lane,ctx);return reply2(await lane.act(ctx.request.args,budget2(ctx),caller(ctx)))}},{command:"native-action-state",contract:AGENT_CONTRACTS["native-action-state"],handler:ctx=>{bind2(lane,ctx);return reply2(lane.state(ctx.request.args,caller(ctx)))}}]}var SENT_ITEM_REPLY_CEILING=524288;var SENT_SEQ_RESERVE=9*2+AGENT_SENT_ITEMS_MAX*2+5*2;var enc8=new TextEncoder;var utf83=s3=>enc8.encode(s3).length;function normalise(s3){return s3.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}function cutToBytes(s3,max){if(max<=0)return"";if(utf83(s3)<=max)return s3;let out="";let used=0;for(const cp of s3){const b3=utf83(cp);if(used+b3>max)break;out+=cp;used+=b3}return out}function previewOf(text5){if(text5==="")return void 0;return Array.from(text5).slice(0,AGENT_SENT_PREVIEW_MAX).join("")}var isRunToken=s3=>typeof s3==="string"&&/^[^\s\p{C}]+$/u.test(s3)&&Array.from(s3).length<=AGENT_SENT_RUN_ID_MAX;function createSentStore(o3){const rows=new Map;const seqMax=o3.seqMax??Number.MAX_SAFE_INTEGER;const now=o3.now??(()=>new Date);let seq=o3.seqStart??0;let accepted=0;let dropped=0;let bodyBytes=0;const inReserve=()=>seqMax-seq<=SENT_SEQ_RESERVE;const waiting=()=>[...rows.values()].filter(r2=>r2.state.kind==="queued").length;const presence=()=>({waiting:waiting(),seq});function step(apply){if(seq>=seqMax)return false;apply();seq++;o3.changed?.(presence());return true}const unfinished=r2=>r2.state.kind==="queued"||r2.state.kind==="taken";const bytesOf=r2=>(r2.text?.bytes??0)+(r2.output?.bytes??0);function makeRoom(rowsNeeded,bytesNeeded,keep){for(const r2 of[...rows.values()].sort((a3,b3)=>a3.n-b3.n)){if(AGENT_SENT_ITEMS_MAX-rows.size>=rowsNeeded&&AGENT_SENT_BODY_BYTES_MAX-bodyBytes>=bytesNeeded)return;if(unfinished(r2)||r2.id===keep)continue;rows.delete(r2.id);bodyBytes-=bytesOf(r2);dropped++}}function store(raw,keep){const text5=normalise(raw);const of=utf83(text5);makeRoom(0,of,keep);const kept=cutToBytes(text5,AGENT_SENT_BODY_BYTES_MAX-bodyBytes);const bytes=utf83(kept);bodyBytes+=bytes;return{text:kept,bytes,of,normalised:text5}}function admit(item){if(!o3.authed)return true;if(inReserve()||seq+1+SENT_SEQ_RESERVE>seqMax)return false;return step(()=>{makeRoom(1,0);const raw=item.kind==="turn"?item.text:item.args;const stored=raw!==""?store(raw):void 0;const row2={id:item.id,n:++accepted,at:now().toISOString(),kind:item.kind,state:{kind:"queued"},lateAfterStop:0,...stored?{text:{text:stored.text,bytes:stored.bytes,of:stored.of}}:{}};if(item.kind==="turn")row2.turn={...stored?{preview:previewOf(stored.normalised)}:{},images:item.images,published:item.published};else row2.command={target:item.target,name:item.name,args:raw!==""};rows.set(row2.id,row2)})}function state(id2,next){const r2=rows.get(id2);if(!r2)return;step(()=>{r2.state=next})}function late2(id2,apply){const r2=rows.get(id2);if(!r2)return;const reserved=inReserve();if(reserved&&r2.lateAfterStop>=2)return;if(step(()=>apply(r2))&&reserved)r2.lateAfterStop++}const reports={run(id2,run){if(!isRunToken(run?.threadId)||!isRunToken(run?.runId)||run.messageId!==void 0&&!isRunToken(run.messageId))return;late2(id2,r2=>{r2.run={threadId:run.threadId,runId:run.runId,...run.messageId!==void 0?{messageId:run.messageId}:{}}})},output(id2,output){const r2=rows.get(id2);if(!r2||r2.kind!=="command"||typeof output!=="string")return;late2(id2,row2=>{if(row2.output)bodyBytes-=row2.output.bytes;row2.output=void 0;const{text:text5,bytes,of}=store(output,row2.id);row2.output={text:text5,bytes,of}})}};function itemOf(r2){const code=r2.state.kind==="refused"||r2.state.kind==="unknown"?{code:r2.state.code}:{};const base={id:r2.id,n:r2.n,status:r2.state.kind,...code,at:r2.at,...r2.run?{run:r2.run}:{}};if(r2.kind==="turn"){const t2=r2.turn;return{...base,kind:"turn",...t2.preview!==void 0?{preview:t2.preview}:{},...t2.images>0?{images:t2.images}:{},...t2.published?{published:true}:{}}}const c3=r2.command;return{...base,kind:"command",target:c3.target,name:c3.name,...c3.args?{args:true}:{},...r2.output?{output:{bytes:r2.output.of}}:{}}}const runtimeOf=ctx=>({id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt});function sent(ctx){const out={runtime:runtimeOf(ctx),seq,accepted,dropped,items:[...rows.values()].sort((a3,b3)=>a3.n-b3.n).map(itemOf)};const defect=sentListDefect(out);if(defect)throw new EpEnvelopeError("internal",`this agent's read-back list failed its own check: ${defect}`,void 0,"not-executed");return out}function sentItem(ctx){const{id:id2}=ctx.request.args;const r2=rows.get(id2);if(!r2)throw new EpEnvelopeError("not-found",`this agent keeps no sent item ${id2}`,void 0,"not-executed");const out=fitDetail({runtime:runtimeOf(ctx),seq,id:id2,state:r2.state},{output:r2.output,text:r2.text},data=>ctx.replyFits(data,SENT_ITEM_REPLY_CEILING));const defect=sentItemDefect(out,id2,r2.turn?.preview);if(defect)throw new EpEnvelopeError("internal",`this agent's read-back item failed its own check: ${defect}`,void 0,"not-executed");return out}const unimplemented=()=>{throw new EpEnvelopeError("unimplemented","this agent keeps no read-back copy: its mesh does not authenticate its owner",void 0,"not-executed")};const handlers=[{command:"sent",contract:AGENT_CONTRACTS.sent,handler:ctx=>o3.authed?sent(ctx):unimplemented()},{command:"sent-item",contract:AGENT_CONTRACTS["sent-item"],handler:ctx=>o3.authed?sentItem(ctx):unimplemented()}];return{serves:o3.authed,admit,state,presence,handlers,...reports}}function fitDetail(head,bodies,fits){const order2=["output","text"].filter(f2=>bodies[f2]!==void 0);const chosen={};const build=c3=>{const out={...head};const cut3={};for(const f2 of order2){const v3=c3[f2];out[f2]=v3;const kept=utf83(v3);if(kept<bodies[f2].of)cut3[f2]={of:bodies[f2].of,kept}}if(cut3.text||cut3.output)out.cut=cut3;return out};for(const[i2,f2]of order2.entries()){const later=order2.slice(i2+1);const combos=later.reduce((acc,l2)=>acc.flatMap(x2=>[{...x2,[l2]:bodies[l2].text},{...x2,[l2]:""}]),[{}]);const fitsWith=v3=>combos.some(cmb=>fits(build({...chosen,[f2]:v3,...cmb})));const stored=bodies[f2].text;if(fitsWith(stored)){chosen[f2]=stored;continue}const cps=Array.from(stored);let lo=0;let hi2=cps.length-1;while(lo<hi2){const mid=Math.ceil((lo+hi2)/2);if(fitsWith(cps.slice(0,mid).join("")))lo=mid;else hi2=mid-1}chosen[f2]=cps.slice(0,lo).join("")}return build(chosen)}async function openAgentEndpoint(ep,opts){if(typeof opts?.warn!=="function")throw new TypeError("openAgentEndpoint needs opts.warn");const max=ep.maxPayload;if(max<PROMPT_DESK_MIN_MAX_PAYLOAD)throw new Error(`the agent endpoint needs a connection whose max_payload is at least ${PROMPT_DESK_MIN_MAX_PAYLOAD} bytes, and this one is ${max}`);const warn=msg=>{try{opts.warn(msg)}catch{}};const desk=createPromptDesk(ep,warn);let showSent=()=>{};const authed=opts.authed===true;const store=createSentStore({authed,...authed?{seqStart:ep.nextSentSeqStart()}:{},changed:now=>{ep.noteSentSeq(now.seq);showSent()}});const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}),opts.first,store.serves?store:void 0);const naming=createNameLane(ep,warn,opts.onNamed);let showOptions=()=>{};const options=optionLaneFor(ep.runtimeId,{warn});const model=createModelLane(opts.dispatcher,{show:opts.showModel??(s3=>ep.setCardModel(s3.model,s3.variant)),warn,policed:opts.policed,authed,exclusive:fn2=>options.runExclusive(fn2)});const steerLane=steerLaneFor(ep.runtimeId,warn);let onNative=()=>{};const native=nativeLaneFor(ep.runtimeId,{warn});let steer;const steerFor={served:()=>steer?.served()??false,steer:(req,budget3,signal)=>steer.steer(req,budget3,signal),detach:()=>steer?.detach()};const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers,...naming.handlers,model.handler,model.choices,...store.handlers,steerHandler(steerFor),...optionHandlers(options),...nativeHandlers(native)]});steer=steerLane.attach(opts.dispatcher?.steer);const detachOptions=options.attach(opts.dispatcher?.options,()=>showOptions());const detachNative=native.attach(opts.dispatcher?.native,authed,()=>onNative());desk.served(serve.ready);let closing;const showServed=()=>{if(closing)return;const nativeFlagsNow=native.flags();ep.setAgentEndpointPresence({...servedCommands(opts.dispatcher),sent:store.serves,steer:steerFor.served(),...options.flags(),...nativeFlagsNow},nativeFlagsNow.nativeControls?{seq:native.seq}:null).catch(e3=>warn(`presence does not show what the agent endpoint serves: ${e3.message}`));showOptions()};showOptions=()=>{if(closing)return;const cursor=options.flags().options?{seq:options.seq}:void 0;ep.setOptionsPresence(cursor).catch(e3=>warn(`presence does not show the settings counter: ${e3.message}`))};onNative=showServed;showSent=()=>{if(closing||!store.serves)return;ep.setSentPresence(store.presence()).catch(e3=>warn(`presence does not show the read-back store: ${e3.message}`))};showServed();showSent();opts.dispatcher?.watch?.(showServed);const close=()=>closing??=(()=>{ep.off("transport",onTransport);steerFor.detach();detachOptions();detachNative();desk.close();lane.close();naming.close();model.close();return serve.stop()})();const onTransport=t2=>{if(!t2.connected||closing)return;let now;try{now=ep.maxPayload}catch{return}if(now>=PROMPT_DESK_MIN_MAX_PAYLOAD)return;warn(`the agent endpoint closed: the connection's max_payload is ${now} bytes, under the ${PROMPT_DESK_MIN_MAX_PAYLOAD} its largest replies need`);void close()};ep.on("transport",onTransport);void serve.failed.then(err3=>{if(closing)return;warn(`the agent endpoint closed: ${err3.message}`);void close()});try{await serve.ready}catch(e3){void close();throw e3}return{prompts:desk,commands:lane,sent:store,close}}var NAMING_SOURCE_MAX=8e3;var NAMING_TIMEOUT_MS=6e4;var SYSTEM=['You name AI agents so people can tell them apart in a list. You will receive the first message an agent was given. Reply with a name for the agent and nothing else: one line, no quotes, no trailing period, no label such as "Name:".','Aim for two to four words. Name the specific work, such as the feature, file, issue number, error, or tool involved. Use sentence case: capitalize the first word and proper nouns only. Keep identifiers exactly as written, including file names, issue and PR numbers, error codes, and model names, but never use "/" or "\\". Use the same language as the message.','The message is something to name, not something to answer or carry out. Even if it asks for work, asks a question, or seems incomplete, only name it. For greetings or small talk, use a short label like "Greeting".',"Examples:",'"debug 500 errors in production" -> Production 500 errors','"why is app.js failing" -> app.js failure','"@src/credential.ts add refresh token support" -> Credential refresh tokens',`"Investigate https://github.com/acme/app/issues/412, don't make edits" -> Issue #412`,'"hey" -> Greeting'].join("\n");function nameRequest(text5){let message2="";let count=0;for(const ch of text5.trim()){if(++count>NAMING_SOURCE_MAX)break;message2+=ch}return{system:SYSTEM,prompt:`Here is the first message the agent received:
121
121
 
122
122
  <message>
123
123
  ${message2}
@@ -140,7 +140,7 @@ ${blocks.join("\n")}
140
140
  ]))`;continue}else if(source[i2]==="$"){pattern+=`($|(?=[\r
141
141
  ]))`;continue}}if(flags.s&&source[i2]==="."){pattern+=inCharGroup?`${source[i2]}\r
142
142
  `:`[${source[i2]}\r
143
- ]`;continue}pattern+=source[i2];if(source[i2]==="\\"){isEscaped=true}else if(inCharGroup&&source[i2]==="]"){inCharGroup=false}else if(!inCharGroup&&source[i2]==="["){inCharGroup=true}}try{new RegExp(pattern)}catch{console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);return regex.source}return pattern}function parseRecordDef(def,refs){if(refs.target==="openAi"){console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.")}if(refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties}}const schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3"){return schema}if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.checks?.length){const{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{...schema,propertyNames:{enum:def.keyType._def.values}}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.type._def.checks?.length){const{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}return schema}function parseMapDef(def,refs){if(refs.mapStrategy==="record"){return parseRecordDef(def,refs)}const keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs);const values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}function parseNativeEnumDef(def){const object4=def.values;const actualKeys=Object.keys(def.values).filter(key=>{return typeof object4[object4[key]]!=="number"});const actualValues=actualKeys.map(key=>object4[key]);const parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);const options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x2=>x2._def.typeName in primitiveMappings&&(!x2._def.checks||!x2._def.checks.length))){const types=options.reduce((types2,x2)=>{const type=primitiveMappings[x2._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x2=>x2._def.typeName==="ZodLiteral"&&!x2.description)){const types=options.reduce((acc,x2)=>{const type=typeof x2._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x2._def.value===null)return[...acc,"null"];case"symbol":case"undefined":case"function":default:return acc}},[]);if(types.length===options.length){const uniqueTypes=types.filter((x2,i2,a3)=>a3.indexOf(x2)===i2);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x2)=>{return acc.includes(x2._def.value)?acc:[...acc,x2._def.value]},[])}}}else if(options.every(x2=>x2._def.typeName==="ZodEnum")){return{type:"string",enum:options.reduce((acc,x2)=>[...acc,...x2._def.values.filter(x3=>!acc.includes(x3))],[])}}return asAnyOf(def,refs)}var asAnyOf=(def,refs)=>{const anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i2}`]})).filter(x2=>!!x2&&(!refs.strictUnions||typeof x2==="object"&&Object.keys(x2).length>0));return anyOf.length?{anyOf}:void 0};function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length)){if(refs.target==="openApi3"){return{type:primitiveMappings[def.innerType._def.typeName],nullable:true}}return{type:[primitiveMappings[def.innerType._def.typeName],"null"]}}if(refs.target==="openApi3"){const base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});if(base2&&"$ref"in base2)return{allOf:[base2],nullable:true};return base2&&{...base2,nullable:true}}const base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}function parseNumberDef(def,refs){const res={type:"number"};if(!def.checks)return res;for(const check2 of def.checks){switch(check2.kind){case"int":res.type="integer";addErrorMessage(res,"type",check2.message,refs);break;case"min":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMinimum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMinimum=true}setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}break;case"max":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMaximum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMaximum=true}setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check2.value,check2.message,refs);break}}return res}function parseObjectDef(def,refs){const forceOptionalIntoNullable=refs.target==="openAi";const result={type:"object",properties:{}};const required2=[];const shape=def.shape();for(const propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0){continue}let propOptional=safeIsOptional(propDef);if(propOptional&&forceOptionalIntoNullable){if(propDef._def.typeName==="ZodOptional"){propDef=propDef._def.innerType}if(!propDef.isNullable()){propDef=propDef.nullable()}propOptional=false}const parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});if(parsedDef===void 0){continue}result.properties[propName]=parsedDef;if(!propOptional){required2.push(propName)}}if(required2.length){result.required=required2}const additionalProperties=decideAdditionalProperties(def,refs);if(additionalProperties!==void 0){result.additionalProperties=additionalProperties}return result}function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever"){return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})}switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}function safeIsOptional(schema){try{return schema.isOptional()}catch{return true}}var parseOptionalDef=(def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString()){return parseDef(def.innerType._def,refs)}const innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)};var parsePipelineDef=(def,refs)=>{if(refs.pipeStrategy==="input"){return parseDef(def.in._def,refs)}else if(refs.pipeStrategy==="output"){return parseDef(def.out._def,refs)}const a3=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]});const b3=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a3?"1":"0"]});return{allOf:[a3,b3].filter(x2=>x2!==void 0)}};function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}function parseSetDef(def,refs){const items=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]});const schema={type:"array",uniqueItems:true,items};if(def.minSize){setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs)}if(def.maxSize){setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs)}return schema}function parseTupleDef(def,refs){if(def.rest){return{type:"array",minItems:def.items.length,items:def.items.map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"items",`${i2}`]})).reduce((acc,x2)=>x2===void 0?acc:[...acc,x2],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}}else{return{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"items",`${i2}`]})).reduce((acc,x2)=>x2===void 0?acc:[...acc,x2],[])}}}function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}function parseUnknownDef(refs){return parseAnyDef(refs)}var parseReadonlyDef=(def,refs)=>{return parseDef(def.innerType._def,refs)};var selectParser=(def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return void 0;default:return(_3=>void 0)(typeName)}};function parseDef(def,refs,forceResolution=false){const seenItem=refs.seen.get(def);if(refs.override){const overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride){return overrideResult}}if(seenItem&&!forceResolution){const seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0){return seenSchema}}const newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);const jsonSchemaOrGetter=selectParser(def,def.typeName,refs);const jsonSchema=typeof jsonSchemaOrGetter==="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema){addMeta(def,refs,jsonSchema)}if(refs.postProcess){const postProcessResult=refs.postProcess(jsonSchema,def,refs);newItem.jsonSchema=jsonSchema;return postProcessResult}newItem.jsonSchema=jsonSchema;return jsonSchema}var get$ref=(item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":{if(item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)){console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);return parseAnyDef(refs)}return refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}}};var addMeta=(def,refs,jsonSchema)=>{if(def.description){jsonSchema.description=def.description;if(refs.markdownDescription){jsonSchema.markdownDescription=def.description}}return jsonSchema};var zodToJsonSchema=(schema,options)=>{const refs=getRefs(options);let definitions=typeof options==="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name3,schema2])=>({...acc,[name3]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name3]},true)??parseAnyDef(refs)}),{}):void 0;const name2=typeof options==="string"?options:options?.nameStrategy==="title"?void 0:options?.name;const main=parseDef(schema._def,name2===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},false)??parseAnyDef(refs);const title2=typeof options==="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;if(title2!==void 0){main.title=title2}if(refs.flags.hasReferencedOpenAiAnyType){if(!definitions){definitions={}}if(!definitions[refs.openAiAnyTypeName]){definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}}}const combined=name2===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name2].join("/"),[refs.definitionPath]:{...definitions,[name2]:main}};if(refs.target==="jsonSchema7"){combined.$schema="http://json-schema.org/draft-07/schema#"}else if(refs.target==="jsonSchema2019-09"||refs.target==="openAi"){combined.$schema="https://json-schema.org/draft/2019-09/schema#"}if(refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))){console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.")}return combined};function mapMiniTarget(t2){if(!t2)return"draft-7";if(t2==="jsonSchema7"||t2==="draft-7")return"draft-7";if(t2==="jsonSchema2019-09"||t2==="draft-2020-12")return"draft-2020-12";return"draft-7"}function toJsonSchemaCompat(schema,opts){if(isZ4Schema(schema)){return toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"})}return zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??true,pipeStrategy:opts?.pipeStrategy??"input"})}function getMethodLiteral(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value!=="string"){throw new Error("Schema method literal must be a string")}return value}function parseWithCompat(schema,data){const result=safeParse2(schema,data);if(!result.success){throw result.error}return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(_options){this._options=_options;this._requestMessageId=0;this._requestHandlers=new Map;this._requestHandlerAbortControllers=new Map;this._notificationHandlers=new Map;this._responseHandlers=new Map;this._progressHandlers=new Map;this._timeoutInfo=new Map;this._pendingDebouncedNotifications=new Set;this._taskProgressTokens=new Map;this._requestResolvers=new Map;this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)});this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)});this.setRequestHandler(PingRequestSchema,_request=>({}));this._taskStore=_options?.taskStore;this._taskMessageQueue=_options?.taskMessageQueue;if(this._taskStore){this.setRequestHandler(GetTaskRequestSchema,async(request2,extra)=>{const task=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return{...task}});this.setRequestHandler(GetTaskPayloadRequestSchema,async(request2,extra)=>{const handleTaskResult=async()=>{const taskId=request2.params.taskId;if(this._taskMessageQueue){let queuedMessage;while(queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId)){if(queuedMessage.type==="response"||queuedMessage.type==="error"){const message2=queuedMessage.message;const requestId=message2.id;const resolver=this._requestResolvers.get(requestId);if(resolver){this._requestResolvers.delete(requestId);if(queuedMessage.type==="response"){resolver(message2)}else{const errorMessage=message2;const error51=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error51)}}else{const messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}const task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`)}if(!isTerminal(task.status)){await this._waitForTaskUpdate(taskId,extra.signal);return await handleTaskResult()}if(isTerminal(task.status)){const result=await this._taskStore.getTaskResult(taskId,extra.sessionId);this._clearTaskQueue(taskId);return{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()});this.setRequestHandler(ListTasksRequestSchema,async(request2,extra)=>{try{const{tasks,nextCursor}=await this._taskStore.listTasks(request2.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error51){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error51 instanceof Error?error51.message:String(error51)}`)}});this.setRequestHandler(CancelTaskRequestSchema,async(request2,extra)=>{try{const task=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request2.params.taskId}`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`)}await this._taskStore.updateTaskStatus(request2.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId);this._clearTaskQueue(request2.params.taskId);const cancelledTask=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!cancelledTask){throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request2.params.taskId}`)}return{_meta:{},...cancelledTask}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error51 instanceof Error?error51.message:String(error51)}`)}})}}async _oncancel(notification){if(!notification.params.requestId){return}const controller=this._requestHandlerAbortControllers.get(notification.params.requestId);controller?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=false){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(!info)return false;const totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout){this._timeoutInfo.delete(messageId);throw McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed})}clearTimeout(info.timeoutId);info.timeoutId=setTimeout(info.onTimeout,info.timeout);return true}_cleanupTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(info){clearTimeout(info.timeoutId);this._timeoutInfo.delete(messageId)}}async connect(transport){if(this._transport){throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.")}this._transport=transport;const _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.();this._onclose()};const _onerror=this.transport?.onerror;this._transport.onerror=error51=>{_onerror?.(error51);this._onerror(error51)};const _onmessage=this._transport?.onmessage;this._transport.onmessage=(message2,extra)=>{_onmessage?.(message2,extra);if(isJSONRPCResultResponse(message2)||isJSONRPCErrorResponse(message2)){this._onresponse(message2)}else if(isJSONRPCRequest(message2)){this._onrequest(message2,extra)}else if(isJSONRPCNotification(message2)){this._onnotification(message2)}else{this._onerror(new Error(`Unknown message type: ${JSON.stringify(message2)}`))}};await this._transport.start()}_onclose(){const responseHandlers=this._responseHandlers;this._responseHandlers=new Map;this._progressHandlers.clear();this._taskProgressTokens.clear();this._pendingDebouncedNotifications.clear();for(const info of this._timeoutInfo.values()){clearTimeout(info.timeoutId)}this._timeoutInfo.clear();for(const controller of this._requestHandlerAbortControllers.values()){controller.abort()}this._requestHandlerAbortControllers.clear();const error51=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;this.onclose?.();for(const handler of responseHandlers.values()){handler(error51)}}_onerror(error51){this.onerror?.(error51)}_onnotification(notification){const handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;if(handler===void 0){return}Promise.resolve().then(()=>handler(notification)).catch(error51=>this._onerror(new Error(`Uncaught error in notification handler: ${error51}`)))}_onrequest(request2,extra){const handler=this._requestHandlers.get(request2.method)??this.fallbackRequestHandler;const capturedTransport=this._transport;const relatedTaskId=request2.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){const errorResponse={jsonrpc:"2.0",id:request2.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&this._taskMessageQueue){this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error51=>this._onerror(new Error(`Failed to enqueue error response: ${error51}`)))}else{capturedTransport?.send(errorResponse).catch(error51=>this._onerror(new Error(`Failed to send an error response: ${error51}`)))}return}const abortController=new AbortController;this._requestHandlerAbortControllers.set(request2.id,abortController);const taskCreationParams=isTaskAugmentedRequestParams(request2.params)?request2.params.task:void 0;const taskStore=this._taskStore?this.requestTaskStore(request2,capturedTransport?.sessionId):void 0;const fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request2.params?._meta,sendNotification:async notification=>{if(abortController.signal.aborted)return;const notificationOptions={relatedRequestId:request2.id};if(relatedTaskId){notificationOptions.relatedTask={taskId:relatedTaskId}}await this.notification(notification,notificationOptions)},sendRequest:async(r2,resultSchema,options)=>{if(abortController.signal.aborted){throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled")}const requestOptions={...options,relatedRequestId:request2.id};if(relatedTaskId&&!requestOptions.relatedTask){requestOptions.relatedTask={taskId:relatedTaskId}}const effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;if(effectiveTaskId&&taskStore){await taskStore.updateTaskStatus(effectiveTaskId,"input_required")}return await this.request(r2,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request2.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(taskCreationParams){this.assertTaskHandlerCapability(request2.method)}}).then(()=>handler(request2,fullExtra)).then(async result=>{if(abortController.signal.aborted){return}const response={result,jsonrpc:"2.0",id:request2.id};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(response)}},async error51=>{if(abortController.signal.aborted){return}const errorResponse={jsonrpc:"2.0",id:request2.id,error:{code:Number.isSafeInteger(error51["code"])?error51["code"]:ErrorCode.InternalError,message:error51.message??"Internal error",...error51["data"]!==void 0&&{data:error51["data"]}}};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(errorResponse)}}).catch(error51=>this._onerror(new Error(`Failed to send response: ${error51}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(request2.id)===abortController){this._requestHandlerAbortControllers.delete(request2.id)}})}_onprogress(notification){const{progressToken,...params}=notification.params;const messageId=Number(progressToken);const handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}const responseHandler=this._responseHandlers.get(messageId);const timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress){try{this._resetTimeout(messageId)}catch(error51){this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);responseHandler(error51);return}}handler(params)}_onresponse(response){const messageId=Number(response.id);const resolver=this._requestResolvers.get(messageId);if(resolver){this._requestResolvers.delete(messageId);if(isJSONRPCResultResponse(response)){resolver(response)}else{const error51=new McpError(response.error.code,response.error.message,response.error.data);resolver(error51)}return}const handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId);this._cleanupTimeout(messageId);let isTaskResponse=false;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result==="object"){const result=response.result;if(result.task&&typeof result.task==="object"){const task=result.task;if(typeof task.taskId==="string"){isTaskResponse=true;this._taskProgressTokens.set(task.taskId,messageId)}}}if(!isTaskResponse){this._progressHandlers.delete(messageId)}if(isJSONRPCResultResponse(response)){handler(response)}else{const error51=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error51)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request2,resultSchema,options){const{task}=options??{};if(!task){try{const result=await this.request(request2,resultSchema,options);yield{type:"result",result}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}return}let taskId;try{const createResult=await this.request(request2,CreateTaskResultSchema,options);if(createResult.task){taskId=createResult.task.taskId;yield{type:"taskCreated",task:createResult.task}}else{throw new McpError(ErrorCode.InternalError,"Task creation did not return a task")}while(true){const task2=await this.getTask({taskId},options);yield{type:"taskStatus",task:task2};if(isTerminal(task2.status)){if(task2.status==="completed"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result}}else if(task2.status==="failed"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}}else if(task2.status==="cancelled"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)}}return}if(task2.status==="input_required"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result};return}const pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve3=>setTimeout(resolve3,pollInterval));options?.signal?.throwIfAborted()}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}}request(request2,resultSchema,options){const{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve3,reject)=>{const earlyReject=error51=>{reject(error51)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===true){try{this.assertCapabilityForMethod(request2.method);if(task){this.assertTaskCapability(request2.method)}}catch(e3){earlyReject(e3);return}}options?.signal?.throwIfAborted();const messageId=this._requestMessageId++;const jsonrpcRequest={...request2,jsonrpc:"2.0",id:messageId};if(options?.onprogress){this._progressHandlers.set(messageId,options.onprogress);jsonrpcRequest.params={...request2.params,_meta:{...request2.params?._meta||{},progressToken:messageId}}}if(task){jsonrpcRequest.params={...jsonrpcRequest.params,task}}if(relatedTask){jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}}}const cancel=reason=>{this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error52=>this._onerror(new Error(`Failed to send cancellation: ${error52}`)));const error51=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error51)};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted){return}if(response instanceof Error){return reject(response)}try{const parseResult=safeParse2(resultSchema,response.result);if(!parseResult.success){reject(parseResult.error)}else{resolve3(parseResult.data)}}catch(error51){reject(error51)}});options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});const timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC;const timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??false);const relatedTaskId=relatedTask?.taskId;if(relatedTaskId){const responseResolver=response=>{const handler=this._responseHandlers.get(messageId);if(handler){handler(response)}else{this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))}};this._requestResolvers.set(messageId,responseResolver);this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}else{this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport){throw new Error("Not connected")}this.assertNotificationCapability(notification.method);const relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){const jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}const debouncedMethods=this._options?.debouncedNotificationMethods??[];const canDebounce=debouncedMethods.includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask;if(canDebounce){if(this._pendingDebouncedNotifications.has(notification.method)){return}this._pendingDebouncedNotifications.add(notification.method);Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method);if(!this._transport){return}let jsonrpcNotification2={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}this._transport?.send(jsonrpcNotification2,options).catch(error51=>this._onerror(error51))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){const method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method);this._requestHandlers.set(method,(request2,extra)=>{const parsed=parseWithCompat(requestSchema,request2);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method)){throw new Error(`A request handler for ${method} already exists, which would be overridden`)}}setNotificationHandler(notificationSchema,handler){const method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{const parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){const progressToken=this._taskProgressTokens.get(taskId);if(progressToken!==void 0){this._progressHandlers.delete(progressToken);this._taskProgressTokens.delete(taskId)}}async _enqueueTaskMessage(taskId,message2,sessionId){if(!this._taskStore||!this._taskMessageQueue){throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured")}const maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message2,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){const messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(const message2 of messages){if(message2.type==="request"&&isJSONRPCRequest(message2.message)){const requestId=message2.message.id;const resolver=this._requestResolvers.get(requestId);if(resolver){resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed"));this._requestResolvers.delete(requestId)}else{this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{const task=await this._taskStore?.getTask(taskId);if(task?.pollInterval){interval=task.pollInterval}}catch{}return new Promise((resolve3,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}const timeoutId=setTimeout(resolve3,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId);reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:true})})}requestTaskStore(request2,sessionId){const taskStore=this._taskStore;if(!taskStore){throw new Error("No task store configured")}return{createTask:async taskParams=>{if(!request2){throw new Error("No request provided")}return await taskStore.createTask(taskParams,request2.id,{method:request2.method,params:request2.params},sessionId)},getTask:async taskId=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return task},storeTaskResult:async(taskId,status2,result)=>{await taskStore.storeTaskResult(taskId,status2,result,sessionId);const task=await taskStore.getTask(taskId,sessionId);if(task){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification);if(isTerminal(task.status)){this._cleanupTaskProgressHandler(taskId)}}},getTaskResult:taskId=>{return taskStore.getTaskResult(taskId,sessionId)},updateTaskStatus:async(taskId,status2,statusMessage)=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status2}". Terminal states (completed, failed, cancelled) cannot transition to other states.`)}await taskStore.updateTaskStatus(taskId,status2,statusMessage,sessionId);const updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification);if(isTerminal(updatedTask.status)){this._cleanupTaskProgressHandler(taskId)}}},listTasks:cursor=>{return taskStore.listTasks(cursor,sessionId)}}}};function isPlainObject2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){const result={...base};for(const key in additional){const k2=key;const addValue=additional[k2];if(addValue===void 0)continue;const baseValue=result[k2];if(isPlainObject2(baseValue)&&isPlainObject2(addValue)){result[k2]={...baseValue,...addValue}}else{result[k2]=addValue}}return result}init_types();var import_ajv=__toESM(require_ajv(),1);var import_ajv_formats=__toESM(require_dist2(),1);function createDefaultAjvInstance(){const ajv=new import_ajv.default({strict:false,validateFormats:true,validateSchema:false,allErrors:true});const addFormats=import_ajv_formats.default;addFormats(ajv);return ajv}var AjvJsonSchemaValidator=class{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){const ajvValidator="$id"in schema&&typeof schema.$id==="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>{const valid=ajvValidator(input);if(valid){return{valid:true,data:input,errorMessage:void 0}}else{return{valid:false,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}}}};init_types();var ExperimentalServerTasks=class{constructor(_server){this._server=_server}requestStream(request2,resultSchema,options){return this._server.requestStream(request2,resultSchema,options)}createMessageStream(params,options){const clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c3=>c3.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c3=>c3.type==="tool_use");if(hasToolResults){if(lastContent.some(c3=>c3.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c3=>c3.type==="tool_use").map(c3=>c3.id));const toolResultIds=new Set(lastContent.filter(c3=>c3.type==="tool_result").map(c3=>c3.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){const clientCapabilities=this._server.getClientCapabilities();const mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}break}case"form":{if(!clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}break}}const normalizedParams=mode==="form"&&params.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"tools/call":if(!requests.tools?.call){throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`)}break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage){throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`)}break;case"elicitation/create":if(!requests.elicitation?.create){throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`)}break;default:break}}var Server=class extends Protocol{constructor(_serverInfo,options){super(options);this._serverInfo=_serverInfo;this._loggingLevels=new Map;this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2]));this.isMessageIgnored=(level,sessionId)=>{const currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):false};this._capabilities=options?.capabilities??{};this._instructions=options?.instructions;this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator;this.setRequestHandler(InitializeRequestSchema,request2=>this._oninitialize(request2));this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.());if(this._capabilities.logging){this.setRequestHandler(SetLevelRequestSchema,async(request2,extra)=>{const transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0;const{level}=request2.params;const parseResult=LoggingLevelSchema.safeParse(level);if(parseResult.success){this._loggingLevels.set(transportSessionId,parseResult.data)}return{}})}}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalServerTasks(this)}}return this._experimental}registerCapabilities(capabilities){if(this.transport){throw new Error("Cannot register capabilities after connecting to transport")}this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){const shape=getObjectShape(requestSchema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}let methodValue;if(isZ4Schema(methodSchema)){const v4Schema=methodSchema;const v4Def=v4Schema._zod?.def;methodValue=v4Def?.value??v4Schema.value}else{const v3Schema=methodSchema;const legacyDef=v3Schema._def;methodValue=legacyDef?.value??v3Schema.value}if(typeof methodValue!=="string"){throw new Error("Schema method literal must be a string")}const method=methodValue;if(method==="tools/call"){const wrappedHandler=async(request2,extra)=>{const validatedRequest=safeParse2(CallToolRequestSchema,request2);if(!validatedRequest.success){const errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}const{params}=validatedRequest.data;const result=await Promise.resolve(handler(request2,extra));if(params.task){const taskValidationResult=safeParse2(CreateTaskResultSchema,result);if(!taskValidationResult.success){const errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}const validationResult=safeParse2(CallToolResultSchema,result);if(!validationResult.success){const errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling){throw new Error(`Client does not support sampling (required for ${method})`)}break;case"elicitation/create":if(!this._clientCapabilities?.elicitation){throw new Error(`Client does not support elicitation (required for ${method})`)}break;case"roots/list":if(!this._clientCapabilities?.roots){throw new Error(`Client does not support listing roots (required for ${method})`)}break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources){throw new Error(`Server does not support notifying about resources (required for ${method})`)}break;case"notifications/tools/list_changed":if(!this._capabilities.tools){throw new Error(`Server does not support notifying of tool list changes (required for ${method})`)}break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts){throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`)}break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url){throw new Error(`Client does not support URL elicitation (required for ${method})`)}break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities){return}switch(method){case"completion/complete":if(!this._capabilities.completions){throw new Error(`Server does not support completions (required for ${method})`)}break;case"logging/setLevel":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts){throw new Error(`Server does not support prompts (required for ${method})`)}break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources){throw new Error(`Server does not support resources (required for ${method})`)}break;case"tools/call":case"tools/list":if(!this._capabilities.tools){throw new Error(`Server does not support tools (required for ${method})`)}break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks){throw new Error(`Server does not support tasks capability (required for ${method})`)}break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){if(!this._capabilities){return}assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request2){const requestedVersion=request2.params.protocolVersion;this._clientCapabilities=request2.params.capabilities;this._clientVersion=request2.params.clientInfo;const protocolVersion=SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION;return{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if(params.tools||params.toolChoice){if(!this._clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c3=>c3.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c3=>c3.type==="tool_use");if(hasToolResults){if(lastContent.some(c3=>c3.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c3=>c3.type==="tool_use").map(c3=>c3.id));const toolResultIds=new Set(lastContent.filter(c3=>c3.type==="tool_result").map(c3=>c3.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}if(params.tools){return this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options)}return this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){const mode=params.mode??"form";switch(mode){case"url":{if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}const urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}const formParams=params.mode==="form"?params:{...params,mode:"form"};const result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema){try{const validator=this._jsonSchemaValidator.getValidator(formParams.requestedSchema);const validationResult=validator(result.content);if(!validationResult.valid){throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error51 instanceof Error?error51.message:String(error51)}`)}}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)")}return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging){if(!this.isMessageIgnored(params.level,sessionId)){return this.notification({method:"notifications/message",params})}}}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};init_types();var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema==="object"&&COMPLETABLE_SYMBOL in schema}function getCompleter(schema){const meta3=schema[COMPLETABLE_SYMBOL];return meta3?.complete}var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name2){const warnings=[];if(name2.length===0){return{isValid:false,warnings:["Tool name cannot be empty"]}}if(name2.length>128){return{isValid:false,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name2.length})`]}}if(name2.includes(" ")){warnings.push("Tool name contains spaces, which may cause parsing issues")}if(name2.includes(",")){warnings.push("Tool name contains commas, which may cause parsing issues")}if(name2.startsWith("-")||name2.endsWith("-")){warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts")}if(name2.startsWith(".")||name2.endsWith(".")){warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts")}if(!TOOL_NAME_REGEX.test(name2)){const invalidChars=name2.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c3=>`"${c3}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");return{isValid:false,warnings}}return{isValid:true,warnings}}function issueToolNameWarning(name2,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name2}":`);for(const warning of warnings){console.warn(` - ${warning}`)}console.warn("Tool registration will proceed, but this may cause compatibility issues.");console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name2){const result=validateToolName(name2);issueToolNameWarning(name2,result.warnings);return result.isValid}var ExperimentalMcpServerTasks=class{constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name2,config2,handler){const execution={taskSupport:"required",...config2.execution};if(execution.taskSupport==="forbidden"){throw new Error(`Cannot register task-based tool '${name2}' with taskSupport 'forbidden'. Use registerTool() instead.`)}const mcpServerInternal=this._mcpServer;return mcpServerInternal._createRegisteredTool(name2,config2.title,config2.description,config2.inputSchema,config2.outputSchema,config2.annotations,execution,config2._meta,handler)}};init_external();init_external();var McpServer=class{constructor(serverInfo,options){this._registeredResources={};this._registeredResourceTemplates={};this._registeredTools={};this._registeredPrompts={};this._toolHandlersInitialized=false;this._completionHandlerInitialized=false;this._resourceHandlersInitialized=false;this._promptHandlersInitialized=false;this.server=new Server(serverInfo,options)}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalMcpServerTasks(this)}}return this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));this.server.registerCapabilities({tools:{listChanged:true}});this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name2,tool])=>{const toolDefinition={name:name2,title:tool.title,description:tool.description,inputSchema:(()=>{const obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){const obj=normalizeObjectSchema(tool.outputSchema);if(obj){toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"output"})}}return toolDefinition})}));this.server.setRequestHandler(CallToolRequestSchema,async(request2,extra)=>{try{const tool=this._registeredTools[request2.params.name];if(!tool){throw new McpError(ErrorCode.InvalidParams,`Tool ${request2.params.name} not found`)}if(!tool.enabled){throw new McpError(ErrorCode.InvalidParams,`Tool ${request2.params.name} disabled`)}const isTaskRequest=!!request2.params.task;const taskSupport=tool.execution?.taskSupport;const isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler){throw new McpError(ErrorCode.InternalError,`Tool ${request2.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`)}if(taskSupport==="required"&&!isTaskRequest){throw new McpError(ErrorCode.MethodNotFound,`Tool ${request2.params.name} requires task augmentation (taskSupport: 'required')`)}if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler){return await this.handleAutomaticTaskPolling(tool,request2,extra)}const args=await this.validateToolInput(tool,request2.params.arguments,request2.params.name);const result=await this.executeToolHandler(tool,args,extra);if(isTaskRequest){return result}await this.validateToolOutput(tool,result,request2.params.name);return result}catch(error51){if(error51 instanceof McpError){if(error51.code===ErrorCode.UrlElicitationRequired){throw error51}}return this.createToolError(error51 instanceof Error?error51.message:String(error51))}});this._toolHandlersInitialized=true}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:true}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema){return void 0}const inputObj=normalizeObjectSchema(tool.inputSchema);const schemaToParse=inputObj??tool.inputSchema;const parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema){return}if(!("content"in result)){return}if(result.isError){return}if(!result.structuredContent){throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`)}const outputObj=normalizeObjectSchema(tool.outputSchema);const parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`)}}async executeToolHandler(tool,args,extra){const handler=tool.handler;const isTaskHandler="createTask"in handler;if(isTaskHandler){if(!extra.taskStore){throw new Error("No task store provided.")}const taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request2,extra){if(!extra.taskStore){throw new Error("No task store provided for task-capable tool.")}const args=await this.validateToolInput(tool,request2.params.arguments,request2.params.name);const handler=tool.handler;const taskExtra={...extra,taskStore:extra.taskStore};const createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra));const taskId=createTaskResult.task.taskId;let task=createTaskResult.task;const pollInterval=task.pollInterval??5e3;while(task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled"){await new Promise(resolve3=>setTimeout(resolve3,pollInterval));const updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask){throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`)}task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){if(this._completionHandlerInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));this.server.registerCapabilities({completions:{}});this.server.setRequestHandler(CompleteRequestSchema,async request2=>{switch(request2.params.ref.type){case"ref/prompt":assertCompleteRequestPrompt(request2);return this.handlePromptCompletion(request2,request2.params.ref);case"ref/resource":assertCompleteRequestResourceTemplate(request2);return this.handleResourceCompletion(request2,request2.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request2.params.ref}`)}});this._completionHandlerInitialized=true}async handlePromptCompletion(request2,ref){const prompt=this._registeredPrompts[ref.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`)}if(!prompt.argsSchema){return EMPTY_COMPLETION_RESULT}const promptShape=getObjectShape(prompt.argsSchema);const field=promptShape?.[request2.params.argument.name];if(!isCompletable(field)){return EMPTY_COMPLETION_RESULT}const completer=getCompleter(field);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request2.params.argument.value,request2.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request2,ref){const template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri]){return EMPTY_COMPLETION_RESULT}throw new McpError(ErrorCode.InvalidParams,`Resource template ${request2.params.ref.uri} not found`)}const completer=template.resourceTemplate.completeCallback(request2.params.argument.name);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request2.params.argument.value,request2.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));this.server.registerCapabilities({resources:{listChanged:true}});this.server.setRequestHandler(ListResourcesRequestSchema,async(request2,extra)=>{const resources2=Object.entries(this._registeredResources).filter(([_3,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata}));const templateResources=[];for(const template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback){continue}const result=await template.resourceTemplate.listCallback(extra);for(const resource of result.resources){templateResources.push({...template.metadata,...resource})}}return{resources:[...resources2,...templateResources]}});this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>{const resourceTemplates=Object.entries(this._registeredResourceTemplates).map(([name2,template])=>({name:name2,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}));return{resourceTemplates}});this.server.setRequestHandler(ReadResourceRequestSchema,async(request2,extra)=>{const uri=new URL(request2.params.uri);const resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled){throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`)}return resource.readCallback(uri,extra)}for(const template of Object.values(this._registeredResourceTemplates)){const variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables){return template.readCallback(uri,variables,extra)}}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)});this._resourceHandlersInitialized=true}setPromptRequestHandlers(){if(this._promptHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));this.server.registerCapabilities({prompts:{listChanged:true}});this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name2,prompt])=>{return{name:name2,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}})}));this.server.setRequestHandler(GetPromptRequestSchema,async(request2,extra)=>{const prompt=this._registeredPrompts[request2.params.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request2.params.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request2.params.name} disabled`)}if(prompt.argsSchema){const argsObj=normalizeObjectSchema(prompt.argsSchema);const parseResult=await safeParseAsync2(argsObj,request2.params.arguments);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request2.params.name}: ${errorMessage}`)}const args=parseResult.data;const cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{const cb=prompt.callback;return await Promise.resolve(cb(extra))}});this._promptHandlersInitialized=true}resource(name2,uriOrTemplate,...rest){let metadata2;if(typeof rest[0]==="object"){metadata2=rest.shift()}const readCallback=rest[0];if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name2,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name2]){throw new Error(`Resource template ${name2} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name2,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}registerResource(name2,uriOrTemplate,config2,readCallback){if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name2,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name2]){throw new Error(`Resource template ${name2} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name2,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}_createRegisteredResource(name2,title2,uri,metadata2,readCallback){const registeredResource={name:name2,title:title2,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResource.update({enabled:false}),enable:()=>registeredResource.update({enabled:true}),remove:()=>registeredResource.update({uri:null}),update:updates=>{if(typeof updates.uri!=="undefined"&&updates.uri!==uri){delete this._registeredResources[uri];if(updates.uri)this._registeredResources[updates.uri]=registeredResource}if(typeof updates.name!=="undefined")registeredResource.name=updates.name;if(typeof updates.title!=="undefined")registeredResource.title=updates.title;if(typeof updates.metadata!=="undefined")registeredResource.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResource.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResource.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResources[uri]=registeredResource;return registeredResource}_createRegisteredResourceTemplate(name2,title2,template,metadata2,readCallback){const registeredResourceTemplate={resourceTemplate:template,title:title2,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResourceTemplate.update({enabled:false}),enable:()=>registeredResourceTemplate.update({enabled:true}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){delete this._registeredResourceTemplates[name2];if(updates.name)this._registeredResourceTemplates[updates.name]=registeredResourceTemplate}if(typeof updates.title!=="undefined")registeredResourceTemplate.title=updates.title;if(typeof updates.template!=="undefined")registeredResourceTemplate.resourceTemplate=updates.template;if(typeof updates.metadata!=="undefined")registeredResourceTemplate.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResourceTemplate.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResourceTemplate.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[name2]=registeredResourceTemplate;const variableNames=template.uriTemplate.variableNames;const hasCompleter=Array.isArray(variableNames)&&variableNames.some(v3=>!!template.completeCallback(v3));if(hasCompleter){this.setCompletionRequestHandler()}return registeredResourceTemplate}_createRegisteredPrompt(name2,title2,description,argsSchema,callback){const registeredPrompt={title:title2,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:true,disable:()=>registeredPrompt.update({enabled:false}),enable:()=>registeredPrompt.update({enabled:true}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){delete this._registeredPrompts[name2];if(updates.name)this._registeredPrompts[updates.name]=registeredPrompt}if(typeof updates.title!=="undefined")registeredPrompt.title=updates.title;if(typeof updates.description!=="undefined")registeredPrompt.description=updates.description;if(typeof updates.argsSchema!=="undefined")registeredPrompt.argsSchema=objectFromShape(updates.argsSchema);if(typeof updates.callback!=="undefined")registeredPrompt.callback=updates.callback;if(typeof updates.enabled!=="undefined")registeredPrompt.enabled=updates.enabled;this.sendPromptListChanged()}};this._registeredPrompts[name2]=registeredPrompt;if(argsSchema){const hasCompletable=Object.values(argsSchema).some(field=>{const inner=field instanceof ZodOptional2?field._def?.innerType:field;return isCompletable(inner)});if(hasCompletable){this.setCompletionRequestHandler()}}return registeredPrompt}_createRegisteredTool(name2,title2,description,inputSchema,outputSchema,annotations,execution,_meta,handler){validateAndWarnToolName(name2);const registeredTool={title:title2,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations,execution,_meta,handler,enabled:true,disable:()=>registeredTool.update({enabled:false}),enable:()=>registeredTool.update({enabled:true}),remove:()=>registeredTool.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){if(typeof updates.name==="string"){validateAndWarnToolName(updates.name)}delete this._registeredTools[name2];if(updates.name)this._registeredTools[updates.name]=registeredTool}if(typeof updates.title!=="undefined")registeredTool.title=updates.title;if(typeof updates.description!=="undefined")registeredTool.description=updates.description;if(typeof updates.paramsSchema!=="undefined")registeredTool.inputSchema=objectFromShape(updates.paramsSchema);if(typeof updates.outputSchema!=="undefined")registeredTool.outputSchema=objectFromShape(updates.outputSchema);if(typeof updates.callback!=="undefined")registeredTool.handler=updates.callback;if(typeof updates.annotations!=="undefined")registeredTool.annotations=updates.annotations;if(typeof updates._meta!=="undefined")registeredTool._meta=updates._meta;if(typeof updates.enabled!=="undefined")registeredTool.enabled=updates.enabled;this.sendToolListChanged()}};this._registeredTools[name2]=registeredTool;this.setToolRequestHandlers();this.sendToolListChanged();return registeredTool}tool(name2,...rest){if(this._registeredTools[name2]){throw new Error(`Tool ${name2} is already registered`)}let description;let inputSchema;let outputSchema;let annotations;if(typeof rest[0]==="string"){description=rest.shift()}if(rest.length>1){const firstArg=rest[0];if(isZodRawShapeCompat(firstArg)){inputSchema=rest.shift();if(rest.length>1&&typeof rest[0]==="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])){annotations=rest.shift()}}else if(typeof firstArg==="object"&&firstArg!==null){if(Object.values(firstArg).some(v3=>typeof v3==="object"&&v3!==null)){throw new Error(`Tool ${name2} expected a Zod schema or ToolAnnotations, but received an unrecognized object`)}annotations=rest.shift()}}const callback=rest[0];return this._createRegisteredTool(name2,void 0,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},void 0,callback)}registerTool(name2,config2,cb){if(this._registeredTools[name2]){throw new Error(`Tool ${name2} is already registered`)}const{title:title2,description,inputSchema,outputSchema,annotations,_meta}=config2;return this._createRegisteredTool(name2,title2,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},_meta,cb)}prompt(name2,...rest){if(this._registeredPrompts[name2]){throw new Error(`Prompt ${name2} is already registered`)}let description;if(typeof rest[0]==="string"){description=rest.shift()}let argsSchema;if(rest.length>1){argsSchema=rest.shift()}const cb=rest[0];const registeredPrompt=this._createRegisteredPrompt(name2,void 0,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}registerPrompt(name2,config2,cb){if(this._registeredPrompts[name2]){throw new Error(`Prompt ${name2} is already registered`)}const{title:title2,description,argsSchema}=config2;const registeredPrompt=this._createRegisteredPrompt(name2,title2,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){if(this.isConnected()){this.server.sendResourceListChanged()}}sendToolListChanged(){if(this.isConnected()){this.server.sendToolListChanged()}}sendPromptListChanged(){if(this.isConnected()){this.server.sendPromptListChanged()}}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value==="object"&&"parse"in value&&typeof value.parse==="function"&&"safeParse"in value&&typeof value.safeParse==="function"}function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}function isZodRawShapeCompat(obj){if(typeof obj!=="object"||obj===null){return false}if(isZodSchemaInstance(obj)){return false}if(Object.keys(obj).length===0){return true}return Object.values(obj).some(isZodTypeLike)}function getZodSchemaObject(schema){if(!schema){return void 0}if(isZodRawShapeCompat(schema)){return objectFromShape(schema)}if(!isZodSchemaInstance(schema)){throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object")}return schema}function promptArgumentsFromSchema(schema){const shape=getObjectShape(schema);if(!shape)return[];return Object.entries(shape).map(([name2,field])=>{const description=getSchemaDescription(field);const isOptional=isSchemaOptional(field);return{name:name2,description,required:!isOptional}})}function getMethodValue(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value==="string"){return value}throw new Error("Schema method literal must be a string")}function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:false}};init_types();init_types();import{createHash as createHash11}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var pinDocAssets=typeof __pinCodexPersonalDocs!=="undefined"&&__pinCodexPersonalDocs;function assetReader(file2){const read=()=>readFileSync6(join8(import.meta.dirname,file2));if(!pinDocAssets)return read;try{const packed=read();return()=>packed}catch(error51){return()=>{throw error51}}}var readCorpusData=assetReader("docs-bundle.bin");var readIndexData=assetReader("docs-index.bin");var DOCS_VERSION="0.193.0";function loadDocsMetadata(){return{"version":"0.193.0","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"acp-clients","title":"Use an ACP client","kind":"Guide","category":"Guide","summary":"Spawn and drive Cotal agents from T3 Code, Zed and other Agent Client Protocol clients."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"artifacts","title":"Artifacts","kind":"Concept (informative)","category":"Concept","summary":"How agents share bytes too large for a message, who may read them, and how long they last."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-chatgpt","title":"Connect ChatGPT","kind":"Guide (informative)","category":"Guide","summary":"Use your Cotal agents from ChatGPT on the web, by voice, and in the ChatGPT desktop app."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-mcp","title":"MCP-only hosts","kind":"Guide","category":"Guide","summary":"Connect an application that supports stdio MCP but has no native Cotal connector."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, resume records, the agent endpoint, agent commands, and the prompt desk."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, agent commands, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command or install the Linux desktop packages."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, agent commands, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrade-matrix","title":"Run the upgrade matrix","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal's upgrade matrix uses the same native harness for release checks and operator diagnostics."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"A user-auth terminal connection closes when the full auth service or a callout replica confirms that its session ended and delivery disconnects it."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readCorpusData();if(packed.length!==1598940||createHash11("sha256").update(packed).digest("hex")!=="6e155c69690ffac1f2f4e38b6b0825ac2e700f4484d398eafe4e6874341dd31f")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it for Cotal 0.193.0: "+(pinDocAssets?"the file read at startup did not match this server. Run `cotal setup` again, then start a new Codex conversation":"it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version"));return corpusPacked=packed}var sourceBounds=[[0,2216],[2216,4210],[4210,9832],[9832,33539],[33539,38358],[38358,42817],[42817,52729],[52729,56451],[56451,63917],[63917,68192],[68192,70036],[70036,80619],[80619,84771],[84771,94420],[94420,96790],[96790,100899],[100899,143904],[143904,164268],[164268,182717],[182717,207216],[207216,229514],[229514,248047],[248047,267460],[267460,308662],[308662,315145],[315145,330168],[330168,356660],[356660,362535],[362535,420051],[420051,434635],[434635,478751],[478751,499346],[499346,529409],[529409,567553],[567553,586209],[586209,588199],[588199,605789],[605789,625700],[625700,628527],[628527,640326],[640326,647116],[647116,652255],[652255,656019],[656019,657948],[657948,660757],[660757,664441],[664441,680294],[680294,682887],[682887,687154],[687154,703568],[703568,713920],[713920,717922],[717922,725406],[725406,730844],[730844,734043],[734043,744768],[744768,747745],[747745,756535],[756535,759525],[759525,767215],[767215,782356],[782356,796666],[796666,804316],[804316,817241],[817241,820590],[820590,823539],[823539,831160],[831160,835197],[835197,837407],[837407,841258],[841258,844675],[844675,845789],[845789,847538],[847538,851201],[851201,863181],[863181,869866],[869866,880750],[880750,896285],[896285,902511],[902511,920538],[920538,925925],[925925,931334],[931334,933851],[933851,939452],[939452,955255],[955255,962338],[962338,978324],[978324,979141],[979141,988350],[988350,994902],[994902,998624],[998624,1003189],[1003189,1008571],[1008571,1014515],[1014515,1017937],[1017937,1022330],[1022330,1027495],[1027495,1031895],[1031895,1047350],[1047350,1050871],[1050871,1053554],[1053554,1056221],[1056221,1059983],[1059983,1069716],[1069716,1074780],[1074780,1093818],[1093818,1103652],[1103652,1184020],[1184020,1187311],[1187311,1188659],[1188659,1197191],[1197191,1206653],[1206653,1218391],[1218391,1227624],[1227624,1232807],[1232807,1551744],[1551744,1591981],[1591981,1598940]];var sourceLengths=[4862,4503,14192,94979,13374,10930,28859,37145,19804,10384,4159,89533,37758,25077,5365,10128,119350,56834,53242,72393,63505,54968,55066,122620,16410,41602,77640,13916,172670,41858,137631,60156,92580,119552,53046,8376,48495,54485,7282,32939,17959,12907,9046,4097,6611,8634,45186,6436,10360,44629,26313,10054,48045,13925,7850,28279,7140,23075,6860,19775,40387,38542,19825,33604,8355,7031,19765,9132,5100,9136,9930,2248,5412,9845,33077,16239,27924,40357,17590,49823,12378,13771,8235,14854,109088,17745,43409,1638,23339,17191,8817,11183,13497,14915,7511,11303,12695,10587,41760,8615,6405,6095,9386,29657,12679,57904,25837,237306,7461,2878,21488,24494,30591,22298,12616,938287,113864,30479];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readIndexData();if(packed.length!==762808||createHash11("sha256").update(packed).digest("hex")!=="d45dc36e99c502c641e26eabd65d0bbddccd64ea0b4b056d2c0b73f4426ceabc")throw new Error("docs data file docs-index.bin beside this module is not the one built with it for Cotal 0.193.0: "+(pinDocAssets?"the file read at startup did not match this server. Run `cotal setup` again, then start a new Codex conversation":"it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version"));return gunzipSync(packed)}var TOKEN3=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN3);if(!raw)return[];const out=[];for(const r2 of raw){if(r2.length>=2)out.push(r2);const t2=r2.replace(EDGE,"");if(t2.length>=2&&t2!==r2)out.push(t2);if(t2.includes(".")){for(const seg of t2.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i2)=>length2!==bodyLengths[i2]))throw new Error("docs index does not match the docs bundle it is searching");const n2=header.sections;const length=4*n2+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i2=0;i2<length;i2++)columns[i2]=bytes.readUInt32LE(4+headerLength+4*i2);const offsets=4*n2;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i2=0;i2<n2;i2++)total+=columns[3*n2+i2];return{sections:n2,terms:header.terms,headings:header.headings,source:columns.subarray(0,n2),start:columns.subarray(n2,2*n2),end:columns.subarray(2*n2,3*n2),length:columns.subarray(3*n2,4*n2),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n2)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page2=pages.get(source);if(!page2){page2={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page2)}return page2}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page2){const meta3=metadata();loadDocsSourceLengths();const reference=page2.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p2,source2)=>(pages.get(source2)??p2).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b3=metadata();const rows=b3.pages.map(p2=>{const kind=p2.kind?`: ${p2.kind}`:"";return`- \`${p2.slug}\`${kind}
143
+ ]`;continue}pattern+=source[i2];if(source[i2]==="\\"){isEscaped=true}else if(inCharGroup&&source[i2]==="]"){inCharGroup=false}else if(!inCharGroup&&source[i2]==="["){inCharGroup=true}}try{new RegExp(pattern)}catch{console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);return regex.source}return pattern}function parseRecordDef(def,refs){if(refs.target==="openAi"){console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.")}if(refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties}}const schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3"){return schema}if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.checks?.length){const{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{...schema,propertyNames:{enum:def.keyType._def.values}}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.type._def.checks?.length){const{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}return schema}function parseMapDef(def,refs){if(refs.mapStrategy==="record"){return parseRecordDef(def,refs)}const keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs);const values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}function parseNativeEnumDef(def){const object4=def.values;const actualKeys=Object.keys(def.values).filter(key=>{return typeof object4[object4[key]]!=="number"});const actualValues=actualKeys.map(key=>object4[key]);const parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);const options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x2=>x2._def.typeName in primitiveMappings&&(!x2._def.checks||!x2._def.checks.length))){const types=options.reduce((types2,x2)=>{const type=primitiveMappings[x2._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x2=>x2._def.typeName==="ZodLiteral"&&!x2.description)){const types=options.reduce((acc,x2)=>{const type=typeof x2._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x2._def.value===null)return[...acc,"null"];case"symbol":case"undefined":case"function":default:return acc}},[]);if(types.length===options.length){const uniqueTypes=types.filter((x2,i2,a3)=>a3.indexOf(x2)===i2);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x2)=>{return acc.includes(x2._def.value)?acc:[...acc,x2._def.value]},[])}}}else if(options.every(x2=>x2._def.typeName==="ZodEnum")){return{type:"string",enum:options.reduce((acc,x2)=>[...acc,...x2._def.values.filter(x3=>!acc.includes(x3))],[])}}return asAnyOf(def,refs)}var asAnyOf=(def,refs)=>{const anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i2}`]})).filter(x2=>!!x2&&(!refs.strictUnions||typeof x2==="object"&&Object.keys(x2).length>0));return anyOf.length?{anyOf}:void 0};function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length)){if(refs.target==="openApi3"){return{type:primitiveMappings[def.innerType._def.typeName],nullable:true}}return{type:[primitiveMappings[def.innerType._def.typeName],"null"]}}if(refs.target==="openApi3"){const base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});if(base2&&"$ref"in base2)return{allOf:[base2],nullable:true};return base2&&{...base2,nullable:true}}const base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}function parseNumberDef(def,refs){const res={type:"number"};if(!def.checks)return res;for(const check2 of def.checks){switch(check2.kind){case"int":res.type="integer";addErrorMessage(res,"type",check2.message,refs);break;case"min":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMinimum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMinimum=true}setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}break;case"max":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMaximum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMaximum=true}setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check2.value,check2.message,refs);break}}return res}function parseObjectDef(def,refs){const forceOptionalIntoNullable=refs.target==="openAi";const result={type:"object",properties:{}};const required2=[];const shape=def.shape();for(const propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0){continue}let propOptional=safeIsOptional(propDef);if(propOptional&&forceOptionalIntoNullable){if(propDef._def.typeName==="ZodOptional"){propDef=propDef._def.innerType}if(!propDef.isNullable()){propDef=propDef.nullable()}propOptional=false}const parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});if(parsedDef===void 0){continue}result.properties[propName]=parsedDef;if(!propOptional){required2.push(propName)}}if(required2.length){result.required=required2}const additionalProperties=decideAdditionalProperties(def,refs);if(additionalProperties!==void 0){result.additionalProperties=additionalProperties}return result}function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever"){return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})}switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}function safeIsOptional(schema){try{return schema.isOptional()}catch{return true}}var parseOptionalDef=(def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString()){return parseDef(def.innerType._def,refs)}const innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)};var parsePipelineDef=(def,refs)=>{if(refs.pipeStrategy==="input"){return parseDef(def.in._def,refs)}else if(refs.pipeStrategy==="output"){return parseDef(def.out._def,refs)}const a3=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]});const b3=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a3?"1":"0"]});return{allOf:[a3,b3].filter(x2=>x2!==void 0)}};function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}function parseSetDef(def,refs){const items=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]});const schema={type:"array",uniqueItems:true,items};if(def.minSize){setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs)}if(def.maxSize){setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs)}return schema}function parseTupleDef(def,refs){if(def.rest){return{type:"array",minItems:def.items.length,items:def.items.map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"items",`${i2}`]})).reduce((acc,x2)=>x2===void 0?acc:[...acc,x2],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}}else{return{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x2,i2)=>parseDef(x2._def,{...refs,currentPath:[...refs.currentPath,"items",`${i2}`]})).reduce((acc,x2)=>x2===void 0?acc:[...acc,x2],[])}}}function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}function parseUnknownDef(refs){return parseAnyDef(refs)}var parseReadonlyDef=(def,refs)=>{return parseDef(def.innerType._def,refs)};var selectParser=(def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return void 0;default:return(_3=>void 0)(typeName)}};function parseDef(def,refs,forceResolution=false){const seenItem=refs.seen.get(def);if(refs.override){const overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride){return overrideResult}}if(seenItem&&!forceResolution){const seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0){return seenSchema}}const newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);const jsonSchemaOrGetter=selectParser(def,def.typeName,refs);const jsonSchema=typeof jsonSchemaOrGetter==="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema){addMeta(def,refs,jsonSchema)}if(refs.postProcess){const postProcessResult=refs.postProcess(jsonSchema,def,refs);newItem.jsonSchema=jsonSchema;return postProcessResult}newItem.jsonSchema=jsonSchema;return jsonSchema}var get$ref=(item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":{if(item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)){console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);return parseAnyDef(refs)}return refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}}};var addMeta=(def,refs,jsonSchema)=>{if(def.description){jsonSchema.description=def.description;if(refs.markdownDescription){jsonSchema.markdownDescription=def.description}}return jsonSchema};var zodToJsonSchema=(schema,options)=>{const refs=getRefs(options);let definitions=typeof options==="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name3,schema2])=>({...acc,[name3]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name3]},true)??parseAnyDef(refs)}),{}):void 0;const name2=typeof options==="string"?options:options?.nameStrategy==="title"?void 0:options?.name;const main=parseDef(schema._def,name2===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},false)??parseAnyDef(refs);const title2=typeof options==="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;if(title2!==void 0){main.title=title2}if(refs.flags.hasReferencedOpenAiAnyType){if(!definitions){definitions={}}if(!definitions[refs.openAiAnyTypeName]){definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}}}const combined=name2===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name2].join("/"),[refs.definitionPath]:{...definitions,[name2]:main}};if(refs.target==="jsonSchema7"){combined.$schema="http://json-schema.org/draft-07/schema#"}else if(refs.target==="jsonSchema2019-09"||refs.target==="openAi"){combined.$schema="https://json-schema.org/draft/2019-09/schema#"}if(refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))){console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.")}return combined};function mapMiniTarget(t2){if(!t2)return"draft-7";if(t2==="jsonSchema7"||t2==="draft-7")return"draft-7";if(t2==="jsonSchema2019-09"||t2==="draft-2020-12")return"draft-2020-12";return"draft-7"}function toJsonSchemaCompat(schema,opts){if(isZ4Schema(schema)){return toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"})}return zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??true,pipeStrategy:opts?.pipeStrategy??"input"})}function getMethodLiteral(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value!=="string"){throw new Error("Schema method literal must be a string")}return value}function parseWithCompat(schema,data){const result=safeParse2(schema,data);if(!result.success){throw result.error}return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(_options){this._options=_options;this._requestMessageId=0;this._requestHandlers=new Map;this._requestHandlerAbortControllers=new Map;this._notificationHandlers=new Map;this._responseHandlers=new Map;this._progressHandlers=new Map;this._timeoutInfo=new Map;this._pendingDebouncedNotifications=new Set;this._taskProgressTokens=new Map;this._requestResolvers=new Map;this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)});this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)});this.setRequestHandler(PingRequestSchema,_request=>({}));this._taskStore=_options?.taskStore;this._taskMessageQueue=_options?.taskMessageQueue;if(this._taskStore){this.setRequestHandler(GetTaskRequestSchema,async(request2,extra)=>{const task=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return{...task}});this.setRequestHandler(GetTaskPayloadRequestSchema,async(request2,extra)=>{const handleTaskResult=async()=>{const taskId=request2.params.taskId;if(this._taskMessageQueue){let queuedMessage;while(queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId)){if(queuedMessage.type==="response"||queuedMessage.type==="error"){const message2=queuedMessage.message;const requestId=message2.id;const resolver=this._requestResolvers.get(requestId);if(resolver){this._requestResolvers.delete(requestId);if(queuedMessage.type==="response"){resolver(message2)}else{const errorMessage=message2;const error51=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error51)}}else{const messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}const task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`)}if(!isTerminal(task.status)){await this._waitForTaskUpdate(taskId,extra.signal);return await handleTaskResult()}if(isTerminal(task.status)){const result=await this._taskStore.getTaskResult(taskId,extra.sessionId);this._clearTaskQueue(taskId);return{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()});this.setRequestHandler(ListTasksRequestSchema,async(request2,extra)=>{try{const{tasks,nextCursor}=await this._taskStore.listTasks(request2.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error51){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error51 instanceof Error?error51.message:String(error51)}`)}});this.setRequestHandler(CancelTaskRequestSchema,async(request2,extra)=>{try{const task=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request2.params.taskId}`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`)}await this._taskStore.updateTaskStatus(request2.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId);this._clearTaskQueue(request2.params.taskId);const cancelledTask=await this._taskStore.getTask(request2.params.taskId,extra.sessionId);if(!cancelledTask){throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request2.params.taskId}`)}return{_meta:{},...cancelledTask}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error51 instanceof Error?error51.message:String(error51)}`)}})}}async _oncancel(notification){if(!notification.params.requestId){return}const controller=this._requestHandlerAbortControllers.get(notification.params.requestId);controller?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=false){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(!info)return false;const totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout){this._timeoutInfo.delete(messageId);throw McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed})}clearTimeout(info.timeoutId);info.timeoutId=setTimeout(info.onTimeout,info.timeout);return true}_cleanupTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(info){clearTimeout(info.timeoutId);this._timeoutInfo.delete(messageId)}}async connect(transport){if(this._transport){throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.")}this._transport=transport;const _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.();this._onclose()};const _onerror=this.transport?.onerror;this._transport.onerror=error51=>{_onerror?.(error51);this._onerror(error51)};const _onmessage=this._transport?.onmessage;this._transport.onmessage=(message2,extra)=>{_onmessage?.(message2,extra);if(isJSONRPCResultResponse(message2)||isJSONRPCErrorResponse(message2)){this._onresponse(message2)}else if(isJSONRPCRequest(message2)){this._onrequest(message2,extra)}else if(isJSONRPCNotification(message2)){this._onnotification(message2)}else{this._onerror(new Error(`Unknown message type: ${JSON.stringify(message2)}`))}};await this._transport.start()}_onclose(){const responseHandlers=this._responseHandlers;this._responseHandlers=new Map;this._progressHandlers.clear();this._taskProgressTokens.clear();this._pendingDebouncedNotifications.clear();for(const info of this._timeoutInfo.values()){clearTimeout(info.timeoutId)}this._timeoutInfo.clear();for(const controller of this._requestHandlerAbortControllers.values()){controller.abort()}this._requestHandlerAbortControllers.clear();const error51=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;this.onclose?.();for(const handler of responseHandlers.values()){handler(error51)}}_onerror(error51){this.onerror?.(error51)}_onnotification(notification){const handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;if(handler===void 0){return}Promise.resolve().then(()=>handler(notification)).catch(error51=>this._onerror(new Error(`Uncaught error in notification handler: ${error51}`)))}_onrequest(request2,extra){const handler=this._requestHandlers.get(request2.method)??this.fallbackRequestHandler;const capturedTransport=this._transport;const relatedTaskId=request2.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){const errorResponse={jsonrpc:"2.0",id:request2.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&this._taskMessageQueue){this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error51=>this._onerror(new Error(`Failed to enqueue error response: ${error51}`)))}else{capturedTransport?.send(errorResponse).catch(error51=>this._onerror(new Error(`Failed to send an error response: ${error51}`)))}return}const abortController=new AbortController;this._requestHandlerAbortControllers.set(request2.id,abortController);const taskCreationParams=isTaskAugmentedRequestParams(request2.params)?request2.params.task:void 0;const taskStore=this._taskStore?this.requestTaskStore(request2,capturedTransport?.sessionId):void 0;const fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request2.params?._meta,sendNotification:async notification=>{if(abortController.signal.aborted)return;const notificationOptions={relatedRequestId:request2.id};if(relatedTaskId){notificationOptions.relatedTask={taskId:relatedTaskId}}await this.notification(notification,notificationOptions)},sendRequest:async(r2,resultSchema,options)=>{if(abortController.signal.aborted){throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled")}const requestOptions={...options,relatedRequestId:request2.id};if(relatedTaskId&&!requestOptions.relatedTask){requestOptions.relatedTask={taskId:relatedTaskId}}const effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;if(effectiveTaskId&&taskStore){await taskStore.updateTaskStatus(effectiveTaskId,"input_required")}return await this.request(r2,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request2.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(taskCreationParams){this.assertTaskHandlerCapability(request2.method)}}).then(()=>handler(request2,fullExtra)).then(async result=>{if(abortController.signal.aborted){return}const response={result,jsonrpc:"2.0",id:request2.id};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(response)}},async error51=>{if(abortController.signal.aborted){return}const errorResponse={jsonrpc:"2.0",id:request2.id,error:{code:Number.isSafeInteger(error51["code"])?error51["code"]:ErrorCode.InternalError,message:error51.message??"Internal error",...error51["data"]!==void 0&&{data:error51["data"]}}};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(errorResponse)}}).catch(error51=>this._onerror(new Error(`Failed to send response: ${error51}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(request2.id)===abortController){this._requestHandlerAbortControllers.delete(request2.id)}})}_onprogress(notification){const{progressToken,...params}=notification.params;const messageId=Number(progressToken);const handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}const responseHandler=this._responseHandlers.get(messageId);const timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress){try{this._resetTimeout(messageId)}catch(error51){this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);responseHandler(error51);return}}handler(params)}_onresponse(response){const messageId=Number(response.id);const resolver=this._requestResolvers.get(messageId);if(resolver){this._requestResolvers.delete(messageId);if(isJSONRPCResultResponse(response)){resolver(response)}else{const error51=new McpError(response.error.code,response.error.message,response.error.data);resolver(error51)}return}const handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId);this._cleanupTimeout(messageId);let isTaskResponse=false;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result==="object"){const result=response.result;if(result.task&&typeof result.task==="object"){const task=result.task;if(typeof task.taskId==="string"){isTaskResponse=true;this._taskProgressTokens.set(task.taskId,messageId)}}}if(!isTaskResponse){this._progressHandlers.delete(messageId)}if(isJSONRPCResultResponse(response)){handler(response)}else{const error51=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error51)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request2,resultSchema,options){const{task}=options??{};if(!task){try{const result=await this.request(request2,resultSchema,options);yield{type:"result",result}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}return}let taskId;try{const createResult=await this.request(request2,CreateTaskResultSchema,options);if(createResult.task){taskId=createResult.task.taskId;yield{type:"taskCreated",task:createResult.task}}else{throw new McpError(ErrorCode.InternalError,"Task creation did not return a task")}while(true){const task2=await this.getTask({taskId},options);yield{type:"taskStatus",task:task2};if(isTerminal(task2.status)){if(task2.status==="completed"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result}}else if(task2.status==="failed"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}}else if(task2.status==="cancelled"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)}}return}if(task2.status==="input_required"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result};return}const pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve3=>setTimeout(resolve3,pollInterval));options?.signal?.throwIfAborted()}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}}request(request2,resultSchema,options){const{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve3,reject)=>{const earlyReject=error51=>{reject(error51)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===true){try{this.assertCapabilityForMethod(request2.method);if(task){this.assertTaskCapability(request2.method)}}catch(e3){earlyReject(e3);return}}options?.signal?.throwIfAborted();const messageId=this._requestMessageId++;const jsonrpcRequest={...request2,jsonrpc:"2.0",id:messageId};if(options?.onprogress){this._progressHandlers.set(messageId,options.onprogress);jsonrpcRequest.params={...request2.params,_meta:{...request2.params?._meta||{},progressToken:messageId}}}if(task){jsonrpcRequest.params={...jsonrpcRequest.params,task}}if(relatedTask){jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}}}const cancel=reason=>{this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error52=>this._onerror(new Error(`Failed to send cancellation: ${error52}`)));const error51=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error51)};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted){return}if(response instanceof Error){return reject(response)}try{const parseResult=safeParse2(resultSchema,response.result);if(!parseResult.success){reject(parseResult.error)}else{resolve3(parseResult.data)}}catch(error51){reject(error51)}});options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});const timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC;const timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??false);const relatedTaskId=relatedTask?.taskId;if(relatedTaskId){const responseResolver=response=>{const handler=this._responseHandlers.get(messageId);if(handler){handler(response)}else{this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))}};this._requestResolvers.set(messageId,responseResolver);this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}else{this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport){throw new Error("Not connected")}this.assertNotificationCapability(notification.method);const relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){const jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}const debouncedMethods=this._options?.debouncedNotificationMethods??[];const canDebounce=debouncedMethods.includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask;if(canDebounce){if(this._pendingDebouncedNotifications.has(notification.method)){return}this._pendingDebouncedNotifications.add(notification.method);Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method);if(!this._transport){return}let jsonrpcNotification2={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}this._transport?.send(jsonrpcNotification2,options).catch(error51=>this._onerror(error51))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){const method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method);this._requestHandlers.set(method,(request2,extra)=>{const parsed=parseWithCompat(requestSchema,request2);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method)){throw new Error(`A request handler for ${method} already exists, which would be overridden`)}}setNotificationHandler(notificationSchema,handler){const method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{const parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){const progressToken=this._taskProgressTokens.get(taskId);if(progressToken!==void 0){this._progressHandlers.delete(progressToken);this._taskProgressTokens.delete(taskId)}}async _enqueueTaskMessage(taskId,message2,sessionId){if(!this._taskStore||!this._taskMessageQueue){throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured")}const maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message2,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){const messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(const message2 of messages){if(message2.type==="request"&&isJSONRPCRequest(message2.message)){const requestId=message2.message.id;const resolver=this._requestResolvers.get(requestId);if(resolver){resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed"));this._requestResolvers.delete(requestId)}else{this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{const task=await this._taskStore?.getTask(taskId);if(task?.pollInterval){interval=task.pollInterval}}catch{}return new Promise((resolve3,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}const timeoutId=setTimeout(resolve3,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId);reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:true})})}requestTaskStore(request2,sessionId){const taskStore=this._taskStore;if(!taskStore){throw new Error("No task store configured")}return{createTask:async taskParams=>{if(!request2){throw new Error("No request provided")}return await taskStore.createTask(taskParams,request2.id,{method:request2.method,params:request2.params},sessionId)},getTask:async taskId=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return task},storeTaskResult:async(taskId,status2,result)=>{await taskStore.storeTaskResult(taskId,status2,result,sessionId);const task=await taskStore.getTask(taskId,sessionId);if(task){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification);if(isTerminal(task.status)){this._cleanupTaskProgressHandler(taskId)}}},getTaskResult:taskId=>{return taskStore.getTaskResult(taskId,sessionId)},updateTaskStatus:async(taskId,status2,statusMessage)=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status2}". Terminal states (completed, failed, cancelled) cannot transition to other states.`)}await taskStore.updateTaskStatus(taskId,status2,statusMessage,sessionId);const updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification);if(isTerminal(updatedTask.status)){this._cleanupTaskProgressHandler(taskId)}}},listTasks:cursor=>{return taskStore.listTasks(cursor,sessionId)}}}};function isPlainObject2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){const result={...base};for(const key in additional){const k2=key;const addValue=additional[k2];if(addValue===void 0)continue;const baseValue=result[k2];if(isPlainObject2(baseValue)&&isPlainObject2(addValue)){result[k2]={...baseValue,...addValue}}else{result[k2]=addValue}}return result}init_types();var import_ajv=__toESM(require_ajv(),1);var import_ajv_formats=__toESM(require_dist2(),1);function createDefaultAjvInstance(){const ajv=new import_ajv.default({strict:false,validateFormats:true,validateSchema:false,allErrors:true});const addFormats=import_ajv_formats.default;addFormats(ajv);return ajv}var AjvJsonSchemaValidator=class{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){const ajvValidator="$id"in schema&&typeof schema.$id==="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>{const valid=ajvValidator(input);if(valid){return{valid:true,data:input,errorMessage:void 0}}else{return{valid:false,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}}}};init_types();var ExperimentalServerTasks=class{constructor(_server){this._server=_server}requestStream(request2,resultSchema,options){return this._server.requestStream(request2,resultSchema,options)}createMessageStream(params,options){const clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c3=>c3.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c3=>c3.type==="tool_use");if(hasToolResults){if(lastContent.some(c3=>c3.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c3=>c3.type==="tool_use").map(c3=>c3.id));const toolResultIds=new Set(lastContent.filter(c3=>c3.type==="tool_result").map(c3=>c3.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){const clientCapabilities=this._server.getClientCapabilities();const mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}break}case"form":{if(!clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}break}}const normalizedParams=mode==="form"&&params.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"tools/call":if(!requests.tools?.call){throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`)}break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage){throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`)}break;case"elicitation/create":if(!requests.elicitation?.create){throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`)}break;default:break}}var Server=class extends Protocol{constructor(_serverInfo,options){super(options);this._serverInfo=_serverInfo;this._loggingLevels=new Map;this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2]));this.isMessageIgnored=(level,sessionId)=>{const currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):false};this._capabilities=options?.capabilities??{};this._instructions=options?.instructions;this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator;this.setRequestHandler(InitializeRequestSchema,request2=>this._oninitialize(request2));this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.());if(this._capabilities.logging){this.setRequestHandler(SetLevelRequestSchema,async(request2,extra)=>{const transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0;const{level}=request2.params;const parseResult=LoggingLevelSchema.safeParse(level);if(parseResult.success){this._loggingLevels.set(transportSessionId,parseResult.data)}return{}})}}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalServerTasks(this)}}return this._experimental}registerCapabilities(capabilities){if(this.transport){throw new Error("Cannot register capabilities after connecting to transport")}this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){const shape=getObjectShape(requestSchema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}let methodValue;if(isZ4Schema(methodSchema)){const v4Schema=methodSchema;const v4Def=v4Schema._zod?.def;methodValue=v4Def?.value??v4Schema.value}else{const v3Schema=methodSchema;const legacyDef=v3Schema._def;methodValue=legacyDef?.value??v3Schema.value}if(typeof methodValue!=="string"){throw new Error("Schema method literal must be a string")}const method=methodValue;if(method==="tools/call"){const wrappedHandler=async(request2,extra)=>{const validatedRequest=safeParse2(CallToolRequestSchema,request2);if(!validatedRequest.success){const errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}const{params}=validatedRequest.data;const result=await Promise.resolve(handler(request2,extra));if(params.task){const taskValidationResult=safeParse2(CreateTaskResultSchema,result);if(!taskValidationResult.success){const errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}const validationResult=safeParse2(CallToolResultSchema,result);if(!validationResult.success){const errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling){throw new Error(`Client does not support sampling (required for ${method})`)}break;case"elicitation/create":if(!this._clientCapabilities?.elicitation){throw new Error(`Client does not support elicitation (required for ${method})`)}break;case"roots/list":if(!this._clientCapabilities?.roots){throw new Error(`Client does not support listing roots (required for ${method})`)}break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources){throw new Error(`Server does not support notifying about resources (required for ${method})`)}break;case"notifications/tools/list_changed":if(!this._capabilities.tools){throw new Error(`Server does not support notifying of tool list changes (required for ${method})`)}break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts){throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`)}break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url){throw new Error(`Client does not support URL elicitation (required for ${method})`)}break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities){return}switch(method){case"completion/complete":if(!this._capabilities.completions){throw new Error(`Server does not support completions (required for ${method})`)}break;case"logging/setLevel":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts){throw new Error(`Server does not support prompts (required for ${method})`)}break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources){throw new Error(`Server does not support resources (required for ${method})`)}break;case"tools/call":case"tools/list":if(!this._capabilities.tools){throw new Error(`Server does not support tools (required for ${method})`)}break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks){throw new Error(`Server does not support tasks capability (required for ${method})`)}break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){if(!this._capabilities){return}assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request2){const requestedVersion=request2.params.protocolVersion;this._clientCapabilities=request2.params.capabilities;this._clientVersion=request2.params.clientInfo;const protocolVersion=SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION;return{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if(params.tools||params.toolChoice){if(!this._clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c3=>c3.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c3=>c3.type==="tool_use");if(hasToolResults){if(lastContent.some(c3=>c3.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c3=>c3.type==="tool_use").map(c3=>c3.id));const toolResultIds=new Set(lastContent.filter(c3=>c3.type==="tool_result").map(c3=>c3.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}if(params.tools){return this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options)}return this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){const mode=params.mode??"form";switch(mode){case"url":{if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}const urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}const formParams=params.mode==="form"?params:{...params,mode:"form"};const result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema){try{const validator=this._jsonSchemaValidator.getValidator(formParams.requestedSchema);const validationResult=validator(result.content);if(!validationResult.valid){throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error51 instanceof Error?error51.message:String(error51)}`)}}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)")}return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging){if(!this.isMessageIgnored(params.level,sessionId)){return this.notification({method:"notifications/message",params})}}}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};init_types();var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema==="object"&&COMPLETABLE_SYMBOL in schema}function getCompleter(schema){const meta3=schema[COMPLETABLE_SYMBOL];return meta3?.complete}var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name2){const warnings=[];if(name2.length===0){return{isValid:false,warnings:["Tool name cannot be empty"]}}if(name2.length>128){return{isValid:false,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name2.length})`]}}if(name2.includes(" ")){warnings.push("Tool name contains spaces, which may cause parsing issues")}if(name2.includes(",")){warnings.push("Tool name contains commas, which may cause parsing issues")}if(name2.startsWith("-")||name2.endsWith("-")){warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts")}if(name2.startsWith(".")||name2.endsWith(".")){warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts")}if(!TOOL_NAME_REGEX.test(name2)){const invalidChars=name2.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c3=>`"${c3}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");return{isValid:false,warnings}}return{isValid:true,warnings}}function issueToolNameWarning(name2,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name2}":`);for(const warning of warnings){console.warn(` - ${warning}`)}console.warn("Tool registration will proceed, but this may cause compatibility issues.");console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name2){const result=validateToolName(name2);issueToolNameWarning(name2,result.warnings);return result.isValid}var ExperimentalMcpServerTasks=class{constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name2,config2,handler){const execution={taskSupport:"required",...config2.execution};if(execution.taskSupport==="forbidden"){throw new Error(`Cannot register task-based tool '${name2}' with taskSupport 'forbidden'. Use registerTool() instead.`)}const mcpServerInternal=this._mcpServer;return mcpServerInternal._createRegisteredTool(name2,config2.title,config2.description,config2.inputSchema,config2.outputSchema,config2.annotations,execution,config2._meta,handler)}};init_external();init_external();var McpServer=class{constructor(serverInfo,options){this._registeredResources={};this._registeredResourceTemplates={};this._registeredTools={};this._registeredPrompts={};this._toolHandlersInitialized=false;this._completionHandlerInitialized=false;this._resourceHandlersInitialized=false;this._promptHandlersInitialized=false;this.server=new Server(serverInfo,options)}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalMcpServerTasks(this)}}return this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));this.server.registerCapabilities({tools:{listChanged:true}});this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name2,tool])=>{const toolDefinition={name:name2,title:tool.title,description:tool.description,inputSchema:(()=>{const obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){const obj=normalizeObjectSchema(tool.outputSchema);if(obj){toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"output"})}}return toolDefinition})}));this.server.setRequestHandler(CallToolRequestSchema,async(request2,extra)=>{try{const tool=this._registeredTools[request2.params.name];if(!tool){throw new McpError(ErrorCode.InvalidParams,`Tool ${request2.params.name} not found`)}if(!tool.enabled){throw new McpError(ErrorCode.InvalidParams,`Tool ${request2.params.name} disabled`)}const isTaskRequest=!!request2.params.task;const taskSupport=tool.execution?.taskSupport;const isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler){throw new McpError(ErrorCode.InternalError,`Tool ${request2.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`)}if(taskSupport==="required"&&!isTaskRequest){throw new McpError(ErrorCode.MethodNotFound,`Tool ${request2.params.name} requires task augmentation (taskSupport: 'required')`)}if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler){return await this.handleAutomaticTaskPolling(tool,request2,extra)}const args=await this.validateToolInput(tool,request2.params.arguments,request2.params.name);const result=await this.executeToolHandler(tool,args,extra);if(isTaskRequest){return result}await this.validateToolOutput(tool,result,request2.params.name);return result}catch(error51){if(error51 instanceof McpError){if(error51.code===ErrorCode.UrlElicitationRequired){throw error51}}return this.createToolError(error51 instanceof Error?error51.message:String(error51))}});this._toolHandlersInitialized=true}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:true}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema){return void 0}const inputObj=normalizeObjectSchema(tool.inputSchema);const schemaToParse=inputObj??tool.inputSchema;const parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema){return}if(!("content"in result)){return}if(result.isError){return}if(!result.structuredContent){throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`)}const outputObj=normalizeObjectSchema(tool.outputSchema);const parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`)}}async executeToolHandler(tool,args,extra){const handler=tool.handler;const isTaskHandler="createTask"in handler;if(isTaskHandler){if(!extra.taskStore){throw new Error("No task store provided.")}const taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request2,extra){if(!extra.taskStore){throw new Error("No task store provided for task-capable tool.")}const args=await this.validateToolInput(tool,request2.params.arguments,request2.params.name);const handler=tool.handler;const taskExtra={...extra,taskStore:extra.taskStore};const createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra));const taskId=createTaskResult.task.taskId;let task=createTaskResult.task;const pollInterval=task.pollInterval??5e3;while(task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled"){await new Promise(resolve3=>setTimeout(resolve3,pollInterval));const updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask){throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`)}task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){if(this._completionHandlerInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));this.server.registerCapabilities({completions:{}});this.server.setRequestHandler(CompleteRequestSchema,async request2=>{switch(request2.params.ref.type){case"ref/prompt":assertCompleteRequestPrompt(request2);return this.handlePromptCompletion(request2,request2.params.ref);case"ref/resource":assertCompleteRequestResourceTemplate(request2);return this.handleResourceCompletion(request2,request2.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request2.params.ref}`)}});this._completionHandlerInitialized=true}async handlePromptCompletion(request2,ref){const prompt=this._registeredPrompts[ref.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`)}if(!prompt.argsSchema){return EMPTY_COMPLETION_RESULT}const promptShape=getObjectShape(prompt.argsSchema);const field=promptShape?.[request2.params.argument.name];if(!isCompletable(field)){return EMPTY_COMPLETION_RESULT}const completer=getCompleter(field);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request2.params.argument.value,request2.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request2,ref){const template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri]){return EMPTY_COMPLETION_RESULT}throw new McpError(ErrorCode.InvalidParams,`Resource template ${request2.params.ref.uri} not found`)}const completer=template.resourceTemplate.completeCallback(request2.params.argument.name);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request2.params.argument.value,request2.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));this.server.registerCapabilities({resources:{listChanged:true}});this.server.setRequestHandler(ListResourcesRequestSchema,async(request2,extra)=>{const resources2=Object.entries(this._registeredResources).filter(([_3,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata}));const templateResources=[];for(const template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback){continue}const result=await template.resourceTemplate.listCallback(extra);for(const resource of result.resources){templateResources.push({...template.metadata,...resource})}}return{resources:[...resources2,...templateResources]}});this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>{const resourceTemplates=Object.entries(this._registeredResourceTemplates).map(([name2,template])=>({name:name2,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}));return{resourceTemplates}});this.server.setRequestHandler(ReadResourceRequestSchema,async(request2,extra)=>{const uri=new URL(request2.params.uri);const resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled){throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`)}return resource.readCallback(uri,extra)}for(const template of Object.values(this._registeredResourceTemplates)){const variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables){return template.readCallback(uri,variables,extra)}}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)});this._resourceHandlersInitialized=true}setPromptRequestHandlers(){if(this._promptHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));this.server.registerCapabilities({prompts:{listChanged:true}});this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name2,prompt])=>{return{name:name2,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}})}));this.server.setRequestHandler(GetPromptRequestSchema,async(request2,extra)=>{const prompt=this._registeredPrompts[request2.params.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request2.params.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request2.params.name} disabled`)}if(prompt.argsSchema){const argsObj=normalizeObjectSchema(prompt.argsSchema);const parseResult=await safeParseAsync2(argsObj,request2.params.arguments);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request2.params.name}: ${errorMessage}`)}const args=parseResult.data;const cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{const cb=prompt.callback;return await Promise.resolve(cb(extra))}});this._promptHandlersInitialized=true}resource(name2,uriOrTemplate,...rest){let metadata2;if(typeof rest[0]==="object"){metadata2=rest.shift()}const readCallback=rest[0];if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name2,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name2]){throw new Error(`Resource template ${name2} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name2,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}registerResource(name2,uriOrTemplate,config2,readCallback){if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name2,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name2]){throw new Error(`Resource template ${name2} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name2,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}_createRegisteredResource(name2,title2,uri,metadata2,readCallback){const registeredResource={name:name2,title:title2,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResource.update({enabled:false}),enable:()=>registeredResource.update({enabled:true}),remove:()=>registeredResource.update({uri:null}),update:updates=>{if(typeof updates.uri!=="undefined"&&updates.uri!==uri){delete this._registeredResources[uri];if(updates.uri)this._registeredResources[updates.uri]=registeredResource}if(typeof updates.name!=="undefined")registeredResource.name=updates.name;if(typeof updates.title!=="undefined")registeredResource.title=updates.title;if(typeof updates.metadata!=="undefined")registeredResource.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResource.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResource.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResources[uri]=registeredResource;return registeredResource}_createRegisteredResourceTemplate(name2,title2,template,metadata2,readCallback){const registeredResourceTemplate={resourceTemplate:template,title:title2,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResourceTemplate.update({enabled:false}),enable:()=>registeredResourceTemplate.update({enabled:true}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){delete this._registeredResourceTemplates[name2];if(updates.name)this._registeredResourceTemplates[updates.name]=registeredResourceTemplate}if(typeof updates.title!=="undefined")registeredResourceTemplate.title=updates.title;if(typeof updates.template!=="undefined")registeredResourceTemplate.resourceTemplate=updates.template;if(typeof updates.metadata!=="undefined")registeredResourceTemplate.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResourceTemplate.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResourceTemplate.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[name2]=registeredResourceTemplate;const variableNames=template.uriTemplate.variableNames;const hasCompleter=Array.isArray(variableNames)&&variableNames.some(v3=>!!template.completeCallback(v3));if(hasCompleter){this.setCompletionRequestHandler()}return registeredResourceTemplate}_createRegisteredPrompt(name2,title2,description,argsSchema,callback){const registeredPrompt={title:title2,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:true,disable:()=>registeredPrompt.update({enabled:false}),enable:()=>registeredPrompt.update({enabled:true}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){delete this._registeredPrompts[name2];if(updates.name)this._registeredPrompts[updates.name]=registeredPrompt}if(typeof updates.title!=="undefined")registeredPrompt.title=updates.title;if(typeof updates.description!=="undefined")registeredPrompt.description=updates.description;if(typeof updates.argsSchema!=="undefined")registeredPrompt.argsSchema=objectFromShape(updates.argsSchema);if(typeof updates.callback!=="undefined")registeredPrompt.callback=updates.callback;if(typeof updates.enabled!=="undefined")registeredPrompt.enabled=updates.enabled;this.sendPromptListChanged()}};this._registeredPrompts[name2]=registeredPrompt;if(argsSchema){const hasCompletable=Object.values(argsSchema).some(field=>{const inner=field instanceof ZodOptional2?field._def?.innerType:field;return isCompletable(inner)});if(hasCompletable){this.setCompletionRequestHandler()}}return registeredPrompt}_createRegisteredTool(name2,title2,description,inputSchema,outputSchema,annotations,execution,_meta,handler){validateAndWarnToolName(name2);const registeredTool={title:title2,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations,execution,_meta,handler,enabled:true,disable:()=>registeredTool.update({enabled:false}),enable:()=>registeredTool.update({enabled:true}),remove:()=>registeredTool.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name2){if(typeof updates.name==="string"){validateAndWarnToolName(updates.name)}delete this._registeredTools[name2];if(updates.name)this._registeredTools[updates.name]=registeredTool}if(typeof updates.title!=="undefined")registeredTool.title=updates.title;if(typeof updates.description!=="undefined")registeredTool.description=updates.description;if(typeof updates.paramsSchema!=="undefined")registeredTool.inputSchema=objectFromShape(updates.paramsSchema);if(typeof updates.outputSchema!=="undefined")registeredTool.outputSchema=objectFromShape(updates.outputSchema);if(typeof updates.callback!=="undefined")registeredTool.handler=updates.callback;if(typeof updates.annotations!=="undefined")registeredTool.annotations=updates.annotations;if(typeof updates._meta!=="undefined")registeredTool._meta=updates._meta;if(typeof updates.enabled!=="undefined")registeredTool.enabled=updates.enabled;this.sendToolListChanged()}};this._registeredTools[name2]=registeredTool;this.setToolRequestHandlers();this.sendToolListChanged();return registeredTool}tool(name2,...rest){if(this._registeredTools[name2]){throw new Error(`Tool ${name2} is already registered`)}let description;let inputSchema;let outputSchema;let annotations;if(typeof rest[0]==="string"){description=rest.shift()}if(rest.length>1){const firstArg=rest[0];if(isZodRawShapeCompat(firstArg)){inputSchema=rest.shift();if(rest.length>1&&typeof rest[0]==="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])){annotations=rest.shift()}}else if(typeof firstArg==="object"&&firstArg!==null){if(Object.values(firstArg).some(v3=>typeof v3==="object"&&v3!==null)){throw new Error(`Tool ${name2} expected a Zod schema or ToolAnnotations, but received an unrecognized object`)}annotations=rest.shift()}}const callback=rest[0];return this._createRegisteredTool(name2,void 0,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},void 0,callback)}registerTool(name2,config2,cb){if(this._registeredTools[name2]){throw new Error(`Tool ${name2} is already registered`)}const{title:title2,description,inputSchema,outputSchema,annotations,_meta}=config2;return this._createRegisteredTool(name2,title2,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},_meta,cb)}prompt(name2,...rest){if(this._registeredPrompts[name2]){throw new Error(`Prompt ${name2} is already registered`)}let description;if(typeof rest[0]==="string"){description=rest.shift()}let argsSchema;if(rest.length>1){argsSchema=rest.shift()}const cb=rest[0];const registeredPrompt=this._createRegisteredPrompt(name2,void 0,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}registerPrompt(name2,config2,cb){if(this._registeredPrompts[name2]){throw new Error(`Prompt ${name2} is already registered`)}const{title:title2,description,argsSchema}=config2;const registeredPrompt=this._createRegisteredPrompt(name2,title2,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){if(this.isConnected()){this.server.sendResourceListChanged()}}sendToolListChanged(){if(this.isConnected()){this.server.sendToolListChanged()}}sendPromptListChanged(){if(this.isConnected()){this.server.sendPromptListChanged()}}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value==="object"&&"parse"in value&&typeof value.parse==="function"&&"safeParse"in value&&typeof value.safeParse==="function"}function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}function isZodRawShapeCompat(obj){if(typeof obj!=="object"||obj===null){return false}if(isZodSchemaInstance(obj)){return false}if(Object.keys(obj).length===0){return true}return Object.values(obj).some(isZodTypeLike)}function getZodSchemaObject(schema){if(!schema){return void 0}if(isZodRawShapeCompat(schema)){return objectFromShape(schema)}if(!isZodSchemaInstance(schema)){throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object")}return schema}function promptArgumentsFromSchema(schema){const shape=getObjectShape(schema);if(!shape)return[];return Object.entries(shape).map(([name2,field])=>{const description=getSchemaDescription(field);const isOptional=isSchemaOptional(field);return{name:name2,description,required:!isOptional}})}function getMethodValue(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value==="string"){return value}throw new Error("Schema method literal must be a string")}function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:false}};init_types();init_types();import{createHash as createHash11}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var pinDocAssets=typeof __pinCodexPersonalDocs!=="undefined"&&__pinCodexPersonalDocs;function assetReader(file2){const read=()=>readFileSync6(join8(import.meta.dirname,file2));if(!pinDocAssets)return read;try{const packed=read();return()=>packed}catch(error51){return()=>{throw error51}}}var readCorpusData=assetReader("docs-bundle.bin");var readIndexData=assetReader("docs-index.bin");var DOCS_VERSION="0.193.1";function loadDocsMetadata(){return{"version":"0.193.1","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"acp-clients","title":"Use an ACP client","kind":"Guide","category":"Guide","summary":"Spawn and drive Cotal agents from T3 Code, Zed and other Agent Client Protocol clients."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"artifacts","title":"Artifacts","kind":"Concept (informative)","category":"Concept","summary":"How agents share bytes too large for a message, who may read them, and how long they last."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-chatgpt","title":"Connect ChatGPT","kind":"Guide (informative)","category":"Guide","summary":"Use your Cotal agents from ChatGPT on the web, by voice, and in the ChatGPT desktop app."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-mcp","title":"MCP-only hosts","kind":"Guide","category":"Guide","summary":"Connect an application that supports stdio MCP but has no native Cotal connector."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, resume records, the agent endpoint, agent commands, and the prompt desk."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, agent commands, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command or install the Linux desktop packages."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, agent commands, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrade-matrix","title":"Run the upgrade matrix","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal's upgrade matrix uses the same native harness for release checks and operator diagnostics."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"A user-auth terminal connection closes when the full auth service or a callout replica confirms that its session ended and delivery disconnects it."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readCorpusData();if(packed.length!==1599309||createHash11("sha256").update(packed).digest("hex")!=="2051344d734473506b450de6fca928f90c17d6e553943ce8bf21189b5a3b3e07")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it for Cotal 0.193.1: "+(pinDocAssets?"the file read at startup did not match this server. Run `cotal setup` again, then start a new Codex conversation":"it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version"));return corpusPacked=packed}var sourceBounds=[[0,2216],[2216,4210],[4210,9832],[9832,33539],[33539,38358],[38358,42817],[42817,52821],[52821,56543],[56543,64009],[64009,68284],[68284,70128],[70128,80711],[80711,84863],[84863,94512],[94512,96882],[96882,100991],[100991,144056],[144056,164420],[164420,182869],[182869,207403],[207403,229701],[229701,248234],[248234,267647],[267647,308924],[308924,315407],[315407,330430],[330430,356922],[356922,362797],[362797,420420],[420420,435004],[435004,479120],[479120,499715],[499715,529778],[529778,567922],[567922,586578],[586578,588568],[588568,606158],[606158,626069],[626069,628896],[628896,640695],[640695,647485],[647485,652624],[652624,656388],[656388,658317],[658317,661126],[661126,664810],[664810,680663],[680663,683256],[683256,687523],[687523,703937],[703937,714289],[714289,718291],[718291,725775],[725775,731213],[731213,734412],[734412,745137],[745137,748114],[748114,756904],[756904,759894],[759894,767584],[767584,782725],[782725,797035],[797035,804685],[804685,817610],[817610,820959],[820959,823908],[823908,831529],[831529,835566],[835566,837776],[837776,841627],[841627,845044],[845044,846158],[846158,847907],[847907,851570],[851570,863550],[863550,870235],[870235,881119],[881119,896654],[896654,902880],[902880,920907],[920907,926294],[926294,931703],[931703,934220],[934220,939821],[939821,955624],[955624,962707],[962707,978693],[978693,979510],[979510,988719],[988719,995271],[995271,998993],[998993,1003558],[1003558,1008940],[1008940,1014884],[1014884,1018306],[1018306,1022699],[1022699,1027864],[1027864,1032264],[1032264,1047719],[1047719,1051240],[1051240,1053923],[1053923,1056590],[1056590,1060352],[1060352,1070085],[1070085,1075149],[1075149,1094187],[1094187,1104021],[1104021,1184389],[1184389,1187680],[1187680,1189028],[1189028,1197560],[1197560,1207022],[1207022,1218760],[1218760,1227993],[1227993,1233176],[1233176,1552113],[1552113,1592350],[1592350,1599309]];var sourceLengths=[4862,4503,14192,94979,13374,10930,29189,37145,19804,10384,4159,89533,37758,25077,5365,10128,119539,56834,53242,72518,63505,54968,55066,122854,16410,41602,77640,13916,173049,41858,137631,60156,92580,119552,53046,8376,48495,54485,7282,32939,17959,12907,9046,4097,6611,8634,45186,6436,10360,44629,26313,10054,48045,13925,7850,28279,7140,23075,6860,19775,40387,38542,19825,33604,8355,7031,19765,9132,5100,9136,9930,2248,5412,9845,33077,16239,27924,40357,17590,49823,12378,13771,8235,14854,109088,17745,43409,1638,23339,17191,8817,11183,13497,14915,7511,11303,12695,10587,41760,8615,6405,6095,9386,29657,12679,57904,25837,237306,7461,2878,21488,24494,30591,22298,12616,938287,113864,30479];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readIndexData();if(packed.length!==762911||createHash11("sha256").update(packed).digest("hex")!=="6c2e904c2aa4f692a4000fa179c4259c60666f177c3db898baa2fbe9a7fad26c")throw new Error("docs data file docs-index.bin beside this module is not the one built with it for Cotal 0.193.1: "+(pinDocAssets?"the file read at startup did not match this server. Run `cotal setup` again, then start a new Codex conversation":"it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version"));return gunzipSync(packed)}var TOKEN3=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN3);if(!raw)return[];const out=[];for(const r2 of raw){if(r2.length>=2)out.push(r2);const t2=r2.replace(EDGE,"");if(t2.length>=2&&t2!==r2)out.push(t2);if(t2.includes(".")){for(const seg of t2.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i2)=>length2!==bodyLengths[i2]))throw new Error("docs index does not match the docs bundle it is searching");const n2=header.sections;const length=4*n2+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i2=0;i2<length;i2++)columns[i2]=bytes.readUInt32LE(4+headerLength+4*i2);const offsets=4*n2;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i2=0;i2<n2;i2++)total+=columns[3*n2+i2];return{sections:n2,terms:header.terms,headings:header.headings,source:columns.subarray(0,n2),start:columns.subarray(n2,2*n2),end:columns.subarray(2*n2,3*n2),length:columns.subarray(3*n2,4*n2),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n2)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page2=pages.get(source);if(!page2){page2={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page2)}return page2}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page2){const meta3=metadata();loadDocsSourceLengths();const reference=page2.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p2,source2)=>(pages.get(source2)??p2).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b3=metadata();const rows=b3.pages.map(p2=>{const kind=p2.kind?`: ${p2.kind}`:"";return`- \`${p2.slug}\`${kind}
144
144
  ${p2.summary}`});return[`# Cotal v${b3.version} documentation`,"","The authoritative docs bundled with this installed version. This index lists what","exists; it holds no answers itself. Your next call:",'- Know the page? Read it in full: `cotal_docs(page: "<slug>")` (e.g. "spec", "architecture").','- Not sure which page? Search: `cotal_docs(query: "\u2026")` returns the most relevant sections.',"Prefer these docs over training memory, and read the full page before writing code or wire","frames. Docs are bundled and version-exact; add `refresh: true` to also pull any patches","published to docs.cotal.ai for this same version.","","## The normative sources",`- \`spec\`: ${b3.spec.title} (the wire contract; where a page disagrees, the spec wins)`,`- \`lang\`: ${b3.lang.title} (the workflow language a durable run executes; spec \xA714)`,`- \`schema\`: ${b3.schema.title} (authoritative for message shapes)`,"","## Pages",...rows].join("\n")}function renderPage(p2,note){return`${note}
145
145
 
146
146
  ${p2.body}`.trimStart()}var K1=1.2;var B2=.75;function sources(){const b3=metadata();return[...b3.pages.map((page2,source)=>pages.get(source)??page2),{slug:"spec",...b3.spec},{slug:"lang",...b3.lang},{slug:"schema",...b3.schema}]}var index;function searchIndex(){if(index)return index;const lengths=loadDocsSourceLengths();for(const[source,page2]of pages)lengths[source]=page2.body.length;return index=decodeIndex(loadDocsIndex(),lengths,DOCS_VERSION)}function termId(terms,term){let low=0;let high=terms.length-1;while(low<=high){const mid=low+high>>>1;const candidate2=terms[mid];if(candidate2===term)return mid;if(candidate2<term)low=mid+1;else high=mid-1}return-1}function searchDocs(query,limit=5){if(limit<=0)return[];let terms=tokenize(query).filter(t2=>!STOP.has(t2));if(!terms.length)terms=tokenize(query);const termSet=new Set(terms);if(!termSet.size)return[];const idx=searchIndex();const N2=idx.sections;const scores=new Float64Array(N2);for(const t2 of termSet){const id2=termId(idx.terms,t2);if(id2<0)continue;const from=idx.offsets[id2];const to=idx.offsets[id2+1];const n2=to-from;const idf=Math.log(1+(N2-n2+.5)/(n2+.5));for(let p2=from;p2<to;p2++){const s3=idx.postSection[p2];const f2=idx.postWeight[p2];scores[s3]+=idf*(f2*(K1+1)/(f2+K1*(1-B2+B2*idx.length[s3]/idx.avgdl)))}}const scored=[];for(let s3=0;s3<N2;s3++)if(scores[s3]>0)scored.push({s:s3,score:scores[s3]});scored.sort((a3,b3)=>b3.score-a3.score);const all=sources();const perPage=new Map;const hits=[];for(const{s:s3,score}of scored){const source=all[idx.source[s3]];const seen=perPage.get(source.slug)??0;if(seen>=2)continue;perPage.set(source.slug,seen+1);hits.push({slug:source.slug,pageTitle:source.title,heading:idx.headings[s3],text:sourceBody(idx.source[s3]).slice(idx.start[s3],idx.end[s3]),score});if(hits.length>=limit)break}return hits}function capSection(text5,maxLines=48){const lines=text5.split("\n");if(lines.length<=maxLines)return text5.trim();return lines.slice(0,maxLines).join("\n").trimEnd()+"\n\n\u2026 (section continues; read the full page)"}function renderSearch(query,hits){loadDocsSourceLengths();if(!hits.length){return`No matches for "${query}" in the Cotal v${DOCS_VERSION} docs. Call cotal_docs() for the page index, or search an exact identifier (a subject, a cotal_* tool, a field name).`}const blocks=hits.map(h3=>`## ${h3.heading}