@cotal-ai/connector-codex 0.171.0 → 0.171.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.
package/dist/host.js CHANGED
@@ -127,7 +127,7 @@ data:
127
127
  `}}function tryAcquireOnce({path,nonce:nonce4,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce:nonce4,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===nonce4){try{unlinkSync2(path)}catch{}}}}}}const inspection=inspectLockSnapshot(path);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path,opts);const deadline=Date.now()+waitMs;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path,opts,result.owner,waitMs);sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path,opts,owner2,waitMs){return opts.onTimeout?.(owner2)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner2.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path}`)}import{createHash}from"node:crypto";import{lstatSync as lstatSync2,mkdirSync as mkdirSync3}from"node:fs";import{userInfo}from"node:os";import{join as join2}from"node:path";var LocalConsumerHeldError=class extends Error{};function localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid){const user=userInfo();const root=process.platform==="linux"?`/tmp/cotal-consumers-${user.uid}`:join2(user.homedir,".cotal-consumers");mkdirSync3(root,{recursive:true,mode:448});const st2=lstatSync2(root);if(!st2.isDirectory()||st2.isSymbolicLink()||process.platform!=="win32"&&(st2.uid!==user.uid||(st2.mode&63)!==0))throw new Error("local consumer custody directory is not private to this OS user");const targets=[...new Set(servers.split(",").map(s3=>{const u2=new URL(s3.trim().includes("://")?s3.trim():`nats://${s3.trim()}`);u2.username="";u2.password="";if(!u2.port)u2.port=u2.protocol==="nats:"?"4222":u2.protocol==="wss:"?"443":"80";return u2.href}))].sort();const key=createHash("sha256").update(JSON.stringify([targets,space2,owner2,actor2,lifecycleUid])).digest("hex");const path=join2(root,`${key}.lock`);try{const file2=lstatSync2(path);if(!file2.isFile()||file2.isSymbolicLink()||process.platform!=="win32"&&(file2.uid!==user.uid||(file2.mode&63)!==0))throw new Error("local consumer custody file is not private to this OS user")}catch(error51){if(error51.code!=="ENOENT")throw error51}return path}function acquireLocalConsumer(servers,space2,owner2,actor2,lifecycleUid){return acquireLock(localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid),{waitMs:0,label:"local inbox consumer",onTimeout:()=>new LocalConsumerHeldError(`local inbox already has a consuming session for ${owner2}.${actor2} in space "${space2}"; preserve that session and choose a distinct actor for a new launch`)})}init_subjects();init_endpoint_subjects();init_canonical();init_endpoint_error();init_endpoint_grants();init_endpoint_subjects();init_issued_authority();init_subjects();init_registry_contract();init_agent_endpoint();init_registry_client();init_endpoint_envelope();init_endpoint_records();init_lifecycle_state();init_environment_manager_grants();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_identity();init_subjects();init_lifecycle_state();var dec6=new TextDecoder;init_endpoint_envelope();init_endpoint_records();init_subjects();init_lifecycle_state();var enc6=new TextEncoder;init_endpoint_cluster();init_endpoint_journal();init_endpoint_binding();init_endpoint_binding();init_canonical();init_space_resource_definitions();init_space_quiescence_resources();init_space_deletion_targets();init_endpoint_envelope();init_broker_identity();var import_jetstream24=__toESM(require_mod4(),1);var import_transport_node24=__toESM(require_transport_node(),1);init_jetstream_missing();init_space_resource_definitions();var import_kv11=__toESM(require_mod6(),1);init_subjects();init_channels();init_space_resource_definitions();init_canonical();init_channels();init_subjects();init_space_resource_definitions();var DEFAULT_FIELDS={replay:true,replayWindow:true,deliveryClass:true};var CHANNEL_FIELDS={...DEFAULT_FIELDS,description:true,instructions:true};init_space_resource_definitions();init_endpoint_binding();init_issued_authority();init_run_admission();init_streams();init_backup_config();init_canonical();var import_jetstream25=__toESM(require_mod4(),1);init_endpoint_service();init_endpoint_service();init_endpoint_invoke();init_endpoint_call();init_endpoint_envelope();init_kv_scan();init_canonical();init_service_gate();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_lifecycle_state();var enc7=new TextEncoder;var dec7=new TextDecoder;init_endpoint_envelope();init_endpoint_subjects();init_subjects();init_endpoint_serve();init_endpoint_describe_observation();init_endpoint_verbs();init_endpoint_invoke();var import_jetstream26=__toESM(require_mod4(),1);var import_transport_node25=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_deadline();init_endpoint_subjects();init_endpoint_records();init_endpoint_journal();init_endpoint_binding();var import_jetstream27=__toESM(require_mod4(),1);var import_transport_node26=__toESM(require_transport_node(),1);init_endpoint_binding();init_endpoint_records();init_jetstream_missing();init_endpoint_action();init_endpoint_error();var COMMON_FIELDS=["v","executor","attemptId","ts","phase"];var PHASE_FIELDS={claimed:COMMON_FIELDS,launching:[...COMMON_FIELDS,"addr"],launched:[...COMMON_FIELDS,"addr"],settled:[...COMMON_FIELDS,"addr"]};init_endpoint_error();var BASE=["v","ts","state","claimant"];var STATE_FIELDS={claimed:BASE,launching:[...BASE,"lifecycleUid","launchAttemptId","executor"],live:[...BASE,"lifecycleUid","runtimeOwner"],preserved:[...BASE,"lifecycleUid","runtimeOwner"],relaunching:[...BASE,"lifecycleUid","launchAttemptId","executor"],draining:[...BASE,"lifecycleUid","runtimeOwner","enteredAt"],released:BASE};init_endpoint_checkpoint();init_endpoint_contract_store();init_lifecycle_state();init_endpoint_service();init_evict();init_endpoint_guard();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_signing();var HANDLE_MAX_LIVE_TTL_MS=24*60*60*1e3;var HANDLE_MAX_STURDY_TTL_MS=30*24*60*60*1e3;var HANDLE_MAX_BYTES=64*1024;init_endpoint_envelope();init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_signing();init_endpoint_error();init_endpoint_subjects();var SESSION_GRANT_MAX_TTL_MS=24*60*60*1e3;var SESSION_GRANT_MAX_BYTES=16*1024;var SESSION_TERMINAL_STATES=Object.freeze(["closed","expired","superseded","retired"]);var TERMINAL_STATE_SNAP=new Set(SESSION_TERMINAL_STATES);init_endpoint_error();var MAX_B64_CHARS=4*1024*1024;var B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var B64_INV=(()=>{const m2=new Int16Array(128).fill(-1);for(let i2=0;i2<B64_ALPHABET.length;i2++)m2[B64_ALPHABET.charCodeAt(i2)]=i2;return m2})();init_endpoint_envelope();init_endpoint_binding();var import_jetstream28=__toESM(require_mod4(),1);init_endpoint_supervisor();init_endpoint_service();init_endpoint_records();init_endpoint_subjects();init_subjects();init_endpoint_receipt();init_endpoint_signing();var RENEW_AT_FRACTION=1/3;var OVERLAP_MS=10*60*1e3;init_endpoint_traits();init_safe_pattern();init_resolve();function presenceAges(p2,now){return{conditionSince:ageAt(now,p2.condition?.since),statusSince:ageAt(now,p2.statusSince),activitySince:p2.activity?ageAt(now,p2.activitySince):void 0,activeAt:ageAt(now,p2.activeAt)}}function formatAge(ms){const s3=Math.floor(ms/1e3);if(s3<60)return`${s3}s`;if(s3<3600)return`${Math.floor(s3/60)}m`;if(s3<86400)return`${Math.floor(s3/3600)}h`;return`${Math.floor(s3/86400)}d`}function ageAt(now,at2){if(typeof at2!=="number"||!Number.isFinite(at2))return void 0;return Math.max(0,now-at2)}init_process_runtime();function oneLine(text3){return text3.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu,c3=>{let escaped="";for(let i2=0;i2<c3.length;i2++)escaped+=`\\u${c3.charCodeAt(i2).toString(16).padStart(4,"0")}`;return escaped})}var PRESENCE_TEXT_MAX=200;function presenceText(text3){const shown=Array.from(text3,oneLine);const width=s3=>[...s3].length;if(shown.reduce((n3,s3)=>n3+width(s3),0)<=PRESENCE_TEXT_MAX)return shown.join("");let kept="";let n2=0;for(const s3 of shown){n2+=width(s3);if(n2>PRESENCE_TEXT_MAX-1)break;kept+=s3}return`${kept}\u2026`}init_connection_cleanup();init_native_connection();init_text_encoding();function parseJoinLink(link){const tls=link.startsWith("cotals://");if(!tls&&!link.startsWith("cotal://"))throw new Error(`not a Cotal link (expected cotal:// or cotals://): ${link}`);const u2=new URL(link.replace(/^cotals?:\/\//,tls?"https://":"http://"));if(!u2.hostname)throw new Error(`Cotal link has no host: ${link}`);const space2=decodeURIComponent(u2.pathname.replace(/^\/+/,"").split("/")[0]??"");if(!space2)throw new Error(`Cotal link has no space (cotal://host/<space>): ${link}`);const chParam=u2.searchParams.get("channels")??u2.searchParams.get("channel");const channels=chParam?chParam.split(",").map(s3=>s3.trim()).filter(Boolean):void 0;const user=u2.username?decodeURIComponent(u2.username):void 0;const pass=u2.password?decodeURIComponent(u2.password):void 0;return{servers:`nats://${u2.hostname}:${u2.port||"4222"}`,space:space2,channels,tls,token:user&&!pass?user:void 0,user:pass?user:void 0,pass:pass||void 0}}function brokerUrlHasUserinfo(servers){return servers.split(",").some(entry=>/^[^:/?#]+:\/\/[^/?#]*@/.test(entry.includes("://")?entry.trim():`nats://${entry.trim()}`))}init_identity();init_secret_store();init_provision();init_jwt();var import_nkeys10=__toESM(require_mod(),1);init_identity();init_nkey_signer();init_jwt();var import_nkeys11=__toESM(require_mod(),1);init_subjects();init_streams();init_anycast_requests();init_transfer();init_backup_config();init_backup();init_channels();init_members();init_acls();init_connection_cleanup();init_native_connection();var import_transport_node27=__toESM(require_transport_node(),1);init_endpoint();var import_kv12=__toESM(require_mod6(),1);init_subjects();init_members();init_kv_scan();init_identity();init_deadline();init_jetstream_missing();init_evict();init_lease();init_liveness();init_agent_file();import{lstatSync as lstatSync4,mkdirSync as mkdirSync5,unlinkSync as unlinkSync3}from"node:fs";import{join as join3}from"node:path";function ensureDirNoSymlink(parent,...segments){let dir=parent;for(const seg of segments){dir=join3(dir,seg);let st2;try{st2=lstatSync4(dir)}catch(e3){if(e3.code==="ENOENT"){mkdirSync5(dir,{mode:448});continue}throw e3}if(st2.isSymbolicLink())throw new Error(`refusing to write under "${dir}": it is a symlink`);if(!st2.isDirectory())throw new Error(`refusing to write under "${dir}": not a directory`)}return dir}init_secret_fs();init_secret_fs();import{mkdtempSync,readFileSync as readFileSync3,realpathSync as realpathSync2,rmSync as rmSync2,rmdirSync,statSync as statSync3}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname as dirname4,join as join4,resolve as resolve2}from"node:path";import{createHmac,randomBytes as randomBytes3,timingSafeEqual}from"node:crypto";import{lstatSync as lstatSync5}from"node:fs";import{dirname as dirname3}from"node:path";var CONTROL_PROTOCOL_VERSION=1;var CONTROL_SERVER_AUTH_DEADLINE_MS=5e3;var MAX_HANDSHAKE_LINE_BYTES=1024;var MAX_CONTROL_REQUEST_BYTES=1<<20;var BASE64URL_43=/^[A-Za-z0-9_-]{43}$/;var MAC_CHARS=43;var MAC_PREFIX_BYTES=MAC_CHARS+1;var NEWLINE=10;var SPACE=32;var utf8=new TextDecoder("utf-8",{fatal:true});function assertControlVersion(version2,where){if(version2===CONTROL_PROTOCOL_VERSION)return;throw new Error(`${where} carries control protocol version ${JSON.stringify(version2)}, and this build speaks only version ${CONTROL_PROTOCOL_VERSION}. A launcher and connector from different releases refuse each other instead of falling back; upgrade both to the same release.`)}function assertControlEndpoint(endpoint){assertControlVersion(endpoint.version,"the control endpoint");if(typeof endpoint.token!=="string"||!endpoint.token)throw new Error("the control endpoint has no key")}function transcriptMac(token2,role,nc,ns,body){const mac3=createHmac("sha256",Buffer.from(token2,"utf8"));mac3.update(`cotal-control/${CONTROL_PROTOCOL_VERSION}\0${role}\0${nc}\0${ns}`,"utf8");if(body!==void 0)mac3.update("\0","utf8").update(body);return mac3.digest("base64url")}function macMatches(presented,expected){if(typeof presented!=="string"||!BASE64URL_43.test(presented))return false;return timingSafeEqual(Buffer.from(presented,"ascii"),Buffer.from(expected,"ascii"))}function openSealed(line,expected){if(line.length<MAC_PREFIX_BYTES||line[MAC_CHARS]!==SPACE)return void 0;const body=line.subarray(MAC_PREFIX_BYTES);if(!macMatches(line.subarray(0,MAC_CHARS).toString("latin1"),expected(body)))return void 0;try{return utf8.decode(body)}catch{return void 0}}function parseHandshake(line){try{const value=JSON.parse(utf8.decode(line));return value&&typeof value==="object"&&!Array.isArray(value)?value:void 0}catch{return void 0}}function lineReader(cap,onLine,oversize){let buf=Buffer.alloc(0);let stopped=false;return chunk=>{if(stopped)return;buf=buf.length?Buffer.concat([buf,chunk]):chunk;for(;;){const limit=cap();const nl=buf.indexOf(NEWLINE);const length=nl<0?buf.length:nl;if(length>limit){stopped=true;return oversize()}if(nl<0)return;const line=buf.subarray(0,nl);buf=buf.subarray(nl+1);if(!onLine(line)){stopped=true;return}}}}var nonce3=()=>randomBytes3(32).toString("base64url");function socketDir(path){return process.platform==="win32"?void 0:dirname3(path)}function assertPrivateDir(dir){const st2=lstatSync5(dir);const uid2=process.getuid();const problem=st2.isSymbolicLink()?"is a symbolic link, not a directory":!st2.isDirectory()?"is not a directory":st2.uid!==uid2?`is owned by uid ${st2.uid}, not by this user (uid ${uid2})`:(st2.mode&63)!==0?`has mode ${(st2.mode&4095).toString(8)}, which lets group or others in`:void 0;if(problem)throw new Error(`control socket directory ${dir} ${problem}, so it is not a private directory of this user. Remove it if you did not create it, or point TMPDIR at a directory only you can write, and relaunch.`)}function assertControlSocketDir(path){if(path.startsWith("\0"))throw new Error("control socket path is in the Linux abstract namespace, which any local user can bind; use a path in a private directory");const dir=socketDir(path);if(!dir)return;try{assertPrivateDir(dir)}catch(e3){if(e3.code!=="ENOENT")throw e3;throw new Error(`control socket directory ${dir} does not exist. The launcher makes it when it mints the endpoint; for a hand-driven COTAL_CONTROL_SOCKET, make it yourself with mode 0700.`)}}function serverExchange(sock,endpoint,onRequest,opts={}){assertControlEndpoint(endpoint);let nc;const ns=nonce3();let settled=false;const drop=()=>{if(!settled){settled=true;clearTimeout(deadline);sock.destroy()}return false};const deadline=setTimeout(drop,opts.deadlineMs??CONTROL_SERVER_AUTH_DEADLINE_MS);deadline.unref?.();const onClose=()=>{settled=true;clearTimeout(deadline)};const onLine=line=>{if(settled)return false;if(nc===void 0){const hello=parseHandshake(line);if(!hello||hello.v!==CONTROL_PROTOCOL_VERSION||typeof hello.nonce!=="string"||!BASE64URL_43.test(hello.nonce))return drop();nc=hello.nonce;try{sock.write(JSON.stringify({v:CONTROL_PROTOCOL_VERSION,nonce:ns,mac:transcriptMac(endpoint.token,"server",nc,ns)})+"\n")}catch{return drop()}return true}const proven=nc;const request=openSealed(line,body=>transcriptMac(endpoint.token,"client",proven,ns,body));if(request===void 0)return drop();settled=true;clearTimeout(deadline);sock.off("data",onData);sock.off("close",onClose);onRequest({request,seal:text3=>{const body=Buffer.from(text3,"utf8");const receipt2=transcriptMac(endpoint.token,"receipt",proven,ns,body);return{line:`${transcriptMac(endpoint.token,"reply",proven,ns,body)} ${text3}
128
128
  `,receiptMatches:presented=>macMatches(presented,receipt2)}}});return false};const onData=lineReader(()=>nc===void 0?MAX_HANDSHAKE_LINE_BYTES:MAC_PREFIX_BYTES+MAX_CONTROL_REQUEST_BYTES,onLine,()=>void drop());sock.on("data",onData);sock.on("close",onClose)}var DIR_PREFIX="cotal-launch-";var MATERIAL_FILE="material.json";var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=statSync3(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=readFileSync3(path,"utf8")}catch(e3){throw new Error(`launch material: cannot read ${path} (${e3 instanceof Error?e3.message:String(e3)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str2=key=>{const v3=raw[key];if(v3===void 0)return;if(typeof v3!=="string"||!v3.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);if(key==="controlKey"&&v3!==v3.trim())throw new Error(`launch material: ${path} has a controlKey with whitespace around it`);material[key]=v3};str2("servers");str2("creds");str2("token");str2("controlKey");if(raw.controlToken!==void 0)throw new Error(`launch material: ${path} carries controlToken, the control key field of a release before the control exchange. This build reads controlKey and refuses the old field; launch with a launcher from the same release.`);if(raw.controlVersion!==void 0){assertControlVersion(raw.controlVersion,`launch material ${path}`);material.controlVersion=raw.controlVersion}if(material.controlKey===void 0!==(material.controlVersion===void 0))throw new Error(`launch material: ${path} has ${material.controlKey===void 0?"a controlVersion without a controlKey":"a controlKey without a controlVersion"}. The control key and its protocol version travel together; a launcher and connector from different releases refuse each other.`);if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.eventPayloadsWithheld!==void 0){if(raw.eventPayloadsWithheld!==true)throw new Error(`launch material: ${path} has eventPayloadsWithheld that is not true`);material.eventPayloadsWithheld=true}if(raw.userAuth!==void 0){const u2=raw.userAuth;if(typeof u2!=="object"||u2===null||Array.isArray(u2))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}=u2;const named={owner:owner2,actor:actor2,sentinelCredsPath};for(const[k2,v3]of Object.entries(named))if(typeof v3!=="string"||!v3.trim())throw new Error(`launch material: ${path} has a userAuth.${k2} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a3=>typeof a3==="string"&&a3))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}function discardLaunchMaterial(path){const file2=resolve2(path);try{rmSync2(file2,{force:true})}catch{}const dir=dirname4(file2);if(basename(file2)!==MATERIAL_FILE||!basename(dir).startsWith(DIR_PREFIX))return;try{if(realpathSync2(dirname4(dir))!==realpathSync2(tmpdir()))return;rmdirSync(dir)}catch{}}init_secret_fs();init_kv_scan();init_jetstream_missing();init_endpoint();var import_transport_node28=__toESM(require_transport_node(),1);var import_jetstream29=__toESM(require_mod4(),1);var import_kv13=__toESM(require_mod6(),1);init_endpoint();init_subjects();init_space_deletion_targets();init_identity();init_provision();import{BlockList,isIPv4,isIPv6}from"node:net";var LOOPBACK=new BlockList;LOOPBACK.addSubnet("127.0.0.0",8,"ipv4");LOOPBACK.addAddress("::1","ipv6");init_subjects();var TARGET_FIELDS=["space","owner","actor","lifecycleUid"];var STRING_FIELDS=[...TARGET_FIELDS,"kind","server","authProvider","exchangeUrl","sentinelCreds","actorToken"];var LIST_FIELDS=["subscribe","allowSubscribe","allowPublish"];var FIELDS=new Set([...STRING_FIELDS,...LIST_FIELDS,"tlsRequired","idp","policy"]);init_subjects();import{AsyncLocalStorage}from"node:async_hooks";function claims(ext){return[ext.name,...ext.aliases??[]].map(word=>`${ext.kind}:${word}`)}var Registry=class{#byKey=new Map;#providers=new Map;#aliases=new Map;#stage=new AsyncLocalStorage;register(...exts){const stage=this.#stage.getStore();const taken=this.#claimed();for(const staged of stage?.values()??[])for(const key of claims(staged))taken.add(key);for(const ext of exts){for(const key of claims(ext)){if(taken.has(key))throw new Error(`extension already registered: ${key}`);taken.add(key)}}if(stage)for(const ext of exts)stage.set(`${ext.kind}:${ext.name}`,ext);else this.#publish(exts)}#claimed(){return new Set([...this.#byKey.keys(),...this.#aliases.keys()])}#publish(exts){for(const ext of exts){const key=`${ext.kind}:${ext.name}`;this.#byKey.set(key,ext);for(const alias of claims(ext).slice(1))this.#aliases.set(alias,key)}}unregister(kind,name2){const key=`${kind}:${name2}`;const ext=this.#byKey.get(key);if(!ext)return false;for(const alias of claims(ext).slice(1))this.#aliases.delete(alias);return this.#byKey.delete(key)}async runStaged(load){const stage=new Map;const value=await this.#stage.run(stage,load);return{value,staged:[...stage.values()]}}commitStaged(staged){const taken=this.#claimed();for(const ext of staged)for(const key of claims(ext))if(taken.has(key))throw new Error(`extension already registered: ${key}`);this.#publish(staged)}has(kind,name2){return this.#byKey.has(this.#canonical(kind,name2))}#canonical(kind,word){const key=`${kind}:${word}`;return this.#aliases.get(key)??key}resolve(kind,name2){const ext=this.#byKey.get(this.#canonical(kind,name2));if(!ext){if(this.#providers.has(`${kind}:${name2}`))throw new Error(`${kind} "${name2}" is declared by a provider this process has not loaded`);throw new Error(`no ${kind} registered for "${name2}"`)}return ext}provide(provider){const keys=provider.provides.map(ref=>`${ref.kind}:${ref.name}`);for(const key of keys)if(this.#providers.has(key))throw new Error(`extension provider already declared: ${key}`);const entry={provider};for(const key of keys)this.#providers.set(key,entry)}provides(kind,name2){return this.#providers.has(`${kind}:${name2}`)}async load(kind,name2){const entry=this.#providers.get(`${kind}:${name2}`);if(entry){entry.loading??=entry.provider.load();await entry.loading;if(!this.#byKey.has(this.#canonical(kind,name2)))throw new Error(`the provider declared for ${kind} "${name2}" loaded without registering it`)}return this.resolve(kind,name2)}all(kind){const values=[...this.#byKey.values()];return kind===void 0?values:values.filter(e3=>e3.kind===kind)}};var registry2=new Registry;import{execFile}from"node:child_process";init_subjects();function bearerCommandFailure(err3,stderr,timeoutMs,stdout=""){const said=stderr.trim();const retryAfter=/^retry-after (\d+)$/.exec(stdout.trim());if(said)return Object.assign(new Error(said),retryAfter?{retryAfterSeconds:Number(retryAfter[1])}:{});if(err3.killed)return new Error(`the bearer command timed out after ${timeoutMs}ms`);if(err3.signal)return new Error(`the bearer command was killed by ${err3.signal}`);if(typeof err3.code==="number")return new Error(`the bearer command exited with code ${err3.code} and printed nothing`);return new Error(err3.message)}function runAgentBearer(argv,opts={}){const timeoutMs=opts.timeoutMs??3e4;return new Promise((resolve4,reject)=>{execFile(argv[0],argv.slice(1),{timeout:timeoutMs,maxBuffer:64*1024,env:opts.env,signal:opts.signal},(err3,stdout,stderr)=>err3?reject(bearerCommandFailure(err3,stderr,timeoutMs,stdout)):resolve4(stdout.trim()))})}init_event_channel();init_subjects();var SELECTION_MAX_ITEMS=32;init_canonical_json();var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});init_subjects();init_base64url();function managerCallerBinding(bearer,expected){let payload;try{const parts=bearer.split(".");if(parts.length!==3)throw new Error("invalid JWT");payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(fromBase64url(parts[1])))}catch{throw new Error("manager control exchange returned an invalid bearer")}const act=payload?.act;if(!act||act.view!=="manager-caller"||payload.sub!==expected.owner||act.owner!==expected.owner||act.actor!==expected.actor||act.lifecycleUid!==expected.lifecycleUid||!(payload.aud===expected.space||Array.isArray(payload.aud)&&payload.aud.length===1&&payload.aud[0]===expected.space))throw new Error("manager control exchange returned different space, principal, lifecycle or view coordinates");if(typeof act.managerInstanceId!=="string")throw new Error("manager control exchange returned no concrete manager instance");const instanceId=assertLifecycleToken(act.managerInstanceId,"managerInstanceId");if(expected.instanceId!==void 0&&instanceId!==expected.instanceId)throw new Error("manager control exchange selected a different manager instance");return{caller:{owner:expected.owner,actor:expected.actor,uid:expected.lifecycleUid},instanceId,...typeof act.credentialId==="string"?{credentialId:act.credentialId}:{}}}init_remote_manager_authority();init_remote_service_authority();init_endpoint_capability_policy();init_canonical();init_endpoint_error();init_identity();init_remote_manager_authority();init_subjects();var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);init_canonical();init_artifact();function partText(p2){if(p2.kind==="text")return p2.text;if(p2.kind==="artifact")return`[artifact ${p2.name} (${p2.mediaType}, ${p2.size} bytes) ${p2.digest}]`;if(p2.kind==="data"){const encoded=JSON.stringify(p2.data);return encoded===void 0?`[empty data part]`:encoded}if(registry2.has("part-renderer",p2.kind)){const renderer=registry2.resolve("part-renderer",p2.kind);try{return renderer.render(p2)}catch(e3){return`[part renderer for ${JSON.stringify(p2.kind)} failed: ${e3.message}]`}}return`[unrenderable part kind ${JSON.stringify(p2.kind)} \u2014 no renderer for it on this surface]`}function partsToText(parts){return parts.map(partText).join(" ")}var AGUI_FRAME_KIND="ag-ui.frame";var AGUI_EVENT_TYPE=Object.freeze({RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",REASONING_MESSAGE_START:"REASONING_MESSAGE_START",REASONING_MESSAGE_CONTENT:"REASONING_MESSAGE_CONTENT",REASONING_MESSAGE_END:"REASONING_MESSAGE_END",CUSTOM:"CUSTOM"});function isAguiFramePart(part){if(typeof part!=="object"||part===null)return false;try{return part.kind===AGUI_FRAME_KIND}catch{return false}}init_event_channel();init_event_channel();import{createHash as createHash6}from"node:crypto";import{constants as constants3}from"node:fs";import{lstat,open,readdir}from"node:fs/promises";import{dirname as dirname5,join as join5,relative,sep}from"node:path";init_subjects();var EVENT_SUBJECT_RECORD_VERSION=1;var SubjectFrontierCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`subject frontier ${path}: expected ${invariant} \u2014 ${detail}`);this.path=path;this.invariant=invariant;this.name="SubjectFrontierCorruptError"}};var EventStateConflictError=class extends Error{constructor(message){super(message);this.name="EventStateConflictError"}};function eventPrincipalLocation(opts){const h3=value=>createHash6("sha256").update(value).digest("hex").slice(0,16);const principalDir=join5(opts.workspaceRoot,".cotal","events",h3(opts.space),h3(opts.principal));return{principalDir,lockPath:join5(principalDir,".lock"),subjectPath:join5(principalDir,"subject.json")}}var isSafeNonNegInt=n2=>typeof n2==="number"&&Number.isSafeInteger(n2)&&n2>=0;async function readEventSubjectRecord(path,opts){let st2;try{st2=await lstat(path)}catch(e3){if(e3.code==="ENOENT")return void 0;throw e3}if(st2.isSymbolicLink())throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the writer never wrote a symlink");let bytes;try{const fh=await open(path,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{bytes=await fh.readFile()}finally{await fh.close()}}catch(e3){const code=e3.code;if(code==="ENOENT")return void 0;if(code==="ELOOP")throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the record became a symlink between the check and the open");throw e3}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new SubjectFrontierCorruptError(path,"valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}if(raw.length===0)throw new SubjectFrontierCorruptError(path,"a non-empty file","the file is zero bytes \u2014 distinct from missing, and never treated as virgin");let parsed;try{parsed=JSON.parse(raw)}catch(e3){throw new SubjectFrontierCorruptError(path,"parseable JSON",e3.message)}const d2=parsed;if(d2?.v!==EVENT_SUBJECT_RECORD_VERSION)throw new SubjectFrontierCorruptError(path,`v === ${EVENT_SUBJECT_RECORD_VERSION}`,String(d2?.v));if(d2.space!==opts.space)throw new SubjectFrontierCorruptError(path,"space matches",`file=${String(d2.space)} caller=${opts.space}`);if(d2.principal!==opts.principal)throw new SubjectFrontierCorruptError(path,"principal matches",`file=${String(d2.principal)} caller=${opts.principal}`);if(!isSafeNonNegInt(d2.tip)||d2.tip>=Number.MAX_SAFE_INTEGER)throw new SubjectFrontierCorruptError(path,"tip is a safe non-negative integer below Number.MAX_SAFE_INTEGER",String(d2.tip));return{v:d2.v,space:d2.space,principal:d2.principal,tip:d2.tip}}async function recoverEventSubjectTip(principalDir,principal){let entries;try{entries=await readdir(principalDir,{withFileTypes:true})}catch(e3){if(e3.code==="ENOENT")return 0;throw e3}let best=0;for(const ent of entries){if(ent.isSymbolicLink())throw new SubjectFrontierCorruptError(join5(principalDir,ent.name),"a real directory beside the record, never a symlink","following it would carry this scan outside the principal directory, and the writer that creates these directories refuses a symlinked component for the same reason");if(!ent.isDirectory())continue;const walPath=join5(principalDir,ent.name,"wal.json");let st2;try{st2=await lstat(walPath)}catch(e3){const code=e3.code;if(code==="ENOENT"||code==="ENOTDIR")continue;throw e3}if(st2.isSymbolicLink())throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","following it would read a log this principal's writer never wrote");if(st2.nlink>1)throw new SubjectFrontierCorruptError(walPath,"a thread log with exactly one name",`it has ${st2.nlink}, so the same file is reachable from outside this principal's directory and its tip is not this principal's to read`);let raw;try{const fh=await open(walPath,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{raw=await fh.readFile()}finally{await fh.close()}}catch(e3){const code=e3.code;if(code==="ENOENT"||code==="ENOTDIR")continue;if(code==="ELOOP")throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","the file became a symlink between the check and the open");throw e3}let doc;try{doc=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(raw))}catch(e3){throw new SubjectFrontierCorruptError(walPath,"a readable thread log while recovering the subject tip",e3.message)}if(doc.principal!==principal)throw new SubjectFrontierCorruptError(walPath,`a thread log for principal ${principal}`,`found ${String(doc.principal)}`);const seq=doc.frontier?.lastSubjectSeq;if(!isSafeNonNegInt(seq))throw new SubjectFrontierCorruptError(walPath,"frontier.lastSubjectSeq is a safe non-negative integer",String(seq));if(seq>best)best=seq;const pending=doc.pending;if(pending&&pending.state==="acked"){const acked=pending.ackSeq;if(!isSafeNonNegInt(acked))throw new SubjectFrontierCorruptError(walPath,"an acked pending carries a safe non-negative ackSeq",String(acked));if(!(acked>seq))throw new SubjectFrontierCorruptError(walPath,"an acked pending is ahead of the frontier it will fold into",`ackSeq=${acked} frontier.lastSubjectSeq=${seq}`);if(acked>best)best=acked}}return best}async function recordedEventTip(path,opts){const record2=await readEventSubjectRecord(path,opts);return record2===void 0?recoverEventSubjectTip(dirname5(path),opts.principal):record2.tip}async function checkEventStartup(opts){const principal=principalKey(opts.principal.owner,opts.principal.actor).key;const loc=eventPrincipalLocation({...opts,principal});ensureDirNoSymlink(opts.workspaceRoot,...relative(opts.workspaceRoot,loc.principalDir).split(sep));if(await recordedEventTip(loc.subjectPath,{space:opts.space,principal})!==0)return;const rows=await opts.retainedMessages();if(rows.some(row=>row.sender===principal&&row.channel===eventChannel(opts.principal)&&row.messages>0)){throw new EventStateConflictError(`Cannot start events for ${principal}: this state root has no acknowledged transcript frontier, but the broker retains events for this principal. Reuse the previous state root or launch with a new principal. Refusing before work; the existing transcript and local logs are unchanged.`)}}init_schema_profile();init_broker_floor();init_endpoint_envelope();init_endpoint_records();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_records();init_run_driver_grants();init_endpoint_subjects();init_subjects();var TURN_INPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["payload"],oneOf:[{required:["deadlineMs"]},{required:["deadlineAt"]}],properties:{payload:{type:"string",minLength:1,maxLength:65536},deadlineMs:{type:"integer",minimum:1},deadlineAt:{type:"integer",minimum:1},handoffFrom:{type:"string",minLength:1,maxLength:200}}});var TURN_OUTPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","deadlineAt","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},deadlineAt:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var TURN_YIELD_OUTPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["goalId","state"],properties:{goalId:{type:"string"},state:{enum:["succeeded","failed","cancelled","expired","uncertain"]}}});var CANCEL_INPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["goalId"],properties:{goalId:{type:"string",minLength:1},mode:{enum:["graceful","terminate"]}}});function deepFreeze3(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze3(child);Object.freeze(v3)}return v3}var TURN_NOTICE_NONCE="turn-pending-notice-v1";function turnNoticeFilter(space2,instanceId,seat){return[spacePrefix(space2),...epPlaneTokens(seat),"reply",endpointToken("manager"),assertLifecycleToken(instanceId,"instanceId"),"*",...callerRailTokens(seat),TURN_NOTICE_NONCE].join(".")}function shownSpawner(name2,fallback){return name2!==void 0&&name2.trim()?name2:fallback}function renderOnceTask(t2){let context=t2.payload;try{const p2=JSON.parse(t2.payload);if(typeof p2.context==="string")context=p2.context}catch{}const from=shownSpawner(t2.spawner,"your spawner");const deadline=t2.deadlineAt!==void 0?`, or at ${new Date(t2.deadlineAt).toISOString()} if you are still working then`:"";return`\u{1F3AF} Cotal \u2014 ${from} started this seat for one task (goal ${t2.goalId}):
129
129
  ${context}
130
- (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=deepFreeze4({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=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze4({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=deepFreeze4({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(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),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=deepFreeze4({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},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze4(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze4(child);Object.freeze(v3)}return v3}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();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 deepFreeze5(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze5(child);Object.freeze(value)}return value}var text2={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 closed3=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed3({owner,actor,lifecycleUid:uid});var pair={threadId:text2,toolCallId:text2};var status=(state,fields={})=>closed3({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed3({owner,actor}),iat:uint2,exp:uint2,issuer:closed3({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint2}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed3({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint2,registrationRevision:{...uint2,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed3({t0:uint2,watermark:uint2,watermarkTakenAt:uint2,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint2}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze5(closed3(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze5({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=deepFreeze5({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze5(closed3({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze5(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze5(closed3({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze5({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze5([{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=deepFreeze5({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();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;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream30=__toESM(require_mod4(),1);var import_transport_node29=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream31=__toESM(require_mod4(),1);var import_kv14=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();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 path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)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(path)}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 path=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token2=material?material.controlKey:directControlKey(env);if(path&&token2){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,token:token2,version:version2}}if(!path&&!token2)return void 0;if(path)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}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 path=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path)discardLaunchMaterial(path)}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 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 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}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,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,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,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{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID10}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 randomUUID9}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(path,invariant,detail){super(`event WAL at ${path} is unusable (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path,expectedGen,foundGen){super(`event WAL at ${path} 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=path;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n2=>Number.isSafeInteger(n2)&&n2>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path,"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(path){return open2(path,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p2,f2){if(p2.E!==f2.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p2.E} frontier.lastSubjectSeq=${f2.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p2.seq!==f2.seq+1)throw new WalCorruptError(path,"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(path,"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(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p2.ackSeq)}`);if(!(p2.ackSeq>f2.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p2.ackSeq} frontier.lastSubjectSeq=${f2.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v3,nullable2){if(v3===null&&nullable2)return null;if(typeof v3!=="object"||v3===null)throw new WalCorruptError(path,`${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(path,`${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,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path,`${field}.${k2} is an array of strings`,JSON.stringify(list))}if(b3.run===void 0&&b3.text.concat(b3.reasoning,b3.tools).length>0)throw new WalCorruptError(path,`${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(path,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(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space2,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(path,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path,"document is an object",typeof d2);const doc=d2;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path,`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(path,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f2=doc.frontier;if(!f2||!isSafeNonNegInt2(f2.seq)||!isSafeNonNegInt2(f2.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f2.sourceCursor!==void 0&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f2.sourceCursor);if(f2.seq===0!==(f2.lastSubjectSeq===0))throw new WalCorruptError(path,"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(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f2));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"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(path,"pending.state is a known tag",String(p2.state));if(typeof p2.id!=="string"||p2.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p2.id));try{assertIdToken(p2.id,"event WAL pending.id")}catch(e3){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e3.message)}if(!isSafeNonNegInt2(p2.E)||!isSafeNonNegInt2(p2.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p2));if(typeof p2.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p2.sourceCursor);if(!Array.isArray(p2.body)||p2.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p2.body));if(doc.v===1)throw new WalCorruptError(path,"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(path,"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(path,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p2.payloadCalls=parsePayloadCalls(path,p2.payloadCalls);pending=p2;assertPendingVintage(path,pending,f2)}const brackets=doc.v===1?null:parseBrackets(path,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f2,pending,payloadCalls:parsePayloadCalls(path,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(path,doc){this.path=path;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 path=join6(parent,entry.name,"wal.json");if(path===this.path)continue;if(entry.isSymbolicLink())throw new WalCorruptError(path,"a real thread directory","found a symlink");if(!entry.isDirectory())continue;let bytes;try{const st2=await lstat2(path);if(!st2.isFile()||st2.nlink!==1)throw new WalCorruptError(path,"a real thread log with one name","refusing linked or non-file state");const file2=await open2(path,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}const raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes);const doc=JSON.parse(raw);if(doc.pending?.state!=="sent_unacked")continue;const threadId=doc.threadId;if(typeof threadId!=="string"||createHash7("sha256").update(threadId).digest("hex").slice(0,16)!==entry.name)throw new WalCorruptError(path,"thread id matches its directory","refusing misplaced state");const sibling=new _EventWal(path,parseDoc(path,raw,this.space,threadId,this.principal));if(sibling.pending)siblings.push(sibling)}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path,opts){let raw;let bytes;try{bytes=await readFile(path)}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(path,"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(path,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path,parseDoc(path,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID9(),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.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)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);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:randomUUID9(),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}.${randomUUID9().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(message){super(message);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")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL principal lock at ${path} (${invariant}): ${detail}`);this.path=path;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(path){try{return await openExclusiveNoFollow(path)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path){let raw;try{raw=await readFile2(path,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path,"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=record2;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path,"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(path,"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(path,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path).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 record2=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID10(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"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 TURN_PULL_RETRY_MS=15e3;var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY=Symbol.for("cotal.once-handoff");function proc(){const g2=globalThis;return g2[KEY]??={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 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}init_peer_label();var LABEL_MAX_CODE_POINTS=40;function capped(s3,max){const points=Array.from(s3);return points.length<=max?s3:`${points.slice(0,max-1).join("")}\u2026`}function attributionSafe(s3){return peerLabel({name:s3})}var FROM_MAX_CODE_POINTS=160;var FROM_MIN_CODE_POINTS=" (unverified name)".length+2;function fmtFrom(i2,maxCodePoints=FROM_MAX_CODE_POINTS){if(!Number.isInteger(maxCodePoints)||maxCodePoints<FROM_MIN_CODE_POINTS)throw new RangeError(`a sender label bound must be a whole number of at least ${FROM_MIN_CODE_POINTS} code points, got ${maxCodePoints}`);const named=i2.fromName.trim()!=="";const label=peerLabel({name:named?i2.fromName:i2.fromId,...i2.fromRole?{role:i2.fromRole}:{}});const marker=named?" (unverified name)":i2.fromRole?" (unverified role)":"";return`${capped(label,maxCodePoints-marker.length)}${marker}`}function fmtBody(text3){return text3.split(LINE_BREAK).join("\n ")}function fmtItem(i2){return formatItem(i2)}function fmtDeliveryItem(i2){const field=value=>Array.from(JSON.stringify(value),char=>[91,93,133,8232,8233].includes(char.charCodeAt(0))?`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`:char).join("");const metadata2=[`sender_id=${field(i2.fromId)}`,...i2.id?[`message_id=${field(i2.id)}`]:[],...i2.contextId?[`context_id=${field(i2.contextId)}`]:[],...i2.replyTo?[`reply_to=${field(i2.replyTo)}`]:[]];return formatItem(i2,`[${metadata2.join(" ")}] `)}function formatItem(i2,metadata2="",attributionMax){const h3=i2.historical?"(history) ":"";const r2=i2.deliveryCount!==void 0&&i2.deliveryCount>1?`(broker redelivery, delivery ${i2.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h3}${r2}${fmtBody(i2.text)}`;if(i2.notice)return`[${i2.notice} notice from the delivery daemon] ${body}`;const label=s3=>attributionMax===void 0?attributionSafe(s3??""):capped(attributionSafe(s3??""),LABEL_MAX_CODE_POINTS);const from=head2=>fmtFrom(i2,attributionMax===void 0?void 0:Math.min(FROM_MAX_CODE_POINTS,attributionMax-Array.from(head2).length-"] ".length));if(i2.kind==="dm")return`[DM from ${from("[DM from ")}] ${body}`;if(i2.kind==="anycast"){const head2=`[@${label(i2.service)} from `;return`${head2}${from(head2)}] ${body}`}const head=`[#${label(i2.channel)}${i2.mentionsMe?" @you":""} `;return`${head}${from(head)}] ${body}`}function fmtChannel(channel){const safe=attributionSafe(channel??"").trim();return safe.length?safe:"?"}var CONNECTOR_VERSION="0.171.0";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(token2){try{const exp=JSON.parse(Buffer.from(token2.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)return Promise.reject(signal.reason);return new Promise((resolve4,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve4(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()}dropBearer(argv){this.managerBearers.delete(JSON.stringify(argv))}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"};if(!user.bearerCmd)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const managerInstanceId=instance??this.config.managerInstanceId;const token2=await this.managerCallBearer([...user.bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]]).catch(e3=>{throw e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token2);return withUserManagerListing({...this.config,managerInstanceId},token2,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(token2=>{const exp=bearerExpiryMs2(token2);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;if(this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)return{ok:false,error:`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`};const managerInstanceId=opts.instanceId??this.config.managerInstanceId;const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearerArgv=[...bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{throw e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});dropBearer=()=>{this.managerBearers.delete(JSON.stringify(bearerArgv))};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.execBearerCmd([...bearerCmd,"--manager-call","--manager-instance",instanceId],signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...this.config.userAuth,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 message=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,message),...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 answer=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer?.ok===true&&answer.instanceId===instanceId?answer.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 order=compareRelease(CONNECTOR_VERSION,manager);if(order>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order<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,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,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 caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??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 caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve4=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{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 resolve4(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve4(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token2,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");nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left});if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(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 resolve4(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 connect3();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 CommandRefused=class extends Error{code;constructor(code,message){super(message);this.code=code;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code,message)=>new EpEnvelopeError(code,message,void 0,"not-executed");var what=c3=>`the ${c3.target} "${c3.name}"`;function cut(text3,max){const chars=[...text3];return chars.length<=max?text3:`${chars.slice(0,max-1).join("")}\u2026`}function fitText(text3,max){return typeof text3==="string"&&text3!==""?cut(text3,max):void 0}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 createCommandLane(dispatcher,onQueued){const entries=new Map;const ended=[];let closed4=false;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued");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 end(e3,state){e3.state=state;ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}async function list(){if(!dispatcher)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}`)}if(!Array.isArray(listed))throw refused("internal","the connector's list is not an array");const commands=[];for(const e3 of listed){if(!isAgentCommandName(e3?.name))continue;if(!dispatcher.targets.has(e3.target))throw refused("internal",`the connector listed the ${String(e3.target)} "${e3.name}" but runs no ${String(e3.target)}s`);const description=fitText(e3.description,AGENT_COMMAND_DESCRIPTION_MAX),inputHint=fitText(e3.inputHint,AGENT_COMMAND_INPUT_HINT_MAX);commands.push({name:e3.name,target:e3.target,...description?{description}:{},...inputHint?{inputHint}:{}})}if(commands.length>AGENT_COMMAND_LIST_MAX)throw refused("resource-exhausted",`the harness lists ${commands.length} commands and skills, over the ${AGENT_COMMAND_LIST_MAX} a reply carries`);return{supported:true,commands}}function run(input){if(!dispatcher)throw refused("unimplemented","this agent's connector runs no commands or skills");if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);if(closed4)throw refused("unavailable","this agent is stopping");if(queued().length>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));entries.set(id2,{id:id2,command:{target:input.target,name:input.name,args:input.args??""},state:{kind:"queued"}});onQueued();return{id:id2}}function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end(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:()=>list()},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx.request.args)},{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})}],get queued(){return queued().length},async dispatchNext(){const e3=queued()[0];if(!e3)return"empty";e3.state={kind:"taken"};try{await dispatcher.dispatch(e3.command);end(e3,{kind:"started"});return"dispatched"}catch(err3){const message=String(err3?.message??err3);end(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut(message,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut(`the harness failed, so ${what(e3.command)} may have started: ${message}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}},close(){closed4=true;for(const e3 of queued())end(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3.command)} started`})}}}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,message){super(message);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 answer=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,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer},true);if(event.result==="gone")return close({kind:"undelivered",answer},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},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer,seen:e3.seen},true);return close({kind:"unconfirmed",answer,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer,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 deepFreeze6(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze6(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused2(code,message,details){return new EpEnvelopeError(code,message,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 closed4=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed4({kind:"expired"}));measure(closed4({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed4({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer,delivery:"unconfirmed"});measure({kind:"sent",answer,delivery:"delivered"});measure(closed4({kind:"answered",answer}));measure(closed4({kind:"unconfirmed",answer,seen:LONGEST_SEEN}));measure(closed4({kind:"undelivered",answer}));measure(closed4({kind:"local",seen:LONGEST_SEEN,late:answer}))}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 content=deepFreeze6(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content);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}})){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 content.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content.form!==void 0&&!content.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content.subject?.type==="tool"?content.subject.input:void 0;if(input?.kind==="omitted"&&content.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(content.form!==void 0){const schema=content.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:content.kind,title:content.title,contentBytes,...content.source!==void 0?{source:content.source}:{}};const largest=largestSummaryBytes(base,content.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:deepFreeze6(base),live:{content,options,...form?{form}:{}},state:deepFreeze6({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=deepFreeze6(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 refused2("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 open6=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open6.push(this.summary(h3));const closed4=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:open6,closed:closed4})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused2("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused2("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 refused2("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused2("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused2("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 refused2("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused2("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 refused2("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused2("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused2("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused2("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused2("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 refused2("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=deepFreeze6({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 refused2("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 refused2("internal","the agent could not check this answer")}throw refused2("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused2("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer},answer.at);if(step.kind!=="move"||!step.deliver)throw refused2("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze6(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve4=>{const w2={resolve:resolve4,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve4(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,caller){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller.owner}.${caller.actor}.${caller.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}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);const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}));const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers]});desk.served(serve.ready);let closing;const close=()=>closing??=(()=>{ep.off("transport",onTransport);desk.close();lane.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,close}}import{randomUUID as randomUUID11}from"node:crypto";import{createHash as createHash9}from"node:crypto";var CHANNEL_CATCHUP_AGE_MS=5*6e4;function afterRecallMark(a3,b3){return a3.ts!==b3.ts?a3.ts>b3.ts:a3.id>b3.id}var MAX_INBOX=200;var TAKE_WAIT_MS=2e3;var TAKE_RETRY_MS=1e4;var MAX_IN_FLIGHT=MAX_INBOX*2;var MAX_AHEAD=256;var CLASSIFICATION_CAP=4096;var FOCUS_EXCLUSION_CAP=4096;var IDLESS_READS=3;var PROTECTED_DISPOSITION_CAP=4096;function deliveryNoticeOf(m2){for(const p2 of m2.parts){if(p2.kind!=="data"||typeof p2.data!=="object"||p2.data===null||Array.isArray(p2.data))continue;if(ANYCAST_NOTICE_KEY in p2.data)return"anycast";if(MENTION_NOTICE_KEY in p2.data)return"mention"}return void 0}function idlessDigest(m2){return createHash9("sha256").update(JSON.stringify(m2)).digest("base64url")}function ingestDedupKey(id2){return id2===""?void 0:id2}var AgentInbox=class{deps;constructor(deps){this.deps=deps}get ep(){return this.deps.endpoint()}get config(){return this.deps.config()}get _transportConnected(){return this.deps.transportConnected()}emit(event,item){this.deps.emit(event,item)}handleEndpointWarning(error51){this.deps.warning(error51)}noteDirected(item){this.deps.noteDirected(item)}inOrder(write){return this.deps.inOrder(write)}requireConnected(){return this.deps.requireConnected()}seedChannelModes(config2){for(const c3 of config2.quiet??[])this.channelModes.set(c3,"quiet");for(const c3 of config2.muted??[])this.channelModes.set(c3,"muted")}onTransport(connected){if(!connected){this.transportDrops++;for(const p2 of this.inbox.filter(x2=>x2.take&&!this.inFlightIds.has(x2.item.recvKey)))this.regate(p2)}if(connected&&this.mayAskTakes()){this.dropLapsedTakes();for(const p2 of this.gated)if(p2.taking===void 0)this.emit("incoming",p2.item)}}stop(){for(const key of[...this.renewals.keys()])this.stopRenewal(key);clearTimeout(this.takeRetry);this.takeRetry=void 0}inbox=[];gated=[];arrivals=0;heldTake;takeRetry;handledIds=new Set;handledIdsPrev=new Set;evictedClassifications=new Map;inFlightIds=new Map;lowerOnRelease=new Set;renewals=new Map;classificationUnsafe=false;protectedPullOnlyIds=new Set;protectedDropIds=new Set;dropUnsafe=false;_lastInboxDrainedAt;_lastAutomaticDrainedAt;_lastAutomaticHeadDrainedAt;_attention="open";_recallCursor={ts:0,id:""};aheadDelivered=new Set;channelModes=new Map;focusSince;enteringFocus=false;recvKeySecret=randomUUID11().replace(/-/g,"");recvKeySeq=0;focusExcludedIds=new Map;focusIdless=new Map;focusIdlessEntries=0;idlessEpoch=0;recallLock=Promise.resolve();transportDrops=0;focusRecallUnsafeChannels=new Set;get lastInboxDrainedAt(){return this._lastInboxDrainedAt}get lastAutomaticDrainedAt(){return this._lastAutomaticDrainedAt}get lastAutomaticHeadDrainedAt(){return this._lastAutomaticHeadDrainedAt}oldestAutomaticKey(){let head;for(const pending of this.inbox){if(pending.pullOnly)continue;if(head===void 0||pending.receivedAt<head.receivedAt)head=pending}return head?.item.recvKey}noteAutomaticHeadProgress(selected){const head=this.oldestAutomaticKey();if(head===void 0)return;if(selected.some(p2=>!p2.pullOnly&&p2.item.recvKey===head))this._lastAutomaticHeadDrainedAt=Date.now()}automaticQueueStalledForMs(now=Date.now()){const oldest=this.oldestAutomaticReceivedAt();if(oldest===void 0)return void 0;const since=Math.max(oldest,this._lastAutomaticHeadDrainedAt??0);const held2=now-since;return held2>0?held2:0}get channelDeliveryIssue(){return this.dropUnsafe?"Channel drop tracking exhausted. Ambient channel traffic is suppressed until restart; non-historical mentions on unmuted channels wake to pull their buffered body. Focus recall may be incomplete.":void 0}async ingestNotice(m2,delivery,meta3,notice){const holder=await this.ep.deliveryLeaseHolder(0);this.ingest(m2,delivery,meta3,holder!==void 0&&holder===m2.from.id?notice:void 0)}ingest(m2,delivery,meta3,notice){const key=ingestDedupKey(m2.id);if(key!==void 0&&(this.handledIds.has(key)||this.handledIdsPrev.has(key))){if(delivery.durable)delivery.ack();return}if(key!==void 0&&(this.protectedPullOnlyIds.has(key)||this.protectedDropIds.has(key))){if(delivery.durable)delivery.ack();return}const existing=key===void 0?void 0:this.inbox.find(p2=>p2.item.id===key)??this.gated.find(p2=>p2.item.id===key);if(existing){if(delivery.durable){existing.ack=delivery.ack;this.own(existing,delivery.redelivery);if(delivery.take)existing.take=delivery.take;if(this.inFlightIds.has(existing.item.recvKey))this.keepOwned(existing.item.recvKey);else if(existing.take&&existing.takenCount!==existing.item.deliveryCount)this.regate(existing);this.emit("incoming",existing.item)}return}if(!meta3)throw new Error(`message ${m2.id} delivered without MessageMeta \u2014 its class is unauthenticated`);const historical=meta3.historical||meta3.kind==="channel"&&delivery.durable&&Date.now()-m2.ts>CHANNEL_CATCHUP_AGE_MS;const item=this.toInboxItem(m2,meta3.kind,historical);if(notice)item.notice=notice;else if(!delivery.take)this.noteDirected(item);if(item.kind==="channel"){const cm=this.channelModes.get(item.channel??"");const digest=item.id===""&&(this.enteringFocus||this._attention==="focus")?idlessDigest(m2):void 0;const tally=digest===void 0?void 0:this.reserveIdless(digest,item.channel??"");const copy2=tally?this.settleIdless(tally):void 0;const idless=copy2&&{digest,copy:copy2};if(this.enteringFocus)this.excludeFromFocus(item);if(this.dropUnsafe){this.excludeFromFocus(item);if(cm!=="muted"&&item.mentionsMe&&!item.historical){this.buffer(item,delivery,true,idless);this.emit("mention-wake",item)}else delivery.ack();return}if(cm==="muted"){this.evictedClassifications.delete(item.id);this.excludeFromFocus(item);this.protectDisposition(item.id,"drop");delivery.ack();return}const remembered=item.id===""?void 0:this.evictedClassifications.get(item.id);if(remembered)this.evictedClassifications.delete(item.id);const snapshottedPullOnly=item.historical||!item.mentionsMe&&(remembered?.pullOnly??cm==="quiet");if(cm==="quiet"||snapshottedPullOnly)this.excludeFromFocus(item);if(this._attention==="focus"&&item.mentionsMe&&!item.historical&&this.focusRecallUnsafeChannels.has(item.channel??"")){this.excludeFromFocus(item);this.buffer(item,delivery,true,idless);this.emit("mention-wake",item);return}if(cm!=="quiet"&&!snapshottedPullOnly&&this._attention==="focus"){this.protectDisposition(item.id,"drop");delivery.ack();if(item.id==="")this.buffer(item,{ack:()=>{}},true,idless);if(item.mentionsMe)this.emit("mention-wake",item);return}const automaticReply=this.config.channelRepliesPullOnly===true&&!!item.replyTo;const pullOnly=snapshottedPullOnly||!item.mentionsMe&&(automaticReply||this.classificationUnsafe);if(pullOnly)this.excludeFromFocus(item);this.buffer(item,delivery,pullOnly,idless);return}this.buffer(item,delivery,false)}buffer(item,delivery,pullOnly,idless){const pending={item,ack:delivery.ack,pullOnly,receivedAt:Date.now(),arrival:this.arrivals++};this.own(pending,delivery.redelivery);if(idless)pending.idless={tally:this.focusIdless,...idless};if(delivery.take){pending.take=delivery.take;this.gated.push(pending);if(this.gated.length>MAX_INBOX)this.gated.shift();this.emit("incoming",item);return}this.admit(pending);this.emit("incoming",item)}admit(pending){let at2=this.inbox.length;while(at2>0&&this.inbox[at2-1].arrival>pending.arrival)at2--;this.inbox.splice(at2,0,pending);if(this.inbox.length>MAX_INBOX){let excess=this.inbox.length-MAX_INBOX;while(excess-- >0){const evictable=p2=>!this.inFlightIds.has(p2.item.recvKey);let index2=this.inbox.findIndex(p2=>p2.pullOnly&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(p2=>p2.item.kind==="channel"&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(evictable);if(index2<0)break;const[evicted]=this.inbox.splice(index2,1);const sacrificingDirected=evicted.item.kind!=="channel";this.rememberEvicted(evicted);if(evicted.idless?.tally===this.focusIdless)this.unsettleIdless(evicted.idless.digest,evicted.idless.copy);if(!sacrificingDirected)evicted.ack()}}}rememberEvicted(p2){if(p2.item.kind!=="channel"||p2.item.mentionsMe||!p2.item.channel)return;if(p2.item.id==="")return;if(this.classificationUnsafe)return;if(!this.evictedClassifications.has(p2.item.id)&&this.evictedClassifications.size>=CLASSIFICATION_CAP){this.classificationUnsafe=true;this.evictedClassifications.clear();return}this.evictedClassifications.set(p2.item.id,{pullOnly:p2.pullOnly,channel:p2.item.channel})}excludeFromFocus(item){if(!this.enteringFocus&&this._attention!=="focus"||item.kind!=="channel"||!item.channel)return;if(item.id==="")return;if(!this.focusExcludedIds.has(item.id)&&this.focusExcludedIds.size>=FOCUS_EXCLUSION_CAP){const oldest=this.focusExcludedIds.entries().next().value;if(oldest){this.focusExcludedIds.delete(oldest[0]);this.focusRecallUnsafeChannels.add(oldest[1])}}this.focusExcludedIds.set(item.id,item.channel)}reserveIdless(digest,channel){if(this.focusIdlessEntries>=FOCUS_EXCLUSION_CAP){this.focusRecallUnsafeChannels.add(channel);return void 0}let tally=this.focusIdless.get(digest);if(!tally)this.focusIdless.set(digest,tally={channel,unbound:[],bound:new Set});this.focusIdlessEntries++;return tally}settleIdless(tally){const episode=this.focusIdless;const drops=this.transportDrops;const unbounded=()=>{if(episode===this.focusIdless)this.focusRecallUnsafeChannels.add(tally.channel)};const copy2={epoch:this.idlessEpoch,ready:Promise.resolve()};copy2.ready=this.ep.chatFrontier().then(frontier=>{if(drops===this.transportDrops)copy2.frontier=frontier;else unbounded()},unbounded);tally.unbound.push(copy2);return copy2}dropEmptyIdless(digest,tally){if(!tally.unbound.length&&!tally.bound.size)this.focusIdless.delete(digest)}unsettleIdless(digest,copy2){const tally=this.focusIdless.get(digest);if(!tally)return;if(tally.unbound.includes(copy2)){copy2.evicted=true;return}if(copy2.seq===void 0||!tally.bound.delete(copy2.seq))return;this.focusIdlessEntries--;this.dropEmptyIdless(digest,tally)}settleIdlessRead(channel,epoch,retained){for(const[digest,tally]of this.focusIdless){if(tally.channel!==channel)continue;const before=tally.unbound.length+tally.bound.size;tally.unbound=tally.unbound.filter(c3=>c3.epoch>=epoch);for(const seq of tally.bound)if(!retained.has(seq))tally.bound.delete(seq);this.focusIdlessEntries-=before-tally.unbound.length-tally.bound.size;this.dropEmptyIdless(digest,tally)}}async idlessReady(tallies,channel){const reads=[];for(const tally of tallies.values())if(tally.channel===channel)for(const c3 of tally.unbound)reads.push(c3.ready);await Promise.all(reads)}bindIdless(tally,epoch,free){let bound=Infinity;for(let i2=tally.unbound.length-1;i2>=0;i2--){const copy2=tally.unbound[i2];if(copy2.frontier===void 0)continue;bound=Math.min(bound,copy2.frontier);if(copy2.epoch>=epoch)continue;let at2=free.length-1;while(at2>=0&&free[at2]>bound)at2--;if(at2<0)continue;const[seq]=free.splice(at2,1);tally.unbound.splice(i2,1);if(copy2.evicted){this.focusIdlessEntries--;continue}copy2.seq=seq;tally.bound.add(seq)}}idlessUnsure(tally,epoch,seq){if(!tally||tally.bound.has(seq))return false;return tally.unbound.some(c3=>c3.epoch>=epoch&&c3.frontier!==void 0&&c3.frontier>=seq)}protectDisposition(id2,disposition){if(id2==="")return;const ids=disposition==="drop"?this.protectedDropIds:this.protectedPullOnlyIds;if((disposition==="drop"?this.dropUnsafe:this.classificationUnsafe)||ids.has(id2))return;if(ids.size>=PROTECTED_DISPOSITION_CAP){if(disposition==="drop")this.dropUnsafe=true;else this.classificationUnsafe=true;if(disposition!=="drop")ids.clear();return}ids.add(id2)}toInboxItem(m2,kind,historical){const text3=partsToText(m2.parts);return{id:m2.id,recvKey:m2.id!==""?m2.id:`${this.recvKeySecret}.${++this.recvKeySeq}`,ts:m2.ts,fromId:m2.from.id,fromName:m2.from.name,fromRole:m2.from.role,kind,channel:m2.channel,service:m2.toService,mentions:m2.mentions,mentionsMe:m2.mentions?.includes(this.config.name.toLowerCase())??false,historical,text:text3,replyTo:m2.replyTo,contextId:m2.contextId}}peekInbox(scope="all"){this.dropLapsedTakes();return this.inbox.filter(p2=>this.inScope(p2,scope)).map(p2=>p2.item)}inboxPreview(scope="all"){this.dropLapsedTakes();const askable=scope==="pull-only"?[]:this.gated.filter(p2=>this.mayOffer(p2));return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...askable].sort((a3,b3)=>a3.arrival-b3.arrival).map(p2=>p2.item)}async takeChosen(scope,choose,waitMs=TAKE_WAIT_MS){const chosen=choose(this.inboxPreview(scope));const keys=new Set(chosen.map(i2=>i2.recvKey));const asked=scope==="pull-only"?[]:this.gated.filter(p2=>keys.has(p2.item.recvKey)&&this.mayOffer(p2));for(const p2 of asked)p2.awaited=(p2.awaited??0)+1;const runs=asked.map(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops?p2.taking:this.startTake(p2));if(runs.length){let timer2;const waited=new Promise(resolve4=>{timer2=setTimeout(resolve4,waitMs);timer2.unref?.()});await Promise.race([Promise.allSettled(runs),waited]);clearTimeout(timer2)}for(const p2 of asked)p2.awaited=(p2.awaited??1)-1;const showable=new Map(this.peekInbox(scope).map(i2=>[i2.recvKey,i2]));return chosen.flatMap(i2=>showable.get(i2.recvKey)??[])}heldTakes(){const count=this.gated.filter(p2=>p2.taking===void 0).length;const waiting=this.gated.filter(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops).length;if(waiting)return{count:waiting+(this.heldTake?count:0),detail:"the delivery daemon has not answered the take yet"};return count&&this.heldTake?{count,detail:this.heldTake.detail}:{count}}mayAskTakes(){return this._transportConnected&&(!this.heldTake||Date.now()>=this.heldTake.retryAt)}mayOffer(p2){return p2.taking!==void 0&&this._transportConnected||this.mayAskTakes()}startTake(p2){const run=this.runTake(p2).catch(e3=>this.handleEndpointWarning(e3)).finally(()=>{if(p2.taking===run)p2.taking=void 0});p2.taking=run;p2.takingDrops=this.transportDrops;return run}async runTake(p2){const take=p2.take;if(!take)return;if(!this._transportConnected)return;if(!this.renewOwned(p2)){this.dropGated(p2);return}const count=p2.item.deliveryCount;const drops=this.transportDrops;const outcome=await take();if(!this.gated.includes(p2)||p2.take!==take)return;if(this.transportDrops!==drops){if(p2.takingDrops!==drops)return;if(this._transportConnected)this.emit("incoming",p2.item);return}if(outcome.taken){this.heldTake=void 0;const current=p2.item.deliveryCount===count&&p2.ownedUntil!==void 0&&Date.now()<p2.ownedUntil;if(!current)return;p2.takenCount=count;p2.takenOnce=true;this.gated.splice(this.gated.indexOf(p2),1);this.noteDirected(p2.item);this.admit(p2);if(!p2.awaited)this.emit("incoming",p2.item);return}if(outcome.drop){this.dropGated(p2);return}const first=this.heldTake?.reason!==outcome.reason;this.heldTake={reason:outcome.reason,detail:outcome.detail,retryAt:Date.now()+TAKE_RETRY_MS};this.takeRetry??=setTimeout(()=>{this.takeRetry=void 0;for(const held2 of this.gated)this.emit("incoming",held2.item)},TAKE_RETRY_MS);this.takeRetry.unref?.();if(first&&outcome.reason!=="daemon-busy")this.handleEndpointWarning(new Error(outcome.detail))}dropGated(p2){const i2=this.gated.indexOf(p2);if(i2>=0)this.gated.splice(i2,1)}regate(p2){const i2=this.inbox.indexOf(p2);if(i2<0)return;this.inbox.splice(i2,1);p2.takenCount=void 0;this.gated.push(p2)}dropLapsedTakes(){const now=Date.now();this.inbox=this.inbox.filter(p2=>!p2.take||this.inFlightIds.has(p2.item.recvKey)||p2.ownedUntil!==void 0&&now<p2.ownedUntil);this.gated=this.gated.filter(p2=>p2.taking!==void 0||p2.ownedUntil===void 0||now<p2.ownedUntil)}holdInFlight(ids){let fresh=0;for(const id2 of ids)if(!this.inFlightIds.has(id2))fresh++;if(this.inFlightIds.size+fresh>MAX_IN_FLIGHT)return false;for(const id2 of ids){this.inFlightIds.set(id2,(this.inFlightIds.get(id2)??0)+1);this.keepOwned(id2)}return true}isInFlight(id2){return this.inFlightIds.has(id2)}releaseInFlight(ids){for(const id2 of ids){const held2=this.inFlightIds.get(id2);if(held2===void 0)continue;if(held2<=1){this.inFlightIds.delete(id2);this.stopRenewal(id2);if(!this.lowerOnRelease.delete(id2))continue;const p2=this.inbox.find(pending=>pending.item.recvKey===id2);if(p2&&!p2.pullOnly){p2.pullOnly=true;this.excludeFromFocus(p2.item)}}else this.inFlightIds.set(id2,held2-1)}}own(p2,redelivery){p2.redelivery=redelivery;p2.ownedUntil=redelivery&&Date.now()+redelivery.ackWaitMs;p2.item.deliveryCount=redelivery?.deliveryCount}keepOwned(key){if(this.renewals.has(key))return;const p2=this.inbox.find(x2=>x2.item.recvKey===key);if(!p2?.redelivery||!this.renewOwned(p2))return;const timer2=setInterval(()=>{const held2=this.inbox.find(x2=>x2.item.recvKey===key);if(!held2||!this.renewOwned(held2))this.stopRenewal(key)},p2.redelivery.ackWaitMs/2);timer2.unref?.();this.renewals.set(key,timer2)}stopRenewal(key){clearInterval(this.renewals.get(key));this.renewals.delete(key)}renewOwned(p2){if(!p2.redelivery||p2.ownedUntil===void 0||Date.now()>=p2.ownedUntil)return false;if(!this._transportConnected)return true;try{p2.redelivery.working()}catch{return false}p2.ownedUntil=Date.now()+p2.redelivery.ackWaitMs;return true}drainInbox(limit,scope="all"){this.dropLapsedTakes();const eligible=this.inbox.filter(p2=>this.inScope(p2,scope));const n2=limit&&limit>0?Math.min(limit,eligible.length):eligible.length;const selected=eligible.slice(0,n2);this.noteAutomaticHeadProgress(selected);const taken=new Set(selected);this.inbox=this.inbox.filter(p2=>!taken.has(p2));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();return items}drainInboxDeliveries(keys){const requested=[...new Set(keys)];const wanted=new Set(requested);const regated=this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&p2.takenOnce);const unshown=new Set(this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&!p2.takenOnce).map(p2=>p2.item.recvKey));if(regated.length)this.gated=this.gated.filter(p2=>!regated.includes(p2));const selected=[...this.inbox.filter(p2=>wanted.has(p2.item.recvKey)),...regated];this.noteAutomaticHeadProgress(selected);const present=new Set(selected.map(p2=>p2.item.recvKey));const pullOnly=new Map(selected.map(p2=>[p2.item.recvKey,p2.pullOnly]));for(const id2 of requested){const remembered=id2!==""?this.evictedClassifications.get(id2):void 0;if(!pullOnly.has(id2)&&remembered)pullOnly.set(id2,remembered.pullOnly)}this.inbox=this.inbox.filter(p2=>!present.has(p2.item.recvKey));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();for(const id2 of requested){if(!present.has(id2)&&!unshown.has(id2)&&!id2.startsWith(`${this.recvKeySecret}.`)){this.markHandled(id2,pullOnly.get(id2)??false);this.evictedClassifications.delete(id2)}}return{items,missingKeys:requested.filter(key=>!present.has(key)&&!unshown.has(key))}}commitPending(taken){for(const p2 of taken){p2.ack();this.markHandled(p2.item.id,p2.pullOnly);this.evictedClassifications.delete(p2.item.id)}return taken.map(p2=>p2.item)}inScope(p2,scope){return scope==="all"||(scope==="pull-only"?p2.pullOnly:!p2.pullOnly)}markHandled(id2,pullOnly=false){if(id2==="")return;if(pullOnly)this.protectDisposition(id2,"pull-only");this.handledIds.add(id2);if(this.handledIds.size>=4096){this.handledIdsPrev=this.handledIds;this.handledIds=new Set}}inboxKeys(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item.recvKey)}inboxPending(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item)}inboxCount(scope="all"){const held2=scope==="pull-only"?0:this.gated.length;return held2+(scope==="all"?this.inbox.length:this.inbox.filter(p2=>this.inScope(p2,scope)).length)}inboxSnapshot(limit=3){if(!Number.isInteger(limit)||limit<0||limit>8)throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);this.dropLapsedTakes();return{unread:this.inbox.length+this.gated.length,items:this.inbox.slice(0,limit).map(p2=>({...p2.item}))}}oldestAutomaticReceivedAt(){let oldest;for(const pending of[...this.inbox,...this.gated]){if(pending.pullOnly)continue;if(oldest===void 0||pending.receivedAt<oldest)oldest=pending.receivedAt}return oldest}get recallCursor(){return this._recallCursor}noteRecalled(mark){if(afterRecallMark(mark,this._recallCursor))this._recallCursor=mark}recallAhead(item){return item.ts>Date.now()}recallAheadSeen(id2){return this.aheadDelivered.has(id2)}recallAheadRoom(){return MAX_AHEAD-this.aheadDelivered.size}noteRecalledAhead(id2){if(this.aheadDelivered.size<MAX_AHEAD)this.aheadDelivered.add(id2)}resetRecallWalk(){this._recallCursor={ts:0,id:""};this.aheadDelivered.clear()}inboxScope(key){const pending=this.inbox.find(p2=>p2.item.recvKey===key)??this.gated.find(p2=>p2.item.recvKey===key);return pending?pending.pullOnly?"pull-only":"automatic":void 0}directedPendingCount(){return this.gated.length+this.inbox.filter(p2=>!p2.pullOnly&&(p2.item.kind!=="channel"||!p2.item.historical&&p2.item.mentionsMe)).length}inboxWake(skip){this.dropLapsedTakes();const held2=this.mayAskTakes()?this.gated.filter(p2=>(p2.taking===void 0||p2.takingDrops!==this.transportDrops)&&!skip?.(p2.item)).length:0;return held2+this.inbox.filter(p2=>{const it2=p2.item;if(p2.pullOnly||it2.kind==="channel"&&it2.historical||skip?.(it2))return false;if(it2.kind!=="channel"||it2.mentionsMe)return true;return this._attention==="open"}).length}get attention(){return this._attention}channelMode(channel){return channel?this.channelModes.get(channel):void 0}channelModeEntries(){return Object.fromEntries(this.channelModes)}async setChannelMode(channel,mode){if(!isConcreteChannel(channel))throw new Error(`"${channel}" must be a concrete channel (no wildcard) to set its attention`);if(!channelInAllow(this.config.allowSubscribe,channel))throw new Error(`"${channel}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]`);await this.inOrder(()=>{if(mode==="normal")this.channelModes.delete(channel);else{this.channelModes.set(channel,mode);this.lowerBuffered(channel,mode==="muted")}return this.ep.setChannelModes(this.channelModeEntries())})}lowerBuffered(channel,mentions,keep=[]){for(const p2 of this.inbox){if(p2.pullOnly||p2.item.kind!=="channel"||!p2.item.channel||!channelInAllow([channel],p2.item.channel))continue;if(channelInAllow(keep,p2.item.channel))continue;if(p2.item.mentionsMe&&!mentions)continue;if(this.inFlightIds.has(p2.item.recvKey)){this.lowerOnRelease.add(p2.item.recvKey);continue}p2.pullOnly=true;this.excludeFromFocus(p2.item)}}async setAttention(mode){await this.inOrder(async()=>{if(mode==="focus"){await this.requireConnected();this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.enteringFocus=this._attention!=="focus";try{this.focusSince=await this.ep.chatFrontier()}catch(error51){this.enteringFocus=false;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();throw error51}this.enteringFocus=false;this.resetRecallWalk()}else{this.enteringFocus=false;this.focusSince=void 0;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.resetRecallWalk()}this._attention=mode;await this.ep.setAttention(mode)})}async recallAmbient(underway=new Set){const run=this.recallLock.then(()=>this.recallAmbientOnce(underway));this.recallLock=run.catch(()=>{});return run}async recallAmbientOnce(underway){if(this._attention!=="focus"||this.focusSince===void 0)return{items:[],droppedChannels:[]};const items=[];const droppedChannels=[];for(const channel of this.ep.joinedChannels()){if(!isConcreteChannel(channel)){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const tallies=this.focusIdless;let epoch=0;let read;for(let attempt=1;attempt<=IDLESS_READS;attempt++){epoch=++this.idlessEpoch;await this.idlessReady(tallies,channel);read=await this.ep.recallChannel(channel,this.focusSince);if(read.unanswered)break;await this.idlessReady(tallies,channel);const unsure=read.messages.some((m2,i2)=>m2.id===""&&this.idlessUnsure(tallies.get(idlessDigest(m2)),epoch,read.seqs[i2]));if(!unsure)break}const{messages,seqs,dropped,unanswered}=read;if(unanswered){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const retained=new Set;const digests=[];const free=new Map;for(const[i2,m2]of messages.entries()){if(m2.id!==""||tallies!==this.focusIdless)continue;retained.add(seqs[i2]);const digest=digests[i2]=idlessDigest(m2);if(tallies.get(digest)?.bound.has(seqs[i2]))continue;const list=free.get(digest);if(list)list.push(seqs[i2]);else free.set(digest,[seqs[i2]])}for(const[digest,list]of free){const tally=tallies.get(digest);if(tally)this.bindIdless(tally,epoch,list)}let incomplete=dropped;for(const[i2,m2]of messages.entries()){if(m2.id!==""){if(underway.has(m2.id)||!this.focusExcludedIds.has(m2.id))items.push(this.toInboxItem(m2,"channel",true));continue}if(tallies!==this.focusIdless)continue;const seq=seqs[i2];const digest=digests[i2];const tally=tallies.get(digest);if(tally?.bound.has(seq))continue;if(this.idlessUnsure(tally,epoch,seq)){incomplete=true;continue}const fresh=this.inbox.length<MAX_INBOX?this.reserveIdless(digest,channel):void 0;if(!fresh){incomplete=true;continue}const copy2={epoch,frontier:seq,ready:Promise.resolve(),seq};fresh.bound.add(seq);this.buffer(this.toInboxItem(m2,"channel",true),{ack:()=>{}},true,{digest,copy:copy2})}if(tallies===this.focusIdless)this.settleIdlessRead(channel,epoch,retained);if(incomplete)droppedChannels.push(channel)}items.sort((a3,b3)=>a3.ts-b3.ts);return{items,droppedChannels}}};var SPAWN_TIMEOUT_MS=4e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s3=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s3.trim()))}var EVENTS_META_KEY="ai.cotal.events";function buildMeta(config2,processCwd,eventsArmed){const meta3={...config2.meta??{}};if(config2.model)meta3.model=config2.model;if(config2.variant)meta3.variant=config2.variant;if(config2.connector)meta3.connector=config2.connector;meta3.host=hostname2();delete meta3["ai.cotal.manager.instance"];if(config2.managerInstanceId)meta3["ai.cotal.manager.instance"]=config2.managerInstanceId;meta3[EVENTS_META_KEY]=eventsArmed??eventPlaneArmed(config2)?"on":"off";if(processCwd)meta3.cwd=process.cwd();else delete meta3.cwd;return Object.keys(meta3).length?meta3:void 0}var MAX_CORRELATIONS=1024;var ENDPOINT_ERROR_LOG_WINDOW_MS=3e4;var MAX_ENDPOINT_NOTICES=16;var NAMED_SIMILAR=5;var MAX_SETTLED_TURNS=32;function settledTurnError(goalId,t2){if(t2.yielded!==void 0)return`turn "${goalId}" was already yielded ${t2.yielded} by this seat${t2.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t2.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}var MAX_DATE_MS=864e13;function isPendingTurn(t2){const r2=t2;if(typeof r2!=="object"||r2===null||typeof r2.goalId!=="string"||typeof r2.payload!=="string")return false;if(!Number.isSafeInteger(r2.acceptedAt)||r2.acceptedAt<0)return false;if(r2.once!==void 0&&r2.once!==true)return false;if(r2.deadlineAt===void 0)return r2.once===true;return Number.isSafeInteger(r2.deadlineAt)&&r2.deadlineAt>=1&&r2.deadlineAt<=MAX_DATE_MS}function onceSpawner(payload){try{const spawner=JSON.parse(payload).once?.spawner;return typeof spawner==="string"&&spawner.length>0?spawner:void 0}catch{return void 0}}function sleep(ms){return new Promise(r2=>setTimeout(r2,ms))}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p2){const escalation=renderEscalation(p2);if(escalation!=="")return escalation;const ask=p2.ask;if(ask===null||typeof ask!=="object")return"";const a3=ask;const entries=a3.schema!==null&&typeof a3.schema==="object"?Object.entries(a3.schema):[];const fields=entries.length===0?"any record":entries.map(([k2,v3])=>`${k2}: ${String(v3)}`).join(", ");const by=typeof a3.deadlineAt==="number"?`, by ${new Date(a3.deadlineAt).toISOString()}`:"";const refused3=typeof a3.refused==="string"?`
130
+ (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=deepFreeze4({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=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze4({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=deepFreeze4({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(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),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=deepFreeze4({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},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze4(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze4(child);Object.freeze(v3)}return v3}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();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 deepFreeze5(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze5(child);Object.freeze(value)}return value}var text2={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 closed3=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed3({owner,actor,lifecycleUid:uid});var pair={threadId:text2,toolCallId:text2};var status=(state,fields={})=>closed3({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed3({owner,actor}),iat:uint2,exp:uint2,issuer:closed3({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint2}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed3({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint2,registrationRevision:{...uint2,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed3({t0:uint2,watermark:uint2,watermarkTakenAt:uint2,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint2}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze5(closed3(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze5({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=deepFreeze5({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze5(closed3({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze5(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze5(closed3({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze5({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze5([{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=deepFreeze5({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();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;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream30=__toESM(require_mod4(),1);var import_transport_node29=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream31=__toESM(require_mod4(),1);var import_kv14=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();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 path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)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(path)}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 path=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token2=material?material.controlKey:directControlKey(env);if(path&&token2){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,token:token2,version:version2}}if(!path&&!token2)return void 0;if(path)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}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 path=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path)discardLaunchMaterial(path)}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 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 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}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,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,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,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{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID10}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 randomUUID9}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(path,invariant,detail){super(`event WAL at ${path} is unusable (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path,expectedGen,foundGen){super(`event WAL at ${path} 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=path;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n2=>Number.isSafeInteger(n2)&&n2>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path,"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(path){return open2(path,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p2,f2){if(p2.E!==f2.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p2.E} frontier.lastSubjectSeq=${f2.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p2.seq!==f2.seq+1)throw new WalCorruptError(path,"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(path,"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(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p2.ackSeq)}`);if(!(p2.ackSeq>f2.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p2.ackSeq} frontier.lastSubjectSeq=${f2.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v3,nullable2){if(v3===null&&nullable2)return null;if(typeof v3!=="object"||v3===null)throw new WalCorruptError(path,`${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(path,`${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,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path,`${field}.${k2} is an array of strings`,JSON.stringify(list))}if(b3.run===void 0&&b3.text.concat(b3.reasoning,b3.tools).length>0)throw new WalCorruptError(path,`${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(path,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(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space2,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(path,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path,"document is an object",typeof d2);const doc=d2;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path,`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(path,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f2=doc.frontier;if(!f2||!isSafeNonNegInt2(f2.seq)||!isSafeNonNegInt2(f2.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f2.sourceCursor!==void 0&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f2.sourceCursor);if(f2.seq===0!==(f2.lastSubjectSeq===0))throw new WalCorruptError(path,"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(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f2));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"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(path,"pending.state is a known tag",String(p2.state));if(typeof p2.id!=="string"||p2.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p2.id));try{assertIdToken(p2.id,"event WAL pending.id")}catch(e3){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e3.message)}if(!isSafeNonNegInt2(p2.E)||!isSafeNonNegInt2(p2.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p2));if(typeof p2.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p2.sourceCursor);if(!Array.isArray(p2.body)||p2.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p2.body));if(doc.v===1)throw new WalCorruptError(path,"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(path,"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(path,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p2.payloadCalls=parsePayloadCalls(path,p2.payloadCalls);pending=p2;assertPendingVintage(path,pending,f2)}const brackets=doc.v===1?null:parseBrackets(path,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f2,pending,payloadCalls:parsePayloadCalls(path,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(path,doc){this.path=path;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 path=join6(parent,entry.name,"wal.json");if(path===this.path)continue;if(entry.isSymbolicLink())throw new WalCorruptError(path,"a real thread directory","found a symlink");if(!entry.isDirectory())continue;let bytes;try{const st2=await lstat2(path);if(!st2.isFile()||st2.nlink!==1)throw new WalCorruptError(path,"a real thread log with one name","refusing linked or non-file state");const file2=await open2(path,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}const raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes);const doc=JSON.parse(raw);if(doc.pending?.state!=="sent_unacked")continue;const threadId=doc.threadId;if(typeof threadId!=="string"||createHash7("sha256").update(threadId).digest("hex").slice(0,16)!==entry.name)throw new WalCorruptError(path,"thread id matches its directory","refusing misplaced state");const sibling=new _EventWal(path,parseDoc(path,raw,this.space,threadId,this.principal));if(sibling.pending)siblings.push(sibling)}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path,opts){let raw;let bytes;try{bytes=await readFile(path)}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(path,"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(path,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path,parseDoc(path,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID9(),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.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)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);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:randomUUID9(),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}.${randomUUID9().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(message){super(message);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")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL principal lock at ${path} (${invariant}): ${detail}`);this.path=path;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(path){try{return await openExclusiveNoFollow(path)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path){let raw;try{raw=await readFile2(path,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path,"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=record2;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path,"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(path,"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(path,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path).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 record2=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID10(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"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 TURN_PULL_RETRY_MS=15e3;var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY=Symbol.for("cotal.once-handoff");function proc(){const g2=globalThis;return g2[KEY]??={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 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}init_peer_label();var LABEL_MAX_CODE_POINTS=40;function capped(s3,max){const points=Array.from(s3);return points.length<=max?s3:`${points.slice(0,max-1).join("")}\u2026`}function attributionSafe(s3){return peerLabel({name:s3})}var FROM_MAX_CODE_POINTS=160;var FROM_MIN_CODE_POINTS=" (unverified name)".length+2;function fmtFrom(i2,maxCodePoints=FROM_MAX_CODE_POINTS){if(!Number.isInteger(maxCodePoints)||maxCodePoints<FROM_MIN_CODE_POINTS)throw new RangeError(`a sender label bound must be a whole number of at least ${FROM_MIN_CODE_POINTS} code points, got ${maxCodePoints}`);const named=i2.fromName.trim()!=="";const label=peerLabel({name:named?i2.fromName:i2.fromId,...i2.fromRole?{role:i2.fromRole}:{}});const marker=named?" (unverified name)":i2.fromRole?" (unverified role)":"";return`${capped(label,maxCodePoints-marker.length)}${marker}`}function fmtBody(text3){return text3.split(LINE_BREAK).join("\n ")}function fmtItem(i2){return formatItem(i2)}function fmtDeliveryItem(i2){const field=value=>Array.from(JSON.stringify(value),char=>[91,93,133,8232,8233].includes(char.charCodeAt(0))?`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`:char).join("");const metadata2=[`sender_id=${field(i2.fromId)}`,...i2.id?[`message_id=${field(i2.id)}`]:[],...i2.contextId?[`context_id=${field(i2.contextId)}`]:[],...i2.replyTo?[`reply_to=${field(i2.replyTo)}`]:[]];return formatItem(i2,`[${metadata2.join(" ")}] `)}function formatItem(i2,metadata2="",attributionMax){const h3=i2.historical?"(history) ":"";const body=`${metadata2}${h3}${redeliveryNote(i2)}${fmtBody(i2.text)}`;if(i2.notice)return`[${i2.notice} notice from the delivery daemon] ${body}`;const label=s3=>attributionMax===void 0?attributionSafe(s3??""):capped(attributionSafe(s3??""),LABEL_MAX_CODE_POINTS);const from=head2=>fmtFrom(i2,attributionMax===void 0?void 0:Math.min(FROM_MAX_CODE_POINTS,attributionMax-Array.from(head2).length-"] ".length));if(i2.kind==="dm")return`[DM from ${from("[DM from ")}] ${body}`;if(i2.kind==="anycast"){const head2=`[@${label(i2.service)} from `;return`${head2}${from(head2)}] ${body}`}const head=`[#${label(i2.channel)}${i2.mentionsMe?" @you":""} `;return`${head}${from(head)}] ${body}`}function redeliveryNote(i2){const n2=i2.deliveryCount;if(n2===void 0||n2<=1)return"";if(i2.firstDeliveryCount===void 0||i2.firstDeliveryCount>1)return`(broker redelivery, delivery ${n2}: prior model handoff unknown) `;if(i2.handedOverAt!==void 0&&i2.handedOverAt<n2)return`(broker redelivery, delivery ${n2}: an earlier handoff in this session was not confirmed) `;return""}function fmtChannel(channel){const safe=attributionSafe(channel??"").trim();return safe.length?safe:"?"}var CONNECTOR_VERSION="0.171.1";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(token2){try{const exp=JSON.parse(Buffer.from(token2.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)return Promise.reject(signal.reason);return new Promise((resolve4,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve4(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()}dropBearer(argv){this.managerBearers.delete(JSON.stringify(argv))}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"};if(!user.bearerCmd)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const managerInstanceId=instance??this.config.managerInstanceId;const token2=await this.managerCallBearer([...user.bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]]).catch(e3=>{throw e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token2);return withUserManagerListing({...this.config,managerInstanceId},token2,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(token2=>{const exp=bearerExpiryMs2(token2);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;if(this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)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 managerInstanceId=opts.instanceId??this.config.managerInstanceId;const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearerArgv=[...bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{if(signal?.aborted||!(e3 instanceof Error)||e3 instanceof EpEnvelopeError)throw e3;const message=e3.message.replace("--manager-instance <instanceId>","the instance argument");if(typeof e3.retryAfterSeconds==="number")throw new EpEnvelopeError("resource-exhausted",message,void 0,"not-executed");if(e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",message,void 0,"not-executed");throw new Error(message)});dropBearer=()=>{this.managerBearers.delete(JSON.stringify(bearerArgv))};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.execBearerCmd([...bearerCmd,"--manager-call","--manager-instance",instanceId],signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...this.config.userAuth,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 message=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,message),...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 answer=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer?.ok===true&&answer.instanceId===instanceId?answer.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 order=compareRelease(CONNECTOR_VERSION,manager);if(order>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order<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,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,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 caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??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 caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve4=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{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 resolve4(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve4(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;try{({caller,instanceId,credentialId}=managerCallerBinding(token2,{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:token2,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??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(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 resolve4(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 connect3();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 CommandRefused=class extends Error{code;constructor(code,message){super(message);this.code=code;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code,message)=>new EpEnvelopeError(code,message,void 0,"not-executed");var what=c3=>`the ${c3.target} "${c3.name}"`;function cut(text3,max){const chars=[...text3];return chars.length<=max?text3:`${chars.slice(0,max-1).join("")}\u2026`}function fitText(text3,max){return typeof text3==="string"&&text3!==""?cut(text3,max):void 0}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 createCommandLane(dispatcher,onQueued){const entries=new Map;const ended=[];let closed4=false;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued");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 end(e3,state){e3.state=state;ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}async function list(){if(!dispatcher)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}`)}if(!Array.isArray(listed))throw refused("internal","the connector's list is not an array");const commands=[];for(const e3 of listed){if(!isAgentCommandName(e3?.name))continue;if(!dispatcher.targets.has(e3.target))throw refused("internal",`the connector listed the ${String(e3.target)} "${e3.name}" but runs no ${String(e3.target)}s`);const description=fitText(e3.description,AGENT_COMMAND_DESCRIPTION_MAX),inputHint=fitText(e3.inputHint,AGENT_COMMAND_INPUT_HINT_MAX);commands.push({name:e3.name,target:e3.target,...description?{description}:{},...inputHint?{inputHint}:{}})}if(commands.length>AGENT_COMMAND_LIST_MAX)throw refused("resource-exhausted",`the harness lists ${commands.length} commands and skills, over the ${AGENT_COMMAND_LIST_MAX} a reply carries`);return{supported:true,commands}}function run(input){if(!dispatcher)throw refused("unimplemented","this agent's connector runs no commands or skills");if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);if(closed4)throw refused("unavailable","this agent is stopping");if(queued().length>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));entries.set(id2,{id:id2,command:{target:input.target,name:input.name,args:input.args??""},state:{kind:"queued"}});onQueued();return{id:id2}}function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end(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:()=>list()},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx.request.args)},{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})}],get queued(){return queued().length},async dispatchNext(){const e3=queued()[0];if(!e3)return"empty";e3.state={kind:"taken"};try{await dispatcher.dispatch(e3.command);end(e3,{kind:"started"});return"dispatched"}catch(err3){const message=String(err3?.message??err3);end(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut(message,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut(`the harness failed, so ${what(e3.command)} may have started: ${message}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}},close(){closed4=true;for(const e3 of queued())end(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3.command)} started`})}}}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,message){super(message);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 answer=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,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer},true);if(event.result==="gone")return close({kind:"undelivered",answer},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},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer,seen:e3.seen},true);return close({kind:"unconfirmed",answer,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer,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 deepFreeze6(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze6(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused2(code,message,details){return new EpEnvelopeError(code,message,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 closed4=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed4({kind:"expired"}));measure(closed4({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed4({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer,delivery:"unconfirmed"});measure({kind:"sent",answer,delivery:"delivered"});measure(closed4({kind:"answered",answer}));measure(closed4({kind:"unconfirmed",answer,seen:LONGEST_SEEN}));measure(closed4({kind:"undelivered",answer}));measure(closed4({kind:"local",seen:LONGEST_SEEN,late:answer}))}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 content=deepFreeze6(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content);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}})){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 content.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content.form!==void 0&&!content.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content.subject?.type==="tool"?content.subject.input:void 0;if(input?.kind==="omitted"&&content.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(content.form!==void 0){const schema=content.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:content.kind,title:content.title,contentBytes,...content.source!==void 0?{source:content.source}:{}};const largest=largestSummaryBytes(base,content.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:deepFreeze6(base),live:{content,options,...form?{form}:{}},state:deepFreeze6({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=deepFreeze6(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 refused2("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 open6=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open6.push(this.summary(h3));const closed4=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:open6,closed:closed4})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused2("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused2("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 refused2("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused2("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused2("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 refused2("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused2("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 refused2("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused2("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused2("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused2("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused2("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 refused2("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=deepFreeze6({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 refused2("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 refused2("internal","the agent could not check this answer")}throw refused2("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused2("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer},answer.at);if(step.kind!=="move"||!step.deliver)throw refused2("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze6(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve4=>{const w2={resolve:resolve4,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve4(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,caller){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller.owner}.${caller.actor}.${caller.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}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);const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}));const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers]});desk.served(serve.ready);let closing;const close=()=>closing??=(()=>{ep.off("transport",onTransport);desk.close();lane.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,close}}import{randomUUID as randomUUID11}from"node:crypto";import{createHash as createHash9}from"node:crypto";var CHANNEL_CATCHUP_AGE_MS=5*6e4;function afterRecallMark(a3,b3){return a3.ts!==b3.ts?a3.ts>b3.ts:a3.id>b3.id}var MAX_INBOX=200;var TAKE_WAIT_MS=2e3;var TAKE_RETRY_MS=1e4;var MAX_IN_FLIGHT=MAX_INBOX*2;var MAX_AHEAD=256;var CLASSIFICATION_CAP=4096;var FOCUS_EXCLUSION_CAP=4096;var IDLESS_READS=3;var PROTECTED_DISPOSITION_CAP=4096;function deliveryNoticeOf(m2){for(const p2 of m2.parts){if(p2.kind!=="data"||typeof p2.data!=="object"||p2.data===null||Array.isArray(p2.data))continue;if(ANYCAST_NOTICE_KEY in p2.data)return"anycast";if(MENTION_NOTICE_KEY in p2.data)return"mention"}return void 0}function idlessDigest(m2){return createHash9("sha256").update(JSON.stringify(m2)).digest("base64url")}function handOver(item){item.handedOverAt??=item.deliveryCount??0}function ingestDedupKey(id2){return id2===""?void 0:id2}var AgentInbox=class{deps;constructor(deps){this.deps=deps}get ep(){return this.deps.endpoint()}get config(){return this.deps.config()}get _transportConnected(){return this.deps.transportConnected()}emit(event,item){this.deps.emit(event,item)}handleEndpointWarning(error51){this.deps.warning(error51)}noteDirected(item){this.deps.noteDirected(item)}inOrder(write){return this.deps.inOrder(write)}requireConnected(){return this.deps.requireConnected()}seedChannelModes(config2){for(const c3 of config2.quiet??[])this.channelModes.set(c3,"quiet");for(const c3 of config2.muted??[])this.channelModes.set(c3,"muted")}onTransport(connected){if(!connected){this.transportDrops++;for(const p2 of this.inbox.filter(x2=>x2.take&&!this.inFlightIds.has(x2.item.recvKey)))this.regate(p2)}if(connected&&this.mayAskTakes()){this.dropLapsedTakes();for(const p2 of this.gated)if(p2.taking===void 0)this.emit("incoming",p2.item)}}stop(){for(const key of[...this.renewals.keys()])this.stopRenewal(key);clearTimeout(this.takeRetry);this.takeRetry=void 0}inbox=[];gated=[];arrivals=0;heldTake;takeRetry;handledIds=new Set;handledIdsPrev=new Set;evictedClassifications=new Map;inFlightIds=new Map;lowerOnRelease=new Set;renewals=new Map;classificationUnsafe=false;protectedPullOnlyIds=new Set;protectedDropIds=new Set;dropUnsafe=false;_lastInboxDrainedAt;_lastAutomaticDrainedAt;_lastAutomaticHeadDrainedAt;_attention="open";_recallCursor={ts:0,id:""};aheadDelivered=new Set;channelModes=new Map;focusSince;enteringFocus=false;recvKeySecret=randomUUID11().replace(/-/g,"");recvKeySeq=0;focusExcludedIds=new Map;focusIdless=new Map;focusIdlessEntries=0;idlessEpoch=0;recallLock=Promise.resolve();transportDrops=0;focusRecallUnsafeChannels=new Set;get lastInboxDrainedAt(){return this._lastInboxDrainedAt}get lastAutomaticDrainedAt(){return this._lastAutomaticDrainedAt}get lastAutomaticHeadDrainedAt(){return this._lastAutomaticHeadDrainedAt}oldestAutomaticKey(){let head;for(const pending of this.inbox){if(pending.pullOnly)continue;if(head===void 0||pending.receivedAt<head.receivedAt)head=pending}return head?.item.recvKey}noteAutomaticHeadProgress(selected){const head=this.oldestAutomaticKey();if(head===void 0)return;if(selected.some(p2=>!p2.pullOnly&&p2.item.recvKey===head))this._lastAutomaticHeadDrainedAt=Date.now()}automaticQueueStalledForMs(now=Date.now()){const oldest=this.oldestAutomaticReceivedAt();if(oldest===void 0)return void 0;const since=Math.max(oldest,this._lastAutomaticHeadDrainedAt??0);const held2=now-since;return held2>0?held2:0}get channelDeliveryIssue(){return this.dropUnsafe?"Channel drop tracking exhausted. Ambient channel traffic is suppressed until restart; non-historical mentions on unmuted channels wake to pull their buffered body. Focus recall may be incomplete.":void 0}async ingestNotice(m2,delivery,meta3,notice){const holder=await this.ep.deliveryLeaseHolder(0);this.ingest(m2,delivery,meta3,holder!==void 0&&holder===m2.from.id?notice:void 0)}ingest(m2,delivery,meta3,notice){const key=ingestDedupKey(m2.id);if(key!==void 0&&(this.handledIds.has(key)||this.handledIdsPrev.has(key))){if(delivery.durable)delivery.ack();return}if(key!==void 0&&(this.protectedPullOnlyIds.has(key)||this.protectedDropIds.has(key))){if(delivery.durable)delivery.ack();return}const existing=key===void 0?void 0:this.inbox.find(p2=>p2.item.id===key)??this.gated.find(p2=>p2.item.id===key);if(existing){if(delivery.durable){existing.ack=delivery.ack;this.own(existing,delivery.redelivery);if(delivery.take)existing.take=delivery.take;if(this.inFlightIds.has(existing.item.recvKey))this.keepOwned(existing.item.recvKey);else if(existing.take&&existing.takenCount!==existing.item.deliveryCount)this.regate(existing);this.emit("incoming",existing.item)}return}if(!meta3)throw new Error(`message ${m2.id} delivered without MessageMeta \u2014 its class is unauthenticated`);const historical=meta3.historical||meta3.kind==="channel"&&delivery.durable&&Date.now()-m2.ts>CHANNEL_CATCHUP_AGE_MS;const item=this.toInboxItem(m2,meta3.kind,historical);if(notice)item.notice=notice;else if(!delivery.take)this.noteDirected(item);if(item.kind==="channel"){const cm=this.channelModes.get(item.channel??"");const digest=item.id===""&&(this.enteringFocus||this._attention==="focus")?idlessDigest(m2):void 0;const tally=digest===void 0?void 0:this.reserveIdless(digest,item.channel??"");const copy2=tally?this.settleIdless(tally):void 0;const idless=copy2&&{digest,copy:copy2};if(this.enteringFocus)this.excludeFromFocus(item);if(this.dropUnsafe){this.excludeFromFocus(item);if(cm!=="muted"&&item.mentionsMe&&!item.historical){this.buffer(item,delivery,true,idless);this.emit("mention-wake",item)}else delivery.ack();return}if(cm==="muted"){this.evictedClassifications.delete(item.id);this.excludeFromFocus(item);this.protectDisposition(item.id,"drop");delivery.ack();return}const remembered=item.id===""?void 0:this.evictedClassifications.get(item.id);if(remembered)this.evictedClassifications.delete(item.id);const snapshottedPullOnly=item.historical||!item.mentionsMe&&(remembered?.pullOnly??cm==="quiet");if(cm==="quiet"||snapshottedPullOnly)this.excludeFromFocus(item);if(this._attention==="focus"&&item.mentionsMe&&!item.historical&&this.focusRecallUnsafeChannels.has(item.channel??"")){this.excludeFromFocus(item);this.buffer(item,delivery,true,idless);this.emit("mention-wake",item);return}if(cm!=="quiet"&&!snapshottedPullOnly&&this._attention==="focus"){this.protectDisposition(item.id,"drop");delivery.ack();if(item.id==="")this.buffer(item,{ack:()=>{}},true,idless);if(item.mentionsMe)this.emit("mention-wake",item);return}const automaticReply=this.config.channelRepliesPullOnly===true&&!!item.replyTo;const pullOnly=snapshottedPullOnly||!item.mentionsMe&&(automaticReply||this.classificationUnsafe);if(pullOnly)this.excludeFromFocus(item);this.buffer(item,delivery,pullOnly,idless);return}this.buffer(item,delivery,false)}buffer(item,delivery,pullOnly,idless){const pending={item,ack:delivery.ack,pullOnly,receivedAt:Date.now(),arrival:this.arrivals++};this.own(pending,delivery.redelivery);if(idless)pending.idless={tally:this.focusIdless,...idless};if(delivery.take){pending.take=delivery.take;this.gated.push(pending);if(this.gated.length>MAX_INBOX)this.gated.shift();this.emit("incoming",item);return}this.admit(pending);this.emit("incoming",item)}admit(pending){let at2=this.inbox.length;while(at2>0&&this.inbox[at2-1].arrival>pending.arrival)at2--;this.inbox.splice(at2,0,pending);if(this.inbox.length>MAX_INBOX){let excess=this.inbox.length-MAX_INBOX;while(excess-- >0){const evictable=p2=>!this.inFlightIds.has(p2.item.recvKey);let index2=this.inbox.findIndex(p2=>p2.pullOnly&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(p2=>p2.item.kind==="channel"&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(evictable);if(index2<0)break;const[evicted]=this.inbox.splice(index2,1);const sacrificingDirected=evicted.item.kind!=="channel";this.rememberEvicted(evicted);if(evicted.idless?.tally===this.focusIdless)this.unsettleIdless(evicted.idless.digest,evicted.idless.copy);if(!sacrificingDirected)evicted.ack()}}}rememberEvicted(p2){if(p2.item.kind!=="channel"||p2.item.mentionsMe||!p2.item.channel)return;if(p2.item.id==="")return;if(this.classificationUnsafe)return;if(!this.evictedClassifications.has(p2.item.id)&&this.evictedClassifications.size>=CLASSIFICATION_CAP){this.classificationUnsafe=true;this.evictedClassifications.clear();return}this.evictedClassifications.set(p2.item.id,{pullOnly:p2.pullOnly,channel:p2.item.channel})}excludeFromFocus(item){if(!this.enteringFocus&&this._attention!=="focus"||item.kind!=="channel"||!item.channel)return;if(item.id==="")return;if(!this.focusExcludedIds.has(item.id)&&this.focusExcludedIds.size>=FOCUS_EXCLUSION_CAP){const oldest=this.focusExcludedIds.entries().next().value;if(oldest){this.focusExcludedIds.delete(oldest[0]);this.focusRecallUnsafeChannels.add(oldest[1])}}this.focusExcludedIds.set(item.id,item.channel)}reserveIdless(digest,channel){if(this.focusIdlessEntries>=FOCUS_EXCLUSION_CAP){this.focusRecallUnsafeChannels.add(channel);return void 0}let tally=this.focusIdless.get(digest);if(!tally)this.focusIdless.set(digest,tally={channel,unbound:[],bound:new Set});this.focusIdlessEntries++;return tally}settleIdless(tally){const episode=this.focusIdless;const drops=this.transportDrops;const unbounded=()=>{if(episode===this.focusIdless)this.focusRecallUnsafeChannels.add(tally.channel)};const copy2={epoch:this.idlessEpoch,ready:Promise.resolve()};copy2.ready=this.ep.chatFrontier().then(frontier=>{if(drops===this.transportDrops)copy2.frontier=frontier;else unbounded()},unbounded);tally.unbound.push(copy2);return copy2}dropEmptyIdless(digest,tally){if(!tally.unbound.length&&!tally.bound.size)this.focusIdless.delete(digest)}unsettleIdless(digest,copy2){const tally=this.focusIdless.get(digest);if(!tally)return;if(tally.unbound.includes(copy2)){copy2.evicted=true;return}if(copy2.seq===void 0||!tally.bound.delete(copy2.seq))return;this.focusIdlessEntries--;this.dropEmptyIdless(digest,tally)}settleIdlessRead(channel,epoch,retained){for(const[digest,tally]of this.focusIdless){if(tally.channel!==channel)continue;const before=tally.unbound.length+tally.bound.size;tally.unbound=tally.unbound.filter(c3=>c3.epoch>=epoch);for(const seq of tally.bound)if(!retained.has(seq))tally.bound.delete(seq);this.focusIdlessEntries-=before-tally.unbound.length-tally.bound.size;this.dropEmptyIdless(digest,tally)}}async idlessReady(tallies,channel){const reads=[];for(const tally of tallies.values())if(tally.channel===channel)for(const c3 of tally.unbound)reads.push(c3.ready);await Promise.all(reads)}bindIdless(tally,epoch,free){let bound=Infinity;for(let i2=tally.unbound.length-1;i2>=0;i2--){const copy2=tally.unbound[i2];if(copy2.frontier===void 0)continue;bound=Math.min(bound,copy2.frontier);if(copy2.epoch>=epoch)continue;let at2=free.length-1;while(at2>=0&&free[at2]>bound)at2--;if(at2<0)continue;const[seq]=free.splice(at2,1);tally.unbound.splice(i2,1);if(copy2.evicted){this.focusIdlessEntries--;continue}copy2.seq=seq;tally.bound.add(seq)}}idlessUnsure(tally,epoch,seq){if(!tally||tally.bound.has(seq))return false;return tally.unbound.some(c3=>c3.epoch>=epoch&&c3.frontier!==void 0&&c3.frontier>=seq)}protectDisposition(id2,disposition){if(id2==="")return;const ids=disposition==="drop"?this.protectedDropIds:this.protectedPullOnlyIds;if((disposition==="drop"?this.dropUnsafe:this.classificationUnsafe)||ids.has(id2))return;if(ids.size>=PROTECTED_DISPOSITION_CAP){if(disposition==="drop")this.dropUnsafe=true;else this.classificationUnsafe=true;if(disposition!=="drop")ids.clear();return}ids.add(id2)}toInboxItem(m2,kind,historical){const text3=partsToText(m2.parts);return{id:m2.id,recvKey:m2.id!==""?m2.id:`${this.recvKeySecret}.${++this.recvKeySeq}`,ts:m2.ts,fromId:m2.from.id,fromName:m2.from.name,fromRole:m2.from.role,kind,channel:m2.channel,service:m2.toService,mentions:m2.mentions,mentionsMe:m2.mentions?.includes(this.config.name.toLowerCase())??false,historical,text:text3,replyTo:m2.replyTo,contextId:m2.contextId}}peekInbox(scope="all"){this.dropLapsedTakes();return this.inbox.filter(p2=>this.inScope(p2,scope)).map(p2=>p2.item)}inboxPreview(scope="all"){this.dropLapsedTakes();const askable=scope==="pull-only"?[]:this.gated.filter(p2=>this.mayOffer(p2));return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...askable].sort((a3,b3)=>a3.arrival-b3.arrival).map(p2=>p2.item)}async takeChosen(scope,choose,waitMs=TAKE_WAIT_MS){const chosen=choose(this.inboxPreview(scope));const keys=new Set(chosen.map(i2=>i2.recvKey));const asked=scope==="pull-only"?[]:this.gated.filter(p2=>keys.has(p2.item.recvKey)&&this.mayOffer(p2));for(const p2 of asked)p2.awaited=(p2.awaited??0)+1;const runs=asked.map(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops?p2.taking:this.startTake(p2));if(runs.length){let timer2;const waited=new Promise(resolve4=>{timer2=setTimeout(resolve4,waitMs);timer2.unref?.()});await Promise.race([Promise.allSettled(runs),waited]);clearTimeout(timer2)}for(const p2 of asked)p2.awaited=(p2.awaited??1)-1;const showable=new Map(this.peekInbox(scope).map(i2=>[i2.recvKey,i2]));const shown=chosen.flatMap(i2=>showable.get(i2.recvKey)??[]);for(const i2 of shown)handOver(i2);return shown}heldTakes(){const count=this.gated.filter(p2=>p2.taking===void 0).length;const waiting=this.gated.filter(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops).length;if(waiting)return{count:waiting+(this.heldTake?count:0),detail:"the delivery daemon has not answered the take yet"};return count&&this.heldTake?{count,detail:this.heldTake.detail}:{count}}mayAskTakes(){return this._transportConnected&&(!this.heldTake||Date.now()>=this.heldTake.retryAt)}mayOffer(p2){return p2.taking!==void 0&&this._transportConnected||this.mayAskTakes()}startTake(p2){const run=this.runTake(p2).catch(e3=>this.handleEndpointWarning(e3)).finally(()=>{if(p2.taking===run)p2.taking=void 0});p2.taking=run;p2.takingDrops=this.transportDrops;return run}async runTake(p2){const take=p2.take;if(!take)return;if(!this._transportConnected)return;if(!this.renewOwned(p2)){this.dropGated(p2);return}const count=p2.item.deliveryCount;const drops=this.transportDrops;const outcome=await take();if(!this.gated.includes(p2)||p2.take!==take)return;if(this.transportDrops!==drops){if(p2.takingDrops!==drops)return;if(this._transportConnected)this.emit("incoming",p2.item);return}if(outcome.taken){this.heldTake=void 0;const current=p2.item.deliveryCount===count&&p2.ownedUntil!==void 0&&Date.now()<p2.ownedUntil;if(!current)return;p2.takenCount=count;p2.takenOnce=true;this.gated.splice(this.gated.indexOf(p2),1);this.noteDirected(p2.item);this.admit(p2);if(!p2.awaited)this.emit("incoming",p2.item);return}if(outcome.drop){this.dropGated(p2);return}const first=this.heldTake?.reason!==outcome.reason;this.heldTake={reason:outcome.reason,detail:outcome.detail,retryAt:Date.now()+TAKE_RETRY_MS};this.takeRetry??=setTimeout(()=>{this.takeRetry=void 0;for(const held2 of this.gated)this.emit("incoming",held2.item)},TAKE_RETRY_MS);this.takeRetry.unref?.();if(first&&outcome.reason!=="daemon-busy")this.handleEndpointWarning(new Error(outcome.detail))}dropGated(p2){const i2=this.gated.indexOf(p2);if(i2>=0)this.gated.splice(i2,1)}regate(p2){const i2=this.inbox.indexOf(p2);if(i2<0)return;this.inbox.splice(i2,1);p2.takenCount=void 0;this.gated.push(p2)}dropLapsedTakes(){const now=Date.now();this.inbox=this.inbox.filter(p2=>!p2.take||this.inFlightIds.has(p2.item.recvKey)||p2.ownedUntil!==void 0&&now<p2.ownedUntil);this.gated=this.gated.filter(p2=>p2.taking!==void 0||p2.ownedUntil===void 0||now<p2.ownedUntil)}holdInFlight(ids){let fresh=0;for(const id2 of ids)if(!this.inFlightIds.has(id2))fresh++;if(this.inFlightIds.size+fresh>MAX_IN_FLIGHT)return false;for(const id2 of ids){this.inFlightIds.set(id2,(this.inFlightIds.get(id2)??0)+1);this.keepOwned(id2)}const held2=new Set(ids);for(const p2 of this.inbox)if(held2.has(p2.item.recvKey))handOver(p2.item);return true}isInFlight(id2){return this.inFlightIds.has(id2)}releaseInFlight(ids){for(const id2 of ids){const held2=this.inFlightIds.get(id2);if(held2===void 0)continue;if(held2<=1){this.inFlightIds.delete(id2);this.stopRenewal(id2);if(!this.lowerOnRelease.delete(id2))continue;const p2=this.inbox.find(pending=>pending.item.recvKey===id2);if(p2&&!p2.pullOnly){p2.pullOnly=true;this.excludeFromFocus(p2.item)}}else this.inFlightIds.set(id2,held2-1)}}own(p2,redelivery){p2.redelivery=redelivery;p2.ownedUntil=redelivery&&Date.now()+redelivery.ackWaitMs;p2.item.deliveryCount=redelivery?.deliveryCount;p2.item.firstDeliveryCount??=redelivery?.deliveryCount??1}keepOwned(key){if(this.renewals.has(key))return;const p2=this.inbox.find(x2=>x2.item.recvKey===key);if(!p2?.redelivery||!this.renewOwned(p2))return;const timer2=setInterval(()=>{const held2=this.inbox.find(x2=>x2.item.recvKey===key);if(!held2||!this.renewOwned(held2))this.stopRenewal(key)},p2.redelivery.ackWaitMs/2);timer2.unref?.();this.renewals.set(key,timer2)}stopRenewal(key){clearInterval(this.renewals.get(key));this.renewals.delete(key)}renewOwned(p2){if(!p2.redelivery||p2.ownedUntil===void 0||Date.now()>=p2.ownedUntil)return false;if(!this._transportConnected)return true;try{p2.redelivery.working()}catch{return false}p2.ownedUntil=Date.now()+p2.redelivery.ackWaitMs;return true}drainInbox(limit,scope="all"){this.dropLapsedTakes();const eligible=this.inbox.filter(p2=>this.inScope(p2,scope));const n2=limit&&limit>0?Math.min(limit,eligible.length):eligible.length;const selected=eligible.slice(0,n2);this.noteAutomaticHeadProgress(selected);const taken=new Set(selected);this.inbox=this.inbox.filter(p2=>!taken.has(p2));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();return items}drainInboxDeliveries(keys){const requested=[...new Set(keys)];const wanted=new Set(requested);const regated=this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&p2.takenOnce);const unshown=new Set(this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&!p2.takenOnce).map(p2=>p2.item.recvKey));if(regated.length)this.gated=this.gated.filter(p2=>!regated.includes(p2));const selected=[...this.inbox.filter(p2=>wanted.has(p2.item.recvKey)),...regated];this.noteAutomaticHeadProgress(selected);const present=new Set(selected.map(p2=>p2.item.recvKey));const pullOnly=new Map(selected.map(p2=>[p2.item.recvKey,p2.pullOnly]));for(const id2 of requested){const remembered=id2!==""?this.evictedClassifications.get(id2):void 0;if(!pullOnly.has(id2)&&remembered)pullOnly.set(id2,remembered.pullOnly)}this.inbox=this.inbox.filter(p2=>!present.has(p2.item.recvKey));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();for(const id2 of requested){if(!present.has(id2)&&!unshown.has(id2)&&!id2.startsWith(`${this.recvKeySecret}.`)){this.markHandled(id2,pullOnly.get(id2)??false);this.evictedClassifications.delete(id2)}}return{items,missingKeys:requested.filter(key=>!present.has(key)&&!unshown.has(key))}}commitPending(taken){for(const p2 of taken){p2.ack();this.markHandled(p2.item.id,p2.pullOnly);this.evictedClassifications.delete(p2.item.id)}return taken.map(p2=>p2.item)}inScope(p2,scope){return scope==="all"||(scope==="pull-only"?p2.pullOnly:!p2.pullOnly)}markHandled(id2,pullOnly=false){if(id2==="")return;if(pullOnly)this.protectDisposition(id2,"pull-only");this.handledIds.add(id2);if(this.handledIds.size>=4096){this.handledIdsPrev=this.handledIds;this.handledIds=new Set}}inboxKeys(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item.recvKey)}inboxPending(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item)}inboxCount(scope="all"){const held2=scope==="pull-only"?0:this.gated.length;return held2+(scope==="all"?this.inbox.length:this.inbox.filter(p2=>this.inScope(p2,scope)).length)}inboxSnapshot(limit=3){if(!Number.isInteger(limit)||limit<0||limit>8)throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);this.dropLapsedTakes();return{unread:this.inbox.length+this.gated.length,items:this.inbox.slice(0,limit).map(p2=>({...p2.item}))}}oldestAutomaticReceivedAt(){let oldest;for(const pending of[...this.inbox,...this.gated]){if(pending.pullOnly)continue;if(oldest===void 0||pending.receivedAt<oldest)oldest=pending.receivedAt}return oldest}get recallCursor(){return this._recallCursor}noteRecalled(mark){if(afterRecallMark(mark,this._recallCursor))this._recallCursor=mark}recallAhead(item){return item.ts>Date.now()}recallAheadSeen(id2){return this.aheadDelivered.has(id2)}recallAheadRoom(){return MAX_AHEAD-this.aheadDelivered.size}noteRecalledAhead(id2){if(this.aheadDelivered.size<MAX_AHEAD)this.aheadDelivered.add(id2)}resetRecallWalk(){this._recallCursor={ts:0,id:""};this.aheadDelivered.clear()}inboxScope(key){const pending=this.inbox.find(p2=>p2.item.recvKey===key)??this.gated.find(p2=>p2.item.recvKey===key);return pending?pending.pullOnly?"pull-only":"automatic":void 0}directedPendingCount(){return this.gated.length+this.inbox.filter(p2=>!p2.pullOnly&&(p2.item.kind!=="channel"||!p2.item.historical&&p2.item.mentionsMe)).length}inboxWake(skip){this.dropLapsedTakes();const held2=this.mayAskTakes()?this.gated.filter(p2=>(p2.taking===void 0||p2.takingDrops!==this.transportDrops)&&!skip?.(p2.item)).length:0;return held2+this.inbox.filter(p2=>{const it2=p2.item;if(p2.pullOnly||it2.kind==="channel"&&it2.historical||skip?.(it2))return false;if(it2.kind!=="channel"||it2.mentionsMe)return true;return this._attention==="open"}).length}get attention(){return this._attention}channelMode(channel){return channel?this.channelModes.get(channel):void 0}channelModeEntries(){return Object.fromEntries(this.channelModes)}async setChannelMode(channel,mode){if(!isConcreteChannel(channel))throw new Error(`"${channel}" must be a concrete channel (no wildcard) to set its attention`);if(!channelInAllow(this.config.allowSubscribe,channel))throw new Error(`"${channel}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]`);await this.inOrder(()=>{if(mode==="normal")this.channelModes.delete(channel);else{this.channelModes.set(channel,mode);this.lowerBuffered(channel,mode==="muted")}return this.ep.setChannelModes(this.channelModeEntries())})}lowerBuffered(channel,mentions,keep=[]){for(const p2 of this.inbox){if(p2.pullOnly||p2.item.kind!=="channel"||!p2.item.channel||!channelInAllow([channel],p2.item.channel))continue;if(channelInAllow(keep,p2.item.channel))continue;if(p2.item.mentionsMe&&!mentions)continue;if(this.inFlightIds.has(p2.item.recvKey)){this.lowerOnRelease.add(p2.item.recvKey);continue}p2.pullOnly=true;this.excludeFromFocus(p2.item)}}async setAttention(mode){await this.inOrder(async()=>{if(mode==="focus"){await this.requireConnected();this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.enteringFocus=this._attention!=="focus";try{this.focusSince=await this.ep.chatFrontier()}catch(error51){this.enteringFocus=false;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();throw error51}this.enteringFocus=false;this.resetRecallWalk()}else{this.enteringFocus=false;this.focusSince=void 0;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.resetRecallWalk()}this._attention=mode;await this.ep.setAttention(mode)})}async recallAmbient(underway=new Set){const run=this.recallLock.then(()=>this.recallAmbientOnce(underway));this.recallLock=run.catch(()=>{});return run}async recallAmbientOnce(underway){if(this._attention!=="focus"||this.focusSince===void 0)return{items:[],droppedChannels:[]};const items=[];const droppedChannels=[];for(const channel of this.ep.joinedChannels()){if(!isConcreteChannel(channel)){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const tallies=this.focusIdless;let epoch=0;let read;for(let attempt=1;attempt<=IDLESS_READS;attempt++){epoch=++this.idlessEpoch;await this.idlessReady(tallies,channel);read=await this.ep.recallChannel(channel,this.focusSince);if(read.unanswered)break;await this.idlessReady(tallies,channel);const unsure=read.messages.some((m2,i2)=>m2.id===""&&this.idlessUnsure(tallies.get(idlessDigest(m2)),epoch,read.seqs[i2]));if(!unsure)break}const{messages,seqs,dropped,unanswered}=read;if(unanswered){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const retained=new Set;const digests=[];const free=new Map;for(const[i2,m2]of messages.entries()){if(m2.id!==""||tallies!==this.focusIdless)continue;retained.add(seqs[i2]);const digest=digests[i2]=idlessDigest(m2);if(tallies.get(digest)?.bound.has(seqs[i2]))continue;const list=free.get(digest);if(list)list.push(seqs[i2]);else free.set(digest,[seqs[i2]])}for(const[digest,list]of free){const tally=tallies.get(digest);if(tally)this.bindIdless(tally,epoch,list)}let incomplete=dropped;for(const[i2,m2]of messages.entries()){if(m2.id!==""){if(underway.has(m2.id)||!this.focusExcludedIds.has(m2.id))items.push(this.toInboxItem(m2,"channel",true));continue}if(tallies!==this.focusIdless)continue;const seq=seqs[i2];const digest=digests[i2];const tally=tallies.get(digest);if(tally?.bound.has(seq))continue;if(this.idlessUnsure(tally,epoch,seq)){incomplete=true;continue}const fresh=this.inbox.length<MAX_INBOX?this.reserveIdless(digest,channel):void 0;if(!fresh){incomplete=true;continue}const copy2={epoch,frontier:seq,ready:Promise.resolve(),seq};fresh.bound.add(seq);this.buffer(this.toInboxItem(m2,"channel",true),{ack:()=>{}},true,{digest,copy:copy2})}if(tallies===this.focusIdless)this.settleIdlessRead(channel,epoch,retained);if(incomplete)droppedChannels.push(channel)}items.sort((a3,b3)=>a3.ts-b3.ts);return{items,droppedChannels}}};var SPAWN_TIMEOUT_MS=4e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s3=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s3.trim()))}var EVENTS_META_KEY="ai.cotal.events";function buildMeta(config2,processCwd,eventsArmed){const meta3={...config2.meta??{}};if(config2.model)meta3.model=config2.model;if(config2.variant)meta3.variant=config2.variant;if(config2.connector)meta3.connector=config2.connector;meta3.host=hostname2();delete meta3["ai.cotal.manager.instance"];if(config2.managerInstanceId)meta3["ai.cotal.manager.instance"]=config2.managerInstanceId;meta3[EVENTS_META_KEY]=eventsArmed??eventPlaneArmed(config2)?"on":"off";if(processCwd)meta3.cwd=process.cwd();else delete meta3.cwd;return Object.keys(meta3).length?meta3:void 0}var MAX_CORRELATIONS=1024;var ENDPOINT_ERROR_LOG_WINDOW_MS=3e4;var MAX_ENDPOINT_NOTICES=16;var NAMED_SIMILAR=5;var MAX_SETTLED_TURNS=32;function settledTurnError(goalId,t2){if(t2.yielded!==void 0)return`turn "${goalId}" was already yielded ${t2.yielded} by this seat${t2.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t2.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}var MAX_DATE_MS=864e13;function isPendingTurn(t2){const r2=t2;if(typeof r2!=="object"||r2===null||typeof r2.goalId!=="string"||typeof r2.payload!=="string")return false;if(!Number.isSafeInteger(r2.acceptedAt)||r2.acceptedAt<0)return false;if(r2.once!==void 0&&r2.once!==true)return false;if(r2.deadlineAt===void 0)return r2.once===true;return Number.isSafeInteger(r2.deadlineAt)&&r2.deadlineAt>=1&&r2.deadlineAt<=MAX_DATE_MS}function onceSpawner(payload){try{const spawner=JSON.parse(payload).once?.spawner;return typeof spawner==="string"&&spawner.length>0?spawner:void 0}catch{return void 0}}function sleep(ms){return new Promise(r2=>setTimeout(r2,ms))}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p2){const escalation=renderEscalation(p2);if(escalation!=="")return escalation;const ask=p2.ask;if(ask===null||typeof ask!=="object")return"";const a3=ask;const entries=a3.schema!==null&&typeof a3.schema==="object"?Object.entries(a3.schema):[];const fields=entries.length===0?"any record":entries.map(([k2,v3])=>`${k2}: ${String(v3)}`).join(", ");const by=typeof a3.deadlineAt==="number"?`, by ${new Date(a3.deadlineAt).toISOString()}`:"";const refused3=typeof a3.refused==="string"?`
131
131
  Your last answer was refused: ${a3.refused}`:"";return`
132
132
  This turn is an ask: the run needs a record from you at step ${String(p2.step)} with fields ${fields} (attempt ${String(a3.attempt)} of ${String(a3.attempts)}${by}).${refused3}`+renderPauseAnswer(p2,"<json record>")}function renderPauseAnswer(p2,value){return`
133
133
  Answer through your native Cotal tools: call cotal_describe for endpoint "manager", then cotal_invoke with endpoint="manager", command="run-answer", self=true and args={"runId":${JSON.stringify(p2.run)},"stepKey":${JSON.stringify(p2.step)},"value":${value}}.
@@ -140,7 +140,7 @@ ${context}${ask}`});const text3=`\u{1F3AF} Cotal \u2014 a run handed you ${waiti
140
140
  ${blocks.join("\n")}
141
141
  (Do the work now with your own tools. ${asked?"An ask must be answered through its native route above before ending your host turn. ":""}For ordinary turns, ending your turn yields "done" automatically; call cotal_yield when blocked or handing off an ordinary turn.)`;return{text:text3,goalIds:waiting.map(t2=>t2.goalId)}}commitSurfacedTurns(goalIds){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return;for(const id2 of goalIds){const t2=this.activeTurns.get(id2);if(t2?.once!==void 0&&!confirmOnceHandoff(this.onceUid(),id2))continue;if(t2)t2.surfaced=true}}unsurfaceTurns(goalIds){for(const id2 of goalIds){const t2=this.activeTurns.get(id2);if(t2&&t2.once===void 0)t2.surfaced=false}}claimTurns(goalIds){return claimOnceHandoff(this.onceUid(),goalIds.filter(id2=>(this.activeTurns.get(id2)??this.settledTurns.get(id2))?.once!==void 0))}releaseTurns(goalIds){for(const id2 of goalIds){if(this.activeTurns.get(id2)?.once===void 0)continue;if(sealOnceHandoff(this.onceUid(),id2))void this.reportUnconfirmed(id2)}}noteTurnsDispatched(goalIds){for(const id2 of goalIds)if(this.activeTurns.get(id2)?.once!==void 0)stopOnceHandoffTimer(this.onceUid(),id2)}boundOnceClaim(goalId){const timer2=setTimeout(()=>{if(!this.activeTurns.has(goalId)||onceHandoffState(this.onceUid(),goalId)!=="pending")return;this.log(`once task ${goalId}: pulled ${ONCE_HANDOFF_MS}ms ago and never handed to the session; reporting it unconfirmed`);if(this.claimTurns([goalId]))this.releaseTurns([goalId])},ONCE_HANDOFF_MS);timer2.unref?.()}offerable(t2){return t2.once===void 0||onceHandoffState(this.onceUid(),t2.goalId)==="pending"}onceUid(){return this.config.lifecycleUid??this.config.name}async reportUnconfirmed(goalId){const until=Date.now()+ONCE_HANDOFF_MS;let delay2=1e3;let exitTried=false;for(;;){const r2=await this.managerInvoke("turn-unconfirmed",{goalId},{target:{mode:"self"}}).catch(e3=>({ok:false,error:e3.message,code:void 0}));const transient=!r2.ok&&(r2.code===void 0||r2.code==="unavailable"||r2.code==="deadline-exceeded");if(!transient){this.log(`once task ${goalId}: its handoff was not confirmed; reported to the manager (${r2.ok?"the task failed":r2.error??"refused"})`);return}if(!exitTried&&Date.now()+delay2>until){exitTried=true;this.log(`once task ${goalId}: its handoff was not confirmed and the manager could not be told; ending this seat so its exit settles the task`);if(await exitOnceSeat())return;this.log(`once task ${goalId}: this seat cannot end itself; reporting until a manager answers`)}if(this._stopping)return;await new Promise(resolve4=>setTimeout(resolve4,delay2));delay2=Math.min(delay2*2,exitTried?6e4:1e4)}}async yieldTurn(status2,opts={}){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return{ok:false,error:"this personal connection has no valid workflow turn participation lease; opt in or renew it first"};try{await this.requireConnected()}catch(error51){throw new Error(`${error51.message}. The yield was not sent.`,{cause:error51})}const t2=opts.turn!==void 0?this.activeTurns.get(opts.turn):[...this.activeTurns.values()].filter(x2=>x2.surfaced).sort((a3,b3)=>a3.acceptedAt-b3.acceptedAt)[0];if(!t2){const id2=opts.turn??[...this.settledTurns.keys()].at(-1);const settled=id2===void 0?void 0:this.settledTurns.get(id2);if(id2!==void 0&&settled!==void 0)return{ok:false,error:settledTurnError(id2,settled)};return{ok:false,error:opts.turn!==void 0?`no active turn "${opts.turn}" on this seat`:"no turn is active \u2014 nothing to yield"}}if(!t2.surfaced)return{ok:false,error:`turn "${t2.goalId}" has not been surfaced into this session yet; nothing was seen, so nothing can be yielded for it`};if(status2==="handoff"&&(opts.to===void 0||opts.to.length===0))return{ok:false,error:"a handoff yield names its addressee (to)"};const r2=await this.managerInvoke("turn-yield",{goalId:t2.goalId,status:status2,to:opts.to,note:opts.note},{target:{mode:"self"}});if(!r2.ok)return r2;this.yieldedSincePull.add(t2.goalId);if(r2.data?.state!=="succeeded"){this.settleTurn(t2);return{ok:false,error:settledTurnError(t2.goalId,t2)}}this.activeTurns.delete(t2.goalId);this.rememberSettled(t2.goalId,{yielded:status2});return r2}settleTurn(t2){if(t2.once!==void 0)endOnceHandoff(this.onceUid(),t2.goalId);this.activeTurns.delete(t2.goalId);this.rememberSettled(t2.goalId,{...t2.deadlineAt!==void 0?{deadlineAt:t2.deadlineAt}:{},...t2.once!==void 0?{once:true}:{}})}rememberSettled(goalId,settled){this.settledTurns.delete(goalId);this.settledTurns.set(goalId,settled);if(this.settledTurns.size>MAX_SETTLED_TURNS)this.settledTurns.delete(this.settledTurns.keys().next().value)}async purgeHistory(opts){await this.requireConnected();const args={includeDms:opts?.includeDms??false};return this.managerInvoke("purge",args)}async definePersona(def){await this.requireConnected();const pin=this.managerPin(def.instance??this.openManagerInstance());if("error"in pin)return pin.error;if(def.announce!==void 0){if(def.announce.trim()==="")throw new Error("announce: empty channel \u2014 omit it to define silently, or name a concrete channel");try{assertValidChannel(def.announce)}catch(e3){throw new Error(`announce: ${e3?.message??String(e3)}`)}if(!isConcreteChannel(def.announce))throw new Error(`announce: "${def.announce}" is a wildcard \u2014 announce to one concrete channel`)}const args={name:def.name,model:def.model,persona:def.prompt,role:def.role,agent:def.agent,subscribe:def.subscribe,allowSubscribe:def.allowSubscribe,allowPublish:def.allowPublish,capabilities:def.capabilities,endpoints:def.endpoints};const reply=await this.managerInvoke("define-persona",args,pin);if(!reply.ok&&reply.outcome!=="not-executed"&&(reply.outcome==="unknown"||reply.code==="deadline-exceeded"&&reply.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.command==="define-persona")))return{...reply,definitionOutcome:"unknown"};if(!reply.ok||!def.announce)return reply;try{await this.send(`defined persona \`${def.name}\` \u2014 in this workspace's persona catalog, spawnable with cotal_spawn`,def.announce)}catch(e3){return{...reply,announceError:e3?.message??String(e3),announceOutcome:isPublishPermissionDenied(e3)?"denied":"unknown"}}return reply}async listPersonas(instance){await this.requireConnected();const pin=this.managerPin(instance??this.openManagerInstance());if("error"in pin)return pin.error;return this.managerInvoke("list-personas",void 0,pin)}async showPersona(name2,instance){await this.requireConnected();const pin=this.managerPin(instance??this.openManagerInstance());if("error"in pin)return pin.error;return this.managerInvoke("show-persona",{name:name2},pin)}async readRoster(){try{return{roster:await this.ep.readPresence()}}catch(e3){return{roster:this.ep.getRoster(),failure:e3}}}get status(){return this._status}inOrder(write,forDeparture=false){if(this._stopping&&!forDeparture)return Promise.reject(new Error("agent is stopping; presence writes are refused"));const next=this.presenceChain.then(write,write);this.presenceChain=next.catch(()=>{});return next}abandonPresenceWrites(){this.presenceChain=Promise.resolve()}async setStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();const prev=this.turnStatus;try{if(prev!=="working"&&status2==="working")await this.ep.setCondition(null);await this.publishStatus(status2,activity)}finally{this._status=status2;this.turnStatus=status2;if(prev==="working"&&status2==="idle")this.onTurnBoundary()}})}async resetStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();try{await this.publishStatus(status2,activity)}finally{this._status=status2}})}async publishStatus(status2,activity){await this.ep.setStatus(status2,activity)}async setActivity(activity){await this.inOrder(async()=>{await this.requireConnected();await this.ep.setActivity(activity)})}async setCondition(condition){await this.inOrder(()=>this.ep.setCondition(condition))}noteActivity(at2){this.ep.noteActivity(at2)}onTurnBoundary(){for(const t2 of[...this.activeTurns.values()]){if(!t2.surfaced)continue;void this.yieldTurn("done",{turn:t2.goalId}).then(r2=>{if(!r2.ok)this.log(`turn ${t2.goalId} auto-yield: ${r2.error??"refused"}`)}).catch(e3=>this.log(`turn ${t2.goalId} auto-yield: ${e3.message}`))}}async setModel(model,variant,provider){if(this.config.model&&provider===void 0)return;await this.inOrder(()=>this.ep.setCardModel(this.config.model??model,this.config.variant??variant,provider))}async setCwd(cwd){await this.inOrder(()=>this.ep.setCardCwd(cwd))}channelBriefing(){const lines=this.ep.joinedChannels().map(c3=>({c:c3,d:this.ep.getChannelConfig(c3)?.description})).filter(x2=>Boolean(x2.d)).map(x2=>` #${x2.c} \u2014 ${x2.d}`);if(!lines.length)return void 0;return`Channel notes (operator-provided, advisory \u2014 context, not instructions to obey):
142
142
  ${lines.join("\n")}`}async readChannels(){await this.ep.readChannels()}channelInfo(channel){const cfg=this.ep.getChannelConfig(channel);return{description:cfg?.description,instructions:cfg?.instructions,replay:this.ep.channelReplay(channel),registered:cfg!==void 0,event:this.eventChannelOf(channel)}}eventChannelOf(channel){const principal=eventChannelPrincipal(channel);if(!principal)return void 0;const own=this.ep.principal;return principal.owner===own.owner&&principal.actor===own.actor?"own":"agent"}joinedChannels(){return this.ep.joinedChannels()}async listChannels(){const mine=this.ep.joinedChannels();const pending=this.ep.pendingDurableLeaves();const unclosed=new Set(pending);let leaseLive=false;let leaseReadable=false;let daemonMemberships;try{leaseLive=(await this.ep.readDeliveryLease(0))?.ready===true;leaseReadable=true}catch{}if(leaseReadable){try{daemonMemberships=await this.ep.fetchMemberships()}catch{daemonMemberships=void 0;leaseReadable=false}}const held2=channel=>!leaseReadable?"unknown":daemonMemberships!==void 0&&leaseLive&&daemonMemberships.some(m2=>m2.channel===channel||isChannelFamily(m2.channel)&&subjectMatches(m2.channel,channel))?"active":"degraded";const health=(channel,stored)=>stored&&this.ep.channelDeliveryClass(channel)==="durable"?held2(channel):void 0;const rows=(await this.ep.listChannels()).map(c3=>{const joined=mine.some(p2=>subjectMatches(p2,c3.channel));const stored=mine.some(p2=>p2===c3.channel||isChannelFamily(p2)&&subjectMatches(p2,c3.channel));return{channel:c3.channel,description:c3.config?.description,replay:this.ep.channelReplay(c3.channel),joined,durableUnclosed:unclosed.has(c3.channel),deliveryHealth:health(c3.channel,stored),messages:c3.messages,mode:this.channelMode(c3.channel)??"normal",event:this.eventChannelOf(c3.channel)}});for(const pattern of mine){if(isConcreteChannel(pattern))continue;const family=isChannelFamily(pattern);rows.push({channel:pattern,replay:this.ep.channelReplay(pattern),joined:true,durableUnclosed:unclosed.has(pattern),deliveryHealth:family?held2(pattern):void 0,messages:0,mode:"normal",follow:family?"family":"live"})}const present=new Set(rows.map(r2=>r2.channel));for(const ch of pending){if(present.has(ch))continue;rows.push({channel:ch,description:void 0,replay:this.ep.channelReplay(ch),joined:false,durableUnclosed:true,deliveryHealth:void 0,messages:0,mode:this.channelMode(ch)??"normal",event:this.eventChannelOf(ch),...isChannelFamily(ch)?{follow:"family"}:{}})}return rows}async joinChannel(channel){await this.requireConnected();return this.ep.joinChannel(channel)}async leaveChannel(channel){await this.requireConnected();const legacyDiscoveryMessage=isLocalServer(this.config.servers)?void 0:"this space's host runs an older delivery service, so this durable leave was not applied and the channel stays joined; the host must update the delivery service";const result=await this.ep.leaveChannel(channel,legacyDiscoveryMessage);if(result.left)this.inboxState.lowerBuffered(channel,false,this.joinedChannels());return result}async requireConnected(){return this.whenConnected(CONNECT_GRACE_MS)}async whenConnected(timeoutMs=CONNECT_GRACE_MS){if(this._connected)return;this.ep.retryNow();if(!await this.awaitConnection(timeoutMs))throw new Error(this.notConnectedMessage())}awaitConnection(timeoutMs){return new Promise(resolve4=>{let settled=false;const finish=ok3=>{if(settled)return;settled=true;clearTimeout(timer2);this.ep.off("connection",onConnection);resolve4(ok3)};const onConnection=e3=>{if(e3.connected)finish(true)};const timer2=setTimeout(()=>finish(false),Math.max(1,timeoutMs));this.ep.on("connection",onConnection);if(this._connected)finish(true)})}notConnectedMessage(){const issue2=this.connectionIssue;if(issue2)return`not connected to the mesh at ${this.config.servers}: ${issue2}`;const remedy=isLocalServer(this.config.servers)?"is it running? (`cotal up`)":"it did not become reachable \u2014 check that the mesh is up and that this machine can reach it.";return`not connected to the mesh at ${this.config.servers} \u2014 ${remedy}`}handleEndpointError(error51){if(!this._connected&&!this._stopping)this.lastConnectionError=error51.message;this.logEndpointNotice("error",error51)}handleEndpointWarning(error51){if(error51 instanceof DmDurableMissingError&&!this._connected&&!this._stopping)this.lastConnectionError=missingInboxIssue(error51);this.logEndpointNotice("warning",error51)}logEndpointNotice(kind,error51){const now=Date.now();const fingerprint=error51.message.replace(/oc_[A-Za-z0-9]+_\d+/g,"oc_*");const prior=this.endpointNoticeLog.get(fingerprint);if(prior&&now-prior.lastLoggedAt<ENDPOINT_ERROR_LOG_WINDOW_MS){prior.suppressed++;return}const suffix=prior?.suppressed?` (${prior.suppressed} repeats suppressed)`:"";this.endpointNoticeLog.set(fingerprint,{lastLoggedAt:now,suppressed:0});if(this.endpointNoticeLog.size>MAX_ENDPOINT_NOTICES)this.endpointNoticeLog.delete(this.endpointNoticeLog.keys().next().value);this.log(`endpoint ${kind}: ${error51.message}${suffix}`)}log(msg){process.stderr.write(`[cotal-connector] ${msg}
143
- `)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function missingInboxIssue(e3){return`this session's direct-message inbox is missing on the broker, and on an authenticated mesh only a new launch creates one, so reconnecting cannot restore it. Restart this session, or respawn it if a manager launched it. Missing durable "${e3.durable}" on stream "${e3.stream}". Retries continue in case a broker restore brings it back.`}function closeChannelNames(channel,known){const out=[];for(const name2 of known){if(name2!==channel&&editDistanceAtMostOne(channel,name2))out.push(name2)}out.sort((a3,b3)=>a3.localeCompare(b3));return out.slice(0,3)}function editDistanceAtMostOne(a3,b3){if(a3===b3)return true;const da=a3.length-b3.length;if(da>1||da<-1)return false;let i2=0;let j2=0;let skipped=false;while(i2<a3.length&&j2<b3.length){if(a3[i2]===b3[j2]){i2++;j2++;continue}if(skipped)return false;skipped=true;if(a3.length>b3.length)i2++;else if(b3.length>a3.length)j2++;else{i2++;j2++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s3){const b3=new _AguiBrackets;b3.run=s3.run;for(const id2 of s3.text)b3.text.add(id2);for(const id2 of s3.reasoning)b3.reasoning.add(id2);for(const id2 of s3.tools)b3.tools.add(id2);return b3}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e3=event;const t2=e3.type;if(t2===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e3.runId)}" while run "${this.run}" is still open`);this.run=String(e3.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t2} emitted outside an open run`);if(t2===AGUI_EVENT_TYPE.RUN_FINISHED||t2===AGUI_EVENT_TYPE.RUN_ERROR){if(t2===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e3.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e3.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t2} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t2){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e3.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e3.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e3.name)))throw new AguiVocabularyError(`CUSTOM "${String(e3.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e3.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e3);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e3.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t2} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t2){if(set3.has(id2))throw new AguiVocabularyError(`${t2} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t2){if(!set3.has(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}closeId(set3,id2,t2){if(!set3.delete(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f2=part;if(f2.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f2.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f2[field]!=="string"||f2[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f2.seq)||f2.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f2.seq??null)}`);if(!Array.isArray(f2.events)||f2.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f2.events.forEach((e3,i2)=>{if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`frame events[${i2}] is not an object`);const t2=e3.type;if(typeof t2!=="string"||!known.has(t2))throw new AguiVocabularyError(`frame events[${i2}] carries an unrecognised type ${JSON.stringify(t2??null)}. A renderer must refuse an event it cannot display rather than skip it: a skipped event is a hole in a transcript that still looks complete.`)});return part}function runStarted(o3){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function assertInterrupts(list){if(!Array.isArray(list)||list.length===0)throw new AguiVocabularyError("outcome.interrupts must be a non-empty array when the outcome is an interrupt");for(const[i2,entry]of list.entries()){const e3=entry;if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`outcome.interrupts[${i2}] is not an object`);if(typeof e3.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].id must be a string`);if(typeof e3.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].reason must be a string`)}}function runFinished(o3){if(o3.outcome?.type==="interrupt")assertInterrupts(o3.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.outcome?{outcome:o3.outcome}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function runError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o3.message,timestamp:o3.timestamp,...o3.code?{code:o3.code}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageStart(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o3.messageId,timestamp:o3.timestamp,...o3.role?{role:o3.role}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageContent(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageEnd(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallStart(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o3.toolCallId,toolCallName:o3.toolCallName,timestamp:o3.timestamp,...o3.parentMessageId?{parentMessageId:o3.parentMessageId}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallArgs(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,toolCallId:o3.toolCallId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallEnd(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o3.toolCallId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallResult(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,messageId:o3.messageId,toolCallId:o3.toolCallId,content:o3.content,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageStart(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_START,messageId:o3.messageId,role:"reasoning",timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageContent(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageEnd(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v3=value;if(typeof v3.toolCallId!=="string")return"value";if(typeof v3.isError!=="boolean")return"value";return void 0}function toolResultMarkerDefect(e3){if("rawEvent"in e3)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e3.value);if(defect===void 0)return void 0;return defect==="value"?"value is not { toolCallId: string, isError: boolean }":`${defect} is not a key the marker's value carries`}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v3=value;return{toolCallId:v3.toolCallId,isError:v3.isError}}function extraPropertyPath(part){for(const key of Object.keys(part)){if(!KNOWN_FRAME_KEYS.has(key))return key}const events=part.events;if(!Array.isArray(events))return void 0;for(let i2=0;i2<events.length;i2++){const e3=events[i2];if(typeof e3!=="object"||e3===null)continue;const t2=e3.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t2);if(!allowed)return`events[${i2}]`;for(const key of Object.keys(e3)){if(!allowed.has(key))return`events[${i2}].${key}`}if(t2===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT){if("rawEvent"in e3)return`events[${i2}].rawEvent`;const defect=toolResultValueDefect(e3.value);if(defect!==void 0)return`events[${i2}].${defect}`}}return void 0}function isForbiddenEgressEventType(type){return typeof type==="string"&&EGRESS_FORBIDDEN_TYPES.has(type)}var RUN_ERROR_EGRESS_MESSAGE="run failed";function egressRunError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function isEgressRunError(e3){return e3.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e3)&&!("rawEvent"in e3)}function isToolResultMarker(e3){return e3.type===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e3){if(!("rawEvent"in e3))return e3;const{rawEvent:_dropped,...rest}=e3;return rest}function applyAguiEgressPolicy(events){return events.filter(e3=>!isForbiddenEgressEventType(e3.type)).map(e3=>e3.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e3):isToolResultMarker(e3)?egressToolResultMarker(e3):e3)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e3 of frame.events){if(isForbiddenEgressEventType(e3.type))return"forbidden-kind"}for(const e3 of frame.events){if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e3))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID13}from"node:crypto";import{dirname as dirname9,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text3=>({text:text3});var err=text3=>({text:text3,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers4={"content-type":"application/json"};const body={...input};if(options.key){headers4.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers4,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e3){return err(`Couldn't reach the feedback intake at ${url2}: ${e3.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.171.0";function loadDocsMetadata(){return{"version":"0.171.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":"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":"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-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, 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 with the shell installer or npm."},{"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, 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":"Participant connections can read retained tool payloads for their own owner and for foreign event channels granted by full name."},{"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=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1335370||createHash10("sha256").update(packed).digest("hex")!=="3b27d91c1efaa8c995c55497cf112505ad20ffdd32d7312a23a121d4a5b2bbb2")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9543],[9543,32236],[32236,36760],[36760,41141],[41141,44869],[44869,51998],[51998,56102],[56102,65899],[65899,70051],[70051,76850],[76850,79168],[79168,83179],[83179,117854],[117854,134765],[134765,150925],[150925,169861],[169861,188438],[188438,203892],[203892,220008],[220008,248383],[248383,254113],[254113,265354],[265354,286918],[286918,291817],[291817,333540],[333540,344177],[344177,378328],[378328,396377],[396377,422421],[422421,454546],[454546,469475],[469475,471429],[471429,480786],[480786,498647],[498647,507057],[507057,511361],[511361,514884],[514884,518327],[518327,519981],[519981,522325],[522325,525173],[525173,533607],[533607,535581],[535581,539319],[539319,552081],[552081,561437],[561437,565187],[565187,572690],[572690,577822],[577822,580826],[580826,591533],[591533,594510],[594510,603230],[603230,606220],[606220,613378],[613378,628087],[628087,641170],[641170,648820],[648820,656628],[656628,659977],[659977,662926],[662926,670483],[670483,674199],[674199,676409],[676409,679871],[679871,683288],[683288,684402],[684402,686151],[686151,689814],[689814,694972],[694972,701657],[701657,712167],[712167,725483],[725483,728750],[728750,742589],[742589,747976],[747976,752285],[752285,754802],[754802,759844],[759844,774090],[774090,780952],[780952,788921],[788921,789738],[789738,794586],[794586,800679],[800679,804361],[804361,808602],[808602,813773],[813773,819354],[819354,822776],[822776,826529],[826529,831694],[831694,835337],[835337,849632],[849632,852488],[852488,855171],[855171,857838],[857838,860508],[860508,864528],[864528,869592],[869592,883548],[883548,892407],[892407,965323],[965323,968614],[968614,969962],[969962,977705],[977705,986803],[986803,997831],[997831,1006642],[1006642,1011825],[1011825,1290431],[1290431,1329934],[1329934,1335370]];var sourceLengths=[4844,4048,13962,90847,12579,10741,38583,18738,9941,85121,37758,17182,5187,9872,94955,45725,45454,54029,51726,44786,44139,81286,14399,30108,62298,11146,124425,29580,103668,51279,78509,99287,41222,8265,23413,48356,22989,10590,8346,8195,3466,5381,6543,22188,4726,8905,34074,23523,9352,48175,12971,7373,28193,7140,22854,6860,18419,39073,34913,19825,19214,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,12695,16240,26828,34218,8172,37640,12378,10647,8235,13306,98213,17095,19868,1638,11237,15872,8719,10286,12927,14071,7511,9451,12695,8527,38435,6616,6405,6095,6534,9711,12679,40667,23081,214696,7461,2878,19155,23391,28608,21160,12616,811071,111760,22568];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=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==672296||createHash10("sha256").update(packed).digest("hex")!=="073d0dc922a550181b763b7d73e00cce9cf2f65769f24161e4501cfee38f9f20")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN2);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 page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.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
+ `)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function missingInboxIssue(e3){return`this session's direct-message inbox is missing on the broker, and on an authenticated mesh only a new launch creates one, so reconnecting cannot restore it. Restart this session, or respawn it if a manager launched it. Missing durable "${e3.durable}" on stream "${e3.stream}". Retries continue in case a broker restore brings it back.`}function closeChannelNames(channel,known){const out=[];for(const name2 of known){if(name2!==channel&&editDistanceAtMostOne(channel,name2))out.push(name2)}out.sort((a3,b3)=>a3.localeCompare(b3));return out.slice(0,3)}function editDistanceAtMostOne(a3,b3){if(a3===b3)return true;const da=a3.length-b3.length;if(da>1||da<-1)return false;let i2=0;let j2=0;let skipped=false;while(i2<a3.length&&j2<b3.length){if(a3[i2]===b3[j2]){i2++;j2++;continue}if(skipped)return false;skipped=true;if(a3.length>b3.length)i2++;else if(b3.length>a3.length)j2++;else{i2++;j2++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s3){const b3=new _AguiBrackets;b3.run=s3.run;for(const id2 of s3.text)b3.text.add(id2);for(const id2 of s3.reasoning)b3.reasoning.add(id2);for(const id2 of s3.tools)b3.tools.add(id2);return b3}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e3=event;const t2=e3.type;if(t2===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e3.runId)}" while run "${this.run}" is still open`);this.run=String(e3.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t2} emitted outside an open run`);if(t2===AGUI_EVENT_TYPE.RUN_FINISHED||t2===AGUI_EVENT_TYPE.RUN_ERROR){if(t2===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e3.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e3.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t2} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t2){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e3.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e3.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e3.name)))throw new AguiVocabularyError(`CUSTOM "${String(e3.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e3.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e3);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e3.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t2} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t2){if(set3.has(id2))throw new AguiVocabularyError(`${t2} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t2){if(!set3.has(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}closeId(set3,id2,t2){if(!set3.delete(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f2=part;if(f2.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f2.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f2[field]!=="string"||f2[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f2.seq)||f2.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f2.seq??null)}`);if(!Array.isArray(f2.events)||f2.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f2.events.forEach((e3,i2)=>{if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`frame events[${i2}] is not an object`);const t2=e3.type;if(typeof t2!=="string"||!known.has(t2))throw new AguiVocabularyError(`frame events[${i2}] carries an unrecognised type ${JSON.stringify(t2??null)}. A renderer must refuse an event it cannot display rather than skip it: a skipped event is a hole in a transcript that still looks complete.`)});return part}function runStarted(o3){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function assertInterrupts(list){if(!Array.isArray(list)||list.length===0)throw new AguiVocabularyError("outcome.interrupts must be a non-empty array when the outcome is an interrupt");for(const[i2,entry]of list.entries()){const e3=entry;if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`outcome.interrupts[${i2}] is not an object`);if(typeof e3.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].id must be a string`);if(typeof e3.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].reason must be a string`)}}function runFinished(o3){if(o3.outcome?.type==="interrupt")assertInterrupts(o3.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.outcome?{outcome:o3.outcome}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function runError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o3.message,timestamp:o3.timestamp,...o3.code?{code:o3.code}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageStart(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o3.messageId,timestamp:o3.timestamp,...o3.role?{role:o3.role}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageContent(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageEnd(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallStart(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o3.toolCallId,toolCallName:o3.toolCallName,timestamp:o3.timestamp,...o3.parentMessageId?{parentMessageId:o3.parentMessageId}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallArgs(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,toolCallId:o3.toolCallId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallEnd(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o3.toolCallId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallResult(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,messageId:o3.messageId,toolCallId:o3.toolCallId,content:o3.content,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageStart(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_START,messageId:o3.messageId,role:"reasoning",timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageContent(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageEnd(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v3=value;if(typeof v3.toolCallId!=="string")return"value";if(typeof v3.isError!=="boolean")return"value";return void 0}function toolResultMarkerDefect(e3){if("rawEvent"in e3)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e3.value);if(defect===void 0)return void 0;return defect==="value"?"value is not { toolCallId: string, isError: boolean }":`${defect} is not a key the marker's value carries`}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v3=value;return{toolCallId:v3.toolCallId,isError:v3.isError}}function extraPropertyPath(part){for(const key of Object.keys(part)){if(!KNOWN_FRAME_KEYS.has(key))return key}const events=part.events;if(!Array.isArray(events))return void 0;for(let i2=0;i2<events.length;i2++){const e3=events[i2];if(typeof e3!=="object"||e3===null)continue;const t2=e3.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t2);if(!allowed)return`events[${i2}]`;for(const key of Object.keys(e3)){if(!allowed.has(key))return`events[${i2}].${key}`}if(t2===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT){if("rawEvent"in e3)return`events[${i2}].rawEvent`;const defect=toolResultValueDefect(e3.value);if(defect!==void 0)return`events[${i2}].${defect}`}}return void 0}function isForbiddenEgressEventType(type){return typeof type==="string"&&EGRESS_FORBIDDEN_TYPES.has(type)}var RUN_ERROR_EGRESS_MESSAGE="run failed";function egressRunError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function isEgressRunError(e3){return e3.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e3)&&!("rawEvent"in e3)}function isToolResultMarker(e3){return e3.type===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e3){if(!("rawEvent"in e3))return e3;const{rawEvent:_dropped,...rest}=e3;return rest}function applyAguiEgressPolicy(events){return events.filter(e3=>!isForbiddenEgressEventType(e3.type)).map(e3=>e3.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e3):isToolResultMarker(e3)?egressToolResultMarker(e3):e3)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e3 of frame.events){if(isForbiddenEgressEventType(e3.type))return"forbidden-kind"}for(const e3 of frame.events){if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e3))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID13}from"node:crypto";import{dirname as dirname9,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text3=>({text:text3});var err=text3=>({text:text3,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers4={"content-type":"application/json"};const body={...input};if(options.key){headers4.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers4,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e3){return err(`Couldn't reach the feedback intake at ${url2}: ${e3.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.171.1";function loadDocsMetadata(){return{"version":"0.171.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":"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":"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-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, 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 with the shell installer or npm."},{"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, 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":"Participant connections can read retained tool payloads for their own owner and for foreign event channels granted by full name."},{"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=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1335828||createHash10("sha256").update(packed).digest("hex")!=="b9806c25c302ad74063d04a0ba9d3183e5f545e006d0b824cece45f203bb08c7")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it for Cotal 0.171.1: 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,2205],[2205,4e3],[4e3,9543],[9543,32236],[32236,36760],[36760,41141],[41141,44869],[44869,51998],[51998,56102],[56102,65899],[65899,70051],[70051,76850],[76850,79168],[79168,83179],[83179,117997],[117997,134908],[134908,151068],[151068,170004],[170004,188581],[188581,204035],[204035,220151],[220151,248526],[248526,254256],[254256,265497],[265497,287104],[287104,292006],[292006,333729],[333729,344366],[344366,378517],[378517,396566],[396566,422610],[422610,454735],[454735,469664],[469664,471618],[471618,480975],[480975,498836],[498836,507246],[507246,511550],[511550,515073],[515073,518516],[518516,520170],[520170,522514],[522514,525362],[525362,533796],[533796,535770],[535770,539508],[539508,552270],[552270,561626],[561626,565376],[565376,572879],[572879,578011],[578011,581015],[581015,591722],[591722,594699],[594699,603419],[603419,606409],[606409,613567],[613567,628276],[628276,641359],[641359,649009],[649009,656817],[656817,660166],[660166,663115],[663115,670672],[670672,674388],[674388,676598],[676598,680060],[680060,683477],[683477,684591],[684591,686340],[686340,690003],[690003,695161],[695161,701846],[701846,712356],[712356,725672],[725672,729021],[729021,742860],[742860,748247],[748247,752556],[752556,755073],[755073,760115],[760115,774361],[774361,781223],[781223,789192],[789192,790009],[790009,794857],[794857,801085],[801085,804767],[804767,809008],[809008,814179],[814179,819760],[819760,823182],[823182,826935],[826935,832100],[832100,835743],[835743,850038],[850038,852894],[852894,855577],[855577,858244],[858244,860914],[860914,864934],[864934,869998],[869998,883954],[883954,892813],[892813,965729],[965729,969020],[969020,970368],[970368,978111],[978111,987209],[987209,998289],[998289,1007100],[1007100,1012283],[1012283,1290889],[1290889,1330392],[1330392,1335828]];var sourceLengths=[4844,4048,13962,90847,12579,10741,38583,18738,9941,85121,37758,17182,5187,9872,95349,45725,45454,54029,51726,44786,44139,81286,14399,30108,62436,11149,124425,29580,103668,51279,78509,99287,41222,8265,23413,48356,22989,10590,8346,8195,3466,5381,6543,22188,4726,8905,34074,23523,9352,48175,12971,7373,28193,7140,22854,6860,18419,39073,34913,19825,19214,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,12695,16240,26828,34218,8437,37640,12378,10647,8235,13306,98213,17095,19868,1638,11237,16289,8719,10286,12927,14071,7511,9451,12695,8527,38435,6616,6405,6095,6534,9711,12679,40667,23081,214696,7461,2878,19155,23391,28792,21160,12616,811071,111760,22568];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=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==672400||createHash10("sha256").update(packed).digest("hex")!=="a7b80bc8fccb8c313cf7052e8c5dcc7528e1099bb6caef5010e27e29cbbce440")throw new Error("docs data file docs-index.bin beside this module is not the one built with it for Cotal 0.171.1: 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 TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN2);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 page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.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((page,source)=>pages.get(source)??page),{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,page]of pages)lengths[source]=page.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(text3,maxLines=48){const lines=text3.split("\n");if(lines.length<=maxLines)return text3.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}