@cotal-ai/connector-claude-code 0.162.0 → 0.163.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ declare const WATCH: {
9
9
  * conversation already holds; an approved request is finished with `cotal_connect` and that id. */
10
10
  export interface ApprovalNotice {
11
11
  name: string;
12
- status: "approved" | "denied" | "expired";
12
+ status: "approved" | "denied" | "expired" | "refused";
13
13
  id: string;
14
14
  }
15
15
  export interface AppHostOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"app-host.d.ts","sourceRoot":"","sources":["../src/app-host.ts"],"names":[],"mappings":"AAKA,OAAO,EAAyF,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAkB,KAAK,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAQ9N;mGACmG;AACnG,QAAA,MAAM,KAAK;;;CAAsC,CAAC;AAElD;oGACoG;AACpG,MAAM,WAAW,cAAc;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAEvG,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,0FAA0F;IAC1F,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC;IAC9D,+EAA+E;IAC/E,WAAW,CAAC,EAAE,CAAC,UAAU,EAAE,iBAAiB,KAAK,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACvF,oFAAoF;IACpF,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACxE,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAC5C;AAyDD,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,OAAO,CAqPxD"}
1
+ {"version":3,"file":"app-host.d.ts","sourceRoot":"","sources":["../src/app-host.ts"],"names":[],"mappings":"AAKA,OAAO,EAAyF,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAkB,KAAK,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAQ9N;mGACmG;AACnG,QAAA,MAAM,KAAK;;;CAAsC,CAAC;AAElD;oGACoG;AACpG,MAAM,WAAW,cAAc;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAEnH,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,0FAA0F;IAC1F,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC;IAC9D,+EAA+E;IAC/E,WAAW,CAAC,EAAE,CAAC,UAAU,EAAE,iBAAiB,KAAK,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACvF,oFAAoF;IACpF,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACxE,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAC5C;AAyDD,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,OAAO,CAkQxD"}
@@ -1 +1 @@
1
- {"version":3,"file":"approval-notice.d.ts","sourceRoot":"","sources":["../src/approval-notice.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,eAAO,MAAM,WAAW,QAAmB,CAAC;AAG5C,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAQxE;AAED,6FAA6F;AAC7F,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,MAAM,CAUvD"}
1
+ {"version":3,"file":"approval-notice.d.ts","sourceRoot":"","sources":["../src/approval-notice.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,eAAO,MAAM,WAAW,QAAmB,CAAC;AAG5C,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAQxE;AAED,6FAA6F;AAC7F,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,MAAM,CAYvD"}
Binary file
Binary file
package/dist/mcp.cjs CHANGED
@@ -135,7 +135,7 @@ ${history.map(format).join("\n")}
135
135
  (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(resolve=>{let settled=false;const done=ok3=>{if(settled)return;settled=true;resolve(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 receipt2="";sock.on("data",d=>{receipt2+=d;if(!receipt2.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}=endpoint;const digest=(0,import_node_crypto17.createHash)("sha256").update(endpoint.token).digest();const server=(0,import_node_net3.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"||path.startsWith("\0")||error51?.code!=="EADDRINUSE")return emit(event,...args);retried=true;let original;try{original=(0,import_node_fs11.lstatSync)(path);if(!original.isSocket())return emit(event,...args)}catch(e){if(e.code!=="ENOENT")return emit(event,...args)}const probe=(0,import_node_net3.connect)(path);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=(0,import_node_fs11.lstatSync)(path);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}(0,import_node_fs11.unlinkSync)(path)}catch(e){if(e.code!=="ENOENT"){emit("error",e);return}}server.listen(path)};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}
136
136
  `);if(opts.fatalBind&&!bound)process.exit(1)});server.listen(path,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path}
137
137
  `)});return server}function prepareInlineDelivery(agent,options){if(!/^[A-Za-z0-9_-]{1,128}$/.test(options.connectionId))throw new Error("invalid inline connection identity");const maxItem=options.maxItemCodePoints??1024;const maxItems=options.maxItems??8;if(!Number.isInteger(maxItem)||maxItem<1||!Number.isInteger(maxItems)||maxItems<1)throw new Error("inline delivery limits must be positive whole numbers");const pending=agent.peekInbox("automatic");const queued=agent.inboxCount("automatic");const selected=[];const render=items=>{const remaining=queued-items.length;return{text:`Cotal: inline messages for connection_id ${options.connectionId}.
138
- `+formatInjection(items,{metadata:true})+"\nThese complete messages were delivered inline; do not fetch them again with cotal_inbox. Native delivery can repeat after an unconfirmed handoff; use message_id to avoid repeating work."+(remaining?` ${remaining} other message${remaining===1?" remains":"s remain"} pending; use cotal_inbox to read those.`:""),count:items.length,remaining}};for(const item of pending){if(selected.length>=maxItems)break;if(agent.isInFlight(item.recvKey)||Array.from(fmtDeliveryItem(item)).length>maxItem)continue;const candidate2=[...selected,{...item}];if(options.fits(render(candidate2)))selected.push(candidate2[candidate2.length-1])}if(!selected.length)return void 0;const keys=selected.map(item=>item.recvKey);if(!agent.holdInFlight(keys))return void 0;let settled=false;return{payload:render(selected),current(){const live=new Set(agent.peekInbox("automatic").map(item=>item.recvKey));return!settled&&!agent.stopping&&keys.every(key=>live.has(key))},settle(delivered){if(settled)return;settled=true;agent.releaseInFlight(keys);if(delivered)agent.drainInboxDeliveries(keys)}}}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const 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}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText2=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText2?`: ${errorText2}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path8=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.162.0";function loadDocsMetadata(){return{"version":"0.162.0","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs12.readFileSync)((0,import_node_path8.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1230265||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="c7963a1480354098e4ce4da4c3418b2f4ff2ecf452bf9dfdeb44d0dd4829ce99")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,9323],[9323,31350],[31350,35747],[35747,40128],[40128,43688],[43688,50491],[50491,54595],[54595,64392],[64392,68544],[68544,73062],[73062,75346],[75346,79357],[79357,110728],[110728,126241],[126241,141994],[141994,160063],[160063,175901],[175901,190952],[190952,206892],[206892,230334],[230334,236064],[236064,245879],[245879,266153],[266153,270642],[270642,308768],[308768,318488],[318488,349441],[349441,366942],[366942,391107],[391107,422026],[422026,436232],[436232,438179],[438179,447055],[447055,463660],[463660,471497],[471497,475116],[475116,478497],[478497,481800],[481800,483931],[483931,486704],[486704,491565],[491565,493462],[493462,497021],[497021,509165],[509165,517956],[517956,521481],[521481,528754],[528754,533798],[533798,536705],[536705,547225],[547225,550202],[550202,558754],[558754,561744],[561744,566689],[566689,578847],[578847,591140],[591140,597110],[597110,604691],[604691,608040],[608040,610989],[610989,618546],[618546,622262],[622262,624472],[624472,627934],[627934,631351],[631351,632465],[632465,634214],[634214,637877],[637877,642518],[642518,649154],[649154,659664],[659664,672980],[672980,674817],[674817,687802],[687802,693189],[693189,697145],[697145,699654],[699654,704696],[704696,718883],[718883,725658],[725658,732649],[732649,733466],[733466,737842],[737842,743762],[743762,747140],[747140,751348],[751348,756438],[756438,762019],[762019,765441],[765441,769032],[769032,774197],[774197,777840],[777840,791066],[791066,793884],[793884,796567],[796567,799234],[799234,801725],[801725,805745],[805745,810490],[810490,813499],[813499,882439],[882439,885510],[885510,886703],[886703,893204],[893204,901943],[901943,912721],[912721,921532],[921532,926715],[926715,1185744],[1185744,1225053],[1225053,1230265]];var sourceLengths=[4844,4048,13310,87378,12190,10741,36165,17849,9941,85121,37758,11019,5079,9872,85545,41733,44337,51405,43738,43514,43587,66202,14399,25780,58259,10129,113e3,26839,93535,49557,72388,95384,39154,8216,22172,44626,21302,8796,8035,7790,4874,6360,12290,4537,8347,32337,21939,8745,47165,12743,7133,27685,7140,22325,6860,12405,31433,32561,14963,18466,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11102,16082,26828,34218,4227,35397,12378,9651,8201,13306,98055,16844,17247,1638,10013,15381,7818,10170,12738,14071,7511,9014,12695,8527,35301,6519,6405,6095,6007,9711,11859,7205,203350,6927,2473,15538,22385,27911,21160,12616,751268,111139,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((0,import_node_zlib.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=(0,import_node_fs12.readFileSync)((0,import_node_path8.join)(__dirname,"docs-index.bin"));if(packed.length!==631356||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="b61ab564f19fdb007b14229bcac57f206aa8fb04cc7b3773ca1efa9a0d5989b6")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return(0,import_node_zlib.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}
138
+ `+formatInjection(items,{metadata:true})+"\nThese complete messages were delivered inline; do not fetch them again with cotal_inbox. Native delivery can repeat after an unconfirmed handoff; use message_id to avoid repeating work."+(remaining?` ${remaining} other message${remaining===1?" remains":"s remain"} pending; use cotal_inbox to read those.`:""),count:items.length,remaining}};for(const item of pending){if(selected.length>=maxItems)break;if(agent.isInFlight(item.recvKey)||Array.from(fmtDeliveryItem(item)).length>maxItem)continue;const candidate2=[...selected,{...item}];if(options.fits(render(candidate2)))selected.push(candidate2[candidate2.length-1])}if(!selected.length)return void 0;const keys=selected.map(item=>item.recvKey);if(!agent.holdInFlight(keys))return void 0;let settled=false;return{payload:render(selected),current(){const live=new Set(agent.peekInbox("automatic").map(item=>item.recvKey));return!settled&&!agent.stopping&&keys.every(key=>live.has(key))},settle(delivered){if(settled)return;settled=true;agent.releaseInFlight(keys);if(delivered)agent.drainInboxDeliveries(keys)}}}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const 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}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText2=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText2?`: ${errorText2}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path8=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.163.0";function loadDocsMetadata(){return{"version":"0.163.0","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs12.readFileSync)((0,import_node_path8.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1233245||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="5e1e5ce542cc1e9df966a26e3a4ea77ff0187763cef4c3244714f434bbf91853")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,9323],[9323,31350],[31350,35747],[35747,40128],[40128,43688],[43688,50491],[50491,54595],[54595,64392],[64392,68544],[68544,73062],[73062,75346],[75346,79357],[79357,111137],[111137,126885],[126885,142638],[142638,160409],[160409,176697],[176697,191748],[191748,207688],[207688,231132],[231132,236862],[236862,246677],[246677,266951],[266951,271440],[271440,309975],[309975,319695],[319695,350864],[350864,368365],[368365,392696],[392696,423615],[423615,437846],[437846,439793],[439793,448669],[448669,465274],[465274,473358],[473358,477179],[477179,480560],[480560,483863],[483863,485994],[485994,488767],[488767,493628],[493628,495525],[495525,499084],[499084,511228],[511228,520019],[520019,523544],[523544,530817],[530817,535861],[535861,538768],[538768,549288],[549288,552265],[552265,560817],[560817,563807],[563807,568752],[568752,580910],[580910,593714],[593714,599684],[599684,607265],[607265,610614],[610614,613563],[613563,621120],[621120,624836],[624836,627046],[627046,630508],[630508,633925],[633925,635039],[635039,636788],[636788,640451],[640451,645092],[645092,651728],[651728,662238],[662238,675554],[675554,677391],[677391,690376],[690376,695763],[695763,699719],[699719,702228],[702228,707270],[707270,721457],[721457,728232],[728232,735223],[735223,736040],[736040,740416],[740416,746336],[746336,749714],[749714,753922],[753922,759012],[759012,764593],[764593,768015],[768015,771606],[771606,776771],[776771,780414],[780414,793640],[793640,796458],[796458,799141],[799141,801808],[801808,804299],[804299,808319],[808319,813064],[813064,816073],[816073,885419],[885419,888490],[888490,889683],[889683,896184],[896184,904923],[904923,915701],[915701,924512],[924512,929695],[929695,1188724],[1188724,1228033],[1228033,1233245]];var sourceLengths=[4844,4048,13310,87378,12190,10741,36165,17849,9941,85121,37758,11019,5079,9872,86645,42336,44337,50452,44969,43514,43587,66199,14399,25780,58259,10129,114255,26839,94086,49557,73031,95384,39217,8216,22172,44626,21923,9348,8035,7790,4874,6360,12290,4537,8347,32337,21939,8745,47165,12743,7133,27685,7140,22325,6860,12405,31433,33984,14963,18466,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11102,16082,26828,34218,4227,35397,12378,9651,8201,13306,98055,16844,17247,1638,10013,15381,7818,10170,12738,14071,7511,9014,12695,8527,35301,6519,6405,6095,6007,9711,11859,7205,204463,6927,2473,15538,22385,27911,21160,12616,751268,111139,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((0,import_node_zlib.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=(0,import_node_fs12.readFileSync)((0,import_node_path8.join)(__dirname,"docs-index.bin"));if(packed.length!==632861||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="8a4915b2760d979f691a55f0ab692729f1a454441a3ad47dacc5afb279d063db")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return(0,import_node_zlib.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}
139
139
  ${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}
140
140
 
141
141
  ${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}
@@ -185,14 +185,14 @@ After they approve, retry cotal_connect with name ${JSON.stringify(candidate2)}$
185
185
  ${body}`:body;return waiting?`${delivered}
186
186
  ${waiting}`:delivered};const surfaceTurns=(agent,ev)=>{if(deps.delivery===false&&deps.turns!==true)return void 0;const peek=agent.peekPendingTurns();if(!peek)return void 0;const rec=inFlight.get(ev);if(rec)rec.turnIds=peek.goalIds;else inFlight.set(ev,{ids:[],agent,turnIds:peek.goalIds});return peek.text};const injectFrame=async(agent,ev,event,extras,begun)=>{const peek=agent.peekPendingTurns();if(peek?.once&&peek.text.length<=HOOK_CONTEXT_CHARS){const join10=parts2=>parts2.filter(Boolean).join("\n\n");const kept=[];for(const x of extras)if(x&&join10([...kept,x,peek.text]).length<=HOOK_CONTEXT_CHARS)kept.push(x);const messages2=await surfaceAutomatic(agent,ev,join10([...kept,peek.text]).length+2);const text2=join10([...kept,messages2,peek.text]);if(terminals===begun&&text2.length<=HOOK_CONTEXT_CHARS&&agent.claimTurns(peek.goalIds)){const rec=inFlight.get(ev);if(rec)rec.onceIds=peek.goalIds;else inFlight.set(ev,{ids:[],agent,onceIds:peek.goalIds});for(const id2 of peek.goalIds)awaitingVerdict.set(id2,agent);return{hookSpecificOutput:{hookEventName:event,additionalContext:text2}}}return withContextFor(agent,ev,event,join10([...kept,messages2])||void 0)}const reserved=extras.reduce((n,x)=>n+(x?.length??0)+2,0)+(peek&&!peek.once?peek.text.length+2:0);const messages=await surfaceAutomatic(agent,ev,reserved);const late2=agent.peekPendingTurns();const fits=late2!==void 0&&[...extras,messages,late2.text].filter(Boolean).join("\n\n").length<=HOOK_CONTEXT_CHARS;const parts=[...extras,messages,peek?.once||late2?.once||!fits?void 0:surfaceTurns(agent,ev)].filter(Boolean);return withContextFor(agent,ev,event,parts.length?parts.join("\n\n"):void 0)};const withContextFor=(agent,ev,event,text2)=>{if(!text2)return{};if(text2.length>HOOK_CONTEXT_CHARS){const batch=inFlight.get(ev);if(batch){inFlight.delete(ev);batch.agent.releaseInFlight(batch.ids)}text2=`${agent.inboxCount("automatic")} Cotal messages still waiting. Read with cotal_inbox. Additional session context did not fit in this hook.`}return{hookSpecificOutput:{hookEventName:event,additionalContext:text2}}};const handle=async(agent,ev)=>{const event=ev.hook_event_name??"";try{switch(event){case"SessionStart":{sealAwaiting();const begun=terminals;adoptEvents(ev.transcript_path,ev.source);recordCarriedFork(deps.env??process.env,ev);if(typeof ev.model==="string")await agent.setModel(ev.model).catch(()=>{});if(typeof ev.cwd==="string"&&(ev.source==="startup"||ev.source==="resume"||ev.source==="fork"))await agent.setCwd(ev.cwd).catch(()=>{});if(!turnOpen){try{await agent.resetStatus("idle")}catch{}}try{await agent.setAttention("open")}catch{}const card=await orientation();return await injectFrame(agent,ev,event,[card,agent.channelBriefing()],begun)}case"UserPromptSubmit":{const begun=terminals;turnOpen=true;pendingTool=void 0;promptOpen=false;flushEvents(ev.transcript_path);await safeStatus(agent,"working");const card=cardOwed?await orientation():void 0;return await injectFrame(agent,ev,event,[card],begun)}case"PreToolUse":if(!turnOpen&&ev.agent_id===void 0){turnOpen=true;promptOpen=false;await safeStatus(agent,"working")}pendingTool=typeof ev.tool_name==="string"&&ev.tool_name?ev.tool_name:void 0;flushEvents(ev.transcript_path);return{};case"PostToolBatch":if(!promptOpen||ev.agent_id!==void 0)return{};promptOpen=false;await safeStatus(agent,"working");return{};case"Notification":{const msg=typeof ev.message==="string"?ev.message:void 0;const activity=pendingTool??msg;promptOpen=turnOpen;const writes=[safeStatus(agent,"waiting",activity)];const notificationType=typeof ev.notification_type==="string"?ev.notification_type:void 0;if(notificationType==="permission_prompt"||notificationType==="agent_needs_input")writes.push(safeCondition(agent,{code:notificationType==="permission_prompt"?"approval":"input",source:notificationType,...msg?{message:msg}:{},since:Date.now()}));await Promise.all(writes);return{}}case"Stop":case"StopFailure":sealAwaiting();turnOpen=false;promptOpen=false;pendingTool=void 0;flushEvents(ev.transcript_path);await closeEvents(Date.now(),stopFailure(ev));if(event==="StopFailure")await safeCondition(agent,failureCondition(ev)??null);await safeStatus(agent,"idle");if(agent.pendingWake()>0)agent.requestWake();return{};case"SessionEnd":sealAwaiting();turnOpen=false;promptOpen=false;flushEvents(ev.transcript_path);await safeStatus(agent,"offline");return{};default:return{}}}catch{const rec=inFlight.get(ev);if(rec){inFlight.delete(ev);if(rec.ids.length)rec.agent.releaseInFlight(rec.ids);if(rec.onceIds?.length){for(const id2 of rec.onceIds)awaitingVerdict.delete(id2);rec.agent.releaseTurns(rec.onceIds)}}return{}}};const onReply=(ev,delivered,handoff=false)=>{const batch=inFlight.get(ev);if(!batch)return;inFlight.delete(ev);const{ids,agent,turnIds,onceIds}=batch;if(onceIds?.length){const pending=onceIds.filter(id2=>awaitingVerdict.delete(id2));if(delivered&&handoff&&pending.length===onceIds.length)agent.commitSurfacedTurns(onceIds);else agent.releaseTurns(onceIds)}if(delivered&&turnIds?.length)agent.commitSurfacedTurns(turnIds);if(!ids.length)return;agent.releaseInFlight(ids);if(!delivered){markUnconfirmed(ids);return}for(const id2 of ids)unconfirmed.delete(id2);try{const committed=agent.drainInboxDeliveries(ids);if(committed.items.length)lastDelivery={count:committed.items.length,event:ev.hook_event_name??""}}catch{markUnconfirmed(ids)}};return{handle,onReply,adoptTranscript:adoptEvents,inboxDeliveryNote:()=>lastDelivery?`No unread messages remain. The most recent confirmed Claude Code hook handoff carried ${lastDelivery.count} message${lastDelivery.count===1?"":"s"} as additionalContext (${lastDelivery.event}). This is a delivery receipt, not a new message.`:void 0}}var NUDGE_RETRY_INITIAL_MS=1e3;var NUDGE_RETRY_MAX_MS=3e4;function createWakePolicy(agent,notify,log=()=>{}){let channelActive=false;let retryTimer;let retryMs=NUDGE_RETRY_INITIAL_MS;let pendingMentionWake;const announced=new WeakMap;const owed=()=>agent.pendingWake(item=>announced.has(item));const clearRetry=resetDelay=>{if(retryTimer)clearTimeout(retryTimer);retryTimer=void 0;if(resetDelay)retryMs=NUDGE_RETRY_INITIAL_MS};const scheduleRetry=()=>{if(retryTimer||!channelActive)return;if(owed()===0&&!pendingMentionWake)return;const delay3=retryMs;retryMs=Math.min(retryMs*2,NUDGE_RETRY_MAX_MS);retryTimer=setTimeout(()=>{retryTimer=void 0;if(pendingMentionWake)nudge(pendingMentionWake.item,pendingMentionWake.hint,true);else if(owed()>0)nudge(void 0,void 0,false,agent.inboxPending("automatic").filter(it=>!announced.has(it)))},delay3);retryTimer.unref?.()};const nudge=(item,pullHint,isMentionWake=false,batch)=>{if(!channelActive)return;const covered=item?[item]:batch??agent.inboxPending("automatic");const n=covered.length;for(const it of covered)announced.set(it,covered);const content=pullHint?`\u{1F4E8} ${pullHint}`:item?`\u{1F4E8} New ${fmtKind(item.kind)}${item.mentionsMe?" \u2014 you were mentioned":""} from ${fmtFrom(item)} \u2014 delivering your Cotal inbox now.`:`\u{1F4E8} ${n} Cotal message${n===1?"":"s"} waiting \u2014 delivering your inbox now.`;void notify({content,meta:item?channelMeta(item):{kind:"batch"}}).then(()=>{if(isMentionWake)pendingMentionWake=void 0;clearRetry(true);if(pendingMentionWake)scheduleRetry()},e=>{for(const it of covered)if(announced.get(it)===covered)announced.delete(it);log(`channel nudge failed: ${e.message}`);scheduleRetry()})};agent.on("incoming",item=>{if(announced.has(item))return;const automatic=agent.inboxScope(item.recvKey)==="automatic";const directedOrMention=item.kind!=="channel"||item.mentionsMe;const ambientWakes=agent.attention==="open"&&agent.status!=="working";if(automatic&&(directedOrMention||ambientWakes))nudge(item)});agent.on("mention-wake",item=>{const hint=`You were mentioned by ${fmtFrom(item)} on #${fmtChannel(item.channel)} \u2014 pull it with cotal_inbox.`;pendingMentionWake={item,hint};nudge(item,hint,true)});agent.on("wake",()=>nudge());return{setChannelActive(active){const activated=active&&!channelActive;channelActive=active;if(!active)clearRetry(true);else if(activated){if(pendingMentionWake)nudge(pendingMentionWake.item,pendingMentionWake.hint,true);else if(agent.pendingWake()>0)nudge()}},surfaced(items){for(const item of items)announced.delete(item)},stop(){clearRetry(true)}}}var import_node_crypto20=require("node:crypto");var import_node_path10=require("node:path");var ORIGIN_RULE={human:"human",channel:"channel","task-notification":null,"auto-continuation":"auto-continuation"};var ABSENT_ORIGIN_RULE={sdk:"sdk",typed:"human",system:null};var runOpeningAttribution=entry=>{const kind=entry.origin?.kind;if(kind===void 0){const ps=entry.promptSource;if(ps===void 0)return null;if(!(ps in ABSENT_ORIGIN_RULE))throw new Error(`agui-map: origin-less entry ${entry.uuid??"<no uuid>"} carries promptSource ${JSON.stringify(ps)}, which this mapper has never measured. Refusing to decide whether it begins a run. Add it to ABSENT_ORIGIN_RULE deliberately, with a measurement.`);return ABSENT_ORIGIN_RULE[ps]}if(!(kind in ORIGIN_RULE))throw new Error(`agui-map: unrecognised origin.kind ${JSON.stringify(kind)} on entry ${entry.uuid??"<no uuid>"} \u2014 refusing to decide whether it begins a run, or to attribute one to a provenance this mapper has never seen. Add it to ORIGIN_RULE deliberately, with a measurement.`);return ORIGIN_RULE[kind]};function stampOf(entry,now){const parsed=entry.timestamp?Date.parse(entry.timestamp):Number.NaN;return Number.isFinite(parsed)?{ts:parsed,arrival:false}:{ts:now(),arrival:true}}function resultContent(raw){return typeof raw==="string"?raw:JSON.stringify(raw??null)}function createClaudeMapper(opts){const now=opts.now??(()=>Date.now());let open5=opts.resumeRunId??null;const map2=entry=>{const{ts,arrival}=stampOf(entry,now);const arrivalMeta=arrival?{tsSource:"arrival"}:void 0;const uuid3=entry.uuid??"";const events=[];if(entry.type==="user"){const content=entry.message?.content;const toolResults=Array.isArray(content)?content.filter(b=>b.type==="tool_result"&&b.tool_use_id):[];if(toolResults.length>0){content.forEach((b,i)=>{if(b.type!=="tool_result"||!b.tool_use_id)return;events.push(toolCallResult({messageId:`${uuid3}#${i}`,toolCallId:b.tool_use_id,content:resultContent(b.content),timestamp:ts,...b.is_error||arrivalMeta?{cotal:{...b.is_error?{isError:true}:{},...arrivalMeta}}:{}}));events.push(toolResultMarker({toolCallId:b.tool_use_id,isError:b.is_error===true,timestamp:ts,...arrivalMeta?{cotal:arrivalMeta}:{}}))});return events.length>0&&open5!==null?{runId:open5,events}:null}const promptText=typeof content==="string"?content:Array.isArray(content)?content.filter(b=>b.type==="text"&&typeof b.text==="string").map(b=>b.text).join("\n"):null;if(promptText===null)return null;if(entry.isCompactSummary===true||entry.isVisibleInTranscriptOnly===true)return null;const turnSource=runOpeningAttribution(entry);if(turnSource===null)return{turn:true};const prior=open5;const runId2=opts.mintRunId();open5=runId2;const messageId=`${uuid3}#0`;const selfAuthored=turnSource!=="channel";const carriesBody=selfAuthored&&promptText.length>0;return{runId:runId2,events:[...prior===null?[]:[runFinished({threadId:opts.threadId,runId:prior,timestamp:ts})],runStarted({threadId:opts.threadId,runId:runId2,timestamp:ts,cotal:{runIdSource:"connector",turnSource,...arrivalMeta}}),...carriesBody?[textMessageStart({messageId,timestamp:ts,role:"user",...arrivalMeta?{cotal:arrivalMeta}:{}}),textMessageContent({messageId,delta:promptText,timestamp:ts}),textMessageEnd({messageId,timestamp:ts})]:[]]}}if(entry.type!=="assistant"||!Array.isArray(entry.message?.content))return null;const runId=open5;entry.message.content.forEach((b,i)=>{const messageId=`${uuid3}#${i}`;const meta3={...entry.message?.id?{providerMessageId:entry.message.id}:{},...entry.message?.stop_reason?{stopReason:entry.message.stop_reason}:{},...arrivalMeta};const cotal=Object.keys(meta3).length>0?{cotal:meta3}:{};if(b.type==="text"&&typeof b.text==="string"){events.push(textMessageStart({messageId,timestamp:ts,role:"assistant",...cotal}),textMessageContent({messageId,delta:b.text,timestamp:ts}),textMessageEnd({messageId,timestamp:ts}));return}if(b.type==="thinking"&&opts.reasoning&&typeof b.thinking==="string"){events.push(reasoningMessageStart({messageId,timestamp:ts,...cotal}),reasoningMessageContent({messageId,delta:b.thinking,timestamp:ts}),reasoningMessageEnd({messageId,timestamp:ts}));return}if(b.type==="tool_use"&&b.id){events.push(toolCallStart({toolCallId:b.id,toolCallName:b.name??"",timestamp:ts,parentMessageId:messageId,...cotal}),toolCallArgs({toolCallId:b.id,delta:JSON.stringify(b.input??null),timestamp:ts}),toolCallEnd({toolCallId:b.id,timestamp:ts}))}});if(events.length===0)return null;return runId===null?null:{runId,events}};const forgetOpenRun=runId=>{if(open5===runId)open5=null};return{map:map2,forgetOpenRun}}var STARTUP_TRANSCRIPT_WAIT_MS=5e3;var STARTUP_TRANSCRIPT_RETRY_INITIAL_MS=25;var STARTUP_TRANSCRIPT_RETRY_MAX_MS=250;var delay2=ms=>new Promise(resolve=>setTimeout(resolve,ms));var isMissingFile=error51=>error51 instanceof Error&&error51.code==="ENOENT";var StartupTranscriptTimeout=class extends Error{};async function readStartupTranscriptWhenReady(read,opts){const sleep2=opts.sleep??delay2;const deadline=performance.now()+opts.waitMs;let retryMs=STARTUP_TRANSCRIPT_RETRY_INITIAL_MS;const timeout=cause=>new StartupTranscriptTimeout(`Claude AG-UI source: session transcript did not appear within ${opts.waitMs}ms; refusing to lose the first run`,{cause});for(;;){const beforeRead=deadline-performance.now();if(beforeRead<=0)throw timeout();let timer;try{return await Promise.race([read(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(timeout()),beforeRead)})])}catch(error51){if(error51 instanceof StartupTranscriptTimeout)throw error51;if(!isMissingFile(error51))throw error51;const remaining=deadline-performance.now();if(remaining<=0)throw timeout(error51);await sleep2(Math.min(retryMs,remaining));retryMs=Math.min(retryMs*2,STARTUP_TRANSCRIPT_RETRY_MAX_MS)}finally{if(timer)clearTimeout(timer)}}}var StartupClaudeTranscriptSource=class{constructor(file2,waitMs,virginRead){this.file=file2;this.waitMs=waitMs;this.virginRead=virginRead}file;waitMs;virginRead;get kind(){return this.file.kind}readWhenReady(){const read=this.virginRead==="from-beginning"?()=>this.file.readFromBeginning():()=>this.file.read(void 0);return readStartupTranscriptWhenReady(read,{waitMs:this.waitMs})}read(cursor){return cursor===void 0?this.readWhenReady():this.file.read(cursor)}end(){return this.file.end()}};function createClaudeTranscriptSource(path,sessionSource,opts={}){const file2=new JsonlFileSource(path);switch(sessionSource){case"startup":return new StartupClaudeTranscriptSource(file2,opts.startupFileWaitMs??STARTUP_TRANSCRIPT_WAIT_MS,"from-beginning");case"fork":return new StartupClaudeTranscriptSource(file2,opts.startupFileWaitMs??STARTUP_TRANSCRIPT_WAIT_MS,"adopt-at-end");case"resume":case"clear":case"compact":return file2;default:throw new Error(`Claude AG-UI source: SessionStart carried unsupported source ${JSON.stringify(sessionSource)}; refusing to guess whether the transcript is new or retained`)}}async function createBoundClaudeTranscriptSource(path,sessionSource,opts={}){const source=createClaudeTranscriptSource(path,sessionSource,opts);if(sessionSource==="startup")return source;const boundary=await source.read(void 0);return new BoundStartSource(source,boundary.cursor)}function createClaudeEventPlane(agent,config2,env,initialSource){const stop=new AbortController;const waitLive=()=>new Promise((resolve,reject)=>{const release=()=>{agent.off("connection",connected);agent.off("transport",connected);stop.signal.removeEventListener("abort",stopped)};const connected=()=>{if(agent.connected&&agent.transportConnected){release();resolve()}};const stopped=()=>{release();reject(new Error("seat stopping while the mesh connection is down; unpublished events stay in the transcript"))};agent.on("connection",connected);agent.on("transport",connected);stop.signal.addEventListener("abort",stopped);if(stop.signal.aborted)stopped();else connected()});let source=initialSource;let mapper;const events=new AguiEmitterHolder(async(transcriptPath,sessionSource)=>{const boundSource=source??=await createBoundClaudeTranscriptSource(transcriptPath,sessionSource);await waitLive();const workspaceRoot=resolveEventsStateRoot(env);const threadId=(0,import_node_path10.basename)(transcriptPath,".jsonl");const principal=principalKey(agent.ep.principal.owner,agent.ep.principal.actor).key;const{walPath,subjectPath}=await ensureEventWalDir({workspaceRoot,space:config2.space,principal,threadId});const subjectFrontier=await FileSubjectFrontier.open(subjectPath,{space:config2.space,principal});const wal=await EventWal.open(walPath,{space:config2.space,threadId,principal,subjectMayExist:false});const resumeRunId=wal.pending===null?wal.brackets?.run:wal.pending.brackets.run;mapper=createClaudeMapper({threadId,mintRunId:()=>(0,import_node_crypto20.randomUUID)(),resumeRunId});return AguiEmitter.start({endpoint:agent.ep,wal,subjectFrontier,source:boundSource,map:mapper.map,onUnreadable:gap=>process.stderr.write(`[cotal-connector] AG-UI source: skipped an unreadable transcript record at offset ${gap.offset} (${gap.bytes} bytes): ${gap.reason}
187
187
  `)})},{onError:eventPlaneStopped({log:line=>process.stderr.write(`[cotal-connector] ${line}
188
- `)}),sourceEnd:path=>new JsonlFileSource(path).end(),onRunClosed:runId=>mapper?.forgetOpenRun(runId),waitLive});return{events,stop:()=>stop.abort()}}var import_node_child_process4=require("node:child_process");var import_node_crypto21=require("node:crypto");var import_node_path11=require("node:path");var PLUMBING_MS=6e4;var JOIN_MS=2e4;var WATCH={pollMs:1e4,graceMs:6e4};function grantedTools(grant){return new Set([...GATEWAY_TOOLS,"cotal_reconnect",...grant.scope.includes("spawn")?["cotal_spawn","cotal_persona","cotal_personas","cotal_despawn"]:[],...grant.scope.includes("run")?["cotal_run","cotal_turn_participate","cotal_yield"]:[]])}var reason=error51=>error51 instanceof Error?error51.message:String(error51);function unfinished(id2,why){return`This conversation is disconnected from the mesh, but its identity cleanup is not finished: ${why}. Call cotal_disconnect with connection_id ${id2} to retry it now, or cotal_connect to retry it and then connect again.`}function launchEnv(base,printed){const env={};for(const[k,v]of Object.entries(base))if(!k.startsWith("COTAL_")||k==="COTAL_HOME")env[k]=v;return{...env,...printed}}function createAppHost(o){const held2=new Map;const bindings=new Map;const pending=new Map;const watches=new Map;const watch=o.watch??WATCH;let opening=Promise.resolve();const serial=fn=>{const next=opening.then(fn);opening=next.catch(()=>{});return next};let reaping;let reapAgain=false;let reapSpace;const plumbing=args=>new Promise((resolve,reject)=>{const cotal=o.cotal();(0,import_node_child_process4.execFile)(cotal[0],[...cotal.slice(1),"app-identity",...args],{cwd:o.cwd,env:o.env,timeout:PLUMBING_MS},(_error,stdout,stderr)=>{try{resolve(JSON.parse(stdout.trim().split("\n").at(-1)??""))}catch{reject(new Error(/Unknown option ['"]--require-approval['"]/.test(stderr)?"The recorded Cotal CLI cannot enforce permission approval. Update Cotal, run `cotal setup`, then reopen Claude. No connection was started.":"the Cotal CLI did not return an identity result; any saved request was retained for recovery"))}})});const retire=async dir=>{if(!dir)return;const reply=await plumbing(["retire","--dir",dir]);if(!reply.ok)throw new Error("error"in reply&&reply.error||"identity retirement is unconfirmed")};const reap=space2=>{if(reaping){reapAgain=true;reapSpace=space2;return}reaping=plumbing(["reap",...space2===void 0?[]:["--space",space2]]).then(()=>{},()=>{}).finally(()=>{reaping=void 0;if(reapAgain){reapAgain=false;const next=reapSpace;reapSpace=void 0;reap(next)}})};const stopWatch=session=>{const w=watches.get(session);if(!w)return void 0;w.stopped=true;if(w.timer)clearTimeout(w.timer);watches.delete(session);return w};const tell=(session,w,status2)=>{let heard=false;try{heard=o.notify?.(session,{name:w.name,status:status2,id:w.approval.id})??false}catch{heard=false}if(!heard)process.stderr.write(`[cotal-connector] a personal connection request was ${status2}, but its native session has no reader to tell
189
- `)};const replay=(session,w)=>{w.timer=void 0;void serial(async()=>{if(w.stopped)return;let reply;try{reply=await plumbing(w.args)}catch{reply=void 0}if(w.stopped)return;if(reply?.ok){w.stopped=true;w.issued=reply.retire?.dir;tell(session,w,"approved");return}if(reply&&!reply.ok&&!reply.pending&&reply.refused){stopWatch(session);tell(session,w,reply.refused==="expired"?"expired":"denied");return}if(reply&&!reply.ok&&reply.pending)w.approval=reply.approval;if(Date.now()>Date.parse(w.approval.expiresAt)+watch.graceMs){stopWatch(session);process.stderr.write("[cotal-connector] a personal connection request passed its expiry without a recorded decision; cotal_connect asks again\n");return}w.timer=setTimeout(()=>replay(session,w),watch.pollMs);w.timer.unref()})};const startWatch=(session,name,args,approval)=>{const current=watches.get(session);if(current&&current.approval.id===approval.id&&!current.stopped){current.approval=approval;return}stopWatch(session);const w={name,args,approval,stopped:false};watches.set(session,w);w.timer=setTimeout(()=>replay(session,w),watch.pollMs);w.timer.unref()};const open5=async(name,context,selection,approvalId,space2)=>{const binding=context?bindings.get(context):void 0;if(context&&!binding)throw new Error("the native conversation has not bound its lifecycle and transcript; no identity was requested");const watched=context?watches.get(context):void 0;if(approvalId!==void 0&&watched&&watched.approval.id!==approvalId)throw new Error("approval_id does not name this conversation's pending request; nothing was connected. Call cotal_connect with the approval_id from this conversation's own pending result, or without one");const prior=context?[...held2].find(([,h2])=>h2.session===context):void 0;if(prior&&!prior[1].stopped)throw new Error("this native conversation already has a connection; disconnect it before connecting again");if(prior)await close(prior[0]);const previous=context?pending.get(context):void 0;if(previous){try{await retire(previous)}catch(error51){throw new Error(`this conversation's previous identity cleanup is not finished: ${reason(error51)}. Call cotal_connect again to retry it`)}pending.delete(context)}const args=["provision","--require-approval","--name",name,...space2===void 0?[]:["--space",space2],...binding?["--session",binding.session,"--events"]:[],...selection?["--selection",JSON.stringify(selection)]:[]];if(watched&&JSON.stringify(watched.args)!==JSON.stringify(args)){if(approvalId!==void 0)throw new Error("approval_id resumes only the unchanged request; omit it to replace the pending name or permissions");stopWatch(context);if(watched.issued){try{await retire(watched.issued)}catch(error51){pending.set(context,watched.issued);throw error51}}}const reply=await plumbing(args);if(!reply.ok){if(reply.pending){if(binding)startWatch(binding.session,name,args,reply.approval);throw new ApprovalRequired({requestId:reply.requestId,approval:reply.approval,proposed:reply.proposed})}if(reply.refused&&binding)stopWatch(binding.session);if(reply.taken)throw new NameTaken(name);throw new Error(reply.error??"identity provisioning failed")}if(binding)stopWatch(binding.session);const dir=reply.retire?.dir;let agent;let plane;try{const source=binding?await createBoundClaudeTranscriptSource(binding.path,"resume"):void 0;const env=launchEnv(o.env,reply.env);const config2=configFromEnv(env);config2.connector="claude";config2.turnRelay=false;if(eventPlaneArmed(config2,env)&&!binding)throw new Error("this mesh requires a bound native event source");agent=new MeshAgent(config2,env,{withholdProcessCwd:true});agent.on("error",()=>process.stderr.write("[cotal-connector] personal connection error; inspect cotal_connection_status\n"));if(eventPlaneArmed(config2,env))plane=createClaudeEventPlane(agent,config2,env,source);const hooks=binding?createClaudeHandle({env,events:()=>plane?.events,delivery:false,turns:true}):void 0;hooks?.adoptTranscript(binding.path,"resume");void agent.start();for(let waited=0;!agent.connected&&waited<JOIN_MS;waited+=100)await new Promise(resolve=>setTimeout(resolve,100));if(!agent.connected)throw new Error(`the personal conversation did not join within ${JOIN_MS/1e3} s; its identity was retained for exact cleanup`);const conn={id:(0,import_node_crypto21.randomUUID)(),agent,config:config2,...reply.grant?{tools:grantedTools(reply.grant)}:{}};held2.set(conn.id,{conn,dir,session:binding?.session,hooks,plane});if(binding&&hooks)await hooks.handle(agent,binding.event);if(config2.userAuth)reap(config2.space);return conn}catch(error51){plane?.stop();await plane?.events.close().catch(()=>{});await agent?.stop().catch(()=>{});try{await retire(dir)}catch{if(context&&dir)pending.set(context,dir)}throw error51}};const close=async id2=>{const h2=held2.get(id2);if(!h2)return false;if(h2.closing)return h2.closing;h2.closing=(async()=>{if(!h2.stopped){h2.plane?.stop();await h2.plane?.events.close();await h2.conn.agent.stop();h2.stopped=true}try{await retire(h2.dir)}catch(error51){h2.unfinished=reason(error51);throw new Error(unfinished(id2,h2.unfinished))}held2.delete(id2);return true})();try{return await h2.closing}finally{h2.closing=void 0}};return{account:()=>"local",open:(_account,name,context,selection,approvalId,space2)=>serial(()=>open5(name,context,selection,approvalId,space2)),async find(_account,id2){const h2=held2.get(id2);if(h2?.stopped)throw new Error(h2.closing?"This conversation is disconnecting from the mesh.":unfinished(id2,h2.unfinished??"it was interrupted"));return h2?.conn},close:(_account,id2)=>close(id2),...o.participate?{participate:(_account,connection)=>o.participate(connection)}:{},sessionFor:id2=>held2.get(id2)?.session,async nativeEvent(event){const session=event.session_id;if(typeof session!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(session)||typeof event.hook_event_name!=="string")throw new Error("invalid native session binding");if(event.agent_id!==void 0)return;const previous=bindings.get(session);const path=typeof event.transcript_path==="string"?event.transcript_path:previous?.path;if(!path||!(0,import_node_path11.isAbsolute)(path)||(0,import_node_path11.basename)(path)!==`${session}.jsonl`||previous&&previous.path!==path)throw new Error("native transcript does not match its explicit session identity");const bound={...event,transcript_path:path};bindings.set(session,{session,path,event:bound});for(const[id2,h2]of held2){if(h2.session!==session||h2.stopped)continue;const reply=await h2.hooks?.handle(h2.conn.agent,bound);const context=reply?.hookSpecificOutput?.additionalContext;if(event.hook_event_name==="SessionStart"&&typeof context==="string")h2.hooks?.onReply(bound,o.turn?.(session,id2,context)===true);if(event.hook_event_name==="SessionEnd")await close(id2)}if(event.hook_event_name==="SessionEnd"){bindings.delete(session);const w=stopWatch(session);if(w?.issued){const dir=w.issued;await serial(()=>retire(dir)).catch(()=>pending.set(session,dir))}}},async closeAll(){for(const session of[...watches.keys()])stopWatch(session);const results=await Promise.allSettled([...held2.keys()].map(close));if(results.some(r=>r.status==="rejected")||pending.size)throw new Error("some personal identities have pending cleanup; their saved lifecycle records were retained")}}}var import_node_fs14=require("node:fs");var import_node_path12=require("node:path");var CLI_RECORD="cli.json";function readCliRecord(dir){let argv;try{argv=JSON.parse((0,import_node_fs14.readFileSync)((0,import_node_path12.join)(dir,CLI_RECORD),"utf8")).argv}catch{argv=void 0}if(!Array.isArray(argv)||argv.length<2||!argv.every(a=>typeof a==="string"&&a))throw new Error("this Cotal plugin was not installed by `cotal setup`, so it cannot find the Cotal CLI. Run `cotal setup` again.");return argv}var APPROVAL_ID=/^[a-z2-7]{26}$/;var STATUSES=new Set(["approved","denied","expired"]);function approvalFrame(frame){const approval=frame?.approval;if(!approval||typeof approval!=="object")return void 0;const{name,status:status2,id:id2}=approval;if(typeof name!=="string"||!name||name.length>128||/[\r\n]/.test(name)||name!==name.trim())return void 0;if(typeof status2!=="string"||!STATUSES.has(status2))return void 0;if(typeof id2!=="string"||!APPROVAL_ID.test(id2))return void 0;return{name,status:status2,id:id2}}var import_node_fs15=require("node:fs");var import_node_net4=require("node:net");var import_node_os5=require("node:os");var import_node_path13=require("node:path");var import_node_crypto22=require("node:crypto");var ID2=/^[A-Za-z0-9_-]{1,128}$/;var INLINE_FRAME_LIMIT=4096;function isNativeInlineFrame(value){if(!value||typeof value!=="object")return false;const frame=value;const item=frame.inline;return typeof frame.id==="string"&&ID2.test(frame.id)&&typeof frame.route==="string"&&!!item&&item.v===1&&typeof item.receipt==="string"&&ID2.test(item.receipt)&&typeof item.session==="string"&&ID2.test(item.session)&&typeof item.text==="string"&&item.text.startsWith(`Cotal: inline messages for connection_id ${frame.id}.
188
+ `)}),sourceEnd:path=>new JsonlFileSource(path).end(),onRunClosed:runId=>mapper?.forgetOpenRun(runId),waitLive});return{events,stop:()=>stop.abort()}}var import_node_child_process4=require("node:child_process");var import_node_crypto21=require("node:crypto");var import_node_path11=require("node:path");var PLUMBING_MS=6e4;var JOIN_MS=2e4;var WATCH={pollMs:1e4,graceMs:6e4};function grantedTools(grant){return new Set([...GATEWAY_TOOLS,"cotal_reconnect",...grant.scope.includes("spawn")?["cotal_spawn","cotal_persona","cotal_personas","cotal_despawn"]:[],...grant.scope.includes("run")?["cotal_run","cotal_turn_participate","cotal_yield"]:[]])}var reason=error51=>error51 instanceof Error?error51.message:String(error51);function unfinished(id2,why){return`This conversation is disconnected from the mesh, but its identity cleanup is not finished: ${why}. Call cotal_disconnect with connection_id ${id2} to retry it now, or cotal_connect to retry it and then connect again.`}function launchEnv(base,printed){const env={};for(const[k,v]of Object.entries(base))if(!k.startsWith("COTAL_")||k==="COTAL_HOME")env[k]=v;return{...env,...printed}}function createAppHost(o){const held2=new Map;const bindings=new Map;const pending=new Map;const watches=new Map;const refusals=new Map;const watch=o.watch??WATCH;let opening=Promise.resolve();const serial=fn=>{const next=opening.then(fn);opening=next.catch(()=>{});return next};let reaping;let reapAgain=false;let reapSpace;const plumbing=args=>new Promise((resolve,reject)=>{const cotal=o.cotal();(0,import_node_child_process4.execFile)(cotal[0],[...cotal.slice(1),"app-identity",...args],{cwd:o.cwd,env:o.env,timeout:PLUMBING_MS},(_error,stdout,stderr)=>{try{resolve(JSON.parse(stdout.trim().split("\n").at(-1)??""))}catch{reject(new Error(/Unknown option ['"]--require-approval['"]/.test(stderr)?"The recorded Cotal CLI cannot enforce permission approval. Update Cotal, run `cotal setup`, then reopen Claude. No connection was started.":"the Cotal CLI did not return an identity result; any saved request was retained for recovery"))}})});const retire=async dir=>{if(!dir)return;const reply=await plumbing(["retire","--dir",dir]);if(!reply.ok)throw new Error("error"in reply&&reply.error||"identity retirement is unconfirmed")};const reap=space2=>{if(reaping){reapAgain=true;reapSpace=space2;return}reaping=plumbing(["reap",...space2===void 0?[]:["--space",space2]]).then(()=>{},()=>{}).finally(()=>{reaping=void 0;if(reapAgain){reapAgain=false;const next=reapSpace;reapSpace=void 0;reap(next)}})};const stopWatch=session=>{const w=watches.get(session);if(!w)return void 0;w.stopped=true;if(w.timer)clearTimeout(w.timer);watches.delete(session);return w};const tell=(session,w,status2)=>{let heard=false;try{heard=o.notify?.(session,{name:w.name,status:status2,id:w.approval.id})??false}catch{heard=false}if(!heard)process.stderr.write(`[cotal-connector] a personal connection request was ${status2}, but its native session has no reader to tell
189
+ `)};const replay=(session,w)=>{w.timer=void 0;void serial(async()=>{if(w.stopped)return;let reply;try{reply=await plumbing(w.args)}catch{reply=void 0}if(w.stopped)return;if(reply?.ok){w.stopped=true;w.issued=reply.retire?.dir;tell(session,w,"approved");return}if(reply&&!reply.ok&&!reply.pending&&(reply.refused||reply.retryable===false)){stopWatch(session);const status2=reply.refused==="denied"||reply.refused==="expired"?reply.refused:"refused";if(status2==="refused")refusals.set(session,{name:w.name,id:w.approval.id,error:reply.error??"The mesh refused this connection. No automatic retry will be made."});tell(session,w,status2);return}if(reply&&!reply.ok&&reply.pending)w.approval=reply.approval;if(Date.now()>Date.parse(w.approval.expiresAt)+watch.graceMs){stopWatch(session);process.stderr.write("[cotal-connector] a personal connection request passed its expiry without a recorded decision; cotal_connect asks again\n");return}w.timer=setTimeout(()=>replay(session,w),watch.pollMs);w.timer.unref()})};const startWatch=(session,name,args,approval)=>{const current=watches.get(session);if(current&&current.approval.id===approval.id&&!current.stopped){current.approval=approval;return}stopWatch(session);const w={name,args,approval,stopped:false};watches.set(session,w);w.timer=setTimeout(()=>replay(session,w),watch.pollMs);w.timer.unref()};const open5=async(name,context,selection,approvalId,space2)=>{const binding=context?bindings.get(context):void 0;if(context&&!binding)throw new Error("the native conversation has not bound its lifecycle and transcript; no identity was requested");const refusal=context?refusals.get(context):void 0;if(approvalId!==void 0&&refusal){if(refusal.id!==approvalId||refusal.name!==name)throw new Error("approval_id does not name this conversation's refused request");throw new Error(refusal.error)}const watched=context?watches.get(context):void 0;if(approvalId!==void 0&&watched&&watched.approval.id!==approvalId)throw new Error("approval_id does not name this conversation's pending request; nothing was connected. Call cotal_connect with the approval_id from this conversation's own pending result, or without one");const prior=context?[...held2].find(([,h2])=>h2.session===context):void 0;if(prior&&!prior[1].stopped)throw new Error("this native conversation already has a connection; disconnect it before connecting again");if(prior)await close(prior[0]);const previous=context?pending.get(context):void 0;if(previous){try{await retire(previous)}catch(error51){throw new Error(`this conversation's previous identity cleanup is not finished: ${reason(error51)}. Call cotal_connect again to retry it`)}pending.delete(context)}const args=["provision","--require-approval","--name",name,...space2===void 0?[]:["--space",space2],...binding?["--session",binding.session,"--events"]:[],...selection?["--selection",JSON.stringify(selection)]:[]];if(watched&&JSON.stringify(watched.args)!==JSON.stringify(args)){if(approvalId!==void 0)throw new Error("approval_id resumes only the unchanged request; omit it to replace the pending name or permissions");stopWatch(context);if(watched.issued){try{await retire(watched.issued)}catch(error51){pending.set(context,watched.issued);throw error51}}}if(context)refusals.delete(context);const reply=await plumbing(args);if(!reply.ok){if(reply.pending){if(binding)startWatch(binding.session,name,args,reply.approval);throw new ApprovalRequired({requestId:reply.requestId,approval:reply.approval,proposed:reply.proposed})}if((reply.refused||reply.retryable===false)&&binding)stopWatch(binding.session);if(reply.taken)throw new NameTaken(name);throw new Error(reply.error??"identity provisioning failed")}if(binding)stopWatch(binding.session);const dir=reply.retire?.dir;let agent;let plane;try{const source=binding?await createBoundClaudeTranscriptSource(binding.path,"resume"):void 0;const env=launchEnv(o.env,reply.env);const config2=configFromEnv(env);config2.connector="claude";config2.turnRelay=false;if(eventPlaneArmed(config2,env)&&!binding)throw new Error("this mesh requires a bound native event source");agent=new MeshAgent(config2,env,{withholdProcessCwd:true});agent.on("error",()=>process.stderr.write("[cotal-connector] personal connection error; inspect cotal_connection_status\n"));if(eventPlaneArmed(config2,env))plane=createClaudeEventPlane(agent,config2,env,source);const hooks=binding?createClaudeHandle({env,events:()=>plane?.events,delivery:false,turns:true}):void 0;hooks?.adoptTranscript(binding.path,"resume");void agent.start();for(let waited=0;!agent.connected&&waited<JOIN_MS;waited+=100)await new Promise(resolve=>setTimeout(resolve,100));if(!agent.connected)throw new Error(`the personal conversation did not join within ${JOIN_MS/1e3} s; its identity was retained for exact cleanup`);const conn={id:(0,import_node_crypto21.randomUUID)(),agent,config:config2,...reply.grant?{tools:grantedTools(reply.grant)}:{}};held2.set(conn.id,{conn,dir,session:binding?.session,hooks,plane});if(binding&&hooks)await hooks.handle(agent,binding.event);if(config2.userAuth)reap(config2.space);return conn}catch(error51){plane?.stop();await plane?.events.close().catch(()=>{});await agent?.stop().catch(()=>{});try{await retire(dir)}catch{if(context&&dir)pending.set(context,dir)}throw error51}};const close=async id2=>{const h2=held2.get(id2);if(!h2)return false;if(h2.closing)return h2.closing;h2.closing=(async()=>{if(!h2.stopped){h2.plane?.stop();await h2.plane?.events.close();await h2.conn.agent.stop();h2.stopped=true}try{await retire(h2.dir)}catch(error51){h2.unfinished=reason(error51);throw new Error(unfinished(id2,h2.unfinished))}held2.delete(id2);return true})();try{return await h2.closing}finally{h2.closing=void 0}};return{account:()=>"local",open:(_account,name,context,selection,approvalId,space2)=>serial(()=>open5(name,context,selection,approvalId,space2)),async find(_account,id2){const h2=held2.get(id2);if(h2?.stopped)throw new Error(h2.closing?"This conversation is disconnecting from the mesh.":unfinished(id2,h2.unfinished??"it was interrupted"));return h2?.conn},close:(_account,id2)=>close(id2),...o.participate?{participate:(_account,connection)=>o.participate(connection)}:{},sessionFor:id2=>held2.get(id2)?.session,async nativeEvent(event){const session=event.session_id;if(typeof session!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(session)||typeof event.hook_event_name!=="string")throw new Error("invalid native session binding");if(event.agent_id!==void 0)return;const previous=bindings.get(session);const path=typeof event.transcript_path==="string"?event.transcript_path:previous?.path;if(!path||!(0,import_node_path11.isAbsolute)(path)||(0,import_node_path11.basename)(path)!==`${session}.jsonl`||previous&&previous.path!==path)throw new Error("native transcript does not match its explicit session identity");const bound={...event,transcript_path:path};bindings.set(session,{session,path,event:bound});for(const[id2,h2]of held2){if(h2.session!==session||h2.stopped)continue;const reply=await h2.hooks?.handle(h2.conn.agent,bound);const context=reply?.hookSpecificOutput?.additionalContext;if(event.hook_event_name==="SessionStart"&&typeof context==="string")h2.hooks?.onReply(bound,o.turn?.(session,id2,context)===true);if(event.hook_event_name==="SessionEnd")await close(id2)}if(event.hook_event_name==="SessionEnd"){bindings.delete(session);refusals.delete(session);const w=stopWatch(session);if(w?.issued){const dir=w.issued;await serial(()=>retire(dir)).catch(()=>pending.set(session,dir))}}},async closeAll(){refusals.clear();for(const session of[...watches.keys()])stopWatch(session);const results=await Promise.allSettled([...held2.keys()].map(close));if(results.some(r=>r.status==="rejected")||pending.size)throw new Error("some personal identities have pending cleanup; their saved lifecycle records were retained")}}}var import_node_fs14=require("node:fs");var import_node_path12=require("node:path");var CLI_RECORD="cli.json";function readCliRecord(dir){let argv;try{argv=JSON.parse((0,import_node_fs14.readFileSync)((0,import_node_path12.join)(dir,CLI_RECORD),"utf8")).argv}catch{argv=void 0}if(!Array.isArray(argv)||argv.length<2||!argv.every(a=>typeof a==="string"&&a))throw new Error("this Cotal plugin was not installed by `cotal setup`, so it cannot find the Cotal CLI. Run `cotal setup` again.");return argv}var APPROVAL_ID=/^[a-z2-7]{26}$/;var STATUSES=new Set(["approved","denied","expired","refused"]);function approvalFrame(frame){const approval=frame?.approval;if(!approval||typeof approval!=="object")return void 0;const{name,status:status2,id:id2}=approval;if(typeof name!=="string"||!name||name.length>128||/[\r\n]/.test(name)||name!==name.trim())return void 0;if(typeof status2!=="string"||!STATUSES.has(status2))return void 0;if(typeof id2!=="string"||!APPROVAL_ID.test(id2))return void 0;return{name,status:status2,id:id2}}var import_node_fs15=require("node:fs");var import_node_net4=require("node:net");var import_node_os5=require("node:os");var import_node_path13=require("node:path");var import_node_crypto22=require("node:crypto");var ID2=/^[A-Za-z0-9_-]{1,128}$/;var INLINE_FRAME_LIMIT=4096;function isNativeInlineFrame(value){if(!value||typeof value!=="object")return false;const frame=value;const item=frame.inline;return typeof frame.id==="string"&&ID2.test(frame.id)&&typeof frame.route==="string"&&!!item&&item.v===1&&typeof item.receipt==="string"&&ID2.test(item.receipt)&&typeof item.session==="string"&&ID2.test(item.session)&&typeof item.text==="string"&&item.text.startsWith(`Cotal: inline messages for connection_id ${frame.id}.
190
190
  `)&&Number.isInteger(item.count)&&item.count>0&&item.count<=8&&Number.isInteger(item.remaining)&&item.remaining>=0&&JSON.stringify(frame).length<=INLINE_FRAME_LIMIT}var NativeDeliveries=class{constructor(route,timeoutMs=3e4){this.route=route;this.timeoutMs=timeoutMs}route;timeoutMs;offers=new Map;sessions=new Set;settled=new Map;pending(session){for(const[receipt2,offer]of this.offers)if(offer.frame.inline.session===session&&!offer.batch.current())this.finish(receipt2,false);return this.sessions.has(session)}fits(id2,session,payload){return isNativeInlineFrame({id:id2,inline:{...payload,v:1,receipt:"0".repeat(36),session},route:this.route})}send(reader,id2,session,batch,onSettled,retry){if(this.pending(session)||!this.fits(id2,session,batch.payload))return false;const receipt2=(0,import_node_crypto22.randomUUID)();const frame={id:id2,inline:{...batch.payload,v:1,receipt:receipt2,session},route:this.route};this.offers.set(receipt2,{frame,reader,batch,claimed:false,onSettled,retry});this.sessions.add(session);try{reader.write(`${JSON.stringify(frame)}
191
191
  `)}catch{this.finish(receipt2,false);return false}return true}request(value){const{receipt:receipt2,session,id:id2,action}=value;if(typeof receipt2!=="string"||typeof session!=="string"||typeof id2!=="string")return{ok:false};const offer=this.offers.get(receipt2);const prior=this.settled.get(receipt2);if(action==="retry"){if(!prior||prior.id!==id2||prior.session!==session)return{ok:false};const retry=prior.retry;prior.retry=void 0;retry?.();return{ok:true}}if(!offer)return{ok:action==="commit"&&prior?.delivered===true&&prior.id===id2&&prior.session===session};if(offer.frame.id!==id2||offer.frame.inline.session!==session)return{ok:false};if(action==="claim"){if(!offer.batch.current()||offer.reader.destroyed){this.finish(receipt2,false);return{ok:false}}if(!offer.claimed){offer.timer=setTimeout(()=>this.finish(receipt2,false),this.timeoutMs);offer.timer.unref?.()}offer.claimed=true;return{ok:true,frame:offer.frame}}if(action==="defer"){clearTimeout(offer.timer);offer.timer=void 0;offer.claimed=false;return{ok:true}}if(action==="reject"){this.finish(receipt2,false);return{ok:true}}if(action==="commit"&&offer.claimed&&typeof value.uuid==="string"&&ID2.test(value.uuid)){return{ok:this.finish(receipt2,true)}}return{ok:false}}finish(receipt2,delivered){const offer=this.offers.get(receipt2);if(!offer)return false;this.offers.delete(receipt2);this.sessions.delete(offer.frame.inline.session);clearTimeout(offer.timer);let committed=delivered;try{offer.batch.settle(delivered)}catch{committed=false}this.settled.set(receipt2,{id:offer.frame.id,session:offer.frame.inline.session,delivered:committed,retry:offer.retry});while(this.settled.size>128)this.settled.delete(this.settled.keys().next().value);offer.onSettled(committed);return committed}dropReader(reader){for(const[receipt2,offer]of this.offers)if(offer.reader===reader)this.finish(receipt2,false)}close(){for(const receipt2 of this.offers.keys())this.finish(receipt2,false);this.settled.clear()}};var WAKE_ID=/^[A-Za-z0-9_-]{1,128}$/;var WIN_PIPES="\\\\.\\pipe\\";var WIN_PREFIX="cotal-claude-wake-";function wakeDir(){if(process.platform==="win32")return WIN_PIPES;const uid2=process.getuid();const dir=(0,import_node_path13.join)((0,import_node_os5.tmpdir)(),`cotal-claude-wake-${uid2}`);(0,import_node_fs15.mkdirSync)(dir,{recursive:true,mode:448});const st=(0,import_node_fs15.lstatSync)(dir);if(!st.isDirectory()||st.uid!==uid2||(st.mode&63)!==0)throw new Error(`${dir} is not a private directory of this user's`);return dir}var entryName=(claudePid,serverPid)=>process.platform==="win32"?`${WIN_PREFIX}${claudePid}-${serverPid}`:`${claudePid}-${serverPid}.sock`;var ENTRY=process.platform==="win32"?new RegExp(`^${WIN_PREFIX}(\\d+)-(\\d+)$`):/^(\d+)-(\d+)\.sock$/;function alive(pid){try{process.kill(pid,0);return true}catch(e){return e.code==="EPERM"}}function wakeSocketPath(claudePid,serverPid=process.pid){const dir=wakeDir();return process.platform==="win32"?`${dir}${entryName(claudePid,serverPid)}`:(0,import_node_path13.join)(dir,entryName(claudePid,serverPid))}function nativeSocketPath(feed){return`${feed}.native`}async function openWakeFeed(claudePid){const dir=wakeDir();if(process.platform!=="win32"){for(const name of(0,import_node_fs15.readdirSync)(dir)){const server2=ENTRY.exec(name.endsWith(".native")?name.slice(0,-7):name)?.[2];if(server2&&!alive(Number(server2)))(0,import_node_fs15.rmSync)((0,import_node_path13.join)(dir,name),{force:true})}}const path=wakeSocketPath(claudePid);const readers=new Map;const joined=[];const deliveries=new NativeDeliveries(path);let native;const nativeSockets=new Set;const lifecycle=(0,import_node_net4.createServer)(s=>{nativeSockets.add(s);let buffer="";s.setEncoding("utf8");s.on("data",piece=>{buffer+=piece;if(buffer.length>16384){s.destroy();return}const end=buffer.indexOf("\n");if(end<0)return;s.removeAllListeners("data");try{const frame=JSON.parse(buffer.slice(0,end));if(frame.op==="inline"){s.end(`${JSON.stringify(deliveries.request(frame))}
192
192
  `);return}if(frame.op!=="native"||!frame.event||!native){s.destroy();return}void native(frame.event).then(()=>s.end('{"ok":true}\n'),()=>s.end('{"ok":false}\n'))}catch{s.destroy()}});s.on("close",()=>nativeSockets.delete(s));s.on("error",()=>s.destroy())});const server=(0,import_node_net4.createServer)(s=>{const watch=(session,inline=false)=>{readers.set(s,{session,inline});for(const fn of joined)fn()};watch();let buffer="";s.setEncoding("utf8");s.on("data",piece=>{buffer+=piece;if(buffer.length>512){s.destroy();return}const end=buffer.indexOf("\n");if(end<0)return;s.removeAllListeners("data");try{const frame=JSON.parse(buffer.slice(0,end));if(frame.op==="watch"&&typeof frame.session==="string"&&WAKE_ID.test(frame.session))watch(frame.session,frame.inline===1);else s.destroy()}catch{s.destroy()}});s.on("close",()=>{readers.delete(s);deliveries.dropReader(s)});s.on("error",()=>s.destroy())});await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(path,()=>resolve())});try{await new Promise((resolve,reject)=>{lifecycle.once("error",reject);lifecycle.listen(nativeSocketPath(path),()=>resolve())})}catch(error51){server.close();throw error51}return{onNative:fn=>{native=fn},supportsInline:session=>[...readers.values()].some(reader=>reader.session===session&&reader.inline),inlinePending:session=>deliveries.pending(session),fitsInline:(id2,session,payload)=>deliveries.fits(id2,session,payload),sendInline(id2,session,batch,settled,retry){const reader=[...readers].find(([,owner2])=>owner2.session===session&&owner2.inline)?.[0];return!!reader&&deliveries.send(reader,id2,session,batch,settled,retry)},send(id2,preview,session){if(!WAKE_ID.test(id2))throw new Error(`not a connection id: ${JSON.stringify(id2)}`);const frame=JSON.stringify({id:id2,preview});if(frame.length>4096)throw new Error(`Cotal wake preview frame is ${frame.length} characters, over 4096`);let sent=false;for(const[s,owner2]of readers){if(session!==void 0&&owner2.session!==session)continue;s.write(`${frame}
193
193
  `);sent=true}return sent},notifyApproval(session,notice){if(!WAKE_ID.test(session))throw new Error(`not a native session: ${JSON.stringify(session)}`);if(!approvalFrame({approval:notice}))throw new Error("not an approval notice");const frame=JSON.stringify({approval:notice});let sent=false;for(const[s,owner2]of readers){if(owner2.session!==session)continue;s.write(`${frame}
194
194
  `);sent=true}return sent},sendTurn(session,id2,text2){if(!WAKE_ID.test(session)||!WAKE_ID.test(id2))throw new Error("invalid native turn route");const frame=JSON.stringify({turn:{id:id2,text:text2}});if(frame.length>12288)throw new Error("native turn frame is too large");let sent=false;for(const[s,owner2]of readers){if(owner2.session!==session)continue;s.write(`${frame}
195
- `);sent=true}return sent},watched:session=>[...readers.values()].some(reader=>session===void 0||reader.session===session),onReader:fn=>void joined.push(fn),close(){deliveries.close();for(const s of readers.keys())s.destroy();for(const s of nativeSockets)s.destroy();lifecycle.close();server.close()}}}var import_node_fs16=require("node:fs");var HOST_EXE_ENV="COTAL_CLAUDE_EXE";var TERM_WAIT_MS=5e3;var KILL_WAIT_MS=2e3;function hostState(host){let stat;try{stat=(0,import_node_fs16.readFileSync)(`/proc/${host.pid}/stat`,"utf8")}catch(e){return e.code==="ENOENT"?"gone":"unknown"}const fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");if(fields[19]!==host.start||fields[0]==="Z")return"gone";try{return(0,import_node_fs16.realpathSync)(`/proc/${host.pid}/exe`)===host.exe?"same":"unknown"}catch{return"unknown"}}function recordHost(env,pid=process.ppid){const exe=env[HOST_EXE_ENV];if(process.platform!=="linux"||!exe||pid<=1)return void 0;try{const stat=(0,import_node_fs16.readFileSync)(`/proc/${pid}/stat`,"utf8");const start=stat.slice(stat.lastIndexOf(")")+2).split(" ")[19];if(!start||(0,import_node_fs16.realpathSync)(`/proc/${pid}/exe`)!==exe)return void 0;return{pid,start,exe}}catch{return void 0}}async function goneWithin(host,ms){const until=Date.now()+ms;for(;;){if(hostState(host)==="gone")return true;if(Date.now()>=until)return false;await new Promise(resolve=>setTimeout(resolve,100))}}async function endHost(host){if(host===void 0)return false;for(const[signal,wait]of[["SIGTERM",TERM_WAIT_MS],["SIGKILL",KILL_WAIT_MS]]){const state=hostState(host);if(state!=="same")return state==="gone";try{process.kill(host.pid,signal)}catch{return hostState(host)==="gone"}if(await goneWithin(host,wait))return true}return false}var LOCAL="This is the Cotal server on this computer. It can join this computer's registered meshes, including signed-in remote spaces. When the person names a mesh, pass it as space to cotal_connect. Omit space only to use the CLI's default target. Do not move .cotal directories or change environment variables to select a conversation's mesh. Disconnect an existing connection before choosing another space. Before connecting, replace an unwanted pending name or permissions by calling cotal_connect with the new values and no approval_id; never ask the person to approve an unwanted request just to clear it. If a hosted Cotal connector is also available, use this one unless the person asks for the hosted one: a conversation uses one Cotal path. ";var DESKTOP="This is the Cotal server on this computer. It joins the person's local Cotal mesh. It cannot join a signed-in Cotal space, such as one on Cotal Cloud, from this chat: for one, use the space's hosted Cotal connector, which the person adds under Settings > Connectors > Add custom connector with the URL cotal_connect names. A conversation uses one Cotal path. ";var CODE_LISTENING=`This plugin's native hooks module delivers Cotal-attributed incoming messages. A prompt beginning "Cotal: inline messages" contains complete messages; answer those without fetching them again. A notification beginning "Cotal:" without complete messages names the connection_id; read those with cotal_inbox. A notification beginning "Cotal: the person approved", "Cotal: the person denied" or "Cotal: the approval for connection" reports the person's decision on this conversation's pending cotal_connect; finish it exactly as that notification says, and after a denial or expiry do not ask again on your own. cotal_connect reports whether its incoming-message reader is connected. Where it is not: `+GATEWAY_LISTENING;async function serveLocal(desktop){const feed=desktop?void 0:await openWakeFeed(process.ppid);const host=createAppHost({cotal:()=>readCliRecord((0,import_node_path14.dirname)(process.argv[1]??"")),cwd:desktop?(0,import_node_path14.parse)((0,import_node_os6.homedir)()).root:process.cwd(),env:process.env,...feed?{notify:(session,notice)=>feed.notifyApproval(session,notice)}:{},...feed?{turn:(session,id2,text2)=>feed.sendTurn(session,id2,text2)}:{},participate:connection=>connection.agent.participateInTurns()});feed?.onNative(event=>host.nativeEvent(event));let rearm=()=>{};const served=await serveGatewayStdio(host,{source:"claude-local",connectContext:!desktop,space:!desktop,...desktop?{}:{tools:NATIVE_GATEWAY_TOOLS,selection:true},...feed?{instructions:`${LOCAL}${GATEWAY_CONNECTING} ${CODE_LISTENING}`,approvalResume:true,wake:{signal(c,preview){const session=host.sessionFor(c.id);if(session&&feed.supportsInline(session)){if(feed.inlinePending(session))return true;const batch=prepareInlineDelivery(c.agent,{connectionId:c.id,fits:payload=>feed.fitsInline(c.id,session,payload)});if(batch){if(feed.sendInline(c.id,session,batch,delivered=>queueMicrotask(()=>rearm(c,delivered)),()=>queueMicrotask(()=>rearm(c))))return true;batch.settle(false)}}return feed.send(c.id,preview,session)},attach(rewake){rearm=rewake;feed.onReader(()=>rewake())},inboxNotice(c){const session=host.sessionFor(c.id);return!session||!feed.supportsInline(session)},listening(c){const session=host.sessionFor(c.id);if(!session||!feed.watched(session))return"Automatic incoming messages are unavailable in this session. Check that the Cotal plugin and its native hooks module are enabled; call cotal_wait to listen.";return feed.supportsInline(session)?"The Cotal incoming-message reader is connected with complete short-message delivery. New messages can start a turn, subject to Claude's Stop and organization policies.":"The Cotal incoming-message reader is connected in notification-only mode. Read messages with cotal_inbox; reload the Cotal plugin to enable complete short-message delivery."}}}:{instructions:`${DESKTOP}${GATEWAY_INSTRUCTIONS}`}});let ending;const end=()=>ending??=host.closeAll().then(()=>served.close()).finally(()=>{feed?.close();process.exit(0)});process.stdin.on("end",end);process.on("SIGINT",end);process.on("SIGTERM",end)}async function main(){if(!hasIdentity()){process.stderr.write("[cotal-connector] no COTAL_NAME \u2014 not a managed session; serving cotal_connect for this computer's meshes\n");await serveLocal(process.argv.includes("--desktop"));return}const host=recordHost(process.env);registerOnceExit(()=>endHost(host));const session=await serveClaudeSession({env:process.env,input:process.stdin,output:process.stdout,fatalBind:true,onShutdown:code=>process.exit(code)});const stop=()=>void session.close().finally(()=>process.exit(0));process.on("SIGINT",stop);process.on("SIGTERM",stop)}async function serveClaudeSession(opts){let close;try{return await startSession(opts,c=>close=c)}catch(e){await close?.();throw e}}async function startSession(opts,setClose){const env={...opts.env};if(opts.input.readableEnded||opts.input.destroyed)throw new Error("hosted MCP input is already ended or destroyed");let events;let wake;const claude=createClaudeHandle({env,events:()=>events,surfaced:items=>wake?.surfaced(items),orientation:async()=>agent.connected?orientationCard(agent,config2,"claude-code",env):void 0});const config2=configFromEnv(env);config2.connector="claude";const channelFlag=envFlag(env,"COTAL_CHANNEL");const agent=new MeshAgent(config2,env,{withholdProcessCwd:true,onceClaimBound:true});const plane=eventPlaneArmed(config2,env)?createClaudeEventPlane(agent,config2,env):void 0;events=plane?.events;const control=controlFromEnv(env);if(!control){throw new Error("no control endpoint for the lifecycle hooks: set COTAL_CONTROL_SOCKET to a socket path and COTAL_CONTROL_TOKEN to a random secret")}const controlPath=control.path;const controlToken=control.token;let controlServer;let mcp;let stopping;let shuttingDown=false;const onInputClose=()=>shutdown();const close=()=>stopping??=(async()=>{opts.input.off("end",onInputClose);opts.input.off("close",onInputClose);plane?.stop();try{controlServer?.close()}catch{}wake?.stop();try{await events?.close();await agent.stop()}finally{await mcp?.close().catch(()=>{})}})();const shutdown=(code=0)=>{if(shuttingDown)return;shuttingDown=true;void close().then(()=>opts.onShutdown?.(code),e=>{process.stderr.write(`[cotal-connector] session shutdown failed: ${String(e)}
195
+ `);sent=true}return sent},watched:session=>[...readers.values()].some(reader=>session===void 0||reader.session===session),onReader:fn=>void joined.push(fn),close(){deliveries.close();for(const s of readers.keys())s.destroy();for(const s of nativeSockets)s.destroy();lifecycle.close();server.close()}}}var import_node_fs16=require("node:fs");var HOST_EXE_ENV="COTAL_CLAUDE_EXE";var TERM_WAIT_MS=5e3;var KILL_WAIT_MS=2e3;function hostState(host){let stat;try{stat=(0,import_node_fs16.readFileSync)(`/proc/${host.pid}/stat`,"utf8")}catch(e){return e.code==="ENOENT"?"gone":"unknown"}const fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");if(fields[19]!==host.start||fields[0]==="Z")return"gone";try{return(0,import_node_fs16.realpathSync)(`/proc/${host.pid}/exe`)===host.exe?"same":"unknown"}catch{return"unknown"}}function recordHost(env,pid=process.ppid){const exe=env[HOST_EXE_ENV];if(process.platform!=="linux"||!exe||pid<=1)return void 0;try{const stat=(0,import_node_fs16.readFileSync)(`/proc/${pid}/stat`,"utf8");const start=stat.slice(stat.lastIndexOf(")")+2).split(" ")[19];if(!start||(0,import_node_fs16.realpathSync)(`/proc/${pid}/exe`)!==exe)return void 0;return{pid,start,exe}}catch{return void 0}}async function goneWithin(host,ms){const until=Date.now()+ms;for(;;){if(hostState(host)==="gone")return true;if(Date.now()>=until)return false;await new Promise(resolve=>setTimeout(resolve,100))}}async function endHost(host){if(host===void 0)return false;for(const[signal,wait]of[["SIGTERM",TERM_WAIT_MS],["SIGKILL",KILL_WAIT_MS]]){const state=hostState(host);if(state!=="same")return state==="gone";try{process.kill(host.pid,signal)}catch{return hostState(host)==="gone"}if(await goneWithin(host,wait))return true}return false}var LOCAL="This is the Cotal server on this computer. It can join this computer's registered meshes, including signed-in remote spaces. When the person names a mesh, pass it as space to cotal_connect. Omit space only to use the CLI's default target. Do not move .cotal directories or change environment variables to select a conversation's mesh. Disconnect an existing connection before choosing another space. Before connecting, replace an unwanted pending name or permissions by calling cotal_connect with the new values and no approval_id; never ask the person to approve an unwanted request just to clear it. If a hosted Cotal connector is also available, use this one unless the person asks for the hosted one: a conversation uses one Cotal path. ";var DESKTOP="This is the Cotal server on this computer. It joins the person's local Cotal mesh. It cannot join a signed-in Cotal space, such as one on Cotal Cloud, from this chat: for one, use the space's hosted Cotal connector, which the person adds under Settings > Connectors > Add custom connector with the URL cotal_connect names. A conversation uses one Cotal path. ";var CODE_LISTENING=`This plugin's native hooks module delivers Cotal-attributed incoming messages. A prompt beginning "Cotal: inline messages" contains complete messages; answer those without fetching them again. A notification beginning "Cotal:" without complete messages names the connection_id; read those with cotal_inbox. A notification beginning "Cotal: the person approved", "Cotal: the person denied" or "Cotal: the approval for connection" reports the person's decision on this conversation's pending cotal_connect; finish it exactly as that notification says, and after a denial or expiry do not ask again on your own. A notification beginning "Cotal: the mesh refused connection" reports a policy or request failure, not a denial by the person. Read the saved refusal with the name and approval_id it gives; that read makes no new connection request. Show the reason and its available actions, and do not retry the connection automatically. cotal_connect reports whether its incoming-message reader is connected. Where it is not: `+GATEWAY_LISTENING;async function serveLocal(desktop){const feed=desktop?void 0:await openWakeFeed(process.ppid);const host=createAppHost({cotal:()=>readCliRecord((0,import_node_path14.dirname)(process.argv[1]??"")),cwd:desktop?(0,import_node_path14.parse)((0,import_node_os6.homedir)()).root:process.cwd(),env:process.env,...feed?{notify:(session,notice)=>feed.notifyApproval(session,notice)}:{},...feed?{turn:(session,id2,text2)=>feed.sendTurn(session,id2,text2)}:{},participate:connection=>connection.agent.participateInTurns()});feed?.onNative(event=>host.nativeEvent(event));let rearm=()=>{};const served=await serveGatewayStdio(host,{source:"claude-local",connectContext:!desktop,space:!desktop,...desktop?{}:{tools:NATIVE_GATEWAY_TOOLS,selection:true},...feed?{instructions:`${LOCAL}${GATEWAY_CONNECTING} ${CODE_LISTENING}`,approvalResume:true,wake:{signal(c,preview){const session=host.sessionFor(c.id);if(session&&feed.supportsInline(session)){if(feed.inlinePending(session))return true;const batch=prepareInlineDelivery(c.agent,{connectionId:c.id,fits:payload=>feed.fitsInline(c.id,session,payload)});if(batch){if(feed.sendInline(c.id,session,batch,delivered=>queueMicrotask(()=>rearm(c,delivered)),()=>queueMicrotask(()=>rearm(c))))return true;batch.settle(false)}}return feed.send(c.id,preview,session)},attach(rewake){rearm=rewake;feed.onReader(()=>rewake())},inboxNotice(c){const session=host.sessionFor(c.id);return!session||!feed.supportsInline(session)},listening(c){const session=host.sessionFor(c.id);if(!session||!feed.watched(session))return"Automatic incoming messages are unavailable in this session. Check that the Cotal plugin and its native hooks module are enabled; call cotal_wait to listen.";return feed.supportsInline(session)?"The Cotal incoming-message reader is connected with complete short-message delivery. New messages can start a turn, subject to Claude's Stop and organization policies.":"The Cotal incoming-message reader is connected in notification-only mode. Read messages with cotal_inbox; reload the Cotal plugin to enable complete short-message delivery."}}}:{instructions:`${DESKTOP}${GATEWAY_INSTRUCTIONS}`}});let ending;const end=()=>ending??=host.closeAll().then(()=>served.close()).finally(()=>{feed?.close();process.exit(0)});process.stdin.on("end",end);process.on("SIGINT",end);process.on("SIGTERM",end)}async function main(){if(!hasIdentity()){process.stderr.write("[cotal-connector] no COTAL_NAME \u2014 not a managed session; serving cotal_connect for this computer's meshes\n");await serveLocal(process.argv.includes("--desktop"));return}const host=recordHost(process.env);registerOnceExit(()=>endHost(host));const session=await serveClaudeSession({env:process.env,input:process.stdin,output:process.stdout,fatalBind:true,onShutdown:code=>process.exit(code)});const stop=()=>void session.close().finally(()=>process.exit(0));process.on("SIGINT",stop);process.on("SIGTERM",stop)}async function serveClaudeSession(opts){let close;try{return await startSession(opts,c=>close=c)}catch(e){await close?.();throw e}}async function startSession(opts,setClose){const env={...opts.env};if(opts.input.readableEnded||opts.input.destroyed)throw new Error("hosted MCP input is already ended or destroyed");let events;let wake;const claude=createClaudeHandle({env,events:()=>events,surfaced:items=>wake?.surfaced(items),orientation:async()=>agent.connected?orientationCard(agent,config2,"claude-code",env):void 0});const config2=configFromEnv(env);config2.connector="claude";const channelFlag=envFlag(env,"COTAL_CHANNEL");const agent=new MeshAgent(config2,env,{withholdProcessCwd:true,onceClaimBound:true});const plane=eventPlaneArmed(config2,env)?createClaudeEventPlane(agent,config2,env):void 0;events=plane?.events;const control=controlFromEnv(env);if(!control){throw new Error("no control endpoint for the lifecycle hooks: set COTAL_CONTROL_SOCKET to a socket path and COTAL_CONTROL_TOKEN to a random secret")}const controlPath=control.path;const controlToken=control.token;let controlServer;let mcp;let stopping;let shuttingDown=false;const onInputClose=()=>shutdown();const close=()=>stopping??=(async()=>{opts.input.off("end",onInputClose);opts.input.off("close",onInputClose);plane?.stop();try{controlServer?.close()}catch{}wake?.stop();try{await events?.close();await agent.stop()}finally{await mcp?.close().catch(()=>{})}})();const shutdown=(code=0)=>{if(shuttingDown)return;shuttingDown=true;void close().then(()=>opts.onShutdown?.(code),e=>{process.stderr.write(`[cotal-connector] session shutdown failed: ${String(e)}
196
196
  `);opts.onShutdown?.(1)})};setClose(close);controlServer=startControlServer(agent,{path:controlPath,token:controlToken},claude.handle,{fatalBind:opts.fatalBind??false,onShutdown:()=>void shutdown(),onReply:claude.onReply});await new Promise((resolve,reject)=>{controlServer.once("listening",resolve);controlServer.once("error",reject)});if(opts.input.readableEnded||opts.input.destroyed)throw new Error("hosted MCP input ended before startup completed");agent.start();const server=new McpServer({name:"cotal",version:DOCS_VERSION},{capabilities:{experimental:{"claude/channel":{}}},instructions:briefing(config2,"claude-code")});mcp=server;registerCotalTools(server,agent,config2,"claude-code",env,claude.inboxDeliveryNote);wake=createWakePolicy(agent,params=>server.server.notification({method:"notifications/claude/channel",params}),msg=>process.stderr.write(`[cotal-connector] ${msg}
197
197
  `));opts.input.once("end",onInputClose);opts.input.once("close",onInputClose);server.server.oninitialized=()=>{const clientCaps=server.server.getClientCapabilities();const channelActive=channelFlag??Boolean(clientCaps?.experimental?.["claude/channel"]);wake?.setChannelActive(channelActive);process.stderr.write(`[cotal-connector] client capabilities: ${JSON.stringify(clientCaps??{})} \u2192 channel ${channelActive?"ACTIVE":"off"}
198
198
  `)};const transport=new StdioServerTransport(opts.input,opts.output);await server.connect(transport);process.stderr.write(`[cotal-connector] MCP ready (stdio) \u2014 space="${config2.space}" name="${config2.name}"${config2.role?` role="${config2.role}"`:""}
package/dist/mcp.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AA6KtD,yFAAyF;AACzF,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,KAAK,EAAE,QAAQ,CAAC;IAChB,MAAM,EAAE,QAAQ,CAAC;IACjB;uDACmD;IACnD,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;gFAC4E;IAC5E,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb;uDACmD;IACnD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;+BAE+B;AAC/B,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CAQ3F;AA4JD;;;;;;;;GAQG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAOnD"}
1
+ {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AA8KtD,yFAAyF;AACzF,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,KAAK,EAAE,QAAQ,CAAC;IAChB,MAAM,EAAE,QAAQ,CAAC;IACjB;uDACmD;IACnD,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;gFAC4E;IAC5E,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb;uDACmD;IACnD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;+BAE+B;AAC/B,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CAQ3F;AA4JD;;;;;;;;GAQG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAOnD"}
package/dist/monitor.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var import_node_net2=require("node:net");var import_node_fs=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path=require("node:path");var isWin=process.platform==="win32";function sys32(exe){const root=process.env.SystemRoot||process.env.windir||"C:\\Windows";return(0,import_node_path.join)(root,"System32",exe)}var cachedSid;function ownerSid(){if(cachedSid)return cachedSid;const out=(0,import_node_child_process.execFileSync)(sys32("whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8"});const sid=out.trim().split(",").pop()?.replace(/^"|"$/g,"").trim();if(!sid||!/^S-1-/.test(sid))throw new Error(`could not determine the current user's SID from \`whoami\` (got: ${out.trim()})`);cachedSid=sid;return sid}var BROAD_SIDS=["S-1-1-0","S-1-5-11","S-1-5-32-545"];function hardenPrivate(path,kind){if(!isWin){if(kind==="file")(0,import_node_fs.closeSync)(openPrivate(path,import_node_fs.constants.O_RDONLY));else(0,import_node_fs.chmodSync)(path,448);return}const perm=kind==="dir"?"(OI)(CI)(F)":"(F)";const removeBroad=BROAD_SIDS.flatMap(sid=>["/remove:g",`*${sid}`]);const grant=sid=>["/grant:r",`*${sid}:${perm}`];try{(0,import_node_child_process.execFileSync)(sys32("icacls.exe"),[(0,import_node_path.toNamespacedPath)((0,import_node_path.resolve)(path)),"/inheritance:r",...removeBroad,...grant(ownerSid()),...grant("S-1-5-18"),...grant("S-1-5-32-544")],{stdio:["ignore","ignore","pipe"]})}catch(e){throw new Error(`failed to harden ${kind} "${path}" to private via icacls: ${e.message.trim()}. Cotal will not leave a secret with a permissive ACL - ensure the path is on an NTFS volume and %SystemRoot%\\System32\\icacls.exe is available.`)}}function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=(0,import_node_fs.openSync)(path,flags,384);try{(0,import_node_fs.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs.openSync)(path,flags|import_node_fs.constants.O_NOFOLLOW|import_node_fs.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs.fstatSync)(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);(0,import_node_fs.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs.constants.O_WRONLY|import_node_fs.constants.O_CREAT|(exclusive?import_node_fs.constants.O_EXCL:0));try{try{(0,import_node_fs.ftruncateSync)(fd);(0,import_node_fs.writeFileSync)(fd,data)}finally{(0,import_node_fs.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs.unlinkSync)(path)}catch{}}throw e}}function writePrivate(path,data,exclusive){writeBytes(path,data,exclusive);if(!isWin)return;try{hardenPrivate(path,"file")}catch(e){try{(0,import_node_fs.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs.mkdirSync)(path,{recursive:true,mode:448});hardenPrivate(path,"dir")}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var MAX_FRAME_BYTES=1<<20;var APPROVAL_ID=/^[a-z2-7]{26}$/;var STATUSES=new Set(["approved","denied","expired"]);function approvalFrame(frame){const approval=frame?.approval;if(!approval||typeof approval!=="object")return void 0;const{name,status,id}=approval;if(typeof name!=="string"||!name||name.length>128||/[\r\n]/.test(name)||name!==name.trim())return void 0;if(typeof status!=="string"||!STATUSES.has(status))return void 0;if(typeof id!=="string"||!APPROVAL_ID.test(id))return void 0;return{name,status,id}}function approvalEvent(n){const name=JSON.stringify(n.name);switch(n.status){case"approved":return`Cotal: the person approved connection ${name}. Finish it: call cotal_connect with name ${name} and approval_id ${JSON.stringify(n.id)}.`;case"denied":return`Cotal: the person denied connection ${name}. Nothing was connected. Do not ask again unless the person asks you to.`;case"expired":return`Cotal: the approval for connection ${name} expired before the person decided. Nothing was connected. Call cotal_connect with name ${name} again to ask again.`}}var import_node_fs2=require("node:fs");var import_node_os=require("node:os");var import_node_path2=require("node:path");var ID=/^[A-Za-z0-9_-]{1,128}$/;var INLINE_FRAME_LIMIT=4096;function isNativeInlineFrame(value){if(!value||typeof value!=="object")return false;const frame=value;const item=frame.inline;return typeof frame.id==="string"&&ID.test(frame.id)&&typeof frame.route==="string"&&!!item&&item.v===1&&typeof item.receipt==="string"&&ID.test(item.receipt)&&typeof item.session==="string"&&ID.test(item.session)&&typeof item.text==="string"&&item.text.startsWith(`Cotal: inline messages for connection_id ${frame.id}.
1
+ "use strict";var import_node_net2=require("node:net");var import_node_fs=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path=require("node:path");var isWin=process.platform==="win32";function sys32(exe){const root=process.env.SystemRoot||process.env.windir||"C:\\Windows";return(0,import_node_path.join)(root,"System32",exe)}var cachedSid;function ownerSid(){if(cachedSid)return cachedSid;const out=(0,import_node_child_process.execFileSync)(sys32("whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8"});const sid=out.trim().split(",").pop()?.replace(/^"|"$/g,"").trim();if(!sid||!/^S-1-/.test(sid))throw new Error(`could not determine the current user's SID from \`whoami\` (got: ${out.trim()})`);cachedSid=sid;return sid}var BROAD_SIDS=["S-1-1-0","S-1-5-11","S-1-5-32-545"];function hardenPrivate(path,kind){if(!isWin){if(kind==="file")(0,import_node_fs.closeSync)(openPrivate(path,import_node_fs.constants.O_RDONLY));else(0,import_node_fs.chmodSync)(path,448);return}const perm=kind==="dir"?"(OI)(CI)(F)":"(F)";const removeBroad=BROAD_SIDS.flatMap(sid=>["/remove:g",`*${sid}`]);const grant=sid=>["/grant:r",`*${sid}:${perm}`];try{(0,import_node_child_process.execFileSync)(sys32("icacls.exe"),[(0,import_node_path.toNamespacedPath)((0,import_node_path.resolve)(path)),"/inheritance:r",...removeBroad,...grant(ownerSid()),...grant("S-1-5-18"),...grant("S-1-5-32-544")],{stdio:["ignore","ignore","pipe"]})}catch(e){throw new Error(`failed to harden ${kind} "${path}" to private via icacls: ${e.message.trim()}. Cotal will not leave a secret with a permissive ACL - ensure the path is on an NTFS volume and %SystemRoot%\\System32\\icacls.exe is available.`)}}function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=(0,import_node_fs.openSync)(path,flags,384);try{(0,import_node_fs.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs.openSync)(path,flags|import_node_fs.constants.O_NOFOLLOW|import_node_fs.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs.fstatSync)(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);(0,import_node_fs.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs.constants.O_WRONLY|import_node_fs.constants.O_CREAT|(exclusive?import_node_fs.constants.O_EXCL:0));try{try{(0,import_node_fs.ftruncateSync)(fd);(0,import_node_fs.writeFileSync)(fd,data)}finally{(0,import_node_fs.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs.unlinkSync)(path)}catch{}}throw e}}function writePrivate(path,data,exclusive){writeBytes(path,data,exclusive);if(!isWin)return;try{hardenPrivate(path,"file")}catch(e){try{(0,import_node_fs.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs.mkdirSync)(path,{recursive:true,mode:448});hardenPrivate(path,"dir")}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var MAX_FRAME_BYTES=1<<20;var APPROVAL_ID=/^[a-z2-7]{26}$/;var STATUSES=new Set(["approved","denied","expired","refused"]);function approvalFrame(frame){const approval=frame?.approval;if(!approval||typeof approval!=="object")return void 0;const{name,status,id}=approval;if(typeof name!=="string"||!name||name.length>128||/[\r\n]/.test(name)||name!==name.trim())return void 0;if(typeof status!=="string"||!STATUSES.has(status))return void 0;if(typeof id!=="string"||!APPROVAL_ID.test(id))return void 0;return{name,status,id}}function approvalEvent(n){const name=JSON.stringify(n.name);switch(n.status){case"approved":return`Cotal: the person approved connection ${name}. Finish it: call cotal_connect with name ${name} and approval_id ${JSON.stringify(n.id)}.`;case"denied":return`Cotal: the person denied connection ${name}. Nothing was connected. Do not ask again unless the person asks you to.`;case"refused":return`Cotal: the mesh refused connection ${name}. Read the refusal: call cotal_connect with name ${name} and approval_id ${JSON.stringify(n.id)}. Do not retry the connection automatically.`;case"expired":return`Cotal: the approval for connection ${name} expired before the person decided. Nothing was connected. Call cotal_connect with name ${name} again to ask again.`}}var import_node_fs2=require("node:fs");var import_node_os=require("node:os");var import_node_path2=require("node:path");var ID=/^[A-Za-z0-9_-]{1,128}$/;var INLINE_FRAME_LIMIT=4096;function isNativeInlineFrame(value){if(!value||typeof value!=="object")return false;const frame=value;const item=frame.inline;return typeof frame.id==="string"&&ID.test(frame.id)&&typeof frame.route==="string"&&!!item&&item.v===1&&typeof item.receipt==="string"&&ID.test(item.receipt)&&typeof item.session==="string"&&ID.test(item.session)&&typeof item.text==="string"&&item.text.startsWith(`Cotal: inline messages for connection_id ${frame.id}.
2
2
  `)&&Number.isInteger(item.count)&&item.count>0&&item.count<=8&&Number.isInteger(item.remaining)&&item.remaining>=0&&JSON.stringify(frame).length<=INLINE_FRAME_LIMIT}var WAKE_ID=/^[A-Za-z0-9_-]{1,128}$/;var WIN_PIPES="\\\\.\\pipe\\";var WIN_PREFIX="cotal-claude-wake-";function wakeDir(){if(process.platform==="win32")return WIN_PIPES;const uid=process.getuid();const dir=(0,import_node_path2.join)((0,import_node_os.tmpdir)(),`cotal-claude-wake-${uid}`);(0,import_node_fs2.mkdirSync)(dir,{recursive:true,mode:448});const st=(0,import_node_fs2.lstatSync)(dir);if(!st.isDirectory()||st.uid!==uid||(st.mode&63)!==0)throw new Error(`${dir} is not a private directory of this user's`);return dir}var entryName=(claudePid,serverPid)=>process.platform==="win32"?`${WIN_PREFIX}${claudePid}-${serverPid}`:`${claudePid}-${serverPid}.sock`;var ENTRY=process.platform==="win32"?new RegExp(`^${WIN_PREFIX}(\\d+)-(\\d+)$`):/^(\d+)-(\d+)\.sock$/;function alive(pid){try{process.kill(pid,0);return true}catch(e){return e.code==="EPERM"}}function wakeSocketPath(claudePid,serverPid=process.pid){const dir=wakeDir();return process.platform==="win32"?`${dir}${entryName(claudePid,serverPid)}`:(0,import_node_path2.join)(dir,entryName(claudePid,serverPid))}function wakeSockets(claudePid){const dir=wakeDir();return(0,import_node_fs2.readdirSync)(dir).flatMap(name=>{const m=ENTRY.exec(name);return m?.[1]===String(claudePid)&&alive(Number(m[2]))?[wakeSocketPath(claudePid,Number(m[2]))]:[]})}function nativeSocketPath(feed){return`${feed}.native`}var import_node_fs3=require("node:fs");var import_node_net=require("node:net");var import_node_os2=require("node:os");var import_node_path3=require("node:path");function stateFile(session){if(!WAKE_ID.test(session))throw new Error("invalid native session identity");const root=(0,import_node_path3.join)((0,import_node_os2.tmpdir)(),`cotal-claude-native-${process.getuid?.()??"local"}`);const st=(0,import_node_fs3.lstatSync)(root,{throwIfNoEntry:false});if(st&&(!st.isDirectory()||process.getuid&&st.uid!==process.getuid()))throw new Error("native session state is not this user's private directory");mkSecretDir(root);return(0,import_node_path3.join)(root,`${session}.json`)}function readRecord(file){const st=(0,import_node_fs3.lstatSync)(file,{throwIfNoEntry:false});if(!st)return void 0;if(!st.isFile()||st.size>16384||process.getuid&&(st.uid!==process.getuid()||(st.mode&63)!==0))throw new Error("native session state is not an owner-private bounded regular file");const value=JSON.parse((0,import_node_fs3.readFileSync)(file,"utf8"));if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("invalid native session state");return value}function transcriptMatches(session,path){return typeof path==="string"&&(0,import_node_path3.isAbsolute)(path)&&(0,import_node_path3.basename)(path)===`${session}.jsonl`}function readPersonalBinding(session){const event=readRecord(stateFile(session));if(!event||event.session_id!==session||!transcriptMatches(session,event.transcript_path))throw new Error("no native command-hook transcript binding for this session");return event}async function forward(event,hostPid){const paths=wakeSockets(hostPid);if(!paths.length)throw new Error("no local native lifecycle server");await Promise.all(paths.map(path=>new Promise((resolve2,reject)=>{const socket=(0,import_node_net.createConnection)(nativeSocketPath(path));let reply="";socket.setEncoding("utf8");socket.setTimeout(2e3,()=>socket.destroy(new Error("native lifecycle relay timed out")));socket.on("connect",()=>socket.write(`${JSON.stringify({op:"native",event})}
3
3
  `));socket.on("data",data=>{reply+=data;if(reply.length>128)socket.destroy()});socket.on("error",reject);socket.on("close",()=>{try{if(JSON.parse(reply).ok===true)resolve2();else reject(new Error("native lifecycle binding refused"))}catch{reject(new Error("native lifecycle binding was not confirmed"))}})})))}async function bindPersonalSession(event,hostPid){const session=event.session_id;if(typeof session!=="string"||!Number.isInteger(hostPid)||hostPid<=0)throw new Error("invalid native lifecycle binding");const previous=readPersonalBinding(session);if(previous.transcript_path!==event.transcript_path)throw new Error("native lifecycle binding does not match the command hook");writeSecretFileAtomic(`${stateFile(session)}.host`,JSON.stringify({hostPid}));await forward(event,hostPid)}var SCAN_MS=1e3;var wakeEvent=id=>`Cotal: a new message for connection_id ${id}. Read it with cotal_inbox.`;var previewEvent=(id,preview)=>`Cotal preview for connection_id ${id}: ${JSON.stringify(preview)}`;async function relayNative(claude,raw){const event=JSON.parse(raw);if(typeof event.session_id!=="string"||!WAKE_ID.test(event.session_id)||raw.length>8192)throw new Error("invalid native lifecycle frame");await bindPersonalSession(event,claude)}async function relayInline(claude,session){let input="";for await(const piece of process.stdin){input+=piece;if(input.length>1024)throw new Error("inline receipt is too large")}const frame=JSON.parse(input);if(!session||frame.session!==session||typeof frame.route!=="string"||!wakeSockets(claude).includes(frame.route)||!["claim","commit","defer","reject","retry"].includes(String(frame.action))||typeof frame.receipt!=="string"||!WAKE_ID.test(frame.receipt)||typeof frame.id!=="string"||!WAKE_ID.test(frame.id))throw new Error("invalid inline receipt");const reply=await new Promise((resolve2,reject)=>{const socket=(0,import_node_net2.createConnection)(nativeSocketPath(frame.route));let buffer="";socket.setEncoding("utf8");socket.setTimeout(2e3,()=>socket.destroy(new Error("inline receipt timed out")));socket.on("connect",()=>socket.write(`${JSON.stringify({...frame,op:"inline"})}
4
4
  `));socket.on("data",piece=>{buffer+=piece;if(buffer.length>INLINE_FRAME_LIMIT+64)socket.destroy(new Error("inline reply is too large"))});socket.on("error",reject);socket.on("close",()=>resolve2(buffer))});const result=JSON.parse(reply);if(result.ok!==true&&result.ok!==false||result.frame!==void 0&&!isNativeInlineFrame(result.frame))throw new Error("invalid inline reply");process.stdout.write(`${JSON.stringify(result)}
@@ -5,6 +5,7 @@ const INLINE = /^Cotal: inline messages for connection_id ([A-Za-z0-9_-]{1,128})
5
5
  // (src/approval-notice.ts). Names are JSON strings; nothing else about the line is free text.
6
6
  const QUOTED = '"((?:[^"\\\\\\x00-\\x1f]|\\\\.){1,512})"';
7
7
  const APPROVED = new RegExp(`^Cotal: the person approved connection ${QUOTED}\\. Finish it: call cotal_connect with name ${QUOTED} and approval_id "([a-z2-7]{26})"\\.$`);
8
+ const REFUSED = new RegExp(`^Cotal: the mesh refused connection ${QUOTED}\\. Read the refusal: call cotal_connect with name ${QUOTED} and approval_id "([a-z2-7]{26})"\\. Do not retry the connection automatically\\.$`);
8
9
  const DENIED = new RegExp(`^Cotal: the person denied connection ${QUOTED}\\. Nothing was connected\\. Do not ask again unless the person asks you to\\.$`);
9
10
  const EXPIRED = new RegExp(`^Cotal: the approval for connection ${QUOTED} expired before the person decided\\. Nothing was connected\\. Call cotal_connect with name ${QUOTED} again to ask again\\.$`);
10
11
  const ID = /^[A-Za-z0-9_-]{1,128}$/;
@@ -24,7 +25,7 @@ let readerSession;
24
25
  let nativeBinding;
25
26
 
26
27
  function approvalLine(line) {
27
- const match = APPROVED.exec(line) || DENIED.exec(line) || EXPIRED.exec(line);
28
+ const match = APPROVED.exec(line) || DENIED.exec(line) || EXPIRED.exec(line) || REFUSED.exec(line);
28
29
  if (!match) return false;
29
30
  try {
30
31
  const name = JSON.parse(`"${match[1]}"`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cotal-ai/connector-claude-code",
3
3
  "description": "Cotal connector for Claude Code: an installed plugin that joins a session to the mesh.",
4
- "version": "0.162.0",
4
+ "version": "0.163.0",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  "@cotal-ai/core": ">=0.1.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@cotal-ai/connector-core": "0.162.0",
29
- "@cotal-ai/core": "0.162.0",
28
+ "@cotal-ai/connector-core": "0.163.0",
29
+ "@cotal-ai/core": "0.163.0",
30
30
  "@cotal-ai/smoke-kit": "0.0.0",
31
31
  "@modelcontextprotocol/sdk": "^1.29.0",
32
32
  "@nats-io/transport-node": "^3.4.0",