grix-connector 4.13.0 → 4.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/acp/acp-adapter.js +13 -13
- package/dist/adapter/acp/grok-liveness.js +3 -0
- package/dist/adapter/agy/agy-adapter.js +10 -10
- package/dist/adapter/agy/stream-parser.js +2 -2
- package/dist/adapter/claude/claude-adapter.js +22 -21
- package/dist/adapter/claude/model-list.js +1 -1
- package/dist/adapter/claude/session-recovery.js +1 -0
- package/dist/adapter/codex/codex-bridge.js +12 -10
- package/dist/adapter/codex/wait-loop.js +1 -0
- package/dist/adapter/cursor/cursor-adapter.js +1 -1
- package/dist/adapter/cursor/fetch-usage.js +1 -1
- package/dist/adapter/cursor/index.js +1 -1
- package/dist/adapter/pi/pi-adapter.js +4 -4
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.14.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/audit/adapters/codex/codex-audit-adapter.js +1 -1
- package/dist/bridge/adapter-pool.js +1 -1
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/event-queue.js +1 -1
- package/dist/bridge/event-stop.js +1 -1
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/rate-limits.js +1 -1
- package/dist/bridge/send-controller.js +3 -3
- package/dist/bridge/session-control-router.js +3 -3
- package/dist/bridge/toolbar-meta.js +1 -1
- package/dist/bridge/toolbar-selection.js +1 -1
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/persistence/session-binding-store.js +2 -2
- package/dist/core/protocol/protocol-send.js +1 -0
- package/dist/core/provider-quota/grix-relay.js +1 -0
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/util/quoted-message-stream.js +3 -3
- package/dist/default-skills/grix-agent-dispatch/SKILL.md +37 -7
- package/dist/default-skills/grix-agent-dispatch/scripts/callback-dedupe.mjs +12 -0
- package/dist/grix.js +6 -6
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +37 -0
- package/openclaw-plugin/index.js +9 -3
- package/openclaw-plugin/skills/grix-agent-dispatch/SKILL.md +37 -7
- package/openclaw-plugin/skills/grix-agent-dispatch/scripts/callback-dedupe.mjs +12 -0
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.13.0.tgz +0 -0
|
@@ -6,7 +6,7 @@ ${s}`),t.filter(i=>i.length>0).join(`
|
|
|
6
6
|
`)}class Y extends L{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){u.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class $ extends L{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundMessageIds=new ce;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;lastContextBySession=new Map;pendingHandoffBySession=new Map;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];transcriptPathBySession=new Map;activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const n=e.options??{};this.bindingStore=n.bindingStore instanceof fe?n.bindingStore:null,this.identity=new re("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new ae,this.internalApi.setInvokeHandler(async(t,n,s,i)=>this.callbacks.agentInvoke(t,n,i)),await this.internalApi.start()),this.notifyBindingReady(),this.refreshModels().then(()=>this.notifyBindingReady()).catch(()=>{}),this.refreshAccountRateLimits().then(()=>this.notifyBindingReady()).catch(()=>{})}get availableModels(){return this._availableModels}get availableModes(){return X.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await pe({command:this.config.command,env:e,cwd:process.cwd()});t.length>0&&(this._availableModels=t,u.info("cursor-adapter",`Loaded ${t.length} available models`))}catch(e){u.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())I(e.child,"SIGTERM");this.activeBySession.clear(),this.transcriptPathBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const n=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...n,cwd:typeof t?.cwd=="string"?t.cwd:n.cwd,modelId:typeof t?.modelId=="string"?t.modelId:n.modelId,modeId:typeof t?.modeId=="string"?t.modeId:n.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.transcriptPathBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingQuestionAnswerBySession.delete(e),this.pendingHandoffBySession.delete(e);for(const[t,n]of this.pendingQuestionByRequestId)n.sessionId===e&&this.pendingQuestionByRequestId.delete(t)}sendPrompt(e){const t=new Y(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const n=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,i=this.pendingBySession.get(s)??[];return i.push({event:n,request:e,handle:t}),this.pendingBySession.set(s,i),this.tryStartNext(s),t}tryStartNext(e){if(this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const n=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),n&&this.startJob(n,!1,0)}startJob(e,t,n){const{event:s,request:i,handle:r}=e;s.audit?.enabled&&!this.auditCaptures.has(s.event_id)&&this.auditCaptures.set(s.event_id,[]);const o=i.adapterSessionId,a=this.sessionRuntime.get(i.adapterSessionId)??{},l=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),l.trust!==!1&&c.push("--trust");const h=a.cwd||l.workspace;this.internalApi&&h&&(this.ensureWorkspaceMcpAndSkills(h),c.push("--approve-mcps")),h&&c.push("--workspace",h);const p=a.modelId||l.model;p&&c.push("--model",p);const _=C(a.modeId||l.mode)??"full_auto";_==="full_auto"?c.push("--yolo"):_==="plan"&&c.push("--plan");const v=a.cursorSessionId??this.bindingStore?.getAcpSessionId(i.adapterSessionId),b=!!(v&&l.use_continue!==!1&&!t);b&&c.push("--resume",v),c.push(this.buildPromptText(i));const f={...process.env,...this.config.env??{}},y=M(this.config.command,f);u.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let g;try{g=B(y.command,[...y.prefixArgs,...c],{cwd:h||process.cwd(),env:y.env,stdio:["ignore","pipe","pipe"]}).process}catch(S){this.finishActive(o,"failed",`spawn failed: ${S instanceof Error?S.message:String(S)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const m={event:s,request:i,handle:r,child:g,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",lastIoAt:Date.now(),sawResult:!1,descendantBaseline:void 0,retryCount:n,usedContinue:b,workspace:h||process.cwd(),args:c};this.activeBySession.set(o,m),this.notifyBindingReady(o),this.armActiveIdleTimer(o);const w=i.timeoutMs&&i.timeoutMs>0?i.timeoutMs:0;w>0&&(m.timer=setTimeout(()=>{m.done||(I(g,"SIGTERM"),this.finishActive(o,"failed",`cursor agent timeout after ${w}ms`))},w)),q({input:g.stdout}).on("line",S=>this.handleStdoutLineForActive(m,S)),g.stderr?.on("data",S=>{if(m.done)return;const k=m.stderr+String(S??"");m.stderr=k.length>$.STDERR_MAX_CHARS?k.slice(-$.STDERR_MAX_CHARS):k,m.lastIoAt=Date.now(),this.armActiveIdleTimer(o)}),g.once("error",S=>{this.finishActive(o,"failed",`spawn failed: ${String(S?.message??S)}`)}),g.once("close",S=>{if(!m.done)if((S??0)===0)this.finishActive(o,"responded");else{if(this.shouldRetryWithoutContinue(m)){m.timer&&clearTimeout(m.timer),m.idleTimer&&clearTimeout(m.idleTimer),this.activeBySession.delete(o),this.startJob(e,!0,m.retryCount+1);return}const k=m.stderr.trim()||`cursor agent exited with code ${S??-1}`;this.finishActive(o,"failed",k)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(I(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){u.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){u.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const n={adapterSessionId:t,text:this.inboundMessageIds.inject(t,Me(String(e.content??""),e),e.msg_id),contextMessages:Be(e)},s=new Y(t),i=this.pendingBySession.get(t)??[];i.push({event:e,request:n,handle:s}),this.pendingBySession.set(t,i),u.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${i.length}`),this.tryStartNext(t)}cancelSessionWork(e,t){const n=this.pendingBySession.get(e)??[];this.pendingBySession.delete(e);const s=this.activeBySession.get(e);s&&(this.killChildWithFallback(s.child),this.finishActive(e,"canceled",t));for(const i of n)this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled",t),i.handle.emitDone({status:"canceled",error:t})}killChildWithFallback(e){I(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{I(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const n=this.activeBySession.get(t);if(n?.event.event_id===e){this.killChildWithFallback(n.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],i=s.findIndex(r=>r.event.event_id===e);if(i>=0){const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[n,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(n,"canceled","stopped");return}for(const[n,s]of this.pendingBySession.entries()){const i=s.findIndex(o=>o.event.event_id===e);if(i<0)continue;const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(n):this.pendingBySession.set(n,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),n=e.params??{},s=String(n.session_id??"").trim(),i=e.action_id;if(t==="claude_interaction_reply")return String(n.kind??"").trim()==="permission"?(this.callbacks.sendLocalActionResult(i,"failed",void 0,"unsupported","Cursor adapter does not support interactive permission approvals"),{handled:!0,kind:"permission_unsupported"}):this.handleQuestionReply(e);switch(t){case"set_model":{const r=String(n.model_id??"").trim();if(!r||!s)return this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modelId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"model_set",session_context:{model_id:r,mode_id:a.mode_id,modelId:r,modeId:a.mode_id},model_id:r,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const r=C(n.mode_id);if(!r||!s)return this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_params","mode_id must be approval, full_auto, or plan and session_id is required"),{handled:!0,kind:"set_mode"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modeId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:r,modelId:a.model_id,modeId:r},model_id:a.model_id,mode_id:r,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const r=s?this.sessionRuntime.get(s):void 0,o=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:r?.cwd??o.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:r?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{await this.refreshAccountRateLimits({force:!0});const r=this.getRateLimitsSnapshot(s||void 0);return this.callbacks.sendLocalActionResult(i,"ok",r),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const r=s?this.getUsageSnapshot(s):null;if(r){const o={inputTokens:r.total.input,outputTokens:r.total.output,cacheReadInputTokens:r.total.cacheRead,cacheCreationInputTokens:r.total.cacheWrite};this.callbacks.sendLocalActionResult(i,"ok",{sessionId:s,adapterType:"cursor",sampledAt:r.sampledAt,turns:r.turns,total:o,models:[{model:this.getToolbarMeta(s).model_id??"auto",turns:r.turns,total:o}]})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"usage_not_found","No usage data found for this session");return{handled:!0,kind:"get_session_usage"}}case"session_control":{const r=String(n.verb??"").trim().toLowerCase();if(r==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(i,"ok",{outcome:"restarted"});else if(r==="status"){const o=this.sessionRuntime.get(s),a=this.config.options??{},l=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(i,"ok",{verb:"status",status:c?"running":"idle",session_context:{model_id:l.model_id,mode_id:l.mode_id,cwd:o?.cwd??a.workspace??null},model_id:l.model_id,mode_id:l.mode_id,modelId:l.model_id,modeId:l.mode_id,cwd:o?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_verb",`Unsupported verb: ${r}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"}]}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n,t)}async runCompactHandoff(e,t=""){if(!e)return{status:"failed",message:"session_id is required"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const n=this.sessionRuntime.get(e)??{},s=this.config.options??{},i=n.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!i)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};const r=String(n.cwd||s.workspace||process.cwd()),o=String(n.modelId||s.model||""),a=C(n.modeId||s.mode)??"full_auto",l=t.trim(),c=l?`${Q}
|
|
7
7
|
|
|
8
8
|
Additional focus from user:
|
|
9
|
-
${l}`:Q;this.emit("pauseIntake","compaction"),u.info("cursor-adapter",`[compact] summarize resume=${i} session=${e}`);try{const h=await this.runPrintOnce({prompt:c,resumeChatId:i,cwd:r,modelId:o||void 0,modeId:a,timeoutMs:W});if(!h.ok||!h.text.trim())return{status:"failed",message:h.error??"Summarize failed (empty result)"};const p=await this.createEmptyChat();return p?(this.sessionRuntime.set(e,{...n,cwd:r,modelId:o||n.modelId,modeId:a,cursorSessionId:p}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,p),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,h.text.trim()),this.lastContextBySession.set(e,Se(0,ve(o))),this.notifyBindingReady(e),u.info("cursor-adapter",`[compact] handoff ready: old=${i} new=${p} summaryChars=${h.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:i,chatId:p}}):{status:"failed",message:"agent create-chat failed"}}finally{this.emit("resumeIntake","compaction")}}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=M(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const i=C(e.modeId)??"full_auto";return i==="full_auto"?s.push("--yolo"):i==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(r=>{let o;try{o=B(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(f){r({ok:!1,text:"",error:`spawn failed: ${f instanceof Error?f.message:String(f)}`});return}let a="",l="",c="",h=!1;const p=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:W,_=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(o),r({ok:!1,text:a,sessionId:l||void 0,error:`compact timeout after ${p}ms`}))},p);_.unref?.();const v=(f,y)=>{h||(h=!0,clearTimeout(_),r({ok:f,text:a,sessionId:l||void 0,error:y}))};q({input:o.stdout}).on("line",f=>{const y=f.trim();if(!y)return;let g;try{g=JSON.parse(y)}catch{return}if(g?.type!=="result")return;const m=typeof g?.result=="string"?g.result:"";m&&(a=m);const w=String(g?.session_id??"").trim();w&&(l=w)}),o.stderr?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),o.on("error",f=>v(!1,f.message)),o.on("close",f=>{if(!h){if(a.trim()){v(!0);return}v(!1,c.trim()||`cursor agent exited with code ${f??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=M(this.config.command,e);return new Promise(n=>{let s;try{s=B(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let i="",r=!1;const o=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{i+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(r)return;r=!0,clearTimeout(o);const l=i.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(l)?l:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!T(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await oe(this.config.command||"cursor-agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?V(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=N(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt);return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const i=(async()=>{const r=await ge();this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits
|
|
9
|
+
${l}`:Q;this.emit("pauseIntake","compaction"),u.info("cursor-adapter",`[compact] summarize resume=${i} session=${e}`);try{const h=await this.runPrintOnce({prompt:c,resumeChatId:i,cwd:r,modelId:o||void 0,modeId:a,timeoutMs:W});if(!h.ok||!h.text.trim())return{status:"failed",message:h.error??"Summarize failed (empty result)"};const p=await this.createEmptyChat();return p?(this.sessionRuntime.set(e,{...n,cwd:r,modelId:o||n.modelId,modeId:a,cursorSessionId:p}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,p),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,h.text.trim()),this.lastContextBySession.set(e,Se(0,ve(o))),this.notifyBindingReady(e),u.info("cursor-adapter",`[compact] handoff ready: old=${i} new=${p} summaryChars=${h.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:i,chatId:p}}):{status:"failed",message:"agent create-chat failed"}}finally{this.emit("resumeIntake","compaction")}}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=M(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const i=C(e.modeId)??"full_auto";return i==="full_auto"?s.push("--yolo"):i==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(r=>{let o;try{o=B(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(f){r({ok:!1,text:"",error:`spawn failed: ${f instanceof Error?f.message:String(f)}`});return}let a="",l="",c="",h=!1;const p=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:W,_=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(o),r({ok:!1,text:a,sessionId:l||void 0,error:`compact timeout after ${p}ms`}))},p);_.unref?.();const v=(f,y)=>{h||(h=!0,clearTimeout(_),r({ok:f,text:a,sessionId:l||void 0,error:y}))};q({input:o.stdout}).on("line",f=>{const y=f.trim();if(!y)return;let g;try{g=JSON.parse(y)}catch{return}if(g?.type!=="result")return;const m=typeof g?.result=="string"?g.result:"";m&&(a=m);const w=String(g?.session_id??"").trim();w&&(l=w)}),o.stderr?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),o.on("error",f=>v(!1,f.message)),o.on("close",f=>{if(!h){if(a.trim()){v(!0);return}v(!1,c.trim()||`cursor agent exited with code ${f??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=M(this.config.command,e);return new Promise(n=>{let s;try{s=B(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let i="",r=!1;const o=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{i+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(r)return;r=!0,clearTimeout(o);const l=i.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(l)?l:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!T(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await oe(this.config.command||"cursor-agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?V(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=N(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt),i=t.rateLimits?.usagePeriod??t.usagePeriod;return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,...i?{usagePeriod:i}:{},contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const i=(async()=>{const r=await ge();if(this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,usagePeriod:r.usagePeriod??r.rateLimits?.usagePeriod,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits){const o=r.rateLimits.usagePeriod;u.info("cursor-adapter",`[rate-limits] period=${o} total=${r.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${r.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${r.rateLimits.fiveHour.resetsAt}`+(r.displayMessage?` msg=${r.displayMessage}`:""))}else u.warn("cursor-adapter",`[rate-limits] unavailable: ${r.error??"unknown"}`)})();this.rateLimitsInflight=i.finally(()=>{this.rateLimitsInflight=null}),await this.rateLimitsInflight}getToolbarMeta(e){const t=this.config.options??{},n=e||String(t.aibotSessionId??""),s=n?this.sessionRuntime.get(n):void 0,i=String(s?.modelId||t.model||"auto"),r=C(s?.modeId||t.mode)??"full_auto",o={model_id:i,mode_id:r,currentModelId:i,currentModeId:r,available_models:this.availableModels,available_modes:this.availableModes},a=this.cachedAccountRateLimits?.rateLimits;if(a?.fiveHour||a?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();o.rate_limits={...a.fiveHour?{fiveHour:a.fiveHour}:{},...a.sevenDay?{sevenDay:a.sevenDay}:{},usagePeriod:a.usagePeriod,sampledAt:c}}const l=n?this.lastContextBySession.get(n):void 0;return l&&(o.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage,usedTokens:l.usedTokens,sizeTokens:l.sizeTokens}),o}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},n=e||String(t.aibotSessionId??"");if(!n)return;const s=this.sessionRuntime.get(n),i=String(s?.cwd||t.workspace||"");i&&this.callbacks.sendUpdateBindingCard(n,this.activeBySession.has(n)?"busy":"ready",i,this.getToolbarMeta(n))}buildPromptText(e){let t;if(!e.contextMessages||e.contextMessages.length===0)t=e.text;else{const i=e.contextMessages.map(r=>`[${r.senderId}] ${r.content}`).join(`
|
|
10
10
|
`);t=R(e.text,`[Conversation context]
|
|
11
11
|
${i}`)}const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=R(t,`[User answered a previous agent question]
|
|
12
12
|
${n}`));const s=this.pendingHandoffBySession.get(e.adapterSessionId);return s&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=R(t,`[Previous conversation summary \u2014 continue from this handoff]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile as
|
|
1
|
+
import{execFile as M}from"node:child_process";import{homedir as S,platform as C}from"node:os";import{join as A}from"node:path";import{promisify as N}from"node:util";const d=N(M),U="https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",_="https://api2.cursor.sh/aiserver.v1.DashboardService/GetPlanInfo";function p(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function v(e){if(e==null||e==="")return 0;const t=typeof e=="number"?e:Number(String(e).trim());return!Number.isFinite(t)||t<=0?0:t>1e12?Math.floor(t/1e3):Math.floor(t)}function g(e){if(e==null||e==="")return 0;const t=typeof e=="number"?e:Number(String(e).trim());return!Number.isFinite(t)||t<=0?0:t>1e12?Math.floor(t):Math.floor(t*1e3)}function F(e){const t=String(e??"").toUpperCase();return t?t.includes("WEEKLY")?"weekly":t.includes("MONTHLY")?"monthly":null:null}function y(e,t){const n=g(e),o=g(t);if(n<=0||o<=n)return null;const r=(o-n)/864e5;return r>=5&&r<=9?"weekly":r>=25&&r<=40?"monthly":null}function I(e,t){const n=e.planUsage;if(!n||typeof n!="object")return null;const o=v(t?.resetsAtMs??e.billingCycleEnd);if(o<=0)return null;const r=t?.usagePeriod??y(e.billingCycleStart,e.billingCycleEnd)??"monthly",l=p(Number(n.totalPercentUsed??0)),u=n.apiPercentUsed,s=n.autoPercentUsed,a=p(Number(u!=null&&Number.isFinite(Number(u))?u:s??0));return{fiveHour:{usedPercentage:l,resetsAt:o},sevenDay:{usedPercentage:a,resetsAt:o},usagePeriod:r}}async function L(){if(C()!=="darwin")return null;try{const{stdout:e}=await d("security",["find-generic-password","-s","cursor-access-token","-a","cursor-user","-w"],{timeout:5e3,encoding:"utf8"});return String(e??"").trim()||null}catch{return null}}async function T(){const e=A(S(),"Library","Application Support","Cursor","User","globalStorage","state.vscdb");try{const{stdout:t}=await d("sqlite3",[e,"SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken' LIMIT 1;"],{timeout:5e3,encoding:"utf8"});return String(t??"").trim()||null}catch{return null}}async function E(){const e=await L();return e||T()}async function b(e,t,n,o){const r=await n(e,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","Connect-Protocol-Version":"1","x-cursor-client-type":"cli"},body:"{}",signal:o});if(!r.ok)return{ok:!1,status:r.status,json:null};try{return{ok:!0,status:r.status,json:await r.json()}}catch{return{ok:!1,status:r.status,json:null}}}async function w(e){const t=new Date().toISOString(),n=e&&Object.prototype.hasOwnProperty.call(e,"token")?e.token??null:await E();if(!n)return{available:!1,rateLimits:null,sampledAt:t,error:"no_cursor_access_token"};const o=e?.fetchImpl??fetch,r=e?.timeoutMs??12e3,l=new AbortController,u=setTimeout(()=>l.abort(),r);try{const[s,a]=await Promise.all([b(U,n,o,l.signal),b(_,n,o,l.signal).catch(()=>({ok:!1,status:0,json:null}))]);if(!s.ok)return{available:!1,rateLimits:null,sampledAt:t,error:`http_${s.status}`};const i=s.json??{},c=(a.ok?a.json:null)??{},h=F(c.planInfo?.includedUsagePeriod),P=y(i.billingCycleStart,i.billingCycleEnd),m=h??P??"monthly",k=c.planInfo?.includedUsageResetsAt??i.billingCycleEnd,f=I(i,{usagePeriod:m,resetsAtMs:k});return f?{available:!0,rateLimits:f,sampledAt:t,usagePeriod:f.usagePeriod,planName:c.planInfo?.planName,displayMessage:i.displayMessage}:{available:!1,rateLimits:null,sampledAt:t,usagePeriod:m,planName:c.planInfo?.planName,displayMessage:i.displayMessage,error:"plan_usage_unavailable"}}catch(s){const a=s instanceof Error?s.message:String(s);return{available:!1,rateLimits:null,sampledAt:t,error:a.includes("abort")?"timeout":a}}finally{clearTimeout(u)}}export{w as fetchCursorAccountUsage,y as inferCursorUsagePeriodFromCycle,I as mapCursorPeriodUsageToRateLimits,F as parseCursorIncludedUsagePeriod,E as readCursorAccessToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CursorAdapter as e,CURSOR_MODE_OPTIONS as s,extractCursorAssistantStreamDelta as
|
|
1
|
+
import{CursorAdapter as e,CURSOR_MODE_OPTIONS as s,extractCursorAssistantStreamDelta as a,mapCursorStreamJsonToRawEnvelope as t,isCursorAskQuestionTool as l,isCursorCreatePlanTool as C,parseCursorAskQuestionPayload as u,formatCursorCreatePlanText as d}from"./cursor-adapter.js";import{collapseCursorDisplayName as n,collapseCursorModelId as p,collapseExplodedCursorModels as m,fetchCursorParameterizedModels as c,fetchExplodedModelsFromCli as x,normalizeCursorAvailableModel as f,parseExplodedCursorModels as P}from"./fetch-models.js";import{fetchCursorAccountUsage as A,inferCursorUsagePeriodFromCycle as M,mapCursorPeriodUsageToRateLimits as U,parseCursorIncludedUsagePeriod as g,readCursorAccessToken as E}from"./fetch-usage.js";import{buildCursorContextWindow as k,buildCursorContextWindowFromUsage as w,estimateCursorContextTokens as O,resolveCursorContextWindowSize as R}from"./context-window.js";export{s as CURSOR_MODE_OPTIONS,e as CursorAdapter,k as buildCursorContextWindow,w as buildCursorContextWindowFromUsage,n as collapseCursorDisplayName,p as collapseCursorModelId,m as collapseExplodedCursorModels,O as estimateCursorContextTokens,a as extractCursorAssistantStreamDelta,A as fetchCursorAccountUsage,c as fetchCursorParameterizedModels,x as fetchExplodedModelsFromCli,d as formatCursorCreatePlanText,M as inferCursorUsagePeriodFromCycle,l as isCursorAskQuestionTool,C as isCursorCreatePlanTool,U as mapCursorPeriodUsageToRateLimits,t as mapCursorStreamJsonToRawEnvelope,f as normalizeCursorAvailableModel,u as parseCursorAskQuestionPayload,g as parseCursorIncludedUsagePeriod,P as parseExplodedCursorModels,E as readCursorAccessToken,R as resolveCursorContextWindowSize};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{execFile as $}from"node:child_process";import{promisify as T}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as R,writeFileSync as M,unlinkSync as C,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as B,delimiter as E}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as O,homedir as w}from"node:os";import{resolveCommandPath as N,resolveWindowsExecInvocation as L,spawnCommand as G,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{piGrixProviderId as Q,removePiGrixProvider as Z,writePiGrixProvider as tt}from"./pi-provider-config.js";import{agentIdOf as et}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as it,recordOmpMcpEntryPid as st,removeOmpMcpEntry as nt}from"./omp-mcp-config.js";function rt(d){return et(d)==="omp"}function ot(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function at(d){const t=ot(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const x=new Map;function dt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ct(d){const t=x.get(d);if(t!==void 0)return t;let e=!1;try{const i=T($),s=L(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return x.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class lt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ht=12e4,pt=90*1e3,b=1800*1e3;function P(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,v=3,ft=500;function gt(d){return new Promise(t=>setTimeout(t,d))}function vt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new W;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":rt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,i]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),s=e.data?.models;if(!s||s.length===0){if(t<v){await gt(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=i.data?.model,r={available_models:s.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))},l=vt(s);l.length>0&&(r.available_providers=l),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_id=n.provider,r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${s.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{C(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await nt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new lt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=i.provider?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:s}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.transport.send("set_model",{provider:s,modelId:p}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=B(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await X(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);if(!p)return{status:"failed",message:"Format: provider:model_id"};const h=await this.transport.send("set_model",{provider:c,modelId:p});return h?.success?{status:"ok",message:`Model set to ${c}:${p}`}:{status:"failed",message:`Failed to set model: ${h?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
1
|
+
import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as L,resolveWindowsExecInvocation as G,spawnCommand as j,killProcessGroup as _,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(d){return rt(d)==="omp"}function lt(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(d){const t=lt(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const b=new Map;function pt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(d){const t=b.get(d);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=G(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return b.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(d){return new Promise(t=>setTimeout(t,d))}function yt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,l=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(l?.piProviderId&&l.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const c={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(c.available_providers=p),r?.id&&(c.model_id=r.id),r?.provider&&(c.provider_id=r.provider,c.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),c),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);return p?(await this.setModelSelection(c,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${c}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
2
|
${r.map(c=>` ${c.provider??"unknown"}:${c.id} (${c.name??c.id})`).join(`
|
|
3
|
-
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=
|
|
4
|
-
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=
|
|
3
|
+
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
4
|
+
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=pt(t),s=u(N(),"grix-pi-mcp");C(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),R(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await ot(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=L(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(a=>a.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),l=it(this.agentName);if(this.provider){const a=this.isOmp(e)?"bare":"dollar";await nt(r,l,this.provider,a)?(n.includes("--provider")||n.push("--provider",l),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await st(r,l).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${l}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)});this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&!this.isOmp(e)&&(await ut(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let c={...process.env,...this.config.env};this.isOmp(e)&&(c=ht(c));const p=this.provider?.apiKey?.trim();p&&!c.GRIX_PROVIDER_API_KEY?.trim()&&(c.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=j(e,n,{env:c,cwd:h}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&at(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(a=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`)}),this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const I=a.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Z(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
|
|
5
5
|
`);e=`${e}
|
|
6
6
|
|
|
7
7
|
[Conversation context]
|
|
@@ -9,4 +9,4 @@ ${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inbou
|
|
|
9
9
|
`);e=`${e}
|
|
10
10
|
|
|
11
11
|
[Conversation context]
|
|
12
|
-
${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}
|
|
12
|
+
${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),l=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${l} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} (reliable) event=${t}`)}).catch(c=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},A.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!$(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let l=0;try{l=W(t,this.descendantBaseline)}catch{l=0}if(l>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${l}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<P||s!==null&&s<P)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(Y(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-f(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&$(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{A as PiAdapter};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
3
|
+
"bridgeVersion": "4.14.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.14.0.tgz",
|
|
5
5
|
"size": 24182,
|
|
6
6
|
"unpackedSize": 96521,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "6bdd548230d6242c551803ff23363fea36879c4b",
|
|
8
|
+
"integrity": "sha512-wJA5oLVBnLXetFfXEC1OzfTSWRRhdtopRpPMCldkfLpTXPp+d/rFW7svL9j3OWeTw9wzkHZc/slWtD+ARjH9uw=="
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{referenceCaptureContent as L}from"../../core/content-reference.js";import{assessToolCallCompleteness as oe,deduplicateGaps as ae}from"../../core/tool-call-audit.js";import{InvalidCodexUsageError as z,normalizeCodexUsage as de}from"../../core/usage.js";import{cleanupRawApiCapture as ue,loadRawApiCapture as ie}from"../../raw-capture/body-source.js";import{extractProviderResponseId as ce,extractRequestModel as pe,extractSystemPrompt as le}from"../../raw-capture/attribution.js";const fe=new Set(["rawResponse/completed","codex/rawResponse/completed"]),me=new Set(["thread/tokenUsage/updated","codex/thread/tokenUsage/updated"]),D=new Set(["item/completed","codex/item/completed"]),H=new Set(["item/started","codex/item/started"]),he=new Set(["rawResponseItem/completed","codex/rawResponseItem/completed"]),Ie=new Set(["error","codex/error"]),ve=new Set(["thread/compacted","codex/thread/compacted"]),V=new Set(["commandExecution","fileChange","mcpToolCall","dynamicToolCall","webSearch","imageView","sleep","imageGeneration"]),G=new Set(["collabAgentToolCall","subAgentActivity"]),ge=Object.freeze({inputOutput:!0,tools:!0,subagents:!0,thinking:!0,rawProviderBody:!1});function w(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return e}function m(e){return typeof e=="string"&&e.length>0?e:void 0}function A(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function M(e,t,n){return e[t]??e[n]}function _e(e){return["totalTokens","total_tokens","inputTokens","input_tokens","cachedInputTokens","cached_input_tokens","cacheWriteInputTokens","cache_write_input_tokens","outputTokens","output_tokens","reasoningOutputTokens","reasoning_output_tokens"].some(t=>Object.hasOwn(e,t))}function ye(e){const t=w(e);if(!(!t||!_e(t)))return{total_tokens:M(t,"totalTokens","total_tokens"),input_tokens:M(t,"inputTokens","input_tokens"),cached_input_tokens:M(t,"cachedInputTokens","cached_input_tokens"),cache_write_input_tokens:M(t,"cacheWriteInputTokens","cache_write_input_tokens"),output_tokens:M(t,"outputTokens","output_tokens"),reasoning_output_tokens:M(t,"reasoningOutputTokens","reasoning_output_tokens")}}function J(e){return[e.input.total,e.input.cacheRead??"unknown",e.input.cacheWrite??"unknown",e.output.total,e.output.reasoning??"unknown"].join(":")}function Q(e,t){return e.input.total!==t.input.total||e.output.total!==t.output.total?!1:[[e.input.cacheRead,t.input.cacheRead],[e.input.cacheWrite,t.input.cacheWrite],[e.output.reasoning,t.output.reasoning]].every(([r,s])=>r===null||s===null||r===s)}function R(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function O(e){const t=m(e);if(!(!t||Number.isNaN(Date.parse(t))))return t}function P(e){return e.options?.enabled===!0?e.options.capture:ge}function C(e){if(typeof e=="string")return e;try{const t=JSON.stringify(e);return t===void 0?"null":t}catch{return String(e)}}function S(e,t){const n=L(t);return e.push(t),n}function x(e,t){t&&(e.some(n=>n.contentId===t.contentId)||e.push(t))}function Y(e){const t=ye(e);return t?{...de(t),providerUsageRaw:e}:void 0}function we(e){return{providerTurnId:m(e.boundary.providerTurnId)??m(e.boundary.turnId)??e.turnId,providerThreadId:m(e.boundary.providerThreadId)??m(e.boundary.threadId)}}function b(e,t){const n=m(e.turnId??e.turn_id);if(n&&n!==t.providerTurnId)return!1;const r=m(e.threadId??e.thread_id);return!(t.providerThreadId&&r&&r!==t.providerThreadId)}function k(e,t,n,r){e.push({code:t,message:n,providerIds:r})}function X(e,t,n){try{const r=Y(e);if(!r){k(n,"codex_usage_missing",`${t.nativeEventType} did not contain a usable usage payload`);return}return{...t,usage:r,providerUsageRaw:e,usageKey:J(r),reconciledWithTokenSnapshot:!1}}catch(r){if(r instanceof z){k(n,"codex_usage_invalid",r.message,t.responseId?{responseId:t.responseId}:void 0);return}throw r}}function K(e){const t=w(e);if(!t)return{events:[]};const n=m(t.modelId);return{...n?{modelId:n}:{},events:Array.isArray(t.events)?t.events.filter(r=>{const s=w(r);return!!(s&&typeof s.method=="string"&&w(s.params))}):[],rolloutEntries:Array.isArray(t.rolloutEntries)?t.rolloutEntries:[],...w(t.rawApiCapture)&&Array.isArray(w(t.rawApiCapture)?.exchanges)?{rawApiCapture:t.rawApiCapture}:{}}}function Z(e){const t=e?.toLowerCase()??"";return t.includes("ndjson")?"text":t.includes("json")?"json":(t.includes("event-stream"),"text")}function j(e){return e.correlation.providerResponseId??(e.upstream.body.value===void 0?void 0:ce(e.upstream.body.value))}function qe(e){const t=e.downstream.method.toUpperCase();if(t!=="POST"&&t!=="WEBSOCKET")return!1;const n=e.downstream.path.toLowerCase().replace(/\/+$/,"");return n.endsWith("/responses")||n.endsWith("/responses/compact")||n.endsWith("/chat/completions")||n.endsWith("/completions")}function xe(e,t,n,r){const s=t.correlation.providerRequestId;return e.find(a=>!r.has(a.spanId)&&(n&&(a.provider.nativeIds.responseId===n||a.provider.nativeIds.requestId===n)||s&&(a.provider.nativeIds.requestId===s||a.provider.nativeIds.responseId===s)))}function Te(e,t){const n=new Map,r=new Set;for(const p of t){const d=xe(e,p,j(p),r);d&&(n.set(p.exchangeId,d),r.add(d.spanId))}const s=t.filter(p=>!n.has(p.exchangeId)),u=e.filter(p=>!r.has(p.spanId));if(s.length!==u.length)return n;s.sort((p,d)=>Date.parse(p.startedAt)-Date.parse(d.startedAt)),u.sort((p,d)=>p.sequence-d.sequence);const a=s.every((p,d)=>{const o=Date.parse(p.completedAt??p.startedAt),c=Date.parse(u[d].startedAt);return Number.isFinite(o)&&Number.isFinite(c)&&o<=c});return s.length>1&&!a||s.forEach((p,d)=>{n.set(p.exchangeId,u[d])}),n}function Ae(e,t,n,r,s){const u=t.completedAt??t.startedAt;return{spanId:`codex-raw-${R(`${e.traceId}|${t.exchangeId}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"llm_request",name:"codex provider request",sequence:n,status:t.status==="cancelled"?"cancelled":t.status==="failed"?"failed":"completed",startedAt:t.startedAt,endedAt:u,durationMs:Math.max(0,Date.parse(u)-Date.parse(t.startedAt)),...r?{modelId:r}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:"provider_raw_api_exchange",nativeIds:{requestId:t.correlation.providerRequestId??t.exchangeId,exchangeId:t.exchangeId,...s?{responseId:s}:{}}},provenance:{source:"provider_raw_body",accuracy:"runtime_exact"}}}function Se(e,t,n,r,s){if(!t)return;if(t.status==="unavailable"){k(s,"codex_raw_api_capture_unavailable",t.unavailableReason??"Codex raw API capture is unavailable");return}for(const i of t.errors)k(s,"codex_raw_api_capture_partial",i);const u=n.filter(i=>i.kind==="llm_request"),a=t.exchanges.filter(qe),p=Te(u,a),d=new Set([...p.values()].map(i=>i.spanId)),o=u.filter(i=>!d.has(i.spanId)).length,c=a.filter(i=>!p.has(i.exchangeId)).length;a.length>0&&o!==c&&k(s,"codex_raw_api_capture_partial",`Codex raw API exchanges and leaf usage requests do not align (${c} exchange(s), ${o} request(s) unmatched)`);let h=n.reduce((i,l)=>Math.max(i,l.sequence),0)+1;for(const i of a){const l=i.downstream.body.value,I=i.upstream.body.value,_=j(i),g=l?pe(l):void 0,q=p.get(i.exchangeId);!q&&o>0&&c>0&&k(s,"codex_raw_api_correlation_ambiguous",`Raw API exchange ${i.exchangeId} has no stable request identifier`,{exchangeId:i.exchangeId});const v=q??Ae(e,i,h++,g,_);n.includes(v)||n.push(v);const y=l===void 0?void 0:S(r,{role:"model_request",format:Z(i.downstream.body.contentType),value:l,sourcePath:i.downstream.body.sourcePath,captureLevel:"provider_exact"}),f=I===void 0?void 0:S(r,{role:"model_response",format:Z(i.upstream.body.contentType),value:I,sourcePath:i.upstream.body.sourcePath,captureLevel:"provider_exact"}),T=l?le(l):void 0;T&&S(r,{role:"system_prompt",format:"json",value:T,sourcePath:i.downstream.body.sourcePath,captureLevel:"provider_exact"}),x(v.inputRefs,y),x(v.outputRefs,f),g&&!v.modelId&&(v.modelId=g),v.provider.nativeIds.exchangeId=i.exchangeId,_&&(v.provider.nativeIds.responseId=_),v.provider.rawAttributes={...v.provider.rawAttributes,rawApiExchange:{method:i.downstream.method,path:i.downstream.path,query:i.downstream.query,requestHeaders:i.downstream.redactedHeaders,responseStatus:i.upstream.statusCode,responseHeaders:i.upstream.redactedHeaders,requestSha256:i.downstream.body.sha256,responseSha256:i.upstream.body.sha256,requestBytes:i.downstream.body.bytes,responseBytes:i.upstream.body.bytes}},(!y||!f||i.errors.length>0)&&k(s,"codex_raw_api_capture_partial",`Raw API exchange ${i.exchangeId} is incomplete`,{exchangeId:i.exchangeId})}}function Ce(e,t,n){const r=new Map;let s=0;for(const u of e){if(!fe.has(u.method)||!b(u.params,t))continue;const a=m(u.params.turnId??u.params.turn_id)??t.providerTurnId,p=m(u.params.threadId??u.params.thread_id)??t.providerThreadId,d=m(u.params.responseId??u.params.response_id),o=X(u.params.usage,{sequence:A(u.sequence)??s,observedAt:O(u.observedAt),providerTurnId:a,threadId:p,responseId:d,nativeEventType:u.method,source:"provider_raw_body"},n);if(s+=1,!o)continue;const c=d?`response:${d}`:`anonymous:${o.sequence}:${o.usageKey}`,h=r.get(c);if(h&&!Q(h.usage,o.usage)){k(n,"codex_response_usage_conflict",`Response ${d??c} reported conflicting usage`,d?{responseId:d}:void 0);continue}h||r.set(c,o)}return[...r.values()].sort((u,a)=>u.sequence-a.sequence)}function ee(e,t,n,r){const s=X(e,n,r);if(!s)return;let u;try{const a=Y(t);a&&(u=[n.threadId??"unknown-thread",n.providerTurnId,J(a)].join("|"))}catch(a){if(a instanceof z)k(r,"codex_total_snapshot_invalid",a.message);else throw a}return{...s,providerUsageRaw:{last:e,total:t},usage:{...s.usage,providerUsageRaw:{last:e,total:t}},snapshotKey:u}}function Re(e,t,n){const r=[];for(const s of e){if(!me.has(s.method)||!b(s.params,t))continue;const u=w(s.params.tokenUsage??s.params.token_usage);if(!u){k(n,"codex_usage_missing",`${s.method} did not contain tokenUsage`);continue}const a=m(s.params.turnId??s.params.turn_id)??t.providerTurnId,p=m(s.params.threadId??s.params.thread_id)??t.providerThreadId,d=ee(u.last??u.last_token_usage,u.total??u.total_token_usage,{sequence:A(s.sequence)??r.length,observedAt:O(s.observedAt),providerTurnId:a,threadId:p,responseId:m(s.params.responseId??s.params.response_id),nativeEventType:s.method,source:"provider_event"},n);d&&r.push(d)}return r}function ke(e,t,n,r){const s=[];return e.forEach((u,a)=>{const p=w(u),d=w(p?.payload);if(p?.type!=="event_msg"||d?.type!=="token_count")return;const o=w(d.info);if(!o)return;const c=ee(o.last_token_usage??o.lastTokenUsage,o.total_token_usage??o.totalTokenUsage,{sequence:A(p?.sequence)??n+a,observedAt:O(p?.timestamp),providerTurnId:t.providerTurnId,threadId:t.providerThreadId,nativeEventType:"rollout/event_msg/token_count",source:"provider_transcript"},r);c&&s.push(c)}),s}function Ee(e){const t=new Set;return e.filter(n=>n.snapshotKey?t.has(n.snapshotKey)?!1:(t.add(n.snapshotKey),!0):!0)}function be(e,t){const n=new Set(e),r=new Set(t);for(const s of t){const u=e.find(a=>!n.has(a)||s.responseId&&a.responseId&&s.responseId!==a.responseId?!1:a.providerTurnId===s.providerTurnId&&Q(a.usage,s.usage));u&&(u.reconciledWithTokenSnapshot=!0,u.snapshotKey=s.snapshotKey,u.threadId??=s.threadId,u.providerUsageRaw={rawResponse:u.providerUsageRaw,tokenUsage:s.providerUsageRaw},u.usage={...u.usage,providerUsageRaw:u.providerUsageRaw},n.delete(u),r.delete(s))}return[...e,...t.filter(s=>r.has(s))].sort((s,u)=>s.sequence-u.sequence)}function $e(e){if(e.responseId)return e.responseId;const t=e.snapshotKey??[e.threadId??"unknown-thread",e.providerTurnId,e.sequence,e.usageKey].join("|");return`codex-usage-${R(t)}`}function Me(e,t,n){const r=$e(t),s={requestId:r,turnId:t.providerTurnId};t.threadId&&(s.threadId=t.threadId),t.responseId&&(s.responseId=t.responseId),t.snapshotKey&&(s.usageSnapshotId=R(t.snapshotKey));const u=t.observedAt??e.startedAt;return{spanId:`codex-llm-${R(`${e.traceId}|${r}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"llm_request",name:"codex response",sequence:t.sequence,status:"completed",startedAt:u,endedAt:u,...n?{modelId:n}:{},inputRefs:[],outputRefs:[],usage:t.usage,provider:{provider:"codex",nativeEventType:t.nativeEventType,nativeIds:s,rawAttributes:{usageSource:t.source,reconciledWithTokenSnapshot:t.reconciledWithTokenSnapshot}},provenance:{source:t.source,accuracy:"provider_reported"}}}function W(e,t){const n=A(e.params.completedAtMs);if(n!==void 0){const r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}return O(e.observedAt)??t.endedAt}function N(e,t){const n=A(e.params.startedAtMs);if(n!==void 0){const r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}return O(e.observedAt)??t}function te(e){const t=m(e.status)?.toLowerCase();return t==="inprogress"||t==="in_progress"||t==="running"?"running":t==="failed"||t==="declined"||t==="error"||A(e.exitCode)!==void 0&&A(e.exitCode)!==0?"failed":t==="cancelled"||t==="canceled"?"cancelled":"completed"}function ne(e){const t=m(e.type)??"tool";if(t==="mcpToolCall"){const n=m(e.server),r=m(e.tool);return[n,r].filter(Boolean).join("/")||t}return m(e.tool)??t}function re(e){switch(m(e.type)){case"commandExecution":return typeof e.command=="string"?{format:"text",value:String(e.command)}:void 0;case"fileChange":return Object.hasOwn(e,"changes")?{format:"json",value:C(e.changes)}:void 0;case"mcpToolCall":case"dynamicToolCall":return Object.hasOwn(e,"arguments")?{format:"json",value:C(e.arguments)}:void 0;case"webSearch":return typeof e.query=="string"?{format:"text",value:String(e.query)}:void 0;default:return{format:"json",value:C(e)}}}function Oe(e){switch(m(e.type)){case"commandExecution":return typeof e.aggregatedOutput=="string"?{format:"text",value:e.aggregatedOutput}:e.status!==void 0||e.exitCode!==void 0?{format:"json",value:C({status:e.status,exitCode:e.exitCode})}:void 0;case"fileChange":return{format:"json",value:C({status:e.status})};case"mcpToolCall":return Object.hasOwn(e,"result")?{format:"json",value:C(e.result)}:Object.hasOwn(e,"error")?{format:"json",value:C(e.error)}:void 0;case"dynamicToolCall":return Object.hasOwn(e,"contentItems")?{format:"json",value:C(e.contentItems)}:void 0;default:return{format:"json",value:C(e)}}}function Pe(e,t,n,r,s){if(!P(e).tools)return[];const u=new Set,a=[],p=new Map;for(const d of t){if(!H.has(d.method)||!b(d.params,n))continue;const o=w(d.params.item),c=m(o?.id);c&&p.set(c,d)}for(const d of t){if(!D.has(d.method)||!b(d.params,n))continue;const o=w(d.params.item),c=m(o?.type);if(!o||!c||!V.has(c))continue;const h=m(o.id)??`sequence-${d.sequence}`;if(u.has(h))continue;u.add(h);const i=W(d,e),l=p.get(h),I=A(o.durationMs),_=Date.parse(i),g=l?N(l,i):I!==void 0&&Number.isFinite(_)?new Date(Math.max(0,_-I)).toISOString():i,q=Date.parse(i)-Date.parse(g),v=Number.isFinite(q)&&q>0?q:I,y=[...r].filter($=>$.sequence<=d.sequence).sort(($,U)=>U.sequence-$.sequence)[0],f=[...r].filter($=>$.sequence>d.sequence).sort(($,U)=>$.sequence-U.sequence)[0],T=y??f,E={spanId:`codex-tool-${R(`${e.traceId}|${h}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:T?.spanId??`codex:${e.turnId}:turn`,kind:"tool_call",name:ne(o),sequence:d.sequence,status:te(o),startedAt:g,endedAt:i,...v!==void 0?{durationMs:Math.max(0,v)}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:d.method,nativeIds:{toolCallId:h,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{itemType:c,auditEventSequence:d.sequence,startEventSequence:l?.sequence,...m(o.cwd)?{cwd:o.cwd}:{},...A(o.exitCode)!==void 0?{exitCode:o.exitCode}:{}}},provenance:{source:"provider_event",accuracy:"provider_reported"}},B=re(o);B&&x(E.inputRefs,S(s,{role:"tool_arguments",...B,captureLevel:"provider_exact"}));const F=Oe(o);F&&x(E.outputRefs,S(s,{role:"tool_result",...F,captureLevel:"provider_exact"})),a.push(E)}for(const[d,o]of p){if(u.has(d))continue;const c=w(o.params.item),h=m(c?.type);if(!c||!h||!V.has(h))continue;const i=N(o,e.startedAt),l=[...r].filter(g=>g.sequence<=o.sequence).sort((g,q)=>q.sequence-g.sequence)[0]??r[0],I={spanId:`codex-tool-${R(`${e.traceId}|${d}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:l?.spanId??`codex:${e.turnId}:turn`,kind:"tool_call",name:ne(c),sequence:o.sequence,status:"running",startedAt:i,endedAt:e.endedAt,durationMs:Math.max(0,Date.parse(e.endedAt)-Date.parse(i)),inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:o.method,nativeIds:{toolCallId:d,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{itemType:h,auditEventSequence:o.sequence,hasCompletion:!1}},provenance:{source:"provider_event",accuracy:"provider_reported"}},_=re(c);_&&x(I.inputRefs,S(s,{role:"tool_arguments",..._,captureLevel:"provider_exact"})),a.push(I)}return a}function De(e,t,n,r,s){if(!P(e).subagents)return[];const u=[],a=new Set,p=new Map;for(const d of t){if(!H.has(d.method)||!b(d.params,n))continue;const o=w(d.params.item),c=m(o?.id);c&&p.set(c,d)}for(const d of t){if(!D.has(d.method)||!b(d.params,n))continue;const o=w(d.params.item),c=m(o?.type);if(!o||!c||!G.has(c))continue;const h=m(o.id)??`sequence-${d.sequence}`;if(a.has(h))continue;a.add(h);const i=[...r].filter(f=>f.sequence<=d.sequence).sort((f,T)=>T.sequence-f.sequence)[0],l=W(d,e),I=p.get(h),_=I?N(I,l):l,g=Date.parse(l)-Date.parse(_),q={spanId:`codex-subagent-${R(`${e.traceId}|${h}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:i?.spanId??`codex:${e.turnId}:turn`,kind:"subagent",name:m(o.tool)??c,sequence:d.sequence,status:te(o),startedAt:_,endedAt:l,...Number.isFinite(g)?{durationMs:Math.max(0,g)}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:d.method,nativeIds:{subagentCallId:h,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...m(o.senderThreadId)?{senderThreadId:String(o.senderThreadId)}:{}},rawAttributes:{itemType:c,auditEventSequence:d.sequence,startEventSequence:I?.sequence,receiverThreadIds:o.receiverThreadIds,agentsStates:o.agentsStates,model:o.model,reasoningEffort:o.reasoningEffort}},provenance:{source:"provider_event",accuracy:"provider_reported"}},v=m(o.prompt);v&&x(q.inputRefs,S(s,{role:"subagent_prompt",format:"text",value:v,captureLevel:"provider_exact"}));const y=o.result??o.agentsStates??o.status;y!==void 0&&x(q.outputRefs,S(s,{role:"subagent_result",format:typeof y=="string"?"text":"json",value:C(y),captureLevel:"provider_exact"})),u.push(q)}for(const[d,o]of p){if(a.has(d))continue;const c=w(o.params.item),h=m(c?.type);if(!c||!h||!G.has(h))continue;const i=N(o,e.startedAt),l=[...r].filter(g=>g.sequence<=o.sequence).sort((g,q)=>q.sequence-g.sequence)[0]??r[0],I={spanId:`codex-subagent-${R(`${e.traceId}|${d}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:l?.spanId??`codex:${e.turnId}:turn`,kind:"subagent",name:m(c.tool)??h,sequence:o.sequence,status:"running",startedAt:i,endedAt:e.endedAt,durationMs:Math.max(0,Date.parse(e.endedAt)-Date.parse(i)),inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:o.method,nativeIds:{subagentCallId:d,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...m(c.senderThreadId)?{senderThreadId:String(c.senderThreadId)}:{}},rawAttributes:{itemType:h,auditEventSequence:o.sequence,hasCompletion:!1,receiverThreadIds:c.receiverThreadIds,model:c.model,reasoningEffort:c.reasoningEffort}},provenance:{source:"provider_event",accuracy:"provider_reported"}},_=m(c.prompt);_&&x(I.inputRefs,S(s,{role:"subagent_prompt",format:"text",value:_,captureLevel:"provider_exact"})),u.push(I)}return u}function Ne(e,t,n,r,s){const u=[];for(const a of t){if(!b(a.params,n))continue;if(Ie.has(a.method)&&a.params.willRetry===!0){const c=O(a.observedAt)??e.endedAt,h=w(a.params.error);u.push({spanId:`codex-retry-${R(`${e.traceId}|${a.sequence}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"retry",name:m(h?.message)??"Codex request retry",sequence:a.sequence,status:"completed",startedAt:c,endedAt:c,durationMs:0,inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:a.method,nativeIds:{turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{error:a.params.error,willRetry:!0}},provenance:{source:"provider_event",accuracy:"provider_reported"}});continue}const p=w(a.params.item),d=D.has(a.method)&&p?.type==="contextCompaction";if(!ve.has(a.method)&&!d)continue;const o=W(a,e);u.push({spanId:`codex-compaction-${R(`${e.traceId}|${a.sequence}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"compaction",name:"Codex context compaction",sequence:a.sequence,status:"completed",startedAt:o,endedAt:o,durationMs:0,inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:a.method,nativeIds:{turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...m(p?.id)?{itemId:String(p?.id)}:{}},rawAttributes:p?{item:p}:{params:a.params}},provenance:{source:"provider_event",accuracy:"provider_reported"}})}if(P(e).rawProviderBody)for(const a of t){if(!he.has(a.method)||!b(a.params,n))continue;const p=S(s,{role:"model_response",format:"json",value:C(a.params.item),captureLevel:"provider_exact"}),d=[...r].filter(o=>o.sequence>=a.sequence).sort((o,c)=>o.sequence-c.sequence)[0]??r.at(-1);d&&x(d.outputRefs,p)}return u}function se(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.content)&&e.content.map(n=>{if(typeof n=="string")return n;const r=w(n);return m(r?.text)??""}).join("")||void 0}function Ue(e,t,n,r,s,u){const a=[...r].sort((l,I)=>l.sequence-I.sequence),p=t.filter(l=>D.has(l.method)&&b(l.params,n)&&w(l.params.item)).sort((l,I)=>l.sequence-I.sequence),d=P(e);let o=Number.NEGATIVE_INFINITY,c=1;const h=new Set;for(const[l,I]of a.entries()){const _=I.sequence,g=p.filter(v=>v.sequence>o&&v.sequence<=_);if(d.inputOutput)for(const v of g){const y=w(v.params.item),f=m(y.type);if(f!=="userMessage"&&f!=="agentMessage")continue;const T=se(y);if(!T)continue;const E=m(y.phase)?.trim().toLowerCase();f==="agentMessage"&&E&&E!=="final_answer"||x(f==="userMessage"?I.inputRefs:I.outputRefs,S(u,{role:f==="userMessage"?"user_input":"assistant_text",format:"text",value:T,captureLevel:"provider_exact"}))}if(d.thinking)for(const v of g){const y=w(v.params.item),f=m(y.type),T=m(y.phase)?.trim().toLowerCase();if(f!=="reasoning"&&!(f==="agentMessage"&&T&&T!=="final_answer"))continue;const E=se(y);E&&x(I.outputRefs,S(u,{role:"thinking",format:"text",value:E,captureLevel:"provider_exact"}))}d.inputOutput&&l===0&&I.inputRefs.length===0&&e.input&&x(I.inputRefs,L(e.input)),d.inputOutput&&l===a.length-1&&I.outputRefs.length===0&&e.finalOutput&&x(I.outputRefs,L(e.finalOutput)),I.sequence=c++;const q=s.filter(v=>{const y=A(v.provider.rawAttributes?.auditEventSequence);return y!==void 0&&y>o&&y<=_}).sort((v,y)=>A(v.provider.rawAttributes?.auditEventSequence)-A(y.provider.rawAttributes?.auditEventSequence));for(const v of q)v.sequence=c++,h.add(v.spanId);o=_}const i=s.filter(l=>!h.has(l.spanId)).sort((l,I)=>l.sequence-I.sequence);for(const l of i)l.sequence=c++;for(const l of s){if(l.outputRefs.length===0)continue;const I=a.findIndex(g=>g.spanId===l.parentSpanId),_=I>=0?a[I+1]:void 0;if(_)for(const g of l.outputRefs)x(_.inputRefs,g)}}class ze{provider="codex";async collect(t){const n=K(t.boundary.codexEvidence),r=w(t.boundary.codexEvidence);return r?.rawApiCapture!==void 0&&(n.rawApiCapture=await ie(r.rawApiCapture)),n}async normalize(t,n){const r=K(n),s=we(t),u=[],a=Ce(r.events,s,u),p=Re(r.events,s,u),d=ke(r.rolloutEntries??[],s,r.events.length+1,u),o=Ee([...p,...d]),h=be(a,o).map(g=>Me(t,g,r.modelId)),i=[],l=Pe(t,r.events,s,h,i),I=De(t,r.events,s,h,i),_=Ne(t,r.events,s,h,i);return Ue(t,r.events,s,h,l,i),Se(t,r.rawApiCapture,h,i,u),{spans:[...h,...l,...I,..._],contents:i,anomalies:u}}async correlate(t,n){return n}validate(t,n){const r=n.spans.filter(f=>f.kind==="llm_request"&&f.usage),s=n.anomalies.some(f=>f.code==="codex_usage_invalid"||f.code==="codex_total_snapshot_invalid"||f.code==="codex_response_usage_conflict"),u=r.length>0&&!s&&r.every(f=>f.usage?.completeness==="complete"),a=P(t),p=!a.inputOutput||!!t.input,d=n.contents.some(f=>f.role==="assistant_text"||f.role==="model_response"||f.role==="final_response"),o=!a.inputOutput||!!t.finalOutput||d,c=oe(n.spans,a.tools),h=c.complete,i=n.spans.filter(f=>f.kind==="subagent"),l=!a.subagents||i.every(f=>f.status!=="running"),I=n.contents.filter(f=>f.role==="model_request"&&f.value!==void 0).length,_=n.contents.filter(f=>f.role==="model_response"&&f.value!==void 0).length,g=n.anomalies.some(f=>f.code==="codex_raw_api_capture_unavailable"||f.code==="codex_raw_api_capture_partial"||f.code==="codex_raw_api_correlation_ambiguous"),q=!a.rawProviderBody||I>0&&_>=I&&!g,v=[];return r.length===0&&v.push({category:"usage",reason:"provider_usage_missing",detail:"No Codex leaf request usage was found for the provider turn"}),r.length>0&&!u&&v.push({category:"provider_usage_cache_partition",reason:"provider_usage_missing",detail:"Codex reported request totals, but one or more cache or reasoning partitions were absent"}),a.subagents&&!l&&v.push({category:"subagents",reason:"correlation_failed",detail:"One or more Codex collaboration items did not reach a terminal state"}),a.rawProviderBody&&(I===0?v.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"Codex raw API capture did not produce a request body"}):q||v.push({category:"raw_provider_body",reason:"correlation_failed",detail:"One or more Codex raw API exchanges are incomplete"})),v.push(...c.gaps),{status:u&&p&&o&&h&&l&&q?"complete":"partial",inputComplete:p,outputComplete:o,toolCallsComplete:h,subagentsComplete:l,usageComplete:u,rawRequestsComplete:q,gaps:ae(v)}}async cleanup(t,n){const r=K(n).rawApiCapture;r&&await ue(r)}}export{ze as CodexAuditAdapter};
|
|
1
|
+
import{referenceCaptureContent as L}from"../../core/content-reference.js";import{assessToolCallCompleteness as oe,deduplicateGaps as ae}from"../../core/tool-call-audit.js";import{InvalidCodexUsageError as z,normalizeCodexUsage as de}from"../../core/usage.js";import{cleanupRawApiCapture as ue,loadRawApiCapture as ie}from"../../raw-capture/body-source.js";import{extractProviderResponseId as ce,extractRequestModel as pe,extractSystemPrompt as le}from"../../raw-capture/attribution.js";const fe=new Set(["rawResponse/completed","codex/rawResponse/completed"]),me=new Set(["thread/tokenUsage/updated","codex/thread/tokenUsage/updated"]),D=new Set(["item/completed","codex/item/completed"]),H=new Set(["item/started","codex/item/started"]),Ie=new Set(["rawResponseItem/completed","codex/rawResponseItem/completed"]),he=new Set(["error","codex/error"]),ve=new Set(["thread/compacted","codex/thread/compacted"]),V=new Set(["commandExecution","fileChange","mcpToolCall","dynamicToolCall","webSearch","imageView","sleep","imageGeneration"]),G=new Set(["collabAgentToolCall","subAgentActivity"]),ge=Object.freeze({inputOutput:!0,tools:!0,subagents:!0,thinking:!0,rawProviderBody:!1});function y(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return e}function h(e){return typeof e=="string"&&e.length>0?e:void 0}function A(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function O(e,t,n){return e[t]??e[n]}function _e(e){return["totalTokens","total_tokens","inputTokens","input_tokens","cachedInputTokens","cached_input_tokens","cacheWriteInputTokens","cache_write_input_tokens","outputTokens","output_tokens","reasoningOutputTokens","reasoning_output_tokens"].some(t=>Object.hasOwn(e,t))}function ye(e){const t=y(e);if(!(!t||!_e(t)))return{total_tokens:O(t,"totalTokens","total_tokens"),input_tokens:O(t,"inputTokens","input_tokens"),cached_input_tokens:O(t,"cachedInputTokens","cached_input_tokens"),cache_write_input_tokens:O(t,"cacheWriteInputTokens","cache_write_input_tokens"),output_tokens:O(t,"outputTokens","output_tokens"),reasoning_output_tokens:O(t,"reasoningOutputTokens","reasoning_output_tokens")}}function J(e){return[e.input.total,e.input.cacheRead??"unknown",e.input.cacheWrite??"unknown",e.output.total,e.output.reasoning??"unknown"].join(":")}function Q(e,t){return e.input.total!==t.input.total||e.output.total!==t.output.total?!1:[[e.input.cacheRead,t.input.cacheRead],[e.input.cacheWrite,t.input.cacheWrite],[e.output.reasoning,t.output.reasoning]].every(([r,s])=>r===null||s===null||r===s)}function C(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function b(e){const t=h(e);if(!(!t||Number.isNaN(Date.parse(t))))return t}function P(e){return e.options?.enabled===!0?e.options.capture:ge}function R(e){if(typeof e=="string")return e;try{const t=JSON.stringify(e);return t===void 0?"null":t}catch{return String(e)}}function S(e,t){const n=L(t);return e.push(t),n}function q(e,t){t&&(e.some(n=>n.contentId===t.contentId)||e.push(t))}function Y(e){const t=ye(e);return t?{...de(t),providerUsageRaw:e}:void 0}function we(e){return{providerTurnId:h(e.boundary.providerTurnId)??h(e.boundary.turnId)??e.turnId,providerThreadId:h(e.boundary.providerThreadId)??h(e.boundary.threadId)}}function $(e,t){const n=h(e.turnId??e.turn_id);if(n&&n!==t.providerTurnId)return!1;const r=h(e.threadId??e.thread_id);return!(t.providerThreadId&&r&&r!==t.providerThreadId)}function k(e,t,n,r){e.push({code:t,message:n,providerIds:r})}function X(e,t,n){try{const r=Y(e);if(!r){k(n,"codex_usage_missing",`${t.nativeEventType} did not contain a usable usage payload`);return}return{...t,usage:r,providerUsageRaw:e,usageKey:J(r),reconciledWithTokenSnapshot:!1}}catch(r){if(r instanceof z){k(n,"codex_usage_invalid",r.message,t.responseId?{responseId:t.responseId}:void 0);return}throw r}}function K(e){const t=y(e);if(!t)return{events:[]};const n=h(t.modelId);return{...n?{modelId:n}:{},events:Array.isArray(t.events)?t.events.filter(r=>{const s=y(r);return!!(s&&typeof s.method=="string"&&y(s.params))}):[],rolloutEntries:Array.isArray(t.rolloutEntries)?t.rolloutEntries:[],...y(t.rawApiCapture)&&Array.isArray(y(t.rawApiCapture)?.exchanges)?{rawApiCapture:t.rawApiCapture}:{}}}function Z(e){const t=e?.toLowerCase()??"";return t.includes("ndjson")?"text":t.includes("json")?"json":(t.includes("event-stream"),"text")}function j(e){return e.correlation.providerResponseId??(e.upstream.body.value===void 0?void 0:ce(e.upstream.body.value))}function xe(e){const t=e.downstream.method.toUpperCase();if(t!=="POST"&&t!=="WEBSOCKET")return!1;const n=e.downstream.path.toLowerCase().replace(/\/+$/,"");return n.endsWith("/responses")||n.endsWith("/responses/compact")||n.endsWith("/chat/completions")||n.endsWith("/completions")}function qe(e,t,n,r){const s=t.correlation.providerRequestId;return e.find(d=>!r.has(d.spanId)&&(n&&(d.provider.nativeIds.responseId===n||d.provider.nativeIds.requestId===n)||s&&(d.provider.nativeIds.requestId===s||d.provider.nativeIds.responseId===s)))}function Te(e,t){const n=new Map,r=new Set;for(const p of t){const a=qe(e,p,j(p),r);a&&(n.set(p.exchangeId,a),r.add(a.spanId))}const s=t.filter(p=>!n.has(p.exchangeId)),u=e.filter(p=>!r.has(p.spanId));if(s.length!==u.length)return n;s.sort((p,a)=>Date.parse(p.startedAt)-Date.parse(a.startedAt)),u.sort((p,a)=>p.sequence-a.sequence);const d=s.every((p,a)=>{const o=Date.parse(p.completedAt??p.startedAt),i=Date.parse(u[a].startedAt);return Number.isFinite(o)&&Number.isFinite(i)&&o<=i});return s.length>1&&!d||s.forEach((p,a)=>{n.set(p.exchangeId,u[a])}),n}function Ae(e,t,n,r,s){const u=t.completedAt??t.startedAt;return{spanId:`codex-raw-${C(`${e.traceId}|${t.exchangeId}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"llm_request",name:"codex provider request",sequence:n,status:t.status==="cancelled"?"cancelled":t.status==="failed"?"failed":"completed",startedAt:t.startedAt,endedAt:u,durationMs:Math.max(0,Date.parse(u)-Date.parse(t.startedAt)),...r?{modelId:r}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:"provider_raw_api_exchange",nativeIds:{requestId:t.correlation.providerRequestId??t.exchangeId,exchangeId:t.exchangeId,...s?{responseId:s}:{}}},provenance:{source:"provider_raw_body",accuracy:"runtime_exact"}}}function Se(e,t,n,r,s){if(!t)return;if(t.status==="unavailable"){k(s,"codex_raw_api_capture_unavailable",t.unavailableReason??"Codex raw API capture is unavailable");return}for(const c of t.errors)k(s,"codex_raw_api_capture_partial",c);const u=n.filter(c=>c.kind==="llm_request"),d=t.exchanges.filter(xe),p=Te(u,d),a=new Set([...p.values()].map(c=>c.spanId)),o=u.filter(c=>!a.has(c.spanId)).length,i=d.filter(c=>!p.has(c.exchangeId)).length;d.length>0&&o!==i&&k(s,"codex_raw_api_capture_partial",`Codex raw API exchanges and leaf usage requests do not align (${i} exchange(s), ${o} request(s) unmatched)`);let v=n.reduce((c,l)=>Math.max(c,l.sequence),0)+1;for(const c of d){const l=c.downstream.body.value,f=c.upstream.body.value,_=j(c),g=l?pe(l):void 0,x=p.get(c.exchangeId);!x&&o>0&&i>0&&k(s,"codex_raw_api_correlation_ambiguous",`Raw API exchange ${c.exchangeId} has no stable request identifier`,{exchangeId:c.exchangeId});const m=x??Ae(e,c,v++,g,_);n.includes(m)||n.push(m);const w=l===void 0?void 0:S(r,{role:"model_request",format:Z(c.downstream.body.contentType),value:l,sourcePath:c.downstream.body.sourcePath,captureLevel:"provider_exact"}),I=f===void 0?void 0:S(r,{role:"model_response",format:Z(c.upstream.body.contentType),value:f,sourcePath:c.upstream.body.sourcePath,captureLevel:"provider_exact"}),T=l?le(l):void 0;T&&S(r,{role:"system_prompt",format:"json",value:T,sourcePath:c.downstream.body.sourcePath,captureLevel:"provider_exact"}),q(m.inputRefs,w),q(m.outputRefs,I),g&&!m.modelId&&(m.modelId=g),m.provider.nativeIds.exchangeId=c.exchangeId,_&&(m.provider.nativeIds.responseId=_),m.provider.rawAttributes={...m.provider.rawAttributes,rawApiExchange:{method:c.downstream.method,path:c.downstream.path,query:c.downstream.query,requestHeaders:c.downstream.redactedHeaders,responseStatus:c.upstream.statusCode,responseHeaders:c.upstream.redactedHeaders,requestSha256:c.downstream.body.sha256,responseSha256:c.upstream.body.sha256,requestBytes:c.downstream.body.bytes,responseBytes:c.upstream.body.bytes}},(!w||!I||c.errors.length>0)&&k(s,"codex_raw_api_capture_partial",`Raw API exchange ${c.exchangeId} is incomplete`,{exchangeId:c.exchangeId})}}function Ce(e,t,n){const r=new Map;let s=0;for(const u of e){if(!fe.has(u.method)||!$(u.params,t))continue;const d=h(u.params.turnId??u.params.turn_id)??t.providerTurnId,p=h(u.params.threadId??u.params.thread_id)??t.providerThreadId,a=h(u.params.responseId??u.params.response_id),o=X(u.params.usage,{sequence:A(u.sequence)??s,observedAt:b(u.observedAt),providerTurnId:d,threadId:p,responseId:a,nativeEventType:u.method,source:"provider_raw_body"},n);if(s+=1,!o)continue;const i=a?`response:${a}`:`anonymous:${o.sequence}:${o.usageKey}`,v=r.get(i);if(v&&!Q(v.usage,o.usage)){k(n,"codex_response_usage_conflict",`Response ${a??i} reported conflicting usage`,a?{responseId:a}:void 0);continue}v||r.set(i,o)}return[...r.values()].sort((u,d)=>u.sequence-d.sequence)}function ee(e,t,n,r){const s=X(e,n,r);if(!s)return;let u;try{const d=Y(t);d&&(u=[n.threadId??"unknown-thread",n.providerTurnId,J(d)].join("|"))}catch(d){if(d instanceof z)k(r,"codex_total_snapshot_invalid",d.message);else throw d}return{...s,providerUsageRaw:{last:e,total:t},usage:{...s.usage,providerUsageRaw:{last:e,total:t}},snapshotKey:u}}function Re(e,t,n){const r=[];for(const s of e){if(!me.has(s.method)||!$(s.params,t))continue;const u=y(s.params.tokenUsage??s.params.token_usage);if(!u){k(n,"codex_usage_missing",`${s.method} did not contain tokenUsage`);continue}const d=h(s.params.turnId??s.params.turn_id)??t.providerTurnId,p=h(s.params.threadId??s.params.thread_id)??t.providerThreadId,a=ee(u.last??u.last_token_usage,u.total??u.total_token_usage,{sequence:A(s.sequence)??r.length,observedAt:b(s.observedAt),providerTurnId:d,threadId:p,responseId:h(s.params.responseId??s.params.response_id),nativeEventType:s.method,source:"provider_event"},n);a&&r.push(a)}return r}function ke(e,t,n,r){const s=[];return e.forEach((u,d)=>{const p=y(u),a=y(p?.payload);if(p?.type!=="event_msg"||a?.type!=="token_count")return;const o=y(a.info);if(!o)return;const i=ee(o.last_token_usage??o.lastTokenUsage,o.total_token_usage??o.totalTokenUsage,{sequence:A(p?.sequence)??n+d,observedAt:b(p?.timestamp),providerTurnId:t.providerTurnId,threadId:t.providerThreadId,nativeEventType:"rollout/event_msg/token_count",source:"provider_transcript"},r);i&&s.push(i)}),s}function Ee(e){const t=new Set;return e.filter(n=>n.snapshotKey?t.has(n.snapshotKey)?!1:(t.add(n.snapshotKey),!0):!0)}function $e(e,t){const n=new Set(e),r=new Set(t);for(const s of t){const u=e.find(d=>!n.has(d)||s.responseId&&d.responseId&&s.responseId!==d.responseId?!1:d.providerTurnId===s.providerTurnId&&Q(d.usage,s.usage));u&&(u.reconciledWithTokenSnapshot=!0,u.snapshotKey=s.snapshotKey,u.threadId??=s.threadId,u.providerUsageRaw={rawResponse:u.providerUsageRaw,tokenUsage:s.providerUsageRaw},u.usage={...u.usage,providerUsageRaw:u.providerUsageRaw},n.delete(u),r.delete(s))}return[...e,...t.filter(s=>r.has(s))].sort((s,u)=>s.sequence-u.sequence)}function Me(e){if(e.responseId)return e.responseId;const t=e.snapshotKey??[e.threadId??"unknown-thread",e.providerTurnId,e.sequence,e.usageKey].join("|");return`codex-usage-${C(t)}`}function Oe(e,t,n){const r=Me(t),s={requestId:r,turnId:t.providerTurnId};t.threadId&&(s.threadId=t.threadId),t.responseId&&(s.responseId=t.responseId),t.snapshotKey&&(s.usageSnapshotId=C(t.snapshotKey));const u=t.observedAt??e.startedAt;return{spanId:`codex-llm-${C(`${e.traceId}|${r}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"llm_request",name:"codex response",sequence:t.sequence,status:"completed",startedAt:u,endedAt:u,...n?{modelId:n}:{},inputRefs:[],outputRefs:[],usage:t.usage,provider:{provider:"codex",nativeEventType:t.nativeEventType,nativeIds:s,rawAttributes:{usageSource:t.source,reconciledWithTokenSnapshot:t.reconciledWithTokenSnapshot}},provenance:{source:t.source,accuracy:"provider_reported"}}}function W(e,t){const n=A(e.params.completedAtMs);if(n!==void 0){const r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}return b(e.observedAt)??t.endedAt}function N(e,t){const n=A(e.params.startedAtMs);if(n!==void 0){const r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}return b(e.observedAt)??t}function te(e){const t=h(e.status)?.toLowerCase();return t==="inprogress"||t==="in_progress"||t==="running"?"running":t==="failed"||t==="declined"||t==="error"||A(e.exitCode)!==void 0&&A(e.exitCode)!==0?"failed":t==="cancelled"||t==="canceled"?"cancelled":"completed"}function ne(e){const t=h(e.type)??"tool";if(t==="mcpToolCall"){const n=h(e.server),r=h(e.tool);return[n,r].filter(Boolean).join("/")||t}return h(e.tool)??t}function re(e){switch(h(e.type)){case"commandExecution":return typeof e.command=="string"?{format:"text",value:String(e.command)}:void 0;case"fileChange":return Object.hasOwn(e,"changes")?{format:"json",value:R(e.changes)}:void 0;case"mcpToolCall":case"dynamicToolCall":return Object.hasOwn(e,"arguments")?{format:"json",value:R(e.arguments)}:void 0;case"webSearch":return typeof e.query=="string"?{format:"text",value:String(e.query)}:void 0;default:return{format:"json",value:R(e)}}}function be(e){switch(h(e.type)){case"commandExecution":return typeof e.aggregatedOutput=="string"?{format:"text",value:e.aggregatedOutput}:e.status!==void 0||e.exitCode!==void 0?{format:"json",value:R({status:e.status,exitCode:e.exitCode})}:void 0;case"fileChange":return{format:"json",value:R({status:e.status})};case"mcpToolCall":return Object.hasOwn(e,"result")?{format:"json",value:R(e.result)}:Object.hasOwn(e,"error")?{format:"json",value:R(e.error)}:void 0;case"dynamicToolCall":return Object.hasOwn(e,"contentItems")?{format:"json",value:R(e.contentItems)}:void 0;default:return{format:"json",value:R(e)}}}function Pe(e,t,n,r,s){if(!P(e).tools)return[];const u=new Set,d=[],p=new Map;for(const a of t){if(!H.has(a.method)||!$(a.params,n))continue;const o=y(a.params.item),i=h(o?.id);i&&p.set(i,a)}for(const a of t){if(!D.has(a.method)||!$(a.params,n))continue;const o=y(a.params.item),i=h(o?.type);if(!o||!i||!V.has(i))continue;const v=h(o.id)??`sequence-${a.sequence}`;if(u.has(v))continue;u.add(v);const c=W(a,e),l=p.get(v),f=A(o.durationMs),_=Date.parse(c),g=l?N(l,c):f!==void 0&&Number.isFinite(_)?new Date(Math.max(0,_-f)).toISOString():c,x=Date.parse(c)-Date.parse(g),m=Number.isFinite(x)&&x>0?x:f,w=[...r].filter(M=>M.sequence<=a.sequence).sort((M,U)=>U.sequence-M.sequence)[0],I=[...r].filter(M=>M.sequence>a.sequence).sort((M,U)=>M.sequence-U.sequence)[0],T=w??I,E={spanId:`codex-tool-${C(`${e.traceId}|${v}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:T?.spanId??`codex:${e.turnId}:turn`,kind:"tool_call",name:ne(o),sequence:a.sequence,status:te(o),startedAt:g,endedAt:c,...m!==void 0?{durationMs:Math.max(0,m)}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:a.method,nativeIds:{toolCallId:v,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{itemType:i,auditEventSequence:a.sequence,startEventSequence:l?.sequence,...h(o.cwd)?{cwd:o.cwd}:{},...A(o.exitCode)!==void 0?{exitCode:o.exitCode}:{}}},provenance:{source:"provider_event",accuracy:"provider_reported"}},B=re(o);B&&q(E.inputRefs,S(s,{role:"tool_arguments",...B,captureLevel:"provider_exact"}));const F=be(o);F&&q(E.outputRefs,S(s,{role:"tool_result",...F,captureLevel:"provider_exact"})),d.push(E)}for(const[a,o]of p){if(u.has(a))continue;const i=y(o.params.item),v=h(i?.type);if(!i||!v||!V.has(v))continue;const c=N(o,e.startedAt),l=[...r].filter(g=>g.sequence<=o.sequence).sort((g,x)=>x.sequence-g.sequence)[0]??r[0],f={spanId:`codex-tool-${C(`${e.traceId}|${a}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:l?.spanId??`codex:${e.turnId}:turn`,kind:"tool_call",name:ne(i),sequence:o.sequence,status:"running",startedAt:c,endedAt:e.endedAt,durationMs:Math.max(0,Date.parse(e.endedAt)-Date.parse(c)),inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:o.method,nativeIds:{toolCallId:a,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{itemType:v,auditEventSequence:o.sequence,hasCompletion:!1}},provenance:{source:"provider_event",accuracy:"provider_reported"}},_=re(i);_&&q(f.inputRefs,S(s,{role:"tool_arguments",..._,captureLevel:"provider_exact"})),d.push(f)}return d}function De(e,t,n,r,s){if(!P(e).subagents)return[];const u=[],d=new Set,p=new Map;for(const a of t){if(!H.has(a.method)||!$(a.params,n))continue;const o=y(a.params.item),i=h(o?.id);i&&p.set(i,a)}for(const a of t){if(!D.has(a.method)||!$(a.params,n))continue;const o=y(a.params.item),i=h(o?.type);if(!o||!i||!G.has(i))continue;const v=h(o.id)??`sequence-${a.sequence}`;if(d.has(v))continue;d.add(v);const c=[...r].filter(I=>I.sequence<=a.sequence).sort((I,T)=>T.sequence-I.sequence)[0],l=W(a,e),f=p.get(v),_=f?N(f,l):l,g=Date.parse(l)-Date.parse(_),x={spanId:`codex-subagent-${C(`${e.traceId}|${v}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:c?.spanId??`codex:${e.turnId}:turn`,kind:"subagent",name:h(o.tool)??i,sequence:a.sequence,status:te(o),startedAt:_,endedAt:l,...Number.isFinite(g)?{durationMs:Math.max(0,g)}:{},inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:a.method,nativeIds:{subagentCallId:v,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...h(o.senderThreadId)?{senderThreadId:String(o.senderThreadId)}:{}},rawAttributes:{itemType:i,auditEventSequence:a.sequence,startEventSequence:f?.sequence,receiverThreadIds:o.receiverThreadIds,agentsStates:o.agentsStates,model:o.model,reasoningEffort:o.reasoningEffort}},provenance:{source:"provider_event",accuracy:"provider_reported"}},m=h(o.prompt);m&&q(x.inputRefs,S(s,{role:"subagent_prompt",format:"text",value:m,captureLevel:"provider_exact"}));const w=o.result??o.agentsStates??o.status;w!==void 0&&q(x.outputRefs,S(s,{role:"subagent_result",format:typeof w=="string"?"text":"json",value:R(w),captureLevel:"provider_exact"})),u.push(x)}for(const[a,o]of p){if(d.has(a))continue;const i=y(o.params.item),v=h(i?.type);if(!i||!v||!G.has(v))continue;const c=N(o,e.startedAt),l=[...r].filter(g=>g.sequence<=o.sequence).sort((g,x)=>x.sequence-g.sequence)[0]??r[0],f={spanId:`codex-subagent-${C(`${e.traceId}|${a}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:l?.spanId??`codex:${e.turnId}:turn`,kind:"subagent",name:h(i.tool)??v,sequence:o.sequence,status:"running",startedAt:c,endedAt:e.endedAt,durationMs:Math.max(0,Date.parse(e.endedAt)-Date.parse(c)),inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:o.method,nativeIds:{subagentCallId:a,turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...h(i.senderThreadId)?{senderThreadId:String(i.senderThreadId)}:{}},rawAttributes:{itemType:v,auditEventSequence:o.sequence,hasCompletion:!1,receiverThreadIds:i.receiverThreadIds,model:i.model,reasoningEffort:i.reasoningEffort}},provenance:{source:"provider_event",accuracy:"provider_reported"}},_=h(i.prompt);_&&q(f.inputRefs,S(s,{role:"subagent_prompt",format:"text",value:_,captureLevel:"provider_exact"})),u.push(f)}return u}function Ne(e,t,n,r,s){const u=[];for(const d of t){if(!$(d.params,n))continue;if(he.has(d.method)&&d.params.willRetry===!0){const i=b(d.observedAt)??e.endedAt,v=y(d.params.error);u.push({spanId:`codex-retry-${C(`${e.traceId}|${d.sequence}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"retry",name:h(v?.message)??"Codex request retry",sequence:d.sequence,status:"completed",startedAt:i,endedAt:i,durationMs:0,inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:d.method,nativeIds:{turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{}},rawAttributes:{error:d.params.error,willRetry:!0}},provenance:{source:"provider_event",accuracy:"provider_reported"}});continue}const p=y(d.params.item),a=D.has(d.method)&&p?.type==="contextCompaction";if(!ve.has(d.method)&&!a)continue;const o=W(d,e);u.push({spanId:`codex-compaction-${C(`${e.traceId}|${d.sequence}`)}`,traceId:e.traceId,turnId:e.turnId,sessionId:e.sessionId,parentSpanId:`codex:${e.turnId}:turn`,kind:"compaction",name:"Codex context compaction",sequence:d.sequence,status:"completed",startedAt:o,endedAt:o,durationMs:0,inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:d.method,nativeIds:{turnId:n.providerTurnId,...n.providerThreadId?{threadId:n.providerThreadId}:{},...h(p?.id)?{itemId:String(p?.id)}:{}},rawAttributes:p?{item:p}:{params:d.params}},provenance:{source:"provider_event",accuracy:"provider_reported"}})}if(P(e).rawProviderBody)for(const d of t){if(!Ie.has(d.method)||!$(d.params,n))continue;const p=S(s,{role:"model_response",format:"json",value:R(d.params.item),captureLevel:"provider_exact"}),a=[...r].filter(o=>o.sequence>=d.sequence).sort((o,i)=>o.sequence-i.sequence)[0]??r.at(-1);a&&q(a.outputRefs,p)}return u}function se(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.content)&&e.content.map(n=>{if(typeof n=="string")return n;const r=y(n);return h(r?.text)??""}).join("")||void 0}function Ue(e,t,n,r,s,u){const d=[...r].sort((l,f)=>l.sequence-f.sequence),p=t.filter(l=>D.has(l.method)&&$(l.params,n)&&y(l.params.item)).sort((l,f)=>l.sequence-f.sequence),a=P(e);let o=Number.NEGATIVE_INFINITY,i=1;const v=new Set;for(const[l,f]of d.entries()){const _=f.sequence,g=p.filter(m=>m.sequence>o&&m.sequence<=_);if(a.inputOutput)for(const m of g){const w=y(m.params.item),I=h(w.type);if(I!=="userMessage"&&I!=="agentMessage")continue;const T=se(w);if(!T)continue;const E=h(w.phase)?.trim().toLowerCase();I==="agentMessage"&&E&&E!=="final_answer"||q(I==="userMessage"?f.inputRefs:f.outputRefs,S(u,{role:I==="userMessage"?"user_input":"assistant_text",format:"text",value:T,captureLevel:"provider_exact"}))}if(a.thinking)for(const m of g){const w=y(m.params.item),I=h(w.type),T=h(w.phase)?.trim().toLowerCase();if(I!=="reasoning"&&!(I==="agentMessage"&&T&&T!=="final_answer"))continue;const E=se(w);E&&q(f.outputRefs,S(u,{role:"thinking",format:"text",value:E,captureLevel:"provider_exact"}))}a.inputOutput&&l===0&&f.inputRefs.length===0&&e.input&&q(f.inputRefs,L(e.input)),a.inputOutput&&l===d.length-1&&f.outputRefs.length===0&&e.finalOutput&&q(f.outputRefs,L(e.finalOutput)),f.sequence=i++;const x=s.filter(m=>{const w=A(m.provider.rawAttributes?.auditEventSequence);return w!==void 0&&w>o&&w<=_}).sort((m,w)=>A(m.provider.rawAttributes?.auditEventSequence)-A(w.provider.rawAttributes?.auditEventSequence));for(const m of x)m.sequence=i++,v.add(m.spanId);o=_}const c=s.filter(l=>!v.has(l.spanId)).sort((l,f)=>l.sequence-f.sequence);for(const l of c)l.sequence=i++;for(const l of s){if(l.outputRefs.length===0)continue;const f=d.findIndex(g=>g.spanId===l.parentSpanId),_=f>=0?d[f+1]:void 0;if(_)for(const g of l.outputRefs)q(_.inputRefs,g)}}class ze{provider="codex";async collect(t){const n=K(t.boundary.codexEvidence),r=y(t.boundary.codexEvidence);return r?.rawApiCapture!==void 0&&(n.rawApiCapture=await ie(r.rawApiCapture)),n}async normalize(t,n){const r=K(n),s=we(t),u=y(t.boundary.sharedTurnOwner);if(h(u?.eventId))return{spans:[{spanId:`codex-input-${C(`${t.traceId}|${t.turnId}`)}`,traceId:t.traceId,turnId:t.turnId,sessionId:t.sessionId,parentSpanId:`codex:${t.turnId}:turn`,kind:"delivery",name:"Codex active input",sequence:1,status:t.outcome,startedAt:t.startedAt,endedAt:t.endedAt,inputRefs:[],outputRefs:[],provider:{provider:"codex",nativeEventType:"turn/steer",nativeIds:{turnId:s.providerTurnId,...s.providerThreadId?{threadId:s.providerThreadId}:{}},rawAttributes:{sharedTurnOwner:u,accepted:r.events.some(m=>m.method==="turn/steer/accepted"),nativeTerminalObserved:r.events.some(m=>m.method==="turn/completed"||m.method==="codex/turn/completed")}},provenance:{source:"connector",accuracy:"runtime_exact"}}],contents:[],anomalies:[]};const p=[],a=Ce(r.events,s,p),o=Re(r.events,s,p),i=ke(r.rolloutEntries??[],s,r.events.length+1,p),v=Ee([...o,...i]),l=$e(a,v).map(m=>Oe(t,m,r.modelId)),f=[],_=Pe(t,r.events,s,l,f),g=De(t,r.events,s,l,f),x=Ne(t,r.events,s,l,f);return Ue(t,r.events,s,l,_,f),Se(t,r.rawApiCapture,l,f,p),{spans:[...l,..._,...g,...x],contents:f,anomalies:p}}async correlate(t,n){return n}validate(t,n){const r=n.spans.filter(I=>I.kind==="llm_request"&&I.usage),s=n.anomalies.some(I=>I.code==="codex_usage_invalid"||I.code==="codex_total_snapshot_invalid"||I.code==="codex_response_usage_conflict"),u=r.length>0&&!s&&r.every(I=>I.usage?.completeness==="complete"),d=P(t),p=!d.inputOutput||!!t.input,a=n.contents.some(I=>I.role==="assistant_text"||I.role==="model_response"||I.role==="final_response"),o=!d.inputOutput||!!t.finalOutput||a,i=oe(n.spans,d.tools),v=i.complete,c=n.spans.filter(I=>I.kind==="subagent"),l=!d.subagents||c.every(I=>I.status!=="running"),f=n.contents.filter(I=>I.role==="model_request"&&I.value!==void 0).length,_=n.contents.filter(I=>I.role==="model_response"&&I.value!==void 0).length,g=n.anomalies.some(I=>I.code==="codex_raw_api_capture_unavailable"||I.code==="codex_raw_api_capture_partial"||I.code==="codex_raw_api_correlation_ambiguous"),x=!d.rawProviderBody||f>0&&_>=f&&!g,m=[];return r.length===0&&m.push({category:"usage",reason:"provider_usage_missing",detail:"No Codex leaf request usage was found for the provider turn"}),r.length>0&&!u&&m.push({category:"provider_usage_cache_partition",reason:"provider_usage_missing",detail:"Codex reported request totals, but one or more cache or reasoning partitions were absent"}),d.subagents&&!l&&m.push({category:"subagents",reason:"correlation_failed",detail:"One or more Codex collaboration items did not reach a terminal state"}),d.rawProviderBody&&(f===0?m.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"Codex raw API capture did not produce a request body"}):x||m.push({category:"raw_provider_body",reason:"correlation_failed",detail:"One or more Codex raw API exchanges are incomplete"})),m.push(...i.gaps),{status:u&&p&&o&&v&&l&&x?"complete":"partial",inputComplete:p,outputComplete:o,toolCallsComplete:v,subagentsComplete:l,usageComplete:u,rawRequestsComplete:x,gaps:ae(m)}}async cleanup(t,n){const r=K(n).rawApiCapture;r&&await ue(r)}}export{ze as CodexAuditAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as i}from"../core/log/index.js";import{RespawnManager as f}from"./respawn-manager.js";import{EventQueue as v}from"./event-queue.js";import{formatWaitDuration as d}from"../core/upgrade/idle-wait.js";const p=6e4;async function h(u){if(!u.startPromise)return;let e;try{await Promise.race([u.startPromise,new Promise((t,s)=>{e=setTimeout(()=>s(new Error(`adapter start timeout (${p}ms) session=${u.sessionId}`)),p)})])}finally{e&&clearTimeout(e)}}const g=12e4,S=5;class m extends Error{constructor(e){super(`adapter pool full (maxSize=${e})`),this.name="PoolFullError"}}const A=6e4,E=2*6e4,w=10*6e4;class b{slots=new Map;config;factory;sendAck;onEventState=null;onQueueComposing=null;onInternalError=null;onEventStarted=null;onEventDone=null;onSessionActivity=null;stopped=!1;startupEvents=new Map;sweepTimer=null;pendingRemovals=new Map;constructor(e,t,s){this.config=e,this.factory=t,this.sendAck=s}setEventStateHandler(e){this.onEventState=e}setQueueComposingHandler(e){this.onQueueComposing=e}setInternalErrorHandler(e){this.onInternalError=e}setEventStartedHandler(e){this.onEventStarted=e}setEventDoneHandler(e){this.onEventDone=e}setSessionActivityHandler(e){this.onSessionActivity=e}async deliverInboundEvent(e){return this.deliverInboundEventInternal(e)}async deliverInboundEventInternal(e,t){if(this.stopped)throw new Error("adapter pool stopped");if(t&&!this.isCurrentStartupTicket(e.event_id,t))return;const s=e.session_id,n=this.slots.get(s);if(n){if(n.stopping)return await this.pendingRemovals.get(s)?.catch(()=>{}),this.deliverInboundEventInternal(e,t);if(n.startPromise){await this.submitAfterStartup(n,e,t);return}if(t){if(!this.retireStartupTicket(e.event_id,t,"submitted"))return}else this.sendAck(e.event_id,e.session_id);n.lastActivityAt=Date.now(),n.state==="stopped"&&i.info("adapter-pool",`Holding event ${e.event_id} in paused queue for restarting slot ${s}`),this.submitToSlotQueue(n,e);return}if(this.slots.size>=this.config.maxPoolSize&&!this.evictDeadSlot()&&!this.evictIdleSlot())throw new m(this.config.maxPoolSize);const r=this.createSlot(s);await this.submitAfterStartup(r,e,t)}async submitAfterStartup(e,t,s){const n=s??{event:t,state:"pending"};if(s){if(!this.isCurrentStartupTicket(t.event_id,n))return}else this.sendAck(t.event_id,t.session_id),this.startupEvents.set(t.event_id,n);try{await e.startPromise}catch(r){if(!this.retireStartupTicket(t.event_id,n,"failed"))return;throw r}if(this.isCurrentStartupTicket(t.event_id,n)&&!this.stopped){if(this.slots.get(e.sessionId)!==e||e.stopping){if(await this.pendingRemovals.get(e.sessionId)?.catch(()=>{}),!this.isCurrentStartupTicket(t.event_id,n)||this.stopped)return;const r=this.slots.get(e.sessionId);if(r&&!r.stopping){await this.submitAfterStartup(r,t,n);return}try{await this.deliverInboundEventInternal(t,n)}catch(a){if(this.stopped||!this.retireStartupTicket(t.event_id,n,"failed"))return;throw a}return}this.retireStartupTicket(t.event_id,n,"submitted"),e.lastActivityAt=Date.now(),this.submitToSlotQueue(e,t)}}isCurrentStartupTicket(e,t){return t.state==="pending"&&this.startupEvents.get(e)===t}retireStartupTicket(e,t,s){return this.isCurrentStartupTicket(e,t)?(t.state=s,this.startupEvents.delete(e),!0):!1}submitToSlotQueue(e,t){e.eventQueue.submit(t)==="rejected"&&i.info("adapter-pool",`Event ${t.event_id} rejected by EventQueue (queue full)`)}eventComplete(e,t){const s=this.startupEvents.get(e);if(s?.event.session_id===t)return this.retireStartupTicket(e,s,"terminal");const n=this.slots.get(t);if(!n)return i.error("adapter-pool",`Cannot complete event ${e}: session slot not found (${t})`),!1;const r=n.eventQueue.complete(e);return r||i.error("adapter-pool",`Cannot complete event ${e}: not running in session ${t}`),r}cleanupEvent(e,t){const s=this.startupEvents.get(e);if(s)return this.retireStartupTicket(e,s,"terminal");const n=t?[this.slots.get(t)].filter(r=>!!r):[...this.slots.values()];for(const r of n)if(r.eventQueue.complete(e)||r.eventQueue.removeQueued(e))return!0;return!0}getEventSessionId(e){const t=this.startupEvents.get(e);if(t)return t.event.session_id;for(const s of this.slots.values()){const n=s.eventQueue.snapshot(s.sessionId);if(n.running.includes(e)||n.queued.some(r=>r.event_id===e))return s.sessionId}}cancelEvent(e,t){if(this.cancelStartupEvent(e,t))return!0;const s=this.slots.get(t);return s?s.eventQueue.cancel(e):!1}cancelStartupEvent(e,t){const s=this.startupEvents.get(e);if(s&&!(t&&s.event.session_id!==t)&&this.retireStartupTicket(e,s,"canceled"))return s.event}removeQueuedEvent(e,t){const s=this.slots.get(e);return s?s.eventQueue.removeQueued(t):!1}clearQueue(e){const t=this.slots.get(e);return t?t.eventQueue.clear(e):[]}reorderQueue(e,t){const s=this.slots.get(e);return s?s.eventQueue.reorder(e,t):[]}holdEvent(e,t,s,n,r){const a=this.slots.get(e);return a?s?a.eventQueue.hold(t,n,r):a.eventQueue.release(t):"not_found"}editQueuedEvent(e,t,s){const n=this.slots.get(e);return n?n.eventQueue.editQueued(t,s):"not_found"}pauseAllQueues(e){for(const t of this.slots.values())t.eventQueue.pause(e)}drainAllQueuedEvents(){const e=[...this.startupEvents.entries()],t=e.map(([,s])=>s.event);for(const[s,n]of e)this.retireStartupTicket(s,n,"drained");this.startupEvents.clear();for(const s of this.slots.values())t.push(...s.eventQueue.drainQueuedForSession(s.sessionId));return t}drainQueuedForSession(e){if(!this.config.eventQueue)return[];const t=this.slots.get(e);return t?t.eventQueue.drainQueuedForSession(e):[]}getQueueSnapshot(e){if(!this.config.eventQueue)return null;const t=this.slots.get(e);return t?t.eventQueue.snapshot(e):null}deliverStopEvent(e,t){if(t){const s=this.slots.get(t);i.info("adapter-pool",`[stop-trace] pool.deliverStopEvent session=${t} event=${e} slotExists=${!!s} -> adapter.deliverStopEvent`),s?.adapter.deliverStopEvent(e,t);return}i.info("adapter-pool",`[stop-trace] pool.deliverStopEvent (broadcast, no session) event=${e} slots=${this.slots.size}`);for(const s of this.slots.values())s.adapter.deliverStopEvent(e)}collectActiveEventIds(){const e=[];for(const t of this.slots.values()){const s=t.adapter.getActiveEventIds;typeof s=="function"&&e.push(...s.call(t.adapter))}return e}clearActiveEventsForShutdown(){for(const e of this.slots.values()){const t=e.adapter.clearActiveEventForShutdown;typeof t=="function"&&t.call(e.adapter)}}async deliverLocalAction(e,t){const s=String((e.params??{}).session_id??"");let n=s?this.slots.get(s):void 0;if(n?.stopping&&(await this.pendingRemovals.get(s)?.catch(()=>{}),n=this.slots.get(s)),!n&&s&&t?.autoCreateSlot&&!this.stopped&&(this.slots.size>=this.config.maxPoolSize&&(this.evictDeadSlot()||this.evictIdleSlotSync()),this.slots.size<this.config.maxPoolSize)){i.info("adapter-pool",`Auto-creating slot for session ${s} (local_action trigger)`);const o=this.createSlot(s);try{await o.startPromise,n=o}catch(c){i.error("adapter-pool",`Failed to auto-create slot for ${s}: ${c}`)}}return n?.adapter?.handleLocalAction?(n.lastActivityAt=Date.now(),n.adapter.handleLocalAction(e)):s?{handled:!1,kind:""}:(await Promise.allSettled([...this.slots.values()].filter(o=>!o.stopping).map(o=>o.adapter.handleLocalAction?.(e)??Promise.resolve({handled:!1,kind:""})))).find(o=>o.status==="fulfilled"&&o.value.handled)?.value??{handled:!1,kind:""}}async waitForSlotRemoval(e){await this.pendingRemovals.get(e)?.catch(()=>{})}async getOrCreateSlot(e){let t=this.slots.get(e);if(t?.stopping&&(await this.pendingRemovals.get(e)?.catch(()=>{}),t=this.slots.get(e)),t)return await h(t),t;if(this.stopped)return;const s=this.createSlot(e);return await h(s),s}getSlot(e){return this.slots.get(e)}getAllSlots(){return[...this.slots.values()]}async removeSlot(e){const t=this.slots.get(e);if(!t){await this.pendingRemovals.get(e)?.catch(()=>{});return}if(t.stopping){await this.pendingRemovals.get(e)?.catch(()=>{});return}t.stopping=!0;const s=this.doRemoveSlot(t);this.pendingRemovals.set(e,s);try{await s}finally{this.pendingRemovals.get(e)===s&&this.pendingRemovals.delete(e)}}async doRemoveSlot(e){const t=e.sessionId;this.onSessionActivity?.(t,!1),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachSlotEventListenersExceptDone(e),await e.adapter.stop().catch(()=>{}),e.adapter.removeAllListeners("eventDone"),this.slots.delete(t)}async stop(){this.stopped=!0,this.stopIdleSweep(),await Promise.allSettled([...this.pendingRemovals.values()]);const e=[...this.slots.values()];this.slots.clear(),await Promise.allSettled(e.map(async t=>{t.eventQueue.destroy(),t.respawn.stopAll(),this.detachAllSlotEventListeners(t),await t.adapter.stop().catch(()=>{})}))}startIdleSweep(){this.stopIdleSweep(),this.sweepTimer=setInterval(()=>this.sweepIdle(),A)}stopIdleSweep(){this.sweepTimer&&(clearInterval(this.sweepTimer),this.sweepTimer=null)}sweepIdle(){const e=Date.now();for(const[t,s]of this.slots){if(s.stopping)continue;if(s.state==="stopped"&&s.respawn.exhausted){i.info("adapter-pool",`Removing dead slot for session ${t} (sweep)`),this.removeSlot(t).catch(()=>{});continue}if(s.state!=="ready")continue;if(s.eventQueue.runningCount>0||s.eventQueue.queuedCount>0){s.adapterBusySince=null,s.lastActivityAt=e;continue}const n=s.adapter.getStatus();if(s.adapterBusySince=n.busy?s.adapterBusySince??e:null,n.busy||n.backgroundBusy){s.lastActivityAt=e;continue}e-s.lastActivityAt<=this.config.idleTimeoutMs||(s.adapter.hasBackgroundWork?s.adapter.hasBackgroundWork().then(r=>{r?(i.info("adapter-pool",`Deferred eviction for session ${t}: background grandchild processes detected`),s.lastActivityAt=Date.now()):this.evictAfterProbe(t,s,"probe idle")}).catch(()=>{this.evictAfterProbe(t,s,"probe failed")}):(i.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(r=>{i.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})))}}evictAfterProbe(e,t,s){if(this.slots.get(e)!==t||t.stopping)return;if(t.eventQueue.runningCount>0||t.eventQueue.queuedCount>0){t.lastActivityAt=Date.now();return}const n=t.adapter.getStatus();if(n.busy||n.backgroundBusy){t.lastActivityAt=Date.now();return}Date.now()-t.lastActivityAt<=this.config.idleTimeoutMs||(i.info("adapter-pool",`Evicting idle slot for session ${e} (${s})`),this.removeSlot(e).catch(r=>{i.error("adapter-pool",`Failed to evict slot ${e}: ${r}`)}))}evictDeadSlot(){for(const[e,t]of this.slots)if(t.state==="stopped"&&t.respawn.exhausted)return i.info("adapter-pool",`Removing dead slot for session ${e} (exhausted respawn)`),this.removeSlot(e).catch(()=>{}),!0;return!1}evictIdleSlot(){let e=null;for(const t of this.slots.values()){if(t.stopping||t.state!=="ready"||t.eventQueue.runningCount>0||t.eventQueue.queuedCount>0)continue;const s=t.adapter.getStatus();s.busy||s.backgroundBusy||(!e||t.lastActivityAt<e.lastActivityAt)&&(e=t)}return e?(i.info("adapter-pool",`Evicting idle slot for session ${e.sessionId} (pool full)`),this.removeSlot(e.sessionId).catch(()=>{}),!0):!1}evictIdleSlotSync(){let e=null,t="";for(const[s,n]of this.slots){if(n.stopping||n.state!=="ready"||n.eventQueue.runningCount>0||n.eventQueue.queuedCount>0)continue;const r=n.adapter.getStatus();r.busy||r.backgroundBusy||(!e||n.lastActivityAt<e.lastActivityAt)&&(e=n,t=s)}return!e||!t?!1:(i.info("adapter-pool",`Evicting idle slot for session ${t} (pool full, sync)`),this.slots.delete(t),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachAllSlotEventListeners(e),e.adapter.stop().catch(()=>{}),!0)}getStatus(){let e=0,t=0;for(const s of this.slots.values())s.state==="ready"&&(e++,s.adapter.getStatus().busy&&t++);return{total:this.slots.size,ready:e,busy:t}}hasPendingWork(){return this.collectBusy(!1,!0).length>0}hasPendingOrBackgroundWork(){return this.collectBusy(!0,!0).length>0}describePendingOrBackgroundWork(){return this.collectBusy(!0,!1)}collectBusy(e,t){const s=[],n=Date.now();if(this.startupEvents.size>0&&(s.push({source:"queued",label:"startup",count:this.startupEvents.size}),t))return s;for(const r of this.slots.values()){if(r.startPromise){const l=n-(r.startPromiseSince??n);if(s.push({source:"starting",session:r.sessionId,...l>E?{suspect:`adapter start has not settled for ${d(l)}`}:{}}),t)return s}const a=r.eventQueue.runningCount,o=r.eventQueue.queuedCount;if(a>0&&(s.push({source:"running",session:r.sessionId,count:a}),t)||o>0&&(s.push({source:"queued",session:r.sessionId,count:o}),t))return s;if(r.state!=="ready")continue;const c=r.adapter.getStatus();if(c.busy){const l=a+o===0&&r.adapterBusySince?n-r.adapterBusySince:0;if(s.push({source:"adapter-busy",session:r.sessionId,...l>w?{suspect:`adapter reports busy with an empty queue for ${d(l)}`}:{}}),t)return s}if(e&&c.backgroundBusy&&(s.push({source:"background",session:r.sessionId}),t))return s}return s}createSlot(e){const t=this.factory(e),s=new f,n=this.createEventQueue(e),r={sessionId:e,adapter:t,respawn:s,state:"starting",lastActivityAt:Date.now(),startPromise:null,startPromiseSince:null,adapterBusySince:null,eventQueue:n,stopping:!1};this.slots.set(e,r);const a=(async()=>{try{this.wireSlotEvents(r),await t.start(),r.state="ready"}catch(o){throw this.detachAllSlotEventListeners(r),this.slots.get(e)===r&&this.slots.delete(e),o}finally{r.startPromise=null,r.startPromiseSince=null}})();return r.startPromise=a,r.startPromiseSince=Date.now(),s.startHealthCheck(this.slotRespawnCtx(r)),r}wireSlotEvents(e){e.adapter.on("exit",t=>{this.stopped||(i.error("adapter-pool",`Slot ${e.sessionId} adapter exited (code=${t})`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on("stuck",()=>{this.stopped||this.slots.get(e.sessionId)===e&&(i.error("adapter-pool",`Slot ${e.sessionId} adapter stuck, triggering respawn`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on?.("error",t=>{if(this.stopped)return;const s=t instanceof Error?t.message:String(t);i.error("adapter-pool",`Slot ${e.sessionId} adapter error: ${s}`)}),e.adapter.on("internalError",t=>{if(!this.stopped){if(this.slots.get(e.sessionId)!==e){i.warn("adapter-pool",`Ignored internalError from detached slot session=${e.sessionId} event=${t.eventId}`);return}if(!this.onInternalError){i.warn("adapter-pool",`Slot ${e.sessionId} emitted internalError but no handler registered: event=${t.eventId} msg=${t.errorMsg}`);return}this.onInternalError(t)}}),e.adapter.on("eventStarted",(t,s)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventStarted?.(t,s)}),e.adapter.on("eventDone",t=>{this.stopped||this.slots.get(e.sessionId)===e&&(this.onEventDone?.(t,e.sessionId),e.eventQueue.markAdapterDone(t))}),e.adapter.on("sessionActivity",(t,s,n)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onSessionActivity?.(t||e.sessionId,s,n)}),e.adapter.on("pauseIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.pause(t)}),e.adapter.on("resumeIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.resume(t)})}detachAllSlotEventListeners(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("eventDone"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}detachSlotEventListenersExceptDone(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}slotRespawnCtx(e){const t=this,s=e.sessionId,n=e.adapter.type==="agy";return{name:`slot-${s}`,get stopped(){return t.stopped||!t.slots.has(s)},get agentAlive(){return e.adapter.isAlive()},pingAgent:r=>e.adapter.ping(r),...n?{healthCheckIntervalMs:g,healthCheckMaxFailures:S}:{},onRespawnNeeded:async()=>{e.eventQueue.pause("restart"),this.detachAllSlotEventListeners(e),await e.adapter.stop().catch(()=>{}),e.adapter=t.factory(s),e.state="starting",t.wireSlotEvents(e),await e.adapter.start(),e.state="ready",e.respawn.resetAttempts(),e.respawn.resetHealthFailures(),e.respawn.stopSlowRetry(),e.respawn.startHealthCheck(t.slotRespawnCtx(e)),e.eventQueue.resume("compaction"),e.eventQueue.resume("barrier"),e.eventQueue.resume("restart")},onCleanupAgent:()=>{"cleanup"in e.adapter&&e.adapter.cleanup()},onAbortActiveRun:r=>{}}}createEventQueue(e){const t=this.config.eventQueue??{maxConcurrent:1,maxQueued:99,queueTimeoutMs:3e5,cancelableQueued:!0,cancelableRunning:!0},s={onDeliver:n=>{const r=this.slots.get(e);r&&r.adapter.deliverInboundEvent(n)},onStateChange:(n,r,a,o)=>{this.onEventState?.(n,r,a,o)},onCancelRunning:n=>{this.deliverStopEvent(n,e)},onRejected:(n,r)=>{this.onEventState?.(n.event_id,n.session_id,"failed",{reason:r})},onComposing:(n,r,a)=>{this.onQueueComposing?.(n,r,a)}};return new v(t,s)}}export{b as AdapterPool,m as PoolFullError};
|
|
1
|
+
import{log as i}from"../core/log/index.js";import{RespawnManager as v}from"./respawn-manager.js";import{EventQueue as f}from"./event-queue.js";import{formatWaitDuration as p}from"../core/upgrade/idle-wait.js";const d=6e4;async function h(u){if(!u.startPromise)return;let e;try{await Promise.race([u.startPromise,new Promise((t,s)=>{e=setTimeout(()=>s(new Error(`adapter start timeout (${d}ms) session=${u.sessionId}`)),d)})])}finally{e&&clearTimeout(e)}}const g=12e4,S=5;class m extends Error{constructor(e){super(`adapter pool full (maxSize=${e})`),this.name="PoolFullError"}}const A=6e4,E=2*6e4,w=10*6e4;class b{slots=new Map;config;factory;sendAck;onEventState=null;onQueueComposing=null;onInternalError=null;onEventStarted=null;onEventDone=null;onSessionActivity=null;stopped=!1;startupEvents=new Map;sweepTimer=null;pendingRemovals=new Map;constructor(e,t,s){this.config=e,this.factory=t,this.sendAck=s}setEventStateHandler(e){this.onEventState=e}setQueueComposingHandler(e){this.onQueueComposing=e}setInternalErrorHandler(e){this.onInternalError=e}setEventStartedHandler(e){this.onEventStarted=e}setEventDoneHandler(e){this.onEventDone=e}setSessionActivityHandler(e){this.onSessionActivity=e}async deliverInboundEvent(e){return this.deliverInboundEventInternal(e)}async deliverInboundEventInternal(e,t){if(this.stopped)throw new Error("adapter pool stopped");if(t&&!this.isCurrentStartupTicket(e.event_id,t))return;const s=e.session_id,n=this.slots.get(s);if(n){if(n.stopping)return await this.pendingRemovals.get(s)?.catch(()=>{}),this.deliverInboundEventInternal(e,t);if(n.startPromise){await this.submitAfterStartup(n,e,t);return}if(t){if(!this.retireStartupTicket(e.event_id,t,"submitted"))return}else this.sendAck(e.event_id,e.session_id);n.lastActivityAt=Date.now(),n.state==="stopped"&&i.info("adapter-pool",`Holding event ${e.event_id} in paused queue for restarting slot ${s}`),this.submitToSlotQueue(n,e);return}if(this.slots.size>=this.config.maxPoolSize&&!this.evictDeadSlot()&&!this.evictIdleSlot())throw new m(this.config.maxPoolSize);const r=this.createSlot(s);await this.submitAfterStartup(r,e,t)}async submitAfterStartup(e,t,s){const n=s??{event:t,state:"pending"};if(s){if(!this.isCurrentStartupTicket(t.event_id,n))return}else this.sendAck(t.event_id,t.session_id),this.startupEvents.set(t.event_id,n);try{await e.startPromise}catch(r){if(!this.retireStartupTicket(t.event_id,n,"failed"))return;throw r}if(this.isCurrentStartupTicket(t.event_id,n)&&!this.stopped){if(this.slots.get(e.sessionId)!==e||e.stopping){if(await this.pendingRemovals.get(e.sessionId)?.catch(()=>{}),!this.isCurrentStartupTicket(t.event_id,n)||this.stopped)return;const r=this.slots.get(e.sessionId);if(r&&!r.stopping){await this.submitAfterStartup(r,t,n);return}try{await this.deliverInboundEventInternal(t,n)}catch(o){if(this.stopped||!this.retireStartupTicket(t.event_id,n,"failed"))return;throw o}return}this.retireStartupTicket(t.event_id,n,"submitted"),e.lastActivityAt=Date.now(),this.submitToSlotQueue(e,t)}}isCurrentStartupTicket(e,t){return t.state==="pending"&&this.startupEvents.get(e)===t}retireStartupTicket(e,t,s){return this.isCurrentStartupTicket(e,t)?(t.state=s,this.startupEvents.delete(e),!0):!1}submitToSlotQueue(e,t){e.eventQueue.submit(t)==="rejected"&&i.info("adapter-pool",`Event ${t.event_id} rejected by EventQueue (queue full)`)}eventComplete(e,t){const s=this.startupEvents.get(e);if(s?.event.session_id===t)return this.retireStartupTicket(e,s,"terminal");const n=this.slots.get(t);if(!n)return i.error("adapter-pool",`Cannot complete event ${e}: session slot not found (${t})`),!1;const r=n.eventQueue.complete(e);return r||i.error("adapter-pool",`Cannot complete event ${e}: not running in session ${t}`),r}cleanupEvent(e,t){const s=this.startupEvents.get(e);if(s)return this.retireStartupTicket(e,s,"terminal");const n=t?[this.slots.get(t)].filter(r=>!!r):[...this.slots.values()];for(const r of n)if(r.eventQueue.complete(e)||r.eventQueue.removeQueued(e))return!0;return!0}getEventSessionId(e){const t=this.startupEvents.get(e);if(t)return t.event.session_id;for(const s of this.slots.values()){const n=s.eventQueue.snapshot(s.sessionId);if(n.running.includes(e)||n.queued.some(r=>r.event_id===e))return s.sessionId}}rejectEventOutput(e,t){const s=t?this.slots.get(t):void 0;s&&(s.adapter.getActiveEventIds().includes(e)||s.eventQueue.snapshot(s.sessionId).running.includes(e))&&(s.adapter.rejectEventOutput?s.adapter.rejectEventOutput(e):s.adapter.deliverStopEvent(e,t)),this.cleanupEvent(e,t)}cancelEvent(e,t){if(this.cancelStartupEvent(e,t))return!0;const s=this.slots.get(t);return s?s.eventQueue.cancel(e):!1}cancelStartupEvent(e,t){const s=this.startupEvents.get(e);if(s&&!(t&&s.event.session_id!==t)&&this.retireStartupTicket(e,s,"canceled"))return s.event}removeQueuedEvent(e,t){const s=this.slots.get(e);return s?s.eventQueue.removeQueued(t):!1}clearQueue(e){const t=this.slots.get(e);return t?t.eventQueue.clear(e):[]}reorderQueue(e,t){const s=this.slots.get(e);return s?s.eventQueue.reorder(e,t):[]}holdEvent(e,t,s,n,r){const o=this.slots.get(e);return o?s?o.eventQueue.hold(t,n,r):o.eventQueue.release(t):"not_found"}editQueuedEvent(e,t,s){const n=this.slots.get(e);return n?n.eventQueue.editQueued(t,s):"not_found"}pauseAllQueues(e){for(const t of this.slots.values())t.eventQueue.pause(e)}drainAllQueuedEvents(){const e=[...this.startupEvents.entries()],t=e.map(([,s])=>s.event);for(const[s,n]of e)this.retireStartupTicket(s,n,"drained");this.startupEvents.clear();for(const s of this.slots.values())t.push(...s.eventQueue.drainQueuedForSession(s.sessionId));return t}drainQueuedForSession(e){if(!this.config.eventQueue)return[];const t=this.slots.get(e);return t?t.eventQueue.drainQueuedForSession(e):[]}getQueueSnapshot(e){if(!this.config.eventQueue)return null;const t=this.slots.get(e);return t?t.eventQueue.snapshot(e):null}deliverStopEvent(e,t){if(t){const s=this.slots.get(t);i.info("adapter-pool",`[stop-trace] pool.deliverStopEvent session=${t} event=${e} slotExists=${!!s} -> adapter.deliverStopEvent`),s?.adapter.deliverStopEvent(e,t);return}i.info("adapter-pool",`[stop-trace] pool.deliverStopEvent (broadcast, no session) event=${e} slots=${this.slots.size}`);for(const s of this.slots.values())s.adapter.deliverStopEvent(e)}collectActiveEventIds(){const e=[];for(const t of this.slots.values()){const s=t.adapter.getActiveEventIds;typeof s=="function"&&e.push(...s.call(t.adapter)),e.push(...t.eventQueue.snapshot(t.sessionId).running)}return[...new Set(e)]}clearActiveEventsForShutdown(){for(const e of this.slots.values()){const t=e.adapter.clearActiveEventForShutdown;typeof t=="function"&&t.call(e.adapter)}}async deliverLocalAction(e,t){const s=String((e.params??{}).session_id??"");let n=s?this.slots.get(s):void 0;if(n?.stopping&&(await this.pendingRemovals.get(s)?.catch(()=>{}),n=this.slots.get(s)),!n&&s&&t?.autoCreateSlot&&!this.stopped&&(this.slots.size>=this.config.maxPoolSize&&(this.evictDeadSlot()||this.evictIdleSlotSync()),this.slots.size<this.config.maxPoolSize)){i.info("adapter-pool",`Auto-creating slot for session ${s} (local_action trigger)`);const a=this.createSlot(s);try{await a.startPromise,n=a}catch(c){i.error("adapter-pool",`Failed to auto-create slot for ${s}: ${c}`)}}return n?.adapter?.handleLocalAction?(n.lastActivityAt=Date.now(),n.adapter.handleLocalAction(e)):s?{handled:!1,kind:""}:(await Promise.allSettled([...this.slots.values()].filter(a=>!a.stopping).map(a=>a.adapter.handleLocalAction?.(e)??Promise.resolve({handled:!1,kind:""})))).find(a=>a.status==="fulfilled"&&a.value.handled)?.value??{handled:!1,kind:""}}async waitForSlotRemoval(e){await this.pendingRemovals.get(e)?.catch(()=>{})}async getOrCreateSlot(e){let t=this.slots.get(e);if(t?.stopping&&(await this.pendingRemovals.get(e)?.catch(()=>{}),t=this.slots.get(e)),t)return await h(t),t;if(this.stopped)return;const s=this.createSlot(e);return await h(s),s}getSlot(e){return this.slots.get(e)}getAllSlots(){return[...this.slots.values()]}async removeSlot(e){const t=this.slots.get(e);if(!t){await this.pendingRemovals.get(e)?.catch(()=>{});return}if(t.stopping){await this.pendingRemovals.get(e)?.catch(()=>{});return}t.stopping=!0;const s=this.doRemoveSlot(t);this.pendingRemovals.set(e,s);try{await s}finally{this.pendingRemovals.get(e)===s&&this.pendingRemovals.delete(e)}}async doRemoveSlot(e){const t=e.sessionId;this.onSessionActivity?.(t,!1),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachSlotEventListenersExceptDone(e),await e.adapter.stop().catch(()=>{}),e.adapter.removeAllListeners("eventDone"),this.slots.delete(t)}async stop(){this.stopped=!0,this.stopIdleSweep(),await Promise.allSettled([...this.pendingRemovals.values()]);const e=[...this.slots.values()];this.slots.clear(),await Promise.allSettled(e.map(async t=>{t.eventQueue.destroy(),t.respawn.stopAll(),this.detachAllSlotEventListeners(t),await t.adapter.stop().catch(()=>{})}))}startIdleSweep(){this.stopIdleSweep(),this.sweepTimer=setInterval(()=>this.sweepIdle(),A)}stopIdleSweep(){this.sweepTimer&&(clearInterval(this.sweepTimer),this.sweepTimer=null)}sweepIdle(){const e=Date.now();for(const[t,s]of this.slots){if(s.stopping)continue;if(s.state==="stopped"&&s.respawn.exhausted){i.info("adapter-pool",`Removing dead slot for session ${t} (sweep)`),this.removeSlot(t).catch(()=>{});continue}if(s.state!=="ready")continue;if(s.eventQueue.runningCount>0||s.eventQueue.queuedCount>0){s.adapterBusySince=null,s.lastActivityAt=e;continue}const n=s.adapter.getStatus();if(s.adapterBusySince=n.busy?s.adapterBusySince??e:null,n.busy||n.backgroundBusy){s.lastActivityAt=e;continue}e-s.lastActivityAt<=this.config.idleTimeoutMs||(s.adapter.hasBackgroundWork?s.adapter.hasBackgroundWork().then(r=>{r?(i.info("adapter-pool",`Deferred eviction for session ${t}: background grandchild processes detected`),s.lastActivityAt=Date.now()):this.evictAfterProbe(t,s,"probe idle")}).catch(()=>{this.evictAfterProbe(t,s,"probe failed")}):(i.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(r=>{i.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})))}}evictAfterProbe(e,t,s){if(this.slots.get(e)!==t||t.stopping)return;if(t.eventQueue.runningCount>0||t.eventQueue.queuedCount>0){t.lastActivityAt=Date.now();return}const n=t.adapter.getStatus();if(n.busy||n.backgroundBusy){t.lastActivityAt=Date.now();return}Date.now()-t.lastActivityAt<=this.config.idleTimeoutMs||(i.info("adapter-pool",`Evicting idle slot for session ${e} (${s})`),this.removeSlot(e).catch(r=>{i.error("adapter-pool",`Failed to evict slot ${e}: ${r}`)}))}evictDeadSlot(){for(const[e,t]of this.slots)if(t.state==="stopped"&&t.respawn.exhausted)return i.info("adapter-pool",`Removing dead slot for session ${e} (exhausted respawn)`),this.removeSlot(e).catch(()=>{}),!0;return!1}evictIdleSlot(){let e=null;for(const t of this.slots.values()){if(t.stopping||t.state!=="ready"||t.eventQueue.runningCount>0||t.eventQueue.queuedCount>0)continue;const s=t.adapter.getStatus();s.busy||s.backgroundBusy||(!e||t.lastActivityAt<e.lastActivityAt)&&(e=t)}return e?(i.info("adapter-pool",`Evicting idle slot for session ${e.sessionId} (pool full)`),this.removeSlot(e.sessionId).catch(()=>{}),!0):!1}evictIdleSlotSync(){let e=null,t="";for(const[s,n]of this.slots){if(n.stopping||n.state!=="ready"||n.eventQueue.runningCount>0||n.eventQueue.queuedCount>0)continue;const r=n.adapter.getStatus();r.busy||r.backgroundBusy||(!e||n.lastActivityAt<e.lastActivityAt)&&(e=n,t=s)}return!e||!t?!1:(i.info("adapter-pool",`Evicting idle slot for session ${t} (pool full, sync)`),this.slots.delete(t),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachAllSlotEventListeners(e),e.adapter.stop().catch(()=>{}),!0)}getStatus(){let e=0,t=0;for(const s of this.slots.values())s.state==="ready"&&(e++,s.adapter.getStatus().busy&&t++);return{total:this.slots.size,ready:e,busy:t}}hasPendingWork(){return this.collectBusy(!1,!0).length>0}hasPendingOrBackgroundWork(){return this.collectBusy(!0,!0).length>0}describePendingOrBackgroundWork(){return this.collectBusy(!0,!1)}collectBusy(e,t){const s=[],n=Date.now();if(this.startupEvents.size>0&&(s.push({source:"queued",label:"startup",count:this.startupEvents.size}),t))return s;for(const r of this.slots.values()){if(r.startPromise){const l=n-(r.startPromiseSince??n);if(s.push({source:"starting",session:r.sessionId,...l>E?{suspect:`adapter start has not settled for ${p(l)}`}:{}}),t)return s}const o=r.eventQueue.runningCount,a=r.eventQueue.queuedCount;if(o>0&&(s.push({source:"running",session:r.sessionId,count:o}),t)||a>0&&(s.push({source:"queued",session:r.sessionId,count:a}),t))return s;if(r.state!=="ready")continue;const c=r.adapter.getStatus();if(c.busy){const l=o+a===0&&r.adapterBusySince?n-r.adapterBusySince:0;if(s.push({source:"adapter-busy",session:r.sessionId,...l>w?{suspect:`adapter reports busy with an empty queue for ${p(l)}`}:{}}),t)return s}if(e&&c.backgroundBusy&&(s.push({source:"background",session:r.sessionId}),t))return s}return s}createSlot(e){const t=this.factory(e),s=new v,n=this.createEventQueue(e),r={sessionId:e,adapter:t,respawn:s,state:"starting",lastActivityAt:Date.now(),startPromise:null,startPromiseSince:null,adapterBusySince:null,eventQueue:n,stopping:!1};this.slots.set(e,r);const o=(async()=>{try{this.wireSlotEvents(r),await t.start(),r.state="ready"}catch(a){throw this.detachAllSlotEventListeners(r),this.slots.get(e)===r&&this.slots.delete(e),a}finally{r.startPromise=null,r.startPromiseSince=null}})();return r.startPromise=o,r.startPromiseSince=Date.now(),s.startHealthCheck(this.slotRespawnCtx(r)),r}wireSlotEvents(e){e.adapter.on("exit",t=>{this.stopped||(i.error("adapter-pool",`Slot ${e.sessionId} adapter exited (code=${t})`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on("stuck",()=>{this.stopped||this.slots.get(e.sessionId)===e&&(i.error("adapter-pool",`Slot ${e.sessionId} adapter stuck, triggering respawn`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on?.("error",t=>{if(this.stopped)return;const s=t instanceof Error?t.message:String(t);i.error("adapter-pool",`Slot ${e.sessionId} adapter error: ${s}`)}),e.adapter.on("internalError",t=>{if(!this.stopped){if(this.slots.get(e.sessionId)!==e){i.warn("adapter-pool",`Ignored internalError from detached slot session=${e.sessionId} event=${t.eventId}`);return}if(!this.onInternalError){i.warn("adapter-pool",`Slot ${e.sessionId} emitted internalError but no handler registered: event=${t.eventId} msg=${t.errorMsg}`);return}this.onInternalError(t)}}),e.adapter.on("eventStarted",(t,s)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventStarted?.(t,s)}),e.adapter.on("eventDone",t=>{this.stopped||this.slots.get(e.sessionId)===e&&(this.onEventDone?.(t,e.sessionId),e.eventQueue.markAdapterDone(t))}),e.adapter.on("sessionActivity",(t,s,n)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onSessionActivity?.(t||e.sessionId,s,n)}),e.adapter.on("pauseIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.pause(t)}),e.adapter.on("resumeIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.resume(t)}),e.adapter.on("activeInputReady",()=>{this.stopped||e.stopping||this.slots.get(e.sessionId)!==e||e.eventQueue.refreshActiveInput()})}detachAllSlotEventListeners(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("eventDone"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake"),e.adapter.removeAllListeners("activeInputReady")}detachSlotEventListenersExceptDone(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake"),e.adapter.removeAllListeners("activeInputReady")}slotRespawnCtx(e){const t=this,s=e.sessionId,n=e.adapter.type==="agy";return{name:`slot-${s}`,get stopped(){return t.stopped||!t.slots.has(s)},get agentAlive(){return e.adapter.isAlive()},pingAgent:r=>e.adapter.ping(r),...n?{healthCheckIntervalMs:g,healthCheckMaxFailures:S}:{},onRespawnNeeded:async()=>{e.eventQueue.pause("restart"),this.detachAllSlotEventListeners(e),await e.adapter.stop().catch(()=>{}),e.adapter=t.factory(s),e.state="starting",t.wireSlotEvents(e),await e.adapter.start(),e.state="ready",e.respawn.resetAttempts(),e.respawn.resetHealthFailures(),e.respawn.stopSlowRetry(),e.respawn.startHealthCheck(t.slotRespawnCtx(e)),e.eventQueue.resume("compaction"),e.eventQueue.resume("barrier"),e.eventQueue.resume("restart")},onCleanupAgent:()=>{"cleanup"in e.adapter&&e.adapter.cleanup()},onAbortActiveRun:r=>{}}}createEventQueue(e){const t=this.config.eventQueue??{maxConcurrent:1,maxQueued:99,queueTimeoutMs:3e5,cancelableQueued:!0,cancelableRunning:!0},s={canDeliverActiveInput:n=>{const r=this.slots.get(e);return!!r&&r.state==="ready"&&!r.stopping&&!!r.adapter.deliverActiveInput&&!!r.adapter.canAcceptActiveInput?.(n)},onDeliver:(n,r)=>{const o=this.slots.get(e);o&&(r?o.adapter.deliverActiveInput(n):o.adapter.deliverInboundEvent(n))},onStateChange:(n,r,o,a)=>{this.onEventState?.(n,r,o,a)},onCancelRunning:n=>{this.deliverStopEvent(n,e)},onRejected:(n,r)=>{this.onEventState?.(n.event_id,n.session_id,"failed",{reason:r})},onComposing:(n,r,o)=>{this.onQueueComposing?.(n,r,o)}};return new f(t,s)}}export{b as AdapterPool,m as PoolFullError};
|