@cotal-ai/connector-claude-code 0.135.4 → 0.135.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs-index.bin +0 -0
- package/dist/hooks.d.ts.map +1 -1
- package/dist/mcp.cjs +3 -3
- package/package.json +3 -3
package/dist/docs-index.bin
CHANGED
|
Binary file
|
package/dist/hooks.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAcA,OAAO,EAML,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,UAAU,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAqEjD,MAAM,WAAW,gBAAgB;IAC/B,mGAAmG;IACnG,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,+FAA+F;IAC/F,MAAM,CAAC,EAAE,MAAM,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACnE,iFAAiF;IACjF,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI,CAAC;IACjD,sFAAsF;IACtF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qGAAqG;IACrG,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;6FAEyF;IACzF,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACjD;AASD,eAAO,MAAM,kBAAkB,OAAQ,CAAC;AAGxC;;+DAE+D;AAC/D,MAAM,WAAW,WAAW;IAC1B;gGAC4F;IAC5F,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;IACrD,MAAM,EAAE,UAAU,CAAC;IACnB,iDAAiD;IACjD,OAAO,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACxE,2FAA2F;IAC3F,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAAC;CACzC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE,gBAAqB,GAAG,WAAW,
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAcA,OAAO,EAML,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,UAAU,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAqEjD,MAAM,WAAW,gBAAgB;IAC/B,mGAAmG;IACnG,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,+FAA+F;IAC/F,MAAM,CAAC,EAAE,MAAM,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACnE,iFAAiF;IACjF,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI,CAAC;IACjD,sFAAsF;IACtF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qGAAqG;IACrG,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;6FAEyF;IACzF,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACjD;AASD,eAAO,MAAM,kBAAkB,OAAQ,CAAC;AAGxC;;+DAE+D;AAC/D,MAAM,WAAW,WAAW;IAC1B;gGAC4F;IAC5F,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;IACrD,MAAM,EAAE,UAAU,CAAC;IACnB,iDAAiD;IACjD,OAAO,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACxE,2FAA2F;IAC3F,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAAC;CACzC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE,gBAAqB,GAAG,WAAW,CAob3E;AAED,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5H,MAAM,WAAW,UAAU;IACzB,+EAA+E;IAC/E,gBAAgB,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;IACxC;+FAC2F;IAC3F,QAAQ,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,GAAG,IAAI,CAAC;IAC5C,sCAAsC;IACtC,IAAI,IAAI,IAAI,CAAC;CACd;AAKD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,GAAG,GAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAe,GAAG,UAAU,CAsH3H"}
|
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 receipt="";sock.on("data",d=>{receipt+=d;if(!receipt.includes("\n"))return;clearTimeout(deadline);try{sock.end()}catch{}done(true)});try{sock.write(JSON.stringify(reply)+"\n",err3=>{if(!err3)return;clearTimeout(deadline);done(false)})}catch{clearTimeout(deadline);done(false)}})}function startControlServer(agent,endpoint,handle,opts={}){const{path}=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_fs10.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_fs10.lstatSync)(path);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}(0,import_node_fs10.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 selected=[];const render=items=>{const remaining=pending.length-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});async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}try{const res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message}`)}}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs11=require("node:fs");var import_node_path8=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.135.4";function loadDocsMetadata(){return{"version":"0.135.4","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. The wire contract (v0.x) may still change under the change process. This page tracks what is deliberately not built yet, and the direction each area is headed."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"cotal setup (implementations/cli/src/commands/setup.ts) saves configuration by default: it checks prerequisites, sets up the chosen application and runtimes, and seeds persona files."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Substrate stability tells you what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs11.readFileSync)((0,import_node_path8.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1115516||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="23dfdbebe0cc56296cd3b54211f8e569f712d4b81156a806dfc2c6767cb1e801")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,9026],[9026,27793],[27793,32010],[32010,36381],[36381,39509],[39509,44742],[44742,48110],[48110,57098],[57098,61250],[61250,65698],[65698,67720],[67720,71731],[71731,101783],[101783,117271],[117271,132401],[132401,15e4],[15e4,164864],[164864,179496],[179496,194752],[194752,214278],[214278,219994],[219994,229552],[229552,247131],[247131,251535],[251535,272621],[272621,281727],[281727,310201],[310201,326106],[326106,348797],[348797,378448],[378448,391542],[391542,393489],[393489,402318],[402318,418324],[418324,425815],[425815,428499],[428499,431880],[431880,435183],[435183,437228],[437228,439833],[439833,444483],[444483,446287],[446287,449838],[449838,461283],[461283,469244],[469244,472769],[472769,477939],[477939,482850],[482850,485721],[485721,493663],[493663,496640],[496640,503788],[503788,506778],[506778,511428],[511428,522409],[522409,533490],[533490,538382],[538382,545913],[545913,549262],[549262,551833],[551833,559091],[559091,562476],[562476,564686],[564686,568148],[568148,571566],[571566,572680],[572680,574429],[574429,578085],[578085,582638],[582638,589071],[589071,599385],[599385,612274],[612274,614111],[614111,626922],[626922,632038],[632038,635774],[635774,638283],[638283,643329],[643329,650104],[650104,656170],[656170,656917],[656917,660831],[660831,665900],[665900,669278],[669278,673164],[673164,677187],[677187,681989],[681989,685140],[685140,688539],[688539,692586],[692586,696111],[696111,708247],[708247,711065],[711065,713748],[713748,716376],[716376,718867],[718867,722887],[722887,727587],[727587,729806],[729806,789585],[789585,792656],[792656,793636],[793636,797715],[797715,805471],[805471,815501],[815501,824023],[824023,829080],[829080,1072662],[1072662,1110304],[1110304,1115516]];var sourceLengths=[4844,4048,12561,75273,11674,10644,29417,13195,8199,78405,37758,10864,4557,9872,81561,41661,42535,50018,41170,42370,41541,54106,14375,25041,49829,9889,60481,24959,86255,44853,67764,91136,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11759,4292,8347,30465,19623,8745,31524,12472,7037,20396,7140,18475,6860,11538,28251,28907,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9816,10853,15565,26241,33068,4227,34884,11735,9122,8201,13307,16844,14721,1464,8767,12941,7818,9320,9965,11921,6532,8528,9633,8223,30647,6519,6405,5824,6007,9711,11730,5283,174038,6927,2023,9304,20040,25734,20345,12299,705228,106096,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse((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_fs11.readFileSync)((0,import_node_path8.join)(__dirname,"docs-index.bin"));if(packed.length!==576892||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="8b0149b1bb37dbb7a2480319ab5a4b505cf05dcdd53b0eb14c716bc9d596374a")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});async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}try{const res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message}`)}}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs11=require("node:fs");var import_node_path8=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.135.5";function loadDocsMetadata(){return{"version":"0.135.5","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal uses pnpm, Changesets and one GitHub Actions workflow."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0. The wire contract (v0.x) may still change under the change process. This page tracks what is deliberately not built yet, and the direction each area is headed."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"cotal setup (implementations/cli/src/commands/setup.ts) saves configuration by default: it checks prerequisites, sets up the chosen application and runtimes, and seeds persona files."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Substrate stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Substrate stability tells you what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs11.readFileSync)((0,import_node_path8.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1115516||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="23dfdbebe0cc56296cd3b54211f8e569f712d4b81156a806dfc2c6767cb1e801")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,9026],[9026,27793],[27793,32010],[32010,36381],[36381,39509],[39509,44742],[44742,48110],[48110,57098],[57098,61250],[61250,65698],[65698,67720],[67720,71731],[71731,101783],[101783,117271],[117271,132401],[132401,15e4],[15e4,164864],[164864,179496],[179496,194752],[194752,214278],[214278,219994],[219994,229552],[229552,247131],[247131,251535],[251535,272621],[272621,281727],[281727,310201],[310201,326106],[326106,348797],[348797,378448],[378448,391542],[391542,393489],[393489,402318],[402318,418324],[418324,425815],[425815,428499],[428499,431880],[431880,435183],[435183,437228],[437228,439833],[439833,444483],[444483,446287],[446287,449838],[449838,461283],[461283,469244],[469244,472769],[472769,477939],[477939,482850],[482850,485721],[485721,493663],[493663,496640],[496640,503788],[503788,506778],[506778,511428],[511428,522409],[522409,533490],[533490,538382],[538382,545913],[545913,549262],[549262,551833],[551833,559091],[559091,562476],[562476,564686],[564686,568148],[568148,571566],[571566,572680],[572680,574429],[574429,578085],[578085,582638],[582638,589071],[589071,599385],[599385,612274],[612274,614111],[614111,626922],[626922,632038],[632038,635774],[635774,638283],[638283,643329],[643329,650104],[650104,656170],[656170,656917],[656917,660831],[660831,665900],[665900,669278],[669278,673164],[673164,677187],[677187,681989],[681989,685140],[685140,688539],[688539,692586],[692586,696111],[696111,708247],[708247,711065],[711065,713748],[713748,716376],[716376,718867],[718867,722887],[722887,727587],[727587,729806],[729806,789585],[789585,792656],[792656,793636],[793636,797715],[797715,805471],[805471,815501],[815501,824023],[824023,829080],[829080,1072662],[1072662,1110304],[1110304,1115516]];var sourceLengths=[4844,4048,12561,75273,11674,10644,29417,13195,8199,78405,37758,10864,4557,9872,81561,41661,42535,50018,41170,42370,41541,54106,14375,25041,49829,9889,60481,24959,86255,44853,67764,91136,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11759,4292,8347,30465,19623,8745,31524,12472,7037,20396,7140,18475,6860,11538,28251,28907,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9816,10853,15565,26241,33068,4227,34884,11735,9122,8201,13307,16844,14721,1464,8767,12941,7818,9320,9965,11921,6532,8528,9633,8223,30647,6519,6405,5824,6007,9711,11730,5283,174038,6927,2023,9304,20040,25734,20345,12299,705228,106096,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse((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_fs11.readFileSync)((0,import_node_path8.join)(__dirname,"docs-index.bin"));if(packed.length!==576893||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="0c2551cfd766f9e0ed6597163fd3cd2bf8e4b9a3e3c67fa3129025e08827cdb8")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}
|
|
@@ -181,9 +181,9 @@ ${card}
|
|
|
181
181
|
${briefing(c.config,"gateway")}`})}catch(e){if(e instanceof ApprovalRequired){const resume=options.approvalResume?` and approval_id ${JSON.stringify(e.pending.approval.id)}`:"";const message=`Permission approval required. This conversation is not connected.
|
|
182
182
|
The person must open ${e.pending.approval.url}, review or edit the permissions, and choose Approve or Deny.
|
|
183
183
|
Expires: ${e.pending.approval.expiresAt}. Only the person's decision in Cotal counts; do not open the decision page or approve on their behalf.
|
|
184
|
-
After they approve, retry cotal_connect with name ${JSON.stringify(candidate2)}${resume} and the same requested permissions. Do not poll or start another request while waiting.`;const structuredContent={v:1,status:"pending",name:candidate2,requestId:e.pending.requestId,approval:e.pending.approval,proposed:e.pending.proposed,message};return{content:[{type:"text",text:message},{type:"text",text:JSON.stringify(structuredContent)}],structuredContent}}if(e instanceof NameTaken){if(approvalId)return refuse2("The approved name is no longer available. Nothing was connected; a different name requires a new permission approval.");continue}return refuse2(`cotal_connect failed for ${JSON.stringify(candidate2)}: ${errorText(e)}`)}}return refuse2(`cotal_connect: ${JSON.stringify(name)} and its next ${GATEWAY_NAME_ATTEMPTS-1} variants are all taken. Choose another name.`)});server.registerTool("cotal_disconnect",{title:"Cotal: disconnect this conversation",annotations:gatewayAnnotations("cotal_disconnect"),description:"Leave the mesh for this conversation's connection. Other conversations stay connected.",inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID})},async({connection_id},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}return await host.close(account,connection_id)?toContent2({text:`Disconnected ${connection_id}.`}):refuse2(CONNECTION_REQUIRED)});if(options.tools?.has("cotal_turn_participate")&&host.participate)server.registerTool("cotal_turn_participate",{title:"Cotal: participate in workflow turns",annotations:gatewayAnnotations("cotal_turn_participate"),description:"Opt this user-owned native personal connection into workflow turn participation, or renew its finite lease. The lease is self-only and grants no process stop or attach custody.",inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID})},async({connection_id},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const connection=await host.find(account,connection_id);if(!connection)return refuse2(CONNECTION_REQUIRED);if(!connection.tools?.has("cotal_turn_participate"))return refuse2("cotal_turn_participate is not available on this connection.");try{const lease=await host.participate(account,connection);connection.agent.authorizeNativeTurnParticipation(lease);return toContent2({text:`Workflow turn participation is active until ${new Date(lease.expiresAt).toISOString()} on manager ${lease.managerInstanceId}. Renew before expiry to keep receiving turns.`})}catch(e){return refuse2(`Couldn't authorize workflow turn participation: ${errorText(e)}`)}});server.registerTool("cotal_wait",{title:"Cotal: wait for a message",annotations:gatewayAnnotations("cotal_wait"),description:`Wait for a message to this connection, and return it as cotal_inbox would. It returns at once when one is already waiting, and otherwise as soon as one arrives, or after at most ${waitSeconds} seconds with none. Call it again to keep listening. Direct messages, role requests and @mentions always end the wait; other channel traffic ends it only in open attention (cotal_status sets attention).`,inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID,seconds:external_exports.number().int().min(1).max(waitSeconds).optional().describe(`The longest to wait, in seconds. Defaults to ${waitSeconds}, the most allowed.`)})},async({connection_id,seconds},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const c=await host.find(account,connection_id);if(!c)return refuse2(CONNECTION_REQUIRED);const inbox=cotalToolSpecs(c.config,source,void 0,toolsOf(c)).find(s=>s.name==="cotal_inbox");if(!inbox)return refuse2("cotal_wait is not available on this connection.");const limit=seconds??waitSeconds;holding.set(c.agent,(holding.get(c.agent)??0)+1);let woke;try{woke=await waitForWake(c.agent,limit*1e3,extra.signal)}finally{holding.set(c.agent,(holding.get(c.agent)??1)-1)}if(c.agent.stopping)return refuse2(CONNECTION_REQUIRED);if(!woke){return toContent2({text:`No new messages in ${limit} second${limit===1?"":"s"}. Call cotal_wait again to keep listening.`})}signalled.delete(c.agent);try{return toContent2(await runFor(inbox,c,{},extra.signal))}catch(e){return refuse2(errorText(e))}});for(const spec of cotalToolSpecs(ADVERTISED,source,void 0,offered)){const channel=spec.name==="cotal_send"?spec.schema.shape.channel:void 0;const shape=channel?spec.schema.extend({channel:channel.describe(SEND_CHANNEL)}):spec.schema;server.registerTool(spec.name,{title:spec.title,annotations:gatewayAnnotations(spec.name),description:`${spec.description} Requires this conversation's connection_id from cotal_connect.`,inputSchema:shape.extend({connection_id:CONNECTION_ID})},async(args,extra)=>{const{connection_id,...rest}=args;let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const c=await host.find(account,connection_id);if(!c)return refuse2(CONNECTION_REQUIRED);const own=cotalToolSpecs(c.config,source,void 0,toolsOf(c)).find(s=>s.name===spec.name);if(!own)return refuse2(`${spec.name} is not available on this connection.`);let result;if(spec.name==="cotal_inbox")signalled.delete(c.agent);try{result=toContent2(await runFor(own,c,rest,extra.signal))}catch(e){result=refuse2(errorText(e))}const notice=spec.name==="cotal_inbox"||wake?.inboxNotice?.(c)===false?void 0:waitingNotice(c.agent);return notice?{...result,content:[...result.content,notice]}:result})}}var GATEWAY_LISTENING="Messages reach you only when you call a tool: to listen, call cotal_wait, which returns as soon as a message arrives. When the person asks you to stay on Cotal or keep listening, call cotal_wait again each time it returns and handle each message as it arrives, until they ask you to stop.";var GATEWAY_CONNECTING="Cotal connects this conversation to the person's Cotal space after they approve its permissions. Call cotal_connect with a short name. If approval is pending, show the person its link and wait for their decision; do not approve for them or poll. Then resume the same request as directed. Only a successful connection returns connection_id, required on every other cotal tool call. Each conversation needs its own connection. Never reuse another conversation's connection_id or approval_id.";var GATEWAY_INSTRUCTIONS=`${GATEWAY_CONNECTING} ${GATEWAY_LISTENING}`;async function serveGatewayStdio(host,o={}){const server=new McpServer({name:"cotal",version:DOCS_VERSION},{instructions:o.instructions??GATEWAY_INSTRUCTIONS});registerCotalGatewayTools(server,host,o.source,{...o.connectContext?{connectContext:true}:{},...o.tools?{tools:o.tools}:{},...o.selection?{selection:true}:{},...o.space?{space:true}:{},...o.approvalResume?{approvalResume:true}:{},...o.waitSeconds===void 0?{}:{waitSeconds:o.waitSeconds},...o.wake?{wake:o.wake}:{}});await server.connect(new StdioServerTransport(o.input,o.output));return{close:()=>server.close()}}var import_node_os6=require("node:os");var import_node_path14=require("node:path");var import_node_crypto19=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path9=require("node:path");var SEAT_PROJECT="seat";var FORK_RECORD="cotal-fork.json";function titleOf(path){let title;for(const line of(0,import_node_fs12.readFileSync)(path,"utf8").split("\n")){try{const entry=JSON.parse(line);if(entry.type==="custom-title"&&typeof entry.customTitle==="string")title=entry.customTitle}catch{}}return title}function sha256(path){return(0,import_node_crypto19.createHash)("sha256").update((0,import_node_fs12.readFileSync)(path)).digest("hex")}function carriedForkRecord(home){return(0,import_node_path9.join)(home,FORK_RECORD)}function recordCarriedFork(env,ev){const source=env.COTAL_CLAUDE_CARRIED;if(!source||!env.CLAUDE_CONFIG_DIR||ev.source!=="fork")return;const project=(0,import_node_path9.join)(env.CLAUDE_CONFIG_DIR,"projects",SEAT_PROJECT);if(typeof ev.session_id!=="string"||ev.session_id===source||ev.transcript_path!==(0,import_node_path9.join)(project,`${ev.session_id}.jsonl`))return;const transcript=(0,import_node_path9.join)(project,`${source}.jsonl`);const title=titleOf(transcript);try{(0,import_node_fs12.writeFileSync)(carriedForkRecord(env.CLAUDE_CONFIG_DIR),JSON.stringify({source,...title?{title}:{},transcriptSha256:sha256(transcript)}),{mode:384,flag:"wx"})}catch(e){if(e.code!=="EEXIST")throw e}}function stopFailure(ev){if(ev.hook_event_name!=="StopFailure")return void 0;const code=typeof ev.error==="string"&&ev.error?ev.error:void 0;const detail=typeof ev.error_details==="string"?ev.error_details.trim():"";return{message:detail||`claude turn ended on ${code??"an unreported error"}`,...code?{code}:{}}}var CLAUDE_FAILURE_CONDITIONS={rate_limit:"rate_limit",overloaded:"overloaded",authentication_failed:"auth",oauth_org_not_allowed:"auth",cloud_credential_error:"auth",account_on_hold:"billing",billing_error:"billing",invalid_request:"request",model_not_found:"model",server_error:"server",max_output_tokens:"context",unknown:"failed"};function failureCondition(ev){if(ev.hook_event_name!=="StopFailure")return void 0;const source=typeof ev.error==="string"&&ev.error?ev.error:void 0;const message=typeof ev.error_details==="string"&&ev.error_details.trim()?ev.error_details.trim():void 0;return{code:source===void 0?"failed":CLAUDE_FAILURE_CONDITIONS[source]??"failed",...source?{source}:{},...message?{message}:{},since:Date.now()}}var REPEAT_NOTE="(A previous delivery of one or more of these was not confirmed, so they may be a repeat.)";var REPEAT_LABEL_CAP=512;var HOOK_CONTEXT_CHARS=9e3;var WAITING_NOTE_RESERVE=160;function createClaudeHandle(deps={}){const events=()=>deps.events?.();let adoptedTranscript;let deferredFlush;let deferredClose;const adoptEvents=(path,source)=>{const holder=events();if(!holder)return;holder.adopt(path,source);if(typeof path!=="string"||path.length===0)return;adoptedTranscript??=path;if(deferredFlush){holder.flush(deferredFlush.path);deferredFlush=void 0}if(deferredClose){holder.closeRun(deferredClose.timestamp,deferredClose.error);deferredClose=void 0}};const flushEvents=path=>{const holder=events();if(!holder)return;if(adoptedTranscript===void 0){deferredFlush??={path};return}holder.flush(path)};const closeEvents=(timestamp,error51)=>{const holder=events();if(!holder)return Promise.resolve();if(adoptedTranscript===void 0){deferredClose??={timestamp,...error51?{error:error51}:{}};return Promise.resolve()}return holder.closeRun(timestamp,error51)};let pendingTool;let turnOpen=false;let cardOwed=false;const orientation=async()=>{const card=await deps.orientation?.();cardOwed=deps.orientation!==void 0&&card===void 0;return card};let promptOpen=false;const inFlight=new WeakMap;const awaitingVerdict=new Map;const sealAwaiting=()=>{for(const[id2,agent]of awaitingVerdict)agent.releaseTurns([id2]);awaitingVerdict.clear()};const unconfirmed=new Set;let lastDelivery;const markUnconfirmed=ids=>{if(unconfirmed.size+ids.length<=REPEAT_LABEL_CAP)for(const id2 of ids)unconfirmed.add(id2);else unconfirmed.clear()};const safeStatus=async(agent,status2,activity)=>{try{await agent.setStatus(status2,activity)}catch{}};const safeCondition=async(agent,condition)=>{try{await agent.setCondition(condition)}catch{}};const surfaceAutomatic=(agent,ev,reserved=0)=>{if(deps.delivery===false)return void 0;const pending=agent.peekInbox("automatic");if(!pending.length)return void 0;const budget=HOOK_CONTEXT_CHARS-reserved-WAITING_NOTE_RESERVE-REPEAT_NOTE.length-1;const items=[];for(const item of pending){const candidate2=formatInjection([...items,item]);if(candidate2&&candidate2.length<=budget)items.push(item)}const remaining=pending.length-items.length;const waiting=remaining?`${remaining} Cotal message${remaining===1?" is":"s are"} still waiting. Read with cotal_inbox; messages too large for a hook remain there.`:void 0;const body=formatInjection(items);if(!body)return waiting!==void 0&&waiting.length<=HOOK_CONTEXT_CHARS-reserved?waiting:void 0;const ids=items.map(i=>i.recvKey);if(!agent.holdInFlight(ids))return void 0;inFlight.set(ev,{ids,agent});deps.surfaced?.(items);const delivered=ids.some(id2=>unconfirmed.has(id2))?`${REPEAT_NOTE}
|
|
184
|
+
After they approve, retry cotal_connect with name ${JSON.stringify(candidate2)}${resume} and the same requested permissions. Do not poll or start another request while waiting.`;const structuredContent={v:1,status:"pending",name:candidate2,requestId:e.pending.requestId,approval:e.pending.approval,proposed:e.pending.proposed,message};return{content:[{type:"text",text:message},{type:"text",text:JSON.stringify(structuredContent)}],structuredContent}}if(e instanceof NameTaken){if(approvalId)return refuse2("The approved name is no longer available. Nothing was connected; a different name requires a new permission approval.");continue}return refuse2(`cotal_connect failed for ${JSON.stringify(candidate2)}: ${errorText(e)}`)}}return refuse2(`cotal_connect: ${JSON.stringify(name)} and its next ${GATEWAY_NAME_ATTEMPTS-1} variants are all taken. Choose another name.`)});server.registerTool("cotal_disconnect",{title:"Cotal: disconnect this conversation",annotations:gatewayAnnotations("cotal_disconnect"),description:"Leave the mesh for this conversation's connection. Other conversations stay connected.",inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID})},async({connection_id},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}return await host.close(account,connection_id)?toContent2({text:`Disconnected ${connection_id}.`}):refuse2(CONNECTION_REQUIRED)});if(options.tools?.has("cotal_turn_participate")&&host.participate)server.registerTool("cotal_turn_participate",{title:"Cotal: participate in workflow turns",annotations:gatewayAnnotations("cotal_turn_participate"),description:"Opt this user-owned native personal connection into workflow turn participation, or renew its finite lease. The lease is self-only and grants no process stop or attach custody.",inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID})},async({connection_id},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const connection=await host.find(account,connection_id);if(!connection)return refuse2(CONNECTION_REQUIRED);if(!connection.tools?.has("cotal_turn_participate"))return refuse2("cotal_turn_participate is not available on this connection.");try{const lease=await host.participate(account,connection);connection.agent.authorizeNativeTurnParticipation(lease);return toContent2({text:`Workflow turn participation is active until ${new Date(lease.expiresAt).toISOString()} on manager ${lease.managerInstanceId}. Renew before expiry to keep receiving turns.`})}catch(e){return refuse2(`Couldn't authorize workflow turn participation: ${errorText(e)}`)}});server.registerTool("cotal_wait",{title:"Cotal: wait for a message",annotations:gatewayAnnotations("cotal_wait"),description:`Wait for a message to this connection, and return it as cotal_inbox would. It returns at once when one is already waiting, and otherwise as soon as one arrives, or after at most ${waitSeconds} seconds with none. Call it again to keep listening. Direct messages, role requests and @mentions always end the wait; other channel traffic ends it only in open attention (cotal_status sets attention).`,inputSchema:external_exports.strictObject({connection_id:CONNECTION_ID,seconds:external_exports.number().int().min(1).max(waitSeconds).optional().describe(`The longest to wait, in seconds. Defaults to ${waitSeconds}, the most allowed.`)})},async({connection_id,seconds},extra)=>{let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const c=await host.find(account,connection_id);if(!c)return refuse2(CONNECTION_REQUIRED);const inbox=cotalToolSpecs(c.config,source,void 0,toolsOf(c)).find(s=>s.name==="cotal_inbox");if(!inbox)return refuse2("cotal_wait is not available on this connection.");const limit=seconds??waitSeconds;holding.set(c.agent,(holding.get(c.agent)??0)+1);let woke;try{woke=await waitForWake(c.agent,limit*1e3,extra.signal)}finally{holding.set(c.agent,(holding.get(c.agent)??1)-1)}if(c.agent.stopping)return refuse2(CONNECTION_REQUIRED);if(!woke){return toContent2({text:`No new messages in ${limit} second${limit===1?"":"s"}. Call cotal_wait again to keep listening.`})}signalled.delete(c.agent);try{return toContent2(await runFor(inbox,c,{},extra.signal))}catch(e){return refuse2(errorText(e))}});for(const spec of cotalToolSpecs(ADVERTISED,source,void 0,offered)){const channel=spec.name==="cotal_send"?spec.schema.shape.channel:void 0;const shape=channel?spec.schema.extend({channel:channel.describe(SEND_CHANNEL)}):spec.schema;server.registerTool(spec.name,{title:spec.title,annotations:gatewayAnnotations(spec.name),description:`${spec.description} Requires this conversation's connection_id from cotal_connect.`,inputSchema:shape.extend({connection_id:CONNECTION_ID})},async(args,extra)=>{const{connection_id,...rest}=args;let account;try{account=host.account(extra.authInfo)}catch(e){return refuse2(`not authenticated: ${errorText(e)}`)}const c=await host.find(account,connection_id);if(!c)return refuse2(CONNECTION_REQUIRED);const own=cotalToolSpecs(c.config,source,void 0,toolsOf(c)).find(s=>s.name===spec.name);if(!own)return refuse2(`${spec.name} is not available on this connection.`);let result;if(spec.name==="cotal_inbox")signalled.delete(c.agent);try{result=toContent2(await runFor(own,c,rest,extra.signal))}catch(e){result=refuse2(errorText(e))}const notice=spec.name==="cotal_inbox"||wake?.inboxNotice?.(c)===false?void 0:waitingNotice(c.agent);return notice?{...result,content:[...result.content,notice]}:result})}}var GATEWAY_LISTENING="Messages reach you only when you call a tool: to listen, call cotal_wait, which returns as soon as a message arrives. When the person asks you to stay on Cotal or keep listening, call cotal_wait again each time it returns and handle each message as it arrives, until they ask you to stop.";var GATEWAY_CONNECTING="Cotal connects this conversation to the person's Cotal space after they approve its permissions. Call cotal_connect with a short name. If approval is pending, show the person its link and wait for their decision; do not approve for them or poll. Then resume the same request as directed. Only a successful connection returns connection_id, required on every other cotal tool call. Each conversation needs its own connection. Never reuse another conversation's connection_id or approval_id.";var GATEWAY_INSTRUCTIONS=`${GATEWAY_CONNECTING} ${GATEWAY_LISTENING}`;async function serveGatewayStdio(host,o={}){const server=new McpServer({name:"cotal",version:DOCS_VERSION},{instructions:o.instructions??GATEWAY_INSTRUCTIONS});registerCotalGatewayTools(server,host,o.source,{...o.connectContext?{connectContext:true}:{},...o.tools?{tools:o.tools}:{},...o.selection?{selection:true}:{},...o.space?{space:true}:{},...o.approvalResume?{approvalResume:true}:{},...o.waitSeconds===void 0?{}:{waitSeconds:o.waitSeconds},...o.wake?{wake:o.wake}:{}});await server.connect(new StdioServerTransport(o.input,o.output));return{close:()=>server.close()}}var import_node_os6=require("node:os");var import_node_path14=require("node:path");var import_node_crypto19=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path9=require("node:path");var SEAT_PROJECT="seat";var FORK_RECORD="cotal-fork.json";function titleOf(path){let title;for(const line of(0,import_node_fs12.readFileSync)(path,"utf8").split("\n")){try{const entry=JSON.parse(line);if(entry.type==="custom-title"&&typeof entry.customTitle==="string")title=entry.customTitle}catch{}}return title}function sha256(path){return(0,import_node_crypto19.createHash)("sha256").update((0,import_node_fs12.readFileSync)(path)).digest("hex")}function carriedForkRecord(home){return(0,import_node_path9.join)(home,FORK_RECORD)}function recordCarriedFork(env,ev){const source=env.COTAL_CLAUDE_CARRIED;if(!source||!env.CLAUDE_CONFIG_DIR||ev.source!=="fork")return;const project=(0,import_node_path9.join)(env.CLAUDE_CONFIG_DIR,"projects",SEAT_PROJECT);if(typeof ev.session_id!=="string"||ev.session_id===source||ev.transcript_path!==(0,import_node_path9.join)(project,`${ev.session_id}.jsonl`))return;const transcript=(0,import_node_path9.join)(project,`${source}.jsonl`);const title=titleOf(transcript);try{(0,import_node_fs12.writeFileSync)(carriedForkRecord(env.CLAUDE_CONFIG_DIR),JSON.stringify({source,...title?{title}:{},transcriptSha256:sha256(transcript)}),{mode:384,flag:"wx"})}catch(e){if(e.code!=="EEXIST")throw e}}function stopFailure(ev){if(ev.hook_event_name!=="StopFailure")return void 0;const code=typeof ev.error==="string"&&ev.error?ev.error:void 0;const detail=typeof ev.error_details==="string"?ev.error_details.trim():"";return{message:detail||`claude turn ended on ${code??"an unreported error"}`,...code?{code}:{}}}var CLAUDE_FAILURE_CONDITIONS={rate_limit:"rate_limit",overloaded:"overloaded",authentication_failed:"auth",oauth_org_not_allowed:"auth",cloud_credential_error:"auth",account_on_hold:"billing",billing_error:"billing",invalid_request:"request",model_not_found:"model",server_error:"server",max_output_tokens:"context",unknown:"failed"};function failureCondition(ev){if(ev.hook_event_name!=="StopFailure")return void 0;const source=typeof ev.error==="string"&&ev.error?ev.error:void 0;const message=typeof ev.error_details==="string"&&ev.error_details.trim()?ev.error_details.trim():void 0;return{code:source===void 0?"failed":CLAUDE_FAILURE_CONDITIONS[source]??"failed",...source?{source}:{},...message?{message}:{},since:Date.now()}}var REPEAT_NOTE="(A previous delivery of one or more of these was not confirmed, so they may be a repeat.)";var REPEAT_LABEL_CAP=512;var HOOK_CONTEXT_CHARS=9e3;var WAITING_NOTE_RESERVE=160;function createClaudeHandle(deps={}){const events=()=>deps.events?.();let adoptedTranscript;let deferredFlush;let deferredClose;const adoptEvents=(path,source)=>{const holder=events();if(!holder)return;holder.adopt(path,source);if(typeof path!=="string"||path.length===0)return;adoptedTranscript??=path;if(deferredFlush){holder.flush(deferredFlush.path);deferredFlush=void 0}if(deferredClose){holder.closeRun(deferredClose.timestamp,deferredClose.error);deferredClose=void 0}};const flushEvents=path=>{const holder=events();if(!holder)return;if(adoptedTranscript===void 0){deferredFlush??={path};return}holder.flush(path)};const closeEvents=(timestamp,error51)=>{const holder=events();if(!holder)return Promise.resolve();if(adoptedTranscript===void 0){deferredClose??={timestamp,...error51?{error:error51}:{}};return Promise.resolve()}return holder.closeRun(timestamp,error51)};let pendingTool;let turnOpen=false;let cardOwed=false;const orientation=async()=>{const card=await deps.orientation?.();cardOwed=deps.orientation!==void 0&&card===void 0;return card};let promptOpen=false;const inFlight=new WeakMap;const awaitingVerdict=new Map;let terminals=0;const sealAwaiting=()=>{terminals++;for(const[id2,agent]of awaitingVerdict)agent.releaseTurns([id2]);awaitingVerdict.clear()};const unconfirmed=new Set;let lastDelivery;const markUnconfirmed=ids=>{if(unconfirmed.size+ids.length<=REPEAT_LABEL_CAP)for(const id2 of ids)unconfirmed.add(id2);else unconfirmed.clear()};const safeStatus=async(agent,status2,activity)=>{try{await agent.setStatus(status2,activity)}catch{}};const safeCondition=async(agent,condition)=>{try{await agent.setCondition(condition)}catch{}};const surfaceAutomatic=(agent,ev,reserved=0)=>{if(deps.delivery===false)return void 0;const pending=agent.peekInbox("automatic");if(!pending.length)return void 0;const budget=HOOK_CONTEXT_CHARS-reserved-WAITING_NOTE_RESERVE-REPEAT_NOTE.length-1;const items=[];for(const item of pending){const candidate2=formatInjection([...items,item]);if(candidate2&&candidate2.length<=budget)items.push(item)}const remaining=pending.length-items.length;const waiting=remaining?`${remaining} Cotal message${remaining===1?" is":"s are"} still waiting. Read with cotal_inbox; messages too large for a hook remain there.`:void 0;const body=formatInjection(items);if(!body)return waiting!==void 0&&waiting.length<=HOOK_CONTEXT_CHARS-reserved?waiting:void 0;const ids=items.map(i=>i.recvKey);if(!agent.holdInFlight(ids))return void 0;inFlight.set(ev,{ids,agent});deps.surfaced?.(items);const delivered=ids.some(id2=>unconfirmed.has(id2))?`${REPEAT_NOTE}
|
|
185
185
|
${body}`:body;return waiting?`${delivered}
|
|
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=(agent,ev,event,extras)=>{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 messages=surfaceAutomatic(agent,ev,join10([...kept,peek.text]).length+2);const text2=join10([...kept,messages,peek.text]);if(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,messages])||void 0)}const reserved=extras.reduce((n,x)=>n+(x?.length??0)+2,0)+(peek&&!peek.once?peek.text.length+2:0);const parts=[...extras,surfaceAutomatic(agent,ev,reserved),peek?.once?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();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 injectFrame(agent,ev,event,[card,agent.channelBriefing()])}case"UserPromptSubmit":{turnOpen=true;pendingTool=void 0;promptOpen=false;flushEvents(ev.transcript_path);await safeStatus(agent,"working");const card=cardOwed?await orientation():void 0;return injectFrame(agent,ev,event,[card])}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.peekInbox("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.peekInbox("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}}:{}}))});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}
|
|
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=(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 messages=surfaceAutomatic(agent,ev,join10([...kept,peek.text]).length+2);const text2=join10([...kept,messages,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,messages])||void 0)}const reserved=extras.reduce((n,x)=>n+(x?.length??0)+2,0)+(peek&&!peek.once?peek.text.length+2:0);const parts=[...extras,surfaceAutomatic(agent,ev,reserved),peek?.once?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 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 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.peekInbox("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.peekInbox("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}}:{}}))});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
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
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&¤t.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_fs13=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_fs13.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_fs14=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}.
|
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.135.
|
|
4
|
+
"version": "0.135.5",
|
|
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.135.
|
|
29
|
-
"@cotal-ai/core": "0.135.
|
|
28
|
+
"@cotal-ai/connector-core": "0.135.5",
|
|
29
|
+
"@cotal-ai/core": "0.135.5",
|
|
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",
|