@yuandc/aica 0.1.43 → 0.1.44
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 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import u from"node:fs";import{BoundedItemBuffer as c}from"../../client/bounded-buffer.js";import{JsonLineRpcClient as h}from"../../client/json-rpc.js";import{startCodexAppServer as p}from"./codex-process.js";import{extractAssistantTextFromTurn as m,mapCodexNotification as f}from"./events.js";import{CodexPlanDeltaState as g}from"./plan-events.js";import{isCodexApprovalRequest as C,resolveCodexApprovalRequest as w}from"./permissions.js";const T=1500,v={sessionResume:!0,imageInput:!0,fileAttachment:!0,filesystem:!0,terminal:!0,permissionRequest:!0,configOptions:!0,usage:!0,contextUsage:!0,contextCompaction:!0,plan:!0,diff:!0};class z{id="native-codex";name="Native Codex";capabilities=v;async createSession(e){return new x(e.cwd,e.providerSessionId??null,e.timeoutMs)}}class x{cwd;providerSessionId;defaultTimeoutMs;started;rpc;initialized=!1;content="";promptActive=!1;currentTurnId=null;updates=new c(16);statusTimeline=[];statusCallback=null;updateCallback=null;permissionCallback=null;abortHandler=null;completedTurns=new Map;pendingTurnCompletions=new Map;agentMessagePhases=new Map;planDeltas=new g;constructor(e,s,t=b()){this.cwd=e,this.providerSessionId=s,this.defaultTimeoutMs=t,this.started=p(e),this.rpc=new h(this.started.child,{onNotification:(n,r)=>this.handleNotification(n,r),onRequest:(n,r)=>this.handleReverseRequest(n,r)})}async sendPrompt(e){const s=Date.now(),t=l(e.mode);this.statusCallback=e.onStatus??null,this.updateCallback=e.onUpdate??null,this.permissionCallback=e.onPermissionRequest??null,this.attachAbortSignal(e.signal),this.emitStatus("initializing","Codex 初始化中","initialize"),await this.initialize();const n=await this.establishThread(e);this.emitStatus("thinking","思考中"),this.content="",this.updates.clear(),this.agentMessagePhases.clear(),this.planDeltas.reset(),this.promptActive=!0;let r,a;try{r=await this.rpc.request("turn/start",{threadId:n,clientUserMessageId:`aca-${Date.now()}-${Math.random().toString(16).slice(2)}`,input:S(e.prompt,e.promptBlocks),cwd:e.cwd,...e.model?{model:e.model}:{},...y(e.configOptionValues)},e.timeoutMs??this.defaultTimeoutMs);const o=String(r?.turn?.id??"");this.currentTurnId=o||null,a=o?await this.waitForTurnCompleted(o,e.timeoutMs??this.defaultTimeoutMs):r?.turn}finally{this.promptActive=!1,this.currentTurnId=null}const d=this.content.trim()||m(a);return this.emitStatus("completed","已完成"),{providerSessionId:n,cliType:"builtin",agentType:"codex",effectiveConfig:t,command:this.started.command,args:this.started.args,cwd:this.cwd,exitCode:this.rpc.exitCode,signal:this.rpc.signal,durationMs:Date.now()-s,stdout:this.rpc.stdout,stderr:this.rpc.stderr,content:d,updateCount:this.updates.count(),updates:this.updates.snapshot(),statusTimeline:this.statusTimeline,promptResponse:r}}async cancel(){try{this.providerSessionId&&this.started.child.exitCode===null&&this.started.child.signalCode===null&&await this.rpc.request("turn/interrupt",{threadId:this.providerSessionId,turnId:this.currentTurnId??""},T).catch(()=>{})}finally{await this.close()}}async close(){this.statusCallback=null,this.updateCallback=null,this.permissionCallback=null;for(const e of this.pendingTurnCompletions.values())clearTimeout(e.timer),e.reject(new Error("Codex app-server session closed"));this.pendingTurnCompletions.clear(),this.abortHandler&&(this.abortHandler=null),await this.closeCodexProcess()}async closeCodexProcess(){this.started.child.exitCode!==null||this.started.child.signalCode!==null||(this.started.child.stdin.end(),!await this.waitForProcessClose(2e3)&&(this.started.child.kill("SIGTERM"),!await this.waitForProcessClose(1e3)&&(this.started.child.kill("SIGKILL"),await this.waitForProcessClose(1e3))))}waitForProcessClose(e){return this.started.child.exitCode!==null||this.started.child.signalCode!==null?Promise.resolve(!0):new Promise(s=>{const t=setTimeout(()=>s(!1),e);t.unref(),this.started.child.once("close",()=>{clearTimeout(t),s(!0)})})}async initialize(){this.initialized||(await this.rpc.request("initialize",{clientInfo:{name:"aca",version:"0.1.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}),this.initialized=!0)}async establishThread(e){const s=l(e.mode);if(this.providerSessionId)try{this.emitStatus("resuming","Codex 会话恢复中","thread/resume");const r=await this.rpc.request("thread/resume",{threadId:this.providerSessionId,cwd:e.cwd,...e.model?{model:e.model}:{},approvalsReviewer:"user",...s},6e4);return this.providerSessionId=String(r?.thread?.id??this.providerSessionId),this.providerSessionId}catch(r){if(e.requireSessionResume){const a=r instanceof Error?r.message:String(r);throw new Error(`无法恢复导入的 Codex Session ${this.providerSessionId}:${a}`)}this.providerSessionId=null}this.emitStatus("acp","Codex 启动中","thread/start");const n=(await this.rpc.request("thread/start",{cwd:e.cwd,...e.model?{model:e.model}:{},approvalsReviewer:"user",...s,ephemeral:!1,threadSource:"aca"},6e4))?.thread?.id;if(!n)throw new Error("Codex app-server thread/start did not return thread id");return this.providerSessionId=n,n}attachAbortSignal(e){if(e){if(this.abortHandler=()=>{this.cancel()},e.aborted)throw new Error("ACP prompt cancelled");e.addEventListener("abort",this.abortHandler,{once:!0})}}handleNotification(e,s){!this.promptActive&&!M(e)||(this.rpc.refreshPendingRequestTimeout("turn/start"),this.updates.push({method:e,params:s}),this.captureAgentMessagePhase(e,s),this.appendFinalAnswerDelta(e,s),e==="turn/completed"&&this.resolveTurnCompleted(s),f(e,s,{pushUpdate:t=>this.updateCallback?.(t),pushStatus:(t,n,r,a)=>this.emitStatus(t,n,r,a)},{agentMessagePhases:this.agentMessagePhases,planDeltas:this.planDeltas}))}captureAgentMessagePhase(e,s){if(e!=="item/started"&&e!=="item/completed")return;const t=s?.item;t?.type!=="agentMessage"||!t.id||this.agentMessagePhases.set(t.id,t.phase??"")}appendFinalAnswerDelta(e,s){if(e!=="item/agentMessage/delta")return;const t=s;if(!t.itemId||typeof t.delta!="string")return;const n=this.agentMessagePhases.get(t.itemId);(n==="final_answer"||!n)&&(this.content+=t.delta)}waitForTurnCompleted(e,s){const t=this.completedTurns.get(e);return t?Promise.resolve(t):new Promise((n,r)=>{const a=setTimeout(()=>{this.pendingTurnCompletions.delete(e),r(new Error("Codex app-server request timed out while waiting for turn/completed"))},s);a.unref(),this.pendingTurnCompletions.set(e,{resolve:n,reject:r,timer:a})})}resolveTurnCompleted(e){const s=e?.turn,t=s?.id;if(!t)return;this.completedTurns.set(t,s);const n=this.pendingTurnCompletions.get(t);if(n){if(this.pendingTurnCompletions.delete(t),clearTimeout(n.timer),s.status==="failed"){n.reject(new Error(`Codex turn failed: ${JSON.stringify(s.error??{})}`));return}n.resolve(s)}}async handleReverseRequest(e,s){return C(e)?(this.emitStatus("requestPermission","等待授权",I(s),e),w(e,s,this.permissionCallback)):{}}emitStatus(e,s,t,n){const r={phase:e,label:s,...t?{detail:t}:{},...n?{updateType:n}:{},atMs:Date.now()},a=this.statusTimeline[this.statusTimeline.length-1];a&&a.phase===r.phase&&a.label===r.label&&a.detail===r.detail&&a.updateType===r.updateType||(this.statusTimeline.push(r),this.statusCallback?.(r))}}function S(i,e){return(e?.length?e:[{type:"text",text:i}]).map(t=>t.type==="image"?t.uri&&u.existsSync(t.uri)?{type:"localImage",path:t.uri}:{type:"image",url:`data:${t.mimeType};base64,${t.data}`}:{type:"text",text:t.text,text_elements:[]})}function l(i){const e=String(i||"").trim();return e==="read-only"?{approvalPolicy:"on-request",sandbox:"read-only"}:e==="acceptEdits"||e==="accept-edits"?{approvalPolicy:"on-failure",sandbox:"workspace-write"}:["agent-full-access","full-access","bypassPermissions","danger-full-access"].includes(e)?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function y(i){if(!i)return{};const e={},s=i.reasoning_effort??i.reasoningEffort??i.model_reasoning_effort??i.modelReasoningEffort??i.effort;return typeof s=="string"&&s&&(e.effort=s),e}function I(i){if(!i||typeof i!="object"||Array.isArray(i))return;const e=i;for(const s of["command","cwd","reason","grantRoot"]){const t=e[s];if(typeof t=="string"&&t.trim())return P(t)}}function P(i){const e=i.replace(/\s+/g," ").trim();return e.length>120?`${e.slice(0,117)}...`:e}function M(i){return i.startsWith("thread/")?!0:["account/rateLimits/updated","account/updated","configWarning","warning","model/rerouted","thread/compacted"].includes(i)}function b(){const i=Number.parseInt(process.env.ACA_ACP_PROMPT_TIMEOUT_MS??"",10);return Number.isInteger(i)&&i>=3e4?i:360*60*1e3}export{z as NativeCodexProvider,v as nativeCodexCapabilities};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{JsonLineRpcClient as
|
|
2
|
-
`);this.lineBuffer=t.pop()??"";for(const s of t){const n=s.trim();if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}this.handleMessage(r)}}async handleMessage(e){if("id"in e&&("result"in e||"error"in e)&&typeof e.method!="string"){this.handleParentResponse(e);return}const t=typeof e.method=="string"?e.method:"",s=e.id;if(t){if(s===void 0){await this.handleNotification(t,u(e.params));return}try{const n=await this.handleRequest(t,u(e.params));this.write({jsonrpc:"2.0",id:s,result:n})}catch(n){this.write({jsonrpc:"2.0",id:s,error:{code:-32603,message:n instanceof Error?n.message:String(n)}})}}}async handleNotification(e,t){e==="session/cancel"&&await this.cancel(t)}async handleRequest(e,t){switch(e){case"initialize":return this.initializeResponse();case"aca/runtime_config":return this.applyRuntimeConfig(t);case"session/new":return this.newSession(t);case"session/resume":case"session/load":return this.resumeSession(t);case"session/fork":return this.forkSession(t);case"session/prompt":return this.prompt(t);case"session/compact":return this.manualCompact(t);case"session/cancel":return await this.cancel(t),{};case"session/close":return await this.closeSession(t),{};case"session/set_config_option":return this.setConfigOption(t);case"session/set_mode":return this.setMode(t);case"fs/read_text_file":case"fs/write_text_file":case"terminal/create":case"terminal/output":case"terminal/wait_for_exit":case"terminal/kill":case"terminal/release":return{};default:throw new Error(`Unsupported ACP method: ${e}`)}}initializeResponse(){return{protocolVersion:1,agentCapabilities:{loadSession:!0,sessionCapabilities:{resume:!0,close:!0}}}}applyRuntimeConfig(e){if(this.started)throw new Error("Codex runtime config must be applied before app-server starts");const t=u(e.codexProvider);if(Object.keys(t).length===0)return this.managedProvider=null,{configured:!1};const s=a(t,"baseUrl"),n=a(t,"apiKey"),r=Number(t.revision||0);if(!s||!n||!Number.isSafeInteger(r)||r<1)throw new Error("Invalid Codex managed provider runtime config");return this.managedProvider={baseUrl:s,apiKey:n,revision:r},{configured:!0,revision:r}}async newSession(e){const t=a(e,"cwd")||process.cwd();this.applyInitialConfig(e),await this.ensureCodex(t);const s=await this.requireRpc().request("thread/start",{cwd:t,approvalsReviewer:"user",...this.codexConfig(),ephemeral:!1,experimentalRawEvents:!0,threadSource:"aca-codex-acp"},6e4),n=I(s);if(!n)throw new Error("Codex thread/start did not return thread id");return this.currentSessionId=n,this.currentCwd=t,this.resetSubtaskState(),this.captureThreadMetadata(s),this.sessionResponse(n)}async resumeSession(e){const t=a(e,"sessionId");if(!t)throw new Error("sessionId is required");const s=a(e,"cwd")||this.currentCwd;this.applyInitialConfig(e),await this.ensureCodex(s);const n=await this.requireRpc().request("thread/resume",{threadId:t,cwd:s,approvalsReviewer:"user",...this.codexConfig()},6e4);return this.currentSessionId=I(n)||t,this.currentCwd=s,this.resetSubtaskState(n),await this.subscribeKnownSubtasks(!1),this.captureThreadMetadata(n),this.sessionResponse(this.currentSessionId)}async forkSession(e){const t=a(e,"sessionId");if(!t)throw new Error("sessionId is required");const s=a(e,"cwd")||this.currentCwd;this.applyInitialConfig(e),await this.ensureCodex(s);const n=await this.requireRpc().request("thread/fork",{threadId:t,cwd:s,approvalsReviewer:"user",ephemeral:!1,threadSource:"aca-codex-acp-fork",...this.codexConfig()},12e4),r=I(n);if(!r)throw new Error("Codex thread/fork did not return thread id");return this.currentSessionId=r,this.currentCwd=s,this.resetSubtaskState(n),this.captureThreadMetadata(n),this.sessionResponse(r)}async prompt(e){const t=a(e,"sessionId")||this.currentSessionId;let s=this.resolveSessionAlias(t);if(!s)throw new Error("sessionId is required");const n=Array.isArray(e.prompt)?e.prompt:[],r=this.requireRpc();this.currentSessionId&&this.currentSessionId!==s&&this.resetSubtaskState(),this.currentSessionId=s;const o=await this.maintainContext("before",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{allowRollover:!0});Z(o),s=this.currentSessionId||s,this.promptActive=!0,this.currentTurnId=null,this.currentPromptText=H(n),this.currentAssistantText="",this.currentAffectedFiles.clear(),this.connectionRecovery.reset(),this.agentMessagePhases.clear(),this.planDeltas.reset(),this.pendingSubtaskNotifications=[];let c;try{c=await r.request("turn/start",{threadId:s,clientUserMessageId:`aca-acp-${Date.now()}-${Math.random().toString(16).slice(2)}`,input:J(n),cwd:this.currentCwd,...V(this.config)},U());const d=String(c?.turn?.id??"");this.currentTurnId=d||null;const l=d?await this.waitForTurnCompleted(d,U()):c?.turn;this.threadTurnCount+=1,this.previousUserText=this.currentPromptText,this.previousAssistantText=this.currentAssistantText,this.previousAffectedFiles.clear();for(const f of this.currentAffectedFiles)this.previousAffectedFiles.add(f);const h=await this.maintainContext("after",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{allowRollover:!0});return{stopReason:"end_turn",sessionId:this.currentSessionId,turn:l,_meta:{acaContextUsage:A(h)??Y(this.latestTokenUsage),acaContextMaintenance:h}}}catch(d){const l=this.connectionRecovery.fail(d);throw l&&this.notifySessionUpdate(l),d}finally{this.promptActive=!1,this.currentTurnId=null,this.pendingSubtaskNotifications=[]}}resetSubtaskState(e){this.subtaskRouter.reset(),this.subtaskAgentMessagePhases.clear(),this.subtaskPlanDeltas.clear(),this.subscribedSubtaskThreadIds.clear(),this.pendingSubtaskSubscriptions.clear(),this.hydratedSubtaskThreadIds.clear(),this.seenSubtaskItemIds.clear(),this.pendingSubtaskNotifications=[],e!==void 0&&this.subtaskRouter.restoreFromSessionSnapshot(e,this.currentSessionId)}async subscribeKnownSubtasks(e=!0){const t=this.subtaskRouter.routesForSubscription().map(s=>this.subscribeSubtask(s,e));await Promise.allSettled(t)}subscribeSubtask(e,t){const s=e.sourceThreadId;if(!s||s===this.currentSessionId||this.subscribedSubtaskThreadIds.has(s))return Promise.resolve();const n=this.pendingSubtaskSubscriptions.get(s);if(n)return n;const r=this.requireRpc().request("thread/resume",{threadId:s,approvalsReviewer:"user",excludeTurns:!1},6e4).then(o=>{this.subscribedSubtaskThreadIds.add(s);const c=this.subtaskRouter.restoreFromSessionSnapshot(o,this.currentSessionId);t&&this.hydrateSubtaskHistory(o,e),c>0&&this.subscribeKnownSubtasks(t)}).catch(()=>{}).finally(()=>{this.pendingSubtaskSubscriptions.delete(s)});return this.pendingSubtaskSubscriptions.set(s,r),r}async cancel(e){const t=a(e,"sessionId")||this.currentSessionId;if(!(!t||!this.rpc)&&(await this.rpc.request("turn/interrupt",{threadId:t}).catch(()=>{}),this.currentTurnId)){const s=this.pendingTurnCompletions.get(this.currentTurnId);s&&(this.pendingTurnCompletions.delete(this.currentTurnId),clearTimeout(s.timer),s.reject(new Error("Codex prompt cancelled")))}}async manualCompact(e){const t=a(e,"sessionId")||this.currentSessionId,s=this.resolveSessionAlias(t);if(!s)throw new Error("sessionId is required");if(this.promptActive||this.maintenanceActive)throw new Error("Codex session is busy");this.currentSessionId=s;const n=k(),r=await this.maintainContext("manual",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{force:!0,allowRollover:e.allowRollover===!0,compactTimeoutMs:X(e,n.compactTimeoutMs)}),o=String(r.action||"");if(o==="compact_failed"||o==="rollover_failed"){const c=String(r.compactError||"Codex 上下文压缩未完成");throw new Error(`Codex 上下文压缩失败:${c}`)}return{sessionId:this.currentSessionId,maintenance:r,contextUsage:A(r)}}async closeSession(e){await this.shutdown()}async ensureCodex(e){if(this.rpc&&this.started&&this.started.child.exitCode===null&&this.started.child.signalCode===null)return;if(this.codexStartupPromise){await this.codexStartupPromise;return}const t=(async()=>{if(this.rpc&&this.started&&this.started.child.exitCode===null&&this.started.child.signalCode===null)return;const s=E(e,this.managedProvider),n=new F(s.child,{peerName:"Codex app-server",onNotification:(r,o)=>this.handleCodexNotification(r,o),onRequest:async(r,o)=>this.handleCodexRequest(r,o)});this.started=s,this.rpc=n,this.initialized=!1,await n.request("initialize",{clientInfo:{name:"aca-codex-acp",version:"0.1.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}},6e4),this.initialized=!0})();this.codexStartupPromise=t;try{await t}catch(s){throw this.rpc&&this.started&&!this.initialized&&await y(this.started.child,1e3),this.rpc=null,this.started=null,s}finally{this.codexStartupPromise===t&&(this.codexStartupPromise=null)}}handleCodexNotification(e,t){const s=R(t);if(this.maintenanceActive&&(!s.threadId||s.threadId===this.currentSessionId)){this.captureContextNotification(e,t);return}if(!K(t,this.currentSessionId,this.currentTurnId)){if(!this.promptActive||!s.threadId||s.threadId===this.currentSessionId)return;const c=this.subtaskRouter.routeFor(s.threadId);if(!c){this.bufferPendingSubtaskNotification(e,t,s.threadId);return}this.handleSubtaskNotification(e,t,c),this.flushPendingSubtaskNotifications();return}const n=this.subtaskRouter.observe(t,this.currentSessionId);if(n>0&&this.subscribeKnownSubtasks(!0),this.captureContextNotification(e,t),this.maintenanceActive||!this.promptActive&&e!=="turn/completed")return;this.rpc?.refreshPendingRequestTimeout("turn/start"),this.captureAgentMessagePhase(e,t);const r=this.connectionRecovery.beforeNotification(e,t);e==="turn/completed"&&this.resolveTurnCompleted(t);const o=e==="rawResponse/completed"?ee(t):C(e,t,{agentMessagePhases:this.agentMessagePhases,planDeltas:this.planDeltas});for(const c of[...r,...o])this.captureUpdateEvidence(c),this.notifySessionUpdate(c);n>0&&this.flushPendingSubtaskNotifications()}handleSubtaskNotification(e,t,s){if(!this.promptActive)return;this.rememberSubtaskItem(s.sourceThreadId,t),this.rpc?.refreshPendingRequestTimeout("turn/start");const n=this.subtaskAgentMessagePhases.get(s.sourceThreadId)??new Map;this.subtaskAgentMessagePhases.set(s.sourceThreadId,n);const r=this.subtaskPlanDeltas.get(s.sourceThreadId)??new T;this.subtaskPlanDeltas.set(s.sourceThreadId,r),this.captureAgentMessagePhase(e,t,n),this.subtaskRouter.observe(t,this.currentSessionId)>0&&this.subscribeKnownSubtasks(!0);const c=C(e,t,{agentMessagePhases:n,planDeltas:r}),d=R(t).turnId;for(const l of c){if(!te(l))continue;const h=_(l,s,d);w(h,this.currentAffectedFiles),this.notifySessionUpdate(h)}}hydrateSubtaskHistory(e,t){if(!(!this.promptActive||this.hydratedSubtaskThreadIds.has(t.sourceThreadId))){this.hydratedSubtaskThreadIds.add(t.sourceThreadId);for(const s of W(e)){const n=M(t.sourceThreadId,s.itemId);if(this.seenSubtaskItemIds.has(n))continue;this.seenSubtaskItemIds.add(n);const r=_(s.update,t,s.sourceTurnId);w(r,this.currentAffectedFiles),this.notifySessionUpdate(r)}}}rememberSubtaskItem(e,t){const s=u(t),n=u(s.item),r=a(n,"id")||a(s,"itemId");r&&this.seenSubtaskItemIds.add(M(e,r))}bufferPendingSubtaskNotification(e,t,s){this.pendingSubtaskNotifications.push({method:e,params:t,threadId:s}),this.pendingSubtaskNotifications.length>200&&this.pendingSubtaskNotifications.shift()}flushPendingSubtaskNotifications(){if(this.pendingSubtaskNotifications.length===0)return;let e=!0;for(;e&&this.pendingSubtaskNotifications.length>0;){e=!1;const t=[];for(const s of this.pendingSubtaskNotifications){const n=this.subtaskRouter.routeFor(s.threadId);if(!n){t.push(s);continue}e=!0,this.handleSubtaskNotification(s.method,s.params,n)}this.pendingSubtaskNotifications=t}}notifySessionUpdate(e){this.notify("session/update",{sessionId:this.currentSessionId,update:e})}async handleCodexRequest(e,t){if(j(e))return $(e,t,async s=>{const n=await this.requestParent("session/request_permission",{sessionId:this.currentSessionId,request:{...s,params:t,method:e}}),r=u(n),o=u(r.outcome);return o.outcome==="selected"&&typeof o.optionId=="string"?{outcome:{outcome:"selected",optionId:o.optionId}}:{outcome:{outcome:"cancelled"}}});if(se(e)){const s=await this.requestParent("elicitation/create",{sessionId:this.currentSessionId,request:{...u(t),method:e}}),n=u(s),r=u(n.outcome);return r.outcome==="submitted"?{outcome:{outcome:"submitted",value:typeof r.value=="string"?r.value:""}}:{outcome:{outcome:"cancelled"}}}return{}}captureAgentMessagePhase(e,t,s=this.agentMessagePhases){if(e!=="item/started"&&e!=="item/completed")return;const n=m(t,"item");if(a(n,"type")!=="agentMessage")return;const r=a(n,"id");r&&s.set(r,a(n,"phase"))}waitForTurnCompleted(e,t){const s=this.completedTurns.get(e);return s?Promise.resolve(s):new Promise((n,r)=>{const o=setTimeout(()=>{this.pendingTurnCompletions.delete(e),r(new Error("Codex app-server request timed out while waiting for turn/completed"))},t);o.unref(),this.pendingTurnCompletions.set(e,{resolve:n,reject:r,timer:o})})}resolveTurnCompleted(e){const t=m(e,"turn"),s=a(t,"id");if(!s)return;this.completedTurns.set(s,t);const n=this.pendingTurnCompletions.get(s);if(n){if(this.pendingTurnCompletions.delete(s),clearTimeout(n.timer),a(t,"status")==="failed"){n.reject(new Error(`Codex turn failed: ${JSON.stringify(t.error??{})}`));return}n.resolve(t)}}async shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.pendingCompaction&&(clearTimeout(this.pendingCompaction.timer),this.pendingCompaction.reject(new Error("Codex ACP adapter closed")),this.pendingCompaction=null);for(const t of this.pendingParentRequests.values())clearTimeout(t.timer),t.reject(new Error("Codex ACP adapter closed"));this.pendingParentRequests.clear();for(const t of this.pendingTurnCompletions.values())clearTimeout(t.timer),t.reject(new Error("Codex ACP adapter closed"));this.pendingTurnCompletions.clear();const e=this.started?.child;!e||e.exitCode!==null||e.signalCode!==null||(e.stdin.end(),!await y(e,2e3)&&(e.kill("SIGTERM"),!await y(e,1e3)&&(e.kill("SIGKILL"),await y(e,1e3))))}sessionResponse(e){return{sessionId:e,modes:{currentModeId:"workspace-write",availableModes:[{id:"read-only",name:"Read Only"},{id:"workspace-write",name:"Workspace Write"},{id:"danger-full-access",name:"Full Access"}]},configOptions:[{id:"model",category:"model",type:"string"},{id:"approvalPolicy",category:"approval",type:"string"},{id:"sandbox",category:"mode",type:"string"}]}}requireRpc(){if(!this.rpc)throw new Error("Codex app-server is not started");return this.rpc}notify(e,t){this.write({jsonrpc:"2.0",method:e,params:t})}requestParent(e,t,s=600*1e3){const n=this.nextParentRequestId++;return new Promise((r,o)=>{const c=setTimeout(()=>{this.pendingParentRequests.delete(n),o(new Error(`ACP client request timed out: ${e}`))},s);c.unref(),this.pendingParentRequests.set(n,{resolve:r,reject:o,timer:c}),this.write({jsonrpc:"2.0",id:n,method:e,params:t})})}handleParentResponse(e){const t=Number(e.id),s=this.pendingParentRequests.get(t);if(s){if(this.pendingParentRequests.delete(t),clearTimeout(s.timer),"error"in e){const n=u(e.error);s.reject(new Error(a(n,"message")||"ACP client request failed"));return}s.resolve(e.result)}}setConfigOption(e){const t=a(e,"configId"),s=e.value;if(!t)throw new Error("configId is required");if(typeof s!="string"&&typeof s!="boolean")throw new Error("config value must be string or boolean");return this.config[t]=s,this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"config_option_update",configId:t,value:s}}),{}}setMode(e){const t=a(e,"modeId");if(!t)throw new Error("modeId is required");return this.config.sandbox=t,this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"current_mode_update",modeId:t}}),{}}applyInitialConfig(e){const t=m(e,"config");for(const[s,n]of Object.entries(t))(typeof n=="string"||typeof n=="boolean")&&(this.config[s]=n)}codexConfig(){return{...typeof this.config.model=="string"&&this.config.model?{model:this.config.model}:{},approvalPolicy:typeof this.config.approvalPolicy=="string"?this.config.approvalPolicy:"on-request",sandbox:typeof this.config.sandbox=="string"?this.config.sandbox:"workspace-write"}}captureContextNotification(e,t){if(e==="thread/tokenUsage/updated"&&(this.latestTokenUsage=B(t)??this.latestTokenUsage),e==="thread/compacted"&&this.pendingCompaction&&this.resolveCompaction(),e==="item/completed"){const s=m(t,"item"),n=a(u(t),"threadId");a(s,"type")==="contextCompaction"&&(!n||n===this.currentSessionId)&&this.resolveCompaction(),a(s,"type")==="agentMessage"&&a(s,"phase")==="final_answer"&&(this.currentAssistantText=g(s)||this.currentAssistantText)}}resolveCompaction(){if(!this.pendingCompaction)return;const e=this.pendingCompaction;this.pendingCompaction=null,clearTimeout(e.timer),e.resolve()}captureUpdateEvidence(e){String(e.sessionUpdate||"")==="agent_message_chunk"&&(this.currentAssistantText+=g(e.content)),w(e,this.currentAffectedFiles)}captureThreadMetadata(e){const t=m(e,"thread");this.currentRolloutPath=a(t,"path")||null,this.threadTurnCount=Array.isArray(t.turns)?t.turns.length:0;const s=Q(t.turns);s.userRequest&&(this.previousUserText=s.userRequest),s.assistantResponse&&(this.previousAssistantText=s.assistantResponse),this.previousAffectedFiles.clear();for(const n of s.affectedFiles)this.previousAffectedFiles.add(n);this.latestTokenUsage=null}async maintainContext(e,t,s={}){const n=k(),r=this.contextState(),o=v(r,n);if(!o.compact&&!s.force||!this.currentSessionId)return this.maintenanceResult({stage:e,action:"none",reasons:o.reasons,beforeState:r});const c=this.currentSessionId;this.notifyContextStatus("正在整理会话上下文",P(r)),this.maintenanceActive=!0;let d=!1,l="",h=r,f=o,x=!1,b="";try{const p=r.usage?.observedAtMs??0;await this.compactThread(c,s.compactTimeoutMs??n.compactTimeoutMs),await this.waitForTokenUsageAfter(p,2e3)}catch(p){d=!0,l=p instanceof Error?p.message:String(p)}try{if(h=this.contextState(),f=v(h,n,{compactAttempted:!0,compactFailed:d}),f.rollover&&s.allowRollover!==!1){this.notifyContextStatus("正在创建轻量会话",f.reasons.join(", "));try{await this.rotateThread(c,t),x=!0}catch(p){b=p instanceof Error?p.message:String(p),this.notifyContextStatus("轻量会话创建失败",b)}}else d||this.notifyContextStatus("会话上下文已压缩",P(h))}finally{this.maintenanceActive=!1}return this.maintenanceResult({action:x?"rollover":b?"rollover_failed":d?"compact_failed":"compact",stage:e,reasons:f.reasons,beforeState:r,afterState:h,compactError:[l,b].filter(Boolean).join("; "),previousThreadId:c,rolloverRecommended:f.rollover&&s.allowRollover===!1})}compactThread(e,t){return this.pendingCompaction?Promise.reject(new Error("Codex context compaction is already running")):new Promise((s,n)=>{const r=setTimeout(()=>{this.pendingCompaction?.timer===r&&(this.pendingCompaction=null),n(new Error("Codex thread compaction timed out"))},t);r.unref(),this.pendingCompaction={resolve:s,reject:n,timer:r},this.requireRpc().request("thread/compact/start",{threadId:e},t).catch(o=>{this.pendingCompaction?.timer===r&&(this.pendingCompaction=null,clearTimeout(r),n(o instanceof Error?o:new Error(String(o))))})})}async rotateThread(e,t){const s=D({previousThreadId:e,cwd:this.currentCwd,userRequest:t.userRequest,assistantResponse:t.assistantResponse,affectedFiles:t.affectedFiles}),n=await this.requireRpc().request("thread/start",{cwd:this.currentCwd,approvalsReviewer:"user",...this.codexConfig(),developerInstructions:s,ephemeral:!1,experimentalRawEvents:!0,threadSource:"aca-codex-acp-rollover"},6e4),r=I(n);if(!r)throw new Error("Codex rollover thread/start did not return thread id");this.sessionAliases.set(e,r),this.currentSessionId=r,this.resetSubtaskState(n),this.captureThreadMetadata(n)}async waitForTokenUsageAfter(e,t){const s=Date.now()+t;for(;Date.now()<s;){if((this.latestTokenUsage?.observedAtMs??0)>e)return;await ne(50)}}resolveSessionAlias(e){if(!e)return null;let t=e;const s=new Set;for(;this.sessionAliases.has(t)&&!s.has(t);)s.add(t),t=this.sessionAliases.get(t)??t;return t}contextState(){return{usage:this.latestTokenUsage,rolloutBytes:z(this.currentRolloutPath),turnCount:this.threadTurnCount}}maintenanceResult(e){return{stage:e.stage,action:e.action,reasons:e.reasons,previousThreadId:e.previousThreadId??null,sessionId:this.currentSessionId,before:e.beforeState,after:e.afterState??null,compactError:e.compactError||null,rolloverRecommended:e.rolloverRecommended===!0}}notifyContextStatus(e,t){this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"aca_context_maintenance",label:e,detail:t}})}write(e){process.stdout.write(`${JSON.stringify(e)}
|
|
3
|
-
`)}}function J(i){return i.map(e=>{const t=u(e);if(t.type==="image"){const s=a(t,"uri");if(s)return{type:"localImage",path:s};const n=a(t,"data");return{type:"image",url:`data:${a(t,"mimeType")||"image/png"};base64,${n}`}}return{type:"text",text:a(t,"text"),text_elements:[]}})}function H(i){return i.map(e=>a(u(e),"text")).filter(Boolean).join(`
|
|
1
|
+
import{JsonLineRpcClient as U}from"../../client/json-rpc.js";import{startCodexAppServer as F}from"../codex/codex-process.js";import{CodexConnectionRecoveryTracker as N}from"../codex/connection-events.js";import{codexAcpSessionUpdatesFromNotification as x}from"../codex/events.js";import{CodexPlanDeltaState as T}from"../codex/plan-events.js";import{isCodexApprovalRequest as $,resolveCodexApprovalRequest as j}from"../codex/permissions.js";import{buildCodexContinuityInstructions as D,codexTokenUsageFromRawResponseCompleted as O,codexTokenUsageFromNotification as B,decideCodexContextMaintenance as v,readCodexContextMaintenancePolicy as k,rolloutFileSize as z}from"./context-maintenance.js";import{codexNotificationBelongsToCurrentTurn as K,codexNotificationRouting as R}from"./notification-routing.js";import{completedSubtaskHistoryUpdates as W}from"./subtask-history.js";import{CodexSubtaskRouter as L}from"./subtask-routing.js";import{waitForCancellableTurnStart as G}from"./cancellation.js";class J{lineBuffer="";started=null;rpc=null;codexStartupPromise=null;initialized=!1;currentSessionId=null;currentCwd=process.cwd();promptActive=!1;currentTurnId=null;turnStartPromise=null;promptCancelled=!1;nextParentRequestId=1;pendingParentRequests=new Map;completedTurns=new Map;pendingTurnCompletions=new Map;agentMessagePhases=new Map;planDeltas=new T;subtaskRouter=new L;subtaskAgentMessagePhases=new Map;subtaskPlanDeltas=new Map;subscribedSubtaskThreadIds=new Set;pendingSubtaskSubscriptions=new Map;hydratedSubtaskThreadIds=new Set;seenSubtaskItemIds=new Set;pendingSubtaskNotifications=[];config={};sessionAliases=new Map;currentAffectedFiles=new Set;connectionRecovery=new N;latestTokenUsage=null;currentRolloutPath=null;threadTurnCount=0;currentPromptText="";currentAssistantText="";previousUserText="";previousAssistantText="";previousAffectedFiles=new Set;maintenanceActive=!1;pendingCompaction=null;shutdownPromise=null;managedProvider=null;constructor(){process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>this.handleInput(String(t)));const e=()=>{this.shutdown().finally(()=>process.exit(0))};process.stdin.once("end",e),process.stdin.once("close",e),process.stdin.once("error",e),process.once("SIGTERM",()=>{this.shutdown().finally(()=>process.exit(0))}),process.once("SIGINT",()=>{this.shutdown().finally(()=>process.exit(130))})}handleInput(e){this.lineBuffer+=e;const t=this.lineBuffer.split(`
|
|
2
|
+
`);this.lineBuffer=t.pop()??"";for(const s of t){const n=s.trim();if(!n)continue;let i;try{i=JSON.parse(n)}catch{continue}this.handleMessage(i)}}async handleMessage(e){if("id"in e&&("result"in e||"error"in e)&&typeof e.method!="string"){this.handleParentResponse(e);return}const t=typeof e.method=="string"?e.method:"",s=e.id;if(t){if(s===void 0){await this.handleNotification(t,u(e.params));return}try{const n=await this.handleRequest(t,u(e.params));this.write({jsonrpc:"2.0",id:s,result:n})}catch(n){this.write({jsonrpc:"2.0",id:s,error:{code:-32603,message:n instanceof Error?n.message:String(n)}})}}}async handleNotification(e,t){if(e==="session/cancel")try{await this.cancel(t)}catch(s){process.stderr.write(`Codex cancel failed: ${s instanceof Error?s.message:String(s)}
|
|
3
|
+
`),await this.shutdown(),process.exit(1)}}async handleRequest(e,t){switch(e){case"initialize":return this.initializeResponse();case"aca/runtime_config":return this.applyRuntimeConfig(t);case"session/new":return this.newSession(t);case"session/resume":case"session/load":return this.resumeSession(t);case"session/fork":return this.forkSession(t);case"session/prompt":return this.prompt(t);case"session/compact":return this.manualCompact(t);case"session/cancel":return await this.cancel(t),{};case"session/close":return await this.closeSession(t),{};case"session/set_config_option":return this.setConfigOption(t);case"session/set_mode":return this.setMode(t);case"fs/read_text_file":case"fs/write_text_file":case"terminal/create":case"terminal/output":case"terminal/wait_for_exit":case"terminal/kill":case"terminal/release":return{};default:throw new Error(`Unsupported ACP method: ${e}`)}}initializeResponse(){return{protocolVersion:1,agentCapabilities:{loadSession:!0,sessionCapabilities:{resume:!0,close:!0}}}}applyRuntimeConfig(e){if(this.started)throw new Error("Codex runtime config must be applied before app-server starts");const t=u(e.codexProvider);if(Object.keys(t).length===0)return this.managedProvider=null,{configured:!1};const s=a(t,"baseUrl"),n=a(t,"apiKey"),i=Number(t.revision||0);if(!s||!n||!Number.isSafeInteger(i)||i<1)throw new Error("Invalid Codex managed provider runtime config");return this.managedProvider={baseUrl:s,apiKey:n,revision:i},{configured:!0,revision:i}}async newSession(e){const t=a(e,"cwd")||process.cwd();this.applyInitialConfig(e),await this.ensureCodex(t);const s=await this.requireRpc().request("thread/start",{cwd:t,approvalsReviewer:"user",...this.codexConfig(),ephemeral:!1,experimentalRawEvents:!0,threadSource:"aca-codex-acp"},6e4),n=I(s);if(!n)throw new Error("Codex thread/start did not return thread id");return this.currentSessionId=n,this.currentCwd=t,this.resetSubtaskState(),this.captureThreadMetadata(s),this.sessionResponse(n)}async resumeSession(e){const t=a(e,"sessionId");if(!t)throw new Error("sessionId is required");const s=a(e,"cwd")||this.currentCwd;this.applyInitialConfig(e),await this.ensureCodex(s);const n=await this.requireRpc().request("thread/resume",{threadId:t,cwd:s,approvalsReviewer:"user",...this.codexConfig()},6e4);return this.currentSessionId=I(n)||t,this.currentCwd=s,this.resetSubtaskState(n),await this.subscribeKnownSubtasks(!1),this.captureThreadMetadata(n),this.sessionResponse(this.currentSessionId)}async forkSession(e){const t=a(e,"sessionId");if(!t)throw new Error("sessionId is required");const s=a(e,"cwd")||this.currentCwd;this.applyInitialConfig(e),await this.ensureCodex(s);const n=await this.requireRpc().request("thread/fork",{threadId:t,cwd:s,approvalsReviewer:"user",ephemeral:!1,threadSource:"aca-codex-acp-fork",...this.codexConfig()},12e4),i=I(n);if(!i)throw new Error("Codex thread/fork did not return thread id");return this.currentSessionId=i,this.currentCwd=s,this.resetSubtaskState(n),this.captureThreadMetadata(n),this.sessionResponse(i)}async prompt(e){this.promptCancelled=!1;const t=a(e,"sessionId")||this.currentSessionId;let s=this.resolveSessionAlias(t);if(!s)throw new Error("sessionId is required");const n=Array.isArray(e.prompt)?e.prompt:[],i=this.requireRpc();this.currentSessionId&&this.currentSessionId!==s&&this.resetSubtaskState(),this.currentSessionId=s;const o=await this.maintainContext("before",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{allowRollover:!0});if(te(o),this.promptCancelled||this.shutdownPromise)throw new Error("Codex prompt cancelled");s=this.currentSessionId||s,this.promptActive=!0,this.currentTurnId=null,this.currentPromptText=H(n),this.currentAssistantText="",this.currentAffectedFiles.clear(),this.connectionRecovery.reset(),this.agentMessagePhases.clear(),this.planDeltas.reset(),this.pendingSubtaskNotifications=[];let c;try{this.turnStartPromise=i.request("turn/start",{threadId:s,clientUserMessageId:`aca-acp-${Date.now()}-${Math.random().toString(16).slice(2)}`,input:V(n),cwd:this.currentCwd,...Q(this.config)},E()),c=await this.turnStartPromise;const d=String(c?.turn?.id??"");this.currentTurnId=d||null;const l=d?await this.waitForTurnCompleted(d,E()):c?.turn;if(this.promptCancelled)throw new Error("Codex prompt cancelled");this.threadTurnCount+=1,this.previousUserText=this.currentPromptText,this.previousAssistantText=this.currentAssistantText,this.previousAffectedFiles.clear();for(const f of this.currentAffectedFiles)this.previousAffectedFiles.add(f);const h=await this.maintainContext("after",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{allowRollover:!0});return{stopReason:"end_turn",sessionId:this.currentSessionId,turn:l,_meta:{acaContextUsage:A(h)??ee(this.latestTokenUsage),acaContextMaintenance:h}}}catch(d){const l=this.connectionRecovery.fail(d);throw l&&this.notifySessionUpdate(l),d}finally{this.promptActive=!1,this.currentTurnId=null,this.turnStartPromise=null,this.pendingSubtaskNotifications=[]}}resetSubtaskState(e){this.subtaskRouter.reset(),this.subtaskAgentMessagePhases.clear(),this.subtaskPlanDeltas.clear(),this.subscribedSubtaskThreadIds.clear(),this.pendingSubtaskSubscriptions.clear(),this.hydratedSubtaskThreadIds.clear(),this.seenSubtaskItemIds.clear(),this.pendingSubtaskNotifications=[],e!==void 0&&this.subtaskRouter.restoreFromSessionSnapshot(e,this.currentSessionId)}async subscribeKnownSubtasks(e=!0){const t=this.subtaskRouter.routesForSubscription().map(s=>this.subscribeSubtask(s,e));await Promise.allSettled(t)}subscribeSubtask(e,t){const s=e.sourceThreadId;if(!s||s===this.currentSessionId||this.subscribedSubtaskThreadIds.has(s))return Promise.resolve();const n=this.pendingSubtaskSubscriptions.get(s);if(n)return n;const i=this.requireRpc().request("thread/resume",{threadId:s,approvalsReviewer:"user",excludeTurns:!1},6e4).then(o=>{this.subscribedSubtaskThreadIds.add(s);const c=this.subtaskRouter.restoreFromSessionSnapshot(o,this.currentSessionId);t&&this.hydrateSubtaskHistory(o,e),c>0&&this.subscribeKnownSubtasks(t)}).catch(()=>{}).finally(()=>{this.pendingSubtaskSubscriptions.delete(s)});return this.pendingSubtaskSubscriptions.set(s,i),i}async cancel(e){const t=this.resolveSessionAlias(a(e,"sessionId")||this.currentSessionId);if(!t||!this.rpc)return;if(t!==this.currentSessionId)throw new Error("Cannot cancel a different Codex session");this.promptCancelled=!0;const s=this.turnStartPromise?await G(this.turnStartPromise):null,n=this.currentTurnId||a(m(s,"turn"),"id");if(await this.rpc.request("turn/interrupt",{threadId:t,turnId:n},5e3),n){const i=this.pendingTurnCompletions.get(n);i&&(this.pendingTurnCompletions.delete(n),clearTimeout(i.timer),i.reject(new Error("Codex prompt cancelled")))}}async manualCompact(e){const t=a(e,"sessionId")||this.currentSessionId,s=this.resolveSessionAlias(t);if(!s)throw new Error("sessionId is required");if(this.promptActive||this.maintenanceActive)throw new Error("Codex session is busy");this.currentSessionId=s;const n=k(),i=await this.maintainContext("manual",{userRequest:this.previousUserText,assistantResponse:this.previousAssistantText,affectedFiles:[...this.previousAffectedFiles]},{force:!0,allowRollover:e.allowRollover===!0,compactTimeoutMs:Z(e,n.compactTimeoutMs)}),o=String(i.action||"");if(o==="compact_failed"||o==="rollover_failed"){const c=String(i.compactError||"Codex 上下文压缩未完成");throw new Error(`Codex 上下文压缩失败:${c}`)}return{sessionId:this.currentSessionId,maintenance:i,contextUsage:A(i)}}async closeSession(e){await this.shutdown()}async ensureCodex(e){if(this.rpc&&this.started&&this.started.child.exitCode===null&&this.started.child.signalCode===null)return;if(this.codexStartupPromise){await this.codexStartupPromise;return}const t=(async()=>{if(this.rpc&&this.started&&this.started.child.exitCode===null&&this.started.child.signalCode===null)return;const s=F(e,this.managedProvider),n=new U(s.child,{peerName:"Codex app-server",onNotification:(i,o)=>this.handleCodexNotification(i,o),onRequest:async(i,o)=>this.handleCodexRequest(i,o)});this.started=s,this.rpc=n,this.initialized=!1,await n.request("initialize",{clientInfo:{name:"aca-codex-acp",version:"0.1.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}},6e4),this.initialized=!0})();this.codexStartupPromise=t;try{await t}catch(s){throw this.rpc&&this.started&&!this.initialized&&await y(this.started.child,1e3),this.rpc=null,this.started=null,s}finally{this.codexStartupPromise===t&&(this.codexStartupPromise=null)}}handleCodexNotification(e,t){const s=R(t);if(this.maintenanceActive&&(!s.threadId||s.threadId===this.currentSessionId)){this.captureContextNotification(e,t);return}if(!K(t,this.currentSessionId,this.currentTurnId)){if(!this.promptActive||!s.threadId||s.threadId===this.currentSessionId)return;const c=this.subtaskRouter.routeFor(s.threadId);if(!c){this.bufferPendingSubtaskNotification(e,t,s.threadId);return}this.handleSubtaskNotification(e,t,c),this.flushPendingSubtaskNotifications();return}const n=this.subtaskRouter.observe(t,this.currentSessionId);if(n>0&&this.subscribeKnownSubtasks(!0),this.captureContextNotification(e,t),this.maintenanceActive||!this.promptActive&&e!=="turn/completed")return;this.rpc?.refreshPendingRequestTimeout("turn/start"),this.captureAgentMessagePhase(e,t);const i=this.connectionRecovery.beforeNotification(e,t);e==="turn/completed"&&this.resolveTurnCompleted(t);const o=e==="rawResponse/completed"?se(t):x(e,t,{agentMessagePhases:this.agentMessagePhases,planDeltas:this.planDeltas});for(const c of[...i,...o])this.captureUpdateEvidence(c),this.notifySessionUpdate(c);n>0&&this.flushPendingSubtaskNotifications()}handleSubtaskNotification(e,t,s){if(!this.promptActive)return;this.rememberSubtaskItem(s.sourceThreadId,t),this.rpc?.refreshPendingRequestTimeout("turn/start");const n=this.subtaskAgentMessagePhases.get(s.sourceThreadId)??new Map;this.subtaskAgentMessagePhases.set(s.sourceThreadId,n);const i=this.subtaskPlanDeltas.get(s.sourceThreadId)??new T;this.subtaskPlanDeltas.set(s.sourceThreadId,i),this.captureAgentMessagePhase(e,t,n),this.subtaskRouter.observe(t,this.currentSessionId)>0&&this.subscribeKnownSubtasks(!0);const c=x(e,t,{agentMessagePhases:n,planDeltas:i}),d=R(t).turnId;for(const l of c){if(!ne(l))continue;const h=_(l,s,d);w(h,this.currentAffectedFiles),this.notifySessionUpdate(h)}}hydrateSubtaskHistory(e,t){if(!(!this.promptActive||this.hydratedSubtaskThreadIds.has(t.sourceThreadId))){this.hydratedSubtaskThreadIds.add(t.sourceThreadId);for(const s of W(e)){const n=M(t.sourceThreadId,s.itemId);if(this.seenSubtaskItemIds.has(n))continue;this.seenSubtaskItemIds.add(n);const i=_(s.update,t,s.sourceTurnId);w(i,this.currentAffectedFiles),this.notifySessionUpdate(i)}}}rememberSubtaskItem(e,t){const s=u(t),n=u(s.item),i=a(n,"id")||a(s,"itemId");i&&this.seenSubtaskItemIds.add(M(e,i))}bufferPendingSubtaskNotification(e,t,s){this.pendingSubtaskNotifications.push({method:e,params:t,threadId:s}),this.pendingSubtaskNotifications.length>200&&this.pendingSubtaskNotifications.shift()}flushPendingSubtaskNotifications(){if(this.pendingSubtaskNotifications.length===0)return;let e=!0;for(;e&&this.pendingSubtaskNotifications.length>0;){e=!1;const t=[];for(const s of this.pendingSubtaskNotifications){const n=this.subtaskRouter.routeFor(s.threadId);if(!n){t.push(s);continue}e=!0,this.handleSubtaskNotification(s.method,s.params,n)}this.pendingSubtaskNotifications=t}}notifySessionUpdate(e){this.notify("session/update",{sessionId:this.currentSessionId,update:e})}async handleCodexRequest(e,t){if($(e))return j(e,t,async s=>{const n=await this.requestParent("session/request_permission",{sessionId:this.currentSessionId,request:{...s,params:t,method:e}}),i=u(n),o=u(i.outcome);return o.outcome==="selected"&&typeof o.optionId=="string"?{outcome:{outcome:"selected",optionId:o.optionId}}:{outcome:{outcome:"cancelled"}}});if(re(e)){const s=await this.requestParent("elicitation/create",{sessionId:this.currentSessionId,request:{...u(t),method:e}}),n=u(s),i=u(n.outcome);return i.outcome==="submitted"?{outcome:{outcome:"submitted",value:typeof i.value=="string"?i.value:""}}:{outcome:{outcome:"cancelled"}}}return{}}captureAgentMessagePhase(e,t,s=this.agentMessagePhases){if(e!=="item/started"&&e!=="item/completed")return;const n=m(t,"item");if(a(n,"type")!=="agentMessage")return;const i=a(n,"id");i&&s.set(i,a(n,"phase"))}waitForTurnCompleted(e,t){const s=this.completedTurns.get(e);return s?Promise.resolve(s):new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingTurnCompletions.delete(e),i(new Error("Codex app-server request timed out while waiting for turn/completed"))},t);o.unref(),this.pendingTurnCompletions.set(e,{resolve:n,reject:i,timer:o})})}resolveTurnCompleted(e){const t=m(e,"turn"),s=a(t,"id");if(!s)return;this.completedTurns.set(s,t);const n=this.pendingTurnCompletions.get(s);if(n){if(this.pendingTurnCompletions.delete(s),clearTimeout(n.timer),a(t,"status")==="failed"){n.reject(new Error(`Codex turn failed: ${JSON.stringify(t.error??{})}`));return}n.resolve(t)}}async shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.pendingCompaction&&(clearTimeout(this.pendingCompaction.timer),this.pendingCompaction.reject(new Error("Codex ACP adapter closed")),this.pendingCompaction=null);for(const t of this.pendingParentRequests.values())clearTimeout(t.timer),t.reject(new Error("Codex ACP adapter closed"));this.pendingParentRequests.clear();for(const t of this.pendingTurnCompletions.values())clearTimeout(t.timer),t.reject(new Error("Codex ACP adapter closed"));this.pendingTurnCompletions.clear();const e=this.started?.child;!e||e.exitCode!==null||e.signalCode!==null||(e.stdin.end(),!await y(e,2e3)&&(e.kill("SIGTERM"),!await y(e,1e3)&&(e.kill("SIGKILL"),await y(e,1e3))))}sessionResponse(e){return{sessionId:e,modes:{currentModeId:"workspace-write",availableModes:[{id:"read-only",name:"Read Only"},{id:"workspace-write",name:"Workspace Write"},{id:"danger-full-access",name:"Full Access"}]},configOptions:[{id:"model",category:"model",type:"string"},{id:"approvalPolicy",category:"approval",type:"string"},{id:"sandbox",category:"mode",type:"string"}]}}requireRpc(){if(!this.rpc)throw new Error("Codex app-server is not started");return this.rpc}notify(e,t){this.write({jsonrpc:"2.0",method:e,params:t})}requestParent(e,t,s=600*1e3){const n=this.nextParentRequestId++;return new Promise((i,o)=>{const c=setTimeout(()=>{this.pendingParentRequests.delete(n),o(new Error(`ACP client request timed out: ${e}`))},s);c.unref(),this.pendingParentRequests.set(n,{resolve:i,reject:o,timer:c}),this.write({jsonrpc:"2.0",id:n,method:e,params:t})})}handleParentResponse(e){const t=Number(e.id),s=this.pendingParentRequests.get(t);if(s){if(this.pendingParentRequests.delete(t),clearTimeout(s.timer),"error"in e){const n=u(e.error);s.reject(new Error(a(n,"message")||"ACP client request failed"));return}s.resolve(e.result)}}setConfigOption(e){const t=a(e,"configId"),s=e.value;if(!t)throw new Error("configId is required");if(typeof s!="string"&&typeof s!="boolean")throw new Error("config value must be string or boolean");return this.config[t]=s,this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"config_option_update",configId:t,value:s}}),{}}setMode(e){const t=a(e,"modeId");if(!t)throw new Error("modeId is required");return this.config.sandbox=t,this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"current_mode_update",modeId:t}}),{}}applyInitialConfig(e){const t=m(e,"config");for(const[s,n]of Object.entries(t))(typeof n=="string"||typeof n=="boolean")&&(this.config[s]=n)}codexConfig(){return{...typeof this.config.model=="string"&&this.config.model?{model:this.config.model}:{},approvalPolicy:typeof this.config.approvalPolicy=="string"?this.config.approvalPolicy:"on-request",sandbox:typeof this.config.sandbox=="string"?this.config.sandbox:"workspace-write"}}captureContextNotification(e,t){if(e==="thread/tokenUsage/updated"&&(this.latestTokenUsage=B(t)??this.latestTokenUsage),e==="thread/compacted"&&this.pendingCompaction&&this.resolveCompaction(),e==="item/completed"){const s=m(t,"item"),n=a(u(t),"threadId");a(s,"type")==="contextCompaction"&&(!n||n===this.currentSessionId)&&this.resolveCompaction(),a(s,"type")==="agentMessage"&&a(s,"phase")==="final_answer"&&(this.currentAssistantText=g(s)||this.currentAssistantText)}}resolveCompaction(){if(!this.pendingCompaction)return;const e=this.pendingCompaction;this.pendingCompaction=null,clearTimeout(e.timer),e.resolve()}captureUpdateEvidence(e){String(e.sessionUpdate||"")==="agent_message_chunk"&&(this.currentAssistantText+=g(e.content)),w(e,this.currentAffectedFiles)}captureThreadMetadata(e){const t=m(e,"thread");this.currentRolloutPath=a(t,"path")||null,this.threadTurnCount=Array.isArray(t.turns)?t.turns.length:0;const s=Y(t.turns);s.userRequest&&(this.previousUserText=s.userRequest),s.assistantResponse&&(this.previousAssistantText=s.assistantResponse),this.previousAffectedFiles.clear();for(const n of s.affectedFiles)this.previousAffectedFiles.add(n);this.latestTokenUsage=null}async maintainContext(e,t,s={}){const n=k(),i=this.contextState(),o=v(i,n);if(!o.compact&&!s.force||!this.currentSessionId)return this.maintenanceResult({stage:e,action:"none",reasons:o.reasons,beforeState:i});const c=this.currentSessionId;this.notifyContextStatus("正在整理会话上下文",P(i)),this.maintenanceActive=!0;let d=!1,l="",h=i,f=o,C=!1,b="";try{const p=i.usage?.observedAtMs??0;await this.compactThread(c,s.compactTimeoutMs??n.compactTimeoutMs),await this.waitForTokenUsageAfter(p,2e3)}catch(p){d=!0,l=p instanceof Error?p.message:String(p)}try{if(e!=="manual"&&this.promptCancelled||this.shutdownPromise)throw new Error("Codex prompt cancelled");if(h=this.contextState(),f=v(h,n,{compactAttempted:!0,compactFailed:d}),f.rollover&&s.allowRollover!==!1){this.notifyContextStatus("正在创建轻量会话",f.reasons.join(", "));try{await this.rotateThread(c,t),C=!0}catch(p){b=p instanceof Error?p.message:String(p),this.notifyContextStatus("轻量会话创建失败",b)}}else d||this.notifyContextStatus("会话上下文已压缩",P(h))}finally{this.maintenanceActive=!1}return this.maintenanceResult({action:C?"rollover":b?"rollover_failed":d?"compact_failed":"compact",stage:e,reasons:f.reasons,beforeState:i,afterState:h,compactError:[l,b].filter(Boolean).join("; "),previousThreadId:c,rolloverRecommended:f.rollover&&s.allowRollover===!1})}compactThread(e,t){return this.pendingCompaction?Promise.reject(new Error("Codex context compaction is already running")):new Promise((s,n)=>{const i=setTimeout(()=>{this.pendingCompaction?.timer===i&&(this.pendingCompaction=null),n(new Error("Codex thread compaction timed out"))},t);i.unref(),this.pendingCompaction={resolve:s,reject:n,timer:i},this.requireRpc().request("thread/compact/start",{threadId:e},t).catch(o=>{this.pendingCompaction?.timer===i&&(this.pendingCompaction=null,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))))})})}async rotateThread(e,t){const s=D({previousThreadId:e,cwd:this.currentCwd,userRequest:t.userRequest,assistantResponse:t.assistantResponse,affectedFiles:t.affectedFiles}),n=await this.requireRpc().request("thread/start",{cwd:this.currentCwd,approvalsReviewer:"user",...this.codexConfig(),developerInstructions:s,ephemeral:!1,experimentalRawEvents:!0,threadSource:"aca-codex-acp-rollover"},6e4),i=I(n);if(!i)throw new Error("Codex rollover thread/start did not return thread id");this.sessionAliases.set(e,i),this.currentSessionId=i,this.resetSubtaskState(n),this.captureThreadMetadata(n)}async waitForTokenUsageAfter(e,t){const s=Date.now()+t;for(;Date.now()<s;){if((this.latestTokenUsage?.observedAtMs??0)>e)return;await ie(50)}}resolveSessionAlias(e){if(!e)return null;let t=e;const s=new Set;for(;this.sessionAliases.has(t)&&!s.has(t);)s.add(t),t=this.sessionAliases.get(t)??t;return t}contextState(){return{usage:this.latestTokenUsage,rolloutBytes:z(this.currentRolloutPath),turnCount:this.threadTurnCount}}maintenanceResult(e){return{stage:e.stage,action:e.action,reasons:e.reasons,previousThreadId:e.previousThreadId??null,sessionId:this.currentSessionId,before:e.beforeState,after:e.afterState??null,compactError:e.compactError||null,rolloverRecommended:e.rolloverRecommended===!0}}notifyContextStatus(e,t){this.notify("session/update",{sessionId:this.currentSessionId,update:{sessionUpdate:"aca_context_maintenance",label:e,detail:t}})}write(e){process.stdout.write(`${JSON.stringify(e)}
|
|
4
|
+
`)}}function V(r){return r.map(e=>{const t=u(e);if(t.type==="image"){const s=a(t,"uri");if(s)return{type:"localImage",path:s};const n=a(t,"data");return{type:"image",url:`data:${a(t,"mimeType")||"image/png"};base64,${n}`}}return{type:"text",text:a(t,"text"),text_elements:[]}})}function H(r){return r.map(e=>a(u(e),"text")).filter(Boolean).join(`
|
|
4
5
|
|
|
5
|
-
`)}function
|
|
6
|
+
`)}function Q(r){const e={};typeof r.model=="string"&&r.model&&(e.model=r.model),typeof r.approvalPolicy=="string"&&r.approvalPolicy&&(e.approvalPolicy=r.approvalPolicy),typeof r.sandbox=="string"&&r.sandbox&&(e.sandboxPolicy=X(r.sandbox));const t=r.reasoning_effort??r.reasoningEffort??r.model_reasoning_effort??r.modelReasoningEffort??r.effort;return typeof t=="string"&&t&&(e.effort=t),e}function X(r){switch(r){case"read-only":return{type:"readOnly",networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[],networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};case"danger-full-access":return{type:"dangerFullAccess"};default:throw new Error(`Unsupported Codex sandbox mode: ${r}`)}}function I(r){const e=m(r,"thread");return a(e,"id")||null}function m(r,e){const t=u(r);return u(t[e])}function u(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function g(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.map(g).filter(Boolean).join("");if(!r||typeof r!="object")return"";const e=u(r);for(const t of["text","message","content","output_text"]){const s=g(e[t]);if(s)return s}return""}function w(r,e){if(Array.isArray(r)){for(const i of r)w(i,e);return}const t=u(r),s=a(t,"type").toLowerCase(),n=a(t,"path");if(n&&["diff","resource_link","content"].includes(s)&&e.add(n),Array.isArray(t.locations))for(const i of t.locations){const o=a(u(i),"path");o&&e.add(o)}for(const i of[t.content,t.update,t.rawInput,t.rawOutput])i&&i!==r&&w(i,e)}function Y(r){if(!Array.isArray(r)||r.length===0)return{userRequest:"",assistantResponse:"",affectedFiles:[]};const e=r.at(-1),t=new Set;w(e,t);let s="",n="";const i=o=>{if(Array.isArray(o)){for(const l of o)i(l);return}if(!o||typeof o!="object")return;const c=u(o),d=a(c,"type").toLowerCase();d==="usermessage"&&(s=g(c)||s),d==="agentmessage"&&(n=g(c)||n);for(const l of["items","content","input"])c[l]&&i(c[l])};return i(e),{userRequest:s,assistantResponse:n,affectedFiles:[...t]}}function Z(r,e){const t=S(r,"timeoutMs");return!Number.isFinite(t)||t<=0?e:Math.max(3e4,Math.min(59e4,t-1e4))}function A(r){const e=String(r.action||"none"),t=u(r.after),s=u(r.before),n=u(t.usage),i=u(s.usage),o=Object.keys(n).length>0?n:i,c=S(o,"contextWindow");if(e==="rollover")return{usedTokens:0,inputTokens:0,contextWindow:c,ratio:0,observedAtMs:Date.now(),state:"new_thread",maintenanceAction:e};if(Object.keys(o).length===0)return null;const d=S(o,"totalTokens"),l=S(o,"inputTokens");return{usedTokens:d||l,inputTokens:l,contextWindow:c,ratio:c>0?(d||l)/c:0,observedAtMs:S(o,"observedAtMs")||Date.now(),state:e==="compact"?"compacted":"active",maintenanceAction:e}}function ee(r){return r?{usedTokens:r.totalTokens||r.inputTokens,inputTokens:r.inputTokens,contextWindow:r.contextWindow,ratio:r.contextWindow>0?(r.totalTokens||r.inputTokens)/r.contextWindow:0,observedAtMs:r.observedAtMs,state:"active",maintenanceAction:null}:null}function P(r){const e=r.usage?`${r.usage.inputTokens} tokens`:"token unknown",t=r.rolloutBytes>0?`${Math.round(r.rolloutBytes/1024/1024)}MB rollout`:"rollout unknown";return`${e}, ${t}, ${r.turnCount} turns`}function te(r){const e=String(r.action||"none");if(e!=="compact_failed"&&e!=="rollover_failed")return;const t=String(r.compactError||"Codex 上下文维护未完成");throw new Error(`Codex 自动上下文维护失败:${t}`)}function S(r,e){const t=u(r)[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function se(r){return O(r)?[{sessionUpdate:"aca_codex_raw_response_usage",_meta:{codex:{rawResponse:r}}}]:[]}function ne(r){return["agent_message_chunk","agent_progress_chunk","agent_thought_chunk","tool_call","tool_call_update","plan","plan_update","plan_removed"].includes(String(r.sessionUpdate||""))}function _(r,e,t){const s=String(r.sessionUpdate||""),n={...r};if(s==="tool_call"||s==="tool_call_update"){const c=a(r,"toolCallId");c&&(n.toolCallId=q(e.sourceThreadId,c))}if(s==="plan"||s==="plan_update"||s==="plan_removed"){const c=a(r,"planId")||a(r,"plan_id")||a(r,"id")||"current";n.planId=q(e.sourceThreadId,c),delete n.plan_id}const i=u(r._meta),o=u(i.aca);return n._meta={...i,aca:{...o,subtask:{parentToolCallId:e.parentToolCallId,sourceThreadId:e.sourceThreadId,sourceTurnId:t,depth:e.depth}}},n}function q(r,e){return`subtask.${r}.${e}`}function M(r,e){return`${r}:${e}`}function a(r,e){const s=u(r)[e];return typeof s=="string"?s:""}function re(r){const e=r.toLowerCase();return e.includes("elicitation")||e.includes("requestuserinput")||e.includes("request_user_input")||e.includes("input/request")}function E(){const r=Number.parseInt(process.env.ACA_ACP_PROMPT_TIMEOUT_MS??"",10);return Number.isInteger(r)&&r>=3e4?r:360*60*1e3}function y(r,e){return r.exitCode!==null||r.signalCode!==null?Promise.resolve(!0):new Promise(t=>{const s=setTimeout(()=>t(!1),e);s.unref(),r.once("close",()=>{clearTimeout(s),t(!0)})})}function ie(r){return new Promise(e=>setTimeout(e,r))}function oe(){new J}const ae=process.argv[1]||"";/(?:^|[\\/])adapter\.(?:js|ts)$/.test(ae)&&oe();export{oe as runCodexAcpAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function i(e){let r;try{return await Promise.race([e,new Promise((t,n)=>{r=setTimeout(()=>n(new Error("Codex cancellation timed out waiting for turn/start")),5e3),r.unref()})])}finally{r&&clearTimeout(r)}}async function a(e,r){try{return await e.client.rpc.request("session/cancel",{sessionId:r},5e3),{forced:!1}}catch(t){const n=t instanceof Error?t.message:String(t);await e.dispose();const o=e.started.child;if(o.exitCode===null&&o.signalCode===null)throw new Error(`Codex 取消失败且运行实例未退出:${n}`);return{forced:!0,reason:n}}}export{a as cancelCodexRuntime,i as waitForCancellableTurnStart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import p from"node:fs";import{runAbortableRequest as v}from"../../client/abortable-request.js";import{BoundedItemBuffer as D}from"../../client/bounded-buffer.js";import{promptBlocksToAcpContent as L}from"../../client/acp-content.js";import{acpSessionUpdateFromParams as O,eventFromAcpSessionUpdate as F,statusFromAcpSessionUpdate as j,subtaskContextFromAcpSessionUpdate as z}from"../../client/acp-events.js";import{defaultAcpRuntimePool as A}from"../../client/acp-runtime-pool.js";import{resolveCodexAcpLaunch as x}from"./launch.js";import{CodexPromptPerformanceTracker as $,CodexUsageLoopDetector as N,codexRawResponseUsageFromAcpSessionUpdate as W,codexTokenUsageFromAcpSessionUpdate as H,readCodexContextMaintenancePolicy as _}from"./context-maintenance.js";import{ensureCodexProviderRuntimeConfig as k}from"../../../core/codex-provider-runtime-config.js";const V={sessionResume:!0,imageInput:!0,fileAttachment:!0,filesystem:!0,terminal:!0,permissionRequest:!0,configOptions:!0,usage:!0,contextUsage:!0,contextCompaction:!0,plan:!0,diff:!0};class de{id="codex-acp";name="Codex ACP";capabilities=V;async createSession(e){return new B(e.cwd,e.providerSessionId??null,e.timeoutMs)}async forkSession(e){if(!p.existsSync(e.cwd)||!p.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=e.sourceProviderSessionId.trim(),o=await k(),r=await A.acquire({providerId:"codex-acp",cwd:e.cwd,providerSessionId:t,runtimeIdentity:o?.runtimeIdentity||"default",env:R(o),...x(),onSessionUpdate:()=>{}});try{await P(r,o),r.initialized||(await r.client.initialize(6e4),r.markInitialized()),e.onStatus?.({phase:"forking",label:"正在分叉 Codex 会话",detail:t,updateType:"session/fork",atMs:Date.now()});const i=await r.client.forkSession({sessionId:t,cwd:e.cwd,config:T(e)},e.timeoutMs??12e4),n=g(i);if(!n)throw new Error("Codex ACP session/fork did not return sessionId");return{providerSessionId:n}}finally{r.release()}}}class B{cwd;providerSessionId;defaultTimeoutMs;lease=null;sessionResponse=null;statusCallback=null;updateCallback=null;permissionCallback=null;userInputCallback=null;abortHandler=null;statusTimeline=[];updates=new D(16);content="";performanceTracker=null;usageLoopDetector=null;usagePatternReport=null;usageLoopWarningActive=!1;constructor(e,t,o=Q()){this.cwd=e,this.providerSessionId=t,this.defaultTimeoutMs=o}async sendPrompt(e){if(!p.existsSync(e.cwd)||!p.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=Date.now();this.statusCallback=e.onStatus??null,this.updateCallback=e.onUpdate??null,this.permissionCallback=e.onPermissionRequest??null,this.userInputCallback=e.onUserInputRequest??null,this.attachAbortSignal(e.signal),this.content="",this.updates.clear(),this.statusTimeline.length=0;const o=_();this.performanceTracker=new $(t),this.usageLoopDetector=new N(o),this.usageLoopWarningActive=!1;const r={error:null};let i=null,n=null,a=this.providerSessionId,c,f=null;try{this.emitStatus("initializing","Codex ACP 启动中","codex-acp");const d=await this.acquireRuntime(e.cwd);this.lease=d,i=d.client,n=d.started,await this.initialize(d),a=await this.establishSession(d,e),await this.applyConfig(i,a,e);const y=i,C=a;this.emitStatus("thinking","思考中"),f=this.startSlowStatusTimer(),this.usagePatternReport=u=>{if(r.error)return;const I=Math.round(u.maxInputTokens/1e3),b=`同一 Turn 已连续请求至少 ${u.sampleCount} 次,单次输入约 ${I}k tokens`;if(u.sampleCount<o.usageLoopInterruptSamples){this.usageLoopWarningActive=!0,this.emitStatus("thinking","Codex 出现低产出内部循环",b,"aca.performance.low_output_loop");return}const E=`Codex 低产出内部循环:同一 Turn 已连续请求至少 ${u.sampleCount} 次,单次输入约 ${I}k tokens,且未执行工具或产生有效输出`;r.error=new Error(E),this.emitStatus("failed","Codex 已中断低产出内部循环",b,"aca.performance.low_output_loop_interrupted"),y.cancel(C)};try{c=await this.promptWithAbort(y,{sessionId:C,prompt:L(e.prompt,e.promptBlocks),timeoutMs:e.timeoutMs??this.defaultTimeoutMs,signal:e.signal})}catch(u){throw r.error?r.error:u}if(r.error)throw r.error;const m=q(c);m&&m!==a&&(a=m,this.providerSessionId=m,d.setProviderSession({providerSessionId:m,sessionResponse:this.sessionResponse}))}finally{f&&clearInterval(f),this.usagePatternReport=null,this.usageLoopDetector=null,this.usageLoopWarningActive=!1,this.abortHandler&&e.signal&&(e.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.releaseLease()}return this.emitStatus("completed","已完成"),{providerSessionId:a,cliType:"builtin",agentType:"codex",effectiveConfig:{model:e.model??null,mode:e.mode??null,configOptionValues:e.configOptionValues??null,command:n.command,processPid:n.child.pid??null,provider:"codex-acp",protocol:"acp"},command:n.command,args:n.args,cwd:e.cwd,exitCode:n.child.exitCode,signal:n.child.signalCode,durationMs:Date.now()-t,stdout:i.rpc.stdout,stderr:i.rpc.stderr,content:this.content.trim(),updateCount:this.updates.count(),updates:this.updates.snapshot(),statusTimeline:[...this.statusTimeline],performance:this.performanceTracker?.snapshot(),contextUsage:ee(c),promptResponse:c}}async compactContext(e){if(!p.existsSync(e.cwd)||!p.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=Date.now();this.statusCallback=e.onStatus??null,this.updateCallback=e.onUpdate??null,this.attachAbortSignal(e.signal);let o=this.providerSessionId,r;try{this.emitStatus("initializing","Codex ACP 启动中","codex-acp");const n=await this.acquireRuntime(e.cwd);this.lease=n,await this.initialize(n),o=await this.establishSession(n,e),await this.applyConfig(n.client,o,e);const a=Z(e.timeoutMs);r=await this.compactWithAbort(n.client,{sessionId:o,allowRollover:e.allowRollover===!0,timeoutMs:a,signal:e.signal});const c=q(r);c&&c!==o&&(o=c,this.providerSessionId=c,n.setProviderSession({providerSessionId:c,sessionResponse:this.sessionResponse}))}catch(n){if(this.lease&&G(n,e.signal)){const a=this.lease;this.lease=null,await a.dispose().catch(()=>{})}throw this.emitStatus("failed","上下文压缩失败",n instanceof Error?n.message:String(n)),n}finally{this.abortHandler&&e.signal&&(e.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.releaseLease()}const i=l(r)??{};return{providerSessionId:o||this.providerSessionId||"",contextUsage:U(i.contextUsage),maintenance:l(i.maintenance)??{},durationMs:Date.now()-t}}async cancel(){this.providerSessionId&&this.lease?.client.cancel(this.providerSessionId)}async close(){this.statusCallback=null,this.updateCallback=null,this.permissionCallback=null,this.userInputCallback=null,this.abortHandler&&(this.abortHandler=null),this.releaseLease()}async acquireRuntime(e){const t=x(),o=await k(),r=await A.acquire({providerId:"codex-acp",cwd:e,providerSessionId:this.providerSessionId,runtimeIdentity:o?.runtimeIdentity||"default",env:R(o),command:t.command,args:t.args,onSessionUpdate:i=>this.handleSessionUpdate(i),onClientRequest:async(i,n)=>{if(i==="session/request_permission")return this.requestPermission(n);if(i==="elicitation/create"||i==="session/request_user_input")return this.requestUserInput(n);throw new Error(`Unsupported Codex ACP client request: ${i}`)}});try{return await P(r,o),r}catch(i){throw await r.dispose().catch(()=>{}),i}}async initialize(e){e.initialized||(await e.client.initialize(6e4),e.markInitialized())}async establishSession(e,t){const o=e.client,r=T(t);if(e.providerSessionId&&e.sessionEstablished)return this.providerSessionId=e.providerSessionId,this.sessionResponse=e.sessionResponse,e.providerSessionId;if(this.providerSessionId)try{this.emitStatus("resuming","Codex ACP 会话恢复中","session/load");const a=await o.loadSession({sessionId:this.providerSessionId,cwd:t.cwd,config:r},6e4);this.sessionResponse=l(a);const c=g(a)||this.providerSessionId;return this.providerSessionId=c,e.setProviderSession({providerSessionId:c,sessionResponse:this.sessionResponse}),c}catch(a){if(t.requireSessionResume){const c=a instanceof Error?a.message:String(a);throw new Error(`无法恢复导入的 Codex ACP Session ${this.providerSessionId}:${c}`)}this.providerSessionId=null}this.emitStatus("acp","Codex ACP 会话创建中","session/new");const i=await o.newSession({cwd:t.cwd,config:r},12e4);this.sessionResponse=l(i);const n=g(i);if(!n)throw new Error("Codex ACP session/new did not return sessionId");return this.providerSessionId=n,e.setProviderSession({providerSessionId:n,sessionResponse:this.sessionResponse}),n}async applyConfig(e,t,o){o.model&&await e.setSessionConfigOption({sessionId:t,configId:"model",value:o.model},6e4).catch(()=>{});const r=S(o.mode);r&&await e.setSessionConfigOption({sessionId:t,configId:"approvalPolicy",value:r},6e4).catch(()=>{});const i=w(o.mode);i&&await e.setSessionConfigOption({sessionId:t,configId:"sandbox",value:i},6e4).catch(()=>{});for(const[n,a]of Object.entries(o.configOptionValues??{}))["model","mode","sandbox","approvalPolicy"].includes(n)||await e.setSessionConfigOption({sessionId:t,configId:n,value:a},6e4).catch(()=>{})}handleSessionUpdate(e){const t=O(e),o=String(t?.update.sessionUpdate||""),r=z(e);if(!r&&X(o))this.performanceTracker?.recordEvent(),this.usageLoopDetector?.recordMeaningfulEvent(),this.usageLoopWarningActive&&(this.usageLoopWarningActive=!1,this.emitStatus("thinking","Codex 已恢复执行","已重新执行工具或产生有效输出","aca.performance.loop_recovered"));else if(!r&&o==="aca_codex_raw_response_usage"){const a=W(e),c=a?this.usageLoopDetector?.recordUsage(a):null;c&&this.usagePatternReport?.(c)}else if(!r&&o==="usage_update"){const a=H(e),c=a?this.usageLoopDetector?.recordUsage(a):null;c&&this.usagePatternReport?.(c)}this.updates.push({method:"session/update",params:e});const i=F(e);i&&(i.type==="agent_message_chunk"&&!r&&(this.content+=i.text??""),this.updateCallback?.(i));const n=j(e);n&&this.emitStatus(n.phase,n.label,n.detail,n.updateType)}startSlowStatusTimer(){const e=_().slowEventThresholdMs,t=setInterval(()=>{const o=this.performanceTracker,r=Date.now();if(!o?.shouldReportSlow(r,e))return;const i=o.snapshot(r),n=Math.max(1,Math.round(i.silentForMs/6e4)),a=this.usageLoopWarningActive?"Codex 可能卡在内部循环":"Codex 长时间没有有效进展";this.emitStatus("thinking",a,`已 ${n} 分钟没有执行工具或产生有效输出`,"aca.performance.slow")},Math.min(3e4,Math.max(1e3,Math.floor(e/4))));return t.unref(),t}attachAbortSignal(e){if(e){if(this.abortHandler=()=>{this.cancel()},e.aborted)throw new Error("Codex ACP prompt cancelled");e.addEventListener("abort",this.abortHandler,{once:!0})}}async promptWithAbort(e,t){return v({signal:t.signal,cancelledMessage:"Codex ACP prompt cancelled",startRequest:()=>e.prompt({sessionId:t.sessionId,prompt:t.prompt},t.timeoutMs),onAbort:async()=>{e.cancel(t.sessionId),await this.lease?.dispose()}})}async compactWithAbort(e,t){return v({signal:t.signal,cancelledMessage:"Codex ACP 上下文压缩已取消",startRequest:()=>e.compactSession({sessionId:t.sessionId,allowRollover:t.allowRollover,timeoutMs:t.timeoutMs},t.timeoutMs),onAbort:async()=>{e.cancel(t.sessionId),await this.lease?.dispose()}})}async requestPermission(e){if(!this.permissionCallback)return{outcome:{outcome:"cancelled"}};const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=t.request&&typeof t.request=="object"&&!Array.isArray(t.request)?t.request:t,i=(Array.isArray(o.options)?o.options:[]).map((n,a)=>{const c=n&&typeof n=="object"&&!Array.isArray(n)?n:{};return{optionId:String(c.optionId??c.id??a),kind:String(c.kind??"choice"),...typeof c.label=="string"?{label:c.label}:{}}});return this.emitStatus("requestPermission","等待授权",Y(o),"session/request_permission"),this.permissionCallback({requestId:String(o.requestId??o.id??`codex-acp-permission-${Date.now()}`),params:e,options:i})}async requestUserInput(e){if(!this.userInputCallback)return{outcome:{outcome:"cancelled"}};const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=t.request&&typeof t.request=="object"&&!Array.isArray(t.request)?t.request:t;return this.emitStatus("requestPermission","等待输入",J(o),"elicitation/create"),this.userInputCallback({requestId:String(o.requestId??o.id??`codex-acp-input-${Date.now()}`),prompt:String(o.prompt??o.message??o.question??""),params:e,...typeof o.defaultValue=="string"?{defaultValue:o.defaultValue}:{}})}emitStatus(e,t,o,r){const i={phase:e,label:t,...o?{detail:o}:{},...r?{updateType:r}:{},atMs:Date.now()},n=this.statusTimeline[this.statusTimeline.length-1];n&&n.phase===i.phase&&n.label===i.label&&n.detail===i.detail&&n.updateType===i.updateType||(this.statusTimeline.push(i),this.statusCallback?.(i))}releaseLease(){this.lease?.release(),this.lease=null}}const K=new Set(["agent_message_chunk","agent_progress_chunk","agent_thought_chunk","tool_call","tool_call_update","plan","plan_update","plan_removed","aca_context_maintenance"]);function X(s){return K.has(s)}async function P(s,e){s.runtimeConfigured||(await s.client.configureRuntime({codexProvider:e?{baseUrl:e.baseUrl,apiKey:e.apiKey,revision:e.revision}:null}),s.markRuntimeConfigured())}function R(s){return s?{OPENAI_API_KEY:s.apiKey,OPENAI_BASE_URL:s.baseUrl}:{}}function G(s,e){if(e?.aborted)return!0;const t=s instanceof Error?s.message:String(s||"");return/compact.*timed out|request timed out.*compact|adapter closed|aborted|cancelled/i.test(t)}function g(s){if(!s||typeof s!="object"||Array.isArray(s))return null;const e=s.sessionId;return typeof e=="string"&&e.trim()?e.trim():null}function l(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function w(s){const e=String(s||"").trim();return e?e==="read-only"?"read-only":["agent-full-access","full-access","bypassPermissions","danger-full-access"].includes(e)?"danger-full-access":"workspace-write":null}function S(s){const e=String(s||"").trim();return e?["agent-full-access","full-access","bypassPermissions","danger-full-access"].includes(e)?"never":e==="acceptEdits"||e==="accept-edits"?"on-failure":"on-request":null}function T(s){return{...s.model?{model:s.model}:{},...S(s.mode)?{approvalPolicy:S(s.mode)}:{},...w(s.mode)?{sandbox:w(s.mode)}:{},...s.configOptionValues??{}}}function Y(s){const e=s.params&&typeof s.params=="object"&&!Array.isArray(s.params)?s.params:s;for(const t of["command","cwd","reason","grantRoot","method"]){const o=e[t];if(typeof o=="string"&&o.trim())return M(o)}}function J(s){for(const e of["prompt","message","question","title"]){const t=s[e];if(typeof t=="string"&&t.trim())return M(t)}}function M(s){const e=s.replace(/\s+/g," ").trim();return e.length>120?`${e.slice(0,117)}...`:e}function Q(){const s=Number.parseInt(process.env.ACA_CODEX_ACP_PROMPT_TIMEOUT_MS??process.env.ACA_ACP_PROMPT_TIMEOUT_MS??"",10);return Number.isInteger(s)&&s>=3e4?s:360*60*1e3}function Z(s){const e=Number.isInteger(s)?Number(s):Number.parseInt(process.env.ACA_CODEX_ACP_COMPACT_TIMEOUT_MS??"",10);return Number.isFinite(e)&&e>=3e4?Math.min(e,6e5):12e4}function q(s){if(!s||typeof s!="object"||Array.isArray(s))return null;const e=s;return typeof e.sessionId=="string"&&e.sessionId.trim()?e.sessionId:null}function ee(s){const e=l(s),t=l(e?._meta);return U(t?.acaContextUsage)}function U(s){const e=l(s);if(!e)return null;const t=h(e.contextWindow),o=h(e.usedTokens),r=h(e.inputTokens),i=String(e.state||"unknown"),n=["active","compacted","new_thread"].includes(i)?i:"unknown";return{usedTokens:o,inputTokens:r,contextWindow:t,ratio:t>0?Math.max(0,h(e.ratio)||o/t):0,observedAtMs:h(e.observedAtMs)||Date.now(),state:n,maintenanceAction:typeof e.maintenanceAction=="string"?e.maintenanceAction:null}}function h(s){return typeof s=="number"&&Number.isFinite(s)&&s>=0?s:0}export{de as CodexAcpProvider,V as codexAcpCapabilities};
|
|
1
|
+
import m from"node:fs";import{runAbortableRequest as x}from"../../client/abortable-request.js";import{BoundedItemBuffer as O}from"../../client/bounded-buffer.js";import{promptBlocksToAcpContent as $}from"../../client/acp-content.js";import{acpSessionUpdateFromParams as F,eventFromAcpSessionUpdate as j,statusFromAcpSessionUpdate as z,subtaskContextFromAcpSessionUpdate as N}from"../../client/acp-events.js";import{defaultAcpRuntimePool as _}from"../../client/acp-runtime-pool.js";import{resolveCodexAcpLaunch as k}from"./launch.js";import{cancelCodexRuntime as W}from"./cancellation.js";import{CodexPromptPerformanceTracker as H,CodexUsageLoopDetector as V,codexRawResponseUsageFromAcpSessionUpdate as B,codexTokenUsageFromAcpSessionUpdate as K,readCodexContextMaintenancePolicy as P}from"./context-maintenance.js";import{ensureCodexProviderRuntimeConfig as R}from"../../../core/codex-provider-runtime-config.js";const X={sessionResume:!0,imageInput:!0,fileAttachment:!0,filesystem:!0,terminal:!0,permissionRequest:!0,configOptions:!0,usage:!0,contextUsage:!0,contextCompaction:!0,plan:!0,diff:!0};class he{id="codex-acp";name="Codex ACP";capabilities=X;async createSession(e){return new G(e.cwd,e.providerSessionId??null,e.timeoutMs)}async forkSession(e){if(!m.existsSync(e.cwd)||!m.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=e.sourceProviderSessionId.trim(),o=await R(),n=await _.acquire({providerId:"codex-acp",cwd:e.cwd,providerSessionId:t,runtimeIdentity:o?.runtimeIdentity||"default",env:M(o),...k(),onSessionUpdate:()=>{}});try{await T(n,o),n.initialized||(await n.client.initialize(6e4),n.markInitialized()),e.onStatus?.({phase:"forking",label:"正在分叉 Codex 会话",detail:t,updateType:"session/fork",atMs:Date.now()});const r=await n.client.forkSession({sessionId:t,cwd:e.cwd,config:q(e)},e.timeoutMs??12e4),i=C(r);if(!i)throw new Error("Codex ACP session/fork did not return sessionId");return{providerSessionId:i}}finally{n.release()}}}class G{cwd;providerSessionId;defaultTimeoutMs;lease=null;sessionResponse=null;statusCallback=null;updateCallback=null;permissionCallback=null;userInputCallback=null;abortHandler=null;statusTimeline=[];updates=new O(16);content="";performanceTracker=null;usageLoopDetector=null;usagePatternReport=null;usageLoopWarningActive=!1;cancellation=null;constructor(e,t,o=te()){this.cwd=e,this.providerSessionId=t,this.defaultTimeoutMs=o}async sendPrompt(e){if(!m.existsSync(e.cwd)||!m.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=Date.now();this.statusCallback=e.onStatus??null,this.updateCallback=e.onUpdate??null,this.permissionCallback=e.onPermissionRequest??null,this.userInputCallback=e.onUserInputRequest??null,this.attachAbortSignal(e.signal),this.content="",this.updates.clear(),this.statusTimeline.length=0;const o=P();this.performanceTracker=new H(t),this.usageLoopDetector=new V(o),this.usageLoopWarningActive=!1;const n={error:null,stopping:null};let r=null,i=null,a=this.providerSessionId,c,S=null;try{this.emitStatus("initializing","Codex ACP 启动中","codex-acp");const d=await this.acquireRuntime(e.cwd);this.lease=d,r=d.client,i=d.started,await this.initialize(d),a=await this.establishSession(d,e),await this.applyConfig(r,a,e);const L=r,v=a;this.emitStatus("thinking","思考中"),S=this.startSlowStatusTimer(),this.usagePatternReport=p=>{if(n.error)return;const A=Math.round(p.maxInputTokens/1e3),g=`同一 Turn 已连续请求至少 ${p.sampleCount} 次,单次输入约 ${A}k tokens`;if(p.sampleCount<o.usageLoopInterruptSamples){this.usageLoopWarningActive=!0,this.emitStatus("thinking","Codex 出现低产出内部循环",g,"aca.performance.low_output_loop");return}const y=`Codex 低产出内部循环:同一 Turn 已连续请求至少 ${p.sampleCount} 次,单次输入约 ${A}k tokens,且未观察到有效进展`;n.error=new Error(y),this.emitStatus("thinking","正在中断 Codex 低产出内部循环",g,"aca.performance.low_output_loop_interrupting"),n.stopping=this.stopRuntime(d,v).then(l=>{const w=l.forced?`${g};取消请求失败:${l.reason};已关闭运行实例`:g;l.forced&&(n.error=new Error(`${y};取消请求失败:${l.reason};已关闭运行实例`)),this.emitStatus("failed","Codex 已中断低产出内部循环",w,"aca.performance.low_output_loop_interrupted")}).catch(l=>{const w=l instanceof Error?l.message:String(l);n.error=new Error(`${y};${w}`),this.emitStatus("failed","Codex 循环中断失败",w,"aca.performance.low_output_loop_interrupt_failed")})};try{c=await this.promptWithAbort(L,{sessionId:v,prompt:$(e.prompt,e.promptBlocks),timeoutMs:e.timeoutMs??this.defaultTimeoutMs,signal:e.signal})}catch(p){throw await n.stopping,n.error?n.error:p}if(await n.stopping,n.error)throw n.error;const h=E(c);h&&h!==a&&(a=h,this.providerSessionId=h,d.setProviderSession({providerSessionId:h,sessionResponse:this.sessionResponse}))}finally{await n.stopping,await this.cancellation?.catch(()=>{}),S&&clearInterval(S),this.usagePatternReport=null,this.usageLoopDetector=null,this.usageLoopWarningActive=!1,this.abortHandler&&e.signal&&(e.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.releaseLease()}return this.emitStatus("completed","已完成"),{providerSessionId:a,cliType:"builtin",agentType:"codex",effectiveConfig:{model:e.model??null,mode:e.mode??null,configOptionValues:e.configOptionValues??null,command:i.command,processPid:i.child.pid??null,provider:"codex-acp",protocol:"acp"},command:i.command,args:i.args,cwd:e.cwd,exitCode:i.child.exitCode,signal:i.child.signalCode,durationMs:Date.now()-t,stdout:r.rpc.stdout,stderr:r.rpc.stderr,content:this.content.trim(),updateCount:this.updates.count(),updates:this.updates.snapshot(),statusTimeline:[...this.statusTimeline],performance:this.performanceTracker?.snapshot(),contextUsage:oe(c),promptResponse:c}}async compactContext(e){if(!m.existsSync(e.cwd)||!m.statSync(e.cwd).isDirectory())throw new Error(`Project root does not exist or is not a directory: ${e.cwd}`);const t=Date.now();this.statusCallback=e.onStatus??null,this.updateCallback=e.onUpdate??null,this.attachAbortSignal(e.signal);let o=this.providerSessionId,n;try{this.emitStatus("initializing","Codex ACP 启动中","codex-acp");const i=await this.acquireRuntime(e.cwd);this.lease=i,await this.initialize(i),o=await this.establishSession(i,e),await this.applyConfig(i.client,o,e);const a=se(e.timeoutMs);n=await this.compactWithAbort(i.client,{sessionId:o,allowRollover:e.allowRollover===!0,timeoutMs:a,signal:e.signal});const c=E(n);c&&c!==o&&(o=c,this.providerSessionId=c,i.setProviderSession({providerSessionId:c,sessionResponse:this.sessionResponse}))}catch(i){if(this.lease&&Q(i,e.signal)){const a=this.lease;this.lease=null,await a.dispose().catch(()=>{})}throw this.emitStatus("failed","上下文压缩失败",i instanceof Error?i.message:String(i)),i}finally{this.abortHandler&&e.signal&&(e.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null),this.releaseLease()}const r=u(n)??{};return{providerSessionId:o||this.providerSessionId||"",contextUsage:D(r.contextUsage),maintenance:u(r.maintenance)??{},durationMs:Date.now()-t}}async cancel(){this.providerSessionId&&this.lease&&await this.stopRuntime(this.lease,this.providerSessionId)}stopRuntime(e,t){if(this.cancellation)return this.cancellation;const o=W(e,t);return this.cancellation=o,o.finally(()=>{this.cancellation===o&&(this.cancellation=null)}).catch(()=>{}),o}async close(){await this.cancellation?.catch(()=>{}),this.statusCallback=null,this.updateCallback=null,this.permissionCallback=null,this.userInputCallback=null,this.abortHandler&&(this.abortHandler=null),this.releaseLease()}async acquireRuntime(e){const t=k(),o=await R(),n=await _.acquire({providerId:"codex-acp",cwd:e,providerSessionId:this.providerSessionId,runtimeIdentity:o?.runtimeIdentity||"default",env:M(o),command:t.command,args:t.args,onSessionUpdate:r=>this.handleSessionUpdate(r),onClientRequest:async(r,i)=>{if(r==="session/request_permission")return this.requestPermission(i);if(r==="elicitation/create"||r==="session/request_user_input")return this.requestUserInput(i);throw new Error(`Unsupported Codex ACP client request: ${r}`)}});try{return await T(n,o),n}catch(r){throw await n.dispose().catch(()=>{}),r}}async initialize(e){e.initialized||(await e.client.initialize(6e4),e.markInitialized())}async establishSession(e,t){const o=e.client,n=q(t);if(e.providerSessionId&&e.sessionEstablished)return this.providerSessionId=e.providerSessionId,this.sessionResponse=e.sessionResponse,e.providerSessionId;if(this.providerSessionId)try{this.emitStatus("resuming","Codex ACP 会话恢复中","session/load");const a=await o.loadSession({sessionId:this.providerSessionId,cwd:t.cwd,config:n},6e4);this.sessionResponse=u(a);const c=C(a)||this.providerSessionId;return this.providerSessionId=c,e.setProviderSession({providerSessionId:c,sessionResponse:this.sessionResponse}),c}catch(a){if(t.requireSessionResume){const c=a instanceof Error?a.message:String(a);throw new Error(`无法恢复导入的 Codex ACP Session ${this.providerSessionId}:${c}`)}this.providerSessionId=null}this.emitStatus("acp","Codex ACP 会话创建中","session/new");const r=await o.newSession({cwd:t.cwd,config:n},12e4);this.sessionResponse=u(r);const i=C(r);if(!i)throw new Error("Codex ACP session/new did not return sessionId");return this.providerSessionId=i,e.setProviderSession({providerSessionId:i,sessionResponse:this.sessionResponse}),i}async applyConfig(e,t,o){o.model&&await e.setSessionConfigOption({sessionId:t,configId:"model",value:o.model},6e4).catch(()=>{});const n=b(o.mode);n&&await e.setSessionConfigOption({sessionId:t,configId:"approvalPolicy",value:n},6e4).catch(()=>{});const r=I(o.mode);r&&await e.setSessionConfigOption({sessionId:t,configId:"sandbox",value:r},6e4).catch(()=>{});for(const[i,a]of Object.entries(o.configOptionValues??{}))["model","mode","sandbox","approvalPolicy"].includes(i)||await e.setSessionConfigOption({sessionId:t,configId:i,value:a},6e4).catch(()=>{})}handleSessionUpdate(e){const t=F(e),o=String(t?.update.sessionUpdate||""),n=N(e);if(!n&&J(o))this.performanceTracker?.recordEvent(),this.usageLoopDetector?.recordMeaningfulEvent(),this.usageLoopWarningActive&&(this.usageLoopWarningActive=!1,this.emitStatus("thinking","Codex 已恢复执行","已重新执行工具或产生有效输出","aca.performance.loop_recovered"));else if(!n&&o==="aca_codex_raw_response_usage"){const a=B(e),c=a?this.usageLoopDetector?.recordUsage(a):null;c&&this.usagePatternReport?.(c)}else if(!n&&o==="usage_update"){const a=K(e),c=a?this.usageLoopDetector?.recordUsage(a):null;c&&this.usagePatternReport?.(c)}this.updates.push({method:"session/update",params:e});const r=j(e);r&&(r.type==="agent_message_chunk"&&!n&&(this.content+=r.text??""),this.updateCallback?.(r));const i=z(e);i&&this.emitStatus(i.phase,i.label,i.detail,i.updateType)}startSlowStatusTimer(){const e=P().slowEventThresholdMs,t=setInterval(()=>{const o=this.performanceTracker,n=Date.now();if(!o?.shouldReportSlow(n,e))return;const r=o.snapshot(n),i=Math.max(1,Math.round(r.silentForMs/6e4)),a=this.usageLoopWarningActive?"Codex 可能卡在内部循环":"Codex 长时间没有有效进展";this.emitStatus("thinking",a,`已 ${i} 分钟没有执行工具或产生有效输出`,"aca.performance.slow")},Math.min(3e4,Math.max(1e3,Math.floor(e/4))));return t.unref(),t}attachAbortSignal(e){if(e){if(this.abortHandler=()=>{this.cancel().catch(()=>{})},e.aborted)throw new Error("Codex ACP prompt cancelled");e.addEventListener("abort",this.abortHandler,{once:!0})}}async promptWithAbort(e,t){return x({signal:t.signal,cancelledMessage:"Codex ACP prompt cancelled",startRequest:()=>e.prompt({sessionId:t.sessionId,prompt:t.prompt},t.timeoutMs),onAbort:async()=>{await this.lease?.dispose()}})}async compactWithAbort(e,t){return x({signal:t.signal,cancelledMessage:"Codex ACP 上下文压缩已取消",startRequest:()=>e.compactSession({sessionId:t.sessionId,allowRollover:t.allowRollover,timeoutMs:t.timeoutMs},t.timeoutMs),onAbort:async()=>{await this.lease?.dispose()}})}async requestPermission(e){if(!this.permissionCallback)return{outcome:{outcome:"cancelled"}};const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=t.request&&typeof t.request=="object"&&!Array.isArray(t.request)?t.request:t,r=(Array.isArray(o.options)?o.options:[]).map((i,a)=>{const c=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{optionId:String(c.optionId??c.id??a),kind:String(c.kind??"choice"),...typeof c.label=="string"?{label:c.label}:{}}});return this.emitStatus("requestPermission","等待授权",Z(o),"session/request_permission"),this.permissionCallback({requestId:String(o.requestId??o.id??`codex-acp-permission-${Date.now()}`),params:e,options:r})}async requestUserInput(e){if(!this.userInputCallback)return{outcome:{outcome:"cancelled"}};const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=t.request&&typeof t.request=="object"&&!Array.isArray(t.request)?t.request:t;return this.emitStatus("requestPermission","等待输入",ee(o),"elicitation/create"),this.userInputCallback({requestId:String(o.requestId??o.id??`codex-acp-input-${Date.now()}`),prompt:String(o.prompt??o.message??o.question??""),params:e,...typeof o.defaultValue=="string"?{defaultValue:o.defaultValue}:{}})}emitStatus(e,t,o,n){const r={phase:e,label:t,...o?{detail:o}:{},...n?{updateType:n}:{},atMs:Date.now()},i=this.statusTimeline[this.statusTimeline.length-1];i&&i.phase===r.phase&&i.label===r.label&&i.detail===r.detail&&i.updateType===r.updateType||(this.statusTimeline.push(r),this.statusCallback?.(r))}releaseLease(){this.lease?.release(),this.lease=null}}const Y=new Set(["agent_message_chunk","agent_progress_chunk","agent_thought_chunk","tool_call","tool_call_update","plan","plan_update","plan_removed","aca_context_maintenance"]);function J(s){return Y.has(s)}async function T(s,e){s.runtimeConfigured||(await s.client.configureRuntime({codexProvider:e?{baseUrl:e.baseUrl,apiKey:e.apiKey,revision:e.revision}:null}),s.markRuntimeConfigured())}function M(s){return s?{OPENAI_API_KEY:s.apiKey,OPENAI_BASE_URL:s.baseUrl}:{}}function Q(s,e){if(e?.aborted)return!0;const t=s instanceof Error?s.message:String(s||"");return/compact.*timed out|request timed out.*compact|adapter closed|aborted|cancelled/i.test(t)}function C(s){if(!s||typeof s!="object"||Array.isArray(s))return null;const e=s.sessionId;return typeof e=="string"&&e.trim()?e.trim():null}function u(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function I(s){const e=String(s||"").trim();return e?e==="read-only"?"read-only":["agent-full-access","full-access","bypassPermissions","danger-full-access"].includes(e)?"danger-full-access":"workspace-write":null}function b(s){const e=String(s||"").trim();return e?["agent-full-access","full-access","bypassPermissions","danger-full-access"].includes(e)?"never":e==="acceptEdits"||e==="accept-edits"?"on-failure":"on-request":null}function q(s){return{...s.model?{model:s.model}:{},...b(s.mode)?{approvalPolicy:b(s.mode)}:{},...I(s.mode)?{sandbox:I(s.mode)}:{},...s.configOptionValues??{}}}function Z(s){const e=s.params&&typeof s.params=="object"&&!Array.isArray(s.params)?s.params:s;for(const t of["command","cwd","reason","grantRoot","method"]){const o=e[t];if(typeof o=="string"&&o.trim())return U(o)}}function ee(s){for(const e of["prompt","message","question","title"]){const t=s[e];if(typeof t=="string"&&t.trim())return U(t)}}function U(s){const e=s.replace(/\s+/g," ").trim();return e.length>120?`${e.slice(0,117)}...`:e}function te(){const s=Number.parseInt(process.env.ACA_CODEX_ACP_PROMPT_TIMEOUT_MS??process.env.ACA_ACP_PROMPT_TIMEOUT_MS??"",10);return Number.isInteger(s)&&s>=3e4?s:360*60*1e3}function se(s){const e=Number.isInteger(s)?Number(s):Number.parseInt(process.env.ACA_CODEX_ACP_COMPACT_TIMEOUT_MS??"",10);return Number.isFinite(e)&&e>=3e4?Math.min(e,6e5):12e4}function E(s){if(!s||typeof s!="object"||Array.isArray(s))return null;const e=s;return typeof e.sessionId=="string"&&e.sessionId.trim()?e.sessionId:null}function oe(s){const e=u(s),t=u(e?._meta);return D(t?.acaContextUsage)}function D(s){const e=u(s);if(!e)return null;const t=f(e.contextWindow),o=f(e.usedTokens),n=f(e.inputTokens),r=String(e.state||"unknown"),i=["active","compacted","new_thread"].includes(r)?r:"unknown";return{usedTokens:o,inputTokens:n,contextWindow:t,ratio:t>0?Math.max(0,f(e.ratio)||o/t):0,observedAtMs:f(e.observedAtMs)||Date.now(),state:i,maintenanceAction:typeof e.maintenanceAction=="string"?e.maintenanceAction:null}}function f(s){return typeof s=="number"&&Number.isFinite(s)&&s>=0?s:0}export{he as CodexAcpProvider,X as codexAcpCapabilities};
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.1.
|
|
1
|
+
const o="0.1.44";export{o as AICA_VERSION};
|