@wular/coder 0.1.2 → 0.1.4

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
- import o from"node:fs";import At from"node:net";import T from"node:path";import W from"node:process";function p(t,u={}){let r=new Set(u.valueOptions??[]),n=new Set(u.booleanOptions??[]),h=u.aliasMap??{},f={},y=[],a=!1;for(let b=0;b<t.length;b+=1){let x=t[b];if(a){y.push(x);continue}if(x==="--"){a=!0;continue}if(!x.startsWith("-")||x==="-"){y.push(x);continue}if(x.startsWith("--")){let[O,G]=x.slice(2).split("=",2),R=h[O]??O;if(n.has(R)){f[R]=G===void 0?!0:G!=="false";continue}if(r.has(R)){let X=G??t[b+1];if(X===void 0)throw Error(`Missing value for --${O}`);if(f[R]=X,G===void 0)b+=1;continue}y.push(x);continue}let j=x.slice(1),J=h[j]??j;if(n.has(J)){f[J]=!0;continue}if(r.has(J)){let O=t[b+1];if(O===void 0)throw Error(`Missing value for -${j}`);f[J]=O,b+=1;continue}y.push(x)}return{options:f,positionals:y}}import Ut from"node:net";import Q from"node:process";import{spawn as vt}from"node:child_process";import Lt from"node:readline";import B from"node:path";import bt from"node:process";function $t(t){return String(t??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function F(t,u=bt.platform){if(u==="win32")return`pipe:\\\\.\\pipe\\${$t(`${B.win32.basename(t)}-codex-app-server`)}`;return`unix:${B.join(t,"broker.sock")}`}function z(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 Wt from"node:net";import Nt from"node:os";import Z from"node:path";import A from"node:process";import{spawn as Rt}from"node:child_process";import{fileURLToPath as zt}from"node:url";import{createHash as lt}from"node:crypto";import{execFileSync as jt}from"node:child_process";import S from"node:fs";import Jt from"node:os";import H from"node:path";var Ot="CODER_HOME";function Mt(){return H.resolve(process.env[Ot]||H.join(Jt.homedir(),".coder"))}function Ht(t){try{return jt("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return t}}function K(t){let u=Ht(t),r=u;try{r=S.realpathSync.native(u)}catch{r=u}let h=(H.basename(u)||"workspace").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"workspace",f=lt("sha256").update(r).digest("hex").slice(0,12);return H.join(Mt(),"state",`${h}-${f}`)}function g(t){return H.join(K(t),"jobs")}function U(t,u){return H.join(g(t),u)}function et(){let t=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${t}`}function st(t,u,r){let n=U(t,u);S.mkdirSync(n,{recursive:!0});let h=H.join(n,"job.json"),y={...d(t,u)??{id:u,createdAt:new Date().toISOString()},...r,updatedAt:new Date().toISOString()};return S.writeFileSync(h,`${JSON.stringify(y,null,2)}
3
- `,"utf8"),y}function d(t,u){let r=H.join(U(t,u),"job.json");if(!S.existsSync(r))return null;try{return JSON.parse(S.readFileSync(r,"utf8"))}catch{return null}}function St(t){let u=g(t);if(!S.existsSync(u))return[];return S.readdirSync(u).map((r)=>d(t,r)).filter(Boolean).sort((r,n)=>String(n.updatedAt??"").localeCompare(String(r.updatedAt??"")))}function tu(t,u){let r=St(t);if(!u)return r[0]??null;let n=r.find((f)=>f.id===u);if(n)return n;let h=r.filter((f)=>f.id.startsWith(u));if(h.length===1)return h[0];if(h.length>1)throw Error(`Job reference "${u}" is ambiguous. Use a longer id.`);return null}function uu(t,u,r){let n=U(t,u);S.mkdirSync(n,{recursive:!0}),S.appendFileSync(H.join(n,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...r})}
4
- `,"utf8")}function ru(t,u,r=40){let n=H.join(U(t,u),"log.jsonl");if(!S.existsSync(n))return[];return S.readFileSync(n,"utf8").split(/\r?\n/).filter(Boolean).slice(-r).map((f)=>{try{return JSON.parse(f)}catch{return{message:f}}})}var Gt="broker.json";function Vt(t="coder-"){return l.mkdtempSync(Z.join(Nt.tmpdir(),t))}function Zt(t){let u=z(t);return Wt.createConnection({path:u.path})}async function s(t,u=2000){let r=Date.now();while(Date.now()-r<u){if(await new Promise((h)=>{let f=Zt(t);f.on("connect",()=>{f.end(),h(!0)}),f.on("error",()=>h(!1))}))return!0;await new Promise((h)=>setTimeout(h,50))}return!1}function mt({scriptPath:t,cwd:u,endpoint:r,pidFile:n,logFile:h,env:f=A.env}){let y=l.openSync(h,"a"),a=Rt(A.execPath,[t,"serve","--endpoint",r,"--cwd",u,"--pid-file",n],{cwd:u,env:f,detached:!0,stdio:["ignore",y,y]});return a.unref(),l.closeSync(y),a}function ot(){let t=[new URL("./lib/broker.js",import.meta.url),new URL("./broker.js",import.meta.url)];for(let u of t){let r=zt(u);if(l.existsSync(r))return r}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function w(t){return Z.join(K(t),Gt)}function E(t){let u=w(t);if(!l.existsSync(u))return null;try{return JSON.parse(l.readFileSync(u,"utf8"))}catch{return null}}function qt(t,u){let r=K(t);l.mkdirSync(r,{recursive:!0}),l.writeFileSync(w(t),`${JSON.stringify(u,null,2)}
5
- `,"utf8")}function Qt(t){let u=w(t);if(l.existsSync(u))l.unlinkSync(u)}async function Xt(t){if(!t)return!1;try{return await s(t,150)}catch{return!1}}async function tt(t,u={}){let r=E(t);if(r&&await Xt(r.endpoint))return r;if(r)e({endpoint:r.endpoint??null,pidFile:r.pidFile??null,logFile:r.logFile??null,sessionDir:r.sessionDir??null,pid:r.pid??null,killProcess:u.killProcess??null}),Qt(t);let n=Vt(),f=(u.createBrokerEndpoint??F)(n,u.platform),y=Z.join(n,"broker.pid"),a=Z.join(n,"broker.log"),b=u.scriptPath??ot(),x=mt({scriptPath:b,cwd:t,endpoint:f,pidFile:y,logFile:a,env:u.env??A.env});if(!await s(f,u.timeoutMs??2000))return e({endpoint:f,pidFile:y,logFile:a,sessionDir:n,pid:x.pid??null,killProcess:u.killProcess??null}),null;let J={endpoint:f,pidFile:y,logFile:a,sessionDir:n,pid:x.pid??null};return qt(t,J),J}function e({endpoint:t=null,pidFile:u,logFile:r,sessionDir:n=null,pid:h=null,killProcess:f=null}){if(Number.isFinite(h)&&f)try{f(h)}catch{}if(u&&l.existsSync(u))l.unlinkSync(u);if(r&&l.existsSync(r))l.unlinkSync(r);if(t)try{let a=z(t);if(a.kind==="unix"&&l.existsSync(a.path))l.unlinkSync(a.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 Yt}from"node:child_process";import q from"node:process";function ut(t,u=[],r={}){let n=Yt(t,u,{cwd:r.cwd,env:r.env,encoding:"utf8",input:r.input,maxBuffer:r.maxBuffer,stdio:r.stdio??"pipe",shell:q.platform==="win32"?q.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 Ou(t,u=["--version"],r={}){let n=ut(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 Ct(t){return/not found|no running instance|cannot find|does not exist|no such process/i.test(t)}function rt(t,u={}){if(!Number.isFinite(t))return{attempted:!1,delivered:!1,method:null};let r=u.platform??q.platform,n=u.runCommandImpl??ut,h=u.killImpl??q.kill.bind(q);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&&Ct(y))return{attempted:!0,delivered:!1,method:"taskkill",result:f};if(f.error?.code==="ENOENT")try{return h(t),{attempted:!0,delivered:!0,method:"kill"}}catch(a){if(a?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"kill"};throw a}if(f.error)throw f.error;throw Error(Kt(f))}try{return h(-t,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(f){if(f?.code!=="ESRCH")try{return h(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 Kt(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 nt="CODER_APP_SERVER_ENDPOINT",ct=-32001,ht={title:"Coder",name:"coder",version:"0.1.0"},it={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function ft(t,u,r){return r===void 0?{code:t,message:u}:{code:t,message:u,data:r}}function P(t,u){let r=Error(t);if(r.data=u,u?.code!==void 0)r.rpcCode=u.code;return r}class _{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,h)=>{this.pending.set(r,{resolve:n,reject:h,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(`
2
+ var $t=Object.defineProperty;var Tt=(t,u)=>{for(var r in u)$t(t,r,{get:u[r],enumerable:!0,configurable:!0,set:(n)=>u[r]=()=>n})};import m from"node:fs";import At from"node:net";import T from"node:path";import S from"node:process";function p(t,u={}){let r=new Set(u.valueOptions??[]),n=new Set(u.booleanOptions??[]),i=u.aliasMap??{},f={},a=[],x=!1;for(let $=0;$<t.length;$+=1){let y=t[$];if(x){a.push(y);continue}if(y==="--"){x=!0;continue}if(!y.startsWith("-")||y==="-"){a.push(y);continue}if(y.startsWith("--")){let[J,z]=y.slice(2).split("=",2),N=i[J]??J;if(n.has(N)){f[N]=z===void 0?!0:z!=="false";continue}if(r.has(N)){let Q=z??t[$+1];if(Q===void 0)throw Error(`Missing value for --${J}`);if(f[N]=Q,z===void 0)$+=1;continue}throw Error(`Unknown option --${J} (use -- to pass literal text starting with -)`)}let j=y.slice(1),O=i[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:a}}import Kt from"node:net";import w from"node:process";import{spawn as vt}from"node:child_process";import Lt from"node:readline";import B from"node:path";import bt from"node:process";function lt(t){return String(t??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function F(t,u=bt.platform){if(u==="win32")return`pipe:\\\\.\\pipe\\${lt(`${B.win32.basename(t)}-codex-app-server`)}`;return`unix:${B.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 Wt from"node:net";import Nt from"node:os";import V from"node:path";import L from"node:process";import{spawn as Rt}from"node:child_process";import{fileURLToPath as zt}from"node:url";import{createHash as jt}from"node:crypto";import{execFileSync as Jt}from"node:child_process";import H from"node:fs";import Ot from"node:os";import M from"node:path";var ot="CODER_HOME";function Mt(){return M.resolve(process.env[ot]||M.join(Ot.homedir(),".coder"))}function Ht(t){try{return Jt("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return t}}function Y(t){let u=Ht(t),r=u;try{r=H.realpathSync.native(u)}catch{r=u}let i=(M.basename(u)||"workspace").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"workspace",f=jt("sha256").update(r).digest("hex").slice(0,12);return M.join(Mt(),"state",`${i}-${f}`)}function g(t){return M.join(Y(t),"jobs")}function C(t,u){return M.join(g(t),u)}function uu(){let t=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${t}`}function ru(t,u,r){let n=C(t,u);H.mkdirSync(n,{recursive:!0});let i=M.join(n,"job.json"),a={...d(t,u)??{id:u,createdAt:new Date().toISOString()},...r,updatedAt:new Date().toISOString()};return H.writeFileSync(i,`${JSON.stringify(a,null,2)}
3
+ `,"utf8"),a}function d(t,u){let r=M.join(C(t,u),"job.json");if(!H.existsSync(r))return null;try{return JSON.parse(H.readFileSync(r,"utf8"))}catch{return null}}function St(t){let u=g(t);if(!H.existsSync(u))return[];return H.readdirSync(u).map((r)=>d(t,r)).filter(Boolean).sort((r,n)=>String(n.updatedAt??"").localeCompare(String(r.updatedAt??"")))}function nu(t,u){let r=St(t);if(!u)return r[0]??null;let n=r.find((f)=>f.id===u);if(n)return n;let i=r.filter((f)=>f.id.startsWith(u));if(i.length===1)return i[0];if(i.length>1)throw Error(`Job reference "${u}" is ambiguous. Use a longer id.`);return null}function fu(t,u,r){let n=C(t,u);H.mkdirSync(n,{recursive:!0}),H.appendFileSync(M.join(n,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...r})}
4
+ `,"utf8")}function cu(t,u,r=40){let n=M.join(C(t,u),"log.jsonl");if(!H.existsSync(n))return[];return H.readFileSync(n,"utf8").split(/\r?\n/).filter(Boolean).slice(-r).map((f)=>{try{return JSON.parse(f)}catch{return{message:f}}})}var Gt="broker.json";function Vt(t="coder-"){return l.mkdtempSync(V.join(Nt.tmpdir(),t))}function Zt(t){let u=R(t);return Wt.createConnection({path:u.path})}async function s(t,u=2000){let r=Date.now();while(Date.now()-r<u){if(await new Promise((i)=>{let f=Zt(t);f.on("connect",()=>{f.end(),i(!0)}),f.on("error",()=>i(!1))}))return!0;await new Promise((i)=>setTimeout(i,50))}return!1}function mt({scriptPath:t,cwd:u,endpoint:r,pidFile:n,logFile:i,env:f=L.env}){let a=l.openSync(i,"a"),x=Rt(L.execPath,[t,"serve","--endpoint",r,"--cwd",u,"--pid-file",n],{cwd:u,env:f,detached:!0,stdio:["ignore",a,a]});return x.unref(),l.closeSync(a),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=zt(u);if(l.existsSync(r))return r}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function A(t){return V.join(Y(t),Gt)}function E(t){let u=A(t);if(!l.existsSync(u))return null;try{return JSON.parse(l.readFileSync(u,"utf8"))}catch{return null}}function wt(t,u){let r=Y(t);l.mkdirSync(r,{recursive:!0}),l.writeFileSync(A(t),`${JSON.stringify(u,null,2)}
5
+ `,"utf8")}function Qt(t){let u=A(t);if(l.existsSync(u))l.unlinkSync(u)}async function Ut(t){if(!t)return!1;try{return await s(t,150)}catch{return!1}}async function tt(t,u={}){let r=E(t);if(r&&await Ut(r.endpoint))return r;if(r)e({endpoint:r.endpoint??null,pidFile:r.pidFile??null,logFile:r.logFile??null,sessionDir:r.sessionDir??null,pid:r.pid??null,killProcess:u.killProcess??null}),Qt(t);let n=Vt(),f=(u.createBrokerEndpoint??F)(n,u.platform),a=V.join(n,"broker.pid"),x=V.join(n,"broker.log"),$=u.scriptPath??qt(),y=mt({scriptPath:$,cwd:t,endpoint:f,pidFile:a,logFile:x,env:u.env??L.env});if(!await s(f,u.timeoutMs??2000))return e({endpoint:f,pidFile:a,logFile:x,sessionDir:n,pid:y.pid??null,killProcess:u.killProcess??null}),null;let O={endpoint:f,pidFile:a,logFile:x,sessionDir:n,pid:y.pid??null};return wt(t,O),O}function e({endpoint:t=null,pidFile:u,logFile:r,sessionDir:n=null,pid:i=null,killProcess:f=null}){if(Number.isFinite(i)&&f)try{f(i)}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 a=n??(u?V.dirname(u):r?V.dirname(r):null);if(a&&l.existsSync(a))try{l.rmdirSync(a)}catch{}}import{spawnSync as Xt}from"node:child_process";import q from"node:process";function ut(t,u=[],r={}){let n=Xt(t,u,{cwd:r.cwd,env:r.env,encoding:"utf8",input:r.input,maxBuffer:r.maxBuffer,stdio:r.stdio??"pipe",shell:q.platform==="win32"?q.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 Hu(t,u=["--version"],r={}){let n=ut(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 Yt(t){return/not found|no running instance|cannot find|does not exist|no such process/i.test(t)}function rt(t,u={}){if(!Number.isFinite(t))return{attempted:!1,delivered:!1,method:null};let r=u.platform??q.platform,n=u.runCommandImpl??ut,i=u.killImpl??q.kill.bind(q);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 a=`${f.stderr}
6
+ ${f.stdout}`.trim();if(!f.error&&Yt(a))return{attempted:!0,delivered:!1,method:"taskkill",result:f};if(f.error?.code==="ENOENT")try{return i(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(Ct(f))}try{return i(-t,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(f){if(f?.code!=="ESRCH")try{return i(t,"SIGTERM"),{attempted:!0,delivered:!0,method:"process"}}catch(a){if(a?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"process"};throw a}return{attempted:!0,delivered:!1,method:"process-group"}}}function Ct(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 nt="CODER_APP_SERVER_ENDPOINT",ct=-32001,it={title:"Coder",name:"coder",version:"0.1.0"},ht={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function ft(t,u,r){return r===void 0?{code:t,message:u}:{code:t,message:u,data:r}}function P(t,u){let r=Error(t);if(r.data=u,u?.code!==void 0)r.rpcCode=u.code;return r}class _{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,i)=>{this.pending.set(r,{resolve:n,reject:i,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
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(P(`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(P(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:ft(-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:ft(-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 yt extends _{proc;readline;constructor(t,u={}){super(t,u);this.transport="direct"}async initialize(){this.proc=vt("codex",["app-server"],{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:P(`codex app-server exited unexpectedly (${u?`signal ${u}`:`exit ${t}`}).${r?`
9
- ${r}`:""}`);this.handleExit(n)}),this.readline=Lt.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??it}),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{rt(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 xt extends _{endpoint;socket;constructor(t,u={}){super(t,u);this.transport="broker",this.endpoint=u.brokerEndpoint}async initialize(){await new Promise((t,u)=>{let r=z(this.endpoint);this.socket=Ut.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??it}),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 D{static async connect(t,u={}){let r=null;if(!u.disableBroker){if(r=u.brokerEndpoint??u.env?.[nt]??Q.env[nt]??null,!r&&u.reuseExistingBroker)r=E(t)?.endpoint??null;if(!r&&!u.reuseExistingBroker)r=(await tt(t,{env:u.env}))?.endpoint??null}let n=r?new xt(t,{...u,brokerEndpoint:r}):new yt(t,u);return await n.initialize(),n}}var wt=new Set(["turn/start","review/start","thread/compact/start"]);function at(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 m(t,u,r){return r===void 0?{code:t,message:u}:{code:t,message:u,data:r}}function N(t,u){if(t.destroyed)return;t.write(`${JSON.stringify(u)}
12
- `)}function Et(t){return t?.method==="turn/interrupt"}function Pt(t){if(!t)return;o.mkdirSync(T.dirname(t),{recursive:!0}),o.writeFileSync(t,`${W.pid}
13
- `,"utf8")}async function _t(){let[t,...u]=W.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}=p(u,{valueOptions:["cwd","pid-file","endpoint"]});if(!r.endpoint)throw Error("Missing required --endpoint.");let n=r.cwd?T.resolve(W.cwd(),r.cwd):W.cwd(),h=String(r.endpoint),f=z(h),y=r["pid-file"]?T.resolve(r["pid-file"]):null;Pt(y);let a=await D.connect(n,{disableBroker:!0}),b=null,x=null,j=null,J=new Set,O=new Map;function G(c){for(let[$,V]of O)if(V===c)O.delete($),a.sendMessage({id:$,error:m(-32000,"Broker client disconnected before answering the server request.")})}function R(c){if(G(c),b===c)b=null;if(x===c)x=null,j=null}function X(c){let $=b??x;if(!$)return;if(N($,c),c.method==="turn/completed"&&x===$){let V=c.params?.threadId??null;if(!V||!j||j.has(V)){if(x=null,j=null,b===$)b=null}}}async function v(c){for(let $ of J)$.end();if(await a.close().catch(()=>{}),await new Promise(($)=>c.close($)),f.kind==="unix"&&o.existsSync(f.path))o.unlinkSync(f.path);if(y&&o.existsSync(y))o.unlinkSync(y)}a.setNotificationHandler(X),a.handleServerRequest=(c)=>{let $=x??b;if(!$||$.destroyed){a.sendMessage({id:c.id,error:m(-32601,`No broker client available to answer ${c.method}.`)});return}O.set(c.id,$),N($,c)};let Y=At.createServer((c)=>{J.add(c),c.setEncoding("utf8");let $="";c.on("data",async(V)=>{$+=V;let C=$.indexOf(`
14
- `);while(C!==-1){let I=$.slice(0,C);if($=$.slice(C+1),C=$.indexOf(`
15
- `),!I.trim())continue;let i;try{i=JSON.parse(I)}catch(M){N(c,{id:null,error:m(-32700,`Invalid JSON: ${M.message}`)});continue}if(i.id!==void 0&&!i.method&&O.has(i.id)){O.delete(i.id),a.sendMessage(i);continue}if(i.id!==void 0&&i.method==="initialize"){N(c,{id:i.id,result:{userAgent:"coder-broker"}});continue}if(i.method==="initialized"&&i.id===void 0)continue;if(i.id!==void 0&&i.method==="broker/shutdown")N(c,{id:i.id,result:{}}),await v(Y),W.exit(0);if(i.id===void 0||!i.method)continue;let k=Et(i)&&x&&x!==c&&!b;if((b&&b!==c||x&&x!==c)&&!k){N(c,{id:i.id,error:m(ct,"Shared Codex broker is busy.")});continue}if(k){try{let M=await a.request(i.method,i.params??{});N(c,{id:i.id,result:M})}catch(M){N(c,{id:i.id,error:m(M.rpcCode??-32000,M.message)})}continue}let L=wt.has(i.method);if(b=c,L)x=c,j=at(i.method,i.params??{},null);try{let M=await a.request(i.method,i.params??{});if(N(c,{id:i.id,result:M}),L)j=at(i.method,i.params??{},M);if(b===c)b=null}catch(M){if(N(c,{id:i.id,error:m(M.rpcCode??-32000,M.message)}),b===c)b=null;if(x===c&&L)x=null,j=null}}}),c.on("close",()=>{J.delete(c),R(c)}),c.on("error",()=>{J.delete(c),R(c)})});W.on("SIGTERM",async()=>{await v(Y),W.exit(0)}),W.on("SIGINT",async()=>{await v(Y),W.exit(0)}),Y.listen(f.path)}_t().catch((t)=>{W.stderr.write(`${t instanceof Error?t.message:String(t)}
16
- `),W.exit(1)});
8
+ `)}}handleLine(t){if(!t.trim())return;let u;try{u=JSON.parse(t)}catch(r){this.handleExit(P(`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(P(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:ft(-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:ft(-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 at extends _{proc;readline;constructor(t,u={}){super(t,u);this.transport="direct"}async initialize(){this.proc=vt("codex",["app-server"],{cwd:this.cwd,env:this.options.env??w.env,stdio:["pipe","pipe","pipe"],shell:w.platform==="win32"?w.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:P(`codex app-server exited unexpectedly (${u?`signal ${u}`:`exit ${t}`}).${r?`
9
+ ${r}`:""}`);this.handleExit(n)}),this.readline=Lt.createInterface({input:this.proc.stdout}),this.readline.on("line",(t)=>{this.handleLine(t)}),await this.request("initialize",{clientInfo:this.options.clientInfo??it,capabilities:this.options.capabilities??ht}),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(w.platform==="win32")try{rt(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 xt extends _{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=Kt.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??it,capabilities:this.options.capabilities??ht}),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 D{static async connect(t,u={}){let r=null;if(!u.disableBroker){if(r=u.brokerEndpoint??u.env?.[nt]??w.env[nt]??null,!r&&u.reuseExistingBroker)r=E(t)?.endpoint??null;if(!r&&!u.reuseExistingBroker)r=(await tt(t,{env:u.env}))?.endpoint??null}let n=r?new xt(t,{...u,brokerEndpoint:r}):new at(t,u);return await n.initialize(),n}}var Et=new Set(["turn/start","review/start","thread/compact/start"]);function yt(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 Z(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 _t(t){if(!t)return;m.mkdirSync(T.dirname(t),{recursive:!0}),m.writeFileSync(t,`${S.pid}
13
+ `,"utf8")}async function Dt(){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}=p(u,{valueOptions:["cwd","pid-file","endpoint"]});if(!r.endpoint)throw Error("Missing required --endpoint.");let n=r.cwd?T.resolve(S.cwd(),r.cwd):S.cwd(),i=String(r.endpoint),f=R(i),a=r["pid-file"]?T.resolve(r["pid-file"]):null;_t(a);let x=await D.connect(n,{disableBroker:!0}),$=null,y=null,j=null,O=new Set,J=new Map;function z(c){for(let[b,G]of J)if(G===c)J.delete(b),x.sendMessage({id:b,error:Z(-32000,"Broker client disconnected before answering the server request.")})}function N(c){if(z(c),$===c)$=null;if(y===c)y=null,j=null}function Q(c){let b=$??y;if(!b)return;if(W(b,c),c.method==="turn/completed"&&y===b){let G=c.params?.threadId??null;if(!G||!j||j.has(G)){if(y=null,j=null,$===b)$=null}}}async function K(c){for(let b of O)b.end();if(await x.close().catch(()=>{}),await new Promise((b)=>c.close(b)),f.kind==="unix"&&m.existsSync(f.path))m.unlinkSync(f.path);if(a&&m.existsSync(a))m.unlinkSync(a)}x.setNotificationHandler(Q),x.handleServerRequest=(c)=>{let b=y??$;if(!b||b.destroyed){x.sendMessage({id:c.id,error:Z(-32601,`No broker client available to answer ${c.method}.`)});return}J.set(c.id,b),W(b,c)};let U=At.createServer((c)=>{O.add(c),c.setEncoding("utf8");let b="";c.on("data",async(G)=>{b+=G;let X=b.indexOf(`
14
+ `);while(X!==-1){let I=b.slice(0,X);if(b=b.slice(X+1),X=b.indexOf(`
15
+ `),!I.trim())continue;let h;try{h=JSON.parse(I)}catch(o){W(c,{id:null,error:Z(-32700,`Invalid JSON: ${o.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(c,{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(c,{id:h.id,result:{}}),await K(U),S.exit(0);if(h.id===void 0||!h.method)continue;let k=Pt(h)&&y&&y!==c&&!$;if(($&&$!==c||y&&y!==c)&&!k){W(c,{id:h.id,error:Z(ct,"Shared Codex broker is busy.")});continue}if(k){try{let o=await x.request(h.method,h.params??{});W(c,{id:h.id,result:o})}catch(o){W(c,{id:h.id,error:Z(o.rpcCode??-32000,o.message)})}continue}let v=Et.has(h.method);if($=c,v)y=c,j=yt(h.method,h.params??{},null);try{let o=await x.request(h.method,h.params??{});if(W(c,{id:h.id,result:o}),v)j=yt(h.method,h.params??{},o);if($===c)$=null}catch(o){if(W(c,{id:h.id,error:Z(o.rpcCode??-32000,o.message)}),$===c)$=null;if(y===c&&v)y=null,j=null}}}),c.on("close",()=>{O.delete(c),N(c)}),c.on("error",()=>{O.delete(c),N(c)})});S.on("SIGTERM",async()=>{await K(U),S.exit(0)}),S.on("SIGINT",async()=>{await K(U),S.exit(0)}),U.listen(f.path)}Dt().catch((t)=>{S.stderr.write(`${t instanceof Error?t.message:String(t)}
16
+ `),S.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wular/coder",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Delegating coding-agent runtime",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,5 +23,8 @@
23
23
  },
24
24
  "engines": {
25
25
  "node": ">=18"
26
+ },
27
+ "dependencies": {
28
+ "zod": "^4.4.3"
26
29
  }
27
30
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: coder
3
- description: Use for any coding or implementation task - features, fixes, refactors, debugging, tests. Dispatches the task to the configured engine chain (Codex or Claude Code) in seconds. Give it one focused, self-contained goal with all context - overview, file paths, constraints e.g. read-only, git rules.
3
+ description: Use Coder for any coding, implementation, or investigation task - features, fixes, refactors, debugging, tests, questions about the code. You are the orchestrator - never implement tasks yourself; dispatch them through the `coder` CLI exactly as this skill instructs, never via your own subagents. Give it one focused, self-contained goal with all context - overview, file paths, constraints e.g. read-only, git rules.
4
4
  ---
5
5
 
6
6
  # Coder dispatch
@@ -1,6 +1,9 @@
1
1
  {
2
2
  "name": "Coder",
3
3
  "version": "0.0.0",
4
+ "interface": {
5
+ "displayName": "Coder (plugin)"
6
+ },
4
7
  "description": "Delegate coding tasks to a Coder subagent. Your main context stays clean.",
5
8
  "skills": "./skills/"
6
9
  }
@@ -1,7 +1,8 @@
1
1
  ---
2
2
  name: coder
3
- description: Use for any coding or implementation task - features, fixes, refactors, debugging, tests. Dispatches the task to the configured engine chain (Codex or Claude). Give it one focused, self-contained goal with all context - overview, file paths, constraints e.g. read-only, git rules.
3
+ description: Use Coder for any coding, implementation, or investigation task - features, fixes, refactors, debugging, tests, questions about the code. You are the orchestrator - never implement tasks yourself; dispatch them through the `coder` CLI exactly as this skill instructs, never via your own subagents. Give it one focused, self-contained goal with all context - overview, file paths, constraints e.g. read-only, git rules.
4
4
  ---
5
+
5
6
  # Coder dispatch (codex host)
6
7
 
7
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.
@@ -10,12 +11,14 @@ If `coder` is not on PATH, set it up yourself: `npm install -g @wular/coder`, th
10
11
 
11
12
  ## Dispatching a task
12
13
 
14
+ - 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.
13
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.
14
16
  - Compose one self-contained task text (goal, relevant paths, constraints) and run:
15
17
 
16
18
  ```bash
17
19
  coder task --host codex --wait "<task text>"
18
20
  ```
21
+
19
22
  - Always pass `--host codex` so the runtime executes Claude itself instead of asking the host to spawn a subagent.
20
23
  - Exit 0: relay the final message. Exit 1: the engine ran but the turn failed - report it, do not retry.
21
24
  - 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:
@@ -23,6 +26,7 @@ If `coder` is not on PATH, set it up yourself: `npm install -g @wular/coder`, th
23
26
  ```bash
24
27
  coder task --host codex --agent claude --wait "<same task text, verbatim>"
25
28
  ```
29
+
26
30
  - 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`, `5.5`; claude models: `opus`, `sonnet`, `fable`; efforts: `low|medium|high`).
27
31
  - 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.
28
32
  - 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.