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