@cotal-ai/connector-opencode 0.181.0 → 0.182.1
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 +7 -9
- package/dist/agui-map2.d.ts.map +1 -1
- package/dist/agui-source.d.ts.map +1 -1
- package/dist/agui-source2.d.ts +5 -9
- package/dist/agui-source2.d.ts.map +1 -1
- package/dist/extension.d.ts.map +1 -1
- package/dist/index.js +8 -8
- package/dist/launch.js +2 -2
- package/dist/plugin/docs-bundle.bin +0 -0
- package/dist/plugin/docs-index.bin +0 -0
- package/dist/plugin/index.js +21 -21
- package/dist/plugin.d.ts.map +1 -1
- package/dist/serve.js +2 -2
- package/dist/stream1.d.ts +1 -1
- package/dist/stream2.d.ts +5 -20
- package/dist/stream2.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/plugin.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAuEA,OAAO,KAAK,EAAE,MAAM,EAAyB,MAAM,qBAAqB,CAAC;AAezE,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,mBAAmB,CAAC;AAW3B,eAAO,MAAM,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAuEA,OAAO,KAAK,EAAE,MAAM,EAAyB,MAAM,qBAAqB,CAAC;AAezE,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,mBAAmB,CAAC;AAW3B,eAAO,MAAM,KAAK,EAAE,MAq1CnB,CAAC"}
|
package/dist/serve.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{execFileSync as execFileSync2,spawn}from"node:child_process";import{once as once2}from"node:events";import{randomBytes as randomBytes2}from"node:crypto";import{accessSync,closeSync as closeSync2,constants as constants2,mkdirSync as mkdirSync3,readdirSync,readFileSync as readFileSync2,rmdirSync,rmSync as rmSync2,statSync as statSync2,writeFileSync as writeFileSync2}from"node:fs";import{delimiter,isAbsolute,join,resolve}from"node:path";import{StringDecoder}from"node:string_decoder";import{execFileSync}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}from"node:path";import{chmodSync,closeSync,constants,fchmodSync,fstatSync,ftruncateSync,linkSync,lstatSync,mkdirSync,openSync,renameSync,unlinkSync,writeFileSync}from"node:fs";var isWin=process.platform==="win32";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 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=execFileSync("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(dirname(path),{recursive:true,mode:448});const nonce=randomBytes(12).toString("hex");const owner={pid:process.pid,start:processStartToken(process.pid),nonce,ts:Date.now(),...opts.label?{label:opts.label}:{}};return{path,nonce,content:`${JSON.stringify(owner)}
|
|
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===nonce){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`)}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}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[join(dir,"opencode.exe"),join(dir,"node_modules","opencode-ai","bin","opencode.exe")]){if(executableFile(exe))return resolve(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||randomBytes2(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([once2(child,"exit").then(()=>true),new Promise(r=>setTimeout(()=>r(false),3e3))]);if(!dead){child.kill("SIGKILL");await once2(child,"exit")}}function processCommand(pid){try{if(process.platform==="win32"){return execFileSync2("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}return execFileSync2("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=join(dataRoot,".cotal","opencode",name);const dbPath=join(agentHome,"opencode.db");const claim=acquireLock(join(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=join(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`);rmSync2(record,{force:true})}let versionRaw;try{versionRaw=execFileSync2(BIN,["--version"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).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(" | ")}`:""}
|
|
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===nonce){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`)}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}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[join(dir,"opencode.exe"),join(dir,"node_modules","opencode-ai","bin","opencode.exe")]){if(executableFile(exe))return resolve(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||randomBytes2(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([once2(child,"exit").then(()=>true),new Promise(r=>setTimeout(()=>r(false),3e3))]);if(!dead){child.kill("SIGKILL");await once2(child,"exit")}}function processCommand(pid){try{if(process.platform==="win32"){return execFileSync2("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:true}).trim()}return execFileSync2("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=join(dataRoot,".cotal","opencode",name);const dbPath=join(agentHome,"opencode.db");const claim=acquireLock(join(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=join(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`);rmSync2(record,{force:true})}let versionRaw;try{versionRaw=execFileSync2(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(" | ")}`:""}
|
|
3
3
|
`);process.exit(1)}const line=opencodeLine(versionRaw,BIN);mkdirSync3(agentHome,{recursive:true});const launchToken=randomBytes2(16).toString("hex");const pidFile=join(agentHome,`serve.${launchToken}.pid`);const bootLog=join(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}
|
|
4
|
-
`);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 serve=spawn(serveCommand,serveArgs,{env:{...process.env,...serveEnv?.(agentHome),COTAL_OPENCODE_SERVER_URL:url,COTAL_OPENCODE_LINE:String(line),OPENCODE_SERVER_USERNAME:USERNAME,OPENCODE_SERVER_PASSWORD:SECRET,OPENCODE_DB:dbPath},stdio:["ignore","pipe","pipe"]});if(process.platform==="win32")writeFileSync2(pidFile,String(serve.pid));serve.on("exit",()=>rmSync2(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)});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;serve.on("close",(code,signal)=>{if(!attached){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(" | ")}
|
|
4
|
+
`);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 serve=spawn(serveCommand,serveArgs,{env:{...process.env,...serveEnv?.(agentHome),COTAL_OPENCODE_SERVER_URL:url,COTAL_OPENCODE_LINE:String(line),OPENCODE_SERVER_USERNAME:USERNAME,OPENCODE_SERVER_PASSWORD:SECRET,OPENCODE_DB:dbPath},stdio:["ignore","pipe","pipe"],windowsHide:true});if(process.platform==="win32")writeFileSync2(pidFile,String(serve.pid));serve.on("exit",()=>rmSync2(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)});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;serve.on("close",(code,signal)=>{if(!attached){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(" | ")}
|
|
5
5
|
`:"\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(resolve2=>{if(sessionId)return resolve2(sessionId);const timer=setTimeout(()=>resolve2(sessionId),Math.max(0,bootDeadline-Date.now()));onSession=id2=>{clearTimeout(timer);resolve2(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.
|
|
6
6
|
`);await terminate(serve);return}if(process.env.COTAL_SERVE_HEADLESS?.trim()==="1"){process.stdout.write(`[cotal-serve] ${JSON.stringify({port:Number(port),session:id})}
|
|
7
7
|
`);return}const tuiEnv={...process.env,OPENCODE_SERVER_USERNAME:USERNAME,OPENCODE_SERVER_PASSWORD:SECRET,OPENCODE_DB:dbPath};delete tuiEnv.OPENCODE_CONFIG_CONTENT;for(const k of Object.keys(tuiEnv))if(k.startsWith("COTAL_"))delete tuiEnv[k];attached=true;const[command,...args]=tuiArgv({url,session:id,line});tui=spawn(command,args,{env:tuiEnv,stdio:"inherit"});serve.on("exit",()=>void terminate(tui));tui.on("exit",(code,signal)=>{void terminate(serve).then(()=>process.exit(code??(signal?1:0)))})}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)}
|
package/dist/stream1.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* each part streams under a key of its own id and its own saved record closes the stream.
|
|
6
6
|
*
|
|
7
7
|
* **A line is anchored at the start of the streaming part's message**, the `<message>:<message>`
|
|
8
|
-
*
|
|
8
|
+
* cursor of its assistant header. The session store holds the
|
|
9
9
|
* part from its first delta, so the store's end would place every line after the part, where its
|
|
10
10
|
* saved record has already closed the stream. The merged source places a line before the first
|
|
11
11
|
* record after its anchor, or where its read starts when it has read past it, so the text arrives
|
package/dist/stream2.d.ts
CHANGED
|
@@ -6,11 +6,8 @@
|
|
|
6
6
|
* 2.0.24). So an element streams under a key of its message, kind and ordinal, and the mapper finds
|
|
7
7
|
* the same key from the element's position when its saved record arrives.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* until the step ends. That record is read when the step starts; until it answers, a line takes the
|
|
12
|
-
* furthest position a read of the session has reached, which is never past it. Either way the
|
|
13
|
-
* records before the step come before the line and the step's saved elements after it.
|
|
9
|
+
* A line is anchored at the step's assistant header, before any of its elements and after the
|
|
10
|
+
* prompt that opened the run. Even a delta sent immediately can take that position by message id.
|
|
14
11
|
*/
|
|
15
12
|
import { type DeltaJournalOptions, type StreamDelta } from "@cotal-ai/connector-core";
|
|
16
13
|
/** The key the element of `kind` at `ordinal` among a message's elements of that kind streams under.
|
|
@@ -27,12 +24,6 @@ export interface StreamEvent2 {
|
|
|
27
24
|
delta?: unknown;
|
|
28
25
|
};
|
|
29
26
|
}
|
|
30
|
-
/** What the stream reads of the session's source: the furthest position a read has reached, read
|
|
31
|
-
* synchronously, and the session's last record before a message. */
|
|
32
|
-
interface StreamSource2 {
|
|
33
|
-
readonly reached: string;
|
|
34
|
-
before(messageId: string): Promise<string>;
|
|
35
|
-
}
|
|
36
27
|
export declare class OpenCode2DeltaStream {
|
|
37
28
|
private readonly reasoning;
|
|
38
29
|
private journal;
|
|
@@ -45,15 +36,11 @@ export declare class OpenCode2DeltaStream {
|
|
|
45
36
|
private readonly turn;
|
|
46
37
|
/** The session's end while the turn's end is journaled. */
|
|
47
38
|
private endedAt;
|
|
48
|
-
|
|
49
|
-
private step;
|
|
50
|
-
private session;
|
|
51
|
-
private onError;
|
|
39
|
+
private anchor;
|
|
52
40
|
/** @param reasoning Whether reasoning is published, and so streamed. */
|
|
53
41
|
constructor(reasoning: boolean);
|
|
54
|
-
/** Journal the elements of
|
|
55
|
-
|
|
56
|
-
open(sessionID: string, source: StreamSource2, opts: Omit<DeltaJournalOptions, "anchor">): void;
|
|
42
|
+
/** Journal the elements of this session from now on. A written line wakes the emitter. */
|
|
43
|
+
open(sessionID: string, opts: Omit<DeltaJournalOptions, "anchor">): void;
|
|
57
44
|
/** Follow one event of the session's event stream. */
|
|
58
45
|
event(ev: StreamEvent2): void;
|
|
59
46
|
/**
|
|
@@ -64,7 +51,5 @@ export declare class OpenCode2DeltaStream {
|
|
|
64
51
|
*/
|
|
65
52
|
turnEnded(end: string): void;
|
|
66
53
|
close(): void;
|
|
67
|
-
private stepStarted;
|
|
68
54
|
}
|
|
69
|
-
export {};
|
|
70
55
|
//# sourceMappingURL=stream2.d.ts.map
|
package/dist/stream2.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream2.d.ts","sourceRoot":"","sources":["../src/stream2.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"stream2.d.ts","sourceRoot":"","sources":["../src/stream2.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAgB,KAAK,mBAAmB,EAAE,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGpG;6FAC6F;AAC7F,eAAO,MAAM,UAAU,GAAI,WAAW,MAAM,EAAE,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,KAAG,MAAkD,CAAC;AAE9I,mDAAmD;AACnD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CAClG;AASD,qBAAa,oBAAoB;IAcnB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAbtC,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,QAAQ,CAAY;IAC5B;+FAC2F;IAC3F,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,gEAAgE;IAChE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAC1C,2DAA2D;IAC3D,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,MAAM,CAAM;IAEpB,wEAAwE;gBAC3C,SAAS,EAAE,OAAO;IAE/C,0FAA0F;IAC1F,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,CAAC,GAAG,IAAI;IAOxE,sDAAsD;IACtD,KAAK,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI;IA4B7B;;;;;OAKG;IACH,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAa5B,KAAK,IAAI,IAAI;CAId"}
|
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.182.1",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -21,9 +21,9 @@
|
|
|
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.182.1",
|
|
25
|
+
"@cotal-ai/connector-core": "0.182.1",
|
|
26
|
+
"@cotal-ai/core": "0.182.1",
|
|
27
27
|
"@cotal-ai/smoke-kit": "0.0.0",
|
|
28
28
|
"@nats-io/transport-node": "3.4.0",
|
|
29
29
|
"@opencode-ai/plugin": "^1.16.2",
|