grix-connector 4.2.8 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import P from"node:path";import{realpath as ee,stat as I}from"node:fs/promises";import{tmpdir as te}from"node:os";import{createHash as Q,randomUUID as O}from"node:crypto";import{ConnectionManager as ne}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as ie}from"../core/aibot/types.js";import{ClaudeAdapter as U}from"../adapter/claude/index.js";import{CodexAdapter as N}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as se}from"../adapter/pi/index.js";import{AcpAdapter as k}from"../adapter/acp/index.js";import{OpenHumanAdapter as oe}from"../adapter/openhuman/index.js";import{CursorAdapter as re}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as ae}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as B}from"../adapter/opencode/index.js";import{AgyAdapter as W}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as de,buildDshBindingToolbarMeta as le,DEFAULT_DSH_PRESETS as ce,listDshPlugins as he,listDshSkills as ue,listDshProfiles as pe,normalizeDshReasoningEffort as ge,normalizeDshThinking as fe,resolveDshAgentPreset as me,resolveDshCatalogForToolbar as ve,resolveDshModeId as G,resolveDshSelectedProfileName as _e}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as E,SESSION_CONTROL_ERROR_CODES as A,SESSION_CONTROL_VERBS as S,SESSION_MODE_IDS as Se}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as be}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as j}from"../audit/raw-capture/types.js";import{syncDefaultSkillsToDir as Ce}from"../default-skills/index.js";import{buildWireSkills as we}from"../core/skill-sync/sync-state.js";import{executeEventTool as Ae}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as Ee}from"../adapter/claude/model-list.js";import{applyProxyEnv as ke,getProxyManager as Re}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ye}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as Pe}from"../core/config/provider-env.js";import{buildProviderEnv as Te}from"../core/config/provider-env.js";import{isClaudeDirectEnv as xe,stripGrixRelayEnv as De}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as Me}from"./native-provider-sweep.js";import{scanCodexSessions as He}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as Le}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as $e,resolveAcpAgentTypes as Ie,scanAcpSessions as Qe,scanReasonixSessionTitles as Oe}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Be}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as Fe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as qe}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ue}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as Ne}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as R,resolveCodexLeafDirs as We,resolveClaudeLeafDirs as Ge,resolveAcpLeafDirs as je,resolvePiLeafDirs as Ke,resolveCodeWhaleLeafDirs as ze,resolveCursorLeafDirs as Je,resolveOpenCodeLeafDirs as Ye,resolveDshLeafDirs as Xe,resolveReasonixLeafDirs as Ve}from"./session-scan-cache.js";import{log as p,ConversationLog as Ze,AgentApiPacketLog as et,BridgeEventLog as tt,GRIX_PATHS as H}from"../core/log/index.js";import{routeSessionControlCommand as nt,routeSessionControlLocalAction as it}from"./session-control-router.js";import{maybeOfferCliInstall as st,handleCliInstallQuestionReply as ot,handleCliInstallInteractionReply as rt,runConfirmedCliInstall as at}from"./cli-install-flow.js";import{handleEventCancel as dt,waitForEventDone as lt,handleAibotStop as ct,killAndResumeStopSlot as ht,handleAibotRevoke as ut}from"./event-stop.js";import{handleConfigureGatewayProvider as pt,getAuditLocalActionHandler as gt,handleAuditLocalAction as ft,handleConnectorRollback as mt,getRelayStateSyncer as vt,relayStateSyncOnConnect as _t,reportRelayStateLocalChange as St,handleApplyRelayState as bt,fetchRelayCredential as Ct,isSharedInstance as wt}from"./connector-ops.js";import{unbindSession as At,handleUnbindTextCommand as Et,handleUnbindLocalAction as kt,handleListSessionsTextCommand as Rt,handleListSessionsLocalAction as yt,handleSyncHistoryLocalAction as Pt}from"./session-list.js";import{handleCodexSessionControlOpen as Tt,handleSessionControlForPool as xt,handleSessionControlLocalActionForPool as Dt,handleCodexSessionControlLocalActionOpen as Mt,handleCursorSessionControlLocalActionOpen as Ht,handlePiSessionControlOpen as Lt,handlePiSessionControlRestart as $t,handlePiSessionControlRestartLocalAction as It,syncOpenCodeBinding as Qt,isWorkspaceFreeClient as Ot,ensureDefaultBindingForWorkspaceFreeClient as Bt,bindSessionForPool as Ft,deferredCallbacks as qt,handleOpenHumanSessionControlOpen as Ut,handleCodeWhaleSessionControlOpen as Nt,handleCodeWhaleSessionControlLocalActionOpen as Wt,handleDeepSeekSessionControlLocalActionOpen as Gt}from"./session-control-open.js";import{handleGetSessionUsage as jt,handleThreadCompact as Kt}from"./session-usage.js";import{handleSkillDeleteLocalAction as zt,handleSkillUploadLocalAction as Jt,handleSkillEnableLocalAction as Yt,handleSkillRefreshLocalAction as Xt,handleSkillDisableLocalAction as Vt,computeSkillReport as Zt,reportSessionSkills as en,skillsSyncGroupKey as tn,forceRefreshSkills as nn,adoptSkillsWireHashFromDisk as sn,buildLibrarySkillsReport as on,skillLookupEnv as rn}from"./skill-actions.js";import{normalizeClaudeModeId as an,handleExecCommandOptions as dn,resolveSessionModelId as ln,resolveSessionModeId as cn,resolveCursorSessionModeId as hn,resolveClaudeSessionEffort as un,resolveClaudeSessionModeId as pn,currentClaudeModeId as gn,resolveCodexSessionModelId as fn,resolveCodexNewSessionGlobalDefault as mn,pinCodexGlobalDefault as vn,buildCursorToolbarMeta as _n,buildAgyToolbarMeta as Sn,buildAgyQuotaMeta as bn,sendAgyBindingCard as Cn,refreshAndPushAgyQuota as wn,handleAgySetModel as An,buildClaudeToolbarMeta as En}from"./toolbar-meta.js";import{resolveProviderQuotaSource as kn,maybeQueryProviderQuota as Rn,startProviderQuotaTimer as yn,stopProviderQuotaTimer as Pn,refreshAndPushProviderQuota as Tn,pushProviderQuotaToBindings as xn,enrichProviderQuotaMeta as Dn,providerQuotaMetaPayload as Mn,refreshProviderQuotaForSession as Hn,refreshQuotaAfterModelSwitch as Ln,doRefreshQuotaAfterModelSwitch as $n}from"./provider-quota.js";import{handleGetRateLimits as In,resolveRateLimitWakeSessionId as Qn,wakeRateLimitSlot as On}from"./rate-limits.js";import{RevokeHandler as Bn}from"./revoke-handler.js";import{AdapterPool as Fn}from"./adapter-pool.js";import{parseSessionControlCommand as qn,handleSessionControlCommand as Un,handleSessionControlLocalAction as Nn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Wn,parseExecApprovalResolutionMessage as Gn,parseAgentQuestionReplyMessage as jn}from"../core/protocol/interaction-parser.js";import{isCliMissingError as Kn,sessionControlOpenFailure as zn}from"./cli-install-offer.js";import{handleAcpSetModel as K,handleAcpSetMode as z,resolveAcpInitialDefaults as Jn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Yn}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Xn,handleCreateFolderAction as Vn,serveLocalFile as Zn,realHomeDir as J}from"../core/files/index.js";import{getMachineName as ei}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as ti}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ni}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as ii}from"./pending-event-coordinator.js";import{LifecycleBarrier as si}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as oi}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as ri,applyConnectorRuntimeConfigPatch as ai,extractConnectorRuntimeConfigPatch as di}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as li,SendController as ci}from"./send-controller.js";import{providerQuotaToRateLimits as hi,providerQuotaToCodexRateLimits as ui}from"../core/provider-quota/index.js";import{buildToolUseCard as x,buildToolResultCard as D,buildDshOnlineToolCard as pi,buildLocalGrixCardLink as Y}from"./tool-card-utils.js";import{planRawEventDelivery as gi,buildAuxiliaryDetailText as fi}from"./raw-event-delivery.js";import{DeferredEventManager as mi}from"./deferred-events.js";import{buildAgentProbeResult as vi,PROBE_CACHE_TTL_STATIC_MS as _i,PROBE_CACHE_TTL_FULL_MS as Si}from"./probe-helper.js";import{BridgeAuditController as bi}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Ci,NoopAuditProducer as wi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as L,AuditPreparationFailedError as Ai,AuditTurnScopeUnsupportedError as Ei}from"../audit/core/audit-state.js";import{extractAuditOptions as X,freezeAuditOptions as ki,stripAuditOptions as Ri}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as yi}from"../audit/core/audit-session-registry.js";const Pi=600*1e3,V=1800*1e3,Ti=60*1e3,xi=4e3;function Di(q,e,t){const s=Q("sha256").update(q).update("\0").update(e).update("\0").update(t).digest("hex");return P.join(H.data,"audit-source","reasonix",`${s}.jsonl`)}const $=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),Z=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),F=3;class ro{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Bn;sessionBindings=new Map;deferredMgr;sendCtrl=new ci(ri);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new si;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=Ti}resolveProviderQuotaSource(e){return kn(this,e)}maybeQueryProviderQuota(e=!1,t){return Rn(this,e,t)}startProviderQuotaTimer(){yn(this)}stopProviderQuotaTimer(){Pn(this)}refreshAndPushProviderQuota(e=!1){return Tn(this,e)}pushProviderQuotaToBindings(e,t=!1){xn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",s=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){return Dn(this,e,t,s,i)}providerQuotaMetaPayload(e,t,s){return Mn(this,e,t,s)}refreshProviderQuotaForSession(e,t,s){return Hn(this,e,t,s)}refreshQuotaAfterModelSwitch(e,t,s){Ln(this,e,t,s)}doRefreshQuotaAfterModelSwitch(e,t,s){return $n(this,e,t,s)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,s=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:s,hasData:!!(e||t||s)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const t=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(t()){const s=Math.round(V/6e4);p.info(this.name,`${e}: active tasks detected, waiting up to ${s}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+V,n=5e3,o=600*1e3;let r=Date.now();for(;t()&&!this.stopped;){if(Date.now()>=i)return p.warn(this.name,`${e}: idle wait exceeded ${s}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,n)),Date.now()-r>=o&&(r=Date.now(),p.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),t()?(p.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(p.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,s=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let n=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{s=!0,n=!0,p.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),n||(t+=1)}return t>0&&p.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),s?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",s=e.conversation?Si:_i;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<s)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",n=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(n,e.timeoutMs??1e4):void 0;let r;try{r=await vi({adapter:n,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{n.stop().catch(()=>{})}return this.probeCache.set(t,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,t){const s=Date.now(),i="__probe__",n=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||te(),r=()=>Date.now()-s;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof k)try{await e.bindSession(i,o)}catch{}let a=null;const c=new Promise(h=>{a=u=>{u===n&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:n,session_id:i,content:"ping",msg_id:n}),e.deliverStopEvent(n,i);let d=null;const l=await Promise.race([c.then(()=>!1),new Promise(h=>{d=setTimeout(()=>h(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,t,s=new wi){this.config=e,this.auditController=new bi(s,{onAuditState:n=>{try{this.aibotHandle.sendAuditState(L(n,Date.now()))}catch{}}}),Ci(s)&&s.addJobSettledHandler((n,o)=>{this.auditController.handleJobSettled(n,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(li[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...ie]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new Ze(e.logDir):null,this.packetLog=e.logDir?new et(e.logDir):null,this.bindingStore=new Yn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new mi(this.name),this.activeEventStore=e.activeEventStorePath?new ni(e.activeEventStorePath):null,this.pendingEvents=new ii(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new R(He,We);else if(i==="claude")this.sessionScanCache=new R(Le,Ge);else if(i==="pi"){const n=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new R(()=>Be(void 0,n),()=>Ke(void 0,n))}else if(i==="codewhale")this.sessionScanCache=new R(Fe,ze);else if(i==="cursor")this.sessionScanCache=new R(qe,Je);else if(i==="opencode")this.sessionScanCache=new R(Ue,Ye);else if(i==="deepseek-harness"){const n=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new R(()=>Ne(n),()=>Xe(n))}else if(i==="agy")this.sessionScanCache=new R(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new R(Oe,Ve));const n=Ie(e.aibot.clientType);this.sessionScanCache=n?new R(()=>Qe(void 0,n),()=>je(void 0,n)):new R(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await Me({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,n])=>String(n.cwd??""))}).then(n=>{n.length>0&&p.info(this.name,`restored native provider config after relay disable: ${n.join(", ")}`)}).catch(n=>{p.warn(this.name,`native provider residue sweep failed: ${n instanceof Error?n.message:String(n)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await Ee().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",s=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||s)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new Fn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},n=>{const o=this.createAdapter(i,n);return o instanceof k&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(n,r),this.sessionScanCache.invalidate()}),o},(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((n,o,r,a)=>{if(p.info(this.name,`[queue-debug] send event_state session=${o} event=${n} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:n,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(n),this.pendingEvents.remove(n).catch(c=>{p.warn(this.name,`Failed to remove running event from pending store event=${n}: ${c instanceof Error?c.message:String(c)}`)})),r==="canceled"||r==="failed"){const c=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:n,status:c,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(n,c,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(n),this.pendingEvents.remove(n).catch(d=>{p.warn(this.name,`Failed to remove queued terminal event from pending store event=${n}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:o,...o?{ttl_ms:oi,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(n=>{this.handleSessionInternalError(n).catch(o=>{p.error(this.name,`[recovery] handleSessionInternalError failed event=${n.eventId} session=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((n,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((n,o)=>{this.markAuditAdapterClosed(n,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const c=this.buildAgyToolbarMeta(o),d=c?.available_models??[];p.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(c?.model_id??"")} available_models=${d.length} meta_keys=${c?Object.keys(c).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,c),this.refreshAndPushAgyQuota(o)}else p.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((n,o,r)=>{const a=this.selfDrivenSessions.has(n),c=this.selfDrivenLabels.get(n);o?(this.selfDrivenSessions.add(n),r&&this.selfDrivenLabels.set(n,r),this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(n),this.selfDrivenLabels.delete(n),a&&this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==c)&&this.pushQueueSnapshotForSession(n)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),p.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)p.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=t.get(r),c=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,c?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const s=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],n=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...s.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){p.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(n)}catch(r){p.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of n){const a=r.event;p.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){p.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=Te(this.config.agent.clientType,e),s=this.config.agent.env;let i=Object.keys(t).length>0?{...t,...s}:s;if(xe(t)){const n=Re()?.getRuntimeInfo(),o={...s??{},...t},r=De(o,{proxyUrl:n?.proxyUrl,caCertPath:n?.caCertPath,caBundlePath:n?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(Pe(this.config.agent.clientType)){const n=ye(this.name);n&&(i={...i??{},...n})}return ke(i,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",xi),sendThinking:(n,o,r)=>this.sendThinkingByRuntimeConfig(n,o,r),sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,void 0,a)},sendRawEventEnvelope:(n,o,r,a)=>{const c=pi(r);if(c){this.sendToolExecutionCard(n,o,c);return}this.deliverRawEventEnvelope(n,o,r,"deepseek",a)},sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"deepseek")},sendUpdateBindingCard:(n,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:n=>this.maybeQueryProviderQuota(n===!0,{providerId:"deepseek"}),agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),eventToolInvoke:async(n,o)=>this.invokeDshEventTool(n,o)},s=Q("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new de({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:P.join(H.data,"deepseek-harness",s),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const s=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(t.model=i);const n=this.resolveCursorSessionModeId(e),o=n??"full_auto";n||this.bindingStore.setCursorModeId(e,o),t.mode=o,s?.cwd&&(t.workspace=s.cwd);const r={sendStreamChunk:(a,c,d,l,h,u,g)=>{this.sendStreamChunkByRuntimeConfig(a,c,d,l,h,u,g)},sendEventResult:(a,c,d)=>{this.sendEventResultWithCleanup(a,c,d)},sendEventAck:(a,c)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:c,received_at:Date.now()})},sendRawEventEnvelope:(a,c,d)=>{this.deliverRawEventEnvelope(a,c,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,c,d)=>{const l=d.questions.map(u=>u.header).join(", "),h=Y(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:c,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,c,d)=>this.platformInvoke(a,c,d),sendLocalActionResult:(a,c,d,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:c,...d!==void 0?{result:d}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,c,d,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:c,cwd:d,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new re({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},r)}createClaudeAdapter(e){const t={sendReply:(n,o,r,a,c)=>{this.sendReplyByRuntimeConfig(n,o,r,a,c)},sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendMedia:(n,o,r,a,c,d,l)=>{this.aibotHandle.sendMedia({event_id:n,session_id:o,content:r,msg_type:2,quoted_message_id:c||void 0,client_msg_id:d||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,a)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,x(r,a))},sendToolResult:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,D(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(n,o,r)=>{this.sendGrixAgentQuestionCard(n,o,r)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"claude")},sendDirectMessage:n=>{this.aibotHandle.sendMsg({session_id:n.sessionId,msg_type:1,content:n.content,...n.clientMsgId?{client_msg_id:n.clientMsgId}:{},...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})},onStatusLineUpdated:n=>{(n.rateLimits?.fiveHour||n.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=n);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:n=>{this.aibotHandle.sendMcpFrame(e,n)}},s=this.config.adapterOptions??{},i={...s,sessionRuntimeResolver:()=>{const n=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:n?.cwd,modeId:this.resolveClaudeSessionModeId(e)??Se.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:n?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new U({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t)}createCodexAdapter(e){let t=null;const s={sendEventResult:(r,a,c)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,c);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,c),d=>{const l=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:c)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,c)=>{this.sendThinkingByRuntimeConfig(r,a,c)},sendRunError:(r,a,c)=>{this.sendRunErrorAsChunk(r,a,c)},sendUpdateBindingCard:(r,a,c,d)=>{const l={...d??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:c,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,c)=>this.platformInvoke(r,a,c),sendLocalActionResult:(r,a,c,d,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...c!==void 0?{result:c}:{},...d?{error_code:d}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,c,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:c,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const c=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:c},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:r,...t?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},n=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return t=new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(n?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(n?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...j(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:P.join(H.data,"audit-replay","raw-spool")}}:{}}},s),t}createCodeWhaleAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,n,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,x(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new ae({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??s.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[pi] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,x(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c),a&&p.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
1
+ import T from"node:path";import{realpath as te,stat as Q}from"node:fs/promises";import{tmpdir as ne}from"node:os";import{createHash as O,randomUUID as B}from"node:crypto";import{ConnectionManager as ie}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as se}from"../core/aibot/types.js";import{ClaudeAdapter as N}from"../adapter/claude/index.js";import{CodexAdapter as W}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as oe}from"../adapter/pi/index.js";import{AcpAdapter as y}from"../adapter/acp/index.js";import{OpenHumanAdapter as re}from"../adapter/openhuman/index.js";import{CursorAdapter as ae}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as de}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as F}from"../adapter/opencode/index.js";import{AgyAdapter as G}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as le,buildDshBindingToolbarMeta as ce,DEFAULT_DSH_PRESETS as he,listDshPlugins as ue,listDshSkills as pe,listDshProfiles as ge,normalizeDshReasoningEffort as fe,normalizeDshThinking as me,resolveDshAgentPreset as ve,resolveDshCatalogForToolbar as _e,resolveDshModeId as j,resolveDshSelectedProfileName as Se}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as k,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as S,SESSION_MODE_IDS as be}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Ce}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as K}from"../audit/raw-capture/types.js";import{syncDefaultSkillsToDir as we}from"../default-skills/index.js";import{buildWireSkills as Ae}from"../core/skill-sync/sync-state.js";import{executeEventTool as Ee}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as ke}from"../adapter/claude/model-list.js";import{applyProxyEnv as Re,getProxyManager as ye}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as Pe}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as Te}from"../core/config/provider-env.js";import{buildProviderEnv as xe}from"../core/config/provider-env.js";import{isClaudeDirectEnv as De,stripGrixRelayEnv as Me}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as He}from"./native-provider-sweep.js";import{scanCodexSessions as Le}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as $e}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as Ie,resolveAcpAgentTypes as Qe,scanAcpSessions as Oe,scanReasonixSessionTitles as Be}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Fe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as qe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as Ue}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ne}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as We}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as P,resolveCodexLeafDirs as Ge,resolveClaudeLeafDirs as je,resolveAcpLeafDirs as Ke,resolvePiLeafDirs as ze,resolveCodeWhaleLeafDirs as Je,resolveCursorLeafDirs as Ye,resolveOpenCodeLeafDirs as Xe,resolveDshLeafDirs as Ve,resolveReasonixLeafDirs as Ze}from"./session-scan-cache.js";import{log as p,ConversationLog as et,AgentApiPacketLog as tt,BridgeEventLog as nt,GRIX_PATHS as L}from"../core/log/index.js";import{routeSessionControlCommand as it,routeSessionControlLocalAction as st}from"./session-control-router.js";import{maybeOfferCliInstall as ot,handleCliInstallQuestionReply as rt,handleCliInstallInteractionReply as at,runConfirmedCliInstall as dt}from"./cli-install-flow.js";import{handleEventCancel as lt,waitForEventDone as ct,handleAibotStop as ht,killAndResumeStopSlot as ut,handleAibotRevoke as pt}from"./event-stop.js";import{handleConfigureGatewayProvider as gt,getAuditLocalActionHandler as ft,handleAuditLocalAction as mt,handleConnectorRollback as vt,getRelayStateSyncer as _t,relayStateSyncOnConnect as St,reportRelayStateLocalChange as bt,handleApplyRelayState as Ct,fetchRelayCredential as wt,isSharedInstance as At}from"./connector-ops.js";import{unbindSession as Et,handleUnbindTextCommand as kt,handleUnbindLocalAction as Rt,handleListSessionsTextCommand as yt,handleListSessionsLocalAction as Pt,handleSyncHistoryLocalAction as Tt}from"./session-list.js";import{handleCodexSessionControlOpen as xt,handleSessionControlForPool as Dt,handleSessionControlLocalActionForPool as Mt,handleCodexSessionControlLocalActionOpen as Ht,handleCursorSessionControlLocalActionOpen as Lt,handlePiSessionControlOpen as $t,handlePiSessionControlRestart as It,handlePiSessionControlRestartLocalAction as Qt,syncOpenCodeBinding as Ot,isWorkspaceFreeClient as Bt,ensureDefaultBindingForWorkspaceFreeClient as Ft,bindSessionForPool as qt,deferredCallbacks as Ut,handleOpenHumanSessionControlOpen as Nt,handleCodeWhaleSessionControlOpen as Wt,handleCodeWhaleSessionControlLocalActionOpen as Gt,handleDeepSeekSessionControlLocalActionOpen as jt}from"./session-control-open.js";import{handleGetSessionUsage as Kt,handleThreadCompact as zt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Jt,handleSkillUploadLocalAction as Yt,handleSkillEnableLocalAction as Xt,handleSkillRefreshLocalAction as Vt,handleSkillDisableLocalAction as Zt,computeSkillReport as en,reportSessionSkills as tn,skillsSyncGroupKey as nn,forceRefreshSkills as sn,adoptSkillsWireHashFromDisk as on,buildLibrarySkillsReport as rn,skillLookupEnv as an}from"./skill-actions.js";import{normalizeClaudeModeId as dn,handleExecCommandOptions as ln,resolveSessionModelId as cn,resolveSessionModeId as hn,resolveCursorSessionModeId as un,resolveClaudeSessionEffort as pn,resolveClaudeSessionModeId as gn,currentClaudeModeId as fn,resolveCodexSessionModelId as mn,resolveCodexNewSessionGlobalDefault as vn,pinCodexGlobalDefault as _n,buildCursorToolbarMeta as Sn,buildAgyToolbarMeta as bn,buildAgyQuotaMeta as Cn,sendAgyBindingCard as wn,refreshAndPushAgyQuota as An,handleAgySetModel as En,buildClaudeToolbarMeta as kn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Rn,maybeQueryProviderQuota as yn,startProviderQuotaTimer as Pn,stopProviderQuotaTimer as Tn,refreshAndPushProviderQuota as xn,pushProviderQuotaToBindings as Dn,enrichProviderQuotaMeta as Mn,providerQuotaMetaPayload as Hn,refreshProviderQuotaForSession as Ln,refreshQuotaAfterModelSwitch as $n,doRefreshQuotaAfterModelSwitch as In}from"./provider-quota.js";import{handleGetRateLimits as Qn,resolveRateLimitWakeSessionId as On,wakeRateLimitSlot as Bn}from"./rate-limits.js";import{RevokeHandler as Fn}from"./revoke-handler.js";import{AdapterPool as qn}from"./adapter-pool.js";import{parseSessionControlCommand as Un,handleSessionControlCommand as Nn,handleSessionControlLocalAction as Wn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Gn,parseExecApprovalResolutionMessage as jn,parseAgentQuestionReplyMessage as Kn}from"../core/protocol/interaction-parser.js";import{isCliMissingError as zn,sessionControlOpenFailure as Jn}from"./cli-install-offer.js";import{handleAcpSetModel as z,handleAcpSetMode as J,resolveAcpInitialDefaults as Yn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Xn}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Vn,handleCreateFolderAction as Zn,serveLocalFile as ei,realHomeDir as Y}from"../core/files/index.js";import{getMachineName as ti}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as ni}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ii}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as si}from"./pending-event-coordinator.js";import{LifecycleBarrier as oi}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ri}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as ai,applyConnectorRuntimeConfigPatch as di,extractConnectorRuntimeConfigPatch as li}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ci,SendController as hi}from"./send-controller.js";import{providerQuotaToRateLimits as ui,providerQuotaToCodexRateLimits as pi}from"../core/provider-quota/index.js";import{buildToolUseCard as D,buildToolResultCard as M,buildDshOnlineToolCard as gi,buildLocalGrixCardLink as X}from"./tool-card-utils.js";import{planRawEventDelivery as fi,buildAuxiliaryDetailText as mi}from"./raw-event-delivery.js";import{DeferredEventManager as vi}from"./deferred-events.js";import{buildAgentProbeResult as _i,PROBE_CACHE_TTL_STATIC_MS as Si,PROBE_CACHE_TTL_FULL_MS as bi}from"./probe-helper.js";import{BridgeAuditController as Ci}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as wi,NoopAuditProducer as Ai}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as $,AuditPreparationFailedError as Ei,AuditTurnScopeUnsupportedError as ki}from"../audit/core/audit-state.js";import{extractAuditOptions as V,freezeAuditOptions as Ri,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Pi}from"../audit/core/audit-session-registry.js";const Ti=600*1e3,Z=1800*1e3,xi=60*1e3,Di=4e3;function Mi(U,e,t){const s=O("sha256").update(U).update("\0").update(e).update("\0").update(t).digest("hex");return T.join(L.data,"audit-source","reasonix",`${s}.jsonl`)}const I=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),ee=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),q=3;class ao{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Fn;sessionBindings=new Map;deferredMgr;sendCtrl=new hi(ai);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new oi;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=xi}resolveProviderQuotaSource(e){return Rn(this,e)}maybeQueryProviderQuota(e=!1,t){return yn(this,e,t)}startProviderQuotaTimer(){Pn(this)}stopProviderQuotaTimer(){Tn(this)}refreshAndPushProviderQuota(e=!1){return xn(this,e)}pushProviderQuotaToBindings(e,t=!1){Dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",s=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){return Mn(this,e,t,s,i)}providerQuotaMetaPayload(e,t,s){return Hn(this,e,t,s)}refreshProviderQuotaForSession(e,t,s){return Ln(this,e,t,s)}refreshQuotaAfterModelSwitch(e,t,s){$n(this,e,t,s)}doRefreshQuotaAfterModelSwitch(e,t,s){return In(this,e,t,s)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,s=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:s,hasData:!!(e||t||s)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const t=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(t()){const s=Math.round(Z/6e4);p.info(this.name,`${e}: active tasks detected, waiting up to ${s}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+Z,n=5e3,o=600*1e3;let r=Date.now();for(;t()&&!this.stopped;){if(Date.now()>=i)return p.warn(this.name,`${e}: idle wait exceeded ${s}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,n)),Date.now()-r>=o&&(r=Date.now(),p.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),t()?(p.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(p.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,s=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let n=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{s=!0,n=!0,p.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),n||(t+=1)}return t>0&&p.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),s?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",s=e.conversation?bi:Si;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<s)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",n=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(n,e.timeoutMs??1e4):void 0;let r;try{r=await _i({adapter:n,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{n.stop().catch(()=>{})}return this.probeCache.set(t,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,t){const s=Date.now(),i="__probe__",n=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||ne(),r=()=>Date.now()-s;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof y)try{await e.bindSession(i,o)}catch{}let a=null;const c=new Promise(h=>{a=g=>{g===n&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:n,session_id:i,content:"ping",msg_id:n}),e.deliverStopEvent(n,i);let d=null;const l=await Promise.race([c.then(()=>!1),new Promise(h=>{d=setTimeout(()=>h(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,t,s=new Ai){this.config=e,this.auditController=new Ci(s,{onAuditState:n=>{try{this.aibotHandle.sendAuditState($(n,Date.now()))}catch{}}}),wi(s)&&s.addJobSettledHandler((n,o)=>{this.auditController.handleJobSettled(n,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ci[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...se]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new et(e.logDir):null,this.packetLog=e.logDir?new tt(e.logDir):null,this.bindingStore=new Xn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new vi(this.name),this.activeEventStore=e.activeEventStorePath?new ii(e.activeEventStorePath):null,this.pendingEvents=new si(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new P(Le,Ge);else if(i==="claude")this.sessionScanCache=new P($e,je);else if(i==="pi"){const n=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new P(()=>Fe(void 0,n),()=>ze(void 0,n))}else if(i==="codewhale")this.sessionScanCache=new P(qe,Je);else if(i==="cursor")this.sessionScanCache=new P(Ue,Ye);else if(i==="opencode")this.sessionScanCache=new P(Ne,Xe);else if(i==="deepseek-harness"){const n=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new P(()=>We(n),()=>Ve(n))}else if(i==="agy")this.sessionScanCache=new P(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new P(Be,Ze));const n=Qe(e.aibot.clientType);this.sessionScanCache=n?new P(()=>Oe(void 0,n),()=>Ke(void 0,n)):new P(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await He({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,n])=>String(n.cwd??""))}).then(n=>{n.length>0&&p.info(this.name,`restored native provider config after relay disable: ${n.join(", ")}`)}).catch(n=>{p.warn(this.name,`native provider residue sweep failed: ${n instanceof Error?n.message:String(n)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await ke().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",s=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||s)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new qn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},n=>{const o=this.createAdapter(i,n);return o instanceof y&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(n,r),this.sessionScanCache.invalidate()}),o},(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((n,o,r,a)=>{if(p.info(this.name,`[queue-debug] send event_state session=${o} event=${n} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:n,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(n),this.pendingEvents.remove(n).catch(c=>{p.warn(this.name,`Failed to remove running event from pending store event=${n}: ${c instanceof Error?c.message:String(c)}`)})),r==="canceled"||r==="failed"){const c=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:n,status:c,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(n,c,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(n),this.pendingEvents.remove(n).catch(d=>{p.warn(this.name,`Failed to remove queued terminal event from pending store event=${n}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:o,...o?{ttl_ms:ri,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(n=>{this.handleSessionInternalError(n).catch(o=>{p.error(this.name,`[recovery] handleSessionInternalError failed event=${n.eventId} session=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((n,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((n,o)=>{this.markAuditAdapterClosed(n,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const c=this.buildAgyToolbarMeta(o),d=c?.available_models??[];p.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(c?.model_id??"")} available_models=${d.length} meta_keys=${c?Object.keys(c).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,c),this.refreshAndPushAgyQuota(o)}else p.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((n,o,r)=>{const a=this.selfDrivenSessions.has(n),c=this.selfDrivenLabels.get(n);o?(this.selfDrivenSessions.add(n),r&&this.selfDrivenLabels.set(n,r),this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(n),this.selfDrivenLabels.delete(n),a&&this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==c)&&this.pushQueueSnapshotForSession(n)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),p.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)p.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=t.get(r),c=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,c?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const s=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],n=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...s.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){p.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(n)}catch(r){p.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of n){const a=r.event;p.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){p.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=xe(this.config.agent.clientType,e),s=this.config.agent.env;let i=Object.keys(t).length>0?{...t,...s}:s;if(De(t)){const n=ye()?.getRuntimeInfo(),o={...s??{},...t},r=Me(o,{proxyUrl:n?.proxyUrl,caCertPath:n?.caCertPath,caBundlePath:n?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(Te(this.config.agent.clientType)){const n=Pe(this.name);n&&(i={...i??{},...n})}return Re(i,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Di),sendThinking:(n,o,r)=>this.sendThinkingByRuntimeConfig(n,o,r),sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,void 0,a)},sendRawEventEnvelope:(n,o,r,a)=>{const c=gi(r);if(c){this.sendToolExecutionCard(n,o,c);return}this.deliverRawEventEnvelope(n,o,r,"deepseek",a)},sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"deepseek")},sendUpdateBindingCard:(n,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:n=>this.maybeQueryProviderQuota(n===!0,{providerId:"deepseek"}),agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),eventToolInvoke:async(n,o)=>this.invokeDshEventTool(n,o)},s=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new le({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:T.join(L.data,"deepseek-harness",s),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const s=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(t.model=i);const n=this.resolveCursorSessionModeId(e),o=n??"full_auto";n||this.bindingStore.setCursorModeId(e,o),t.mode=o,s?.cwd&&(t.workspace=s.cwd);const r={sendStreamChunk:(a,c,d,l,h,g,u)=>{this.sendStreamChunkByRuntimeConfig(a,c,d,l,h,g,u)},sendEventResult:(a,c,d)=>{this.sendEventResultWithCleanup(a,c,d)},sendEventAck:(a,c)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:c,received_at:Date.now()})},sendRawEventEnvelope:(a,c,d)=>{this.deliverRawEventEnvelope(a,c,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,c,d)=>{const l=d.questions.map(g=>g.header).join(", "),h=X(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:c,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,c,d)=>this.platformInvoke(a,c,d),sendLocalActionResult:(a,c,d,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:c,...d!==void 0?{result:d}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,c,d,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:c,cwd:d,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new ae({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},r)}createClaudeAdapter(e){const t={sendReply:(n,o,r,a,c)=>{this.sendReplyByRuntimeConfig(n,o,r,a,c)},sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendMedia:(n,o,r,a,c,d,l)=>{this.aibotHandle.sendMedia({event_id:n,session_id:o,content:r,msg_type:2,quoted_message_id:c||void 0,client_msg_id:d||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,a)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,D(r,a))},sendToolResult:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,M(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(n,o,r)=>{this.sendGrixAgentQuestionCard(n,o,r)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"claude")},sendDirectMessage:n=>{this.aibotHandle.sendMsg({session_id:n.sessionId,msg_type:1,content:n.content,...n.clientMsgId?{client_msg_id:n.clientMsgId}:{},...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})},onStatusLineUpdated:n=>{(n.rateLimits?.fiveHour||n.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=n);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:n=>{this.aibotHandle.sendMcpFrame(e,n)}},s=this.config.adapterOptions??{},i={...s,sessionRuntimeResolver:()=>{const n=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:n?.cwd,modeId:this.resolveClaudeSessionModeId(e)??be.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:n?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t)}createCodexAdapter(e){let t=null;const s={sendEventResult:(r,a,c)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,c);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,c),d=>{const l=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:c)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,c)=>{this.sendThinkingByRuntimeConfig(r,a,c)},sendRunError:(r,a,c)=>{this.sendRunErrorAsChunk(r,a,c)},sendUpdateBindingCard:(r,a,c,d)=>{const l={...d??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:c,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,c)=>this.platformInvoke(r,a,c),sendLocalActionResult:(r,a,c,d,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...c!==void 0?{result:c}:{},...d?{error_code:d}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,c,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:c,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const c=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:c},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:r,...t?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},n=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return t=new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(n?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(n?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...K(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:T.join(L.data,"audit-replay","raw-spool")}}:{}}},s),t}createCodeWhaleAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,n,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new de({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??s.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[pi] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c),a&&p.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
2
2
 
3
- Error: ${o}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},s=this.config.adapterOptions??{};return new se({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:async(i,n,o,r)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(i,n,r)}catch(a){throw p.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${i}: ${a}`),a}},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[openhuman] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,x(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
3
+ Error: ${o}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},s=this.config.adapterOptions??{};return new oe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:async(i,n,o,r)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(i,n,r)}catch(a){throw p.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${i}: ${a}`),a}},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[openhuman] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
4
4
 
5
- Error: ${o}`,0,!1)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new oe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,host:s.host,workspaceDir:s.workspace_dir,sessionToken:s.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[opencode] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,x(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendRunErrorAsChunk(i,n,o)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"opencode")},sendAgentQuestionCard:(i,n,o)=>{this.sendGrixAgentQuestionCard(i,n,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new B({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,hostname:s.hostname,model:s.model??this.resolveSessionModelId(e),agent:s.agent,permissionPolicy:s.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),forceCompleteInternalEvent:(i,n)=>{this.pool.eventComplete(i,n),this.pushQueueSnapshotForSession(n)},persistConversationId:(i,n)=>{this.bindingStore.setAgyConversationId(i,n)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=i=>{const n=this.bindingStore.get(i);return{cwd:n?.cwd,modelId:this.resolveSessionModelId(i),conversationId:n?.agyConversationId}};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,s)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),s={sendStreamChunk:(d,l,h,u,g,v,f)=>{this.sendStreamChunkByRuntimeConfig(d,l,h,u,g,v,f)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,l,h)=>{this.sendEventResultWithCleanup(d,l,h)},sendEventAck:(d,l)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:l,received_at:Date.now()})},agentInvoke:async(d,l,h)=>this.platformInvoke(d,l,h),sendLocalActionResult:(d,l,h,u,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:l,...h!==void 0?{result:h}:{},...u?{error_code:u}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,l,h)=>{this.sendAcpRawEventEnvelope(d,l,h)},sendToolUse:(d,l,h,u)=>{if(t){this.sendAcpRawEventEnvelope(d,l,{type:"tool_use",payload:{tool_name:h,tool_input:u??""}});return}this.sendToolExecutionCard(d,l,x(h,u))},sendToolResult:(d,l,h,u)=>{this.sendToolExecutionCard(d,l,D(h,u))},sendThinking:(d,l,h)=>{this.sendThinkingByRuntimeConfig(d,l,h)},sendRunError:(d,l,h)=>{this.sendStreamChunkByRuntimeConfig(d,l,`
5
+ Error: ${o}`,0,!1)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new re({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,host:s.host,workspaceDir:s.workspace_dir,sessionToken:s.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[opencode] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendRunErrorAsChunk(i,n,o)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"opencode")},sendAgentQuestionCard:(i,n,o)=>{this.sendGrixAgentQuestionCard(i,n,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new F({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,hostname:s.hostname,model:s.model??this.resolveSessionModelId(e),agent:s.agent,permissionPolicy:s.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),forceCompleteInternalEvent:(i,n)=>{this.pool.eventComplete(i,n),this.pushQueueSnapshotForSession(n)},persistConversationId:(i,n)=>{this.bindingStore.setAgyConversationId(i,n)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=i=>{const n=this.bindingStore.get(i);return{cwd:n?.cwd,modelId:this.resolveSessionModelId(i),conversationId:n?.agyConversationId}};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,s)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),s={sendStreamChunk:(d,l,h,g,u,f,b)=>{this.sendStreamChunkByRuntimeConfig(d,l,h,g,u,f,b)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,l,h)=>{this.sendEventResultWithCleanup(d,l,h)},sendEventAck:(d,l)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:l,received_at:Date.now()})},agentInvoke:async(d,l,h)=>this.platformInvoke(d,l,h),sendLocalActionResult:(d,l,h,g,u)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:l,...h!==void 0?{result:h}:{},...g?{error_code:g}:{},...u?{error_msg:u}:{}},e)},sendRawEventEnvelope:(d,l,h)=>{this.sendAcpRawEventEnvelope(d,l,h)},sendToolUse:(d,l,h,g)=>{if(t){this.sendAcpRawEventEnvelope(d,l,{type:"tool_use",payload:{tool_name:h,tool_input:g??""}});return}this.sendToolExecutionCard(d,l,D(h,g))},sendToolResult:(d,l,h,g)=>{this.sendToolExecutionCard(d,l,M(h,g))},sendThinking:(d,l,h)=>{this.sendThinkingByRuntimeConfig(d,l,h)},sendRunError:(d,l,h)=>{this.sendStreamChunkByRuntimeConfig(d,l,`
6
6
 
7
- Error: ${h}`,1,!1)},sendAgentQuestionCard:(d,l,h)=>{this.sendGrixAgentQuestionCard(d,l,h)},sendPermissionCard:d=>{p.info("bridge","sendPermissionCard callback entered",{rawTransport:t,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(t){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}}),p.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const h=`perm_${O()}`,u={event_id:d.eventId,session_id:d.sessionId,client_msg_id:h,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,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};p.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:h,toolCallId:d.toolCallId,contentLength:u.content.length});try{this.aibotHandle.sendMsg(u),p.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:h})}catch(g){p.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:h,error:g instanceof Error?g.message:String(g)})}},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,h,u)=>{const g={...u??{}};if(!g.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const v=this.providerQuotaToRateLimits(this.cachedProviderQuota);v&&(g.rate_limits=v)}!g.provider_quota&&this.cachedProviderQuota?.success&&(g.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:h,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:we(d,H.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},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);p.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const u="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:u,remainingPercentage:100-u}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),g.provider_quota=this.cachedProviderQuota;const v=this.providerQuotaToRateLimits(this.cachedProviderQuota);v&&(g.rate_limits=v)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,n=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&n?Di(this.name,e,n.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Jn({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&c&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,c),(a||c)&&p.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new k({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},s,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,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 tt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const t=await new ne().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const s=this.aibotHandle.authAck;if(this.applyAgentProfile(s?.agent_name,s?.introduction,{source:"auth_ack",respawnOnChange:!1},s?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(n=>{p.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof k&&a.adapter.getSessionBindings().delete(i.session_id);const c=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(c);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:A.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(n){p.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(i=>{p.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){p.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(n){p.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(n){p.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{p.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(n){p.error(this.name,`onSkillSync failed: ${n}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(n=>{p.error(this.name,`handleAibotRevoke failed: ${n}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(n=>{p.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(i=>{p.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(n=>{p.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((i,n)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(n):p.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const n=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const n=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,n);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(p.info(this.name,`recv event_hold event_id=${o} session_id=${n} hold=${r} reason=${i.reason??""}`),!n||!o){this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",c=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,d=this.pool.holdEvent(n,o,r,a,c),l=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:d}}),l&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(p.info(this.name,`recv queue_edit event_id=${o} session_id=${n}`),!n||!o){this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:!1,error:"bad_request"});return}const r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(n,o,r),c=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:c,...c?{}:{error:a}}),c&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),p.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){p.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const n of i)p.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,n)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,t,s,i){const n=String(e??"").trim(),o=String(t??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=n!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:n,introduction:o},this.agentSystemPrompt=r,n||o?p.info(this.name,`agent profile (${s.source}): GOT name="${n}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):p.warn(this.name,`agent profile (${s.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&s.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let s=0;for(const r of t)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),s++}catch(a){p.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=t.filter(r=>r.adapter instanceof U),n=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-n.length;p.info(this.name,`${e}: notified ${s} adapter(s) via hook; respawning ${n.length} idle Claude slot(s), skipping ${o} busy`);for(const r of n)this.pool.removeSlot(r.sessionId).catch(a=>{p.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 t=this.pool?.getQueueSnapshot(e)??null,s=t?[...t.running]:[],i=t?t.running_items.map(o=>({event_id:o.event_id,...o.content_preview?{content_preview:o.content_preview}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},actions:[{type:"stop"}]})):[],n=t?t.queued.map(o=>({event_id:o.event_id,position:o.position,...o.content_preview?{content_preview:o.content_preview}:{},...typeof o.content=="string"?{content:o.content}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},held:o.held===!0,held_reason:o.held_reason??"",actions:[{type:"cancel"}]})):[];if(s.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";s.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:s,running_items:i,queued:n}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);p.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,s){return e==="file_link"?Zn(t):e==="file_upload"?this.uploadFileAndSendMedia(t):this.aibotHandle.agentInvoke(e,t,s)}invokeDshEventTool(e,t){const s=Ae(this.aibotHandle,e,t),i=s.content[0]?.text??"";if(s.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),s=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),n=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!s)throw new Error("session_id is required");const o=await ti({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:s,filePath:t}),r=await this.aibotHandle.sendMedia({session_id:s,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${O()}`,...n?{quoted_message_id:n}:{},extra:o.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:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,s,i,n){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,s),this.sendCtrl.sendReply(e,o,s,i,n),s&&this.conversationLog?.logOutbound?.(o,e,"reply",s)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const i=t.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const n=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return n?{...e,quoted_message_id:n}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,s=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(s&&s!=="final_answer")return;const i=t?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(s,i,n)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(s,i,n,t)}catch(o){throw p.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${s}: ${o}`),o}p.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${s}`)}}sendStreamChunkByRuntimeConfig(e,t,s,i,n,o,r){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,i,s),this.sendCtrl.sendStreamChunk(e,a,s,i,n,o,r),(s||n)&&this.conversationLog?.logOutbound?.(a,e,n?"stream_chunk_finish":"stream_chunk",s)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,t,s){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,t,`
7
+ Error: ${h}`,1,!1)},sendAgentQuestionCard:(d,l,h)=>{this.sendGrixAgentQuestionCard(d,l,h)},sendPermissionCard:d=>{p.info("bridge","sendPermissionCard callback entered",{rawTransport:t,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(t){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}}),p.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const h=`perm_${B()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:h,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,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};p.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:h,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),p.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:h})}catch(u){p.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:h,error:u instanceof Error?u.message:String(u)})}},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,h,g)=>{const u={...g??{}};if(!u.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}!u.provider_quota&&this.cachedProviderQuota?.success&&(u.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:h,...Object.keys(u).length>0?{meta:u}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Ae(d,L.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},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);p.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),u={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(()=>{}),u.provider_quota=this.cachedProviderQuota;const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:u})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,n=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&n?Mi(this.name,e,n.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Yn({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&c&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,c),(a||c)&&p.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},s,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,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 nt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const t=await new ie().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const s=this.aibotHandle.authAck;if(this.applyAgentProfile(s?.agent_name,s?.introduction,{source:"auth_ack",respawnOnChange:!1},s?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(n=>{p.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof y&&a.adapter.getSessionBindings().delete(i.session_id);const c=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(c);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(n){p.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(i=>{p.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){p.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(n){p.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(n){p.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{p.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(n){p.error(this.name,`onSkillSync failed: ${n}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(n=>{p.error(this.name,`handleAibotRevoke failed: ${n}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(n=>{p.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(i=>{p.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(n=>{p.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((i,n)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(n):p.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const n=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const n=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,n);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(p.info(this.name,`recv event_hold event_id=${o} session_id=${n} hold=${r} reason=${i.reason??""}`),!n||!o){this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",c=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,d=this.pool.holdEvent(n,o,r,a,c),l=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:d}}),l&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(p.info(this.name,`recv queue_edit event_id=${o} session_id=${n}`),!n||!o){this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:!1,error:"bad_request"});return}const r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(n,o,r),c=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:c,...c?{}:{error:a}}),c&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),p.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){p.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const n of i)p.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,n)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,t,s,i){const n=String(e??"").trim(),o=String(t??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=n!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:n,introduction:o},this.agentSystemPrompt=r,n||o?p.info(this.name,`agent profile (${s.source}): GOT name="${n}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):p.warn(this.name,`agent profile (${s.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&s.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let s=0;for(const r of t)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),s++}catch(a){p.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=t.filter(r=>r.adapter instanceof N),n=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-n.length;p.info(this.name,`${e}: notified ${s} adapter(s) via hook; respawning ${n.length} idle Claude slot(s), skipping ${o} busy`);for(const r of n)this.pool.removeSlot(r.sessionId).catch(a=>{p.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 t=this.pool?.getQueueSnapshot(e)??null,s=t?[...t.running]:[],i=t?t.running_items.map(o=>({event_id:o.event_id,...o.content_preview?{content_preview:o.content_preview}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},actions:[{type:"stop"}]})):[],n=t?t.queued.map(o=>({event_id:o.event_id,position:o.position,...o.content_preview?{content_preview:o.content_preview}:{},...typeof o.content=="string"?{content:o.content}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},held:o.held===!0,held_reason:o.held_reason??"",actions:[{type:"cancel"}]})):[];if(s.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";s.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:s,running_items:i,queued:n}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);p.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,s){return e==="file_link"?ei(t):e==="file_upload"?this.uploadFileAndSendMedia(t):this.aibotHandle.agentInvoke(e,t,s)}invokeDshEventTool(e,t){const s=Ee(this.aibotHandle,e,t),i=s.content[0]?.text??"";if(s.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),s=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),n=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!s)throw new Error("session_id is required");const o=await ni({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:s,filePath:t}),r=await this.aibotHandle.sendMedia({session_id:s,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${B()}`,...n?{quoted_message_id:n}:{},extra:o.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:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,s,i,n){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,s),this.sendCtrl.sendReply(e,o,s,i,n),s&&this.conversationLog?.logOutbound?.(o,e,"reply",s)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const i=t.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const n=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return n?{...e,quoted_message_id:n}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,s=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(s&&s!=="final_answer")return;const i=t?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(s,i,n)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(s,i,n,t)}catch(o){throw p.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${s}: ${o}`),o}p.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${s}`)}}sendStreamChunkByRuntimeConfig(e,t,s,i,n,o,r){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,i,s),this.sendCtrl.sendStreamChunk(e,a,s,i,n,o,r),(s||n)&&this.conversationLog?.logOutbound?.(a,e,n?"stream_chunk_finish":"stream_chunk",s)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,t,s){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,t,`
8
8
 
9
- Error: ${s}`,1,!1))}sendEventResultWithCleanup(e,t,s,i,n=!1){const o=this.eventSessionIndex.get(e);n&&this.surfacedRunErrorEvents.add(e),t==="failed"&&o&&s?.trim()&&this.sendRunErrorAsChunk(e,o,s),this.auditController.markResponded(e,t,s),this.sendCtrl.sendEventResult(e,t,s,i),o&&(this.pool.eventComplete(e,o)===!1&&p.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${t}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,t,s),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{p.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:s,errorMsg:i}=e;if(this.stopped)return;const n=this.inflightEvents.get(t);if(!n){p.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${s}; surface failure directly`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const r=this.config.adapterType??"acp";if(o>F){p.error(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${F} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}p.info(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${F} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(s);a.length>0&&p.info(this.name,`[recovery] session=${s} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(s)}catch(l){p.warn(this.name,`[recovery] removeSlot failed session=${s}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=e.replayOriginalContent?n.content:this.resolveRecoveryPrompt(r,n),d={...n,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){p.error(this.name,`[recovery] redeliver failed event=${t} session=${s}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(t,"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(h){p.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${s}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,s){this.sendCtrl.sendThinking(e,t,s)}bufferStreamChunk(e,t,s,i,n){this.auditController.captureUnsequencedStreamChunk(e,s),this.sendCtrl.bufferOnly(e,t,s,i,n)}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)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(i=>i.event.event_id).filter(Boolean)),s=[];p.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const n=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)):(this.restorePendingReplayAuditTurn(n),this.deferredMgr.defer(i.channel,i.sessionId,n),s.push(i))}else await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);p.error(this.name,`Pending event replay failed event=${n.event_id}: ${r}`),this.sendEventResultWithCleanup(n.event_id,"failed",r),this.pendingEvents.markCanceled(n.event_id),await this.pendingEvents.remove(n.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(t,[...s,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,s))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(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_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const s=ki({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!s.enabled)return;const i=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:s,createdAt:new Date().toISOString()}),n=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});n&&(e.audit={...t,auditId:n.auditId,turnId:n.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const s=this.eventSessionIndex.get(e);return s?(s!==t&&p.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${s} supplied=${t}`),s):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const s=e.codex_payload?.params?.delta;if(!s)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:s.length,content:s})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,s){this.shouldDropAcpRawDisplayEvent(e,s.type)||this.deliverRawEventEnvelope(e,t,s,"acp",this.buildAcpRawEventFallbackText(s))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){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] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,s,i,n){const o=gi({envelope:s,fallbackText:n,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}p.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,fi({envelopeType:s.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{p.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),s=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(s.tool_title??s.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(s.tool_name??s.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(s.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,s,i){this.sendCtrl.sendToolExecutionCard(e,t,s,i)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${O()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,s){const i=s.questions.map(o=>o.header).join(", "),n=Y(`[Agent Question] ${s.request_id}`,"agent_question",s);this.aibotHandle.sendText({event_id:e,session_id:t,content:n,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const t=jn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=i instanceof k?"acp":i instanceof B?"opencode":this.config.adapterType??"unknown",o=i instanceof B?i.handleQuestionReplyEvent(t):i instanceof k?await i.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(p.info(this.name,`[${n}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${n}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${o.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode??"interaction_reply_failed",msg:o.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=Gn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=t.params,o=String(n.tool_call_id??n.approval_command_id??n.approval_id??n.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.handleExecApprovalEvent({...n,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return r.delivered?(p.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${o||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}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 t=this.config.adapterType??"acp",s=qn(e);let i;if(s&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const n=di(e.extra);if(n.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:n.error,updated_at:Date.now()});return}const o=n.patch,r=X(e.extra);if((r.state!=="absent"||r.error)&&p.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){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_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,u=h.extra,g=h.audit??(u&&typeof u=="object"?u.audit:void 0);return!g||typeof g!="object"?!1:g.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState(L({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&t!=="claude"&&t!=="codex"&&t!=="cursor"&&t!=="opencode"&&t!=="pi"&&t!=="codewhale"&&t!=="deepseek-harness"&&t!=="agy"&&t!=="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: ${t}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState(L({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: ${t}`},Date.now()))}catch{}return}if(s){if(r.state!=="absent"||s.verb===S.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(s.verb===S.exec){await this.handleSessionControlCommand(s,e);return}if(s.verb===S.listSessions){await this.handleListSessionsTextCommand(e);return}if(s.verb===S.unbind){await this.handleUnbindTextCommand(e);return}if(t==="claude"){await this.handleSessionControlCommand(s,e);return}if(t==="codex"&&s.verb===S.open){await this.handleCodexSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.open){await this.handlePiSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.restart){await this.handlePiSessionControlRestart(e);return}if((t==="openhuman"||t==="opencode")&&s.verb===S.open){await this.handleOpenHumanSessionControlOpen(s,e);return}if(t==="codewhale"&&s.verb===S.open){await this.handleCodeWhaleSessionControlOpen(s,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===S.open){const l=s.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:A.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=P.resolve(l);if(!(await I(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:A.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const u=String(h?.code??""),g=u==="ENOENT"?`Directory does not exist: ${P.resolve(l)}`:u==="EACCES"||u==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:A.invalidCwd,msg:g,updated_at:Date.now()});return}}if(s.verb===S.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await I(l.cwd)}catch{p.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.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 h=this.pool.getSlot(e.session_id);h?.adapter instanceof k&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(s,e),t==="acp"&&s.verb===S.stop){const h=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 ${h}`,updated_at:Date.now()});return}if(Un(s,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===S.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),t==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}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 a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(Z.has(t)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),Z.has(t)&&!this.bindingStore.get(e.session_id)?.cwd){const h=t,u=this.prepareAuditedInboundEvent(e,o,a);p.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const v=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:u});if(this.lifecycleBarrier.isClosed()&&!v)throw new Error("pending event store unavailable during lifecycle drain")}catch(v){const f=v instanceof Error?v.message:String(v);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",f,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(u,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),u);const g=this.resolveBindingChannelKey(t);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:{[g]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:A.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,u,g]=h,f=this.pool.getSlot(e.session_id)?.adapter;if(f?.execCommand&&(f.getSupportedCommands?.()??[]).some(m=>m.name===u||m.name===`/${u}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await f.execCommand(u,g.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,u,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&j(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof N&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(p.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)):p.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),p.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{p.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,t){const s=t instanceof Error?t.message:String(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",s,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:s,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return Tt(this,e,t)}handleSessionControlForPool(e,t){return xt(this,e,t)}handleSessionControlLocalActionForPool(e){return Dt(this,e)}handleCodexSessionControlLocalActionOpen(e){return Mt(this,e)}handleCursorSessionControlLocalActionOpen(e){return Ht(this,e)}handlePiSessionControlOpen(e,t){return Lt(this,e,t)}handlePiSessionControlRestart(e){return $t(this,e)}handlePiSessionControlRestartLocalAction(e){return It(this,e)}syncOpenCodeBinding(e,t){return Qt(this,e,t)}isWorkspaceFreeClient(){return Ot(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Bt(this,e,t)}bindSessionForPool(e,t){return Ft(this,e,t)}deferredCallbacks(){return qt(this)}handleOpenHumanSessionControlOpen(e,t){return Ut(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Nt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Wt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return Gt(this,e)}normalizeClaudeModeId(e){return an(this,e)}handleExecCommandOptions(e,t,s){dn(this,e,t,s)}resolveSessionModelId(e){return ln(this,e)}resolveSessionModeId(e){return cn(this,e)}resolveCursorSessionModeId(e){return hn(this,e)}resolveClaudeSessionEffort(e){return un(this,e)}resolveClaudeSessionModeId(e){return pn(this,e)}currentClaudeModeId(e){return gn(this,e)}resolveCodexSessionModelId(e){return fn(this,e)}resolveCodexNewSessionGlobalDefault(e,t,s){return mn(this,e,t,s)}pinCodexGlobalDefault(e,t){return vn(this,e,t)}buildCursorToolbarMeta(e){return _n(this,e)}buildAgyToolbarMeta(e,t){return Sn(this,e,t)}buildAgyQuotaMeta(e){return bn(this,e)}sendAgyBindingCard(e,t,s){return Cn(this,e,t,s)}refreshAndPushAgyQuota(e,t=!1){return wn(this,e,t)}handleAgySetModel(e,t){return An(this,e,t)}buildClaudeToolbarMeta(e){return En(this,e)}providerQuotaToCodexRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return hi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const t=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t))){const n=new Error(`Specified path is not valid on this host: ${t}`);throw n.cwdErrorCode=A.invalidCwd,n}const s=P.resolve(t);let i;try{i=await I(s)}catch(n){const o=String(n?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${s}`);throw r.cwdErrorCode=A.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=A.invalidCwd,r}throw n}if(!i.isDirectory()){const n=new Error("Specified path is not a directory.");throw n.cwdErrorCode=A.invalidCwd,n}try{return await ee(s)}catch{return s}}failSessionOpen(e,t){const{code:s,msg:i}=zn(e);return this.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(s,i),{code:s,msg:i}}maybeOfferCliInstall(e){st(this,e)}handleCliInstallQuestionReply(e){return ot(this,e)}handleCliInstallInteractionReply(e){return rt(this,e)}runConfirmedCliInstall(e,t){return at(this,e,t)}getClaudeWorkerStatus(e){const t=this.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,t){const s=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,s),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:s,cwd:t,meta:this.buildClaudeToolbarMeta(e)}),s}handleSkillDeleteLocalAction(e){return zt(this,e)}handleSkillUploadLocalAction(e){return Jt(this,e)}handleSkillEnableLocalAction(e){return Yt(this,e)}handleSkillRefreshLocalAction(e){Xt(this,e)}handleSkillDisableLocalAction(e){return Vt(this,e)}computeSkillReport(e){return Zt(this,e)}reportSessionSkills(e){en(this,e)}skillsSyncGroupKey(){return tn(this)}forceRefreshSkills(e,t){return nn(this,e,t)}adoptSkillsWireHashFromDisk(){sn(this)}buildLibrarySkillsReport(e){return on(this,e)}skillLookupEnv(){return rn(this)}async ensureSlotStarted(e,t=6e4){const s=await this.pool.getOrCreateSlot(e);if(!s)throw new Error("Failed to allocate session slot");s.startPromise&&(p.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([s.startPromise,new Promise((i,n)=>setTimeout(()=>n(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),p.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const t=$e(e);if(!t)return;const s=this.reasonixTitleScan.get().filter(i=>i.stamp===t);return s.length===1?s[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(s=>s.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;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,t){const s=String(e??"").trim(),i=String(t??"").trim();if(!s||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(s,i);break;case"codex":this.bindingStore.setCodexThreadId(s,i);break;case"pi":this.bindingStore.setPiSessionPath(s,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(s,i);break;case"agy":this.bindingStore.setAgyConversationId(s,i);break;default:this.bindingStore.setAcpSessionId(s,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const t=String(e??"").trim();if(!t)return"";const s=P.resolve(t);return process.platform==="win32"?s.toLowerCase():s}ensureImportedAgentSession(e,t){const s=String(e??"").trim();if(!s)return;const i=this.normalizePathForCompare(t);let n="";const o=this.config.adapterType??"acp";if(o==="codex"?n=this.sessionScanCache.get().find(c=>c.threadId===s)?.cwd??"":o==="claude"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="cursor"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="acp"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="deepseek-harness"&&(n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??""),!n){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===s){n=a.cwd??"";break}}if(!n){const a=new Error(`agent session not found: ${s}`);throw a.sessionControlErrorCode=A.invalidAgentSession,a}const r=this.normalizePathForCompare(n);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${t}, got ${n}`);throw a.sessionControlErrorCode=A.invalidAgentSession,a}}buildOpenedBindingResult(e,t,s="ready"){const i=this.bindingStore.get(e),n=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:t,workerStatus:s};return n&&(o.bindingId=n,o.agentSessionId=n),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const t=this.globalConfigStore?.get(this.name),s=this.bindingStore.get(e),i=this.config.adapterOptions??{},n=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const b=me(t?.dshAgentPreset,ce);this.bindingStore.setDshAgentPreset(e,b)}const o=this.bindingStore.getDshSelectedProfile(e),r=_e({binding:o,global:t?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),c=this.bindingStore.getDshSettings(e),d=c?.providerId??t?.dshProviderId,l=ve({dataRoot:a,providerId:d}),h=[c?.modelId,t?.dshModelId,l.models[0]?.id].find(b=>!!b&&l.models.some(_=>_.id===b))??l.models[0]?.id,u=G(s?.dshModeId,t?.dshModeId),g={};!s?.dshProviderId&&l.providerId&&(g.providerId=l.providerId),!s?.dshModelId&&h&&(g.modelId=h),s?.dshModeId||(g.modeId=u),s?.dshThinking||(g.thinking=fe(t?.dshThinking)??"enabled"),s?.dshReasoningEffort||(g.reasoningEffort=ge(t?.dshReasoningEffort)??"high"),Object.keys(g).length>0&&this.bindingStore.updateDshSettings(e,g);const v=this.bindingStore.getDshSettings(e);let f=[],C=[],m=!1;try{f=he({dshHome:n,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),m=!1}catch{}const y=P.join(a,"dsh-session-skills");return Ce(y),C=ue({skillsDir:y,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),le({agentPreset:v?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:pe({dshHome:n}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:f,skills:C,pluginRestartRequired:m,providerId:v?.providerId??l.providerId,modelId:v?.modelId??h,modeId:G(this.bindingStore.get(e)?.dshModeId,t?.dshModeId),thinking:v?.thinking,reasoningEffort:v?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=Q("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return P.join(H.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}unbindSession(e){return At(this,e)}handleUnbindTextCommand(e){return Et(this,e)}handleUnbindLocalAction(e){return kt(this,e)}handleListSessionsTextCommand(e){return Rt(this,e)}handleListSessionsLocalAction(e){return yt(this,e)}handleSyncHistoryLocalAction(e){return Pt(this,e)}handleSessionControlCommand(e,t){return nt(this,e,t)}handleSessionControlLocalAction(e){return it(this,e)}handleEventCancel(e){return dt(this,e)}waitForEventDone(e,t,s){return lt(this,e,t,s)}handleAibotStop(e){ct(this,e)}killAndResumeStopSlot(e,t){return ht(this,e,t)}handleAibotRevoke(e){return ut(this,e)}handleConfigureGatewayProvider(e){return pt(this,e)}getAuditLocalActionHandler(){return gt(this)}handleAuditLocalAction(e){return ft(this,e)}handleConnectorRollback(e){return mt(this,e)}getRelayStateSyncer(){return vt(this)}relayStateSyncOnConnect(){_t(this)}reportRelayStateLocalChange(){St(this)}handleApplyRelayState(e){return bt(this,e)}fetchRelayCredential(e){return Ct(this,e)}isSharedInstance(){return wt(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",s=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();p.debug(this.name,`local_action received action_type=${t} verb=${i||"-"} action_id=${e.action_id} session_id=${s}`);let n;if(t===E.sessionControl&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===E.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(be(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===E.sessionControl&&i===S.exec&&await this.handleSessionControlLocalAction(e))return;if(t===E.sessionControl&&i===S.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===E.sessionControl&&i===S.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===E.sessionControl&&i===S.unbind){await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(t===E.interactionReply||t==="exec_approve"||t==="exec_reject")||r&&t===E.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===E.sessionControl){const u=this.config.adapterType??"acp",g=u==="codex",v=u==="pi",f=String((e.params??{}).verb??"").trim().toLowerCase();if(g&&f===S.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(u==="cursor"&&f===S.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(g&&f==="restart"){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:s,cwd:_,workerStatus:"ready"}}});return}if(v&&f===S.open){try{const b=e.params??{},_=String(b.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:A.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(_),T=String(b.agent_session_id??"").trim();this.ensureImportedAgentSession(T,w),this.bindingStore.set(s,w),this.setResolvedAgentSessionId(s,T),this.sessionBindings.set(s,w),await this.ensureSlotStarted(s).catch(M=>{if(Kn(M))throw M;p.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,w)}})}catch(b){this.failSessionOpen(b,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,w)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:w})})}return}if(v&&f===S.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((u==="openhuman"||u==="opencode")&&f===S.open){try{const b=e.params??{},_=String(b.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:A.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(_),T=String(b.agent_session_id??"").trim();this.ensureImportedAgentSession(T,w),this.bindingStore.set(s,w),this.setResolvedAgentSessionId(s,T),this.sessionBindings.set(s,w),await this.syncOpenCodeBinding(s,w),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,w)}})}catch(b){this.failSessionOpen(b,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,w)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:w})})}return}if(u==="codewhale"&&f===S.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(u==="deepseek-harness"&&f===S.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(u==="acp"&&f===S.stop){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:s,cwd:_,workerStatus:"stopped"}}});return}try{if(f===S.open){const b=e.params??{},_=String(b.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:A.cwdRequired,error_msg:"session cwd is required"});return}const w=String(b.agent_session_id??"").trim();if(w){const T=await this.resolveCwdForBinding(_);this.ensureImportedAgentSession(w,T)}}await this.handleSessionControlLocalActionForPool(e)}catch(b){this.failSessionOpen(b,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,w)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:w})});return}if(f===S.open){const b=e.params??{},_=await this.resolveCwdForBinding(String(b.cwd??"").trim());this.setResolvedAgentSessionId(s,String(b.agent_session_id??"").trim()),u==="agy"&&(this.bindingStore.set(s,_),this.sessionBindings.set(s,_)),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,_)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(s,_),this.refreshAndPushAgyQuota(s,!0))}else Nn(e,this.sessionControlCtx(s),this.sessionControlSenders(s));return}if(t==="file_list"){const u=Date.now(),g=s?this.bindingStore.get(s)?.cwd:void 0,v=e.params??{},f=String(v.parent_id??"").trim(),C=Array.isArray(v.allowed_extensions)?v.allowed_extensions.filter(_=>typeof _=="string").map(_=>_.trim()).filter(_=>_.length>0):[];p.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${s} parent_id=${f||"<root>"} show_hidden=${!!v.show_hidden} ext_count=${C.length} bound_cwd=${g??"<none>"}`);const m=await Xn({parent_id:f||null,session_id:s,show_hidden:!!v.show_hidden,allowed_extensions:C},{resolveCwd:()=>g??this.config.agent.cwd??process.cwd(),fallbackDir:J()}),y=Date.now()-u,b=m.result?.files?.length??0;p.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${m.status} elapsed=${y}ms count=${b} 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:ei()}}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(t==="create_folder"){const u=s?this.bindingStore.get(s)?.cwd:void 0,g=String((e.params??{}).parent_id??"").trim(),v=String((e.params??{}).name??"").trim(),f=await Vn({parent_id:g||null,name:v,session_id:s},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:J()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:f.status,...f.result?{result:f.result}:{},...f.error_code?{error_code:f.error_code}:{},...f.error_msg?{error_msg:f.error_msg}:{}});return}if(t===E.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,s);return}if(t===E.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetSessionUsage(e,s);return}if(t===E.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetRateLimits(e,s);return}const a=(this.config.adapterType??"acp")==="acp",c=(this.config.adapterType??"acp")==="cursor";if((o||a||c)&&t===E.threadCompact){await this.handleThreadCompact(e,s);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===E.getAgentGlobalConfig){const u=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...u?{config:u}:{config:null}}});return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",l=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!s&&!!this.bindingStore.get(s)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const u=String((e.params??{}).mode_id??"");u&&(d==="cursor"?(this.bindingStore.setCursorModeId(s,u),this.globalConfigStore?.set(this.name,{cursorModeId:u})):d==="claude"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):d==="opencode"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):$.has(d)?d==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:u}):this.globalConfigStore?.set(this.name,{acpInitialMode:u}))}else if(h.kind==="set_model"){const u=String((e.params??{}).model_id??"").trim();if(u){d==="cursor"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="opencode"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codewhale"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:u,codexReasoningEffort:void 0}):$.has(d)||this.globalConfigStore?.set(this.name,{modelId:u});const g=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(s,u,g)}}else if(h.kind==="set_reasoning_effort"){const u=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");u&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:u})}else if(h.kind==="set_sandbox_mode"){const u=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(u){const g=u==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexSandboxMode:g})}}else if(h.kind==="set_service_tier"){const u=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(u){const g=u.toLowerCase()==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexServiceTier:g})}}return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&s&&!this.bindingStore.get(s)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:A.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){const u=this.sessionControlSenders(s),g=this.pool.getSlot(s)?.adapter,v={bindingStore:this.bindingStore,acpAdapter:g instanceof k?g:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};if(t==="set_mode"){const f=String((e.params??{}).mode_id??""),C=await z(v,s,f);if(C.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,C.errorCode,C.errorMsg);else{const m=g instanceof k?g.buildToolbarContext(C.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,y=m?{...m,...C.result}:C.result;u.sendLocalActionResult(e.action_id,"ok",y)}}else{const f=String((e.params??{}).model_id??""),C=await K(v,s,f);if(C.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,C.errorCode,C.errorMsg);else{const m=g instanceof k?g.buildToolbarContext(C.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,y=m?{...m,...C.result}:C.result;u.sendLocalActionResult(e.action_id,"ok",y),C.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(s,f)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${t} is not supported`})}finally{n?.()}}handleGetSessionUsage(e,t){return jt(this,e,t)}handleThreadCompact(e,t){return Kt(this,e,t)}handleGetRateLimits(e,t){return In(this,e,t)}resolveRateLimitWakeSessionId(e,t){return Qn(this,e,t)}wakeRateLimitSlot(e,t){return On(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),s=t?.adapter instanceof k?t.adapter:null,i=(this.config.adapterType??"acp")==="acp",n={bindingStore:this.bindingStore,acpAdapter:s,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(s)return s.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!s?.isAlive(),getAcpSessionOptions:()=>s?.acpSessionOptions??null,setMode:o=>s?s.setMode(o):Promise.resolve(!1),setModel:o=>s?s.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>z(n,o,r):void 0,acpSetModel:i?(o,r)=>K(n,o,r):void 0,getPendingApproval:o=>{const r=s?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>s?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(s&&s.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{p.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof W?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):$.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):$.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,s)=>this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()}),sendEventResult:(t,s,i)=>this.aibotHandle.sendEventResult({event_id:t,status:s,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,s,i,n,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...i?{result:i}:{},...n?{error_code:n}:{},...o?{error_msg:o}:{}},e)}}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"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{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==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const s=t instanceof Error?t.message:String(t),i=(()=>{const a=X(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),n=t instanceof Ei||t instanceof Ai,o=t instanceof yi&&i,r=o?"audit_config_invalid":n?t.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:r,msg:s,updated_at:Date.now()}),n||o)try{this.aibotHandle.sendAuditState(L({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:s},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const i=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,t,s){const i=this.buildInboundEvent(e,t),n=this.bindingStore.get(e.session_id),o=n?this.resolveAgentSessionId(n):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:s,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",...o?{providerSessionId:o}:{}}});return c&&(i.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,...s?{scope:s.options.scope,profile:s.options.profile,...s.options.retentionDays===void 0?{}:{retentionDays:s.options.retentionDays},capture:{...s.options.capture}}:{},rawProviderBody:s?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,t){const s=ai(this.sendCtrl.getGlobalRuntimeConfig(),t),i=Ri(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:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:s.responseDelivery,tool_events:s.toolEvents,thinking_events:s.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(s=>!Wn(String(s?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Pi}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{p.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=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}}export{ro as AgentInstance};
9
+ Error: ${s}`,1,!1))}sendEventResultWithCleanup(e,t,s,i,n=!1){const o=this.eventSessionIndex.get(e);n&&this.surfacedRunErrorEvents.add(e),t==="failed"&&o&&s?.trim()&&this.sendRunErrorAsChunk(e,o,s),this.auditController.markResponded(e,t,s),this.sendCtrl.sendEventResult(e,t,s,i),o&&(this.pool.eventComplete(e,o)===!1&&p.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${t}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,t,s),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{p.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:s,errorMsg:i}=e;if(this.stopped)return;const n=this.inflightEvents.get(t);if(!n){p.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${s}; surface failure directly`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const r=this.config.adapterType??"acp";if(o>q){p.error(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}p.info(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(s);a.length>0&&p.info(this.name,`[recovery] session=${s} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(s)}catch(l){p.warn(this.name,`[recovery] removeSlot failed session=${s}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=e.replayOriginalContent?n.content:this.resolveRecoveryPrompt(r,n),d={...n,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){p.error(this.name,`[recovery] redeliver failed event=${t} session=${s}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(t,"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(h){p.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${s}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,s){this.sendCtrl.sendThinking(e,t,s)}bufferStreamChunk(e,t,s,i,n){this.auditController.captureUnsequencedStreamChunk(e,s),this.sendCtrl.bufferOnly(e,t,s,i,n)}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)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(i=>i.event.event_id).filter(Boolean)),s=[];p.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const n=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)):(this.restorePendingReplayAuditTurn(n),this.deferredMgr.defer(i.channel,i.sessionId,n),s.push(i))}else await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);p.error(this.name,`Pending event replay failed event=${n.event_id}: ${r}`),this.sendEventResultWithCleanup(n.event_id,"failed",r),this.pendingEvents.markCanceled(n.event_id),await this.pendingEvents.remove(n.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(t,[...s,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,s))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(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_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const s=Ri({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!s.enabled)return;const i=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:s,createdAt:new Date().toISOString()}),n=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});n&&(e.audit={...t,auditId:n.auditId,turnId:n.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const s=this.eventSessionIndex.get(e);return s?(s!==t&&p.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${s} supplied=${t}`),s):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const s=e.codex_payload?.params?.delta;if(!s)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:s.length,content:s})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,s){this.shouldDropAcpRawDisplayEvent(e,s.type)||this.deliverRawEventEnvelope(e,t,s,"acp",this.buildAcpRawEventFallbackText(s))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){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] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,s,i,n){const o=fi({envelope:s,fallbackText:n,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}p.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,mi({envelopeType:s.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{p.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),s=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(s.tool_title??s.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(s.tool_name??s.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(s.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,s,i){this.sendCtrl.sendToolExecutionCard(e,t,s,i)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${B()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,s){const i=s.questions.map(o=>o.header).join(", "),n=X(`[Agent Question] ${s.request_id}`,"agent_question",s);this.aibotHandle.sendText({event_id:e,session_id:t,content:n,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const t=Kn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=i instanceof y?"acp":i instanceof F?"opencode":this.config.adapterType??"unknown",o=i instanceof F?i.handleQuestionReplyEvent(t):i instanceof y?await i.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(p.info(this.name,`[${n}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${n}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${o.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode??"interaction_reply_failed",msg:o.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=jn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=t.params,o=String(n.tool_call_id??n.approval_command_id??n.approval_id??n.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.handleExecApprovalEvent({...n,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return r.delivered?(p.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${o||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}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 t=this.config.adapterType??"acp",s=Un(e);let i;if(s&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const n=li(e.extra);if(n.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:n.error,updated_at:Date.now()});return}const o=n.patch,r=V(e.extra);if((r.state!=="absent"||r.error)&&p.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){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_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,g=h.extra,u=h.audit??(g&&typeof g=="object"?g.audit:void 0);return!u||typeof u!="object"?!1:u.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&t!=="claude"&&t!=="codex"&&t!=="cursor"&&t!=="opencode"&&t!=="pi"&&t!=="codewhale"&&t!=="deepseek-harness"&&t!=="agy"&&t!=="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: ${t}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState($({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: ${t}`},Date.now()))}catch{}return}if(s){if(r.state!=="absent"||s.verb===S.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(s.verb===S.exec){await this.handleSessionControlCommand(s,e);return}if(s.verb===S.listSessions){await this.handleListSessionsTextCommand(e);return}if(s.verb===S.unbind){await this.handleUnbindTextCommand(e);return}if(t==="claude"){await this.handleSessionControlCommand(s,e);return}if(t==="codex"&&s.verb===S.open){await this.handleCodexSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.open){await this.handlePiSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.restart){await this.handlePiSessionControlRestart(e);return}if((t==="openhuman"||t==="opencode")&&s.verb===S.open){await this.handleOpenHumanSessionControlOpen(s,e);return}if(t==="codewhale"&&s.verb===S.open){await this.handleCodeWhaleSessionControlOpen(s,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===S.open){const l=s.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=T.resolve(l);if(!(await Q(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const g=String(h?.code??""),u=g==="ENOENT"?`Directory does not exist: ${T.resolve(l)}`:g==="EACCES"||g==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:u,updated_at:Date.now()});return}}if(s.verb===S.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await Q(l.cwd)}catch{p.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.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 h=this.pool.getSlot(e.session_id);h?.adapter instanceof y&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(s,e),t==="acp"&&s.verb===S.stop){const h=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 ${h}`,updated_at:Date.now()});return}if(Nn(s,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===S.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),t==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}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 a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(ee.has(t)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),ee.has(t)&&!this.bindingStore.get(e.session_id)?.cwd){const h=t,g=this.prepareAuditedInboundEvent(e,o,a);p.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const f=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:g});if(this.lifecycleBarrier.isClosed()&&!f)throw new Error("pending event store unavailable during lifecycle drain")}catch(f){const b=f instanceof Error?f.message:String(f);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",b,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:b,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(g,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),g);const u=this.resolveBindingChannelKey(t);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:E.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,g,u]=h,b=this.pool.getSlot(e.session_id)?.adapter;if(b?.execCommand&&(b.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await b.execCommand(g,u.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&K(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof W&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(p.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)):p.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),p.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{p.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,t){const s=t instanceof Error?t.message:String(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",s,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:s,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return xt(this,e,t)}handleSessionControlForPool(e,t){return Dt(this,e,t)}handleSessionControlLocalActionForPool(e){return Mt(this,e)}handleCodexSessionControlLocalActionOpen(e){return Ht(this,e)}handleCursorSessionControlLocalActionOpen(e){return Lt(this,e)}handlePiSessionControlOpen(e,t){return $t(this,e,t)}handlePiSessionControlRestart(e){return It(this,e)}handlePiSessionControlRestartLocalAction(e){return Qt(this,e)}syncOpenCodeBinding(e,t){return Ot(this,e,t)}isWorkspaceFreeClient(){return Bt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Ft(this,e,t)}bindSessionForPool(e,t){return qt(this,e,t)}deferredCallbacks(){return Ut(this)}handleOpenHumanSessionControlOpen(e,t){return Nt(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Wt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Gt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return jt(this,e)}normalizeClaudeModeId(e){return dn(this,e)}handleExecCommandOptions(e,t,s){ln(this,e,t,s)}resolveSessionModelId(e){return cn(this,e)}resolveSessionModeId(e){return hn(this,e)}resolveCursorSessionModeId(e){return un(this,e)}resolveClaudeSessionEffort(e){return pn(this,e)}resolveClaudeSessionModeId(e){return gn(this,e)}currentClaudeModeId(e){return fn(this,e)}resolveCodexSessionModelId(e){return mn(this,e)}resolveCodexNewSessionGlobalDefault(e,t,s){return vn(this,e,t,s)}pinCodexGlobalDefault(e,t){return _n(this,e,t)}buildCursorToolbarMeta(e){return Sn(this,e)}buildAgyToolbarMeta(e,t){return bn(this,e,t)}buildAgyQuotaMeta(e){return Cn(this,e)}sendAgyBindingCard(e,t,s){return wn(this,e,t,s)}refreshAndPushAgyQuota(e,t=!1){return An(this,e,t)}handleAgySetModel(e,t){return En(this,e,t)}buildClaudeToolbarMeta(e){return kn(this,e)}providerQuotaToCodexRateLimits(e){return pi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const t=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t))){const n=new Error(`Specified path is not valid on this host: ${t}`);throw n.cwdErrorCode=E.invalidCwd,n}const s=T.resolve(t);let i;try{i=await Q(s)}catch(n){const o=String(n?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${s}`);throw r.cwdErrorCode=E.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=E.invalidCwd,r}throw n}if(!i.isDirectory()){const n=new Error("Specified path is not a directory.");throw n.cwdErrorCode=E.invalidCwd,n}try{return await te(s)}catch{return s}}failSessionOpen(e,t){const{code:s,msg:i}=Jn(e);return this.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(s,i),{code:s,msg:i}}maybeOfferCliInstall(e){ot(this,e)}handleCliInstallQuestionReply(e){return rt(this,e)}handleCliInstallInteractionReply(e){return at(this,e)}runConfirmedCliInstall(e,t){return dt(this,e,t)}getClaudeWorkerStatus(e){const t=this.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,t){const s=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,s),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:s,cwd:t,meta:this.buildClaudeToolbarMeta(e)}),s}handleSkillDeleteLocalAction(e){return Jt(this,e)}handleSkillUploadLocalAction(e){return Yt(this,e)}handleSkillEnableLocalAction(e){return Xt(this,e)}handleSkillRefreshLocalAction(e){Vt(this,e)}handleSkillDisableLocalAction(e){return Zt(this,e)}computeSkillReport(e){return en(this,e)}reportSessionSkills(e){tn(this,e)}skillsSyncGroupKey(){return nn(this)}forceRefreshSkills(e,t){return sn(this,e,t)}adoptSkillsWireHashFromDisk(){on(this)}buildLibrarySkillsReport(e){return rn(this,e)}skillLookupEnv(){return an(this)}async ensureSlotStarted(e,t=6e4){const s=await this.pool.getOrCreateSlot(e);if(!s)throw new Error("Failed to allocate session slot");s.startPromise&&(p.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([s.startPromise,new Promise((i,n)=>setTimeout(()=>n(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),p.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const t=Ie(e);if(!t)return;const s=this.reasonixTitleScan.get().filter(i=>i.stamp===t);return s.length===1?s[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(s=>s.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;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,t){const s=String(e??"").trim(),i=String(t??"").trim();if(!s||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(s,i);break;case"codex":this.bindingStore.setCodexThreadId(s,i);break;case"pi":this.bindingStore.setPiSessionPath(s,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(s,i);break;case"agy":this.bindingStore.setAgyConversationId(s,i);break;default:this.bindingStore.setAcpSessionId(s,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const t=String(e??"").trim();if(!t)return"";const s=T.resolve(t);return process.platform==="win32"?s.toLowerCase():s}ensureImportedAgentSession(e,t){const s=String(e??"").trim();if(!s)return;const i=this.normalizePathForCompare(t);let n="";const o=this.config.adapterType??"acp";if(o==="codex"?n=this.sessionScanCache.get().find(c=>c.threadId===s)?.cwd??"":o==="claude"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="cursor"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="acp"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="deepseek-harness"&&(n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??""),!n){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===s){n=a.cwd??"";break}}if(!n){const a=new Error(`agent session not found: ${s}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}const r=this.normalizePathForCompare(n);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${t}, got ${n}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}}buildOpenedBindingResult(e,t,s="ready"){const i=this.bindingStore.get(e),n=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:t,workerStatus:s};return n&&(o.bindingId=n,o.agentSessionId=n),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const t=this.globalConfigStore?.get(this.name),s=this.bindingStore.get(e),i=this.config.adapterOptions??{},n=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const R=ve(t?.dshAgentPreset,he);this.bindingStore.setDshAgentPreset(e,R)}const o=this.bindingStore.getDshSelectedProfile(e),r=Se({binding:o,global:t?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),c=this.bindingStore.getDshSettings(e),d=c?.providerId??t?.dshProviderId,l=_e({dataRoot:a,providerId:d}),h=[c?.modelId,t?.dshModelId,l.models[0]?.id].find(R=>!!R&&l.models.some(C=>C.id===R))??l.models[0]?.id,g=j(s?.dshModeId,t?.dshModeId),u={};!s?.dshProviderId&&l.providerId&&(u.providerId=l.providerId),!s?.dshModelId&&h&&(u.modelId=h),s?.dshModeId||(u.modeId=g),s?.dshThinking||(u.thinking=me(t?.dshThinking)??"enabled"),s?.dshReasoningEffort||(u.reasoningEffort=fe(t?.dshReasoningEffort)??"high"),Object.keys(u).length>0&&this.bindingStore.updateDshSettings(e,u);const f=this.bindingStore.getDshSettings(e);let b=[],v=[],m=!1;try{b=ue({dshHome:n,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),m=!1}catch{}const w=T.join(a,"dsh-session-skills");return we(w),v=pe({skillsDir:w,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),ce({agentPreset:f?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:ge({dshHome:n}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:b,skills:v,pluginRestartRequired:m,providerId:f?.providerId??l.providerId,modelId:f?.modelId??h,modeId:j(this.bindingStore.get(e)?.dshModeId,t?.dshModeId),thinking:f?.thinking,reasoningEffort:f?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return T.join(L.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}unbindSession(e){return Et(this,e)}handleUnbindTextCommand(e){return kt(this,e)}handleUnbindLocalAction(e){return Rt(this,e)}handleListSessionsTextCommand(e){return yt(this,e)}handleListSessionsLocalAction(e){return Pt(this,e)}handleSyncHistoryLocalAction(e){return Tt(this,e)}handleSessionControlCommand(e,t){return it(this,e,t)}handleSessionControlLocalAction(e){return st(this,e)}handleEventCancel(e){return lt(this,e)}waitForEventDone(e,t,s){return ct(this,e,t,s)}handleAibotStop(e){ht(this,e)}killAndResumeStopSlot(e,t){return ut(this,e,t)}handleAibotRevoke(e){return pt(this,e)}handleConfigureGatewayProvider(e){return gt(this,e)}getAuditLocalActionHandler(){return ft(this)}handleAuditLocalAction(e){return mt(this,e)}handleConnectorRollback(e){return vt(this,e)}getRelayStateSyncer(){return _t(this)}relayStateSyncOnConnect(){St(this)}reportRelayStateLocalChange(){bt(this)}handleApplyRelayState(e){return Ct(this,e)}fetchRelayCredential(e){return wt(this,e)}isSharedInstance(){return At(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",s=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();p.debug(this.name,`local_action received action_type=${t} verb=${i||"-"} action_id=${e.action_id} session_id=${s}`);let n;if(t===k.sessionControl&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===k.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Ce(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===k.sessionControl&&i===S.exec&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl&&i===S.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===k.sessionControl&&i===S.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===k.sessionControl&&i===S.unbind){await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(t===k.interactionReply||t==="exec_approve"||t==="exec_reject")||r&&t===k.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl){const u=this.config.adapterType??"acp",f=u==="codex",b=u==="pi",v=String((e.params??{}).verb??"").trim().toLowerCase();if(f&&v===S.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(u==="cursor"&&v===S.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(f&&v==="restart"){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:s,cwd:_,workerStatus:"ready"}}});return}if(b&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.ensureSlotStarted(s).catch(H=>{if(zn(H))throw H;p.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${H instanceof Error?H.message:String(H)}`)}),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:A}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(b&&v===S.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((u==="openhuman"||u==="opencode")&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.syncOpenCodeBinding(s,A),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(u==="codewhale"&&v===S.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(u==="deepseek-harness"&&v===S.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(u==="acp"&&v===S.stop){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:s,cwd:_,workerStatus:"stopped"}}});return}try{if(v===S.open){const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=String(C.agent_session_id??"").trim();if(A){const x=await this.resolveCwdForBinding(_);this.ensureImportedAgentSession(A,x)}}await this.handleSessionControlLocalActionForPool(e)}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})});return}if(v===S.open){const C=e.params??{},_=await this.resolveCwdForBinding(String(C.cwd??"").trim());this.setResolvedAgentSessionId(s,String(C.agent_session_id??"").trim()),u==="agy"&&(this.bindingStore.set(s,_),this.sessionBindings.set(s,_)),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,_)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(s,_),this.refreshAndPushAgyQuota(s,!0))}else Wn(e,this.sessionControlCtx(s),this.sessionControlSenders(s));return}if(t==="file_list"){const u=Date.now(),f=s?this.bindingStore.get(s)?.cwd:void 0,b=e.params??{},v=String(b.parent_id??"").trim(),m=Array.isArray(b.allowed_extensions)?b.allowed_extensions.filter(_=>typeof _=="string").map(_=>_.trim()).filter(_=>_.length>0):[];p.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${s} parent_id=${v||"<root>"} show_hidden=${!!b.show_hidden} ext_count=${m.length} bound_cwd=${f??"<none>"}`);const w=await Vn({parent_id:v||null,session_id:s,show_hidden:!!b.show_hidden,allowed_extensions:m},{resolveCwd:()=>f??this.config.agent.cwd??process.cwd(),fallbackDir:Y()}),R=Date.now()-u,C=w.result?.files?.length??0;p.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${w.status} elapsed=${R}ms count=${C} current_path=${w.result?.current_path??""} error_code=${w.error_code??""} error_msg=${w.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:w.status,...w.result?{result:{...w.result,machine_name:ti()}}:{},...w.error_code?{error_code:w.error_code}:{},...w.error_msg?{error_msg:w.error_msg}:{}});return}if(t==="create_folder"){const u=s?this.bindingStore.get(s)?.cwd:void 0,f=String((e.params??{}).parent_id??"").trim(),b=String((e.params??{}).name??"").trim(),v=await Zn({parent_id:f||null,name:b,session_id:s},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:Y()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:v.result}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(t===k.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,s);return}if(t===k.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetSessionUsage(e,s);return}if(t===k.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetRateLimits(e,s);return}const a=(this.config.adapterType??"acp")==="acp",c=(this.config.adapterType??"acp")==="cursor";if((o||a||c)&&t===k.threadCompact){await this.handleThreadCompact(e,s);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===k.getAgentGlobalConfig){const u=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...u?{config:u}:{config:null}}});return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",l=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!s&&!!this.bindingStore.get(s)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const u=String((e.params??{}).mode_id??"");u&&(d==="cursor"?(this.bindingStore.setCursorModeId(s,u),this.globalConfigStore?.set(this.name,{cursorModeId:u})):d==="claude"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):d==="opencode"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):I.has(d)?d==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:u}):this.globalConfigStore?.set(this.name,{acpInitialMode:u}))}else if(h.kind==="set_model"){const u=String((e.params??{}).model_id??"").trim();if(u){d==="cursor"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="opencode"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codewhale"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:u,codexReasoningEffort:void 0}):I.has(d)||this.globalConfigStore?.set(this.name,{modelId:u});const f=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(s,u,f)}}else if(h.kind==="set_reasoning_effort"){const u=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");u&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:u})}else if(h.kind==="set_sandbox_mode"){const u=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(u){const f=u==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexSandboxMode:f})}}else if(h.kind==="set_service_tier"){const u=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(u){const f=u.toLowerCase()==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexServiceTier:f})}}return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&s&&!this.bindingStore.get(s)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){const u=this.sessionControlSenders(s),f=this.pool.getSlot(s)?.adapter,b={bindingStore:this.bindingStore,acpAdapter:f instanceof y?f:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};if(t==="set_mode"){const v=String((e.params??{}).mode_id??""),m=await J(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R)}}else{const v=String((e.params??{}).model_id??""),m=await z(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(s,v)}}return}const g=!!s&&!!this.pool.getSlot(s);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{n?.()}}handleGetSessionUsage(e,t){return Kt(this,e,t)}handleThreadCompact(e,t){return zt(this,e,t)}handleGetRateLimits(e,t){return Qn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return On(this,e,t)}wakeRateLimitSlot(e,t){return Bn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),s=t?.adapter instanceof y?t.adapter:null,i=(this.config.adapterType??"acp")==="acp",n={bindingStore:this.bindingStore,acpAdapter:s,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(s)return s.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!s?.isAlive(),getAcpSessionOptions:()=>s?.acpSessionOptions??null,setMode:o=>s?s.setMode(o):Promise.resolve(!1),setModel:o=>s?s.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>J(n,o,r):void 0,acpSetModel:i?(o,r)=>z(n,o,r):void 0,getPendingApproval:o=>{const r=s?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>s?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(s&&s.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{p.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof G?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,s)=>this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()}),sendEventResult:(t,s,i)=>this.aibotHandle.sendEventResult({event_id:t,status:s,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,s,i,n,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...i?{result:i}:{},...n?{error_code:n}:{},...o?{error_msg:o}:{}},e)}}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"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{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==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const s=t instanceof Error?t.message:String(t),i=(()=>{const a=V(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),n=t instanceof ki||t instanceof Ei,o=t instanceof Pi&&i,r=o?"audit_config_invalid":n?t.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:r,msg:s,updated_at:Date.now()}),n||o)try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:s},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const i=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,t,s){const i=this.buildInboundEvent(e,t),n=this.bindingStore.get(e.session_id),o=n?this.resolveAgentSessionId(n):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:s,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",...o?{providerSessionId:o}:{}}});return c&&(i.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,...s?{scope:s.options.scope,profile:s.options.profile,...s.options.retentionDays===void 0?{}:{retentionDays:s.options.retentionDays},capture:{...s.options.capture}}:{},rawProviderBody:s?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,t){const s=di(this.sendCtrl.getGlobalRuntimeConfig(),t),i=yi(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:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:s.responseDelivery,tool_events:s.toolEvents,thinking_events:s.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(s=>!Gn(String(s?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Ti}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{p.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=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}}export{ao as AgentInstance};