@cotal-ai/connector-jcode 0.133.9 → 0.133.10

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.
Binary file
Binary file
package/dist/host.js CHANGED
@@ -129,7 +129,7 @@ ${tail}`)}if(history.length){blocks.push(`\u{1F4DA} Cotal \u2014 ${history.lengt
129
129
  ${history.map(format).join("\n")}
130
130
  (This is replayed history, not new work. Do not act on or reply to these old requests unless the person explicitly asks.)`)}return blocks.join("\n\n")}function writeReply(sock,reply,awaitHandoff){return new Promise(resolve4=>{let settled=false;const done=ok3=>{if(settled)return;settled=true;resolve4(ok3)};sock.once("error",()=>done(false));sock.once("close",()=>done(false));if(!awaitHandoff){const stall=setTimeout(()=>done(false),LEGACY_WRITE_DEADLINE_MS);stall.unref?.();try{sock.end(JSON.stringify(reply)+"\n",(err3=>{clearTimeout(stall);done(!err3)}))}catch{clearTimeout(stall);done(false)}return}const deadline=setTimeout(()=>{sock.destroy();done(false)},HANDOFF_DEADLINE_MS);deadline.unref?.();let receipt="";sock.on("data",d=>{receipt+=d;if(!receipt.includes("\n"))return;clearTimeout(deadline);try{sock.end()}catch{}done(true)});try{sock.write(JSON.stringify(reply)+"\n",err3=>{if(!err3)return;clearTimeout(deadline);done(false)})}catch{clearTimeout(deadline);done(false)}})}function startControlServer(agent,endpoint,handle,opts={}){const{path:path4}=endpoint;const digest=createHash10("sha256").update(endpoint.token).digest();const server=createServer(sock=>{let buf="";let handled=false;sock.setEncoding("utf8");const deadline=setTimeout(()=>sock.destroy(),AUTH_DEADLINE_MS);deadline.unref?.();sock.on("close",()=>clearTimeout(deadline));sock.on("data",async d=>{if(handled)return;buf+=d;if(buf.length>MAX_FRAME_BYTES){sock.destroy();return}const nl=buf.indexOf("\n");if(nl<0)return;handled=true;clearTimeout(deadline);let frame={};try{frame=JSON.parse(buf.slice(0,nl)||"{}")}catch{}if(!tokenMatches(frame.token,digest)){sock.destroy();return}const op=frame.op;if(op==="shutdown"){try{sock.end(JSON.stringify({ok:true})+"\n")}catch{}opts.onShutdown?.();return}if(op==="session"){const sessionId=opts.onSession?.();try{sock.end(JSON.stringify(sessionId?{ok:true,sessionId}:{ok:false,error:"session not ready"})+"\n")}catch{}return}const ev=frame.event??{};const awaitHandoff=frame.handoff===true;const reply=await handle(agent,ev);const delivered=await writeReply(sock,reply,awaitHandoff);opts.onReply?.(ev,delivered)});sock.on("error",()=>{})});let bound=false;let retried=false;const emit=server.emit.bind(server);server.emit=(event,...args)=>{const error2=args[0];if(event!=="error"||bound||retried||process.platform==="win32"||path4.startsWith("\0")||error2?.code!=="EADDRINUSE")return emit(event,...args);retried=true;let original;try{original=lstatSync5(path4);if(!original.isSocket())return emit(event,...args)}catch(e){if(e.code!=="ENOENT")return emit(event,...args)}const probe=connect2(path4);let settled=false;const finish=stale=>{if(settled)return;settled=true;clearTimeout(deadline);probe.destroy();server.off("close",cancel);if(!stale){emit(event,...args);return}try{const current=lstatSync5(path4);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}unlinkSync4(path4)}catch(e){if(e.code!=="ENOENT"){emit("error",e);return}}server.listen(path4)};const cancel=()=>{settled=true;clearTimeout(deadline);probe.destroy()};const deadline=setTimeout(()=>finish(false),250);server.once("close",cancel);probe.once("connect",()=>finish(false));probe.once("error",e=>finish(e.code==="ECONNREFUSED"||e.code==="ENOENT"));return true};server.on("error",e=>{process.stderr.write(`[cotal-connector] control server error: ${e.message}
131
131
  `);if(opts.fatalBind&&!bound)process.exit(1)});server.listen(path4,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path4}
132
- `)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});async function submitFeedback(input,options={}){const url=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.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}try{const res=await fetch(url,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url}: ${e.message}`)}}import{execFileSync as execFileSync3}from"node:child_process";import{createHash as createHash11}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.133.9";function loadDocsMetadata(){return{"version":"0.133.9","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"Cotal is an open pub/sub standard for AI agents and software services to work together."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Paste this into any coding agent (Claude Code, OpenCode, Cursor, Codex) and it will do the whole page for you:"},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"Cotal is built as a thin waist: the normative wire contract (subjects, message schemas, presence/discovery, delivery semantics, the auth grammar) is the standard (SPEC), and everything else is a pl\u2026"},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"The tools are defined once, platform-neutrally, in @cotal-ai/connector-core and rendered onto each host's native tool API (an MCP server for Claude Code, Codex and Jcode, native plugin tools for Op\u2026"},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel permissions decide who can read, who can post, and what each agent tunes into at boot."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"Who can do what on a mesh, and how it is enforced."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"An agent's identity and persona live in one Markdown file instead of being passed flag-by-flag, the same shape Claude Code uses for subagents:"},{"slug":"api-reference","title":"API reference","kind":"Reference (informative)","category":"Reference","summary":"Cotal exposes a wire protocol, TypeScript libraries, CLI commands and agent tools."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP interface of the stock auth public listener: 11 paths and 12 operations."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Reference: describes the TypeScript reference implementation, not the wire contract.","category":"Reference","summary":"A connector teaches Cotal how to launch one agent harness (Claude Code, OpenCode, your own) as a mesh node."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"This page is the reading order for implementing a Cotal client in another language (Go, Python, Rust, or anything with a NATS client library) against the spec, without reimplementing the protocol."},{"slug":"cli","title":"`cotal` CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"cotal is the operator command line for the reference implementation: bring a mesh up, mint identities, launch agents, watch what they do, and tear it all down."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Four things configure a Cotal workstation: the config file (per-connector settings, notably which of your MCP servers get shared with spawned agents), your preferences (the defaults your own comman\u2026"},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"The Claude Code connector turns a real claude session into a Cotal mesh peer."},{"slug":"connect-codex","title":"Connect Codex (beta)","kind":"Guide (informative)","category":"Guide","summary":"OpenAI Codex joins a Cotal mesh as a lateral peer: the same cotal tool surface, the same message delivery and attention model as the other connectors, plus mid-turn steering: a directed peer messag\u2026"},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Hermes (Nous Research) joins a Cotal mesh as a lateral peer, with the same shared cotal tool surface and delivery model as the other connectors."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Jcode joins a Cotal mesh as a lateral peer."},{"slug":"connect-opencode","title":"Connect OpenCode (beta)","kind":"Guide (informative)","category":"Guide","summary":"OpenCode joins a Cotal mesh as a lateral peer, at parity with Claude Code: the same cotal tool surface, the same message delivery and attention model."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"@cotal-ai/pi is Cotal's first host-native framework adapter."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Every connector puts a real agent session on the mesh with the same cotal tools, presence, and delivery model (MCP tools)."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"Cotal once had a privileged control rail: a fixed set of named service tiers (self / manager / admin / delivery) on their own ctl."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP interface of the @cotal-ai/web reference implementation."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"The Quickstart gives you one agent. To run a specific team (your own channels, your own agents, and the channel access for each agent), describe it once in a cotal.yaml and launch it with a single\u2026"},{"slug":"delivery-daemon","title":"The delivery daemon (Plane-3)","kind":"Concept (informative)","category":"Concept","summary":"Live channel delivery is at-most-once: a message reaches only the peers subscribed at the moment it is published (SPEC \xA74)."},{"slug":"deploy","title":"Deploying agent teams","kind":"Guide (informative)","category":"Guide","summary":"The deploy/ tree runs a team of agents in an isolated container that dials out to an existing Cotal broker."},{"slug":"embedding","title":"Embedding Cotal","kind":"Guide (informative)","category":"Guide","summary":"The cotal binary in this repo is one composition root: an operator CLI."},{"slug":"examples","title":"Examples","kind":"Guide (informative)","category":"Guide","summary":"Examples live in examples/, one self-contained folder each."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"One-line definitions of the terms used across these docs and the spec."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"One page to write a correct workflow program."},{"slug":"manifest","title":"Mesh manifest (`cotal.yaml`)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"A manifest (cotal.yaml, kind: Mesh) describes a whole team (its channels, its agents, and who may read and post where) in one file."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"MeshView is the CLI's shared model for the terminal console and its plain stream."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How peers see each other and how messages reach them: the presence directory, the three delivery modes, and the two delivery guarantees."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. The wire contract (v0.x) may still change under the change process. This page tracks what is deliberately not built yet, and the direction each area is headed."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Day-to-day operation of a local mesh: what cotal up actually runs, how spawning resolves personas, harnesses, and models, how to reach a mesh from any directory, and the operator-only maintenance v\u2026"},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Cotal v0 provides containment and sender authenticity for peers sharing one trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"cotal setup (implementations/cli/src/commands/setup.ts) saves configuration by default: it checks prerequisites, sets up the chosen application and runtimes, and seeds persona files."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"The space concept, and why it is distinct from a channel."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"The cotal CLI sends usage data about commands, failures and platforms."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"What in Cotal is the protocol, what is the transport, and what a transport binding must provide."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Substrate stability tells you what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Guide (informative)","category":"Guide","summary":"Cotal can run a local team, connect a session to a shared space, or expose a service to agents."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Cotal's watch surfaces show who is present, their reported activity and the messages your credential permits you to read."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"A workflow run is a program that coordinates agents over hours or days and survives the process that started it."}],"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!==1011351||createHash11("sha256").update(packed).digest("hex")!=="45d8059ff86830e9a053c858a5ffb5d4bf111793201173a7fd012cac6a951b81")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,2452],[2452,9118],[9118,18828],[18828,34667],[34667,37458],[37458,66068],[66068,71569],[71569,74836],[74836,83632],[83632,87999],[87999,92168],[92168,359261],[359261,377346],[377346,409245],[409245,419225],[419225,425654],[425654,438203],[438203,444487],[444487,448952],[448952,452529],[452529,470986],[470986,475418],[475418,481608],[481608,489810],[489810,493097],[493097,545142],[545142,546999],[546999,550257],[550257,554004],[554004,558817],[558817,564741],[564741,574192],[574192,577871],[577871,581019],[581019,602007],[602007,608237],[608237,620119],[620119,622730],[622730,625211],[625211,629283],[629283,633478],[633478,692416],[692416,695540],[695540,704837],[704837,730325],[730325,968497],[968497,1006139],[1006139,1011351]];var sourceLengths=[5208,15763,23039,47651,6757,75407,12629,7832,76592,10114,9704,805600,47318,86254,24768,15562,32690,15114,9720,8073,49834,25032,15534,21252,7249,145145,3758,8366,8397,11335,13357,23090,8770,6525,55562,14726,29983,5486,5367,9775,9903,171720,6967,22142,68170,688894,106096,21676];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!==437018||createHash11("sha256").update(packed).digest("hex")!=="40decf3a6c21039ccda167803a56b2b41398e2affb6a1264c397baa83a95e10e")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.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,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+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 i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}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 key=page.trim().toLowerCase().replace(/\.md$/,"");const meta2=metadata();loadDocsSourceLengths();const count=meta2.pages.length;if(key==="spec")return{slug:"spec",title:meta2.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta2.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta2.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta2.pages.findIndex((p,source2)=>(pages.get(source2)??p).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 b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
132
+ `)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});async function submitFeedback(input,options={}){const url=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.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}try{const res=await fetch(url,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url}: ${e.message}`)}}import{execFileSync as execFileSync3}from"node:child_process";import{createHash as createHash11}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.133.10";function loadDocsMetadata(){return{"version":"0.133.10","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"Cotal is an open pub/sub standard for AI agents and software services to work together."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Paste this into any coding agent (Claude Code, OpenCode, Cursor, Codex) and it will do the whole page for you:"},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"Cotal is built as a thin waist: the normative wire contract (subjects, message schemas, presence/discovery, delivery semantics, the auth grammar) is the standard (SPEC), and everything else is a pl\u2026"},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"The tools are defined once, platform-neutrally, in @cotal-ai/connector-core and rendered onto each host's native tool API (an MCP server for Claude Code, Codex and Jcode, native plugin tools for Op\u2026"},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel permissions decide who can read, who can post, and what each agent tunes into at boot."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"Who can do what on a mesh, and how it is enforced."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"An agent's identity and persona live in one Markdown file instead of being passed flag-by-flag, the same shape Claude Code uses for subagents:"},{"slug":"api-reference","title":"API reference","kind":"Reference (informative)","category":"Reference","summary":"Cotal exposes a wire protocol, TypeScript libraries, CLI commands and agent tools."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP interface of the stock auth public listener: 11 paths and 12 operations."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Reference: describes the TypeScript reference implementation, not the wire contract.","category":"Reference","summary":"A connector teaches Cotal how to launch one agent harness (Claude Code, OpenCode, your own) as a mesh node."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"This page is the reading order for implementing a Cotal client in another language (Go, Python, Rust, or anything with a NATS client library) against the spec, without reimplementing the protocol."},{"slug":"cli","title":"`cotal` CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"cotal is the operator command line for the reference implementation: bring a mesh up, mint identities, launch agents, watch what they do, and tear it all down."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Four things configure a Cotal workstation: the config file (per-connector settings, notably which of your MCP servers get shared with spawned agents), your preferences (the defaults your own comman\u2026"},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"The Claude Code connector turns a real claude session into a Cotal mesh peer."},{"slug":"connect-codex","title":"Connect Codex (beta)","kind":"Guide (informative)","category":"Guide","summary":"OpenAI Codex joins a Cotal mesh as a lateral peer: the same cotal tool surface, the same message delivery and attention model as the other connectors, plus mid-turn steering: a directed peer messag\u2026"},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Hermes (Nous Research) joins a Cotal mesh as a lateral peer, with the same shared cotal tool surface and delivery model as the other connectors."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Jcode joins a Cotal mesh as a lateral peer."},{"slug":"connect-opencode","title":"Connect OpenCode (beta)","kind":"Guide (informative)","category":"Guide","summary":"OpenCode joins a Cotal mesh as a lateral peer, at parity with Claude Code: the same cotal tool surface, the same message delivery and attention model."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"@cotal-ai/pi is Cotal's first host-native framework adapter."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Every connector puts a real agent session on the mesh with the same cotal tools, presence, and delivery model (MCP tools)."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"Cotal once had a privileged control rail: a fixed set of named service tiers (self / manager / admin / delivery) on their own ctl."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP interface of the @cotal-ai/web reference implementation."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"The Quickstart gives you one agent. To run a specific team (your own channels, your own agents, and the channel access for each agent), describe it once in a cotal.yaml and launch it with a single\u2026"},{"slug":"delivery-daemon","title":"The delivery daemon (Plane-3)","kind":"Concept (informative)","category":"Concept","summary":"Live channel delivery is at-most-once: a message reaches only the peers subscribed at the moment it is published (SPEC \xA74)."},{"slug":"deploy","title":"Deploying agent teams","kind":"Guide (informative)","category":"Guide","summary":"The deploy/ tree runs a team of agents in an isolated container that dials out to an existing Cotal broker."},{"slug":"embedding","title":"Embedding Cotal","kind":"Guide (informative)","category":"Guide","summary":"The cotal binary in this repo is one composition root: an operator CLI."},{"slug":"examples","title":"Examples","kind":"Guide (informative)","category":"Guide","summary":"Examples live in examples/, one self-contained folder each."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"One-line definitions of the terms used across these docs and the spec."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"One page to write a correct workflow program."},{"slug":"manifest","title":"Mesh manifest (`cotal.yaml`)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"A manifest (cotal.yaml, kind: Mesh) describes a whole team (its channels, its agents, and who may read and post where) in one file."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"MeshView is the CLI's shared model for the terminal console and its plain stream."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How peers see each other and how messages reach them: the presence directory, the three delivery modes, and the two delivery guarantees."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. The wire contract (v0.x) may still change under the change process. This page tracks what is deliberately not built yet, and the direction each area is headed."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Day-to-day operation of a local mesh: what cotal up actually runs, how spawning resolves personas, harnesses, and models, how to reach a mesh from any directory, and the operator-only maintenance v\u2026"},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Cotal v0 provides containment and sender authenticity for peers sharing one trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"cotal setup (implementations/cli/src/commands/setup.ts) saves configuration by default: it checks prerequisites, sets up the chosen application and runtimes, and seeds persona files."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"The space concept, and why it is distinct from a channel."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"The cotal CLI sends usage data about commands, failures and platforms."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"What in Cotal is the protocol, what is the transport, and what a transport binding must provide."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Substrate stability tells you what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Guide (informative)","category":"Guide","summary":"Cotal can run a local team, connect a session to a shared space, or expose a service to agents."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Cotal's watch surfaces show who is present, their reported activity and the messages your credential permits you to read."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"A workflow run is a program that coordinates agents over hours or days and survives the process that started it."}],"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!==1011481||createHash11("sha256").update(packed).digest("hex")!=="c3f45289ea025715cdade91f546a7fc191fec70023d1442085fe715b2ddd4a47")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,2452],[2452,9118],[9118,18828],[18828,34667],[34667,37458],[37458,66068],[66068,71569],[71569,74836],[74836,83632],[83632,87999],[87999,92168],[92168,359261],[359261,377346],[377346,409245],[409245,419225],[419225,425654],[425654,438238],[438238,444617],[444617,449082],[449082,452659],[452659,471116],[471116,475548],[475548,481738],[481738,489940],[489940,493227],[493227,545272],[545272,547129],[547129,550387],[550387,554134],[554134,558947],[558947,564871],[564871,574322],[574322,578001],[578001,581149],[581149,602137],[602137,608367],[608367,620249],[620249,622860],[622860,625341],[625341,629413],[629413,633608],[633608,692546],[692546,695670],[695670,704967],[704967,730455],[730455,968627],[968627,1006269],[1006269,1011481]];var sourceLengths=[5208,15763,23039,47651,6757,75407,12629,7832,76592,10114,9704,805600,47318,86254,24768,15562,32785,15375,9720,8073,49834,25032,15534,21252,7249,145145,3758,8366,8397,11335,13357,23090,8770,6525,55562,14726,29983,5486,5367,9775,9903,171720,6967,22142,68170,688894,106096,21676];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!==437025||createHash11("sha256").update(packed).digest("hex")!=="38a2250452043505412c3b88172116834add29f4b72d3ecb7d103d2dc183b6c3")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.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,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+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 i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}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 key=page.trim().toLowerCase().replace(/\.md$/,"");const meta2=metadata();loadDocsSourceLengths();const count=meta2.pages.length;if(key==="spec")return{slug:"spec",title:meta2.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta2.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta2.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta2.pages.findIndex((p,source2)=>(pages.get(source2)??p).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 b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
133
133
  ${p.summary}`});return[`# Cotal v${b.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\`: ${b.spec.title} (the wire contract; where a page disagrees, the spec wins)`,`- \`lang\`: ${b.lang.title} (the workflow language a durable run executes; spec \xA714)`,`- \`schema\`: ${b.schema.title} (authoritative for message shapes)`,"","## Pages",...rows].join("\n")}function renderPage(p,note){return`${note}
134
134
 
135
135
  ${p.body}`.trimStart()}var K1=1.2;var B=.75;function sources(){const b=metadata();return[...b.pages.map((page,source)=>pages.get(source)??page),{slug:"spec",...b.spec},{slug:"lang",...b.lang},{slug:"schema",...b.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(t=>!STOP.has(t));if(!terms.length)terms=tokenize(query);const termSet=new Set(terms);if(!termSet.size)return[];const idx=searchIndex();const N=idx.sections;const scores=new Float64Array(N);for(const t of termSet){const id2=termId(idx.terms,t);if(id2<0)continue;const from=idx.offsets[id2];const to=idx.offsets[id2+1];const n=to-from;const idf=Math.log(1+(N-n+.5)/(n+.5));for(let p=from;p<to;p++){const s=idx.postSection[p];const f=idx.postWeight[p];scores[s]+=idf*(f*(K1+1)/(f+K1*(1-B+B*idx.length[s]/idx.avgdl)))}}const scored=[];for(let s=0;s<N;s++)if(scores[s]>0)scored.push({s,score:scores[s]});scored.sort((a,b)=>b.score-a.score);const all=sources();const perPage=new Map;const hits=[];for(const{s,score}of scored){const source=all[idx.source[s]];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[s],text:sourceBody(idx.source[s]).slice(idx.start[s],idx.end[s]),score});if(hits.length>=limit)break}return hits}function capSection(text2,maxLines=48){const lines=text2.split("\n");if(lines.length<=maxLines)return text2.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(h2=>`## ${h2.heading}
@@ -171,7 +171,7 @@ ${stderr.trim()}`:""))}import net from"node:net";import{EventEmitter as EventEmi
171
171
 
172
172
  ${structuredInstructions(schema)}`}function buildStructuredCorrectionPrompt(schema,attempt){return["Your previous response did not satisfy the required structured-output contract.","Return a corrected response as JSON only, with no markdown, prose, code fences, or comments.","It must validate against this JSON Schema:","```json",stableStringify(schema),"```","Validation errors:",...attempt.errors.map(issue2=>`- ${formatIssue(issue2)}`),"Previous response:","```",truncate(attempt.text,4e3),"```"].join("\n")}function assertRetryCount(maxRetries){if(!Number.isSafeInteger(maxRetries)||maxRetries<0){throw new HarnessError("invalid_request","maxRetries must be a non-negative safe integer")}}function formatIssue(issue2){const path4=issue2.path||"/";return`${path4} ${issue2.message}`}function structuredInstructions(schema){return["Return the answer as JSON only, with no markdown, prose, code fences, or comments.","The JSON value must validate against this JSON Schema:","```json",stableStringify(schema),"```"].join("\n")}function normalizeAjvErrors(errors){return errors.map(error2=>({path:error2.instancePath||"/",keyword:error2.keyword,message:error2.message??`failed ${error2.keyword} validation`,params:error2.params}))}function parseJsonFromText(text2){const candidates=jsonCandidates(text2);let lastError="input was empty";for(const candidate2 of candidates){try{return{ok:true,value:JSON.parse(candidate2)}}catch(error2){lastError=error2 instanceof Error?error2.message:String(error2)}}return{ok:false,error:{path:"/",keyword:"parse",message:`invalid JSON: ${lastError}`}}}function jsonCandidates(text2){const trimmed=text2.trim();if(!trimmed)return[];const candidates=[trimmed];const fenced=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(trimmed);if(fenced?.[1])candidates.push(fenced[1].trim());const container=firstJsonContainer(trimmed);if(container&&!candidates.includes(container))candidates.push(container);return candidates}function firstJsonContainer(text2){const start=text2.search(/[\[{]/);if(start<0)return void 0;const stack=[];let inString=false;let escaped=false;for(let index2=start;index2<text2.length;index2+=1){const char=text2[index2];if(inString){if(escaped){escaped=false}else if(char==="\\"){escaped=true}else if(char==='"'){inString=false}continue}if(char==='"'){inString=true;continue}if(char==="{"||char==="["){stack.push(char==="{"?"}":"]");continue}if(char==="}"||char==="]"){if(stack.pop()!==char)return void 0;if(stack.length===0)return text2.slice(start,index2+1)}}return void 0}function stableStringify(value){return JSON.stringify(sortJson(value),null,2)}function sortJson(value){if(Array.isArray(value))return value.map(sortJson);if(!value||typeof value!=="object")return value;const record2=value;return Object.fromEntries(Object.keys(record2).sort().map(key=>[key,sortJson(record2[key])]))}function truncate(value,maxChars){if(value.length<=maxChars)return value;return`${value.slice(0,maxChars)}
173
173
  \u2026 truncated ${value.length-maxChars} chars`}function unixSocketTransport(socketPath){return new Promise((resolve4,reject)=>{const socket=net.createConnection(transportEndpoint(socketPath));socket.setNoDelay(true);const onConnectError=cause=>reject(connectError(socketPath,cause));socket.once("error",onConnectError);socket.once("connect",()=>{socket.removeListener("error",onConnectError);socket.on("error",()=>{});resolve4({write:data=>{if(socket.destroyed||socket.writableEnded){throw new HarnessError("disconnected","harness connection closed")}try{socket.write(data,()=>{})}catch(cause){throw new HarnessError("disconnected",`write failed: ${String(cause)}`)}},onData:listener=>socket.on("data",listener),onClose:listener=>{socket.on("close",()=>listener());socket.on("error",error2=>listener(error2))},close:()=>socket.destroy()})})})}function connectError(socketPath,cause){const code2=cause.code??"unknown";const hint=code2==="ENOENT"?`no harness API socket at ${socketPath}. Start the bridge with \`jcode api-bridge\`, or set JCODE_API_SOCKET to its path.`:code2==="ECONNREFUSED"?`nothing is listening on ${socketPath}; a stale socket file is left over from a bridge that exited. Restart the bridge.`:code2==="EACCES"?`permission denied on ${socketPath}: the socket belongs to another user.`:`could not connect to ${socketPath}: ${cause.message}`;const error2=new HarnessError("connect_failed",hint);error2.cause=cause;return error2}var JcodeClient=class _JcodeClient extends EventEmitter3{transport;decoder=new NdjsonDecoder;pending=new Map;requestTimeoutMs;socketPath;clientName;nextId=1;closed=false;closeError;server="";capabilities=[];supports(capability){return this.capabilities.includes(capability)}constructor(transport,requestTimeoutMs,socketPath,clientName){super();this.setMaxListeners(0);this.transport=transport;this.requestTimeoutMs=requestTimeoutMs;this.socketPath=socketPath;this.clientName=clientName;transport.onData(chunk=>this.ingest(chunk));transport.onClose(error2=>this.handleClose(error2))}instance;get instanceHome(){return this.instance?.jcodeHome}static async launch(options={}){const instance=await launchInstance(options);try{const client=await _JcodeClient.connect({...options,socketPath:instance.socketPath});client.instance=instance;return client}catch(error2){await instance.shutdown();throw error2}}static async connect(options={}){const socketPath=options.transport?void 0:options.socketPath??apiSocketPath();const transport=options.transport??await unixSocketTransport(socketPath);const clientName=options.clientName??"jcode-sdk-ts";const client=new _JcodeClient(transport,options.requestTimeoutMs??3e4,socketPath,clientName);const frame=await client.request({req:"hello",min_version:API_VERSION_MAJOR,max_version:API_VERSION_MAJOR,client:clientName});if(frame.ev!=="hello_ok"){client.close();throw new HarnessError("handshake_failed",`unexpected reply: ${frame.ev}`)}client.server=String(frame.server??"");client.capabilities=frame.capabilities??[];return client}ingest(chunk){let frames;try{frames=this.decoder.push(chunk)}catch(error2){this.emitSafe("error",error2);return}for(const raw of frames){const frame=raw;const replyTo=frame.reply_to;if(typeof replyTo==="number"&&this.pending.has(replyTo)){const waiter=this.pending.get(replyTo);this.pending.delete(replyTo);if(waiter.timer)clearTimeout(waiter.timer);waiter.resolve(frame);continue}this.emit("event",frame);this.emitSafe(frame.ev==="error"?"harness_error":frame.ev,frame)}}emitSafe(event,payload){if(event==="error"&&this.listenerCount("error")===0)return;this.emit(event,payload)}handleClose(error2){this.closed=true;this.closeError=error2??new Error("harness connection closed");for(const[,waiter]of this.pending){if(waiter.timer)clearTimeout(waiter.timer);waiter.reject(this.closeError)}this.pending.clear();this.emit("close",error2)}request(request){if(this.closed)return Promise.reject(this.closeError??new Error("client closed"));const id2=this.nextId++;return new Promise((resolve4,reject)=>{const entry={resolve:resolve4,reject};if(this.requestTimeoutMs>0){entry.timer=setTimeout(()=>{this.pending.delete(id2);reject(new HarnessError("timeout",`no reply to ${request.req} within ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);entry.timer.unref?.()}this.pending.set(id2,entry);try{this.transport.write(encodeFrame({v:API_VERSION_MAJOR,id:id2,...request}))}catch(error2){this.pending.delete(id2);if(entry.timer)clearTimeout(entry.timer);reject(error2)}})}async requestOk(request){const frame=await this.request(request);if(frame.ev==="error"){throw new HarnessError(String(frame.code),String(frame.message))}return frame}async expectReply(request,kind){const frame=await this.requestOk(request);if(frame.ev!==kind){throw new HarnessError("unexpected_reply",`expected ${kind}, got ${frame.ev}`)}return frame}async listSessions(options={}){const frame=await this.expectReply({req:"list_sessions",include_archived:options.includeArchived},"sessions");return frame.sessions??[]}async archiveSession(sessionId){await this.requestOk({req:"archive_session",session_id:sessionId})}async restoreSession(sessionId){await this.requestOk({req:"restore_session",session_id:sessionId})}async setRetentionPolicy(archiveAfterDays){await this.requestOk({req:"set_retention_policy",archive_after_days:archiveAfterDays})}async createSession(workingDir){const frame=await this.expectReply({req:"create_session",working_dir:workingDir},"attached");return frame.session}async attachSession(sessionId){const frame=await this.expectReply({req:"attach_session",session_id:sessionId},"attached");return frame.session}async detachSession(sessionId){await this.requestOk({req:"detach_session",session_id:sessionId})}async sendMessage(sessionId,content,imagesOrOptions=[],legacyOptions={}){const options=Array.isArray(imagesOrOptions)?{...legacyOptions,images:imagesOrOptions}:imagesOrOptions;const images=options.images??[];if(options.noReply){await this.requestOk({req:"send_message",session_id:sessionId,content,images,no_reply:true});return}const waitForAccept=options.waitForAccept??true;const accepted=waitForAccept?this.waitForEvent(frame=>frame.ev==="message_accepted"&&frame.session_id===sessionId,options.acceptTimeoutMs??1e4):void 0;this.notify({req:"send_message",session_id:sessionId,content,images});await accepted}notify(request){if(this.closed)throw this.closeError??new Error("client closed");const id2=this.nextId++;this.transport.write(encodeFrame({v:API_VERSION_MAJOR,id:id2,...request}))}waitForEvent(predicate,timeoutMs){return new Promise(resolve4=>{const finish=()=>{clearTimeout(timer);this.off("event",onEvent);this.off("close",finish);resolve4()};const onEvent=frame=>{if(predicate(frame))finish()};const timer=setTimeout(finish,timeoutMs);timer.unref?.();this.on("event",onEvent);this.once("close",finish)})}async cancel(sessionId){await this.requestOk({req:"cancel",session_id:sessionId})}async softInterrupt(sessionId,content,urgent=false){await this.requestOk({req:"soft_interrupt",session_id:sessionId,content,urgent})}async getHistory(sessionId){const frame=await this.expectReply({req:"get_history",session_id:sessionId},"history");return frame.messages??[]}async peekSession(sessionId,limit){const frame=await this.expectReply({req:"peek_session",session_id:sessionId,limit},"history");return frame.messages??[]}async clear(sessionId){await this.requestOk({req:"clear",session_id:sessionId})}async rewind(sessionId,messageIndex){await this.requestOk({req:"rewind",session_id:sessionId,message_index:messageIndex})}async respondToPermission(sessionId,requestId,decision){await this.requestOk({req:"permission_response",session_id:sessionId,request_id:requestId,decision})}async listModels(sessionId){const frame=await this.expectReply({req:"list_models",session_id:sessionId},"models");return{models:frame.models??[],current:frame.current}}async getRuntimeInfo(sessionId){await this.ping();const frame=await this.expectReply({req:"get_runtime_info",session_id:sessionId},"runtime_info");const routes=frame.routes??[];return{server:this.server,protocolVersion:API_VERSION_MAJOR,capabilities:[...this.capabilities],healthy:true,sessionId:frame.session_id,provider:frame.provider,model:frame.model,providers:[...new Set([frame.provider,...routes.map(route=>route.provider)].filter(provider=>provider!==void 0))],routes}}async setApiKey(provider,apiKey){await this.expectReply({req:"set_api_key",provider,api_key:apiKey},"credential_updated")}async clearApiKey(provider){await this.expectReply({req:"clear_api_key",provider},"credential_updated")}async readFile(sessionId,path4,maxBytes){const frame=await this.expectReply({req:"read_file",session_id:sessionId,path:path4,max_bytes:maxBytes},"file_content");return{path:frame.path,content:frame.content,size:frame.size,truncated:frame.truncated}}async findFiles(sessionId,query,limit){const frame=await this.expectReply({req:"find_files",session_id:sessionId,query,limit},"files");return frame.paths}async searchText(sessionId,query,options={}){const frame=await this.expectReply({req:"search_text",session_id:sessionId,query,...options},"text_matches");return frame.matches}async fileStatus(sessionId,path4){const frame=await this.expectReply({req:"file_status",session_id:sessionId,path:path4},"file_status");return{path:frame.path,exists:frame.exists,kind:frame.kind,size:frame.size,modifiedMs:frame.modified_ms}}async setModel(sessionId,model){await this.requestOk({req:"set_model",session_id:sessionId,model})}async setReasoningEffort(sessionId,effort){await this.requestOk({req:"set_reasoning_effort",session_id:sessionId,effort})}async compact(sessionId){const frame=await this.expectReply({req:"compact",session_id:sessionId},"compacted");return frame.message}async renameSession(sessionId,title){await this.requestOk({req:"rename_session",session_id:sessionId,title})}async rewindUndo(sessionId){await this.requestOk({req:"rewind_undo",session_id:sessionId})}async cancelSoftInterrupts(sessionId){await this.requestOk({req:"cancel_soft_interrupts",session_id:sessionId})}async ping(){await this.requestOk({req:"ping"})}events(sessionId){const queue=[];let resolveNext;let done=false;const onEvent=frame=>{if(sessionId&&"session_id"in frame&&frame.session_id!==sessionId)return;if(resolveNext){const resolve4=resolveNext;resolveNext=void 0;resolve4({value:frame,done:false})}else{queue.push(frame)}};const onClose=()=>{void stop()};const stop=()=>{done=true;queue.length=0;this.off("event",onEvent);this.off("close",onClose);if(resolveNext){const resolve4=resolveNext;resolveNext=void 0;resolve4({value:void 0,done:true})}return Promise.resolve({value:void 0,done:true})};this.on("event",onEvent);this.once("close",onClose);return{[Symbol.asyncIterator](){return this},next:()=>{if(queue.length>0){return Promise.resolve({value:queue.shift(),done:false})}if(done)return stop();return new Promise(resolve4=>{resolveNext=resolve4})},return:stop,throw:stop}}globalEvents(options={}){if(!this.socketPath){throw new HarnessError("unsupported_transport","globalEvents requires a native socket connection; custom transports cannot be cloned into per-session child connections")}if(this.closed){throw this.closeError??new HarnessError("disconnected","harness connection closed")}const discoveryIntervalMs=options.discoveryIntervalMs??1e3;const maxBufferedEvents=options.maxBufferedEvents??1e4;if(!Number.isFinite(discoveryIntervalMs)||discoveryIntervalMs<0){throw new HarnessError("invalid_option","discoveryIntervalMs must be a finite number >= 0")}if(!Number.isInteger(maxBufferedEvents)||maxBufferedEvents<1){throw new HarnessError("invalid_option","maxBufferedEvents must be a positive integer")}const queue=[];const children=new Map;const starting=new Set;const startTasks=new Set;let waiter;let stopped=false;let terminalError;let discoveryTimer;let cleanupPromise;const settleWaiter=()=>{if(!waiter)return;const pending=waiter;waiter=void 0;if(terminalError)pending.reject(terminalError);else pending.resolve({value:void 0,done:true})};const onParentClose=error2=>{void finish(error2)};const onAbort=()=>{void finish()};const finish=error2=>{if(cleanupPromise)return cleanupPromise;stopped=true;terminalError=error2;queue.length=0;if(discoveryTimer)clearTimeout(discoveryTimer);this.off("close",onParentClose);options.signal?.removeEventListener("abort",onAbort);settleWaiter();const closing=[];for(const{client,stream,pump}of children.values()){closing.push(Promise.resolve(stream.return?.(void 0)));closing.push(client.close());if(pump)closing.push(pump)}children.clear();closing.push(...startTasks);cleanupPromise=Promise.allSettled(closing).then(()=>void 0);return cleanupPromise};const enqueue=event=>{if(stopped)return;if(waiter){const pending=waiter;waiter=void 0;pending.resolve({value:event,done:false});return}if(queue.length>=maxBufferedEvents){void finish(new HarnessError("event_buffer_overflow",`globalEvents consumer fell behind ${maxBufferedEvents} buffered events`));return}queue.push(event)};const startChild=async sessionId=>{if(stopped||children.has(sessionId)||starting.has(sessionId))return;starting.add(sessionId);let child;try{child=await _JcodeClient.connect({socketPath:this.socketPath,clientName:`${this.clientName}/global-events`,requestTimeoutMs:this.requestTimeoutMs});if(stopped){await child.close();return}const stream=child.events(sessionId);const childState={client:child,stream};children.set(sessionId,childState);await child.attachSession(sessionId);if(stopped)return;const pump=(async()=>{try{for await(const event of stream)enqueue(event)}finally{if(children.get(sessionId)===childState)children.delete(sessionId);await childState.client.close()}})();childState.pump=pump;void pump}catch(error2){if(child&&children.get(sessionId)?.client===child)children.delete(sessionId);await child?.close();if(!stopped&&!(error2 instanceof HarnessError&&error2.code==="unknown_session")){void finish(error2 instanceof Error?error2:new Error(String(error2)))}}finally{starting.delete(sessionId)}};const scan=async()=>{if(stopped)return;try{const sessions=await this.listSessions({includeArchived:true});if(stopped)return;const tasks=sessions.map(session=>{const task=startChild(session.session_id);startTasks.add(task);void task.finally(()=>startTasks.delete(task));return task});await Promise.allSettled(tasks)}catch(error2){if(!stopped)void finish(error2 instanceof Error?error2:new Error(String(error2)))}if(!stopped&&discoveryIntervalMs>0){discoveryTimer=setTimeout(()=>void scan(),discoveryIntervalMs);discoveryTimer.unref?.()}};this.once("close",onParentClose);if(options.signal?.aborted)void finish();else{options.signal?.addEventListener("abort",onAbort,{once:true});void scan()}return{[Symbol.asyncIterator](){return this},next:()=>{if(queue.length>0){return Promise.resolve({value:queue.shift(),done:false})}if(terminalError)return Promise.reject(terminalError);if(stopped){return Promise.resolve({value:void 0,done:true})}if(waiter){return Promise.reject(new HarnessError("concurrent_next","globalEvents does not support concurrent next() calls"))}return new Promise((resolve4,reject)=>{waiter={resolve:resolve4,reject}})},return:async()=>{await finish();return{value:void 0,done:true}},throw:async error2=>{await finish();throw error2}}}async run(sessionId,content,options={}){const stream=this.events(sessionId);await this.sendMessage(sessionId,content,options.images??[]);const result={text:"",reasoning:"",toolCalls:[],usage:void 0};for await(const event of stream){options.onEvent?.(event);switch(event.ev){case"text_delta":result.text+=event.text;break;case"reasoning_delta":result.reasoning+=event.text;break;case"tool_done":result.toolCalls.push({callId:event.call_id,name:event.name,output:event.output,error:event.error});break;case"token_usage":result.usage={input:event.input,output:event.output,cacheReadInput:event.cache_read_input};break;case"permission_request":if(options.autoApprove){await this.respondToPermission(sessionId,event.request_id,"allow")}break;case"turn_done":await stream.return?.(void 0);return result;case"error":await stream.return?.(void 0);throw new HarnessError(event.code??"internal",event.message??"harness error")}}return result}async runStructured(sessionId,content,options){const{schema,maxRetries=2,...runOptions}=options;assertRetryCount(maxRetries);const validate2=compileStructuredSchema(schema);const attempts=[];let prompt=buildStructuredPrompt(content,schema);for(let attemptNumber=1;attemptNumber<=maxRetries+1;attemptNumber+=1){const turn=await this.run(sessionId,prompt,runOptions);const validation=validateStructuredText(turn.text,validate2);const attempt={attempt:attemptNumber,text:turn.text,errors:validation.errors};attempts.push(attempt);if(validation.ok)return{...turn,data:validation.data,attempts};prompt=buildStructuredCorrectionPrompt(schema,attempt)}throw new StructuredOutputError(attempts)}close(){this.transport.close();const instance=this.instance;this.instance=void 0;return instance?instance.shutdown():Promise.resolve()}};import{createHash as createHash13,randomBytes as randomBytes3}from"node:crypto";import{closeSync as closeSync4,constants as constants7,copyFileSync as copyFileSync2,fstatSync as fstatSync3,lstatSync as lstatSync6,mkdirSync as mkdirSync6,openSync as openSync4,readdirSync as readdirSync2,renameSync as renameSync2,rmSync as rmSync4,rmdirSync as rmdirSync2,statSync as statSync4,symlinkSync,unlinkSync as unlinkSync5}from"node:fs";import{homedir}from"node:os";import{basename as basename2,dirname as dirname8,isAbsolute,join as join10,relative,resolve as resolve2,sep}from"node:path";import{closeSync as closeSync3,constants as constants6,copyFileSync,mkdtempSync as mkdtempSync2,openSync as openSync3,rmSync as rmSync3}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import{join as join9}from"node:path";import{DatabaseSync}from"node:sqlite";var CURSOR_DATABASE_FILES=[".config/Cursor/User/globalStorage/state.vscdb",".config/cursor/User/globalStorage/state.vscdb","Library/Application Support/Cursor/User/globalStorage/state.vscdb","Library/Application Support/cursor/User/globalStorage/state.vscdb","AppData/Roaming/Cursor/User/globalStorage/state.vscdb","AppData/Roaming/cursor/User/globalStorage/state.vscdb"];function copyCursorCredentials(source,destination){const input=new DatabaseSync(source,{readOnly:true});let rows;try{rows=input.prepare("SELECT key, value FROM ItemTable WHERE key IN (?, ?, ?)").all("cursorAuth/accessToken","cursorAuth/refreshToken","storage.serviceMachineId")}finally{input.close()}const stage=mkdtempSync2(join9(tmpdir2(),"cotal-jcode-cursor-"));try{const path4=join9(stage,"auth.sqlite");closeSync3(openSync3(path4,"wx",384));const output=new DatabaseSync(path4);try{output.exec("CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value BLOB)");const insert=output.prepare("INSERT INTO ItemTable VALUES (?, ?)");for(const row of rows)insert.run(row.key,row.value)}finally{output.close()}copyFileSync(path4,destination,constants6.COPYFILE_EXCL)}finally{rmSync3(stage,{recursive:true,force:true})}}var MAX_API_SOCKET_BYTES=100;var JCODE_CREDENTIAL_FILES=["auth.json","openai-auth.json","antigravity_oauth.json","gemini_oauth.json","google_oauth.json","google_credentials.json","config.toml"];var EXTERNAL_CREDENTIAL_FILES2=[".claude/.credentials.json",".codex/auth.json",".gemini/oauth_creds.json",".cursor/auth.json",".config/cursor/auth.json","AppData/Roaming/Cursor/auth.json",...CURSOR_DATABASE_FILES,".config/github-copilot/hosts.json",".config/github-copilot/apps.json",".copilot/config.json",".hermes/auth.json",".pi/agent/auth.json",".openclaw/agent/auth.json",".openclaw/credentials/oauth.json",".local/share/opencode/auth.json"];function assertRelative(relativePath){if(isAbsolute(relativePath)||relativePath.split(/[\\/]+/u).includes(".."))throw new Error(`unsafe Jcode credential mirror path: ${relativePath}`)}function privateDirectory(path4,{replaceSymlink=false,requireOwner=false,beforeEnsure,pin}){if(pin){ensurePinnedPrivateDirectory(path4,{replaceSymlink,requireOwner,beforeEnsure});return}ensureUnpinnedPrivateDirectory(path4,{replaceSymlink,requireOwner,beforeEnsure})}function ensureUnpinnedPrivateDirectory(path4,{replaceSymlink=false,requireOwner=false,beforeEnsure}){try{const stats=lstatSync6(path4);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();rmSync4(path4,{force:true});mkdirSync6(path4,{mode:448})}else if(!stats.isDirectory()){throw new Error(`Jcode private path is not a directory: ${path4}`)}else if(requireOwner){assertCurrentUserOwns(path4,stats.uid)}}catch(error2){if(error2.code!=="ENOENT")throw error2;beforeEnsure?.();mkdirSync6(path4,{mode:448})}hardenPrivate(path4,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync6(path4).uid)}function ensurePinnedPrivateDirectory(path4,{replaceSymlink=false,requireOwner=false,beforeEnsure}={}){const parent=dirname8(path4);const name=basename2(path4);if(name===""||name==="."||name==="..")throw new Error(`unsafe Jcode private directory: ${path4}`);const pin=PinnedParent.open(parent);try{const leaf=pin.leaf(name);try{const stats=lstatSync6(leaf);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();unlinkSync5(leaf);mkdirSync6(leaf,{mode:448})}else if(!stats.isDirectory()){throw new Error(`Jcode private path is not a directory: ${path4}`)}else if(requireOwner){assertCurrentUserOwns(path4,stats.uid)}}catch(error2){if(error2.code!=="ENOENT")throw error2;beforeEnsure?.();mkdirSync6(leaf,{mode:448})}hardenPrivate(leaf,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync6(leaf).uid)}finally{pin.close()}}function assertCurrentUserOwns(path4,uid2){if(process.platform==="win32")return;const currentUid=process.getuid?.();if(currentUid===void 0)throw new Error(`cannot determine effective UID for Jcode short API socket directory: ${path4}`);if(uid2!==currentUid)throw new Error(`refusing Jcode short API socket directory owned by uid ${uid2}, not effective uid ${currentUid}: ${path4}`)}function credentialDestination(home,destinationRelative){assertRelative(destinationRelative);const destination=join10(home,destinationRelative);if(!resolve2(destination).startsWith(resolve2(home)+sep))throw new Error(`Jcode credential mirror escapes its private home: ${destination}`);return destination}var PIN_DIRECTORY=constants7.O_RDONLY|constants7.O_DIRECTORY|constants7.O_NOFOLLOW;var OPEN_DIRECTORY=constants7.O_RDONLY|constants7.O_DIRECTORY;function assertComponent(name){if(name===""||name==="."||name===".."||name.includes("/")||name.includes("\\")||name.includes("\0"))throw new Error(`unsafe Jcode credential mirror path component: ${name}`)}function pinUnsupportedMessage(detail){return`Jcode credential mirroring requires a directory pin to name each parent by inode (${detail})`}function pinMode(){if(process.platform==="linux")return"procfs-fd";if(process.platform==="win32")throw new Error(pinUnsupportedMessage(`platform ${process.platform}`));return"cwd-inode"}function assertPinnedFdTraversal(dirFd){const probe=`/dev/fd/${dirFd}/.`;let probeFd;try{probeFd=openSync4(probe,OPEN_DIRECTORY)}catch(error2){throw new Error(pinUnsupportedMessage(`opening ${probe} failed with ${error2.code??"unknown"}`))}closeSync4(probeFd)}function sameInode(a,b){return a.dev===b.dev&&a.ino===b.ino}var PinnedParent=class _PinnedParent{#mode;#fd;#entryCwd;#closed=false;constructor(mode,fd,entryCwd){this.#mode=mode;this.#fd=fd;this.#entryCwd=entryCwd}static open(directory,beforeEnter){const mode=pinMode();const fd=openSync4(directory,OPEN_DIRECTORY);if(mode==="procfs-fd"){try{assertPinnedFdTraversal(fd);beforeEnter?.()}catch(error2){closeSync4(fd);throw error2}return new _PinnedParent(mode,fd,void 0)}let entryCwd;try{entryCwd=process.cwd()}catch(error2){closeSync4(fd);throw new Error(pinUnsupportedMessage(`the working directory is unreadable: ${error2.message}`))}const pin=new _PinnedParent(mode,fd,entryCwd);try{beforeEnter?.();process.chdir(directory);pin.#assertCwdIsPinned(directory)}catch(error2){pin.close();throw error2}return pin}leaf(name){assertComponent(name);return this.#mode==="procfs-fd"?`/dev/fd/${this.#fd}/${name}`:name}descend(name,displayPath,create){const next=create?this.#openOrCreateChild(name,displayPath):this.#openChild(name);if(this.#mode==="procfs-fd"){closeSync4(this.#fd);this.#fd=next;return}const previous=this.#fd;try{process.chdir(name)}catch(error2){closeSync4(next);throw error2}this.#fd=next;try{this.#assertCwdIsPinned(displayPath)}finally{closeSync4(previous)}}close(){if(this.#closed)return;this.#closed=true;try{if(this.#entryCwd!==void 0)process.chdir(this.#entryCwd)}finally{closeSync4(this.#fd)}}#openChild(name){return openSync4(this.leaf(name),PIN_DIRECTORY)}#openOrCreateChild(name,displayPath){try{const fd=this.#openChild(name);hardenPrivate(this.leaf(name),"dir");return fd}catch(error2){const code2=error2.code;if(code2==="ENOENT"){try{mkdirSync6(this.leaf(name),{mode:448})}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}}else if(code2==="ELOOP"||code2==="ENOTDIR"){let isLink=code2==="ELOOP";if(code2==="ENOTDIR"){try{isLink=lstatSync6(this.leaf(name)).isSymbolicLink()}catch(inner){this.mapOpenError(inner,name,displayPath)}}if(!isLink)this.mapOpenError(error2,name,displayPath);unlinkSync5(this.leaf(name));mkdirSync6(this.leaf(name),{mode:448})}else{this.mapOpenError(error2,name,displayPath)}try{const fd=this.#openChild(name);hardenPrivate(this.leaf(name),"dir");return fd}catch(retry){this.mapOpenError(retry,name,displayPath)}}}#assertCwdIsPinned(displayPath){if(!sameInode(statSync4("."),fstatSync3(this.#fd)))throw new Error(`refusing swapped Jcode credential mirror parent: ${displayPath}`)}mapOpenError(error2,name,displayPath){const code2=error2.code;if(code2==="ELOOP")throw new Error(`refusing symlinked Jcode credential mirror parent: ${displayPath}`);if(code2==="ENOTDIR"){if(lstatSync6(this.leaf(name)).isSymbolicLink())throw new Error(`refusing symlinked Jcode credential mirror parent: ${displayPath}`);throw new Error(`Jcode credential mirror parent is not a directory: ${displayPath}`)}throw error2}};function walkPinnedParents(home,parentRelative,pin,create){let current=home;for(const part of parentRelative.split(sep).filter(Boolean)){current=join10(current,part);try{pin.descend(part,current,create)}catch(error2){if(create||error2.code==="ENOENT")throw error2;pin.mapOpenError(error2,part,current)}}}function removeCredentialMirror(home,destinationRelative,beforeUnlink){const destination=credentialDestination(home,destinationRelative);const parentRelative=relative(home,dirname8(destination));assertRelative(parentRelative);const base=basename2(destination);let pin;try{pin=PinnedParent.open(home)}catch(error2){if(error2.code==="ENOENT")return false;throw error2}try{try{walkPinnedParents(home,parentRelative,pin,false)}catch(error2){if(error2.code==="ENOENT")return false;throw error2}try{if(lstatSync6(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error2){if(error2.code==="ENOENT")return false;throw error2}beforeUnlink?.();try{unlinkSync5(pin.leaf(base))}catch(error2){if(error2.code==="ENOENT")return false;throw error2}return true}finally{pin.close()}}function copyCredentialFile(home,source,destinationRelative,beforeCopy){assertRelative(destinationRelative);let sourceStats;try{sourceStats=statSync4(source)}catch(error2){if(error2.code==="ENOENT"){removeCredentialMirror(home,destinationRelative);return false}throw error2}if(!sourceStats.isFile()){removeCredentialMirror(home,destinationRelative);return false}const destination=credentialDestination(home,destinationRelative);const parentRelative=relative(home,dirname8(destination));assertRelative(parentRelative);const base=basename2(destination);const pin=PinnedParent.open(home);try{walkPinnedParents(home,parentRelative,pin,true);try{if(lstatSync6(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error2){if(error2.code!=="ENOENT")throw error2}beforeCopy?.();const tempName=`.${randomBytes3(6).toString("hex")}.tmp`;const temp=pin.leaf(tempName);try{if(CURSOR_DATABASE_FILES.some(path4=>join10("external",path4)===destinationRelative))copyCursorCredentials(source,temp);else copyFileSync2(source,temp,constants7.COPYFILE_EXCL);hardenPrivate(temp,"file");renameSync2(temp,pin.leaf(base))}finally{rmSync4(temp,{force:true})}if(lstatSync6(pin.leaf(base)).isSymbolicLink())throw new Error(`Jcode credential mirror remained symlinked: ${destination}`);return true}finally{pin.close()}}function optionalEntries(path4){try{return readdirSync2(path4,{withFileTypes:true})}catch(error2){if(error2.code==="ENOENT")return[];throw error2}}function credentialSources(){return{jcodeHome:userJcodeHome(),appConfigDir:userAppConfigDir(),externalHome:homedir()}}function jcodeCredentialMirrorInventory(home,sources2){const inventory=JCODE_CREDENTIAL_FILES.map(name=>({family:"jcode-home",source:join10(sources2.jcodeHome,name),destinationRelative:name}));const appConfigNames=new Set([...optionalEntries(sources2.appConfigDir).filter(entry=>(entry.isFile()||entry.isSymbolicLink())&&entry.name.endsWith(".env")).map(entry=>entry.name),...optionalEntries(join10(home,"config","jcode")).filter(entry=>!entry.isDirectory()&&entry.name.endsWith(".env")).map(entry=>entry.name)]);for(const name of[...appConfigNames].sort())inventory.push({family:"app-config",source:join10(sources2.appConfigDir,name),destinationRelative:join10("config","jcode",name)});for(const relativePath of EXTERNAL_CREDENTIAL_FILES2)inventory.push({family:"external-static",source:join10(sources2.externalHome,relativePath),destinationRelative:join10("external",relativePath)});const agents=join10(sources2.externalHome,".openclaw","agents");const agentNames=new Set([...optionalEntries(agents).filter(entry=>entry.isDirectory()).map(entry=>entry.name),...optionalEntries(join10(home,"external",".openclaw","agents")).filter(entry=>entry.isDirectory()).map(entry=>entry.name)]);for(const agent of[...agentNames].sort()){for(const name of["auth-profiles.json","auth.json"]){const relativePath=join10(".openclaw","agents",agent,"agent",name);inventory.push({family:"external-agent",source:join10(sources2.externalHome,relativePath),destinationRelative:join10("external",relativePath)})}}return inventory}function mirrorJcodeCredentials(home,sources2=credentialSources()){privateDirectory(home,{pin:true});for(const entry of jcodeCredentialMirrorInventory(home,sources2))copyCredentialFile(home,entry.source,entry.destinationRelative)}function reclaimSocketAlias(alias){let stats;try{stats=lstatSync6(alias)}catch(error2){if(error2.code!=="ENOENT")throw error2;return}rmSync4(alias,{force:true,recursive:stats.isDirectory()})}function shortSocketHome(home){const id2=createHash13("sha256").update(resolve2(home)).digest("hex").slice(0,12);const socketDir=join10("/tmp",`jc-${id2}`);privateDirectory(socketDir,{requireOwner:true,pin:false});const alias=join10(socketDir,"home");reclaimSocketAlias(alias);try{symlinkSync(home,alias,"dir")}catch(error2){throw new Error(`cannot create Jcode short API socket alias ${alias}: ${error2.message}`)}const apiSocket=join10(alias,"run","jcode-api.sock");if(Buffer.byteLength(apiSocket)>=MAX_API_SOCKET_BYTES){rmSync4(alias,{force:true});throw new Error(`Jcode API socket path is too long even in its private short directory: ${apiSocket}`)}return{jcodeHome:alias,socketDir,dispose:()=>{rmSync4(alias,{force:true});try{rmdirSync2(socketDir)}catch(error2){if(error2.code!=="ENOENT")throw error2}}}}import{randomBytes as randomBytes4}from"node:crypto";import{readFileSync as readFileSync6,readdirSync as readdirSync3}from"node:fs";import{execFileSync as execFileSync4}from"node:child_process";import{join as join11}from"node:path";var isPid=value=>Number.isInteger(value)&&value>1;var LAUNCH_IDENTITY_ENV="JCODE_COTAL_LAUNCH_IDENTITY";function processStat(pid){try{if(process.platform==="linux"){const stat=readFileSync6(`/proc/${pid}/stat`,"utf8");const after=stat.lastIndexOf(") ");if(after<0)return void 0;const fields=stat.slice(after+2).trim().split(/\s+/u);const parentPid=Number(fields[1]);const start=fields[19];return Number.isInteger(parentPid)&&parentPid>=0&&start?{pid,parentPid,start}:void 0}if(process.platform==="darwin"||process.platform.endsWith("bsd")){const out=execFileSync4("/bin/ps",["-o","ppid=","-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();const match=out.match(/^(\d+)\s+(.+)$/u);const parentPid=Number(match?.[1]);const start=match?.[2]?.trim();return Number.isInteger(parentPid)&&parentPid>=0&&start?{pid,parentPid,start}:void 0}}catch{return void 0}return void 0}function launchIdentityEnv(){return{key:LAUNCH_IDENTITY_ENV,value:randomBytes4(24).toString("base64url")}}function captureProcessIdentity(pid){if(!isPid(pid))throw new Error(`jcode connector: cannot capture invalid launch PID ${pid}`);const stat=processStat(pid);if(!stat)throw new Error(`jcode connector: cannot capture immutable identity for launch PID ${pid} on ${process.platform} \u2014 refusing unsafe lifecycle tracking`);return{pid,start:stat.start}}function processMatches(identity){const stat=processStat(identity.pid);return stat!==void 0&&stat.start===identity.start}function processPids(){try{if(process.platform==="linux")return readdirSync3("/proc").map(Number).filter(isPid);if(process.platform==="darwin"||process.platform.endsWith("bsd"))return execFileSync4("/bin/ps",["-axo","pid="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/u).map(Number).filter(isPid)}catch(error2){throw new Error(`jcode connector: cannot enumerate launch descendants on ${process.platform}: ${error2.message}`)}throw new Error(`jcode connector: cannot prove Jcode process ownership on unsupported platform ${process.platform}`)}var processIdentityProbe={readEnviron:pid=>readFileSync6(`/proc/${pid}/environ`,"utf8"),ps:pid=>execFileSync4("/bin/ps",["eww","-p",String(pid),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),pidExists:pid=>{try{process.kill(pid,0);return true}catch(error2){const code2=error2.code;if(code2==="ESRCH")return false;if(code2==="EPERM")return true;throw error2}}};function processHasLaunchIdentityFromPs(pid,identityValue,probe){try{const out=probe.ps(pid);return out.includes(`${LAUNCH_IDENTITY_ENV}=${identityValue}`)}catch(error2){const status2=error2.status;if(status2===1&&!probe.pidExists(pid))return false;throw error2}}function launchIdentityProof(pid,identityValue,probe){if(process.platform==="linux"){let environ;try{environ=probe.readEnviron(pid)}catch(error2){const code2=error2.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")return void 0;throw error2}if(environ.length===0)return void 0;return environ.split("\0").includes(`${LAUNCH_IDENTITY_ENV}=${identityValue}`)}if(process.platform==="darwin"||process.platform.endsWith("bsd"))return processHasLaunchIdentityFromPs(pid,identityValue,probe);throw new Error(`jcode connector: launch-bound process identity is unavailable on ${process.platform}`)}function captureLaunchProcesses(identityValue,probe=processIdentityProbe){const owned=[];for(const pid of processPids()){try{if(launchIdentityProof(pid,identityValue,probe)!==true)continue;const stat=processStat(pid);if(stat)owned.push({pid:stat.pid,start:stat.start})}catch(error2){const code2=error2.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")continue;throw new Error(`jcode connector: cannot prove launch-bound identity for PID ${pid}: ${error2.message}`)}}return owned}function recordedTreePids(jcodeHome){const pids=new Set;try{const registry4=JSON.parse(readFileSync6(join11(jcodeHome,"servers.json"),"utf8"));for(const entry of Object.values(registry4??{})){const pid=Number(entry?.pid);if(isPid(pid))pids.add(pid)}}catch{}try{for(const file of readdirSync3(join11(jcodeHome,"active_pids"))){const pid=Number(readFileSync6(join11(jcodeHome,"active_pids",file),"utf8").trim());if(isPid(pid))pids.add(pid)}}catch{}pids.delete(process.pid);return[...pids]}var alive=pid=>{const stat=processStat(pid);if(stat){try{if(process.platform==="linux"){const raw=readFileSync6(`/proc/${pid}/stat`,"utf8");const after=raw.lastIndexOf(") ");if(after>=0&&raw.slice(after+2).startsWith("Z "))return false}}catch{return false}return true}try{process.kill(pid,0);return true}catch(error2){return error2.code==="EPERM"}};function signalPid(pid,signal){try{process.kill(pid,signal)}catch{}}function signalTree(pids,signal){for(const pid of pids){try{process.kill(-pid,signal)}catch{try{process.kill(pid,signal)}catch{}}}}async function waitGone(pids,timeoutMs){const deadline=Date.now()+timeoutMs;for(;;){if(!pids.some(alive))return true;if(Date.now()>deadline)return false;await new Promise(resolve4=>setTimeout(resolve4,50))}}var LAUNCH_RECORD_FILE="cotal-launch.json";function recordLaunch(home,record2){const path4=join11(home,LAUNCH_RECORD_FILE);writePrivateRecord(path4,`${JSON.stringify(record2)}
174
- `)}function readLaunchRecord(home){let parsed;try{parsed=JSON.parse(readFileSync6(join11(home,LAUNCH_RECORD_FILE),"utf8"))}catch{return void 0}const record2=parsed;const identity=record2?.identity;const host=record2?.host;if(typeof identity!=="string"||!identity)return void 0;return isPid(host?.pid)&&typeof host?.start==="string"&&host.start?{identity,host:{pid:host.pid,start:host.start}}:void 0}async function stopOrphanedTree(options){const{home,gracefulWaitMs=3e3,killWaitMs=2e3}=options;const record2=readLaunchRecord(home);if(!record2)return[];if(alive(record2.host.pid))return[];const targets=captureLaunchProcesses(record2.identity).filter(identity=>identity.pid!==process.pid&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(!targets.length)return[];signalTree(targets,"SIGTERM");if(!await waitGone(targets,gracefulWaitMs)){signalTree(targets.filter(alive),"SIGKILL");if(!await waitGone(targets,killWaitMs))throw new Error(`jcode connector: a previous lifecycle's Jcode processes survived teardown (pids ${targets.filter(alive).join(", ")}) \u2014 this seat's runtime directory is still held`)}return targets}async function stopPrivateTree(options){const{jcodeHome,launch,identityValue,gracefulWaitMs=3e3,killWaitMs=2e3,settleMs=500,identityProbe=processIdentityProbe}=options;const owned=new Map;const refreshOwned=()=>{for(const identity of captureLaunchProcesses(identityValue,identityProbe))owned.set(identity.pid,identity)};refreshOwned();if(alive(launch.pid)&&processMatches(launch)&&launchIdentityProof(launch.pid,identityValue,identityProbe)===false)throw new Error(`jcode connector: spawned Jcode bridge ${launch.pid} does not carry its launch-bound identity \u2014 refusing unsafe teardown`);if(processMatches(launch)){signalPid(launch.pid,"SIGTERM");if(!await waitGone([launch.pid],gracefulWaitMs)){signalPid(launch.pid,"SIGKILL");if(!await waitGone([launch.pid],killWaitMs))throw new Error(`jcode connector: Jcode bridge survived teardown (pid ${launch.pid}) \u2014 the seat's tree is NOT stopped`)}}let quietSince=Date.now();let capturedAfterBridge=false;for(;;){if(capturedAfterBridge)refreshOwned();else capturedAfterBridge=true;const recorded=recordedTreePids(jcodeHome);const targets=recorded.map(pid=>owned.get(pid)).filter(identity=>identity!==void 0&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(targets.length){signalTree(targets,"SIGTERM");if(!await waitGone(targets,gracefulWaitMs)){signalTree(targets.filter(alive),"SIGKILL");if(!await waitGone(targets,killWaitMs))throw new Error(`jcode connector: private Jcode processes survived teardown (pids ${targets.filter(alive).join(", ")}) \u2014 the seat's tree is NOT stopped`)}quietSince=Date.now();continue}if(Date.now()-quietSince<settleMs){await new Promise(resolve4=>setTimeout(resolve4,25));continue}const unrecorded=[...owned.values()].filter(identity=>identity.pid!==launch.pid&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(!unrecorded.length)return;signalTree(unrecorded,"SIGTERM");if(!await waitGone(unrecorded,gracefulWaitMs)){signalTree(unrecorded.filter(alive),"SIGKILL");if(!await waitGone(unrecorded,killWaitMs))throw new Error(`jcode connector: unrecorded launch-owned Jcode processes survived teardown (pids ${unrecorded.filter(alive).join(", ")}) \u2014 the seat's tree is NOT stopped`)}quietSince=Date.now()}}var replies=new WeakMap;async function connectSteerClient(socketPath,requestTimeoutMs){const socket=await unixSocketTransport(socketPath);const state={late:new Map};let client;try{client=await JcodeClient.connect({socketPath,...requestTimeoutMs===void 0?{}:{requestTimeoutMs},transport:{write(data){const frame=JSON.parse(data);if(frame.req==="soft_interrupt")state.capture?.(frame.id);socket.write(data)},onData:listener=>socket.onData(listener),onClose:listener=>socket.onClose(listener),close:()=>socket.close()}})}catch(error2){socket.close();throw error2}replies.set(client,state);client.on("event",frame=>{if(typeof frame.reply_to!=="number")return;const settle=state.late.get(frame.reply_to);if(!settle)return;state.late.delete(frame.reply_to);settle(frame.ev==="ok")});client.on("close",()=>state.late.clear());return client}function softInterruptWithLateReply(client,session,content,settle){const state=replies.get(client);if(!state)throw new Error("jcode connector: steer client has no request observer");let id2;state.capture=value=>{id2=value};let request;try{request=client.softInterrupt(session,content,false)}finally{state.capture=void 0}let disposed=false;const dispose=()=>{disposed=true;if(id2!==void 0)state.late.delete(id2)};request=request.catch(error2=>{if(!disposed&&id2!==void 0&&error2 instanceof HarnessError&&error2.code==="timeout")state.late.set(id2,settle);throw error2});return{request,dispose}}function chooseSessionToResume(candidates,cwd){if(!candidates?.length)return void 0;const usable=candidates.filter(c=>typeof c.session_id==="string"&&c.session_id.length>0&&c.archived!==true&&typeof c.working_dir==="string"&&c.working_dir===cwd&&typeof c.transcript_bytes==="number"&&c.transcript_bytes>0);if(!usable.length)return void 0;return[...usable].sort((a,b)=>(b.transcript_bytes??0)-(a.transcript_bytes??0)||a.session_id.localeCompare(b.session_id))[0]}import{createHash as createHash14,randomBytes as randomBytes5}from"node:crypto";import{existsSync,mkdirSync as mkdirSync7,readFileSync as readFileSync7,renameSync as renameSync3,writeFileSync as writeFileSync3}from"node:fs";import{join as join12}from"node:path";var SESSION_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,199}$/;var MARKER="cotal-resume.json";var STABLE_READ_ATTEMPTS=5;var TITLE_MAX=1024;function jcodeSeatHome(root,space2,name){const slug=`${space2}-${name}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);const key=createHash14("sha256").update(`${space2}\0${name}`).digest("hex").slice(0,12);return join12(root,".cotal","jcode",`${slug||"agent"}-${key}`)}function code(error2){return error2.code??error2.message}var RawJSON=JSON;function parseTranscript(text2){return JSON.parse(text2,(_key,value,context)=>typeof value==="number"&&context?.source!==void 0&&context.source!==String(value)?RawJSON.rawJSON(context.source):value)}var U64_MAX=2n**64n-1n;var isRecord2=value=>typeof value==="object"&&value!==null&&!Array.isArray(value)&&!RawJSON.isRawJSON(value);var isString=value=>typeof value==="string";var isCount=value=>{const spelling=RawJSON.isRawJSON(value)?value.rawJSON:typeof value==="number"?String(value):"";return/^(0|[1-9]\d*)$/.test(spelling)&&BigInt(spelling)<=U64_MAX};var optional2=(value,check)=>value===void 0||value===null||check(value);var RFC3339=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;function instant(value){const match=isString(value)?RFC3339.exec(value):null;const seconds=match?Date.parse(`${match[1]}${match[3]}`):NaN;return Number.isNaN(seconds)?void 0:[seconds,Number((match[2]??"").padEnd(9,"0"))]}var notAfter=(a,b)=>a[0]<b[0]||a[0]===b[0]&&a[1]<=b[1];var CONTENT_BLOCKS={text:b=>isString(b.text)&&optional2(b.cache_control,c=>isRecord2(c)&&isString(c.type)&&optional2(c.ttl,isString)),reasoning:b=>isString(b.text),reasoning_trace:b=>isString(b.text),anthropic_thinking:b=>isString(b.thinking)&&isString(b.signature),open_a_i_reasoning:b=>isString(b.id)&&Array.isArray(b.summary)&&b.summary.every(isString)&&optional2(b.encrypted_content,isString)&&optional2(b.status,isString),tool_use:b=>isString(b.id)&&isString(b.name)&&"input"in b&&optional2(b.thought_signature,isString),tool_result:b=>isString(b.tool_use_id)&&isString(b.content)&&optional2(b.is_error,v=>typeof v==="boolean"),image:b=>isString(b.media_type)&&isString(b.data),open_a_i_compaction:b=>isString(b.encrypted_content),tool_reference:b=>isString(b.tool_use_id)&&isString(b.tool_name),provider_native:b=>isString(b.provider)&&"item"in b};var isTokenUsage=u=>isRecord2(u)&&isCount(u.input_tokens)&&isCount(u.output_tokens)&&["prompt_tokens","cache_read_input_tokens","cache_creation_input_tokens"].every(key=>optional2(u[key],isCount));var isCompaction=value=>isRecord2(value)&&isString(value.summary_text)&&optional2(value.openai_encrypted_content,isString)&&isCount(value.covers_up_to_turn)&&isCount(value.original_turn_count)&&isCount(value.compacted_count);function messageFault(value){if(!isRecord2(value))return"is not an object";if(!isString(value.id))return"has no string id";if(value.role!=="user"&&value.role!=="assistant")return`has role ${JSON.stringify(value.role)}, not user or assistant`;if(!Array.isArray(value.content))return"has content that is not an array";for(const[index2,block]of value.content.entries()){const type=isRecord2(block)?block.type:void 0;if(!isString(type)||!Object.hasOwn(CONTENT_BLOCKS,type)||!CONTENT_BLOCKS[type](block))return`has a content block ${index2+1} that is not a Jcode ${isString(type)?`${JSON.stringify(type)} block`:"content block"}`}if(!optional2(value.display_role,v=>v==="system"||v==="background_task"))return"has an unknown display_role";if(!optional2(value.timestamp,v=>instant(v)!==void 0))return"has a timestamp that is not an RFC 3339 time";if(!optional2(value.tool_duration_ms,isCount))return"has a tool_duration_ms that is not a count";if(!optional2(value.token_usage,isTokenUsage))return"has a token_usage Jcode cannot read";return void 0}function readOptional(path4,refuse2){try{return readFileSync7(path4)}catch(error2){if(error2.code!=="ENOENT")refuse2(`${path4} could not be read (${code(error2)})`);return void 0}}function readJcodeForkSource(sourceHome,sessionId){if(!SESSION_ID.test(sessionId)||sessionId.includes(".."))throw new Error(`jcode connector: cannot resume ${JSON.stringify(sessionId)}: not a Jcode session id`);const snapshotPath=join12(sourceHome,"sessions",`${sessionId}.json`);const journalPath=join12(sourceHome,"sessions",`${sessionId}.journal.jsonl`);const refuse2=why=>{throw new Error(`jcode connector: cannot resume session ${sessionId}: ${why}`)};const readSnapshot=()=>{try{return readFileSync7(snapshotPath)}catch(error2){return refuse2(`no readable transcript at ${snapshotPath} (${code(error2)})`)}};let previous;for(let attempt=0;attempt<STABLE_READ_ATTEMPTS;attempt++){const read={snapshot:readSnapshot(),journal:readOptional(journalPath,refuse2)};const same=previous!==void 0&&read.snapshot.equals(previous.snapshot)&&(read.journal===void 0?previous.journal===void 0:previous.journal!==void 0&&read.journal.equals(previous.journal));previous=read;if(!same)continue;const parsed=parseJcodeSource(sessionId,snapshotPath,journalPath,read.snapshot,read.journal,refuse2);if(parsed)return parsed;previous=void 0}return refuse2(`${snapshotPath} kept changing while it was read, or its journal predates the snapshot (a Jcode checkpoint in progress); retry the resume`)}function parseJcodeSource(sessionId,snapshotPath,journalPath,snapshot,journal,refuse2){let session;try{session=parseTranscript(snapshot.toString("utf8"))}catch(error2){return refuse2(`${snapshotPath} is not valid JSON (${error2.message})`)}if(!isRecord2(session)||session.id!==sessionId||!Array.isArray(session.messages))refuse2(`${snapshotPath} is not a Jcode session snapshot for that id`);const checkFields=(where,fields)=>{for(const key of["title","system_prompt","model"])if(!optional2(fields[key],isString))refuse2(`${where} has a non-string ${key}`);if(!optional2(fields.compaction,isCompaction))refuse2(`${where} has a compaction Jcode cannot read`);return instant(fields.updated_at)??refuse2(`${where} has no updated_at Jcode can read`)};const checkMessages=(where,list)=>{for(const[index2,message]of list.entries()){const fault=messageFault(message);if(fault)refuse2(`message ${index2+1} of ${where} ${fault}`)}};const snapshotAt=checkFields(snapshotPath,session);const messages=[...session.messages];checkMessages(snapshotPath,messages);const seen=new Set(messages.map(message=>message.id));const lines=journal?journal.toString("utf8").split("\n").filter(line=>line.trim()):[];for(const[index2,line]of lines.entries()){const where=`line ${index2+1} of ${journalPath}`;let entry;try{entry=parseTranscript(line)}catch(error2){return refuse2(`${where} is not valid JSON (${error2.message})`)}if(!isRecord2(entry)||!isRecord2(entry.meta))return refuse2(`${where} has no metadata`);if(notAfter(checkFields(where,entry.meta),snapshotAt))return void 0;const appended=entry.append_messages??[];if(!Array.isArray(appended))return refuse2(`${where} has append_messages that are not a list`);checkMessages(`append_messages on ${where}`,appended);for(const message of appended){if(seen.has(message.id))return void 0;seen.add(message.id)}for(const key of["title","system_prompt","compaction","model"])session[key]=entry.meta[key]??null;messages.push(...appended)}if(typeof session.title==="string"&&session.title.length>TITLE_MAX)refuse2(`its title is ${session.title.length} characters, more than the ${TITLE_MAX} a resume records with the fork`);const hash=createHash14("sha256").update(snapshot);if(journal)hash.update(journal);return{sessionId,...typeof session.title==="string"?{title:session.title}:{},transcriptSha256:hash.digest("hex"),messages,compaction:session.compaction??void 0,systemPrompt:session.system_prompt??void 0,model:session.model??void 0}}function writeMarker(seatHome,marker){const path4=join12(seatHome,MARKER);const tmp=`${path4}.${process.pid}.${randomBytes5(4).toString("hex")}.tmp`;writeFileSync3(tmp,JSON.stringify(marker),{mode:384,flag:"wx"});renameSync3(tmp,path4)}function ownedJcodeFork(seatHome,sessionId){const markerPath=join12(seatHome,MARKER);let raw;try{raw=readFileSync7(markerPath,"utf8")}catch(error2){if(error2.code==="ENOENT")return void 0;throw new Error(`jcode connector: ${markerPath} could not be read (${code(error2)})`)}let marker;try{marker=JSON.parse(raw)}catch(error2){throw new Error(`jcode connector: ${markerPath} is not valid JSON (${error2.message}); remove it to fork session ${sessionId} again`)}if(!isRecord2(marker))throw new Error(`jcode connector: ${markerPath} is not a fork record; remove it to fork session ${sessionId} again`);if(marker.source!==sessionId||typeof marker.fork!=="string"||!SESSION_ID.test(marker.fork)||!existsSync(join12(seatHome,"sessions",`${marker.fork}.json`)))return void 0;return{source:marker.source,fork:marker.fork,...typeof marker.title==="string"?{title:marker.title}:{},transcriptSha256:String(marker.transcriptSha256??""),briefed:marker.briefed===true}}function markJcodeForkBriefed(seatHome,sessionId){const marker=ownedJcodeFork(seatHome,sessionId);if(!marker)throw new Error(`jcode connector: the seat's fork of ${sessionId} is gone from ${seatHome}`);if(!marker.briefed)writeMarker(seatHome,{...marker,briefed:true})}function forkJcodeSession(opts){const sessions=join12(opts.seatHome,"sessions");const owned=ownedJcodeFork(opts.seatHome,opts.sessionId);if(owned)return{forkId:owned.fork,...owned.title!==void 0?{title:owned.title}:{},transcriptSha256:owned.transcriptSha256,created:false,briefed:owned.briefed};const source=readJcodeForkSource(opts.sourceHome,opts.sessionId);const now=new Date().toISOString();const word=/^session_([^_]+)_/.exec(opts.sessionId)?.[1]??"fork";const forkId=`session_${word}_${Date.now()}_${randomBytes5(8).toString("hex")}`;const fork={id:forkId,parent_id:opts.sessionId,title:null,created_at:now,updated_at:now,messages:source.messages,...source.systemPrompt!==void 0?{system_prompt:source.systemPrompt}:{},...source.compaction!==void 0?{compaction:source.compaction}:{},...source.model!==void 0?{model:source.model}:{},working_dir:opts.cwd,status:"Closed"};mkdirSync7(sessions,{recursive:true,mode:448});const target2=join12(sessions,`${forkId}.json`);writeFileSync3(`${target2}.tmp`,JSON.stringify(fork),{mode:384,flag:"wx"});renameSync3(`${target2}.tmp`,target2);writeMarker(opts.seatHome,{source:opts.sessionId,fork:forkId,...source.title!==void 0?{title:source.title}:{},transcriptSha256:source.transcriptSha256,briefed:false});return{forkId,...source.title!==void 0?{title:source.title}:{},transcriptSha256:source.transcriptSha256,created:true,briefed:false}}function activeModelRoute(runtime,model){const matches=runtime?.routes?.filter(route=>route?.model===model)??[];return matches.find(route=>route.provider===runtime?.provider)??(matches.length===1?matches[0]:void 0)}function effectiveProvider(runtime,model){return activeModelRoute(runtime,model)?.provider||runtime?.provider||void 0}function describeRoute(runtime,model){const matched=activeModelRoute(runtime,model);const provider=effectiveProvider(runtime,model);if(!provider)return`model ${model} is served by an unreported provider (the Harness API named none)`;const via=matched?.api_method?` via ${matched.api_method}`:"";const unavailable=matched&&matched.available===false?" (route reports itself UNAVAILABLE)":"";return`model ${model} is served by provider ${provider}${via}${unavailable}`}function bareModelId(model){const slash=model.indexOf("/");if(slash<=0||slash===model.length-1)return{ok:true};return{ok:false,bare:model.slice(slash+1),prefix:model.slice(0,slash)}}import{constants as constants8,lstatSync as lstatSync7,mkdirSync as mkdirSync8,openSync as openSync5,writeSync}from"node:fs";import{join as join13}from"node:path";var JcodeConnectorError=class extends Error{constructor(code2,message,options){super(message,options);this.code=code2}code};var JcodeSessionsEnumerationFailure=class extends Error{constructor(sessionsPath,causeText){super(`could not enumerate stored sessions at ${sessionsPath}: ${causeText}`);this.sessionsPath=sessionsPath;this.causeText=causeText}sessionsPath;causeText;code="sessions_enumeration_failed"};var JcodeSessionsUnwritableFailure=class extends Error{constructor(sessionsPath,errnoCode){super(`stored sessions directory is not writable at ${sessionsPath} (${errnoCode})`);this.sessionsPath=sessionsPath;this.errnoCode=errnoCode}sessionsPath;errnoCode;code="sessions_unwritable"};var diagnosticLogFd;function installJcodeDiagnosticLog(home){const logs=join13(home,"logs");try{const stats=lstatSync7(logs);if(stats.isSymbolicLink())throw new Error(`refusing symlinked Jcode connector log directory: ${logs}`);if(!stats.isDirectory())throw new Error(`Jcode connector log path is not a directory: ${logs}`)}catch(error2){if(error2.code!=="ENOENT")throw error2;mkdirSync8(logs,{mode:448})}hardenPrivate(logs,"dir");const timestamp=new Date().toISOString().replace(/[:.]/g,"-");const path4=join13(logs,`connector-${timestamp}-${process.pid}.log`);diagnosticLogFd=openSync5(path4,constants8.O_WRONLY|constants8.O_CREAT|constants8.O_EXCL|(constants8.O_NOFOLLOW??0),384);hardenPrivate(path4,"file");return path4}function writeJcodeDiagnostic(message){process.stderr.write(message);if(diagnosticLogFd!==void 0)writeSync(diagnosticLogFd,message)}var JcodeReadinessProviderRefusal=class extends Error{constructor(providerCode2,parameter,value){super(`provider refused ${parameter} ${JSON.stringify(value)} (${providerCode2})`);this.providerCode=providerCode2;this.parameter=parameter;this.value=value}providerCode;parameter;value};var JcodeEffortRefusal=class extends Error{constructor(requestedTier,effectiveModel,provider,apiMethod,acceptedLadder){super("Jcode reasoning effort was refused");this.requestedTier=requestedTier;this.effectiveModel=effectiveModel;this.provider=provider;this.apiMethod=apiMethod;this.acceptedLadder=acceptedLadder}requestedTier;effectiveModel;provider;apiMethod;acceptedLadder;providerCode="invalid_request"};var JcodeEffortUnsupported=class extends Error{constructor(requestedTier,effectiveModel,provider,apiMethod){super("Jcode route does not support reasoning effort");this.requestedTier=requestedTier;this.effectiveModel=effectiveModel;this.provider=provider;this.apiMethod=apiMethod}requestedTier;effectiveModel;provider;apiMethod};var SAFE_CODE=/^[a-z][a-z0-9_]{0,63}$/;var SAFE_EFFORT_TIERS=new Set(["minimal","low","medium","high","xhigh","max","none"]);var SAFE_VALUE=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function providerBody(message){const json=message.slice(message.indexOf("{"));try{const parsed=JSON.parse(json);const body=parsed.error??parsed;if(!body||typeof body!=="object")return void 0;return body}catch{return void 0}}function providerCode(message,body){if(typeof body?.code==="string"&&SAFE_CODE.test(body.code))return body.code;const prefix=/^\s*([a-z][a-z0-9_]{0,63}):/.exec(message)?.[1];return prefix&&SAFE_CODE.test(prefix)?prefix:void 0}function classifiedCode(message,body){return providerCode(message,body)??"invalid_request"}function rejectedParameter(message){const match=/\b(model(?:[ _-]?(?:id|parameter))?|reasoning[ _-]?effort|effort(?:[ _-]?tier)?)\s*(?:=|:|is|was)?\s*["'`]?([A-Za-z0-9][A-Za-z0-9._:/-]{0,255})/i.exec(message);if(!match||!SAFE_VALUE.test(match[2]))return void 0;return{parameter:/^model/i.test(match[1])?"model":"reasoning effort",value:match[2]}}function acceptedEffortLadder(error2){if(!(error2 instanceof Error))return[];const listed=/\b(?:accepted\s+(?:tiers?|efforts?)|available)\s*:\s*([^;\r\n]{1,256})/i.exec(error2.message)?.[1];if(!listed)return[];return[...new Set(listed.split(",").map(part=>part.trim().replace(/^["'`(\[]+|["'`\])\s]+$/g,"").toLowerCase()).filter(tier=>SAFE_EFFORT_TIERS.has(tier)))]}function jcodeEffortRefusal(error2,requestedTier,identity){if(error2 instanceof HarnessError&&/^invalid_request: Reasoning effort is not supported by the current model\/profile\./.test(error2.message)){return new JcodeEffortUnsupported(requestedTier,identity.model,identity.provider,identity.apiMethod)}return new JcodeEffortRefusal(requestedTier,identity.model,identity.provider,identity.apiMethod,acceptedEffortLadder(error2))}function classifyReadinessFailure(error2){if(!(error2 instanceof HarnessError)||error2.code!=="internal")return void 0;if(error2.message.startsWith("internal: Failed to send OpenAI-compatible chat request\n")){return new JcodeConnectorError("provider_request_failed","Jcode could not send the readiness request to its provider")}if(error2.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 401 Unauthorized\r?$/m.test(error2.message)){return new JcodeConnectorError("provider_auth_refused","Jcode provider refused readiness authentication")}return void 0}function classifyReadinessProviderRefusal(error2,requestedModel){if(!(error2 instanceof HarnessError))return void 0;if(error2.code==="internal"){if(!requestedModel||!SAFE_VALUE.test(requestedModel)||!error2.message.startsWith("internal: OpenAI-compatible chat request failed\n")||!/^ status: 404 Not Found\r?$/m.test(error2.message))return void 0;const response=/^ response: (\{[^\r\n]*\})\r?$/m.exec(error2.message)?.[1];if(!response)return void 0;try{const parsed=JSON.parse(response);if(parsed?.error?.code==="model_not_found"&&parsed.error.param==="model")return new JcodeReadinessProviderRefusal("model_not_found","model",requestedModel)}catch{}return void 0}if(error2.code!=="invalid_request")return void 0;const body=providerBody(error2.message);const code2=classifiedCode(error2.message,body);const parameter=rejectedParameter(typeof body?.message==="string"?body.message:error2.message);return parameter?new JcodeReadinessProviderRefusal(code2,parameter.parameter,parameter.value):void 0}import{closeSync as closeSync5,lstatSync as lstatSync8,openSync as openSync6,readdirSync as readdirSync4,unlinkSync as unlinkSync6}from"node:fs";import{join as join14}from"node:path";function storedSessionsPath(jcodeHome){return join14(jcodeHome,"sessions")}function inspectStoredSessions(jcodeHome){const path4=storedSessionsPath(jcodeHome);try{const stats=lstatSync8(path4);if(!stats.isDirectory())return{kind:"not-a-directory",path:path4};const entries=readdirSync4(path4).length;if(entries===0)return{kind:"empty-directory",path:path4};return{kind:"populated",path:path4,entries}}catch(error2){const code2=error2.code;if(code2==="ENOENT")return{kind:"absent",path:path4};return{kind:"unreadable",path:path4,code:code2??"unknown"}}}function isEmptyStoredSessionsDirectory(inspection){return inspection.kind==="empty-directory"}var WRITE_PROBE_PREFIX=".cotal-write-probe-";function unwritableStoredSessions(inspection){if(process.platform==="win32")return void 0;if(inspection.kind!=="empty-directory"&&inspection.kind!=="populated"&&inspection.kind!=="unreadable")return void 0;const probe=join14(inspection.path,`${WRITE_PROBE_PREFIX}${process.pid}`);try{const fd=openSync6(probe,"wx",384);closeSync5(fd);unlinkSync6(probe);return void 0}catch(error2){return{path:inspection.path,code:error2.code??"unknown"}}}var STORED_SESSION_PANIC_SITE="crates/jcode-harness-api-server/src/translate.rs";var STORED_SESSION_PANIC=new RegExp(`thread '[^']*'[^\\n]* panicked at (${STORED_SESSION_PANIC_SITE.replace(/[.]/g,"\\.")}:\\d+:\\d+):\\s*\\n\\s*(chunk size must be non-zero)`);function classifyStoredSessionPanic(stderr){const match=STORED_SESSION_PANIC.exec(stderr);return match?`${match[2]} at ${match[1]}`:void 0}var UNRECOGNISED_STORED_SESSION_CAUSE="unrecognised harness failure";function boundStoredSessionCause(text2){if(/chunk size must be non-zero/.test(text2))return"chunk size must be non-zero";if(/harness connection closed/i.test(text2))return"harness connection closed";if(/write EPIPE/i.test(text2))return"write EPIPE";return UNRECOGNISED_STORED_SESSION_CAUSE}var JCODE_READINESS_TIMEOUT_MS=18e4;function attributionBlockedByOpenRun(unsettledRunDispatches,blockedForMs=0){if(unsettledRunDispatches<=0)return false;return blockedForMs<DEFERRAL_MAX_MS}var DEFERRAL_MAX_MS=readDeferralMaxMs();function readDeferralMaxMs(){const raw=process.env.COTAL_JCODE_DEFERRAL_MAX_MS?.trim();if(!raw)return 3e5;const parsed=Number(raw);if(!Number.isFinite(parsed)||parsed<=0||parsed>3e5)return 3e5;return parsed}function deferralExhausted(unsettledRunDispatches,blockedForMs){return unsettledRunDispatches>0&&blockedForMs>=DEFERRAL_MAX_MS}function exhaustedDeferralAction(bridgeRecoveryAvailable){return bridgeRecoveryAvailable?"replace-bridge":"stop-attempting"}var FALLBACK_INITIAL_MS=1e3;var FALLBACK_MAX_MS=6e4;function nextFallbackAction(s){if(s.stopping)return{action:"stop",reason:"stopping"};if(!s.initialized)return{action:"wait",reason:"not-initialized"};if(!s.hasSession)return{action:"wait",reason:"no-session"};if(s.reconnecting)return{action:"wait",reason:"reconnecting"};if(!s.sessionBusy){if(!s.driveWork)return{action:"wait",reason:"nothing-owed"};if(s.consecutiveFailures>=s.giveUpAfter)return{action:"wait",reason:"gave-up"};return{action:"drive",reason:"turn-work"}}if(s.unserved<=0)return{action:"wait",reason:"nothing-owed"};if(s.softInterruptFailed)return{action:"queue-turn",reason:"soft-interrupt-timed-out"};if(s.steering)return{action:"wait",reason:"steer-in-flight"};return{action:"steer",reason:"mid-turn-handoff"}}function nextFallbackDelay(current){const doubled=current*2;return doubled>FALLBACK_MAX_MS?FALLBACK_MAX_MS:doubled}function fallbackStillOwed(s){if(s.stopping)return false;if(s.queuedTurnTierStopped)return false;return s.unserved>0||s.driveWork}import{createHash as createHash15}from"node:crypto";function stamp(message,now){const parsed=message.timestamp?Date.parse(message.timestamp):Number.NaN;return Number.isFinite(parsed)?{value:parsed,arrival:false}:{value:now(),arrival:true}}function messageId(threadId,cursor,messageIndex,partIndex){const position=createHash15("sha256").update(`${cursor}\0${messageIndex}\0${partIndex}`).digest("base64url").slice(0,22);return`${threadId}:${position}`}function createJcodeMapper(opts){const now=opts.now??(()=>Date.now());let open6=opts.resumeRunId??null;const tools=new Set(opts.resumeTools??[]);const interrupt=(message,code2,timestamp)=>{const events=[...tools].sort().map(toolCallId=>toolCallEnd({toolCallId,timestamp}));tools.clear();open6=null;return[...events,runError({message,code:code2,timestamp})]};const map=({cursor,record:record2})=>{if(record2?.journal_fold){const runId2=open6;return runId2===null?null:{runId:runId2,events:interrupt("Jcode session journal compacted into its snapshot; records not yet emitted were lost and are not reconstructed","jcode_journal_fold",now())}}if(record2===null||typeof record2!=="object"||!Array.isArray(record2.append_messages))return null;const events=[];let runId=open6;for(const[messageIndex,message]of record2.append_messages.entries()){if(message===null||typeof message!=="object"||!Array.isArray(message.content))continue;const{value:timestamp,arrival}=stamp(message,now);const timeMeta=arrival?{cotal:{tsSource:"arrival"}}:{};const parts=message.content;const durableOutput=parts.some(part=>message.role==="assistant"?part?.type==="text"||part?.type==="reasoning"||part?.type==="reasoning_trace"||part?.type==="tool_use":message.role==="user"&&part?.type==="tool_result");if(durableOutput&&open6===null){open6=opts.mintRunId();runId=open6;events.push(runStarted({threadId:opts.threadId,runId:open6,timestamp,cotal:{runIdSource:"connector",...arrival?{tsSource:"arrival"}:{}}}))}if(open6===null)continue;runId=open6;if(message.role==="user"){const remaining=new Set(tools);const missingStart=parts.some(part=>part?.type==="tool_result"&&typeof part.tool_use_id==="string"&&part.tool_use_id.length>0&&!remaining.delete(part.tool_use_id));if(missingStart){events.push(...interrupt("Jcode tool result has no observed start; this record cannot be replayed as a complete event sequence","jcode_tool_start_missing",timestamp));return{runId,events}}}parts.forEach((part,partIndex)=>{if(part===null||typeof part!=="object")return;const observationId=messageId(opts.threadId,cursor,messageIndex,partIndex);if(message.role==="assistant"&&part.type==="text"&&typeof part.text==="string"&&part.text.length>0){events.push(textMessageStart({messageId:observationId,role:"assistant",timestamp,...timeMeta}),textMessageContent({messageId:observationId,delta:part.text,timestamp}),textMessageEnd({messageId:observationId,timestamp}));return}if(message.role==="assistant"&&(part.type==="reasoning"||part.type==="reasoning_trace")&&typeof part.text==="string"&&part.text.length>0){events.push(reasoningMessageStart({messageId:observationId,timestamp,...timeMeta}),reasoningMessageContent({messageId:observationId,delta:part.text,timestamp}),reasoningMessageEnd({messageId:observationId,timestamp}));return}if(message.role==="assistant"&&part.type==="tool_use"&&typeof part.id==="string"&&part.id.length>0){tools.add(part.id);events.push(toolCallStart({toolCallId:part.id,toolCallName:typeof part.name==="string"?part.name:"",parentMessageId:observationId,timestamp,...timeMeta}));return}if(message.role==="user"&&part.type==="tool_result"&&typeof part.tool_use_id==="string"&&part.tool_use_id.length>0){tools.delete(part.tool_use_id);events.push(toolCallEnd({toolCallId:part.tool_use_id,timestamp,...timeMeta}))}})}return runId===null||events.length===0?null:{runId,events}};return{map,forgetOpenRun(runId){if(open6===runId){open6=null;tools.clear()}}}}import{access,open as open5}from"node:fs/promises";import{constants as constants9}from"node:fs";import{basename as basename3,dirname as dirname9,join as join15}from"node:path";var JOURNAL_WAIT_MS=5e3;var RETRY_INITIAL_MS=25;var RETRY_MAX_MS=250;var delay2=ms=>new Promise(resolve4=>setTimeout(resolve4,ms));var isMissing=error2=>error2 instanceof Error&&error2.code==="ENOENT";function jcodeJournalPath(jcodeHome,sessionId){return join15(jcodeHome,"sessions",`${sessionId}.journal.jsonl`)}async function captureJcodeJournalCursor(path4,waitMs=JOURNAL_WAIT_MS){const file=new JsonlFileSource(path4);const deadline=performance.now()+waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){try{return(await file.read(void 0)).cursor}catch(error2){if(!isMissing(error2))throw error2;const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`Jcode AG-UI source: session journal did not appear within ${waitMs}ms`,{cause:error2});await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}}async function initializeJcodeEventBoundary(path4,wal){const acknowledged=wal.frontier.sourceCursor;if(acknowledged!==void 0)return acknowledged;const boundary=await captureJcodeJournalCursor(path4);await wal.advanceCursorOnly(boundary);return boundary}var JcodeJournalSource=class{constructor(path4,waitMs=JOURNAL_WAIT_MS){this.path=path4;this.waitMs=waitMs;this.file=new JsonlFileSource(path4)}path;waitMs;kind="jcode-session-journal";file;end(){return this.file.end()}async read(cursor){if(cursor!==void 0){try{return await this.file.read(cursor)}catch(error2){if(!isMissing(error2)&&!(error2 instanceof JsonlFileResetError))throw error2;const fresh=await this.foldedSince();if(fresh===void 0)throw error2;if(fresh===null){return{cursor,records:[{cursor,value:{journal_fold:{}}}]}}return{cursor:fresh.fresh.cursor,records:[{cursor:fresh.beginning,value:{journal_fold:{}}},...fresh.fresh.records]}}}const deadline=performance.now()+this.waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){try{await access(this.path,constants9.R_OK);return await this.file.readFromBeginning()}catch(error2){if(!isMissing(error2))throw error2;const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`Jcode AG-UI source: session journal did not appear within ${this.waitMs}ms; refusing to lose the first run`,{cause:error2});await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}}async hasSessionSnapshot(){const sessionId=basename3(this.path,".journal.jsonl");const snapshot=join15(dirname9(this.path),`${sessionId}.json`);try{const file=await open5(snapshot,constants9.O_RDONLY|(constants9.O_NOFOLLOW??0));try{if(!(await file.stat()).isFile())throw new Error("Jcode AG-UI source: session snapshot is not a regular file");const parsed=JSON.parse(await file.readFile("utf8"));if(parsed===null||typeof parsed!=="object"||parsed.id!==sessionId||!Array.isArray(parsed.messages))throw new Error("Jcode AG-UI source: checkpoint snapshot does not identify this session");return true}finally{await file.close()}}catch(error2){if(isMissing(error2))return false;throw error2}}async foldedSince(){const deadline=performance.now()+this.waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){if(await this.hasSessionSnapshot()){try{const beginning=await this.file.cursorAtBeginning();const fresh=await this.file.read(beginning);return{beginning,fresh}}catch(error2){if(!isMissing(error2)&&!(error2 instanceof JsonlFileResetError))throw error2;return null}}const remaining=deadline-performance.now();if(remaining<=0)return void 0;await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}};function positionedJcodeJournalSource(source){return{kind:source.kind,end:()=>source.end(),async read(cursor){const read=await source.read(cursor);return{cursor:read.cursor,records:read.records.map(record2=>({cursor:record2.cursor,value:{cursor:record2.cursor,record:record2.value}})),...read.unreadable?{unreadable:read.unreadable}:{}}}}}var MAX_RELAY_BYTES=4*1024*1024;var RELAY_REBIND_POLL_MS=1e3;var RUN_ACCEPT_WINDOW_MS=1e4;var BRIDGE_RECOVERY_WINDOW_MS=6e4;function readinessTurnTimeoutMs(){const raw=process.env.COTAL_JCODE_READINESS_TIMEOUT_MS?.trim();if(!raw)return JCODE_READINESS_TIMEOUT_MS;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<=0)throw new Error(`jcode connector: COTAL_JCODE_READINESS_TIMEOUT_MS ${JSON.stringify(raw)} is not a positive integer`);return parsed}function requestTimeoutOverrideMs(){const raw=process.env.COTAL_JCODE_REQUEST_TIMEOUT_MS?.trim();if(!raw)return void 0;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<=0)throw new Error(`jcode connector: COTAL_JCODE_REQUEST_TIMEOUT_MS ${JSON.stringify(raw)} is not a positive integer`);return parsed}var PERMANENT_BRIDGE_RECOVERY_CODES=new Set(["handshake_failed","invalid_instance_home","invalid_request","jcode_not_found","unknown_request","unknown_session","unsupported_version"]);var PERMANENT_BRIDGE_CONNECT_CAUSE_CODES=new Set(["EACCES"]);function permanentBridgeRecoveryFailure(error2){if(!(error2 instanceof HarnessError))return false;if(PERMANENT_BRIDGE_RECOVERY_CODES.has(error2.code))return true;if(error2.code==="connect_failed")return PERMANENT_BRIDGE_CONNECT_CAUSE_CODES.has(error2.cause?.code??"");return false}var PRESENCE_CONDITION_CODES=new Set(["rate_limit","overloaded","auth","billing","budget","context","model","request","server","retrying","approval","input","failed"]);function jcodeTurnCondition(error2,since=Date.now()){if(!(error2 instanceof HarnessError))return void 0;const source=String(error2.code);const code2=PRESENCE_CONDITION_CODES.has(source)?source:"failed";return{code:code2,source,message:error2.message,since}}function privateAgentHome(space2,name){const root=process.env.COTAL_JCODE_HOME?.trim();if(!root)throw new Error("COTAL_JCODE_HOME is not set \u2014 the connector must pin the agent's Jcode home");const managedRoot=join16(root,".cotal","jcode");const home=jcodeSeatHome(root,space2,name);if(!resolve3(home).startsWith(resolve3(managedRoot)+sep2))throw new Error(`jcode home ${home} escapes ${managedRoot} \u2014 refusing`);for(const path4 of[join16(root,".cotal"),managedRoot,home]){try{if(lstatSync9(path4).isSymbolicLink())throw new Error(`refusing symlinked managed path: ${path4}`)}catch(error2){if(error2.code!=="ENOENT")throw error2}}mkdirSync9(home,{recursive:true,mode:448});hardenPrivate(home,"dir");return home}function publicConfig(config2){return{...config2,creds:config2.creds||config2.userAuth?"managed":void 0,userAuth:void 0,token:void 0,user:void 0,pass:void 0,servers:"held by the Jcode host",feedbackKey:void 0}}function assertNoProjectMcpConfig(cwd){const found=[".jcode/mcp.json",".mcp.json",".claude/mcp.json"].filter(relative2=>existsSync2(join16(cwd,relative2)));if(found.length)throw new Error(`jcode connector: project MCP configuration (${found.join(", ")}) is not supported \u2014 Jcode overlays it over the managed cotal MCP bridge. Remove it or use a workspace without project MCP configuration; tool-sharing is not implemented.`)}function mcpEntry(){const built=import.meta.url.includes("/dist/");if(built)return{command:process.execPath,args:[filePath("mcp.js")]};return{command:filePath("../node_modules/.bin/tsx"),args:[filePath("mcp-main.ts")]}}function filePath(relative2){return fileURLToPath(new URL(relative2,import.meta.url))}function writeMcpConfig(home,relay,config2){const{command,args}=mcpEntry();const mcp={servers:{cotal:{command,args,env:{COTAL_JCODE_MCP_SOCKET:relay.path,COTAL_JCODE_MCP_TOKEN:relay.token,COTAL_JCODE_MCP_CONFIG:JSON.stringify(publicConfig(config2))},shared:true}}};const path4=join16(home,"mcp.json");rmSync5(path4,{force:true});let fd;try{fd=openSync7(path4,"wx",384)}catch(error2){throw new Error(`refusing to write Jcode MCP config at ${path4}: ${error2.message}`)}try{writeFileSync4(fd,JSON.stringify(mcp))}finally{closeSync6(fd)}if(process.platform!=="win32")hardenPrivate(path4,"file")}function relayEndpoint(space2,name){const token2=randomBytes6(32).toString("base64url");const id2=createHash16("sha256").update(`${space2}\0${name}\0${process.pid}\0${token2}`).digest("base64url").slice(0,32);if(process.platform==="win32")return{dir:"",path:`\\\\.\\pipe\\cotal-jcode-${id2}`,token:token2};const dir=join16("/tmp",`cotal-jcode-${id2}`);return{dir,path:join16(dir,"relay.sock"),token:token2}}function ensureRelayDirectory(endpoint){if(process.platform==="win32")return;mkdirSync9(endpoint.dir,{recursive:true,mode:448});hardenPrivate(endpoint.dir,"dir")}function instructions(config2,persona){const mesh=`You are connected to the Cotal mesh as "${config2.name}"${config2.role?` (role: ${config2.role})`:""} in space "${config2.space}". ${ORIENTATION_BOOTSTRAP} ${feedbackLine(config2)}${MESH_FIRST_STEER} ${WORKFLOW_STEER} ${CHANNEL_GUIDANCE} Peer messages are delivered into your turns as blocks marked \u{1F4E8}. Reply with cotal_dm (privately, to the sender), cotal_send (to a channel), or cotal_anycast (to a role); use cotal_roster to see who is present and cotal_status to report what you are doing. Reply only when a reply is actually needed \u2014 silent acknowledgement is correct, and @-mention a peer only when you need that peer to act now.`;return persona?`${persona}
174
+ `)}function readLaunchRecord(home){let parsed;try{parsed=JSON.parse(readFileSync6(join11(home,LAUNCH_RECORD_FILE),"utf8"))}catch{return void 0}const record2=parsed;const identity=record2?.identity;const host=record2?.host;if(typeof identity!=="string"||!identity)return void 0;return isPid(host?.pid)&&typeof host?.start==="string"&&host.start?{identity,host:{pid:host.pid,start:host.start}}:void 0}async function stopOrphanedTree(options){const{home,gracefulWaitMs=3e3,killWaitMs=2e3}=options;const record2=readLaunchRecord(home);if(!record2)return[];if(alive(record2.host.pid))return[];const targets=captureLaunchProcesses(record2.identity).filter(identity=>identity.pid!==process.pid&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(!targets.length)return[];signalTree(targets,"SIGTERM");if(!await waitGone(targets,gracefulWaitMs)){signalTree(targets.filter(alive),"SIGKILL");if(!await waitGone(targets,killWaitMs))throw new Error(`jcode connector: a previous lifecycle's Jcode processes survived teardown (pids ${targets.filter(alive).join(", ")}) \u2014 this seat's runtime directory is still held`)}return targets}async function stopPrivateTree(options){const{jcodeHome,launch,identityValue,gracefulWaitMs=3e3,killWaitMs=2e3,settleMs=500,identityProbe=processIdentityProbe}=options;const owned=new Map;const refreshOwned=()=>{for(const identity of captureLaunchProcesses(identityValue,identityProbe))owned.set(identity.pid,identity)};refreshOwned();if(alive(launch.pid)&&processMatches(launch)&&launchIdentityProof(launch.pid,identityValue,identityProbe)===false)throw new Error(`jcode connector: spawned Jcode bridge ${launch.pid} does not carry its launch-bound identity \u2014 refusing unsafe teardown`);if(processMatches(launch)){signalPid(launch.pid,"SIGTERM");if(!await waitGone([launch.pid],gracefulWaitMs)){signalPid(launch.pid,"SIGKILL");if(!await waitGone([launch.pid],killWaitMs))throw new Error(`jcode connector: Jcode bridge survived teardown (pid ${launch.pid}) \u2014 the seat's tree is NOT stopped`)}}let quietSince=Date.now();let capturedAfterBridge=false;for(;;){if(capturedAfterBridge)refreshOwned();else capturedAfterBridge=true;const recorded=recordedTreePids(jcodeHome);const targets=recorded.map(pid=>owned.get(pid)).filter(identity=>identity!==void 0&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(targets.length){signalTree(targets,"SIGTERM");if(!await waitGone(targets,gracefulWaitMs)){signalTree(targets.filter(alive),"SIGKILL");if(!await waitGone(targets,killWaitMs))throw new Error(`jcode connector: private Jcode processes survived teardown (pids ${targets.filter(alive).join(", ")}) \u2014 the seat's tree is NOT stopped`)}quietSince=Date.now();continue}if(Date.now()-quietSince<settleMs){await new Promise(resolve4=>setTimeout(resolve4,25));continue}const unrecorded=[...owned.values()].filter(identity=>identity.pid!==launch.pid&&processMatches(identity)&&alive(identity.pid)).map(identity=>identity.pid);if(!unrecorded.length)return;signalTree(unrecorded,"SIGTERM");if(!await waitGone(unrecorded,gracefulWaitMs)){signalTree(unrecorded.filter(alive),"SIGKILL");if(!await waitGone(unrecorded,killWaitMs))throw new Error(`jcode connector: unrecorded launch-owned Jcode processes survived teardown (pids ${unrecorded.filter(alive).join(", ")}) \u2014 the seat's tree is NOT stopped`)}quietSince=Date.now()}}var replies=new WeakMap;async function connectSteerClient(socketPath,requestTimeoutMs){const socket=await unixSocketTransport(socketPath);const state={late:new Map};let client;try{client=await JcodeClient.connect({socketPath,...requestTimeoutMs===void 0?{}:{requestTimeoutMs},transport:{write(data){const frame=JSON.parse(data);if(frame.req==="soft_interrupt")state.capture?.(frame.id);socket.write(data)},onData:listener=>socket.onData(listener),onClose:listener=>socket.onClose(listener),close:()=>socket.close()}})}catch(error2){socket.close();throw error2}replies.set(client,state);client.on("event",frame=>{if(typeof frame.reply_to!=="number")return;const settle=state.late.get(frame.reply_to);if(!settle)return;state.late.delete(frame.reply_to);settle(frame.ev==="ok")});client.on("close",()=>state.late.clear());return client}function softInterruptWithLateReply(client,session,content,settle){const state=replies.get(client);if(!state)throw new Error("jcode connector: steer client has no request observer");let id2;state.capture=value=>{id2=value};let request;try{request=client.softInterrupt(session,content,false)}finally{state.capture=void 0}let disposed=false;const dispose=()=>{disposed=true;if(id2!==void 0)state.late.delete(id2)};request=request.catch(error2=>{if(!disposed&&id2!==void 0&&error2 instanceof HarnessError&&error2.code==="timeout")state.late.set(id2,settle);throw error2});return{request,dispose}}function chooseSessionToResume(candidates,cwd){if(!candidates?.length)return void 0;const usable=candidates.filter(c=>typeof c.session_id==="string"&&c.session_id.length>0&&c.archived!==true&&typeof c.working_dir==="string"&&c.working_dir===cwd&&typeof c.transcript_bytes==="number"&&c.transcript_bytes>0);if(!usable.length)return void 0;return[...usable].sort((a,b)=>(b.transcript_bytes??0)-(a.transcript_bytes??0)||a.session_id.localeCompare(b.session_id))[0]}import{createHash as createHash14,randomBytes as randomBytes5}from"node:crypto";import{existsSync,mkdirSync as mkdirSync7,readFileSync as readFileSync7,renameSync as renameSync3,writeFileSync as writeFileSync3}from"node:fs";import{join as join12}from"node:path";var SESSION_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,199}$/;var MARKER="cotal-resume.json";var STABLE_READ_ATTEMPTS=5;var TITLE_MAX=1024;function jcodeSeatHome(root,space2,name){const slug=`${space2}-${name}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);const key=createHash14("sha256").update(`${space2}\0${name}`).digest("hex").slice(0,12);return join12(root,".cotal","jcode",`${slug||"agent"}-${key}`)}function code(error2){return error2.code??error2.message}var RawJSON=JSON;function parseTranscript(text2){return JSON.parse(text2,(_key,value,context)=>typeof value==="number"&&context?.source!==void 0&&context.source!==String(value)?RawJSON.rawJSON(context.source):value)}var U64_MAX=2n**64n-1n;var isRecord2=value=>typeof value==="object"&&value!==null&&!Array.isArray(value)&&!RawJSON.isRawJSON(value);var isString=value=>typeof value==="string";var isCount=value=>{const spelling=RawJSON.isRawJSON(value)?value.rawJSON:typeof value==="number"?String(value):"";return/^(0|[1-9]\d*)$/.test(spelling)&&BigInt(spelling)<=U64_MAX};var optional2=(value,check)=>value===void 0||value===null||check(value);var RFC3339=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;function instant(value){const match=isString(value)?RFC3339.exec(value):null;const seconds=match?Date.parse(`${match[1]}${match[3]}`):NaN;return Number.isNaN(seconds)?void 0:[seconds,Number((match[2]??"").padEnd(9,"0"))]}var notAfter=(a,b)=>a[0]<b[0]||a[0]===b[0]&&a[1]<=b[1];var CONTENT_BLOCKS={text:b=>isString(b.text)&&optional2(b.cache_control,c=>isRecord2(c)&&isString(c.type)&&optional2(c.ttl,isString)),reasoning:b=>isString(b.text),reasoning_trace:b=>isString(b.text),anthropic_thinking:b=>isString(b.thinking)&&isString(b.signature),open_a_i_reasoning:b=>isString(b.id)&&Array.isArray(b.summary)&&b.summary.every(isString)&&optional2(b.encrypted_content,isString)&&optional2(b.status,isString),tool_use:b=>isString(b.id)&&isString(b.name)&&"input"in b&&optional2(b.thought_signature,isString),tool_result:b=>isString(b.tool_use_id)&&isString(b.content)&&optional2(b.is_error,v=>typeof v==="boolean"),image:b=>isString(b.media_type)&&isString(b.data),open_a_i_compaction:b=>isString(b.encrypted_content),tool_reference:b=>isString(b.tool_use_id)&&isString(b.tool_name),provider_native:b=>isString(b.provider)&&"item"in b};var isTokenUsage=u=>isRecord2(u)&&isCount(u.input_tokens)&&isCount(u.output_tokens)&&["prompt_tokens","cache_read_input_tokens","cache_creation_input_tokens"].every(key=>optional2(u[key],isCount));var isCompaction=value=>isRecord2(value)&&isString(value.summary_text)&&optional2(value.openai_encrypted_content,isString)&&isCount(value.covers_up_to_turn)&&isCount(value.original_turn_count)&&isCount(value.compacted_count);function messageFault(value){if(!isRecord2(value))return"is not an object";if(!isString(value.id))return"has no string id";if(value.role!=="user"&&value.role!=="assistant")return`has role ${JSON.stringify(value.role)}, not user or assistant`;if(!Array.isArray(value.content))return"has content that is not an array";for(const[index2,block]of value.content.entries()){const type=isRecord2(block)?block.type:void 0;if(!isString(type)||!Object.hasOwn(CONTENT_BLOCKS,type)||!CONTENT_BLOCKS[type](block))return`has a content block ${index2+1} that is not a Jcode ${isString(type)?`${JSON.stringify(type)} block`:"content block"}`}if(!optional2(value.display_role,v=>v==="system"||v==="background_task"))return"has an unknown display_role";if(!optional2(value.timestamp,v=>instant(v)!==void 0))return"has a timestamp that is not an RFC 3339 time";if(!optional2(value.tool_duration_ms,isCount))return"has a tool_duration_ms that is not a count";if(!optional2(value.token_usage,isTokenUsage))return"has a token_usage Jcode cannot read";return void 0}function readOptional(path4,refuse2){try{return readFileSync7(path4)}catch(error2){if(error2.code!=="ENOENT")refuse2(`${path4} could not be read (${code(error2)})`);return void 0}}function readJcodeForkSource(sourceHome,sessionId){if(!SESSION_ID.test(sessionId)||sessionId.includes(".."))throw new Error(`jcode connector: cannot resume ${JSON.stringify(sessionId)}: not a Jcode session id`);const snapshotPath=join12(sourceHome,"sessions",`${sessionId}.json`);const journalPath=join12(sourceHome,"sessions",`${sessionId}.journal.jsonl`);const refuse2=why=>{throw new Error(`jcode connector: cannot resume session ${sessionId}: ${why}`)};const readSnapshot=()=>{try{return readFileSync7(snapshotPath)}catch(error2){return refuse2(`no readable transcript at ${snapshotPath} (${code(error2)})`)}};let previous;for(let attempt=0;attempt<STABLE_READ_ATTEMPTS;attempt++){const read={snapshot:readSnapshot(),journal:readOptional(journalPath,refuse2)};const same=previous!==void 0&&read.snapshot.equals(previous.snapshot)&&(read.journal===void 0?previous.journal===void 0:previous.journal!==void 0&&read.journal.equals(previous.journal));previous=read;if(!same)continue;const parsed=parseJcodeSource(sessionId,snapshotPath,journalPath,read.snapshot,read.journal,refuse2);if(parsed)return parsed;previous=void 0}return refuse2(`${snapshotPath} kept changing while it was read, or its journal predates the snapshot (a Jcode checkpoint in progress); retry the resume`)}function parseJcodeSource(sessionId,snapshotPath,journalPath,snapshot,journal,refuse2){let session;try{session=parseTranscript(snapshot.toString("utf8"))}catch(error2){return refuse2(`${snapshotPath} is not valid JSON (${error2.message})`)}if(!isRecord2(session)||session.id!==sessionId||!Array.isArray(session.messages))refuse2(`${snapshotPath} is not a Jcode session snapshot for that id`);const checkFields=(where,fields)=>{for(const key of["title","system_prompt","model"])if(!optional2(fields[key],isString))refuse2(`${where} has a non-string ${key}`);if(!optional2(fields.compaction,isCompaction))refuse2(`${where} has a compaction Jcode cannot read`);return instant(fields.updated_at)??refuse2(`${where} has no updated_at Jcode can read`)};const checkMessages=(where,list)=>{for(const[index2,message]of list.entries()){const fault=messageFault(message);if(fault)refuse2(`message ${index2+1} of ${where} ${fault}`)}};const snapshotAt=checkFields(snapshotPath,session);const messages=[...session.messages];checkMessages(snapshotPath,messages);const seen=new Set(messages.map(message=>message.id));const lines=journal?journal.toString("utf8").split("\n").filter(line=>line.trim()):[];for(const[index2,line]of lines.entries()){const where=`line ${index2+1} of ${journalPath}`;let entry;try{entry=parseTranscript(line)}catch(error2){return refuse2(`${where} is not valid JSON (${error2.message})`)}if(!isRecord2(entry)||!isRecord2(entry.meta))return refuse2(`${where} has no metadata`);if(notAfter(checkFields(where,entry.meta),snapshotAt))return void 0;const appended=entry.append_messages??[];if(!Array.isArray(appended))return refuse2(`${where} has append_messages that are not a list`);checkMessages(`append_messages on ${where}`,appended);for(const message of appended){if(seen.has(message.id))return void 0;seen.add(message.id)}for(const key of["title","system_prompt","compaction","model"])session[key]=entry.meta[key]??null;messages.push(...appended)}if(typeof session.title==="string"&&session.title.length>TITLE_MAX)refuse2(`its title is ${session.title.length} characters, more than the ${TITLE_MAX} a resume records with the fork`);const hash=createHash14("sha256").update(snapshot);if(journal)hash.update(journal);return{sessionId,...typeof session.title==="string"?{title:session.title}:{},transcriptSha256:hash.digest("hex"),messages,compaction:session.compaction??void 0,systemPrompt:session.system_prompt??void 0,model:session.model??void 0}}function writeMarker(seatHome,marker){const path4=join12(seatHome,MARKER);const tmp=`${path4}.${process.pid}.${randomBytes5(4).toString("hex")}.tmp`;writeFileSync3(tmp,JSON.stringify(marker),{mode:384,flag:"wx"});renameSync3(tmp,path4)}function ownedJcodeFork(seatHome,sessionId){const markerPath=join12(seatHome,MARKER);let raw;try{raw=readFileSync7(markerPath,"utf8")}catch(error2){if(error2.code==="ENOENT")return void 0;throw new Error(`jcode connector: ${markerPath} could not be read (${code(error2)})`)}let marker;try{marker=JSON.parse(raw)}catch(error2){throw new Error(`jcode connector: ${markerPath} is not valid JSON (${error2.message}); remove it to fork session ${sessionId} again`)}if(!isRecord2(marker))throw new Error(`jcode connector: ${markerPath} is not a fork record; remove it to fork session ${sessionId} again`);if(marker.source!==sessionId||typeof marker.fork!=="string"||!SESSION_ID.test(marker.fork)||!existsSync(join12(seatHome,"sessions",`${marker.fork}.json`)))return void 0;return{source:marker.source,fork:marker.fork,...typeof marker.title==="string"?{title:marker.title}:{},transcriptSha256:String(marker.transcriptSha256??""),briefed:marker.briefed===true}}function markJcodeForkBriefed(seatHome,sessionId){const marker=ownedJcodeFork(seatHome,sessionId);if(!marker)throw new Error(`jcode connector: the seat's fork of ${sessionId} is gone from ${seatHome}`);if(!marker.briefed)writeMarker(seatHome,{...marker,briefed:true})}function forkJcodeSession(opts){const sessions=join12(opts.seatHome,"sessions");const owned=ownedJcodeFork(opts.seatHome,opts.sessionId);if(owned)return{forkId:owned.fork,...owned.title!==void 0?{title:owned.title}:{},transcriptSha256:owned.transcriptSha256,created:false,briefed:owned.briefed};const source=readJcodeForkSource(opts.sourceHome,opts.sessionId);const now=new Date().toISOString();const word=/^session_([^_]+)_/.exec(opts.sessionId)?.[1]??"fork";const forkId=`session_${word}_${Date.now()}_${randomBytes5(8).toString("hex")}`;const fork={id:forkId,parent_id:opts.sessionId,title:null,created_at:now,updated_at:now,messages:source.messages,...source.systemPrompt!==void 0?{system_prompt:source.systemPrompt}:{},...source.compaction!==void 0?{compaction:source.compaction}:{},...source.model!==void 0?{model:source.model}:{},working_dir:opts.cwd,status:"Closed"};mkdirSync7(sessions,{recursive:true,mode:448});const target2=join12(sessions,`${forkId}.json`);writeFileSync3(`${target2}.tmp`,JSON.stringify(fork),{mode:384,flag:"wx"});renameSync3(`${target2}.tmp`,target2);writeMarker(opts.seatHome,{source:opts.sessionId,fork:forkId,...source.title!==void 0?{title:source.title}:{},transcriptSha256:source.transcriptSha256,briefed:false});return{forkId,...source.title!==void 0?{title:source.title}:{},transcriptSha256:source.transcriptSha256,created:true,briefed:false}}function activeModelRoute(runtime,model){const matches=runtime?.routes?.filter(route=>route?.model===model)??[];return matches.find(route=>route.provider===runtime?.provider)??(matches.length===1?matches[0]:void 0)}function effectiveProvider(runtime,model){return activeModelRoute(runtime,model)?.provider||runtime?.provider||void 0}function describeRoute(runtime,model){const matched=activeModelRoute(runtime,model);const provider=effectiveProvider(runtime,model);if(!provider)return`model ${model} is served by an unreported provider (the Harness API named none)`;const via=matched?.api_method?` via ${matched.api_method}`:"";const unavailable=matched&&matched.available===false?" (route reports itself UNAVAILABLE)":"";return`model ${model} is served by provider ${provider}${via}${unavailable}`}function bareModelId(model){const slash=model.indexOf("/");if(slash<=0||slash===model.length-1)return{ok:true};return{ok:false,bare:model.slice(slash+1),prefix:model.slice(0,slash)}}import{constants as constants8,lstatSync as lstatSync7,mkdirSync as mkdirSync8,openSync as openSync5,writeSync}from"node:fs";import{join as join13}from"node:path";var JcodeConnectorError=class extends Error{constructor(code2,message,options){super(message,options);this.code=code2}code};var JcodeSessionsEnumerationFailure=class extends Error{constructor(sessionsPath,causeText){super(`could not enumerate stored sessions at ${sessionsPath}: ${causeText}`);this.sessionsPath=sessionsPath;this.causeText=causeText}sessionsPath;causeText;code="sessions_enumeration_failed"};var JcodeSessionsUnwritableFailure=class extends Error{constructor(sessionsPath,errnoCode){super(`stored sessions directory is not writable at ${sessionsPath} (${errnoCode})`);this.sessionsPath=sessionsPath;this.errnoCode=errnoCode}sessionsPath;errnoCode;code="sessions_unwritable"};var diagnosticLogFd;function installJcodeDiagnosticLog(home){const logs=join13(home,"logs");try{const stats=lstatSync7(logs);if(stats.isSymbolicLink())throw new Error(`refusing symlinked Jcode connector log directory: ${logs}`);if(!stats.isDirectory())throw new Error(`Jcode connector log path is not a directory: ${logs}`)}catch(error2){if(error2.code!=="ENOENT")throw error2;mkdirSync8(logs,{mode:448})}hardenPrivate(logs,"dir");const timestamp=new Date().toISOString().replace(/[:.]/g,"-");const path4=join13(logs,`connector-${timestamp}-${process.pid}.log`);diagnosticLogFd=openSync5(path4,constants8.O_WRONLY|constants8.O_CREAT|constants8.O_EXCL|(constants8.O_NOFOLLOW??0),384);hardenPrivate(path4,"file");return path4}function writeJcodeDiagnostic(message){process.stderr.write(message);if(diagnosticLogFd!==void 0)writeSync(diagnosticLogFd,message)}var JcodeReadinessProviderRefusal=class extends Error{constructor(providerCode2,parameter,value){super(`provider refused ${parameter} ${JSON.stringify(value)} (${providerCode2})`);this.providerCode=providerCode2;this.parameter=parameter;this.value=value}providerCode;parameter;value};var JcodeEffortRefusal=class extends Error{constructor(requestedTier,effectiveModel,provider,apiMethod,acceptedLadder){super("Jcode reasoning effort was refused");this.requestedTier=requestedTier;this.effectiveModel=effectiveModel;this.provider=provider;this.apiMethod=apiMethod;this.acceptedLadder=acceptedLadder}requestedTier;effectiveModel;provider;apiMethod;acceptedLadder;providerCode="invalid_request"};var JcodeEffortUnsupported=class extends Error{constructor(requestedTier,effectiveModel,provider,apiMethod){super("Jcode route does not support reasoning effort");this.requestedTier=requestedTier;this.effectiveModel=effectiveModel;this.provider=provider;this.apiMethod=apiMethod}requestedTier;effectiveModel;provider;apiMethod};var SAFE_CODE=/^[a-z][a-z0-9_]{0,63}$/;var SAFE_EFFORT_TIERS=new Set(["minimal","low","medium","high","xhigh","max","none"]);var SAFE_VALUE=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/;function providerBody(message){const json=message.slice(message.indexOf("{"));try{const parsed=JSON.parse(json);const body=parsed.error??parsed;if(!body||typeof body!=="object")return void 0;return body}catch{return void 0}}function providerCode(message,body){if(typeof body?.code==="string"&&SAFE_CODE.test(body.code))return body.code;const prefix=/^\s*([a-z][a-z0-9_]{0,63}):/.exec(message)?.[1];return prefix&&SAFE_CODE.test(prefix)?prefix:void 0}function classifiedCode(message,body){return providerCode(message,body)??"invalid_request"}function rejectedParameter(message){const match=/\b(model(?:[ _-]?(?:id|parameter))?|reasoning[ _-]?effort|effort(?:[ _-]?tier)?)\s*(?:=|:|is|was)?\s*["'`]?([A-Za-z0-9][A-Za-z0-9._:/-]{0,255})/i.exec(message);if(!match||!SAFE_VALUE.test(match[2]))return void 0;return{parameter:/^model/i.test(match[1])?"model":"reasoning effort",value:match[2]}}function acceptedEffortLadder(error2){if(!(error2 instanceof Error))return[];const listed=/\b(?:accepted\s+(?:tiers?|efforts?)|available)\s*:\s*([^;\r\n]{1,256})/i.exec(error2.message)?.[1];if(!listed)return[];return[...new Set(listed.split(",").map(part=>part.trim().replace(/^["'`(\[]+|["'`\])\s]+$/g,"").toLowerCase()).filter(tier=>SAFE_EFFORT_TIERS.has(tier)))]}function jcodeEffortRefusal(error2,requestedTier,identity){if(error2 instanceof HarnessError&&/^invalid_request: Reasoning effort is not supported by the current model\/profile\./.test(error2.message)){return new JcodeEffortUnsupported(requestedTier,identity.model,identity.provider,identity.apiMethod)}return new JcodeEffortRefusal(requestedTier,identity.model,identity.provider,identity.apiMethod,acceptedEffortLadder(error2))}function classifyReadinessFailure(error2){if(!(error2 instanceof HarnessError)||error2.code!=="internal")return void 0;if(error2.message.startsWith("internal: Failed to send OpenAI-compatible chat request\n")){return new JcodeConnectorError("provider_request_failed","Jcode could not send the readiness request to its provider")}if(error2.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 401 Unauthorized\r?$/m.test(error2.message)){return new JcodeConnectorError("provider_auth_refused","Jcode provider refused readiness authentication")}if(error2.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 402 Payment Required\r?$/m.test(error2.message)){return new JcodeConnectorError("provider_payment_required","Jcode provider refused the readiness request for payment")}return void 0}function classifyReadinessProviderRefusal(error2,requestedModel){if(!(error2 instanceof HarnessError))return void 0;if(error2.code==="internal"){if(!requestedModel||!SAFE_VALUE.test(requestedModel)||!error2.message.startsWith("internal: OpenAI-compatible chat request failed\n")||!/^ status: 404 Not Found\r?$/m.test(error2.message))return void 0;const response=/^ response: (\{[^\r\n]*\})\r?$/m.exec(error2.message)?.[1];if(!response)return void 0;try{const parsed=JSON.parse(response);if(parsed?.error?.code==="model_not_found"&&parsed.error.param==="model")return new JcodeReadinessProviderRefusal("model_not_found","model",requestedModel)}catch{}return void 0}if(error2.code!=="invalid_request")return void 0;const body=providerBody(error2.message);const code2=classifiedCode(error2.message,body);const parameter=rejectedParameter(typeof body?.message==="string"?body.message:error2.message);return parameter?new JcodeReadinessProviderRefusal(code2,parameter.parameter,parameter.value):void 0}import{closeSync as closeSync5,lstatSync as lstatSync8,openSync as openSync6,readdirSync as readdirSync4,unlinkSync as unlinkSync6}from"node:fs";import{join as join14}from"node:path";function storedSessionsPath(jcodeHome){return join14(jcodeHome,"sessions")}function inspectStoredSessions(jcodeHome){const path4=storedSessionsPath(jcodeHome);try{const stats=lstatSync8(path4);if(!stats.isDirectory())return{kind:"not-a-directory",path:path4};const entries=readdirSync4(path4).length;if(entries===0)return{kind:"empty-directory",path:path4};return{kind:"populated",path:path4,entries}}catch(error2){const code2=error2.code;if(code2==="ENOENT")return{kind:"absent",path:path4};return{kind:"unreadable",path:path4,code:code2??"unknown"}}}function isEmptyStoredSessionsDirectory(inspection){return inspection.kind==="empty-directory"}var WRITE_PROBE_PREFIX=".cotal-write-probe-";function unwritableStoredSessions(inspection){if(process.platform==="win32")return void 0;if(inspection.kind!=="empty-directory"&&inspection.kind!=="populated"&&inspection.kind!=="unreadable")return void 0;const probe=join14(inspection.path,`${WRITE_PROBE_PREFIX}${process.pid}`);try{const fd=openSync6(probe,"wx",384);closeSync5(fd);unlinkSync6(probe);return void 0}catch(error2){return{path:inspection.path,code:error2.code??"unknown"}}}var STORED_SESSION_PANIC_SITE="crates/jcode-harness-api-server/src/translate.rs";var STORED_SESSION_PANIC=new RegExp(`thread '[^']*'[^\\n]* panicked at (${STORED_SESSION_PANIC_SITE.replace(/[.]/g,"\\.")}:\\d+:\\d+):\\s*\\n\\s*(chunk size must be non-zero)`);function classifyStoredSessionPanic(stderr){const match=STORED_SESSION_PANIC.exec(stderr);return match?`${match[2]} at ${match[1]}`:void 0}var UNRECOGNISED_STORED_SESSION_CAUSE="unrecognised harness failure";function boundStoredSessionCause(text2){if(/chunk size must be non-zero/.test(text2))return"chunk size must be non-zero";if(/harness connection closed/i.test(text2))return"harness connection closed";if(/write EPIPE/i.test(text2))return"write EPIPE";return UNRECOGNISED_STORED_SESSION_CAUSE}var JCODE_READINESS_TIMEOUT_MS=18e4;function attributionBlockedByOpenRun(unsettledRunDispatches,blockedForMs=0){if(unsettledRunDispatches<=0)return false;return blockedForMs<DEFERRAL_MAX_MS}var DEFERRAL_MAX_MS=readDeferralMaxMs();function readDeferralMaxMs(){const raw=process.env.COTAL_JCODE_DEFERRAL_MAX_MS?.trim();if(!raw)return 3e5;const parsed=Number(raw);if(!Number.isFinite(parsed)||parsed<=0||parsed>3e5)return 3e5;return parsed}function deferralExhausted(unsettledRunDispatches,blockedForMs){return unsettledRunDispatches>0&&blockedForMs>=DEFERRAL_MAX_MS}function exhaustedDeferralAction(bridgeRecoveryAvailable){return bridgeRecoveryAvailable?"replace-bridge":"stop-attempting"}var FALLBACK_INITIAL_MS=1e3;var FALLBACK_MAX_MS=6e4;function nextFallbackAction(s){if(s.stopping)return{action:"stop",reason:"stopping"};if(!s.initialized)return{action:"wait",reason:"not-initialized"};if(!s.hasSession)return{action:"wait",reason:"no-session"};if(s.reconnecting)return{action:"wait",reason:"reconnecting"};if(!s.sessionBusy){if(!s.driveWork)return{action:"wait",reason:"nothing-owed"};if(s.consecutiveFailures>=s.giveUpAfter)return{action:"wait",reason:"gave-up"};return{action:"drive",reason:"turn-work"}}if(s.unserved<=0)return{action:"wait",reason:"nothing-owed"};if(s.softInterruptFailed)return{action:"queue-turn",reason:"soft-interrupt-timed-out"};if(s.steering)return{action:"wait",reason:"steer-in-flight"};return{action:"steer",reason:"mid-turn-handoff"}}function nextFallbackDelay(current){const doubled=current*2;return doubled>FALLBACK_MAX_MS?FALLBACK_MAX_MS:doubled}function fallbackStillOwed(s){if(s.stopping)return false;if(s.queuedTurnTierStopped)return false;return s.unserved>0||s.driveWork}import{createHash as createHash15}from"node:crypto";function stamp(message,now){const parsed=message.timestamp?Date.parse(message.timestamp):Number.NaN;return Number.isFinite(parsed)?{value:parsed,arrival:false}:{value:now(),arrival:true}}function messageId(threadId,cursor,messageIndex,partIndex){const position=createHash15("sha256").update(`${cursor}\0${messageIndex}\0${partIndex}`).digest("base64url").slice(0,22);return`${threadId}:${position}`}function createJcodeMapper(opts){const now=opts.now??(()=>Date.now());let open6=opts.resumeRunId??null;const tools=new Set(opts.resumeTools??[]);const interrupt=(message,code2,timestamp)=>{const events=[...tools].sort().map(toolCallId=>toolCallEnd({toolCallId,timestamp}));tools.clear();open6=null;return[...events,runError({message,code:code2,timestamp})]};const map=({cursor,record:record2})=>{if(record2?.journal_fold){const runId2=open6;return runId2===null?null:{runId:runId2,events:interrupt("Jcode session journal compacted into its snapshot; records not yet emitted were lost and are not reconstructed","jcode_journal_fold",now())}}if(record2===null||typeof record2!=="object"||!Array.isArray(record2.append_messages))return null;const events=[];let runId=open6;for(const[messageIndex,message]of record2.append_messages.entries()){if(message===null||typeof message!=="object"||!Array.isArray(message.content))continue;const{value:timestamp,arrival}=stamp(message,now);const timeMeta=arrival?{cotal:{tsSource:"arrival"}}:{};const parts=message.content;const durableOutput=parts.some(part=>message.role==="assistant"?part?.type==="text"||part?.type==="reasoning"||part?.type==="reasoning_trace"||part?.type==="tool_use":message.role==="user"&&part?.type==="tool_result");if(durableOutput&&open6===null){open6=opts.mintRunId();runId=open6;events.push(runStarted({threadId:opts.threadId,runId:open6,timestamp,cotal:{runIdSource:"connector",...arrival?{tsSource:"arrival"}:{}}}))}if(open6===null)continue;runId=open6;if(message.role==="user"){const remaining=new Set(tools);const missingStart=parts.some(part=>part?.type==="tool_result"&&typeof part.tool_use_id==="string"&&part.tool_use_id.length>0&&!remaining.delete(part.tool_use_id));if(missingStart){events.push(...interrupt("Jcode tool result has no observed start; this record cannot be replayed as a complete event sequence","jcode_tool_start_missing",timestamp));return{runId,events}}}parts.forEach((part,partIndex)=>{if(part===null||typeof part!=="object")return;const observationId=messageId(opts.threadId,cursor,messageIndex,partIndex);if(message.role==="assistant"&&part.type==="text"&&typeof part.text==="string"&&part.text.length>0){events.push(textMessageStart({messageId:observationId,role:"assistant",timestamp,...timeMeta}),textMessageContent({messageId:observationId,delta:part.text,timestamp}),textMessageEnd({messageId:observationId,timestamp}));return}if(message.role==="assistant"&&(part.type==="reasoning"||part.type==="reasoning_trace")&&typeof part.text==="string"&&part.text.length>0){events.push(reasoningMessageStart({messageId:observationId,timestamp,...timeMeta}),reasoningMessageContent({messageId:observationId,delta:part.text,timestamp}),reasoningMessageEnd({messageId:observationId,timestamp}));return}if(message.role==="assistant"&&part.type==="tool_use"&&typeof part.id==="string"&&part.id.length>0){tools.add(part.id);events.push(toolCallStart({toolCallId:part.id,toolCallName:typeof part.name==="string"?part.name:"",parentMessageId:observationId,timestamp,...timeMeta}));return}if(message.role==="user"&&part.type==="tool_result"&&typeof part.tool_use_id==="string"&&part.tool_use_id.length>0){tools.delete(part.tool_use_id);events.push(toolCallEnd({toolCallId:part.tool_use_id,timestamp,...timeMeta}))}})}return runId===null||events.length===0?null:{runId,events}};return{map,forgetOpenRun(runId){if(open6===runId){open6=null;tools.clear()}}}}import{access,open as open5}from"node:fs/promises";import{constants as constants9}from"node:fs";import{basename as basename3,dirname as dirname9,join as join15}from"node:path";var JOURNAL_WAIT_MS=5e3;var RETRY_INITIAL_MS=25;var RETRY_MAX_MS=250;var delay2=ms=>new Promise(resolve4=>setTimeout(resolve4,ms));var isMissing=error2=>error2 instanceof Error&&error2.code==="ENOENT";function jcodeJournalPath(jcodeHome,sessionId){return join15(jcodeHome,"sessions",`${sessionId}.journal.jsonl`)}async function captureJcodeJournalCursor(path4,waitMs=JOURNAL_WAIT_MS){const file=new JsonlFileSource(path4);const deadline=performance.now()+waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){try{return(await file.read(void 0)).cursor}catch(error2){if(!isMissing(error2))throw error2;const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`Jcode AG-UI source: session journal did not appear within ${waitMs}ms`,{cause:error2});await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}}async function initializeJcodeEventBoundary(path4,wal){const acknowledged=wal.frontier.sourceCursor;if(acknowledged!==void 0)return acknowledged;const boundary=await captureJcodeJournalCursor(path4);await wal.advanceCursorOnly(boundary);return boundary}var JcodeJournalSource=class{constructor(path4,waitMs=JOURNAL_WAIT_MS){this.path=path4;this.waitMs=waitMs;this.file=new JsonlFileSource(path4)}path;waitMs;kind="jcode-session-journal";file;end(){return this.file.end()}async read(cursor){if(cursor!==void 0){try{return await this.file.read(cursor)}catch(error2){if(!isMissing(error2)&&!(error2 instanceof JsonlFileResetError))throw error2;const fresh=await this.foldedSince();if(fresh===void 0)throw error2;if(fresh===null){return{cursor,records:[{cursor,value:{journal_fold:{}}}]}}return{cursor:fresh.fresh.cursor,records:[{cursor:fresh.beginning,value:{journal_fold:{}}},...fresh.fresh.records]}}}const deadline=performance.now()+this.waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){try{await access(this.path,constants9.R_OK);return await this.file.readFromBeginning()}catch(error2){if(!isMissing(error2))throw error2;const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`Jcode AG-UI source: session journal did not appear within ${this.waitMs}ms; refusing to lose the first run`,{cause:error2});await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}}async hasSessionSnapshot(){const sessionId=basename3(this.path,".journal.jsonl");const snapshot=join15(dirname9(this.path),`${sessionId}.json`);try{const file=await open5(snapshot,constants9.O_RDONLY|(constants9.O_NOFOLLOW??0));try{if(!(await file.stat()).isFile())throw new Error("Jcode AG-UI source: session snapshot is not a regular file");const parsed=JSON.parse(await file.readFile("utf8"));if(parsed===null||typeof parsed!=="object"||parsed.id!==sessionId||!Array.isArray(parsed.messages))throw new Error("Jcode AG-UI source: checkpoint snapshot does not identify this session");return true}finally{await file.close()}}catch(error2){if(isMissing(error2))return false;throw error2}}async foldedSince(){const deadline=performance.now()+this.waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){if(await this.hasSessionSnapshot()){try{const beginning=await this.file.cursorAtBeginning();const fresh=await this.file.read(beginning);return{beginning,fresh}}catch(error2){if(!isMissing(error2)&&!(error2 instanceof JsonlFileResetError))throw error2;return null}}const remaining=deadline-performance.now();if(remaining<=0)return void 0;await delay2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,RETRY_MAX_MS)}}};function positionedJcodeJournalSource(source){return{kind:source.kind,end:()=>source.end(),async read(cursor){const read=await source.read(cursor);return{cursor:read.cursor,records:read.records.map(record2=>({cursor:record2.cursor,value:{cursor:record2.cursor,record:record2.value}})),...read.unreadable?{unreadable:read.unreadable}:{}}}}}var MAX_RELAY_BYTES=4*1024*1024;var RELAY_REBIND_POLL_MS=1e3;var RUN_ACCEPT_WINDOW_MS=1e4;var BRIDGE_RECOVERY_WINDOW_MS=6e4;function readinessTurnTimeoutMs(){const raw=process.env.COTAL_JCODE_READINESS_TIMEOUT_MS?.trim();if(!raw)return JCODE_READINESS_TIMEOUT_MS;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<=0)throw new Error(`jcode connector: COTAL_JCODE_READINESS_TIMEOUT_MS ${JSON.stringify(raw)} is not a positive integer`);return parsed}function requestTimeoutOverrideMs(){const raw=process.env.COTAL_JCODE_REQUEST_TIMEOUT_MS?.trim();if(!raw)return void 0;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<=0)throw new Error(`jcode connector: COTAL_JCODE_REQUEST_TIMEOUT_MS ${JSON.stringify(raw)} is not a positive integer`);return parsed}var PERMANENT_BRIDGE_RECOVERY_CODES=new Set(["handshake_failed","invalid_instance_home","invalid_request","jcode_not_found","unknown_request","unknown_session","unsupported_version"]);var PERMANENT_BRIDGE_CONNECT_CAUSE_CODES=new Set(["EACCES"]);function permanentBridgeRecoveryFailure(error2){if(!(error2 instanceof HarnessError))return false;if(PERMANENT_BRIDGE_RECOVERY_CODES.has(error2.code))return true;if(error2.code==="connect_failed")return PERMANENT_BRIDGE_CONNECT_CAUSE_CODES.has(error2.cause?.code??"");return false}var PRESENCE_CONDITION_CODES=new Set(["rate_limit","overloaded","auth","billing","budget","context","model","request","server","retrying","approval","input","failed"]);function jcodeTurnCondition(error2,since=Date.now()){if(!(error2 instanceof HarnessError))return void 0;const source=String(error2.code);const code2=PRESENCE_CONDITION_CODES.has(source)?source:"failed";return{code:code2,source,message:error2.message,since}}function privateAgentHome(space2,name){const root=process.env.COTAL_JCODE_HOME?.trim();if(!root)throw new Error("COTAL_JCODE_HOME is not set \u2014 the connector must pin the agent's Jcode home");const managedRoot=join16(root,".cotal","jcode");const home=jcodeSeatHome(root,space2,name);if(!resolve3(home).startsWith(resolve3(managedRoot)+sep2))throw new Error(`jcode home ${home} escapes ${managedRoot} \u2014 refusing`);for(const path4 of[join16(root,".cotal"),managedRoot,home]){try{if(lstatSync9(path4).isSymbolicLink())throw new Error(`refusing symlinked managed path: ${path4}`)}catch(error2){if(error2.code!=="ENOENT")throw error2}}mkdirSync9(home,{recursive:true,mode:448});hardenPrivate(home,"dir");return home}function publicConfig(config2){return{...config2,creds:config2.creds||config2.userAuth?"managed":void 0,userAuth:void 0,token:void 0,user:void 0,pass:void 0,servers:"held by the Jcode host",feedbackKey:void 0}}function assertNoProjectMcpConfig(cwd){const found=[".jcode/mcp.json",".mcp.json",".claude/mcp.json"].filter(relative2=>existsSync2(join16(cwd,relative2)));if(found.length)throw new Error(`jcode connector: project MCP configuration (${found.join(", ")}) is not supported \u2014 Jcode overlays it over the managed cotal MCP bridge. Remove it or use a workspace without project MCP configuration; tool-sharing is not implemented.`)}function mcpEntry(){const built=import.meta.url.includes("/dist/");if(built)return{command:process.execPath,args:[filePath("mcp.js")]};return{command:filePath("../node_modules/.bin/tsx"),args:[filePath("mcp-main.ts")]}}function filePath(relative2){return fileURLToPath(new URL(relative2,import.meta.url))}function writeMcpConfig(home,relay,config2){const{command,args}=mcpEntry();const mcp={servers:{cotal:{command,args,env:{COTAL_JCODE_MCP_SOCKET:relay.path,COTAL_JCODE_MCP_TOKEN:relay.token,COTAL_JCODE_MCP_CONFIG:JSON.stringify(publicConfig(config2))},shared:true}}};const path4=join16(home,"mcp.json");rmSync5(path4,{force:true});let fd;try{fd=openSync7(path4,"wx",384)}catch(error2){throw new Error(`refusing to write Jcode MCP config at ${path4}: ${error2.message}`)}try{writeFileSync4(fd,JSON.stringify(mcp))}finally{closeSync6(fd)}if(process.platform!=="win32")hardenPrivate(path4,"file")}function relayEndpoint(space2,name){const token2=randomBytes6(32).toString("base64url");const id2=createHash16("sha256").update(`${space2}\0${name}\0${process.pid}\0${token2}`).digest("base64url").slice(0,32);if(process.platform==="win32")return{dir:"",path:`\\\\.\\pipe\\cotal-jcode-${id2}`,token:token2};const dir=join16("/tmp",`cotal-jcode-${id2}`);return{dir,path:join16(dir,"relay.sock"),token:token2}}function ensureRelayDirectory(endpoint){if(process.platform==="win32")return;mkdirSync9(endpoint.dir,{recursive:true,mode:448});hardenPrivate(endpoint.dir,"dir")}function instructions(config2,persona){const mesh=`You are connected to the Cotal mesh as "${config2.name}"${config2.role?` (role: ${config2.role})`:""} in space "${config2.space}". ${ORIENTATION_BOOTSTRAP} ${feedbackLine(config2)}${MESH_FIRST_STEER} ${WORKFLOW_STEER} ${CHANNEL_GUIDANCE} Peer messages are delivered into your turns as blocks marked \u{1F4E8}. Reply with cotal_dm (privately, to the sender), cotal_send (to a channel), or cotal_anycast (to a role); use cotal_roster to see who is present and cotal_status to report what you are doing. Reply only when a reply is actually needed \u2014 silent acknowledgement is correct, and @-mention a peer only when you need that peer to act now.`;return persona?`${persona}
175
175
 
176
176
  ${mesh}`:mesh}function constantTokenMatches(presented,expected){if(typeof presented!=="string")return false;const actual=Buffer.from(presented);const wanted=Buffer.from(expected);return actual.length===wanted.length&&timingSafeEqual2(actual,wanted)}async function startRelay(agent,config2,endpoint){const specs=new Map(cotalToolSpecs(config2,"jcode").map(spec=>[spec.name,spec]));ensureRelayDirectory(endpoint);if(process.platform!=="win32"&&existsSync2(endpoint.path))rmSync5(endpoint.path,{force:true});const server=createServer2(socket=>{let input="";let handled=false;const deadline=setTimeout(()=>socket.destroy(),5e3);deadline.unref?.();socket.setEncoding("utf8");socket.on("close",()=>clearTimeout(deadline));socket.on("data",chunk=>{if(handled)return;input+=chunk;if(input.length>MAX_RELAY_BYTES)return socket.destroy();const newline=input.indexOf("\n");if(newline<0)return;handled=true;clearTimeout(deadline);void(async()=>{try{const frame=JSON.parse(input.slice(0,newline));if(!constantTokenMatches(frame.token,endpoint.token))return socket.destroy();if(typeof frame.name!=="string"||!specs.has(frame.name))throw new Error("unknown cotal tool");const spec=specs.get(frame.name);const args=parseToolArgs(spec,frame.args);const result=await spec.run(agent,config2,spec.name==="cotal_inbox"?{...args,scope:"pull-only"}:args);socket.end(JSON.stringify({result})+"\n")}catch(error2){socket.end(JSON.stringify({error:error2.message})+"\n")}})()});socket.on("error",()=>{})});const listen=()=>new Promise((resolvePromise,reject)=>{server.once("error",reject);server.listen(endpoint.path,()=>{server.removeListener("error",reject);resolvePromise()})});await listen();if(process.platform!=="win32"){let rebinding=false;const watch=setInterval(()=>{if(rebinding||!server.listening||existsSync2(endpoint.path))return;rebinding=true;void(async()=>{try{ensureRelayDirectory(endpoint);await closeServer(server);await listen();writeJcodeDiagnostic(`[cotal-jcode] the tool relay socket was deleted; re-bound it at the same path
177
177
  `)}catch(error2){writeJcodeDiagnostic(`[cotal-jcode] the tool relay socket was deleted and could not be re-bound: ${error2.message}
@@ -217,7 +217,7 @@ ${bridgeStderr}`))}const resumed=prior!==void 0&&(fork?fork.briefed:true);sessio
217
217
  `:`[cotal-jcode] pre-join readiness outcome: orientation proved; joining with no spawn --prompt
218
218
  `);watchClient(client);turnActive=readinessTurnOpen;await agent.start();if(!readinessTurnOpen)await ensureEventsBound();if(stopping)return;const joinNotice=`You are now connected to the Cotal mesh as "${config2.name}". The earlier cotal_orientation result was captured before this join; use cotal_orientation again for live context.`;if(bootPrompt){try{await client.sendMessage(sessionId,joinNotice,{noReply:true})}catch(notice){writeJcodeDiagnostic(`[cotal-jcode] post-join notice not delivered: ${notice.message}
219
219
  `)}}else{pendingKickoff=joinNotice}initialized=true;if(!readinessTurnOpen)await ensureEventsBound();if(hasDriveWork())await drive()}catch(error2){if(stopping)return;startControl?.close();await retireRelay(relayServer,relay);try{await stopPrivateJcode({skipClientClose:error2 instanceof JcodeConnectorError&&error2.code==="readiness_timeout"})}catch(teardown){writeJcodeDiagnostic(`[cotal-jcode] ${teardown.message}
220
- `)}socketHome.dispose();await agent.stop().catch(()=>{});throw error2}}var STARTUP_FAILURE_CODES=new Set(["project_mcp_config","jcode_not_found","startup_failed","startup_timeout","invalid_instance_home","connect_failed","handshake_failed","unsupported_version","model_prefix_rejected","model_refused","model_mismatch","private_state","readiness_timeout","sessions_enumeration_failed","sessions_unwritable","provider_auth_refused","provider_request_failed"]);function startupFailureCode(error2){if(error2 instanceof Error&&error2.message.startsWith("jcode connector: project MCP configuration"))return"project_mcp_config";const code2=typeof error2==="object"&&error2!==null&&"code"in error2?error2.code:void 0;return typeof code2==="string"&&STARTUP_FAILURE_CODES.has(code2)?code2:"unknown"}function renderEffortRefusal(error2){if(!(error2 instanceof JcodeEffortRefusal))return void 0;const ladder=error2.acceptedLadder.length?`; accepted tiers: ${error2.acceptedLadder.join(", ")}`:"";const via=error2.apiMethod?` via ${JSON.stringify(error2.apiMethod)}`:"";return`Jcode reasoning effort refused: requested tier ${JSON.stringify(error2.requestedTier)}; effective model ${JSON.stringify(error2.effectiveModel)}; provider ${JSON.stringify(error2.provider)}${via}; provider code ${error2.providerCode}${ladder}`}runJcodeHost().catch(error2=>{if(error2 instanceof JcodeEffortUnsupported){const via=error2.apiMethod?` via ${JSON.stringify(error2.apiMethod)}`:"";writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode model ${JSON.stringify(error2.effectiveModel)} on provider ${JSON.stringify(error2.provider)}${via} does not support reasoning effort; requested tier ${JSON.stringify(error2.requestedTier)} was not applied.
220
+ `)}socketHome.dispose();await agent.stop().catch(()=>{});throw error2}}var STARTUP_FAILURE_CODES=new Set(["project_mcp_config","jcode_not_found","startup_failed","startup_timeout","invalid_instance_home","connect_failed","handshake_failed","unsupported_version","model_prefix_rejected","model_refused","model_mismatch","private_state","readiness_timeout","sessions_enumeration_failed","sessions_unwritable","provider_auth_refused","provider_payment_required","provider_request_failed"]);function startupFailureCode(error2){if(error2 instanceof Error&&error2.message.startsWith("jcode connector: project MCP configuration"))return"project_mcp_config";const code2=typeof error2==="object"&&error2!==null&&"code"in error2?error2.code:void 0;return typeof code2==="string"&&STARTUP_FAILURE_CODES.has(code2)?code2:"unknown"}function renderEffortRefusal(error2){if(!(error2 instanceof JcodeEffortRefusal))return void 0;const ladder=error2.acceptedLadder.length?`; accepted tiers: ${error2.acceptedLadder.join(", ")}`:"";const via=error2.apiMethod?` via ${JSON.stringify(error2.apiMethod)}`:"";return`Jcode reasoning effort refused: requested tier ${JSON.stringify(error2.requestedTier)}; effective model ${JSON.stringify(error2.effectiveModel)}; provider ${JSON.stringify(error2.provider)}${via}; provider code ${error2.providerCode}${ladder}`}runJcodeHost().catch(error2=>{if(error2 instanceof JcodeEffortUnsupported){const via=error2.apiMethod?` via ${JSON.stringify(error2.apiMethod)}`:"";writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode model ${JSON.stringify(error2.effectiveModel)} on provider ${JSON.stringify(error2.provider)}${via} does not support reasoning effort; requested tier ${JSON.stringify(error2.requestedTier)} was not applied.
221
221
  `);process.exit(1)}const effortRefusal=renderEffortRefusal(error2);if(effortRefusal){writeJcodeDiagnostic(`[cotal-jcode] fatal: ${effortRefusal}
222
222
  `);process.exit(1)}if(error2 instanceof JcodeReadinessProviderRefusal){writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode readiness turn refused ${error2.parameter} ${JSON.stringify(error2.value)} (${error2.providerCode}); inspect the private Jcode logs for other details.
223
223
  `)}else if(error2 instanceof JcodeSessionsEnumerationFailure){writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode host startup failed (sessions_enumeration_failed): ${error2.causeText} while reading ${error2.sessionsPath}