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