grix-connector 4.2.7 → 4.2.9

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,13 +1,9 @@
1
- import $ from"node:path";import{existsSync as ce}from"node:fs";import{realpath as xe,stat as z}from"node:fs/promises";import{tmpdir as De,homedir as U}from"node:os";import{createHash as V,randomUUID as F}from"node:crypto";import{ConnectionManager as Be}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as Qe}from"../core/aibot/types.js";import{ClaudeAdapter as B}from"../adapter/claude/index.js";import{CodexAdapter as le}from"../adapter/codex/index.js";import{PiAdapter as Oe}from"../adapter/pi/index.js";import{AcpAdapter as R}from"../adapter/acp/index.js";import{OpenHumanAdapter as qe}from"../adapter/openhuman/index.js";import{CursorAdapter as N,CURSOR_MODE_OPTIONS as Ue,fetchCursorAccountUsage as Fe}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as ue}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as W}from"../adapter/opencode/index.js";import{AgyAdapter as he}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as Y,buildDshBindingToolbarMeta as Ne,DEFAULT_DSH_PRESETS as We,listDshPlugins as Ke,listDshSkills as Ge,listDshProfiles as je,normalizeDshReasoningEffort as ze,normalizeDshThinking as Ve,readDshCredentials as Ye,resolveDshAgentPreset as Je,resolveDshCatalogForToolbar as Xe,resolveDshHome as Ze,resolveDshModeId as ge,resolveDshSelectedProfileName as et}from"../adapter/deepseek-harness/index.js";import{getCachedAgyModels as pe,resolveAgyToolbarModelId as fe}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as J,refreshAgyQuotaInfo as X}from"../adapter/agy/quota.js";import{LOCAL_ACTION_ERROR_CODES as L,LOCAL_ACTION_TYPES as E,SESSION_CONTROL_ERROR_CODES as f,SESSION_CONTROL_VERBS as v,SESSION_MODE_IDS as y}from"../adapter/claude/protocol-contract.js";import{AuditLocalActionHandler as tt,isAuditLocalActionType as it}from"../audit/query/audit-local-actions.js";import{AuditReplayQueryService as nt}from"../audit/query/audit-replay-query-service.js";import{resolveDefaultAuditStorageRootDir as st}from"../audit/runtime/default-audit-recorder.js";import{FileAuditReplayStore as ot}from"../audit/storage/file-audit-replay-store.js";import{shouldEnableRawApiCapture as me}from"../audit/raw-capture/types.js";import{parseClaudeSessionUsage as rt}from"../adapter/claude/usage-parser.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{SESSION_HISTORY_ERROR_CODES as K,SessionHistoryError as at,getSessionHistoryReader as dt}from"../adapter/shared/session-history.js";import{resolveSkillScanMode as H}from"../adapter/claude/skill-scanner.js";import{resolveHermesHomeDir as ct}from"../adapter/shared/native-provider-config.js";import{buildReportedSkills as lt,syncDefaultSkillsToDir as ut}from"../default-skills/index.js";import{buildWireSkills as _e}from"../core/skill-sync/sync-state.js";import{executeEventTool as ht}from"../core/mcp/event-tool-executor.js";import{uploadSkill as gt}from"../core/skill-sync/skill-upload.js";import{deleteLocalSkill as pt}from"../core/skill-sync/skill-delete.js";import{buildLibrarySkills as ft}from"../core/skill-sync/library-skills.js";import{enableSkill as mt,disableSkill as _t,SkillEnableError as ve}from"../core/skill-sync/skill-enable.js";import{fetchAvailableModels as Z,getCachedModels as ee,readSettingsEnv as vt}from"../adapter/claude/model-list.js";import{parseAcpSessionUsage as St}from"../adapter/acp/usage-parser.js";import{applyProxyEnv as bt,getProxyManager as Se,relayHostsForClientType as wt,buildGatewayRoute as Ct}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as At}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as be}from"../core/config/provider-env.js";import{RelayFetchError as Et,deriveGatewayBaseUrls as te,fetchRelayCredentialWithRetry as kt}from"../core/proxy/relay-credential-fetch.js";import{RelayStateSyncer as Rt}from"../core/proxy/relay-state-sync.js";import{isDirectRelayExplicitlyUnsupported as yt}from"../core/proxy/relay-credential.js";import{buildProviderEnv as we}from"../core/config/provider-env.js";import{CLAUDE_EFFORT_LEVELS as Q,isClaudeDirectEnv as $t,normalizeClaudeEffort as ie,stripGrixRelayEnv as Pt}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as It}from"./native-provider-sweep.js";import{parseCodexSessionUsage as Tt}from"../adapter/codex/usage-parser.js";import{readCodexProviderSettings as Lt}from"../adapter/codex/codex-trust.js";import{resolveKimiProviderSettings as Ht}from"../core/provider-quota/index.js";import{scanCodexSessions as Mt}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as xt}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as Dt,resolveAcpAgentTypes as Bt,scanAcpSessions as Qt,scanReasonixSessionTitles as Ot}from"../adapter/acp/session-scanner.js";import{scanPiSessions as qt}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as Ut}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as Ft}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Nt}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as Wt}from"../adapter/deepseek-harness/session-scanner.js";import{parsePiSessionUsage as Kt}from"../adapter/pi/usage-parser.js";import{SessionScanCache as P,resolveCodexLeafDirs as Gt,resolveClaudeLeafDirs as jt,resolveAcpLeafDirs as zt,resolvePiLeafDirs as Vt,resolveCodeWhaleLeafDirs as Yt,resolveCursorLeafDirs as Jt,resolveOpenCodeLeafDirs as Xt,resolveDshLeafDirs as Zt,resolveReasonixLeafDirs as ei}from"./session-scan-cache.js";import{log as u,ConversationLog as ti,AgentApiPacketLog as ii,BridgeEventLog as ni,GRIX_PATHS as I}from"../core/log/index.js";import{RevokeHandler as si}from"./revoke-handler.js";import{AdapterPool as oi}from"./adapter-pool.js";import{parseSessionControlCommand as ri,handleSessionControlCommand as Ce,handleSessionControlLocalAction as ai}from"./session-controller.js";import{isOpenSessionDirectiveMessage as di,parseExecApprovalResolutionMessage as ci,parseAgentQuestionReplyMessage as Ae}from"../core/protocol/interaction-parser.js";import{resolveCliPath as li}from"../core/util/cli-probe.js";import{buildCliInstallQuestion as ui,CLI_INSTALL_OPTION_YES as hi,CLI_INSTALL_REQUEST_PREFIX as gi,cliDisplayName as pi,isCliMissingError as ne,isInstallConfirmReply as fi,resolveInstallAgentType as mi,sessionControlOpenFailure as _i}from"./cli-install-offer.js";import{handleAcpSetModel as Ee,handleAcpSetMode as ke,resolveAcpInitialDefaults as vi}from"./acp-toolbar-persist.js";import{SessionBindingStore as Si}from"../core/persistence/session-binding-store.js";import{handleFileListAction as bi,handleCreateFolderAction as wi,serveLocalFile as Ci,realHomeDir as Re}from"../core/files/index.js";import{getMachineName as Ai}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as Ei}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ki}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as Ri}from"./pending-event-coordinator.js";import{LifecycleBarrier as yi}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as $i}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Pi,applyConnectorRuntimeConfigPatch as Ii,extractConnectorRuntimeConfigPatch as Ti}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as Li,SendController as Hi}from"./send-controller.js";import{sharedProviderQuotaService as se,detectProviderFromModel as O,normalizeProviderId as oe,readPiProviderSettings as Mi,readOpenCodeProviderSettings as xi,providerQuotaToRateLimits as ye,providerQuotaToCodexRateLimits as $e,isOpenaiCodexProviderName as Di,queryOpenaiCodexQuota as Pe,openaiCodexQuotaCacheKey as Bi}from"../core/provider-quota/index.js";import{queryKiroQuota as re}from"../core/provider-quota/kiro.js";import{buildToolUseCard as M,buildToolResultCard as x,buildDshOnlineToolCard as Qi,buildLocalGrixCardLink as Ie}from"./tool-card-utils.js";import{planRawEventDelivery as Oi,buildAuxiliaryDetailText as qi}from"./raw-event-delivery.js";import{DeferredEventManager as Ui}from"./deferred-events.js";import{buildAgentProbeResult as Fi,PROBE_CACHE_TTL_STATIC_MS as Ni,PROBE_CACHE_TTL_FULL_MS as Wi}from"./probe-helper.js";import{BridgeAuditController as Ki}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Gi,NoopAuditProducer as ji}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as G,AuditPreparationFailedError as zi,AuditTurnScopeUnsupportedError as Vi}from"../audit/core/audit-state.js";import{extractAuditOptions as Te,freezeAuditOptions as Yi,stripAuditOptions as Ji}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Xi}from"../audit/core/audit-session-registry.js";const Zi=600*1e3,Le=1800*1e3,en=60*1e3,He=30*1e3,tn=10*1e3,nn=10*1e3,sn=4e3;function ae(q,e){return JSON.stringify({skills:q,library_skills:e})}function on(q,e,n){const t=V("sha256").update(q).update("\0").update(e).update("\0").update(n).digest("hex");return $.join(I.data,"audit-source","reasonix",`${t}.jsonl`)}const j=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),Me=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),rn=new Set(["hermes"]),de=3;class zs{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new si;sessionBindings=new Map;deferredMgr;sendCtrl=new Hi(Pi);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new yi;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const n=Number(e);return n>0&&Date.now()-n<=en}async resolveProviderQuotaSource(e){if(e?.disabled||e?.providerId==="openai_codex")return null;let n=this.config.providerBaseUrl??this.config.agent.provider?.baseUrl,t=this.config.providerApiKey??this.config.agent.provider?.apiKey;if((this.config.adapterType??"acp")==="deepseek-harness"){if(t??=this.config.agent.env?.DEEPSEEK_API_KEY,n??=this.config.agent.env?.DEEPSEEK_BASE_URL,!t){const s=Ze(typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:void 0,this.config.agent.env);try{const o=await Ye(s),r=typeof o.DEEPSEEK_API_KEY=="string"?o.DEEPSEEK_API_KEY.trim():"";r&&(t=r,n??=typeof o.DEEPSEEK_BASE_URL=="string"&&o.DEEPSEEK_BASE_URL.trim()?o.DEEPSEEK_BASE_URL.trim():"https://api.deepseek.com",u.debug(this.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}catch(o){u.warn(this.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${o instanceof Error?o.message:String(o)}`)}}n??=t?"https://api.deepseek.com":void 0}if((!n||!t)&&(this.config.adapterType??"acp")==="claude"){const s=vt();n||(n=(s.ANTHROPIC_BASE_URL??"").trim()||void 0),t||(t=(s.ANTHROPIC_API_KEY??"").trim()||(s.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!n||!t)&&(this.config.adapterType??"acp")==="codex"){const s=Lt();!n&&s.baseUrl&&(n=s.baseUrl),!t&&s.apiKey&&(t=s.apiKey)}if((!n||!t)&&(this.config.adapterType??"acp")==="acp"&&this.config.aibot.clientType==="kimi"){const s=await Ht();!n&&s.baseUrl&&(n=s.baseUrl),!t&&s.apiKey&&(t=s.apiKey)}if((!n||!t)&&(this.config.adapterType??"acp")==="pi"){const s=Mi(e);!n&&s.baseUrl&&(n=s.baseUrl),!t&&s.apiKey&&(t=s.apiKey)}if((!n||!t)&&(this.config.adapterType??"acp")==="opencode"){const s=xi(e);!n&&s.baseUrl&&(n=s.baseUrl),!t&&s.apiKey&&(t=s.apiKey)}if(!n||!t)return null;const i=oe(e?.providerId)??O(e?.model)?.id??oe(this.config.agent.provider?.providerId)??O(this.config.agent.provider?.model)?.id;return{baseUrl:n,...this.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:this.config.agent.provider.quotaBaseUrl}:{},apiKey:t,...i?{providerId:i}:{}}}async maybeQueryProviderQuota(e=!1,n){if(this.config.aibot.clientType==="kiro"){if(!e&&this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const s=await re();return this.cachedProviderQuota=s,this.cachedProviderQuotaSampledAtMs=Date.now(),this.cachedProviderQuotaKey="kiro",u.info(this.name,`[provider-quota] kiro queried: success=${s.success}`+(s.balance?` balance=${s.balance.remaining} ${s.balance.unit}`:"")+(s.planName?` plan=${s.planName}`:"")+(s.error?` error=${s.error}`:"")),s}catch(s){return u.warn(this.name,`[provider-quota] kiro query failed: ${s instanceof Error?s.message:String(s)}`),null}}if(n?.providerId==="openai_codex")try{const s=await Pe();return s.quota.success?s.quota:null}catch(s){return u.warn(this.name,`[provider-quota] openai_codex query failed: ${s instanceof Error?s.message:String(s)}`),null}const t=await this.resolveProviderQuotaSource(n);if(!t)return null;const i=se.cacheKey(t);if(!e&&this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota&&this.cachedProviderQuotaKey===i)return this.cachedProviderQuota;try{const s=await se.query(t,{fresh:e}),o=s.quota;return this.cachedProviderQuota=o,this.cachedProviderQuotaSampledAtMs=s.sampledAt,this.cachedProviderQuotaKey=s.cacheKey,u.info(this.name,`[provider-quota] queried: provider=${o.provider} success=${o.success}`+(o.tiers.length>0?` tiers=${o.tiers.map(r=>`${r.name}=${r.usedPercent}%`).join(",")}`:"")+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.error}`:"")),o}catch(s){return u.warn(this.name,`[provider-quota] query failed: ${s instanceof Error?s.message:String(s)}`),null}}startProviderQuotaTimer(){this.stopped||this.providerQuotaTimer||(this.providerQuotaTimer=setInterval(()=>{if(this.stopped){this.stopProviderQuotaTimer();return}this.refreshAndPushProviderQuota().catch(()=>{})},He),u.info(this.name,`[provider-quota-timer] started (interval=${He}ms)`))}stopProviderQuotaTimer(){this.providerQuotaTimer&&(clearInterval(this.providerQuotaTimer),this.providerQuotaTimer=null,u.info(this.name,"[provider-quota-timer] stopped"))}async refreshAndPushProviderQuota(e=!1){try{let n;if(this.config.aibot.clientType==="kiro")n=await re(),this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),this.cachedProviderQuotaKey="kiro";else{const t=[...this.sessionBindings.entries()].filter(([i,s])=>!!s&&this.sessionProviderHints.has(i));if(t.length>0&&await Promise.all(t.map(([i,s])=>this.refreshProviderQuotaForSession(i,s,e))),t.length===this.sessionBindings.size&&t.length>0)return;n=await this.maybeQueryProviderQuota(e)}n?.success&&this.pushProviderQuotaToBindings(n,this.sessionProviderHints.size>0)}catch{}}pushProviderQuotaToBindings(e,n=!1){const t=this.providerQuotaToRateLimits(e);for(const[i,s]of this.sessionBindings.entries()){if(!s||n&&this.sessionProviderHints.has(i))continue;if((this.config.adapterType??"acp")==="deepseek-harness"){const a=this.pool.getSlot(i)?.adapter;if(a instanceof Y){a.updateProviderQuotaSnapshot(e);continue}}const o={provider_quota:e};t&&(o.rate_limits=t);const r=this.cachedAcpContextWindow;r&&("usedPercentage"in r?o.context_window={usedPercentage:r.usedPercentage,remainingPercentage:100-r.usedPercentage}:o.context_window=r),this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:s,meta:o})}}enrichProviderQuotaMeta(e,n="standard",t=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){const s={...e??{}};if(!t?.success||(s.provider_quota||(s.provider_quota=t),s.rate_limits))return s;if(n==="codex"){const r=$e(t,i??Date.now());return r&&(s.rate_limits=r.rateLimits,s.rate_limit_primary_percent=r.primaryPercent,s.rate_limit_secondary_percent=r.secondaryPercent,s.rate_limit_primary_window_min=r.primaryWindowMin,s.rate_limit_secondary_window_min=r.secondaryWindowMin),s}const o=ye(t,i??Date.now());return o&&(s.rate_limits=o),s}providerQuotaMetaPayload(e,n,t){let i=this.cachedProviderQuota,s=this.cachedProviderQuotaSampledAtMs,o=!1;if(n){const a=typeof e?.model_provider=="string"?e.model_provider:void 0,d=typeof e?.model_id=="string"?e.model_id:void 0,c=oe(a)??O(a)?.id??O(d)?.id??(Di(a)?"openai_codex":null);if(c||d){const h=a?.trim().toLowerCase()??"",g=h==="grix"||h.startsWith("grix-"),p={...c?{providerId:c}:{},...d?{model:d}:{},...!!a&&!g&&!c?{disabled:!0}:{}},_=this.sessionProviderHints.get(n),b=_?.providerId!==p.providerId||_?.model!==p.model||_?.disabled!==p.disabled;this.sessionProviderHints.set(n,p),this.sessionProviderMeta.set(n,{...e??{}}),b&&this.sessionProviderQuotas.delete(n),(b||!this.sessionProviderQuotas.has(n))&&t&&this.refreshProviderQuotaForSession(n,t,!1)}const l=this.sessionProviderQuotas.get(n);o=this.sessionProviderHints.has(n),o&&(i=null,s=null),l&&(i=l.quota,s=l.sampledAt)}const r=this.enrichProviderQuotaMeta(e,"standard",i,s);return o&&(r.provider_quota||(r.provider_quota=null),r.rate_limits||(r.rate_limits=null)),Object.keys(r).length>0?{meta:r}:{}}async refreshProviderQuotaForSession(e,n,t){const i=this.sessionProviderHints.get(e);if(!i)return;if(i.disabled){u.debug(this.name,`[provider-quota] session skip: session=${e} reason=hint_disabled providerId=${i.providerId??""} model=${i.model??""}`);return}const s=`${i.providerId??""}|${i.model??""}|false`;try{let o,r,a;if(i.providerId==="openai_codex"){const h=this.sessionProviderQuotas.get(e);if(!t&&h&&h.quota.success&&h.cacheKey.startsWith("openai_codex|")&&this.isRateLimitsCacheFresh(h.sampledAt))o=h.quota,r=h.sampledAt,a=h.cacheKey;else{const g=await Pe();o=g.quota,r=Date.now(),a=Bi(g.accountKey)}}else{const h=await this.resolveProviderQuotaSource(i);if(!h){u.debug(this.name,`[provider-quota] session skip: session=${e} reason=no_source providerId=${i.providerId??""} model=${i.model??""}`);return}const g=await se.query(h,{fresh:t});o=g.quota,r=g.sampledAt,a=g.cacheKey}const d=this.sessionProviderHints.get(e);if(`${d?.providerId??""}|${d?.model??""}|${d?.disabled===!0}`!==s)return;if(u.info(this.name,`[provider-quota] queried: provider=${o.provider} success=${o.success}`+(o.tiers.length>0?` tiers=${o.tiers.map(h=>`${h.name}=${h.usedPercent}%`).join(",")}`:"")+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.error}`:"")+` session=${e}`),!o.success){const h=this.sessionProviderQuotas.get(e);(!h?.quota.success||h.cacheKey!==a)&&this.sessionProviderQuotas.delete(e);return}this.sessionProviderQuotas.set(e,{quota:o,sampledAt:r,cacheKey:a});const l=this.enrichProviderQuotaMeta(this.sessionProviderMeta.get(e),"standard",o,r);this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:l})}catch(o){u.warn(this.name,`[provider-quota] session query failed: session=${e} ${o instanceof Error?o.message:String(o)}`)}}refreshQuotaAfterModelSwitch(e,n,t){const i=n.trim();if(!e||!i)return;const s=t?.trim()||void 0,o=`${e}|${s??""}|${i}`,r=Date.now();this.lastModelSwitchQuotaRefresh&&this.lastModelSwitchQuotaRefresh.key===o&&r-this.lastModelSwitchQuotaRefresh.at<tn||(this.lastModelSwitchQuotaRefresh={key:o,at:r},this.doRefreshQuotaAfterModelSwitch(e,i,s).catch(a=>{u.warn(this.name,`[provider-quota] model-switch refresh failed: session=${e} model=${i} ${a instanceof Error?a.message:String(a)}`)}))}async doRefreshQuotaAfterModelSwitch(e,n,t){const i=this.sessionProviderHints.get(e);if(i||t){const o=t??O(n)?.id??i?.providerId,r={...o?{providerId:o}:{},model:n,...i?.disabled?{disabled:!0}:{}},a=i?.providerId!==r.providerId||i?.model!==r.model||i?.disabled!==r.disabled;this.sessionProviderHints.set(e,r),a&&this.sessionProviderQuotas.delete(e);const d=this.sessionBindings.get(e)??this.bindingStore.get(e)?.cwd??"";(a||!this.sessionProviderQuotas.has(e))&&d&&await this.refreshProviderQuotaForSession(e,d,!0);return}const s=await this.maybeQueryProviderQuota(!0,{model:n});s?.success&&this.pushProviderQuotaToBindings(s,this.sessionProviderHints.size>0)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,n=this.cachedCodexContextWindow,t=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:n,tokenUsage:t,hasData:!!(e||n||t)}}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(n=>n.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const n=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(n()){const t=Math.round(Le/6e4);u.info(this.name,`${e}: active tasks detected, waiting up to ${t}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+Le,s=5e3,o=600*1e3;let r=Date.now();for(;n()&&!this.stopped;){if(Date.now()>=i)return u.warn(this.name,`${e}: idle wait exceeded ${t}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,s)),Date.now()-r>=o&&(r=Date.now(),u.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),n()?(u.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(u.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,u.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 n=0,t=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let s=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{t=!0,s=!0,u.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),s||(n+=1)}return n>0&&u.info(this.name,`recycled ${n} adapter slot(s) so the new Grix relay env takes effect`),t?(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 n=e.conversation?"full":"static",t=e.conversation?Wi:Ni;if(!e.fresh){const a=this.probeCache.get(n);if(a&&Date.now()-a.sampledAt<t)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",s=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(s,e.timeoutMs??1e4):void 0;let r;try{r=await Fi({adapter:s,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{s.stop().catch(()=>{})}return this.probeCache.set(n,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,n){const t=Date.now(),i="__probe__",s=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||De(),r=()=>Date.now()-t;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof R)try{await e.bindSession(i,o)}catch{}let a=null;const d=new Promise(h=>{a=g=>{g===s&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:s,session_id:i,content:"ping",msg_id:s}),e.deliverStopEvent(s,i);let c=null;const l=await Promise.race([d.then(()=>!1),new Promise(h=>{c=setTimeout(()=>h(!0),n)})]);return c&&clearTimeout(c),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${n}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,n,t=new ji){this.config=e,this.auditController=new Ki(t,{onAuditState:s=>{try{this.aibotHandle.sendAuditState(G(s,Date.now()))}catch{}}}),Gi(t)&&t.addJobSettledHandler((s,o)=>{this.auditController.handleJobSettled(s,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(Li[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...Qe]}:{}},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 ti(e.logDir):null,this.packetLog=e.logDir?new ii(e.logDir):null,this.bindingStore=new Si(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=n??null,this.deferredMgr=new Ui(this.name),this.activeEventStore=e.activeEventStorePath?new ki(e.activeEventStorePath):null,this.pendingEvents=new Ri(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new P(Mt,Gt);else if(i==="claude")this.sessionScanCache=new P(xt,jt);else if(i==="pi"){const s=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new P(()=>qt(void 0,s),()=>Vt(void 0,s))}else if(i==="codewhale")this.sessionScanCache=new P(Ut,Yt);else if(i==="cursor")this.sessionScanCache=new P(Ft,Jt);else if(i==="opencode")this.sessionScanCache=new P(Nt,Xt);else if(i==="deepseek-harness"){const s=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new P(()=>Wt(s),()=>Zt(s))}else if(i==="agy")this.sessionScanCache=new P(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new P(Ot,ei));const s=Bt(e.aibot.clientType);this.sessionScanCache=s?new P(()=>Qt(void 0,s),()=>zt(void 0,s)):new P(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await It({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(([,s])=>String(s.cwd??""))}).then(s=>{s.length>0&&u.info(this.name,`restored native provider config after relay disable: ${s.join(", ")}`)}).catch(s=>{u.warn(this.name,`native provider residue sweep failed: ${s instanceof Error?s.message:String(s)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await Z().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),n=(this.config.adapterType??"acp")==="pi",t=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(n||t)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new oi({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},s=>{const o=this.createAdapter(i,s);return o instanceof R&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(s,r),this.sessionScanCache.invalidate()}),o},(s,o)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((s,o,r,a)=>{if(u.info(this.name,`[queue-debug] send event_state session=${o} event=${s} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:s,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(s),this.pendingEvents.remove(s).catch(d=>{u.warn(this.name,`Failed to remove running event from pending store event=${s}: ${d instanceof Error?d.message:String(d)}`)})),r==="canceled"||r==="failed"){const d=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:s,status:d,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(s,d,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(s),this.pendingEvents.remove(s).catch(c=>{u.warn(this.name,`Failed to remove queued terminal event from pending store event=${s}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((s,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:o,...o?{ttl_ms:$i,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(s=>{this.handleSessionInternalError(s).catch(o=>{u.error(this.name,`[recovery] handleSessionInternalError failed event=${s.eventId} session=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((s,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((s,o)=>{this.markAuditAdapterClosed(s,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const d=this.buildAgyToolbarMeta(o),c=d?.available_models??[];u.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,d),this.refreshAndPushAgyQuota(o)}else u.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((s,o,r)=>{const a=this.selfDrivenSessions.has(s),d=this.selfDrivenLabels.get(s);o?(this.selfDrivenSessions.add(s),r&&this.selfDrivenLabels.set(s,r),this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(s),this.selfDrivenLabels.delete(s),a&&this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==d)&&this.pushQueueSnapshotForSession(s)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),u.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const n=this.stopOnce();this.stopPromise=n,n.catch(()=>{this.stopPromise===n&&(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()??[],n=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)u.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=n.get(r),d=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,d?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const t=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],s=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...t.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){u.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(s)}catch(r){u.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of s){const a=r.event;u.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){u.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,n=we(this.config.agent.clientType,e),t=this.config.agent.env;let i=Object.keys(n).length>0?{...n,...t}:t;if($t(n)){const s=Se()?.getRuntimeInfo(),o={...t??{},...n},r=Pt(o,{proxyUrl:s?.proxyUrl,caCertPath:s?.caCertPath,caBundlePath:s?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(be(this.config.agent.clientType)){const s=At(this.name);s&&(i={...i??{},...s})}return bt(i,this.name,this.config.agent.clientType)}createAdapter(e,n){switch(e){case"claude":return this.createClaudeAdapter(n);case"codex":return this.createCodexAdapter(n);case"pi":return this.createPiAdapter(n);case"openhuman":return this.createOpenHumanAdapter(n);case"codewhale":return this.createCodeWhaleAdapter(n);case"cursor":return this.createCursorAdapter(n);case"opencode":return this.createOpenCodeAdapter(n);case"agy":return this.createAgyAdapter(n);case"deepseek-harness":return this.createDshAdapter(n);default:return this.createAcpAdapter(n)}}createDshAdapter(e){const n={sendStreamChunk:(s,o,r,a,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(s,o,r,a,d,c,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",sn),sendThinking:(s,o,r)=>this.sendThinkingByRuntimeConfig(s,o,r),sendEventResult:(s,o,r,a)=>{this.sendEventResultWithCleanup(s,o,r,void 0,a)},sendRawEventEnvelope:(s,o,r,a)=>{const d=Qi(r);if(d){this.sendToolExecutionCard(s,o,d);return}this.deliverRawEventEnvelope(s,o,r,"deepseek",a)},sendLocalActionResult:(s,o,r,a,d)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...d?{error_msg:d}:{}},e)},sendPermissionCard:s=>{this.sendGrixApprovalCard(s,"deepseek")},sendUpdateBindingCard:(s,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:s=>this.maybeQueryProviderQuota(s===!0,{providerId:"deepseek"}),agentInvoke:async(s,o,r)=>this.platformInvoke(s,o,r),eventToolInvoke:async(s,o)=>this.invokeDshEventTool(s,o)},t=V("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new Y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},n,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:$.join(I.data,"deepseek-harness",t),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const n={...this.config.adapterOptions??{}};n.bindingStore=this.bindingStore,n.aibotSessionId=e;const t=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(n.model=i);const s=this.resolveCursorSessionModeId(e),o=s??"full_auto";s||this.bindingStore.setCursorModeId(e,o),n.mode=o,t?.cwd&&(n.workspace=t.cwd);const r={sendStreamChunk:(a,d,c,l,h,g,m)=>{this.sendStreamChunkByRuntimeConfig(a,d,c,l,h,g,m)},sendEventResult:(a,d,c)=>{this.sendEventResultWithCleanup(a,d,c)},sendEventAck:(a,d)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:d,received_at:Date.now()})},sendRawEventEnvelope:(a,d,c)=>{this.deliverRawEventEnvelope(a,d,c,"cursor",this.buildCursorRawEventFallbackText(c))},sendAgentQuestionCard:(a,d,c)=>{const l=c.questions.map(g=>g.header).join(", "),h=Ie(`[Agent Question] ${c.request_id}`,"agent_question",c);this.aibotHandle.sendText({event_id:a,session_id:d,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,d,c)=>this.platformInvoke(a,d,c),sendLocalActionResult:(a,d,c,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:d,...c!==void 0?{result:c}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,d,c,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:d,cwd:c,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},r)}createClaudeAdapter(e){const n={sendReply:(s,o,r,a,d)=>{this.sendReplyByRuntimeConfig(s,o,r,a,d)},sendStreamChunk:(s,o,r,a,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(s,o,r,a,d,c,l)},sendMedia:(s,o,r,a,d,c,l)=>{this.aibotHandle.sendMedia({event_id:s,session_id:o,content:r,msg_type:2,quoted_message_id:d||void 0,client_msg_id:c||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(s,o,r,a)=>{this.sendEventResultWithCleanup(s,o,r,a)},sendEventAck:(s,o)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:o,received_at:Date.now()})},agentInvoke:async(s,o,r)=>this.platformInvoke(s,o,r),sendLocalActionResult:(s,o,r,a,d)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...d?{error_msg:d}:{}},e)},sendToolUse:(s,o,r,a)=>{this.sendToolExecutionCard(s,o,M(r,a))},sendToolResult:(s,o,r,a)=>{this.sendToolExecutionCard(s,o,x(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(s,o,r)=>{this.sendGrixAgentQuestionCard(s,o,r)},sendPermissionCard:s=>{this.sendGrixApprovalCard(s,"claude")},sendDirectMessage:s=>{this.aibotHandle.sendMsg({session_id:s.sessionId,msg_type:1,content:s.content,...s.clientMsgId?{client_msg_id:s.clientMsgId}:{},...s.quotedMessageId?{quoted_message_id:s.quotedMessageId}:{}})},onStatusLineUpdated:s=>{(s.rateLimits?.fiveHour||s.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=s);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:s=>{this.aibotHandle.sendMcpFrame(e,s)}},t=this.config.adapterOptions??{},i={...t,sessionRuntimeResolver:()=>{const s=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:s?.cwd,modeId:this.resolveClaudeSessionModeId(e)??y.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:t.pluginDir,claudeSessionId:s?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new B({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},n)}createCodexAdapter(e){let n=null;const t={sendEventResult:(r,a,d)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,d);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,d),c=>{const l=`codex output acceptance fence failed: ${c instanceof Error?c.message:String(c)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:d)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,d)=>{this.sendThinkingByRuntimeConfig(r,a,d)},sendRunError:(r,a,d)=>{this.sendRunErrorAsChunk(r,a,d)},sendUpdateBindingCard:(r,a,d,c)=>{const l={...c??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:d,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,d)=>this.platformInvoke(r,a,d),sendLocalActionResult:(r,a,d,c,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,d,c)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:d,...c??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const d=this.cachedRateLimitsSampledAtMs,c={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:d},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...n?.getEffortMeta()};this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:c})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:r,...n?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},s=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return n=new le({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,s?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(s?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,s?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(s?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...me(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:$.join(I.data,"audit-replay","raw-spool")}}:{}}},t),n}createCodeWhaleAdapter(e){const n={sendEventResult:(i,s,o)=>{this.sendEventResultWithCleanup(i,s,o)},sendEventAck:(i,s)=>this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()}),sendStreamChunk:(i,s,o,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(i,s,o,r,a,d)},sendUpdateBindingCard:(i,s,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,s,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,s,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:s,active:o,...r??{}})},sendToolUse:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,M(o,r))},sendToolResult:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,x(o,r))},agentInvoke:async(i,s,o)=>this.platformInvoke(i,s,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},t=this.config.adapterOptions??{};return new ue({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??t.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},n)}createPiAdapter(e){const n={sendEventResult:(i,s,o)=>{this.sendEventResultWithCleanup(i,s,o),u.info("bridge",`[pi] sendEventResult event=${i} status=${s}`)},sendEventAck:(i,s)=>this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()}),sendUpdateBindingCard:(i,s,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,s,o)=>this.platformInvoke(i,s,o),sendLocalActionResult:(i,s,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,s,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:s,active:o,...r??{}})},sendToolUse:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,M(o,r))},sendToolResult:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,x(o,r))},sendStreamChunk:(i,s,o,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(i,s,o,r,a,d),a&&u.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,s,o)=>{this.sendThinkingByRuntimeConfig(i,s,o)},sendRunError:(i,s,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,s,`
1
+ import T from"node:path";import{realpath as te,stat as Q}from"node:fs/promises";import{tmpdir as ne}from"node:os";import{createHash as O,randomUUID as B}from"node:crypto";import{ConnectionManager as ie}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as se}from"../core/aibot/types.js";import{ClaudeAdapter as N}from"../adapter/claude/index.js";import{CodexAdapter as W}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as oe}from"../adapter/pi/index.js";import{AcpAdapter as y}from"../adapter/acp/index.js";import{OpenHumanAdapter as re}from"../adapter/openhuman/index.js";import{CursorAdapter as ae}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as de}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as F}from"../adapter/opencode/index.js";import{AgyAdapter as G}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as le,buildDshBindingToolbarMeta as ce,DEFAULT_DSH_PRESETS as he,listDshPlugins as ue,listDshSkills as pe,listDshProfiles as ge,normalizeDshReasoningEffort as fe,normalizeDshThinking as me,resolveDshAgentPreset as ve,resolveDshCatalogForToolbar as _e,resolveDshModeId as j,resolveDshSelectedProfileName as Se}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as k,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as S,SESSION_MODE_IDS as be}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Ce}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as K}from"../audit/raw-capture/types.js";import{syncDefaultSkillsToDir as we}from"../default-skills/index.js";import{buildWireSkills as Ae}from"../core/skill-sync/sync-state.js";import{executeEventTool as Ee}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as ke}from"../adapter/claude/model-list.js";import{applyProxyEnv as Re,getProxyManager as ye}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as Pe}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as Te}from"../core/config/provider-env.js";import{buildProviderEnv as xe}from"../core/config/provider-env.js";import{isClaudeDirectEnv as De,stripGrixRelayEnv as Me}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as He}from"./native-provider-sweep.js";import{scanCodexSessions as Le}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as $e}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as Ie,resolveAcpAgentTypes as Qe,scanAcpSessions as Oe,scanReasonixSessionTitles as Be}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Fe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as qe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as Ue}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ne}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as We}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as P,resolveCodexLeafDirs as Ge,resolveClaudeLeafDirs as je,resolveAcpLeafDirs as Ke,resolvePiLeafDirs as ze,resolveCodeWhaleLeafDirs as Je,resolveCursorLeafDirs as Ye,resolveOpenCodeLeafDirs as Xe,resolveDshLeafDirs as Ve,resolveReasonixLeafDirs as Ze}from"./session-scan-cache.js";import{log as p,ConversationLog as et,AgentApiPacketLog as tt,BridgeEventLog as nt,GRIX_PATHS as L}from"../core/log/index.js";import{routeSessionControlCommand as it,routeSessionControlLocalAction as st}from"./session-control-router.js";import{maybeOfferCliInstall as ot,handleCliInstallQuestionReply as rt,handleCliInstallInteractionReply as at,runConfirmedCliInstall as dt}from"./cli-install-flow.js";import{handleEventCancel as lt,waitForEventDone as ct,handleAibotStop as ht,killAndResumeStopSlot as ut,handleAibotRevoke as pt}from"./event-stop.js";import{handleConfigureGatewayProvider as gt,getAuditLocalActionHandler as ft,handleAuditLocalAction as mt,handleConnectorRollback as vt,getRelayStateSyncer as _t,relayStateSyncOnConnect as St,reportRelayStateLocalChange as bt,handleApplyRelayState as Ct,fetchRelayCredential as wt,isSharedInstance as At}from"./connector-ops.js";import{unbindSession as Et,handleUnbindTextCommand as kt,handleUnbindLocalAction as Rt,handleListSessionsTextCommand as yt,handleListSessionsLocalAction as Pt,handleSyncHistoryLocalAction as Tt}from"./session-list.js";import{handleCodexSessionControlOpen as xt,handleSessionControlForPool as Dt,handleSessionControlLocalActionForPool as Mt,handleCodexSessionControlLocalActionOpen as Ht,handleCursorSessionControlLocalActionOpen as Lt,handlePiSessionControlOpen as $t,handlePiSessionControlRestart as It,handlePiSessionControlRestartLocalAction as Qt,syncOpenCodeBinding as Ot,isWorkspaceFreeClient as Bt,ensureDefaultBindingForWorkspaceFreeClient as Ft,bindSessionForPool as qt,deferredCallbacks as Ut,handleOpenHumanSessionControlOpen as Nt,handleCodeWhaleSessionControlOpen as Wt,handleCodeWhaleSessionControlLocalActionOpen as Gt,handleDeepSeekSessionControlLocalActionOpen as jt}from"./session-control-open.js";import{handleGetSessionUsage as Kt,handleThreadCompact as zt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Jt,handleSkillUploadLocalAction as Yt,handleSkillEnableLocalAction as Xt,handleSkillRefreshLocalAction as Vt,handleSkillDisableLocalAction as Zt,computeSkillReport as en,reportSessionSkills as tn,skillsSyncGroupKey as nn,forceRefreshSkills as sn,adoptSkillsWireHashFromDisk as on,buildLibrarySkillsReport as rn,skillLookupEnv as an}from"./skill-actions.js";import{normalizeClaudeModeId as dn,handleExecCommandOptions as ln,resolveSessionModelId as cn,resolveSessionModeId as hn,resolveCursorSessionModeId as un,resolveClaudeSessionEffort as pn,resolveClaudeSessionModeId as gn,currentClaudeModeId as fn,resolveCodexSessionModelId as mn,resolveCodexNewSessionGlobalDefault as vn,pinCodexGlobalDefault as _n,buildCursorToolbarMeta as Sn,buildAgyToolbarMeta as bn,buildAgyQuotaMeta as Cn,sendAgyBindingCard as wn,refreshAndPushAgyQuota as An,handleAgySetModel as En,buildClaudeToolbarMeta as kn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Rn,maybeQueryProviderQuota as yn,startProviderQuotaTimer as Pn,stopProviderQuotaTimer as Tn,refreshAndPushProviderQuota as xn,pushProviderQuotaToBindings as Dn,enrichProviderQuotaMeta as Mn,providerQuotaMetaPayload as Hn,refreshProviderQuotaForSession as Ln,refreshQuotaAfterModelSwitch as $n,doRefreshQuotaAfterModelSwitch as In}from"./provider-quota.js";import{handleGetRateLimits as Qn,resolveRateLimitWakeSessionId as On,wakeRateLimitSlot as Bn}from"./rate-limits.js";import{RevokeHandler as Fn}from"./revoke-handler.js";import{AdapterPool as qn}from"./adapter-pool.js";import{parseSessionControlCommand as Un,handleSessionControlCommand as Nn,handleSessionControlLocalAction as Wn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Gn,parseExecApprovalResolutionMessage as jn,parseAgentQuestionReplyMessage as Kn}from"../core/protocol/interaction-parser.js";import{isCliMissingError as zn,sessionControlOpenFailure as Jn}from"./cli-install-offer.js";import{handleAcpSetModel as z,handleAcpSetMode as J,resolveAcpInitialDefaults as Yn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Xn}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Vn,handleCreateFolderAction as Zn,serveLocalFile as ei,realHomeDir as Y}from"../core/files/index.js";import{getMachineName as ti}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as ni}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ii}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as si}from"./pending-event-coordinator.js";import{LifecycleBarrier as oi}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ri}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as ai,applyConnectorRuntimeConfigPatch as di,extractConnectorRuntimeConfigPatch as li}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ci,SendController as hi}from"./send-controller.js";import{providerQuotaToRateLimits as ui,providerQuotaToCodexRateLimits as pi}from"../core/provider-quota/index.js";import{buildToolUseCard as D,buildToolResultCard as M,buildDshOnlineToolCard as gi,buildLocalGrixCardLink as X}from"./tool-card-utils.js";import{planRawEventDelivery as fi,buildAuxiliaryDetailText as mi}from"./raw-event-delivery.js";import{DeferredEventManager as vi}from"./deferred-events.js";import{buildAgentProbeResult as _i,PROBE_CACHE_TTL_STATIC_MS as Si,PROBE_CACHE_TTL_FULL_MS as bi}from"./probe-helper.js";import{BridgeAuditController as Ci}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as wi,NoopAuditProducer as Ai}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as $,AuditPreparationFailedError as Ei,AuditTurnScopeUnsupportedError as ki}from"../audit/core/audit-state.js";import{extractAuditOptions as V,freezeAuditOptions as Ri,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Pi}from"../audit/core/audit-session-registry.js";const Ti=600*1e3,Z=1800*1e3,xi=60*1e3,Di=4e3;function Mi(U,e,t){const s=O("sha256").update(U).update("\0").update(e).update("\0").update(t).digest("hex");return T.join(L.data,"audit-source","reasonix",`${s}.jsonl`)}const I=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),ee=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),q=3;class ao{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Fn;sessionBindings=new Map;deferredMgr;sendCtrl=new hi(ai);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new oi;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=xi}resolveProviderQuotaSource(e){return Rn(this,e)}maybeQueryProviderQuota(e=!1,t){return yn(this,e,t)}startProviderQuotaTimer(){Pn(this)}stopProviderQuotaTimer(){Tn(this)}refreshAndPushProviderQuota(e=!1){return xn(this,e)}pushProviderQuotaToBindings(e,t=!1){Dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",s=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){return Mn(this,e,t,s,i)}providerQuotaMetaPayload(e,t,s){return Hn(this,e,t,s)}refreshProviderQuotaForSession(e,t,s){return Ln(this,e,t,s)}refreshQuotaAfterModelSwitch(e,t,s){$n(this,e,t,s)}doRefreshQuotaAfterModelSwitch(e,t,s){return In(this,e,t,s)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,s=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:s,hasData:!!(e||t||s)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const t=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(t()){const s=Math.round(Z/6e4);p.info(this.name,`${e}: active tasks detected, waiting up to ${s}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+Z,n=5e3,o=600*1e3;let r=Date.now();for(;t()&&!this.stopped;){if(Date.now()>=i)return p.warn(this.name,`${e}: idle wait exceeded ${s}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,n)),Date.now()-r>=o&&(r=Date.now(),p.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),t()?(p.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(p.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,s=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let n=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{s=!0,n=!0,p.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),n||(t+=1)}return t>0&&p.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),s?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",s=e.conversation?bi:Si;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<s)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",n=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(n,e.timeoutMs??1e4):void 0;let r;try{r=await _i({adapter:n,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{n.stop().catch(()=>{})}return this.probeCache.set(t,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,t){const s=Date.now(),i="__probe__",n=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||ne(),r=()=>Date.now()-s;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof y)try{await e.bindSession(i,o)}catch{}let a=null;const c=new Promise(h=>{a=g=>{g===n&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:n,session_id:i,content:"ping",msg_id:n}),e.deliverStopEvent(n,i);let d=null;const l=await Promise.race([c.then(()=>!1),new Promise(h=>{d=setTimeout(()=>h(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,t,s=new Ai){this.config=e,this.auditController=new Ci(s,{onAuditState:n=>{try{this.aibotHandle.sendAuditState($(n,Date.now()))}catch{}}}),wi(s)&&s.addJobSettledHandler((n,o)=>{this.auditController.handleJobSettled(n,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ci[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...se]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new et(e.logDir):null,this.packetLog=e.logDir?new tt(e.logDir):null,this.bindingStore=new Xn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new vi(this.name),this.activeEventStore=e.activeEventStorePath?new ii(e.activeEventStorePath):null,this.pendingEvents=new si(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new P(Le,Ge);else if(i==="claude")this.sessionScanCache=new P($e,je);else if(i==="pi"){const n=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new P(()=>Fe(void 0,n),()=>ze(void 0,n))}else if(i==="codewhale")this.sessionScanCache=new P(qe,Je);else if(i==="cursor")this.sessionScanCache=new P(Ue,Ye);else if(i==="opencode")this.sessionScanCache=new P(Ne,Xe);else if(i==="deepseek-harness"){const n=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new P(()=>We(n),()=>Ve(n))}else if(i==="agy")this.sessionScanCache=new P(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new P(Be,Ze));const n=Qe(e.aibot.clientType);this.sessionScanCache=n?new P(()=>Oe(void 0,n),()=>Ke(void 0,n)):new P(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await He({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,n])=>String(n.cwd??""))}).then(n=>{n.length>0&&p.info(this.name,`restored native provider config after relay disable: ${n.join(", ")}`)}).catch(n=>{p.warn(this.name,`native provider residue sweep failed: ${n instanceof Error?n.message:String(n)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await ke().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",s=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||s)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new qn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},n=>{const o=this.createAdapter(i,n);return o instanceof y&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(n,r),this.sessionScanCache.invalidate()}),o},(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((n,o,r,a)=>{if(p.info(this.name,`[queue-debug] send event_state session=${o} event=${n} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:n,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(n),this.pendingEvents.remove(n).catch(c=>{p.warn(this.name,`Failed to remove running event from pending store event=${n}: ${c instanceof Error?c.message:String(c)}`)})),r==="canceled"||r==="failed"){const c=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:n,status:c,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(n,c,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(n),this.pendingEvents.remove(n).catch(d=>{p.warn(this.name,`Failed to remove queued terminal event from pending store event=${n}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:o,...o?{ttl_ms:ri,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(n=>{this.handleSessionInternalError(n).catch(o=>{p.error(this.name,`[recovery] handleSessionInternalError failed event=${n.eventId} session=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((n,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((n,o)=>{this.markAuditAdapterClosed(n,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const c=this.buildAgyToolbarMeta(o),d=c?.available_models??[];p.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(c?.model_id??"")} available_models=${d.length} meta_keys=${c?Object.keys(c).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,c),this.refreshAndPushAgyQuota(o)}else p.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((n,o,r)=>{const a=this.selfDrivenSessions.has(n),c=this.selfDrivenLabels.get(n);o?(this.selfDrivenSessions.add(n),r&&this.selfDrivenLabels.set(n,r),this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(n),this.selfDrivenLabels.delete(n),a&&this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==c)&&this.pushQueueSnapshotForSession(n)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),p.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)p.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=t.get(r),c=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,c?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const s=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],n=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...s.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){p.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(n)}catch(r){p.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of n){const a=r.event;p.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){p.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=xe(this.config.agent.clientType,e),s=this.config.agent.env;let i=Object.keys(t).length>0?{...t,...s}:s;if(De(t)){const n=ye()?.getRuntimeInfo(),o={...s??{},...t},r=Me(o,{proxyUrl:n?.proxyUrl,caCertPath:n?.caCertPath,caBundlePath:n?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(Te(this.config.agent.clientType)){const n=Pe(this.name);n&&(i={...i??{},...n})}return Re(i,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Di),sendThinking:(n,o,r)=>this.sendThinkingByRuntimeConfig(n,o,r),sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,void 0,a)},sendRawEventEnvelope:(n,o,r,a)=>{const c=gi(r);if(c){this.sendToolExecutionCard(n,o,c);return}this.deliverRawEventEnvelope(n,o,r,"deepseek",a)},sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"deepseek")},sendUpdateBindingCard:(n,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:n=>this.maybeQueryProviderQuota(n===!0,{providerId:"deepseek"}),agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),eventToolInvoke:async(n,o)=>this.invokeDshEventTool(n,o)},s=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new le({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:T.join(L.data,"deepseek-harness",s),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const s=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(t.model=i);const n=this.resolveCursorSessionModeId(e),o=n??"full_auto";n||this.bindingStore.setCursorModeId(e,o),t.mode=o,s?.cwd&&(t.workspace=s.cwd);const r={sendStreamChunk:(a,c,d,l,h,g,u)=>{this.sendStreamChunkByRuntimeConfig(a,c,d,l,h,g,u)},sendEventResult:(a,c,d)=>{this.sendEventResultWithCleanup(a,c,d)},sendEventAck:(a,c)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:c,received_at:Date.now()})},sendRawEventEnvelope:(a,c,d)=>{this.deliverRawEventEnvelope(a,c,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,c,d)=>{const l=d.questions.map(g=>g.header).join(", "),h=X(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:c,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,c,d)=>this.platformInvoke(a,c,d),sendLocalActionResult:(a,c,d,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:c,...d!==void 0?{result:d}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,c,d,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:c,cwd:d,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new ae({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},r)}createClaudeAdapter(e){const t={sendReply:(n,o,r,a,c)=>{this.sendReplyByRuntimeConfig(n,o,r,a,c)},sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendMedia:(n,o,r,a,c,d,l)=>{this.aibotHandle.sendMedia({event_id:n,session_id:o,content:r,msg_type:2,quoted_message_id:c||void 0,client_msg_id:d||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,a)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,D(r,a))},sendToolResult:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,M(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(n,o,r)=>{this.sendGrixAgentQuestionCard(n,o,r)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"claude")},sendDirectMessage:n=>{this.aibotHandle.sendMsg({session_id:n.sessionId,msg_type:1,content:n.content,...n.clientMsgId?{client_msg_id:n.clientMsgId}:{},...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})},onStatusLineUpdated:n=>{(n.rateLimits?.fiveHour||n.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=n);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:n=>{this.aibotHandle.sendMcpFrame(e,n)}},s=this.config.adapterOptions??{},i={...s,sessionRuntimeResolver:()=>{const n=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:n?.cwd,modeId:this.resolveClaudeSessionModeId(e)??be.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:n?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t)}createCodexAdapter(e){let t=null;const s={sendEventResult:(r,a,c)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,c);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,c),d=>{const l=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:c)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,c)=>{this.sendThinkingByRuntimeConfig(r,a,c)},sendRunError:(r,a,c)=>{this.sendRunErrorAsChunk(r,a,c)},sendUpdateBindingCard:(r,a,c,d)=>{const l={...d??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:c,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,c)=>this.platformInvoke(r,a,c),sendLocalActionResult:(r,a,c,d,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...c!==void 0?{result:c}:{},...d?{error_code:d}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,c,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:c,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const c=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:c},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:r,...t?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},n=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return t=new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(n?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(n?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...K(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:T.join(L.data,"audit-replay","raw-spool")}}:{}}},s),t}createCodeWhaleAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,n,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new de({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??s.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[pi] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c),a&&p.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
2
2
 
3
- Error: ${o}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Oe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},n)}createOpenHumanAdapter(e){const n={sendStreamChunk:(i,s,o,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(i,s,o,r,a,d)},sendFinalStreamChunkReliable:async(i,s,o,r)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(i,s,r)}catch(a){throw u.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${i}: ${a}`),a}},sendEventResult:(i,s,o)=>{this.sendEventResultWithCleanup(i,s,o),u.info("bridge",`[openhuman] sendEventResult event=${i} status=${s}`)},sendEventAck:(i,s)=>this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()}),sendToolUse:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,M(o,r))},sendToolResult:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,x(o,r))},sendThinking:(i,s,o)=>{this.sendThinkingByRuntimeConfig(i,s,o)},sendRunError:(i,s,o)=>{this.sendStreamChunkByRuntimeConfig(i,s,`
3
+ Error: ${o}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},s=this.config.adapterOptions??{};return new oe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:async(i,n,o,r)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(i,n,r)}catch(a){throw p.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${i}: ${a}`),a}},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[openhuman] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
4
4
 
5
- Error: ${o}`,0,!1)},sendUpdateBindingCard:(i,s,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,s,o)=>this.platformInvoke(i,s,o),sendLocalActionResult:(i,s,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},t=this.config.adapterOptions??{};return new qe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},n,{port:t.port,host:t.host,workspaceDir:t.workspace_dir,sessionToken:t.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const n={sendStreamChunk:(i,s,o,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(i,s,o,r,a,d)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(i,s,o)=>{this.sendEventResultWithCleanup(i,s,o),u.info("bridge",`[opencode] sendEventResult event=${i} status=${s}`)},sendEventAck:(i,s)=>this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()}),sendToolUse:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,M(o,r))},sendToolResult:(i,s,o,r)=>{this.sendToolExecutionCard(i,s,x(o,r))},sendThinking:(i,s,o)=>{this.sendThinkingByRuntimeConfig(i,s,o)},sendRunError:(i,s,o)=>{this.sendRunErrorAsChunk(i,s,o)},sendUpdateBindingCard:(i,s,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:s,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,s,o)=>this.platformInvoke(i,s,o),sendLocalActionResult:(i,s,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"opencode")},sendAgentQuestionCard:(i,s,o)=>{this.sendGrixAgentQuestionCard(i,s,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},t=this.config.adapterOptions??{};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},n,{port:t.port,hostname:t.hostname,model:t.model??this.resolveSessionModelId(e),agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const n={sendStreamChunk:(i,s,o,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(i,s,o,r,a,d)},sendEventResult:(i,s,o)=>{this.sendEventResultWithCleanup(i,s,o)},sendEventAck:(i,s)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()})},agentInvoke:async(i,s,o)=>this.platformInvoke(i,s,o),forceCompleteInternalEvent:(i,s)=>{this.pool.eventComplete(i,s),this.pushQueueSnapshotForSession(s)},persistConversationId:(i,s)=>{this.bindingStore.setAgyConversationId(i,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},t=i=>{const s=this.bindingStore.get(i);return{cwd:s?.cwd,modelId:this.resolveSessionModelId(i),conversationId:s?.agyConversationId}};return new he({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},n,t)}createAcpAdapter(e){const n=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(c,l,h,g,m,p,_)=>{this.sendStreamChunkByRuntimeConfig(c,l,h,g,m,p,_)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(c,l,h)=>{this.sendEventResultWithCleanup(c,l,h)},sendEventAck:(c,l)=>{this.aibotHandle.sendEventAck({event_id:c,session_id:l,received_at:Date.now()})},agentInvoke:async(c,l,h)=>this.platformInvoke(c,l,h),sendLocalActionResult:(c,l,h,g,m)=>{this.aibotHandle.sendLocalActionResult({action_id:c,status:l,...h!==void 0?{result:h}:{},...g?{error_code:g}:{},...m?{error_msg:m}:{}},e)},sendRawEventEnvelope:(c,l,h)=>{this.sendAcpRawEventEnvelope(c,l,h)},sendToolUse:(c,l,h,g)=>{if(n){this.sendAcpRawEventEnvelope(c,l,{type:"tool_use",payload:{tool_name:h,tool_input:g??""}});return}this.sendToolExecutionCard(c,l,M(h,g))},sendToolResult:(c,l,h,g)=>{this.sendToolExecutionCard(c,l,x(h,g))},sendThinking:(c,l,h)=>{this.sendThinkingByRuntimeConfig(c,l,h)},sendRunError:(c,l,h)=>{this.sendStreamChunkByRuntimeConfig(c,l,`
5
+ Error: ${o}`,0,!1)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new re({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,host:s.host,workspaceDir:s.workspace_dir,sessionToken:s.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[opencode] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendRunErrorAsChunk(i,n,o)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"opencode")},sendAgentQuestionCard:(i,n,o)=>{this.sendGrixAgentQuestionCard(i,n,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new F({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,hostname:s.hostname,model:s.model??this.resolveSessionModelId(e),agent:s.agent,permissionPolicy:s.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),forceCompleteInternalEvent:(i,n)=>{this.pool.eventComplete(i,n),this.pushQueueSnapshotForSession(n)},persistConversationId:(i,n)=>{this.bindingStore.setAgyConversationId(i,n)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=i=>{const n=this.bindingStore.get(i);return{cwd:n?.cwd,modelId:this.resolveSessionModelId(i),conversationId:n?.agyConversationId}};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,s)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),s={sendStreamChunk:(d,l,h,g,u,f,b)=>{this.sendStreamChunkByRuntimeConfig(d,l,h,g,u,f,b)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,l,h)=>{this.sendEventResultWithCleanup(d,l,h)},sendEventAck:(d,l)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:l,received_at:Date.now()})},agentInvoke:async(d,l,h)=>this.platformInvoke(d,l,h),sendLocalActionResult:(d,l,h,g,u)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:l,...h!==void 0?{result:h}:{},...g?{error_code:g}:{},...u?{error_msg:u}:{}},e)},sendRawEventEnvelope:(d,l,h)=>{this.sendAcpRawEventEnvelope(d,l,h)},sendToolUse:(d,l,h,g)=>{if(t){this.sendAcpRawEventEnvelope(d,l,{type:"tool_use",payload:{tool_name:h,tool_input:g??""}});return}this.sendToolExecutionCard(d,l,D(h,g))},sendToolResult:(d,l,h,g)=>{this.sendToolExecutionCard(d,l,M(h,g))},sendThinking:(d,l,h)=>{this.sendThinkingByRuntimeConfig(d,l,h)},sendRunError:(d,l,h)=>{this.sendStreamChunkByRuntimeConfig(d,l,`
6
6
 
7
- Error: ${h}`,1,!1)},sendAgentQuestionCard:(c,l,h)=>{this.sendGrixAgentQuestionCard(c,l,h)},sendPermissionCard:c=>{u.info("bridge","sendPermissionCard callback entered",{rawTransport:n,eventId:c.eventId,sessionId:c.sessionId,toolCallId:c.toolCallId,toolName:c.toolName,toolTitle:c.toolTitle});const l=c.toolInput&&c.toolTitle&&c.toolInput!==c.toolTitle?`${c.toolTitle}: ${c.toolInput}`:c.toolTitle||c.toolInput||c.toolName;if(n){this.sendAcpRawEventEnvelope(c.eventId,c.sessionId,{type:"permission_request",payload:{tool_call_id:c.toolCallId,tool_name:c.toolName,tool_title:c.toolTitle,...c.toolInput?{tool_input:c.toolInput}:{},options:c.options}}),u.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:c.eventId,toolCallId:c.toolCallId});return}const h=`perm_${F()}`,g={event_id:c.eventId,session_id:c.sessionId,client_msg_id:h,msg_type:1,content:c.toolTitle?`Permission required: ${c.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:c.toolCallId,approvalSlug:c.toolName},grix:{execApproval:{approval_command_id:c.toolCallId,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};u.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:c.eventId,sessionId:c.sessionId,clientMsgId:h,toolCallId:c.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),u.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:c.eventId,clientMsgId:h})}catch(m){u.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:c.eventId,clientMsgId:h,error:m instanceof Error?m.message:String(m)})}},sendAuthNotification:(c,l)=>{c&&this.aibotHandle.sendMsg({session_id:c,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(c,l)=>{c&&l&&this.aibotHandle.sendMsg({session_id:c,msg_type:1,content:l})},sendUpdateBindingCard:(c,l,h,g)=>{const m={...g??{}};if(!m.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const p=this.providerQuotaToRateLimits(this.cachedProviderQuota);p&&(m.rate_limits=p)}!m.provider_quota&&this.cachedProviderQuota?.success&&(m.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:c,worker_status:l,cwd:h,...Object.keys(m).length>0?{meta:m}:{}})},onSkillsUpdate:(c,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:_e(c,I.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},onContextWindowUpdated:c=>{this.cachedAcpContextWindow=c,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in c?c.usedPercentage.toFixed(1):(c.used/c.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const g="usedPercentage"in c?c.usedPercentage:Math.min(100,c.used/c.size*100),m={context_window:{..."usedPercentage"in c?{}:c,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(()=>{}),m.provider_quota=this.cachedProviderQuota;const p=this.providerQuotaToRateLimits(this.cachedProviderQuota);p&&(m.rate_limits=p)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:m})}},sendMcpFrame:c=>{this.aibotHandle.sendMcpFrame(e,c)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,s=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&s?on(this.name,e,s.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:d}=vi({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&d&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,d),(a||d)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${d??"<none>"}`),new R({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:d,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:n,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 ni(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const n=await new Be().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw n.disconnect(),new Error("connection aborted");this.aibotHandle=n;const t=this.aibotHandle.authAck;if(this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"auth_ack",respawnOnChange:!1},t?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(s=>{u.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof R&&a.adapter.getSessionBindings().delete(i.session_id);const d=this.config.adapterType??"acp",c=this.resolveBindingChannelKey(d);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:f.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(s){u.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(i=>{u.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){u.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(s){u.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(s){u.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{u.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(s){u.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(s=>{u.error(this.name,`handleAibotRevoke failed: ${s}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(s=>{u.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(i=>{u.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(s=>{u.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((i,s)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(s):u.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const s=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const s=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const s=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(u.info(this.name,`recv event_hold event_id=${o} session_id=${s} hold=${r} reason=${i.reason??""}`),!s||!o){this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",d=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,c=this.pool.holdEvent(s,o,r,a,d),l=c==="ok";this.aibotHandle.sendEventHoldResult({session_id:s,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:c}}),l&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const s=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(u.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 r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(s,o,r),d=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:s,event_id:o,ok:d,...d?{}:{error:a}}),d&&this.pushQueueSnapshotForSession(s)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){u.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const s of i)u.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 i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,s)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,n,t,i){const s=String(e??"").trim(),o=String(n??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=s!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:s,introduction:o},this.agentSystemPrompt=r,s||o?u.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const n=this.pool.getAllSlots();let t=0;for(const r of n)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),t++}catch(a){u.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=n.filter(r=>r.adapter instanceof B),s=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-s.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${s.length} idle Claude slot(s), skipping ${o} busy`);for(const r of s)this.pool.removeSlot(r.sessionId).catch(a=>{u.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 n=this.pool?.getQueueSnapshot(e)??null,t=n?[...n.running]:[],i=n?n.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=n?n.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(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:t,running_items:i,queued:s}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const n=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${n.running.length} queued=${n.queued.length} running_ids=[${n.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(n)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,n,t){return e==="file_link"?Ci(n):e==="file_upload"?this.uploadFileAndSendMedia(n):this.aibotHandle.agentInvoke(e,n,t)}invokeDshEventTool(e,n){const t=ht(this.aibotHandle,e,n),i=t.content[0]?.text??"";if(t.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const n=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),s=String(e.reply_to_message_id??"").trim();if(!n)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const o=await Ei({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:n}),r=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${F()}`,...s?{quoted_message_id:s}:{},extra:o.extra});if(r.cmd!=="send_ack"){const d=r.payload??{},c=String(d.msg??r.cmd);throw new Error(`media message send failed: ${c}`)}const a=r.payload??{};return{ok:!0,file_name:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,n,t,i,s){const o=this.indexEventSession(e,n)??n;this.auditController.captureReply(e,t),this.sendCtrl.sendReply(e,o,t,i,s),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const n=e;if(n.codex_method!=="item/agentMessage/delta")return e;const i=n.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const s=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return s?{...e,quoted_message_id:s}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const n=e.codex_payload?.params,t=typeof n?.phase=="string"?n.phase.trim().toLowerCase():"";if(t&&t!=="final_answer")return;const i=n?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,n){return async(t,i,s)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(t,i,s,n)}catch(o){throw u.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${t}: ${o}`),o}u.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${t}`)}}sendStreamChunkByRuntimeConfig(e,n,t,i,s,o,r){const a=this.indexEventSession(e,n)??n;this.auditController.captureStreamChunk(e,i,t),this.sendCtrl.sendStreamChunk(e,a,t,i,s,o,r),(t||s)&&this.conversationLog?.logOutbound?.(a,e,s?"stream_chunk_finish":"stream_chunk",t)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,n,t){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,n,`
7
+ Error: ${h}`,1,!1)},sendAgentQuestionCard:(d,l,h)=>{this.sendGrixAgentQuestionCard(d,l,h)},sendPermissionCard:d=>{p.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const l=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(t){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),p.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const h=`perm_${B()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:h,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};p.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:h,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),p.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:h})}catch(u){p.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:h,error:u instanceof Error?u.message:String(u)})}},sendAuthNotification:(d,l)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(d,l)=>{d&&l&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l})},sendUpdateBindingCard:(d,l,h,g)=>{const u={...g??{}};if(!u.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}!u.provider_quota&&this.cachedProviderQuota?.success&&(u.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:h,...Object.keys(u).length>0?{meta:u}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Ae(d,L.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);p.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),u={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),u.provider_quota=this.cachedProviderQuota;const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:u})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,n=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&n?Mi(this.name,e,n.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Yn({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&c&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,c),(a||c)&&p.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},s,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new nt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const t=await new ie().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const s=this.aibotHandle.authAck;if(this.applyAgentProfile(s?.agent_name,s?.introduction,{source:"auth_ack",respawnOnChange:!1},s?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(n=>{p.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof y&&a.adapter.getSessionBindings().delete(i.session_id);const c=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(c);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(n){p.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(i=>{p.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){p.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(n){p.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(n){p.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{p.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(n){p.error(this.name,`onSkillSync failed: ${n}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(n=>{p.error(this.name,`handleAibotRevoke failed: ${n}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(n=>{p.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(i=>{p.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(n=>{p.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((i,n)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(n):p.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const n=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const n=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,n);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(p.info(this.name,`recv event_hold event_id=${o} session_id=${n} hold=${r} reason=${i.reason??""}`),!n||!o){this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",c=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,d=this.pool.holdEvent(n,o,r,a,c),l=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:d}}),l&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(p.info(this.name,`recv queue_edit event_id=${o} session_id=${n}`),!n||!o){this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:!1,error:"bad_request"});return}const r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(n,o,r),c=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:c,...c?{}:{error:a}}),c&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),p.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){p.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const n of i)p.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,n)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,t,s,i){const n=String(e??"").trim(),o=String(t??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=n!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:n,introduction:o},this.agentSystemPrompt=r,n||o?p.info(this.name,`agent profile (${s.source}): GOT name="${n}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):p.warn(this.name,`agent profile (${s.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&s.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let s=0;for(const r of t)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),s++}catch(a){p.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=t.filter(r=>r.adapter instanceof N),n=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-n.length;p.info(this.name,`${e}: notified ${s} adapter(s) via hook; respawning ${n.length} idle Claude slot(s), skipping ${o} busy`);for(const r of n)this.pool.removeSlot(r.sessionId).catch(a=>{p.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,s=t?[...t.running]:[],i=t?t.running_items.map(o=>({event_id:o.event_id,...o.content_preview?{content_preview:o.content_preview}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},actions:[{type:"stop"}]})):[],n=t?t.queued.map(o=>({event_id:o.event_id,position:o.position,...o.content_preview?{content_preview:o.content_preview}:{},...typeof o.content=="string"?{content:o.content}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},held:o.held===!0,held_reason:o.held_reason??"",actions:[{type:"cancel"}]})):[];if(s.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";s.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:s,running_items:i,queued:n}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);p.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,s){return e==="file_link"?ei(t):e==="file_upload"?this.uploadFileAndSendMedia(t):this.aibotHandle.agentInvoke(e,t,s)}invokeDshEventTool(e,t){const s=Ee(this.aibotHandle,e,t),i=s.content[0]?.text??"";if(s.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),s=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),n=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!s)throw new Error("session_id is required");const o=await ni({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:s,filePath:t}),r=await this.aibotHandle.sendMedia({session_id:s,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${B()}`,...n?{quoted_message_id:n}:{},extra:o.extra});if(r.cmd!=="send_ack"){const c=r.payload??{},d=String(c.msg??r.cmd);throw new Error(`media message send failed: ${d}`)}const a=r.payload??{};return{ok:!0,file_name:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,s,i,n){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,s),this.sendCtrl.sendReply(e,o,s,i,n),s&&this.conversationLog?.logOutbound?.(o,e,"reply",s)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const i=t.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const n=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return n?{...e,quoted_message_id:n}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,s=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(s&&s!=="final_answer")return;const i=t?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(s,i,n)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(s,i,n,t)}catch(o){throw p.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${s}: ${o}`),o}p.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${s}`)}}sendStreamChunkByRuntimeConfig(e,t,s,i,n,o,r){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,i,s),this.sendCtrl.sendStreamChunk(e,a,s,i,n,o,r),(s||n)&&this.conversationLog?.logOutbound?.(a,e,n?"stream_chunk_finish":"stream_chunk",s)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,t,s){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,t,`
8
8
 
9
- Error: ${t}`,1,!1))}sendEventResultWithCleanup(e,n,t,i,s=!1){const o=this.eventSessionIndex.get(e);s&&this.surfacedRunErrorEvents.add(e),n==="failed"&&o&&t?.trim()&&this.sendRunErrorAsChunk(e,o,t),this.auditController.markResponded(e,n,t),this.sendCtrl.sendEventResult(e,n,t,i),o&&(this.pool.eventComplete(e,o)===!1&&u.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${n}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,n,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{u.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),n==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:n,sessionId:t,errorMsg:i}=e;if(this.stopped)return;const s=this.inflightEvents.get(n);if(!s){u.warn(this.name,`[recovery] no inflight event for internalError event=${n} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(n,t,i),this.sendEventResultWithCleanup(n,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(n)??0)+1;this.restartCount.set(n,o);const r=this.config.adapterType??"acp";if(o>de){u.error(this.name,`[recovery] adapter=${r} session=${t} event=${n} restart=${o}/${de} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(n,t,i),this.sendEventResultWithCleanup(n,"failed",i,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${r} session=${t} event=${n} restart=${o}/${de} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=e.replayOriginalContent?s.content:this.resolveRecoveryPrompt(r,s),c={...s,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${n} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(n,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,n){return e==="acp"?"continue":n.content}sendThinkingByRuntimeConfig(e,n,t){this.sendCtrl.sendThinking(e,n,t)}bufferStreamChunk(e,n,t,i,s){this.auditController.captureUnsequencedStreamChunk(e,t),this.sendCtrl.bufferOnly(e,n,t,i,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 n=new Set(e.map(i=>i.event.event_id).filter(Boolean)),t=[];u.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const s=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||t.push(i)):(this.restorePendingReplayAuditTurn(s),this.deferredMgr.defer(i.channel,i.sessionId,s),t.push(i))}else await this.deliverPendingReplayEvent(s),this.pendingStartedEventIds.has(s.event_id)||t.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);u.error(this.name,`Pending event replay failed event=${s.event_id}: ${r}`),this.sendEventResultWithCleanup(s.event_id,"failed",r),this.pendingEvents.markCanceled(s.event_id),await this.pendingEvents.remove(s.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(n,[...t,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(n,t))}failEventIfLifecycleDraining(e,n="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:n,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,n){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",n),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,n){this.sessionBindings.set(e.sessionId,n),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,n):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,n)}restorePendingReplayAuditTurn(e){const n=e.audit;if(!n?.enabled||!n.auditId||!n.capture||!n.profile||!n.scope)return;const t=Yi({enabled:!0,scope:n.scope,profile:n.profile,capture:n.capture,...n.retentionDays===void 0?{}:{retentionDays:n.retentionDays}});if(!t.enabled)return;const i=Object.freeze({auditId:n.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:t,createdAt:new Date().toISOString()}),s=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});s&&(e.audit={...n,auditId:s.auditId,turnId:s.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,n){if(!e||!n)return;const t=this.eventSessionIndex.get(e);return t?(t!==n&&u.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${t} supplied=${n}`),t):(this.eventSessionIndex.set(e,n),n)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,n){return this.sendCtrl.shouldDropCodexDisplayEvent(e,n)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,n){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,n)}sendAcpRawEventEnvelope(e,n,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.deliverRawEventEnvelope(e,n,t,"acp",this.buildAcpRawEventFallbackText(t))}buildAcpRawEventFallbackText(e){const n=String(e.type??"").trim();if(!n)return"[acp] event";switch(n){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] ${n}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,n,t,i,s){const o=Oi({envelope:t,fallbackText:s,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:n,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}u.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,n,qi({envelopeType:t.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{u.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const n=String(e?.type??"").trim(),t=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(n){case"permission_request":return`Permission required: ${String(t.tool_title??t.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(t.tool_name??t.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(t.message??"agent error")}`;default:return n?`[cursor] ${n}`:"[cursor] event"}}sendToolExecutionCard(e,n,t,i){this.sendCtrl.sendToolExecutionCard(e,n,t,i)}sendGrixApprovalCard(e,n){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${F()}`,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:n}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,n,t){const i=t.questions.map(o=>o.header).join(", "),s=Ie(`[Agent Question] ${t.request_id}`,"agent_question",t);this.aibotHandle.sendText({event_id:e,session_id:n,content:s,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const n=Ae(String(e.content??""));if(!n)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,s=i instanceof R?"acp":i instanceof W?"opencode":this.config.adapterType??"unknown",o=i instanceof W?i.handleQuestionReplyEvent(n):i instanceof R?await i.handleQuestionReplyEvent(n):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(u.info(this.name,`[${s}] question reply delivered event=${e.event_id} session=${e.session_id} request=${n.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(u.warn(this.name,`[${s}] question reply rejected event=${e.event_id} session=${e.session_id} request=${n.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 n=ci(String(e.content??""));if(!n)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,s=n.params,o=String(s.tool_call_id??s.approval_command_id??s.approval_id??s.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.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 r.delivered?(u.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()})):(u.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const n=this.config.adapterType??"acp",t=ri(e);let i;if(t&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(n==="opencode"||n==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const s=Ti(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,r=Te(e.extra);if((r.state!=="absent"||r.error)&&u.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,g=h.extra,m=h.audit??(g&&typeof g=="object"?g.audit:void 0);return!m||typeof m!="object"?!1:m.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState(G({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&n!=="claude"&&n!=="codex"&&n!=="cursor"&&n!=="opencode"&&n!=="pi"&&n!=="codewhale"&&n!=="deepseek-harness"&&n!=="agy"&&n!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${n}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState(G({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${n}`},Date.now()))}catch{}return}if(t){if(r.state!=="absent"||t.verb===v.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(t.verb===v.exec){await this.handleSessionControlCommand(t,e);return}if(t.verb===v.listSessions){await this.handleListSessionsTextCommand(e);return}if(t.verb===v.unbind){await this.handleUnbindTextCommand(e);return}if(n==="claude"){await this.handleSessionControlCommand(t,e);return}if(n==="codex"&&t.verb===v.open){await this.handleCodexSessionControlOpen(t,e);return}if(n==="pi"&&t.verb===v.open){await this.handlePiSessionControlOpen(t,e);return}if(n==="pi"&&t.verb===v.restart){await this.handlePiSessionControlRestart(e);return}if((n==="openhuman"||n==="opencode")&&t.verb===v.open){await this.handleOpenHumanSessionControlOpen(t,e);return}if(n==="codewhale"&&t.verb===v.open){await this.handleCodeWhaleSessionControlOpen(t,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),t.verb===v.open){const l=t.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:f.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=$.resolve(l);if(!(await z(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:f.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const g=String(h?.code??""),m=g==="ENOENT"?`Directory does not exist: ${$.resolve(l)}`:g==="EACCES"||g==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:f.invalidCwd,msg:m,updated_at:Date.now()});return}}if(t.verb===v.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await z(l.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const h=this.pool.getSlot(e.session_id);h?.adapter instanceof R&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(t,e),n==="acp"&&t.verb===v.stop){const h=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${h}`,updated_at:Date.now()});return}if(Ce(t,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),t.verb===v.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),n==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(Me.has(n)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,n),Me.has(n)&&!this.bindingStore.get(e.session_id)?.cwd){const h=n,g=this.prepareAuditedInboundEvent(e,o,a);u.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const p=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:g});if(this.lifecycleBarrier.isClosed()&&!p)throw new Error("pending event store unavailable during lifecycle drain")}catch(p){const _=p instanceof Error?p.message:String(p);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",_,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(g,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),g);const m=this.resolveBindingChannelKey(n);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[m]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:f.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,g,m]=h,_=this.pool.getSlot(e.session_id)?.adapter;if(_?.execCommand&&(_.getSupportedCommands?.()??[]).some(S=>S.name===g||S.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const S=await _.execCommand(g,m.trim(),e.session_id);S.status==="options"&&S.data&&this.handleExecCommandOptions(e.session_id,g,S.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:S.status==="failed"?"failed":"responded",msg:S.message,updated_at:Date.now()})}catch(S){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:S instanceof Error?S.message:String(S),updated_at:Date.now()})}return}}}if(n==="codex"&&me(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof le&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(u.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)):u.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const c=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:c});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(c,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),u.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(c),await this.pool.deliverInboundEvent(c)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{u.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,n){const t=n instanceof Error?n.message:String(n);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",t,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:t,updated_at:Date.now()})}async handleCodexSessionControlOpen(e,n){const t=n.session_id,i=e.args.trim(),s=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!i){s(),o("failed",{msg:"Usage: /grix open <working-directory>",code:f.cwdRequired});return}try{const r=await this.resolveCwdForBinding(i),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){s(),this.sessionBindings.set(t,c),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,c),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),o("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:f.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s(),o("responded",{msg:`Session bound to ${r}`})}catch(r){s(),this.failSessionOpen(r,{sessionId:t,eventId:n.event_id,quotedMessageId:n.msg_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",{code:a,msg:d})})}}async handleSessionControlForPool(e,n){e.verb===v.open&&await this.bindSessionForPool(n.session_id,e.args.trim())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==E.sessionControl)return;const n=e.params??{};if(String(n.verb??"").trim().toLowerCase()!==v.open)return;const i=String(n.session_id??"").trim(),s=String(n.cwd??"").trim();!i||!s||await this.bindSessionForPool(i,s)}async handleCodexSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),i=String(n.cwd??"").trim(),s=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!i){o("failed",void 0,f.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(i);this.ensureImportedAgentSession(s,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,c),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,c),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){o("failed",void 0,f.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){this.failSessionOpen(r,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",void 0,a,d)})}}async handleCursorSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),i=String(n.cwd??"").trim(),s=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!i){o("failed",void 0,f.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(i);this.ensureImportedAgentSession(s,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,c),await this.bindSessionForPool(t,c),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:c,meta:this.buildCursorToolbarMeta(t)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){o("failed",void 0,f.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r,meta:this.buildCursorToolbarMeta(t)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){this.failSessionOpen(r,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",void 0,a,d)})}}async handlePiSessionControlOpen(e,n){const t=n.session_id,i=e.args.trim(),s=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!i){s(),o("failed",{msg:"Usage: /grix open <working-directory>",code:f.cwdRequired});return}try{const r=await this.resolveCwdForBinding(i),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.sessionBindings.set(t,c),await this.ensureSlotStarted(t),s(),o("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:n.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:n.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:f.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t).catch(d=>{if(ne(d))throw d;u.warn("bridge",`pi ensureSlotStarted on bind failed (non-fatal): ${d instanceof Error?d.message:String(d)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s(),o("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:n.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:n.msg_id})}catch(r){s(),this.failSessionOpen(r,{sessionId:t,eventId:n.event_id,quotedMessageId:n.msg_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",{code:a,msg:d})})}}async handlePiSessionControlRestart(e){const n=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:n,received_at:Date.now()}),i=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),o=this.bindingStore.get(n)?.cwd??"";if(!o){t(),i("failed",{msg:"session binding was not found",code:f.bindingMissing});return}t(),await this.pool.removeSlot(n).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"ready",cwd:o}),i("responded",{msg:`Session worker restarted for ${o}`})}async handlePiSessionControlRestartLocalAction(e){const n=e.params??{},t=String(n.session_id??"").trim(),s=(t?this.bindingStore.get(t):void 0)?.cwd??"",o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){o("failed",void 0,"session_id_required","session_id is required for restart");return}if(!s){o("failed",void 0,f.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:s}),o("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:s,workerStatus:"ready"}})}async syncOpenCodeBinding(e,n){if(!e||!n)return;try{this.resolveSessionModelId(e),this.resolveSessionModeId(e)}catch(i){u.warn(this.name,`[opencode] resolve global toolbar default failed: ${i instanceof Error?i.message:String(i)}`)}let t=this.pool.getSlot(e);t?.stopping&&(await this.pool.waitForSlotRemoval(e),t=this.pool.getSlot(e)),!t&&(this.config.adapterType??"acp")==="opencode"&&(await this.ensureSlotStarted(e),t=this.pool.getSlot(e)),t?.startPromise&&await t.startPromise,t?.adapter instanceof W&&await t.adapter.bindSession(e,n)}isWorkspaceFreeClient(){const e=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();return rn.has(e)}async ensureDefaultBindingForWorkspaceFreeClient(e,n){if(!e||!this.isWorkspaceFreeClient()||this.bindingStore.get(e)?.cwd)return;let t;try{t=await this.resolveCwdForBinding(U())}catch(i){u.warn(this.name,`[${n}] default cwd unavailable, falling back to binding prompt session=${e}: ${i instanceof Error?i.message:String(i)}`);return}this.bindingStore.set(e,t),this.sessionBindings.set(e,t),u.info(this.name,`[${n}] auto-bound workspace-free client session=${e} cwd=${t}`)}async bindSessionForPool(e,n){const t=String(n??"").trim();if(!e||!t)return;const i=await this.pool.getOrCreateSlot(e);if(!i||(i.startPromise&&await i.startPromise,!i.adapter))return;const s=i.adapter instanceof R?i.adapter:null;if(!s?.hasSessionBinding)return;const o=await this.resolveCwdForBinding(t);s.announceDeferredComposing(e),await s.bindSession(e,o),this.sessionBindings.set(e,o),this.sessionScanCache.invalidate(),s.replayDeferredEvents(e),this.forceRefreshSkills(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:async e=>{await this.pool.deliverInboundEvent(e)},sendEventResult:(e,n,t)=>{this.sendEventResultWithCleanup(e,n,t),this.pendingEvents.remove(e).catch(i=>{u.warn(this.name,`Failed to remove terminal deferred event from pending store event=${e}: ${i instanceof Error?i.message:String(i)}`)})},sendSessionComposing:(e,n,t)=>{const i={};n&&(i.ttl_ms=t?.ttlMs??3e4,t?.activity&&(i.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:n,...i})}}}async handleOpenHumanSessionControlOpen(e,n){const t=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});try{const i=await this.resolveCwdForBinding(e.args.trim());await this.handleSessionControlForPool(e,n),await this.syncOpenCodeBinding(n.session_id,i),Ce(e,n,this.sessionControlCtx(n.session_id),this.sessionControlSenders(n.session_id)),await this.deferredMgr.release(n.session_id,this.deferredCallbacks())}catch(i){t(),this.failSessionOpen(i,{sessionId:n.session_id,eventId:n.event_id,quotedMessageId:n.msg_id,cwd:this.bindingStore.get(n.session_id)?.cwd||e.args.trim(),send:(s,o)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",code:s,msg:o,updated_at:Date.now()})})}}async handleCodeWhaleSessionControlOpen(e,n){const t=n.session_id,i=e.args.trim(),s=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!i){s(),o("failed",{msg:"Usage: /grix open <working-directory>",code:f.cwdRequired});return}try{const r=await this.resolveCwdForBinding(i),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){s(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:f.rebindForbidden});return}s(),o("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s(),o("responded",{msg:`Session bound to ${r}`})}catch(r){s(),this.failSessionOpen(r,{sessionId:t,eventId:n.event_id,quotedMessageId:n.msg_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",{code:a,msg:d})})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),i=String(n.cwd??"").trim(),s=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!i){o("failed",void 0,f.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(i);this.ensureImportedAgentSession(s,r);const a=this.bindingStore.get(t);if(a?.cwd){const d=await this.resolveCwdForBinding(a.cwd);if(d!==r){o("failed",void 0,f.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,s),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){this.failSessionOpen(r,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",void 0,a,d)})}}async handleDeepSeekSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),i=String(n.cwd??"").trim(),s=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!i){o("failed",void 0,f.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(i);this.ensureImportedAgentSession(s,r);const a=this.bindingStore.get(t);if(a?.cwd){const d=await this.resolveCwdForBinding(a.cwd);if(d!==r){o("failed",void 0,f.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,d),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:d,meta:this.buildDshOpenedToolbarMeta(t)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,s),this.sessionBindings.set(t,r),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r,meta:this.buildDshOpenedToolbarMeta(t)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){this.failSessionOpen(r,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||i,send:(a,d)=>o("failed",void 0,a,d)})}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===y.approval?y.approval:y.fullAuto}handleExecCommandOptions(e,n,t){const i=Array.isArray(t?.options)?t.options:[];if(i.length===0)return;const o=this.bindingStore.get(e)?.cwd??"",r={};if(n==="model"){r.available_models=i.map(d=>({id:d.id,displayName:d.label}));const a=i.find(d=>d.current);a&&(r.model_id=a.id)}else if(n==="mode"){r.available_modes=i.map(d=>({id:d.id,displayName:d.label}));const a=i.find(d=>d.current);a&&(r.mode_id=a.id)}else r[`${n}_options`]=i;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:o,meta:r})}resolveSessionModelId(e){const n=this.bindingStore.getModelId(e);if(n)return n;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveSessionModeId(e){const n=this.bindingStore.getModeId(e);if(n)return n;const t=String(this.globalConfigStore?.get(this.name)?.modeId??"").trim();if(t)return this.bindingStore.setModeId(e,t),t}resolveCursorSessionModeId(e){const n=this.bindingStore.getCursorModeId(e);if(n)return n;const t=String(this.globalConfigStore?.get(this.name)?.cursorModeId??"").trim();if(t)return this.bindingStore.setCursorModeId(e,t),t}resolveClaudeSessionEffort(e){const n=this.bindingStore.getEffort(e);if(n)return n;if(this.bindingStore.get(e)?.claudeSessionId)return;const i=ie(this.globalConfigStore?.get(this.name)?.effort);if(i)return this.bindingStore.setEffort(e,i),i}resolveClaudeSessionModeId(e){const n=this.bindingStore.getModeId(e);if(n)return n;if(this.bindingStore.get(e)?.claudeSessionId)return;const i=String(this.globalConfigStore?.get(this.name)?.modeId??"").trim();if(!i)return;const s=this.normalizeClaudeModeId(i);return this.bindingStore.setModeId(e,s),s}currentClaudeModeId(e){return this.normalizeClaudeModeId(this.resolveClaudeSessionModeId(e))}resolveCodexSessionModelId(e){const n=this.bindingStore.getCodexModelId(e);if(n)return n;if(this.bindingStore.getCodexThreadId(e))return;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}resolveCodexNewSessionGlobalDefault(e,n,t){const i=String(n??"").trim();if(i&&!this.bindingStore.getCodexThreadId(e))return t(i),i}pinCodexGlobalDefault(e,n){const t=String(e??"").trim();if(t)return n(t),t}buildCursorToolbarMeta(e){const n=this.pool.getSlot(e);if(n?.adapter instanceof N)return n.adapter.getToolbarMeta(e);const t=this.bindingStore.getModelId(e)??"auto",i=this.resolveCursorSessionModeId(e)??"full_auto";return{model_id:t,mode_id:i,currentModelId:t,currentModeId:i,available_models:[],available_modes:Ue.map(s=>({...s}))}}buildAgyToolbarMeta(e,n){if(!this.bindingStore.get(e))return;const i=pe(this.config.agent.command),s=i.length>0?i[0].id:"";let o=fe(this.resolveSessionModelId(e)||"",i)||s;i.length>0&&!i.some(a=>a.id===o)&&(o=s);const r=n??J(this.config.agent.command);return{model_id:o,currentModelId:o,available_models:i.map(a=>({id:a.id,displayName:a.displayName})),...this.buildAgyQuotaMeta(r)}}buildAgyQuotaMeta(e){const n={rate_limits:null,extra_limits:null};return e.rateLimits&&(n.rate_limits={primary:e.rateLimits.primary,secondary:e.rateLimits.secondary,sampledAt:e.sampledAt??Date.now()},e.rateLimits.extras&&e.rateLimits.extras.length>0&&(n.extra_limits=e.rateLimits.extras)),{...n,...e.plan!==void 0&&{plan:e.plan},...e.quota_exhausted!==void 0&&{quota_exhausted:e.quota_exhausted},...e.quota_reset_at!==void 0&&{quota_reset_at:e.quota_reset_at},...e.available_credits!==void 0&&{available_credits:e.available_credits}}}sendAgyBindingCard(e,n,t){const i=t??this.buildAgyToolbarMeta(e);return this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,...i?{meta:i}:{}}),i}async refreshAndPushAgyQuota(e,n=!1){const t=await X(this.config.agent.command,n),i=this.bindingStore.get(e);return i?.cwd&&this.sendAgyBindingCard(e,i.cwd,this.buildAgyToolbarMeta(e,t)),t}async handleAgySetModel(e,n){const t=e.params??{},i=pe(this.config.agent.command),s=fe(String(t.model_id??t.modelId??""),i);if(!n){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const o=this.bindingStore.get(n);if(!o?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.bindingMissing,error_msg:"session binding was not found"});return}o.modelId!==s&&(this.bindingStore.setModelId(n,s),this.globalConfigStore?.set(this.name,{modelId:s}));const r=await X(this.config.agent.command,!0).catch(()=>J(this.config.agent.command));this.sendAgyBindingCard(n,o.cwd,this.buildAgyToolbarMeta(n,r)),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:o.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=ee(),i=t.length>0?t[0].id:"";let s=this.resolveSessionModelId(e)||i;t.length>0&&!t.some(g=>g.id===s)&&(s=i);const o=this.currentClaudeModeId(e);let r;try{const g=this.providerResolver?this.providerResolver():this.config.agent.provider;r=ie(g?.effort)}catch{}const a=this.resolveClaudeSessionEffort(e)??r??"auto",d={model_id:s,mode_id:o,currentModelId:s,currentModeId:o,available_efforts:[...Q],effort:a,reasoning_effort:a,available_models:t.map(g=>({id:g.id,displayName:g.displayName}))},c=this.pool.getSlot(e),l=c?.adapter instanceof B?c.adapter.getSessionState():null;(l?.rateLimits?.fiveHour||l?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=l);const h=l??this.getFreshClaudeRateLimitState();if(h){const g=h.rateLimits;g&&(g.fiveHour||g.sevenDay)&&(d.rate_limits={...g.fiveHour?{fiveHour:g.fiveHour}:{},...g.sevenDay?{sevenDay:g.sevenDay}:{},sampledAt:h.sampledAt||Date.now()})}if(l){const g=l.contextWindow;g.usedPercentage!=null&&(d.context_window={usedPercentage:g.usedPercentage,remainingPercentage:g.remainingPercentage})}if(!d.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const g=this.providerQuotaToRateLimits(this.cachedProviderQuota);g&&(d.rate_limits=g),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(g)}`)}return d.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(d.rate_limits)}`),d}providerQuotaToCodexRateLimits(e){return $e(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ye(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const n=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(n)||/^\\\\/.test(n))){const s=new Error(`Specified path is not valid on this host: ${n}`);throw s.cwdErrorCode=f.invalidCwd,s}const t=$.resolve(n);let i;try{i=await z(t)}catch(s){const o=String(s?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=f.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=f.invalidCwd,r}throw s}if(!i.isDirectory()){const s=new Error("Specified path is not a directory.");throw s.cwdErrorCode=f.invalidCwd,s}try{return await xe(t)}catch{return t}}failSessionOpen(e,n){const{code:t,msg:i}=_i(e);return this.maybeOfferCliInstall({sessionId:n.sessionId,eventId:n.eventId,quotedMessageId:n.quotedMessageId,cwd:n.cwd,err:e}),n.send?.(t,i),{code:t,msg:i}}maybeOfferCliInstall(e){if(!this.installAgentHandler||!ne(e.err))return;const n=mi(this.config.adapterType,this.config.agent.clientType||this.config.aibot.clientType);if(!n)return;const t=pi(n,this.config.agent.command),i=`${gi}${F()}`,s=String(e.cwd??"").trim()||this.bindingStore.get(e.sessionId)?.cwd;this.pendingCliInstalls.set(i,{sessionId:e.sessionId,agentType:n,cliName:t,cwd:s});const o=e.eventId||`cli-install:${e.sessionId}`,r=`\u6CA1\u627E\u5230\u672C\u673A\u7A0B\u5E8F \`${t}\`\uFF0C\u65E0\u6CD5\u542F\u52A8\u3002\u662F\u5426\u9700\u8981\u5B89\u88C5\uFF1F`;this.aibotHandle.sendMsg({event_id:o,session_id:e.sessionId,msg_type:1,content:r,...e.quotedMessageId?{quoted_message_id:e.quotedMessageId}:{}}),this.sendGrixAgentQuestionCard(o,e.sessionId,ui(i,t)),u.warn(this.name,`cli missing: offered install card session=${e.sessionId} agentType=${n} cli=${t}`)}async handleCliInstallQuestionReply(e){const n=Ae(String(e.content??""));if(!n)return!1;const t=this.pendingCliInstalls.get(n.request_id);if(!t)return!1;if(this.pendingCliInstalls.delete(n.request_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),!fi(n))return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:`\u5DF2\u53D6\u6D88\u5B89\u88C5 ${t.cliName}\u3002`,quoted_message_id:e.msg_id}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()}),!0;try{await this.runConfirmedCliInstall(t,{eventId:e.event_id,sessionId:e.session_id,quotedMessageId:e.msg_id})}catch(i){this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:`${t.cliName} \u5B89\u88C5\u5931\u8D25\uFF1A${i instanceof Error?i.message:String(i)}`,quoted_message_id:e.msg_id})}return this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()}),!0}async handleCliInstallInteractionReply(e){const n=e.params??{},t=String(n.request_id??"").trim();if(!t)return!1;const i=this.pendingCliInstalls.get(t);if(!i)return!1;this.pendingCliInstalls.delete(t);const s=n.resolution??n.response??{},o=String(n.action??n.kind??"").trim(),r=String(s.value??n.value??"").trim(),a=o==="accept"||r===hi||/^yes$/i.test(r)||/^install$/i.test(r),d=String(n.session_id??i.sessionId).trim()||i.sessionId,c=`cli-install:${t}`;if(!a)return this.aibotHandle.sendMsg({event_id:c,session_id:d,msg_type:1,content:`\u5DF2\u53D6\u6D88\u5B89\u88C5 ${i.cliName}\u3002`}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"install_declined"}}),!0;try{await this.runConfirmedCliInstall(i,{eventId:c,sessionId:d}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"install_started"}})}catch(l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"cli_install_failed",error_msg:l instanceof Error?l.message:String(l)})}return!0}async runConfirmedCliInstall(e,n){const t=s=>{this.aibotHandle.sendMsg({event_id:n.eventId,session_id:n.sessionId,msg_type:1,content:s,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})};if(!this.installAgentHandler){t(`\u65E0\u6CD5\u5B89\u88C5 ${e.cliName}\uFF1A\u5B89\u88C5\u5668\u672A\u5C31\u7EEA\u3002`);return}t(`\u5F00\u59CB\u5B89\u88C5 ${e.cliName}\u2026`);const i=await this.installAgentHandler({agentType:e.agentType});if(!i.ok){t(`${e.cliName} \u5B89\u88C5\u5931\u8D25\uFF1A${i.error?.message??i.phase}`);return}try{await li(e.cliName)}catch{}t(`\u2705 ${e.cliName} \u5B89\u88C5\u6210\u529F\u3002`),e.cwd&&(this.bindingStore.set(e.sessionId,e.cwd),this.sessionBindings.set(e.sessionId,e.cwd));try{await this.ensureSlotStarted(e.sessionId),e.cwd&&(await this.bindSessionForPool(e.sessionId,e.cwd),this.aibotHandle.sendUpdateBindingCard({session_id:e.sessionId,worker_status:"ready",cwd:e.cwd}),t(`\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u5C31\u7EEA\uFF1A\`${e.cwd}\``))}catch(s){t(`\u5B89\u88C5\u6210\u529F\uFF0C\u4F46\u542F\u52A8\u4ECD\u5931\u8D25\uFF1A${s instanceof Error?s.message:String(s)}`)}}getClaudeWorkerStatus(e){const n=this.pool.getSlot(e);return n?n.state==="starting"?"starting":n.state==="stopped"?"stopped":n.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,n){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:n,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillDeleteLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),i=String(n.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const s=H(this.config.adapterType,this.config.aibot.clientType),o=this.bindingStore.get(i)?.cwd||this.sessionBindings.get(i)||void 0;try{const r=await pt(t,{mode:s,projectDir:o});this.forceRefreshSkills(i||void 0,{force:!0})||u.warn(this.name,`skill_delete refresh push failed name=${r.name}; toolbar may keep a stale entry until next scan`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:r.name,path:r.path}}),u.info(this.name,`skill_delete name=${r.name} path=${r.path}`)}catch(r){u.warn(this.name,`skill_delete failed name=${t}: ${r instanceof Error?r.message:String(r)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_DELETE_FAILED",error_msg:r instanceof Error?r.message:String(r)})}}async handleSkillUploadLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),i=String(n.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const s=H(this.config.adapterType,this.config.aibot.clientType),o=this.bindingStore.get(i)?.cwd||this.sessionBindings.get(i)||void 0,r=s==="kiro"?o:o||process.cwd();try{await gt(t,{mode:s,projectDir:r},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(a){u.warn(this.name,`skill_upload failed name=${t}: ${a instanceof Error?a.message:String(a)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:a instanceof Error?a.message:String(a)})}}async handleSkillEnableLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),i=String(n.session_id??"").trim(),s=String(n.scope??"").trim(),o=String(n.actor_id??"").trim(),r=n.force==="replace_link"||n.force==="replace_with_link"?n.force:void 0,a=H(this.config.adapterType,this.config.aibot.clientType),d=this.bindingStore.get(i)?.cwd||this.sessionBindings.get(i)||void 0;try{const c=await mt({skillsDir:I.skills,mode:a,home:U(),cwd:d,env:this.skillLookupEnv()},{name:t,scope:s,actorId:o,force:r});u.info(this.name,`skill_enable name=${t} scope=${s} actor=${o||"-"} changed=${c.changed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:c.name,scope:c.scope,path:c.path,changed:c.changed,enable_state:c.status,uninstallable:!0,...c.hermes_trust?{hermes_trust:c.hermes_trust}:{}}})}catch(c){const l=c instanceof ve?c.code:"SKILL_ENABLE_FAILED";u.warn(this.name,`skill_enable failed name=${t} scope=${s}: ${c instanceof Error?c.message:String(c)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:l,error_msg:c instanceof Error?c.message:String(c),result:{conflict_kind:l==="CONFLICT"||l==="NEEDS_FORCE"||l==="BLOCKED"?l.toLowerCase():void 0}})}this.forceRefreshSkills()}handleSkillRefreshLocalAction(e){const n=e.params??{},t=String(n.session_id??"").trim();if(this.forceRefreshSkills(t||void 0,{force:!0})){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{session_id:t||void 0}});return}u.warn(this.name,`skill_refresh produced no report session=${t||"-"}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_REFRESH_FAILED",error_msg:"skill rescan produced no report (scan error or empty skill set)"})}async handleSkillDisableLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),i=String(n.session_id??"").trim(),s=String(n.scope??"").trim(),o=String(n.actor_id??"").trim(),r=H(this.config.adapterType,this.config.aibot.clientType),a=this.bindingStore.get(i)?.cwd||this.sessionBindings.get(i)||void 0;try{const d=await _t({skillsDir:I.skills,mode:r,home:U(),cwd:a,env:this.skillLookupEnv()},{name:t,scope:s,actorId:o});u.info(this.name,`skill_disable name=${t} scope=${s} actor=${o||"-"} removed=${d.removed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:d.name,scope:d.scope,path:d.path,removed:d.removed,enable_state:"none",uninstallable:!1}})}catch(d){const c=d instanceof ve?d.code:"SKILL_DISABLE_FAILED";u.warn(this.name,`skill_disable failed name=${t} scope=${s}: ${d instanceof Error?d.message:String(d)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:c,error_msg:d instanceof Error?d.message:String(d),result:{conflict_kind:c==="CONFLICT"||c==="BLOCKED"?c.toLowerCase():void 0}})}this.forceRefreshSkills()}computeSkillReport(e){const n=H(this.config.adapterType,this.config.aibot.clientType),t=n==="kiro"?e:e||process.cwd();let i;try{i=lt({mode:n,projectDir:t,env:this.skillLookupEnv()})}catch{return null}if(i.length===0)return null;const s=JSON.stringify(i.map(o=>`${o.source}:${o.name}`));return{skills:_e(i,I.skills),hash:s}}reportSessionSkills(e){const n=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,t=this.computeSkillReport(n);if(!t)return;const i=this.buildLibrarySkillsReport(n),s=ae(t.skills,i);if(!(t.hash===this.lastReportedSkillsHash&&s===this.lastReportedSkillsWireHash)){this.lastReportedSkillsHash=t.hash,this.lastReportedSkillsWireHash=s;try{this.aibotHandle.sendSkillsUpdate({skills:t.skills,library_skills:i})}catch{}}}skillsSyncGroupKey(){const e=String(this.config.aibot.clientType??"").trim().toLowerCase()||"unknown",n=String(this.config.aibot.sharedOwnerId??"").trim();return n?`shared:${n}:${e}`:`primary:${e}`}forceRefreshSkills(e,n){const t=e?.trim(),i=t||this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0}),s=t?this.bindingStore.get(t)?.cwd||this.sessionBindings.get(t)||void 0:i?this.bindingStore.get(i)?.cwd:void 0,o=this.computeSkillReport(s);if(!o)return!1;const r=this.buildLibrarySkillsReport(s),a=ae(o.skills,r);if(!n?.force&&a===this.lastReportedSkillsWireHash)return this.lastReportedSkillsHash=o.hash,!0;this.lastReportedSkillsHash=o.hash,this.lastReportedSkillsWireHash=a;try{return this.aibotHandle.sendSkillsUpdate({skills:o.skills,library_skills:r,...n?.ownerLibrarySync?{owner_library_sync:!0}:{}}),!0}catch{return!1}}adoptSkillsWireHashFromDisk(){const e=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0}),n=e?this.bindingStore.get(e)?.cwd:void 0,t=this.computeSkillReport(n);if(!t)return;const i=this.buildLibrarySkillsReport(n);this.lastReportedSkillsHash=t.hash,this.lastReportedSkillsWireHash=ae(t.skills,i)}buildLibrarySkillsReport(e){const n=H(this.config.adapterType,this.config.aibot.clientType);return ft({skillsDir:I.skills,mode:n,home:U(),cwd:e,env:this.skillLookupEnv()})}skillLookupEnv(){const e={...process.env,...this.config.agent.env};if((this.config.agent.clientType??"").trim().toLowerCase()==="hermes"&&!e.HERMES_HOME?.trim()){const n=this.providerResolver?this.providerResolver():this.config.agent.provider,t={...we(this.config.agent.clientType,n),...e};e.HERMES_HOME=ct(t,this.name)}return e}async ensureSlotStarted(e,n=6e4){const t=await this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((i,s)=>setTimeout(()=>s(new Error(`ensureSlotStarted timeout (${n}ms) session=${e}`)),n))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const n=Dt(e);if(!n)return;const t=this.reasonixTitleScan.get().filter(i=>i.stamp===n);return t.length===1?t[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(t=>t.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,n){const t=String(e??"").trim(),i=String(n??"").trim();if(!t||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,i);break;case"codex":this.bindingStore.setCodexThreadId(t,i);break;case"pi":this.bindingStore.setPiSessionPath(t,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,i);break;case"agy":this.bindingStore.setAgyConversationId(t,i);break;default:this.bindingStore.setAcpSessionId(t,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const n=String(e??"").trim();if(!n)return"";const t=$.resolve(n);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,n){const t=String(e??"").trim();if(!t)return;const i=this.normalizePathForCompare(n);let s="";const o=this.config.adapterType??"acp";if(o==="codex"?s=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":o==="claude"?s=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":o==="cursor"?s=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":o==="acp"?s=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":o==="deepseek-harness"&&(s=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!s){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){s=a.cwd??"";break}}if(!s){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=f.invalidAgentSession,a}const r=this.normalizePathForCompare(s);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${n}, got ${s}`);throw a.sessionControlErrorCode=f.invalidAgentSession,a}}buildOpenedBindingResult(e,n,t="ready"){const i=this.bindingStore.get(e),s=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:n,workerStatus:t};return s&&(o.bindingId=s,o.agentSessionId=s),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const n=this.globalConfigStore?.get(this.name),t=this.bindingStore.get(e),i=this.config.adapterOptions??{},s=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const C=Je(n?.dshAgentPreset,We);this.bindingStore.setDshAgentPreset(e,C)}const o=this.bindingStore.getDshSelectedProfile(e),r=et({binding:o,global:n?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),d=this.bindingStore.getDshSettings(e),c=d?.providerId??n?.dshProviderId,l=Xe({dataRoot:a,providerId:c}),h=[d?.modelId,n?.dshModelId,l.models[0]?.id].find(C=>!!C&&l.models.some(w=>w.id===C))??l.models[0]?.id,g=ge(t?.dshModeId,n?.dshModeId),m={};!t?.dshProviderId&&l.providerId&&(m.providerId=l.providerId),!t?.dshModelId&&h&&(m.modelId=h),t?.dshModeId||(m.modeId=g),t?.dshThinking||(m.thinking=Ve(n?.dshThinking)??"enabled"),t?.dshReasoningEffort||(m.reasoningEffort=ze(n?.dshReasoningEffort)??"high"),Object.keys(m).length>0&&this.bindingStore.updateDshSettings(e,m);const p=this.bindingStore.getDshSettings(e);let _=[],b=[],S=!1;try{_=Ke({dshHome:s,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),S=!1}catch{}const k=$.join(a,"dsh-session-skills");return ut(k),b=Ge({skillsDir:k,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),Ne({agentPreset:p?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:je({dshHome:s}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:_,skills:b,pluginRestartRequired:S,providerId:p?.providerId??l.providerId,modelId:p?.modelId??h,modeId:ge(this.bindingStore.get(e)?.dshModeId,n?.dshModeId),thinking:p?.thinking,reasoningEffort:p?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=V("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return $.join(I.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}async unbindSession(e){const n=this.pool.getSlot(e)?.adapter;this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.claudeWorkerStatus.delete(e),this.deferredMgr.clearSession(e);for(const i of this.pool.drainQueuedForSession(e))this.discardEventTrackingState(i.event_id);const t=this.pool.removeSlot(e).catch(i=>{u.warn(this.name,`failed to remove adapter slot on unbind: ${i instanceof Error?i.message:String(i)}`)});n instanceof Y&&await n.destroySession(e).catch(i=>{u.warn(this.name,`failed to delete DeepSeek Harness session state: ${i instanceof Error?i.message:String(i)}`)}),await t,this.aibotHandle.clearBindingCardMetaCache?.(e),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"stopped"})}async handleUnbindTextCommand(e){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),!this.bindingStore.get(e.session_id)?.cwd){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:f.bindingMissing,msg:"No session binding found for this session",updated_at:Date.now()});return}await this.unbindSession(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"Session unbound",updated_at:Date.now()})}async handleUnbindLocalAction(e){const n=String((e.params??{}).session_id??"");if(!this.bindingStore.get(n)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.bindingMissing,error_msg:"No session binding found for this session"});return}await this.unbindSession(n),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"unbound",sessionId:n}})}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const i=Array.from(this.bindingStore.entries()),s=new Map;for(const[a,d]of i){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";s.set(c,{aibotSessionId:a,workerStatus:h})}}const o=[],r=new Set;if(n==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=s.get(d.threadId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.threadId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),o.push(` Created: ${new Date(d.createdAt).toISOString()}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="deepseek-harness"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),d.createdAt&&o.push(` Created: ${new Date(d.createdAt).toISOString()}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="pi"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionPath);const c=s.get(d.sessionPath);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionPath}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="codewhale"||n==="opencode"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}for(const[a,d]of i){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",g=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026");o.push(` Title: ${g}`),o.push(` AIBot: ${a}`),c&&o.push(` Agent: ${c}`),o.push(` CWD: ${d.cwd??"-"}`),o.push(` State: ${h}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}if(o.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${o.filter(a=>a==="---").length}):
10
- ${o.join(`
11
- `)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const n=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const i=Array.from(this.bindingStore.entries()),s=new Map;for(const[a,d]of i){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";s.set(c,{aibotSessionId:a,workerStatus:h,bindingUpdatedAt:d.updatedAt??0})}}const o=[],r=new Set;if(n==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=s.get(d.threadId),l={agentSessionId:d.threadId,cwd:d.cwd||null,workerStatus:c?.workerStatus??(d.archived?"archived":"inactive"),createdAt:d.createdAt,updatedAt:d.updatedAt,archived:d.archived};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),o.push(l)}}else if(n==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId),l={agentSessionId:d.sessionId,cwd:d.cwd||null,workerStatus:c?.workerStatus??"inactive",updatedAt:d.updatedAt};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),o.push(l)}}else if(n==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,h={agentSessionId:d.sessionId,cwd:d.cwd||null,agentType:d.agentType,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(h.aibotSessionId=c.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),o.push(h)}}else if(n==="deepseek-harness"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=s.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,h={agentSessionId:d.sessionId,cwd:d.cwd||null,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(h.aibotSessionId=c.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),o.push(h)}}else if(n==="pi"||n==="codewhale"||n==="opencode"){const a=this.sessionScanCache.get();for(const d of a){const c="sessionPath"in d?d.sessionPath:d.sessionId;r.add(c);const l=s.get(c),h={agentSessionId:c,cwd:d.cwd||null,workerStatus:l?.workerStatus??("archived"in d&&d.archived?"archived":"inactive"),updatedAt:l&&l.bindingUpdatedAt>0?l.bindingUpdatedAt:d.updatedAt};l&&(h.aibotSessionId=l.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),"archived"in d&&(h.archived=d.archived),o.push(h)}}for(const[a,d]of i){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",g={aibotSessionId:a,cwd:d.cwd??null,workerStatus:h,updatedAt:d.updatedAt,title:this.resolveOrphanTitle(c)??(c?`${c.slice(0,8)}\u2026`:`${a.slice(0,8)}\u2026`)};c&&(g.agentSessionId=c),o.push(g)}o.sort((a,d)=>d.updatedAt-a.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:o,total:o.length}})}async handleSyncHistoryLocalAction(e){const n=e.params??{},t=String(n.provider_key??this.config.adapterType??"acp").trim().toLowerCase(),i=String(n.agent_session_id??"").trim(),s=String(n.cwd??"").trim(),o=typeof n.sync_run_id=="string"&&n.sync_run_id?n.sync_run_id:void 0,r=(d,c)=>{u.warn(this.name,`sync_history failed action_id=${e.action_id} provider=${t} code=${d} msg=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:d,error_msg:c})};if(!i){r(K.agentSessionRequired,"agent_session_id is required for sync_history");return}if(!s){r(K.cwdRequired,"cwd is required for sync_history");return}const a=dt(t);if(!a){r(K.providerUnsupported,`provider ${t} does not support sync_history`);return}try{const d=await a({session_id:String(n.session_id??""),provider_key:t,agent_session_id:i,cwd:s,cursor:typeof n.cursor=="string"&&n.cursor?n.cursor:void 0,limit:typeof n.limit=="number"?n.limit:void 0,sync_run_id:o});u.debug(this.name,`sync_history ok action_id=${e.action_id} provider=${t} agent_session_id=${i} messages=${d.messages.length} has_more=${d.has_more}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"history_synced",messages:d.messages,has_more:d.has_more,next_cursor:d.next_cursor,...o?{sync_run_id:o}:{}}})}catch(d){d instanceof at?r(d.code,d.message):r(K.runtimeError,String(d))}}async handleSessionControlCommand(e,n){const t=n.session_id,i=(s,o,r)=>{this.aibotHandle.sendEventResult({event_id:n.event_id,status:s,...o?{msg:o}:{},...r?{code:r}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case v.open:{await Z().catch(()=>{});const s=e.args.trim();if(!s){i("failed","Usage: /grix open <working-directory>",f.cwdRequired);return}let o="";try{o=await this.resolveCwdForBinding(s)}catch(a){i("failed",a instanceof Error?a.message:String(a),f.invalidCwd);return}const r=this.bindingStore.get(t);if(r?.cwd){const a=await this.resolveCwdForBinding(r.cwd);if(a!==o){i("failed","session binding cannot be changed to another working directory",f.rebindForbidden);return}this.bindingStore.ensureModeId(t,y.fullAuto),this.sessionBindings.set(t,a),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,a),i("responded",`Working directory already bound: ${a}`);return}this.bindingStore.set(t,o,{modeId:y.fullAuto}),this.sessionBindings.set(t,o),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,o),i("responded",`Session bound to ${o}`);return}case v.where:{const s=this.bindingStore.get(t);if(!s?.cwd){i("failed","session binding was not found",f.bindingMissing);return}i("responded",`Working directory: ${s.cwd}`);return}case v.status:{const s=this.bindingStore.get(t);if(!s?.cwd){i("failed","session binding was not found",f.bindingMissing);return}const o=this.currentClaudeModeId(t),r=this.getClaudeWorkerStatus(t);i("responded",`Status: worker=${r} mode=${o} cwd=${s.cwd}`);return}case v.stop:{const s=this.bindingStore.get(t);if(!s?.cwd){i("failed","session binding was not found",f.bindingMissing);return}await this.pool.removeSlot(t),this.claudeWorkerStatus.set(t,"stopped"),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:s.cwd}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:s.cwd,meta:this.buildClaudeToolbarMeta(t)}),i("responded",`Session worker stopped for ${s.cwd}`);return}case v.restart:{const s=this.bindingStore.get(t);if(!s?.cwd){i("failed","session binding was not found",f.bindingMissing);return}await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,s.cwd),i("responded",`Session worker restarted for ${s.cwd}`);return}case v.setMode:{const s=e.args.trim();if(!s){i("failed","Usage: /grix set_mode <mode-id>",L.modeInvalid);return}const o=this.normalizeClaudeModeId(s);if(o!==s.toLowerCase()){i("failed","set mode_id is invalid",L.modeInvalid);return}const r=this.bindingStore.get(t);if(!r?.cwd){i("failed","session binding was not found",f.bindingMissing);return}if(this.currentClaudeModeId(t)===o){i("responded",`Mode unchanged: ${o}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){i("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F",f.workerBusy);return}this.bindingStore.setModeId(t,o),this.globalConfigStore?.set(this.name,{modeId:o}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,r.cwd),i("responded",`Mode set to ${o}`);return}case v.setModel:{const s=e.args.trim();if(!s){i("failed","Usage: /grix set_model <model-id>");return}const o=this.bindingStore.get(t);if(!o?.cwd){i("failed","session binding was not found",f.bindingMissing);return}if((o.modelId??"")===s){i("responded",`Model unchanged: ${s}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){i("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B",f.workerBusy);return}this.bindingStore.setModelId(t,s),this.globalConfigStore?.set(this.name,{modelId:s}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,o.cwd),this.refreshQuotaAfterModelSwitch(t,s),i("responded",`Model set to ${s}`);return}case v.listOptions:{const s=ee(),o=this.bindingStore.get(t),r=s.map(c=>c.id).join(", "),a=`${y.fullAuto}, ${y.approval}`,d=this.resolveClaudeSessionEffort(t)??"auto";i("responded",`Modes (current: ${this.currentClaudeModeId(t)}): ${a}
12
- Models (current: ${o?.modelId??"default"}): ${r}
13
- Effort (current: ${d}): ${Q.join(", ")}`);return}case v.exec:{const[s,...o]=e.args.trim().split(/\s+/);if(!s){i("failed","Usage: /grix exec <command> [args]",f.verbInvalid);return}const a=this.pool.getSlot(t)?.adapter;if(!a?.execCommand){i("failed","Agent does not support command execution",f.verbInvalid);return}const d=a.getSupportedCommands?.()??[];if(!d.some(c=>c.name===s)){i("failed",`Unknown command: ${s}. Supported: ${d.map(c=>c.name).join(", ")}`,f.verbInvalid);return}try{const c=await a.execCommand(s,o.join(" "),t);i(c.status==="ok"?"responded":"failed",c.message??`${s} ${c.status}`,c.status==="ok"?void 0:f.runtimeError)}catch(c){i("failed",`exec error: ${c instanceof Error?c.message:c}`,f.runtimeError)}return}default:i("failed",`Unsupported command for Claude: /grix ${e.verb}`,f.verbInvalid)}}catch(s){if(e.verb===v.open){const{code:o,msg:r}=this.failSessionOpen(s,{sessionId:t,eventId:n.event_id,quotedMessageId:n.msg_id,cwd:this.bindingStore.get(t)?.cwd||e.args.trim()});i("failed",r,o)}else i("failed",s instanceof Error?s.message:String(s),f.runtimeError)}}async handleSessionControlLocalAction(e){const n=String(e.action_type??"").trim();if(n!==E.sessionControl&&n!==E.setMode&&n!=="set_mode"&&n!==E.setModel&&n!=="set_model"&&n!==E.setReasoningEffort&&n!=="set_effort")return!1;const t=e.params??{},i=String(t.session_id??"").trim(),s=n===E.setMode?v.setMode:n===E.setModel?v.setModel:n===E.setReasoningEffort||n==="set_effort"?E.setReasoningEffort:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${s} action_id=${e.action_id} session_id=${i}`),!i)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:L.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const o=a=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a},i)},r=(a,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${i} verb=${s} code=${a} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:a,error_msg:d})};try{switch(s){case v.open:{await Z().catch(()=>{});const a=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!a)return r(f.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${a} session_id=${i}`);const c=await this.resolveCwdForBinding(a);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(i);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(r(f.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(i,y.fullAuto),this.setResolvedAgentSessionId(i,d),this.sessionBindings.set(i,h),await this.ensureSlotStarted(i),await this.deferredMgr.release(i,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(i,h),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(i,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(i)?.modeId)}}),!0)}return this.bindingStore.set(i,c,{modeId:y.fullAuto}),this.setResolvedAgentSessionId(i,d),this.sessionBindings.set(i,c),await this.ensureSlotStarted(i),await this.deferredMgr.release(i,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(i,c),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(i,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(i)?.modeId)}}),!0}case v.status:case v.where:{const a=this.bindingStore.get(i);return a?.cwd?(o({outcome:s,binding:{cwd:a.cwd,mode_id:this.currentClaudeModeId(i),worker_status:this.getClaudeWorkerStatus(i)}}),!0):(r(f.bindingMissing,"session binding was not found"),!0)}case v.stop:{const a=this.bindingStore.get(i);return a?.cwd?(await this.pool.removeSlot(i),o({outcome:"stopped",binding:{cwd:a.cwd,mode_id:this.currentClaudeModeId(i),worker_status:"stopped"}}),!0):(r(f.bindingMissing,"session binding was not found"),!0)}case v.restart:{const a=this.bindingStore.get(i);return a?.cwd?(await this.pool.removeSlot(i),await this.ensureSlotStarted(i),this.refreshClaudeWorkerStatusCard(i,a.cwd),o({outcome:"restarted",binding:{cwd:a.cwd,mode_id:this.currentClaudeModeId(i)}}),!0):(r(f.bindingMissing,"session binding was not found"),!0)}case E.setReasoningEffort:{const a=[t.effort,t.reasoning_effort,t.reasoning_eff,t.value].map(h=>String(h??"").trim()).find(Boolean)??"",d=ie(a);if(!a||!d)return r(L.effortInvalid,`effort is invalid; expected one of ${Q.join(", ")}`),!0;const c=this.bindingStore.get(i);if(!c?.cwd)return r(f.bindingMissing,"session binding was not found"),!0;if(this.bindingStore.getEffort(i)!==d){if(this.getClaudeWorkerStatus(i)==="busy")return r(f.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362 effort"),!0;this.bindingStore.setEffort(i,d),await this.pool.removeSlot(i),await this.ensureSlotStarted(i)}return this.globalConfigStore?.set(this.name,{effort:d}),this.refreshClaudeWorkerStatusCard(i,c.cwd),o({outcome:"effort_set",effort:d,reasoning_effort:d,available_efforts:[...Q],binding:{cwd:c.cwd,effort:d}}),!0}case v.setMode:{const a=String(t.mode_id??t.modeId??"").trim();if(!a)return r(L.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(a);if(d!==a.toLowerCase())return r(L.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(i);if(!c?.cwd)return r(f.bindingMissing,"session binding was not found"),!0;if(this.currentClaudeModeId(i)!==d){if(this.getClaudeWorkerStatus(i)==="busy")return r(f.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(i,d),this.globalConfigStore?.set(this.name,{modeId:d}),await this.pool.removeSlot(i),await this.ensureSlotStarted(i),this.refreshClaudeWorkerStatusCard(i,c.cwd)}return o({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case v.setModel:{const a=String(t.model_id??t.modelId??"").trim();if(!a)return r("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(i);if(!d?.cwd)return r(f.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==a){if(this.getClaudeWorkerStatus(i)==="busy")return r(f.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(i,a),this.globalConfigStore?.set(this.name,{modelId:a}),await this.pool.removeSlot(i),await this.ensureSlotStarted(i),this.refreshClaudeWorkerStatusCard(i,d.cwd),this.refreshQuotaAfterModelSwitch(i,a)}return o({outcome:"model_set",model_id:a,binding:{cwd:d.cwd,model_id:a}}),!0}case v.listOptions:{const a=ee(),d=this.pool.getSlot(i),c=this.resolveClaudeSessionEffort(i)??"auto";return o({modes:[y.fullAuto,y.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(i)?.modeId),models:a.map(l=>({modelId:l.id,name:l.displayName})),currentModelId:this.bindingStore.get(i)?.modelId??"",available_models:a.map(l=>({id:l.id,displayName:l.displayName})),available_efforts:[...Q],effort:c,reasoning_effort:c,agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case v.exec:{const[a,...d]=String(t.args??"").trim().split(/\s+/);if(!a)return r(f.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(i);const l=this.pool.getSlot(i)?.adapter;if(!l?.execCommand)return r(f.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(g=>g.name===a))return r(f.verbInvalid,`Unknown command: ${a}. Supported: ${h.map(g=>g.name).join(", ")}`),!0;try{const g=await l.execCommand(a,d.join(" "),i);g.status==="ok"?o({outcome:"exec",command:a,message:g.message,data:g.data}):r(f.runtimeError,g.message??`${a} failed`)}catch(g){r(f.runtimeError,`exec error: ${g instanceof Error?g.message:g}`)}return!0}default:return r(f.verbInvalid,`session control verb ${s} is not supported`),!0}}catch(a){if(s===v.open){const{code:d,msg:c}=this.failSessionOpen(a,{sessionId:i,eventId:e.action_id,cwd:this.bindingStore.get(i)?.cwd||String(t.cwd??"").trim()});u.error(this.name,`handleSessionControlLocalAction error verb=${s} session_id=${i}: ${c}`),r(d,c)}else{const d=a instanceof Error?a.message:String(a);u.error(this.name,`handleSessionControlLocalAction error verb=${s} session_id=${i}: ${d}`),r(f.runtimeError,d)}return!0}}async handleEventCancel(e){const{event_id:n,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${n} session_id=${t}`),this.pendingEvents.markCanceled(n),this.pool.cancelEvent(n,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)){await this.pendingEvents.remove(n),this.sendEventResultWithCleanup(n,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(n,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}const s=this.deferredMgr.removeEvent(n);if(s){await this.pendingEvents.remove(n),this.sendCanceledPendingEventResult(s,"canceled"),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"});return}const o=await this.pendingEvents.cancel(n,t);if(o){this.sendCanceledPendingEventResult(o.event,"canceled"),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"});return}this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,n,t){return new Promise(i=>{const s=this.pool.getSlot(n);if(!s?.adapter){i();return}const o=setTimeout(()=>{s.adapter.removeListener("eventDone",r),i()},t),r=a=>{a===e&&(clearTimeout(o),s.adapter.removeListener("eventDone",r),i())};s.adapter.on("eventDone",r)})}handleAibotStop(e){const n=e.event_id?.trim()??"",t=e.scope?.trim()??"";u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${n||"-"} scope=${t||"event"} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`);const i=this.pool.getSlot(e.session_id),s=i?.adapter?.getStatus().busy??!1;let o=!1,r=[];if(i?.adapter)try{r=[...new Set(i.adapter.getActiveEventIds().map(p=>p.trim()).filter(Boolean))]}catch(p){o=!0,u.warn(this.name,`[stop-trace] handleAibotStop active event probe failed session=${e.session_id}: ${p}`)}const a=t==="session";let d=a?"":n;const c=p=>({stop_id:e.stop_id,...p?{event_id:p}:{},...e.terminal_commit_token?{terminal_commit_token:e.terminal_commit_token}:{},session_id:e.session_id,...t?{scope:t}:{}}),l=p=>{!p||!e.terminal_commit_token?.trim()||this.sendEventResultWithCleanup(p,"canceled","stopped by owner","event_stopped")};if(a)if(!o&&r.length===1)[d]=r;else if(!o&&r.length===0&&!s){this.aibotHandle.sendEventStopAck({...c(""),accepted:!0,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"already_finished",updated_at:Date.now()}),u.info(this.name,`[stop-trace] handleAibotStop session idle -> stopResult(already_finished) session=${e.session_id} stop_id=${e.stop_id||"-"}`);return}else{const p=o?"session_stop_target_unavailable":r.length>1?"session_stop_target_ambiguous":"session_stop_target_unresolved",_=o?"failed to inspect active events for session stop":r.length>1?"multiple active events prevent a safe session stop":"adapter is busy but no active event can be identified";this.aibotHandle.sendEventStopAck({...c(""),accepted:!1,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"failed",code:p,msg:_,updated_at:Date.now()}),u.warn(this.name,`[stop-trace] handleAibotStop session target unsafe -> stopResult(failed) session=${e.session_id} activeIds=[${r.join(",")}] busy=${s} code=${p}`);return}if(this.aibotHandle.sendEventStopAck({...c(d),accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,d)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"}`),e.terminal_commit_token?.trim()?l(d):this.discardEventTrackingState(d),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});return}const h=(this.config.adapterType??"acp")==="acp",g=r.length>0?r.includes(d):s,m=(h||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&g;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${d} scope=${t||"event"} slotExists=${!!i?.adapter} busy=${s} activeIds=[${r.join(",")}] stoppingActiveEvent=${g} killOnStop=${m}`),g&&this.sendCtrl.markEventStopped(d),i?.adapter&&s){const p=m?this.pool.drainQueuedForSession(e.session_id):[];let _=!1,b=null;const S=C=>{_||(_=!0,b&&(clearTimeout(b),b=null),i.adapter.removeListener("eventDone",k),u.info(this.name,`[stop-trace] handleAibotStop ${C} -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"} killOnStop=${m}`),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()}),m&&this.killAndResumeStopSlot(e.session_id,p))},k=C=>{C===d&&S("eventDone")};i.adapter.on("eventDone",k),b=setTimeout(()=>S("timeout"),nn),this.pool.deliverStopEvent(d,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${d} slotExists=${!!i?.adapter}`),this.pool.deliverStopEvent(d,e.session_id),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:d,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,n){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${n.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${n.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of n){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(i){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${i instanceof Error?i.message:String(i)}`),this.sendEventResultWithCleanup(t.event_id,"failed",i instanceof Error?i.message:String(i))}}}}async handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const n=e.event_id,t=e.session_id;if(this.pendingEvents.markCanceled(n),t&&this.pool.cancelEvent(n,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)||(await this.pendingEvents.remove(n),this.sendEventResultWithCleanup(n,"canceled","revoked"));return}const i=this.deferredMgr.removeEvent(n);if(i){await this.pendingEvents.remove(n),this.sendCanceledPendingEventResult(i,"revoked");return}const s=this.pool.cancelStartupEvent(n,t||void 0);if(s){await this.pendingEvents.remove(n),this.sendCanceledPendingEventResult(s,"revoked");return}const o=await this.pendingEvents.cancel(n,t||void 0);if(o){this.sendCanceledPendingEventResult(o.event,"revoked");return}this.pool.deliverStopEvent(n,t||void 0)}async handleConfigureGatewayProvider(e){const n=e.params??{},t=String(n.api_key??"").trim(),i=String(n.anthropic_base_url??"").trim(),s=String(n.openai_base_url??"").trim(),o=typeof n.provider_id=="string"&&n.provider_id.trim().toLowerCase()||void 0,r=typeof n.quota_base_url=="string"&&n.quota_base_url.trim()||void 0,a=typeof n.model=="string"&&n.model.trim()||void 0;let d=!1,c;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const l=this.config.adapterType??"acp",h=l==="claude"||l==="codex",g=h&&yt(n.direct_relay,l),m=h&&n.direct_relay!==void 0&&!g;try{if(m){if(!this.relayStateApplyPorts){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:"relay state applier is not configured"});return}const p=await this.relayStateApplyPorts.applyEnable({apiKey:t,...i?{anthropicBaseUrl:i}:{},...s?{openaiBaseUrl:s}:{},...a?{model:a}:{},directRelay:n.direct_relay},a);p&&(c=p,d=p.busy||p.pending!==void 0)}else if(h){const p=l==="claude"?i:s;if(!p){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${l==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const _=Se();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const b=wt(l),S=Ct(l,p,t,{model:a});_.setRoute(S);for(const k of b)_.setHostDefaultRoute(k,S.routeKey);await _.setAgentRelayEnabled(this.name,!0,{relayHosts:b}),d=!await this.recycleAdaptersForRelayChange()}else{if(!this.providerConfigHandler){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:`client type "${l}" does not support Grix relay provider config`});return}const p=this.config.aibot.clientType,_=be(p),b=_?i:s;if(!b){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${_?"anthropic_base_url":"openai_base_url"} is required`});return}if(_&&!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_MODEL",error_msg:'model is required for client type "kiro"'});return}await this.providerConfigHandler({...o?{provider_id:o}:{},base_url:b||void 0,...r?{quota_base_url:r}:{},api_key:t,model:a})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:d,...c?{restarted:c.restarted,busy:c.busy,...c.pending?{pending:c.pending}:{}}:{}}})}catch(p){u.error(this.name,`handleConfigureGatewayProvider failed: ${p}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:p instanceof Error?p.message:String(p)})}}getAuditLocalActionHandler(){if(!this.auditLocalActionHandler){const e=new ot({rootDir:st()});this.auditLocalActionHandler=new tt(new nt(e))}return this.auditLocalActionHandler}async handleAuditLocalAction(e){const n=await this.getAuditLocalActionHandler().handle(e.action_type,e.params);if(n.status==="ok"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:n.result});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:n.errorCode,error_msg:n.errorMsg})}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 n=e.action_type??"",t=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${n} verb=${i||"-"} action_id=${e.action_id} session_id=${t}`);let s;if(n===E.sessionControl&&(s=this.lifecycleBarrier.tryEnter()??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(n===E.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(it(n)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(n===E.sessionControl&&i===v.exec&&await this.handleSessionControlLocalAction(e))return;if(n===E.sessionControl&&i===v.listSessions){await this.handleListSessionsLocalAction(e);return}if(n===E.sessionControl&&i===v.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(n===E.sessionControl&&i===v.unbind){await this.handleUnbindLocalAction(e);return}if(n==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(n==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(n==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(n==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(n==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(n===E.interactionReply||n==="exec_approve"||n==="exec_reject")||r&&n===E.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(n===E.sessionControl){const g=this.config.adapterType??"acp",m=g==="codex",p=g==="pi",_=String((e.params??{}).verb??"").trim().toLowerCase();if(m&&_===v.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(g==="cursor"&&_===v.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(m&&_==="restart"){const w=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:w,workerStatus:"ready"}}});return}if(p&&_===v.open){try{const C=e.params??{},w=String(C.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(w),T=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(T,A),this.bindingStore.set(t,A),this.setResolvedAgentSessionId(t,T),this.sessionBindings.set(t,A),await this.ensureSlotStarted(t).catch(D=>{if(ne(D))throw D;u.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${D instanceof Error?D.message:String(D)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:A}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,A)}})}catch(C){this.failSessionOpen(C,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||String((e.params??{}).cwd??"").trim(),send:(w,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:w,error_msg:A})})}return}if(p&&_===v.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((g==="openhuman"||g==="opencode")&&_===v.open){try{const C=e.params??{},w=String(C.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(w),T=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(T,A),this.bindingStore.set(t,A),this.setResolvedAgentSessionId(t,T),this.sessionBindings.set(t,A),await this.syncOpenCodeBinding(t,A),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,A)}})}catch(C){this.failSessionOpen(C,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||String((e.params??{}).cwd??"").trim(),send:(w,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:w,error_msg:A})})}return}if(g==="codewhale"&&_===v.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(g==="deepseek-harness"&&_===v.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(g==="acp"&&_===v.stop){const w=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:w,workerStatus:"stopped"}}});return}try{if(_===v.open){const C=e.params??{},w=String(C.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.cwdRequired,error_msg:"session cwd is required"});return}const A=String(C.agent_session_id??"").trim();if(A){const T=await this.resolveCwdForBinding(w);this.ensureImportedAgentSession(A,T)}}await this.handleSessionControlLocalActionForPool(e)}catch(C){this.failSessionOpen(C,{sessionId:t,eventId:e.action_id,cwd:this.bindingStore.get(t)?.cwd||String((e.params??{}).cwd??"").trim(),send:(w,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:w,error_msg:A})});return}if(_===v.open){const C=e.params??{},w=await this.resolveCwdForBinding(String(C.cwd??"").trim());this.setResolvedAgentSessionId(t,String(C.agent_session_id??"").trim()),g==="agy"&&(this.bindingStore.set(t,w),this.sessionBindings.set(t,w)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(t,w),this.refreshAndPushAgyQuota(t,!0))}else ai(e,this.sessionControlCtx(t),this.sessionControlSenders(t));return}if(n==="file_list"){const g=Date.now(),m=t?this.bindingStore.get(t)?.cwd:void 0,p=e.params??{},_=String(p.parent_id??"").trim(),b=Array.isArray(p.allowed_extensions)?p.allowed_extensions.filter(w=>typeof w=="string").map(w=>w.trim()).filter(w=>w.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${_||"<root>"} show_hidden=${!!p.show_hidden} ext_count=${b.length} bound_cwd=${m??"<none>"}`);const S=await bi({parent_id:_||null,session_id:t,show_hidden:!!p.show_hidden,allowed_extensions:b},{resolveCwd:()=>m??this.config.agent.cwd??process.cwd(),fallbackDir:Re()}),k=Date.now()-g,C=S.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${S.status} elapsed=${k}ms count=${C} current_path=${S.result?.current_path??""} error_code=${S.error_code??""} error_msg=${S.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:S.status,...S.result?{result:{...S.result,machine_name:Ai()}}:{},...S.error_code?{error_code:S.error_code}:{},...S.error_msg?{error_msg:S.error_msg}:{}});return}if(n==="create_folder"){const g=t?this.bindingStore.get(t)?.cwd:void 0,m=String((e.params??{}).parent_id??"").trim(),p=String((e.params??{}).name??"").trim(),_=await wi({parent_id:m||null,name:p,session_id:t},{resolveCwd:()=>g??this.config.agent.cwd??process.cwd(),fallbackDir:Re()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:_.status,..._.result?{result:_.result}:{},..._.error_code?{error_code:_.error_code}:{},..._.error_msg?{error_msg:_.error_msg}:{}});return}if(n===E.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(n===E.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!t&&!!this.bindingStore.get(t)?.cwd})).handled)return;await this.handleGetSessionUsage(e,t);return}if(n===E.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!t&&!!this.bindingStore.get(t)?.cwd})).handled)return;await this.handleGetRateLimits(e,t);return}const a=(this.config.adapterType??"acp")==="acp",d=(this.config.adapterType??"acp")==="cursor";if((o||a||d)&&n===E.threadCompact){await this.handleThreadCompact(e,t);return}if(n==="connector_rollback"){await this.handleConnectorRollback(e);return}if(n==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(n===E.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(n==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(n==="apply_relay_state"){await this.handleApplyRelayState(e);return}const c=this.config.adapterType??"acp",l=(c==="codex"||c==="cursor"||c==="pi"||c==="openhuman"||c==="opencode"||c==="deepseek-harness"||c==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const g=String((e.params??{}).mode_id??"");g&&(c==="cursor"?(this.bindingStore.setCursorModeId(t,g),this.globalConfigStore?.set(this.name,{cursorModeId:g})):c==="claude"?(this.bindingStore.setModeId(t,g),this.globalConfigStore?.set(this.name,{modeId:g})):c==="opencode"?(this.bindingStore.setModeId(t,g),this.globalConfigStore?.set(this.name,{modeId:g})):j.has(c)?c==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:g}):this.globalConfigStore?.set(this.name,{acpInitialMode:g}))}else if(h.kind==="set_model"){const g=String((e.params??{}).model_id??"").trim();if(g){c==="cursor"?(this.bindingStore.setModelId(t,g),this.globalConfigStore?.set(this.name,{modelId:g})):c==="opencode"?(this.bindingStore.setModelId(t,g),this.globalConfigStore?.set(this.name,{modelId:g})):c==="codewhale"?(this.bindingStore.setModelId(t,g),this.globalConfigStore?.set(this.name,{modelId:g})):c==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:g,codexReasoningEffort:void 0}):j.has(c)||this.globalConfigStore?.set(this.name,{modelId:g});const m=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(t,g,m)}}else if(h.kind==="set_reasoning_effort"){const g=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");g&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:g})}else if(h.kind==="set_sandbox_mode"){const g=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(g){const m=g==="default"?void 0:g;this.globalConfigStore?.set(this.name,{codexSandboxMode:m})}}else if(h.kind==="set_service_tier"){const g=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(g){const m=g.toLowerCase()==="default"?void 0:g;this.globalConfigStore?.set(this.name,{codexServiceTier:m})}}return}if((c==="codex"||c==="cursor"||c==="pi"||c==="openhuman"||c==="opencode"||c==="deepseek-harness")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(c==="acp"&&(n==="set_mode"||n==="set_model")){const g=this.sessionControlSenders(t),m=this.pool.getSlot(t)?.adapter,p={bindingStore:this.bindingStore,acpAdapter:m instanceof R?m:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(n==="set_mode"){const _=String((e.params??{}).mode_id??""),b=await ke(p,t,_);if(b.status==="failed")g.sendLocalActionResult(e.action_id,"failed",void 0,b.errorCode,b.errorMsg);else{const S=m instanceof R?m.buildToolbarContext(b.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,k=S?{...S,...b.result}:b.result;g.sendLocalActionResult(e.action_id,"ok",k)}}else{const _=String((e.params??{}).model_id??""),b=await Ee(p,t,_);if(b.status==="failed")g.sendLocalActionResult(e.action_id,"failed",void 0,b.errorCode,b.errorMsg);else{const S=m instanceof R?m.buildToolbarContext(b.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,k=S?{...S,...b.result}:b.result;g.sendLocalActionResult(e.action_id,"ok",k),b.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(t,_)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${n} is not supported`})}finally{s?.()}}async handleGetSessionUsage(e,n){if(!n){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",i=this.bindingStore.get(n),s=i?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${n} adapterType=${t} hasBinding=${!!i} cwd=${s}`);let o=null,r,a;switch(t){case"claude":{if(r=i?.claudeSessionId,!r){u.warn(this.name,`[usage] no claude binding for session_id=${n}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${r} cwd=${s}`),o=await rt(r,s),a="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"agy print-mode adapter does not track token usage"});return}case"opencode":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"opencode session usage parsing is not implemented"});return}case"openhuman":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"openhuman is deprecated; session usage is not tracked"});return}case"acp":default:{if(r=i?.acpSessionId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}o=await St(r,s,this.config.aibot.clientType),a=t,(!a||a==="acp")&&(a="acp");break}case"codex":{if(r=i?.codexThreadId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}o=await Tt(r),a="codex";break}case"pi":{if(r=i?.piSessionPath,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}o=await Kt(r),a="pi";break}case"cursor":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof N)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(n);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const h={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:l.total.cacheRead,cacheCreationInputTokens:l.total.cacheWrite};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:n,adapterType:"cursor",models:[{model:this.bindingStore.get(n)?.modelId??"auto",turns:l.turns,total:h}],total:h,turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof ue)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const h={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:0,cacheCreationInputTokens:0};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:n,adapterType:"codewhale",models:[{model:this.bindingStore.get(n)?.modelId??"codewhale",turns:l.turns,total:h}],total:h,turns:l.turns,sampledAt:l.sampledAt}});return}}if(!o){u.info(this.name,`[usage] no usage data found: session_id=${n} adapterSessionId=${r} adapterType=${a}`);const d=String(this.config.aibot.clientType??"").trim().toLowerCase(),l=t==="acp"&&new Set(["hermes","reasonix","kimi","copilot"]).has(d)?`${d} session usage parsing is not available`:"No usage data found for this session";this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:l});return}u.info(this.name,`[usage] result ok: session_id=${n} adapterSessionId=${r} turns=${o.turns} models=${o.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:r,adapterType:a,models:o.models,total:o.total,turns:o.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,n){if(!n){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(n)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(n);const s=this.pool.getSlot(n)?.adapter;if(!s?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${n} action_id=${e.action_id}`);const o=await s.execCommand("compact","",n);o.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:o.message,data:o.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.runtimeError,error_msg:o.message??"compact failed"})}catch(i){u.warn(this.name,`thread_compact error session_id=${n}: ${i instanceof Error?i.message:i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f.runtimeError,error_msg:i instanceof Error?i.message:String(i)})}}async handleGetRateLimits(e,n){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const i=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),s=this.cachedAcpContextWindow;if(i&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:s,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const o=await re();this.cachedProviderQuota=o,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${o.success}`+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:s,tokenUsage:null,providerQuota:o}})}catch(o){u.warn(this.name,`[rate-limits] kiro quota query failed: ${o instanceof Error?o.message:String(o)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:s,tokenUsage:null}})}return}switch(t){case"codex":{const i=this.maybeQueryProviderQuota(),s=this.getFreshCodexGlobalRateLimitCache();if(s.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(s.hasData){s.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${s.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${s.rateLimits.primary.resetsAt} secondary=${s.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${s.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!s.contextWindow} hasToken=${!!s.tokenUsage}`);const l=await i;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:s.hasData||!!l,cached:!0,sampledAt:s.sampledAt,rateLimits:s.rateLimits,contextWindow:s.contextWindow,tokenUsage:s.tokenUsage,providerQuota:l}});return}const r=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(r&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${r.sessionId}`),(await r.adapter.handleLocalAction?.(e))?.handled))return;const a=this.resolveRateLimitWakeSessionId(n,t);if(a){const l=await this.wakeRateLimitSlot(a,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await i,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const i=this.maybeQueryProviderQuota(),s=this.getFreshClaudeRateLimitState();if(s){const c=s.rateLimits,l=await i;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${s.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:s.sampledAt,rateLimits:s.rateLimits??null,contextWindow:s.contextWindow,tokenUsage:null,providerQuota:l}});return}let o=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof B)??null;if(!o){const c=this.resolveRateLimitWakeSessionId(n,t);c&&(o=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${n} adapterType=claude hasSlot=${!!o} hasAdapter=${!!o?.adapter}`);const r=o?.adapter,a=r instanceof B?r.getSessionState():null,d=await i;if(a){(a.rateLimits?.fiveHour||a.rateLimits?.sevenDay||a.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=a);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!a.rateLimits?{...a,rateLimits:c.rateLimits}:a,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!a.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!r} adapterType=${r?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const s=(n?this.pool.getSlot(n):null)?.adapter;if(s instanceof N){await s.refreshAccountRateLimits({force:!0});const r=s.getRateLimitsSnapshot(n);u.info(this.name,`[rate-limits] cursor: available=${r.available} monthly=${r.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${r.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r});return}const o=await Fe();u.info(this.name,`[rate-limits] cursor(no-slot): available=${o.available} monthly=${o.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${o.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(o.error?` error=${o.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:o.available,cached:!1,sampledAt:Number.isFinite(Date.parse(o.sampledAt))?Date.parse(o.sampledAt):Date.now(),rateLimits:o.rateLimits,contextWindow:null,tokenUsage:null,...o.displayMessage?{displayMessage:o.displayMessage}:{},...o.error?{error:o.error}:{}}});return}case"agy":{const i=await X(this.config.agent.command,!0).catch(()=>J(this.config.agent.command)),s=n?this.buildAgyToolbarMeta(n,i):{...this.buildAgyQuotaMeta(i)},o=n?this.bindingStore.get(n):void 0;o?.cwd&&this.sendAgyBindingCard(n,o.cwd,s),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"agy",available:!!i.rateLimits,cached:!1,sampledAt:i.sampledAt??null,rateLimits:i.rateLimits?{primary:i.rateLimits.primary,secondary:i.rateLimits.secondary,sampledAt:i.sampledAt??Date.now()}:null,extraLimits:i.rateLimits?.extras??[],contextWindow:null,tokenUsage:null,...i.plan!==void 0?{plan:i.plan}:{},...i.quota_exhausted!==void 0?{quota_exhausted:i.quota_exhausted}:{},...i.quota_reset_at!==void 0?{quota_reset_at:i.quota_reset_at}:{},...i.available_credits!==void 0?{available_credits:i.available_credits}:{}}});return}default:{const i=this.sessionProviderHints.get(n),s=this.sessionBindings.get(n)||this.bindingStore.get(n)?.cwd;if(i&&s&&!i.disabled){await this.refreshProviderQuotaForSession(n,s,!0);const a=this.sessionProviderQuotas.get(n),d=a?.quota??null;if(!d){u.info(this.name,`[rate-limits] no session provider quota available for adapterType=${t} session=${n}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] session provider quota queried: provider=${d.provider} success=${d.success}`+(d.tiers.length>0?` tiers=${d.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(d.error?` error=${d.error}`:"")+` session=${n}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!1,sampledAt:a?.sampledAt??null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:d}});return}const o=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,r=await this.maybeQueryProviderQuota();if(!r){u.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] provider quota ${o?"cached":"queried"}: provider=${r.provider} success=${r.success}`+(r.tiers.length>0?` tiers=${r.tiers.map(a=>`${a.name}=${a.usedPercent}%`).join(",")}`:"")+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:o,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:r}});return}}}resolveRateLimitWakeSessionId(e,n){const t=String(e??"").trim(),i=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return i?t&&t===i?t:n==="codex"||n==="claude"?(t&&t!==i&&u.info(this.name,`[rate-limits] ${n} remap wake session: requested=${t} use_recent=${i}`),i):t&&t!==i?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=not_recent_session recent=${i}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${n} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,n){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=binding_cwd_missing`),null;try{const s=await this.pool.getOrCreateSlot(t);if(!s)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=slot_unavailable`),null;if(s.startPromise){const o=n==="claude"?6e4:2e4;await Promise.race([s.startPromise,new Promise((r,a)=>setTimeout(()=>a(new Error(`wake rate-limits slot timeout (${o}ms)`)),o))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${n}`),this.pool.getSlot(t)??s}catch(s){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${n} err=${s instanceof Error?s.message:String(s)}`),null}}sessionControlCtx(e){const n=this.pool.getSlot(e),t=n?.adapter instanceof R?n.adapter:null,i=(this.config.adapterType??"acp")==="acp",s={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:o=>t?t.setMode(o):Promise.resolve(!1),setModel:o=>t?t.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>ke(s,o,r):void 0,acpSetModel:i?(o,r)=>Ee(s,o,r):void 0,getPendingApproval:o=>{const r=t?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>t?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(t&&t.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{u.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&n?.adapter instanceof he?(n.adapter.cancelCurrentRun(),Promise.resolve()):n?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):j.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):j.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendEventResult:(n,t,i)=>this.aibotHandle.sendEventResult({event_id:n,status:t,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(n,t,i,s,o)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...i?{result:i}:{},...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,n){this.sendCtrl.finalizeThinking(e,n)}logInboundConversation(e){const n=String(e.session_id??"").trim();n&&this.conversationLog?.logInbound(n,{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,n){const t=n instanceof Error?n.message:String(n),i=(()=>{const a=Te(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),s=n instanceof Vi||n instanceof zi,o=n instanceof Xi&&i,r=o?"audit_config_invalid":s?n.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r,msg:t,updated_at:Date.now()}),s||o)try{this.aibotHandle.sendAuditState(G({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:t},Date.now()))}catch{}}markAuditAdapterClosed(e,n){const i=this.pool.getSlot(n)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,n,t){const i=this.buildInboundEvent(e,n),s=this.bindingStore.get(e.session_id),o=s?this.resolveAgentSessionId(s):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,d=this.auditController.startTurn({session:t,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return d&&(i.audit={enabled:!0,auditId:d.auditId,turnId:d.turnId,...t?{scope:t.options.scope,profile:t.options.profile,...t.options.retentionDays===void 0?{}:{retentionDays:t.options.retentionDays},capture:{...t.options.capture}}:{},rawProviderBody:t?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,n){const t=Ii(this.sendCtrl.getGlobalRuntimeConfig(),n),i=Ji(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const n=e.filter(t=>!di(String(t?.content??"")));if(n.length!==0)return JSON.stringify(n)}isStaleEvent(e){const n=Number(e.created_at);return!Number.isFinite(n)||n<=0?!1:Date.now()-n>Zi}async handleConnectorRollback(e){let n=null,t=!1,i=!1,s=String((e.params??{}).target_version??"").trim();const o=String((e.params??{}).reason??"server_initiated");if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${s} reason=${o}`);try{const{UpgradeError:r,armWindowsUpgradeHandoff:a,normalizeUpgradeVersion:d,npmInstall:c,pendingExists:l,upgradeLog:h,verifyInstalledVersion:g,writePending:m}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:p}=await import("../core/util/client-version.js");s=d(s);const _=p(),b=process.platform==="win32";if(l())throw new r("UPGRADE_IN_PROGRESS","Another connector upgrade transaction is already active");if(b){const w=["upgrade-guardian.mjs","upgrade-guardian.fallback.mjs"].map(A=>$.join(I.base,"bin",A)).find(A=>ce(A));if(process.env.GRIX_WRAPPER_SUPERVISED!=="1"||!w||!this.daemonShutdownRequester)throw new r("WINDOWS_UPGRADE_UNSUPPORTED","Windows rollback requires a refreshed managed wrapper and external guardian")}h(`server rollback: ${_} -> ${s} reason=${o}`);const k=m(_,s,b?"preparing":void 0).transaction_id;if(!k)throw new r("INVALID_UPGRADE_STATE","Upgrade transaction has no owner ID");if(n=k,(await c("grix-connector",s))?.activationRequired||g(s),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,target_version:s}}),i=!0,t=!0,!await this.waitUntilLifecycleIdle("connector_rollback"))throw h("server rollback: aborted before idle restart (instance stopped, idle wait timed out, or work arrived)"),new r("UPGRADE_ABORTED","Connector rollback was aborted before lifecycle handoff");if(b){if(!["upgrade-guardian.mjs","upgrade-guardian.fallback.mjs"].some(A=>ce($.join(I.base,"bin",A))))throw new r("WINDOWS_UPGRADE_UNSUPPORTED","Windows external guardian disappeared before lifecycle handoff");a(process.pid,k),await this.daemonShutdownRequester("upgrade")}else process.kill(process.pid,"SIGTERM")}catch(r){try{const{discardPendingStaging:d,finalizePendingTransaction:c,readPending:l,removePending:h,removeWindowsHandoffFiles:g,rollbackPendingInstall:m}=await import("../core/upgrade/npm-upgrader.js"),p=l(),_=!!(n&&p?.transaction_id===n);_&&process.platform==="win32"?(g(),d(p)):_&&m(p),_&&(process.platform==="win32"?c(p):h(n))}catch{}t&&this.lifecycleAdmissionRestorer?.();const a=r instanceof Error?r.message:String(r);u.error(this.name,`connector_rollback failed: ${a}`),i||this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"ROLLBACK_FAILED",error_msg:a})}}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=>{u.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}getRelayStateSyncer(){const e=this.relayStateApplyPorts;return!e||!this.aibotHandle||this.isSharedInstance()?null:(this.relayStateSyncer||(this.relayStateSyncer=new Rt({...e,sendSyncRequest:(n,t)=>{const{anthropicBaseUrl:i,openaiBaseUrl:s}=te(this.aibotConfig.url);return this.aibotHandle.relayStateSyncRequest({anthropic_base_url:i,openai_base_url:s,...n},t)},sendCredentialRequest:(n,t)=>{const{anthropicBaseUrl:i,openaiBaseUrl:s}=te(this.aibotConfig.url);return this.aibotHandle.relayCredentialRequest({anthropic_base_url:i,openai_base_url:s,...n},t)},sendReport:n=>this.aibotHandle.sendRelayStateReport(n),log:{info:n=>u.info(this.name,n),warn:n=>u.warn(this.name,n)}})),this.relayStateSyncer)}relayStateSyncOnConnect(){const e=this.getRelayStateSyncer();e&&e.syncOnConnect().catch(n=>{u.warn(this.name,`relay state sync failed: ${n instanceof Error?n.message:String(n)}`)})}reportRelayStateLocalChange(){try{this.getRelayStateSyncer()?.reportLocalChange()}catch{}}async handleApplyRelayState(e){const n=e.params??{},t=n.enabled,i=Number(n.revision);if(typeof t!="boolean"||!Number.isFinite(i)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"INVALID_PARAMS",error_msg:"enabled (boolean) and revision (number) are required"});return}const s=this.getRelayStateSyncer();if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"RELAY_UNAVAILABLE",error_msg:"relay state sync is not available on this agent",result:{revision:i}});return}const o=await s.applyFromLocalAction({enabled:t,model:typeof n.model=="string"?n.model:void 0,revision:i});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:o.ok?"ok":"failed",result:{revision:o.revision},...o.error_code?{error_code:o.error_code}:{},...o.error_msg?{error_msg:o.error_msg}:{}})}async fetchRelayCredential(e){const n=this.aibotHandle;if(!n||n.status!=="ready")throw new Et("agent websocket is not connected","OFFLINE");const{anthropicBaseUrl:t,openaiBaseUrl:i}=te(this.aibotConfig.url);return kt((s,o)=>n.relayCredentialRequest(s,o),{anthropic_base_url:t,openai_base_url:i,...e.model?{model:e.model}:{}})}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{zs as AgentInstance};
9
+ Error: ${s}`,1,!1))}sendEventResultWithCleanup(e,t,s,i,n=!1){const o=this.eventSessionIndex.get(e);n&&this.surfacedRunErrorEvents.add(e),t==="failed"&&o&&s?.trim()&&this.sendRunErrorAsChunk(e,o,s),this.auditController.markResponded(e,t,s),this.sendCtrl.sendEventResult(e,t,s,i),o&&(this.pool.eventComplete(e,o)===!1&&p.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${t}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,t,s),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{p.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:s,errorMsg:i}=e;if(this.stopped)return;const n=this.inflightEvents.get(t);if(!n){p.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${s}; surface failure directly`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const r=this.config.adapterType??"acp";if(o>q){p.error(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}p.info(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(s);a.length>0&&p.info(this.name,`[recovery] session=${s} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(s)}catch(l){p.warn(this.name,`[recovery] removeSlot failed session=${s}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=e.replayOriginalContent?n.content:this.resolveRecoveryPrompt(r,n),d={...n,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){p.error(this.name,`[recovery] redeliver failed event=${t} session=${s}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(t,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){p.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${s}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,s){this.sendCtrl.sendThinking(e,t,s)}bufferStreamChunk(e,t,s,i,n){this.auditController.captureUnsequencedStreamChunk(e,s),this.sendCtrl.bufferOnly(e,t,s,i,n)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(i=>i.event.event_id).filter(Boolean)),s=[];p.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const n=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)):(this.restorePendingReplayAuditTurn(n),this.deferredMgr.defer(i.channel,i.sessionId,n),s.push(i))}else await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);p.error(this.name,`Pending event replay failed event=${n.event_id}: ${r}`),this.sendEventResultWithCleanup(n.event_id,"failed",r),this.pendingEvents.markCanceled(n.event_id),await this.pendingEvents.remove(n.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(t,[...s,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,s))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const s=Ri({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!s.enabled)return;const i=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:s,createdAt:new Date().toISOString()}),n=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});n&&(e.audit={...t,auditId:n.auditId,turnId:n.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const s=this.eventSessionIndex.get(e);return s?(s!==t&&p.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${s} supplied=${t}`),s):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const s=e.codex_payload?.params?.delta;if(!s)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:s.length,content:s})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,s){this.shouldDropAcpRawDisplayEvent(e,s.type)||this.deliverRawEventEnvelope(e,t,s,"acp",this.buildAcpRawEventFallbackText(s))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,s,i,n){const o=fi({envelope:s,fallbackText:n,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}p.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,mi({envelopeType:s.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{p.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),s=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(s.tool_title??s.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(s.tool_name??s.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(s.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,s,i){this.sendCtrl.sendToolExecutionCard(e,t,s,i)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${B()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,s){const i=s.questions.map(o=>o.header).join(", "),n=X(`[Agent Question] ${s.request_id}`,"agent_question",s);this.aibotHandle.sendText({event_id:e,session_id:t,content:n,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const t=Kn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=i instanceof y?"acp":i instanceof F?"opencode":this.config.adapterType??"unknown",o=i instanceof F?i.handleQuestionReplyEvent(t):i instanceof y?await i.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(p.info(this.name,`[${n}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${n}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${o.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode??"interaction_reply_failed",msg:o.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=jn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=t.params,o=String(n.tool_call_id??n.approval_command_id??n.approval_id??n.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.handleExecApprovalEvent({...n,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return r.delivered?(p.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${o||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const t=this.config.adapterType??"acp",s=Un(e);let i;if(s&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const n=li(e.extra);if(n.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:n.error,updated_at:Date.now()});return}const o=n.patch,r=V(e.extra);if((r.state!=="absent"||r.error)&&p.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,g=h.extra,u=h.audit??(g&&typeof g=="object"?g.audit:void 0);return!u||typeof u!="object"?!1:u.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&t!=="claude"&&t!=="codex"&&t!=="cursor"&&t!=="opencode"&&t!=="pi"&&t!=="codewhale"&&t!=="deepseek-harness"&&t!=="agy"&&t!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${t}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${t}`},Date.now()))}catch{}return}if(s){if(r.state!=="absent"||s.verb===S.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(s.verb===S.exec){await this.handleSessionControlCommand(s,e);return}if(s.verb===S.listSessions){await this.handleListSessionsTextCommand(e);return}if(s.verb===S.unbind){await this.handleUnbindTextCommand(e);return}if(t==="claude"){await this.handleSessionControlCommand(s,e);return}if(t==="codex"&&s.verb===S.open){await this.handleCodexSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.open){await this.handlePiSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.restart){await this.handlePiSessionControlRestart(e);return}if((t==="openhuman"||t==="opencode")&&s.verb===S.open){await this.handleOpenHumanSessionControlOpen(s,e);return}if(t==="codewhale"&&s.verb===S.open){await this.handleCodeWhaleSessionControlOpen(s,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===S.open){const l=s.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=T.resolve(l);if(!(await Q(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const g=String(h?.code??""),u=g==="ENOENT"?`Directory does not exist: ${T.resolve(l)}`:g==="EACCES"||g==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:u,updated_at:Date.now()});return}}if(s.verb===S.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await Q(l.cwd)}catch{p.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const h=this.pool.getSlot(e.session_id);h?.adapter instanceof y&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(s,e),t==="acp"&&s.verb===S.stop){const h=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${h}`,updated_at:Date.now()});return}if(Nn(s,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===S.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),t==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(ee.has(t)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),ee.has(t)&&!this.bindingStore.get(e.session_id)?.cwd){const h=t,g=this.prepareAuditedInboundEvent(e,o,a);p.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const f=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:g});if(this.lifecycleBarrier.isClosed()&&!f)throw new Error("pending event store unavailable during lifecycle drain")}catch(f){const b=f instanceof Error?f.message:String(f);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",b,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:b,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(g,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),g);const u=this.resolveBindingChannelKey(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,g,u]=h,b=this.pool.getSlot(e.session_id)?.adapter;if(b?.execCommand&&(b.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await b.execCommand(g,u.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&K(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof W&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(p.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):p.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),p.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{p.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,t){const s=t instanceof Error?t.message:String(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",s,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:s,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return xt(this,e,t)}handleSessionControlForPool(e,t){return Dt(this,e,t)}handleSessionControlLocalActionForPool(e){return Mt(this,e)}handleCodexSessionControlLocalActionOpen(e){return Ht(this,e)}handleCursorSessionControlLocalActionOpen(e){return Lt(this,e)}handlePiSessionControlOpen(e,t){return $t(this,e,t)}handlePiSessionControlRestart(e){return It(this,e)}handlePiSessionControlRestartLocalAction(e){return Qt(this,e)}syncOpenCodeBinding(e,t){return Ot(this,e,t)}isWorkspaceFreeClient(){return Bt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Ft(this,e,t)}bindSessionForPool(e,t){return qt(this,e,t)}deferredCallbacks(){return Ut(this)}handleOpenHumanSessionControlOpen(e,t){return Nt(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Wt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Gt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return jt(this,e)}normalizeClaudeModeId(e){return dn(this,e)}handleExecCommandOptions(e,t,s){ln(this,e,t,s)}resolveSessionModelId(e){return cn(this,e)}resolveSessionModeId(e){return hn(this,e)}resolveCursorSessionModeId(e){return un(this,e)}resolveClaudeSessionEffort(e){return pn(this,e)}resolveClaudeSessionModeId(e){return gn(this,e)}currentClaudeModeId(e){return fn(this,e)}resolveCodexSessionModelId(e){return mn(this,e)}resolveCodexNewSessionGlobalDefault(e,t,s){return vn(this,e,t,s)}pinCodexGlobalDefault(e,t){return _n(this,e,t)}buildCursorToolbarMeta(e){return Sn(this,e)}buildAgyToolbarMeta(e,t){return bn(this,e,t)}buildAgyQuotaMeta(e){return Cn(this,e)}sendAgyBindingCard(e,t,s){return wn(this,e,t,s)}refreshAndPushAgyQuota(e,t=!1){return An(this,e,t)}handleAgySetModel(e,t){return En(this,e,t)}buildClaudeToolbarMeta(e){return kn(this,e)}providerQuotaToCodexRateLimits(e){return pi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const t=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t))){const n=new Error(`Specified path is not valid on this host: ${t}`);throw n.cwdErrorCode=E.invalidCwd,n}const s=T.resolve(t);let i;try{i=await Q(s)}catch(n){const o=String(n?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${s}`);throw r.cwdErrorCode=E.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=E.invalidCwd,r}throw n}if(!i.isDirectory()){const n=new Error("Specified path is not a directory.");throw n.cwdErrorCode=E.invalidCwd,n}try{return await te(s)}catch{return s}}failSessionOpen(e,t){const{code:s,msg:i}=Jn(e);return this.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(s,i),{code:s,msg:i}}maybeOfferCliInstall(e){ot(this,e)}handleCliInstallQuestionReply(e){return rt(this,e)}handleCliInstallInteractionReply(e){return at(this,e)}runConfirmedCliInstall(e,t){return dt(this,e,t)}getClaudeWorkerStatus(e){const t=this.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,t){const s=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,s),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:s,cwd:t,meta:this.buildClaudeToolbarMeta(e)}),s}handleSkillDeleteLocalAction(e){return Jt(this,e)}handleSkillUploadLocalAction(e){return Yt(this,e)}handleSkillEnableLocalAction(e){return Xt(this,e)}handleSkillRefreshLocalAction(e){Vt(this,e)}handleSkillDisableLocalAction(e){return Zt(this,e)}computeSkillReport(e){return en(this,e)}reportSessionSkills(e){tn(this,e)}skillsSyncGroupKey(){return nn(this)}forceRefreshSkills(e,t){return sn(this,e,t)}adoptSkillsWireHashFromDisk(){on(this)}buildLibrarySkillsReport(e){return rn(this,e)}skillLookupEnv(){return an(this)}async ensureSlotStarted(e,t=6e4){const s=await this.pool.getOrCreateSlot(e);if(!s)throw new Error("Failed to allocate session slot");s.startPromise&&(p.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([s.startPromise,new Promise((i,n)=>setTimeout(()=>n(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),p.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const t=Ie(e);if(!t)return;const s=this.reasonixTitleScan.get().filter(i=>i.stamp===t);return s.length===1?s[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(s=>s.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,t){const s=String(e??"").trim(),i=String(t??"").trim();if(!s||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(s,i);break;case"codex":this.bindingStore.setCodexThreadId(s,i);break;case"pi":this.bindingStore.setPiSessionPath(s,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(s,i);break;case"agy":this.bindingStore.setAgyConversationId(s,i);break;default:this.bindingStore.setAcpSessionId(s,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const t=String(e??"").trim();if(!t)return"";const s=T.resolve(t);return process.platform==="win32"?s.toLowerCase():s}ensureImportedAgentSession(e,t){const s=String(e??"").trim();if(!s)return;const i=this.normalizePathForCompare(t);let n="";const o=this.config.adapterType??"acp";if(o==="codex"?n=this.sessionScanCache.get().find(c=>c.threadId===s)?.cwd??"":o==="claude"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="cursor"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="acp"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="deepseek-harness"&&(n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??""),!n){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===s){n=a.cwd??"";break}}if(!n){const a=new Error(`agent session not found: ${s}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}const r=this.normalizePathForCompare(n);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${t}, got ${n}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}}buildOpenedBindingResult(e,t,s="ready"){const i=this.bindingStore.get(e),n=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:t,workerStatus:s};return n&&(o.bindingId=n,o.agentSessionId=n),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const t=this.globalConfigStore?.get(this.name),s=this.bindingStore.get(e),i=this.config.adapterOptions??{},n=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const R=ve(t?.dshAgentPreset,he);this.bindingStore.setDshAgentPreset(e,R)}const o=this.bindingStore.getDshSelectedProfile(e),r=Se({binding:o,global:t?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),c=this.bindingStore.getDshSettings(e),d=c?.providerId??t?.dshProviderId,l=_e({dataRoot:a,providerId:d}),h=[c?.modelId,t?.dshModelId,l.models[0]?.id].find(R=>!!R&&l.models.some(C=>C.id===R))??l.models[0]?.id,g=j(s?.dshModeId,t?.dshModeId),u={};!s?.dshProviderId&&l.providerId&&(u.providerId=l.providerId),!s?.dshModelId&&h&&(u.modelId=h),s?.dshModeId||(u.modeId=g),s?.dshThinking||(u.thinking=me(t?.dshThinking)??"enabled"),s?.dshReasoningEffort||(u.reasoningEffort=fe(t?.dshReasoningEffort)??"high"),Object.keys(u).length>0&&this.bindingStore.updateDshSettings(e,u);const f=this.bindingStore.getDshSettings(e);let b=[],v=[],m=!1;try{b=ue({dshHome:n,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),m=!1}catch{}const w=T.join(a,"dsh-session-skills");return we(w),v=pe({skillsDir:w,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),ce({agentPreset:f?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:ge({dshHome:n}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:b,skills:v,pluginRestartRequired:m,providerId:f?.providerId??l.providerId,modelId:f?.modelId??h,modeId:j(this.bindingStore.get(e)?.dshModeId,t?.dshModeId),thinking:f?.thinking,reasoningEffort:f?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return T.join(L.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}unbindSession(e){return Et(this,e)}handleUnbindTextCommand(e){return kt(this,e)}handleUnbindLocalAction(e){return Rt(this,e)}handleListSessionsTextCommand(e){return yt(this,e)}handleListSessionsLocalAction(e){return Pt(this,e)}handleSyncHistoryLocalAction(e){return Tt(this,e)}handleSessionControlCommand(e,t){return it(this,e,t)}handleSessionControlLocalAction(e){return st(this,e)}handleEventCancel(e){return lt(this,e)}waitForEventDone(e,t,s){return ct(this,e,t,s)}handleAibotStop(e){ht(this,e)}killAndResumeStopSlot(e,t){return ut(this,e,t)}handleAibotRevoke(e){return pt(this,e)}handleConfigureGatewayProvider(e){return gt(this,e)}getAuditLocalActionHandler(){return ft(this)}handleAuditLocalAction(e){return mt(this,e)}handleConnectorRollback(e){return vt(this,e)}getRelayStateSyncer(){return _t(this)}relayStateSyncOnConnect(){St(this)}reportRelayStateLocalChange(){bt(this)}handleApplyRelayState(e){return Ct(this,e)}fetchRelayCredential(e){return wt(this,e)}isSharedInstance(){return At(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",s=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();p.debug(this.name,`local_action received action_type=${t} verb=${i||"-"} action_id=${e.action_id} session_id=${s}`);let n;if(t===k.sessionControl&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===k.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Ce(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===k.sessionControl&&i===S.exec&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl&&i===S.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===k.sessionControl&&i===S.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===k.sessionControl&&i===S.unbind){await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(t===k.interactionReply||t==="exec_approve"||t==="exec_reject")||r&&t===k.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl){const u=this.config.adapterType??"acp",f=u==="codex",b=u==="pi",v=String((e.params??{}).verb??"").trim().toLowerCase();if(f&&v===S.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(u==="cursor"&&v===S.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(f&&v==="restart"){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:s,cwd:_,workerStatus:"ready"}}});return}if(b&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.ensureSlotStarted(s).catch(H=>{if(zn(H))throw H;p.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${H instanceof Error?H.message:String(H)}`)}),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:A}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(b&&v===S.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((u==="openhuman"||u==="opencode")&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.syncOpenCodeBinding(s,A),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(u==="codewhale"&&v===S.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(u==="deepseek-harness"&&v===S.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(u==="acp"&&v===S.stop){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:s,cwd:_,workerStatus:"stopped"}}});return}try{if(v===S.open){const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=String(C.agent_session_id??"").trim();if(A){const x=await this.resolveCwdForBinding(_);this.ensureImportedAgentSession(A,x)}}await this.handleSessionControlLocalActionForPool(e)}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})});return}if(v===S.open){const C=e.params??{},_=await this.resolveCwdForBinding(String(C.cwd??"").trim());this.setResolvedAgentSessionId(s,String(C.agent_session_id??"").trim()),u==="agy"&&(this.bindingStore.set(s,_),this.sessionBindings.set(s,_)),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,_)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(s,_),this.refreshAndPushAgyQuota(s,!0))}else Wn(e,this.sessionControlCtx(s),this.sessionControlSenders(s));return}if(t==="file_list"){const u=Date.now(),f=s?this.bindingStore.get(s)?.cwd:void 0,b=e.params??{},v=String(b.parent_id??"").trim(),m=Array.isArray(b.allowed_extensions)?b.allowed_extensions.filter(_=>typeof _=="string").map(_=>_.trim()).filter(_=>_.length>0):[];p.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${s} parent_id=${v||"<root>"} show_hidden=${!!b.show_hidden} ext_count=${m.length} bound_cwd=${f??"<none>"}`);const w=await Vn({parent_id:v||null,session_id:s,show_hidden:!!b.show_hidden,allowed_extensions:m},{resolveCwd:()=>f??this.config.agent.cwd??process.cwd(),fallbackDir:Y()}),R=Date.now()-u,C=w.result?.files?.length??0;p.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${w.status} elapsed=${R}ms count=${C} current_path=${w.result?.current_path??""} error_code=${w.error_code??""} error_msg=${w.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:w.status,...w.result?{result:{...w.result,machine_name:ti()}}:{},...w.error_code?{error_code:w.error_code}:{},...w.error_msg?{error_msg:w.error_msg}:{}});return}if(t==="create_folder"){const u=s?this.bindingStore.get(s)?.cwd:void 0,f=String((e.params??{}).parent_id??"").trim(),b=String((e.params??{}).name??"").trim(),v=await Zn({parent_id:f||null,name:b,session_id:s},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:Y()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:v.result}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(t===k.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,s);return}if(t===k.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetSessionUsage(e,s);return}if(t===k.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetRateLimits(e,s);return}const a=(this.config.adapterType??"acp")==="acp",c=(this.config.adapterType??"acp")==="cursor";if((o||a||c)&&t===k.threadCompact){await this.handleThreadCompact(e,s);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===k.getAgentGlobalConfig){const u=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...u?{config:u}:{config:null}}});return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",l=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!s&&!!this.bindingStore.get(s)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const u=String((e.params??{}).mode_id??"");u&&(d==="cursor"?(this.bindingStore.setCursorModeId(s,u),this.globalConfigStore?.set(this.name,{cursorModeId:u})):d==="claude"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):d==="opencode"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):I.has(d)?d==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:u}):this.globalConfigStore?.set(this.name,{acpInitialMode:u}))}else if(h.kind==="set_model"){const u=String((e.params??{}).model_id??"").trim();if(u){d==="cursor"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="opencode"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codewhale"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:u,codexReasoningEffort:void 0}):I.has(d)||this.globalConfigStore?.set(this.name,{modelId:u});const f=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(s,u,f)}}else if(h.kind==="set_reasoning_effort"){const u=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");u&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:u})}else if(h.kind==="set_sandbox_mode"){const u=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(u){const f=u==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexSandboxMode:f})}}else if(h.kind==="set_service_tier"){const u=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(u){const f=u.toLowerCase()==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexServiceTier:f})}}return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&s&&!this.bindingStore.get(s)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){const u=this.sessionControlSenders(s),f=this.pool.getSlot(s)?.adapter,b={bindingStore:this.bindingStore,acpAdapter:f instanceof y?f:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};if(t==="set_mode"){const v=String((e.params??{}).mode_id??""),m=await J(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R)}}else{const v=String((e.params??{}).model_id??""),m=await z(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(s,v)}}return}const g=!!s&&!!this.pool.getSlot(s);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{n?.()}}handleGetSessionUsage(e,t){return Kt(this,e,t)}handleThreadCompact(e,t){return zt(this,e,t)}handleGetRateLimits(e,t){return Qn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return On(this,e,t)}wakeRateLimitSlot(e,t){return Bn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),s=t?.adapter instanceof y?t.adapter:null,i=(this.config.adapterType??"acp")==="acp",n={bindingStore:this.bindingStore,acpAdapter:s,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(s)return s.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!s?.isAlive(),getAcpSessionOptions:()=>s?.acpSessionOptions??null,setMode:o=>s?s.setMode(o):Promise.resolve(!1),setModel:o=>s?s.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>J(n,o,r):void 0,acpSetModel:i?(o,r)=>z(n,o,r):void 0,getPendingApproval:o=>{const r=s?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>s?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(s&&s.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{p.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof G?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,s)=>this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()}),sendEventResult:(t,s,i)=>this.aibotHandle.sendEventResult({event_id:t,status:s,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,s,i,n,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...i?{result:i}:{},...n?{error_code:n}:{},...o?{error_msg:o}:{}},e)}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const s=t instanceof Error?t.message:String(t),i=(()=>{const a=V(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),n=t instanceof ki||t instanceof Ei,o=t instanceof Pi&&i,r=o?"audit_config_invalid":n?t.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r,msg:s,updated_at:Date.now()}),n||o)try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:s},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const i=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,t,s){const i=this.buildInboundEvent(e,t),n=this.bindingStore.get(e.session_id),o=n?this.resolveAgentSessionId(n):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:s,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return c&&(i.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,...s?{scope:s.options.scope,profile:s.options.profile,...s.options.retentionDays===void 0?{}:{retentionDays:s.options.retentionDays},capture:{...s.options.capture}}:{},rawProviderBody:s?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,t){const s=di(this.sendCtrl.getGlobalRuntimeConfig(),t),i=yi(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:s.responseDelivery,tool_events:s.toolEvents,thinking_events:s.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(s=>!Gn(String(s?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Ti}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{p.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{ao as AgentInstance};