grix-connector 5.0.0 → 5.1.1

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,3 +1,4 @@
1
- import R from"node:path";import{tmpdir as U}from"node:os";import{createHash as $,randomUUID as T}from"node:crypto";import{ConnectionManager as q}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as W}from"../core/aibot/types.js";import{ClaudeAdapter as D}from"../adapter/claude/index.js";import{CodexAdapter as H}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 N}from"../adapter/pi/index.js";import{AcpAdapter as S}from"../adapter/acp/index.js";import{OpenHumanAdapter as j}from"../adapter/openhuman/index.js";import{CursorAdapter as G}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as K}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as P}from"../adapter/opencode/index.js";import{AgyAdapter as Q}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as z}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as m,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as w,SESSION_MODE_IDS as J}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Y}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as O}from"../audit/raw-capture/types.js";import{buildWireSkills as V}from"../core/skill-sync/sync-state.js";import{executeEventTool as X}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as Z}from"../adapter/claude/model-list.js";import{primeAgyModels as ee}from"../adapter/agy/model-list.js";import{applyProxyEnv as te,getProxyManager as ne}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ie}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as se}from"../core/config/provider-env.js";import{buildProviderEnv as oe}from"../core/config/provider-env.js";import{isClaudeDirectEnv as re,stripGrixRelayEnv as ae}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as de}from"./native-provider-sweep.js";import{scanCodexSessions as le}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as ce}from"../adapter/claude/session-scanner.js";import{resolveClaudeConfigPaths as he}from"../adapter/claude/config-paths.js";import{resolveAcpAgentTypes as ue,scanAcpSessions as pe,scanReasonixSessionTitles as ge}from"../adapter/acp/session-scanner.js";import{scanPiSessions as fe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as me}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as ve}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as _e}from"../adapter/opencode/session-scanner.js";import{agentIdOf as Se}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as Ce}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as _,resolveCodexLeafDirs as be,resolveClaudeLeafDirs as Ae,resolveAcpLeafDirs as Ee,resolvePiLeafDirs as we,resolveCodeWhaleLeafDirs as ye,resolveCursorLeafDirs as ke,resolveOpenCodeLeafDirs as Re,resolveDshLeafDirs as Te,resolveReasonixLeafDirs as Pe}from"./session-scan-cache.js";import{log as h,ConversationLog as xe,AgentApiPacketLog as Le,BridgeEventLog as Me,GRIX_PATHS as y}from"../core/log/index.js";import{routeSessionControlCommand as $e,routeSessionControlLocalAction as De}from"./session-control-router.js";import{maybeOfferCliInstall as He,handleCliInstallQuestionReply as Qe,handleCliInstallInteractionReply as Oe,runConfirmedCliInstall as Ie}from"./cli-install-flow.js";import{handleEventCancel as Be,waitForEventDone as Fe,handleAibotStop as Ue,killAndResumeStopSlot as qe,handleAibotRevoke as We}from"./event-stop.js";import{handleConfigureGatewayProvider as Ne,getAuditLocalActionHandler as je,handleAuditLocalAction as Ge,handleConnectorRollback as Ke,getRelayStateSyncer as ze,relayStateSyncOnConnect as Je,reportRelayStateLocalChange as Ye,handleApplyRelayState as Ve,fetchRelayCredential as Xe,isSharedInstance as Ze}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as et,handleConnectorAdminLocalAction as tt}from"./remote-admin.js";import{unbindSession as nt,handleUnbindTextCommand as it,handleUnbindLocalAction as st,handleListSessionsTextCommand as ot,handleListSessionsLocalAction as rt,handleSyncHistoryLocalAction as at}from"./session-list.js";import{handleCodexSessionControlOpen as dt,handleSessionControlForPool as lt,handleSessionControlLocalActionForPool as ct,handleCodexSessionControlLocalActionOpen as ht,handleCursorSessionControlLocalActionOpen as ut,handlePiSessionControlOpen as pt,handlePiSessionControlRestart as gt,handlePiSessionControlRestartLocalAction as ft,syncOpenCodeBinding as mt,isWorkspaceFreeClient as vt,isCwdLockedClient as _t,ensureDefaultBindingForWorkspaceFreeClient as St,bindSessionForPool as Ct,deferredCallbacks as bt,handleOpenHumanSessionControlOpen as At,handleCodeWhaleSessionControlOpen as Et,handleCodeWhaleSessionControlLocalActionOpen as wt,handleDeepSeekSessionControlLocalActionOpen as yt}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as kt}from"./cwd-policy.js";import{normalizeCustomToolbarItems as Rt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as Tt,handleThreadCompact as Pt}from"./session-usage.js";import{handleSkillDeleteLocalAction as xt,handleSkillUploadLocalAction as Lt,handleSkillEnableLocalAction as Mt,handleSkillRefreshLocalAction as $t,handleSkillDisableLocalAction as Dt,computeSkillReport as Ht,reportSessionSkills as Qt,skillsSyncGroupKey as Ot,forceRefreshSkills as It,adoptSkillsWireHashFromDisk as Bt,buildLibrarySkillsReport as Ft,skillLookupEnv as Ut}from"./skill-actions.js";import{resolveToolbarSelection as qt,persistToolbarSelection as I}from"./toolbar-selection.js";import{normalizeClaudeModeId as Wt,handleExecCommandOptions as Nt,resolveSessionModelId as jt,resolveSessionModeId as Gt,resolveCursorSessionModeId as Kt,resolveClaudeSessionEffort as zt,resolveClaudeSessionModeId as Jt,currentClaudeModeId as Yt,buildCursorToolbarMeta as Vt,buildAgyToolbarMeta as Xt,buildAgyQuotaMeta as Zt,sendAgyBindingCard as en,refreshAndPushAgyQuota as tn,handleAgySetModel as nn,buildClaudeToolbarMeta as sn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as on,maybeQueryProviderQuota as rn,startProviderQuotaTimer as an,stopProviderQuotaTimer as dn,refreshAndPushProviderQuota as ln,pushProviderQuotaToBindings as cn,enrichProviderQuotaMeta as hn,providerQuotaMetaPayload as un,refreshProviderQuotaForSession as pn,refreshQuotaAfterModelSwitch as gn,doRefreshQuotaAfterModelSwitch as fn}from"./provider-quota.js";import{handleGetRateLimits as mn,resolveRateLimitWakeSessionId as vn,wakeRateLimitSlot as _n}from"./rate-limits.js";import{RevokeHandler as Sn}from"./revoke-handler.js";import{AdapterPool as Cn}from"./adapter-pool.js";import{parseSessionControlCommand as bn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as An,parseExecApprovalResolutionMessage as En,parseAgentQuestionReplyMessage as wn}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as yn}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as kn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as Rn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as Tn}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as Pn,handleFileListLocalAction as xn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Ln,persistToolbarSelection as Mn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as $n,ensureImportedAgentSession as Dn,hasDiskScanner as Hn,normalizePathForCompare as Qn,providerKeyForAdapter as On,resolveAgentSessionId as In,resolveOrphanTitle as Bn,setResolvedAgentSessionId as Fn}from"./session-identity.js";import{buildDshOpenedToolbarMeta as Un,dshCatalogDataRoot as qn}from"./dsh-toolbar.js";import{ensureSlotStarted as Wn,failSessionOpen as Nn,getClaudeWorkerStatus as jn,refreshClaudeWorkerStatusCard as Gn,resolveCwdForBinding as Kn}from"./session-open-helpers.js";import{handleAcpSetModel as zn,handleAcpSetMode as Jn,resolveAcpInitialDefaults as Yn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Vn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as Xn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Zn}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as ei,buildInboundAttachmentsJson as ti,materializeInboundAttachments as ni}from"../core/protocol/inbound-attachments.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 C,buildToolResultCard as b,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 Ci}from"./probe-helper.js";import{BridgeAuditController as bi}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Ai,NoopAuditProducer as Ei}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as B,AuditPreparationFailedError as wi,AuditTurnScopeUnsupportedError as yi}from"../audit/core/audit-state.js";import{extractAuditOptions as F,freezeAuditOptions as ki,stripAuditOptions as Ri}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Ti}from"../audit/core/audit-session-registry.js";import{waitForIdle as Pi,formatWaitDuration as xi}from"../core/upgrade/idle-wait.js";const Li=600*1e3,Mi=1800*1e3,$i=5*6e4,Di=60*1e3,Hi=4e3;function Qi(L,e,t){const r=$("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return R.join(y.data,"audit-source","reasonix",`${r}.jsonl`)}const Oi=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),k=3;class Ro{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Sn;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new hi(ai);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=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;rejectedOutputEvents=new Set;blockedDispatchEvents=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<=Di}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return on(this,e)}maybeQueryProviderQuota(e=!1,t){return rn(this,e,t)}startProviderQuotaTimer(){an(this)}stopProviderQuotaTimer(){dn(this)}refreshAndPushProviderQuota(e=!1){return ln(this,e)}pushProviderQuotaToBindings(e,t=!1){cn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return hn(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return un(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return pn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){gn(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return fn(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||r)}}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)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>$i?{suspect:`admission held for ${xi(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return Pi({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:Mi,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}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,h.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,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let s=!1;await this.pool.removeSlot(n.sessionId).catch(o=>{r=!0,s=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${o}`)}),s||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),r?(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",r=e.conversation?Ci:Si;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",s=this.createAdapter(n,"__probe__"),o=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(s,e.timeoutMs??1e4):void 0;let i;try{i=await _i({adapter:s,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{s.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",s=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||U(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof S)try{await e.bindSession(n,o)}catch{}let a=null;const l=new Promise(u=>{a=p=>{p===s&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:s,session_id:n,content:"ping",msg_id:s}),e.deliverStopEvent(s,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new Ei){this.config=e,this.auditController=new bi(r,{onAuditState:s=>{try{this.aibotHandle.sendAuditState(B(s,Date.now()))}catch{}}}),Ai(r)&&r.addJobSettledHandler((s,o)=>{this.auditController.handleJobSettled(s,o)}),this.name=e.name;const n=e.adapterType??"acp";if(n==="claude"&&(e.claudeConfigPaths??=he({...process.env,...e.agent.env})),this.sendCtrl.setDefaultQuoteTrigger(ci[n]),this.aibotConfig={...e.aibot,...n==="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",...W]}:{}},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 xe(e.logDir):null,this.packetLog=e.logDir?new Le(e.logDir):null,this.bindingStore=new Vn(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),n==="codex")this.sessionScanCache=new _(le,be);else if(n==="claude"){const s=e.claudeConfigPaths?.projectsDir;this.sessionScanCache=new _(()=>ce(s),()=>Ae(s))}else if(n==="pi"){const s=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new _(()=>fe(void 0,s),()=>we(void 0,s))}else if(n==="codewhale")this.sessionScanCache=new _(me,ye);else if(n==="cursor")this.sessionScanCache=new _(ve,ke);else if(n==="opencode"){const s=Se(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new _(()=>_e(void 0,s),()=>Re(void 0,s))}else if(n==="deepseek-harness"){const s=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new _(()=>Ce(s),()=>Te(s))}else if(n==="agy")this.sessionScanCache=new _(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new _(ge,Pe));const s=ue(e.aibot.clientType);this.sessionScanCache=s?new _(()=>pe(void 0,s),()=>Ee(void 0,s)):new _(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await de({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(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&h.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{h.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await Z(this.config.claudeConfigPaths).catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}else(this.config.adapterType??"acp")==="agy"&&ee(this.config.agent.command).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",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||r)&&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 s=this.config.adapterType??"acp";if(this.pool=new Cn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const i=this.createAdapter(s,o);return i instanceof S&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(o,a),this.sessionScanCache.invalidate()}),i},(o,i)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((o,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${o} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(o),this.pendingEvents.remove(o).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${o}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:o,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(o,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(o),this.pendingEvents.remove(o).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${o}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((o,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:i,...i?{ttl_ms:ri,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((o,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((o,i)=>{this.markAuditAdapterClosed(o,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((o,i,a)=>{const l=this.selfDrivenSessions.has(o),d=this.selfDrivenLabels.get(o);i?(this.selfDrivenSessions.add(o),a&&this.selfDrivenLabels.set(o,a),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),l&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(o)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${s}, 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(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],s=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{o=await this.pendingEvents.mergeForShutdown(s)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!o)for(const i of s){const a=i.event;h.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){h.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=oe(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(re(t)){const s=ne()?.getRuntimeInfo(),o={...r??{},...t},i=ae(o,{proxyUrl:s?.proxyUrl,caCertPath:s?.caCertPath,caBundlePath:s?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(se(this.config.agent.clientType)){const s=ie(this.name);s&&(n={...n??{},...s})}return te(n,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:(s,o,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(s,o,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Hi),sendThinking:(s,o,i)=>this.sendThinkingByRuntimeConfig(s,o,i),sendEventResult:(s,o,i,a)=>{this.sendEventResultWithCleanup(s,o,i,void 0,a)},sendRawEventEnvelope:(s,o,i,a)=>{const l=gi(i);if(l){this.sendToolExecutionCard(s,o,l);return}this.deliverRawEventEnvelope(s,o,i,"deepseek",a)},sendLocalActionResult:(s,o,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:o,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:s=>{this.sendGrixApprovalCard(s,"deepseek")},sendUpdateBindingCard:(s,o,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:o,cwd:i,...this.providerQuotaMetaPayload(a,s,i)})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:(s,o)=>this.maybeQueryProviderQuota(s===!0,o??{providerId:"deepseek"}),agentInvoke:async(s,o,i)=>this.platformInvoke(s,o,i),eventToolInvoke:async(s,o)=>this.invokeDshEventTool(s,o)},r=$("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:R.join(y.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.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 r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const s=this.resolveCursorSessionModeId(e),o=s??"full_auto";s||this.bindingStore.setCursorModeId(e,o),t.mode=o,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,p,g)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,p,g)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{const c=d.questions.map(p=>p.header).join(", "),u=x(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:l,content:u,msg_type:1,extra:{card_type:"agent_question",summary_text:c}})},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,E.bindingMissing,!0),this.pool.removeSlot(e).catch(d=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${d instanceof Error?d.message:String(d)}`)});const l=this.resolveBindingChannelKey("claude");this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:x(i.message,"agent_open_session",{summary_text:i.message,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,p)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,p)},sendMedia:(i,a,l,d,c,u,p)=>{this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:p?{media_caption:d,...p}:{media_caption:d}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,C(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},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:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay||(i.rateLimits?.modelScoped?.length??0)>0)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},s=this.config.adapterOptions??{},o={...s,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??J.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o,claudeConfigPaths:this.config.claudeConfigPaths},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_${i}`,5e3,!0,!0,this.sendCtrl.getCodexDefaultQuotedMessageId(i)).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendStreamChunk:(i,a,l,d,c,u,p,g)=>{const v=typeof g?.phase=="string"?g.phase.trim().toLowerCase():"";(!v||v==="final_answer")&&l&&this.auditController.captureUnsequencedStreamChunk(i,l);const M=p!==void 0?p:this.sendCtrl.getCodexDefaultQuotedMessageId(i),f=this.indexEventSession(i,a)??a;this.sendCtrl.sendStreamChunk(i,f,l,d,c,u,M,{forceStream:!0,...g?.threadId?{threadId:g.threadId}:{}}),(l||c)&&this.conversationLog?.logOutbound?.(f,i,c?"stream_chunk_finish":"stream_chunk",l)},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.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:i=>{if(!i)return;this.cachedCodexContextWindow=i,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:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},s=this.auditController.getAdapterPreparation(e),o=i=>qt(this,"codex",e,i);return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:o("model")??n.model,collaborationMode:o("mode")??n.collaborationMode,reasoningEffort:o("reasoningEffort")??n.reasoningEffort,serviceTier:o("serviceTier")??n.serviceTier,sandboxMode:o("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...O(s?.options)?{rawApiCapture:{auditId:s.auditId,sessionId:e,spoolRootDir:R.join(y.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),sendLocalActionResult:(n,s,o,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,s,o,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:s,active:o,...i??{}})},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,C(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,s,o,i,a)=>{this.sendEventResultWithCleanup(n,s,o,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,s,o,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:s,active:o,...i??{}})},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,C(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o,i,a)=>{this.sendRunErrorAsChunk(n,s,o,i,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendFinalStreamChunkReliable:async(n,s,o,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,s,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,C(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o)=>{this.sendRunErrorAsChunk(n,s,o,0)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new j({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,s,o,i,a)=>{this.sendEventResultWithCleanup(n,s,o,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,C(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o)=>{this.sendRunErrorAsChunk(n,s,o)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,s,o)=>{this.sendGrixAgentQuestionCard(n,s,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new P({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o)},sendEventAck:(n,s)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()})},agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),forceCompleteInternalEvent:(n,s)=>{this.pool.eventComplete(n,s),this.pushQueueSnapshotForSession(s)},persistConversationId:(n,s)=>{this.bindingStore.setAgyConversationId(n,s)},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,C(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const s=this.bindingStore.get(n);return{cwd:s?.cwd,modelId:this.resolveSessionModelId(n),conversationId:s?.agyConversationId}};return new Q({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,p,g,v,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,p,g,v,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,p,g)=>{this.sendEventResultWithCleanup(d,c,u,p,g)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,p,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...p?{error_code:p}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,p)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:p??""}});return}this.sendToolExecutionCard(d,c,C(u,p))},sendToolResult:(d,c,u,p)=>{this.sendToolExecutionCard(d,c,b(u,p))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=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}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${T()}`,p={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:p.content.length});try{this.aibotHandle.sendMsg(p),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(g){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:g instanceof Error?g.message:String(g)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,p)=>{const g={...p??{}};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:c,cwd:u,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:V(d,y.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const p="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:p,remainingPercentage:100-p}};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:u.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,s=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&s?Qi(this.name,e,s.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=Yn({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new S({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,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 Me(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new q().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 r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(s=>{h.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const o=s instanceof Error?s.message:String(s);this.handleStaleCwdError(n,o)||this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(s){h.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){h.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(s){h.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(s){h.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(s){h.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(s=>{h.error(this.name,`handleAibotRevoke failed: ${s}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(s=>{h.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(s=>{h.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((n,s)=>{const o=this.pool.getSlot(n)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(s):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const s=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const s=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],o=this.pool.reorderQueue(n.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const s=typeof n.session_id=="string"?n.session_id:"",o=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${o} session_id=${s} hold=${i} reason=${n.reason??""}`),!s||!o){this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(s,o,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const s=typeof n.session_id=="string"?n.session_id:"",o=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${o} session_id=${s}`),!s||!o){this.aibotHandle.sendQueueEditResult({session_id:s,event_id:o,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(s,o,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:s,event_id:o,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const s of n)h.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,s)=>{this.handleStreamRejected(n,s)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(s=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${s}`)});try{this.pool?.rejectEventOutput(e,r)}catch(s){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${s}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const s=String(e??"").trim(),o=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=s!==this.agentProfile.agentName||o!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:s,introduction:o},this.agentSystemPrompt=i,s||o?h.info(this.name,`agent profile (${r.source}): GOT name="${s}" intro_len=${o.length} system_prompt_len=${i.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof D),s=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=n.length-s.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${s.length} idle Claude slot(s), skipping ${o} busy`);for(const i of s)this.pool.removeSlot(i.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=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"}]})):[],s=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(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(o),n.push({event_id:o,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:s}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.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,r){if(e==="file_link")return Xn(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const s of n)this.rejectedOutputEvents.has(s)||this.blockedDispatchEvents.set(s,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=Rt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=X(this.aibotHandle,e,t),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),s=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const o=await Zn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${o.attachment_type}]`,client_msg_id:`file_upload_${T()}`,...s?{quoted_message_id:s}:{},extra:o.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.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,r,n,s){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,o,r,n,s),r&&this.conversationLog?.logOutbound?.(o,e,"reply",r)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:n,...s}=e;return s}if(e.codex_method!=="item/agentMessage/delta")return e;const r=this.sendCtrl.getCodexDefaultQuotedMessageId(e.event_id);return r?{...e,quoted_message_id:r}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}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(r,n,s,o)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,s,t,!1,!1,o)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,s,o,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,s,o,i),(r||s)&&this.conversationLog?.logOutbound?.(a,e,s?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,s){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
1
+ import P from"node:path";import{tmpdir as j}from"node:os";import{createHash as D,randomUUID as x}from"node:crypto";import{ConnectionManager as G}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as K}from"../core/aibot/types.js";import{ClaudeAdapter as H}from"../adapter/claude/index.js";import{CodexAdapter as Q}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 z}from"../adapter/pi/index.js";import{AcpAdapter as C}from"../adapter/acp/index.js";import{OpenHumanAdapter as J}from"../adapter/openhuman/index.js";import{CursorAdapter as X}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as Y}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as M}from"../adapter/opencode/index.js";import{AgyAdapter as O}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as V}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as m,SESSION_CONTROL_ERROR_CODES as w,SESSION_CONTROL_VERBS as y,SESSION_MODE_IDS as Z}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as ee}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as I}from"../audit/raw-capture/types.js";import{buildWireSkills as te}from"../core/skill-sync/sync-state.js";import{executeEventTool as ne}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as ie}from"../adapter/claude/model-list.js";import{primeAgyModels as se}from"../adapter/agy/model-list.js";import{applyProxyEnv as oe,getProxyManager as re}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ae}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as de}from"../core/config/provider-env.js";import{buildProviderEnv as le}from"../core/config/provider-env.js";import{isClaudeDirectEnv as ce,stripGrixRelayEnv as he}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as ue}from"./native-provider-sweep.js";import{scanCodexSessions as pe}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as ge}from"../adapter/claude/session-scanner.js";import{resolveClaudeConfigPaths as fe}from"../adapter/claude/config-paths.js";import{resolveAcpAgentTypes as me,scanAcpSessions as ve,scanReasonixSessionTitles as _e}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Se}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as Ce}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as be}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ae}from"../adapter/opencode/session-scanner.js";import{agentIdOf as Ee}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as we}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as _,resolveCodexLeafDirs as ye,resolveClaudeLeafDirs as Re,resolveAcpLeafDirs as ke,resolvePiLeafDirs as Te,resolveCodeWhaleLeafDirs as Pe,resolveCursorLeafDirs as xe,resolveOpenCodeLeafDirs as Me,resolveDshLeafDirs as Le,resolveReasonixLeafDirs as $e}from"./session-scan-cache.js";import{log as h,ConversationLog as De,AgentApiPacketLog as He,BridgeEventLog as Qe,GRIX_PATHS as R}from"../core/log/index.js";import{routeSessionControlCommand as Oe,routeSessionControlLocalAction as Ie}from"./session-control-router.js";import{maybeOfferCliInstall as Be,handleCliInstallQuestionReply as Fe,handleCliInstallInteractionReply as Ue,runConfirmedCliInstall as qe}from"./cli-install-flow.js";import{handleEventCancel as Ne,waitForEventDone as We,handleAibotStop as je,killAndResumeStopSlot as Ge,handleAibotRevoke as Ke}from"./event-stop.js";import{handleConfigureGatewayProvider as ze,getAuditLocalActionHandler as Je,handleAuditLocalAction as Xe,handleConnectorRollback as Ye,getRelayStateSyncer as Ve,relayStateSyncOnConnect as Ze,reportRelayStateLocalChange as et,handleApplyRelayState as tt,fetchRelayCredential as nt,isSharedInstance as it}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as st,handleConnectorAdminLocalAction as ot}from"./remote-admin.js";import{unbindSession as rt,handleUnbindTextCommand as at,handleUnbindLocalAction as dt,handleListSessionsTextCommand as lt,handleListSessionsLocalAction as ct,handleSyncHistoryLocalAction as ht}from"./session-list.js";import{handleCodexSessionControlOpen as ut,handleSessionControlForPool as pt,handleSessionControlLocalActionForPool as gt,handleCodexSessionControlLocalActionOpen as ft,handleCursorSessionControlLocalActionOpen as mt,handlePiSessionControlOpen as vt,handlePiSessionControlRestart as _t,handlePiSessionControlRestartLocalAction as St,syncOpenCodeBinding as Ct,isWorkspaceFreeClient as bt,isCwdLockedClient as At,ensureDefaultBindingForWorkspaceFreeClient as Et,bindSessionForPool as wt,deferredCallbacks as yt,handleOpenHumanSessionControlOpen as Rt,handleCodeWhaleSessionControlOpen as kt,handleCodeWhaleSessionControlLocalActionOpen as Tt,handleDeepSeekSessionControlLocalActionOpen as Pt}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as xt}from"./cwd-policy.js";import{normalizeCustomToolbarItems as Mt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as Lt,handleThreadCompact as $t}from"./session-usage.js";import{handleSkillDeleteLocalAction as Dt,handleSkillUploadLocalAction as Ht,handleSkillEnableLocalAction as Qt,handleSkillRefreshLocalAction as Ot,handleSkillDisableLocalAction as It,computeSkillReport as Bt,reportSessionSkills as Ft,skillsSyncGroupKey as Ut,forceRefreshSkills as qt,adoptSkillsWireHashFromDisk as Nt,buildLibrarySkillsReport as Wt,skillLookupEnv as jt}from"./skill-actions.js";import{resolveToolbarSelection as Gt,persistToolbarSelection as B}from"./toolbar-selection.js";import{normalizeClaudeModeId as Kt,handleExecCommandOptions as zt,resolveSessionModelId as Jt,resolveSessionModeId as Xt,resolveCursorSessionModeId as Yt,resolveClaudeSessionEffort as Vt,resolveClaudeSessionModeId as Zt,currentClaudeModeId as en,buildCursorToolbarMeta as tn,buildAgyToolbarMeta as nn,buildAgyQuotaMeta as sn,sendAgyBindingCard as on,refreshAndPushAgyQuota as rn,handleAgySetModel as an,buildClaudeToolbarMeta as dn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as ln,maybeQueryProviderQuota as cn,startProviderQuotaTimer as hn,stopProviderQuotaTimer as un,refreshAndPushProviderQuota as pn,pushProviderQuotaToBindings as gn,enrichProviderQuotaMeta as fn,providerQuotaMetaPayload as mn,refreshProviderQuotaForSession as vn,refreshQuotaAfterModelSwitch as _n,doRefreshQuotaAfterModelSwitch as Sn}from"./provider-quota.js";import{handleGetRateLimits as Cn,resolveRateLimitWakeSessionId as bn,wakeRateLimitSlot as An}from"./rate-limits.js";import{RevokeHandler as En}from"./revoke-handler.js";import{AdapterPool as wn}from"./adapter-pool.js";import{parseSessionControlCommand as yn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Rn,parseExecApprovalResolutionMessage as kn,parseAgentQuestionReplyMessage as Tn}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as Pn}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as xn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as Mn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as Ln}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as $n,handleFileListLocalAction as Dn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Hn,persistToolbarSelection as Qn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as On,ensureImportedAgentSession as In,hasDiskScanner as Bn,normalizePathForCompare as Fn,providerKeyForAdapter as Un,resolveAgentSessionId as qn,resolveOrphanTitle as Nn,setResolvedAgentSessionId as Wn}from"./session-identity.js";import{buildDshOpenedToolbarMeta as jn,dshCatalogDataRoot as Gn}from"./dsh-toolbar.js";import{ensureSlotStarted as Kn,failSessionOpen as zn,getClaudeWorkerStatus as Jn,refreshClaudeWorkerStatusCard as Xn,resolveCwdForBinding as Yn}from"./session-open-helpers.js";import{handleAcpSetModel as Vn,handleAcpSetMode as Zn,resolveAcpInitialDefaults as ei}from"./acp-toolbar-persist.js";import{SessionBindingStore as ti}from"../core/persistence/session-binding-store.js";import{serveLocalFile as ni}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as ii}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as si,buildInboundAttachmentsJson as oi,materializeInboundAttachments as ri}from"../core/protocol/inbound-attachments.js";import{ActiveEventStore as ai}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as di}from"./pending-event-coordinator.js";import{LifecycleBarrier as li}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ci}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as hi,applyConnectorRuntimeConfigPatch as ui,extractConnectorRuntimeConfigPatch as pi}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as gi,SendController as fi}from"./send-controller.js";import{splitTextForSendMsg as mi,clampProtocolText as S,AIBOT_PROTOCOL_MAX_MESSAGE_RUNES as F}from"../core/protocol/protocol-text.js";import{providerQuotaToRateLimits as vi,providerQuotaToCodexRateLimits as _i}from"../core/provider-quota/index.js";import{buildToolUseCard as b,buildToolResultCard as A,buildDshOnlineToolCard as Si,buildLocalGrixCardLink as U}from"./tool-card-utils.js";import{planRawEventDelivery as Ci,buildAuxiliaryDetailText as bi}from"./raw-event-delivery.js";import{DeferredEventManager as Ai}from"./deferred-events.js";import{buildAgentProbeResult as Ei,PROBE_CACHE_TTL_STATIC_MS as wi,PROBE_CACHE_TTL_FULL_MS as yi}from"./probe-helper.js";import{BridgeAuditController as Ri}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as ki,NoopAuditProducer as Ti}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as q,AuditPreparationFailedError as Pi,AuditTurnScopeUnsupportedError as xi}from"../audit/core/audit-state.js";import{extractAuditOptions as N,freezeAuditOptions as Mi,stripAuditOptions as Li}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as $i}from"../audit/core/audit-session-registry.js";import{waitForIdle as Di,formatWaitDuration as Hi}from"../core/upgrade/idle-wait.js";const Qi=600*1e3,W=4e3,k=500,Oi=4e3,Ii=1800*1e3,Bi=5*6e4,Fi=60*1e3,Ui=4e3;function qi(L,e,t){const r=D("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return P.join(R.data,"audit-source","reasonix",`${r}.jsonl`)}const Ni=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),T=3;class Do{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new En;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new fi(hi);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=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 li;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;rejectedOutputEvents=new Set;blockedDispatchEvents=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<=Fi}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return ln(this,e)}maybeQueryProviderQuota(e=!1,t){return cn(this,e,t)}startProviderQuotaTimer(){hn(this)}stopProviderQuotaTimer(){un(this)}refreshAndPushProviderQuota(e=!1){return pn(this,e)}pushProviderQuotaToBindings(e,t=!1){gn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return fn(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return mn(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return vn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){_n(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return Sn(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||r)}}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)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>Bi?{suspect:`admission held for ${Hi(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return Di({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:Ii,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}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,h.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,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let s=!1;await this.pool.removeSlot(n.sessionId).catch(o=>{r=!0,s=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${o}`)}),s||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),r?(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",r=e.conversation?yi:wi;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",s=this.createAdapter(n,"__probe__"),o=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(s,e.timeoutMs??1e4):void 0;let i;try{i=await Ei({adapter:s,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{s.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",s=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||j(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof C)try{await e.bindSession(n,o)}catch{}let a=null;const l=new Promise(u=>{a=g=>{g===s&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:s,session_id:n,content:"ping",msg_id:s}),e.deliverStopEvent(s,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new Ti){this.config=e,this.auditController=new Ri(r,{onAuditState:s=>{try{this.aibotHandle.sendAuditState(q(s,Date.now()))}catch{}}}),ki(r)&&r.addJobSettledHandler((s,o)=>{this.auditController.handleJobSettled(s,o)}),this.name=e.name;const n=e.adapterType??"acp";if(n==="claude"&&(e.claudeConfigPaths??=fe({...process.env,...e.agent.env})),this.sendCtrl.setDefaultQuoteTrigger(gi[n]),this.aibotConfig={...e.aibot,...n==="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",...K]}:{}},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 De(e.logDir):null,this.packetLog=e.logDir?new He(e.logDir):null,this.bindingStore=new ti(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new Ai(this.name),this.activeEventStore=e.activeEventStorePath?new ai(e.activeEventStorePath):null,this.pendingEvents=new di(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new _(pe,ye);else if(n==="claude"){const s=e.claudeConfigPaths?.projectsDir;this.sessionScanCache=new _(()=>ge(s),()=>Re(s))}else if(n==="pi"){const s=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new _(()=>Se(void 0,s),()=>Te(void 0,s))}else if(n==="codewhale")this.sessionScanCache=new _(Ce,Pe);else if(n==="cursor")this.sessionScanCache=new _(be,xe);else if(n==="opencode"){const s=Ee(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new _(()=>Ae(void 0,s),()=>Me(void 0,s))}else if(n==="deepseek-harness"){const s=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new _(()=>we(s),()=>Le(s))}else if(n==="agy")this.sessionScanCache=new _(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new _(_e,$e));const s=me(e.aibot.clientType);this.sessionScanCache=s?new _(()=>ve(void 0,s),()=>ke(void 0,s)):new _(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await ue({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(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&h.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{h.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await ie(this.config.claudeConfigPaths).catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}else(this.config.adapterType??"acp")==="agy"&&se(this.config.agent.command).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",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||r)&&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 s=this.config.adapterType??"acp";if(this.pool=new wn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const i=this.createAdapter(s,o);return i instanceof C&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(o,a),this.sessionScanCache.invalidate()}),i},(o,i)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((o,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${o} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(o),this.pendingEvents.remove(o).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${o}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:o,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(o,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(o),this.pendingEvents.remove(o).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${o}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((o,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:i,...i?{ttl_ms:ci,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((o,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((o,i)=>{this.markAuditAdapterClosed(o,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((o,i,a)=>{const l=this.selfDrivenSessions.has(o),d=this.selfDrivenLabels.get(o);i?(this.selfDrivenSessions.add(o),a&&this.selfDrivenLabels.set(o,a),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),l&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(o)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${s}, 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(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],s=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{o=await this.pendingEvents.mergeForShutdown(s)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!o)for(const i of s){const a=i.event;h.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){h.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=le(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(ce(t)){const s=re()?.getRuntimeInfo(),o={...r??{},...t},i=he(o,{proxyUrl:s?.proxyUrl,caCertPath:s?.caCertPath,caBundlePath:s?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(de(this.config.agent.clientType)){const s=ae(this.name);s&&(n={...n??{},...s})}return oe(n,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:(s,o,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(s,o,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Ui),sendThinking:(s,o,i)=>this.sendThinkingByRuntimeConfig(s,o,i),sendEventResult:(s,o,i,a)=>{this.sendEventResultWithCleanup(s,o,i,void 0,a)},sendRawEventEnvelope:(s,o,i,a)=>{const l=Si(i);if(l){this.sendToolExecutionCard(s,o,l);return}this.deliverRawEventEnvelope(s,o,i,"deepseek",a)},sendLocalActionResult:(s,o,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:o,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:s=>{this.sendGrixApprovalCard(s,"deepseek")},sendUpdateBindingCard:(s,o,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:o,cwd:i,...this.providerQuotaMetaPayload(a,s,i)})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:(s,o)=>this.maybeQueryProviderQuota(s===!0,o??{providerId:"deepseek"}),agentInvoke:async(s,o,i)=>this.platformInvoke(s,o,i),eventToolInvoke:async(s,o)=>this.invokeDshEventTool(s,o)},r=D("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new V({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:P.join(R.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.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 r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const s=this.resolveCursorSessionModeId(e),o=s??"full_auto";s||this.bindingStore.setCursorModeId(e,o),t.mode=o,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,g,p)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,g,p)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{this.sendGrixAgentQuestionCard(a,l,d)},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new X({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,w.bindingMissing,!0),this.pool.removeSlot(e).catch(c=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${c instanceof Error?c.message:String(c)}`)});const l=this.resolveBindingChannelKey("claude"),d=S(i.message,k);this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:U(d,"agent_open_session",{summary_text:d,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:w.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,g)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,g)},sendMedia:(i,a,l,d,c,u,g)=>{const p=S(d??"",W);this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:g?{media_caption:p,...g}:{media_caption:p}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,A(l,d))},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:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.sendDirectMessageInParts(i)},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay||(i.rateLimits?.modelScoped?.length??0)>0)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},s=this.config.adapterOptions??{},o={...s,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??Z.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o,claudeConfigPaths:this.config.claudeConfigPaths},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_${i}`,5e3,!0,!0,this.sendCtrl.getCodexDefaultQuotedMessageId(i)).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendStreamChunk:(i,a,l,d,c,u,g,p)=>{const v=typeof p?.phase=="string"?p.phase.trim().toLowerCase():"";(!v||v==="final_answer")&&l&&this.auditController.captureUnsequencedStreamChunk(i,l);const $=g!==void 0?g:this.sendCtrl.getCodexDefaultQuotedMessageId(i),f=this.indexEventSession(i,a)??a;this.sendCtrl.sendStreamChunk(i,f,l,d,c,u,$,{forceStream:!0,...p?.threadId?{threadId:p.threadId}:{}}),(l||c)&&this.conversationLog?.logOutbound?.(f,i,c?"stream_chunk_finish":"stream_chunk",l)},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.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:i=>{if(!i)return;this.cachedCodexContextWindow=i,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:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},s=this.auditController.getAdapterPreparation(e),o=i=>Gt(this,"codex",e,i);return t=new Q({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:o("model")??n.model,collaborationMode:o("mode")??n.collaborationMode,reasoningEffort:o("reasoningEffort")??n.reasoningEffort,serviceTier:o("serviceTier")??n.serviceTier,sandboxMode:o("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...I(s?.options)?{rawApiCapture:{auditId:s.auditId,sessionId:e,spoolRootDir:P.join(R.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),sendLocalActionResult:(n,s,o,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,s,o,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:s,active:o,...i??{}})},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,A(o,i))},agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new Y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,s,o,i,a)=>{this.sendEventResultWithCleanup(n,s,o,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,s,o,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:s,active:o,...i??{}})},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,A(o,i))},sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o,i,a)=>{this.sendRunErrorAsChunk(n,s,o,i,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendFinalStreamChunkReliable:async(n,s,o,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,s,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,A(o,i))},sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o)=>{this.sendRunErrorAsChunk(n,s,o,0)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new J({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,s,o,i,a)=>{this.sendEventResultWithCleanup(n,s,o,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${s}`)},sendEventAck:(n,s)=>this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()}),sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,A(o,i))},sendThinking:(n,s,o)=>{this.sendThinkingByRuntimeConfig(n,s,o)},sendRunError:(n,s,o)=>{this.sendRunErrorAsChunk(n,s,o)},sendUpdateBindingCard:(n,s,o,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(i,n,o)}),agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),sendLocalActionResult:(n,s,o,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:s,...o!==void 0?{result:o}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,s,o)=>{this.sendGrixAgentQuestionCard(n,s,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new M({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(n,s,o,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,s,o,i,a,l)},sendEventResult:(n,s,o)=>{this.sendEventResultWithCleanup(n,s,o)},sendEventAck:(n,s)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:s,received_at:Date.now()})},agentInvoke:async(n,s,o)=>this.platformInvoke(n,s,o),forceCompleteInternalEvent:(n,s)=>{this.pool.eventComplete(n,s),this.pushQueueSnapshotForSession(s)},persistConversationId:(n,s)=>{this.bindingStore.setAgyConversationId(n,s)},sendToolUse:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,b(o,i))},sendToolResult:(n,s,o,i)=>{this.sendToolExecutionCard(n,s,A(o,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const s=this.bindingStore.get(n);return{cwd:s?.cwd,modelId:this.resolveSessionModelId(n),conversationId:s?.agyConversationId}};return new O({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,g,p,v,E)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,g,p,v,E)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,g,p)=>{this.sendEventResultWithCleanup(d,c,u,g,p)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,g,p)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...g?{error_code:g}:{},...p?{error_msg:p}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,g)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:g??""}});return}this.sendToolExecutionCard(d,c,b(u,g))},sendToolResult:(d,c,u,g)=>{this.sendToolExecutionCard(d,c,A(u,g))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=S(d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName,Oi);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}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${x()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${S(d.toolTitle,k)}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(p){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:p instanceof Error?p.message:String(p)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,g)=>{const p={...g??{}};if(!p.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const v=this.providerQuotaToRateLimits(this.cachedProviderQuota);v&&(p.rate_limits=v)}!p.provider_quota&&this.cachedProviderQuota?.success&&(p.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(p).length>0?{meta:p}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:te(d,R.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),p={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(()=>{}),p.provider_quota=this.cachedProviderQuota;const v=this.providerQuotaToRateLimits(this.cachedProviderQuota);v&&(p.rate_limits=v)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:p})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,s=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&s?qi(this.name,e,s.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=ei({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new C({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,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 Qe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new G().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 r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(s=>{h.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const o=s instanceof Error?s.message:String(s);this.handleStaleCwdError(n,o)||this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(s){h.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){h.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(s){h.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(s){h.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(s){h.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(s=>{h.error(this.name,`handleAibotRevoke failed: ${s}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(s=>{h.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(s=>{h.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((n,s)=>{const o=this.pool.getSlot(n)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(s):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const s=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const s=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],o=this.pool.reorderQueue(n.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const s=typeof n.session_id=="string"?n.session_id:"",o=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${o} session_id=${s} hold=${i} reason=${n.reason??""}`),!s||!o){this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(s,o,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const s=typeof n.session_id=="string"?n.session_id:"",o=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${o} session_id=${s}`),!s||!o){this.aibotHandle.sendQueueEditResult({session_id:s,event_id:o,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(s,o,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:s,event_id:o,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const s of n)h.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,s)=>{this.handleStreamRejected(n,s)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(s=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${s}`)});try{this.pool?.rejectEventOutput(e,r)}catch(s){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${s}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const s=String(e??"").trim(),o=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=s!==this.agentProfile.agentName||o!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:s,introduction:o},this.agentSystemPrompt=i,s||o?h.info(this.name,`agent profile (${r.source}): GOT name="${s}" intro_len=${o.length} system_prompt_len=${i.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof H),s=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=n.length-s.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${s.length} idle Claude slot(s), skipping ${o} busy`);for(const i of s)this.pool.removeSlot(i.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=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"}]})):[],s=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(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(o),n.push({event_id:o,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:s}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.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,r){if(e==="file_link")return ni(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const s of n)this.rejectedOutputEvents.has(s)||this.blockedDispatchEvents.set(s,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=Mt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=ne(this.aibotHandle,e,t),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=S(String(e.caption??"").trim(),W),s=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const o=await ii({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${o.attachment_type}]`,client_msg_id:`file_upload_${x()}`,...s?{quoted_message_id:s}:{},extra:o.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.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,r,n,s){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,o,r,n,s),r&&this.conversationLog?.logOutbound?.(o,e,"reply",r)}sendDirectMessageInParts(e){const t=mi(e.content);t.length===0&&t.push(e.content);const r=t.length>1;for(let n=0;n<t.length;n++)this.aibotHandle.sendMsg({session_id:e.sessionId,msg_type:1,content:t[n],...e.clientMsgId?{client_msg_id:r?`${e.clientMsgId}_p${n+1}`:e.clientMsgId}:{},...n===0&&e.quotedMessageId?{quoted_message_id:e.quotedMessageId}:{}})}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:n,...s}=e;return s}if(e.codex_method!=="item/agentMessage/delta")return e;const r=this.sendCtrl.getCodexDefaultQuotedMessageId(e.event_id);return r?{...e,quoted_message_id:r}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}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(r,n,s,o)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,s,t,!1,!1,o)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,s,o,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,s,o,i),(r||s)&&this.conversationLog?.logOutbound?.(a,e,s?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,s){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
2
2
 
3
- Error: ${r}`,n,!1,s))}sendEventResultWithCleanup(e,t,r,n,s=!1){if(this.rejectedOutputEvents?.has(e))return;const o=this.blockedDispatchEvents?.get(e);this.blockedDispatchEvents?.delete(e),o&&t==="responded"&&(t="canceled",n=`agent_blocked_${o}`,r=`${o}: dispatch checkpoint saved; awaiting owner input`);const i=this.pool.getEventSessionId(e)??this.eventSessionIndex.get(e),a=r?.trim()??"";s&&this.markRunErrorSurfaced(e,a),t==="failed"&&i&&a&&this.sendRunErrorAsChunk(e,i,a);const l=t==="failed"&&a!==""&&(this.surfacedRunErrorTexts.get(e)?.has(a)??!1);if(this.auditController.markResponded(e,t,r),this.sendCtrl.finalizeOpenStreams(e),this.sendCtrl.sendEventResult(e,t,r,n,l),this.rejectedOutputEvents?.has(e))return;this.pool.cleanupEvent(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i??"-"} status=${t}`),i&&(this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,t,r)),this.eventSessionIndex.delete(e),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(c=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${c instanceof Error?c.message:String(c)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:r,errorMsg:n}=e;if(this.stopped||this.rejectedOutputEvents?.has(t))return;const s=this.inflightEvents.get(t);if(!s){h.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(t,r,n),this.sendEventResultWithCleanup(t,"failed",n,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const i=this.config.adapterType??"acp";if(o>k){h.error(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${o}/${k} outcome=give-up err=${n}`);const c=`${i} agent kept failing after ${k} automatic restarts: ${n}`;this.sendRunErrorAsChunk(t,r,c),this.sendEventResultWithCleanup(t,"failed",c,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${o}/${k} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped||this.rejectedOutputEvents?.has(t)){for(const c of a)this.stopped||await this.pool.deliverInboundEvent(c);return}const l=e.replayOriginalContent?s.content:this.resolveRecoveryPrompt(i,s),d={...s,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${t} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(t,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,r){this.sendCtrl.sendThinking(e,t,r)}bufferStreamChunk(e,t,r,n,s){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,t,r,n,s)}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(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const s=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const o=this.bindingStore.get(n.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(n,o.cwd),await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(s),this.deferredMgr.defer(n.channel,n.sessionId,s),r.push(n))}else await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||r.push(n)}catch(o){const i=o instanceof Error?o.message:String(o);h.error(this.name,`Pending event replay failed event=${s.event_id}: ${i}`),this.sendEventResultWithCleanup(s.event_id,"failed",i),this.pendingEvents.markCanceled(s.event_id),await this.pendingEvents.remove(s.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(t,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,r))}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 r=ki({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),s=this.auditController.startTurn({session:n,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"}});s&&(e.audit={...t,auditId:s.auditId,turnId:s.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const r=this.eventSessionIndex.get(e);return r?(r!==t&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${t}`),r):(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 r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,t,r,"acp",this.buildAcpRawEventFallbackText(r))}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,r,n,s){const o=fi({envelope:r,fallbackText:s,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),i=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[n]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){i();return}h.info("bridge",`${n} 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:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);i()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,r,n){this.sendCtrl.sendToolExecutionCard(e,t,r,n)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${T()}`,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,r){const n=r.questions.map(o=>o.header).join(", "),s=x(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:t,content:s,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const t=wn(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 n=this.pool.getSlot(e.session_id)?.adapter,s=n instanceof S?"acp":n instanceof P?"opencode":this.config.adapterType??"unknown",o=n instanceof P?n.handleQuestionReplyEvent(t):n instanceof S?await n.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(h.info(this.name,`[${s}] 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()})):(h.warn(this.name,`[${s}] 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=En(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 n=this.pool.getSlot(e.session_id)?.adapter,s=t.params,o=String(s.tool_call_id??s.approval_command_id??s.approval_id??s.exec_context_id??""),i=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...s,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 i.delivered?(h.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()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${i.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i.errorCode,msg:i.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.rejectedOutputEvents?.has(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}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",r=bn(e);if(t==="claude"&&this.sendCtrl.hasTerminalResult(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}let n;if(r&&(n=this.lifecycleBarrier.tryEnter(`session-control:${r.verb}`)??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const s=li(e.extra);if(s.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:s.error,updated_at:Date.now()});return}const o=s.patch,i=F(e.extra);if(yn(this,e,t,i))return;if(r){await Rn(this,r,e,t,i,this.config.agent.clientType??this.config.aibot.clientType);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(c){this.sendAuditConfigurationError(e,c);return}if(await kn(this,e,t,Oi.has(t),o,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,p,g]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(f=>f.name===p||f.name===`/${p}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const f=await A.execCommand(p,g.trim(),e.session_id);f.status==="options"&&f.data&&this.handleExecCommandOptions(e.session_id,p,f.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:f.status==="failed"?"failed":"responded",msg:f.message,updated_at:Date.now()})}catch(f){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f instanceof Error?f.message:String(f),updated_at:Date.now()})}return}}}if(t==="codex"&&O(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof H&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);d.attachments_json=await ni(d.attachments_json,{extraAllowedHosts:ei(this.aibotConfig.url),logTag:this.name});try{const c=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(!c)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()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}handleStaleCwdError(e,t){if(!/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(t)||!e.session_id)return!1;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 n=this.pool.getSlot(e.session_id);n?.adapter instanceof S&&n.adapter.getSessionBindings().delete(e.session_id);const s=this.config.adapterType??"acp",o=this.resolveBindingChannelKey(s);return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:t,extra:{channel_data:{[o]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:e.msg_id}),!0}failUndeliveredInboundEvent(e,t){const r=t instanceof Error?t.message:String(t);h.warn(this.name,`Inbound event undelivered event=${e.event_id} session=${e.session_id}: ${r}`),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),!this.handleStaleCwdError(e,r)&&this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return dt(this,e,t)}handleSessionControlForPool(e,t){return lt(this,e,t)}handleSessionControlLocalActionForPool(e){return ct(this,e)}handleCodexSessionControlLocalActionOpen(e){return ht(this,e)}handleCursorSessionControlLocalActionOpen(e){return ut(this,e)}handlePiSessionControlOpen(e,t){return pt(this,e,t)}handlePiSessionControlRestart(e){return gt(this,e)}handlePiSessionControlRestartLocalAction(e){return ft(this,e)}syncOpenCodeBinding(e,t){return mt(this,e,t)}isWorkspaceFreeClient(){return vt(this)}isCwdLockedClient(){return _t(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return St(this,e,t)}bindSessionForPool(e,t){return Ct(this,e,t)}deferredCallbacks(){return bt(this)}handleOpenHumanSessionControlOpen(e,t){return At(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Et(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return wt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return yt(this,e)}normalizeClaudeModeId(e){return Wt(this,e)}handleExecCommandOptions(e,t,r){Nt(this,e,t,r)}resolveSessionModelId(e){return jt(this,e)}resolveSessionModeId(e){return Gt(this,e)}resolveCursorSessionModeId(e){return Kt(this,e)}resolveClaudeSessionEffort(e){return zt(this,e)}resolveClaudeSessionModeId(e){return Jt(this,e)}currentClaudeModeId(e){return Yt(this,e)}buildCursorToolbarMeta(e){return Vt(this,e)}buildAgyToolbarMeta(e,t){return Xt(this,e,t)}buildAgyQuotaMeta(e){return Zt(this,e)}sendAgyBindingCard(e,t,r){return en(this,e,t,r)}refreshAndPushAgyQuota(e,t=!1){return tn(this,e,t)}handleAgySetModel(e,t){return nn(this,e,t)}buildClaudeToolbarMeta(e){return sn(this,e)}providerQuotaToCodexRateLimits(e){return pi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return Kn(e)}failSessionOpen(e,t){return Nn(this,e,t)}getClaudeWorkerStatus(e){return jn(this,e)}refreshClaudeWorkerStatusCard(e,t){return Gn(this,e,t)}async ensureSlotStarted(e,t=6e4){return Wn(this,e,t)}maybeOfferCliInstall(e){He(this,e)}handleCliInstallQuestionReply(e){return Qe(this,e)}handleCliInstallInteractionReply(e){return Oe(this,e)}runConfirmedCliInstall(e,t){return Ie(this,e,t)}handleSkillDeleteLocalAction(e){return xt(this,e)}handleSkillUploadLocalAction(e){return Lt(this,e)}handleSkillEnableLocalAction(e){return Mt(this,e)}handleSkillRefreshLocalAction(e){$t(this,e)}handleSkillDisableLocalAction(e){return Dt(this,e)}computeSkillReport(e){return Ht(this,e)}reportSessionSkills(e){Qt(this,e)}skillsSyncGroupKey(){return Ot(this)}forceRefreshSkills(e,t){return It(this,e,t)}adoptSkillsWireHashFromDisk(){Bt(this)}buildLibrarySkillsReport(e){return Ft(this,e)}skillLookupEnv(){return Ut(this)}resolveOrphanTitle(e){return Bn(this,e)}resolveAgentSessionId(e){return In(this,e)}providerKeyForAdapter(){return On(this)}setResolvedAgentSessionId(e,t){Fn(this,e,t)}normalizePathForCompare(e){return Qn(e)}ensureImportedAgentSession(e,t){Dn(this,e,t)}buildOpenedBindingResult(e,t,r="ready"){return $n(this,e,t,r)}buildDshOpenedToolbarMeta(e){return Un(this,e)}dshCatalogDataRoot(){return qn(this)}hasDiskScanner(){return Hn(this)}unbindSession(e){return nt(this,e)}handleUnbindTextCommand(e){return it(this,e)}handleUnbindLocalAction(e){return st(this,e)}handleListSessionsTextCommand(e){return ot(this,e)}handleListSessionsLocalAction(e){return rt(this,e)}handleSyncHistoryLocalAction(e){return at(this,e)}handleSessionControlCommand(e,t){return $e(this,e,t)}handleSessionControlLocalAction(e){return De(this,e)}handleEventCancel(e){return Be(this,e)}waitForEventDone(e,t,r){return Fe(this,e,t,r)}handleAibotStop(e){Ue(this,e)}killAndResumeStopSlot(e,t){return qe(this,e,t)}handleAibotRevoke(e){return We(this,e)}handleConfigureGatewayProvider(e){return Ne(this,e)}getAuditLocalActionHandler(){return je(this)}handleAuditLocalAction(e){return Ge(this,e)}handleConnectorRollback(e){return Ke(this,e)}getRelayStateSyncer(){return ze(this)}relayStateSyncOnConnect(){Je(this)}reportRelayStateLocalChange(){Ye(this)}handleApplyRelayState(e){return Ve(this,e)}fetchRelayCredential(e){return Xe(this,e)}handleConnectorAdminLocalAction(e){return tt(this,e)}isSharedInstance(){return Ze(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??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${t} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let s;if(t===m.sessionControl&&(s=this.lifecycleBarrier.tryEnter(`local-action:${n||t}`)??void 0,!s)){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===m.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Y(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===m.sessionControl&&n===w.exec&&await this.handleSessionControlLocalAction(e))return;if(t===m.sessionControl&&n===w.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===m.sessionControl&&n===w.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===m.sessionControl&&n===w.unbind){if(this.isCwdLockedClient()){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.verbInvalid,error_msg:kt});return}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 i=(this.config.adapterType??"acp")==="opencode";if((o&&(t===m.interactionReply||t==="exec_approve"||t==="exec_reject")||i&&t===m.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===m.sessionControl){await Tn(this,e,r);return}if(t==="file_list"){await xn(this,e,r);return}if(t==="create_folder"){await Pn(this,e,r);return}if(t===m.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(t===m.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(t===m.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((o||a||l)&&t===m.threadCompact){await this.handleThreadCompact(e,r);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===m.getAgentGlobalConfig){const g=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...g?{config:g}:{config:null}}});return}if(t===et){await this.handleConnectorAdminLocalAction(e);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",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){Mn(this,e,r,d,u);return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.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")){await Ln(this,e,r,t);return}const p=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:p?`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{s?.()}}handleGetSessionUsage(e,t){return Tt(this,e,t)}handleThreadCompact(e,t){return Pt(this,e,t)}handleGetRateLimits(e,t){return mn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return vn(this,e,t)}wakeRateLimitSlot(e,t){return _n(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),r=t?.adapter instanceof S?t.adapter:null,n=(this.config.adapterType??"acp")==="acp",s={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const i=this.bindingStore.get(e);i?.cwd&&o.set(e,i.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:o=>r?r.setMode(o):Promise.resolve(!1),setModel:o=>r?r.setModel(o):Promise.resolve(!1),acpSetMode:n?(o,i)=>Jn(s,o,i):void 0,acpSetModel:n?(o,i)=>zn(s,o,i):void 0,getPendingApproval:o=>{const i=r?.pendingApprovalEntries.get(o);return i?{requestId:i}:void 0},deletePendingApproval:o=>r?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,i)=>(r&&r.respondToPermission(o,i),Promise.resolve()),onSessionBound:(o,i)=>{this.bindingStore.set(o,i)},onSessionUnbound:o=>{this.unbindSession(o).catch(i=>{h.warn(this.name,`session unbind cleanup failed: ${i instanceof Error?i.message:String(i)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof Q?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{I(this,this.config.adapterType??"acp",e,"mode",o)},onModelSet:o=>{I(this,this.config.adapterType??"acp",e,"model",o),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,r)=>this.aibotHandle.sendEventAck({event_id:t,session_id:r,received_at:Date.now()}),sendEventResult:(t,r,n)=>this.aibotHandle.sendEventResult({event_id:t,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,r,n,s,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:r,...n?{result:n}:{},...s?{error_code:s}:{},...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 r=t instanceof Error?t.message:String(t),n=(()=>{const a=F(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),s=t instanceof yi||t instanceof wi,o=t instanceof Ti&&n,i=o?"audit_config_invalid":s?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:i,msg:r,updated_at:Date.now()}),s||o)try{this.aibotHandle.sendAuditState(B({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const n=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,t,r){const n=this.buildInboundEvent(e,t),s=this.bindingStore.get(e.session_id),o=s?this.resolveAgentSessionId(s):void 0,i=Number(e.created_at),a=Number.isFinite(i)&&i>0?new Date(i).toISOString():void 0,l=this.auditController.startTurn({session:r,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 l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,t){const r=di(this.sendCtrl.getGlobalRuntimeConfig(),t),n=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:n===void 0?void 0:JSON.stringify(n),attachments_json:ti(e.attachments),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(r=>!An(String(r?.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>Li}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=>{h.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}setRemoteAdminPorts(e){this.remoteAdminPorts=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};
3
+ Error: ${r}`,n,!1,s))}sendEventResultWithCleanup(e,t,r,n,s=!1){if(this.rejectedOutputEvents?.has(e))return;const o=this.blockedDispatchEvents?.get(e);this.blockedDispatchEvents?.delete(e),o&&t==="responded"&&(t="canceled",n=`agent_blocked_${o}`,r=`${o}: dispatch checkpoint saved; awaiting owner input`);const i=this.pool.getEventSessionId(e)??this.eventSessionIndex.get(e),a=r?.trim()??"";s&&this.markRunErrorSurfaced(e,a),t==="failed"&&i&&a&&this.sendRunErrorAsChunk(e,i,a);const l=t==="failed"&&a!==""&&(this.surfacedRunErrorTexts.get(e)?.has(a)??!1);if(this.auditController.markResponded(e,t,r),this.sendCtrl.finalizeOpenStreams(e),this.sendCtrl.sendEventResult(e,t,r,n,l),this.rejectedOutputEvents?.has(e))return;this.pool.cleanupEvent(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i??"-"} status=${t}`),i&&(this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,t,r)),this.eventSessionIndex.delete(e),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(c=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${c instanceof Error?c.message:String(c)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:r,errorMsg:n}=e;if(this.stopped||this.rejectedOutputEvents?.has(t))return;const s=this.inflightEvents.get(t);if(!s){h.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(t,r,n),this.sendEventResultWithCleanup(t,"failed",n,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const i=this.config.adapterType??"acp";if(o>T){h.error(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${o}/${T} outcome=give-up err=${n}`);const c=`${i} agent kept failing after ${T} automatic restarts: ${n}`;this.sendRunErrorAsChunk(t,r,c),this.sendEventResultWithCleanup(t,"failed",c,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${o}/${T} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped||this.rejectedOutputEvents?.has(t)){for(const c of a)this.stopped||await this.pool.deliverInboundEvent(c);return}const l=e.replayOriginalContent?s.content:this.resolveRecoveryPrompt(i,s),d={...s,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${t} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(t,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,r){this.sendCtrl.sendThinking(e,t,r)}bufferStreamChunk(e,t,r,n,s){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,t,r,n,s)}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(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const s=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const o=this.bindingStore.get(n.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(n,o.cwd),await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(s),this.deferredMgr.defer(n.channel,n.sessionId,s),r.push(n))}else await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||r.push(n)}catch(o){const i=o instanceof Error?o.message:String(o);h.error(this.name,`Pending event replay failed event=${s.event_id}: ${i}`),this.sendEventResultWithCleanup(s.event_id,"failed",i),this.pendingEvents.markCanceled(s.event_id),await this.pendingEvents.remove(s.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(t,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,r))}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 r=Mi({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),s=this.auditController.startTurn({session:n,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"}});s&&(e.audit={...t,auditId:s.auditId,turnId:s.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const r=this.eventSessionIndex.get(e);return r?(r!==t&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${t}`),r):(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 r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,t,r,"acp",this.buildAcpRawEventFallbackText(r))}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,r,n,s){const o=Ci({envelope:r,fallbackText:s,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),i=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[n]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){i();return}h.info("bridge",`${n} 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,bi({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);i()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,r,n){this.sendCtrl.sendToolExecutionCard(e,t,r,n)}sendGrixApprovalCard(e,t){const r=S(e.toolTitle||e.toolName,k);this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${x()}`,msg_type:1,content:e.toolTitle?`Permission required: ${r}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:r,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,r){const n=S(r.questions.map(o=>o.header).join(", "),k);let s=U(`[Agent Question] ${r.request_id}`,"agent_question",r);[...s].length>F&&(h.warn("bridge",`agent question card too large, falling back to text request=${r.request_id}`),s=S(`[Agent Question] ${r.request_id}
4
+ ${n}`,F)),this.aibotHandle.sendText({event_id:e,session_id:t,content:s,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const t=Tn(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 n=this.pool.getSlot(e.session_id)?.adapter,s=n instanceof C?"acp":n instanceof M?"opencode":this.config.adapterType??"unknown",o=n instanceof M?n.handleQuestionReplyEvent(t):n instanceof C?await n.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(h.info(this.name,`[${s}] 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()})):(h.warn(this.name,`[${s}] 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=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 n=this.pool.getSlot(e.session_id)?.adapter,s=t.params,o=String(s.tool_call_id??s.approval_command_id??s.approval_id??s.exec_context_id??""),i=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...s,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 i.delivered?(h.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()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${i.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i.errorCode,msg:i.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.rejectedOutputEvents?.has(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}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",r=yn(e);if(t==="claude"&&this.sendCtrl.hasTerminalResult(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}let n;if(r&&(n=this.lifecycleBarrier.tryEnter(`session-control:${r.verb}`)??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const s=pi(e.extra);if(s.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:s.error,updated_at:Date.now()});return}const o=s.patch,i=N(e.extra);if(Pn(this,e,t,i))return;if(r){await Mn(this,r,e,t,i,this.config.agent.clientType??this.config.aibot.clientType);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(c){this.sendAuditConfigurationError(e,c);return}if(await xn(this,e,t,Ni.has(t),o,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,g,p]=u,E=this.pool.getSlot(e.session_id)?.adapter;if(E?.execCommand&&(E.getSupportedCommands?.()??[]).some(f=>f.name===g||f.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const f=await E.execCommand(g,p.trim(),e.session_id);f.status==="options"&&f.data&&this.handleExecCommandOptions(e.session_id,g,f.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:f.status==="failed"?"failed":"responded",msg:f.message,updated_at:Date.now()})}catch(f){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f instanceof Error?f.message:String(f),updated_at:Date.now()})}return}}}if(t==="codex"&&I(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof Q&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);d.attachments_json=await ri(d.attachments_json,{extraAllowedHosts:si(this.aibotConfig.url),logTag:this.name});try{const c=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(!c)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()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}handleStaleCwdError(e,t){if(!/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(t)||!e.session_id)return!1;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 n=this.pool.getSlot(e.session_id);n?.adapter instanceof C&&n.adapter.getSessionBindings().delete(e.session_id);const s=this.config.adapterType??"acp",o=this.resolveBindingChannelKey(s);return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:t,extra:{channel_data:{[o]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:w.invalidCwd}}}},quoted_message_id:e.msg_id}),!0}failUndeliveredInboundEvent(e,t){const r=t instanceof Error?t.message:String(t);h.warn(this.name,`Inbound event undelivered event=${e.event_id} session=${e.session_id}: ${r}`),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),!this.handleStaleCwdError(e,r)&&this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return ut(this,e,t)}handleSessionControlForPool(e,t){return pt(this,e,t)}handleSessionControlLocalActionForPool(e){return gt(this,e)}handleCodexSessionControlLocalActionOpen(e){return ft(this,e)}handleCursorSessionControlLocalActionOpen(e){return mt(this,e)}handlePiSessionControlOpen(e,t){return vt(this,e,t)}handlePiSessionControlRestart(e){return _t(this,e)}handlePiSessionControlRestartLocalAction(e){return St(this,e)}syncOpenCodeBinding(e,t){return Ct(this,e,t)}isWorkspaceFreeClient(){return bt(this)}isCwdLockedClient(){return At(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Et(this,e,t)}bindSessionForPool(e,t){return wt(this,e,t)}deferredCallbacks(){return yt(this)}handleOpenHumanSessionControlOpen(e,t){return Rt(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return kt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Tt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return Pt(this,e)}normalizeClaudeModeId(e){return Kt(this,e)}handleExecCommandOptions(e,t,r){zt(this,e,t,r)}resolveSessionModelId(e){return Jt(this,e)}resolveSessionModeId(e){return Xt(this,e)}resolveCursorSessionModeId(e){return Yt(this,e)}resolveClaudeSessionEffort(e){return Vt(this,e)}resolveClaudeSessionModeId(e){return Zt(this,e)}currentClaudeModeId(e){return en(this,e)}buildCursorToolbarMeta(e){return tn(this,e)}buildAgyToolbarMeta(e,t){return nn(this,e,t)}buildAgyQuotaMeta(e){return sn(this,e)}sendAgyBindingCard(e,t,r){return on(this,e,t,r)}refreshAndPushAgyQuota(e,t=!1){return rn(this,e,t)}handleAgySetModel(e,t){return an(this,e,t)}buildClaudeToolbarMeta(e){return dn(this,e)}providerQuotaToCodexRateLimits(e){return _i(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return vi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return Yn(e)}failSessionOpen(e,t){return zn(this,e,t)}getClaudeWorkerStatus(e){return Jn(this,e)}refreshClaudeWorkerStatusCard(e,t){return Xn(this,e,t)}async ensureSlotStarted(e,t=6e4){return Kn(this,e,t)}maybeOfferCliInstall(e){Be(this,e)}handleCliInstallQuestionReply(e){return Fe(this,e)}handleCliInstallInteractionReply(e){return Ue(this,e)}runConfirmedCliInstall(e,t){return qe(this,e,t)}handleSkillDeleteLocalAction(e){return Dt(this,e)}handleSkillUploadLocalAction(e){return Ht(this,e)}handleSkillEnableLocalAction(e){return Qt(this,e)}handleSkillRefreshLocalAction(e){Ot(this,e)}handleSkillDisableLocalAction(e){return It(this,e)}computeSkillReport(e){return Bt(this,e)}reportSessionSkills(e){Ft(this,e)}skillsSyncGroupKey(){return Ut(this)}forceRefreshSkills(e,t){return qt(this,e,t)}adoptSkillsWireHashFromDisk(){Nt(this)}buildLibrarySkillsReport(e){return Wt(this,e)}skillLookupEnv(){return jt(this)}resolveOrphanTitle(e){return Nn(this,e)}resolveAgentSessionId(e){return qn(this,e)}providerKeyForAdapter(){return Un(this)}setResolvedAgentSessionId(e,t){Wn(this,e,t)}normalizePathForCompare(e){return Fn(e)}ensureImportedAgentSession(e,t){In(this,e,t)}buildOpenedBindingResult(e,t,r="ready"){return On(this,e,t,r)}buildDshOpenedToolbarMeta(e){return jn(this,e)}dshCatalogDataRoot(){return Gn(this)}hasDiskScanner(){return Bn(this)}unbindSession(e){return rt(this,e)}handleUnbindTextCommand(e){return at(this,e)}handleUnbindLocalAction(e){return dt(this,e)}handleListSessionsTextCommand(e){return lt(this,e)}handleListSessionsLocalAction(e){return ct(this,e)}handleSyncHistoryLocalAction(e){return ht(this,e)}handleSessionControlCommand(e,t){return Oe(this,e,t)}handleSessionControlLocalAction(e){return Ie(this,e)}handleEventCancel(e){return Ne(this,e)}waitForEventDone(e,t,r){return We(this,e,t,r)}handleAibotStop(e){je(this,e)}killAndResumeStopSlot(e,t){return Ge(this,e,t)}handleAibotRevoke(e){return Ke(this,e)}handleConfigureGatewayProvider(e){return ze(this,e)}getAuditLocalActionHandler(){return Je(this)}handleAuditLocalAction(e){return Xe(this,e)}handleConnectorRollback(e){return Ye(this,e)}getRelayStateSyncer(){return Ve(this)}relayStateSyncOnConnect(){Ze(this)}reportRelayStateLocalChange(){et(this)}handleApplyRelayState(e){return tt(this,e)}fetchRelayCredential(e){return nt(this,e)}handleConnectorAdminLocalAction(e){return ot(this,e)}isSharedInstance(){return it(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??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${t} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let s;if(t===m.sessionControl&&(s=this.lifecycleBarrier.tryEnter(`local-action:${n||t}`)??void 0,!s)){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===m.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(ee(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===m.sessionControl&&n===y.exec&&await this.handleSessionControlLocalAction(e))return;if(t===m.sessionControl&&n===y.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===m.sessionControl&&n===y.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===m.sessionControl&&n===y.unbind){if(this.isCwdLockedClient()){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:w.verbInvalid,error_msg:xt});return}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 i=(this.config.adapterType??"acp")==="opencode";if((o&&(t===m.interactionReply||t==="exec_approve"||t==="exec_reject")||i&&t===m.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===m.sessionControl){await Ln(this,e,r);return}if(t==="file_list"){await Dn(this,e,r);return}if(t==="create_folder"){await $n(this,e,r);return}if(t===m.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(t===m.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(t===m.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((o||a||l)&&t===m.threadCompact){await this.handleThreadCompact(e,r);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===m.getAgentGlobalConfig){const p=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...p?{config:p}:{config:null}}});return}if(t===st){await this.handleConnectorAdminLocalAction(e);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",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){Qn(this,e,r,d,u);return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:w.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){await Hn(this,e,r,t);return}const g=!!r&&!!this.pool.getSlot(r);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{s?.()}}handleGetSessionUsage(e,t){return Lt(this,e,t)}handleThreadCompact(e,t){return $t(this,e,t)}handleGetRateLimits(e,t){return Cn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return bn(this,e,t)}wakeRateLimitSlot(e,t){return An(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),r=t?.adapter instanceof C?t.adapter:null,n=(this.config.adapterType??"acp")==="acp",s={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const i=this.bindingStore.get(e);i?.cwd&&o.set(e,i.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:o=>r?r.setMode(o):Promise.resolve(!1),setModel:o=>r?r.setModel(o):Promise.resolve(!1),acpSetMode:n?(o,i)=>Zn(s,o,i):void 0,acpSetModel:n?(o,i)=>Vn(s,o,i):void 0,getPendingApproval:o=>{const i=r?.pendingApprovalEntries.get(o);return i?{requestId:i}:void 0},deletePendingApproval:o=>r?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,i)=>(r&&r.respondToPermission(o,i),Promise.resolve()),onSessionBound:(o,i)=>{this.bindingStore.set(o,i)},onSessionUnbound:o=>{this.unbindSession(o).catch(i=>{h.warn(this.name,`session unbind cleanup failed: ${i instanceof Error?i.message:String(i)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof O?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{B(this,this.config.adapterType??"acp",e,"mode",o)},onModelSet:o=>{B(this,this.config.adapterType??"acp",e,"model",o),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,r)=>this.aibotHandle.sendEventAck({event_id:t,session_id:r,received_at:Date.now()}),sendEventResult:(t,r,n)=>this.aibotHandle.sendEventResult({event_id:t,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,r,n,s,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:r,...n?{result:n}:{},...s?{error_code:s}:{},...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 r=t instanceof Error?t.message:String(t),n=(()=>{const a=N(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),s=t instanceof xi||t instanceof Pi,o=t instanceof $i&&n,i=o?"audit_config_invalid":s?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:i,msg:r,updated_at:Date.now()}),s||o)try{this.aibotHandle.sendAuditState(q({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const n=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,t,r){const n=this.buildInboundEvent(e,t),s=this.bindingStore.get(e.session_id),o=s?this.resolveAgentSessionId(s):void 0,i=Number(e.created_at),a=Number.isFinite(i)&&i>0?new Date(i).toISOString():void 0,l=this.auditController.startTurn({session:r,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 l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,t){const r=ui(this.sendCtrl.getGlobalRuntimeConfig(),t),n=Li(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:n===void 0?void 0:JSON.stringify(n),attachments_json:oi(e.attachments),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(r=>!Rn(String(r?.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>Qi}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=>{h.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}setRemoteAdminPorts(e){this.remoteAdminPorts=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{Do as AgentInstance};