@wular/coder 0.1.16 → 0.1.18

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.
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- var bt=Object.defineProperty;var pt=(t,u)=>{for(var r in u)bt(t,r,{get:u[r],enumerable:!0,configurable:!0,set:(n)=>u[r]=()=>n})};import q from"node:fs";import Ct from"node:net";import k from"node:path";import S from"node:process";function F(t,u={}){let r=new Set(u.valueOptions??[]),n=new Set(u.booleanOptions??[]),c=u.aliasMap??{},f={},y=[],x=!1;for(let $=0;$<t.length;$+=1){let a=t[$];if(x){y.push(a);continue}if(a==="--"){x=!0;continue}if(!a.startsWith("-")||a==="-"){y.push(a);continue}if(a.startsWith("--")){let[J,G]=a.slice(2).split("=",2),z=c[J]??J;if(n.has(z)){f[z]=G===void 0?!0:G!=="false";continue}if(r.has(z)){let Y=G??t[$+1];if(Y===void 0)throw Error(`Missing value for --${J}`);if(f[z]=Y,G===void 0)$+=1;continue}throw Error(`Unknown option --${J} (use -- to pass literal text starting with -)`)}let j=a.slice(1),O=c[j]??j;if(n.has(O)){f[O]=!0;continue}if(r.has(O)){let J=t[$+1];if(J===void 0)throw Error(`Missing value for -${j}`);f[O]=J,$+=1;continue}throw Error(`Unknown option -${j} (use -- to pass literal text starting with -)`)}return{options:f,positionals:y}}import vt from"node:net";import Q from"node:process";import{spawn as Et}from"node:child_process";import At from"node:readline";import g from"node:path";import lt from"node:process";function jt(t){return String(t??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function d(t,u=lt.platform){if(u==="win32")return`pipe:\\\\.\\pipe\\${jt(`${g.win32.basename(t)}-codex-app-server`)}`;return`unix:${g.join(t,"broker.sock")}`}function R(t){if(typeof t!=="string"||t.length===0)throw Error("Missing broker endpoint.");if(t.startsWith("pipe:")){let u=t.slice(5);if(!u)throw Error("Broker pipe endpoint is missing its path.");return{kind:"pipe",path:u}}if(t.startsWith("unix:")){let u=t.slice(5);if(!u)throw Error("Broker Unix socket endpoint is missing its path.");return{kind:"unix",path:u}}throw Error(`Unsupported broker endpoint: ${t}`)}import l from"node:fs";import zt from"node:net";import Rt from"node:os";import Z from"node:path";import A from"node:process";import{spawn as Gt}from"node:child_process";import{fileURLToPath as Ut}from"node:url";import{createHash as Jt}from"node:crypto";import{execFileSync as Ot}from"node:child_process";import N from"node:fs";import Mt from"node:os";import H from"node:path";var Ht="CODER_HOME";function Nt(){return H.resolve(process.env[Ht]||H.join(Mt.homedir(),".coder"))}function St(t){try{return Ot("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return t}}function m(t){let u=St(t),r=u;try{r=N.realpathSync.native(u)}catch{r=u}let c=(H.basename(u)||"workspace").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"workspace",f=Jt("sha256").update(r).digest("hex").slice(0,12);return H.join(Nt(),"state",`${c}-${f}`)}function e(t){return H.join(m(t),"jobs")}function L(t,u){return H.join(e(t),u)}function fu(){let t=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${t}`}function iu(t,u,r){let n=L(t,u);N.mkdirSync(n,{recursive:!0});let c=H.join(n,"job.json"),y={...s(t,u)??{id:u,createdAt:new Date().toISOString()},...r,updatedAt:new Date().toISOString()};return N.writeFileSync(c,`${JSON.stringify(y,null,2)}
3
- `,"utf8"),y}function s(t,u){let r=H.join(L(t,u),"job.json");if(!N.existsSync(r))return null;try{return JSON.parse(N.readFileSync(r,"utf8"))}catch{return null}}function Wt(t){let u=e(t);if(!N.existsSync(u))return[];return N.readdirSync(u).map((r)=>s(t,r)).filter(Boolean).sort((r,n)=>String(n.updatedAt??"").localeCompare(String(r.updatedAt??"")))}function cu(t,u){let r=Wt(t);if(!u)return r[0]??null;let n=r.find((f)=>f.id===u);if(n)return n;let c=r.filter((f)=>f.id.startsWith(u));if(c.length===1)return c[0];if(c.length>1)throw Error(`Job reference "${u}" is ambiguous. Use a longer id.`);return null}function hu(t,u,r){let n=L(t,u);N.mkdirSync(n,{recursive:!0}),N.appendFileSync(H.join(n,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...r})}
4
- `,"utf8")}function yu(t,u,r=40){let n=H.join(L(t,u),"log.jsonl");if(!N.existsSync(n))return[];return N.readFileSync(n,"utf8").split(/\r?\n/).filter(Boolean).slice(-r).map((f)=>{try{return JSON.parse(f)}catch{return{message:f}}})}var Zt="broker.json";function ot(t="coder-"){return l.mkdtempSync(Z.join(Rt.tmpdir(),t))}function qt(t){let u=R(t);return zt.createConnection({path:u.path})}async function ut(t,u=2000){let r=Date.now();while(Date.now()-r<u){if(await new Promise((c)=>{let f=qt(t);f.on("connect",()=>{f.end(),c(!0)}),f.on("error",()=>c(!1))}))return!0;await new Promise((c)=>setTimeout(c,50))}return!1}function wt({scriptPath:t,cwd:u,endpoint:r,pidFile:n,logFile:c,env:f=A.env}){let y=l.openSync(c,"a"),x=Gt(A.execPath,[t,"serve","--endpoint",r,"--cwd",u,"--pid-file",n],{cwd:u,env:f,detached:!0,stdio:["ignore",y,y]});return x.unref(),l.closeSync(y),x}function Qt(){let t=[new URL("./lib/broker.js",import.meta.url),new URL("./broker.js",import.meta.url)];for(let u of t){let r=Ut(u);if(l.existsSync(r))return r}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function T(t){return Z.join(m(t),Zt)}function _(t){let u=T(t);if(!l.existsSync(u))return null;try{return JSON.parse(l.readFileSync(u,"utf8"))}catch{return null}}function Yt(t,u){let r=m(t);l.mkdirSync(r,{recursive:!0}),l.writeFileSync(T(t),`${JSON.stringify(u,null,2)}
5
- `,"utf8")}function Xt(t){let u=T(t);if(l.existsSync(u))l.unlinkSync(u)}async function Kt(t){if(!t)return!1;try{return await ut(t,150)}catch{return!1}}async function rt(t,u={}){let r=_(t);if(r&&await Kt(r.endpoint))return r;if(r)tt({endpoint:r.endpoint??null,pidFile:r.pidFile??null,logFile:r.logFile??null,sessionDir:r.sessionDir??null,pid:r.pid??null,killProcess:u.killProcess??null}),Xt(t);let n=ot(),f=(u.createBrokerEndpoint??d)(n,u.platform),y=Z.join(n,"broker.pid"),x=Z.join(n,"broker.log"),$=u.scriptPath??Qt(),a=wt({scriptPath:$,cwd:t,endpoint:f,pidFile:y,logFile:x,env:u.env??A.env});if(!await ut(f,u.timeoutMs??2000))return tt({endpoint:f,pidFile:y,logFile:x,sessionDir:n,pid:a.pid??null,killProcess:u.killProcess??null}),null;let O={endpoint:f,pidFile:y,logFile:x,sessionDir:n,pid:a.pid??null};return Yt(t,O),O}function tt({endpoint:t=null,pidFile:u,logFile:r,sessionDir:n=null,pid:c=null,killProcess:f=null}){if(Number.isFinite(c)&&f)try{f(c)}catch{}if(u&&l.existsSync(u))l.unlinkSync(u);if(r&&l.existsSync(r))l.unlinkSync(r);if(t)try{let x=R(t);if(x.kind==="unix"&&l.existsSync(x.path))l.unlinkSync(x.path)}catch{}let y=n??(u?Z.dirname(u):r?Z.dirname(r):null);if(y&&l.existsSync(y))try{l.rmdirSync(y)}catch{}}import{spawnSync as mt}from"node:child_process";import w from"node:process";function V(t,u=[],r={}){let n=mt(t,u,{cwd:r.cwd,env:r.env,encoding:"utf8",input:r.input,maxBuffer:r.maxBuffer,stdio:r.stdio??"pipe",shell:w.platform==="win32"?w.env.SHELL||!0:!1,windowsHide:!0});return{command:t,args:u,status:n.status??0,signal:n.signal??null,stdout:n.stdout??"",stderr:n.stderr??"",error:n.error??null}}function zu(t,u=["--version"],r={}){let n=V(t,u,r);if(n.error&&n.error.code==="ENOENT")return{available:!1,detail:"not found"};if(n.error)return{available:!1,detail:n.error.message};if(n.status!==0)return{available:!1,detail:n.stderr.trim()||n.stdout.trim()||`exit ${n.status}`};return{available:!0,detail:n.stdout.trim()||n.stderr.trim()||"ok"}}function Lt(t){return/not found|no running instance|cannot find|does not exist|no such process/i.test(t)}function nt(t,u={}){if(!Number.isFinite(t))return{attempted:!1,delivered:!1,method:null};let r=u.platform??w.platform,n=u.runCommandImpl??V,c=u.killImpl??w.kill.bind(w);if(r==="win32"){let f=n("taskkill",["/PID",String(t),"/T","/F"],{cwd:u.cwd,env:u.env});if(!f.error&&f.status===0)return{attempted:!0,delivered:!0,method:"taskkill",result:f};let y=`${f.stderr}
6
- ${f.stdout}`.trim();if(!f.error&&Lt(y))return{attempted:!0,delivered:!1,method:"taskkill",result:f};if(f.error?.code==="ENOENT")try{return c(t),{attempted:!0,delivered:!0,method:"kill"}}catch(x){if(x?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"kill"};throw x}if(f.error)throw f.error;throw Error(Vt(f))}try{return c(-t,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(f){if(f?.code!=="ESRCH")try{return c(t,"SIGTERM"),{attempted:!0,delivered:!0,method:"process"}}catch(y){if(y?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"process"};throw y}return{attempted:!0,delivered:!1,method:"process-group"}}}function Vt(t){let u=[`${t.command} ${t.args.join(" ")}`.trim()];if(t.signal)u.push(`signal=${t.signal}`);else u.push(`exit=${t.status}`);let r=(t.stderr||"").trim(),n=(t.stdout||"").trim();if(r)u.push(r);else if(n)u.push(n);return u.join(": ")}var ft="CODER_APP_SERVER_ENDPOINT",ct=-32001,Tt="0.144.1",C;function _t(){if(C===void 0){let t=V("codex",["--version"]),u=/(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(`${t.stdout} ${t.stderr}`);C=u?u[1]:Tt}return C}function ht(){return{title:"Coder",name:"coder",version:_t()}}var yt={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function it(t,u,r){return r===void 0?{code:t,message:u}:{code:t,message:u,data:r}}function D(t,u){let r=Error(t);if(r.data=u,u?.code!==void 0)r.rpcCode=u.code;return r}class P{cwd;options;pending;nextId;stderr;closed;exitError;notificationHandler;serverRequestHandler;lineBuffer;transport;exitPromise;exitResolved;resolveExit;handleServerRequest;constructor(t,u={}){this.cwd=t,this.options=u,this.pending=new Map,this.nextId=1,this.stderr="",this.closed=!1,this.exitError=null,this.notificationHandler=null,this.serverRequestHandler=null,this.lineBuffer="",this.transport="unknown",this.handleServerRequest=(r)=>this.defaultHandleServerRequest(r),this.exitPromise=new Promise((r)=>{this.resolveExit=r})}setNotificationHandler(t){this.notificationHandler=t}setServerRequestHandler(t){this.serverRequestHandler=t}request(t,u){if(this.closed)throw Error("codex app-server client is closed.");let r=this.nextId;return this.nextId+=1,new Promise((n,c)=>{this.pending.set(r,{resolve:n,reject:c,method:t}),this.sendMessage({id:r,method:t,params:u})})}notify(t,u={}){if(this.closed)return;this.sendMessage({method:t,params:u})}handleChunk(t){this.lineBuffer+=t;let u=this.lineBuffer.indexOf(`
7
- `);while(u!==-1){let r=this.lineBuffer.slice(0,u);this.lineBuffer=this.lineBuffer.slice(u+1),this.handleLine(r),u=this.lineBuffer.indexOf(`
8
- `)}}handleLine(t){if(!t.trim())return;let u;try{u=JSON.parse(t)}catch(r){this.handleExit(D(`Failed to parse codex app-server JSONL: ${r.message}`,{line:t}));return}if(u.id!==void 0&&u.method){this.handleServerRequest(u);return}if(u.id!==void 0){let r=this.pending.get(u.id);if(!r)return;if(this.pending.delete(u.id),u.error)r.reject(D(u.error.message??`codex app-server ${r.method} failed.`,u.error));else r.resolve(u.result??{});return}if(u.method&&this.notificationHandler)this.notificationHandler(u)}defaultHandleServerRequest(t){if(!this.serverRequestHandler){this.sendMessage({id:t.id,error:it(-32601,`Unsupported server request: ${t.method}`)});return}Promise.resolve().then(()=>this.serverRequestHandler(t.method,t.params??{})).then((u)=>{this.sendMessage({id:t.id,result:u??{}})}).catch((u)=>{this.sendMessage({id:t.id,error:it(-32000,u instanceof Error?u.message:String(u))})})}handleExit(t){if(this.exitResolved)return;this.exitResolved=!0,this.exitError=t??null;for(let u of this.pending.values())u.reject(this.exitError??Error("codex app-server connection closed."));this.pending.clear(),this.resolveExit(void 0)}sendMessage(t){throw Error("sendMessage must be implemented by subclasses.")}}class xt extends P{proc;readline;constructor(t,u={}){super(t,u);this.transport="direct"}async initialize(){this.proc=Et("codex",["app-server","--disable","plugins"],{cwd:this.cwd,env:this.options.env??Q.env,stdio:["pipe","pipe","pipe"],shell:Q.platform==="win32"?Q.env.SHELL||!0:!1,windowsHide:!0}),this.proc.stdout.setEncoding("utf8"),this.proc.stderr.setEncoding("utf8"),this.proc.stderr.on("data",(t)=>{this.stderr+=t}),this.proc.on("error",(t)=>{this.handleExit(t)}),this.proc.on("exit",(t,u)=>{let r=this.stderr.trim(),n=t===0?null:D(`codex app-server exited unexpectedly (${u?`signal ${u}`:`exit ${t}`}).${r?`
9
- ${r}`:""}`);this.handleExit(n)}),this.readline=At.createInterface({input:this.proc.stdout}),this.readline.on("line",(t)=>{this.handleLine(t)}),await this.request("initialize",{clientInfo:this.options.clientInfo??ht(),capabilities:this.options.capabilities??yt}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.readline)this.readline.close();if(this.proc&&!this.proc.killed)this.proc.stdin.end(),setTimeout(()=>{if(this.proc&&!this.proc.killed&&this.proc.exitCode===null)if(Q.platform==="win32")try{nt(this.proc.pid)}catch{}else this.proc.kill("SIGTERM")},50).unref?.();await this.exitPromise}sendMessage(t){let u=`${JSON.stringify(t)}
10
- `,r=this.proc?.stdin;if(!r)throw Error("codex app-server stdin is not available.");r.write(u)}}class at extends P{endpoint;socket;constructor(t,u={}){super(t,u);this.transport="broker",this.endpoint=u.brokerEndpoint}async initialize(){await new Promise((t,u)=>{let r=R(this.endpoint);this.socket=vt.createConnection({path:r.path}),this.socket.setEncoding("utf8"),this.socket.on("connect",t),this.socket.on("data",(n)=>{this.handleChunk(n)}),this.socket.on("error",(n)=>{if(!this.exitResolved)u(n);this.handleExit(n)}),this.socket.on("close",()=>{this.handleExit(this.exitError)})}),await this.request("initialize",{clientInfo:this.options.clientInfo??ht(),capabilities:this.options.capabilities??yt}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.socket)this.socket.end();await this.exitPromise}sendMessage(t){let u=`${JSON.stringify(t)}
11
- `,r=this.socket;if(!r)throw Error("codex app-server broker connection is not connected.");r.write(u)}}class I{static async connect(t,u={}){let r=null;if(!u.disableBroker){if(r=u.brokerEndpoint??u.env?.[ft]??Q.env[ft]??null,!r&&u.reuseExistingBroker)r=_(t)?.endpoint??null;if(!r&&!u.reuseExistingBroker)r=(await rt(t,{env:u.env}))?.endpoint??null}let n=r?new at(t,{...u,brokerEndpoint:r}):new xt(t,u);return await n.initialize(),n}}var Dt=new Set(["turn/start","review/start","thread/compact/start"]);function $t(t,u,r){let n=new Set;if(u?.threadId)n.add(u.threadId);if(t==="review/start"&&r?.reviewThreadId)n.add(r.reviewThreadId);return n}function o(t,u,r){return r===void 0?{code:t,message:u}:{code:t,message:u,data:r}}function W(t,u){if(t.destroyed)return;t.write(`${JSON.stringify(u)}
12
- `)}function Pt(t){return t?.method==="turn/interrupt"}function It(t){if(!t)return;q.mkdirSync(k.dirname(t),{recursive:!0}),q.writeFileSync(t,`${S.pid}
13
- `,"utf8")}async function kt(){let[t,...u]=S.argv.slice(2);if(t!=="serve")throw Error("Usage: node src/lib/broker.mjs serve --endpoint <value> [--cwd <path>] [--pid-file <path>]");let{options:r}=F(u,{valueOptions:["cwd","pid-file","endpoint"]});if(!r.endpoint)throw Error("Missing required --endpoint.");let n=r.cwd?k.resolve(S.cwd(),r.cwd):S.cwd(),c=String(r.endpoint),f=R(c),y=r["pid-file"]?k.resolve(r["pid-file"]):null;It(y);let x=await I.connect(n,{disableBroker:!0}),$=null,a=null,j=null,O=new Set,J=new Map;function G(i){for(let[b,U]of J)if(U===i)J.delete(b),x.sendMessage({id:b,error:o(-32000,"Broker client disconnected before answering the server request.")})}function z(i){if(G(i),$===i)$=null;if(a===i)a=null,j=null}function Y(i){let b=$??a;if(!b)return;if(W(b,i),i.method==="turn/completed"&&a===b){let U=i.params?.threadId??null;if(!U||!j||j.has(U)){if(a=null,j=null,$===b)$=null}}}async function v(i){for(let b of O)b.end();if(await x.close().catch(()=>{}),await new Promise((b)=>i.close(b)),f.kind==="unix"&&q.existsSync(f.path))q.unlinkSync(f.path);if(y&&q.existsSync(y))q.unlinkSync(y)}x.setNotificationHandler(Y),x.handleServerRequest=(i)=>{let b=a??$;if(!b||b.destroyed){x.sendMessage({id:i.id,error:o(-32601,`No broker client available to answer ${i.method}.`)});return}J.set(i.id,b),W(b,i)};let X=Ct.createServer((i)=>{O.add(i),i.setEncoding("utf8");let b="";i.on("data",async(U)=>{b+=U;let K=b.indexOf(`
14
- `);while(K!==-1){let p=b.slice(0,K);if(b=b.slice(K+1),K=b.indexOf(`
15
- `),!p.trim())continue;let h;try{h=JSON.parse(p)}catch(M){W(i,{id:null,error:o(-32700,`Invalid JSON: ${M.message}`)});continue}if(h.id!==void 0&&!h.method&&J.has(h.id)){J.delete(h.id),x.sendMessage(h);continue}if(h.id!==void 0&&h.method==="initialize"){W(i,{id:h.id,result:{userAgent:"coder-broker"}});continue}if(h.method==="initialized"&&h.id===void 0)continue;if(h.id!==void 0&&h.method==="broker/shutdown")W(i,{id:h.id,result:{}}),await v(X),S.exit(0);if(h.id===void 0||!h.method)continue;let B=Pt(h)&&a&&a!==i&&!$;if(($&&$!==i||a&&a!==i)&&!B){W(i,{id:h.id,error:o(ct,"Shared Codex broker is busy.")});continue}if(B){try{let M=await x.request(h.method,h.params??{});W(i,{id:h.id,result:M})}catch(M){W(i,{id:h.id,error:o(M.rpcCode??-32000,M.message)})}continue}let E=Dt.has(h.method);if($=i,E)a=i,j=$t(h.method,h.params??{},null);try{let M=await x.request(h.method,h.params??{});if(W(i,{id:h.id,result:M}),E)j=$t(h.method,h.params??{},M);if($===i)$=null}catch(M){if(W(i,{id:h.id,error:o(M.rpcCode??-32000,M.message)}),$===i)$=null;if(a===i&&E)a=null,j=null}}}),i.on("close",()=>{O.delete(i),z(i)}),i.on("error",()=>{O.delete(i),z(i)})});S.on("SIGTERM",async()=>{await v(X),S.exit(0)}),S.on("SIGINT",async()=>{await v(X),S.exit(0)}),X.listen(f.path)}kt().catch((t)=>{S.stderr.write(`${t instanceof Error?t.message:String(t)}
16
- `),S.exit(1)});
2
+ var T$=Object.defineProperty;var G1=($,W)=>{for(var q in W)T$($,q,{get:W[q],enumerable:!0,configurable:!0,set:(Z)=>W[q]=()=>Z})};import E from"node:fs";import e$ from"node:net";import r from"node:path";import x from"node:process";function e($,W={}){let q=new Set(W.valueOptions??[]),Z=new Set(W.booleanOptions??[]),G=W.aliasMap??{},Y={},Q=[],H=!1;for(let X=0;X<$.length;X+=1){let y=$[X];if(H){Q.push(y);continue}if(y==="--"){H=!0;continue}if(!y.startsWith("-")||y==="-"){Q.push(y);continue}if(y.startsWith("--")){let[O,_]=y.slice(2).split("=",2),f=G[O]??O;if(Z.has(f)){Y[f]=_===void 0?!0:_!=="false";continue}if(q.has(f)){let S=_??$[X+1];if(S===void 0)throw Error(`Missing value for --${O}`);if(Y[f]=S,_===void 0)X+=1;continue}throw Error(`Unknown option --${O} (use -- to pass literal text starting with -)`)}let N=y.slice(1),J=G[N]??N;if(Z.has(J)){Y[J]=!0;continue}if(q.has(J)){let O=$[X+1];if(O===void 0)throw Error(`Missing value for -${N}`);Y[J]=O,X+=1;continue}throw Error(`Unknown option -${N} (use -- to pass literal text starting with -)`)}return{options:Y,positionals:Q}}import i$ from"node:net";import I from"node:process";import{spawn as d$}from"node:child_process";import r$ from"node:readline";import $$ from"node:path";import x$ from"node:process";function A$($){return String($??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function W$($,W=x$.platform){if(W==="win32")return`pipe:\\\\.\\pipe\\${A$(`${$$.win32.basename($)}-codex-app-server`)}`;return`unix:${$$.join($,"broker.sock")}`}function R($){if(typeof $!=="string"||$.length===0)throw Error("Missing broker endpoint.");if($.startsWith("pipe:")){let W=$.slice(5);if(!W)throw Error("Broker pipe endpoint is missing its path.");return{kind:"pipe",path:W}}if($.startsWith("unix:")){let W=$.slice(5);if(!W)throw Error("Broker Unix socket endpoint is missing its path.");return{kind:"unix",path:W}}throw Error(`Unsupported broker endpoint: ${$}`)}import M from"node:fs";import S$ from"node:net";import k$ from"node:os";import B from"node:path";import c from"node:process";import{spawn as F$}from"node:child_process";import{fileURLToPath as v$}from"node:url";import{createHash as _$}from"node:crypto";import{execFileSync as Z$}from"node:child_process";import V from"node:fs";import f$ from"node:os";import T from"node:path";var q$=["completed","failed","cancelled"],y1=["queued","running"];var R$="CODER_HOME";function P$(){return T.resolve(process.env[R$]||T.join(f$.homedir(),".coder"))}function B$($){try{return Z$("git",["rev-parse","--show-toplevel"],{cwd:$,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return $}}function v($){let W=B$($),q=W;try{q=V.realpathSync.native(W)}catch{q=W}let G=(T.basename(W)||"workspace").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"workspace",Y=_$("sha256").update(q).digest("hex").slice(0,12);return T.join(P$(),"state",`${G}-${Y}`)}function G$($){return T.join(v($),"jobs")}function u($,W){return T.join(G$($),W)}function L1(){let $=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${$}`}function C$($,W,q){let Z=u($,W);V.mkdirSync(Z,{recursive:!0});let G=T.join(Z,"job.json"),Q={...g($,W)??{id:W,createdAt:new Date().toISOString(),status:"queued"},...q,updatedAt:new Date().toISOString()};return V.writeFileSync(G,`${JSON.stringify(Q,null,2)}
3
+ `,"utf8"),Q}function g($,W){let q=T.join(u($,W),"job.json");if(!V.existsSync(q))return null;try{return JSON.parse(V.readFileSync(q,"utf8"))}catch{return null}}function T1($,W){let q=u($,W);if(!V.existsSync(q))return!1;return V.rmSync(q,{recursive:!0,force:!0}),!0}function E$($){if(!$)return!1;try{return process.kill($,0),!0}catch(W){return W.code==="EPERM"}}function h$($){try{let W=Z$("ps",["-o","lstart=","-p",String($)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),q=W?Date.parse(W):NaN;return Number.isFinite(q)?q:null}catch{return null}}function u$($,W){if(!E$($))return!1;let q=h$($),Z=Date.parse(W.createdAt??"");if(q===null||!Number.isFinite(Z))return!0;return q<=Z+60000}var D$=60000;function K$($,W){if(W.status!=="running"&&W.status!=="queued")return W;let q;if(W.pid)q=!u$(W.pid,W);else{let Z=Date.parse(W.updatedAt??W.createdAt??"");q=Number.isFinite(Z)&&Date.now()-Z>D$}if(q)return C$($,W.id,{status:"failed",error:"worker exited without finishing",completedAt:new Date().toISOString()});return W}function I$($){let W=G$($);if(!V.existsSync(W))return[];return V.readdirSync(W).map((q)=>g($,q)).filter((q)=>q!==null).map((q)=>K$($,q)).sort((q,Z)=>String(Z.updatedAt??"").localeCompare(String(q.updatedAt??"")))}function x1($,W){let q=I$($);if(!W)return q[0]??null;let Z=q.find((Y)=>Y.id===W);if(Z)return Z;let G=q.filter((Y)=>Y.id.startsWith(W));if(G.length===1)return G[0];if(G.length>1)throw Error(`Job reference "${W}" is ambiguous. Use a longer id.`);return null}async function A1($,W,q=400){let Z=W;while(!q$.includes(Z.status))await new Promise((G)=>setTimeout(G,q)),Z=K$($,g($,Z.id)??Z);return Z}function _1($,W,q){let Z=u($,W);V.mkdirSync(Z,{recursive:!0}),V.appendFileSync(T.join(Z,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...q})}
4
+ `,"utf8")}function f1($,W,q=40){let Z=T.join(u($,W),"log.jsonl");if(!V.existsSync(Z))return[];return V.readFileSync(Z,"utf8").split(/\r?\n/).filter(Boolean).slice(-q).map((Y)=>{try{return JSON.parse(Y)}catch{return{message:Y}}})}import m from"node:fs";import{fileURLToPath as p}from"node:url";var C1=p(import.meta.url);function Q$(){try{return JSON.parse(m.readFileSync(p(new URL("../package.json",import.meta.url)),"utf8")).version??"unknown"}catch{return"unknown"}}function E1($){try{return JSON.parse(m.readFileSync($,"utf8")).version??null}catch{return null}}function h1(){return p(new URL("..",import.meta.url))}var w$="broker.json";function j$($="coder-"){return M.mkdtempSync(B.join(k$.tmpdir(),$))}function b$($){let W=R($);return S$.createConnection({path:W.path})}async function z$($,W=2000){let q=Date.now();while(Date.now()-q<W){if(await new Promise((G)=>{let Y=b$($);Y.on("connect",()=>{Y.end(),G(!0)}),Y.on("error",()=>G(!1))}))return!0;await new Promise((G)=>setTimeout(G,50))}return!1}function g$({scriptPath:$,cwd:W,endpoint:q,pidFile:Z,logFile:G,env:Y=c.env}){let Q=M.openSync(G,"a"),H=F$(c.execPath,[$,"serve","--endpoint",q,"--cwd",W,"--pid-file",Z],{cwd:W,env:Y,detached:!0,stdio:["ignore",Q,Q]});return H.unref(),M.closeSync(Q),H}function m$(){let $=[new URL("./lib/broker.js",import.meta.url),new URL("./broker.js",import.meta.url)];for(let W of $){let q=v$(W);if(M.existsSync(q))return q}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function n($){return B.join(v($),w$)}function a($){let W=n($);if(!M.existsSync(W))return null;try{return JSON.parse(M.readFileSync(W,"utf8"))}catch{return null}}function p$($,W){let q=v($);M.mkdirSync(q,{recursive:!0}),M.writeFileSync(n($),`${JSON.stringify(W,null,2)}
5
+ `,"utf8")}function c$($){let W=n($);if(M.existsSync(W))M.unlinkSync(W)}async function n$($){if(!$)return!1;try{return await z$($,150)}catch{return!1}}async function X$($,W={}){let q=W.scriptPath??m$(),Z=Q$(),G=a($),Y=G?.version===Z&&G?.scriptPath===q;if(G&&Y&&await n$(G.endpoint))return G;if(G)Y$({endpoint:G.endpoint??null,pidFile:G.pidFile??null,logFile:G.logFile??null,sessionDir:G.sessionDir??null,pid:G.pid??null,killProcess:W.killProcess??null}),c$($);let Q=j$(),X=(W.createBrokerEndpoint??W$)(Q,W.platform),y=B.join(Q,"broker.pid"),N=B.join(Q,"broker.log"),J=g$({scriptPath:q,cwd:$,endpoint:X,pidFile:y,logFile:N,env:W.env??c.env});if(!await z$(X,W.timeoutMs??2000))return Y$({endpoint:X,pidFile:y,logFile:N,sessionDir:Q,pid:J.pid??null,killProcess:W.killProcess??null}),null;let _={endpoint:X,pidFile:y,logFile:N,sessionDir:Q,pid:J.pid??null,version:Z,scriptPath:q};return p$($,_),_}function Y$({endpoint:$=null,pidFile:W,logFile:q,sessionDir:Z=null,pid:G=null,killProcess:Y=null}){if(Number.isFinite(G)&&Y)try{Y(G)}catch{}if(W&&M.existsSync(W))M.unlinkSync(W);if(q&&M.existsSync(q))M.unlinkSync(q);if($)try{let H=R($);if(H.kind==="unix"&&M.existsSync(H.path))M.unlinkSync(H.path)}catch{}let Q=Z??(W?B.dirname(W):q?B.dirname(q):null);if(Q&&M.existsSync(Q))try{M.rmdirSync(Q)}catch{}}import{spawnSync as a$}from"node:child_process";import D from"node:process";function w($,W=[],q={}){let Z=a$($,W,{cwd:q.cwd,env:q.env,encoding:"utf8",input:q.input,maxBuffer:q.maxBuffer,stdio:q.stdio??"pipe",shell:D.platform==="win32"?D.env.SHELL||!0:!1,windowsHide:!0});return{command:$,args:W,status:Z.status??0,signal:Z.signal??null,stdout:Z.stdout??"",stderr:Z.stderr??"",error:Z.error??null}}function n1($,W=["--version"],q={}){let Z=w($,W,q);if(Z.error&&Z.error.code==="ENOENT")return{available:!1,detail:"not found"};if(Z.error)return{available:!1,detail:Z.error.message};if(Z.status!==0)return{available:!1,detail:Z.stderr.trim()||Z.stdout.trim()||`exit ${Z.status}`};return{available:!0,detail:Z.stdout.trim()||Z.stderr.trim()||"ok"}}function l$($){return/not found|no running instance|cannot find|does not exist|no such process/i.test($)}function y$($,W={}){if(!Number.isFinite($))return{attempted:!1,delivered:!1,method:null};let q=$,Z=W.platform??D.platform,G=W.runCommandImpl??w,Y=W.killImpl??D.kill.bind(D);if(Z==="win32"){let Q=G("taskkill",["/PID",String(q),"/T","/F"],{cwd:W.cwd,env:W.env});if(!Q.error&&Q.status===0)return{attempted:!0,delivered:!0,method:"taskkill",result:Q};let H=`${Q.stderr}
6
+ ${Q.stdout}`.trim();if(!Q.error&&l$(H))return{attempted:!0,delivered:!1,method:"taskkill",result:Q};if(Q.error?.code==="ENOENT")try{return Y(q),{attempted:!0,delivered:!0,method:"kill"}}catch(X){if(X?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"kill"};throw X}if(Q.error)throw Q.error;throw Error(t$(Q))}try{return Y(-q,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(Q){if(Q?.code!=="ESRCH")try{return Y(q,"SIGTERM"),{attempted:!0,delivered:!0,method:"process"}}catch(H){if(H?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"process"};throw H}return{attempted:!0,delivered:!1,method:"process-group"}}}function t$($){let W=[`${$.command} ${$.args.join(" ")}`.trim()];if($.signal)W.push(`signal=${$.signal}`);else W.push(`exit=${$.status}`);let q=($.stderr||"").trim(),Z=($.stdout||"").trim();if(q)W.push(q);else if(Z)W.push(Z);return W.join(": ")}var H$="CODER_APP_SERVER_ENDPOINT",M$=-32001,o$="0.144.1",l;function s$(){if(l===void 0){let $=w("codex",["--version"]),W=/(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(`${$.stdout} ${$.stderr}`);l=W?W[1]:o$}return l}function N$(){return{title:"Coder",name:"coder",version:s$()}}var O$={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function U$($,W,q){return q===void 0?{code:$,message:W}:{code:$,message:W,data:q}}function t($,W){let q=Error($);if(q.data=W,W?.code!==void 0)q.rpcCode=W.code;return q}class i{cwd;options;pending;nextId;stderr;closed;exitError;notificationHandler;serverRequestHandler;lineBuffer;transport;exitPromise;exitResolved;resolveExit;handleServerRequest;constructor($,W={}){this.cwd=$,this.options=W,this.pending=new Map,this.nextId=1,this.stderr="",this.closed=!1,this.exitError=null,this.notificationHandler=null,this.serverRequestHandler=null,this.lineBuffer="",this.transport="unknown",this.handleServerRequest=(q)=>this.defaultHandleServerRequest(q),this.exitPromise=new Promise((q)=>{this.resolveExit=q})}setNotificationHandler($){this.notificationHandler=$}setServerRequestHandler($){this.serverRequestHandler=$}request($,W){if(this.closed)throw Error("codex app-server client is closed.");let q=this.nextId;return this.nextId+=1,new Promise((Z,G)=>{this.pending.set(q,{resolve:Z,reject:G,method:$}),this.sendMessage({id:q,method:$,params:W})})}notify($,W={}){if(this.closed)return;this.sendMessage({method:$,params:W})}handleChunk($){this.lineBuffer+=$;let W=this.lineBuffer.indexOf(`
7
+ `);while(W!==-1){let q=this.lineBuffer.slice(0,W);this.lineBuffer=this.lineBuffer.slice(W+1),this.handleLine(q),W=this.lineBuffer.indexOf(`
8
+ `)}}handleLine($){if(!$.trim())return;let W;try{W=JSON.parse($)}catch(q){this.handleExit(t(`Failed to parse codex app-server JSONL: ${q instanceof Error?q.message:String(q)}`,{line:$}));return}if(W.id!==void 0&&W.method){this.handleServerRequest(W);return}if(W.id!==void 0){let q=this.pending.get(W.id);if(!q)return;if(this.pending.delete(W.id),W.error)q.reject(t(W.error.message??`codex app-server ${q.method} failed.`,W.error));else q.resolve(W.result??{});return}if(W.method&&this.notificationHandler)this.notificationHandler(W)}defaultHandleServerRequest($){let W=this.serverRequestHandler;if(!W){this.sendMessage({id:$.id,error:U$(-32601,`Unsupported server request: ${$.method}`)});return}Promise.resolve().then(()=>W($.method,$.params??{})).then((q)=>{this.sendMessage({id:$.id,result:q??{}})}).catch((q)=>{this.sendMessage({id:$.id,error:U$(-32000,q instanceof Error?q.message:String(q))})})}handleExit($){if(this.exitResolved)return;this.exitResolved=!0,this.exitError=$??null;for(let W of this.pending.values())W.reject(this.exitError??Error("codex app-server connection closed."));this.pending.clear(),this.resolveExit(void 0)}sendMessage($){throw Error("sendMessage must be implemented by subclasses.")}}class V$ extends i{proc;readline;constructor($,W={}){super($,W);this.transport="direct"}async initialize(){this.proc=d$("codex",["app-server","--disable","plugins"],{cwd:this.cwd,env:this.options.env??I.env,stdio:["pipe","pipe","pipe"],shell:I.platform==="win32"?I.env.SHELL||!0:!1,windowsHide:!0});let $=this.proc.stdout,W=this.proc.stderr;if(!$||!W)throw Error("codex app-server did not expose stdio streams.");$.setEncoding("utf8"),W.setEncoding("utf8"),W.on("data",(q)=>{this.stderr+=q}),this.proc.on("error",(q)=>{this.handleExit(q)}),this.proc.on("exit",(q,Z)=>{let G=this.stderr.trim(),Y=q===0?null:t(`codex app-server exited unexpectedly (${Z?`signal ${Z}`:`exit ${q}`}).${G?`
9
+ ${G}`:""}`);this.handleExit(Y)}),this.readline=r$.createInterface({input:$}),this.readline.on("line",(q)=>{this.handleLine(q)}),await this.request("initialize",{clientInfo:this.options.clientInfo??N$(),capabilities:this.options.capabilities??O$}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.readline)this.readline.close();if(this.proc&&!this.proc.killed)this.proc.stdin?.end(),setTimeout(()=>{if(this.proc&&!this.proc.killed&&this.proc.exitCode===null)if(I.platform==="win32")try{y$(this.proc.pid)}catch{}else this.proc.kill("SIGTERM")},50).unref?.();await this.exitPromise}sendMessage($){let W=`${JSON.stringify($)}
10
+ `,q=this.proc?.stdin;if(!q)throw Error("codex app-server stdin is not available.");q.write(W)}}class J$ extends i{endpoint;socket;constructor($,W={}){super($,W);this.transport="broker",this.endpoint=W.brokerEndpoint}async initialize(){await new Promise(($,W)=>{let q=R(this.endpoint);this.socket=i$.createConnection({path:q.path}),this.socket.setEncoding("utf8"),this.socket.on("connect",$),this.socket.on("data",(Z)=>{this.handleChunk(Z)}),this.socket.on("error",(Z)=>{if(!this.exitResolved)W(Z);this.handleExit(Z)}),this.socket.on("close",()=>{this.handleExit(this.exitError)})}),await this.request("initialize",{clientInfo:this.options.clientInfo??N$(),capabilities:this.options.capabilities??O$}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.socket)this.socket.end();await this.exitPromise}sendMessage($){let W=`${JSON.stringify($)}
11
+ `,q=this.socket;if(!q)throw Error("codex app-server broker connection is not connected.");q.write(W)}}class d{static async connect($,W={}){let q=null;if(!W.disableBroker){if(q=W.brokerEndpoint??W.env?.[H$]??I.env[H$]??null,!q&&W.reuseExistingBroker)q=a($)?.endpoint??null;if(!q&&!W.reuseExistingBroker)q=(await X$($,{env:W.env}))?.endpoint??null}let Z=q?new J$($,{...W,brokerEndpoint:q}):new V$($,W);return await Z.initialize(),Z}}var $1=new Set(["turn/start","review/start","thread/compact/start"]);function L$($,W,q){let Z=new Set;if(W?.threadId)Z.add(W.threadId);if($==="review/start"&&q?.reviewThreadId)Z.add(q.reviewThreadId);return Z}function C($,W,q){return q===void 0?{code:$,message:W}:{code:$,message:W,data:q}}function A($,W){if($.destroyed)return;$.write(`${JSON.stringify(W)}
12
+ `)}function W1($){return $?.method==="turn/interrupt"}function q1($){if(!$)return;E.mkdirSync(r.dirname($),{recursive:!0}),E.writeFileSync($,`${x.pid}
13
+ `,"utf8")}async function Z1(){let[$,...W]=x.argv.slice(2);if($!=="serve")throw Error("Usage: node src/lib/broker.mjs serve --endpoint <value> [--cwd <path>] [--pid-file <path>]");let{options:q}=e(W,{valueOptions:["cwd","pid-file","endpoint"]});if(!q.endpoint)throw Error("Missing required --endpoint.");let Z=q.cwd?r.resolve(x.cwd(),q.cwd):x.cwd(),G=String(q.endpoint),Y=R(G),Q=q["pid-file"]?r.resolve(q["pid-file"]):null;q1(Q);let H=await d.connect(Z,{disableBroker:!0}),X=null,y=null,N=null,J=new Set,O=new Map;function _(K){for(let[U,P]of O)if(P===K)O.delete(U),H.sendMessage({id:U,error:C(-32000,"Broker client disconnected before answering the server request.")})}function f(K){if(_(K),X===K)X=null;if(y===K)y=null,N=null}function S(K){let U=X??y;if(!U)return;if(A(U,K),K.method==="turn/completed"&&y===U){let P=K.params?.threadId??null;if(!P||!N||N.has(P)){if(y=null,N=null,X===U)X=null}}}async function j(K){for(let U of J)U.end();if(await H.close().catch(()=>{}),await new Promise((U)=>K.close(U)),Y.kind==="unix"&&E.existsSync(Y.path))E.unlinkSync(Y.path);if(Q&&E.existsSync(Q))E.unlinkSync(Q)}H.setNotificationHandler(S),H.handleServerRequest=(K)=>{let U=y??X;if(!U||U.destroyed){H.sendMessage({id:K.id,error:C(-32601,`No broker client available to answer ${K.method}.`)});return}O.set(K.id,U),A(U,K)};let k=e$.createServer((K)=>{J.add(K),K.setEncoding("utf8");let U="";K.on("data",async(P)=>{U+=P;let F=U.indexOf(`
14
+ `);while(F!==-1){let o=U.slice(0,F);if(U=U.slice(F+1),F=U.indexOf(`
15
+ `),!o.trim())continue;let z;try{z=JSON.parse(o)}catch(L){A(K,{id:null,error:C(-32700,`Invalid JSON: ${L instanceof Error?L.message:String(L)}`)});continue}if(z.id!==void 0&&!z.method&&O.has(z.id)){O.delete(z.id),H.sendMessage(z);continue}if(z.id!==void 0&&z.method==="initialize"){A(K,{id:z.id,result:{userAgent:"coder-broker"}});continue}if(z.method==="initialized"&&z.id===void 0)continue;if(z.id!==void 0&&z.method==="broker/shutdown")A(K,{id:z.id,result:{}}),await j(k),x.exit(0);if(z.id===void 0||!z.method)continue;let s=W1(z)&&y&&y!==K&&!X;if((X&&X!==K||y&&y!==K)&&!s){A(K,{id:z.id,error:C(M$,"Shared Codex broker is busy.")});continue}if(s){try{let L=await H.request(z.method,z.params??{});A(K,{id:z.id,result:L})}catch(L){let h=L;A(K,{id:z.id,error:C(h.rpcCode??-32000,h.message)})}continue}let b=$1.has(z.method);if(X=K,b)y=K,N=L$(z.method,z.params??{},null);try{let L=await H.request(z.method,z.params??{});if(A(K,{id:z.id,result:L}),b)N=L$(z.method,z.params??{},L);if(X===K)X=null}catch(L){let h=L;if(A(K,{id:z.id,error:C(h.rpcCode??-32000,h.message)}),X===K)X=null;if(y===K&&b)y=null,N=null}}}),K.on("close",()=>{J.delete(K),f(K)}),K.on("error",()=>{J.delete(K),f(K)})});x.on("SIGTERM",async()=>{await j(k),x.exit(0)}),x.on("SIGINT",async()=>{await j(k),x.exit(0)}),k.listen(Y.path)}Z1().catch(($)=>{x.stderr.write(`${$ instanceof Error?$.message:String($)}
16
+ `),x.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wular/coder",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Delegating coding-agent runtime",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coder",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Delegate coding tasks to a Coder subagent. Codex first, Claude fallback; your main context stays clean.",
5
5
  "author": {
6
6
  "name": "muzam1l"
@@ -9,12 +9,12 @@ shell steps, keep commentary to a line or two, and only expand when something
9
9
  needs the user's decision. Use AskUserQuestion for the decision points.
10
10
 
11
11
  1. In one shell call, ensure the runtime then read its status:
12
- `command -v coder >/dev/null || npm install -g @wular/coder; coder setup --json`
12
+ `command -v coder >/dev/null || npm install -g @wular/coder; coder host-setup --json`
13
13
  (codex/claude availability and auth are in the JSON).
14
14
  2. Codex is the recommended primary engine; Claude (opus subagents in Claude Code) is the fallback. Choose the default from what is installed. Do NOT ask about chain ordering:
15
15
  - **Codex installed** (logged in, or logged out; installed still counts): keep the default `codex → claude` chain.
16
- - **Auto-update if stale**: the default codex model is a GPT-5.6 tier, which needs codex `>= 0.144`. Parse the version from the JSON's `codex.detail` (e.g. `codex-cli 0.143.0`); if it is below `0.144.0`, update it automatically without asking with `codex update` (codex's own updater - it detects the install method and refetches the binary; fall back to `npm install -g @openai/codex@latest` if that fails), then re-run `coder setup --json` to confirm.
17
- - If it is logged out, tell the user to run `codex login` themselves, then re-run `coder setup` to confirm.
16
+ - **Auto-update if stale**: the default codex model is a GPT-5.6 tier, which needs codex `>= 0.144`. Parse the version from the JSON's `codex.detail` (e.g. `codex-cli 0.143.0`); if it is below `0.144.0`, update it automatically without asking with `codex update` (codex's own updater - it detects the install method and refetches the binary; fall back to `npm install -g @openai/codex@latest` if that fails), then re-run `coder host-setup --json` to confirm.
17
+ - If it is logged out, tell the user to run `codex login` themselves, then re-run `coder host-setup` to confirm.
18
18
  - **Codex not installed**: run `coder config set chain claude,codex` so tasks run on Claude opus subagents immediately, tell the user that is the default for now, then ask (AskUserQuestion) whether to install Codex since it is the recommended primary. On yes: `npm install -g @openai/codex`, have them run `codex login`, then `coder config set chain codex,claude`.
19
19
  3. Show the final config (`coder config`) and mention overrides live in `~/.coder/config.json` (machine) and `coder.config.json` (per repo).
20
20
  4. Suggest trying it: "Use Coder to <some small task>".
@@ -13,17 +13,25 @@ If `coder` is not on PATH, install it yourself without asking (`npm install -g @
13
13
 
14
14
  - One coder per focused goal. When the work splits into independent parts, decompose it and dispatch each part as its own background `coder task` - fan out a wide web of coders running in parallel, not one giant dispatch. Give each coder a self-contained goal with all context - overview, file paths, constraints (read-only, git rules). Run independent tasks concurrently; use `steer` to continue a single coder's thread.
15
15
  - Delegation is a hard gate for anything the engine can do itself: do not read source files, investigate, or write code first - no matter how simple the task. Fold into the task text whatever only you have - conversation context, results from tools the engine lacks. The coder worker runs with plugins disabled (no skills, MCP, or connectors), so include any context only a plugin or MCP tool of yours produced.
16
- - Compose one self-contained task text (goal, relevant paths, constraints) and run it as a **background Bash call** so you are notified on completion instead of blocking or polling:
16
+ - Compose one self-contained task text (goal, relevant paths, constraints) and dispatch it. It backgrounds by default: the runtime does a startup check and prints a task id (or errors / hands off, see exit codes):
17
17
 
18
18
  ```bash
19
- coder task --wait "<task text>" # Bash run_in_background: true
19
+ coder task run "<task text>"
20
20
  ```
21
21
 
22
- - The harness re-invokes you when the command exits. Exit 0: usually relay the final message, BUT if stdout is a `spawn-claude-subagent` payload (Claude is the configured engine), this is a clean delegation - spawn the subagent as below, do not treat it as a result. Exit 1: the engine ran but the turn failed - report it, do not retry or fall back yourself. Exit 3: Codex failed and handed off to Claude (see below).
22
+ Fetch the answer with `coder task result <task-id> --wait` - it blocks until the task finishes, then prints only the final answer (keeps your context clean). Run it as a **background Bash call** so it does not block you and you are re-invoked on completion:
23
+
24
+ ```bash
25
+ coder task result <task-id> --wait # Bash run_in_background: true
26
+ ```
27
+
28
+ Only use `--wait` when you can run it in a background shell like that; without one, poll `coder task result <task-id>` (no `--wait`) until it is done. Or skip the two steps and block on the run itself with `--wait` on `coder task run`.
29
+
30
+ - `coder task run` exits after its startup check. Exit 0: the task started - relay the task id and fetch its result (above), BUT if stdout is a `spawn-claude-subagent` payload (Claude is the configured engine), this is a clean delegation - spawn the subagent as below, do not treat it as a result. Exit 1: it failed to start - report it, do not retry or fall back yourself. Exit 3: Codex failed to start and handed off to Claude (see below).
23
31
  - Engine, model, and effort come from config; add `--agent` / `--model` / `--effort` when the user asks or it is unambiguous from context (agents: `codex`, `claude`; codex models: `spark`, `luna`, `terra`, `sol`; claude models: `opus`, `sonnet`, `fable`; efforts: `low|medium|high`).
24
32
  - `spark` is only for the very lightest tasks (formatting, renames, quick lookups) - very fast and very cheap. It runs on a separate quota, so reach for it when the others hit a usage limit; it may still run once they are exhausted.
25
33
  - Permissions default to auto mode (workspace-write + policy-answered escalations). Pass `--permissions read-only` when the task is read-only; `--permissions workspace-write` to forbid any escalation beyond the project.
26
- - For long jobs the user may want to manage by id, drop `--wait`: the runtime detaches a worker, does its own startup check, and prints a job id plus status/result/steer commands. Relay that and do not poll.
34
+ - A background dispatch prints a task id plus its result/steer/stop commands. Relay them and fetch the result (above) rather than polling.
27
35
 
28
36
  ## Claude engine (spawn-claude-subagent payload)
29
37
 
@@ -36,12 +44,12 @@ Spawn one `general-purpose` subagent via the Agent tool, passing the payload's `
36
44
 
37
45
  Relay its output when it completes.
38
46
 
39
- ## Controlling jobs
47
+ ## Controlling tasks
40
48
 
41
- - Continue prior work ("keep going", "apply the top fix"): `coder steer <job-id> "<follow-up>"`.
42
- - Inspect: `coder status <job-id>` / `result <job-id>` / `jobs`.
43
- - Interrupt: `coder stop <job-id>`.
44
- - If status shows `pendingApprovals`, surface them to the user; apply their decision with `coder approve <job-id> <approval-id> [--deny]`.
49
+ - Continue prior work ("keep going", "apply the top fix"): `coder task steer <task-id> "<follow-up>"`.
50
+ - Inspect: `coder task result <task-id>` (status + answer; add `--wait` to block until done) and `coder task list`. (`coder task stream <task-id>` streams the live progress log - to watch/debug in special cases, generally not for you to consume.)
51
+ - Interrupt: `coder task stop <task-id>`.
52
+ - If status shows `pendingApprovals`, surface them to the user; apply their decision with `coder task approve <task-id> <approval-id> [--deny]`.
45
53
 
46
54
  ## Hard rules
47
55
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coder",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "interface": {
5
5
  "displayName": "Coder (plugin)"
6
6
  },
@@ -7,40 +7,42 @@ description: Use Coder for any coding, implementation, or investigation task - f
7
7
 
8
8
  You dispatch coding tasks through the `coder` runtime instead of implementing them yourself. By default the runtime picks the engine from its configured chain; `--agent`/`--model`/`--effort` override it. You never spawn agents yourself in this host.
9
9
 
10
- If `coder` is not on PATH, install it yourself without asking: `npm install -g @wular/coder`, then `coder setup --codex`. Only if that fails, show the user the error and those two commands. On first setup, mention the chain is Codex-first with Claude on fallback. The Claude fallback engine needs the claude CLI; if it is not installed, ask the user before installing it (on yes: `npm install -g @anthropic-ai/claude-code`, then have them run `claude` once to log in). If the user prefers Claude engines first, run `coder config set chain claude,codex`.
10
+ If `coder` is not on PATH, install it yourself without asking: `npm install -g @wular/coder`, then `coder host-setup --codex`. Only if that fails, show the user the error and those two commands. On first setup, mention the chain is Codex-first with Claude on fallback. The Claude fallback engine needs the claude CLI; if it is not installed, ask the user before installing it (on yes: `npm install -g @anthropic-ai/claude-code`, then have them run `claude` once to log in). If the user prefers Claude engines first, run `coder config set chain claude,codex`.
11
11
 
12
12
  When you run setup, also check codex is new enough for the default GPT-5.6 model, which needs codex `>= 0.144` (`codex --version`). If it is older, update it automatically without asking with `codex update` (codex's own updater; fall back to `npm install -g @openai/codex@latest` if it fails), then tell the user to restart their codex session so the update takes effect.
13
13
 
14
14
  ## Dispatching a task
15
15
 
16
16
  - Run every `coder` command with escalated permissions (outside your sandbox), justification: Coder is a supervisor - it spawns engines, keeps state in `~/.coder`, and enforces its own sandbox and approval policy on the task. Never retry a sandbox-blocked `coder` call sandboxed again or with HOME/state env workarounds.
17
- - One coder per focused goal. When the work splits into independent parts, decompose it and dispatch each part as its own `coder task --host codex` call - fan out a wide web of coders, not one giant dispatch. Give each coder a self-contained goal with all context - overview, file paths, constraints (read-only, git rules); use `steer` to continue a single coder's thread.
17
+ - One coder per focused goal. When the work splits into independent parts, decompose it and dispatch each part as its own `coder task run --host codex` call - fan out a wide web of coders, not one giant dispatch. Give each coder a self-contained goal with all context - overview, file paths, constraints (read-only, git rules); use `steer` to continue a single coder's thread.
18
18
  - Delegation is a hard gate for anything the engine can do itself: do not read source files, investigate, or write code first - no matter how simple the task. Fold into the task text whatever only you have - conversation context, results from tools the engine lacks. The coder worker runs with plugins disabled (no skills, MCP, or connectors), so include any context only a plugin or MCP tool of yours produced.
19
- - Compose one self-contained task text (goal, relevant paths, constraints) and run:
19
+ - Compose one self-contained task text (goal, relevant paths, constraints) and dispatch it. It backgrounds by default: the runtime does a startup check and prints a task id (or errors / hands off, see exit codes):
20
20
 
21
21
  ```bash
22
- coder task --host codex --wait "<task text>"
22
+ coder task run --host codex "<task text>"
23
23
  ```
24
24
 
25
- - Always pass `--host codex` so the runtime executes Claude itself instead of asking the host to spawn a subagent.
26
- - Exit 0: relay the final message. Exit 1: the engine ran but the turn failed - report it, do not retry.
27
- - Exit 3: Codex could not start (auth, quota, rate limit - mention this to the user, including any limit-reset time). Rerun once with the Claude engine and relay its result:
25
+ Fetch the answer with `coder task result <task-id> --wait` - it blocks until the task finishes, then prints only the final result (keeps your context clean). Only use `--wait` when you can run it in a **background shell** (so it does not block you); if you can't use that, poll `coder task result <task-id>` (no `--wait`) until it is done. Or skip the two steps and block on the run itself with `--wait` on `coder task run`.
26
+
27
+ - Always pass `--host codex` to identify yourself.
28
+ - `coder task run` exits after its startup check. Exit 0: the task started - fetch its result (above). Exit 1: it failed to start / the turn failed - report it, do not retry.
29
+ - Exit 3: Codex could not start (auth, quota, rate limit - mention this to the user, including any limit-reset time). Rerun once with the Claude engine and fetch its result:
28
30
 
29
31
  ```bash
30
- coder task --host codex --agent claude --wait "<same task text, verbatim>"
32
+ coder task run --host codex --agent claude "<same task text, verbatim>"
31
33
  ```
32
34
 
33
35
  - Engine, model, and effort come from config; add `--agent` / `--model` / `--effort` when the user asks or it is unambiguous from context (agents: `codex`, `claude`; codex models: `spark`, `luna`, `terra`, `sol`; claude models: `opus`, `sonnet`, `fable`; efforts: `low|medium|high`).
34
36
  - `spark` is only for the very lightest tasks (formatting, renames, quick lookups) - very fast and very cheap. It runs on a separate quota, so reach for it when the others hit a usage limit; it may still run once they are exhausted.
35
37
  - Permissions default to auto mode. Pass `--permissions read-only` when the task is read-only; `--permissions workspace-write` to forbid any escalation beyond the project.
36
- - For long jobs the user may want to manage by id, drop `--wait`: the runtime detaches a worker and prints a job id plus status/result/steer commands. Relay that.
38
+ - A background dispatch prints a task id plus its result/steer/stop commands. Relay them and fetch the result (above) rather than polling.
37
39
 
38
- ## Controlling jobs
40
+ ## Controlling tasks
39
41
 
40
- - Continue prior work ("keep going", "apply the top fix"): `coder steer <job-id> "<follow-up>"`.
41
- - Inspect: `coder status <job-id>` / `result <job-id>` / `jobs`.
42
- - Interrupt: `coder stop <job-id>`.
43
- - If status shows `pendingApprovals`, surface them to the user; apply their decision with `coder approve <job-id> <approval-id> [--deny]`.
42
+ - Continue prior work ("keep going", "apply the top fix"): `coder task steer <task-id> "<follow-up>"`.
43
+ - Inspect: `coder task result <task-id>` (status + answer; add `--wait` to block until done) and `coder task list`. (`coder task stream <task-id>` streams the live progress log - to watch/debug in special cases, generally not for you to consume.)
44
+ - Interrupt: `coder task stop <task-id>`.
45
+ - If status shows `pendingApprovals`, surface them to the user; apply their decision with `coder task approve <task-id> <approval-id> [--deny]`.
44
46
 
45
47
  ## Hard rules
46
48