@messenger-agent/codex-agent 0.38.0-alpha.0 → 0.38.0-alpha.2
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.
|
@@ -5,6 +5,7 @@ type DynamicToolHandler = typeof handleDynamicToolCall;
|
|
|
5
5
|
export declare function findCodexPath(): string;
|
|
6
6
|
export declare class AppServerClient extends EventEmitter {
|
|
7
7
|
private toolHandler;
|
|
8
|
+
private apiKey?;
|
|
8
9
|
private child;
|
|
9
10
|
private nextId;
|
|
10
11
|
private pending;
|
|
@@ -13,7 +14,7 @@ export declare class AppServerClient extends EventEmitter {
|
|
|
13
14
|
private answeredUserInputRequests;
|
|
14
15
|
private started;
|
|
15
16
|
private buffer;
|
|
16
|
-
constructor(toolHandler?: DynamicToolHandler);
|
|
17
|
+
constructor(toolHandler?: DynamicToolHandler, apiKey?: string | undefined);
|
|
17
18
|
request<T = unknown>(method: string, params: unknown): Promise<T>;
|
|
18
19
|
private writeRequest;
|
|
19
20
|
notify(method: string, params: unknown): Promise<void>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as g}from"node:child_process";import{EventEmitter as I}from"node:events";import{statSync as l}from"node:fs";import{createRequire as f}from"node:module";import o from"node:path";import{handleDynamicToolCall as w,inheritManagedTaskToolContextFromNotification as q}from"./dynamic-tools.js";import{appConfig as y}from"./config.js";import{logger as c}from"@messenger-agent/shared/logger";const u="@openai/codex",R={"x86_64-unknown-linux-musl":"@openai/codex-linux-x64","aarch64-unknown-linux-musl":"@openai/codex-linux-arm64","x86_64-apple-darwin":"@openai/codex-darwin-x64","aarch64-apple-darwin":"@openai/codex-darwin-arm64","x86_64-pc-windows-msvc":"@openai/codex-win32-x64","aarch64-pc-windows-msvc":"@openai/codex-win32-arm64"},v=f(import.meta.url);function E(){const{platform:s,arch:e}=process;let t=null;switch(s){case"linux":case"android":e==="x64"&&(t="x86_64-unknown-linux-musl"),e==="arm64"&&(t="aarch64-unknown-linux-musl");break;case"darwin":e==="x64"&&(t="x86_64-apple-darwin"),e==="arm64"&&(t="aarch64-apple-darwin");break;case"win32":e==="x64"&&(t="x86_64-pc-windows-msvc"),e==="arm64"&&(t="aarch64-pc-windows-msvc");break;default:break}if(!t)throw new Error(`Unsupported platform: ${s} (${e})`);const r=R[t];if(!r)throw new Error(`Unsupported target triple: ${t}`);let n;try{const a=v.resolve(`${u}/package.json`),x=f(a).resolve(`${r}/package.json`);n=o.join(o.dirname(x),"vendor")}catch{throw new Error(`Unable to locate Codex CLI binaries. Ensure ${u} is installed with optional dependencies.`)}const i=process.platform==="win32"?"codex.exe":"codex",d=U(n,t,i);if(!d)throw new Error(`Unable to locate Codex CLI binaries for ${t}. Ensure ${u} is installed with optional dependencies.`);return d.executablePath}function U(s,e,t){const r=o.join(s,e),n=o.join(r,"bin",t);if(p(n)&&p(o.join(r,"codex-package.json")))return{executablePath:n,pathDirs:m(o.join(r,"codex-path"))};const i=o.join(r,"codex",t);return p(i)?{executablePath:i,pathDirs:m(o.join(r,"path"))}:null}function m(...s){return s.filter(P)}function p(s){try{return l(s).isFile()}catch{return!1}}function P(s){try{return l(s).isDirectory()}catch{return!1}}function S(s){const e=s.trim();if(!e)return{command:"codex",args:["app-server","--listen","stdio://"]};const t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[],[r,...n]=t.map(i=>i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i);return{command:r??"codex",args:n}}class $ extends I{toolHandler;apiKey;child;nextId=1;pending=new Map;pendingUserInputRequests=new Map;notifiedUserInputRequests=new Set;answeredUserInputRequests=new Set;started;buffer="";constructor(e=w,t){super(),this.toolHandler=e,this.apiKey=t}async request(e,t){return await this.ensureStarted(),this.writeRequest(e,t)}async writeRequest(e,t){if(!this.child)throw new Error("Codex app-server is not running");const r=this.nextId++,n=JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t});return new Promise((i,d)=>{this.pending.set(r,{resolve:a=>i(a),reject:d}),this.child?.stdin.write(`${n}
|
|
2
2
|
`,a=>{a&&(this.pending.delete(r),d(a))})})}async notify(e,t){if(await this.ensureStarted(),!this.child)throw new Error("Codex app-server is not running");this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
|
|
3
|
-
`)}async respondToUserInput(e,t,r){if(await this.ensureStarted(),!this.child)throw new Error("Codex app-server is not running");const
|
|
4
|
-
`),!0):!1}pendingUserInputTurnId(e,t){return this.pendingUserInputRequests.get(
|
|
3
|
+
`)}async respondToUserInput(e,t,r){if(await this.ensureStarted(),!this.child)throw new Error("Codex app-server is not running");const n=h(e,t);if(this.answeredUserInputRequests.has(n))throw new Error(`User input request already answered for item: ${t}`);const i=this.pendingUserInputRequests.get(n);return i?(this.pendingUserInputRequests.delete(n),this.answeredUserInputRequests.add(n),this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:i.requestId,result:r})}
|
|
4
|
+
`),!0):!1}pendingUserInputTurnId(e,t){return this.pendingUserInputRequests.get(h(e,t))?.turnId}discardPendingUserInput(e,t){const r=h(e,t);this.pendingUserInputRequests.delete(r),this.notifiedUserInputRequests.delete(r),this.answeredUserInputRequests.delete(r)}async ensureStarted(){return this.started||(this.started=this.start()),this.started}async start(){const e=process.env.CODEX_APP_SERVER_COMMAND,{command:t,args:r}=e?S(e):{command:E(),args:["app-server","--listen","stdio://"]},n={...process.env,...this.apiKey?{OPENAI_API_KEY:this.apiKey}:null};if(this.child=g(t,r,{env:n,stdio:["pipe","pipe","pipe"]}),this.child.stdout.setEncoding("utf-8"),this.child.stderr.setEncoding("utf-8"),this.child.stdout.on("data",i=>this.handleStdout(i)),this.child.stderr.on("data",i=>c.debug(`codex app-server stderr: ${i.trimEnd()}`)),this.child.on("exit",(i,d)=>this.handleExit(i,d)),this.child.on("error",i=>this.handleProcessError(i)),await this.writeRequest("initialize",{clientInfo:{name:"codex-agent",title:"codex-agent",version:"0.1.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}),!this.child)throw new Error("Codex app-server is not running");this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",method:"initialized",params:{}})}
|
|
5
5
|
`)}handleStdout(e){for(this.buffer+=e;;){const t=this.buffer.indexOf(`
|
|
6
|
-
`);if(t===-1)break;const r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{this.handleMessage(JSON.parse(r))}catch(
|
|
7
|
-
`);return}if(e.method==="item/tool/requestUserInput"){const t=e.params,r=
|
|
6
|
+
`);if(t===-1)break;const r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{this.handleMessage(JSON.parse(r))}catch(n){c.error("Failed to parse codex app-server JSON-RPC message:",n)}}}handleMessage(e){if((!e.method||!(e.method.endsWith("/delta")||e.method.endsWith("/outputDelta")||e.method==="turn/diff/updated"))&&c.debug("Received message:",e),e.id!==void 0&&e.method){this.handleServerRequest(e).catch(t=>c.error("Failed to handle app-server request:",t));return}if(e.id!==void 0){const t=this.pending.get(e.id);if(!t)return;this.pending.delete(e.id),e.error?t.reject(new Error(e.error.message??`Codex app-server request failed: ${e.error.code}`)):t.resolve(e.result);return}e.method&&(q(e.method,e.params),this.emit("notification",{method:e.method,params:e.params}))}async handleServerRequest(e){if(!(!this.child||e.id===void 0||!e.method))try{if(e.method==="item/tool/call"){const t=await this.toolHandler(e.params);this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:e.id,result:t})}
|
|
7
|
+
`);return}if(e.method==="item/tool/requestUserInput"){const t=e.params,r=h(t.threadId,t.itemId);if(this.pendingUserInputRequests.set(r,{threadId:t.threadId,turnId:t.turnId,itemId:t.itemId,requestId:e.id}),this.notifiedUserInputRequests.has(r))return;this.notifiedUserInputRequests.add(r),this.emit("notification",{method:e.method,params:t});return}this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported server request: ${e.method}`}})}
|
|
8
8
|
`)}catch(t){const r=t instanceof Error?t.message:String(t);this.child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:e.id,error:{code:-32e3,message:r}})}
|
|
9
|
-
`)}}handleExit(e,t){const r=new Error(`Codex app-server exited${t?` with signal ${t}`:` with code ${e}`}`);for(const
|
|
9
|
+
`)}}handleExit(e,t){const r=new Error(`Codex app-server exited${t?` with signal ${t}`:` with code ${e}`}`);for(const n of this.pending.values())n.reject(r);this.pending.clear(),this.pendingUserInputRequests.clear(),this.notifiedUserInputRequests.clear(),this.answeredUserInputRequests.clear(),this.child=void 0,this.started=void 0,this.emit("exit",r)}handleProcessError(e){for(const t of this.pending.values())t.reject(e);this.pending.clear(),this.pendingUserInputRequests.clear(),this.notifiedUserInputRequests.clear(),this.answeredUserInputRequests.clear(),this.emit("exit",e)}}function h(s,e){return`${s}:${e}`}const b=new $(w,y.codex.apiKey);b.setMaxListeners(20);export{$ as AppServerClient,b as appServerClient,E as findCodexPath};
|
package/dist/codex.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{mkdirSync as k,existsSync as P}from"node:fs";import{appServerClient as
|
|
2
|
-
`);return{items:d,finalResponse:i||void 0,usage:a}}async runStreamed(e,t){const n=
|
|
3
|
-
`)}class
|
|
1
|
+
import{mkdirSync as k,existsSync as P}from"node:fs";import{appServerClient as c}from"./app-server-client.js";import{dynamicToolSpecs as U}from"./dynamic-tools.js";import{loadAllSessions as E,persistSession as T}from"./db.js";import{appConfig as p}from"./config.js";import{logger as _}from"@messenger-agent/shared/logger";import{resolveAgentWorkdir as C}from"@messenger-agent/shared/agent-workspaces";import{loadCodexPlatformInstructions as N}from"./platform-instructions.js";const v=N(void 0,p.schedule?.enabled===!0);class I extends Error{path;constructor(e){super(`Workdir not found: ${e}`),this.path=e}}class b{id;model;workingDirectory;constructor(e,t,n){this.id=e,this.model=t,this.workingDirectory=n}async run(e,t){const n=await this.runStreamed(e,t),r=new Map,o=new Set;let a=null;for await(const u of n.events)if(u.type==="item.started")o.has(u.item.id)||r.set(u.item.id,u.item);else if(u.type==="item.completed")o.add(u.item.id),r.set(u.item.id,u.item);else if(u.type==="thread.tokenUsage.updated")a=u.usage;else if(u.type==="turn.failed")throw new Error(u.error.message);const d=Array.from(r.values()),i=d.filter(u=>u.type==="agentMessage").map(u=>u.text).join(`
|
|
2
|
+
`);return{items:d,finalResponse:i||void 0,usage:a}}async runStreamed(e,t){const n=c.request("turn/start",this.turnStartParams(e,t)),r=await this.waitForTurnStart(n,t?.signal),o=r.turn.id;return{turnId:o,events:this.eventsForTurn(o,r.turn,t?.signal)}}async waitForTurnStart(e,t){if(!t)return e;let n,r;const o=new Promise((d,i)=>{r=i}),a=()=>{n=t.reason??new DOMException("The operation was aborted","AbortError"),r(n)};t.addEventListener("abort",a,{once:!0}),t.aborted&&a();try{return await Promise.race([e,o])}catch(d){throw d===n&&e.then(i=>this.interrupt(i.turn.id)).catch(i=>_.error("Failed to clean up aborted Codex turn start:",i)),d}finally{t.removeEventListener("abort",a)}}async steerStreamed(e,t,n){const r={threadId:this.id,input:[{type:"text",text:e}],expectedTurnId:t},o=await c.request("turn/steer",r);return{turnId:o.turnId,events:this.eventsForTurn(o.turnId,void 0,n?.signal,void 0,!0)}}async continueWithUserInput(e,t,n){const r=c.pendingUserInputTurnId(this.id,e);return r?{turnId:r,events:this.eventsForTurn(r,void 0,n?.signal,async()=>{if(!await c.respondToUserInput(this.id,e,t))throw new Error(`No pending user input request found for item: ${e}`)})}:(await this.interruptStaleTurn(n?.sourceTurnId),this.runStreamed(F(e,t),n))}async submitPendingUserInput(e,t){const n=c.pendingUserInputTurnId(this.id,e);if(!(!n||!await c.respondToUserInput(this.id,e,t)))return n}async interrupt(e){await c.request("turn/interrupt",{threadId:this.id,turnId:e})}async interruptPendingUserInput(e,t){await this.interrupt(e),c.discardPendingUserInput(this.id,t)}async interruptStaleTurn(e){if(!e)return;(await c.request("thread/read",{threadId:this.id,includeTurns:!0})).thread.turns?.find(r=>r.id===e)?.status==="inProgress"&&await this.interrupt(e)}turnStartParams(e,t){return{threadId:this.id,input:[{type:"text",text:e,text_elements:[]}],cwd:this.workingDirectory,approvalPolicy:"never",model:this.model,...t?.collaborationMode?{collaborationMode:t.collaborationMode}:null}}async*eventsForTurn(e,t,n,r,o=!1){const a=[...t||o?[{type:"thread.started",thread_id:this.id},{type:"turn.started",turn_id:e}]:[],...t?A(t):[]];let d=t?.status==="completed"||t?.status==="failed"||t?.status==="interrupted",i,u=!1,l=()=>{};const f=({method:h,params:w})=>{if(u)return;const g=R(h,w,this.id,e);g&&(a.push(g),(g.type==="turn.completed"||g.type==="turn.failed")&&(d=!0),l())},y=h=>{i=h,d=!0,l()},m=()=>{u=!0,a.length=0,d=!0,l()};c.on("notification",f),c.on("exit",y),n?.addEventListener("abort",m,{once:!0}),n?.aborted&&m();try{for(await r?.();!d||a.length>0;){for(;a.length>0;)yield a.shift();if(d)break;await new Promise(h=>{const w=setTimeout(()=>{l=()=>{},h()},50);l=()=>{clearTimeout(w),l=()=>{},h()}})}i&&(yield{type:"error",message:i.message})}finally{c.off("notification",f),c.off("exit",y),n?.removeEventListener("abort",m)}}}function F(s,e){return[`The user answered a previous request_user_input prompt (${s}), but the original pending tool request is no longer active.`,"Continue the task using this answer:",JSON.stringify(e,null,2)].join(`
|
|
3
|
+
`)}class M{sessions=new Map;constructor(){for(const e of E())this.sessions.set(e.sessionId,{workdir:e.workdir,botName:e.botName??"main",llmProxyBinding:e.llmProxyBinding});_.info(`SessionManager: loaded ${this.sessions.size} persisted sessions`)}async getOrCreate(e,t,n,r,o,a,d){const i=this.resolveWorkdir(n,r);if(e){const l=this.sessions.get(e);if(l&&l.workdir===i){const f=l.llmProxyBinding??d,y=await c.request("thread/resume",this.threadResumeParams(e,o,i,a,f));if(!l.llmProxyBinding&&f){const m={...l,llmProxyBinding:f};this.sessions.set(e,m),T({sessionId:e,botName:m.botName,workdir:m.workdir,createdAt:Date.now(),llmProxyBinding:f})}return{thread:new b(y.thread.id,o,i),sessionId:e,isNewSession:!1}}}if(n&&!P(i))throw new I(i);k(i,{recursive:!0});const u=await c.request("thread/start",this.threadStartParams(o,i,a,d));return{thread:new b(u.thread.id,o,i),sessionId:void 0,isNewSession:!0}}async fork(e,t,n,r,o,a,d){const i=this.resolveWorkdir(n,r);if(n&&!P(i))throw new I(i);k(i,{recursive:!0});const l=(await c.request("thread/fork",this.threadForkParams(e.threadId,e.turnId,o,i,a,d))).thread.id;return this.persist(l,t,n,r,d),{thread:new b(l,o,i),sessionId:l,isNewSession:!1}}persist(e,t,n,r,o){const a=t??"main",d=this.resolveWorkdir(n,r);this.sessions.set(e,{botName:a,workdir:d,llmProxyBinding:o}),T({sessionId:e,botName:a,workdir:d,createdAt:Date.now(),llmProxyBinding:o})}bindingFor(e){return e?this.sessions.get(e)?.llmProxyBinding:void 0}workdirFor(e){return e?this.sessions.get(e)?.workdir:void 0}hasSession(e){return!!e&&this.sessions.has(e)}resolveWorkdir(e,t){return C(p,t,e)}threadStartParams(e,t,n,r){return{model:e,modelProvider:p.codex.baseUrl?"custom":null,cwd:t,approvalPolicy:"never",sandbox:n,config:this.codexConfig(r),developerInstructions:v,dynamicTools:U(p.schedule?.enabled===!0),experimentalRawEvents:!1,persistExtendedHistory:!1}}threadResumeParams(e,t,n,r,o){return{threadId:e,model:t,modelProvider:p.codex.baseUrl?"custom":null,cwd:n,approvalPolicy:"never",sandbox:r,config:this.codexConfig(o),developerInstructions:v,excludeTurns:!0,persistExtendedHistory:!1}}threadForkParams(e,t,n,r,o,a){return{threadId:e,lastTurnId:t,model:n,modelProvider:p.codex.baseUrl?"custom":null,cwd:r,approvalPolicy:"never",sandbox:o,config:this.codexConfig(a),developerInstructions:v,ephemeral:!1,excludeTurns:!0}}codexConfig(e){return{approval_policy:"never",...p.codex.baseUrl?{model_provider:"custom",model_reasoning_effort:"medium",disable_response_storage:!0,model_providers:{custom:{name:"custom",base_url:p.codex.baseUrl,wire_api:"responses",...p.codex.apiKey?{env_key:"OPENAI_API_KEY"}:null,...e?{http_headers:{"X-Elevo-LLM-Binding":e}}:null}},"features.default_mode_request_user_input":!1}:null}}}function A(s){const e=[];for(const t of s.items??[])e.push({type:"item.completed",item:t});return s.status==="completed"?e.push({type:"turn.completed"}):s.status==="failed"&&e.push({type:"turn.failed",error:{message:s.error?.message??"Codex turn failed"}}),e}function R(s,e,t,n){const r=e;if(!r)return;const o=r.threadId,a=r.turnId;if(!(typeof o=="string"&&o!==t)&&!(typeof a=="string"&&a!==n)){if(s==="item/started"&&S(r.item))return{type:"item.started",item:r.item};if(s==="item/completed"&&S(r.item))return{type:"item.completed",item:r.item};if(s==="item/agentMessage/delta")return x(r,"agentMessage");if(s==="item/reasoning/summaryTextDelta"||s==="item/reasoning/textDelta")return x(r,"reasoning");if(s==="item/plan/delta")return x(r,"plan");if(s==="item/tool/requestUserInput")return{type:"item.tool.requestUserInput",params:r};if(s==="turn/diff/updated"&&typeof r.diff=="string")return{type:"turn.diff.updated",diff:r.diff};if(s==="thread/tokenUsage/updated")return{type:"thread.tokenUsage.updated",usage:D(r)};if(s==="turn/completed"){const d=r.turn;return d?.status==="failed"?{type:"turn.failed",error:{message:d.error?.message??"Codex turn failed"}}:{type:"turn.completed"}}if(s==="error")return console.error("Received error notification from app-server:",r),{type:"error",message:q(r)}}}function q(s){const e=s.error,t=e&&typeof e=="object"&&"message"in e?e.message:void 0,n=s.additionalDetails,r=typeof t=="string"&&t.trim()?t:"Codex app-server error";return typeof n=="string"&&n.trim()?`${r}: ${n}`:r}function x(s,e){if(!(typeof s.itemId!="string"||typeof s.delta!="string"))return{type:"item.delta",item_id:s.itemId,item_type:e,delta:s.delta}}function D(s){const e=s.tokenUsage;if(!e||typeof e!="object")return null;const t=e,n=t.total,r=t.last;if(!n||typeof n!="object"||!r||typeof r!="object")return null;const o=d=>{const i=d;return{input_tokens:typeof i.inputTokens=="number"?i.inputTokens:void 0,output_tokens:typeof i.outputTokens=="number"?i.outputTokens:void 0,total_tokens:typeof i.totalTokens=="number"?i.totalTokens:void 0}},a=t.modelContextWindow;return{total:o(n),last:o(r),model_context_window:typeof a=="number"?a:void 0}}function S(s){return!!(s&&typeof s=="object"&&"type"in s&&"id"in s)}const z=new M;export{b as CodexThread,I as WorkdirNotFoundError,z as sessionManager};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@messenger-agent/codex-agent",
|
|
3
|
-
"version": "0.38.0-alpha.
|
|
3
|
+
"version": "0.38.0-alpha.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"ws": "^8.21.0",
|
|
23
23
|
"yaml": "^2.9.0",
|
|
24
24
|
"zod": "^4.4.3",
|
|
25
|
-
"@messenger-agent/shared": "0.38.0-alpha.
|
|
25
|
+
"@messenger-agent/shared": "0.38.0-alpha.2"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/ws": "^8.18.1"
|