@wular/coder 0.2.9 → 0.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib/broker.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`,"utf8")}function
|
|
5
|
-
`,"utf8")}function
|
|
6
|
-
${
|
|
7
|
-
|
|
8
|
-
`)
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`,
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
`)
|
|
2
|
+
var D$=Object.defineProperty;var P1=($,W)=>{for(var Z in W)D$($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:(q)=>W[Z]=()=>q})};import k from"node:fs";import U1 from"node:net";import W$ from"node:path";import T from"node:process";function K$($,W={}){let Z=new Set(W.valueOptions??[]),q=new Set(W.booleanOptions??[]),K=W.aliasMap??{},X={},Y=[],G=!1;for(let H=0;H<$.length;H+=1){let M=$[H];if(G){Y.push(M);continue}if(M==="--"){G=!0;continue}if(!M.startsWith("-")||M==="-"){Y.push(M);continue}if(M.startsWith("--")){let[y,_]=M.slice(2).split("=",2),A=K[y]??y;if(q.has(A)){X[A]=_===void 0?!0:_!=="false";continue}if(Z.has(A)){let D=_??$[H+1];if(D===void 0)throw Error(`Missing value for --${y}`);if(X[A]=D,_===void 0)H+=1;continue}throw Error(`Unknown option --${y} (use -- to pass literal text starting with -)`)}let R=M.slice(1),x=K[R]??R;if(q.has(x)){X[x]=!0;continue}if(Z.has(x)){let y=$[H+1];if(y===void 0)throw Error(`Missing value for -${R}`);X[x]=y,H+=1;continue}throw Error(`Unknown option -${R} (use -- to pass literal text starting with -)`)}return{options:X,positionals:Y}}import G1 from"node:net";import F from"node:process";import{spawn as M1}from"node:child_process";import N1 from"node:readline";import Y$ from"node:path";import h$ from"node:process";function v$($){return String($??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function X$($,W=h$.platform){if(W==="win32")return`pipe:\\\\.\\pipe\\${v$(`${Y$.win32.basename($)}-codex-app-server`)}`;return`unix:${Y$.join($,"broker.sock")}`}function J($){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 U from"node:fs";import d$ from"node:net";import r$ from"node:os";import u from"node:path";import i from"node:process";import{spawn as s$}from"node:child_process";import{fileURLToPath as o$}from"node:url";import{execFileSync as N$}from"node:child_process";import V from"node:fs";import m$ from"node:os";import N from"node:path";import{spawn as Q$,spawnSync as w$}from"node:child_process";import g$ from"node:fs";import j$ from"node:os";import z$ from"node:path";function H$($){try{let W=Q$("codex",["archive",$],{detached:!0,stdio:"ignore"});W.on("error",()=>{}),W.unref()}catch{}}function S1($){let W=z$.join(process.env.CODEX_HOME||z$.join(j$.homedir(),".codex"),"archived_sessions");try{return g$.readdirSync(W).some((Z)=>Z.endsWith(`-${$}.jsonl`))}catch{return!1}}function I1($){return new Promise((W)=>{try{let Z=Q$("codex",["unarchive",$],{stdio:"ignore"});Z.on("error",()=>W(!1)),Z.on("close",(q)=>W(q===0))}catch{W(!1)}})}function F1($){return w$("codex",["delete","--force",$],{encoding:"utf8"}).status===0}var G$=["completed","failed","cancelled"],h1=["queued","running"];var b$="CODER_HOME";function V$(){return N.resolve(process.env[b$]||N.join(m$.homedir(),".coder"))}var M$=new Map;function n1($){let W=M$.get($);if(W!==void 0)return W;let Z;try{Z=N$("git",["rev-parse","--show-toplevel"],{cwd:$,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{Z=$}return M$.set($,Z),Z}var O$="global";function S($){return N.join(V$(),"state",O$)}var w=null;function n(){if(w)return w;let $=N.join(V$(),"state"),W=[];try{W=V.readdirSync($,{withFileTypes:!0})}catch{}return w=W.filter((Z)=>Z.isDirectory()&&Z.name!==O$).map((Z)=>N.join($,Z.name)),w}function c($){return N.join(S($),"jobs")}function g($){return N.join(S($),"archive")}function P($,W){let Z=N.join(c($),W);if(V.existsSync(N.join(Z,"job.json")))return Z;let q=N.join(g($),W);if(V.existsSync(N.join(q,"job.json")))return q;for(let K of n()){let X=N.join(K,"jobs",W);if(V.existsSync(N.join(X,"job.json")))return X}return Z}function p$($,W){return W.archived?W:R$($,W.id,{archived:!0,archivedAt:new Date().toISOString()})}function U$($,W){let Z=p$($,W);if(W.engine==="codex"&&W.threadId)H$(W.threadId);let q=P($,W.id),K=N.join(g($),W.id);if(q!==K)try{V.mkdirSync(g($),{recursive:!0}),V.renameSync(q,K)}catch{}return Z}function c1(){let $=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${$}`}function R$($,W,Z){let q=P($,W);V.mkdirSync(q,{recursive:!0});let K=N.join(q,"job.json"),Y={...x$($,W)??{id:W,createdAt:new Date().toISOString(),status:"queued"},...Z,updatedAt:new Date().toISOString()};return V.writeFileSync(K,`${JSON.stringify(Y,null,2)}
|
|
3
|
+
`,"utf8"),Y}function y$($){if(!$.engine&&($.agent==="codex"||$.agent==="claude"))$.engine=$.agent;return $}function x$($,W){let Z=N.join(P($,W),"job.json");if(!V.existsSync(Z))return null;try{return y$(JSON.parse(V.readFileSync(Z,"utf8")))}catch{return null}}function l1($,W){let Z=P($,W);if(!V.existsSync(Z))return!1;return V.rmSync(Z,{recursive:!0,force:!0}),!0}function n$($){if(!$)return!1;try{return process.kill($,0),!0}catch(W){return W.code==="EPERM"}}function c$($){try{let W=N$("ps",["-o","lstart=","-p",String($)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Z=W?Date.parse(W):NaN;return Number.isFinite(Z)?Z:null}catch{return null}}function l$($,W){if(!n$($))return!1;let Z=c$($),q=Date.parse(W.createdAt??"");if(Z===null||!Number.isFinite(q))return!0;return Z<=q+60000}var a$=60000;function L$($,W){if(W.status!=="running"&&W.status!=="queued")return W;let Z;if(W.pid)Z=!l$(W.pid,W);else{let q=Date.parse(W.updatedAt??W.createdAt??"");Z=Number.isFinite(q)&&Date.now()-q>a$}if(Z)return R$($,W.id,{status:"failed",error:"worker exited without finishing",completedAt:new Date().toISOString()});return W}function p($,W){let Z=[];for(let q of $){let K=[];try{K=V.readdirSync(q)}catch{continue}for(let X of K){if(W.has(X))continue;let Y=N.join(q,X,"job.json");try{let G=y$(JSON.parse(V.readFileSync(Y,"utf8")));W.add(X),Z.push(G)}catch{}}}return Z}var l=($,W)=>String(W.updatedAt??"").localeCompare(String($.updatedAt??""));function t$($){let W=[c($),...n().map((q)=>N.join(q,"jobs"))],Z=[];for(let q of p(W,new Set))if(q.archived)U$($,q);else Z.push(L$($,q));return Z.sort(l)}function i$($,W){let Z=W?.migrate??!0,q=new Set,K=p([g($)],q),X=[c($),...n().map((Y)=>N.join(Y,"jobs"))];for(let Y of p(X,q))if(Y.archived)K.push(Z?U$($,Y):Y);return K.sort(l)}function a1($,W){let Z=[...t$($),...i$($)].sort(l);if(!W)return Z[0]??null;let q=Z.find((X)=>X.id===W);if(q)return q;let K=Z.filter((X)=>X.id.startsWith(W));if(K.length===1)return K[0];if(K.length>1)throw Error(`Job reference "${W}" is ambiguous. Use a longer id.`);return null}function t1($,W){let Z=P($,W);try{V.mkdirSync(Z,{recursive:!0}),V.writeFileSync(N.join(Z,"heartbeat"),"","utf8")}catch{}}function i1($,W){let Z=P($,W.id),q=Date.parse(W.updatedAt??"")||0;for(let K of["log.jsonl","heartbeat"])try{q=Math.max(q,V.statSync(N.join(Z,K)).mtimeMs)}catch{}return q?new Date(q).toISOString():void 0}async function d1($,W,Z=400){let q=W;while(!G$.includes(q.status))await new Promise((K)=>setTimeout(K,Z)),q=L$($,x$($,q.id)??q);return q}var T$="steer-queue.jsonl";function r1($,W,Z){let q=P($,W);V.mkdirSync(q,{recursive:!0}),V.appendFileSync(N.join(q,T$),`${JSON.stringify({at:new Date().toISOString(),text:Z})}
|
|
4
|
+
`,"utf8")}function s1($,W){let Z=P($,W),q=N.join(Z,T$),K=N.join(Z,`steer-claim-${process.pid}-${Date.now()}.tmp`);try{V.renameSync(q,K)}catch{return[]}try{return V.readFileSync(K,"utf8").split(/\r?\n/).filter(Boolean).map((X)=>{try{return String(JSON.parse(X).text??"")}catch{return""}}).filter(Boolean)}finally{try{V.unlinkSync(K)}catch{}}}function o1($,W,Z){let q=P($,W);V.mkdirSync(q,{recursive:!0}),V.appendFileSync(N.join(q,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...Z})}
|
|
5
|
+
`,"utf8")}function e1($,W,Z=40){let q=N.join(P($,W),"log.jsonl");if(!V.existsSync(q))return[];return V.readFileSync(q,"utf8").split(/\r?\n/).filter(Boolean).slice(-Z).map((X)=>{try{return JSON.parse(X)}catch{return{message:X}}})}import a from"node:fs";import{fileURLToPath as t}from"node:url";var q2=t(import.meta.url);function P$(){try{return JSON.parse(a.readFileSync(t(new URL("../package.json",import.meta.url)),"utf8")).version??"unknown"}catch{return"unknown"}}function K2($){try{return JSON.parse(a.readFileSync($,"utf8")).version??null}catch{return null}}function Y2(){return t(new URL("..",import.meta.url))}var e$="broker.json";function $1($="coder-"){return U.mkdtempSync(u.join(r$.tmpdir(),$))}function W1($){let W=J($);return d$.createConnection({path:W.path})}async function _$($,W=2000){let Z=Date.now();while(Date.now()-Z<W){if(await new Promise((K)=>{let X=W1($);X.on("connect",()=>{X.end(),K(!0)}),X.on("error",()=>K(!1))}))return!0;await new Promise((K)=>setTimeout(K,50))}return!1}function Z1({scriptPath:$,cwd:W,endpoint:Z,pidFile:q,logFile:K,env:X=i.env}){let Y=U.openSync(K,"a"),G=s$(i.execPath,[$,"serve","--endpoint",Z,"--cwd",W,"--pid-file",q],{cwd:W,env:X,detached:!0,stdio:["ignore",Y,Y]});return G.unref(),U.closeSync(Y),G}function q1(){let $=[new URL("./lib/broker.js",import.meta.url),new URL("./broker.js",import.meta.url)];for(let W of $){let Z=o$(W);if(U.existsSync(Z))return Z}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function d($){return u.join(S($),e$)}function r($){let W=d($);if(!U.existsSync(W))return null;try{return JSON.parse(U.readFileSync(W,"utf8"))}catch{return null}}function K1($,W){let Z=S($);U.mkdirSync(Z,{recursive:!0}),U.writeFileSync(d($),`${JSON.stringify(W,null,2)}
|
|
6
|
+
`,"utf8")}function Y1($){let W=d($);if(U.existsSync(W))U.unlinkSync(W)}async function X1($){if(!$)return!1;try{return await _$($,150)}catch{return!1}}async function A$($,W={}){let Z=W.scriptPath??q1(),q=P$(),K=r($),X=K?.version===q&&K?.scriptPath===Z;if(K&&X&&await X1(K.endpoint))return K;if(K)B$({endpoint:K.endpoint??null,pidFile:K.pidFile??null,logFile:K.logFile??null,sessionDir:K.sessionDir??null,pid:K.pid??null,killProcess:W.killProcess??null}),Y1($);let Y=$1(),H=(W.createBrokerEndpoint??X$)(Y,W.platform),M=u.join(Y,"broker.pid"),R=u.join(Y,"broker.log"),x=Z1({scriptPath:Z,cwd:$,endpoint:H,pidFile:M,logFile:R,env:W.env??i.env});if(!await _$(H,W.timeoutMs??2000))return B$({endpoint:H,pidFile:M,logFile:R,sessionDir:Y,pid:x.pid??null,killProcess:W.killProcess??null}),null;let _={endpoint:H,pidFile:M,logFile:R,sessionDir:Y,pid:x.pid??null,version:q,scriptPath:Z};return K1($,_),_}function B$({endpoint:$=null,pidFile:W,logFile:Z,sessionDir:q=null,pid:K=null,killProcess:X=null}){if(Number.isFinite(K)&&X)try{X(K)}catch{}if(W&&U.existsSync(W))U.unlinkSync(W);if(Z&&U.existsSync(Z))U.unlinkSync(Z);if($)try{let G=J($);if(G.kind==="unix"&&U.existsSync(G.path))U.unlinkSync(G.path)}catch{}let Y=q??(W?u.dirname(W):Z?u.dirname(Z):null);if(Y&&U.existsSync(Y))try{U.rmdirSync(Y)}catch{}}import{spawnSync as z1}from"node:child_process";import I from"node:process";function j($,W=[],Z={}){let q=z1($,W,{cwd:Z.cwd,env:Z.env,encoding:"utf8",input:Z.input,maxBuffer:Z.maxBuffer,stdio:Z.stdio??"pipe",shell:I.platform==="win32"?I.env.SHELL||!0:!1,windowsHide:!0});return{command:$,args:W,status:q.status??0,signal:q.signal??null,stdout:q.stdout??"",stderr:q.stderr??"",error:q.error??null}}function T2($,W=["--version"],Z={}){let q=j($,W,Z);if(q.error&&q.error.code==="ENOENT")return{available:!1,detail:"not found"};if(q.error)return{available:!1,detail:q.error.message};if(q.status!==0)return{available:!1,detail:q.stderr.trim()||q.stdout.trim()||`exit ${q.status}`};return{available:!0,detail:q.stdout.trim()||q.stderr.trim()||"ok"}}function Q1($){return/not found|no running instance|cannot find|does not exist|no such process/i.test($)}function J$($,W={}){if(!Number.isFinite($))return{attempted:!1,delivered:!1,method:null};let Z=$,q=W.platform??I.platform,K=W.runCommandImpl??j,X=W.killImpl??I.kill.bind(I);if(q==="win32"){let Y=K("taskkill",["/PID",String(Z),"/T","/F"],{cwd:W.cwd,env:W.env});if(!Y.error&&Y.status===0)return{attempted:!0,delivered:!0,method:"taskkill",result:Y};let G=`${Y.stderr}
|
|
7
|
+
${Y.stdout}`.trim();if(!Y.error&&Q1(G))return{attempted:!0,delivered:!1,method:"taskkill",result:Y};if(Y.error?.code==="ENOENT")try{return X(Z),{attempted:!0,delivered:!0,method:"kill"}}catch(H){if(H?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"kill"};throw H}if(Y.error)throw Y.error;throw Error(H1(Y))}try{return X(-Z,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(Y){if(Y?.code!=="ESRCH")try{return X(Z,"SIGTERM"),{attempted:!0,delivered:!0,method:"process"}}catch(G){if(G?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"process"};throw G}return{attempted:!0,delivered:!1,method:"process-group"}}}function H1($){let W=[`${$.command} ${$.args.join(" ")}`.trim()];if($.signal)W.push(`signal=${$.signal}`);else W.push(`exit=${$.status}`);let Z=($.stderr||"").trim(),q=($.stdout||"").trim();if(Z)W.push(Z);else if(q)W.push(q);return W.join(": ")}var C$="CODER_APP_SERVER_ENDPOINT",f$=-32001,V1="0.144.1",s;function O1(){if(s===void 0){let $=j("codex",["--version"]),W=/(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(`${$.stdout} ${$.stderr}`);s=W?W[1]:V1}return s}function k$(){return{title:"Coder",name:"coder",version:O1()}}var E$={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function u$($,W,Z){return Z===void 0?{code:$,message:W}:{code:$,message:W,data:Z}}function o($,W){let Z=Error($);if(Z.data=W,W?.code!==void 0)Z.rpcCode=W.code;return Z}class e{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=(Z)=>this.defaultHandleServerRequest(Z),this.exitPromise=new Promise((Z)=>{this.resolveExit=Z})}setNotificationHandler($){this.notificationHandler=$}setServerRequestHandler($){this.serverRequestHandler=$}request($,W){if(this.closed)throw Error("codex app-server client is closed.");let Z=this.nextId;return this.nextId+=1,new Promise((q,K)=>{this.pending.set(Z,{resolve:q,reject:K,method:$}),this.sendMessage({id:Z,method:$,params:W})})}notify($,W={}){if(this.closed)return;this.sendMessage({method:$,params:W})}handleChunk($){this.lineBuffer+=$;let W=this.lineBuffer.indexOf(`
|
|
8
|
+
`);while(W!==-1){let Z=this.lineBuffer.slice(0,W);this.lineBuffer=this.lineBuffer.slice(W+1),this.handleLine(Z),W=this.lineBuffer.indexOf(`
|
|
9
|
+
`)}}handleLine($){if(!$.trim())return;let W;try{W=JSON.parse($)}catch(Z){this.handleExit(o(`Failed to parse codex app-server JSONL: ${Z instanceof Error?Z.message:String(Z)}`,{line:$}));return}if(W.id!==void 0&&W.method){this.handleServerRequest(W);return}if(W.id!==void 0){let Z=this.pending.get(W.id);if(!Z)return;if(this.pending.delete(W.id),W.error)Z.reject(o(W.error.message??`codex app-server ${Z.method} failed.`,W.error));else Z.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((Z)=>{this.sendMessage({id:$.id,result:Z??{}})}).catch((Z)=>{this.sendMessage({id:$.id,error:u$(-32000,Z instanceof Error?Z.message:String(Z))})})}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 S$ extends e{proc;readline;constructor($,W={}){super($,W);this.transport="direct"}async initialize(){this.proc=M1("codex",["-c","sandbox_workspace_write.network_access=false","app-server","--disable","plugins"],{cwd:this.cwd,env:this.options.env??F.env,stdio:["pipe","pipe","pipe"],shell:F.platform==="win32"?F.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",(Z)=>{this.stderr+=Z}),this.proc.on("error",(Z)=>{this.handleExit(Z)}),this.proc.on("exit",(Z,q)=>{let K=this.stderr.trim(),X=Z===0?null:o(`codex app-server exited unexpectedly (${q?`signal ${q}`:`exit ${Z}`}).${K?`
|
|
10
|
+
${K}`:""}`);this.handleExit(X)}),this.readline=N1.createInterface({input:$}),this.readline.on("line",(Z)=>{this.handleLine(Z)}),await this.request("initialize",{clientInfo:this.options.clientInfo??k$(),capabilities:this.options.capabilities??E$}),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(F.platform==="win32")try{J$(this.proc.pid)}catch{}else this.proc.kill("SIGTERM")},50).unref?.();await this.exitPromise}sendMessage($){let W=`${JSON.stringify($)}
|
|
11
|
+
`,Z=this.proc?.stdin;if(!Z)throw Error("codex app-server stdin is not available.");Z.write(W)}}class I$ extends e{endpoint;socket;constructor($,W={}){super($,W);this.transport="broker",this.endpoint=W.brokerEndpoint}async initialize(){await new Promise(($,W)=>{let Z=J(this.endpoint);this.socket=G1.createConnection({path:Z.path}),this.socket.setEncoding("utf8"),this.socket.on("connect",$),this.socket.on("data",(q)=>{this.handleChunk(q)}),this.socket.on("error",(q)=>{if(!this.exitResolved)W(q);this.handleExit(q)}),this.socket.on("close",()=>{this.handleExit(this.exitError)})}),await this.request("initialize",{clientInfo:this.options.clientInfo??k$(),capabilities:this.options.capabilities??E$}),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($)}
|
|
12
|
+
`,Z=this.socket;if(!Z)throw Error("codex app-server broker connection is not connected.");Z.write(W)}}class $${static async connect($,W={}){let Z=null;if(!W.disableBroker){if(Z=W.brokerEndpoint??W.env?.[C$]??F.env[C$]??null,!Z&&W.reuseExistingBroker)Z=r($)?.endpoint??null;if(!Z&&!W.reuseExistingBroker)Z=(await A$($,{env:W.env}))?.endpoint??null}let q=Z?new I$($,{...W,brokerEndpoint:Z}):new S$($,W);return await q.initialize(),q}}var R1=new Set(["turn/start","review/start","thread/compact/start"]);function F$($,W,Z){let q=new Set;if(W?.threadId)q.add(W.threadId);if($==="review/start"&&Z?.reviewThreadId)q.add(Z.reviewThreadId);return q}function f($,W,Z){return Z===void 0?{code:$,message:W}:{code:$,message:W,data:Z}}function B($,W){if($.destroyed)return;$.write(`${JSON.stringify(W)}
|
|
13
|
+
`)}var y1=new Set(["turn/interrupt","turn/steer"]);function x1($){return typeof $?.method==="string"&&y1.has($.method)}function L1($){if(!$)return;k.mkdirSync(W$.dirname($),{recursive:!0}),k.writeFileSync($,`${T.pid}
|
|
14
|
+
`,"utf8")}async function T1(){let[$,...W]=T.argv.slice(2);if($!=="serve")throw Error("Usage: node src/lib/broker.mjs serve --endpoint <value> [--cwd <path>] [--pid-file <path>]");let{options:Z}=K$(W,{valueOptions:["cwd","pid-file","endpoint"]});if(!Z.endpoint)throw Error("Missing required --endpoint.");let q=Z.cwd?W$.resolve(T.cwd(),Z.cwd):T.cwd(),K=String(Z.endpoint),X=J(K),Y=Z["pid-file"]?W$.resolve(Z["pid-file"]):null;L1(Y);let G=await $$.connect(q,{disableBroker:!0}),H=null,M=null,R=null,x=new Set,y=new Map;function _(z){for(let[O,C]of y)if(C===z)y.delete(O),G.sendMessage({id:O,error:f(-32000,"Broker client disconnected before answering the server request.")})}function A(z){if(_(z),H===z)H=null;if(M===z)M=null,R=null}function D(z){let O=H??M;if(!O)return;if(B(O,z),z.method==="turn/completed"&&M===O){let C=z.params?.threadId??null;if(!C||!R||R.has(C)){if(M=null,R=null,H===O)H=null}}}async function m(z){for(let O of x)O.end();if(await G.close().catch(()=>{}),await new Promise((O)=>z.close(O)),X.kind==="unix"&&k.existsSync(X.path))k.unlinkSync(X.path);if(Y&&k.existsSync(Y))k.unlinkSync(Y)}G.setNotificationHandler(D),G.handleServerRequest=(z)=>{let O=M??H;if(!O||O.destroyed){G.sendMessage({id:z.id,error:f(-32601,`No broker client available to answer ${z.method}.`)});return}y.set(z.id,O),B(O,z)};let h=U1.createServer((z)=>{x.add(z),z.setEncoding("utf8");let O="";z.on("data",async(C)=>{O+=C;let v=O.indexOf(`
|
|
15
|
+
`);while(v!==-1){let Z$=O.slice(0,v);if(O=O.slice(v+1),v=O.indexOf(`
|
|
16
|
+
`),!Z$.trim())continue;let Q;try{Q=JSON.parse(Z$)}catch(L){B(z,{id:null,error:f(-32700,`Invalid JSON: ${L instanceof Error?L.message:String(L)}`)});continue}if(Q.id!==void 0&&!Q.method&&y.has(Q.id)){y.delete(Q.id),G.sendMessage(Q);continue}if(Q.id!==void 0&&Q.method==="initialize"){B(z,{id:Q.id,result:{userAgent:"coder-broker"}});continue}if(Q.method==="initialized"&&Q.id===void 0)continue;if(Q.id!==void 0&&Q.method==="broker/shutdown")B(z,{id:Q.id,result:{}}),await m(h),T.exit(0);if(Q.id===void 0||!Q.method)continue;let q$=x1(Q)&&M&&M!==z&&!H;if((H&&H!==z||M&&M!==z)&&!q$){B(z,{id:Q.id,error:f(f$,"Shared Codex broker is busy.")});continue}if(q$){try{let L=await G.request(Q.method,Q.params??{});B(z,{id:Q.id,result:L})}catch(L){let E=L;B(z,{id:Q.id,error:f(E.rpcCode??-32000,E.message)})}continue}let b=R1.has(Q.method);if(H=z,b)M=z,R=F$(Q.method,Q.params??{},null);try{let L=await G.request(Q.method,Q.params??{});if(B(z,{id:Q.id,result:L}),b)R=F$(Q.method,Q.params??{},L);if(H===z)H=null}catch(L){let E=L;if(B(z,{id:Q.id,error:f(E.rpcCode??-32000,E.message)}),H===z)H=null;if(M===z&&b)M=null,R=null}}}),z.on("close",()=>{x.delete(z),A(z)}),z.on("error",()=>{x.delete(z),A(z)})});T.on("SIGTERM",async()=>{await m(h),T.exit(0)}),T.on("SIGINT",async()=>{await m(h),T.exit(0)}),h.listen(X.path)}T1().catch(($)=>{T.stderr.write(`${$ instanceof Error?$.message:String($)}
|
|
16
17
|
`),T.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "coder",
|
|
3
3
|
"displayName": "Coder",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.10",
|
|
5
5
|
"description": "Delegate coding tasks to supervised Coder subagents running on Codex, Claude, or any OpenAI-compatible model. Your main context stays clean.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "muzam1l"
|