grix-connector 3.8.2 → 3.8.3
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/adapter/claude/claude-adapter.js +1 -1
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/codex/codex-bridge.js +8 -7
- package/dist/bridge/adapter-pool.js +1 -1
- package/dist/bridge/bridge.js +5 -5
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/persistence/session-binding-store.js +1 -1
- package/dist/log.js +2 -2
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
package/dist/bridge/bridge.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import T from"node:path";import{realpath as j,stat as H}from"node:fs/promises";import{tmpdir as V}from"node:os";import{randomUUID as M}from"node:crypto";import{ConnectionManager as Y}from"../core/aibot/index.js";import{ClaudeAdapter as y}from"../adapter/claude/index.js";import{CodexAdapter as J}from"../adapter/codex/index.js";import{PiAdapter as X}from"../adapter/pi/index.js";import{AcpAdapter as A}from"../adapter/acp/index.js";import{OpenHumanAdapter as Z}from"../adapter/openhuman/index.js";import{CursorAdapter as I}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as U}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as ee}from"../adapter/opencode/index.js";import{AgyAdapter as O}from"../adapter/agy/index.js";import{getCachedAgyModels as te}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as ie}from"../adapter/agy/quota.js";import{LOCAL_ACTION_ERROR_CODES as x,LOCAL_ACTION_TYPES as b,SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as p,SESSION_MODE_IDS as C}from"../adapter/claude/protocol-contract.js";import{parseClaudeSessionUsage as ne}from"../adapter/claude/usage-parser.js";import{resolveSkillScanMode as se}from"../adapter/claude/skill-scanner.js";import{buildReportedSkills as oe}from"../default-skills/index.js";import{fetchAvailableModels as D,getCachedModels as Q,readSettingsEnv as re}from"../adapter/claude/model-list.js";import{parseAcpSessionUsage as ae}from"../adapter/acp/usage-parser.js";import{applyProxyEnv as de,getProxyManager as ce,relayHostsForClientType as le,buildGatewayRoute as ue}from"../core/proxy/index.js";import{buildProviderEnv as he}from"../core/config/provider-env.js";import{sweepNativeProviderResidue as ge}from"./native-provider-sweep.js";import{parseCodexSessionUsage as me}from"../adapter/codex/usage-parser.js";import{readCodexProviderSettings as pe}from"../adapter/codex/codex-trust.js";import{scanCodexSessions as fe}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as _e}from"../adapter/claude/session-scanner.js";import{scanAcpSessions as ve}from"../adapter/acp/session-scanner.js";import{parsePiSessionUsage as Se}from"../adapter/pi/usage-parser.js";import{SessionScanCache as L,resolveCodexLeafDirs as be,resolveClaudeLeafDirs as we,resolveAcpLeafDirs as Ce}from"./session-scan-cache.js";import{log as u,ConversationLog as Ae,AgentApiPacketLog as ke,BridgeEventLog as Re}from"../core/log/index.js";import{RevokeHandler as Ee}from"./revoke-handler.js";import{AdapterPool as $e,PoolFullError as ye}from"./adapter-pool.js";import{parseSessionControlCommand as xe,handleSessionControlCommand as q,handleSessionControlLocalAction as Te}from"./session-controller.js";import{handleAcpSetModel as W,handleAcpSetMode as N,resolveAcpInitialDefaults as Le}from"./acp-toolbar-persist.js";import{SessionBindingStore as Pe}from"../core/persistence/session-binding-store.js";import{handleFileListAction as He,handleCreateFolderAction as Me,serveLocalFile as Ie,realHomeDir as K}from"../core/files/index.js";import{getMachineName as De}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as Qe}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as Be}from"../core/persistence/active-event-store.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Fe,applyConnectorRuntimeConfigPatch as Ue,extractConnectorRuntimeConfigPatch as Oe}from"./runtime-config.js";import{SendController as qe}from"./send-controller.js";import{queryProviderQuota as z}from"../core/provider-quota/index.js";import{queryKiroQuota as B}from"../core/provider-quota/kiro.js";import{buildToolUseCard as E,buildToolResultCard as $,buildLocalGrixCardLink as We}from"./tool-card-utils.js";import{DeferredEventManager as Ne}from"./deferred-events.js";import{buildAgentProbeResult as Ke,PROBE_CACHE_TTL_STATIC_MS as ze,PROBE_CACHE_TTL_FULL_MS as Ge}from"./probe-helper.js";const je=600*1e3,Ve=60*1e3,G=30*1e3,Ye=10*1e3,P=new Set(["claude","acp","agy","cursor","codex"]),Je=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp"]),F=3;class jt{config;name;aibotHandle;aibotConfig;pool;stopped=!1;revokeHandler=new Ee;sessionBindings=new Map;deferredMgr;sendCtrl=new qe(Fe);bindingStore;globalConfigStore;upgradeTrigger=null;agentDeletedHandler=null;shareSetHandler=null;providerConfigHandler=null;agentProfile={agentName:"",introduction:""};activeEventStore;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";conversationLog=null;packetLog=null;kiroQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;sessionScanCache;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const o=Number(e);return o>0&&Date.now()-o<=Ve}async maybeQueryProviderQuota(){if(this.config.aibot.clientType==="kiro"){if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await B();return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] kiro queried: success=${t.success}`+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.planName?` plan=${t.planName}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] kiro query failed: ${t instanceof Error?t.message:String(t)}`),null}}let e=this.config.providerBaseUrl,o=this.config.providerApiKey;if((!e||!o)&&(this.config.adapterType??"acp")==="claude"){const t=re();e||(e=(t.ANTHROPIC_BASE_URL??"").trim()||void 0),o||(o=(t.ANTHROPIC_API_KEY??"").trim()||(t.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!e||!o)&&(this.config.adapterType??"acp")==="codex"){const t=pe();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if(!e||!o)return null;if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await z(e,o);return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] queried: provider=${t.provider} success=${t.success}`+(t.tiers.length>0?` tiers=${t.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] query failed: ${t instanceof Error?t.message:String(t)}`),null}}startKiroQuotaTimer(){this.kiroQuotaTimer||(this.kiroQuotaTimer=setInterval(()=>{if(this.stopped){this.stopKiroQuotaTimer();return}this.refreshAndPushKiroQuota().catch(()=>{})},G),u.info(this.name,`[kiro-quota-timer] started (interval=${G}ms)`))}stopKiroQuotaTimer(){this.kiroQuotaTimer&&(clearInterval(this.kiroQuotaTimer),this.kiroQuotaTimer=null,u.info(this.name,"[kiro-quota-timer] stopped"))}async refreshAndPushKiroQuota(){try{const e=await B();this.cachedProviderQuota=e,this.cachedProviderQuotaSampledAtMs=Date.now(),e.success&&this.pushKiroQuotaToBindings(e)}catch{}}pushKiroQuotaToBindings(e){const o=this.providerQuotaToRateLimits(e);for(const[t,n]of this.sessionBindings.entries()){if(!n)continue;const i={provider_quota:e};o&&(i.rate_limits=o);const s=this.cachedAcpContextWindow;s&&("usedPercentage"in s?i.context_window={usedPercentage:s.usedPercentage,remainingPercentage:100-s.usedPercentage}:i.context_window=s),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:n,meta:i})}}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,o=this.cachedCodexContextWindow,t=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:o,tokenUsage:t,hasData:!!(e||o||t)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,exhausted:this.pool?[...this.pool.getAllSlots()].some(o=>o.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let o=0,t=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let i=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{t=!0,i=!0,u.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),i||(o+=1)}return o>0&&u.info(this.name,`recycled ${o} adapter slot(s) so the new Grix relay env takes effect`),t?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const o=e.conversation?"full":"static",t=e.conversation?Ge:ze;if(!e.fresh){const a=this.probeCache.get(o);if(a&&Date.now()-a.sampledAt<t)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",i=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(i,e.timeoutMs??1e4):void 0;let r;try{r=await Ke({adapter:i,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{i.stop().catch(()=>{})}return this.probeCache.set(o,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,o){const t=Date.now(),n="__probe__",i=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||V(),r=()=>Date.now()-t;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof A)try{await e.bindSession(n,s)}catch{}let a=null;const d=new Promise(h=>{a=m=>{m===i&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:i,session_id:n,content:"ping",msg_id:i}),e.deliverStopEvent(i,n);let c=null;const l=await Promise.race([d.then(()=>!1),new Promise(h=>{c=setTimeout(()=>h(!0),o)})]);return c&&clearTimeout(c),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${o}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,o){this.config=e,this.name=e.name;const t=e.adapterType??"acp";this.aibotConfig={...e.aibot,...t==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","thread_compact","get_agent_global_config"]}:{}},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 Ae(e.logDir):null,this.packetLog=e.logDir?new ke(e.logDir):null,this.bindingStore=new Pe(e.bindingsPath),this.bindingStore.load(),this.globalConfigStore=o??null,this.deferredMgr=new Ne(this.name),this.activeEventStore=e.activeEventStorePath?new Be(e.activeEventStorePath):null,t==="codex"?this.sessionScanCache=new L(fe,be):t==="claude"?this.sessionScanCache=new L(_e,we):t==="agy"?this.sessionScanCache=new L(()=>[],()=>[]):this.sessionScanCache=new L(ve,Ce)}async start(){await ge({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&u.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{u.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),(this.config.adapterType??"acp")==="claude"&&(await D().catch(()=>{}),this.maybeQueryProviderQuota().catch(()=>{})),this.config.aibot.clientType==="kiro"&&(this.maybeQueryProviderQuota().catch(()=>{}),this.startKiroQuotaTimer()),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),await this.connectAibot(),this.sendCtrl.bind(this.aibotHandle);const e=this.config.adapterType??"acp";this.pool=new $e({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const t=this.createAdapter(e,o);return t instanceof A&&t.on("acpSessionReady",n=>{this.bindingStore.setAcpSessionId(o,n),this.sessionScanCache.invalidate()}),t},(o,t)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:t,received_at:Date.now()})}),this.pool.setEventStateHandler((o,t,n,i)=>{u.info(this.name,`[queue-debug] send event_state session=${t} event=${o} state=${n} queue_pos=${i?.queue_position??""} queue_total=${i?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:t,state:n,content_preview:i?.content_preview,queue_position:i?.queue_position,queue_total:i?.queue_total,actions:i?.actions,reason:i?.reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(t),(n==="canceled"||n==="failed")&&this.aibotHandle.sendEventResult({event_id:o,status:n==="canceled"?"canceled":"failed",msg:i?.reason,updated_at:Date.now()})}),this.pool.setQueueComposingHandler((o,t,n)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:t,...t?{ttl_ms:3e4,ref_event_id:n}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(t=>{u.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}),this.pool.setEventStartedHandler((o,t)=>{if(this.reportSessionSkills(t),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(t,"busy");const n=this.bindingStore.get(t);n?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"busy",cwd:n.cwd,meta:this.buildClaudeToolbarMeta(t)})}),this.pool.setEventDoneHandler((o,t)=>{const n=this.config.adapterType??"acp";if(n==="claude"){this.claudeWorkerStatus.set(t,"ready");const i=this.bindingStore.get(t);i?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)})}else if(n==="agy"){const i=this.bindingStore.get(t);if(i?.cwd){const s=this.buildAgyToolbarMeta(t),r=s?.available_models??[];u.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${t} model_id=${String(s?.model_id??"")} available_models=${r.length} meta_keys=${s?Object.keys(s).join(","):"<none>"}`),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:s})}else u.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${t}`)}}),this.pool.setSessionActivityHandler((o,t,n)=>{const i=this.selfDrivenSessions.has(o),s=this.selfDrivenLabels.get(o);t?(this.selfDrivenSessions.add(o),n&&this.selfDrivenLabels.set(o,n),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),i&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(i!==t||t&&n!==void 0&&n!==s)&&this.pushQueueSnapshotForSession(o)}),this.pool.startIdleSweep(),u.info(this.name,`Ready (adapter: ${e}, poolMax: ${this.config.poolMaxSize??20})`)}async stop(){this.stopped=!0,this.pool?.stopIdleSweep(),this.stopKiroQuotaTimer();const e=this.pool?.collectActiveEventIds()??[];e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const n of e)u.info(this.name,`Canceling active event on shutdown: ${n}`),this.sendEventResultWithCleanup(n,"canceled","process shutting down");e.length>0&&await new Promise(n=>setTimeout(n,100)),this.pool?.clearActiveEventsForShutdown();const o=this.deferredMgr.getAllDeferredEvents();for(const n of o)u.info(this.name,`Failing deferred event on shutdown: ${n.event_id}`),this.sendEventResultWithCleanup(n.event_id,"failed","process shutting down");const t=this.pool?.drainAllQueuedEvents()??[];for(const n of t)u.info(this.name,`Failing queued event on shutdown: ${n.event_id}`),this.sendEventResultWithCleanup(n.event_id,"failed","process shutting down");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()}resolveSpawnEnv(){const e=he(this.config.agent.clientType,this.config.agent.provider),o=this.config.agent.env,t=Object.keys(e).length>0?{...e,...o}:o;return de(t,this.name,this.config.agent.clientType)}createAdapter(e,o){switch(e){case"claude":return this.createClaudeAdapter(o);case"codex":return this.createCodexAdapter(o);case"pi":return this.createPiAdapter(o);case"openhuman":return this.createOpenHumanAdapter(o);case"codewhale":return this.createCodeWhaleAdapter(o);case"cursor":return this.createCursorAdapter(o);case"opencode":return this.createOpenCodeAdapter(o);case"agy":return this.createAgyAdapter(o);default:return this.createAcpAdapter(o)}}createCursorAdapter(e){const o={...this.config.adapterOptions??{}};o.bindingStore=this.bindingStore,o.aibotSessionId=e;const t=this.bindingStore.get(e),n=t?.modelId??this.globalConfigStore?.get(this.name)?.modelId;n&&(o.model=n),t?.modeId&&(o.mode=t.modeId);const i={sendStreamChunk:(s,r,a,d,c)=>{this.sendStreamChunkByRuntimeConfig(s,r,a,d,c)},sendEventResult:(s,r,a)=>{this.sendEventResultWithCleanup(s,r,a)},sendEventAck:(s,r)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:r,received_at:Date.now()})},sendRawEventEnvelope:(s,r,a)=>{this.aibotHandle.sendMsg({event_id:s,session_id:r,msg_type:1,content:"[cursor] raw_event",extra:{channel_data:{cursor:{raw_event:a}},agent_api_origin:!0}})},agentInvoke:async(s,r,a)=>this.platformInvoke(s,r,a),sendLocalActionResult:(s,r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})}};return new I({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o},i)}createClaudeAdapter(e){const o={sendReply:(i,s,r,a,d)=>{this.sendReplyByRuntimeConfig(i,s,r,a,d)},sendStreamChunk:(i,s,r,a,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(i,s,r,a,d,c,l)},sendMedia:(i,s,r,a,d,c,l)=>{this.aibotHandle.sendMedia({event_id:i,session_id:s,content:r,msg_type:2,quoted_message_id:d||void 0,client_msg_id:c||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(i,s,r,a)=>{this.sendEventResultWithCleanup(i,s,r,a)},sendEventAck:(i,s)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()})},agentInvoke:async(i,s,r)=>this.platformInvoke(i,s,r),sendLocalActionResult:(i,s,r,a,d)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...d?{error_msg:d}:{}})},sendToolUse:(i,s,r,a)=>{this.sendToolExecutionCard(i,s,E(r,a))},sendToolResult:(i,s,r,a)=>{this.sendToolExecutionCard(i,s,$(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,s,r)=>{const a=r.questions.map(c=>c.header).join(", "),d=We(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:i,session_id:s,content:d,msg_type:1,extra:{card_type:"agent_question",summary_text:a}})},sendPermissionCard:i=>{this.aibotHandle.sendMsg({event_id:i.eventId,session_id:i.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:i.toolTitle?`Permission required: ${i.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:i.approvalId,approvalSlug:i.toolName},grix:{execApproval:{approval_command_id:i.approvalId,command:i.toolTitle||i.toolName,host:"claude"}}},agent_api_origin:!0}})},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);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:i=>{this.aibotHandle.sendMcpFrame(e,i)}},t=this.config.adapterOptions??{},n={...t,sessionRuntimeResolver:()=>{const i=this.bindingStore.get(e);return{cwd:i?.cwd,modeId:i?.modeId??C.fullAuto,modelId:i?.modelId??this.globalConfigStore?.get(this.name)?.modelId,pluginDir:t.pluginDir,claudeSessionId:i?.claudeSessionId,onSessionIdAssigned:s=>{this.bindingStore.setClaudeSessionId(e,s),this.sessionScanCache.invalidate()}}}};return new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},o)}createCodexAdapter(e){let o=null;const t={sendEventResult:(s,r,a)=>{this.sendEventResultWithCleanup(s,r,a)},sendEventAck:(s,r)=>this.aibotHandle.sendEventAck({event_id:s,session_id:r,received_at:Date.now()}),sendCodexEvent:s=>{this.shouldDropCodexDisplayEvent(s.event_id,s.codex_method)||(this.aibotHandle.sendCodexEvent(s),this.logCodexEventToConversation(s))},sendCodexEventReliable:async s=>{if(!this.shouldDropCodexDisplayEvent(s.event_id,s.codex_method)){try{await this.aibotHandle.sendCodexEventReliable(s)}catch(r){u.warn("bridge",`[codex] sendCodexEventReliable ACK failed event=${s.event_id}: ${r}`)}u.info("bridge",`[codex] sendCodexEventReliable done event=${s.event_id} method=${s.codex_method}`),this.logCodexEventToConversation(s)}},sendRunError:(s,r,a)=>{this.sendStreamChunkByRuntimeConfig(s,r,`
|
|
1
|
+
import T from"node:path";import{realpath as j,stat as H}from"node:fs/promises";import{tmpdir as V}from"node:os";import{randomUUID as M}from"node:crypto";import{ConnectionManager as Y}from"../core/aibot/index.js";import{ClaudeAdapter as y}from"../adapter/claude/index.js";import{CodexAdapter as J}from"../adapter/codex/index.js";import{PiAdapter as X}from"../adapter/pi/index.js";import{AcpAdapter as A}from"../adapter/acp/index.js";import{OpenHumanAdapter as Z}from"../adapter/openhuman/index.js";import{CursorAdapter as I}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as U}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as ee}from"../adapter/opencode/index.js";import{AgyAdapter as O}from"../adapter/agy/index.js";import{getCachedAgyModels as te}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as ie}from"../adapter/agy/quota.js";import{LOCAL_ACTION_ERROR_CODES as x,LOCAL_ACTION_TYPES as b,SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as p,SESSION_MODE_IDS as C}from"../adapter/claude/protocol-contract.js";import{parseClaudeSessionUsage as ne}from"../adapter/claude/usage-parser.js";import{resolveSkillScanMode as se}from"../adapter/claude/skill-scanner.js";import{buildReportedSkills as oe}from"../default-skills/index.js";import{fetchAvailableModels as D,getCachedModels as Q,readSettingsEnv as re}from"../adapter/claude/model-list.js";import{parseAcpSessionUsage as ae}from"../adapter/acp/usage-parser.js";import{applyProxyEnv as de,getProxyManager as ce,relayHostsForClientType as le,buildGatewayRoute as ue}from"../core/proxy/index.js";import{buildProviderEnv as he}from"../core/config/provider-env.js";import{sweepNativeProviderResidue as ge}from"./native-provider-sweep.js";import{parseCodexSessionUsage as me}from"../adapter/codex/usage-parser.js";import{readCodexProviderSettings as pe}from"../adapter/codex/codex-trust.js";import{scanCodexSessions as fe}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as _e}from"../adapter/claude/session-scanner.js";import{scanAcpSessions as ve}from"../adapter/acp/session-scanner.js";import{parsePiSessionUsage as Se}from"../adapter/pi/usage-parser.js";import{SessionScanCache as L,resolveCodexLeafDirs as be,resolveClaudeLeafDirs as we,resolveAcpLeafDirs as Ce}from"./session-scan-cache.js";import{log as u,ConversationLog as Ae,AgentApiPacketLog as ke,BridgeEventLog as Re}from"../core/log/index.js";import{RevokeHandler as Ee}from"./revoke-handler.js";import{AdapterPool as $e,PoolFullError as ye}from"./adapter-pool.js";import{parseSessionControlCommand as xe,handleSessionControlCommand as q,handleSessionControlLocalAction as Te}from"./session-controller.js";import{handleAcpSetModel as W,handleAcpSetMode as N,resolveAcpInitialDefaults as Le}from"./acp-toolbar-persist.js";import{SessionBindingStore as Pe}from"../core/persistence/session-binding-store.js";import{handleFileListAction as He,handleCreateFolderAction as Me,serveLocalFile as Ie,realHomeDir as K}from"../core/files/index.js";import{getMachineName as De}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as Qe}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as Be}from"../core/persistence/active-event-store.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Fe,applyConnectorRuntimeConfigPatch as Ue,extractConnectorRuntimeConfigPatch as Oe}from"./runtime-config.js";import{SendController as qe}from"./send-controller.js";import{queryProviderQuota as z}from"../core/provider-quota/index.js";import{queryKiroQuota as B}from"../core/provider-quota/kiro.js";import{buildToolUseCard as E,buildToolResultCard as $,buildLocalGrixCardLink as We}from"./tool-card-utils.js";import{DeferredEventManager as Ne}from"./deferred-events.js";import{buildAgentProbeResult as Ke,PROBE_CACHE_TTL_STATIC_MS as ze,PROBE_CACHE_TTL_FULL_MS as Ge}from"./probe-helper.js";const je=600*1e3,Ve=60*1e3,G=30*1e3,Ye=10*1e3,P=new Set(["claude","acp","agy","cursor","codex"]),Je=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp"]),F=3;class jt{config;name;aibotHandle;aibotConfig;pool;stopped=!1;revokeHandler=new Ee;sessionBindings=new Map;deferredMgr;sendCtrl=new qe(Fe);bindingStore;globalConfigStore;upgradeTrigger=null;agentDeletedHandler=null;shareSetHandler=null;providerConfigHandler=null;agentProfile={agentName:"",introduction:""};activeEventStore;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";conversationLog=null;packetLog=null;kiroQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;sessionScanCache;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const o=Number(e);return o>0&&Date.now()-o<=Ve}async maybeQueryProviderQuota(){if(this.config.aibot.clientType==="kiro"){if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await B();return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] kiro queried: success=${t.success}`+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.planName?` plan=${t.planName}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] kiro query failed: ${t instanceof Error?t.message:String(t)}`),null}}let e=this.config.providerBaseUrl,o=this.config.providerApiKey;if((!e||!o)&&(this.config.adapterType??"acp")==="claude"){const t=re();e||(e=(t.ANTHROPIC_BASE_URL??"").trim()||void 0),o||(o=(t.ANTHROPIC_API_KEY??"").trim()||(t.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!e||!o)&&(this.config.adapterType??"acp")==="codex"){const t=pe();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if(!e||!o)return null;if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await z(e,o);return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] queried: provider=${t.provider} success=${t.success}`+(t.tiers.length>0?` tiers=${t.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] query failed: ${t instanceof Error?t.message:String(t)}`),null}}startKiroQuotaTimer(){this.kiroQuotaTimer||(this.kiroQuotaTimer=setInterval(()=>{if(this.stopped){this.stopKiroQuotaTimer();return}this.refreshAndPushKiroQuota().catch(()=>{})},G),u.info(this.name,`[kiro-quota-timer] started (interval=${G}ms)`))}stopKiroQuotaTimer(){this.kiroQuotaTimer&&(clearInterval(this.kiroQuotaTimer),this.kiroQuotaTimer=null,u.info(this.name,"[kiro-quota-timer] stopped"))}async refreshAndPushKiroQuota(){try{const e=await B();this.cachedProviderQuota=e,this.cachedProviderQuotaSampledAtMs=Date.now(),e.success&&this.pushKiroQuotaToBindings(e)}catch{}}pushKiroQuotaToBindings(e){const o=this.providerQuotaToRateLimits(e);for(const[t,n]of this.sessionBindings.entries()){if(!n)continue;const i={provider_quota:e};o&&(i.rate_limits=o);const s=this.cachedAcpContextWindow;s&&("usedPercentage"in s?i.context_window={usedPercentage:s.usedPercentage,remainingPercentage:100-s.usedPercentage}:i.context_window=s),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:n,meta:i})}}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,o=this.cachedCodexContextWindow,t=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:o,tokenUsage:t,hasData:!!(e||o||t)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,exhausted:this.pool?[...this.pool.getAllSlots()].some(o=>o.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let o=0,t=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let i=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{t=!0,i=!0,u.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),i||(o+=1)}return o>0&&u.info(this.name,`recycled ${o} adapter slot(s) so the new Grix relay env takes effect`),t?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const o=e.conversation?"full":"static",t=e.conversation?Ge:ze;if(!e.fresh){const a=this.probeCache.get(o);if(a&&Date.now()-a.sampledAt<t)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",i=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(i,e.timeoutMs??1e4):void 0;let r;try{r=await Ke({adapter:i,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{i.stop().catch(()=>{})}return this.probeCache.set(o,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,o){const t=Date.now(),n="__probe__",i=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||V(),r=()=>Date.now()-t;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof A)try{await e.bindSession(n,s)}catch{}let a=null;const d=new Promise(h=>{a=m=>{m===i&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:i,session_id:n,content:"ping",msg_id:i}),e.deliverStopEvent(i,n);let c=null;const l=await Promise.race([d.then(()=>!1),new Promise(h=>{c=setTimeout(()=>h(!0),o)})]);return c&&clearTimeout(c),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${o}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,o){this.config=e,this.name=e.name;const t=e.adapterType??"acp";this.aibotConfig={...e.aibot,...t==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","thread_compact","get_agent_global_config"]}:{}},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 Ae(e.logDir):null,this.packetLog=e.logDir?new ke(e.logDir):null,this.bindingStore=new Pe(e.bindingsPath),this.bindingStore.load(),this.globalConfigStore=o??null,this.deferredMgr=new Ne(this.name),this.activeEventStore=e.activeEventStorePath?new Be(e.activeEventStorePath):null,t==="codex"?this.sessionScanCache=new L(fe,be):t==="claude"?this.sessionScanCache=new L(_e,we):t==="agy"?this.sessionScanCache=new L(()=>[],()=>[]):this.sessionScanCache=new L(ve,Ce)}async start(){await ge({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&u.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{u.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),(this.config.adapterType??"acp")==="claude"&&(await D().catch(()=>{}),this.maybeQueryProviderQuota().catch(()=>{})),this.config.aibot.clientType==="kiro"&&(this.maybeQueryProviderQuota().catch(()=>{}),this.startKiroQuotaTimer()),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),await this.connectAibot(),this.sendCtrl.bind(this.aibotHandle);const e=this.config.adapterType??"acp";this.pool=new $e({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const t=this.createAdapter(e,o);return t instanceof A&&t.on("acpSessionReady",n=>{this.bindingStore.setAcpSessionId(o,n),this.sessionScanCache.invalidate()}),t},(o,t)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:t,received_at:Date.now()})}),this.pool.setEventStateHandler((o,t,n,i)=>{u.info(this.name,`[queue-debug] send event_state session=${t} event=${o} state=${n} queue_pos=${i?.queue_position??""} queue_total=${i?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:t,state:n,content_preview:i?.content_preview,queue_position:i?.queue_position,queue_total:i?.queue_total,actions:i?.actions,reason:i?.reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(t),(n==="canceled"||n==="failed")&&this.aibotHandle.sendEventResult({event_id:o,status:n==="canceled"?"canceled":"failed",msg:i?.reason,updated_at:Date.now()})}),this.pool.setQueueComposingHandler((o,t,n)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:t,...t?{ttl_ms:3e4,ref_event_id:n}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(t=>{u.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}),this.pool.setEventStartedHandler((o,t)=>{if(this.reportSessionSkills(t),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(t,"busy");const n=this.bindingStore.get(t);n?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"busy",cwd:n.cwd,meta:this.buildClaudeToolbarMeta(t)})}),this.pool.setEventDoneHandler((o,t)=>{const n=this.config.adapterType??"acp";if(n==="claude"){this.claudeWorkerStatus.set(t,"ready");const i=this.bindingStore.get(t);i?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)})}else if(n==="agy"){const i=this.bindingStore.get(t);if(i?.cwd){const s=this.buildAgyToolbarMeta(t),r=s?.available_models??[];u.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${t} model_id=${String(s?.model_id??"")} available_models=${r.length} meta_keys=${s?Object.keys(s).join(","):"<none>"}`),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:s})}else u.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${t}`)}}),this.pool.setSessionActivityHandler((o,t,n)=>{const i=this.selfDrivenSessions.has(o),s=this.selfDrivenLabels.get(o);t?(this.selfDrivenSessions.add(o),n&&this.selfDrivenLabels.set(o,n),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),i&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(i!==t||t&&n!==void 0&&n!==s)&&this.pushQueueSnapshotForSession(o)}),this.pool.startIdleSweep(),u.info(this.name,`Ready (adapter: ${e}, poolMax: ${this.config.poolMaxSize??20})`)}async stop(){this.stopped=!0,this.pool?.stopIdleSweep(),this.stopKiroQuotaTimer();const e=this.pool?.collectActiveEventIds()??[];e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const n of e)u.info(this.name,`Canceling active event on shutdown: ${n}`),this.sendEventResultWithCleanup(n,"canceled","process shutting down");e.length>0&&await new Promise(n=>setTimeout(n,100)),this.pool?.clearActiveEventsForShutdown();const o=this.deferredMgr.getAllDeferredEvents();for(const n of o)u.info(this.name,`Failing deferred event on shutdown: ${n.event_id}`),this.sendEventResultWithCleanup(n.event_id,"failed","process shutting down");const t=this.pool?.drainAllQueuedEvents()??[];for(const n of t)u.info(this.name,`Failing queued event on shutdown: ${n.event_id}`),this.sendEventResultWithCleanup(n.event_id,"failed","process shutting down");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()}resolveSpawnEnv(){const e=he(this.config.agent.clientType,this.config.agent.provider),o=this.config.agent.env,t=Object.keys(e).length>0?{...e,...o}:o;return de(t,this.name,this.config.agent.clientType)}createAdapter(e,o){switch(e){case"claude":return this.createClaudeAdapter(o);case"codex":return this.createCodexAdapter(o);case"pi":return this.createPiAdapter(o);case"openhuman":return this.createOpenHumanAdapter(o);case"codewhale":return this.createCodeWhaleAdapter(o);case"cursor":return this.createCursorAdapter(o);case"opencode":return this.createOpenCodeAdapter(o);case"agy":return this.createAgyAdapter(o);default:return this.createAcpAdapter(o)}}createCursorAdapter(e){const o={...this.config.adapterOptions??{}};o.bindingStore=this.bindingStore,o.aibotSessionId=e;const t=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(o.model=n),t?.modeId&&(o.mode=t.modeId);const i={sendStreamChunk:(s,r,a,d,c)=>{this.sendStreamChunkByRuntimeConfig(s,r,a,d,c)},sendEventResult:(s,r,a)=>{this.sendEventResultWithCleanup(s,r,a)},sendEventAck:(s,r)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:r,received_at:Date.now()})},sendRawEventEnvelope:(s,r,a)=>{this.aibotHandle.sendMsg({event_id:s,session_id:r,msg_type:1,content:"[cursor] raw_event",extra:{channel_data:{cursor:{raw_event:a}},agent_api_origin:!0}})},agentInvoke:async(s,r,a)=>this.platformInvoke(s,r,a),sendLocalActionResult:(s,r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})}};return new I({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o},i)}createClaudeAdapter(e){const o={sendReply:(i,s,r,a,d)=>{this.sendReplyByRuntimeConfig(i,s,r,a,d)},sendStreamChunk:(i,s,r,a,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(i,s,r,a,d,c,l)},sendMedia:(i,s,r,a,d,c,l)=>{this.aibotHandle.sendMedia({event_id:i,session_id:s,content:r,msg_type:2,quoted_message_id:d||void 0,client_msg_id:c||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(i,s,r,a)=>{this.sendEventResultWithCleanup(i,s,r,a)},sendEventAck:(i,s)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:s,received_at:Date.now()})},agentInvoke:async(i,s,r)=>this.platformInvoke(i,s,r),sendLocalActionResult:(i,s,r,a,d)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:s,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...d?{error_msg:d}:{}})},sendToolUse:(i,s,r,a)=>{this.sendToolExecutionCard(i,s,E(r,a))},sendToolResult:(i,s,r,a)=>{this.sendToolExecutionCard(i,s,$(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,s,r)=>{const a=r.questions.map(c=>c.header).join(", "),d=We(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:i,session_id:s,content:d,msg_type:1,extra:{card_type:"agent_question",summary_text:a}})},sendPermissionCard:i=>{this.aibotHandle.sendMsg({event_id:i.eventId,session_id:i.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:i.toolTitle?`Permission required: ${i.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:i.approvalId,approvalSlug:i.toolName},grix:{execApproval:{approval_command_id:i.approvalId,command:i.toolTitle||i.toolName,host:"claude"}}},agent_api_origin:!0}})},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);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:i=>{this.aibotHandle.sendMcpFrame(e,i)}},t=this.config.adapterOptions??{},n={...t,sessionRuntimeResolver:()=>{const i=this.bindingStore.get(e);return{cwd:i?.cwd,modeId:i?.modeId??C.fullAuto,modelId:this.resolveSessionModelId(e),pluginDir:t.pluginDir,claudeSessionId:i?.claudeSessionId,onSessionIdAssigned:s=>{this.bindingStore.setClaudeSessionId(e,s),this.sessionScanCache.invalidate()}}}};return new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},o)}createCodexAdapter(e){let o=null;const t={sendEventResult:(s,r,a)=>{this.sendEventResultWithCleanup(s,r,a)},sendEventAck:(s,r)=>this.aibotHandle.sendEventAck({event_id:s,session_id:r,received_at:Date.now()}),sendCodexEvent:s=>{this.shouldDropCodexDisplayEvent(s.event_id,s.codex_method)||(this.aibotHandle.sendCodexEvent(s),this.logCodexEventToConversation(s))},sendCodexEventReliable:async s=>{if(!this.shouldDropCodexDisplayEvent(s.event_id,s.codex_method)){try{await this.aibotHandle.sendCodexEventReliable(s)}catch(r){u.warn("bridge",`[codex] sendCodexEventReliable ACK failed event=${s.event_id}: ${r}`)}u.info("bridge",`[codex] sendCodexEventReliable done event=${s.event_id} method=${s.codex_method}`),this.logCodexEventToConversation(s)}},sendRunError:(s,r,a)=>{this.sendStreamChunkByRuntimeConfig(s,r,`
|
|
2
2
|
|
|
3
|
-
Error: ${a}`,1,!1)},sendUpdateBindingCard:(s,r,a,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);l&&(c.rate_limits=l.rateLimits,c.rate_limit_primary_percent=l.primaryPercent,c.rate_limit_secondary_percent=l.secondaryPercent,c.rate_limit_primary_window_min=l.primaryWindowMin,c.rate_limit_secondary_window_min=l.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:r,cwd:a,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(s,r,a)=>this.platformInvoke(s,r,a),sendLocalActionResult:(s,r,a,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:s,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}}),sendSessionActivitySet:(s,r,a,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:r,active:a,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,onRateLimitsUpdated:s=>{this.cachedRateLimits=s,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const r=this.bindingStore.get(e);if(r?.cwd){const a=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...s.primary.windowMinutes>0?{primary:s.primary}:{},...s.secondary.windowMinutes>0?{secondary:s.secondary}:{},sampledAt:a},rate_limit_primary_percent:s.primary.usedPercent,rate_limit_secondary_percent:s.secondary.usedPercent,rate_limit_primary_window_min:s.primary.windowMinutes,rate_limit_secondary_window_min:s.secondary.windowMinutes,...o?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:r.cwd,meta:d})}},onContextWindowUpdated:s=>{if(!s)return;this.cachedCodexContextWindow=s,this.cachedCodexUsageSampledAtMs=Date.now();const r=this.bindingStore.get(e);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:r.cwd,meta:{context_window:s,...o?.getEffortMeta()}})},onTokenUsageUpdated:s=>{s&&(this.cachedCodexTokenUsage=s,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},i=this.globalConfigStore?.get(this.name);return o=new J({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:this.
|
|
3
|
+
Error: ${a}`,1,!1)},sendUpdateBindingCard:(s,r,a,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);l&&(c.rate_limits=l.rateLimits,c.rate_limit_primary_percent=l.primaryPercent,c.rate_limit_secondary_percent=l.secondaryPercent,c.rate_limit_primary_window_min=l.primaryWindowMin,c.rate_limit_secondary_window_min=l.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:r,cwd:a,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(s,r,a)=>this.platformInvoke(s,r,a),sendLocalActionResult:(s,r,a,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:s,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}}),sendSessionActivitySet:(s,r,a,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:r,active:a,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,onRateLimitsUpdated:s=>{this.cachedRateLimits=s,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const r=this.bindingStore.get(e);if(r?.cwd){const a=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...s.primary.windowMinutes>0?{primary:s.primary}:{},...s.secondary.windowMinutes>0?{secondary:s.secondary}:{},sampledAt:a},rate_limit_primary_percent:s.primary.usedPercent,rate_limit_secondary_percent:s.secondary.usedPercent,rate_limit_primary_window_min:s.primary.windowMinutes,rate_limit_secondary_window_min:s.secondary.windowMinutes,...o?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:r.cwd,meta:d})}},onContextWindowUpdated:s=>{if(!s)return;this.cachedCodexContextWindow=s,this.cachedCodexUsageSampledAtMs=Date.now();const r=this.bindingStore.get(e);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:r.cwd,meta:{context_window:s,...o?.getEffortMeta()}})},onTokenUsageUpdated:s=>{s&&(this.cachedCodexTokenUsage=s,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},i=this.globalConfigStore?.get(this.name);return o=new J({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:this.resolveCodexSessionModelId(e)??n.model,collaborationMode:this.bindingStore.getCodexModeId(e)??n.collaborationMode,reasoningEffort:i?.codexReasoningEffort??n.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??n.serviceTier,sandboxMode:i?.codexSandboxMode??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore}},t),o}createCodeWhaleAdapter(e){const o={sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s)},sendEventAck:(n,i)=>this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()}),sendStreamChunk:(n,i,s,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(n,i,s,r,a,d)},sendUpdateBindingCard:(n,i,s,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:i,cwd:s,...r?{meta:r}:{}}),sendLocalActionResult:(n,i,s,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:i,...s!==void 0?{result:s}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}}),sendSessionActivitySet:(n,i,s,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:i,active:s,...r??{}})},sendToolUse:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,E(s,r))},sendToolResult:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,$(s,r))},agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new U({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createPiAdapter(e){const o={sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s),u.info("bridge",`[pi] sendEventResult event=${n} status=${i}`)},sendEventAck:(n,i)=>this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()}),sendUpdateBindingCard:(n,i,s,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:i,cwd:s,...r?{meta:r}:{}}),agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),sendLocalActionResult:(n,i,s,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:i,...s!==void 0?{result:s}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}})},sendSessionActivitySet:(n,i,s,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:i,active:s,...r??{}})},sendToolUse:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,E(s,r))},sendToolResult:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,$(s,r))},sendStreamChunk:(n,i,s,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(n,i,s,r,a,d),a&&u.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${r}`)},sendFinalStreamChunkReliable:async(n,i,s,r)=>{if(this.finalizeThinking(n,i),this.resolveEventRuntimeConfig(n).responseDelivery==="single_message"&&n){this.bufferStreamChunk(n,i,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:n,session_id:i,delta_content:"",chunk_seq:s,is_finish:!0,...r?{client_msg_id:r}:{}})}catch(d){u.warn("bridge",`[pi] sendFinalStreamChunkReliable ACK failed event=${n}: ${d}`)}u.info("bridge",`[pi] sendFinalStreamChunkReliable done event=${n} seq=${s}`)},sendThinking:(n,i,s)=>{this.sendThinkingByRuntimeConfig(n,i,s)},sendRunError:(n,i,s,r,a)=>{this.sendStreamChunkByRuntimeConfig(n,i,`
|
|
4
4
|
|
|
5
5
|
Error: ${s}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new X({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createOpenHumanAdapter(e){const o={sendStreamChunk:(n,i,s,r,a,d)=>{this.finalizeThinking(n,i),this.sendStreamChunkByRuntimeConfig(n,i,s,r,a,d)},sendFinalStreamChunkReliable:async(n,i,s,r)=>{if(this.finalizeThinking(n,i),this.resolveEventRuntimeConfig(n).responseDelivery==="single_message"&&n){this.bufferStreamChunk(n,i,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:n,session_id:i,delta_content:"",chunk_seq:s,is_finish:!0,...r?{client_msg_id:r}:{}})}catch(d){u.warn("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${d}`)}},sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s),u.info("bridge",`[openhuman] sendEventResult event=${n} status=${i}`)},sendEventAck:(n,i)=>this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()}),sendToolUse:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,E(s,r))},sendToolResult:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,$(s,r))},sendThinking:(n,i,s)=>{this.sendThinkingByRuntimeConfig(n,i,s)},sendRunError:(n,i,s)=>{this.sendStreamChunkByRuntimeConfig(n,i,`
|
|
6
6
|
|
|
7
7
|
Error: ${s}`,0,!1)},sendUpdateBindingCard:(n,i,s)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:i,cwd:s}),agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),sendLocalActionResult:(n,i,s,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:i,...s!==void 0?{result:s}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,host:t.host,workspaceDir:t.workspace_dir,sessionToken:t.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const o={sendStreamChunk:(n,i,s,r,a,d)=>{this.sendStreamChunkByRuntimeConfig(n,i,s,r,a,d)},sendFinalStreamChunkReliable:async(n,i,s,r)=>{if(this.finalizeThinking(n,i),this.resolveEventRuntimeConfig(n).responseDelivery==="single_message"&&n){this.bufferStreamChunk(n,i,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:n,session_id:i,delta_content:"",chunk_seq:s,is_finish:!0,...r?{client_msg_id:r}:{}})}catch(d){u.warn("bridge",`[opencode] sendFinalStreamChunkReliable ACK failed event=${n}: ${d}`)}},sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s),u.info("bridge",`[opencode] sendEventResult event=${n} status=${i}`)},sendEventAck:(n,i)=>this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()}),sendToolUse:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,E(s,r))},sendToolResult:(n,i,s,r)=>{this.sendToolExecutionCard(n,i,$(s,r))},sendThinking:(n,i,s)=>{this.sendThinkingByRuntimeConfig(n,i,s)},sendRunError:(n,i,s)=>{this.sendStreamChunkByRuntimeConfig(n,i,`
|
|
8
8
|
|
|
9
|
-
Error: ${s}`,0,!1)},sendUpdateBindingCard:(n,i,s)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:i,cwd:s}),agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),sendLocalActionResult:(n,i,s,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:i,...s!==void 0?{result:s}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new ee({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(n,i,s,r,a)=>{this.sendStreamChunkByRuntimeConfig(n,i,s,r,a)},sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s)},sendEventAck:(n,i)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()})},agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),forceCompleteInternalEvent:(n,i)=>{this.pool.eventComplete(n,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(n,i)=>{this.bindingStore.setAgyConversationId(n,i)},getAgentProfile:()=>this.agentProfile},t=n=>{const i=this.bindingStore.get(n);return{cwd:i?.cwd,modelId:
|
|
9
|
+
Error: ${s}`,0,!1)},sendUpdateBindingCard:(n,i,s)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:i,cwd:s}),agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),sendLocalActionResult:(n,i,s,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:i,...s!==void 0?{result:s}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new ee({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(n,i,s,r,a)=>{this.sendStreamChunkByRuntimeConfig(n,i,s,r,a)},sendEventResult:(n,i,s)=>{this.sendEventResultWithCleanup(n,i,s)},sendEventAck:(n,i)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:i,received_at:Date.now()})},agentInvoke:async(n,i,s)=>this.platformInvoke(n,i,s),forceCompleteInternalEvent:(n,i)=>{this.pool.eventComplete(n,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(n,i)=>{this.bindingStore.setAgyConversationId(n,i)},getAgentProfile:()=>this.agentProfile},t=n=>{const i=this.bindingStore.get(n);return{cwd:i?.cwd,modelId:this.resolveSessionModelId(n),conversationId:i?.agyConversationId}};return new O({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},o,t)}createAcpAdapter(e){const o=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(a,d,c,l,h,m,v)=>{this.finalizeThinking(a,d),this.sendStreamChunkByRuntimeConfig(a,d,c,l,h,m,v)},sendFinalStreamChunkReliable:async(a,d,c,l)=>{if(this.finalizeThinking(a,d),this.resolveEventRuntimeConfig(a).responseDelivery==="single_message"&&a){this.bufferStreamChunk(a,d,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:a,session_id:d,delta_content:"",chunk_seq:c,is_finish:!0,...l?{client_msg_id:l}:{}})}catch(m){u.warn("bridge",`[acp] sendFinalStreamChunkReliable ACK failed event=${a}: ${m}`)}u.info("bridge",`[acp] sendFinalStreamChunkReliable done event=${a} seq=${c}`)},sendEventResult:(a,d,c)=>{this.sendEventResultWithCleanup(a,d,c)},sendEventAck:(a,d)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:d,received_at:Date.now()})},agentInvoke:async(a,d,c)=>this.platformInvoke(a,d,c),sendLocalActionResult:(a,d,c,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:d,...c!==void 0?{result:c}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}})},sendRawEventEnvelope:(a,d,c)=>{this.sendAcpRawEventEnvelope(a,d,c)},sendToolUse:(a,d,c,l)=>{if(o){this.sendAcpRawEventEnvelope(a,d,{type:"tool_use",payload:{tool_name:c,tool_input:l??""}});return}this.sendToolExecutionCard(a,d,E(c,l))},sendToolResult:(a,d,c,l)=>{this.sendToolExecutionCard(a,d,$(c,l))},sendThinking:(a,d,c)=>{this.sendThinkingByRuntimeConfig(a,d,c)},sendRunError:(a,d,c)=>{this.sendStreamChunkByRuntimeConfig(a,d,`
|
|
10
10
|
|
|
11
|
-
Error: ${c}`,1,!1)},sendPermissionCard:a=>{if(o){this.sendAcpRawEventEnvelope(a.eventId,a.sessionId,{type:"permission_request",payload:{tool_call_id:a.toolCallId,tool_name:a.toolName,tool_title:a.toolTitle,options:a.options}});return}this.aibotHandle.sendMsg({event_id:a.eventId,session_id:a.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:a.toolTitle?`Permission required: ${a.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:a.toolCallId,approvalSlug:a.toolName},grix:{execApproval:{approval_command_id:a.toolCallId,command:a.toolTitle||a.toolName,host:"acp"}}},agent_api_origin:!0}})},sendAuthNotification:(a,d)=>{a&&this.aibotHandle.sendMsg({session_id:a,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendUpdateBindingCard:(a,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:a=>{try{this.aibotHandle.sendSkillsUpdate({skills:a})}catch(d){}},onContextWindowUpdated:a=>{this.cachedAcpContextWindow=a,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in a?a.usedPercentage.toFixed(1):(a.used/a.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l={context_window:"usedPercentage"in a?{usedPercentage:a.usedPercentage,remainingPercentage:100-a.usedPercentage}:a};if(this.config.aibot.clientType==="kiro"&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),l.provider_quota=this.cachedProviderQuota;const h=this.providerQuotaToRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:l})}},sendMcpFrame:a=>{this.aibotHandle.sendMcpFrame(e,a)},getAgentProfile:()=>this.agentProfile},n=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:s,initialMode:r}=Le({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return(s||r)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${s??"<none>"} mode=${r??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:r,acpInitialModel:s,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Re(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new Y;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(n=>{u.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const r=this.pool.getSlot(t.session_id);r?.adapter instanceof A&&r.adapter.getSessionBindings().delete(t.session_id);const a=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(a);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(n){u.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){u.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(n){u.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(n){u.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(n){u.error(this.name,`handleAibotRevoke failed: ${n}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(n=>{u.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(n=>{u.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((t,n)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(n):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const n=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const n of t)u.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,n)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const n=String(e??"").trim(),i=String(o??"").trim(),s=n!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:n,introduction:i},n||i?u.info(this.name,`agent profile (${t.source}): GOT name="${n}" intro_len=${i.length} changed=${s}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),s&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const r of o)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),t++}catch(a){u.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const n=o.filter(r=>r.adapter instanceof y),i=n.filter(r=>r.state==="ready"&&!r.adapter.getStatus().busy),s=n.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${s} busy`);for(const r of i)this.pool.removeSlot(r.sessionId).catch(a=>{u.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],n=o?o.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"}]})):[],i=o?o.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(s),n.push({event_id:s,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:t,running_items:n,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?Ie(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const s=await Qe({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),r=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${M()}`,...i?{quoted_message_id:i}:{},extra:s.extra});if(r.cmd!=="send_ack"){const d=r.payload??{},c=String(d.msg??r.cmd);throw new Error(`media message send failed: ${c}`)}const a=r.payload??{};return{ok:!0,file_name: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,o,t,n,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,n,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}sendStreamChunkByRuntimeConfig(e,o,t,n,i,s,r){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,n,i,s,r),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
|
|
11
|
+
Error: ${c}`,1,!1)},sendPermissionCard:a=>{if(o){this.sendAcpRawEventEnvelope(a.eventId,a.sessionId,{type:"permission_request",payload:{tool_call_id:a.toolCallId,tool_name:a.toolName,tool_title:a.toolTitle,options:a.options}});return}this.aibotHandle.sendMsg({event_id:a.eventId,session_id:a.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:a.toolTitle?`Permission required: ${a.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:a.toolCallId,approvalSlug:a.toolName},grix:{execApproval:{approval_command_id:a.toolCallId,command:a.toolTitle||a.toolName,host:"acp"}}},agent_api_origin:!0}})},sendAuthNotification:(a,d)=>{a&&this.aibotHandle.sendMsg({session_id:a,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendUpdateBindingCard:(a,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:a=>{try{this.aibotHandle.sendSkillsUpdate({skills:a})}catch(d){}},onContextWindowUpdated:a=>{this.cachedAcpContextWindow=a,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in a?a.usedPercentage.toFixed(1):(a.used/a.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l={context_window:"usedPercentage"in a?{usedPercentage:a.usedPercentage,remainingPercentage:100-a.usedPercentage}:a};if(this.config.aibot.clientType==="kiro"&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),l.provider_quota=this.cachedProviderQuota;const h=this.providerQuotaToRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:l})}},sendMcpFrame:a=>{this.aibotHandle.sendMcpFrame(e,a)},getAgentProfile:()=>this.agentProfile},n=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:s,initialMode:r}=Le({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&s&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,s),(s||r)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${s??"<none>"} mode=${r??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:r,acpInitialModel:s,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Re(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new Y;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(n=>{u.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const r=this.pool.getSlot(t.session_id);r?.adapter instanceof A&&r.adapter.getSessionBindings().delete(t.session_id);const a=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(a);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(n){u.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){u.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(n){u.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(n){u.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(n){u.error(this.name,`handleAibotRevoke failed: ${n}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(n=>{u.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(n=>{u.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((t,n)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(n):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const n=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const n of t)u.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,n)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const n=String(e??"").trim(),i=String(o??"").trim(),s=n!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:n,introduction:i},n||i?u.info(this.name,`agent profile (${t.source}): GOT name="${n}" intro_len=${i.length} changed=${s}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),s&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const r of o)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),t++}catch(a){u.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const n=o.filter(r=>r.adapter instanceof y),i=n.filter(r=>r.state==="ready"&&!r.adapter.getStatus().busy),s=n.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${s} busy`);for(const r of i)this.pool.removeSlot(r.sessionId).catch(a=>{u.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],n=o?o.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"}]})):[],i=o?o.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(s),n.push({event_id:s,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:t,running_items:n,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?Ie(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const s=await Qe({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),r=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${M()}`,...i?{quoted_message_id:i}:{},extra:s.extra});if(r.cmd!=="send_ack"){const d=r.payload??{},c=String(d.msg??r.cmd);throw new Error(`media message send failed: ${c}`)}const a=r.payload??{};return{ok:!0,file_name: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,o,t,n,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,n,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}sendStreamChunkByRuntimeConfig(e,o,t,n,i,s,r){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,n,i,s,r),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
|
|
12
12
|
|
|
13
|
-
Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,n){this.sendCtrl.sendEventResult(e,o,t,n);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.maybeQueryProviderQuota().catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:n}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,n),this.sendEventResultWithCleanup(o,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,s);const r=this.config.adapterType??"acp";if(s>F){u.error(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${s}/${F} outcome=give-up err=${n}`),this.sendRunErrorAsChunk(o,t,n),this.sendEventResultWithCleanup(o,"failed",n,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${s}/${F} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(r,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,n,i){this.sendCtrl.bufferOnly(e,o,t,n,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:this.buildAcpRawEventFallbackText(t),extra:{channel_data:{acp:{raw_event:t}},agent_api_origin:!0}})}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}sendToolExecutionCard(e,o,t,n){this.sendCtrl.sendToolExecutionCard(e,o,t,n)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=Oe(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 n=t.patch,i=xe(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const a=i.args.trim();if(!a){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=T.resolve(a);if(!(await H(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${T.resolve(a)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${a}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const a=this.bindingStore.get(e.session_id);if(a?.cwd)try{await H(a.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${a.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(q(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const a=this.bindingStore.get(e.session_id)?.cwd??"";a&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:a,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(Je.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,n));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(_=>_.name===c||_.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const _=await m.execCommand(c,l.trim(),e.session_id);_.status==="options"&&_.data&&this.handleExecCommandOptions(e.session_id,c,_.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:_.status==="failed"?"failed":"responded",msg:_.message,updated_at:Date.now()})}catch(_){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_ instanceof Error?_.message:String(_),updated_at:Date.now()})}return}}}const r=this.buildInboundEvent(e,n);try{this.captureEventRuntimeConfig(r),await this.pool.deliverInboundEvent(r)}catch(a){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.inflightEvents.delete(e.event_id),this.restartCount.delete(e.event_id),this.eventSessionIndex.delete(e.event_id),a instanceof ye)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:a.message,updated_at:Date.now()});else throw a}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),s("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const n=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!n||!i||await this.bindSessionForPool(n,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),s("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:o.msg_id})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),s=this.bindingStore.get(o)?.cwd??"";if(!s){t(),n("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:s}),n("responded",{msg:`Session worker restarted for ${s}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){s("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){s("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),s("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const n=this.pool.getOrCreateSlot(e);if(!n||(n.startPromise&&await n.startPromise,!n.adapter))return;const i=n.adapter instanceof A?n.adapter:null;if(!i?.hasSessionBinding)return;const s=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,s),this.sessionBindings.set(e,s),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const n={};o&&(n.ttl_ms=t?.ttlMs??3e4,t?.activity&&(n.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...n})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),q(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(n){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:n?.cwdErrorCode,msg:n instanceof Error?n.message:String(n),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),s("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){const d=await this.resolveCwdForBinding(a.cwd);if(d!==r){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const n=Array.isArray(t?.options)?t.options:[];if(n.length===0)return;const s=this.bindingStore.get(e)?.cwd??"",r={};if(o==="model"){r.available_models=n.map(d=>({id:d.id,displayName:d.label}));const a=n.find(d=>d.current);a&&(r.model_id=a.id)}else if(o==="mode"){r.available_modes=n.map(d=>({id:d.id,displayName:d.label}));const a=n.find(d=>d.current);a&&(r.mode_id=a.id)}else r[`${o}_options`]=n;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:s,meta:r})}buildAgyToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=te(this.config.agent.command),n=t.length>0?t[0].id:"";let i=o.modelId||this.globalConfigStore?.get(this.name)?.modelId||n;t.length>0&&!t.some(r=>r.id===i)&&(i=n);const s=ie();return{model_id:i,currentModelId:i,available_models:t.map(r=>({id:r.id,displayName:r.displayName})),...s.plan!==void 0&&{plan:s.plan},...s.quota_exhausted!==void 0&&{quota_exhausted:s.quota_exhausted},...s.quota_reset_at!==void 0&&{quota_reset_at:s.quota_reset_at},...s.available_credits!==void 0&&{available_credits:s.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},n=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!n){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==n&&(this.bindingStore.setModelId(o,n),this.globalConfigStore?.set(this.name,{modelId:n})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:n,binding:{cwd:i.cwd,model_id:n}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=Q(),n=t.length>0?t[0].id:"";let i=o.modelId||this.globalConfigStore?.get(this.name)?.modelId||n;t.length>0&&!t.some(l=>l.id===i)&&(i=n);const s=this.normalizeClaudeModeId(o.modeId),r={model_id:i,mode_id:s,currentModelId:i,currentModeId:s,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},a=this.pool.getSlot(e),d=a?.adapter instanceof y?a.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(r.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(r.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!r.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(r.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return r.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(r.rate_limits)}`),r}providerQuotaToCodexRateLimits(e){const o=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit"),n=i=>i||null;if(o||t){const i={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};let s=0,r=0,a=0,d=0;return o&&(i.primary={usedPercent:o.usedPercent,windowMinutes:300,resetsAt:n(o.resetsAt)},s=o.usedPercent,r=300),t&&(i.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:n(t.resetsAt)},a=t.usedPercent,d=10080),{rateLimits:i,primaryPercent:s,secondaryPercent:a,primaryWindowMin:r,secondaryWindowMin:d}}if(e.balance){const i=e.balance,s=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:s,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()},primaryPercent:s,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}return null}providerQuotaToRateLimits(e){const o=i=>{if(!i)return 0;const s=Date.parse(i);return Number.isFinite(s)?Math.floor(s/1e3):0},t=e.tiers.find(i=>i.name==="five_hour"),n=e.tiers.find(i=>i.name==="weekly_limit");if(t||n)return{...t?{fiveHour:{usedPercentage:t.usedPercent,resetsAt:o(t.resetsAt)}}:{},...n?{sevenDay:{usedPercentage:n.usedPercent,resetsAt:o(n.resetsAt)}}:{},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};if(e.balance){const i=e.balance;return{credit:{remaining:i.remaining,total:i.total,used:i.used,unit:i.unit,resetsAt:i.resetsAt?o(i.resetsAt):0},planName:e.planName,sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()}}return null}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=T.resolve(o);let n;try{n=await H(t)}catch(i){const s=String(i?.code??"");if(s==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=g.invalidCwd,r}if(s==="EACCES"||s==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=g.invalidCwd,r}throw i}if(!n.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await j(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}reportSessionSkills(e){const o=se(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,n=o==="kiro"?t:t||process.cwd();let i;try{i=oe({mode:o,projectDir:n})}catch{return}if(i.length===0)return;const s=JSON.stringify(i.map(r=>`${r.source}:${r.name}`));if(s!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=s;try{this.aibotHandle.sendSkillsUpdate({skills:i})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((n,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),n=String(o??"").trim();if(!t||!n)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,n);break;case"codex":this.bindingStore.setCodexThreadId(t,n);break;case"pi":this.bindingStore.setPiSessionPath(t,n);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,n);break;case"agy":this.bindingStore.setAgyConversationId(t,n);break;default:this.bindingStore.setAcpSessionId(t,n);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=T.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const n=this.normalizePathForCompare(o);let i="";const s=this.config.adapterType??"acp";if(s==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":s==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":s==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){i=a.cwd??"";break}}if(!i){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}const r=this.normalizePathForCompare(i);if(r&&n&&r!==n){const a=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}}buildOpenedBindingResult(e,o,t="ready"){const n=this.bindingStore.get(e),i=n?String(this.resolveAgentSessionId(n)??"").trim():"",s={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(s.bindingId=i,s.agentSessionId=i),s}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const n=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:a,workerStatus:h})}}const s=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=i.get(d.threadId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.threadId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),s.push(` Created: ${new Date(d.createdAt).toISOString()}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.sessionId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??"inactive"}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.sessionId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??"inactive"}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed";s.push(` Title: ${c?c.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026"}`),s.push(` AIBot: ${a}`),c&&s.push(` Agent: ${c}`),s.push(` CWD: ${d.cwd??"-"}`),s.push(` State: ${h}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}if(s.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${s.filter(a=>a==="---").length}):
|
|
13
|
+
Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,n){this.sendCtrl.sendEventResult(e,o,t,n);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.maybeQueryProviderQuota().catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:n}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,n),this.sendEventResultWithCleanup(o,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,s);const r=this.config.adapterType??"acp";if(s>F){u.error(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${s}/${F} outcome=give-up err=${n}`),this.sendRunErrorAsChunk(o,t,n),this.sendEventResultWithCleanup(o,"failed",n,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${r} session=${t} event=${o} restart=${s}/${F} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(r,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,n,i){this.sendCtrl.bufferOnly(e,o,t,n,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:this.buildAcpRawEventFallbackText(t),extra:{channel_data:{acp:{raw_event:t}},agent_api_origin:!0}})}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}sendToolExecutionCard(e,o,t,n){this.sendCtrl.sendToolExecutionCard(e,o,t,n)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=Oe(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 n=t.patch,i=xe(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const a=i.args.trim();if(!a){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=T.resolve(a);if(!(await H(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${T.resolve(a)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${a}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const a=this.bindingStore.get(e.session_id);if(a?.cwd)try{await H(a.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${a.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(q(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const a=this.bindingStore.get(e.session_id)?.cwd??"";a&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:a,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(Je.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,n));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(_=>_.name===c||_.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const _=await m.execCommand(c,l.trim(),e.session_id);_.status==="options"&&_.data&&this.handleExecCommandOptions(e.session_id,c,_.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:_.status==="failed"?"failed":"responded",msg:_.message,updated_at:Date.now()})}catch(_){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_ instanceof Error?_.message:String(_),updated_at:Date.now()})}return}}}const r=this.buildInboundEvent(e,n);try{this.captureEventRuntimeConfig(r),await this.pool.deliverInboundEvent(r)}catch(a){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.inflightEvents.delete(e.event_id),this.restartCount.delete(e.event_id),this.eventSessionIndex.delete(e.event_id),a instanceof ye)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:a.message,updated_at:Date.now()});else throw a}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),s("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const n=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!n||!i||await this.bindSessionForPool(n,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),s("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:o.msg_id})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),n=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),s=this.bindingStore.get(o)?.cwd??"";if(!s){t(),n("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:s}),n("responded",{msg:`Session worker restarted for ${s}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){s("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){s("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),s("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const n=this.pool.getOrCreateSlot(e);if(!n||(n.startPromise&&await n.startPromise,!n.adapter))return;const i=n.adapter instanceof A?n.adapter:null;if(!i?.hasSessionBinding)return;const s=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,s),this.sessionBindings.set(e,s),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const n={};o&&(n.ttl_ms=t?.ttlMs??3e4,t?.activity&&(n.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...n})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),q(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(n){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:n?.cwdErrorCode,msg:n instanceof Error?n.message:String(n),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,n=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:r,...a,updated_at:Date.now()});if(!n){i(),s("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(n),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){i(),s("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),s("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),s("responded",{msg:`Session bound to ${r}`})}catch(r){i(),s("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),n=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),s=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!n){s("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(n);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){const d=await this.resolveCwdForBinding(a.cwd);if(d!==r){s("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,i),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),s("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){s("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const n=Array.isArray(t?.options)?t.options:[];if(n.length===0)return;const s=this.bindingStore.get(e)?.cwd??"",r={};if(o==="model"){r.available_models=n.map(d=>({id:d.id,displayName:d.label}));const a=n.find(d=>d.current);a&&(r.model_id=a.id)}else if(o==="mode"){r.available_modes=n.map(d=>({id:d.id,displayName:d.label}));const a=n.find(d=>d.current);a&&(r.mode_id=a.id)}else r[`${o}_options`]=n;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:s,meta:r})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=te(this.config.agent.command),n=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||n;t.length>0&&!t.some(r=>r.id===i)&&(i=n);const s=ie();return{model_id:i,currentModelId:i,available_models:t.map(r=>({id:r.id,displayName:r.displayName})),...s.plan!==void 0&&{plan:s.plan},...s.quota_exhausted!==void 0&&{quota_exhausted:s.quota_exhausted},...s.quota_reset_at!==void 0&&{quota_reset_at:s.quota_reset_at},...s.available_credits!==void 0&&{available_credits:s.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},n=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!n){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==n&&(this.bindingStore.setModelId(o,n),this.globalConfigStore?.set(this.name,{modelId:n})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:n,binding:{cwd:i.cwd,model_id:n}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=Q(),n=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||n;t.length>0&&!t.some(l=>l.id===i)&&(i=n);const s=this.normalizeClaudeModeId(o.modeId),r={model_id:i,mode_id:s,currentModelId:i,currentModeId:s,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},a=this.pool.getSlot(e),d=a?.adapter instanceof y?a.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(r.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(r.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!r.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(r.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return r.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(r.rate_limits)}`),r}providerQuotaToCodexRateLimits(e){const o=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit"),n=i=>i||null;if(o||t){const i={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};let s=0,r=0,a=0,d=0;return o&&(i.primary={usedPercent:o.usedPercent,windowMinutes:300,resetsAt:n(o.resetsAt)},s=o.usedPercent,r=300),t&&(i.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:n(t.resetsAt)},a=t.usedPercent,d=10080),{rateLimits:i,primaryPercent:s,secondaryPercent:a,primaryWindowMin:r,secondaryWindowMin:d}}if(e.balance){const i=e.balance,s=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:s,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()},primaryPercent:s,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}return null}providerQuotaToRateLimits(e){const o=i=>{if(!i)return 0;const s=Date.parse(i);return Number.isFinite(s)?Math.floor(s/1e3):0},t=e.tiers.find(i=>i.name==="five_hour"),n=e.tiers.find(i=>i.name==="weekly_limit");if(t||n)return{...t?{fiveHour:{usedPercentage:t.usedPercent,resetsAt:o(t.resetsAt)}}:{},...n?{sevenDay:{usedPercentage:n.usedPercent,resetsAt:o(n.resetsAt)}}:{},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};if(e.balance){const i=e.balance;return{credit:{remaining:i.remaining,total:i.total,used:i.used,unit:i.unit,resetsAt:i.resetsAt?o(i.resetsAt):0},planName:e.planName,sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()}}return null}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=T.resolve(o);let n;try{n=await H(t)}catch(i){const s=String(i?.code??"");if(s==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=g.invalidCwd,r}if(s==="EACCES"||s==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=g.invalidCwd,r}throw i}if(!n.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await j(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}reportSessionSkills(e){const o=se(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,n=o==="kiro"?t:t||process.cwd();let i;try{i=oe({mode:o,projectDir:n})}catch{return}if(i.length===0)return;const s=JSON.stringify(i.map(r=>`${r.source}:${r.name}`));if(s!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=s;try{this.aibotHandle.sendSkillsUpdate({skills:i})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((n,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),n=String(o??"").trim();if(!t||!n)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,n);break;case"codex":this.bindingStore.setCodexThreadId(t,n);break;case"pi":this.bindingStore.setPiSessionPath(t,n);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,n);break;case"agy":this.bindingStore.setAgyConversationId(t,n);break;default:this.bindingStore.setAcpSessionId(t,n);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=T.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const n=this.normalizePathForCompare(o);let i="";const s=this.config.adapterType??"acp";if(s==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":s==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":s==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){i=a.cwd??"";break}}if(!i){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}const r=this.normalizePathForCompare(i);if(r&&n&&r!==n){const a=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}}buildOpenedBindingResult(e,o,t="ready"){const n=this.bindingStore.get(e),i=n?String(this.resolveAgentSessionId(n)??"").trim():"",s={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(s.bindingId=i,s.agentSessionId=i),s}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const n=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:a,workerStatus:h})}}const s=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=i.get(d.threadId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.threadId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),s.push(` Created: ${new Date(d.createdAt).toISOString()}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.sessionId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??"inactive"}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&s.push(` Title: ${d.title}`),s.push(` Agent: ${d.sessionId}`),c&&s.push(` AIBot: ${c.aibotSessionId}`),s.push(` CWD: ${d.cwd||"-"}`),s.push(` State: ${c?.workerStatus??"inactive"}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}}for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed";s.push(` Title: ${c?c.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026"}`),s.push(` AIBot: ${a}`),c&&s.push(` Agent: ${c}`),s.push(` CWD: ${d.cwd??"-"}`),s.push(` State: ${h}`),s.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),s.push("---")}if(s.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${s.filter(a=>a==="---").length}):
|
|
14
14
|
${s.join(`
|
|
15
15
|
`)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const o=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const n=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:a,workerStatus:h,bindingUpdatedAt:d.updatedAt??0})}}const s=[],r=new Set;if(o==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=i.get(d.threadId),l={agentSessionId:d.threadId,cwd:d.cwd||null,workerStatus:c?.workerStatus??(d.archived?"archived":"inactive"),createdAt:d.createdAt,updatedAt:d.updatedAt,archived:d.archived};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),s.push(l)}}else if(o==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId),l={agentSessionId:d.sessionId,cwd:d.cwd||null,workerStatus:c?.workerStatus??"inactive",updatedAt:d.updatedAt};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),s.push(l)}}else if(o==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,h={agentSessionId:d.sessionId,cwd:d.cwd||null,agentType:d.agentType,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(h.aibotSessionId=c.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),s.push(h)}}for(const[a,d]of n){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m={aibotSessionId:a,cwd:d.cwd??null,workerStatus:h,updatedAt:d.updatedAt,title:c?`${c.slice(0,8)}\u2026`:`${a.slice(0,8)}\u2026`};c&&(m.agentSessionId=c),s.push(m)}s.sort((a,d)=>d.updatedAt-a.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:s,total:s.length}})}async handleSessionControlCommand(e,o){const t=o.session_id,n=(i,s,r)=>{this.aibotHandle.sendEventResult({event_id:o.event_id,status:i,...s?{msg:s}:{},...r?{code:r}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case p.open:{await D().catch(()=>{});const i=e.args.trim();if(!i){n("failed","Usage: /grix open <working-directory>",g.cwdRequired);return}let s="";try{s=await this.resolveCwdForBinding(i)}catch(a){n("failed",a instanceof Error?a.message:String(a),g.invalidCwd);return}const r=this.bindingStore.get(t);if(r?.cwd){const a=await this.resolveCwdForBinding(r.cwd);if(a!==s){n("failed","session binding cannot be changed to another working directory",g.rebindForbidden);return}this.bindingStore.ensureModeId(t,C.fullAuto),this.sessionBindings.set(t,a),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,a),n("responded",`Working directory already bound: ${a}`);return}this.bindingStore.set(t,s,{modeId:C.fullAuto}),this.sessionBindings.set(t,s),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,s),n("responded",`Session bound to ${s}`);return}case p.where:{const i=this.bindingStore.get(t);if(!i?.cwd){n("failed","session binding was not found",g.bindingMissing);return}n("responded",`Working directory: ${i.cwd}`);return}case p.status:{const i=this.bindingStore.get(t);if(!i?.cwd){n("failed","session binding was not found",g.bindingMissing);return}const s=this.normalizeClaudeModeId(i.modeId),r=this.getClaudeWorkerStatus(t);n("responded",`Status: worker=${r} mode=${s} cwd=${i.cwd}`);return}case p.stop:{const i=this.bindingStore.get(t);if(!i?.cwd){n("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),this.claudeWorkerStatus.set(t,"stopped"),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)}),n("responded",`Session worker stopped for ${i.cwd}`);return}case p.restart:{const i=this.bindingStore.get(t);if(!i?.cwd){n("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,i.cwd),n("responded",`Session worker restarted for ${i.cwd}`);return}case p.setMode:{const i=e.args.trim();if(!i){n("failed","Usage: /grix set_mode <mode-id>",x.modeInvalid);return}const s=this.normalizeClaudeModeId(i);if(s!==i.toLowerCase()){n("failed","set mode_id is invalid",x.modeInvalid);return}const r=this.bindingStore.get(t);if(!r?.cwd){n("failed","session binding was not found",g.bindingMissing);return}if(this.normalizeClaudeModeId(r.modeId)===s){n("responded",`Mode unchanged: ${s}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){n("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F",g.workerBusy);return}this.bindingStore.setModeId(t,s),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,r.cwd),n("responded",`Mode set to ${s}`);return}case p.setModel:{const i=e.args.trim();if(!i){n("failed","Usage: /grix set_model <model-id>");return}const s=this.bindingStore.get(t);if(!s?.cwd){n("failed","session binding was not found",g.bindingMissing);return}if((s.modelId??"")===i){n("responded",`Model unchanged: ${i}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){n("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B",g.workerBusy);return}this.bindingStore.setModelId(t,i),this.globalConfigStore?.set(this.name,{modelId:i}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,s.cwd),n("responded",`Model set to ${i}`);return}case p.listOptions:{const i=Q(),s=this.bindingStore.get(t),r=i.map(d=>d.id).join(", "),a=`${C.fullAuto}, ${C.approval}`;n("responded",`Modes (current: ${this.normalizeClaudeModeId(s?.modeId)}): ${a}
|
|
16
16
|
Models (current: ${s?.modelId??"default"}): ${r}`);return}case p.exec:{const[i,...s]=e.args.trim().split(/\s+/);if(!i){n("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const a=this.pool.getSlot(t)?.adapter;if(!a?.execCommand){n("failed","Agent does not support command execution",g.verbInvalid);return}const d=a.getSupportedCommands?.()??[];if(!d.some(c=>c.name===i)){n("failed",`Unknown command: ${i}. Supported: ${d.map(c=>c.name).join(", ")}`,g.verbInvalid);return}try{const c=await a.execCommand(i,s.join(" "),t);n(c.status==="ok"?"responded":"failed",c.message??`${i} ${c.status}`,c.status==="ok"?void 0:g.runtimeError)}catch(c){n("failed",`exec error: ${c instanceof Error?c.message:c}`,g.runtimeError)}return}default:n("failed",`Unsupported command for Claude: /grix ${e.verb}`,g.verbInvalid)}}catch(i){n("failed",i instanceof Error?i.message:String(i),g.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==b.sessionControl&&o!==b.setMode&&o!=="set_mode"&&o!==b.setModel&&o!=="set_model")return!1;const t=e.params??{},n=String(t.session_id??"").trim(),i=o===b.setMode?p.setMode:o===b.setModel?p.setModel:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${n}`),!n)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:x.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const s=a=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a})},r=(a,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${n} verb=${i} code=${a} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:a,error_msg:d})};try{switch(i){case p.open:{await D().catch(()=>{});const a=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!a)return r(g.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${a} session_id=${n}`);const c=await this.resolveCwdForBinding(a);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(n);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(r(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(n,C.fullAuto),this.setResolvedAgentSessionId(n,d),this.sessionBindings.set(n,h),await this.ensureSlotStarted(n),await this.replayDeferredEventsForSession(n),this.refreshClaudeWorkerStatusCard(n,h),s({outcome:"opened",binding:{...this.buildOpenedBindingResult(n,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(n)?.modeId)}}),!0)}return this.bindingStore.set(n,c,{modeId:C.fullAuto}),this.setResolvedAgentSessionId(n,d),this.sessionBindings.set(n,c),await this.ensureSlotStarted(n),await this.replayDeferredEventsForSession(n),this.refreshClaudeWorkerStatusCard(n,c),s({outcome:"opened",binding:{...this.buildOpenedBindingResult(n,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(n)?.modeId)}}),!0}case p.status:case p.where:{const a=this.bindingStore.get(n);return a?.cwd?(s({outcome:i,binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:this.getClaudeWorkerStatus(n)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case p.stop:{const a=this.bindingStore.get(n);return a?.cwd?(await this.pool.removeSlot(n),s({outcome:"stopped",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:"stopped"}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case p.restart:{const a=this.bindingStore.get(n);return a?.cwd?(await this.pool.removeSlot(n),await this.ensureSlotStarted(n),this.refreshClaudeWorkerStatusCard(n,a.cwd),s({outcome:"restarted",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case p.setMode:{const a=String(t.mode_id??t.modeId??"").trim();if(!a)return r(x.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(a);if(d!==a.toLowerCase())return r(x.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(n);if(!c?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(n)==="busy")return r(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(n,d),await this.pool.removeSlot(n),await this.ensureSlotStarted(n),this.refreshClaudeWorkerStatusCard(n,c.cwd)}return s({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case p.setModel:{const a=String(t.model_id??t.modelId??"").trim();if(!a)return r("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(n);if(!d?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==a){if(this.getClaudeWorkerStatus(n)==="busy")return r(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(n,a),this.globalConfigStore?.set(this.name,{modelId:a}),await this.pool.removeSlot(n),await this.ensureSlotStarted(n),this.refreshClaudeWorkerStatusCard(n,d.cwd)}return s({outcome:"model_set",model_id:a,binding:{cwd:d.cwd,model_id:a}}),!0}case p.listOptions:{const a=Q(),d=this.pool.getSlot(n);return s({modes:[C.fullAuto,C.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(n)?.modeId),models:a.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(n)?.modelId??"",available_models:a.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case p.exec:{const[a,...d]=String(t.args??"").trim().split(/\s+/);if(!a)return r(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(n);const l=this.pool.getSlot(n)?.adapter;if(!l?.execCommand)return r(g.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(m=>m.name===a))return r(g.verbInvalid,`Unknown command: ${a}. Supported: ${h.map(m=>m.name).join(", ")}`),!0;try{const m=await l.execCommand(a,d.join(" "),n);m.status==="ok"?s({outcome:"exec",command:a,message:m.message,data:m.data}):r(g.runtimeError,m.message??`${a} failed`)}catch(m){r(g.runtimeError,`exec error: ${m instanceof Error?m.message:m}`)}return!0}default:return r(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(a){const d=a instanceof Error&&a.cwdErrorCode?a.cwdErrorCode:a instanceof Error&&a.sessionControlErrorCode?a.sessionControlErrorCode:g.runtimeError;return u.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${n}: ${a instanceof Error?a.message:a}`),r(d,a instanceof Error?a.message:String(a)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(n=>{const i=this.pool.getSlot(o);if(!i?.adapter){n();return}const s=setTimeout(()=>{i.adapter.removeListener("eventDone",r),n()},t),r=a=>{a===e&&(clearTimeout(s),i.adapter.removeListener("eventDone",r),n())};i.adapter.on("eventDone",r)})}handleAibotStop(e){if(u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`),this.aibotHandle.sendEventStopAck({stop_id:e.stop_id,event_id:e.event_id,accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,e.event_id)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"}`),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});return}const o=this.pool.getSlot(e.session_id),t=o?.adapter?.getStatus().busy??!1,n=(this.config.adapterType??"acp")==="acp",i=o?.adapter?.getActiveEventIds,s=typeof i=="function"?i.call(o.adapter):[],r=s.length>0?s.includes(e.event_id):t,a=(n||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&r;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter} busy=${t} activeIds=[${s.join(",")}] stoppingActiveEvent=${r} killOnStop=${a}`),r&&this.sendCtrl.markEventStopped(e.event_id),o?.adapter&&t){const d=a?this.pool.drainQueuedForSession(e.session_id):[];let c=!1,l=null;const h=v=>{c||(c=!0,l&&(clearTimeout(l),l=null),o.adapter.removeListener("eventDone",m),u.info(this.name,`[stop-trace] handleAibotStop ${v} -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} killOnStop=${a}`),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()}),a&&this.killAndResumeStopSlot(e.session_id,d))},m=v=>{v===e.event_id&&h("eventDone")};o.adapter.on("eventDone",m),l=setTimeout(()=>h("timeout"),Ye),this.pool.deliverStopEvent(e.event_id,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter}`),this.pool.deliverStopEvent(e.event_id,e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:e.event_id,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(n){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${n instanceof Error?n.message:String(n)}`),this.sendEventResultWithCleanup(t.event_id,"failed",n instanceof Error?n.message:String(n))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),n=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),s=typeof o.model=="string"&&o.model.trim()||void 0;let r=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const a=this.config.adapterType??"acp",d=a==="claude"||a==="codex";try{if(d){const c=a==="claude"?n:i;if(!c){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${a==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const l=ce();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const h=le(a),m=ue(a,c,t,{model:s});l.setRoute(m);for(const v of h)l.setHostDefaultRoute(v,m.routeKey);await l.setAgentRelayEnabled(this.name,!0,{relayHosts:h}),r=!await this.recycleAdaptersForRelayChange()}else{if(!this.providerConfigHandler){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:`client type "${a}" does not support Grix relay provider config`});return}await this.providerConfigHandler({base_url:i||void 0,api_key:t,model:s})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:r}})}catch(c){u.error(this.name,`handleConfigureGatewayProvider failed: ${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:c instanceof Error?c.message:String(c)})}}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${o} verb=${n||"-"} action_id=${e.action_id} session_id=${t}`);const i=(this.config.adapterType??"acp")==="claude";if(o===b.sessionControl&&n===p.exec&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl&&n===p.listSessions){await this.handleListSessionsLocalAction(e);return}if(i&&(o===b.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl){const c=this.config.adapterType??"acp",l=c==="codex",h=c==="pi",m=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&m===p.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(c==="cursor"&&m===p.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&m==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(h&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),k=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(k,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,k),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(h&&m===p.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((c==="openhuman"||c==="opencode")&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),k=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(k,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,k),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(c==="codewhale"&&m===p.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(c==="acp"&&m===p.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(m===p.open){const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=String(f.agent_session_id??"").trim();if(w){const k=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,k)}}await this.handleSessionControlLocalActionForPool(e)}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.runtimeError,error_msg:f instanceof Error?f.message:String(f)});return}if(m===p.open){const f=e.params??{},S=await this.resolveCwdForBinding(String(f.cwd??"").trim());this.setResolvedAgentSessionId(t,String(f.agent_session_id??"").trim()),c==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else Te(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const c=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,h=e.params??{},m=String(h.parent_id??"").trim(),v=Array.isArray(h.allowed_extensions)?h.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${m||"<root>"} show_hidden=${!!h.show_hidden} ext_count=${v.length} bound_cwd=${l??"<none>"}`);const _=await He({parent_id:m||null,session_id:t,show_hidden:!!h.show_hidden,allowed_extensions:v},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:K()}),R=Date.now()-c,f=_.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${_.status} elapsed=${R}ms count=${f} current_path=${_.result?.current_path??""} error_code=${_.error_code??""} error_msg=${_.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:_.status,..._.result?{result:{..._.result,machine_name:De()}}:{},..._.error_code?{error_code:_.error_code}:{},..._.error_msg?{error_msg:_.error_msg}:{}});return}if(o==="create_folder"){const c=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),h=String((e.params??{}).name??"").trim(),m=await Me({parent_id:l||null,name:h,session_id:t},{resolveCwd:()=>c??this.config.agent.cwd??process.cwd(),fallbackDir:K()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:m.result}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o===b.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===b.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===b.getRateLimits){await this.handleGetRateLimits(e,t);return}const s=(this.config.adapterType??"acp")==="acp";if((i||s)&&o===b.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===b.getAgentGlobalConfig){const c=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...c?{config:c}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}const r=this.config.adapterType??"acp",a=(r==="codex"||r==="cursor"||r==="pi"||r==="openhuman"||r==="opencode"||r==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,d=await this.pool.deliverLocalAction(e,{autoCreateSlot:a});if(d.handled){if(d.kind==="set_mode"){const c=String((e.params??{}).mode_id??"");c&&(r==="cursor"||r==="claude"?this.bindingStore.setModeId(t,c):P.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:c}))}else if(d.kind==="set_model"){const c=String((e.params??{}).model_id??"");c&&(r==="cursor"?(this.bindingStore.setModelId(t,c),this.globalConfigStore?.set(this.name,{modelId:c})):r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:c}):P.has(r)||this.globalConfigStore?.set(this.name,{modelId:c}))}else if(d.kind==="set_reasoning_effort"){const c=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");c&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:c})}else if(d.kind==="set_sandbox_mode"){const c=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(c){const l=c==="default"?void 0:c;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}return}if((r==="codex"||r==="cursor"||r==="pi"||r==="openhuman"||r==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(r==="acp"&&(o==="set_mode"||o==="set_model")){const c=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,h={bindingStore:this.bindingStore,acpAdapter:l instanceof A?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(o==="set_mode"){const m=String((e.params??{}).mode_id??""),v=await N(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}else{const m=String((e.params??{}).model_id??""),v=await W(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",n=this.bindingStore.get(o),i=n?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!n} cwd=${i}`);let s=null,r,a;switch(t){case"claude":{if(r=n?.claudeSessionId,!r){u.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${r} cwd=${i}`),s=await ne(r,i),a="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"agy",available:!1,reason:"agy print-mode adapter does not track token usage"}});return}case"acp":default:{if(r=n?.acpSessionId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}s=await ae(r,i,this.config.aibot.clientType),a=t,(!a||a==="acp")&&(a="acp");break}case"codex":{if(r=n?.codexThreadId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}s=await me(r),a="codex";break}case"pi":{if(r=n?.piSessionPath,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}s=await Se(r),a="pi";break}case"cursor":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof I)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{modelId:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite}],total:{input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite},turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof U)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{modelId:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,input:l.total.input,output:l.total.output}],total:{input:l.total.input,output:l.total.output},turns:l.turns,sampledAt:l.sampledAt}});return}}if(!s){u.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${r} adapterType=${a}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}u.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${r} turns=${s.turns} models=${s.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:r,adapterType:a,models:s.models,total:s.total,turns:s.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const s=await i.execCommand("compact","",o);s.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:s.message,data:s.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:s.message??"compact failed"})}catch(n){u.warn(this.name,`thread_compact error session_id=${o}: ${n instanceof Error?n.message:n}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:n instanceof Error?n.message:String(n)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const n=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(n&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const s=await B();this.cachedProviderQuota=s,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${s.success}`+(s.balance?` balance=${s.balance.remaining} ${s.balance.unit}`:"")+(s.error?` error=${s.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:s}})}catch(s){u.warn(this.name,`[rate-limits] kiro quota query failed: ${s instanceof Error?s.message:String(s)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const n=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await n;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const r=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(r&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${r.sessionId}`),(await r.adapter.handleLocalAction?.(e))?.handled))return;const a=this.resolveRateLimitWakeSessionId(o,t);if(a){const l=await this.wakeRateLimitSlot(a,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await n,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const n=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const c=i.rateLimits,l=await n;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let s=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof y)??null;if(!s){const c=this.resolveRateLimitWakeSessionId(o,t);c&&(s=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!s} hasAdapter=${!!s?.adapter}`);const r=s?.adapter,a=r instanceof y?r.getSessionState():null,d=await n;if(a){(a.rateLimits?.fiveHour||a.rateLimits?.sevenDay||a.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=a);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!a.rateLimits?{...a,rateLimits:c.rateLimits}:a,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!a.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!r} adapterType=${r?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter,s=i instanceof I?i.getRateLimitsSnapshot():{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:s});return}default:{const n=this.config.providerBaseUrl,i=this.config.providerApiKey;if(!n||!i){u.info(this.name,`[rate-limits] no provider config for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null}});return}if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota){u.info(this.name,`[rate-limits] provider quota cached: provider=${this.cachedProviderQuota.provider} success=${this.cachedProviderQuota.success}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const r=await z(n,i);this.cachedProviderQuota=r,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] provider quota queried: provider=${r.provider} success=${r.success}`+(r.tiers.length>0?` tiers=${r.tiers.map(a=>`${a.name}=${a.usedPercent}%`).join(",")}`:"")+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:r}})}catch(r){u.warn(this.name,`[rate-limits] provider quota query failed: ${r instanceof Error?r.message:String(r)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null}})}return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),n=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return n?t&&t===n?t:o==="codex"||o==="claude"?(t&&t!==n&&u.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${n}`),n):t&&t!==n?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${n}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const s=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((r,a)=>setTimeout(()=>a(new Error(`wake rate-limits slot timeout (${s}ms)`)),s))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof A?o.adapter:null,n=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const s=this.sessionBindings;if(e&&!s.has(e)){const r=this.bindingStore.get(e);r?.cwd&&s.set(e,r.cwd)}return s},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:s=>t?t.setMode(s):Promise.resolve(!1),setModel:s=>t?t.setModel(s):Promise.resolve(!1),acpSetMode:n?(s,r)=>N(i,s,r):void 0,acpSetModel:n?(s,r)=>W(i,s,r):void 0,getPendingApproval:s=>{const r=t?.pendingApprovalEntries.get(s);return r?{requestId:r}:void 0},deletePendingApproval:s=>t?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,r)=>(t&&t.respondToPermission(s,r),Promise.resolve()),onSessionBound:(s,r)=>{this.bindingStore.set(s,r)},onSessionUnbound:s=>{const a=this.bindingStore.get(s)?.cwd??"";this.bindingStore.delete(s),this.sessionBindings.delete(s),this.claudeWorkerStatus.delete(s),this.deferredMgr.clearSession(s),this.pool.drainQueuedForSession(s),a&&this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"stopped",cwd:a})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof O?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{const r=this.config.adapterType??"acp";P.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:s})},onModelSet:s=>{const r=this.config.adapterType??"acp";P.has(r)||this.globalConfigStore?.set(this.name,{modelId:s})}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,n,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...n?{error_code:n}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}buildInboundEvent(e,o){const t=Ue(this.sendCtrl.getGlobalRuntimeConfig(),o);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:e.context_messages?JSON.stringify(e.context_messages):void 0,extra_json:e.extra?JSON.stringify(e.extra):void 0,connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>je}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:n,writePending:i,removePending:s,upgradeLog:r}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:a}=await import("../core/util/client-version.js"),d=a();r(`server rollback: ${d} -> ${o} reason=${t}`),i(d,o),await n("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(n){try{const{removePending:s}=await import("../core/upgrade/npm-upgrader.js");s()}catch{}const i=n instanceof Error?n.message:String(n);u.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{jt as AgentInstance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as o,writeJSONFileAtomic as
|
|
1
|
+
import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const
|
|
1
|
+
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as c,writeJSONFileAtomic as g}from"../util/json-file.js";import{log as l}from"../log/index.js";import{SESSION_MODE_IDS as s}from"../../adapter/claude/protocol-contract.js";const a=s.fullAuto;function n(r){const e=String(r??"").trim().toLowerCase();return e===s.approval||e===s.fullAuto?e:a}class x{bindings=new Map;filePath;writePromise=Promise.resolve();constructor(e){this.filePath=e??null}load(){if(!this.filePath)return;const e=c(this.filePath);if(Array.isArray(e)){this.bindings.clear();for(const d of e)d.aibotSessionId&&this.bindings.set(d.aibotSessionId,{...d,modeId:n(d.modeId)})}}set(e,d,t){const i=this.bindings.get(e),o=n(t?.modeId??i?.modeId);this.bindings.set(e,{aibotSessionId:e,cwd:d,acpSessionId:i?.acpSessionId,claudeSessionId:i?.claudeSessionId,codexThreadId:i?.codexThreadId,codexModelId:i?.codexModelId,codexModeId:i?.codexModeId,codewhaleThreadId:i?.codewhaleThreadId,agyConversationId:i?.agyConversationId,codexReasoningEffort:i?.codexReasoningEffort,codexServiceTier:i?.codexServiceTier,codexSandboxMode:i?.codexSandboxMode,piSessionPath:i?.piSessionPath,modeId:o,modelId:i?.modelId,acpModelId:i?.acpModelId,acpModeId:i?.acpModeId,updatedAt:Date.now()}),this.scheduleWrite()}setAcpSessionId(e,d){this.updateBinding(e,{acpSessionId:d})}setClaudeSessionId(e,d){this.updateBinding(e,{claudeSessionId:d})}getClaudeSessionId(e){return this.bindings.get(e)?.claudeSessionId}setCodexThreadId(e,d){this.updateBinding(e,{codexThreadId:d})}getCodexThreadId(e){return this.bindings.get(e)?.codexThreadId}setAgyConversationId(e,d){this.updateBinding(e,{agyConversationId:d})}getAgyConversationId(e){return this.bindings.get(e)?.agyConversationId}setCodexContext(e,d){this.updateBinding(e,{codexModelId:d.modelId,codexModeId:d.modeId,codexReasoningEffort:d.reasoningEffort,codexServiceTier:d.serviceTier,codexSandboxMode:d.sandboxMode})}getCodexModelId(e){return this.bindings.get(e)?.codexModelId}getCodexModeId(e){return this.bindings.get(e)?.codexModeId}getCodexReasoningEffort(e){return this.bindings.get(e)?.codexReasoningEffort}getCodexServiceTier(e){return this.bindings.get(e)?.codexServiceTier}getCodexSandboxMode(e){return this.bindings.get(e)?.codexSandboxMode}setPiSessionPath(e,d){this.updateBinding(e,{piSessionPath:d})}getPiSessionPath(e){return this.bindings.get(e)?.piSessionPath}setCodeWhaleThreadId(e,d){this.updateBinding(e,{codewhaleThreadId:d})}getCodeWhaleThreadId(e){return this.bindings.get(e)?.codewhaleThreadId}setModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=n(d);t.modeId!==i&&(this.bindings.set(e,{...t,modeId:i,updatedAt:Date.now()}),this.scheduleWrite())}ensureModeId(e,d=a){const t=this.bindings.get(e);t&&(t.modeId||(this.bindings.set(e,{...t,modeId:n(d),updatedAt:Date.now()}),this.scheduleWrite()))}getAcpSessionId(e){return this.bindings.get(e)?.acpSessionId}getModeId(e){const d=this.bindings.get(e)?.modeId;return d?n(d):void 0}setModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=d.trim();t.modelId!==i&&(this.bindings.set(e,{...t,modelId:i,updatedAt:Date.now()}),this.scheduleWrite())}getModelId(e){return this.bindings.get(e)?.modelId}setAcpModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModelId!==o&&(this.bindings.set(e,{...t,acpModelId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModelId(e){return this.bindings.get(e)?.acpModelId}setAcpModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModeId!==o&&(this.bindings.set(e,{...t,acpModeId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModeId(e){return this.bindings.get(e)?.acpModeId}get(e){return this.bindings.get(e)}getMostRecentlyUpdatedSessionId(e){const d=e?.requireCwd!==!1;let t,i=-1;for(const o of this.bindings.values())d&&!String(o.cwd??"").trim()||o.updatedAt>i&&(i=o.updatedAt,t=o.aibotSessionId);return t}delete(e){this.bindings.delete(e),this.scheduleWrite()}entries(){return this.bindings.entries()}async flush(){await this.writePromise}scheduleWrite(){this.filePath&&(this.writePromise=this.writePromise.then(()=>this.write()).catch(e=>{l.error("session-binding-store",`Persist failed: ${e instanceof Error?e.message:e}`)}))}async write(){if(!this.filePath)return;const e=Array.from(this.bindings.values());await g(this.filePath,e)}updateBinding(e,d){const t=this.bindings.get(e),i={aibotSessionId:e,acpSessionId:Object.prototype.hasOwnProperty.call(d,"acpSessionId")?d.acpSessionId:t?.acpSessionId,claudeSessionId:Object.prototype.hasOwnProperty.call(d,"claudeSessionId")?d.claudeSessionId:t?.claudeSessionId,codexThreadId:Object.prototype.hasOwnProperty.call(d,"codexThreadId")?d.codexThreadId:t?.codexThreadId,codexModelId:Object.prototype.hasOwnProperty.call(d,"codexModelId")?d.codexModelId:t?.codexModelId,codexModeId:Object.prototype.hasOwnProperty.call(d,"codexModeId")?d.codexModeId:t?.codexModeId,codewhaleThreadId:Object.prototype.hasOwnProperty.call(d,"codewhaleThreadId")?d.codewhaleThreadId:t?.codewhaleThreadId,agyConversationId:Object.prototype.hasOwnProperty.call(d,"agyConversationId")?d.agyConversationId:t?.agyConversationId,codexReasoningEffort:Object.prototype.hasOwnProperty.call(d,"codexReasoningEffort")?d.codexReasoningEffort:t?.codexReasoningEffort,codexServiceTier:Object.prototype.hasOwnProperty.call(d,"codexServiceTier")?d.codexServiceTier:t?.codexServiceTier,codexSandboxMode:Object.prototype.hasOwnProperty.call(d,"codexSandboxMode")?d.codexSandboxMode:t?.codexSandboxMode,piSessionPath:Object.prototype.hasOwnProperty.call(d,"piSessionPath")?d.piSessionPath:t?.piSessionPath,cwd:t?.cwd,modeId:n(t?.modeId),modelId:t?.modelId,acpModelId:t?.acpModelId,acpModeId:t?.acpModeId,updatedAt:Date.now()};this.bindings.set(e,i),this.scheduleWrite()}}export{x as SessionBindingStore};
|
|
1
|
+
import{readJSONFile as c,writeJSONFileAtomic as g}from"../util/json-file.js";import{log as l}from"../log/index.js";import{SESSION_MODE_IDS as s}from"../../adapter/claude/protocol-contract.js";const a=s.fullAuto;function n(r){const e=String(r??"").trim().toLowerCase();return e===s.approval||e===s.fullAuto?e:a}class x{bindings=new Map;filePath;writePromise=Promise.resolve();constructor(e){this.filePath=e??null}load(){if(!this.filePath)return;const e=c(this.filePath);if(Array.isArray(e)){this.bindings.clear();for(const d of e)d.aibotSessionId&&this.bindings.set(d.aibotSessionId,{...d,modeId:n(d.modeId)})}}set(e,d,t){const i=this.bindings.get(e),o=n(t?.modeId??i?.modeId);this.bindings.set(e,{aibotSessionId:e,cwd:d,acpSessionId:i?.acpSessionId,claudeSessionId:i?.claudeSessionId,codexThreadId:i?.codexThreadId,codexModelId:i?.codexModelId,codexModeId:i?.codexModeId,codewhaleThreadId:i?.codewhaleThreadId,agyConversationId:i?.agyConversationId,codexReasoningEffort:i?.codexReasoningEffort,codexServiceTier:i?.codexServiceTier,codexSandboxMode:i?.codexSandboxMode,piSessionPath:i?.piSessionPath,modeId:o,modelId:i?.modelId,acpModelId:i?.acpModelId,acpModeId:i?.acpModeId,updatedAt:Date.now()}),this.scheduleWrite()}setAcpSessionId(e,d){this.updateBinding(e,{acpSessionId:d})}setClaudeSessionId(e,d){this.updateBinding(e,{claudeSessionId:d})}getClaudeSessionId(e){return this.bindings.get(e)?.claudeSessionId}setCodexThreadId(e,d){this.updateBinding(e,{codexThreadId:d})}getCodexThreadId(e){return this.bindings.get(e)?.codexThreadId}setAgyConversationId(e,d){this.updateBinding(e,{agyConversationId:d})}getAgyConversationId(e){return this.bindings.get(e)?.agyConversationId}setCodexContext(e,d){this.updateBinding(e,{codexModelId:d.modelId,codexModeId:d.modeId,codexReasoningEffort:d.reasoningEffort,codexServiceTier:d.serviceTier,codexSandboxMode:d.sandboxMode})}getCodexModelId(e){return this.bindings.get(e)?.codexModelId}setCodexModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim();!i||t.codexModelId===i||(this.bindings.set(e,{...t,codexModelId:i,updatedAt:Date.now()}),this.scheduleWrite())}getCodexModeId(e){return this.bindings.get(e)?.codexModeId}getCodexReasoningEffort(e){return this.bindings.get(e)?.codexReasoningEffort}getCodexServiceTier(e){return this.bindings.get(e)?.codexServiceTier}getCodexSandboxMode(e){return this.bindings.get(e)?.codexSandboxMode}setPiSessionPath(e,d){this.updateBinding(e,{piSessionPath:d})}getPiSessionPath(e){return this.bindings.get(e)?.piSessionPath}setCodeWhaleThreadId(e,d){this.updateBinding(e,{codewhaleThreadId:d})}getCodeWhaleThreadId(e){return this.bindings.get(e)?.codewhaleThreadId}setModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=n(d);t.modeId!==i&&(this.bindings.set(e,{...t,modeId:i,updatedAt:Date.now()}),this.scheduleWrite())}ensureModeId(e,d=a){const t=this.bindings.get(e);t&&(t.modeId||(this.bindings.set(e,{...t,modeId:n(d),updatedAt:Date.now()}),this.scheduleWrite()))}getAcpSessionId(e){return this.bindings.get(e)?.acpSessionId}getModeId(e){const d=this.bindings.get(e)?.modeId;return d?n(d):void 0}setModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=d.trim();t.modelId!==i&&(this.bindings.set(e,{...t,modelId:i,updatedAt:Date.now()}),this.scheduleWrite())}getModelId(e){return this.bindings.get(e)?.modelId}setAcpModelId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModelId!==o&&(this.bindings.set(e,{...t,acpModelId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModelId(e){return this.bindings.get(e)?.acpModelId}setAcpModeId(e,d){const t=this.bindings.get(e);if(!t)return;const i=String(d??"").trim(),o=i===""?void 0:i;t.acpModeId!==o&&(this.bindings.set(e,{...t,acpModeId:o,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModeId(e){return this.bindings.get(e)?.acpModeId}get(e){return this.bindings.get(e)}getMostRecentlyUpdatedSessionId(e){const d=e?.requireCwd!==!1;let t,i=-1;for(const o of this.bindings.values())d&&!String(o.cwd??"").trim()||o.updatedAt>i&&(i=o.updatedAt,t=o.aibotSessionId);return t}delete(e){this.bindings.delete(e),this.scheduleWrite()}entries(){return this.bindings.entries()}async flush(){await this.writePromise}scheduleWrite(){this.filePath&&(this.writePromise=this.writePromise.then(()=>this.write()).catch(e=>{l.error("session-binding-store",`Persist failed: ${e instanceof Error?e.message:e}`)}))}async write(){if(!this.filePath)return;const e=Array.from(this.bindings.values());await g(this.filePath,e)}updateBinding(e,d){const t=this.bindings.get(e),i={aibotSessionId:e,acpSessionId:Object.prototype.hasOwnProperty.call(d,"acpSessionId")?d.acpSessionId:t?.acpSessionId,claudeSessionId:Object.prototype.hasOwnProperty.call(d,"claudeSessionId")?d.claudeSessionId:t?.claudeSessionId,codexThreadId:Object.prototype.hasOwnProperty.call(d,"codexThreadId")?d.codexThreadId:t?.codexThreadId,codexModelId:Object.prototype.hasOwnProperty.call(d,"codexModelId")?d.codexModelId:t?.codexModelId,codexModeId:Object.prototype.hasOwnProperty.call(d,"codexModeId")?d.codexModeId:t?.codexModeId,codewhaleThreadId:Object.prototype.hasOwnProperty.call(d,"codewhaleThreadId")?d.codewhaleThreadId:t?.codewhaleThreadId,agyConversationId:Object.prototype.hasOwnProperty.call(d,"agyConversationId")?d.agyConversationId:t?.agyConversationId,codexReasoningEffort:Object.prototype.hasOwnProperty.call(d,"codexReasoningEffort")?d.codexReasoningEffort:t?.codexReasoningEffort,codexServiceTier:Object.prototype.hasOwnProperty.call(d,"codexServiceTier")?d.codexServiceTier:t?.codexServiceTier,codexSandboxMode:Object.prototype.hasOwnProperty.call(d,"codexSandboxMode")?d.codexSandboxMode:t?.codexSandboxMode,piSessionPath:Object.prototype.hasOwnProperty.call(d,"piSessionPath")?d.piSessionPath:t?.piSessionPath,cwd:t?.cwd,modeId:n(t?.modeId),modelId:t?.modelId,acpModelId:t?.acpModelId,acpModeId:t?.acpModeId,updatedAt:Date.now()};this.bindings.set(e,i),this.scheduleWrite()}}export{x as SessionBindingStore};
|