grix-connector 3.19.0 → 3.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,9 +8,9 @@ Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n,r)=>this.aibotHandle.sendUpdate
8
8
 
9
9
  Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n,...this.providerQuotaMetaPayload(r,s,n)}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(s,i,n,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,r,a,c)},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),forceCompleteInternalEvent:(s,i)=>{this.pool.eventComplete(s,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(s,i)=>{this.bindingStore.setAgyConversationId(s,i)},getAgentProfile:()=>this.agentProfile},t=s=>{const i=this.bindingStore.get(s);return{cwd:i?.cwd,modelId:this.resolveSessionModelId(s),conversationId:i?.agyConversationId}};return new X({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},o,t)}createAcpAdapter(e){const o=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(d,l,u,g,_,m,b)=>{this.finalizeThinking(d,l),this.sendStreamChunkByRuntimeConfig(d,l,u,g,_,m,b)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,l,u)=>{this.sendEventResultWithCleanup(d,l,u)},sendEventAck:(d,l)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:l,received_at:Date.now()})},agentInvoke:async(d,l,u)=>this.platformInvoke(d,l,u),sendLocalActionResult:(d,l,u,g,_)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:l,...u!==void 0?{result:u}:{},...g?{error_code:g}:{},..._?{error_msg:_}:{}})},sendRawEventEnvelope:(d,l,u)=>{this.sendAcpRawEventEnvelope(d,l,u)},sendToolUse:(d,l,u,g)=>{if(o){this.sendAcpRawEventEnvelope(d,l,{type:"tool_use",payload:{tool_name:u,tool_input:g??""}});return}this.sendToolExecutionCard(d,l,T(u,g))},sendToolResult:(d,l,u,g)=>{this.sendToolExecutionCard(d,l,P(u,g))},sendThinking:(d,l,u)=>{this.sendThinkingByRuntimeConfig(d,l,u)},sendRunError:(d,l,u)=>{this.sendStreamChunkByRuntimeConfig(d,l,`
10
10
 
11
- Error: ${u}`,1,!1)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const l=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(o){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${F()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,command:l,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(_){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:_ instanceof Error?_.message:String(_)})}},sendAuthNotification:(d,l)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(d,l)=>{d&&l&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l})},sendUpdateBindingCard:(d,l,u,g)=>{const _={...g??{}};if(!_.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(_.rate_limits=m)}!_.provider_quota&&this.cachedProviderQuota?.success&&(_.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:u,...Object.keys(_).length>0?{meta:_}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:ee(d,y.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${l}%`);const u=this.bindingStore.get(e);if(u?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),_={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),_.provider_quota=this.cachedProviderQuota;const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(_.rate_limits=m)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:_})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=e?this.auditController.getSession(e):void 0,n=this.config.aibot.clientType==="reasonix"&&i?ni(this.name,e,i.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Rt({sessionBinding:s,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,a),(a||c)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new R({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new vt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:n,agentType:this.config.aibot.clientType})}async connectAibot(){const e=new fe;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{h.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id),this.sessionProviderHints.delete(t.session_id),this.sessionProviderQuotas.delete(t.session_id),this.sessionProviderMeta.delete(t.session_id);const r=this.pool.getSlot(t.session_id);r?.adapter instanceof R&&r.adapter.getSessionBindings().delete(t.session_id);const a=this.config.adapterType??"acp",c=this.resolveBindingChannelKey(a);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:p.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){h.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{h.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){h.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){h.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){h.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(t=>{try{h.info(this.name,`skill_sync received owner=${t?.owner_id??""} name=${t?.name??""}`),this.skillSyncHandler?.()}catch(s){h.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){h.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{h.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{h.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{h.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):h.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(t=>{const s=Array.isArray(t.ordered_event_ids)?t.ordered_event_ids.filter(n=>typeof n=="string"&&n.length>0):[],i=this.pool.reorderQueue(t.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:t.session_id,applied_event_ids:i}),this.pushQueueSnapshotForSession(t.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(t=>{const s=typeof t.session_id=="string"?t.session_id:"",i=typeof t.event_id=="string"?t.event_id:"",n=t.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${i} session_id=${s} hold=${n} reason=${t.reason??""}`),!s||!i){this.aibotHandle.sendEventHoldResult({session_id:s,event_id:i,ok:!1,held:!1,error:"bad_request"});return}const r=typeof t.reason=="string"?t.reason:"",a=typeof t.ttl_ms=="number"?t.ttl_ms:void 0,c=this.pool.holdEvent(s,i,n,r,a),d=c==="ok";this.aibotHandle.sendEventHoldResult({session_id:s,event_id:i,ok:d,held:d?n:!1,...d?{}:{error:c}}),d&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(t=>{const s=typeof t.session_id=="string"?t.session_id:"",i=typeof t.event_id=="string"?t.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${i} session_id=${s}`),!s||!i){this.aibotHandle.sendQueueEditResult({session_id:s,event_id:i,ok:!1,error:"bad_request"});return}const n=typeof t.content=="string"?t.content:"",r=this.pool.editQueuedEvent(s,i,n),a=r==="ok";this.aibotHandle.sendQueueEditResult({session_id:s,event_id:i,ok:a,...a?{}:{error:r}}),a&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){h.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)h.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0}),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?h.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):h.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const r of o)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),t++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const s=o.filter(r=>r.adapter instanceof L),i=s.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),n=s.length-i.length;h.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const r of i)this.pool.removeSlot(r.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...typeof n.content=="string"?{content:n.content}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},held:n.held===!0,held_reason:n.held_reason??"",actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?Tt(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Lt({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),r=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${F()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(r.cmd!=="send_ack"){const c=r.payload??{},d=String(c.msg??r.cmd);throw new Error(`media message send failed: ${d}`)}const a=r.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.auditController.captureReply(e,t),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:n,...r}=e;return r}const o=e;if(o.codex_method!=="item/agentMessage/delta")return e;const s=o.codex_payload?.params?.phase;if(typeof s=="string"&&s.trim()&&s.trim().toLowerCase()!=="final_answer")return e;const i=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return i?{...e,quoted_message_id:i}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const o=e.codex_payload?.params,t=typeof o?.phase=="string"?o.phase.trim().toLowerCase():"";if(t&&t!=="final_answer")return;const s=o?.delta;typeof s!="string"||!s||this.auditController.captureUnsequencedStreamChunk(e.event_id,s)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,o){return async(t,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(t,s,i,o)}catch(n){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${t}: ${n}`),n}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${t}`)}}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,r){this.indexEventSession(e,o),this.auditController.captureStreamChunk(e,s,t),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,r),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
11
+ Error: ${u}`,1,!1)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const l=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(o){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${F()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,command:l,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(_){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:_ instanceof Error?_.message:String(_)})}},sendAuthNotification:(d,l)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(d,l)=>{d&&l&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l})},sendUpdateBindingCard:(d,l,u,g)=>{const _={...g??{}};if(!_.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(_.rate_limits=m)}!_.provider_quota&&this.cachedProviderQuota?.success&&(_.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:u,...Object.keys(_).length>0?{meta:_}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:ee(d,y.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${l}%`);const u=this.bindingStore.get(e);if(u?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),_={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),_.provider_quota=this.cachedProviderQuota;const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(_.rate_limits=m)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:_})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=e?this.auditController.getSession(e):void 0,n=this.config.aibot.clientType==="reasonix"&&i?ni(this.name,e,i.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Rt({sessionBinding:s,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,a),(a||c)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new R({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new vt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:n,agentType:this.config.aibot.clientType})}async connectAibot(){const e=new fe;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{h.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id),this.sessionProviderHints.delete(t.session_id),this.sessionProviderQuotas.delete(t.session_id),this.sessionProviderMeta.delete(t.session_id);const r=this.pool.getSlot(t.session_id);r?.adapter instanceof R&&r.adapter.getSessionBindings().delete(t.session_id);const a=this.config.adapterType??"acp",c=this.resolveBindingChannelKey(a);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:p.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){h.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{h.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){h.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){h.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){h.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(t=>{try{h.info(this.name,`skill_sync received owner=${t?.owner_id??""} name=${t?.name??""}`),this.skillSyncHandler?.()}catch(s){h.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){h.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{h.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{h.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{h.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):h.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(t=>{const s=Array.isArray(t.ordered_event_ids)?t.ordered_event_ids.filter(n=>typeof n=="string"&&n.length>0):[],i=this.pool.reorderQueue(t.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:t.session_id,applied_event_ids:i}),this.pushQueueSnapshotForSession(t.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(t=>{const s=typeof t.session_id=="string"?t.session_id:"",i=typeof t.event_id=="string"?t.event_id:"",n=t.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${i} session_id=${s} hold=${n} reason=${t.reason??""}`),!s||!i){this.aibotHandle.sendEventHoldResult({session_id:s,event_id:i,ok:!1,held:!1,error:"bad_request"});return}const r=typeof t.reason=="string"?t.reason:"",a=typeof t.ttl_ms=="number"?t.ttl_ms:void 0,c=this.pool.holdEvent(s,i,n,r,a),d=c==="ok";this.aibotHandle.sendEventHoldResult({session_id:s,event_id:i,ok:d,held:d?n:!1,...d?{}:{error:c}}),d&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(t=>{const s=typeof t.session_id=="string"?t.session_id:"",i=typeof t.event_id=="string"?t.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${i} session_id=${s}`),!s||!i){this.aibotHandle.sendQueueEditResult({session_id:s,event_id:i,ok:!1,error:"bad_request"});return}const n=typeof t.content=="string"?t.content:"",r=this.pool.editQueuedEvent(s,i,n),a=r==="ok";this.aibotHandle.sendQueueEditResult({session_id:s,event_id:i,ok:a,...a?{}:{error:r}}),a&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){h.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)h.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0}),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?h.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):h.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const r of o)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),t++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const s=o.filter(r=>r.adapter instanceof L),i=s.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),n=s.length-i.length;h.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const r of i)this.pool.removeSlot(r.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...typeof n.content=="string"?{content:n.content}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},held:n.held===!0,held_reason:n.held_reason??"",actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?Tt(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Lt({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),r=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${F()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(r.cmd!=="send_ack"){const c=r.payload??{},d=String(c.msg??r.cmd);throw new Error(`media message send failed: ${d}`)}const a=r.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.auditController.captureReply(e,t),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:n,...r}=e;return r}const o=e;if(o.codex_method!=="item/agentMessage/delta")return e;const s=o.codex_payload?.params?.phase;if(typeof s=="string"&&s.trim()&&s.trim().toLowerCase()!=="final_answer")return e;const i=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return i?{...e,quoted_message_id:i}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const o=e.codex_payload?.params,t=typeof o?.phase=="string"?o.phase.trim().toLowerCase():"";if(t&&t!=="final_answer")return;const s=o?.delta;typeof s!="string"||!s||this.auditController.captureUnsequencedStreamChunk(e.event_id,s)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,o){return async(t,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(t,s,i,o)}catch(n){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${t}: ${n}`),n}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${t}`)}}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,r){this.indexEventSession(e,o),this.auditController.captureStreamChunk(e,s,t),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,r),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,o,t){this.surfacedRunErrorEvents.has(e)||(this.sendStreamChunkByRuntimeConfig(e,o,`
12
12
 
13
- Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,s){this.auditController.markResponded(e,o,t),this.sendCtrl.sendEventResult(e,o,t,s);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){h.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const r=this.config.adapterType??"acp";if(n>G){h.error(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${n}/${G} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${n}/${G} outcome=restarting err=${s}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&h.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){h.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=this.resolveRecoveryPrompt(r,i),d={...i,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){h.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(l.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.auditController.captureUnsequencedStreamChunk(e,t),this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.deliverRawEventEnvelope(e,o,t,"acp",this.buildAcpRawEventFallbackText(t))}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,o,t,s,i){const n=Ot({envelope:t,fallbackText:i,channelKey:s,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:n.fallbackText,extra:{channel_data:{[s]:{raw_event:n.envelope}},agent_api_origin:!0}})};if(!n.sharded){r();return}h.info("bridge",`${s} raw_event oversized, sharded delivery: event=${e} fields=${n.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of n.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,o,Ut({envelopeType:t.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{h.warn("bridge",`${s} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const o=String(e?.type??"").trim(),t=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(o){case"permission_request":return`Permission required: ${String(t.tool_title??t.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(t.tool_name??t.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(t.message??"agent error")}`;default:return o?`[cursor] ${o}`:"[cursor] event"}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=It(e.extra);if(t.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:t.error,updated_at:Date.now()});return}const s=t.patch,i=Xt(e.extra);if((i.state!=="absent"||i.error)&&h.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${i.state??"error"} scope=${i.options?.enabled?i.options.scope:""} error=${i.error??""}`),i.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:i.error,updated_at:Date.now()});return}if(i.state==="enabled"&&o!=="claude"&&o!=="codex"&&o!=="cursor"&&o!=="opencode"&&o!=="pi"&&o!=="codewhale"&&o!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${o}`,updated_at:Date.now()}),i.options?.enabled&&i.options.scope==="turn")try{this.aibotHandle.sendAuditState(z({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${o}`},Date.now()))}catch{}return}const n=Ct(e);if(n){if(i.state!=="absent"||n.verb===v.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(d){this.sendAuditConfigurationError(e,d);return}if(n.verb===v.exec){await this.handleSessionControlCommand(n,e);return}if(n.verb===v.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(n,e);return}if(o==="codex"&&n.verb===v.open){await this.handleCodexSessionControlOpen(n,e);return}if(o==="pi"&&n.verb===v.open){await this.handlePiSessionControlOpen(n,e);return}if(o==="pi"&&n.verb===v.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&n.verb===v.open){await this.handleOpenHumanSessionControlOpen(n,e);return}if(o==="codewhale"&&n.verb===v.open){await this.handleCodeWhaleSessionControlOpen(n,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.verb===v.open){const d=n.args.trim();if(!d){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const l=$.resolve(d);if(!(await B(l)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.invalidCwd,msg:`Path is not a directory: ${l}`,updated_at:Date.now()});return}}catch(l){const u=String(l?.code??""),g=u==="ENOENT"?`Directory does not exist: ${$.resolve(d)}`:u==="EACCES"||u==="EPERM"?"Directory is not accessible":`Invalid path: ${d}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.invalidCwd,msg:g,updated_at:Date.now()});return}}if(n.verb===v.open){const d=this.bindingStore.get(e.session_id);if(d?.cwd)try{await B(d.cwd)}catch{h.info("bridge",`Stale binding detected for session ${e.session_id}: ${d.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const l=this.pool.getSlot(e.session_id);l?.adapter instanceof R&&l.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(n,e),o==="acp"&&n.verb===v.stop){const l=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${l}`,updated_at:Date.now()});return}if(ne(n,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),n.verb===v.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const d=this.bindingStore.get(e.session_id)?.cwd??"";d&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:d,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let r;try{r=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(d){this.sendAuditConfigurationError(e,d);return}if(oi.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const l=o;h.info(this.name,`[${l}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(l,String(e.session_id??"").trim(),this.prepareAuditedInboundEvent(e,s,r));const u=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:p.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const l=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(l){const[,u,g]=l,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(f=>f.name===u||f.name===`/${u}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const f=await m.execCommand(u,g.trim(),e.session_id);f.status==="options"&&f.data&&this.handleExecCommandOptions(e.session_id,u,f.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:f.status==="failed"?"failed":"responded",msg:f.message,updated_at:Date.now()})}catch(f){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f instanceof Error?f.message:String(f),updated_at:Date.now()})}return}}}if(o==="codex"&&Z(r?.options)){const d=this.pool.getSlot(e.session_id);if(d?.adapter instanceof V&&!d.adapter.hasRawApiCaptureRelay()){const l=d.eventQueue.snapshot(e.session_id);l.running.length===0&&l.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${l.running.length} queued=${l.queued.length}`)}}const c=this.prepareAuditedInboundEvent(e,s,r);try{this.captureEventRuntimeConfig(c),await this.pool.deliverInboundEvent(c)}catch(d){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",d instanceof Error?d.message:String(d),{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),d instanceof wt)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:d.message,updated_at:Date.now()});else throw d}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),n("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{c=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleSessionControlForPool(e,o){e.verb===v.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==C.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==v.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{const d=await this.resolveCwdForBinding(a.cwd);if(d===r){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}}catch{c=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{const d=await this.resolveCwdForBinding(a.cwd);if(d===r){this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,d),await this.bindSessionForPool(t,d),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:d,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}}catch{c=!0,h.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),n("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:o.msg_id});return}}catch{c=!0,h.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t).catch(c=>{h.warn("bridge",`pi ensureSlotStarted on bind failed (non-fatal): ${c instanceof Error?c.message:String(c)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:o.msg_id})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:p.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,p.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}syncOpenCodeBinding(e,o){if(!e||!o)return;const t=this.pool.getSlot(e);t?.adapter instanceof Y&&t.adapter.bindSession(e,o)}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof R?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{const s=await this.resolveCwdForBinding(e.args.trim());await this.handleSessionControlForPool(e,o),this.syncOpenCodeBinding(o.session_id,s),ne(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){const c=await this.resolveCwdForBinding(a.cwd);if(c!==r){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===A.approval?A.approval:A.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",r={};if(o==="model"){r.available_models=s.map(c=>({id:c.id,displayName:c.label}));const a=s.find(c=>c.current);a&&(r.model_id=a.id)}else if(o==="mode"){r.available_modes=s.map(c=>({id:c.id,displayName:c.label}));const a=s.find(c=>c.current);a&&(r.mode_id=a.id)}else r[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:r})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;if(this.bindingStore.getCodexThreadId(e))return;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}resolveCodexNewSessionGlobalDefault(e,o,t){const s=String(o??"").trim();if(s&&!this.bindingStore.getCodexThreadId(e))return t(s),s}buildCursorToolbarMeta(e){const o=this.pool.getSlot(e);if(o?.adapter instanceof I)return o.adapter.getToolbarMeta(e);const t=this.bindingStore.getModelId(e)??"auto",s=this.bindingStore.getCursorModeId(e)??"full_auto";return{model_id:t,mode_id:s,currentModelId:t,currentModeId:s,available_models:[],available_modes:be.map(i=>({...i}))}}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=Ce(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(r=>r.id===i)&&(i=s);const n=Ae();return{model_id:i,currentModelId:i,available_models:t.map(r=>({id:r.id,displayName:r.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),await ke().catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=U(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),r={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},a=this.pool.getSlot(e),c=a?.adapter instanceof L?a.adapter.getSessionState():null;(c?.rateLimits?.fiveHour||c?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=c);const d=c??this.getFreshClaudeRateLimitState();if(d){const l=d.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(r.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:d.sampledAt||Date.now()})}if(c){const l=c.contextWindow;l.usedPercentage!=null&&(r.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!r.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(r.rate_limits=l),h.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return r.rate_limits&&h.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(r.rate_limits)}`),r}providerQuotaToCodexRateLimits(e){return ce(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return de(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=p.invalidCwd,i}const t=$.resolve(o);let s;try{s=await B(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=p.invalidCwd,r}if(n==="EACCES"||n==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=p.invalidCwd,r}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=p.invalidCwd,i}try{return await ge(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillUploadLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const i=H(this.config.adapterType,this.config.aibot.clientType),n=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0,r=i==="kiro"?n:n||process.cwd();try{await xe(t,{mode:i,projectDir:r},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(a){h.warn(this.name,`skill_upload failed name=${t}: ${a instanceof Error?a.message:String(a)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:a instanceof Error?a.message:String(a)})}}async handleSkillEnableLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim(),i=String(o.scope??"").trim(),n=String(o.actor_id??"").trim(),r=o.force==="replace_link"||o.force==="replace_with_link"?o.force:void 0,a=H(this.config.adapterType,this.config.aibot.clientType),c=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const d=await Me({skillsDir:y.skills,mode:a,home:q(),cwd:c},{name:t,scope:i,actorId:n,force:r});h.info(this.name,`skill_enable name=${t} scope=${i} actor=${n||"-"} changed=${d.changed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:d.name,scope:d.scope,path:d.path,changed:d.changed,enable_state:d.status,uninstallable:!0}})}catch(d){const l=d instanceof te?d.code:"SKILL_ENABLE_FAILED";h.warn(this.name,`skill_enable failed name=${t} scope=${i}: ${d instanceof Error?d.message:String(d)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:l,error_msg:d instanceof Error?d.message:String(d),result:{conflict_kind:l==="CONFLICT"||l==="NEEDS_FORCE"||l==="BLOCKED"?l.toLowerCase():void 0}})}this.forceRefreshSkills()}handleSkillRefreshLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim();if(this.forceRefreshSkills(t||void 0)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{session_id:t||void 0}});return}h.warn(this.name,`skill_refresh produced no report session=${t||"-"}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_REFRESH_FAILED",error_msg:"skill rescan produced no report (scan error or empty skill set)"})}async handleSkillDisableLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim(),i=String(o.scope??"").trim(),n=String(o.actor_id??"").trim(),r=H(this.config.adapterType,this.config.aibot.clientType),a=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const c=await Ie({skillsDir:y.skills,mode:r,home:q(),cwd:a},{name:t,scope:i,actorId:n});h.info(this.name,`skill_disable name=${t} scope=${i} actor=${n||"-"} removed=${c.removed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:c.name,scope:c.scope,path:c.path,removed:c.removed,enable_state:"none",uninstallable:!1}})}catch(c){const d=c instanceof te?c.code:"SKILL_DISABLE_FAILED";h.warn(this.name,`skill_disable failed name=${t} scope=${i}: ${c instanceof Error?c.message:String(c)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:d,error_msg:c instanceof Error?c.message:String(c),result:{conflict_kind:d==="CONFLICT"||d==="BLOCKED"?d.toLowerCase():void 0}})}this.forceRefreshSkills()}computeSkillReport(e){const o=H(this.config.adapterType,this.config.aibot.clientType),t=o==="kiro"?e:e||process.cwd();let s;try{s=Le({mode:o,projectDir:t})}catch{return null}if(s.length===0)return null;const i=JSON.stringify(s.map(n=>`${n.source}:${n.name}`));return{skills:ee(s,y.skills),hash:i}}reportSessionSkills(e){const o=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,t=this.computeSkillReport(o);if(t&&t.hash!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=t.hash;try{this.aibotHandle.sendSkillsUpdate({skills:t.skills,library_skills:this.buildLibrarySkillsReport(o)})}catch{}}}forceRefreshSkills(e){const o=e?.trim(),t=o||this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0}),s=o?this.bindingStore.get(o)?.cwd||this.sessionBindings.get(o)||void 0:t?this.bindingStore.get(t)?.cwd:void 0,i=this.computeSkillReport(s);if(!i)return!1;this.lastReportedSkillsHash=i.hash;try{return this.aibotHandle.sendSkillsUpdate({skills:i.skills,library_skills:this.buildLibrarySkillsReport(s)}),!0}catch{return!1}}buildLibrarySkillsReport(e){const o=H(this.config.adapterType,this.config.aibot.clientType);return He({skillsDir:y.skills,mode:o,home:q(),cwd:e})}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(h.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),h.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const o=Ze(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(t=>t.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=$.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(c=>c.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":n==="cursor"?i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??""),!i){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){i=a.cwd??"";break}}if(!i){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=p.invalidAgentSession,a}const r=this.normalizePathForCompare(i);if(r&&s&&r!==s){const a=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw a.sessionControlErrorCode=p.invalidAgentSession,a}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d){const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(d,{aibotSessionId:a,workerStatus:u})}}const n=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.threadId);const d=i.get(c.threadId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.threadId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??(c.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(c.createdAt).toISOString()}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionPath);const d=i.get(c.sessionPath);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionPath}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="opencode"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d&&r.has(d))continue;const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"closed",g=this.resolveOrphanTitle(d)??(d?d.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026");n.push(` Title: ${g}`),n.push(` AIBot: ${a}`),d&&n.push(` Agent: ${d}`),n.push(` CWD: ${c.cwd??"-"}`),n.push(` State: ${u}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(a=>a==="---").length}):
13
+ Error: ${t}`,1,!1),this.surfacedRunErrorEvents.add(e))}sendEventResultWithCleanup(e,o,t,s){const i=this.eventSessionIndex.get(e);o==="failed"&&i&&t?.trim()&&this.sendRunErrorAsChunk(e,i,t),this.auditController.markResponded(e,o,t),this.sendCtrl.sendEventResult(e,o,t,s),i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){h.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const r=this.config.adapterType??"acp";if(n>G){h.error(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${n}/${G} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${n}/${G} outcome=restarting err=${s}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&h.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){h.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=this.resolveRecoveryPrompt(r,i),d={...i,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){h.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(l.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.auditController.captureUnsequencedStreamChunk(e,t),this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.deliverRawEventEnvelope(e,o,t,"acp",this.buildAcpRawEventFallbackText(t))}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,o,t,s,i){const n=Ot({envelope:t,fallbackText:i,channelKey:s,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:n.fallbackText,extra:{channel_data:{[s]:{raw_event:n.envelope}},agent_api_origin:!0}})};if(!n.sharded){r();return}h.info("bridge",`${s} raw_event oversized, sharded delivery: event=${e} fields=${n.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of n.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,o,Ut({envelopeType:t.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{h.warn("bridge",`${s} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const o=String(e?.type??"").trim(),t=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(o){case"permission_request":return`Permission required: ${String(t.tool_title??t.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(t.tool_name??t.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(t.message??"agent error")}`;default:return o?`[cursor] ${o}`:"[cursor] event"}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=It(e.extra);if(t.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:t.error,updated_at:Date.now()});return}const s=t.patch,i=Xt(e.extra);if((i.state!=="absent"||i.error)&&h.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${i.state??"error"} scope=${i.options?.enabled?i.options.scope:""} error=${i.error??""}`),i.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:i.error,updated_at:Date.now()});return}if(i.state==="enabled"&&o!=="claude"&&o!=="codex"&&o!=="cursor"&&o!=="opencode"&&o!=="pi"&&o!=="codewhale"&&o!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${o}`,updated_at:Date.now()}),i.options?.enabled&&i.options.scope==="turn")try{this.aibotHandle.sendAuditState(z({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${o}`},Date.now()))}catch{}return}const n=Ct(e);if(n){if(i.state!=="absent"||n.verb===v.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(d){this.sendAuditConfigurationError(e,d);return}if(n.verb===v.exec){await this.handleSessionControlCommand(n,e);return}if(n.verb===v.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(n,e);return}if(o==="codex"&&n.verb===v.open){await this.handleCodexSessionControlOpen(n,e);return}if(o==="pi"&&n.verb===v.open){await this.handlePiSessionControlOpen(n,e);return}if(o==="pi"&&n.verb===v.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&n.verb===v.open){await this.handleOpenHumanSessionControlOpen(n,e);return}if(o==="codewhale"&&n.verb===v.open){await this.handleCodeWhaleSessionControlOpen(n,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.verb===v.open){const d=n.args.trim();if(!d){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const l=$.resolve(d);if(!(await B(l)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.invalidCwd,msg:`Path is not a directory: ${l}`,updated_at:Date.now()});return}}catch(l){const u=String(l?.code??""),g=u==="ENOENT"?`Directory does not exist: ${$.resolve(d)}`:u==="EACCES"||u==="EPERM"?"Directory is not accessible":`Invalid path: ${d}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:p.invalidCwd,msg:g,updated_at:Date.now()});return}}if(n.verb===v.open){const d=this.bindingStore.get(e.session_id);if(d?.cwd)try{await B(d.cwd)}catch{h.info("bridge",`Stale binding detected for session ${e.session_id}: ${d.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const l=this.pool.getSlot(e.session_id);l?.adapter instanceof R&&l.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(n,e),o==="acp"&&n.verb===v.stop){const l=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${l}`,updated_at:Date.now()});return}if(ne(n,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),n.verb===v.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const d=this.bindingStore.get(e.session_id)?.cwd??"";d&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:d,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let r;try{r=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(d){this.sendAuditConfigurationError(e,d);return}if(oi.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const l=o;h.info(this.name,`[${l}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(l,String(e.session_id??"").trim(),this.prepareAuditedInboundEvent(e,s,r));const u=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:p.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const l=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(l){const[,u,g]=l,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(f=>f.name===u||f.name===`/${u}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const f=await m.execCommand(u,g.trim(),e.session_id);f.status==="options"&&f.data&&this.handleExecCommandOptions(e.session_id,u,f.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:f.status==="failed"?"failed":"responded",msg:f.message,updated_at:Date.now()})}catch(f){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f instanceof Error?f.message:String(f),updated_at:Date.now()})}return}}}if(o==="codex"&&Z(r?.options)){const d=this.pool.getSlot(e.session_id);if(d?.adapter instanceof V&&!d.adapter.hasRawApiCaptureRelay()){const l=d.eventQueue.snapshot(e.session_id);l.running.length===0&&l.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${l.running.length} queued=${l.queued.length}`)}}const c=this.prepareAuditedInboundEvent(e,s,r);try{this.captureEventRuntimeConfig(c),await this.pool.deliverInboundEvent(c)}catch(d){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",d instanceof Error?d.message:String(d),{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),d instanceof wt)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:d.message,updated_at:Date.now()});else throw d}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),n("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{c=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleSessionControlForPool(e,o){e.verb===v.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==C.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==v.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{const d=await this.resolveCwdForBinding(a.cwd);if(d===r){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}}catch{c=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{const d=await this.resolveCwdForBinding(a.cwd);if(d===r){this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,d),await this.bindSessionForPool(t,d),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:d,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}}catch{c=!0,h.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let c=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),n("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:o.msg_id});return}}catch{c=!0,h.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!c){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t).catch(c=>{h.warn("bridge",`pi ensureSlotStarted on bind failed (non-fatal): ${c instanceof Error?c.message:String(c)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:o.msg_id})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:p.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,p.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}syncOpenCodeBinding(e,o){if(!e||!o)return;const t=this.pool.getSlot(e);t?.adapter instanceof Y&&t.adapter.bindSession(e,o)}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof R?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{const s=await this.resolveCwdForBinding(e.args.trim());await this.handleSessionControlForPool(e,o),this.syncOpenCodeBinding(o.session_id,s),ne(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:p.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){i(),n("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:p.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),n("responded",{msg:`Session bound to ${r}`})}catch(r){i(),n("failed",{code:p.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(r,a,c,d)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...c?{error_code:c}:{},...d?{error_msg:d}:{}})};if(!t||!s){n("failed",void 0,p.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){const c=await this.resolveCwdForBinding(a.cwd);if(c!==r){n("failed",void 0,p.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){n("failed",void 0,r?.sessionControlErrorCode??p.invalidCwd,r instanceof Error?r.message:String(r))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===A.approval?A.approval:A.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",r={};if(o==="model"){r.available_models=s.map(c=>({id:c.id,displayName:c.label}));const a=s.find(c=>c.current);a&&(r.model_id=a.id)}else if(o==="mode"){r.available_modes=s.map(c=>({id:c.id,displayName:c.label}));const a=s.find(c=>c.current);a&&(r.mode_id=a.id)}else r[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:r})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;if(this.bindingStore.getCodexThreadId(e))return;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}resolveCodexNewSessionGlobalDefault(e,o,t){const s=String(o??"").trim();if(s&&!this.bindingStore.getCodexThreadId(e))return t(s),s}buildCursorToolbarMeta(e){const o=this.pool.getSlot(e);if(o?.adapter instanceof I)return o.adapter.getToolbarMeta(e);const t=this.bindingStore.getModelId(e)??"auto",s=this.bindingStore.getCursorModeId(e)??"full_auto";return{model_id:t,mode_id:s,currentModelId:t,currentModeId:s,available_models:[],available_modes:be.map(i=>({...i}))}}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=Ce(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(r=>r.id===i)&&(i=s);const n=Ae();return{model_id:i,currentModelId:i,available_models:t.map(r=>({id:r.id,displayName:r.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),await ke().catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=U(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),r={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},a=this.pool.getSlot(e),c=a?.adapter instanceof L?a.adapter.getSessionState():null;(c?.rateLimits?.fiveHour||c?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=c);const d=c??this.getFreshClaudeRateLimitState();if(d){const l=d.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(r.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:d.sampledAt||Date.now()})}if(c){const l=c.contextWindow;l.usedPercentage!=null&&(r.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!r.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(r.rate_limits=l),h.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return r.rate_limits&&h.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(r.rate_limits)}`),r}providerQuotaToCodexRateLimits(e){return ce(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return de(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=p.invalidCwd,i}const t=$.resolve(o);let s;try{s=await B(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=p.invalidCwd,r}if(n==="EACCES"||n==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=p.invalidCwd,r}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=p.invalidCwd,i}try{return await ge(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillUploadLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const i=H(this.config.adapterType,this.config.aibot.clientType),n=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0,r=i==="kiro"?n:n||process.cwd();try{await xe(t,{mode:i,projectDir:r},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(a){h.warn(this.name,`skill_upload failed name=${t}: ${a instanceof Error?a.message:String(a)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:a instanceof Error?a.message:String(a)})}}async handleSkillEnableLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim(),i=String(o.scope??"").trim(),n=String(o.actor_id??"").trim(),r=o.force==="replace_link"||o.force==="replace_with_link"?o.force:void 0,a=H(this.config.adapterType,this.config.aibot.clientType),c=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const d=await Me({skillsDir:y.skills,mode:a,home:q(),cwd:c},{name:t,scope:i,actorId:n,force:r});h.info(this.name,`skill_enable name=${t} scope=${i} actor=${n||"-"} changed=${d.changed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:d.name,scope:d.scope,path:d.path,changed:d.changed,enable_state:d.status,uninstallable:!0}})}catch(d){const l=d instanceof te?d.code:"SKILL_ENABLE_FAILED";h.warn(this.name,`skill_enable failed name=${t} scope=${i}: ${d instanceof Error?d.message:String(d)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:l,error_msg:d instanceof Error?d.message:String(d),result:{conflict_kind:l==="CONFLICT"||l==="NEEDS_FORCE"||l==="BLOCKED"?l.toLowerCase():void 0}})}this.forceRefreshSkills()}handleSkillRefreshLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim();if(this.forceRefreshSkills(t||void 0)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{session_id:t||void 0}});return}h.warn(this.name,`skill_refresh produced no report session=${t||"-"}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_REFRESH_FAILED",error_msg:"skill rescan produced no report (scan error or empty skill set)"})}async handleSkillDisableLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim(),i=String(o.scope??"").trim(),n=String(o.actor_id??"").trim(),r=H(this.config.adapterType,this.config.aibot.clientType),a=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const c=await Ie({skillsDir:y.skills,mode:r,home:q(),cwd:a},{name:t,scope:i,actorId:n});h.info(this.name,`skill_disable name=${t} scope=${i} actor=${n||"-"} removed=${c.removed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:c.name,scope:c.scope,path:c.path,removed:c.removed,enable_state:"none",uninstallable:!1}})}catch(c){const d=c instanceof te?c.code:"SKILL_DISABLE_FAILED";h.warn(this.name,`skill_disable failed name=${t} scope=${i}: ${c instanceof Error?c.message:String(c)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:d,error_msg:c instanceof Error?c.message:String(c),result:{conflict_kind:d==="CONFLICT"||d==="BLOCKED"?d.toLowerCase():void 0}})}this.forceRefreshSkills()}computeSkillReport(e){const o=H(this.config.adapterType,this.config.aibot.clientType),t=o==="kiro"?e:e||process.cwd();let s;try{s=Le({mode:o,projectDir:t})}catch{return null}if(s.length===0)return null;const i=JSON.stringify(s.map(n=>`${n.source}:${n.name}`));return{skills:ee(s,y.skills),hash:i}}reportSessionSkills(e){const o=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,t=this.computeSkillReport(o);if(t&&t.hash!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=t.hash;try{this.aibotHandle.sendSkillsUpdate({skills:t.skills,library_skills:this.buildLibrarySkillsReport(o)})}catch{}}}forceRefreshSkills(e){const o=e?.trim(),t=o||this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0}),s=o?this.bindingStore.get(o)?.cwd||this.sessionBindings.get(o)||void 0:t?this.bindingStore.get(t)?.cwd:void 0,i=this.computeSkillReport(s);if(!i)return!1;this.lastReportedSkillsHash=i.hash;try{return this.aibotHandle.sendSkillsUpdate({skills:i.skills,library_skills:this.buildLibrarySkillsReport(s)}),!0}catch{return!1}}buildLibrarySkillsReport(e){const o=H(this.config.adapterType,this.config.aibot.clientType);return He({skillsDir:y.skills,mode:o,home:q(),cwd:e})}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(h.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),h.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const o=Ze(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(t=>t.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=$.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(c=>c.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":n==="cursor"?i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??""),!i){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){i=a.cwd??"";break}}if(!i){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=p.invalidAgentSession,a}const r=this.normalizePathForCompare(i);if(r&&s&&r!==s){const a=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw a.sessionControlErrorCode=p.invalidAgentSession,a}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d){const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(d,{aibotSessionId:a,workerStatus:u})}}const n=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.threadId);const d=i.get(c.threadId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.threadId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??(c.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(c.createdAt).toISOString()}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionPath);const d=i.get(c.sessionPath);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionPath}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="opencode"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId);c.title&&n.push(` Title: ${c.title}`),n.push(` Agent: ${c.sessionId}`),d&&n.push(` AIBot: ${d.aibotSessionId}`),n.push(` CWD: ${c.cwd||"-"}`),n.push(` State: ${d?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}}for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d&&r.has(d))continue;const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"closed",g=this.resolveOrphanTitle(d)??(d?d.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026");n.push(` Title: ${g}`),n.push(` AIBot: ${a}`),d&&n.push(` Agent: ${d}`),n.push(` CWD: ${c.cwd??"-"}`),n.push(` State: ${u}`),n.push(` Updated: ${new Date(c.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(a=>a==="---").length}):
14
14
  ${n.join(`
15
15
  `)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d){const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(d,{aibotSessionId:a,workerStatus:u,bindingUpdatedAt:c.updatedAt??0})}}const n=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.threadId);const d=i.get(c.threadId),l={agentSessionId:c.threadId,cwd:c.cwd||null,workerStatus:d?.workerStatus??(c.archived?"archived":"inactive"),createdAt:c.createdAt,updatedAt:c.updatedAt,archived:c.archived};d&&(l.aibotSessionId=d.aibotSessionId),c.title&&(l.title=c.title),n.push(l)}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId),l={agentSessionId:c.sessionId,cwd:c.cwd||null,workerStatus:d?.workerStatus??"inactive",updatedAt:c.updatedAt};d&&(l.aibotSessionId=d.aibotSessionId),c.title&&(l.title=c.title),n.push(l)}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const c of a){r.add(c.sessionId);const d=i.get(c.sessionId),l=d&&d.bindingUpdatedAt>0?d.bindingUpdatedAt:c.updatedAt,u={agentSessionId:c.sessionId,cwd:c.cwd||null,agentType:c.agentType,workerStatus:d?.workerStatus??"inactive",updatedAt:l};d&&(u.aibotSessionId=d.aibotSessionId),c.title&&(u.title=c.title),c.createdAt&&(u.createdAt=c.createdAt),n.push(u)}}else if(o==="pi"||o==="codewhale"||o==="opencode"){const a=this.sessionScanCache.get();for(const c of a){const d="sessionPath"in c?c.sessionPath:c.sessionId;r.add(d);const l=i.get(d),u={agentSessionId:d,cwd:c.cwd||null,workerStatus:l?.workerStatus??("archived"in c&&c.archived?"archived":"inactive"),updatedAt:l&&l.bindingUpdatedAt>0?l.bindingUpdatedAt:c.updatedAt};l&&(u.aibotSessionId=l.aibotSessionId),c.title&&(u.title=c.title),c.createdAt&&(u.createdAt=c.createdAt),"archived"in c&&(u.archived=c.archived),n.push(u)}}for(const[a,c]of s){const d=this.resolveAgentSessionId(c);if(d&&r.has(d))continue;const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"closed",g={aibotSessionId:a,cwd:c.cwd??null,workerStatus:u,updatedAt:c.updatedAt,title:this.resolveOrphanTitle(d)??(d?`${d.slice(0,8)}\u2026`:`${a.slice(0,8)}\u2026`)};d&&(g.agentSessionId=d),n.push(g)}n.sort((a,c)=>c.updatedAt-a.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:n,total:n.length}})}async handleSessionControlCommand(e,o){const t=o.session_id,s=(i,n,r)=>{this.aibotHandle.sendEventResult({event_id:o.event_id,status:i,...n?{msg:n}:{},...r?{code:r}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case v.open:{await O().catch(()=>{});const i=e.args.trim();if(!i){s("failed","Usage: /grix open <working-directory>",p.cwdRequired);return}let n="";try{n=await this.resolveCwdForBinding(i)}catch(a){s("failed",a instanceof Error?a.message:String(a),p.invalidCwd);return}const r=this.bindingStore.get(t);if(r?.cwd){const a=await this.resolveCwdForBinding(r.cwd);if(a!==n){s("failed","session binding cannot be changed to another working directory",p.rebindForbidden);return}this.bindingStore.ensureModeId(t,A.fullAuto),this.sessionBindings.set(t,a),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,a),s("responded",`Working directory already bound: ${a}`);return}this.bindingStore.set(t,n,{modeId:A.fullAuto}),this.sessionBindings.set(t,n),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,n),s("responded",`Session bound to ${n}`);return}case v.where:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",p.bindingMissing);return}s("responded",`Working directory: ${i.cwd}`);return}case v.status:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",p.bindingMissing);return}const n=this.normalizeClaudeModeId(i.modeId),r=this.getClaudeWorkerStatus(t);s("responded",`Status: worker=${r} mode=${n} cwd=${i.cwd}`);return}case v.stop:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",p.bindingMissing);return}await this.pool.removeSlot(t),this.claudeWorkerStatus.set(t,"stopped"),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)}),s("responded",`Session worker stopped for ${i.cwd}`);return}case v.restart:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",p.bindingMissing);return}await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,i.cwd),s("responded",`Session worker restarted for ${i.cwd}`);return}case v.setMode:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_mode <mode-id>",x.modeInvalid);return}const n=this.normalizeClaudeModeId(i);if(n!==i.toLowerCase()){s("failed","set mode_id is invalid",x.modeInvalid);return}const r=this.bindingStore.get(t);if(!r?.cwd){s("failed","session binding was not found",p.bindingMissing);return}if(this.normalizeClaudeModeId(r.modeId)===n){s("responded",`Mode unchanged: ${n}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F",p.workerBusy);return}this.bindingStore.setModeId(t,n),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,r.cwd),s("responded",`Mode set to ${n}`);return}case v.setModel:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_model <model-id>");return}const n=this.bindingStore.get(t);if(!n?.cwd){s("failed","session binding was not found",p.bindingMissing);return}if((n.modelId??"")===i){s("responded",`Model unchanged: ${i}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B",p.workerBusy);return}this.bindingStore.setModelId(t,i),this.globalConfigStore?.set(this.name,{modelId:i}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,n.cwd),this.refreshQuotaAfterModelSwitch(t,i),s("responded",`Model set to ${i}`);return}case v.listOptions:{const i=U(),n=this.bindingStore.get(t),r=i.map(c=>c.id).join(", "),a=`${A.fullAuto}, ${A.approval}`;s("responded",`Modes (current: ${this.normalizeClaudeModeId(n?.modeId)}): ${a}
16
16
  Models (current: ${n?.modelId??"default"}): ${r}`);return}case v.exec:{const[i,...n]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",p.verbInvalid);return}const a=this.pool.getSlot(t)?.adapter;if(!a?.execCommand){s("failed","Agent does not support command execution",p.verbInvalid);return}const c=a.getSupportedCommands?.()??[];if(!c.some(d=>d.name===i)){s("failed",`Unknown command: ${i}. Supported: ${c.map(d=>d.name).join(", ")}`,p.verbInvalid);return}try{const d=await a.execCommand(i,n.join(" "),t);s(d.status==="ok"?"responded":"failed",d.message??`${i} ${d.status}`,d.status==="ok"?void 0:p.runtimeError)}catch(d){s("failed",`exec error: ${d instanceof Error?d.message:d}`,p.runtimeError)}return}default:s("failed",`Unsupported command for Claude: /grix ${e.verb}`,p.verbInvalid)}}catch(i){s("failed",i instanceof Error?i.message:String(i),p.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==C.sessionControl&&o!==C.setMode&&o!=="set_mode"&&o!==C.setModel&&o!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=o===C.setMode?v.setMode:o===C.setModel?v.setModel:String(t.verb??"").trim().toLowerCase();if(h.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${s}`),!s)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:x.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const n=a=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a})},r=(a,c)=>{h.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${a} msg=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:a,error_msg:c})};try{switch(i){case v.open:{await O().catch(()=>{});const a=String(t.cwd??"").trim(),c=String(t.agent_session_id??"").trim();if(!a)return r(p.cwdRequired,"session control cwd is required"),!0;h.info(this.name,`handleSessionControlLocalAction open cwd=${a} session_id=${s}`);const d=await this.resolveCwdForBinding(a);this.ensureImportedAgentSession(c,d);const l=this.bindingStore.get(s);if(l?.cwd){const u=await this.resolveCwdForBinding(l.cwd);return u!==d?(r(p.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,A.fullAuto),this.setResolvedAgentSessionId(s,c),this.sessionBindings.set(s,u),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,u),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,u),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,d,{modeId:A.fullAuto}),this.setResolvedAgentSessionId(s,c),this.sessionBindings.set(s,d),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,d),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,d),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case v.status:case v.where:{const a=this.bindingStore.get(s);return a?.cwd?(n({outcome:i,binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(r(p.bindingMissing,"session binding was not found"),!0)}case v.stop:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),n({outcome:"stopped",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:"stopped"}}),!0):(r(p.bindingMissing,"session binding was not found"),!0)}case v.restart:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,a.cwd),n({outcome:"restarted",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId)}}),!0):(r(p.bindingMissing,"session binding was not found"),!0)}case v.setMode:{const a=String(t.mode_id??t.modeId??"").trim();if(!a)return r(x.modeInvalid,"set mode_id is invalid"),!0;const c=this.normalizeClaudeModeId(a);if(c!==a.toLowerCase())return r(x.modeInvalid,"set mode_id is invalid"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return r(p.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(d.modeId)!==c){if(this.getClaudeWorkerStatus(s)==="busy")return r(p.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(s,c),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd)}return n({outcome:"mode_set",mode_id:c,binding:{cwd:d.cwd,mode_id:c}}),!0}case v.setModel:{const a=String(t.model_id??t.modelId??"").trim();if(!a)return r("set_model_invalid","model_id is required"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return r(p.bindingMissing,"session binding was not found"),!0;if((c.modelId??"")!==a){if(this.getClaudeWorkerStatus(s)==="busy")return r(p.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(s,a),this.globalConfigStore?.set(this.name,{modelId:a}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,c.cwd),this.refreshQuotaAfterModelSwitch(s,a)}return n({outcome:"model_set",model_id:a,binding:{cwd:c.cwd,model_id:a}}),!0}case v.listOptions:{const a=U(),c=this.pool.getSlot(s);return n({modes:[A.fullAuto,A.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:a.map(d=>({modelId:d.id,name:d.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:a.map(d=>({id:d.id,displayName:d.displayName})),agent_commands:c?.adapter?.getSupportedCommands?.()??[]}),!0}case v.exec:{const[a,...c]=String(t.args??"").trim().split(/\s+/);if(!a)return r(p.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return r(p.verbInvalid,"Agent does not support command execution"),!0;const u=l.getSupportedCommands?.()??[];if(!u.some(g=>g.name===a))return r(p.verbInvalid,`Unknown command: ${a}. Supported: ${u.map(g=>g.name).join(", ")}`),!0;try{const g=await l.execCommand(a,c.join(" "),s);g.status==="ok"?n({outcome:"exec",command:a,message:g.message,data:g.data}):r(p.runtimeError,g.message??`${a} failed`)}catch(g){r(p.runtimeError,`exec error: ${g instanceof Error?g.message:g}`)}return!0}default:return r(p.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(a){const c=a instanceof Error&&a.cwdErrorCode?a.cwdErrorCode:a instanceof Error&&a.sessionControlErrorCode?a.sessionControlErrorCode:p.runtimeError;return h.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${a instanceof Error?a.message:a}`),r(c,a instanceof Error?a.message:String(a)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(h.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(s=>{const i=this.pool.getSlot(o);if(!i?.adapter){s();return}const n=setTimeout(()=>{i.adapter.removeListener("eventDone",r),s()},t),r=a=>{a===e&&(clearTimeout(n),i.adapter.removeListener("eventDone",r),s())};i.adapter.on("eventDone",r)})}handleAibotStop(e){const o=e.event_id?.trim()??"",t=e.scope?.trim()??"";h.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${o||"-"} scope=${t||"event"} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`);const s=this.pool.getSlot(e.session_id),i=s?.adapter?.getStatus().busy??!1;let n=!1,r=[];if(s?.adapter)try{r=[...new Set(s.adapter.getActiveEventIds().map(m=>m.trim()).filter(Boolean))]}catch(m){n=!0,h.warn(this.name,`[stop-trace] handleAibotStop active event probe failed session=${e.session_id}: ${m}`)}const a=t==="session";let c=a?"":o;const d=m=>({stop_id:e.stop_id,...m?{event_id:m}:{},...e.terminal_commit_token?{terminal_commit_token:e.terminal_commit_token}:{},session_id:e.session_id,...t?{scope:t}:{}}),l=m=>{!m||!e.terminal_commit_token?.trim()||this.sendEventResultWithCleanup(m,"canceled","stopped by owner","event_stopped")};if(a)if(!n&&r.length===1)[c]=r;else if(!n&&r.length===0&&!i){this.aibotHandle.sendEventStopAck({...d(""),accepted:!0,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...d(""),status:"already_finished",updated_at:Date.now()}),h.info(this.name,`[stop-trace] handleAibotStop session idle -> stopResult(already_finished) session=${e.session_id} stop_id=${e.stop_id||"-"}`);return}else{const m=n?"session_stop_target_unavailable":r.length>1?"session_stop_target_ambiguous":"session_stop_target_unresolved",b=n?"failed to inspect active events for session stop":r.length>1?"multiple active events prevent a safe session stop":"adapter is busy but no active event can be identified";this.aibotHandle.sendEventStopAck({...d(""),accepted:!1,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...d(""),status:"failed",code:m,msg:b,updated_at:Date.now()}),h.warn(this.name,`[stop-trace] handleAibotStop session target unsafe -> stopResult(failed) session=${e.session_id} activeIds=[${r.join(",")}] busy=${i} code=${m}`);return}if(this.aibotHandle.sendEventStopAck({...d(c),accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,c)){h.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${c} stop_id=${e.stop_id||"-"}`),e.terminal_commit_token?.trim()?l(c):this.discardEventTrackingState(c),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({...d(c),status:"stopped",updated_at:Date.now()});return}const u=(this.config.adapterType??"acp")==="acp",g=r.length>0?r.includes(c):i,_=(u||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&g;if(h.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${c} scope=${t||"event"} slotExists=${!!s?.adapter} busy=${i} activeIds=[${r.join(",")}] stoppingActiveEvent=${g} killOnStop=${_}`),g&&this.sendCtrl.markEventStopped(c),s?.adapter&&i){const m=_?this.pool.drainQueuedForSession(e.session_id):[];let b=!1,f=null;const S=k=>{b||(b=!0,f&&(clearTimeout(f),f=null),s.adapter.removeListener("eventDone",w),h.info(this.name,`[stop-trace] handleAibotStop ${k} -> stopResult(stopped) session=${e.session_id} event=${c} stop_id=${e.stop_id||"-"} killOnStop=${_}`),l(c),this.aibotHandle.sendEventStopResult({...d(c),status:"stopped",updated_at:Date.now()}),_&&this.killAndResumeStopSlot(e.session_id,m))},w=k=>{k===c&&S("eventDone")};s.adapter.on("eventDone",w),f=setTimeout(()=>S("timeout"),si),this.pool.deliverStopEvent(c,e.session_id)}else h.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${c} slotExists=${!!s?.adapter}`),this.pool.deliverStopEvent(c,e.session_id),l(c),this.aibotHandle.sendEventStopResult({...d(c),status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:c,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){h.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),h.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){h.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){h.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${s instanceof Error?s.message:String(s)}`),this.sendEventResultWithCleanup(t.event_id,"failed",s instanceof Error?s.message:String(s))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),s=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),n=typeof o.provider_id=="string"&&o.provider_id.trim().toLowerCase()||void 0,r=typeof o.quota_base_url=="string"&&o.quota_base_url.trim()||void 0,a=typeof o.model=="string"&&o.model.trim()||void 0;let c=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const d=this.config.adapterType??"acp",l=d==="claude"||d==="codex";try{if(l){const u=d==="claude"?s:i;if(!u){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${d==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const g=qe();if(!g){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const _=Fe(d),m=Oe(d,u,t,{model:a});g.setRoute(m);for(const b of _)g.setHostDefaultRoute(b,m.routeKey);await g.setAgentRelayEnabled(this.name,!0,{relayHosts:_}),c=!await this.recycleAdaptersForRelayChange()}else{if(!this.providerConfigHandler){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:`client type "${d}" does not support Grix relay provider config`});return}const u=this.config.aibot.clientType,g=ie(u),_=g?s:i;if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${g?"anthropic_base_url":"openai_base_url"} is required`});return}if(g&&!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_MODEL",error_msg:'model is required for client type "kiro"'});return}await this.providerConfigHandler({...n?{provider_id:n}:{},base_url:_||void 0,...r?{quota_base_url:r}:{},api_key:t,model:a})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:c}})}catch(u){h.error(this.name,`handleConfigureGatewayProvider failed: ${u}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:u instanceof Error?u.message:String(u)})}}getAuditLocalActionHandler(){if(!this.auditLocalActionHandler){const e=new Te({rootDir:$e()});this.auditLocalActionHandler=new Re(new ye(e))}return this.auditLocalActionHandler}async handleAuditLocalAction(e){const o=await this.getAuditLocalActionHandler().handle(e.action_type,e.params);if(o.status==="ok"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:o.result});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:o.errorCode,error_msg:o.errorMsg})}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();if(h.debug(this.name,`local_action received action_type=${o} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`),Ee(o)){await this.handleAuditLocalAction(e);return}const i=(this.config.adapterType??"acp")==="claude";if(o===C.sessionControl&&s===v.exec&&await this.handleSessionControlLocalAction(e))return;if(o===C.sessionControl&&s===v.listSessions){await this.handleListSessionsLocalAction(e);return}if(o==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(o==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(o==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(o==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}if(i&&(o===C.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===C.sessionControl){const d=this.config.adapterType??"acp",l=d==="codex",u=d==="pi",g=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&g===v.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(d==="cursor"&&g===v.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&g==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(u&&g===v.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),k=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(k,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,k),this.sessionBindings.set(t,w),await this.ensureSlotStarted(t).catch(Q=>{h.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${Q instanceof Error?Q.message:String(Q)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??p.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(u&&g===v.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((d==="openhuman"||d==="opencode")&&g===v.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),k=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(k,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,k),this.sessionBindings.set(t,w),this.syncOpenCodeBinding(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??p.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(d==="codewhale"&&g===v.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(d==="acp"&&g===v.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(g===v.open){const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.cwdRequired,error_msg:"session cwd is required"});return}const w=String(f.agent_session_id??"").trim();if(w){const k=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,k)}}await this.handleSessionControlLocalActionForPool(e)}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??p.runtimeError,error_msg:f instanceof Error?f.message:String(f)});return}if(g===v.open){const f=e.params??{},S=await this.resolveCwdForBinding(String(f.cwd??"").trim());this.setResolvedAgentSessionId(t,String(f.agent_session_id??"").trim()),d==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else At(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const d=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,u=e.params??{},g=String(u.parent_id??"").trim(),_=Array.isArray(u.allowed_extensions)?u.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];h.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${g||"<root>"} show_hidden=${!!u.show_hidden} ext_count=${_.length} bound_cwd=${l??"<none>"}`);const m=await yt({parent_id:g||null,session_id:t,show_hidden:!!u.show_hidden,allowed_extensions:_},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:ae()}),b=Date.now()-d,f=m.result?.files?.length??0;h.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${m.status} elapsed=${b}ms count=${f} current_path=${m.result?.current_path??""} error_code=${m.error_code??""} error_msg=${m.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:{...m.result,machine_name:Pt()}}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o==="create_folder"){const d=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),u=String((e.params??{}).name??"").trim(),g=await $t({parent_id:l||null,name:u,session_id:t},{resolveCwd:()=>d??this.config.agent.cwd??process.cwd(),fallbackDir:ae()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:g.status,...g.result?{result:g.result}:{},...g.error_code?{error_code:g.error_code}:{},...g.error_msg?{error_msg:g.error_msg}:{}});return}if(o===C.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===C.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===C.getRateLimits){await this.handleGetRateLimits(e,t);return}const n=(this.config.adapterType??"acp")==="acp";if((i||n)&&o===C.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===C.getAgentGlobalConfig){const d=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...d?{config:d}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(o==="apply_relay_state"){await this.handleApplyRelayState(e);return}const r=this.config.adapterType??"acp",a=(r==="codex"||r==="cursor"||r==="pi"||r==="openhuman"||r==="opencode"||r==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,c=await this.pool.deliverLocalAction(e,{autoCreateSlot:a});if(c.handled){if(c.kind==="set_mode"){const d=String((e.params??{}).mode_id??"");d&&(r==="cursor"?this.bindingStore.setCursorModeId(t,d):r==="claude"?this.bindingStore.setModeId(t,d):D.has(r)?r==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:d}):this.globalConfigStore?.set(this.name,{acpInitialMode:d}))}else if(c.kind==="set_model"){const d=String((e.params??{}).model_id??"");if(d){r==="cursor"?(this.bindingStore.setModelId(t,d),this.globalConfigStore?.set(this.name,{modelId:d})):r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:d}):D.has(r)||this.globalConfigStore?.set(this.name,{modelId:d});const l=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(t,d,l)}}else if(c.kind==="set_reasoning_effort"){const d=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");d&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:d})}else if(c.kind==="set_sandbox_mode"){const d=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(d){const l=d==="default"?void 0:d;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}else if(c.kind==="set_service_tier"){const d=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(d){const l=d.toLowerCase()==="default"?void 0:d;this.globalConfigStore?.set(this.name,{codexServiceTier:l})}}return}if((r==="codex"||r==="cursor"||r==="pi"||r==="openhuman"||r==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(r==="acp"&&(o==="set_mode"||o==="set_model")){const d=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,u={bindingStore:this.bindingStore,acpAdapter:l instanceof R?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};if(o==="set_mode"){const g=String((e.params??{}).mode_id??""),_=await re(u,t,g);if(_.status==="failed")d.sendLocalActionResult(e.action_id,"failed",void 0,_.errorCode,_.errorMsg);else{const m=l instanceof R?l.buildToolbarContext(_.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,b=m?{...m,..._.result}:_.result;d.sendLocalActionResult(e.action_id,"ok",b)}}else{const g=String((e.params??{}).model_id??""),_=await oe(u,t,g);if(_.status==="failed")d.sendLocalActionResult(e.action_id,"failed",void 0,_.errorCode,_.errorMsg);else{const m=l instanceof R?l.buildToolbarContext(_.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,b=m?{...m,..._.result}:_.result;d.sendLocalActionResult(e.action_id,"ok",b),_.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(t,g)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){h.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",s=this.bindingStore.get(o),i=s?.cwd??this.config.agent.cwd??process.cwd();h.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let n=null,r,a;switch(t){case"claude":{if(r=s?.claudeSessionId,!r){h.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}h.info(this.name,`[usage] parsing claude usage: claudeSessionId=${r} cwd=${i}`),n=await Pe(r,i),a="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"agy print-mode adapter does not track token usage"});return}case"opencode":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"opencode session usage parsing is not implemented"});return}case"openhuman":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"openhuman is deprecated; session usage is not tracked"});return}case"acp":default:{if(r=s?.acpSessionId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}n=await Qe(r,i,this.config.aibot.clientType),a=t,(!a||a==="acp")&&(a="acp");break}case"codex":{if(r=s?.codexThreadId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}n=await je(r),a="codex";break}case"pi":{if(r=s?.piSessionPath,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}n=await at(r),a="pi";break}case"cursor":{const d=this.pool.getSlot(o)?.adapter;if(!(d instanceof I)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=d.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const u={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:l.total.cacheRead,cacheCreationInputTokens:l.total.cacheWrite};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{model:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const d=this.pool.getSlot(o)?.adapter;if(!(d instanceof J)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=d.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const u={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:0,cacheCreationInputTokens:0};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{model:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}}if(!n){h.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${r} adapterType=${a}`);const c=String(this.config.aibot.clientType??"").trim().toLowerCase(),l=t==="acp"&&new Set(["hermes","reasonix","kimi","copilot"]).has(c)?`${c} session usage parsing is not available`:"No usage data found for this session";this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:l});return}h.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${r} turns=${n.turns} models=${n.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:r,adapterType:a,models:n.models,total:n.total,turns:n.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.runtimeError,error_msg:"Agent does not support command execution"});return}h.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const n=await i.execCommand("compact","",o);n.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:n.message,data:n.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.runtimeError,error_msg:n.message??"compact failed"})}catch(s){h.warn(this.name,`thread_compact error session_id=${o}: ${s instanceof Error?s.message:s}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:p.runtimeError,error_msg:s instanceof Error?s.message:String(s)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(s&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const n=await K();this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),h.info(this.name,`[rate-limits] kiro quota queried: success=${n.success}`+(n.balance?` balance=${n.balance.remaining} ${n.balance.unit}`:"")+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:n}})}catch(n){h.warn(this.name,`[rate-limits] kiro quota query failed: ${n instanceof Error?n.message:String(n)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const s=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(u=>u.state==="ready"&&u.adapter);if(l&&(h.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?h.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):h.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await s;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const r=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(r&&(h.info(this.name,`[rate-limits] codex reuse existing slot: session=${r.sessionId}`),(await r.adapter.handleLocalAction?.(e))?.handled))return;const a=this.resolveRateLimitWakeSessionId(o,t);if(a){const l=await this.wakeRateLimitSlot(a,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const c=await s,d=!!c;h.info(this.name,`[rate-limits] codex no native data, providerQuota=${c?c.provider:"none"} available=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:c}});return}case"claude":{const s=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const d=i.rateLimits,l=await s;h.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!d}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let n=this.pool.getAllSlots().find(d=>d.state==="ready"&&d.adapter instanceof L)??null;if(!n){const d=this.resolveRateLimitWakeSessionId(o,t);d&&(n=await this.wakeRateLimitSlot(d,t))}h.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!n} hasAdapter=${!!n?.adapter}`);const r=n?.adapter,a=r instanceof L?r.getSessionState():null,c=await s;if(a){(a.rateLimits?.fiveHour||a.rateLimits?.sevenDay||a.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=a);const d=this.getFreshClaudeRateLimitState(),l=d?.rateLimits&&!a.rateLimits?{...a,rateLimits:d.rateLimits}:a,u=l.rateLimits;h.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!u}`+(u?` fiveHour=${u.fiveHour?.usedPercentage??"n/a"}% resetsAt=${u.fiveHour?.resetsAt??"n/a"} sevenDay=${u.sevenDay?.usedPercentage??"n/a"}% resetsAt=${u.sevenDay?.resetsAt??"n/a"}`:"")+(d?.rateLimits&&!a.rateLimits?" source=live+cached-fallback":" source=live")+(c?` providerQuota=${c.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:c}})}else h.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!r} adapterType=${r?.constructor?.name??"n/a"}`+(c?` providerQuota=${c.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:c}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter;if(i instanceof I){await i.refreshAccountRateLimits({force:!0});const r=i.getRateLimitsSnapshot(o);h.info(this.name,`[rate-limits] cursor: available=${r.available} monthly=${r.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${r.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r});return}const n=await we();h.info(this.name,`[rate-limits] cursor(no-slot): available=${n.available} monthly=${n.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${n.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:n.available,cached:!1,sampledAt:Number.isFinite(Date.parse(n.sampledAt))?Date.parse(n.sampledAt):Date.now(),rateLimits:n.rateLimits,contextWindow:null,tokenUsage:null,...n.displayMessage?{displayMessage:n.displayMessage}:{},...n.error?{error:n.error}:{}}});return}default:{const s=this.sessionProviderHints.get(o),i=this.sessionBindings.get(o)||this.bindingStore.get(o)?.cwd;if(s&&i&&!s.disabled){await this.refreshProviderQuotaForSession(o,i,!0);const a=this.sessionProviderQuotas.get(o),c=a?.quota??null;if(!c){h.info(this.name,`[rate-limits] no session provider quota available for adapterType=${t} session=${o}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}h.info(this.name,`[rate-limits] session provider quota queried: provider=${c.provider} success=${c.success}`+(c.tiers.length>0?` tiers=${c.tiers.map(d=>`${d.name}=${d.usedPercent}%`).join(",")}`:"")+(c.error?` error=${c.error}`:"")+` session=${o}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!1,sampledAt:a?.sampledAt??null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:c}});return}const n=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,r=await this.maybeQueryProviderQuota();if(!r){h.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}h.info(this.name,`[rate-limits] provider quota ${n?"cached":"queried"}: provider=${r.provider} success=${r.success}`+(r.tiers.length>0?` tiers=${r.tiers.map(a=>`${a.name}=${a.usedPercent}%`).join(",")}`:"")+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:n,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:r}});return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:o==="codex"||o==="claude"?(t&&t!==s&&h.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${s}`),null):t||null:(h.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const n=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((r,a)=>setTimeout(()=>a(new Error(`wake rate-limits slot timeout (${n}ms)`)),n))])}return h.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return h.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof R?o.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const n=this.sessionBindings;if(e&&!n.has(e)){const r=this.bindingStore.get(e);r?.cwd&&n.set(e,r.cwd)}return n},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:n=>t?t.setMode(n):Promise.resolve(!1),setModel:n=>t?t.setModel(n):Promise.resolve(!1),acpSetMode:s?(n,r)=>re(i,n,r):void 0,acpSetModel:s?(n,r)=>oe(i,n,r):void 0,getPendingApproval:n=>{const r=t?.pendingApprovalEntries.get(n);return r?{requestId:r}:void 0},deletePendingApproval:n=>t?.pendingApprovalEntries.delete(n)??!1,respondPermission:(n,r)=>(t&&t.respondToPermission(n,r),Promise.resolve()),onSessionBound:(n,r)=>{this.bindingStore.set(n,r)},onSessionUnbound:n=>{const a=this.bindingStore.get(n)?.cwd??"";this.bindingStore.delete(n),this.sessionBindings.delete(n),this.sessionProviderHints.delete(n),this.sessionProviderQuotas.delete(n),this.sessionProviderMeta.delete(n),this.claudeWorkerStatus.delete(n),this.deferredMgr.clearSession(n),this.aibotHandle.clearBindingCardMetaCache?.(n);for(const c of this.pool.drainQueuedForSession(n))this.discardEventTrackingState(c.event_id);a&&this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"stopped",cwd:a})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof X?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:n=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:n}):D.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:n})},onModelSet:n=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:n}):D.has(r)||this.globalConfigStore?.set(this.name,{modelId:n}),this.refreshQuotaAfterModelSwitch(e,n)}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...s?{error_code:s}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"?e:"acp"}sendAuditConfigurationError(e,o){const t=o instanceof Error?o.message:String(o),s=o instanceof Yt||o instanceof Jt,i=s?o.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i,msg:t,updated_at:Date.now()}),s)try{this.aibotHandle.sendAuditState(z({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:t},Date.now()))}catch{}}markAuditAdapterClosed(e,o){const s=this.pool.getSlot(o)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,s)}prepareAuditedInboundEvent(e,o,t){const s=this.buildInboundEvent(e,o),i=this.bindingStore.get(e.session_id),n=i?this.resolveAgentSessionId(i):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:t,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...n?{providerSessionId:n}:{}}});return c&&(s.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,rawProviderBody:t?.options.capture.rawProviderBody===!0}),s}buildInboundEvent(e,o){const t=Mt(this.sendCtrl.getGlobalRuntimeConfig(),o),s=Zt(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:s===void 0?void 0:JSON.stringify(s),connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const o=e.filter(t=>!kt(String(t?.content??"")));if(o.length!==0)return JSON.stringify(o)}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>ei}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}h.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:n,upgradeLog:r}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:a}=await import("../core/util/client-version.js"),c=a();r(`server rollback: ${c} -> ${o} reason=${t}`),i(c,o),await s("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:n}=await import("../core/upgrade/npm-upgrader.js");n()}catch{}const i=s instanceof Error?s.message:String(s);h.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}getRelayStateSyncer(){const e=this.relayStateApplyPorts;return!e||!this.aibotHandle||this.isSharedInstance()?null:(this.relayStateSyncer||(this.relayStateSyncer=new Ke({...e,sendSyncRequest:(o,t)=>this.aibotHandle.relayStateSyncRequest(o,t),sendCredentialRequest:(o,t)=>{const{anthropicBaseUrl:s,openaiBaseUrl:i}=se(this.aibotConfig.url);return this.aibotHandle.relayCredentialRequest({anthropic_base_url:s,openai_base_url:i,...o},t)},sendReport:o=>this.aibotHandle.sendRelayStateReport(o),log:{info:o=>h.info(this.name,o),warn:o=>h.warn(this.name,o)}})),this.relayStateSyncer)}relayStateSyncOnConnect(){const e=this.getRelayStateSyncer();e&&e.syncOnConnect().catch(o=>{h.warn(this.name,`relay state sync failed: ${o instanceof Error?o.message:String(o)}`)})}reportRelayStateLocalChange(){try{this.getRelayStateSyncer()?.reportLocalChange()}catch{}}async handleApplyRelayState(e){const o=e.params??{},t=o.enabled,s=Number(o.revision);if(typeof t!="boolean"||!Number.isFinite(s)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"INVALID_PARAMS",error_msg:"enabled (boolean) and revision (number) are required"});return}const i=this.getRelayStateSyncer();if(!i){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"RELAY_UNAVAILABLE",error_msg:"relay state sync is not available on this agent",result:{revision:s}});return}const n=await i.applyFromLocalAction({enabled:t,model:typeof o.model=="string"?o.model:void 0,revision:s});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:n.ok?"ok":"failed",result:{revision:n.revision},...n.error_code?{error_code:n.error_code}:{},...n.error_msg?{error_msg:n.error_msg}:{}})}async fetchRelayCredential(e){const o=this.aibotHandle;if(!o||o.status!=="ready")throw new Ne("agent websocket is not connected","OFFLINE");const{anthropicBaseUrl:t,openaiBaseUrl:s}=se(this.aibotConfig.url);return We((i,n)=>o.relayCredentialRequest(i,n),{anthropic_base_url:t,openai_base_url:s,...e.model?{model:e.model}:{}})}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{Es as AgentInstance};
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1,7 +1,7 @@
1
- import{existsSync as x,readFileSync as A}from"node:fs";import{mkdir as d,rm as g,writeFile as f}from"node:fs/promises";import{join as u}from"node:path";import{rootCertificates as H}from"node:tls";import{DynamicCertificateAuthority as P}from"./crypto/index.js";import{TrafficCaptureWriter as D,TrafficEventEmitter as C}from"./capture/index.js";import{HostInterceptList as S,RuntimeRouteRegistry as T}from"./routing/index.js";import{AcpTrafficProxyServer as _}from"./server/index.js";import{logProxyRuntimeStderr as n}from"./server/logger.js";function R(o){const t=Array.isArray(o)?o:[o],e=new Set,r=[];for(const s of t){const i=String(s??"").trim();i&&!e.has(i)&&(e.add(i),r.push(i))}return r}function L(o){return R([...o.relayHosts??[],...o.relayHost?[o.relayHost]:[]])}class y{filePath="";append(){}close(){return Promise.resolve()}}class $ extends Error{agentName;host;code="NO_RELAY_ROUTE";constructor(t,e){super(`no usable relay route for agent "${t}" (host ${e}); provision a gateway key first`),this.agentName=t,this.host=e,this.name="ProxyNoRelayRouteError"}}class w extends Error{constructor(t){super(t),this.name="ProxyLifecycleTimeoutError"}}const p="proxy-state.json",E="routes.json",l="grix-gateway";class m{proxyDataDir;certificateAuthority=null;captureWriter=new y;runtimeRoutes=new T;interceptHosts=new S;server=null;runtimeInfo=null;relayAgents=new Map;configExtras={};persistQueue=Promise.resolve();configLoaded=!1;lifecycleQueue=Promise.resolve();static LIFECYCLE_OP_TIMEOUT_MS=3e4;withLifecycleTimeout(t){return new Promise((e,r)=>{const s=setTimeout(()=>{r(new w(`proxy lifecycle operation timed out after ${m.LIFECYCLE_OP_TIMEOUT_MS}ms`))},m.LIFECYCLE_OP_TIMEOUT_MS);t().then(i=>{clearTimeout(s),e(i)},i=>{clearTimeout(s),r(i)})})}enqueueLifecycle(t){const e=()=>this.withLifecycleTimeout(t),r=this.lifecycleQueue.then(e,e);return r.catch(s=>{s instanceof w&&n("error",`proxy lifecycle operation timed out: ${s.message}`)}),this.lifecycleQueue=r.catch(()=>{}),r}constructor(t){this.proxyDataDir=u(t,"proxy"),this.loadConfigFromDisk()}loadConfigFromDisk(){if(this.configLoaded)return;this.configLoaded=!0;const t=this.loadRoutesFile();t&&(this.applyRoutesFile(t),t.capture!==void 0&&(this.configExtras.capture=t.capture),t.mitmPort!==void 0&&(this.configExtras.mitmPort=t.mitmPort),t.interceptHosts&&this.interceptHosts.setHosts(t.interceptHosts),this.relayAgents.size>0&&this.syncInterceptHosts())}async start(t={}){return this.enqueueLifecycle(()=>this.startInternal(t))}async startInternal(t={}){if(this.runtimeInfo)return this.runtimeInfo;await d(this.proxyDataDir,{recursive:!0});const e=t.captureEnabled??this.configExtras.capture??process.env.GRIX_PROXY_CAPTURE==="1";this.captureWriter=e?await D.create(this.proxyDataDir,{onCleanupError:(a,h)=>{const I=h instanceof Error?h.message:String(h);n("warn",`stale capture cleanup skipped ${a}: ${I}`)}}):new y,this.certificateAuthority=new P(this.proxyDataDir);const r=await this.certificateAuthority.ensureRootCertificate(),s=await this.writeCaBundle(r.certPem);t.interceptHosts&&this.interceptHosts.setHosts(t.interceptHosts),this.server=new _(this.captureWriter,this.certificateAuthority,new C,this.runtimeRoutes,this.interceptHosts);const i=t.port??this.configExtras.mitmPort??0,{port:c}=await this.server.start(i,"127.0.0.1");return this.runtimeInfo={mitmPort:c,proxyUrl:`http://127.0.0.1:${c}`,caCertPath:r.certPath,caBundlePath:s,captureFilePath:this.captureWriter.filePath,interceptHosts:this.interceptHosts.getHosts()},await this.writeStateFile(this.runtimeInfo),this.runtimeInfo}async setAgentRelayEnabled(t,e,r={}){return this.enqueueLifecycle(()=>this.setAgentRelayEnabledInternal(t,e,r))}async setAgentRelayEnabledInternal(t,e,r={}){const s=t.trim();if(s){if(e){const i=L(r);if(i.length===0)throw new Error(`relayHost(s) required to enable relay for agent "${s}"`);const c=i.map(a=>this.runtimeRoutes.getUsableRouteKeyForHost(a)).find(a=>a!==null);if(!c)throw new $(s,i[0]);for(const a of i)this.runtimeRoutes.hasUsableHostRoute(a)||this.runtimeRoutes.setHostDefaultRoute(a,c);await this.startInternal(),this.relayAgents.set(s,i)}else this.relayAgents.delete(s);this.syncInterceptHosts(),await this.persistConfig()}}syncInterceptHosts(){this.interceptHosts.setHosts(new Set([...this.relayAgents.values()].flat())),this.runtimeInfo&&(this.runtimeInfo={...this.runtimeInfo,interceptHosts:this.interceptHosts.getHosts()},this.writeStateFile(this.runtimeInfo).catch(t=>{n("warn",`failed to write proxy-state.json: ${t}`)}))}isAgentRelayEnabled(t){return this.relayAgents.has(t.trim())}getRelayAgents(){return[...this.relayAgents.keys()]}isRelayExpectedButUnavailable(t){return this.isAgentRelayEnabled(t)&&!this.runtimeInfo}getDegradedRelayAgents(){return this.runtimeInfo?[]:[...this.relayAgents.keys()]}async startIfAnyRelayAgent(){this.relayAgents.size!==0&&await this.start()}async stopIfUnused(t){return this.enqueueLifecycle(async()=>!this.runtimeInfo||this.relayAgents.size>0||t?.()?!1:(await this.stopInternal(),!0))}async disableAllAgentRelay(){return this.enqueueLifecycle(async()=>{const t=[...this.relayAgents.keys()];return this.relayAgents.clear(),this.syncInterceptHosts(),await this.persistConfig(),t})}async stop(){return this.enqueueLifecycle(()=>this.stopInternal())}async stopInternal(){this.server&&(await this.server.stop().catch(()=>{}),this.server=null),await this.captureWriter.close().catch(()=>{}),this.captureWriter=new y,this.runtimeInfo=null,await g(u(this.proxyDataDir,p),{force:!0}).catch(()=>{})}async clearRuntimeState(){this.runtimeInfo||await g(u(this.proxyDataDir,p),{force:!0}).catch(()=>{})}getRuntimeInfo(){return this.runtimeInfo}getMitmPort(){return this.runtimeInfo?.mitmPort??null}getCaCertPath(){return this.runtimeInfo?.caCertPath??null}getCaBundlePath(){return this.runtimeInfo?.caBundlePath??null}setRoute(t){this.runtimeRoutes.setRoute(t)}deleteRoute(t){this.runtimeRoutes.deleteRoute(t)}setDefaultRouteKey(t){this.runtimeRoutes.setDefaultRouteKey(t)}setHostDefaultRoute(t,e){this.runtimeRoutes.setHostDefaultRoute(t,e)}getInterceptHosts(){return this.interceptHosts.getHosts()}setInterceptHosts(t){this.interceptHosts.setHosts(t),this.runtimeInfo&&(this.runtimeInfo={...this.runtimeInfo,interceptHosts:this.interceptHosts.getHosts()},this.writeStateFile(this.runtimeInfo).catch(e=>{n("warn",`failed to write proxy-state.json: ${e}`)}))}getConfigSnapshot(){const t={routes:this.runtimeRoutes.listRoutes(),interceptHosts:this.interceptHosts.getHosts(),relayAgents:Object.fromEntries(this.relayAgents)},e=this.runtimeRoutes.getDefaultRouteKey();e&&(t.defaultRouteKey=e);const r=this.runtimeRoutes.getHostDefaultRoutes();return Object.keys(r).length>0&&(t.hostDefaultRoutes=r),this.configExtras.capture!==void 0&&(t.capture=this.configExtras.capture),this.configExtras.mitmPort!==void 0&&(t.mitmPort=this.configExtras.mitmPort),t}async persistConfig(){const t=this.getConfigSnapshot(),e=this.persistQueue.then(()=>this.writeConfigFile(t));return this.persistQueue=e.catch(()=>{}),e}async writeConfigFile(t){await d(this.proxyDataDir,{recursive:!0});const e=u(this.proxyDataDir,E);await f(e,`${JSON.stringify(t,null,2)}
1
+ import{existsSync as x,readFileSync as A}from"node:fs";import{mkdir as g,rm as R,writeFile as y}from"node:fs/promises";import{join as u}from"node:path";import{rootCertificates as H}from"node:tls";import{DynamicCertificateAuthority as P}from"./crypto/index.js";import{TrafficCaptureWriter as D,TrafficEventEmitter as C}from"./capture/index.js";import{HostInterceptList as S,RuntimeRouteRegistry as T}from"./routing/index.js";import{AcpTrafficProxyServer as _}from"./server/index.js";import{logProxyRuntimeStderr as n}from"./server/logger.js";function w(o){const t=Array.isArray(o)?o:[o],e=new Set,r=[];for(const s of t){const i=String(s??"").trim();i&&!e.has(i)&&(e.add(i),r.push(i))}return r}function $(o){return w([...o.relayHosts??[],...o.relayHost?[o.relayHost]:[]])}class p{filePath="";append(){}close(){return Promise.resolve()}}class L extends Error{agentName;host;code="NO_RELAY_ROUTE";constructor(t,e){super(`no usable relay route for agent "${t}" (host ${e}); provision a gateway key first`),this.agentName=t,this.host=e,this.name="ProxyNoRelayRouteError"}}class E extends Error{constructor(t){super(t),this.name="ProxyLifecycleTimeoutError"}}const m="proxy-state.json",I="routes.json",h="grix-gateway";class d{proxyDataDir;certificateAuthority=null;captureWriter=new p;runtimeRoutes=new T;interceptHosts=new S;server=null;runtimeInfo=null;relayAgents=new Map;configExtras={};persistQueue=Promise.resolve();configLoaded=!1;lifecycleQueue=Promise.resolve();static LIFECYCLE_OP_TIMEOUT_MS=3e4;withLifecycleTimeout(t){return new Promise((e,r)=>{const s=setTimeout(()=>{r(new E(`proxy lifecycle operation timed out after ${d.LIFECYCLE_OP_TIMEOUT_MS}ms`))},d.LIFECYCLE_OP_TIMEOUT_MS);t().then(i=>{clearTimeout(s),e(i)},i=>{clearTimeout(s),r(i)})})}enqueueLifecycle(t){const e=()=>this.withLifecycleTimeout(t),r=this.lifecycleQueue.then(e,e);return r.catch(s=>{s instanceof E&&n("error",`proxy lifecycle operation timed out: ${s.message}`)}),this.lifecycleQueue=r.catch(()=>{}),r}constructor(t){this.proxyDataDir=u(t,"proxy"),this.loadConfigFromDisk()}loadConfigFromDisk(){if(this.configLoaded)return;this.configLoaded=!0;const t=this.loadRoutesFile();t&&(this.applyRoutesFile(t),t.capture!==void 0&&(this.configExtras.capture=t.capture),t.mitmPort!==void 0&&(this.configExtras.mitmPort=t.mitmPort),t.interceptHosts&&this.interceptHosts.setHosts(t.interceptHosts),this.relayAgents.size>0&&this.syncInterceptHosts())}async start(t={}){return this.enqueueLifecycle(()=>this.startInternal(t))}async startInternal(t={}){if(this.runtimeInfo)return this.runtimeInfo;await g(this.proxyDataDir,{recursive:!0});const e=t.captureEnabled??this.configExtras.capture??process.env.GRIX_PROXY_CAPTURE==="1";this.captureWriter=e?await D.create(this.proxyDataDir,{onCleanupError:(f,l)=>{const a=l instanceof Error?l.message:String(l);n("warn",`stale capture cleanup skipped ${f}: ${a}`)}}):new p,this.certificateAuthority=new P(this.proxyDataDir);const r=await this.certificateAuthority.ensureRootCertificate(),s=await this.writeCaBundle(r.certPem);t.interceptHosts&&this.interceptHosts.setHosts(t.interceptHosts),this.server=new _(this.captureWriter,this.certificateAuthority,new C,this.runtimeRoutes,this.interceptHosts);const i=t.port??this.configExtras.mitmPort??0,{port:c}=await this.server.start(i,"127.0.0.1");return this.runtimeInfo={mitmPort:c,proxyUrl:`http://127.0.0.1:${c}`,caCertPath:r.certPath,caBundlePath:s,captureFilePath:this.captureWriter.filePath,interceptHosts:this.interceptHosts.getHosts()},await this.writeStateFile(this.runtimeInfo),this.runtimeInfo}async setAgentRelayEnabled(t,e,r={}){return this.enqueueLifecycle(()=>this.setAgentRelayEnabledInternal(t,e,r))}async setAgentRelayEnabledInternal(t,e,r={}){const s=t.trim();if(s){if(e){const i=$(r);if(i.length===0)throw new Error(`relayHost(s) required to enable relay for agent "${s}"`);const c=i.map(a=>this.runtimeRoutes.getUsableRouteKeyForHost(a)).find(a=>a!==null);if(!c)throw new L(s,i[0]);for(const a of i)this.runtimeRoutes.hasUsableHostRoute(a)||this.runtimeRoutes.setHostDefaultRoute(a,c);const f=this.runtimeInfo!==null,l=await this.startInternal();f||n("info",`mitm proxy started on demand for relay agent "${s}" (port ${l.mitmPort})`),this.relayAgents.set(s,i)}else this.relayAgents.delete(s);this.syncInterceptHosts(),await this.persistConfig()}}syncInterceptHosts(){this.interceptHosts.setHosts(new Set([...this.relayAgents.values()].flat())),this.runtimeInfo&&(this.runtimeInfo={...this.runtimeInfo,interceptHosts:this.interceptHosts.getHosts()},this.writeStateFile(this.runtimeInfo).catch(t=>{n("warn",`failed to write proxy-state.json: ${t}`)}))}isAgentRelayEnabled(t){return this.relayAgents.has(t.trim())}getRelayAgents(){return[...this.relayAgents.keys()]}isRelayExpectedButUnavailable(t){return this.isAgentRelayEnabled(t)&&!this.runtimeInfo}getDegradedRelayAgents(){return this.runtimeInfo?[]:[...this.relayAgents.keys()]}async startIfAnyRelayAgent(){this.relayAgents.size!==0&&await this.start()}async stopIfUnused(t){return this.enqueueLifecycle(async()=>!this.runtimeInfo||this.relayAgents.size>0||t?.()?!1:(await this.stopInternal(),!0))}async disableAllAgentRelay(){return this.enqueueLifecycle(async()=>{const t=[...this.relayAgents.keys()];return this.relayAgents.clear(),this.syncInterceptHosts(),await this.persistConfig(),t})}async stop(){return this.enqueueLifecycle(()=>this.stopInternal())}async stopInternal(){this.server&&(await this.server.stop().catch(()=>{}),this.server=null),await this.captureWriter.close().catch(()=>{}),this.captureWriter=new p,this.runtimeInfo=null,await R(u(this.proxyDataDir,m),{force:!0}).catch(()=>{})}async clearRuntimeState(){this.runtimeInfo||await R(u(this.proxyDataDir,m),{force:!0}).catch(()=>{})}getRuntimeInfo(){return this.runtimeInfo}getMitmPort(){return this.runtimeInfo?.mitmPort??null}getCaCertPath(){return this.runtimeInfo?.caCertPath??null}getCaBundlePath(){return this.runtimeInfo?.caBundlePath??null}setRoute(t){this.runtimeRoutes.setRoute(t)}deleteRoute(t){this.runtimeRoutes.deleteRoute(t)}setDefaultRouteKey(t){this.runtimeRoutes.setDefaultRouteKey(t)}setHostDefaultRoute(t,e){this.runtimeRoutes.setHostDefaultRoute(t,e)}getInterceptHosts(){return this.interceptHosts.getHosts()}setInterceptHosts(t){this.interceptHosts.setHosts(t),this.runtimeInfo&&(this.runtimeInfo={...this.runtimeInfo,interceptHosts:this.interceptHosts.getHosts()},this.writeStateFile(this.runtimeInfo).catch(e=>{n("warn",`failed to write proxy-state.json: ${e}`)}))}getConfigSnapshot(){const t={routes:this.runtimeRoutes.listRoutes(),interceptHosts:this.interceptHosts.getHosts(),relayAgents:Object.fromEntries(this.relayAgents)},e=this.runtimeRoutes.getDefaultRouteKey();e&&(t.defaultRouteKey=e);const r=this.runtimeRoutes.getHostDefaultRoutes();return Object.keys(r).length>0&&(t.hostDefaultRoutes=r),this.configExtras.capture!==void 0&&(t.capture=this.configExtras.capture),this.configExtras.mitmPort!==void 0&&(t.mitmPort=this.configExtras.mitmPort),t}async persistConfig(){const t=this.getConfigSnapshot(),e=this.persistQueue.then(()=>this.writeConfigFile(t));return this.persistQueue=e.catch(()=>{}),e}async writeConfigFile(t){await g(this.proxyDataDir,{recursive:!0});const e=u(this.proxyDataDir,I);await y(e,`${JSON.stringify(t,null,2)}
2
2
  `,"utf8")}getInjectionEnv(t){return!this.isAgentRelayEnabled(t)||!this.runtimeInfo?null:{HTTPS_PROXY:this.runtimeInfo.proxyUrl,NODE_EXTRA_CA_CERTS:this.runtimeInfo.caCertPath,SSL_CERT_FILE:this.runtimeInfo.caBundlePath}}async writeCaBundle(t){const e=u(this.proxyDataDir,"ca-bundle.pem"),r=H.join(`
3
3
  `),s=t.endsWith(`
4
4
  `)?t:`${t}
5
- `;return await f(e,`${r}
6
- ${s}`,"utf8"),e}loadRoutesFile(){const t=u(this.proxyDataDir,E);if(!x(t))return null;try{return JSON.parse(A(t,"utf8"))}catch(e){const r=e instanceof Error?e.message:String(e);return n("warn",`proxy routes file ignored (${t}): ${r}`),null}}applyRoutesFile(t){if(Array.isArray(t.relayAgents))n("warn","relayAgents in routes.json is an outdated array format (no host info): discarding it. Re-enable Grix relay per agent in the desktop app.");else for(const[e,r]of Object.entries(t.relayAgents??{})){const s=e.trim(),i=R(r);s&&i.length>0&&this.relayAgents.set(s,i)}this.relayAgents.size>0&&n("info",`proxy relay agents restored: ${[...this.relayAgents.keys()].join(", ")}`),t.relayAgents===void 0&&(t.routes??[]).some(e=>e.routeKey.startsWith("grix-gateway"))&&n("warn","found legacy Grix relay config without per-agent list: relay is now per-agent and starts OFF. Re-enable it per agent in the desktop app (Settings \u2192 Grix relay).");for(const e of t.routes??[]){if(e.routeKey===l){n("info",`proxy legacy route dropped: ${l}`);continue}try{this.runtimeRoutes.handleControlLine(JSON.stringify(e.type==="delete_route"?e:{type:"set_route",routeKey:e.routeKey,targetBaseUrl:e.targetBaseUrl,...e.headers?{headers:e.headers}:{},...e.model?{model:e.model}:{},...e.modelMap?{modelMap:e.modelMap}:{},...e.passthrough?{passthrough:!0}:{},...e.relayOnly?{relayOnly:!0}:{},...e.codexResponsesToChat?{codexResponsesToChat:!0}:{}})),n("info",`proxy route loaded: ${e.routeKey} \u2192 ${e.targetBaseUrl}`)}catch(r){const s=r instanceof Error?r.message:String(r);n("warn",`proxy route "${e.routeKey}" skipped: ${s}`)}}t.defaultRouteKey&&t.defaultRouteKey!==l?(this.runtimeRoutes.setDefaultRouteKey(t.defaultRouteKey),n("info",`proxy default route key: ${t.defaultRouteKey}`)):t.defaultRouteKey===l&&n("info",`proxy legacy default route key dropped: ${l}`);for(const[e,r]of Object.entries(t.hostDefaultRoutes??{}))this.runtimeRoutes.setHostDefaultRoute(e,r),n("info",`proxy host default route: ${e} \u2192 ${r}`)}async writeStateFile(t){const e=u(this.proxyDataDir,p),r={...t,pid:process.pid,updated_at:Date.now()};await f(e,`${JSON.stringify(r,null,2)}
7
- `,"utf8")}}export{m as ProxyManager,$ as ProxyNoRelayRouteError};
5
+ `;return await y(e,`${r}
6
+ ${s}`,"utf8"),e}loadRoutesFile(){const t=u(this.proxyDataDir,I);if(!x(t))return null;try{return JSON.parse(A(t,"utf8"))}catch(e){const r=e instanceof Error?e.message:String(e);return n("warn",`proxy routes file ignored (${t}): ${r}`),null}}applyRoutesFile(t){if(Array.isArray(t.relayAgents))n("warn","relayAgents in routes.json is an outdated array format (no host info): discarding it. Re-enable Grix relay per agent in the desktop app.");else for(const[e,r]of Object.entries(t.relayAgents??{})){const s=e.trim(),i=w(r);s&&i.length>0&&this.relayAgents.set(s,i)}this.relayAgents.size>0&&n("info",`proxy relay agents restored: ${[...this.relayAgents.keys()].join(", ")}`),t.relayAgents===void 0&&(t.routes??[]).some(e=>e.routeKey.startsWith("grix-gateway"))&&n("warn","found legacy Grix relay config without per-agent list: relay is now per-agent and starts OFF. Re-enable it per agent in the desktop app (Settings \u2192 Grix relay).");for(const e of t.routes??[]){if(e.routeKey===h){n("info",`proxy legacy route dropped: ${h}`);continue}try{this.runtimeRoutes.handleControlLine(JSON.stringify(e.type==="delete_route"?e:{type:"set_route",routeKey:e.routeKey,targetBaseUrl:e.targetBaseUrl,...e.headers?{headers:e.headers}:{},...e.model?{model:e.model}:{},...e.modelMap?{modelMap:e.modelMap}:{},...e.passthrough?{passthrough:!0}:{},...e.relayOnly?{relayOnly:!0}:{},...e.codexResponsesToChat?{codexResponsesToChat:!0}:{}})),n("info",`proxy route loaded: ${e.routeKey} \u2192 ${e.targetBaseUrl}`)}catch(r){const s=r instanceof Error?r.message:String(r);n("warn",`proxy route "${e.routeKey}" skipped: ${s}`)}}t.defaultRouteKey&&t.defaultRouteKey!==h?(this.runtimeRoutes.setDefaultRouteKey(t.defaultRouteKey),n("info",`proxy default route key: ${t.defaultRouteKey}`)):t.defaultRouteKey===h&&n("info",`proxy legacy default route key dropped: ${h}`);for(const[e,r]of Object.entries(t.hostDefaultRoutes??{}))this.runtimeRoutes.setHostDefaultRoute(e,r),n("info",`proxy host default route: ${e} \u2192 ${r}`)}async writeStateFile(t){const e=u(this.proxyDataDir,m),r={...t,pid:process.pid,updated_at:Date.now()};await y(e,`${JSON.stringify(r,null,2)}
7
+ `,"utf8")}}export{d as ProxyManager,L as ProxyNoRelayRouteError};
@@ -1 +1 @@
1
- import{fetchRelayCredentialWithRetry as l,RelayFetchError as c}from"./relay-credential-fetch.js";const p=15e3;function a(n){return n instanceof Error?n.message:String(n)}function o(n){if(n instanceof c)return n.bizCode?.trim()||n.code;const e=n?.code;return typeof e=="string"&&e.trim()?e.trim():"INTERNAL"}class u{ports;lastRevision=null;applyingFromServer=0;chain=Promise.resolve();constructor(e){this.ports=e}get knownRevision(){return this.lastRevision}syncOnConnect(){return this.enqueue(()=>this.doSync())}applyFromLocalAction(e){return this.enqueue(()=>this.doApply(e))}reportLocalChange(){if(this.applyingFromServer>0)return;const e=this.lastRevision;e!=null&&this.safeReport({applied:this.currentApplied(),revision:e})}enqueue(e){const t=this.chain.catch(()=>{}).then(e);return this.chain=t.then(()=>{},()=>{}),t}async doSync(){const e=this.ports.getLocalState();let t;try{t=await this.ports.sendSyncRequest({local_enabled:e.enabled,...e.model?{local_model:e.model}:{}},p)}catch(i){this.ports.log.warn(`relay_state_sync_request not answered: ${a(i)}`);return}if(t.cmd==="error"){const i=t.payload??{};this.ports.log.warn(`relay_state_sync_request rejected by server: code=${i.code??"?"} msg=${i.msg??""}`);return}const r=t.payload??{};if(r.status!=="ok"){this.ports.log.warn(`relay_state_sync_result failed: ${r.error_code??""} ${r.error_msg??""}`.trim());return}const s=Number(r.revision);if(!Number.isFinite(s)){this.ports.log.warn("relay_state_sync_result missing/invalid revision; ignored");return}this.lastRevision=s;try{r.enabled?await this.ensureEnabled(r.model?.trim()||void 0,r.credential):await this.guarded(()=>this.ports.applyDisable())}catch(i){this.ports.log.warn(`relay state apply after sync failed: ${a(i)}`),this.safeReport({applied:this.currentApplied(),revision:s,error_code:o(i)});return}this.safeReport({applied:this.currentApplied(),revision:s})}async doApply(e){const t=e.revision;this.lastRevision=t;const r=e.model?.trim()||void 0;try{return e.enabled?await this.ensureEnabled(r,void 0):await this.guarded(()=>this.ports.applyDisable()),{ok:!0,revision:t}}catch(s){return this.ports.log.warn(`apply_relay_state failed: ${a(s)}`),{ok:!1,error_code:o(s),error_msg:a(s),revision:t}}}async ensureEnabled(e,t){const r=t?.api_key?.trim();if(r){await this.guarded(()=>this.ports.applyEnable({apiKey:r,anthropicBaseUrl:t?.anthropic_base_url?.trim()||void 0,openaiBaseUrl:t?.openai_base_url?.trim()||void 0,model:e},e));return}const s=this.ports.getLocalState();if(s.enabled&&(!e||!s.model||s.model===e))return;const i=await l(this.ports.sendCredentialRequest,e?{model:e}:{});await this.guarded(()=>this.ports.applyEnable(i,e??i.model))}async guarded(e){this.applyingFromServer++;try{await e()}finally{this.applyingFromServer--}}currentApplied(){try{return this.ports.getLocalState().enabled}catch{return!1}}safeReport(e){try{this.ports.sendReport(e)}catch(t){this.ports.log.warn(`relay_state_report not sent: ${a(t)}`)}}}export{u as RelayStateSyncer};
1
+ import{fetchRelayCredentialWithRetry as l,RelayFetchError as c}from"./relay-credential-fetch.js";const p=15e3;function a(i){return i instanceof Error?i.message:String(i)}function o(i){if(i instanceof c)return i.bizCode?.trim()||i.code;const e=i?.code;return typeof e=="string"&&e.trim()?e.trim():"INTERNAL"}class u{ports;lastRevision=null;applyingFromServer=0;chain=Promise.resolve();constructor(e){this.ports=e}get knownRevision(){return this.lastRevision}syncOnConnect(){return this.enqueue(()=>this.doSync())}applyFromLocalAction(e){return this.enqueue(()=>this.doApply(e))}reportLocalChange(){if(this.applyingFromServer>0)return;const e=this.lastRevision;e!=null&&this.safeReport({applied:this.currentApplied(),revision:e})}enqueue(e){const t=this.chain.catch(()=>{}).then(e);return this.chain=t.then(()=>{},()=>{}),t}async doSync(){const e=this.ports.getLocalState();let t;try{t=await this.ports.sendSyncRequest({local_enabled:e.enabled,...e.model?{local_model:e.model}:{}},p)}catch(n){this.ports.log.warn(`relay_state_sync_request not answered: ${a(n)}`);return}if(t.cmd==="error"){const n=t.payload??{};this.ports.log.warn(`relay_state_sync_request rejected by server: code=${n.code??"?"} msg=${n.msg??""}`);return}const r=t.payload??{};if(r.status!=="ok"){this.ports.log.warn(`relay_state_sync_result failed: ${r.error_code??""} ${r.error_msg??""}`.trim());return}const s=Number(r.revision);if(!Number.isFinite(s)){this.ports.log.warn("relay_state_sync_result missing/invalid revision; ignored");return}this.lastRevision=s;try{r.enabled?await this.ensureEnabled(r.model?.trim()||void 0,r.credential):await this.ensureDisabled()}catch(n){this.ports.log.warn(`relay state apply after sync failed: ${a(n)}`),this.safeReport({applied:this.currentApplied(),revision:s,error_code:o(n)});return}this.safeReport({applied:this.currentApplied(),revision:s})}async doApply(e){const t=e.revision;this.lastRevision=t;const r=e.model?.trim()||void 0;try{return e.enabled?await this.ensureEnabled(r,void 0):await this.ensureDisabled(),{ok:!0,revision:t}}catch(s){return this.ports.log.warn(`apply_relay_state failed: ${a(s)}`),{ok:!1,error_code:o(s),error_msg:a(s),revision:t}}}async ensureEnabled(e,t){const r=t?.api_key?.trim();if(r){await this.guarded(()=>this.ports.applyEnable({apiKey:r,anthropicBaseUrl:t?.anthropic_base_url?.trim()||void 0,openaiBaseUrl:t?.openai_base_url?.trim()||void 0,model:e},e));return}const s=this.ports.getLocalState();if(s.enabled&&(!e||!s.model||s.model===e))return;const n=await l(this.ports.sendCredentialRequest,e?{model:e}:{});await this.guarded(()=>this.ports.applyEnable(n,e??n.model))}async ensureDisabled(){this.ports.getLocalState().enabled&&await this.guarded(()=>this.ports.applyDisable())}async guarded(e){this.applyingFromServer++;try{await e()}finally{this.applyingFromServer--}}currentApplied(){try{return this.ports.getLocalState().enabled}catch{return!1}}safeReport(e){try{this.ports.sendReport(e)}catch(t){this.ports.log.warn(`relay_state_report not sent: ${a(t)}`)}}}export{u as RelayStateSyncer};