@cotal-ai/connector-opencode 0.155.2 → 0.156.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agui-map2.d.ts +35 -0
- package/dist/agui-map2.d.ts.map +1 -0
- package/dist/agui-source2.d.ts +110 -0
- package/dist/agui-source2.d.ts.map +1 -0
- package/dist/plugin/docs-bundle.bin +0 -0
- package/dist/plugin/docs-index.bin +0 -0
- package/dist/plugin/index.js +4 -4
- package/dist/plugin2.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps OpenCode 2.x session records to AG-UI events, with the same arms and the same withholding as
|
|
3
|
+
* the 1.x mapper (`agui-map.ts`). The source hands over only settled records, in session order, so
|
|
4
|
+
* each record is mapped once, whole.
|
|
5
|
+
*
|
|
6
|
+
* - `text` -> `TEXT_MESSAGE_*`, assistant only
|
|
7
|
+
* - `reasoning` -> `REASONING_*`, off by default
|
|
8
|
+
* - `tool` -> `TOOL_CALL_START` / `ARGS` / `END` / `RESULT`, `toolCallId` is the native call id
|
|
9
|
+
* - `user` -> nothing of its own: it closes the open run, because a new turn began. Its text is
|
|
10
|
+
* never published, for the 1.x reason: a peer batch is prepended into the person's own prompt, so
|
|
11
|
+
* the record has no boundary between the two authors to filter on.
|
|
12
|
+
* - `idle` -> closes the open run with the outcome the server recorded: `failed` is `RUN_ERROR`,
|
|
13
|
+
* and `succeeded` and `interrupted` are `RUN_FINISHED` with no outcome, which says the run ended
|
|
14
|
+
* without claiming it succeeded. A stop someone pressed is not a failure.
|
|
15
|
+
* - every other message kind -> nothing, and it closes nothing.
|
|
16
|
+
*
|
|
17
|
+
* A turn that ends before its first element opened no run, so its `idle` has nothing to close and
|
|
18
|
+
* publishes nothing, as on 1.x. Tool arguments and results are mapped here and dropped by the
|
|
19
|
+
* emitter's egress policy before anything is written, the one place that decides what leaves.
|
|
20
|
+
*/
|
|
21
|
+
import { type RecordMapper } from "@cotal-ai/connector-core";
|
|
22
|
+
import type { OpenCode2Record } from "./agui-source2.js";
|
|
23
|
+
export interface OpenCode2MapperOptions {
|
|
24
|
+
/** The native session id: the `threadId` on every event. */
|
|
25
|
+
threadId: string;
|
|
26
|
+
/** Mints a `runId`. Connector-minted, so every `RUN_STARTED` carries `runIdSource: "connector"`. */
|
|
27
|
+
mintRunId: () => string;
|
|
28
|
+
/** The run the write-ahead log has open when this mapper is built, so a re-established plane
|
|
29
|
+
* attributes the next records to it. */
|
|
30
|
+
resumeRunId?: string;
|
|
31
|
+
/** Emit `REASONING_*` for reasoning elements. Off by default. */
|
|
32
|
+
reasoning?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export declare function createOpenCode2Mapper(opts: OpenCode2MapperOptions): RecordMapper<OpenCode2Record>;
|
|
35
|
+
//# sourceMappingURL=agui-map2.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agui-map2.d.ts","sourceRoot":"","sources":["../src/agui-map2.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAEL,KAAK,YAAY,EAclB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAoB,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAE3E,MAAM,WAAW,sBAAsB;IACrC,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB,oGAAoG;IACpG,SAAS,EAAE,MAAM,MAAM,CAAC;IACxB;6CACyC;IACzC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iEAAiE;IACjE,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAcD,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,YAAY,CAAC,eAAe,CAAC,CA4DjG"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A {@link DurableSource} over an OpenCode 2.x session, read through `GET /api/session/:id/message`,
|
|
3
|
+
* the server's supported message list. The shapes below were measured against OpenCode 2.2.5; the
|
|
4
|
+
* redacted captures are `smoke/fixtures/opencode2-sessions.json`.
|
|
5
|
+
*
|
|
6
|
+
* **What 2.x writes, and why it decides the record and the settle rule.** Each model step is one
|
|
7
|
+
* `assistant` message whose `content` holds its elements in the order they started: `text` and
|
|
8
|
+
* `reasoning` carry no id and no end mark of their own, and a `tool` carries its call id and a state
|
|
9
|
+
* that moves from `streaming` to `running` to `completed` or `error`. Streamed deltas never reach
|
|
10
|
+
* the list: a text element holds `""` until it ends and then its whole text. The message gets
|
|
11
|
+
* `time.streamed` once the step's output has ended and `time.completed` once its tools have too.
|
|
12
|
+
* Each turn closes with an `idle` message carrying the turn's `outcome`, so the end of a turn and how
|
|
13
|
+
* it ended are records in order. A prompt sent while a turn runs waits in the session inbox and
|
|
14
|
+
* enters the list only when it is delivered at a step boundary.
|
|
15
|
+
*
|
|
16
|
+
* So a record is one element, keyed by its message id and its position, and the cursor is that pair
|
|
17
|
+
* compared as an order. Message ids sort by creation (measured on every captured session). A message
|
|
18
|
+
* with no element is one record of its own: a user prompt, a turn end, and a step that has not
|
|
19
|
+
* written anything yet, which must hold the read like any unsettled element does.
|
|
20
|
+
*/
|
|
21
|
+
import type { DurableSource, SourceRead } from "@cotal-ai/connector-core";
|
|
22
|
+
/** The fields of a 2.x message this source and its mapper read. */
|
|
23
|
+
export interface OpenCode2Message {
|
|
24
|
+
id: string;
|
|
25
|
+
/** `assistant`, `user`, `idle`, `synthetic`, `system`, `skill`, `shell`, `compaction`, or a
|
|
26
|
+
* `*-switched` setting change. */
|
|
27
|
+
type: string;
|
|
28
|
+
time: {
|
|
29
|
+
created: number;
|
|
30
|
+
streamed?: number;
|
|
31
|
+
completed?: number;
|
|
32
|
+
};
|
|
33
|
+
/** An assistant message's elements, in the order they started. */
|
|
34
|
+
content?: OpenCode2Element[];
|
|
35
|
+
/** How the turn an `idle` message closes ended. */
|
|
36
|
+
outcome?: "succeeded" | "failed" | "interrupted";
|
|
37
|
+
error?: {
|
|
38
|
+
type?: string;
|
|
39
|
+
message?: string;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export type OpenCode2Element = {
|
|
43
|
+
type: "text";
|
|
44
|
+
text: string;
|
|
45
|
+
} | {
|
|
46
|
+
type: "reasoning";
|
|
47
|
+
text: string;
|
|
48
|
+
time?: {
|
|
49
|
+
created: number;
|
|
50
|
+
completed?: number;
|
|
51
|
+
};
|
|
52
|
+
} | {
|
|
53
|
+
type: "tool";
|
|
54
|
+
id: string;
|
|
55
|
+
name: string;
|
|
56
|
+
state: {
|
|
57
|
+
status: "streaming" | "running" | "completed" | "error";
|
|
58
|
+
input?: unknown;
|
|
59
|
+
content?: Array<{
|
|
60
|
+
type: string;
|
|
61
|
+
text?: string;
|
|
62
|
+
}>;
|
|
63
|
+
error?: {
|
|
64
|
+
type?: string;
|
|
65
|
+
message?: string;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
time: {
|
|
69
|
+
created: number;
|
|
70
|
+
ran?: number;
|
|
71
|
+
completed?: number;
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
/** One page of the message list, newest first, with the keyset cursor of the page after it. */
|
|
75
|
+
export interface OpenCode2MessagePage {
|
|
76
|
+
data: OpenCode2Message[];
|
|
77
|
+
cursor: {
|
|
78
|
+
next?: string | null;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Fetches the newest page, or the page after the one whose `cursor.next` is passed. Injected so the
|
|
82
|
+
* source can be read without a server. */
|
|
83
|
+
export type FetchMessagePage = (next: string | undefined) => Promise<OpenCode2MessagePage>;
|
|
84
|
+
/** One element of an assistant message at its position, or a message with no element at `-1`. */
|
|
85
|
+
export interface OpenCode2Record {
|
|
86
|
+
message: OpenCode2Message;
|
|
87
|
+
index: number;
|
|
88
|
+
element?: OpenCode2Element;
|
|
89
|
+
}
|
|
90
|
+
export interface OpenCode2SessionSourceOptions {
|
|
91
|
+
page: FetchMessagePage;
|
|
92
|
+
/** Called once per cursor whose record is no longer in the session, which is what a revert does.
|
|
93
|
+
* The read stays correct without it, because the cursor is compared as an order. */
|
|
94
|
+
onVanished?: (cursor: string) => void;
|
|
95
|
+
}
|
|
96
|
+
export declare class OpenCode2SessionSource implements DurableSource<OpenCode2Record> {
|
|
97
|
+
readonly kind = "opencode2-session";
|
|
98
|
+
private readonly page;
|
|
99
|
+
private readonly onVanished?;
|
|
100
|
+
private reportedVanished?;
|
|
101
|
+
constructor(opts: OpenCode2SessionSourceOptions);
|
|
102
|
+
/** Every message at or after `from`, or the whole session when `from` is absent. Pages run newest
|
|
103
|
+
* first, so the read stops at the first page that reaches back to `from`. */
|
|
104
|
+
private messages;
|
|
105
|
+
/** The records in session order, each with whether a later `idle` has ended its turn. */
|
|
106
|
+
private ordered;
|
|
107
|
+
end(): Promise<string>;
|
|
108
|
+
read(cursor: string | undefined): Promise<SourceRead<OpenCode2Record>>;
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=agui-source2.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agui-source2.d.ts","sourceRoot":"","sources":["../src/agui-source2.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAE1E,mEAAmE;AACnE,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX;uCACmC;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACjE,kEAAkE;IAClE,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC7B,mDAAmD;IACnD,OAAO,CAAC,EAAE,WAAW,GAAG,QAAQ,GAAG,aAAa,CAAC;IACjD,KAAK,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC7C;AAED,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACnF;IACE,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE;QACL,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,WAAW,GAAG,OAAO,CAAC;QACxD,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,OAAO,CAAC,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QACjD,KAAK,CAAC,EAAE;YAAE,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;KAC7C,CAAC;IACF,IAAI,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC7D,CAAC;AAEN,+FAA+F;AAC/F,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,gBAAgB,EAAE,CAAC;IACzB,MAAM,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;CAClC;AAED;2CAC2C;AAC3C,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAE3F,iGAAiG;AACjG,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,gBAAgB,CAAC;CAC5B;AAiCD,MAAM,WAAW,6BAA6B;IAC5C,IAAI,EAAE,gBAAgB,CAAC;IACvB;yFACqF;IACrF,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CACvC;AAED,qBAAa,sBAAuB,YAAW,aAAa,CAAC,eAAe,CAAC;IAC3E,QAAQ,CAAC,IAAI,uBAAuB;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAmB;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAA2B;IACvD,OAAO,CAAC,gBAAgB,CAAC,CAAS;gBAEtB,IAAI,EAAE,6BAA6B;IAK/C;kFAC8E;YAChE,QAAQ;IAYtB,yFAAyF;YAC3E,OAAO;IAaf,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC;IAOtB,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC;CAoB7E"}
|
|
Binary file
|
|
Binary file
|
package/dist/plugin/index.js
CHANGED
|
@@ -130,7 +130,7 @@ ${tail}`)}if(history.length){blocks.push(`\u{1F4DA} Cotal \u2014 ${history.lengt
|
|
|
130
130
|
${history.map(format).join("\n")}
|
|
131
131
|
(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(resolve2=>{let settled=false;const done=ok3=>{if(settled)return;settled=true;resolve2(ok3)};sock.once("error",()=>done(false));sock.once("close",()=>done(false));if(!awaitHandoff){const stall=setTimeout(()=>done(false),LEGACY_WRITE_DEADLINE_MS);stall.unref?.();try{sock.end(JSON.stringify(reply)+"\n",(err3=>{clearTimeout(stall);done(!err3)}))}catch{clearTimeout(stall);done(false)}return}const deadline=setTimeout(()=>{sock.destroy();done(false)},HANDOFF_DEADLINE_MS);deadline.unref?.();let receipt2="";sock.on("data",d=>{receipt2+=d;if(!receipt2.includes("\n"))return;clearTimeout(deadline);try{sock.end()}catch{}done(true)});try{sock.write(JSON.stringify(reply)+"\n",err3=>{if(!err3)return;clearTimeout(deadline);done(false)})}catch{clearTimeout(deadline);done(false)}})}function startControlServer(agent,endpoint,handle,opts={}){const{path}=endpoint;const digest=createHash9("sha256").update(endpoint.token).digest();const server=createServer(sock=>{let buf="";let handled=false;sock.setEncoding("utf8");const deadline=setTimeout(()=>sock.destroy(),AUTH_DEADLINE_MS);deadline.unref?.();sock.on("close",()=>clearTimeout(deadline));sock.on("data",async d=>{if(handled)return;buf+=d;if(buf.length>MAX_FRAME_BYTES){sock.destroy();return}const nl=buf.indexOf("\n");if(nl<0)return;handled=true;clearTimeout(deadline);let frame={};try{frame=JSON.parse(buf.slice(0,nl)||"{}")}catch{}if(!tokenMatches(frame.token,digest)){sock.destroy();return}const op=frame.op;if(op==="shutdown"){try{sock.end(JSON.stringify({ok:true})+"\n")}catch{}opts.onShutdown?.();return}if(op==="session"){const sessionId=opts.onSession?.();try{sock.end(JSON.stringify(sessionId?{ok:true,sessionId}:{ok:false,error:"session not ready"})+"\n")}catch{}return}const ev=frame.event??{};const awaitHandoff=frame.handoff===true;const reply=await handle(agent,ev);const delivered=await writeReply(sock,reply,awaitHandoff);opts.onReply?.(ev,delivered,awaitHandoff)});sock.on("error",()=>{})});let bound=false;let retried=false;const emit=server.emit.bind(server);server.emit=(event,...args)=>{const error51=args[0];if(event!=="error"||bound||retried||process.platform==="win32"||path.startsWith("\0")||error51?.code!=="EADDRINUSE")return emit(event,...args);retried=true;let original;try{original=lstatSync5(path);if(!original.isSocket())return emit(event,...args)}catch(e){if(e.code!=="ENOENT")return emit(event,...args)}const probe=connect2(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=lstatSync5(path);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}unlinkSync4(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}
|
|
132
132
|
`);if(opts.fatalBind&&!bound)process.exit(1)});server.listen(path,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path}
|
|
133
|
-
`)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{execFileSync as execFileSync2}from"node:child_process";init_external();init_external();import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join7}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.155.2";function loadDocsMetadata(){return{"version":"0.155.2","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join7(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1206031||createHash10("sha256").update(packed).digest("hex")!=="376e02369e4c65816671be0250802a4fb078a8410811afcdbaae2a583d82ab00")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9323],[9323,31318],[31318,35715],[35715,40096],[40096,43618],[43618,50421],[50421,54525],[54525,63513],[63513,67665],[67665,72113],[72113,74397],[74397,78408],[78408,109576],[109576,125064],[125064,140537],[140537,158546],[158546,173825],[173825,188876],[188876,204359],[204359,226081],[226081,231811],[231811,241574],[241574,261751],[261751,266240],[266240,296492],[296492,306212],[306212,336746],[336746,354247],[354247,378135],[378135,408648],[408648,422793],[422793,424740],[424740,433616],[433616,450050],[450050,457822],[457822,461441],[461441,464822],[464822,468125],[468125,470354],[470354,473010],[473010,477735],[477735,479563],[479563,483122],[483122,494591],[494591,502656],[502656,506181],[506181,513454],[513454,518498],[518498,521405],[521405,531925],[531925,534902],[534902,542993],[542993,545983],[545983,550928],[550928,562554],[562554,574469],[574469,579361],[579361,586935],[586935,590284],[590284,593004],[593004,600262],[600262,603682],[603682,605892],[605892,609354],[609354,612771],[612771,613885],[613885,615634],[615634,619297],[619297,623938],[623938,630574],[630574,641084],[641084,654389],[654389,656226],[656226,669211],[669211,674598],[674598,678537],[678537,681046],[681046,686088],[686088,699995],[699995,706770],[706770,713364],[713364,714181],[714181,718490],[718490,724306],[724306,727684],[727684,731892],[731892,736714],[736714,741516],[741516,744938],[744938,748529],[748529,753694],[753694,757337],[757337,770563],[770563,773381],[773381,776064],[776064,778731],[778731,781222],[781222,785242],[785242,789942],[789942,792291],[792291,860693],[860693,863764],[863764,864957],[864957,871458],[871458,879754],[879754,890356],[890356,899167],[899167,904350],[904350,1161509],[1161509,1200819],[1200819,1206031]];var sourceLengths=[4844,4048,13310,87273,12190,10741,35598,17849,9941,78405,37758,10864,5079,9872,84938,41661,43505,51200,42364,43514,42263,60885,14399,25632,57992,10129,88229,26839,92244,49557,71462,93959,38982,8216,22172,44099,21106,8796,8035,7790,5277,6062,11949,4349,8347,30545,19884,8745,47165,12743,7133,27685,7140,21069,6860,12405,30020,31428,12022,18432,8355,6411,18823,7536,5100,8160,9930,2248,5412,9845,11102,16082,26828,34181,4227,35397,12378,9603,8201,13306,96391,16844,16096,1638,9825,15068,7818,10170,12034,11921,7511,9014,12695,8527,35301,6519,6405,6095,6007,9711,11730,5622,201752,6927,2473,15538,21211,27423,21160,12616,746009,111138,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readFileSync5(join7(import.meta.dirname,"docs-index.bin"));if(packed.length!==622109||createHash10("sha256").update(packed).digest("hex")!=="2259fc90c6723c8be0a9ee8c8a10f7478459b641b995870144b60ece2f0d6d3b")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p,source2)=>(pages.get(source2)??p).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
133
|
+
`)});return server}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{execFileSync as execFileSync2}from"node:child_process";init_external();init_external();import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join7}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.156.0";function loadDocsMetadata(){return{"version":"0.156.0","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join7(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1208752||createHash10("sha256").update(packed).digest("hex")!=="eca4a2a9db4b7dc7cacebdc48a192209cd6248636eec172e1c41702547440891")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9323],[9323,31318],[31318,35715],[35715,40096],[40096,43618],[43618,50421],[50421,54525],[54525,63513],[63513,67665],[67665,72113],[72113,74397],[74397,78408],[78408,109765],[109765,125253],[125253,140726],[140726,158735],[158735,174014],[174014,189065],[189065,204548],[204548,226270],[226270,232e3],[232e3,241763],[241763,262037],[262037,266526],[266526,297874],[297874,307594],[307594,338128],[338128,355629],[355629,379666],[379666,410179],[410179,424324],[424324,426271],[426271,435147],[435147,451581],[451581,459353],[459353,462972],[462972,466353],[466353,469656],[469656,471787],[471787,474443],[474443,479168],[479168,480973],[480973,484532],[484532,496001],[496001,504066],[504066,507591],[507591,514864],[514864,519908],[519908,522815],[522815,533335],[533335,536312],[536312,544403],[544403,547393],[547393,552338],[552338,563964],[563964,575879],[575879,580771],[580771,588345],[588345,591694],[591694,594643],[594643,601958],[601958,605378],[605378,607588],[607588,611050],[611050,614467],[614467,615581],[615581,617330],[617330,620993],[620993,625634],[625634,632270],[632270,642780],[642780,656085],[656085,657922],[657922,670907],[670907,676294],[676294,680233],[680233,682742],[682742,687784],[687784,701691],[701691,708466],[708466,715317],[715317,716134],[716134,720443],[720443,726259],[726259,729637],[729637,733845],[733845,738667],[738667,743469],[743469,746891],[746891,750482],[750482,755647],[755647,759290],[759290,772516],[772516,775334],[775334,778017],[778017,780684],[780684,783175],[783175,787195],[787195,791895],[791895,794244],[794244,862928],[862928,865999],[865999,867192],[867192,873693],[873693,882300],[882300,893078],[893078,901889],[901889,907072],[907072,1164231],[1164231,1203540],[1203540,1208752]];var sourceLengths=[4844,4048,13310,87273,12190,10741,35598,17849,9941,78405,37758,10864,5079,9872,85540,41661,43505,51200,42364,43514,42263,60885,14399,25632,58259,10129,91926,26839,92244,49557,71995,93959,38982,8216,22172,44099,21106,8796,8035,7790,4909,6062,11949,4291,8347,30545,19884,8745,47165,12743,7133,27685,7140,21069,6860,12405,30020,31428,12022,18432,8355,7031,19015,7536,5100,8160,9930,2248,5412,9845,11102,16082,26828,34181,4227,35397,12378,9603,8201,13306,96391,16844,16847,1638,9825,15068,7818,10170,12034,11921,7511,9014,12695,8527,35301,6519,6405,6095,6007,9711,11730,5622,202714,6927,2473,15538,21977,27911,21160,12616,746009,111139,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readFileSync5(join7(import.meta.dirname,"docs-index.bin"));if(packed.length!==623192||createHash10("sha256").update(packed).digest("hex")!=="8540cbac54a2d9d982151570afad1f5e22f4557bacb73067c3e1cf52236b99b4")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p,source2)=>(pages.get(source2)??p).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
134
134
|
${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}
|
|
135
135
|
|
|
136
136
|
${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}
|
|
@@ -173,13 +173,13 @@ ${carried}`:boot??carried;const items=text2?[]:await agent.takeChosen("automatic
|
|
|
173
173
|
|
|
174
174
|
${briefing(config2,"opencode")}`;if(!batch.surface(ids))return;if(turnPeek&&agent.claimTurns(turnPeek.goalIds)){turnIds=turnPeek.goalIds;parts.push({type:"text",text:turnPeek.text})}if(!text2&&ids.length===0&&turnIds.length===0){batch.abandon();return}busy=true;const endsAtSend=turnEndsSeen;await opencodeApi(`/session/${encodeURIComponent(id2)}/prompt_async`,{method:"POST",body:JSON.stringify(body)},1e4);if(turnIds.length&&(turnEndsSeen!==endsAtSend||sessionID!==id2))agent.releaseTurns(turnIds);if(turnIds.length)agent.commitSurfacedTurns(turnIds);submittedWake=carried;if(boot!==void 0)bootPrompt=void 0;if(carried!==void 0&&wakeSeq===carriedSeq)pendingWake=void 0;briefed=true;primed=true}catch(e){agent.releaseTurns(turnIds);busy=false;batch.abandon();log(`drive failed: ${e.message}`);scheduleErrorRetry()}finally{driving=false}}void(async()=>{if(bootPrompt===void 0)return;const id2=await sessionReady;while(!stopping&&!agent.connected)await new Promise(r=>setTimeout(r,100).unref?.());if(stopping||bootPrompt===void 0)return;if(!id2){log("initial prompt not submitted \u2014 this session was never created");bootPrompt=void 0;return}bootReady=true;await drive()})();const turnEnds=new Map;const turnEnded=async(session,close)=>{if(!close)return;if(session===void 0)return close;const settled=Promise.all([turnEnds.get(session),close]).then(()=>void 0);const barrier=settled.finally(()=>{if(turnEnds.get(session)===barrier)turnEnds.delete(session)});turnEnds.set(session,barrier);await barrier};async function injectIntoPrompt(output){if(driving)return;const textPart=output.parts?.find(p=>typeof p==="object"&&p!==null&&p.type==="text"&&typeof p.text==="string");if(!textPart)return;if(!batch.open)await agent.takeChosen("automatic",preview=>preview);if(driving)return;const prefix=batch.inject();if(prefix===void 0)return;textPart.text=`${prefix}
|
|
175
175
|
|
|
176
|
-
${textPart.text}`;if(batch.open)busy=true}function completeTurn(){if(!busy&&!batch.open)return;busy=false;if(batch.open)batch.ack();submittedWake=void 0;clearInterruptIntent();clearErrorRetry(true);if(workPending())void drive()}agent.on("incoming",item=>{if(busy)return;const automatic=agent.inboxScope(item.recvKey)==="automatic";const directed=item.kind!=="channel"||item.mentionsMe;if(automatic&&(directed||agent.attention==="open"))void drive()});agent.on("mention-wake",item=>{pendingWake=`\u{1F4E8} You were mentioned by ${fmtFrom(item)} on #${fmtChannel(item.channel)} \u2014 read it with cotal_inbox.`;wakeSeq+=1;void drive()});agent.on("wake",()=>{if(!busy)void drive()});const ours=id2=>{if(!id2)return!sessionID;if(!sessionID)adoptSession(id2,"first event");return id2===sessionID};const fence=intake2=>Object.fromEntries(Object.entries(intake2).map(([name,hook])=>[name,async(...args)=>stopping?void 0:await hook(...args)]));const fenceTools=tools=>Object.fromEntries(Object.entries(tools).map(([name,def2])=>[name,{...def2,execute:async(...args)=>stopping?`\u26A0 ${name} was not run: this seat is shutting down`:await track(def2.execute(...args))}]));const intake={event:async({event})=>{if(event.type==="permission.asked"){const p=event.properties;if(!p.sessionID||ours(p.sessionID))await safeStatus("waiting",p.title);return}switch(event.type){case"session.created":{if(event.properties.info.parentID)break;const created=event.properties.info.id;const swap=swapChain.then(async()=>{swapping=true;try{adoptSession(created,"top-level session create");const previous=events;if(previous&&previous.path!==void 0&&previous.path!==created){previous.flush(previous.path);previous.closeRun(Date.now());const drained=await settleWithin(previous.settled(),SWAP_SETTLE_MS,`drain of ${previous.path}`);log(`${SESSION_RETIRED} ${previous.path} superseded by ${created}; ${drained?"drained before release":"ABANDONED UNDRAINED"}`);const retired=previous.path;await settleWithin(previous.close(),SWAP_SETTLE_MS,`release of ${retired}`);await reapRetiredWal(retired,drained);events=newEventHolder()}eventsFor(created)?.adopt(created)}finally{swapping=false}if(workPending())void drive()});swapChain=swap.catch(()=>void 0);await swap;break}case"session.idle":{const idleSession=event.properties.sessionID;if(!ours(idleSession))return;noteTurnEnd();eventsFor(sessionID)?.flush(sessionID);await turnEnded(idleSession,eventsFor(sessionID)?.closeRun(Date.now()));await safeStatus("idle");completeTurn();break}case"session.status":{if(!ours(event.properties.sessionID))return;const s=event.properties.status;if(s.type==="busy"){busy=true;await safeStatus("working")}else if(s.type==="idle"){noteTurnEnd();await safeStatus("idle")}else if(s.type==="retry"){await safeStatus("working",`retrying: ${s.message}`)}break}case"session.error":if(event.properties.sessionID&&!ours(event.properties.sessionID))return;noteTurnEnd();if(!busy&&!batch.open)return;const interrupted=consumeInterruptIntent(event.properties.sessionID)||isMessageAbortedError(event.properties.error);const eventHolder=eventsFor(sessionID);eventHolder?.flush(sessionID);await turnEnded(sessionID,eventHolder?.closeRun(Date.now(),interrupted?void 0:runErrorOf(event.properties.error)));busy=false;if(batch.open){if(interrupted){batch.ack();submittedWake=void 0}else{batch.abandon();if(submittedWake!==void 0&&pendingWake===void 0){pendingWake=submittedWake;wakeSeq+=1}submittedWake=void 0}}await safeStatus("idle");if(!interrupted)scheduleErrorRetry();else{clearErrorRetry(true);if(workPending())void drive()}break;case"message.part.updated":{const partSession=event.properties.part?.sessionID;if(!ours(partSession))return;eventsFor(sessionID)?.flush(sessionID);break}case"tui.command.execute":{const p=event.properties;if(p.command==="session.interrupt")markInterruptIntent(p.sessionID);break}case"session.deleted":if(!ours(event.properties.info.id))return;await safeStatus("offline");break}},"tool.execute.before":async input=>{if(!ours(input.sessionID))return;await safeStatus("working",input.tool)}};const hooks={tool:fenceTools(buildCotalTools(agent,config2)),...fence(intake),"chat.message":async(input,output)=>{if(stopping)throw new Error("the prompt was not run: this seat is shutting down");if(!ours(input.sessionID))return;for(let barrier=turnEnds.get(input.sessionID);barrier!==void 0;barrier=turnEnds.get(input.sessionID))await barrier;if(input.model)await track(agent.setModel(`${input.model.providerID}/${input.model.modelID}`,input.variant));await injectIntoPrompt(output)},dispose:shutdown};guard.__cotalOpencodeHooks=hooks;log(`opencode plugin ready \u2014 space="${config2.space}" name="${config2.name}"${config2.role?` role="${config2.role}"`:""}`);return hooks};function log2(msg){process.stderr.write(`[cotal-connector] ${msg}
|
|
177
|
-
`)}var guard2=globalThis;var
|
|
176
|
+
${textPart.text}`;if(batch.open)busy=true}function completeTurn(){if(!busy&&!batch.open)return;busy=false;if(batch.open)batch.ack();submittedWake=void 0;clearInterruptIntent();clearErrorRetry(true);if(workPending())void drive()}agent.on("incoming",item=>{if(busy)return;const automatic=agent.inboxScope(item.recvKey)==="automatic";const directed=item.kind!=="channel"||item.mentionsMe;if(automatic&&(directed||agent.attention==="open"))void drive()});agent.on("mention-wake",item=>{pendingWake=`\u{1F4E8} You were mentioned by ${fmtFrom(item)} on #${fmtChannel(item.channel)} \u2014 read it with cotal_inbox.`;wakeSeq+=1;void drive()});agent.on("wake",()=>{if(!busy)void drive()});const ours=id2=>{if(!id2)return!sessionID;if(!sessionID)adoptSession(id2,"first event");return id2===sessionID};const fence=intake2=>Object.fromEntries(Object.entries(intake2).map(([name,hook])=>[name,async(...args)=>stopping?void 0:await hook(...args)]));const fenceTools=tools=>Object.fromEntries(Object.entries(tools).map(([name,def2])=>[name,{...def2,execute:async(...args)=>stopping?`\u26A0 ${name} was not run: this seat is shutting down`:await track(def2.execute(...args))}]));const intake={event:async({event})=>{if(event.type==="permission.asked"){const p=event.properties;if(!p.sessionID||ours(p.sessionID))await safeStatus("waiting",p.title);return}switch(event.type){case"session.created":{if(event.properties.info.parentID)break;const created=event.properties.info.id;const swap=swapChain.then(async()=>{swapping=true;try{adoptSession(created,"top-level session create");const previous=events;if(previous&&previous.path!==void 0&&previous.path!==created){previous.flush(previous.path);previous.closeRun(Date.now());const drained=await settleWithin(previous.settled(),SWAP_SETTLE_MS,`drain of ${previous.path}`);log(`${SESSION_RETIRED} ${previous.path} superseded by ${created}; ${drained?"drained before release":"ABANDONED UNDRAINED"}`);const retired=previous.path;await settleWithin(previous.close(),SWAP_SETTLE_MS,`release of ${retired}`);await reapRetiredWal(retired,drained);events=newEventHolder()}eventsFor(created)?.adopt(created)}finally{swapping=false}if(workPending())void drive()});swapChain=swap.catch(()=>void 0);await swap;break}case"session.idle":{const idleSession=event.properties.sessionID;if(!ours(idleSession))return;noteTurnEnd();eventsFor(sessionID)?.flush(sessionID);await turnEnded(idleSession,eventsFor(sessionID)?.closeRun(Date.now()));await safeStatus("idle");completeTurn();break}case"session.status":{if(!ours(event.properties.sessionID))return;const s=event.properties.status;if(s.type==="busy"){busy=true;await safeStatus("working")}else if(s.type==="idle"){noteTurnEnd();await safeStatus("idle")}else if(s.type==="retry"){await safeStatus("working",`retrying: ${s.message}`)}break}case"session.error":if(event.properties.sessionID&&!ours(event.properties.sessionID))return;noteTurnEnd();if(!busy&&!batch.open)return;const interrupted=consumeInterruptIntent(event.properties.sessionID)||isMessageAbortedError(event.properties.error);const eventHolder=eventsFor(sessionID);eventHolder?.flush(sessionID);await turnEnded(sessionID,eventHolder?.closeRun(Date.now(),interrupted?void 0:runErrorOf(event.properties.error)));busy=false;if(batch.open){if(interrupted){batch.ack();submittedWake=void 0}else{batch.abandon();if(submittedWake!==void 0&&pendingWake===void 0){pendingWake=submittedWake;wakeSeq+=1}submittedWake=void 0}}await safeStatus("idle");if(!interrupted)scheduleErrorRetry();else{clearErrorRetry(true);if(workPending())void drive()}break;case"message.part.updated":{const partSession=event.properties.part?.sessionID;if(!ours(partSession))return;eventsFor(sessionID)?.flush(sessionID);break}case"tui.command.execute":{const p=event.properties;if(p.command==="session.interrupt")markInterruptIntent(p.sessionID);break}case"session.deleted":if(!ours(event.properties.info.id))return;await safeStatus("offline");break}},"tool.execute.before":async input=>{if(!ours(input.sessionID))return;await safeStatus("working",input.tool)}};const hooks={tool:fenceTools(buildCotalTools(agent,config2)),...fence(intake),"chat.message":async(input,output)=>{if(stopping)throw new Error("the prompt was not run: this seat is shutting down");if(!ours(input.sessionID))return;for(let barrier=turnEnds.get(input.sessionID);barrier!==void 0;barrier=turnEnds.get(input.sessionID))await barrier;if(input.model)await track(agent.setModel(`${input.model.providerID}/${input.model.modelID}`,input.variant));await injectIntoPrompt(output)},dispose:shutdown};guard.__cotalOpencodeHooks=hooks;log(`opencode plugin ready \u2014 space="${config2.space}" name="${config2.name}"${config2.role?` role="${config2.role}"`:""}`);return hooks};import{randomUUID as randomUUID10}from"node:crypto";function cursorOf2(record2){return`${record2.message.id}:${record2.index}`}function parseCursor2(cursor){const i=cursor.indexOf(":");const index2=cursor.slice(i+1);if(i<=0||!/^(?:-1|0|[1-9]\d*)$/.test(index2)){throw new Error(`OpenCode2SessionSource: malformed cursor ${JSON.stringify(cursor)} (want <messageId>:<index>)`)}return{messageId:cursor.slice(0,i),index:Number(index2)}}function isAfter2(record2,at){if(record2.message.id!==at.messageId)return record2.message.id>at.messageId;return record2.index>at.index}function isSettled2(record2,turnEnded){const{message,element}=record2;if(message.type!=="assistant")return true;if(message.time.completed!==void 0||turnEnded)return true;if(element===void 0)return false;if(element.type==="tool")return element.state.status==="completed"||element.state.status==="error";return message.time.streamed!==void 0}var OpenCode2SessionSource=class{kind="opencode2-session";page;onVanished;reportedVanished;constructor(opts){this.page=opts.page;this.onVanished=opts.onVanished}async messages(from){const out=[];let next;for(;;){const page=await this.page(next);out.push(...page.data);const oldest=page.data.at(-1);if(oldest===void 0||!page.cursor.next||from!==void 0&&oldest.id<=from)return out;next=page.cursor.next}}async ordered(from){const messages=(await this.messages(from)).sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0);const lastIdle=messages.findLast(m=>m.type==="idle")?.id;const ordered=[];for(const message of messages){const turnEnded=lastIdle!==void 0&&message.id<lastIdle;const content=message.type==="assistant"?message.content??[]:[];if(content.length===0)ordered.push({record:{message,index:-1},turnEnded});content.forEach((element,index2)=>ordered.push({record:{message,index:index2,element},turnEnded}))}return ordered}async end(){const newest=(await this.page(void 0)).data[0];if(newest===void 0)return"";const count=newest.type==="assistant"?newest.content?.length??0:0;return`${newest.id}:${count-1}`}async read(cursor){if(cursor===void 0)return{records:[],cursor:await this.end()};const at=cursor===""?void 0:parseCursor2(cursor);const ordered=await this.ordered(at?.messageId);if(at!==void 0&&this.onVanished&&this.reportedVanished!==cursor&&!ordered.some(({record:record2})=>record2.message.id===at.messageId&&record2.index===at.index)){this.reportedVanished=cursor;this.onVanished(cursor)}const records=[];for(const{record:record2,turnEnded}of ordered){if(at!==void 0&&!isAfter2(record2,at))continue;if(!isSettled2(record2,turnEnded))break;records.push({value:record2,cursor:cursorOf2(record2)})}return{records,cursor:records.at(-1)?.cursor??cursor}}};function stampOf2(record2,element){if(element.type==="text")return record2.message.time.created;return element.time?.created??record2.message.time.created}function toolResultContent2(state){if(state.status==="error")return state.error?.message??"";return(state.content??[]).map(c=>c.text??"").join("")}function createOpenCode2Mapper(opts){let open4=opts.resumeRunId??null;return record2=>{const{message,index:index2,element}=record2;const timestamp=message.time.created;if(message.type==="user"||message.type==="idle"){if(open4===null)return null;const runId2=open4;open4=null;const failed=message.type==="idle"&&message.outcome==="failed";const terminal=failed?runError({message:message.error?.message||"opencode turn failed",timestamp,...message.error?.type?{code:message.error.type}:{}}):runFinished({threadId:opts.threadId,runId:runId2,timestamp});return{runId:runId2,events:[terminal]}}if(message.type!=="assistant"||element===void 0)return null;const ts=stampOf2(record2,element);const events=[];if(open4===null){open4=opts.mintRunId();events.push(runStarted({threadId:opts.threadId,runId:open4,timestamp:ts,cotal:{runIdSource:"connector"}}))}const runId=open4;const messageId=`${message.id}#${index2}`;const cotal2={providerMessageId:message.id};if(element.type==="text"&&element.text){events.push(textMessageStart({messageId,timestamp:ts,role:"assistant",cotal:cotal2}),textMessageContent({messageId,delta:element.text,timestamp:ts}),textMessageEnd({messageId,timestamp:ts}))}else if(element.type==="reasoning"&&opts.reasoning&&element.text){events.push(reasoningMessageStart({messageId,timestamp:ts,cotal:cotal2}),reasoningMessageContent({messageId,delta:element.text,timestamp:ts}),reasoningMessageEnd({messageId,timestamp:ts}))}else if(element.type==="tool"){const isError=element.state.status==="error";events.push(toolCallStart({toolCallId:element.id,toolCallName:element.name,timestamp:ts,parentMessageId:messageId,cotal:cotal2}),toolCallArgs({toolCallId:element.id,delta:JSON.stringify(element.state.input??null),timestamp:ts}),toolCallEnd({toolCallId:element.id,timestamp:ts}),toolCallResult({messageId:`${messageId}#result`,toolCallId:element.id,content:toolResultContent2(element.state),timestamp:ts,...isError?{cotal:{isError:true}}:{}}))}return events.length===0?null:{runId,events}}}function log2(msg){process.stderr.write(`[cotal-connector] ${msg}
|
|
177
|
+
`)}var guard2=globalThis;var MODEL_LIST_SETTLE_MS=1e4;var MENTION_NUDGE="\u{1F4E8} You were mentioned \u2014 read it with cotal_inbox.";async function verifyServerModel2(serverUrl,serverAuth,selectedModel,settleMs=MODEL_LIST_SETTLE_MS){const slash=selectedModel.indexOf("/");const provider=selectedModel.slice(0,slash);const model=selectedModel.slice(slash+1);const deadline=Date.now()+settleMs;for(;;){const response=await fetch(`${serverUrl}/api/model`,{headers:{authorization:serverAuth},signal:AbortSignal.timeout(1e4)});if(!response.ok)throw new Error(`opencode connector: server /api/model returned HTTP ${response.status} while checking model ${selectedModel}`);const listing=await response.json();if(slash<1||!model)throw new Error(modelRefusalSentence(selectedModel,"GET /api/model does not list it"));const data=listing.data??[];if(data.some(m=>m.providerID===provider&&m.modelID===model))return;if(data.some(m=>m.providerID===provider))throw new Error(modelRefusalSentence(selectedModel,"GET /api/model does not list it"));if(Date.now()>=deadline)throw new Error(modelRefusalSentence(selectedModel,`GET /api/model listed no provider within ${settleMs/1e3} s`));await new Promise(r=>setTimeout(r,200))}}var EVENT_QUIESCE_MS=1e4;async function setupCotal(ctx){if(!hasIdentity())return;const previous=guard2.__cotalOpencodeSetup;if(previous)return previous.complete?void 0:previous.ready;const state={complete:false,ready:Promise.resolve().then(async()=>{const teardown=await setupSession(ctx);state.complete=true;let stopping;return()=>stopping??=teardown().then(()=>{if(guard2.__cotalOpencodeSetup===state)delete guard2.__cotalOpencodeSetup})})};guard2.__cotalOpencodeSetup=state;try{return await state.ready}catch(error51){if(guard2.__cotalOpencodeSetup===state)delete guard2.__cotalOpencodeSetup;throw error51}}async function setupSession(ctx){const config2=configFromEnv();const eventsArmed=eventPlaneArmed(config2);scrubLaunchMaterial();config2.connector="opencode";const serverUrl=process.env.COTAL_OPENCODE_SERVER_URL?.trim();const serverUsername=process.env.OPENCODE_SERVER_USERNAME?.trim()||"opencode";const serverPassword=process.env.OPENCODE_SERVER_PASSWORD?.trim();if(!serverUrl||!serverPassword)throw new Error("opencode connector: missing COTAL_OPENCODE_SERVER_URL/OPENCODE_SERVER_PASSWORD");const serverAuth=`Basic ${Buffer.from(`${serverUsername}:${serverPassword}`).toString("base64")}`;const selectedModel=process.env.COTAL_MODEL?.trim();const settleOverride=Number(process.env.COTAL_MODEL_LIST_SETTLE_MS);const settleMs=Number.isFinite(settleOverride)&&settleOverride>0?settleOverride:MODEL_LIST_SETTLE_MS;const modelReady=(async()=>{if(!selectedModel)return;await verifyServerModel2(serverUrl,serverAuth,selectedModel,settleMs)})();const agent=new MeshAgent(config2);const controller=new AbortController;async function opencodeApi(path,init,timeoutMs=1e4){const res=await fetch(`${serverUrl}${path}`,{...init,signal:init?.signal??AbortSignal.timeout(timeoutMs),headers:{authorization:serverAuth,"content-type":"application/json",...init?.headers??{}}});if(!res.ok)throw new Error(`OpenCode HTTP ${res.status} ${res.statusText} for ${path}`);if(res.status===204)return void 0;return await res.json()}const sessionSource=id2=>new OpenCode2SessionSource({page:next=>opencodeApi(`/api/session/${encodeURIComponent(id2)}/message?limit=200&${next===void 0?"order=desc":`cursor=${encodeURIComponent(next)}`}`,void 0,3e4),onVanished:cursor=>log2(`AG-UI: the resume cursor was removed from the session (revert): ${cursor}`)});let eventLock;function eventHolder(){let bound;return new AguiEmitterHolder(async id2=>{bound??=new BoundStartSource(sessionSource(id2),"");await agent.whenConnected(2e4);const principal=principalKey(agent.ep.principal.owner,agent.ep.principal.actor).key;const{walPath,subjectPath,lock}=await ensureEventWalDir({workspaceRoot:resolveEventsStateRoot(process.env),space:config2.space,principal,threadId:id2});eventLock=lock;const subjectFrontier=await FileSubjectFrontier.open(subjectPath,{space:config2.space,principal});const wal=await EventWal.open(walPath,{space:config2.space,threadId:id2,principal,subjectMayExist:false});const resumeRunId=wal.pending===null?wal.brackets?.run:wal.pending.brackets.run;return AguiEmitter.start({endpoint:agent.ep,wal,subjectFrontier,source:bound,map:createOpenCode2Mapper({threadId:id2,mintRunId:()=>randomUUID10(),resumeRunId})})},{onError:eventPlaneStopped({log:log2}),sourceEnd:id2=>sessionSource(id2).end()})}const events=eventsArmed?eventHolder():void 0;const def=process.env.COTAL_AGENT_FILE?.trim()?loadAgentFile(process.env.COTAL_AGENT_FILE.trim()):void 0;const persona=def?.persona||void 0;let bootPrompt=process.env.COTAL_OPENCODE_PROMPT?.trim()||void 0;let bootReady=false;const bootPending=()=>bootReady&&bootPrompt!==void 0;let sessionID;let execution;let primed=false;let briefed=false;const batch=new SurfacedBatch(agent);let ended;let started;let unorderedEnds=0;let pendingMention=false;let submitting;const sessionReady=(async()=>{try{await modelReady;const res=await opencodeApi("/api/session",{method:"POST",body:JSON.stringify({title:`cotal:${config2.space}:${config2.name}`})},1e4);const id2=res.data?.id;if(id2){sessionID=id2;agent.setContextId(id2);process.stderr.write(`[cotal-session] ${id2}
|
|
178
178
|
`)}else log2("session.create returned no id")}catch(e){log2(`session.create failed: ${e.message}`)}return sessionID})();async function ensureSession(){return sessionID??await sessionReady}const safeStatus=async(status2,activity)=>{try{if(agent.connected)await agent.setStatus(status2,activity)}catch{}};async function drive(){if(execution||submitting||controller.signal.aborted)return;const id2=await ensureSession();if(!id2)return;if(execution||submitting||controller.signal.aborted)return;const boot=bootPending()?bootPrompt:void 0;const override=pendingMention?MENTION_NUDGE:void 0;if(bootPrompt!==void 0&&boot===void 0)return;const parts=[];let ids=[];let turnIds=[];const turnPeek=agent.peekPendingTurns();if(boot!==void 0){parts.push(boot)}else if(override!==void 0){parts.push(override)}else{const openBefore=batch.open;const items=await agent.takeChosen("automatic",preview=>preview);if(execution||submitting||!openBefore&&batch.open||controller.signal.aborted)return;if(items.length===0&&!turnPeek)return;if(items.length>0){ids=items.map(i=>i.recvKey);const inj=formatInjection(items);if(inj)parts.push(inj)}}const brief=briefed?void 0:agent.channelBriefing();if(brief)parts.unshift(brief);if(parts.length===0&&!turnPeek)return;const system=!primed&&persona?`${persona}
|
|
179
179
|
|
|
180
180
|
${briefing(config2,"opencode")}`:void 0;if(!batch.surface(ids))return;if(turnPeek&&agent.claimTurns(turnPeek.goalIds)){turnIds=turnPeek.goalIds;parts.push(turnPeek.text)}if(boot===void 0&&override===void 0&&ids.length===0&&turnIds.length===0){batch.abandon();return}const text2=parts.join("\n\n");execution="submitted";briefed=true;const endAtSend=ended;const unorderedAtSend=unorderedEnds;submitting=(async()=>{try{await opencodeApi(`/api/session/${encodeURIComponent(id2)}/prompt`,{method:"POST",body:JSON.stringify({text:text2,...system?{system}:{}})},1e4);if(turnIds.length&&(ended!==endAtSend||unorderedEnds!==unorderedAtSend))agent.releaseTurns(turnIds);if(turnIds.length)agent.commitSurfacedTurns(turnIds);if(system)primed=true;if(boot!==void 0)bootPrompt=void 0;else if(override!==void 0)pendingMention=false}catch(e){agent.releaseTurns(turnIds);if(execution==="submitted")execution=void 0;batch.abandon();log2(`drive failed: ${e.message}`)}finally{submitting=void 0}})();await submitting}function replayed(ev,mark=ended){if(!positioned(ev)){log2(`${ev.type} carries no durable log position; ignored`);return true}return ev.durable.aggregateID===mark?.aggregateID&&ev.durable.seq<=mark.seq}function positioned(ev){const at=ev.durable;return typeof at?.aggregateID==="string"&&at.aggregateID.length>0&&typeof at.seq==="number"&&Number.isFinite(at.seq)}async function completeTurn(ev,settle){if(!positioned(ev))unorderedEnds+=1;if(replayed(ev)||execution==="running"&&replayed(ev,started))return;ended=ev.durable;if(execution!=="running")return;execution=void 0;const carried=new Set(batch.keys);settle();await safeStatus("idle");void(async()=>{await submitting;if(ended!==ev.durable)return;if(bootPending()||pendingMention||agent.pendingWake(item=>carried.has(item.recvKey))>0)void drive()})()}agent.on("incoming",item=>{if(execution)return;const automatic=agent.inboxScope(item.recvKey)==="automatic";const directed=item.kind!=="channel"||item.mentionsMe;if(automatic&&(directed||agent.attention==="open"))void drive()});agent.on("mention-wake",()=>{pendingMention=true;void drive()});agent.on("wake",()=>{if(!execution)void drive()});await ctx.session.hook("prompt",async e=>{if(sessionID&&e.sessionID!==sessionID)return;if(!batch.open)await agent.takeChosen("automatic",preview=>preview);const prefix=batch.inject();if(prefix!==void 0)e.prompt.text=`${prefix}
|
|
181
181
|
|
|
182
|
-
${e.prompt.text}`});await ctx.session.hook("model.request",e=>{if(e.kind!=="primary")return;void agent.setModel(`${e.model.providerID}/${e.model.id}`)});await ctx.tool.hook("execute.before",e=>{if(sessionID&&e.sessionID!==sessionID)return;void safeStatus("working",e.tool)});await ctx.tool.transform(ed=>{for(const t of buildCotalTools2(agent,config2))ed.add(t)});void modelReady.then(()=>{if(controller.signal.aborted)return;return agent.start()},error51=>{if(controller.signal.aborted)return;log2(error51.message);process.exit(1)});const eventLoop=(async()=>{try{for await(const ev of ctx.event.subscribe({signal:controller.signal})){const data=ev.data??{};switch(ev.type){case"session.created":{if(data.parentID)break;const id2=data.sessionID;if(id2&&!sessionID){sessionID=id2;agent.setContextId(id2)}break}case"session.execution.started":{if(data.sessionID!==sessionID||replayed(ev)||replayed(ev,started))break;execution="running";started=ev.durable;await safeStatus("working");break}case"session.execution.succeeded":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.ack());break}case"session.execution.failed":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.abandon());break}case"session.execution.interrupted":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.ack());break}case"permission.asked":{const p=data;if(!p.sessionID||!sessionID||p.sessionID===sessionID)await safeStatus("waiting",p.title);break}case"session.deleted":{const id2=data.info?.id;if(id2&&(!sessionID||id2===sessionID))await safeStatus("offline");break}}}}catch(e){if(!controller.signal.aborted)log2(`event loop ended: ${e.message}`)}})();void(async()=>{if(bootPrompt===void 0)return;const id2=await sessionReady;while(!controller.signal.aborted&&!agent.connected)await new Promise(r=>setTimeout(r,100).unref?.());if(controller.signal.aborted||bootPrompt===void 0)return;if(!id2){log2("initial prompt not submitted \u2014 this session was never created");bootPrompt=void 0;return}bootReady=true;await drive()})();const teardown=async()=>{controller.abort();await settleWithin(eventLoop,EVENT_QUIESCE_MS,"opencode 2.x event loop at teardown");await agent.stop()};registerOnceExit(()=>void teardown().finally(()=>process.exit(1)));return teardown}var plugin_entry_default={id:"cotal",server:cotal,setup:setupCotal};export{plugin_entry_default as default};
|
|
182
|
+
${e.prompt.text}`});await ctx.session.hook("model.request",e=>{if(e.kind!=="primary")return;void agent.setModel(`${e.model.providerID}/${e.model.id}`)});await ctx.tool.hook("execute.before",e=>{if(sessionID&&e.sessionID!==sessionID)return;void safeStatus("working",e.tool)});await ctx.tool.transform(ed=>{for(const t of buildCotalTools2(agent,config2))ed.add(t)});void modelReady.then(()=>{if(controller.signal.aborted)return;return agent.start()},error51=>{if(controller.signal.aborted)return;log2(error51.message);process.exit(1)});void sessionReady.then(id2=>{if(id2===void 0||controller.signal.aborted)return;events?.adopt(id2);events?.flush(id2)});const eventLoop=(async()=>{try{for await(const ev of ctx.event.subscribe({signal:controller.signal})){const data=ev.data??{};if(events?.path!==void 0&&ev.durable?.aggregateID===events.path)events.flush(events.path);switch(ev.type){case"session.created":{if(data.parentID)break;const id2=data.sessionID;if(id2&&!sessionID){sessionID=id2;agent.setContextId(id2)}break}case"session.execution.started":{if(data.sessionID!==sessionID||replayed(ev)||replayed(ev,started))break;execution="running";started=ev.durable;await safeStatus("working");break}case"session.execution.succeeded":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.ack());break}case"session.execution.failed":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.abandon());break}case"session.execution.interrupted":{if(data.sessionID!==sessionID)break;await completeTurn(ev,()=>batch.ack());break}case"permission.asked":{const p=data;if(!p.sessionID||!sessionID||p.sessionID===sessionID)await safeStatus("waiting",p.title);break}case"session.deleted":{const id2=data.info?.id;if(id2&&(!sessionID||id2===sessionID))await safeStatus("offline");break}}}}catch(e){if(!controller.signal.aborted)log2(`event loop ended: ${e.message}`)}})();void(async()=>{if(bootPrompt===void 0)return;const id2=await sessionReady;while(!controller.signal.aborted&&!agent.connected)await new Promise(r=>setTimeout(r,100).unref?.());if(controller.signal.aborted||bootPrompt===void 0)return;if(!id2){log2("initial prompt not submitted \u2014 this session was never created");bootPrompt=void 0;return}bootReady=true;await drive()})();const teardown=async()=>{controller.abort();await settleWithin(eventLoop,EVENT_QUIESCE_MS,"opencode 2.x event loop at teardown");await settleWithin(events?.close(),EVENT_QUIESCE_MS,"event holder at teardown");await eventLock?.release().catch(e=>log2(`event WAL lock release failed: ${e.message}`));await agent.stop()};registerOnceExit(()=>void teardown().finally(()=>process.exit(1)));return teardown}var plugin_entry_default={id:"cotal",server:cotal,setup:setupCotal};export{plugin_entry_default as default};
|
|
183
183
|
/*! Bundled license information:
|
|
184
184
|
|
|
185
185
|
js-sha256/src/sha256.js:
|
package/dist/plugin2.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin2.d.ts","sourceRoot":"","sources":["../src/plugin2.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"plugin2.d.ts","sourceRoot":"","sources":["../src/plugin2.ts"],"names":[],"mappings":"AAqCA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,sBAAsB,CAAC;AAgB7E;;;;8EAI8E;AAC9E,eAAO,MAAM,oBAAoB,QAAS,CAAC;AAuC3C;0FAC0F;AAC1F,wBAAsB,UAAU,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAsB7F"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cotal-ai/connector-opencode",
|
|
3
3
|
"description": "Cotal connector for OpenCode: a native in-process plugin that joins a session to the mesh.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.156.0",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
"@cotal-ai/core": ">=0.1.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@cotal-ai/connector-core": "0.
|
|
25
|
-
"@cotal-ai/core": "0.
|
|
24
|
+
"@cotal-ai/connector-core": "0.156.0",
|
|
25
|
+
"@cotal-ai/core": "0.156.0",
|
|
26
26
|
"@cotal-ai/smoke-kit": "0.0.0",
|
|
27
27
|
"@nats-io/transport-node": "^3.4.0",
|
|
28
28
|
"@opencode-ai/plugin": "^1.16.2",
|