@cotal-ai/connector-opencode 0.192.0 → 0.193.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.
Files changed (55) hide show
  1. package/dist/approved-fork2.d.ts +19 -0
  2. package/dist/approved-fork2.d.ts.map +1 -0
  3. package/dist/catalog2.d.ts +3 -1
  4. package/dist/catalog2.d.ts.map +1 -1
  5. package/dist/commands2.d.ts +3 -0
  6. package/dist/commands2.d.ts.map +1 -1
  7. package/dist/compact2.d.ts +9 -0
  8. package/dist/compact2.d.ts.map +1 -0
  9. package/dist/event-holder.d.ts +21 -0
  10. package/dist/event-holder.d.ts.map +1 -0
  11. package/dist/extension.d.ts.map +1 -1
  12. package/dist/fork-snapshot2.d.ts +4 -0
  13. package/dist/fork-snapshot2.d.ts.map +1 -0
  14. package/dist/fork-source2.d.ts +16 -0
  15. package/dist/fork-source2.d.ts.map +1 -0
  16. package/dist/index.js +4 -39
  17. package/dist/launch-config.d.ts +26 -0
  18. package/dist/launch-config.d.ts.map +1 -0
  19. package/dist/launch.d.ts.map +1 -1
  20. package/dist/launch.js +8 -7
  21. package/dist/model-choices2.d.ts +10 -0
  22. package/dist/model-choices2.d.ts.map +1 -0
  23. package/dist/native-history2.d.ts +9 -0
  24. package/dist/native-history2.d.ts.map +1 -0
  25. package/dist/native-idle.d.ts +30 -0
  26. package/dist/native-idle.d.ts.map +1 -0
  27. package/dist/native-shell-stop2.d.ts +17 -0
  28. package/dist/native-shell-stop2.d.ts.map +1 -0
  29. package/dist/native2.d.ts +8 -2
  30. package/dist/native2.d.ts.map +1 -1
  31. package/dist/opencode-line.d.ts +1 -0
  32. package/dist/opencode-line.d.ts.map +1 -1
  33. package/dist/opencode2-http.d.ts +2 -0
  34. package/dist/opencode2-http.d.ts.map +1 -1
  35. package/dist/opencode2-launch.d.ts +35 -0
  36. package/dist/opencode2-launch.d.ts.map +1 -0
  37. package/dist/opencode2-types.d.ts +5 -1
  38. package/dist/opencode2-types.d.ts.map +1 -1
  39. package/dist/plugin/docs-bundle.bin +0 -0
  40. package/dist/plugin/docs-index.bin +0 -0
  41. package/dist/plugin/index.js +68 -39
  42. package/dist/plugin-body.d.ts +4 -0
  43. package/dist/plugin-body.d.ts.map +1 -0
  44. package/dist/plugin.d.ts.map +1 -1
  45. package/dist/plugin2.d.ts.map +1 -1
  46. package/dist/serve.js +8 -7
  47. package/dist/session-continuation.d.ts +85 -0
  48. package/dist/session-continuation.d.ts.map +1 -0
  49. package/dist/settled-models.d.ts +2 -0
  50. package/dist/settled-models.d.ts.map +1 -1
  51. package/dist/sleep-gate.d.ts +78 -0
  52. package/dist/sleep-gate.d.ts.map +1 -0
  53. package/dist/tui-control.d.ts +51 -0
  54. package/dist/tui-control.d.ts.map +1 -0
  55. package/package.json +5 -4
@@ -0,0 +1,26 @@
1
+ import type { LaunchOpts } from "@cotal-ai/core";
2
+ /** The permission rules of a launch with `askPermissions`. Every tool asks except the ones always
3
+ * allowed and the agent's own `cotal_*` tools. The last matching rule wins, so the catch-all is first. */
4
+ export declare const ASKING_PERMISSION: {
5
+ "*": string;
6
+ question: string;
7
+ read: {
8
+ "*": string;
9
+ "*.env": string;
10
+ "*.env.*": string;
11
+ "*.env.example": string;
12
+ };
13
+ glob: string;
14
+ grep: string;
15
+ lsp: string;
16
+ todowrite: string;
17
+ task: string;
18
+ skill: string;
19
+ "cotal_*": string;
20
+ };
21
+ /** The permission rules a launch runs under. An `askPermissions` launch may not also set `permission`. */
22
+ export declare function launchPermission(opts: LaunchOpts): unknown;
23
+ /** Write the inline OpenCode config and the model env onto `env`. Returns nothing. The plugin
24
+ * reads the config from the env, and the attached TUI inherits the same model. */
25
+ export declare function applyOpenCodeConfig(env: Record<string, string>, opts: LaunchOpts, pluginDir: string): void;
26
+ //# sourceMappingURL=launch-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch-config.d.ts","sourceRoot":"","sources":["../src/launch-config.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAKjD;2GAC2G;AAC3G,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;CAW7B,CAAC;AAEF,0GAA0G;AAC1G,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAK1D;AAED;mFACmF;AACnF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CA8B1G"}
@@ -1 +1 @@
1
- {"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../src/launch.ts"],"names":[],"mappings":"AAmDA,eAAO,MAAM,GAAG,QAAuB,CAAC;AAyFxC;kEACkE;AAClE,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;AAE/G;;0BAE0B;AAC1B,KAAK,QAAQ,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAC,UAAU,CAAC;AAEzD,wBAAsB,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAsOjF"}
1
+ {"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../src/launch.ts"],"names":[],"mappings":"AAsDA,eAAO,MAAM,GAAG,QAAuB,CAAC;AAyFxC;kEACkE;AAClE,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;AAE/G;;0BAE0B;AAC1B,KAAK,QAAQ,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAC,UAAU,CAAC;AAEzD,wBAAsB,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAuPjF"}
package/dist/launch.js CHANGED
@@ -1,7 +1,8 @@
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"],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
- `);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),COTAL_OPENCODE_VERSION:versionRaw,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
- `:"\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
- `);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
- `);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)))})}export{BIN,launch};
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}export{BIN,launch};
@@ -0,0 +1,10 @@
1
+ import { type ModelChoice } from "@cotal-ai/core";
2
+ import type { OpenCodeApi } from "./opencode2-http.js";
3
+ interface Root {
4
+ id: string;
5
+ directory: string;
6
+ }
7
+ /** Read the private server's settled model inventory only for the launch-owned root's directory. */
8
+ export declare function listOpenCode2ModelChoices(api: OpenCodeApi, root: () => Root | undefined, signal: AbortSignal): Promise<ModelChoice[]>;
9
+ export {};
10
+ //# sourceMappingURL=model-choices2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-choices2.d.ts","sourceRoot":"","sources":["../src/model-choices2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAGvD,UAAU,IAAI;IAAG,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE;AAGhD,oGAAoG;AACpG,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAoB3I"}
@@ -0,0 +1,9 @@
1
+ import { type NativeRows } from "@cotal-ai/core";
2
+ import { type NativeHeader } from "./native-rows2.js";
3
+ type HistoryRow = NativeRows["history"];
4
+ type Get = (path: string) => Promise<unknown>;
5
+ export declare function openCodeHistoryRows(get: Get, sessionId: string, header: (kind: "history", key: string, title: string, scope: "session") => NativeHeader): Promise<HistoryRow[]>;
6
+ /** A stored user message is a native conversation boundary, not a file snapshot. */
7
+ export declare function openCodeCheckpointRows(get: Get, sessionId: string, sessionRowId: string, header: (kind: "checkpoints", key: string, title: string, scope: "session") => NativeHeader): Promise<NativeRows["checkpoints"][]>;
8
+ export {};
9
+ //# sourceMappingURL=native-history2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-history2.d.ts","sourceRoot":"","sources":["../src/native-history2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiC,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAkD,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEtG,KAAK,UAAU,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;AAoBxC,KAAK,GAAG,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AA8B9C,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EACnE,MAAM,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAYhH;AAED,oFAAoF;AACpF,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAC5F,MAAM,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC,CASnI"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What "the native server says this session is idle" means, asked after the TUI has been detached.
3
+ * 1.x answers `GET /session/status` with a map. An absent entry, or one whose type is `idle`, is idle.
4
+ *
5
+ * 2.x answers TWO routes, because upstream's own contract (OpenAPI 2.0.20/2.2.5/2.4.3) says so:
6
+ * `GET /api/session/active` is the live active-sessions map — a session present there is running,
7
+ * and a session absent is not — and `GET /api/session/:id` is `Session.Info`, whose `time` carries
8
+ * `busy` and `idle` timestamps only from 2.2.5 on (2.0.20 has neither). The two checks are ordered
9
+ * active-map first, and a failure or malformed shape on either is NOT idle: quiesce refuses rather
10
+ * than guess. `time.busy` without a `time.idle` at least as new is busy; its ABSENCE is no verdict
11
+ * at all (a 2.0.20-shaped body), which is why the active map is required and never advisory.
12
+ */
13
+ /** A 1.x status map entry. OpenCode reports `busy`, `idle`, and `retry`. */
14
+ export declare function sessionStatusIdle(body: unknown, sessionId: string): boolean;
15
+ /** A 2.x active map: `GET /api/session/active` wraps `{data: {ses_...: {type: "running"}}}`. True
16
+ * only when the shape is a map of objects; the caller decides what absence means, and a malformed
17
+ * reply is `undefined` so it can refuse rather than read it as "all idle". */
18
+ export declare function activeSessionsOf(body: unknown): Record<string, unknown> | undefined;
19
+ /** A 2.x Session.Info id check: the record must name the id it was fetched for. */
20
+ export declare function sessionInfoNames(body: unknown, sessionId: string): boolean;
21
+ /** A 2.x Session.Info busy/idle ordering. True when the session is idle by its own timestamps:
22
+ * `time.busy` absent is NO verdict (a 2.0.20-shaped record; the active map decides), `time.busy`
23
+ * present with no `time.idle` at least as new is busy, and both present is idle exactly when
24
+ * `time.idle >= time.busy`. A record without a `time` object at all is no verdict either. */
25
+ export declare function sessionInfoIdleByTime(body: unknown): boolean | undefined;
26
+ /** The whole 2.x verdict: `active` is the `/api/session/active` map (required, already
27
+ * shape-checked), `info` the `GET /api/session/:id` record. Idle only when the id matches, the
28
+ * session is absent from the active map, and the timestamps (when the version has them) agree. */
29
+ export declare function sessionRecordIdle(active: Record<string, unknown> | undefined, info: unknown, sessionId: string): boolean;
30
+ //# sourceMappingURL=native-idle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-idle.d.ts","sourceRoot":"","sources":["../src/native-idle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAK3E;AAOD;;+EAE+E;AAC/E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAMnF;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAI1E;AAED;;;8FAG8F;AAC9F,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,SAAS,CASxE;AAED;;mGAEmG;AACnG,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAMxH"}
@@ -0,0 +1,17 @@
1
+ import { type NativeDispatcher } from "@cotal-ai/connector-core";
2
+ import type { OpenCodeApi } from "./opencode2-http.js";
3
+ import type { OpenCode2Event } from "./opencode2-types.js";
4
+ export declare function runningShellId(job: Record<string, unknown>): string | undefined;
5
+ type Call = (path: string, method?: "GET" | "POST") => Promise<unknown>;
6
+ interface Deps {
7
+ api: OpenCodeApi;
8
+ signal: AbortSignal;
9
+ session(): string | undefined;
10
+ localDirectory?(): string | undefined;
11
+ }
12
+ /** Offer one fixed native write on OpenCode 2.4.3. Only a pinned shell exit settles the owner key. */
13
+ export declare function nativeShellStop(deps: Deps, target: (get: Call, sessionID: string, resourceId: string) => Promise<string | undefined>): Required<Pick<NativeDispatcher, "actions" | "act">> & {
14
+ event(ev: OpenCode2Event): void;
15
+ };
16
+ export {};
17
+ //# sourceMappingURL=native-shell-stop2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-shell-stop2.d.ts","sourceRoot":"","sources":["../src/native-shell-stop2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,gBAAgB,EAAyB,MAAM,0BAA0B,CAAC;AAEvG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAI/E;AAID,KAAK,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,KAAK,GAAG,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAGxE,UAAU,IAAI;IACZ,GAAG,EAAE,WAAW,CAAC;IACjB,MAAM,EAAE,WAAW,CAAC;IACpB,OAAO,IAAI,MAAM,GAAG,SAAS,CAAC;IAC9B,cAAc,CAAC,IAAI,MAAM,GAAG,SAAS,CAAC;CACvC;AAgBD,sGAAsG;AACtG,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,GACnI,QAAQ,CAAC,IAAI,CAAC,gBAAgB,EAAE,SAAS,GAAG,KAAK,CAAC,CAAC,GAAG;IAAE,KAAK,CAAC,EAAE,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,CAyD1F"}
package/dist/native2.d.ts CHANGED
@@ -1,18 +1,24 @@
1
- import type { NativeDispatcher } from "@cotal-ai/connector-core";
1
+ import { type NativeDispatcher } from "@cotal-ai/connector-core";
2
2
  import type { OpenCodeApi } from "./opencode2-http.js";
3
3
  import type { OpenCode2Event } from "./opencode2-types.js";
4
+ import { nativeHeaders } from "./native-rows2.js";
4
5
  interface Deps {
5
6
  api: OpenCodeApi;
6
7
  version?: string;
7
8
  signal: AbortSignal;
8
9
  profileOwned: boolean;
10
+ /** Stable row identity for the same launch across a host plugin reload. */
11
+ header?: Header;
12
+ /** Verified default local directory shared by the root session and its native events. */
13
+ localDirectory?(): string | undefined;
9
14
  session(): string | undefined;
10
15
  sessionReady(): Promise<string | undefined>;
11
16
  running(): boolean;
12
17
  }
18
+ type Header = ReturnType<typeof nativeHeaders>;
19
+ export { qualifiedOpenCode2Version } from "./opencode-line.js";
13
20
  export declare function opencodeNative2(deps: Deps): {
14
21
  dispatcher: NativeDispatcher;
15
22
  event(ev: OpenCode2Event): void;
16
23
  };
17
- export {};
18
24
  //# sourceMappingURL=native2.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"native2.d.ts","sourceRoot":"","sources":["../src/native2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,UAAU,IAAI;IACZ,GAAG,EAAE,WAAW,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,WAAW,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,IAAI,MAAM,GAAG,SAAS,CAAC;IAC9B,YAAY,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC5C,OAAO,IAAI,OAAO,CAAC;CACpB;AAkBD,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG;IAAE,UAAU,EAAE,gBAAgB,CAAC;IAAC,KAAK,CAAC,EAAE,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,CA0B7G"}
1
+ {"version":3,"file":"native2.d.ts","sourceRoot":"","sources":["../src/native2.ts"],"names":[],"mappings":"AACA,OAAO,EAAW,KAAK,gBAAgB,EAAwB,MAAM,0BAA0B,CAAC;AAChG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAA4B,aAAa,EAAgC,MAAM,mBAAmB,CAAC;AAI1G,UAAU,IAAI;IACZ,GAAG,EAAE,WAAW,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,WAAW,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IACtB,2EAA2E;IAC3E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,yFAAyF;IACzF,cAAc,CAAC,IAAI,MAAM,GAAG,SAAS,CAAC;IACtC,OAAO,IAAI,MAAM,GAAG,SAAS,CAAC;IAC9B,YAAY,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC5C,OAAO,IAAI,OAAO,CAAC;CACpB;AAYD,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;AAE/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAiB/D,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG;IAAE,UAAU,EAAE,gBAAgB,CAAC;IAAC,KAAK,CAAC,EAAE,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,CAsE7G"}
@@ -2,4 +2,5 @@
2
2
  * (@opencode/cli). Pure so both launch.ts (the launcher) and extension.ts (the model catalog) can
3
3
  * detect the line from the same rule with no fallback for anything else. */
4
4
  export declare function opencodeLine(raw: string, bin: string): 1 | 2;
5
+ export declare const qualifiedOpenCode2Version: (version: string | undefined) => string | undefined;
5
6
  //# sourceMappingURL=opencode-line.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"opencode-line.d.ts","sourceRoot":"","sources":["../src/opencode-line.ts"],"names":[],"mappings":"AAAA;;6EAE6E;AAC7E,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,CAAC,CAQ5D"}
1
+ {"version":3,"file":"opencode-line.d.ts","sourceRoot":"","sources":["../src/opencode-line.ts"],"names":[],"mappings":"AAAA;;6EAE6E;AAC7E,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,CAAC,CAQ5D;AAID,eAAO,MAAM,yBAAyB,GAAI,SAAS,MAAM,GAAG,SAAS,KAAG,MAAM,GAAG,SAC7B,CAAC"}
@@ -12,4 +12,6 @@ export declare class OpenCodeHttpError extends Error {
12
12
  /** The private server's authenticated HTTP API. */
13
13
  export type OpenCodeApi = <T>(path: string, init?: RequestInit, timeoutMs?: number, maxJsonBytes?: number) => Promise<T>;
14
14
  export declare function privateOpenCodeApi(serverUrl: string, serverAuth: string): OpenCodeApi;
15
+ /** Read the native export as bytes so its revision hashes the same payload the caller receives. */
16
+ export declare function readOpenCodeExport(serverUrl: string, serverAuth: string, id: string, signal: AbortSignal, maxBytes: number): Promise<Buffer>;
15
17
  //# sourceMappingURL=opencode2-http.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"opencode2-http.d.ts","sourceRoot":"","sources":["../src/opencode2-http.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAExC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS;IAChC,QAAQ,CAA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AC,CAAC,CAAC;AAEzH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,WAAW,CAWrF;AAUD,mGAAmG;AACnG,wBAAsB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOlJ"}
@@ -0,0 +1,35 @@
1
+ import type { OpenCodeApi } from "./opencode2-http.js";
2
+ interface RootSession {
3
+ id?: string | undefined;
4
+ directory?: string | undefined;
5
+ }
6
+ type Launch = ReturnType<typeof readLaunch> & {
7
+ root?: Promise<RootSession>;
8
+ bootSent?: true;
9
+ };
10
+ declare function readLaunch(): {
11
+ config: import("@cotal-ai/connector-core").AgentConfig;
12
+ eventsArmed: boolean;
13
+ control: import("@cotal-ai/core").ControlEndpoint | undefined;
14
+ tuiEndpoint: import("@cotal-ai/core").ControlEndpoint | undefined;
15
+ sessionStatePath: string | undefined;
16
+ target: {
17
+ continueSession: string;
18
+ } | {
19
+ reopenSession: string;
20
+ } | undefined;
21
+ forkSource: {
22
+ id: string;
23
+ directory: string;
24
+ data: import("./native-rows2.js").NativeObject;
25
+ } | undefined;
26
+ header: (kind: keyof import("@cotal-ai/core").NativeRows, key: string, title: string, scope: import("@cotal-ai/core").NativeScope) => import("./native-rows2.js").NativeHeader;
27
+ };
28
+ /** A host reload can run setup again in the same process. It reuses the already parsed launch,
29
+ * without restoring the material file or passing its secrets back through the environment. */
30
+ export declare function opencode2Launch(serverUrl: string): Launch;
31
+ /** Start a root once. A reload checks the exact original ID at the same native location. A missing
32
+ * root or ambiguous create result does not authorize another create. */
33
+ export declare function resolveOpencode2Root(launch: Launch, api: OpenCodeApi, title: string): Promise<RootSession>;
34
+ export {};
35
+ //# sourceMappingURL=opencode2-launch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opencode2-launch.d.ts","sourceRoot":"","sources":["../src/opencode2-launch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAKvD,UAAU,WAAW;IAAG,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE;AACjF,KAAK,MAAM,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG;IAAE,IAAI,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAAC,QAAQ,CAAC,EAAE,IAAI,CAAA;CAAE,CAAC;AAG/F,iBAAS,UAAU;;;;;;;;;;;;;;;;;EAalB;AAED;+FAC+F;AAC/F,wBAAgB,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CASzD;AAaD;yEACyE;AACzE,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAchH"}
@@ -7,7 +7,7 @@
7
7
  * than importing the SDK's `Part` union. This file describes what plugin2.ts actually reads, not
8
8
  * everything OpenCode 2.x may hand it.
9
9
  */
10
- /** One event off `ctx.event.subscribe`. Same shape as `GET /api/event`. */
10
+ /** One event off `ctx.event.subscribe`. HTTP exposes the public location without `workspaceID`. */
11
11
  export interface OpenCode2Event {
12
12
  id?: string;
13
13
  type: string;
@@ -19,6 +19,10 @@ export interface OpenCode2Event {
19
19
  aggregateID: string;
20
20
  seq: number;
21
21
  };
22
+ location?: {
23
+ directory?: unknown;
24
+ workspaceID?: unknown;
25
+ };
22
26
  data?: Record<string, unknown>;
23
27
  }
24
28
  interface OpenCode2EventSubscribe {
@@ -1 +1 @@
1
- {"version":3,"file":"opencode2-types.d.ts","sourceRoot":"","sources":["../src/opencode2-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,2EAA2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