@cotal-ai/connector-opencode 0.192.0 → 0.193.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/approved-fork2.d.ts +19 -0
- package/dist/approved-fork2.d.ts.map +1 -0
- package/dist/catalog2.d.ts +3 -1
- package/dist/catalog2.d.ts.map +1 -1
- package/dist/commands2.d.ts +3 -0
- package/dist/commands2.d.ts.map +1 -1
- package/dist/compact2.d.ts +9 -0
- package/dist/compact2.d.ts.map +1 -0
- package/dist/event-holder.d.ts +21 -0
- package/dist/event-holder.d.ts.map +1 -0
- package/dist/extension.d.ts.map +1 -1
- package/dist/fork-snapshot2.d.ts +4 -0
- package/dist/fork-snapshot2.d.ts.map +1 -0
- package/dist/fork-source2.d.ts +16 -0
- package/dist/fork-source2.d.ts.map +1 -0
- package/dist/index.js +4 -39
- package/dist/launch-config.d.ts +26 -0
- package/dist/launch-config.d.ts.map +1 -0
- package/dist/launch.d.ts.map +1 -1
- package/dist/launch.js +8 -7
- package/dist/model-choices2.d.ts +10 -0
- package/dist/model-choices2.d.ts.map +1 -0
- package/dist/native-history2.d.ts +9 -0
- package/dist/native-history2.d.ts.map +1 -0
- package/dist/native-idle.d.ts +30 -0
- package/dist/native-idle.d.ts.map +1 -0
- package/dist/native-shell-stop2.d.ts +17 -0
- package/dist/native-shell-stop2.d.ts.map +1 -0
- package/dist/native2.d.ts +8 -2
- package/dist/native2.d.ts.map +1 -1
- package/dist/opencode-line.d.ts +1 -0
- package/dist/opencode-line.d.ts.map +1 -1
- package/dist/opencode2-http.d.ts +2 -0
- package/dist/opencode2-http.d.ts.map +1 -1
- package/dist/opencode2-launch.d.ts +35 -0
- package/dist/opencode2-launch.d.ts.map +1 -0
- package/dist/opencode2-types.d.ts +5 -1
- package/dist/opencode2-types.d.ts.map +1 -1
- package/dist/plugin/docs-bundle.bin +0 -0
- package/dist/plugin/docs-index.bin +0 -0
- package/dist/plugin/index.js +68 -39
- package/dist/plugin-body.d.ts +4 -0
- package/dist/plugin-body.d.ts.map +1 -0
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin2.d.ts.map +1 -1
- package/dist/serve.js +8 -7
- package/dist/session-continuation.d.ts +85 -0
- package/dist/session-continuation.d.ts.map +1 -0
- package/dist/settled-models.d.ts +2 -0
- package/dist/settled-models.d.ts.map +1 -1
- package/dist/sleep-gate.d.ts +78 -0
- package/dist/sleep-gate.d.ts.map +1 -0
- package/dist/tui-control.d.ts +51 -0
- package/dist/tui-control.d.ts.map +1 -0
- package/package.json +5 -4
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Hooks } from "@opencode-ai/plugin";
|
|
2
|
+
export { SESSION_RETIRED, SETTLE_ABANDONED, WAL_REAPED, WAL_KEPT, modelRefusalSentence, verifyServerModel, settleWithin, SurfacedBatch, } from "./plugin-seams.js";
|
|
3
|
+
export declare function cotalBody(): Promise<Hooks>;
|
|
4
|
+
//# sourceMappingURL=plugin-body.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-body.d.ts","sourceRoot":"","sources":["../src/plugin-body.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,KAAK,EAA8B,MAAM,qBAAqB,CAAC;AAqB7E,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,mBAAmB,CAAC;AAQ3B,wBAAsB,SAAS,IAAI,OAAO,CAAC,KAAK,CAAC,CAEhD"}
|
package/dist/plugin.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,mBAAmB,CAAC;AAE3B,eAAO,MAAM,KAAK,EAAE,MAAgC,CAAC"}
|
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":"AAsCA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,sBAAsB,CAAC;AA0E7E;0FAC0F;AAC1F,wBAAsB,UAAU,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAsB7F"}
|
package/dist/serve.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import{execFileSync as
|
|
2
|
-
`}}function tryAcquireOnce({path,nonce,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===
|
|
3
|
-
|
|
4
|
-
`);const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`);
|
|
1
|
+
import{execFileSync as execFileSync3,spawn as spawn2}from"node:child_process";import{once as once3}from"node:events";import{randomBytes as randomBytes4}from"node:crypto";import{accessSync,closeSync as closeSync2,constants as constants2,lstatSync as lstatSync2,mkdirSync as mkdirSync3,openSync as openSync2,readdirSync,readFileSync as readFileSync2,rmdirSync,rmSync as rmSync3,statSync as statSync2,writeFileSync as writeFileSync2}from"node:fs";import{delimiter,isAbsolute,join as join3,resolve as resolve2}from"node:path";import{StringDecoder}from"node:string_decoder";import{execFileSync as execFileSync2}from"node:child_process";import{linkSync as linkSync2,mkdirSync as mkdirSync2,readFileSync,rmSync,statSync,unlinkSync as unlinkSync2}from"node:fs";import{randomBytes}from"node:crypto";import{dirname as dirname2}from"node:path";import{chmodSync,closeSync,constants,fchmodSync,fstatSync,ftruncateSync,linkSync,lstatSync,mkdirSync,openSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{execFile,execFileSync}from"node:child_process";import{dirname,join,resolve,toNamespacedPath}from"node:path";var isWin=process.platform==="win32";function sys32(exe){const root=process.env.SystemRoot||process.env.windir||"C:\\Windows";return join(root,"System32",exe)}var cachedSid;function ownerSid(){if(cachedSid)return cachedSid;const out=execFileSync(sys32("whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8",windowsHide:true});const sid=out.trim().split(",").pop()?.replace(/^"|"$/g,"").trim();if(!sid||!/^S-1-/.test(sid))throw new Error(`could not determine the current user's SID from \`whoami\` (got: ${out.trim()})`);cachedSid=sid;return sid}var BROAD_SIDS=["S-1-1-0","S-1-5-11","S-1-5-32-545"];function hardenPrivate(path,kind){if(!isWin){if(kind==="file")closeSync(openPrivate(path,constants.O_RDONLY));else chmodSync(path,448);return}try{execFileSync(sys32("icacls.exe"),icaclsPrivateArgs(path,kind),{stdio:["ignore","ignore","pipe"],windowsHide:true})}catch(e){throw hardeningFailure(path,kind,e)}}function icaclsPrivateArgs(path,kind){const perm=kind==="dir"?"(OI)(CI)(F)":"(F)";const grant=sid=>["/grant:r",`*${sid}:${perm}`];return[toNamespacedPath(resolve(path)),"/inheritance:r",...BROAD_SIDS.flatMap(sid=>["/remove:g",`*${sid}`]),...grant(ownerSid()),...grant("S-1-5-18"),...grant("S-1-5-32-544")]}function hardeningFailure(path,kind,cause){return new Error(`failed to harden ${kind} "${path}" to private via icacls: ${cause.message.trim()}. Cotal will not leave a secret with a permissive ACL - ensure the path is on an NTFS volume and %SystemRoot%\\System32\\icacls.exe is available.`)}function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=openSync(path,flags,384);try{fchmodSync(fd2,384)}catch(e){closeSync(fd2);throw e}return fd2}let fd;try{fd=openSync(path,flags|constants.O_NOFOLLOW|constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=fstatSync(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);fchmodSync(fd,384);return fd}catch(e){closeSync(fd);throw e}}function openPrivateAppend(path){return openPrivate(path,constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND)}function createPrivateRecord(path,data){writeBytes(path,data,true)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,constants.O_WRONLY|constants.O_CREAT|(exclusive?constants.O_EXCL:0));try{try{ftruncateSync(fd);writeFileSync(fd,data)}finally{closeSync(fd)}}catch(e){if(exclusive){try{unlinkSync(path)}catch{}}throw e}}function mkSecretDir(path){mkdirSync(path,{recursive:true,mode:448});hardenPrivate(path,"dir")}function processStatFields(pid){try{const stat=readFileSync(`/proc/${pid}/stat`,"utf8");const after=stat.lastIndexOf(") ");if(after<0||stat.slice(0,stat.indexOf(" "))!==String(pid))return void 0;return stat.slice(after+2).trim().split(/\s+/)}catch{return void 0}}function processStartToken(pid){if(process.platform==="win32")return void 0;if(process.platform==="linux")return processStatFields(pid)?.[19];try{const out=execFileSync2("ps",["-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return out||void 0}catch{return void 0}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function pidAlive(pid){try{process.kill(pid,0);return true}catch(e){const code=e.code;if(code==="ESRCH")return false;if(code==="EPERM")return true;throw e}}function readOwner(path){let raw;try{raw=readFileSync(path,"utf8")}catch(e){const code=e.code;if(code==="ENOENT")return void 0;if(code==="EISDIR"||code==="EACCES"||code==="EPERM")throw new Error(`advisory lock path ${path} is unreadable (${code}) - remove the stray file or directory there and retry`);throw e}let ino;try{ino=statSync(path).ino}catch{}try{return{owner:JSON.parse(raw),ino}}catch{return{ino}}}function inspectLock(path){const inspection=inspectLockSnapshot(path);return inspection.state==="active"?{state:"active",owner:inspection.owner}:{state:inspection.state}}function inspectLockSnapshot(path){const found=readOwner(path);if(found===void 0)return{state:"absent"};const{owner,ino}=found;if(!owner||typeof owner.pid!=="number"||!Number.isInteger(owner.pid)||owner.pid<=0||typeof owner.nonce!=="string"){return{state:"stale",ino}}if(!pidAlive(owner.pid))return{state:"stale",ino};if(owner.start!==void 0){const fields=process.platform==="linux"?processStatFields(owner.pid):void 0;const now=process.platform==="linux"?fields?.[19]:processStartToken(owner.pid);if(now===owner.start&&fields?.[0]==="Z")return{state:"stale",ino};if(now!==void 0&&now!==owner.start)return{state:"stale",ino}}return{state:"active",owner,ino}}function publishAtomic(path,content){const tmp=`${path}.${randomBytes(8).toString("hex")}.tmp`;createPrivateRecord(tmp,content);try{linkSync2(tmp,path);return true}catch(e){if(e.code==="EEXIST")return false;throw e}finally{try{unlinkSync2(tmp)}catch{}}}function reclaimStale(path,inspectedIno){const sentinel=`${path}.reclaim`;const mine=JSON.stringify({pid:process.pid,start:processStartToken(process.pid),nonce:randomBytes(8).toString("hex"),ts:Date.now()});if(!publishAtomic(sentinel,mine)){const reclaimer=inspectLock(sentinel);if(reclaimer.state==="stale")throw new Error(`a lock reclaim was interrupted and its sentinel remains (${sentinel}) - if no cotal process is running, remove it and retry`);return reclaimer.state==="active"?reclaimer.owner:void 0}try{const inspection=inspectLockSnapshot(path);if(inspection.state!=="stale")return;if(inspectedIno!==void 0&&inspection.ino!==void 0&&inspection.ino!==inspectedIno)return;unlinkSync2(path)}catch(e){if(e.code!=="ENOENT")throw e}finally{try{unlinkSync2(sentinel)}catch{}}}function newAttempt(path,opts){mkdirSync2(dirname2(path),{recursive:true,mode:448});const nonce2=randomBytes(12).toString("hex");const owner={pid:process.pid,start:processStartToken(process.pid),nonce:nonce2,ts:Date.now(),...opts.label?{label:opts.label}:{}};return{path,nonce:nonce2,content:`${JSON.stringify(owner)}
|
|
2
|
+
`}}function tryAcquireOnce({path,nonce:nonce2,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce:nonce2,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===nonce2){try{unlinkSync2(path)}catch{}}}}}}const inspection=inspectLockSnapshot(path);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path,opts);const deadline=Date.now()+waitMs;let waiting=false;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path,opts,result.owner,waitMs);if(!waiting){waiting=true;opts.onWait?.()}sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path,opts,owner,waitMs){return opts.onTimeout?.(owner)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path}`)}var OPENCODE_BOOT_TIMEOUT_MS=12e4;var OPENCODE_READINESS_TIMEOUT_MS=OPENCODE_BOOT_TIMEOUT_MS+5e3;function opencodeLine(raw,bin){const m=raw.match(/(?:^|v)(\d+)\.\d+/);const major=m?Number(m[1]):NaN;if(major===1||major===2)return major;throw new Error(`opencode connector: unsupported OpenCode version "${raw}" from ${bin}; this connector supports the 1.x (opencode-ai) and 2.x (@opencode/cli) lines. Install a supported OpenCode in place of ${bin}, for example with \`npm install -g opencode-ai\`, then try again`)}var QUALIFIED_VERSION=/^(?:opencode\s+)?v?(2\.0\.20|2\.4\.3)$/i;var qualifiedOpenCode2Version=version=>QUALIFIED_VERSION.exec(version?.trim()??"")?.[1];var FORK_FILE_ENV="COTAL_OPENCODE_FORK_SOURCE_FILE";var FORK_REVISION_ENV="COTAL_OPENCODE_FORK_SOURCE_REVISION";import{once}from"node:events";import{createServer}from"node:net";async function freePort(){const srv=createServer();srv.listen(0,"127.0.0.1");await once(srv,"listening");const port=srv.address().port;await new Promise(r=>srv.close(()=>r()));return port}import{spawn}from"node:child_process";import{once as once2}from"node:events";import{randomBytes as randomBytes3}from"node:crypto";import{createServer as createServer2}from"node:net";import{tmpdir}from"node:os";import{join as join2}from"node:path";import{rmSync as rmSync2}from"node:fs";import{createHmac,randomBytes as randomBytes2,timingSafeEqual}from"node:crypto";var CONTROL_PROTOCOL_VERSION=1;var CONTROL_SERVER_AUTH_DEADLINE_MS=5e3;var MAX_HANDSHAKE_LINE_BYTES=1024;var MAX_CONTROL_REQUEST_BYTES=1<<20;var BASE64URL_43=/^[A-Za-z0-9_-]{43}$/;var MAC_CHARS=43;var MAC_PREFIX_BYTES=MAC_CHARS+1;var NEWLINE=10;var SPACE=32;var utf8=new TextDecoder("utf-8",{fatal:true});function assertControlVersion(version,where){if(version===CONTROL_PROTOCOL_VERSION)return;throw new Error(`${where} carries control protocol version ${JSON.stringify(version)}, and this build speaks only version ${CONTROL_PROTOCOL_VERSION}. A launcher and connector from different releases refuse each other instead of falling back; upgrade both to the same release.`)}function assertControlEndpoint(endpoint){assertControlVersion(endpoint.version,"the control endpoint");if(typeof endpoint.token!=="string"||!endpoint.token)throw new Error("the control endpoint has no key")}function transcriptMac(token,role,nc,ns,body){const mac=createHmac("sha256",Buffer.from(token,"utf8"));mac.update(`cotal-control/${CONTROL_PROTOCOL_VERSION}\0${role}\0${nc}\0${ns}`,"utf8");if(body!==void 0)mac.update("\0","utf8").update(body);return mac.digest("base64url")}function macMatches(presented,expected){if(typeof presented!=="string"||!BASE64URL_43.test(presented))return false;return timingSafeEqual(Buffer.from(presented,"ascii"),Buffer.from(expected,"ascii"))}function openSealed(line,expected){if(line.length<MAC_PREFIX_BYTES||line[MAC_CHARS]!==SPACE)return void 0;const body=line.subarray(MAC_PREFIX_BYTES);if(!macMatches(line.subarray(0,MAC_CHARS).toString("latin1"),expected(body)))return void 0;try{return utf8.decode(body)}catch{return void 0}}function parseHandshake(line){try{const value=JSON.parse(utf8.decode(line));return value&&typeof value==="object"&&!Array.isArray(value)?value:void 0}catch{return void 0}}function lineReader(cap,onLine,oversize){let buf=Buffer.alloc(0);let stopped=false;return chunk=>{if(stopped)return;buf=buf.length?Buffer.concat([buf,chunk]):chunk;for(;;){const limit=cap();const nl=buf.indexOf(NEWLINE);const length=nl<0?buf.length:nl;if(length>limit){stopped=true;return oversize()}if(nl<0)return;const line=buf.subarray(0,nl);buf=buf.subarray(nl+1);if(!onLine(line)){stopped=true;return}}}}var nonce=()=>randomBytes2(32).toString("base64url");function serverExchange(sock,endpoint,onRequest,opts={}){assertControlEndpoint(endpoint);let nc;const ns=nonce();let settled=false;const drop=()=>{if(!settled){settled=true;clearTimeout(deadline);sock.destroy()}return false};const deadline=setTimeout(drop,opts.deadlineMs??CONTROL_SERVER_AUTH_DEADLINE_MS);deadline.unref?.();const onClose=()=>{settled=true;clearTimeout(deadline)};const onLine=line=>{if(settled)return false;if(nc===void 0){const hello=parseHandshake(line);if(!hello||hello.v!==CONTROL_PROTOCOL_VERSION||typeof hello.nonce!=="string"||!BASE64URL_43.test(hello.nonce))return drop();nc=hello.nonce;try{sock.write(JSON.stringify({v:CONTROL_PROTOCOL_VERSION,nonce:ns,mac:transcriptMac(endpoint.token,"server",nc,ns)})+"\n")}catch{return drop()}return true}const proven=nc;const request=openSealed(line,body=>transcriptMac(endpoint.token,"client",proven,ns,body));if(request===void 0)return drop();settled=true;clearTimeout(deadline);sock.off("data",onData);sock.off("close",onClose);onRequest({request,seal:text=>{const body=Buffer.from(text,"utf8");const receipt=transcriptMac(endpoint.token,"receipt",proven,ns,body);return{line:`${transcriptMac(endpoint.token,"reply",proven,ns,body)} ${text}
|
|
3
|
+
`,receiptMatches:presented=>macMatches(presented,receipt)}}});return false};const onData=lineReader(()=>nc===void 0?MAX_HANDSHAKE_LINE_BYTES:MAC_PREFIX_BYTES+MAX_CONTROL_REQUEST_BYTES,onLine,()=>void drop());sock.on("data",onData);sock.on("close",onClose)}var TUI_TERM_GRACE_MS=3e3;var TUI_SOCKET_ENV="COTAL_OPENCODE_TUI_SOCKET";var TUI_TOKEN_ENV="COTAL_OPENCODE_TUI_TOKEN";function mintTuiEndpoint(){const token=randomBytes3(32).toString("base64url");if(process.platform==="win32"){return{path:`\\\\.\\pipe\\cotal-tui-${randomBytes3(12).toString("hex")}`,token,version:CONTROL_PROTOCOL_VERSION}}const dir=join2(tmpdir(),`cotal-tui-${randomBytes3(8).toString("hex")}`);mkSecretDir(dir);return{path:join2(dir,"tui.sock"),token,version:CONTROL_PROTOCOL_VERSION}}async function reapChild(child,graceMs=TUI_TERM_GRACE_MS){if(child.exitCode!==null||child.signalCode!==null)return;child.kill("SIGTERM");const dead=await Promise.race([once2(child,"exit").then(()=>true),new Promise(resolve3=>setTimeout(()=>resolve3(false),graceMs))]);if(!dead){child.kill("SIGKILL");await once2(child,"exit")}}function startTuiControl(host){let child;let session;let detaching=false;function attach(next){if(host.stopping()||child)return;session=next;const[command,...args]=host.argv(next);const tui=spawn(command,args,{env:host.env,stdio:"inherit"});child=tui;tui.on("exit",(code,signal)=>{if(child!==tui)return;child=void 0;const asked=detaching;detaching=false;if(!asked&&!host.stopping())host.onUnexpectedExit(code,signal)})}async function detach(){const tui=child;if(!tui)return true;detaching=true;try{await reapChild(tui);return true}catch{if(child===tui)detaching=false;return false}}const server=createServer2(sock=>{sock.on("error",()=>void 0);serverExchange(sock,host.endpoint,({request,seal})=>{let frame;try{frame=JSON.parse(request)}catch{try{sock.end(seal(JSON.stringify({ok:false,reason:"malformed TUI control frame"})).line)}catch{}return}const answer=body=>{try{sock.end(seal(JSON.stringify(body)).line)}catch{}};if(frame.op==="detach"){void detach().then(ok=>answer(ok?{ok:true}:{ok:false,reason:"the OpenCode TUI did not exit"}));return}if(frame.op==="attach"){const id=frame.session||session;if(!id)return answer({ok:false,reason:"there is no OpenCode session to attach"});if(host.stopping())return answer({ok:false,reason:"this opencode seat is shutting down"});attach(id);return answer({ok:true})}answer({ok:false,reason:"unknown TUI control op"})})});server.listen(host.endpoint.path);return{server,attach,detach,close(){server.close();if(process.platform!=="win32")rmSync2(join2(host.endpoint.path,".."),{recursive:true,force:true})}}}function resolveOpencodeBin(){const override=process.env.COTAL_OPENCODE_BIN?.trim()||process.env.COTAL_OPENCODE_RESOLVED_BIN?.trim();if(process.platform!=="win32")return located(override||"opencode");if(override)return override;for(const dir of(process.env.PATH??"").split(delimiter)){if(!dir)continue;for(const exe of[join3(dir,"opencode.exe"),join3(dir,"node_modules","opencode-ai","bin","opencode.exe")]){if(executableFile(exe))return resolve2(exe)}}return"opencode"}var BIN=resolveOpencodeBin();function executableFile(file){try{accessSync(file,constants2.X_OK);return statSync2(file).isFile()}catch{return false}}function located(bin){if(bin.includes("/"))return bin;for(const dir of(process.env.PATH??"/usr/bin:/bin").split(delimiter)){const absoluteDir=isAbsolute(dir)?dir:dir?`${process.cwd()}/${dir}`:process.cwd();const file=`${absoluteDir}/${bin}`;if(executableFile(file))return file}return bin}var USERNAME="opencode";var SECRET=process.env.OPENCODE_SERVER_PASSWORD||randomBytes4(24).toString("hex");var RECORD_THEN_EXEC=`printf %s "$$" > "$1" && shift && exec "$@"`;async function terminate(child){if(child.exitCode!==null||child.signalCode!==null)return;child.kill("SIGTERM");const dead=await Promise.race([once3(child,"exit").then(()=>true),new Promise(r=>setTimeout(()=>r(false),3e3))]);if(!dead){child.kill("SIGKILL");await once3(child,"exit")}}function processCommand(pid){try{if(process.platform==="win32"){return execFileSync3("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:true}).trim()}return execFileSync3("ps",["-p",String(pid),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return void 0}}function pidAlive2(pid){try{process.kill(pid,0);return true}catch{return false}}function isLiveOpencodeServe(pid){if(!Number.isInteger(pid)||pid<=0||!pidAlive2(pid))return false;const cmd=processCommand(pid);if(!cmd)return pidAlive2(pid);return/\bserve\b/.test(cmd)&&(/(?:^|[\\/\s])opencode(?:\.exe)?(?:\s|$)/i.test(cmd)||/--hostname\s+127\.0\.0\.1\b/.test(cmd)&&/--port\s+\d+\b/.test(cmd))}async function launch(tuiArgv,serveEnv){const port=process.env.COTAL_OPENCODE_PORT?.trim()||String(await freePort());const url=`http://127.0.0.1:${port}`;const name=process.env.COTAL_NAME?.trim()||"agent";const dataRoot=process.env.COTAL_OPENCODE_HOME?.trim();if(!dataRoot)throw new Error("COTAL_OPENCODE_HOME is not set \u2014 the connector must pin the agent's data root");const agentHome=join3(dataRoot,".cotal","opencode",name);const dbPath=join3(agentHome,"opencode.db");const claim=acquireLock(join3(agentHome,"launch.lock"),{waitMs:0,label:`agent "${name}"'s launch`,onTimeout:owner=>new Error(`agent "${name}" is already running (launcher pid ${owner.pid}) \u2014 kill it first`)});process.on("exit",()=>claim.release());let records=[];try{records=readdirSync(agentHome).filter(file=>/^serve(?:\.[0-9a-f]{32})?\.pid$/.test(file))}catch(e){if(e.code!=="ENOENT")throw e}for(const file of records){const record=join3(agentHome,file);let recorded;try{try{recorded=readFileSync2(record,"utf8")}catch(e){if(e.code!=="EISDIR")throw e;rmdirSync(record)}}catch(e){if(e.code!=="ENOENT")throw e}if(recorded===void 0)continue;const pid=Number(recorded);if(isLiveOpencodeServe(pid))throw new Error(`agent "${name}" is already running (opencode serve pid ${pid}) \u2014 kill it first`);rmSync3(record,{force:true})}let versionRaw="";try{versionRaw=execFileSync3(BIN,["--version"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:true}).trim()}catch(error){const stderr=String(error.stderr??"").trim();process.stderr.write(`[cotal-connector] OpenCode version probe failed${stderr?`: ${stderr.split(/\r?\n/).slice(-2).join(" | ")}`:""}
|
|
4
|
+
`);process.exit(1)}const line=opencodeLine(versionRaw,BIN);mkdirSync3(agentHome,{recursive:true});if(process.env[FORK_FILE_ENV]!==void 0||process.env[FORK_REVISION_ENV]!==void 0){if(!process.env[FORK_FILE_ENV]||!process.env[FORK_REVISION_ENV]||process.platform!=="linux"||!qualifiedOpenCode2Version(versionRaw))throw new Error("approved OpenCode forks require a qualified OpenCode 2.x build and a local snapshot");try{if(["-wal","-shm","-journal"].some(suffix=>lstatSync2(dbPath+suffix,{throwIfNoEntry:false})))throw new Error;closeSync2(openSync2(dbPath,"wx",384))}catch{throw new Error("approved OpenCode forks require a fresh private database in the destination seat")}}const launchToken=randomBytes4(16).toString("hex");const pidFile=join3(agentHome,`serve.${launchToken}.pid`);const bootLog=join3(agentHome,`boot.${launchToken}.log`);const bootFd=openPrivateAppend(bootLog);process.on("exit",()=>closeSync2(bootFd));const bootOutput=d=>{writeFileSync2(bootFd,d);process.stderr.write(d)};bootOutput(`OpenCode boot log: ${bootLog}
|
|
5
|
+
`);const serveArgv=[BIN,"serve","--hostname","127.0.0.1","--port",port];const[serveCommand,...serveArgs]=process.platform==="win32"?serveArgv:["/bin/sh","-c",RECORD_THEN_EXEC,"cotal-serve",pidFile,...serveArgv];const tuiControl=process.env.COTAL_SERVE_HEADLESS?.trim()==="1"?void 0:mintTuiEndpoint();const serve=spawn2(serveCommand,serveArgs,{env:{...process.env,...serveEnv?.(agentHome),COTAL_OPENCODE_SERVER_URL:url,COTAL_OPENCODE_LINE:String(line),COTAL_OPENCODE_VERSION:versionRaw,OPENCODE_SERVER_USERNAME:USERNAME,OPENCODE_SERVER_PASSWORD:SECRET,OPENCODE_DB:dbPath,...tuiControl?{[TUI_SOCKET_ENV]:tuiControl.path,[TUI_TOKEN_ENV]:tuiControl.token}:{}},stdio:["ignore","pipe","pipe"],windowsHide:true});if(process.platform==="win32")writeFileSync2(pidFile,String(serve.pid));serve.on("exit",()=>rmSync3(pidFile,{force:true}));let tui;let stopping=false;for(const sig of["SIGINT","SIGTERM"])process.on(sig,()=>{stopping=true;void terminate(serve);if(tui)void terminate(tui);viewer?.close()});let sessionId;let attached=false;let onSession;let connectorLine;let lastOutput="";const scanner=()=>{const decoder=new StringDecoder("utf8");let partial="";return d=>{if(!attached){lastOutput=(lastOutput+d.toString()).slice(-4e3);bootOutput(d)}if(sessionId)return;const lines=(partial+decoder.write(d)).split("\n");partial=lines.pop()??"";for(const line2 of lines){const session=/\[cotal-session\] (\S+)/.exec(line2);if(session){sessionId=session[1];connectorLine=void 0;onSession?.(sessionId);return}const message=/^\[cotal-connector\] (.+)$/.exec(line2.trimEnd());if(message)connectorLine=message[1]}}};serve.stdout?.on("data",scanner());serve.stderr?.on("data",scanner());let bootFailed=false;let viewer;serve.on("close",(code,signal)=>{if(attached){void(viewer?viewer.detach():Promise.resolve(true)).finally(()=>{viewer?.close();process.exit(code||(signal?1:0))});return}if(!bootFailed&&!stopping)bootOutput(`[cotal-connector] OpenCode exited before its Cotal session was ready (code ${code??signal}); boot log: ${bootLog}. `+(connectorLine?`Last connector message: ${connectorLine}. `:"")+(lastOutput.trim()?`Last output: ${lastOutput.trim().split(/\r?\n/).slice(-2).join(" | ")}
|
|
6
|
+
`:"\n"));process.exit(bootFailed?1:code||(signal||!sessionId&&!stopping?1:0))});const auth=`Basic ${Buffer.from(`${USERNAME}:${SECRET}`).toString("base64")}`;const pokePath=line===2?"/api/config":"/session";const bootDeadline=Date.now()+OPENCODE_BOOT_TIMEOUT_MS;void(async()=>{while(Date.now()<bootDeadline&&!sessionId&&!bootFailed&&!stopping){try{await fetch(`${url}${pokePath}`,{headers:{authorization:auth},signal:AbortSignal.timeout(1500)})}catch{}await new Promise(r=>setTimeout(r,200))}})();const id=await new Promise(resolve3=>{if(sessionId)return resolve3(sessionId);const timer=setTimeout(()=>resolve3(sessionId),Math.max(0,bootDeadline-Date.now()));onSession=id2=>{clearTimeout(timer);resolve3(id2)}});if(!id){bootFailed=true;bootOutput(`[cotal-connector] OpenCode session not ready after ${OPENCODE_BOOT_TIMEOUT_MS/1e3}s: first-run dependencies or plugin/mesh setup did not finish. Check the retained boot log, then launch again.
|
|
7
|
+
`);await terminate(serve);return}if(!tuiControl){process.stdout.write(`[cotal-serve] ${JSON.stringify({port:Number(port),session:id})}
|
|
8
|
+
`);return}attached=true;viewer=runAttachedViewer({endpoint:tuiControl,tuiArgv,url,session:id,line,dbPath,stopping:()=>stopping,onGone:(code,signal)=>void terminate(serve).then(()=>{viewer?.close();process.exit(code===null?1:code||(signal?1:0))})})}function runAttachedViewer(input){const env={...process.env,OPENCODE_SERVER_USERNAME:USERNAME,OPENCODE_SERVER_PASSWORD:SECRET,OPENCODE_DB:input.dbPath};delete env.OPENCODE_CONFIG_CONTENT;for(const k of Object.keys(env))if(k.startsWith("COTAL_"))delete env[k];const tui=startTuiControl({endpoint:input.endpoint,argv:session=>input.tuiArgv({url:input.url,session,line:input.line}),env,stopping:input.stopping,onUnexpectedExit:(code,signal)=>input.onGone(code,signal)});tui.attach(input.session);return tui}launch(({url,session,line})=>line===2?[BIN,"--server",url,"--session",session]:[BIN,"attach",url,"--session",session]).catch(error=>{process.stderr.write(`[cotal-connector] ${error instanceof Error?error.message:String(error)}
|
|
8
9
|
`);process.exit(1)});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** The shape the manager's `readSessionStatePath` parses (version 1 only). */
|
|
2
|
+
export interface SessionState {
|
|
3
|
+
version: 1;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
status: "running" | "quit";
|
|
6
|
+
}
|
|
7
|
+
/** Read `COTAL_OPENCODE_SESSION_STATE`; undefined when this launch carries none (no lifecycle uid). */
|
|
8
|
+
export declare function sessionStatePathFromEnv(env?: NodeJS.ProcessEnv): string | undefined;
|
|
9
|
+
/** Persist the session state atomically (0600, atomic rename). Throws on a failed write. */
|
|
10
|
+
export declare function persistSessionState(path: string | undefined, sessionId: string, status: SessionState["status"]): void;
|
|
11
|
+
/** Mint the launch's per-lifecycle session-state path and prepare it:
|
|
12
|
+
* `<workspaceRoot>/.cotal/opencode-sessions/<name>-<lifecycleUid>.json`. Undefined when the
|
|
13
|
+
* launch carries no lifecycle uid (a standalone `cotal spawn` has no supervisor to prove anything
|
|
14
|
+
* to). A stale file from a previous run of this lifecycle is REMOVED here, before the child
|
|
15
|
+
* starts, so the new process is the only writer and a reader between builds never sees a dead
|
|
16
|
+
* seat's session as current. `validateOnly` writes nothing and keeps any existing file. Returns
|
|
17
|
+
* the path for the LaunchSpec; the caller sets the env carrier once it knows the launch runs. */
|
|
18
|
+
export declare function mintSessionStatePath(env: Record<string, string>, opts: {
|
|
19
|
+
name: string;
|
|
20
|
+
workspaceRoot?: string;
|
|
21
|
+
lifecycleUid?: string;
|
|
22
|
+
validateOnly?: boolean;
|
|
23
|
+
}): string | undefined;
|
|
24
|
+
/** A failed quit-persist must never break the exit path; it is logged and the stop goes on. */
|
|
25
|
+
export declare function logFailedPersist(log: (line: string) => void, e: unknown, at: string): void;
|
|
26
|
+
/** The launch's continuation target, read once at boot from the env the connector set.
|
|
27
|
+
* A key that is present is a request, even when its value is empty or whitespace: that is a
|
|
28
|
+
* refusal, not a plain launch. */
|
|
29
|
+
export declare function continuationTargetFromEnv(env?: NodeJS.ProcessEnv): {
|
|
30
|
+
continueSession: string;
|
|
31
|
+
} | {
|
|
32
|
+
reopenSession: string;
|
|
33
|
+
} | undefined;
|
|
34
|
+
/** Validate an exact-session id the connector was asked to continue or reopen. Refuses an id a
|
|
35
|
+
* URL path segment cannot carry honestly: empty, or carrying control characters. */
|
|
36
|
+
export declare function assertSessionIdField(value: string | undefined, field: string): void;
|
|
37
|
+
/** The whole launch-side validation of a continued/reopened launch: one launch, one
|
|
38
|
+
* session, mutually exclusive with `resume` (a fork of a FOREIGN transcript is a different
|
|
39
|
+
* operation than continuing THIS seat's own session) and never carrying a boot prompt (the
|
|
40
|
+
* session already exists and its first turn ran, so re-submitting it would replay the kickoff).
|
|
41
|
+
* Refused here, before anything is provisioned, so a bad id or a hand-written launch answers
|
|
42
|
+
* with a sentence instead of a half-built seat. */
|
|
43
|
+
export declare function assertContinuationLaunch(opts: {
|
|
44
|
+
continueSession?: string;
|
|
45
|
+
reopenSession?: string;
|
|
46
|
+
resume?: string;
|
|
47
|
+
prompt?: string;
|
|
48
|
+
}): void;
|
|
49
|
+
/** GET a session by id. Returns `undefined` on 404 (the session is gone). Throws on other failures. */
|
|
50
|
+
export declare function lookupSession<T>(get: (path: string) => Promise<T>, sessionPath: (id: string) => string, id: string): Promise<T | undefined>;
|
|
51
|
+
/** Resolve the session this launch must run. Both `continueSession` and `reopenSession` require a
|
|
52
|
+
* successful GET whose body names that id. A missing, malformed, or different id is a refusal.
|
|
53
|
+
* Nothing is created: a fresh id would be a different session from the one the manager asked for,
|
|
54
|
+
* and the manager's proof would only notice after the replacement had already started. */
|
|
55
|
+
export declare function resolveContinuation<T extends {
|
|
56
|
+
id?: string;
|
|
57
|
+
}>(target: {
|
|
58
|
+
continueSession: string;
|
|
59
|
+
} | {
|
|
60
|
+
reopenSession: string;
|
|
61
|
+
}, lookup: (id: string) => Promise<T | undefined>): Promise<T>;
|
|
62
|
+
/** The 1.x plugin's whole session-resolution step: the plain launch creates its session; a
|
|
63
|
+
* continued/reopened launch resolves through {@link resolveContinuation} over `GET /session/:id`
|
|
64
|
+
* and creates nothing. A reply that does not name the requested id is not a match. */
|
|
65
|
+
export declare function resolve1xSession(api: <T>(path: string, init?: RequestInit, timeoutMs?: number) => Promise<T>, title: string): Promise<{
|
|
66
|
+
id?: string;
|
|
67
|
+
reason?: "continued launch";
|
|
68
|
+
}>;
|
|
69
|
+
/** The managed-session promise both plugin lines share: await the mesh, resolve the
|
|
70
|
+
* session (plain create or continuation), persist the state file, THEN let the line adopt it,
|
|
71
|
+
* and write the `[cotal-session]` handshake line LAST. The id is not visible to `onSession` or
|
|
72
|
+
* `quiesce` until the running checkpoint has landed, and a resolve that returns after teardown
|
|
73
|
+
* has begun writes nothing. A failure is logged and `fail` runs: a seat with no checkpoint must
|
|
74
|
+
* not stay up. */
|
|
75
|
+
export declare function resolveManagedSession<S>(opts: {
|
|
76
|
+
meshReady: Promise<unknown>;
|
|
77
|
+
aborted(): boolean;
|
|
78
|
+
resolve(): Promise<S>;
|
|
79
|
+
adopt(session: S): void;
|
|
80
|
+
sessionReady(): string | undefined;
|
|
81
|
+
statePath: string | undefined;
|
|
82
|
+
log(line: string): void;
|
|
83
|
+
fail(reason: string): void;
|
|
84
|
+
}): () => Promise<string | undefined>;
|
|
85
|
+
//# sourceMappingURL=session-continuation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-continuation.d.ts","sourceRoot":"","sources":["../src/session-continuation.ts"],"names":[],"mappings":"AAsBA,8EAA8E;AAC9E,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,CAAC,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC;CAC5B;AAED,uGAAuG;AACvG,wBAAgB,uBAAuB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,GAAG,SAAS,CAGhG;AAED,4FAA4F;AAC5F,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,QAAQ,CAAC,GAAG,IAAI,CAIrH;AAED;;;;;;kGAMkG;AAClG,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC3B,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,YA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,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,GAC7C,OAAO,CAAC,CAAC,CAAC,CAOZ;AAED;;uFAEuF;AACvF,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EAC5E,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAC,CAcvD;AAED;;;;;mBAKmB;AACnB,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,IAAI,EAAE;IAC7C,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5B,OAAO,IAAI,OAAO,CAAC;IACnB,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;IACtB,KAAK,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC;IACxB,YAAY,IAAI,MAAM,GAAG,SAAS,CAAC;IACnC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,GAAG,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAwBpC"}
|
package/dist/settled-models.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** An empty plugin list means the location is still loading. */
|
|
2
|
+
export declare function awaitOpenCode2Plugins(read: (path: string) => Promise<unknown>, signal: AbortSignal): Promise<void>;
|
|
1
3
|
/**
|
|
2
4
|
* Reads an OpenCode 2.x server's model list once the server's plugins have loaded, and returns the
|
|
3
5
|
* reply's `data`. Until then `GET /api/model` answers 200 with an empty or partial list (measured on
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settled-models.d.ts","sourceRoot":"","sources":["../src/settled-models.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"settled-models.d.ts","sourceRoot":"","sources":["../src/settled-models.ts"],"names":[],"mappings":"AAWA,gEAAgE;AAChE,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAGxH;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAsBvH"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenCode connector's cooperative sleep gate: the shared `quiesce`/`unquiesce`
|
|
3
|
+
* control-op bodies both plugin lines use (`plugin.ts` for 1.x, `plugin2.ts` for 2.x), so the two
|
|
4
|
+
* cannot drift on what a refusal means, the way connector-core's control ops and the Pi driver
|
|
5
|
+
* established the shape.
|
|
6
|
+
*
|
|
7
|
+
* THE REFUSAL ORDER, and why each step sits where it does:
|
|
8
|
+
* 1. A seat that has begun its teardown REFUSES FIRST, before the already-quiesced fast path, so
|
|
9
|
+
* a late frame can never rewrite a `quit` session-state marker back to `running`.
|
|
10
|
+
* 2. An already-quiesced seat answers read-only (`{ok:true,sessionId}`), with no second write of
|
|
11
|
+
* the state file. The gate is already held and the id already proven.
|
|
12
|
+
* 3. A held workflow turn or an in-flight turn pull refuses. A trapped turn under a gated seat has
|
|
13
|
+
* no yield path until `unquiesce`, which a refusal never triggers.
|
|
14
|
+
* 4. The seat-local in-flight checks (turn, batch, submission, command, ask, boot prompt, a native
|
|
15
|
+
* hook still inside its await) refuse and leave the seat live.
|
|
16
|
+
* 5. The attached TUI is detached, then the native server is asked whether the session is idle.
|
|
17
|
+
* Local state alone can return success after a prompt was admitted and before the busy event.
|
|
18
|
+
* 6. Every local check is read again. A refusal reattaches the TUI and leaves the gate down.
|
|
19
|
+
* 7. The session state is PERSISTED BEFORE the gate rises, so a failed write answers `{ok:false}`
|
|
20
|
+
* with the gate down.
|
|
21
|
+
*/
|
|
22
|
+
import { startControlServer, type MeshAgent, type QuiesceReply, type UnquiesceReply } from "@cotal-ai/connector-core";
|
|
23
|
+
import type { ControlEndpoint } from "@cotal-ai/core";
|
|
24
|
+
import { type TuiControlOp } from "./tui-control.js";
|
|
25
|
+
/** What a plugin line reports about its own in-flight work. */
|
|
26
|
+
export interface QuiesceSeatState {
|
|
27
|
+
/** The OpenCode session id, undefined when the session is not ready yet. */
|
|
28
|
+
sessionId(): string | undefined;
|
|
29
|
+
/** A sentence for a turn, batch, submission, command, ask or boot prompt still in flight. */
|
|
30
|
+
inFlight(): string | undefined;
|
|
31
|
+
/** True while a native prompt or command hook is inside its own await. */
|
|
32
|
+
nativeHook(): boolean;
|
|
33
|
+
/** The server's own view, after the TUI is gone. False means the server did not confirm idle. */
|
|
34
|
+
confirmIdle(sessionId: string): Promise<boolean>;
|
|
35
|
+
/** Ask the launcher to take the TUI off, or put it back. Absent on a headless launch. */
|
|
36
|
+
tui?: {
|
|
37
|
+
call(op: TuiControlOp, sessionId: string): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
/** Held true from the first idle check until the gate is up or the refusal is answered. */
|
|
40
|
+
quiescing?: {
|
|
41
|
+
value: boolean;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** The in-flight refusal sentence for a line whose "busy" is one boolean per source. First true
|
|
45
|
+
* reason wins. Undefined when all idle. */
|
|
46
|
+
export declare function reasonWhenInFlight(agent: MeshAgent, sources: {
|
|
47
|
+
turnOrBatch: boolean;
|
|
48
|
+
submitting: boolean;
|
|
49
|
+
bootPending: boolean;
|
|
50
|
+
nativeHook?: boolean;
|
|
51
|
+
}): string | undefined;
|
|
52
|
+
/** The `onQuiesce` body both plugin lines share. See the module note for the ordering. `stopping`
|
|
53
|
+
* is a live read: teardown can begin while the gate is between two awaits (the TUI detach, the
|
|
54
|
+
* server's idle answer), and a value captured before those awaits would let `finishQuiesce` write
|
|
55
|
+
* `status:"running"` over a quit already recorded and latch a seat that is going away. */
|
|
56
|
+
export declare function quiesceSeat(agent: MeshAgent, stopping: () => boolean, seat: QuiesceSeatState, statePath: string | undefined, quiescing?: {
|
|
57
|
+
promise?: Promise<QuiesceReply>;
|
|
58
|
+
}): QuiesceReply | Promise<QuiesceReply>;
|
|
59
|
+
/** The `onUnquiesce` body both plugin lines share. A wake that races a quiesce still in flight is
|
|
60
|
+
* refused. Otherwise the gate lifts, the TUI comes back, and whatever waited is dispatched. The
|
|
61
|
+
* stopping check is a live read on both sides of every await, for the same reason as quiesce. */
|
|
62
|
+
export declare function unquiesceSeat(agent: MeshAgent, stopping: () => boolean, seat: QuiesceSeatState, dispatch: () => void): Promise<UnquiesceReply>;
|
|
63
|
+
/** The final `status:"quit"` write at teardown. Best-effort: a failed write is logged and the
|
|
64
|
+
* stop goes on, because the next launch checks the recorded id against the live store. */
|
|
65
|
+
export declare function persistQuitState(statePath: string | undefined, sessionId: string | undefined, log: (line: string) => void): void;
|
|
66
|
+
/** The authenticated control server a sleep-gated line serves. The hook-frame handle stays a
|
|
67
|
+
* refusal because both lines serve hooks in-process. */
|
|
68
|
+
export declare function startSleepControl(agent: MeshAgent, control: ControlEndpoint, opts: {
|
|
69
|
+
statePath: string | undefined;
|
|
70
|
+
forkSource?: (request: unknown, signal: AbortSignal) => Promise<Record<string, unknown>>;
|
|
71
|
+
stopping(): boolean;
|
|
72
|
+
shutdown(): void;
|
|
73
|
+
seat: QuiesceSeatState;
|
|
74
|
+
wake(): void;
|
|
75
|
+
}): ReturnType<typeof startControlServer>;
|
|
76
|
+
/** The seat's TUI caller, when the launch published one. A missing endpoint is a headless launch. */
|
|
77
|
+
export declare function tuiCaller(endpoint: ControlEndpoint | undefined): QuiesceSeatState["tui"];
|
|
78
|
+
//# sourceMappingURL=sleep-gate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sleep-gate.d.ts","sourceRoot":"","sources":["../src/sleep-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,kBAAkB,EAAE,KAAK,SAAS,EAAE,KAAK,YAAY,EAAE,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AACtH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAErE,+DAA+D;AAC/D,MAAM,WAAW,gBAAgB;IAC/B,4EAA4E;IAC5E,SAAS,IAAI,MAAM,GAAG,SAAS,CAAC;IAChC,6FAA6F;IAC7F,QAAQ,IAAI,MAAM,GAAG,SAAS,CAAC;IAC/B,0EAA0E;IAC1E,UAAU,IAAI,OAAO,CAAC;IACtB,iGAAiG;IACjG,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACjD,yFAAyF;IACzF,GAAG,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,CAAC;IACnE,2FAA2F;IAC3F,SAAS,CAAC,EAAE;QAAE,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;CAChC;AAED;4CAC4C;AAC5C,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAChB,OAAO,EAAE;IAAE,WAAW,EAAE,OAAO,CAAC;IAAC,UAAU,EAAE,OAAO,CAAC;IAAC,WAAW,EAAE,OAAO,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,GACjG,MAAM,GAAG,SAAS,CAQpB;AAgBD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}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The foreground TUI a non-headless OpenCode launch attaches, owned so a sleep can take it off
|
|
3
|
+
* the session and put it back. The launcher process holds the child. The plugin, inside
|
|
4
|
+
* `opencode serve`, asks it to detach and attach over an authenticated socket that uses the same
|
|
5
|
+
* control exchange as the manager's control plane (`@cotal-ai/core`'s `control-exchange`).
|
|
6
|
+
*
|
|
7
|
+
* A detach must finish before quiesce trusts the server's idle answer: the TUI is the one native
|
|
8
|
+
* writer this connector starts, and a prompt it has already typed stays in flight until the
|
|
9
|
+
* process is gone. An unexpected exit still tears the server down. A detach's exit does not.
|
|
10
|
+
*/
|
|
11
|
+
import { type ChildProcess } from "node:child_process";
|
|
12
|
+
import { type Server } from "node:net";
|
|
13
|
+
import { type ControlEndpoint } from "@cotal-ai/core/control-exchange";
|
|
14
|
+
/** What the launcher tells the plugin, and what the plugin sends back. */
|
|
15
|
+
export declare const TUI_SOCKET_ENV = "COTAL_OPENCODE_TUI_SOCKET";
|
|
16
|
+
export declare const TUI_TOKEN_ENV = "COTAL_OPENCODE_TUI_TOKEN";
|
|
17
|
+
/** One line both ends agree on. `detach` reaps the child. `attach` starts it on `session`. */
|
|
18
|
+
export type TuiControlOp = "detach" | "attach";
|
|
19
|
+
/** The socket the launcher binds and the plugin dials. Undefined in headless mode. */
|
|
20
|
+
export declare function mintTuiEndpoint(): ControlEndpoint;
|
|
21
|
+
/** Put the endpoint on the server's env and drop it from a viewer env. The token never reaches argv. */
|
|
22
|
+
export declare function publishTuiEndpoint(env: NodeJS.ProcessEnv, endpoint: ControlEndpoint): void;
|
|
23
|
+
/** Remove the endpoint from an env once the plugin has read it. The launcher keeps its own copy. */
|
|
24
|
+
export declare function scrubTuiEndpoint(env?: NodeJS.ProcessEnv): void;
|
|
25
|
+
/** The endpoint the plugin inherited, or undefined when this launch attached no TUI. */
|
|
26
|
+
export declare function tuiEndpointFromEnv(env?: NodeJS.ProcessEnv): ControlEndpoint | undefined;
|
|
27
|
+
/** Ask the launcher to detach or reattach. Throws when the launcher refuses or does not answer. */
|
|
28
|
+
export declare function callTuiControl(endpoint: ControlEndpoint, op: TuiControlOp, session?: string): Promise<void>;
|
|
29
|
+
/** SIGTERM, then SIGKILL, resolving once the child has exited. A child that has already exited resolves at once. */
|
|
30
|
+
export declare function reapChild(child: ChildProcess, graceMs?: number): Promise<void>;
|
|
31
|
+
/** What the launcher uses to start the viewer and to notice it leave. */
|
|
32
|
+
export interface TuiControlHost {
|
|
33
|
+
endpoint: ControlEndpoint;
|
|
34
|
+
/** Build the viewer's argv for the session it should open. */
|
|
35
|
+
argv(session: string): [command: string, ...args: string[]];
|
|
36
|
+
env: NodeJS.ProcessEnv;
|
|
37
|
+
/** An exit the operator caused (not a sleep detach) tears the seat down. */
|
|
38
|
+
onUnexpectedExit(code: number | null, signal: NodeJS.Signals | null): void;
|
|
39
|
+
stopping(): boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Own the one TUI this launch starts. `start` attaches the first viewer. Later attaches replace
|
|
43
|
+
* it. `detach` reaps it and remembers that the exit was asked for, so the seat stays up.
|
|
44
|
+
*/
|
|
45
|
+
export declare function startTuiControl(host: TuiControlHost): {
|
|
46
|
+
server: Server;
|
|
47
|
+
attach(session: string): void;
|
|
48
|
+
detach(): Promise<boolean>;
|
|
49
|
+
close(): void;
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=tui-control.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tui-control.d.ts","sourceRoot":"","sources":["../src/tui-control.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAG9D,OAAO,EAAgB,KAAK,MAAM,EAAe,MAAM,UAAU,CAAC;AAIlE,OAAO,EAIL,KAAK,eAAe,EACrB,MAAM,iCAAiC,CAAC;AAMzC,0EAA0E;AAC1E,eA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AI,EAAE,cAAc,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAAC,KAAK,IAAI,IAAI,CAAA;CAAE,CAwElJ"}
|
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.193.0",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -21,10 +21,11 @@
|
|
|
21
21
|
"@cotal-ai/core": ">=0.1.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@cotal-ai/auth": "0.
|
|
25
|
-
"@cotal-ai/connector-core": "0.
|
|
26
|
-
"@cotal-ai/core": "0.
|
|
24
|
+
"@cotal-ai/auth": "0.193.0",
|
|
25
|
+
"@cotal-ai/connector-core": "0.193.0",
|
|
26
|
+
"@cotal-ai/core": "0.193.0",
|
|
27
27
|
"@cotal-ai/smoke-kit": "0.0.0",
|
|
28
|
+
"@nats-io/jetstream": "3.4.0",
|
|
28
29
|
"@nats-io/transport-node": "3.4.0",
|
|
29
30
|
"@opencode-ai/plugin": "^1.16.2",
|
|
30
31
|
"esbuild": "^0.28.0",
|