@cotal-ai/connector-jcode 0.135.11 → 0.135.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-index.bin +0 -0
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +6 -5
- package/dist/mcp.js +1 -1
- package/dist/private-state.d.ts +5 -0
- package/dist/private-state.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/host.js
CHANGED
|
@@ -131,7 +131,7 @@ ${tail}`)}if(history.length){blocks.push(`\u{1F4DA} Cotal \u2014 ${history.lengt
|
|
|
131
131
|
${history.map(format).join("\n")}
|
|
132
132
|
(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,awaitHandoff)});sock.on("error",()=>{})});let bound=false;let retried=false;const emit=server.emit.bind(server);server.emit=(event,...args)=>{const error51=args[0];if(event!=="error"||bound||retried||process.platform==="win32"||path4.startsWith("\0")||error51?.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}
|
|
133
133
|
`);if(opts.fatalBind&&!bound)process.exit(1)});server.listen(path4,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path4}
|
|
134
|
-
`)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});async function submitFeedback(input,options={}){const url2=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(url2,{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 ${url2}: ${e.message}`)}}import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();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.135.11";function loadDocsMetadata(){return{"version":"0.135.11","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. 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","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"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":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"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":"Start here","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1116097||createHash11("sha256").update(packed).digest("hex")!=="4bc00f1c1f7969b0fb6d5abee3cf8f0d8e39dc70eb3a4c256dba29d4b15747e8")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9104],[9104,27871],[27871,32088],[32088,36459],[36459,39587],[39587,44820],[44820,48334],[48334,57322],[57322,61474],[61474,65922],[65922,67944],[67944,71955],[71955,102007],[102007,117495],[117495,132625],[132625,150224],[150224,165088],[165088,179720],[179720,195073],[195073,214599],[214599,220315],[220315,229873],[229873,247452],[247452,251856],[251856,272942],[272942,282048],[282048,310522],[310522,326427],[326427,349118],[349118,378769],[378769,391863],[391863,393810],[393810,402639],[402639,418645],[418645,426136],[426136,428820],[428820,432201],[432201,435504],[435504,437549],[437549,440154],[440154,444804],[444804,446608],[446608,450159],[450159,461604],[461604,469565],[469565,473090],[473090,478260],[478260,483171],[483171,486042],[486042,493984],[493984,496961],[496961,504157],[504157,507147],[507147,511797],[511797,522778],[522778,533859],[533859,538751],[538751,546282],[546282,549631],[549631,552202],[552202,559460],[559460,562845],[562845,565055],[565055,568517],[568517,571935],[571935,573049],[573049,574798],[574798,578454],[578454,583007],[583007,589440],[589440,599754],[599754,612643],[612643,614480],[614480,627345],[627345,632461],[632461,636197],[636197,638706],[638706,643752],[643752,650527],[650527,656593],[656593,657340],[657340,661412],[661412,666481],[666481,669859],[669859,673745],[673745,677768],[677768,682570],[682570,685721],[685721,689120],[689120,693167],[693167,696692],[696692,708828],[708828,711646],[711646,714329],[714329,716957],[716957,719448],[719448,723468],[723468,728168],[728168,730387],[730387,790166],[790166,793237],[793237,794217],[794217,798296],[798296,806052],[806052,816082],[816082,824604],[824604,829661],[829661,1073243],[1073243,1110885],[1110885,1116097]];var sourceLengths=[4844,4048,12754,75273,11674,10644,29417,13195,8549,78405,37758,10864,4557,9872,81561,41661,42535,50018,41170,42370,41811,54106,14375,25041,49829,9889,60481,24959,86255,44853,67764,91136,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11759,4292,8347,30465,19623,8745,31524,12472,7037,20396,7140,18615,6860,11538,28251,28907,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9816,10853,15565,26241,33068,4227,35e3,11735,9122,8201,13307,16844,14721,1464,9180,12941,7818,9320,9965,11921,6532,8528,9633,8223,30647,6519,6405,5824,6007,9711,11730,5283,174038,6927,2023,9304,20040,25734,20345,12299,705228,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!==577238||createHash11("sha256").update(packed).digest("hex")!=="dce32df59ed2622be9fa2015559255f328b1f8d25aaee10d6b133813437e1f24")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);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 meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((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}
|
|
134
|
+
`)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});async function submitFeedback(input,options={}){const url2=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(url2,{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 ${url2}: ${e.message}`)}}import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();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.135.12";function loadDocsMetadata(){return{"version":"0.135.12","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. 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","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"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":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"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":"Start here","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1116217||createHash11("sha256").update(packed).digest("hex")!=="16d4c2afb345beabcad76cf4c3a777655b4c3a931b7f7ca95668920d0a997f55")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9104],[9104,27871],[27871,32088],[32088,36459],[36459,39587],[39587,44820],[44820,48334],[48334,57322],[57322,61474],[61474,65922],[65922,67944],[67944,71955],[71955,102007],[102007,117495],[117495,132625],[132625,150224],[150224,165088],[165088,179720],[179720,195073],[195073,214599],[214599,220315],[220315,229873],[229873,247452],[247452,251856],[251856,272942],[272942,282048],[282048,310522],[310522,326427],[326427,349118],[349118,378769],[378769,391863],[391863,393810],[393810,402639],[402639,418645],[418645,426136],[426136,428820],[428820,432201],[432201,435504],[435504,437549],[437549,440154],[440154,444804],[444804,446608],[446608,450159],[450159,461604],[461604,469565],[469565,473090],[473090,478260],[478260,483171],[483171,486042],[486042,493984],[493984,496961],[496961,504157],[504157,507147],[507147,511797],[511797,522778],[522778,533859],[533859,538751],[538751,546282],[546282,549631],[549631,552202],[552202,559460],[559460,562845],[562845,565055],[565055,568517],[568517,571935],[571935,573049],[573049,574798],[574798,578454],[578454,583007],[583007,589440],[589440,599754],[599754,612643],[612643,614480],[614480,627465],[627465,632581],[632581,636317],[636317,638826],[638826,643872],[643872,650647],[650647,656713],[656713,657460],[657460,661532],[661532,666601],[666601,669979],[669979,673865],[673865,677888],[677888,682690],[682690,685841],[685841,689240],[689240,693287],[693287,696812],[696812,708948],[708948,711766],[711766,714449],[714449,717077],[717077,719568],[719568,723588],[723588,728288],[728288,730507],[730507,790286],[790286,793357],[793357,794337],[794337,798416],[798416,806172],[806172,816202],[816202,824724],[824724,829781],[829781,1073363],[1073363,1111005],[1111005,1116217]];var sourceLengths=[4844,4048,12754,75273,11674,10644,29417,13195,8549,78405,37758,10864,4557,9872,81561,41661,42535,50018,41170,42370,41811,54106,14375,25041,49829,9889,60481,24959,86255,44853,67764,91136,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11759,4292,8347,30465,19623,8745,31524,12472,7037,20396,7140,18615,6860,11538,28251,28907,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9816,10853,15565,26241,33068,4227,35397,11735,9122,8201,13307,16844,14721,1464,9180,12941,7818,9320,9965,11921,6532,8528,9633,8223,30647,6519,6405,5824,6007,9711,11730,5283,174038,6927,2023,9304,20040,25734,20345,12299,705228,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!==577263||createHash11("sha256").update(packed).digest("hex")!=="c3b76d461294dcb419bd4be313b7a9048df8b72465b35ec49c0a2bd400f880cf")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);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 meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((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}
|
|
135
135
|
${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}
|
|
136
136
|
|
|
137
137
|
${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}
|
|
@@ -172,7 +172,7 @@ ${stderr.trim()}`:""))}if(fs.existsSync(socketPath)){return{socketPath,jcodeHome
|
|
|
172
172
|
${stderr.trim()}`:""))}import net from"node:net";import{EventEmitter as EventEmitter3}from"node:events";var import_ajv=__toESM(require_ajv(),1);var StructuredOutputError=class extends HarnessError{attempts;validationErrors;lastText;constructor(attempts){const last=attempts[attempts.length-1];const count=attempts.length;const summary=last?.errors.map(formatIssue).join("; ")||"no structured output attempts ran";super("structured_output_invalid",`model did not produce valid structured output after ${count} attempt${count===1?"":"s"}: ${summary}`);this.name="StructuredOutputError";this.attempts=attempts;this.validationErrors=last?.errors??[];this.lastText=last?.text??""}};var ajv=new import_ajv.Ajv({allErrors:true,coerceTypes:false,removeAdditional:false,useDefaults:false,strict:false,validateSchema:true});function compileStructuredSchema(schema){try{return ajv.compile(schema)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);throw new HarnessError("structured_schema_invalid",message)}}function validateStructuredText(text2,validate2){const parsed=parseJsonFromText(text2);if(!parsed.ok)return{ok:false,errors:[parsed.error]};if(validate2(parsed.value)){return{ok:true,data:parsed.value,errors:[]}}return{ok:false,errors:normalizeAjvErrors(validate2.errors??[])}}function buildStructuredPrompt(content,schema){return`${content}
|
|
173
173
|
|
|
174
174
|
${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(error51=>({path:error51.instancePath||"/",keyword:error51.keyword,message:error51.message??`failed ${error51.keyword} validation`,params:error51.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(error51){lastError=error51 instanceof Error?error51.message:String(error51)}}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)}
|
|
175
|
-
\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",error51=>listener(error51))},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 error51=new HarnessError("connect_failed",hint);error51.cause=cause;return error51}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(error51=>this.handleClose(error51))}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(error51){await instance.shutdown();throw error51}}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(error51){this.emitSafe("error",error51);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(error51){this.closed=true;this.closeError=error51??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",error51)}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(error51){this.pending.delete(id2);if(entry.timer)clearTimeout(entry.timer);reject(error51)}})}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=error51=>{void finish(error51)};const onAbort=()=>{void finish()};const finish=error51=>{if(cleanupPromise)return cleanupPromise;stopped=true;terminalError=error51;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(error51){if(child&&children.get(sessionId)?.client===child)children.delete(sessionId);await child?.close();if(!stopped&&!(error51 instanceof HarnessError&&error51.code==="unknown_session")){void finish(error51 instanceof Error?error51:new Error(String(error51)))}}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(error51){if(!stopped)void finish(error51 instanceof Error?error51:new Error(String(error51)))}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 error51=>{await finish();throw error51}}}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 closeSync3,constants as constants7,copyFileSync,fstatSync as fstatSync3,lstatSync as lstatSync7,mkdirSync as mkdirSync7,mkdtempSync as mkdtempSync2,openSync as openSync4,readdirSync as readdirSync2,renameSync as renameSync2,rmSync as rmSync3,rmdirSync as rmdirSync2,statSync as statSync4,symlinkSync,unlinkSync as unlinkSync5}from"node:fs";import{homedir,tmpdir as tmpdir2}from"node:os";import{basename as basename2,dirname as dirname8,isAbsolute,join as join10,relative,resolve as resolve2,sep}from"node:path";import{DatabaseSync}from"node:sqlite";import{constants as constants6,lstatSync as lstatSync6,mkdirSync as mkdirSync6,openSync as openSync3,writeSync}from"node:fs";import{join as join9}from"node:path";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)}}var JcodeConnectorError=class extends Error{constructor(code2,message,options){super(message,options);this.code=code2}code};var JcodeModelMismatch=class extends JcodeConnectorError{constructor(requestedModel,requestedTier,runtime){const model=requestedModel??runtime?.model;const matches=model?runtime?.routes?.filter(route2=>route2?.model===model)??[]:[];const route=model?activeModelRoute(runtime,model):void 0;const reason=!model?"no model was reported":matches.length===0?"no matching model route was reported":!route?"matching routes could not be disambiguated by the reported provider":"the selected route has no provider";const identity=(value,missing="(unreported)")=>value===void 0||value===""?missing:typeof value==="string"&&SAFE_VALUE.test(value)?JSON.stringify(value):"(withheld)";const tier=SAFE_EFFORT_TIERS.has(requestedTier)?JSON.stringify(requestedTier):"(withheld)";super("model_mismatch",`${reason}; requested model ${identity(requestedModel,"(provider default)")}; reported model ${identity(runtime?.model)}; reported provider ${identity(runtime?.provider)}; matching model routes: ${matches.length}; requested tier ${tier} was not applied`)}};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 JcodeCursorStateUnreadable=class extends Error{constructor(sourceRelative,reason,sqliteCode){super(`Cursor's state database ~/${sourceRelative} could not be read (${reason}${sqliteCode===void 0?"":`, SQLite code ${sqliteCode}`})`);this.sourceRelative=sourceRelative;this.reason=reason;this.sqliteCode=sqliteCode}sourceRelative;reason;sqliteCode;code="cursor_state_unreadable"};var diagnosticLogFd;function installJcodeDiagnosticLog(home){const logs=join9(home,"logs");try{const stats=lstatSync6(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(error51){if(error51.code!=="ENOENT")throw error51;mkdirSync6(logs,{mode:448})}hardenPrivate(logs,"dir");const timestamp=new Date().toISOString().replace(/[:.]/g,"-");const path4=join9(logs,`connector-${timestamp}-${process.pid}.log`);diagnosticLogFd=openSync3(path4,constants6.O_WRONLY|constants6.O_CREAT|constants6.O_EXCL|(constants6.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 json2=message.slice(message.indexOf("{"));try{const parsed=JSON.parse(json2);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(error51){if(!(error51 instanceof Error))return[];const listed=/\b(?:accepted\s+(?:tiers?|efforts?)|available)\s*:\s*([^;\r\n]{1,256})/i.exec(error51.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(error51,requestedTier,identity){if(error51 instanceof HarnessError&&/^invalid_request: Reasoning effort is not supported by the current model\/profile\./.test(error51.message)){return new JcodeEffortUnsupported(requestedTier,identity.model,identity.provider,identity.apiMethod)}return new JcodeEffortRefusal(requestedTier,identity.model,identity.provider,identity.apiMethod,acceptedEffortLadder(error51))}function classifyReadinessFailure(error51){if(!(error51 instanceof HarnessError)||error51.code!=="internal")return void 0;if(error51.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(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 401 Unauthorized\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_auth_refused","Jcode provider refused readiness authentication")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 402 Payment Required\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_payment_required","Jcode provider refused the readiness request for payment")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 403 Forbidden\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_forbidden","Jcode provider refused the readiness request as forbidden")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 429 Too Many Requests\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_rate_limited","Jcode provider rate-limited the readiness request")}return void 0}function classifyReadinessProviderRefusal(error51,requestedModel){if(!(error51 instanceof HarnessError))return void 0;if(error51.code==="internal"){if(!requestedModel||!SAFE_VALUE.test(requestedModel)||!error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")||!/^ status: 404 Not Found\r?$/m.test(error51.message))return void 0;const response=/^ response: (\{[^\r\n]*\})\r?$/m.exec(error51.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(error51.code!=="invalid_request")return void 0;const body=providerBody(error51.message);const code2=classifiedCode(error51.message,body);const parameter=rejectedParameter(typeof body?.message==="string"?body.message:error51.message);return parameter?new JcodeReadinessProviderRefusal(code2,parameter.parameter,parameter.value):void 0}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",".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"];var CURSOR_STATE_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"];var CURSOR_STATE_KEYS=["cursorAuth/accessToken","cursorAuth/refreshToken","storage.serviceMachineId","cursorAuth/cachedEmail"];var CURSOR_STATE_BUSY_MS=2e3;var CURSOR_STATE_VALUE_MAX_BYTES=16*1024;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=lstatSync7(path4);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();rmSync3(path4,{force:true});mkdirSync7(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(error51){if(error51.code!=="ENOENT")throw error51;beforeEnsure?.();mkdirSync7(path4,{mode:448})}hardenPrivate(path4,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync7(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=lstatSync7(leaf);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();unlinkSync5(leaf);mkdirSync7(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(error51){if(error51.code!=="ENOENT")throw error51;beforeEnsure?.();mkdirSync7(leaf,{mode:448})}hardenPrivate(leaf,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync7(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(error51){throw new Error(pinUnsupportedMessage(`opening ${probe} failed with ${error51.code??"unknown"}`))}closeSync3(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(error51){closeSync3(fd);throw error51}return new _PinnedParent(mode,fd,void 0)}let entryCwd;try{entryCwd=process.cwd()}catch(error51){closeSync3(fd);throw new Error(pinUnsupportedMessage(`the working directory is unreadable: ${error51.message}`))}const pin=new _PinnedParent(mode,fd,entryCwd);try{beforeEnter?.();process.chdir(directory);pin.#assertCwdIsPinned(directory)}catch(error51){pin.close();throw error51}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"){closeSync3(this.#fd);this.#fd=next;return}const previous=this.#fd;try{process.chdir(name)}catch(error51){closeSync3(next);throw error51}this.#fd=next;try{this.#assertCwdIsPinned(displayPath)}finally{closeSync3(previous)}}close(){if(this.#closed)return;this.#closed=true;try{if(this.#entryCwd!==void 0)process.chdir(this.#entryCwd)}finally{closeSync3(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(error51){const code2=error51.code;if(code2==="ENOENT"){try{mkdirSync7(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=lstatSync7(this.leaf(name)).isSymbolicLink()}catch(inner){this.mapOpenError(inner,name,displayPath)}}if(!isLink)this.mapOpenError(error51,name,displayPath);unlinkSync5(this.leaf(name));mkdirSync7(this.leaf(name),{mode:448})}else{this.mapOpenError(error51,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(error51,name,displayPath){const code2=error51.code;if(code2==="ELOOP")throw new Error(`refusing symlinked Jcode credential mirror parent: ${displayPath}`);if(code2==="ENOTDIR"){if(lstatSync7(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 error51}};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(error51){if(create||error51.code==="ENOENT")throw error51;pin.mapOpenError(error51,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(error51){if(error51.code==="ENOENT")return false;throw error51}try{try{walkPinnedParents(home,parentRelative,pin,false)}catch(error51){if(error51.code==="ENOENT")return false;throw error51}try{if(lstatSync7(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error51){if(error51.code==="ENOENT")return false;throw error51}beforeUnlink?.();try{unlinkSync5(pin.leaf(base))}catch(error51){if(error51.code==="ENOENT")return false;throw error51}return true}finally{pin.close()}}function copyCredentialFile(home,source,destinationRelative,beforeCopy){assertRelative(destinationRelative);let sourceStats;try{sourceStats=statSync4(source)}catch(error51){if(error51.code==="ENOENT"){removeCredentialMirror(home,destinationRelative);return false}throw error51}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(lstatSync7(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error51){if(error51.code!=="ENOENT")throw error51}beforeCopy?.();const tempName=`.${randomBytes3(6).toString("hex")}.tmp`;const temp=pin.leaf(tempName);try{copyFileSync(source,temp,constants7.COPYFILE_EXCL);hardenPrivate(temp,"file");renameSync2(temp,pin.leaf(base))}finally{rmSync3(temp,{force:true})}if(lstatSync7(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(error51){if(error51.code==="ENOENT")return[];throw error51}}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)});for(const relativePath of CURSOR_STATE_FILES)inventory.push({family:"cursor-state",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 sqliteReason(code2){if(code2===776)return"hot_journal";switch(code2&255){case 5:case 6:return"locked";case 11:return"corrupt";case 26:return"not_sqlite";default:return"sqlite_error"}}function readCursorState(source,sourceRelative){let stats;try{stats=statSync4(source)}catch(error51){if(error51.code==="ENOENT")return void 0;throw error51}if(!stats.isFile())return void 0;const unreadable=(reason,code2)=>new JcodeCursorStateUnreadable(sourceRelative,reason,code2);let db;try{db=new DatabaseSync(source,{readOnly:true});db.exec(`PRAGMA busy_timeout = ${CURSOR_STATE_BUSY_MS}`);db.exec("BEGIN");if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'ItemTable'").get())throw unreadable("no_item_table");const select=db.prepare(`SELECT typeof(value) AS kind, CASE WHEN typeof(value) = 'text' AND octet_length(value) <= ${CURSOR_STATE_VALUE_MAX_BYTES} THEN value END AS value FROM ItemTable WHERE key = ?`);const values=new Map;for(const key of CURSOR_STATE_KEYS){const row=select.get(key);if(row===void 0||row.kind==="null")continue;if(row.kind!=="text")throw unreadable("value_type");if(row.value===null)throw unreadable("value_size");if(row.value.trim())values.set(key,row.value)}db.exec("COMMIT");return values}catch(error51){if(error51 instanceof JcodeCursorStateUnreadable)throw error51;const code2=error51.errcode;if(typeof code2!=="number")throw error51;throw unreadable(sqliteReason(code2),code2)}finally{db?.close()}}function publishCursorState(home,destinationRelative,values){if(!values||values.size===0){removeCredentialMirror(home,destinationRelative);return}const scratch=mkdtempSync2(join10(tmpdir2(),"cotal-jcode-cursor-"));try{const file2=join10(scratch,"state.vscdb");const db=new DatabaseSync(file2);try{db.exec("CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)");const insert=db.prepare("INSERT INTO ItemTable (key, value) VALUES (?, ?)");for(const[key,value]of values)insert.run(key,value)}finally{db.close()}copyCredentialFile(home,file2,destinationRelative)}finally{rmSync3(scratch,{recursive:true,force:true})}}function mirrorJcodeCredentials(home,sources2=credentialSources()){privateDirectory(home,{pin:true});const inventory=jcodeCredentialMirrorInventory(home,sources2);const cursorStates=inventory.filter(entry=>entry.family==="cursor-state").map(entry=>({entry,values:readCursorState(entry.source,relative(sources2.externalHome,entry.source))}));for(const entry of inventory)if(entry.family!=="cursor-state")copyCredentialFile(home,entry.source,entry.destinationRelative);for(const{entry,values}of cursorStates)publishCursorState(home,entry.destinationRelative,values)}function reclaimSocketAlias(alias){let stats;try{stats=lstatSync7(alias)}catch(error51){if(error51.code!=="ENOENT")throw error51;return}rmSync3(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(error51){throw new Error(`cannot create Jcode short API socket alias ${alias}: ${error51.message}`)}const apiSocket=join10(alias,"run","jcode-api.sock");if(Buffer.byteLength(apiSocket)>=MAX_API_SOCKET_BYTES){rmSync3(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:()=>{rmSync3(alias,{force:true});try{rmdirSync2(socketDir)}catch(error51){if(error51.code!=="ENOENT")throw error51}}}}import{randomBytes as randomBytes4}from"node:crypto";import{readFileSync as readFileSync6,readdirSync as readdirSync3,rmSync as rmSync4}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 group=Number(fields[2]);const start=fields[19];if(!(Number.isInteger(parentPid)&&parentPid>=0&&Number.isInteger(group)&&group>=0&&start))return void 0;return fields[0]==="Z"?{pid,parentPid,group,start,zombie:true}:{pid,parentPid,group,start}}if(process.platform==="darwin"||process.platform.endsWith("bsd")){const out=execFileSync4("/bin/ps",["-o","ppid=","-o","pgid=","-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();const match=out.match(/^(\d+)\s+(\d+)\s+(.+)$/u);const parentPid=Number(match?.[1]);const group=Number(match?.[2]);const start=match?.[3]?.trim();return Number.isInteger(parentPid)&&parentPid>=0&&Number.isInteger(group)&&group>=0&&start?{pid,parentPid,group,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(error51){throw new Error(`jcode connector: cannot enumerate launch descendants on ${process.platform}: ${error51.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(error51){const code2=error51.code;if(code2==="ESRCH")return false;if(code2==="EPERM")return true;throw error51}}};function processHasLaunchIdentityFromPs(pid,identityValue,probe){try{const out=probe.ps(pid);return out.includes(`${LAUNCH_IDENTITY_ENV}=${identityValue}`)}catch(error51){const status2=error51.status;if(status2===1&&!probe.pidExists(pid))return false;throw error51}}function launchIdentityProof(pid,identityValue,probe){if(process.platform==="linux"){let environ;try{environ=probe.readEnviron(pid)}catch(error51){const code2=error51.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")return void 0;throw error51}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,readStat=processStat){const owned=[];for(const pid of processPids()){try{if(launchIdentityProof(pid,identityValue,probe)!==true)continue;const stat=readStat(pid);if(stat)owned.push(stat)}catch(error51){const code2=error51.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")continue;throw new Error(`jcode connector: cannot prove launch-bound identity for PID ${pid}: ${error51.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 file2 of readdirSync3(join11(jcodeHome,"active_pids"))){const pid=Number(readFileSync6(join11(jcodeHome,"active_pids",file2),"utf8").trim());if(isPid(pid))pids.add(pid)}}catch{}pids.delete(process.pid);return[...pids]}var alive=pid=>{const stat=processStat(pid);if(stat)return!stat.zombie;try{process.kill(pid,0);return true}catch(error51){return error51.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)}
|
|
175
|
+
\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",error51=>listener(error51))},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 error51=new HarnessError("connect_failed",hint);error51.cause=cause;return error51}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(error51=>this.handleClose(error51))}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(error51){await instance.shutdown();throw error51}}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(error51){this.emitSafe("error",error51);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(error51){this.closed=true;this.closeError=error51??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",error51)}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(error51){this.pending.delete(id2);if(entry.timer)clearTimeout(entry.timer);reject(error51)}})}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=error51=>{void finish(error51)};const onAbort=()=>{void finish()};const finish=error51=>{if(cleanupPromise)return cleanupPromise;stopped=true;terminalError=error51;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(error51){if(child&&children.get(sessionId)?.client===child)children.delete(sessionId);await child?.close();if(!stopped&&!(error51 instanceof HarnessError&&error51.code==="unknown_session")){void finish(error51 instanceof Error?error51:new Error(String(error51)))}}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(error51){if(!stopped)void finish(error51 instanceof Error?error51:new Error(String(error51)))}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 error51=>{await finish();throw error51}}}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 closeSync3,constants as constants7,copyFileSync,fstatSync as fstatSync3,lstatSync as lstatSync7,mkdirSync as mkdirSync7,mkdtempSync as mkdtempSync2,openSync as openSync4,readdirSync as readdirSync2,renameSync as renameSync2,rmSync as rmSync3,rmdirSync as rmdirSync2,statSync as statSync4,symlinkSync,unlinkSync as unlinkSync5}from"node:fs";import{homedir,tmpdir as tmpdir2}from"node:os";import{basename as basename2,dirname as dirname8,isAbsolute,join as join10,relative,resolve as resolve2,sep}from"node:path";import{DatabaseSync}from"node:sqlite";import{constants as constants6,lstatSync as lstatSync6,mkdirSync as mkdirSync6,openSync as openSync3,writeSync}from"node:fs";import{join as join9}from"node:path";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)}}var JcodeConnectorError=class extends Error{constructor(code2,message,options){super(message,options);this.code=code2}code};var JcodeModelMismatch=class extends JcodeConnectorError{constructor(requestedModel,requestedTier,runtime){const model=requestedModel??runtime?.model;const matches=model?runtime?.routes?.filter(route2=>route2?.model===model)??[]:[];const route=model?activeModelRoute(runtime,model):void 0;const reason=!model?"no model was reported":matches.length===0?"no matching model route was reported":!route?"matching routes could not be disambiguated by the reported provider":"the selected route has no provider";const identity=(value,missing="(unreported)")=>value===void 0||value===""?missing:typeof value==="string"&&SAFE_VALUE.test(value)?JSON.stringify(value):"(withheld)";const tier=SAFE_EFFORT_TIERS.has(requestedTier)?JSON.stringify(requestedTier):"(withheld)";super("model_mismatch",`${reason}; requested model ${identity(requestedModel,"(provider default)")}; reported model ${identity(runtime?.model)}; reported provider ${identity(runtime?.provider)}; matching model routes: ${matches.length}; requested tier ${tier} was not applied`)}};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 JcodeCursorStateUnreadable=class extends Error{constructor(sourceRelative,reason,sqliteCode){super(`Cursor's state database ~/${sourceRelative} could not be read (${reason}${sqliteCode===void 0?"":`, SQLite code ${sqliteCode}`})`);this.sourceRelative=sourceRelative;this.reason=reason;this.sqliteCode=sqliteCode}sourceRelative;reason;sqliteCode;code="cursor_state_unreadable"};var diagnosticLogFd;function installJcodeDiagnosticLog(home){const logs=join9(home,"logs");try{const stats=lstatSync6(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(error51){if(error51.code!=="ENOENT")throw error51;mkdirSync6(logs,{mode:448})}hardenPrivate(logs,"dir");const timestamp=new Date().toISOString().replace(/[:.]/g,"-");const path4=join9(logs,`connector-${timestamp}-${process.pid}.log`);diagnosticLogFd=openSync3(path4,constants6.O_WRONLY|constants6.O_CREAT|constants6.O_EXCL|(constants6.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 json2=message.slice(message.indexOf("{"));try{const parsed=JSON.parse(json2);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(error51){if(!(error51 instanceof Error))return[];const listed=/\b(?:accepted\s+(?:tiers?|efforts?)|available)\s*:\s*([^;\r\n]{1,256})/i.exec(error51.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(error51,requestedTier,identity){if(error51 instanceof HarnessError&&/^invalid_request: Reasoning effort is not supported by the current model\/profile\./.test(error51.message)){return new JcodeEffortUnsupported(requestedTier,identity.model,identity.provider,identity.apiMethod)}return new JcodeEffortRefusal(requestedTier,identity.model,identity.provider,identity.apiMethod,acceptedEffortLadder(error51))}function classifyReadinessFailure(error51){if(!(error51 instanceof HarnessError)||error51.code!=="internal")return void 0;if(error51.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(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 401 Unauthorized\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_auth_refused","Jcode provider refused readiness authentication")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 402 Payment Required\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_payment_required","Jcode provider refused the readiness request for payment")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 403 Forbidden\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_forbidden","Jcode provider refused the readiness request as forbidden")}if(error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")&&/^ status: 429 Too Many Requests\r?$/m.test(error51.message)){return new JcodeConnectorError("provider_rate_limited","Jcode provider rate-limited the readiness request")}return void 0}function classifyReadinessProviderRefusal(error51,requestedModel){if(!(error51 instanceof HarnessError))return void 0;if(error51.code==="internal"){if(!requestedModel||!SAFE_VALUE.test(requestedModel)||!error51.message.startsWith("internal: OpenAI-compatible chat request failed\n")||!/^ status: 404 Not Found\r?$/m.test(error51.message))return void 0;const response=/^ response: (\{[^\r\n]*\})\r?$/m.exec(error51.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(error51.code!=="invalid_request")return void 0;const body=providerBody(error51.message);const code2=classifiedCode(error51.message,body);const parameter=rejectedParameter(typeof body?.message==="string"?body.message:error51.message);return parameter?new JcodeReadinessProviderRefusal(code2,parameter.parameter,parameter.value):void 0}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",".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"];var CURSOR_STATE_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"];var CURSOR_STATE_KEYS=["cursorAuth/accessToken","cursorAuth/refreshToken","storage.serviceMachineId","cursorAuth/cachedEmail"];var CURSOR_STATE_BUSY_MS=2e3;var CURSOR_STATE_VALUE_MAX_BYTES=16*1024;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=lstatSync7(path4);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();rmSync3(path4,{force:true});mkdirSync7(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(error51){if(error51.code!=="ENOENT")throw error51;beforeEnsure?.();mkdirSync7(path4,{mode:448})}hardenPrivate(path4,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync7(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=lstatSync7(leaf);if(stats.isSymbolicLink()){if(!replaceSymlink)throw new Error(`refusing symlinked Jcode private directory: ${path4}`);beforeEnsure?.();unlinkSync5(leaf);mkdirSync7(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(error51){if(error51.code!=="ENOENT")throw error51;beforeEnsure?.();mkdirSync7(leaf,{mode:448})}hardenPrivate(leaf,"dir");if(requireOwner)assertCurrentUserOwns(path4,lstatSync7(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(error51){throw new Error(pinUnsupportedMessage(`opening ${probe} failed with ${error51.code??"unknown"}`))}closeSync3(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(error51){closeSync3(fd);throw error51}return new _PinnedParent(mode,fd,void 0)}let entryCwd;try{entryCwd=process.cwd()}catch(error51){closeSync3(fd);throw new Error(pinUnsupportedMessage(`the working directory is unreadable: ${error51.message}`))}const pin=new _PinnedParent(mode,fd,entryCwd);try{beforeEnter?.();process.chdir(directory);pin.#assertCwdIsPinned(directory)}catch(error51){pin.close();throw error51}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"){closeSync3(this.#fd);this.#fd=next;return}const previous=this.#fd;try{process.chdir(name)}catch(error51){closeSync3(next);throw error51}this.#fd=next;try{this.#assertCwdIsPinned(displayPath)}finally{closeSync3(previous)}}close(){if(this.#closed)return;this.#closed=true;try{if(this.#entryCwd!==void 0)process.chdir(this.#entryCwd)}finally{closeSync3(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(error51){const code2=error51.code;if(code2==="ENOENT"){try{mkdirSync7(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=lstatSync7(this.leaf(name)).isSymbolicLink()}catch(inner){this.mapOpenError(inner,name,displayPath)}}if(!isLink)this.mapOpenError(error51,name,displayPath);unlinkSync5(this.leaf(name));mkdirSync7(this.leaf(name),{mode:448})}else{this.mapOpenError(error51,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(error51,name,displayPath){const code2=error51.code;if(code2==="ELOOP")throw new Error(`refusing symlinked Jcode credential mirror parent: ${displayPath}`);if(code2==="ENOTDIR"){if(lstatSync7(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 error51}};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(error51){if(create||error51.code==="ENOENT")throw error51;pin.mapOpenError(error51,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(error51){if(error51.code==="ENOENT")return false;throw error51}try{try{walkPinnedParents(home,parentRelative,pin,false)}catch(error51){if(error51.code==="ENOENT")return false;throw error51}try{if(lstatSync7(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error51){if(error51.code==="ENOENT")return false;throw error51}beforeUnlink?.();try{unlinkSync5(pin.leaf(base))}catch(error51){if(error51.code==="ENOENT")return false;throw error51}return true}finally{pin.close()}}function copyCredentialFile(home,source,destinationRelative,beforeCopy){assertRelative(destinationRelative);let sourceStats;try{sourceStats=statSync4(source)}catch(error51){if(error51.code==="ENOENT"){removeCredentialMirror(home,destinationRelative);return false}throw error51}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(lstatSync7(pin.leaf(base)).isDirectory())throw new Error(`Jcode credential mirror destination is a directory: ${destination}`)}catch(error51){if(error51.code!=="ENOENT")throw error51}beforeCopy?.();const tempName=`.${randomBytes3(6).toString("hex")}.tmp`;const temp=pin.leaf(tempName);try{copyFileSync(source,temp,constants7.COPYFILE_EXCL);hardenPrivate(temp,"file");renameSync2(temp,pin.leaf(base))}finally{rmSync3(temp,{force:true})}if(lstatSync7(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(error51){if(error51.code==="ENOENT")return[];throw error51}}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)});for(const relativePath of CURSOR_STATE_FILES)inventory.push({family:"cursor-state",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 sqliteReason(code2){if(code2===776)return"hot_journal";switch(code2&255){case 5:case 6:return"locked";case 11:return"corrupt";case 26:return"not_sqlite";default:return"sqlite_error"}}function readCursorState(source,sourceRelative){let stats;try{stats=statSync4(source)}catch(error51){if(error51.code==="ENOENT")return void 0;throw error51}if(!stats.isFile())return void 0;const unreadable=(reason,code2)=>new JcodeCursorStateUnreadable(sourceRelative,reason,code2);let db;try{db=new DatabaseSync(source,{readOnly:true});db.exec(`PRAGMA busy_timeout = ${CURSOR_STATE_BUSY_MS}`);db.exec("BEGIN");if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'ItemTable'").get())throw unreadable("no_item_table");const select=db.prepare(`SELECT typeof(value) AS kind, CASE WHEN typeof(value) = 'text' AND octet_length(value) <= ${CURSOR_STATE_VALUE_MAX_BYTES} THEN value END AS value FROM ItemTable WHERE key = ?`);const values=new Map;for(const key of CURSOR_STATE_KEYS){const row=select.get(key);if(row===void 0||row.kind==="null")continue;if(row.kind!=="text")throw unreadable("value_type");if(row.value===null)throw unreadable("value_size");if(row.value.trim())values.set(key,row.value)}db.exec("COMMIT");return values}catch(error51){if(error51 instanceof JcodeCursorStateUnreadable)throw error51;const code2=error51.errcode;if(typeof code2!=="number")throw error51;throw unreadable(sqliteReason(code2),code2)}finally{db?.close()}}function publishCursorState(home,destinationRelative,values){if(!values||values.size===0){removeCredentialMirror(home,destinationRelative);return}const scratch=mkdtempSync2(join10(tmpdir2(),"cotal-jcode-cursor-"));try{const file2=join10(scratch,"state.vscdb");const db=new DatabaseSync(file2);try{db.exec("CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)");const insert=db.prepare("INSERT INTO ItemTable (key, value) VALUES (?, ?)");for(const[key,value]of values)insert.run(key,value)}finally{db.close()}copyCredentialFile(home,file2,destinationRelative)}finally{rmSync3(scratch,{recursive:true,force:true})}}function mirrorJcodeCredentials(home,sources2=credentialSources()){privateDirectory(home,{pin:true});const inventory=jcodeCredentialMirrorInventory(home,sources2);const cursorStates=inventory.filter(entry=>entry.family==="cursor-state").map(entry=>({entry,values:readCursorState(entry.source,relative(sources2.externalHome,entry.source))}));for(const entry of inventory)if(entry.family!=="cursor-state")copyCredentialFile(home,entry.source,entry.destinationRelative);for(const{entry,values}of cursorStates)publishCursorState(home,entry.destinationRelative,values)}function removeJcodeCredentials(home,sources2=credentialSources()){let removed=0;for(const entry of jcodeCredentialMirrorInventory(home,sources2))if(removeCredentialMirror(home,entry.destinationRelative))removed++;return removed}function reclaimSocketAlias(alias){let stats;try{stats=lstatSync7(alias)}catch(error51){if(error51.code!=="ENOENT")throw error51;return}rmSync3(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(error51){throw new Error(`cannot create Jcode short API socket alias ${alias}: ${error51.message}`)}const apiSocket=join10(alias,"run","jcode-api.sock");if(Buffer.byteLength(apiSocket)>=MAX_API_SOCKET_BYTES){rmSync3(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:()=>{rmSync3(alias,{force:true});try{rmdirSync2(socketDir)}catch(error51){if(error51.code!=="ENOENT")throw error51}}}}import{randomBytes as randomBytes4}from"node:crypto";import{readFileSync as readFileSync6,readdirSync as readdirSync3,rmSync as rmSync4}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 group=Number(fields[2]);const start=fields[19];if(!(Number.isInteger(parentPid)&&parentPid>=0&&Number.isInteger(group)&&group>=0&&start))return void 0;return fields[0]==="Z"?{pid,parentPid,group,start,zombie:true}:{pid,parentPid,group,start}}if(process.platform==="darwin"||process.platform.endsWith("bsd")){const out=execFileSync4("/bin/ps",["-o","ppid=","-o","pgid=","-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();const match=out.match(/^(\d+)\s+(\d+)\s+(.+)$/u);const parentPid=Number(match?.[1]);const group=Number(match?.[2]);const start=match?.[3]?.trim();return Number.isInteger(parentPid)&&parentPid>=0&&Number.isInteger(group)&&group>=0&&start?{pid,parentPid,group,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(error51){throw new Error(`jcode connector: cannot enumerate launch descendants on ${process.platform}: ${error51.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(error51){const code2=error51.code;if(code2==="ESRCH")return false;if(code2==="EPERM")return true;throw error51}}};function processHasLaunchIdentityFromPs(pid,identityValue,probe){try{const out=probe.ps(pid);return out.includes(`${LAUNCH_IDENTITY_ENV}=${identityValue}`)}catch(error51){const status2=error51.status;if(status2===1&&!probe.pidExists(pid))return false;throw error51}}function launchIdentityProof(pid,identityValue,probe){if(process.platform==="linux"){let environ;try{environ=probe.readEnviron(pid)}catch(error51){const code2=error51.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")return void 0;throw error51}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,readStat=processStat){const owned=[];for(const pid of processPids()){try{if(launchIdentityProof(pid,identityValue,probe)!==true)continue;const stat=readStat(pid);if(stat)owned.push(stat)}catch(error51){const code2=error51.code;if(code2==="ENOENT"||code2==="ESRCH"||code2==="EACCES"||code2==="EPERM")continue;throw new Error(`jcode connector: cannot prove launch-bound identity for PID ${pid}: ${error51.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 file2 of readdirSync3(join11(jcodeHome,"active_pids"))){const pid=Number(readFileSync6(join11(jcodeHome,"active_pids",file2),"utf8").trim());if(isPid(pid))pids.add(pid)}}catch{}pids.delete(process.pid);return[...pids]}var alive=pid=>{const stat=processStat(pid);if(stat)return!stat.zombie;try{process.kill(pid,0);return true}catch(error51){return error51.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)}
|
|
176
176
|
`)}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}var LIFECYCLE_UID=/^[a-z0-9]{26,32}$/u;function onceRecordPath(home,uid2){if(!LIFECYCLE_UID.test(uid2))throw new Error(`jcode connector: "${uid2}" is not a lifecycle uid`);return join11(home,`cotal-once-${uid2}.json`)}function readOnceRecord(home,uid2){const path4=onceRecordPath(home,uid2);let raw;try{raw=readFileSync6(path4,"utf8")}catch(error51){if(error51.code==="ENOENT")return void 0;throw error51}const r=JSON.parse(raw);if(r?.uid!==uid2)throw new Error(`jcode connector: ${path4} does not name once seat ${uid2}`);if(r.retired===true)return{uid:uid2,retired:true};const launches=r.launches;if(!isPid(r.host?.pid)||typeof r.host?.start!=="string"||!r.host.start||!Array.isArray(launches)||launches.length===0||!launches.every(v=>typeof v==="string"&&v.length>0))throw new Error(`jcode connector: ${path4} is not well formed`);return{uid:uid2,host:{pid:r.host.pid,start:r.host.start},launches}}function recordOnceLaunch(home,uid2,record2){const prior=readOnceRecord(home,uid2);if(prior&&"retired"in prior)throw new Error(`jcode connector: once seat ${uid2} was already proved retired \u2014 refusing to launch under it again`);if(prior&&(prior.host.pid!==record2.host.pid||prior.host.start!==record2.host.start))throw new Error(`jcode connector: once seat ${uid2} was launched by another host \u2014 refusing to launch under it`);writeSecretFileAtomic(onceRecordPath(home,uid2),`${JSON.stringify({uid:uid2,host:record2.host,launches:[...prior?.launches??[],record2.identity]})}
|
|
177
177
|
`)}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(error51){socket.close();throw error51}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(error51=>{if(!disposed&&id2!==void 0&&error51 instanceof HarnessError&&error51.code==="timeout")state.late.set(id2,settle);throw error51});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 mkdirSync8,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(error51){return error51.code??error51.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,check2)=>value===void 0||value===null||check2(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(error51){if(error51.code!=="ENOENT")refuse2(`${path4} could not be read (${code(error51)})`);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(error51){return refuse2(`no readable transcript at ${snapshotPath} (${code(error51)})`)}};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(error51){return refuse2(`${snapshotPath} is not valid JSON (${error51.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(error51){return refuse2(`${where} is not valid JSON (${error51.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 hash2=createHash14("sha256").update(snapshot);if(journal)hash2.update(journal);return{sessionId,...typeof session.title==="string"?{title:session.title}:{},transcriptSha256:hash2.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(error51){if(error51.code==="ENOENT")return void 0;throw new Error(`jcode connector: ${markerPath} could not be read (${code(error51)})`)}let marker;try{marker=JSON.parse(raw)}catch(error51){throw new Error(`jcode connector: ${markerPath} is not valid JSON (${error51.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"};mkdirSync8(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}}import{closeSync as closeSync4,lstatSync as lstatSync8,openSync as openSync5,readdirSync as readdirSync4,unlinkSync as unlinkSync6}from"node:fs";import{join as join13}from"node:path";function storedSessionsPath(jcodeHome){return join13(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(error51){const code2=error51.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=join13(inspection.path,`${WRITE_PROBE_PREFIX}${process.pid}`);try{const fd=openSync5(probe,"wx",384);closeSync4(fd);unlinkSync6(probe);return void 0}catch(error51){return{path:inspection.path,code:error51.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 map2=({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:map2,forgetOpenRun(runId){if(open6===runId){open6=null;tools.clear()}}}}import{access,open as open5}from"node:fs/promises";import{constants as constants8}from"node:fs";import{basename as basename3,dirname as dirname9,join as join14}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=error51=>error51 instanceof Error&&error51.code==="ENOENT";function jcodeJournalPath(jcodeHome,sessionId){return join14(jcodeHome,"sessions",`${sessionId}.journal.jsonl`)}async function captureJcodeJournalCursor(path4,waitMs=JOURNAL_WAIT_MS){const file2=new JsonlFileSource(path4);const deadline=performance.now()+waitMs;let retryMs=RETRY_INITIAL_MS;for(;;){try{return(await file2.read(void 0)).cursor}catch(error51){if(!isMissing(error51))throw error51;const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`Jcode AG-UI source: session journal did not appear within ${waitMs}ms`,{cause:error51});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(error51){if(!isMissing(error51)&&!(error51 instanceof JsonlFileResetError))throw error51;const fresh=await this.foldedSince();if(fresh===void 0)throw error51;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,constants8.R_OK);return await this.file.readFromBeginning()}catch(error51){if(!isMissing(error51))throw error51;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:error51});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=join14(dirname9(this.path),`${sessionId}.json`);try{const file2=await open5(snapshot,constants8.O_RDONLY|(constants8.O_NOFOLLOW??0));try{if(!(await file2.stat()).isFile())throw new Error("Jcode AG-UI source: session snapshot is not a regular file");const parsed=JSON.parse(await file2.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 file2.close()}}catch(error51){if(isMissing(error51))return false;throw error51}}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(error51){if(!isMissing(error51)&&!(error51 instanceof JsonlFileResetError))throw error51;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(error51){if(!(error51 instanceof HarnessError))return false;if(PERMANENT_BRIDGE_RECOVERY_CODES.has(error51.code))return true;if(error51.code==="connect_failed")return PERMANENT_BRIDGE_CONNECT_CAUSE_CODES.has(error51.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(error51,since=Date.now()){if(!(error51 instanceof HarnessError))return void 0;const source=String(error51.code);const code2=PRESENCE_CONDITION_CODES.has(source)?source:"failed";return{code:code2,source,message:error51.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=join15(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[join15(root,".cotal"),managedRoot,home]){try{if(lstatSync9(path4).isSymbolicLink())throw new Error(`refusing symlinked managed path: ${path4}`)}catch(error51){if(error51.code!=="ENOENT")throw error51}}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(join15(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=join15(home,"mcp.json");rmSync5(path4,{force:true});let fd;try{fd=openSync6(path4,"wx",384)}catch(error51){throw new Error(`refusing to write Jcode MCP config at ${path4}: ${error51.message}`)}try{writeFileSync4(fd,JSON.stringify(mcp))}finally{closeSync5(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=join15("/tmp",`cotal-jcode-${id2}`);return{dir,path:join15(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=briefing(config2,"jcode");return persona?`${persona}
|
|
178
178
|
|
|
@@ -180,12 +180,13 @@ ${mesh}`:mesh}function constantTokenMatches(presented,expected){if(typeof presen
|
|
|
180
180
|
`)}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] the tool relay socket was deleted and could not be re-bound: ${error51.message}
|
|
181
181
|
`)}finally{rebinding=false}})()},RELAY_REBIND_POLL_MS);watch.unref?.()}return server}function closeServer(server){return new Promise(resolve4=>server?.close(()=>resolve4())??resolve4())}async function retireRelay(server,endpoint){await closeServer(server);if(process.platform!=="win32")rmSync5(endpoint.dir,{recursive:true,force:true})}function noCotalEnv(){const env={};for(const[key,value]of Object.entries(process.env))if(value!==void 0&&!key.startsWith("COTAL_"))env[key]=value;return env}async function runJcodeHost(){const config2=configFromEnv();config2.connector="jcode";const control=controlFromEnv();if(!control)throw new Error("jcode connector: managed session has no control endpoint");const binary=process.env.COTAL_JCODE_BIN?.trim()||"jcode";const tuiOverride=envFlag(process.env,"COTAL_JCODE_TUI");const bootPrompt=process.env.COTAL_JCODE_PROMPT?.trim();const onceUid=process.env.COTAL_JCODE_ONCE==="1"?config2.lifecycleUid:void 0;if(process.env.COTAL_JCODE_ONCE==="1"&&!onceUid)throw new Error("jcode connector: a once seat has no lifecycle uid");let pendingKickoff=bootPrompt;const readinessBudgetMs=readinessTurnTimeoutMs();const requestTimeoutMs=requestTimeoutOverrideMs();const eventsArmed=eventPlaneArmed(config2);const eventsWorkspaceRoot=eventsArmed?resolveEventsStateRoot(process.env):void 0;const def=process.env.COTAL_AGENT_FILE?.trim()?loadAgentFile(process.env.COTAL_AGENT_FILE.trim()):void 0;const cwd=process.cwd();assertNoProjectMcpConfig(cwd);const home=privateAgentHome(config2.space,config2.name);installJcodeDiagnosticLog(home);try{const stopped=await stopOrphanedTree({home});if(stopped.length)writeJcodeDiagnostic(`[cotal-jcode] stopped ${stopped.length} Jcode process(es) left running by a previous lifecycle of this seat
|
|
182
182
|
`)}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|
|
183
|
-
`)}let socketHome;const resumeSource=process.env.COTAL_JCODE_RESUME?.trim();let fork;try{mirrorJcodeCredentials(home);if(resumeSource){const sourceHome=process.env.COTAL_JCODE_RESUME_HOME?.trim();if(!sourceHome)throw new Error("COTAL_JCODE_RESUME_HOME is not set \u2014 the launch must name the home it validated the source in");fork=forkJcodeSession({sourceHome,sessionId:resumeSource,seatHome:home,cwd})}socketHome=shortSocketHome(home)}catch(error51){if(error51 instanceof JcodeCursorStateUnreadable)throw error51;throw new JcodeConnectorError("private_state","jcode connector: the seat's private Jcode state could not be prepared",{cause:error51})}const
|
|
183
|
+
`)}let socketHome;const resumeSource=process.env.COTAL_JCODE_RESUME?.trim();let fork;try{mirrorJcodeCredentials(home);if(resumeSource){const sourceHome=process.env.COTAL_JCODE_RESUME_HOME?.trim();if(!sourceHome)throw new Error("COTAL_JCODE_RESUME_HOME is not set \u2014 the launch must name the home it validated the source in");fork=forkJcodeSession({sourceHome,sessionId:resumeSource,seatHome:home,cwd})}socketHome=shortSocketHome(home)}catch(error51){if(error51 instanceof JcodeCursorStateUnreadable)throw error51;throw new JcodeConnectorError("private_state","jcode connector: the seat's private Jcode state could not be prepared",{cause:error51})}const removeCredentials=()=>{try{removeJcodeCredentials(home)}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] the seat's credential copies could not be removed: ${error51.message}
|
|
184
|
+
`)}};const relay=relayEndpoint(config2.space,config2.name);scrubLaunchMaterial();for(const key of Object.keys(process.env))if(key.startsWith("COTAL_"))delete process.env[key];const agent=new MeshAgent(config2);const relayServer=await startRelay(agent,config2,relay);writeMcpConfig(home,relay,config2);let eventLock;let mapper;const eventWaitStop=new AbortController;const events=eventsArmed?new AguiEmitterHolder(async journalPath=>{const workspaceRoot=eventsWorkspaceRoot;if(!sessionId)throw new Error("jcode connector: cannot start AG-UI without a Harness session id");const threadId=sessionId;const expectedPath=jcodeJournalPath(socketHome.jcodeHome,threadId);if(resolve3(journalPath)!==resolve3(expectedPath))throw new Error(`jcode connector: event source ${journalPath} does not belong to session ${threadId}`);const principal=principalKey(agent.ep.principal.owner,agent.ep.principal.actor).key;const{walPath,subjectPath,lock}=await ensureEventWalDir({workspaceRoot,space:config2.space,principal,threadId});eventLock=lock;const subjectFrontier=await FileSubjectFrontier.open(subjectPath,{space:config2.space,principal});const wal=await EventWal.open(walPath,{space:config2.space,threadId,principal,subjectMayExist:false});await initializeJcodeEventBoundary(journalPath,wal);const resumeBrackets=wal.pending===null?wal.brackets:wal.pending.brackets;mapper=createJcodeMapper({threadId,mintRunId:()=>randomUUID9(),resumeRunId:resumeBrackets?.run,resumeTools:resumeBrackets?.tools});return AguiEmitter.start({endpoint:agent.ep,wal,subjectFrontier,source:positionedJcodeJournalSource(new JcodeJournalSource(journalPath)),map:mapper.map,onUnreadable:gap=>writeJcodeDiagnostic(`[cotal-jcode] AG-UI source: skipped an unreadable journal record at offset ${gap.offset} (${gap.bytes} bytes): ${gap.reason}
|
|
184
185
|
`)})},{onError:eventPlaneStopped({log:line=>writeJcodeDiagnostic(`[cotal-jcode] ${line}
|
|
185
186
|
`)}),sourceEnd:journalPath=>new JcodeJournalSource(journalPath).end(),onRunClosed:runId=>mapper?.forgetOpenRun(runId),waitLive:()=>new Promise((resolve4,reject)=>{const live=()=>agent.connected&&agent.transportConnected;const release=()=>{agent.off("connection",onConnection);agent.off("transport",onTransport);eventWaitStop.signal.removeEventListener("abort",onStop)};const finish=()=>{release();resolve4()};const onStop=()=>{release();reject(new Error("seat stopping while the mesh connection is down; unpublished events stay in the journal"))};const onConnection=e=>{if(e.connected&&agent.transportConnected)finish()};const onTransport=e=>{if(e.connected&&agent.connected)finish()};agent.on("connection",onConnection);agent.on("transport",onTransport);eventWaitStop.signal.addEventListener("abort",onStop);if(live())finish();else if(eventWaitStop.signal.aborted)onStop()})}):void 0;let eventJournal;const closeEventRun=error51=>{if(!events?.running||!eventJournal)return;events.flush(eventJournal);events.closeRun(Date.now(),error51?{message:error51.message,code:error51.name}:void 0)};const ensureEventsBound=async()=>{if(!events||!eventJournal||events.running)return;events.adopt(eventJournal);await events.settled()};const releaseEventLock=async()=>{const lock=eventLock;eventLock=void 0;if(!lock)return;try{await lock.release()}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] event WAL lock release failed: ${error51.message}
|
|
186
187
|
`)}};let instance;let launchIdentity;let launchIdentityValue;let client;let bridgeStderr="";let tui;let stopping=false;let reconnecting=false;let bridgeRecoveryUsed=false;let sessionId;let driving=false;let turnActive=false;let briefed=false;let initialized=false;let wakeQueued=false;let pendingMentionWake;let surfacedIds=[];let nativeTreePreserved=false;const unansweredSteers=new Set;const releaseUnansweredSteers=()=>{for(const release of unansweredSteers)release();unansweredSteers.clear()};let sessionDispatch=Promise.resolve();let unsettledLapsedDispatches=0;const oweAcceptanceDebt=settledWhenHarnessDone=>{unsettledLapsedDispatches+=1;void settledWhenHarnessDone.then(()=>{unsettledLapsedDispatches-=1},()=>{unsettledLapsedDispatches-=1})};let acceptanceSuspectUntilBridgeReplaced=false;let deferralStartedAt;let deferralAnnounced=false;let queuedTurnTierStopped=false;let bridgeReplacementRequestedForSuspicion=false;const withExclusiveDispatch=async operation=>{const previous=sessionDispatch;let release;sessionDispatch=new Promise(resolve4=>{release=resolve4});await previous.catch(()=>{});try{return await operation()}finally{release()}};const onceAccepted=(on,session,withinMs)=>new Promise(resolve4=>{const done=()=>{clearTimeout(timer);on.off("message_accepted",listener);resolve4()};const listener=event=>{if("session_id"in event&&event.session_id===session)done()};const timer=setTimeout(done,withinMs);timer.unref?.();on.on("message_accepted",listener)});let reservedIds=new Set;const heldReservations=new Set;const releaseUnheldReservations=()=>{const held2=new Set;for(const batch of heldReservations)for(const key of batch)held2.add(key);reservedIds=held2};const promoteToSurfaced=keys=>{const known=new Set(surfacedIds);for(const key of keys)if(!known.has(key))surfacedIds.push(key)};const reserveForHandover=keys=>{if(!agent.holdInFlight(keys))return void 0;const batch=new Set(keys);heldReservations.add(batch);for(const key of keys)reservedIds.add(key);let released=false;return()=>{if(released)return;released=true;if(!heldReservations.delete(batch))return;agent.releaseInFlight([...batch].filter(key=>!surfacedIds.includes(key)));const stillHeld=new Set;for(const other of heldReservations)for(const key of other)stillHeld.add(key);for(const key of keys)if(!stillHeld.has(key))reservedIds.delete(key)}};let steering=false;let softInterruptFailed=false;let steerSettled=Promise.resolve();const receivedAt=new Map;const stopPrivateJcode=async opts=>{if(!opts?.skipClientClose)await client?.close().catch(()=>{});else void client?.close().catch(()=>{});client=void 0;if(launchIdentity&&launchIdentityValue)await stopPrivateTree({jcodeHome:socketHome.jcodeHome,launch:launchIdentity,identityValue:launchIdentityValue})};const launchPrivateJcode=async deadline=>{const remaining=()=>deadline===void 0?void 0:Math.max(1,deadline-Date.now());const exitListenersBefore=new Set(process.listeners("exit"));const launchBound=launchIdentityEnv();launchIdentityValue=launchBound.value;recordLaunch(home,{identity:launchBound.value,host:captureProcessIdentity(process.pid)});if(onceUid)recordOnceLaunch(home,onceUid,{identity:launchBound.value,host:captureProcessIdentity(process.pid)});instance=await launchInstance({binary,jcodeHome:socketHome.jcodeHome,workingDir:cwd,inheritLogins:false,env:{JCODE_DISABLE_CLAUDE_MCP:"1",JCODE_NO_AUTO_UPDATE:"1",[launchBound.key]:launchBound.value},...remaining()!==void 0?{startupTimeoutMs:remaining()}:{}});const sdkExitListeners=process.listeners("exit").filter(listener=>!exitListenersBefore.has(listener));for(const listener of sdkExitListeners)process.removeListener("exit",listener);if(sdkExitListeners.length!==1)throw new Error(`jcode connector: expected one SDK instance exit hook, found ${sdkExitListeners.length} \u2014 refusing unsafe lifecycle ownership`);launchIdentity=captureProcessIdentity(instance.process.pid);bridgeStderr="";instance.process.stderr?.on("data",chunk=>{bridgeStderr+=String(chunk);if(bridgeStderr.length>16384)bridgeStderr=bridgeStderr.slice(-8e3)});const perRequestMs=remaining()??requestTimeoutMs;return connectSteerClient(instance.socketPath,perRequestMs)};const launchTui=()=>{const runtime=join15(socketHome.jcodeHome,"run");tui=spawn2(binary,["--socket",join15(runtime,"jcode.sock"),"--resume",sessionId],{cwd,env:{...noCotalEnv(),JCODE_HOME:socketHome.jcodeHome,JCODE_RUNTIME_DIR:runtime,JCODE_SOCKET:join15(runtime,"jcode.sock")},stdio:"inherit"});tui.once("exit",code2=>void shutdown(code2??0))};const shutdown=async(code2=0,signal)=>{if(stopping)return;stopping=true;let exit=code2;if(onceUid){try{await stopPrivateJcode({skipClientClose:true})}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|
|
187
188
|
`);exit=1}}agent.releaseInFlight(surfacedIds);surfacedIds=[];for(const batch of heldReservations)agent.releaseInFlight([...batch]);heldReservations.clear();eventWaitStop.abort();if(fallbackTimer!==void 0){clearTimeout(fallbackTimer);fallbackTimer=void 0}try{tui?.kill("SIGTERM")}catch{}await retireRelay(relayServer,relay);try{closeEventRun();await events?.settled();await events?.close()}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] AG-UI shutdown failed: ${error51.message}
|
|
188
|
-
`);exit=1}await releaseEventLock();try{await stopPrivateJcode()}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|
|
189
|
+
`);exit=1}await releaseEventLock();try{await stopPrivateJcode();removeCredentials()}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|
|
189
190
|
`);exit=1}socketHome.dispose();await agent.stop().catch(()=>{});if(signal)writeJcodeDiagnostic(`[cotal-jcode] received ${signal}; shutting down; signal sender unavailable from Node.js
|
|
190
191
|
`);process.exit(exit)};const ERROR_RETRY_INITIAL_MS2=1e3;const ERROR_RETRY_MAX_MS=6e4;const ERROR_RETRY_GIVE_UP=8;let errorRetryMs=ERROR_RETRY_INITIAL_MS2;let errorRetryTimer;let consecutiveFailures=0;let turnConditionPublished=false;let lastTurnError;const relayTurnCondition=condition=>{if(condition)lastTurnError=condition.message;if(!condition&&!turnConditionPublished)return;turnConditionPublished=condition!==null;void agent.setCondition(condition).catch(()=>{})};const BRIDGE_RECOVERY_RETRY_MS=1e3;const sleep2=ms=>new Promise(resolve4=>setTimeout(resolve4,ms));const hasDriveWork=()=>pendingKickoff!==void 0||pendingMentionWake!==void 0||agent.pendingWake()>0||wakeQueued;const scheduleErrorRetry=()=>{if(stopping||errorRetryTimer)return;if(consecutiveFailures>=ERROR_RETRY_GIVE_UP){writeJcodeDiagnostic(`[cotal-jcode] giving up after ${consecutiveFailures} consecutive failed turns - the batch stays un-acked and will redeliver; the seat stays degraded until a new wake arrives
|
|
191
192
|
`);return}if(agent.pendingWake()===0&&!wakeQueued&&!pendingMentionWake)return;const delay3=errorRetryMs;errorRetryMs=Math.min(errorRetryMs*2,ERROR_RETRY_MAX_MS);errorRetryTimer=setTimeout(()=>{errorRetryTimer=void 0;if(stopping||driving||turnActive)return;if(hasDriveWork())void drive()},delay3);errorRetryTimer.unref?.()};const sessionBusy=()=>driving||turnActive;const publishInboundHealth=()=>{const pending=agent.peekInbox("automatic");const live=new Set(pending.map(item=>item.recvKey));for(const key of receivedAt.keys())if(!live.has(key))receivedAt.delete(key);const queued=pending.length;if(queued===0){void agent.setStatus(sessionBusy()?"working":"idle","").catch(()=>{});return}let oldest;for(const item of pending){const at=receivedAt.get(item.recvKey);if(at===void 0)continue;if(oldest===void 0||at<oldest)oldest=at}const ageS=oldest===void 0?0:Math.max(0,Math.round((Date.now()-oldest)/1e3));const activity=`inbound: ${queued} automatic queued, oldest ${ageS}s`;void agent.setStatus(sessionBusy()?"working":"waiting",activity).catch(()=>{})};const commitSteeredIfHostIdle=async()=>{if(driving)return;await steerSettled;if(driving||!surfacedIds.length)return;const committed=surfacedIds;surfacedIds=[];agent.drainInboxDeliveries(committed);agent.releaseInFlight(committed);publishInboundHealth()};const finishHostIdleTurn=async()=>{await steerSettled;if(!sessionBusy())releaseUnansweredSteers();await commitSteeredIfHostIdle();if(!sessionBusy()&&!reconnecting&&hasDriveWork())void drive()};const drive=async()=>{if(stopping||reconnecting||!initialized||driving||turnActive||!client||!sessionId)return;if(events){await ensureEventsBound();await events.settled();if(stopping)return}driving=true;if(pendingKickoff!==void 0&&steering)writeJcodeDiagnostic("[cotal-jcode] startup kickoff waiting for in-flight steering\n");await steerSettled;if(stopping||reconnecting||turnActive||!client||!sessionId){driving=false;writeJcodeDiagnostic("[cotal-jcode] deferred turn after steering: native session unavailable\n");return}releaseUnansweredSteers();if(surfacedIds.length){const committed=surfacedIds;surfacedIds=[];agent.drainInboxDeliveries(committed);agent.releaseInFlight(committed)}wakeQueued=pendingKickoff!==void 0&&agent.peekInbox("automatic").length>0;const parts=[];let ids=[];let turnIds=[];const mentionWake=pendingKickoff===void 0?pendingMentionWake:void 0;const turnPeek=agent.peekPendingTurns();if(pendingKickoff!==void 0)parts.push(pendingKickoff);else{const inbox=agent.peekInbox("automatic").filter(item=>!reservedIds.has(item.recvKey));const injection=formatInjection(inbox);if(!injection&&!turnPeek&&!mentionWake){driving=false;return}if(injection){ids=inbox.map(item=>item.recvKey);parts.push(injection)}}if(mentionWake)parts.push(mentionWake.hint);if(turnPeek){turnIds=turnPeek.goalIds;parts.push(turnPeek.text)}if(!briefed){briefed=true;const briefing2=agent.channelBriefing();if(briefing2)parts.unshift(briefing2)}if(!agent.holdInFlight(ids)){driving=false;return}turnActive=true;surfacedIds=[...ids];releaseUnheldReservations();relayTurnCondition(null);publishInboundHealth();let turnClient;try{turnClient=client;pendingKickoff=void 0;const{dispatched:runTurn}=await withExclusiveDispatch(async()=>{const attributable=unsettledLapsedDispatches===0&&!acceptanceSuspectUntilBridgeReplaced;if(stopping||!agent.claimTurns(turnIds))throw new Error("the once task ended, or the seat began stopping, while its send waited at the dispatch gate; nothing was sent");const dispatched=turnClient.run(sessionId,parts.join("\n\n"),{autoApprove:true});dispatched.catch(()=>{});if(attributable&&turnIds.length){const surface=event=>{if(!("session_id"in event&&event.session_id===sessionId))return;stopSurfacing();agent.commitSurfacedTurns(turnIds)};const stopSurfacing=()=>{turnClient.off("message_accepted",surface)};turnClient.on("message_accepted",surface);void dispatched.then(stopSurfacing,stopSurfacing)}let acknowledgedHere=false;const noteAccepted=event=>{if("session_id"in event&&event.session_id===sessionId)acknowledgedHere=true};turnClient.on("message_accepted",noteAccepted);try{await Promise.race([dispatched.then(()=>void 0,()=>void 0),onceAccepted(turnClient,sessionId,RUN_ACCEPT_WINDOW_MS)])}finally{turnClient.off("message_accepted",noteAccepted)}if(!attributable||!acknowledgedHere)agent.releaseTurns(turnIds);if(!acknowledgedHere)oweAcceptanceDebt(dispatched);return{dispatched}});await runTurn;closeEventRun();await events?.settled();if(reconnecting||client!==turnClient)throw new Error("Jcode Harness connection closed during the turn; leaving the inbox batch unacknowledged");await steerSettled;const committed=surfacedIds;surfacedIds=[];if(committed.length)agent.drainInboxDeliveries(committed);agent.releaseInFlight(committed);publishInboundHealth();errorRetryMs=ERROR_RETRY_INITIAL_MS2;consecutiveFailures=0;lastTurnError=void 0;if(mentionWake&&pendingMentionWake===mentionWake)pendingMentionWake=void 0}catch(error51){closeEventRun(error51);await events?.settled();if(!nativeTreePreserved||!reconnecting&&client===turnClient){agent.releaseInFlight(surfacedIds);surfacedIds=[]}consecutiveFailures++;const condition=jcodeTurnCondition(error51);if(condition)relayTurnCondition(condition);writeJcodeDiagnostic(`[cotal-jcode] turn failed (${consecutiveFailures} in a row): ${error51.message}
|
|
@@ -221,7 +222,7 @@ ${bridgeStderr}`))}const resumed=prior!==void 0&&(fork?fork.briefed:true);sessio
|
|
|
221
222
|
`);throw new Error("jcode connector: the cotal MCP bridge did not become callable during its two mandatory readiness turns \u2014 refusing to join a mesh seat without its tool surface")}writeJcodeDiagnostic(bootPrompt?`[cotal-jcode] pre-join readiness outcome: orientation proved; joining, then submitting the spawn --prompt
|
|
222
223
|
`:`[cotal-jcode] pre-join readiness outcome: orientation proved; joining with no spawn --prompt
|
|
223
224
|
`);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}
|
|
224
|
-
`)}}else{pendingKickoff=joinNotice}initialized=true;if(!readinessTurnOpen)await ensureEventsBound();if(hasDriveWork())await drive()}catch(error51){if(stopping)return;startControl?.close();await retireRelay(relayServer,relay);try{await stopPrivateJcode({skipClientClose:error51 instanceof JcodeConnectorError&&error51.code==="readiness_timeout"})}catch(teardown){writeJcodeDiagnostic(`[cotal-jcode] ${teardown.message}
|
|
225
|
+
`)}}else{pendingKickoff=joinNotice}initialized=true;if(!readinessTurnOpen)await ensureEventsBound();if(hasDriveWork())await drive()}catch(error51){if(stopping)return;startControl?.close();await retireRelay(relayServer,relay);try{await stopPrivateJcode({skipClientClose:error51 instanceof JcodeConnectorError&&error51.code==="readiness_timeout"});removeCredentials()}catch(teardown){writeJcodeDiagnostic(`[cotal-jcode] ${teardown.message}
|
|
225
226
|
`)}socketHome.dispose();await agent.stop().catch(()=>{});throw error51}}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","cursor_state_unreadable","provider_auth_refused","provider_payment_required","provider_forbidden","provider_rate_limited","provider_request_failed"]);function startupFailureCode(error51){if(error51 instanceof Error&&error51.message.startsWith("jcode connector: project MCP configuration"))return"project_mcp_config";const code2=typeof error51==="object"&&error51!==null&&"code"in error51?error51.code:void 0;return typeof code2==="string"&&STARTUP_FAILURE_CODES.has(code2)?code2:"unknown"}function renderEffortRefusal(error51){if(!(error51 instanceof JcodeEffortRefusal))return void 0;const ladder=error51.acceptedLadder.length?`; accepted tiers: ${error51.acceptedLadder.join(", ")}`:"";const via=error51.apiMethod?` via ${JSON.stringify(error51.apiMethod)}`:"";return`Jcode reasoning effort refused: requested tier ${JSON.stringify(error51.requestedTier)}; effective model ${JSON.stringify(error51.effectiveModel)}; provider ${JSON.stringify(error51.provider)}${via}; provider code ${error51.providerCode}${ladder}`}runJcodeHost().catch(error51=>{if(error51 instanceof JcodeEffortUnsupported){const via=error51.apiMethod?` via ${JSON.stringify(error51.apiMethod)}`:"";writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode model ${JSON.stringify(error51.effectiveModel)} on provider ${JSON.stringify(error51.provider)}${via} does not support reasoning effort; requested tier ${JSON.stringify(error51.requestedTier)} was not applied.
|
|
226
227
|
`);process.exit(1)}const effortRefusal=renderEffortRefusal(error51);if(effortRefusal){writeJcodeDiagnostic(`[cotal-jcode] fatal: ${effortRefusal}
|
|
227
228
|
`);process.exit(1)}if(error51 instanceof JcodeReadinessProviderRefusal){writeJcodeDiagnostic(`[cotal-jcode] fatal: Jcode readiness turn refused ${error51.parameter} ${JSON.stringify(error51.value)} (${error51.providerCode}); inspect the private Jcode logs for other details.
|