grix-connector 5.0.0 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- import{isRequestTimeoutError as C}from"../core/aibot/errors.js";import{log as h}from"../core/log/index.js";import{splitTextForAibotProtocol as _,AIBOT_PROTOCOL_MAX_RUNES as y}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as S,isToolEventDropped as T,normalizeRuntimeConfigSnapshot as M}from"./runtime-config.js";const b={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class p{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;eventTriggerQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;openStreams=new Map;rejectedEvents=new Set;terminalEvents=new Set;terminalResultEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=$();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e),this.rejectedEvents.size>p.MAX_TERMINAL_EVENTS&&this.rejectedEvents.delete(this.rejectedEvents.values().next().value);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const i=this.streamCoalesce.get(s);i.timer&&clearTimeout(i.timer),this.streamCoalesce.delete(s)}h.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}hasTerminalResult(e){return!!e&&(this.terminalResultEvents.has(e)||this.terminalEvents.has(e))}rememberTerminalResult(e){if(e&&(this.terminalResultEvents.add(e),this.terminalResultEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalResultEvents.values().next().value;t!==void 0&&this.terminalResultEvents.delete(t)}}markEventStopped(e){e&&(this.stoppedEvents.add(e),h.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,i,n,l){!e||!this.stoppedEvents.has(e)||h.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${i} is_finish=${n} len=${l}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id),this.terminalResultEvents.delete(e.event_id);const t=M(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const i=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:i.responseDelivery,toolEvents:i.toolEvents,thinkingEvents:i.thinkingEvents}),h.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${i.responseDelivery} tool_events=${i.toolEvents} thinking_events=${i.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id);const s=typeof e.quoted_message_id=="string"?e.quoted_message_id.trim():"";s&&!this.eventTriggerQuotedMessageIds.has(e.event_id)&&this.eventTriggerQuotedMessageIds.set(e.event_id,s)}discardEventState(e){e&&(this.rememberTerminalResult(e),this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.eventTriggerQuotedMessageIds.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&h.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of[...this.openStreams.keys()])t.startsWith(`${e}:`)&&this.openStreams.delete(t);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}applyExplicitFinalQuote(e,t,s){const i=typeof s=="string"?s.trim():"";if(!i)return;const n=this.bufferedEventTexts.get(e);n&&!n.quotedMessageId&&(n.quotedMessageId=i);const l=this.streamCoalesce.get(`${e}:${t??"default"}`);return l&&!l.quotedMessageId&&(l.quotedMessageId=i),i}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}getCodexDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventTriggerQuotedMessageIds.get(e)??this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return T(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return S(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,i,n,l){if(!l?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&R(s,n)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!n){const o=_(s),r=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(o.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:i||void 0});return}for(let u=0;u<o.length;u++){const f=u===o.length-1;this.sendStreamChunk(e,t,o[u],u+1,f,r,i)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:i||void 0,...n?{extra:n}:{}})}sendStreamChunk(e,t,s,i,n,l,a,o){if(this.isEventClosed(e))return;a=a??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",i,n,(s||"").length);const r=this.resolveEventRuntimeConfig(e);if(!o?.forceStream&&r.responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,a,l);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,i,n,l,a,o?.threadId);return}this.coalesceStreamChunk(e,t,s,n,l,a,o?.threadId)}async sendFinalStreamChunkReliable(e,t,s,i,n=!1,l=!1,a){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);l||this.finalizeThinking(e,t);const o=this.applyExplicitFinalQuote(e,s,a),r=this.resolveEventRuntimeConfig(e);if(!n&&r.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,i),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const u=`${e}:${s??"default"}`;this.flushCoalesce(u,!1),this.streamCoalesce.delete(u);const f=(this.chunkSeqMap.get(u)??0)+1;this.chunkSeqMap.set(u,f),this.openStreams.delete(u);const d=o||this.getDefaultQuotedMessageId(e),E={event_id:e,session_id:t,delta_content:"",chunk_seq:f,is_finish:!0,...s?{client_msg_id:s}:{},...d?{quoted_message_id:d}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",f,!0,0);const m=async()=>{const c=await this.handle.sendStreamChunkRequest(E,i);if(c.cmd!=="send_ack"){const k=c.payload;throw new Error(`final chunk rejected: cmd=${c.cmd} code=${k?.code??""} msg=${k?.msg??""}`)}};try{await m()}catch(c){if(C(c))h.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${f} event=${e}`),await m();else throw h.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${c}`),c}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,i){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const a=this.getDefaultQuotedMessageId(e),o=_(s);for(let r=0;r<o.length;r++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",r+1,!1,o[r].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o[r],...r===0&&a?{quoted_message_id:a}:{},client_msg_id:o.length>1?`${i}_p${r+1}`:i});return!0}const l=_(s);for(const a of l)this.sendStreamChunk(e,t,a,0,!1,i);return await this.sendFinalStreamChunkReliable(e,t,i,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,i,n,l,a){if(!s&&!i)return;const o=`${e}:${n??"default"}`;let r=this.streamCoalesce.get(o);if(r||(r={eventId:e,sessionId:t,clientMsgId:n,quotedMessageId:l,threadId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,r)),s&&(r.text+=s),r.sessionId=t,n!==void 0&&(r.clientMsgId=n),!r.quotedMessageId&&l&&(r.quotedMessageId=l),!r.threadId&&a&&(r.threadId=a),i){this.flushCoalesce(o,!0);return}if(!r.flushedOnce||r.text.length>=p.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}r.timer||(r.timer=setTimeout(()=>this.flushCoalesce(o,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const i=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!i&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,i,0,t,s.clientMsgId,s.quotedMessageId,s.threadId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,i,n,l,a,o){const r=s||(n?`
2
- `:"");if(!r&&!n)return;const u=_(r,y);u.length===0&&u.push(r||`
3
- `);const f=`${e}:${l??"default"}`;for(let d=0;d<u.length;d++){const E=d===u.length-1,m=this.chunkSeqMap.get(f)??0,c=d===0&&i>m?i:m+1;this.chunkSeqMap.set(f,c),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:u[d],chunk_seq:c,is_finish:E&&n,...l?{client_msg_id:l}:{},...a?{quoted_message_id:a}:{},...o?{thread_id:o}:{}})}e&&(n?this.openStreams.delete(f):this.openStreams.set(f,{eventId:e,sessionId:t,clientMsgId:l,quotedMessageId:a}))}finalizeOpenStreams(e){if(!e||this.isEventClosed(e))return;this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const t=`${e}:`;for(const[s,i]of[...this.openStreams]){if(!s.startsWith(t))continue;this.openStreams.delete(s);const n=(this.chunkSeqMap.get(s)??0)+1;this.chunkSeqMap.set(s,n),this.handle.sendStreamChunk({event_id:i.eventId,session_id:i.sessionId,delta_content:"",chunk_seq:n,is_finish:!0,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}}),h.info("send-ctrl",`appended missing stream fence before terminal event=${i.eventId} client_msg_id=${i.clientMsgId??"default"} chunk_seq=${n}`)}}sendEventResult(e,t,s,i,n=!1){if(!e||this.hasTerminalResult(e))return;this.rememberTerminalResult(e),this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const l=this.ensureSingleMessageDelivery(e),a=(o,r=s,u=i)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",u=u||"agent_output_rejected",r=r||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...r?{msg:r}:{},...u?{code:u}:{},...n&&o===t?{error_surfaced:!0}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!l){a(t);return}l.then(()=>a(t),o=>{const r=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?r:s,t==="responded"?"agent_output_delivery_failed":i)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const i=_(s,y);i.length===0&&i.push(s),this.thinkingSessionMap.set(e,t);for(const n of i){const l=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,l),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:n,chunk_seq:l,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}}sendToolExecutionCard(e,t,s,i){if(this.shouldDropToolDisplayEvent(e)){h.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const l=Date.now(),a=`${e}:${s.summaryText}:${s.detailText??""}`,o=this.recentToolCards.get(a);if(o!==void 0&&l-o<p.TOOL_CARD_DEDUP_MS){h.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(a,l);const r={summary_text:s.summaryText};s.detailText&&(r.detail_text=s.detailText),h.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:i??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:r}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,i,n){n=n??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,n)}bufferStreamChunk(e,t,s,i,n){const l=typeof n=="string"&&n.startsWith("reply_"),a=this.bufferedEventTexts.get(e);if(!a){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:i||void 0,replyReceived:l});return}l?a.replyReceived?s&&(a.text+=s):(a.text=s??"",a.replyReceived=!0):!a.replyReceived&&s&&(a.text+=s),!a.quotedMessageId&&i&&(a.quotedMessageId=i)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const i=this.bufferedEventTexts.get(e);if(!i||(this.bufferedEventTexts.delete(e),!i.text))return;const n=(async()=>{const l={event_id:e,session_id:i.sessionId,content:i.text,client_msg_id:`agent_single_${e}`,...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}},a=async()=>{const o=t===void 0?await this.handle.sendText(l):await this.handle.sendText(l,t);if(o.cmd!=="send_ack"){const r=o.payload;throw new Error(`single-message output rejected: cmd=${o.cmd} code=${r?.code??""} msg=${r?.msg??""}`)}};try{await a()}catch(o){if(!C(o))throw o;h.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${l.client_msg_id} event=${e}`),await a()}})();return this.singleMessageDeliveries.set(e,n),n}}function $(){const g=process.env.GRIX_STREAM_COALESCE_MS;if(g===void 0||g==="")return 500;const e=Number(g);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function R(g,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(g)||/^\[tool result\]/.test(g)}export{b as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,p as SendController};
1
+ import{isRequestTimeoutError as $}from"../core/aibot/errors.js";import{log as c}from"../core/log/index.js";import{splitTextForAibotProtocol as C,splitTextForSendMsg as S,AIBOT_PROTOCOL_MAX_RUNES as M,AIBOT_PROTOCOL_PAYLOAD_TOO_LARGE_CODE as R}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as D,isToolEventDropped as v,normalizeRuntimeConfigSnapshot as w}from"./runtime-config.js";const P={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;eventTriggerQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;openStreams=new Map;rejectedEvents=new Set;terminalEvents=new Set;terminalResultEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=q();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e),this.rejectedEvents.size>_.MAX_TERMINAL_EVENTS&&this.rejectedEvents.delete(this.rejectedEvents.values().next().value);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const i=this.streamCoalesce.get(s);i.timer&&clearTimeout(i.timer),this.streamCoalesce.delete(s)}c.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}hasTerminalResult(e){return!!e&&(this.terminalResultEvents.has(e)||this.terminalEvents.has(e))}rememberTerminalResult(e){if(e&&(this.terminalResultEvents.add(e),this.terminalResultEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalResultEvents.values().next().value;t!==void 0&&this.terminalResultEvents.delete(t)}}markEventStopped(e){e&&(this.stoppedEvents.add(e),c.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,i,r,a){!e||!this.stoppedEvents.has(e)||c.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${i} is_finish=${r} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id),this.terminalResultEvents.delete(e.event_id);const t=w(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const i=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:i.responseDelivery,toolEvents:i.toolEvents,thinkingEvents:i.thinkingEvents}),c.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${i.responseDelivery} tool_events=${i.toolEvents} thinking_events=${i.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id);const s=typeof e.quoted_message_id=="string"?e.quoted_message_id.trim():"";s&&!this.eventTriggerQuotedMessageIds.has(e.event_id)&&this.eventTriggerQuotedMessageIds.set(e.event_id,s)}discardEventState(e){e&&(this.rememberTerminalResult(e),this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.eventTriggerQuotedMessageIds.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&c.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of[...this.openStreams.keys()])t.startsWith(`${e}:`)&&this.openStreams.delete(t);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}applyExplicitFinalQuote(e,t,s){const i=typeof s=="string"?s.trim():"";if(!i)return;const r=this.bufferedEventTexts.get(e);r&&!r.quotedMessageId&&(r.quotedMessageId=i);const a=this.streamCoalesce.get(`${e}:${t??"default"}`);return a&&!a.quotedMessageId&&(a.quotedMessageId=i),i}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}getCodexDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventTriggerQuotedMessageIds.get(e)??this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return v(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return D(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,i,r,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&A(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const n=C(s),o=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(n.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:i||void 0});return}for(let u=0;u<n.length;u++){const h=u===n.length-1;this.sendStreamChunk(e,t,n[u],u+1,h,o,i)}return}this.sendMsgInProtocolParts(e,t,s,i,r)}sendMsgInProtocolParts(e,t,s,i,r){const a=r?[s]:S(s);a.length===0&&a.push(s);const l=a.length>1;for(let n=0;n<a.length;n++)this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:a[n],...n===0&&i?{quoted_message_id:i}:{},...r?{extra:r}:{},...l?{client_msg_id:`agent_msg_${e||Date.now()}_p${n+1}`}:{}})}sendStreamChunk(e,t,s,i,r,a,l,n){if(this.isEventClosed(e))return;l=l??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",i,r,(s||"").length);const o=this.resolveEventRuntimeConfig(e);if(!n?.forceStream&&o.responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,l,a);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,i,r,a,l,n?.threadId);return}this.coalesceStreamChunk(e,t,s,r,a,l,n?.threadId)}async sendFinalStreamChunkReliable(e,t,s,i,r=!1,a=!1,l){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const n=this.applyExplicitFinalQuote(e,s,l),o=this.resolveEventRuntimeConfig(e);if(!r&&o.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,i),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const u=`${e}:${s??"default"}`;this.flushCoalesce(u,!1),this.streamCoalesce.delete(u);const h=(this.chunkSeqMap.get(u)??0)+1;this.chunkSeqMap.set(u,h),this.openStreams.delete(u);const g=n||this.getDefaultQuotedMessageId(e),p={event_id:e,session_id:t,delta_content:"",chunk_seq:h,is_finish:!0,...s?{client_msg_id:s}:{},...g?{quoted_message_id:g}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",h,!0,0);const d=async()=>{const f=await this.handle.sendStreamChunkRequest(p,i);if(f.cmd!=="send_ack"){const E=f.payload;throw new Error(`final chunk rejected: cmd=${f.cmd} code=${E?.code??""} msg=${E?.msg??""}`)}};try{await d()}catch(f){if($(f))c.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${h} event=${e}`),await d();else throw c.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${f}`),f}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,i){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const l=this.getDefaultQuotedMessageId(e),n=C(s);for(let o=0;o<n.length;o++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",o+1,!1,n[o].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:n[o],...o===0&&l?{quoted_message_id:l}:{},client_msg_id:n.length>1?`${i}_p${o+1}`:i});return!0}const a=C(s);for(const l of a)this.sendStreamChunk(e,t,l,0,!1,i);return await this.sendFinalStreamChunkReliable(e,t,i,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,i,r,a,l){if(!s&&!i)return;const n=`${e}:${r??"default"}`;let o=this.streamCoalesce.get(n);if(o||(o={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:a,threadId:l,text:"",flushedOnce:!1},this.streamCoalesce.set(n,o)),s&&(o.text+=s),o.sessionId=t,r!==void 0&&(o.clientMsgId=r),!o.quotedMessageId&&a&&(o.quotedMessageId=a),!o.threadId&&l&&(o.threadId=l),i){this.flushCoalesce(n,!0);return}if(!o.flushedOnce||o.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(n,!1);return}o.timer||(o.timer=setTimeout(()=>this.flushCoalesce(n,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const i=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!i&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,i,0,t,s.clientMsgId,s.quotedMessageId,s.threadId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,i,r,a,l,n){const o=s||(r?`
2
+ `:"");if(!o&&!r)return;const u=C(o,M);u.length===0&&u.push(o||`
3
+ `);const h=`${e}:${a??"default"}`;for(let g=0;g<u.length;g++){const p=g===u.length-1,d=this.chunkSeqMap.get(h)??0,f=g===0&&i>d?i:d+1;this.chunkSeqMap.set(h,f),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:u[g],chunk_seq:f,is_finish:p&&r,...a?{client_msg_id:a}:{},...l?{quoted_message_id:l}:{},...n?{thread_id:n}:{}})}e&&(r?this.openStreams.delete(h):this.openStreams.set(h,{eventId:e,sessionId:t,clientMsgId:a,quotedMessageId:l}))}finalizeOpenStreams(e){if(!e||this.isEventClosed(e))return;this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const t=`${e}:`;for(const[s,i]of[...this.openStreams]){if(!s.startsWith(t))continue;this.openStreams.delete(s);const r=(this.chunkSeqMap.get(s)??0)+1;this.chunkSeqMap.set(s,r),this.handle.sendStreamChunk({event_id:i.eventId,session_id:i.sessionId,delta_content:"",chunk_seq:r,is_finish:!0,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}}),c.info("send-ctrl",`appended missing stream fence before terminal event=${i.eventId} client_msg_id=${i.clientMsgId??"default"} chunk_seq=${r}`)}}sendEventResult(e,t,s,i,r=!1){if(!e||this.hasTerminalResult(e))return;this.rememberTerminalResult(e),this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const a=this.ensureSingleMessageDelivery(e),l=(n,o=s,u=i)=>{n==="responded"&&this.rejectedEvents.has(e)&&(n="failed",u=u||"agent_output_rejected",o=o||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:n,...o?{msg:o}:{},...u?{code:u}:{},...r&&n===t?{error_surfaced:!0}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!a){l(t);return}a.then(()=>l(t),n=>{const o=`final output delivery failed: ${n instanceof Error?n.message:String(n)}`;l(t==="responded"?"failed":t,t==="responded"?o:s,t==="responded"?"agent_output_delivery_failed":i)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const i=C(s,M);i.length===0&&i.push(s),this.thinkingSessionMap.set(e,t);for(const r of i){const a=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,a),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:r,chunk_seq:a,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}}sendToolExecutionCard(e,t,s,i){if(this.shouldDropToolDisplayEvent(e)){c.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),l=`${e}:${s.summaryText}:${s.detailText??""}`,n=this.recentToolCards.get(l);if(n!==void 0&&a-n<_.TOOL_CARD_DEDUP_MS){c.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(l,a);const o={summary_text:s.summaryText};s.detailText&&(o.detail_text=s.detailText),c.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:i??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:o}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,i,r){r=r??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,r)}bufferStreamChunk(e,t,s,i,r){const a=typeof r=="string"&&r.startsWith("reply_"),l=this.bufferedEventTexts.get(e);if(!l){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:i||void 0,replyReceived:a});return}a?l.replyReceived?s&&(l.text+=s):(l.text=s??"",l.replyReceived=!0):!l.replyReceived&&s&&(l.text+=s),!l.quotedMessageId&&i&&(l.quotedMessageId=i)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const i=this.bufferedEventTexts.get(e);if(!i||(this.bufferedEventTexts.delete(e),!i.text))return;const r=(async()=>{const a=async(n,o,u,h)=>{const g={event_id:e,session_id:i.sessionId,content:n,client_msg_id:o,...u?{quoted_message_id:u}:{}},p=async()=>t===void 0?this.handle.sendText(g):this.handle.sendText(g,t);let d;try{d=await p()}catch(y){if(!$(y))throw y;c.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${o} event=${e}`),d=await p()}if(d.cmd==="send_ack")return;const f=d.payload,E=Number(f?.code??0);if(E===R&&h<4){const y=Math.max(1,Math.ceil([...n].length/2)),T=S(n,y);if(T.length>1){c.warn("send-ctrl",`single-message too large (code=${E}), splitting ${[...n].length} runes into ${T.length} parts depth=${h+1} event=${e}`);for(let k=0;k<T.length;k++)await a(T[k],`${o}.${k+1}`,k===0?u:void 0,h+1);return}}throw new Error(`single-message output rejected: cmd=${d.cmd} code=${f?.code??""} msg=${f?.msg??""}`)},l=S(i.text);for(let n=0;n<l.length;n++)await a(l[n],l.length>1?`agent_single_${e}_p${n+1}`:`agent_single_${e}`,n===0?i.quotedMessageId:void 0,0)})();return this.singleMessageDeliveries.set(e,r),r}}function q(){const m=process.env.GRIX_STREAM_COALESCE_MS;if(m===void 0||m==="")return 500;const e=Number(m);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function A(m,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(m)||/^\[tool result\]/.test(m)}export{P as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1,2 +1,2 @@
1
- import{EventEmitter as I}from"node:events";import{randomUUID as w}from"node:crypto";import T from"node:os";import k from"ws";import{log as m}from"../log/index.js";import{getMachineName as F}from"../util/index.js";import{detectTailnetIPv4 as P,ensureServerAndGetPort as q,getFileServerHttpsPort as B}from"../files/file-serve.js";import{TerminalOutbox as D}from"../persistence/terminal-outbox.js";import{TerminalCommitTokenStore as N}from"../persistence/terminal-commit-token-store.js";import{StopResultOutbox as U}from"../persistence/stop-result-outbox.js";import{AIBOT_PROTOCOL_SEND_RETRYABLE_CODE as $,computeAibotSendThrottleDelayMs as W,pruneAibotSendWindow as L,resolveAibotSendRetryDelayMs as S,resolveAibotSendRetryMaxAttempts as C}from"../protocol/protocol-send.js";import{AUTH_CODE_AGENT_DELETED as A,KICKED_REASON_AGENT_DELETED as R,AgentDeletedError as M,RequestTimeoutError as x}from"./errors.js";function G(E){let e="",t=0,n=!1,s=!1;for(;t<E.length;){const i=E[t];if(n){e+=i,s?s=!1:i==="\\"?s=!0:i==='"'&&(n=!1),t++;continue}if(i==='"'){n=!0,e+=i,t++;continue}if(i==="-"||i>="0"&&i<="9"){const r=t;i==="-"&&t++;const a=t;for(;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;let o=!1;if(E[t]===".")for(o=!0,t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;if(E[t]==="e"||E[t]==="E")for(o=!0,t++,(E[t]==="+"||E[t]==="-")&&t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;const c=E.slice(r,t),u=t-a;e+=!o&&u>=16?`"${c}"`:c;continue}e+=i,t++}return e}function j(E){const e=[...E??["stream_chunk","local_action_v1","agent_invoke"]];return e.includes("agent_invoke")||e.push("agent_invoke"),e.includes("event_result_ack")||e.push("event_result_ack"),e.includes("terminal_commit_v1")||e.push("terminal_commit_v1"),e.includes("audit_replay_v2")||e.push("audit_replay_v2"),e.includes("session_send_quote_v1")||e.push("session_send_quote_v1"),e}function z(E){const e=[...E??["exec_approve","exec_reject"]];return e.includes("apply_relay_state")||e.push("apply_relay_state"),e.includes("connector_admin")||e.push("connector_admin"),e}const H="aibot-agent-api-v1",K=1;class p extends I{static DROPPABLE_COMMANDS=new Set(["update_binding_card"]);static OUTPUT_NACK_CMDS=new Set(["send_msg","client_stream_chunk"]);static UNMATCHED_NACK_LOG_WINDOW_MS=5*6e4;unmatchedNackLoggedAt=new Map;static BUFFER_OVERFLOW_RETAIN_COMMANDS=new Set(["event_result","codex_event","client_stream_chunk","send_msg","audit_state"]);static MAX_OUTBOUND_BUFFER_SIZE=1e3;static MAX_OUTBOUND_BUFFER_HARD_SIZE=1200;static MAX_UNFENCED_REPLAY_CHUNKS_PER_EVENT=1e3;static BACKPRESSURE_THRESHOLD=64*1024;static TERMINAL_RETRY_DELAY_MS=15e3;static MAX_TOKENIZED_TERMINAL_REJECTIONS=5;static EVENT_CORRELATION_TTL_MS=5*6e4;static MAX_EVENT_CORRELATIONS=1024;static MAX_BLOCKED_OUTPUT_EVENTS=4096;static MAX_COMMITTED_TERMINAL_EVENTS=4096;static OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS=1e4;static MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS=2e4;static ORDERED_OUTPUT_COMMANDS=new Set(["client_stream_chunk","send_msg","codex_event"]);ws=null;seq=0;heartbeatTimer=null;heartbeatSec=30;heartbeatFailures=0;static HEARTBEAT_MAX_FAILURES=2;connected=!1;reconnecting=!1;reconnectAttempts=0;reconnectRunGeneration=0;everConnected=!1;agentDeleted=!1;config;packetLog;pendingInvokes=new Map;eventCorrelations=new Map;clientMsgEventMap=new Map;eventCorrelationCleanupTimer=null;lastCorrelationPruneAt=0;pendingRequests=new Map;outboundBuffer=[];outboundEntryOrders=new WeakMap;nextOutboundEntryOrder=0;connectionGeneration=0;nextOutboundFlushGeneration=0;outboundFlushInFlight=null;pendingOutputWrites=new Map;pendingOutputSeqsByEvent=new Map;pendingAcceptedOutputs=new Map;pendingAcceptedOutputSeqsByEvent=new Map;pendingAcceptedSeqsByClientMsgId=new Map;unfencedOutputEventsBySocket=new Map;provisionalRespondedTerminals=new Map;outputIntegrityFailed=new Map;blockedOutputEvents=new Map;committedTerminalEvents=new Set;ackPolicy=null;negotiatedCapabilities=new Set;terminalOutbox;terminalCommitTokens;stopResultOutbox;terminalInFlight=new Set;terminalRetryTimers=new Map;terminalReplayAfterFlight=new Set;tokenizedTerminalRejections=new Map;stopResultInFlight=new Set;stopResultRetryTimers=new Map;sendMsgWindowBySession=new Map;sendMsgAttempts=new WeakMap;sendMsgRetryAfter=new WeakMap;rateLimitedSeqs=new Set;sendMsgRequestWaiters=new Map;constructor(e,t){super(),this.packetLog=t?.packetLog??null,this.config={url:e.url,agentId:e.agentId,apiKey:e.apiKey,clientType:e.clientType,clientVersion:e.clientVersion??"",adapterHint:e.adapterHint??"",capabilities:j(e.capabilities),localActions:z(e.localActions),skills:e.skills,librarySkills:e.librarySkills,sharedOwnerId:e.sharedOwnerId,concurrency:e.concurrency,terminalOutboxPath:e.terminalOutboxPath,terminalCommitTokenStorePath:e.terminalCommitTokenStorePath,stopResultOutboxPath:e.stopResultOutboxPath},this.terminalOutbox=new D(this.config.terminalOutboxPath),this.terminalCommitTokens=new N(this.config.terminalCommitTokenStorePath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.tokens`:void 0)),this.stopResultOutbox=new U(this.config.stopResultOutboxPath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.stops`:void 0));for(const n of this.terminalOutbox.listPending())n.payload.code==="agent_output_integrity_failed"&&this.blockEventOutput(n.payload.event_id)}get isConnected(){return this.connected}async connect(){this.negotiatedCapabilities.clear();const e=this.ws,t=this.connectionGeneration;if(this.pendingRequests.size>0&&this.rejectAllPendingRequests("connection generation replaced"),e){this.connected=!1,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers();const o=this.outboundFlushInFlight;o&&o.socket===e&&o.connectionGeneration===t&&this.cancelOutboundFlush(o,"connection_lost","connection generation replaced"),this.settleUnfencedOutputsForSocket(e,"connection generation replaced"),this.abortPendingOutputWrites(!0,e,t,"connection generation replaced"),this.abortPendingAcceptedOutputs(!0,e,t),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1012,"connection generation replaced")}catch{}this.ws===e&&(this.ws=null)}else this.outboundFlushInFlight&&this.cancelOutboundFlush(this.outboundFlushInFlight,"discard","detached connection generation replaced");const n=++this.connectionGeneration;let s,i,r;const a=(async()=>{try{if(s=await P(),s!==void 0)try{i=await q(s);const o=B();o>0&&(r=o)}catch(o){m.warn("aibot",`file server pre-start failed: ${o}`)}}catch(o){m.warn("aibot",`tailnet detect failed: ${o}`)}})();return new Promise((o,c)=>{const u=new k(this.config.url);this.ws=u;const f=setTimeout(()=>{if(!this.isConnectionCurrent(u,n))return;const d=this.pendingRequests.get(g);d&&(this.pendingRequests.delete(g),clearTimeout(d.timer),d.reject(new Error("Auth timeout: no auth_ack received within 15s"))),this.cleanupSocket(u,n)},15e3),g=++this.seq,b=setTimeout(()=>{if(!this.isConnectionCurrent(u,n))return;const d=this.pendingRequests.get(g);d&&(this.pendingRequests.delete(g),d.reject(new Error("Auth request timeout"))),this.cleanupSocket(u,n)},15e3);this.pendingRequests.set(g,{expected:["auth_ack"],resolve:d=>{clearTimeout(f);const l=d.payload;if(l.code===0){this.negotiatedCapabilities=new Set(Array.isArray(l.supported_capabilities)?l.supported_capabilities:[]),this.connected=!0,this.everConnected=!0,this.reconnectAttempts=0,l.heartbeat_sec&&(this.heartbeatSec=l.heartbeat_sec),l.ack_policy&&(this.ackPolicy=l.ack_policy,m.info("aibot",`ack_policy received: push_ack_timeout_ms=${l.ack_policy.push_ack_timeout_ms??"default"} max_retries=${l.ack_policy.max_retries??"default"} timeout_action=${l.ack_policy.timeout_action??"default"}`)),this.startHeartbeat();const h=this.flushOutboundBuffer(u,n);this.emit("auth",l),o(l),h.then(_=>{this.isConnectionCurrent(u,n)&&(_?(this.replayTerminalOutbox(),this.replayStopResultOutbox()):this.reconnectAfterOutboundFlushFailure(u,n))})}else l.code===A?(this.agentDeleted=!0,c(new M(`Agent deleted: code=${l.code} msg=${l.msg}`))):c(new Error(`Auth failed: code=${l.code} msg=${l.msg}`))},reject:d=>{clearTimeout(f),c(d)},timer:b}),u.on("open",async()=>{if(await a,!this.isConnectionCurrent(u,n))return;const d={agent_id:this.config.agentId,api_key:this.config.apiKey,client_type:this.config.clientType,protocol_version:H,contract_version:K,capabilities:this.config.capabilities??[],local_actions:this.config.localActions,skills:this.config.skills,library_skills:this.config.librarySkills};this.config.sharedOwnerId&&(d.shared_owner_id=this.config.sharedOwnerId),this.config.clientVersion&&(d.client="grix-connector",d.client_version=this.config.clientVersion,d.host_type=this.config.clientType,d.host_version=this.config.clientVersion),this.config.adapterHint&&(d.adapter_hint=this.config.adapterHint),d.host_meta={hostname:F(),platform:T.platform(),arch:T.arch(),os_release:T.release(),...s!==void 0&&{tailnet_ip:s},...i!==void 0&&i>0&&{file_server_port:i},...r!==void 0&&r>0&&{file_server_https_port:r}},this.config.concurrency&&(d.concurrency=this.config.concurrency),this.sendPacket("auth",d,g)}),u.on("message",d=>{if(!this.isConnectionCurrent(u,n))return;let l;try{l=JSON.parse(G(d.toString()))}catch{return}try{this.handlePacket(l)}catch(h){this.emitClientError(new Error(`handlePacket error: ${h}`))}}),u.on("close",(d,l)=>{if(!this.isConnectionCurrent(u,n))return;const h=this.everConnected&&!this.agentDeleted;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("websocket closed");const _=`websocket closed code=${d} reason=${l.toString()||"<none>"}`,O=this.outboundFlushInFlight;O&&O.socket===u&&O.connectionGeneration===n&&this.cancelOutboundFlush(O,h?"connection_lost":"discard",_),h?this.settleUnfencedOutputsForSocket(u,_):this.unfencedOutputEventsBySocket.delete(u),this.abortPendingOutputWrites(h,u,n,h?_:void 0),this.abortPendingAcceptedOutputs(h,u,n),this.clearAllEventCorrelations(),this.ws===u&&(this.ws=null),this.connectionGeneration++,this.emit("close",d,l.toString());const y=h;m.info("aibot",`ws closed agent=${this.config.clientType}:${this.config.agentId} code=${d} reason=${l.toString()||"<none>"} everConnected=${this.everConnected} reconnecting=${this.reconnecting} agentDeleted=${this.agentDeleted} willReconnect=${y}`),y&&this.attemptReconnect(d===1e3||d===1001)}),u.on("error",d=>{if(this.isConnectionCurrent(u,n)&&(this.emitClientError(d instanceof Error?d:new Error(String(d))),!this.connected)){const l=this.pendingRequests.get(g);l&&(this.pendingRequests.delete(g),clearTimeout(l.timer),l.reject(d instanceof Error?d:new Error(String(d))))}})})}handlePacket(e){if(this.packetLog?.logInboundPacket(e.cmd,e.seq,e.payload),this.handleCorrelatedSendResponse(e),e.seq>0&&this.pendingRequests.has(e.seq)){const t=this.pendingRequests.get(e.seq);this.pendingRequests.delete(e.seq),clearTimeout(t.timer),t.expected.includes(e.cmd)?t.resolve(e):t.reject(new Error(`unexpected response: got ${e.cmd}, expected ${t.expected.join("/")}`));return}switch(e.cmd){case"auth_ack":break;case"ping":{this.sendPacket("pong",e.payload??{});break}case"event_msg":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("event",t);break}case"local_action":{this.emit("localAction",e.payload);break}case"event_stop":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("stop",t);break}case"event_revoke":{this.emit("revoke",e.payload);break}case"event_edit":{this.emit("edit",e.payload);break}case"event_cancel":{this.emit("eventCancel",e.payload);break}case"queue_clear":{this.emit("queueClear",e.payload);break}case"queue_reorder":{this.emit("queueReorder",e.payload);break}case"queue_snapshot_query":{this.emit("queueSnapshotQuery",e.payload);break}case"event_hold":{this.emit("eventHold",e.payload);break}case"queue_edit":{this.emit("queueEdit",e.payload);break}case"control_share_set":{this.emit("shareSet",e.payload);break}case"agent_profile_push":{this.emit("profilePush",e.payload);break}case"skill_sync":{this.emit("skillSync",e.payload);break}case"kicked":{const t=e.payload;this.emit("kicked",t),this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("kicked");const n=this.ws,s=this.connectionGeneration,i=this.outboundFlushInFlight;if(i&&n&&i.socket===n&&i.connectionGeneration===this.connectionGeneration&&this.cancelOutboundFlush(i,t?.reason===R?"discard":"connection_lost",`kicked reason=${t?.reason??"<none>"}`),t?.reason!==R&&n&&this.settleUnfencedOutputsForSocket(n,`kicked reason=${t?.reason??"<none>"}`),this.abortPendingOutputWrites(t?.reason!==R,n??void 0,s,t?.reason!==R?`kicked reason=${t?.reason??"<none>"}`:void 0),this.abortPendingAcceptedOutputs(t?.reason!==R,n??void 0,s),this.clearAllEventCorrelations(),this.connectionGeneration++,t?.reason===R){if(this.agentDeleted=!0,this.reconnecting=!1,this.outboundBuffer.length=0,this.outputIntegrityFailed.clear(),this.unfencedOutputEventsBySocket.clear(),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws=null}m.error("aibot",`kicked: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}, reconnect disabled`),this.emit("agentDeleted",{source:"kicked",reason:t.reason});break}if(this.reconnectAttempts=Math.max(this.reconnectAttempts,3),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws===n&&(this.ws=null)}this.attemptReconnect();break}case"error":{const t=e.payload,n=[t.ref_cmd?`ref_cmd=${t.ref_cmd}`:"",t.ref_id?`ref_id=${t.ref_id}`:""].filter(Boolean).join(" ");this.emitClientError(new Error(`Server error: code=${t.code} msg=${t.msg}${n?` ${n}`:""}`));break}case"agent_invoke_result":{this.handleInvokeResult(e.payload);break}case"mcp_frame":{const t=e.payload;this.emit("mcpFrame",t.session_id??"",t.frame??null);break}case"send_ack":break;case"send_nack":this.logUnmatchedNack(e);break;case"local_action_ack":break;default:break}}captureInboundTerminalCommitToken(e,t){const n=t?.trim();if(!n)return!0;if(!e?.trim())return this.rejectInboundTerminalCommitToken("tokenized event is missing event_id"),!1;if(!this.negotiatedCapabilities.has("terminal_commit_v1"))return this.rejectInboundTerminalCommitToken(`tokenized event received without terminal_commit_v1 negotiation event=${e}`),!1;try{return this.terminalCommitTokens.register(e,n),!0}catch(s){return this.rejectInboundTerminalCommitToken(`terminal commit token persist failed event=${e}: ${s instanceof Error?s.message:s}`),!1}}rejectInboundTerminalCommitToken(e){this.emitClientError(new Error(e));const t=this.ws;if(t)try{t.close(1011,"terminal commit token persistence failed")}catch{}}withTerminalCommitToken(e){const t=e.event_id.trim();if(!t)throw new Error("terminal event_result is missing event_id");const n=e.terminal_commit_token?.trim(),s=this.terminalCommitTokens.get(t);if(n&&s&&n!==s)throw new Error(`terminal commit token mismatch for event=${t}`);n&&!s&&this.terminalCommitTokens.register(t,n);const i=s??n;return i?{...e,event_id:t,terminal_commit_token:i}:{...e,event_id:t}}sendEventAck(e){this.sendPacket("event_ack",e)||m.warn("aibot",`event_ack NOT sent (ws not open) event=${e.event_id} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}sendStreamChunk(e){!e.delta_content&&!e.is_finish&&(m.warn("aibot",`stream_chunk delta_content empty, patched to newline event=${e.event_id??""} session=${e.session_id} chunk_seq=${e.chunk_seq} is_finish=${e.is_finish}`),e={...e,delta_content:`
2
- `}),this.sendPacket("client_stream_chunk",e)}sendMsg(e){const t={...e,client_msg_id:e.client_msg_id?.trim()||w()};this.sendPacket("send_msg",t)||m.warn("aibot",`send_msg queued or NOT sent event=${t.event_id??""} session=${t.session_id??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}sendMsgDelay(e,t=!1){const n=e.session_id?.trim();if(!n)return 0;const s=Date.now();for(const[a,o]of this.sendMsgWindowBySession){const c=L(o,s);c.length?this.sendMsgWindowBySession.set(a,c):this.sendMsgWindowBySession.delete(a)}const i=this.sendMsgWindowBySession.get(n)??[],r=W(i,s);return t&&r===0&&(i.push(s),this.sendMsgWindowBySession.set(n,i)),r}async awaitSendMsgRequestSlot(e,t,n,s=0){for(;;){if(!this.connected||!this.isConnectionCurrent(t,n))throw new Error("connection changed while waiting for send_msg rate slot");const i=this.outboundFlushInFlight;if(i&&!i.finalized){if(!await i.promise)throw new Error("outbound flush failed before send_msg");continue}const r=Math.max(this.sendMsgDelay(e),s-Date.now());if(r<=0)return;await new Promise((a,o)=>{const c=()=>{clearTimeout(u),this.sendMsgRequestWaiters.delete(c),o(new Error("connection lost while waiting for send_msg rate slot"))},u=setTimeout(()=>{this.sendMsgRequestWaiters.delete(c),a()},r);u.unref?.(),this.sendMsgRequestWaiters.set(c,{socket:t,generation:n})})}}tryRetrySendMsgNack(e,t,n){if(n!==$)return!1;const s=this.pendingAcceptedOutputs.get(e);if(!s||s.entry.cmd!=="send_msg"||s.eventId!==t)return!1;const{entry:i}=s,r=this.sendMsgAttempts.get(i)??1;return r>=C()?!1:(this.sendMsgAttempts.set(i,r+1),this.sendMsgRetryAfter.set(i,Date.now()+S(r)),this.rememberRateLimitedSeq(e),this.settlePendingOutputWrite(e,!0,!1),this.removeSeqFromEventCorrelation(e),this.bufferOutboundEntry(i),this.settlePendingAcceptedOutput(e,"retry",!1),m.warn("aibot",`send_msg rate limited event=${t} seq=${e} retry=${r+1}/${C()}`),this.connected&&this.startPacedOutboundFlush(),!0)}rememberRateLimitedSeq(e){this.rateLimitedSeqs.add(e),this.rateLimitedSeqs.size>p.MAX_BLOCKED_OUTPUT_EVENTS&&this.rateLimitedSeqs.delete(this.rateLimitedSeqs.values().next().value)}startPacedOutboundFlush(){const e=this.ws,t=this.connectionGeneration;this.flushOutboundBuffer().then(n=>{!n&&e&&this.connected&&this.isConnectionCurrent(e,t)&&this.reconnectAfterOutboundFlushFailure(e,t)})}editMsg(e){this.sendPacket("edit_msg",e)}sendEventResult(e){try{e=this.withTerminalCommitToken(e)}catch(o){this.emitClientError(new Error(`event_result token validation failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}const t=this.terminalOutbox.get(e.event_id);let n,s=this.outputIntegrityFailed.get(e.event_id);const i=t;if(!s&&i?.payload.code==="agent_output_integrity_failed"&&(s={reason:i.payload.msg??"required agent output was discarded before delivery",terminalObserved:!1,terminalSettled:!1},this.outputIntegrityFailed.set(e.event_id,s)),s){if(s.terminalObserved=!0,this.provisionalRespondedTerminals.delete(e.event_id),i&&i.payload.code!=="agent_output_integrity_failed"&&!this.canReplaceUnsentOutputGuard(i)){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(i?.payload.code==="agent_output_integrity_failed"){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(s.terminalSettled||this.committedTerminalEvents.has(e.event_id)&&!i){this.outputIntegrityFailed.delete(e.event_id);return}try{n=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e.event_id,s.reason))}catch(o){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0});return}if(this.committedTerminalEvents.has(e.event_id)&&!t){m.info("aibot",`ignored duplicate terminal after committed ACK event=${e.event_id} status=${e.status}`);return}if(t){if(!(this.canReplaceUnsentOutputGuard(t)&&(e.status==="canceled"||e.status==="failed"))){m.info("aibot",`preserving first durable terminal event=${e.event_id} existing_status=${t.payload.status} ignored_status=${e.status}`),this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}this.provisionalRespondedTerminals.delete(e.event_id)}if(e.status==="responded"&&this.hasUnfencedOutput(e.event_id)&&!this.hasPendingOutputAcceptanceFence(e.event_id)){this.markOutputIntegrityFailed(e.event_id,"terminal requested before a complete output acceptance fence");const o=this.outputIntegrityFailed.get(e.event_id);o&&(o.terminalObserved=!0);return}const r=e.status==="responded"&&this.hasUnconfirmedEventOutput(e.event_id),a=r?{...e,status:"failed",code:"agent_output_unconfirmed",msg:"required agent output was not durably confirmed before connector restart",updated_at:Date.now()}:e;r?this.provisionalRespondedTerminals.set(e.event_id,{...e}):this.provisionalRespondedTerminals.delete(e.event_id);try{n=this.terminalOutbox.enqueue(a)}catch(o){this.provisionalRespondedTerminals.delete(e.event_id),this.emitClientError(new Error(`event_result outbox persist failed: event=${e.event_id} status=${e.status}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0})}sendLocalActionResult(e){this.sendPacket("local_action_result",e)}sendEventStopAck(e){this.sendPacket("event_stop_ack",e)}sendEventStopResult(e){const t=e.event_id?.trim(),n=e.terminal_commit_token?.trim(),s=t?this.terminalCommitTokens.get(t):void 0;if(n&&s&&n!==s){this.emitClientError(new Error(`event_stop_result token mismatch event=${t??""}`));return}const i=s??n;if(t&&i&&(e.status==="stopped"||e.status==="already_finished")){try{const r=this.stopResultOutbox.enqueue({...e,event_id:t,terminal_commit_token:i});this.scheduleStopResultDelivery(r,{ignoreNotBefore:!0})}catch(r){this.emitClientError(new Error(`event_stop_result outbox persist failed: event=${t} stop=${e.stop_id}: ${r instanceof Error?r.message:r}`))}return}this.sendPacket("event_stop_result",e)}sendSessionActivitySet(e){this.sendPacket("session_activity_set",e)}sendCodexEvent(e){this.sendPacket("codex_event",e)}sendUpdateBindingCard(e){this.sendPacket("update_binding_card",e)}sendAuditState(e){this.sendPacket("audit_state",e)}sendSkillsUpdate(e){this.sendPacket("agent_skills_update",e)}sendPing(){this.sendPacket("ping",{})}sendEventState(e){this.sendPacket("event_state",e)}sendEventCancelResult(e){this.sendPacket("event_cancel_result",e)}sendQueueClearResult(e){this.sendPacket("queue_clear_result",e)}sendQueueReorderResult(e){this.sendPacket("queue_reorder_result",e)}sendEventHoldResult(e){this.sendPacket("event_hold_result",e)}sendQueueEditResult(e){this.sendPacket("queue_edit_result",e)}sendQueueSnapshot(e){this.sendPacket("queue_snapshot",e)}agentInvoke(e,t,n=15e3){return new Promise((s,i)=>{const r=w(),a=Math.max(1e3,Math.min(n,75e3)),o=setTimeout(()=>{this.pendingInvokes.delete(r),i(new Error(`agent_invoke timeout: ${e}`))},a);this.pendingInvokes.set(r,{resolve:s,reject:i,timer:o}),this.sendPacket("agent_invoke",{invoke_id:r,action:e,params:t,timeout_ms:a})})}sendMcpFrame(e,t){this.sendPacket("mcp_frame",{session_id:e,frame:t})}async request(e,t,n){const s=this.outboundFlushInFlight;if(s){if(!await s.promise)throw new Error(`outbound flush failed before request: ${e}`);if(!this.isConnectionCurrent(s.socket,s.connectionGeneration))throw new Error(`connection changed while waiting for outbound flush: ${e}`)}if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN)throw new Error(`send failed: ${e} (websocket not connected)`);for(;e==="send_msg"&&(this.sendMsgDelay(t)>0||this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized);)await this.awaitSendMsgRequestSlot(t,this.ws,this.connectionGeneration);return new Promise((i,r)=>{const a=++this.seq,o=setTimeout(()=>{this.pendingRequests.delete(a),r(new x(`request timeout: ${e} (expected ${n.expected.join("/")})`))},n.timeoutMs);this.pendingRequests.set(a,{expected:n.expected,resolve:i,reject:r,timer:o,retryRateLimit:n.retryRateLimit}),this.sendPacket(e,t,a)||(this.pendingRequests.delete(a),clearTimeout(o),r(new Error(`send failed: ${e}`)))})}async sendStreamChunkRequest(e,t=2e4){return this.request("client_stream_chunk",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async relayCredentialRequest(e,t=15e3){return this.request("relay_credential_request",e,{expected:["relay_credential_result","error"],timeoutMs:t})}async relayStateSyncRequest(e,t=15e3){return this.request("relay_state_sync_request",e,{expected:["relay_state_sync_result","error"],timeoutMs:t})}sendRelayStateReport(e){this.sendPacket("relay_state_report",e)}async sendText(e,t=2e4){return this.sendMessageRequestWithRetry({msg_type:1,...e,client_msg_id:e.client_msg_id?.trim()||w()},t)}async sendMedia(e,t=2e4){return this.sendMessageRequestWithRetry({...e,msg_type:2,client_msg_id:e.client_msg_id?.trim()||w()},t)}async sendMessageRequestWithRetry(e,t){const n=C();for(let s=1;;s++){const i=await this.request("send_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t,retryRateLimit:s<n});if(i.cmd==="send_ack"||Number(i.payload.code)!==$||s>=n)return i;if(!this.ws)throw new Error("connection lost before send_msg retry");await this.awaitSendMsgRequestSlot(e,this.ws,this.connectionGeneration,Date.now()+S(s))}}async editMessage(e,t=2e4){return this.request("edit_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async deleteMessage(e,t,n=2e4){return this.request("delete_msg",{session_id:e,msg_id:t},{expected:["send_ack","send_nack","error"],timeoutMs:n})}async sendEventResultRequest(e,t=5e3){return this.request("event_result",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}disconnect(){m.info("aibot",`disconnect() agent=${this.config.clientType}:${this.config.agentId} wasConnected=${this.connected} reconnecting=${this.reconnecting} reconnectAttempts=${this.reconnectAttempts}`),this.connected=!1,this.negotiatedCapabilities.clear(),this.everConnected=!1,this.reconnecting=!1,this.reconnectRunGeneration++,this.reconnectAttempts=0,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.sendMsgWindowBySession.clear(),this.rateLimitedSeqs.clear();const e=this.ws,t=this.connectionGeneration,n=this.outboundFlushInFlight;n&&this.cancelOutboundFlush(n,"discard","explicit disconnect"),this.connectionGeneration++,this.rejectAllPendingInvokes("disconnect"),this.rejectAllPendingRequests("disconnect"),this.abortPendingOutputWrites(!1,e??void 0,t),this.abortPendingAcceptedOutputs(!1,e??void 0,t),this.clearAllEventCorrelations(),this.outboundBuffer.length=0,this.provisionalRespondedTerminals.clear(),this.outputIntegrityFailed.clear(),this.unfencedOutputEventsBySocket.clear(),this.ws&&(this.ws.close(1e3,"client disconnect"),this.ws=null)}static MAX_CONSECUTIVE_AUTH_FAILURES=5;async attemptReconnect(e=!1){if(this.reconnecting||this.agentDeleted)return;this.reconnecting=!0;const t=++this.reconnectRunGeneration;m.info("aibot",`attemptReconnect start agent=${this.config.clientType}:${this.config.agentId} fromAttempts=${this.reconnectAttempts} fastFirstAttempt=${e}`),this.emit("disconnected");let n=0;for(;this.reconnecting&&this.reconnectRunGeneration===t;){const s=e&&this.reconnectAttempts===0,i=s?Math.floor(Math.random()*500):Math.min(1e3*2**this.reconnectAttempts,3e4),r=s?0:Math.floor(i*.2*Math.random());if(this.reconnectAttempts++,await new Promise(c=>setTimeout(c,i+r)),!this.reconnecting||this.reconnectRunGeneration!==t)return;let a=null,o=this.connectionGeneration;try{const c=this.connect();if(a=this.ws,o=this.connectionGeneration,await c,this.reconnectRunGeneration!==t)return;if(!a||!this.isConnectionCurrent(a,o)){if(this.connected&&this.ws){this.reconnecting=!1;return}continue}const u=this.reconnectAttempts;this.reconnectAttempts=0,this.reconnecting=!1,m.info("aibot",`reconnect succeeded agent=${this.config.clientType}:${this.config.agentId} attempt=${u}`);return}catch(c){if(this.reconnectRunGeneration!==t)return;if(a&&!this.isConnectionCurrent(a,o)&&this.connected&&this.ws){this.reconnecting=!1;return}if(a&&this.isConnectionCurrent(a,o)){this.connectionGeneration++;try{a.close()}catch{}this.ws===a&&(this.ws=null)}const u=c instanceof Error?c.message:String(c);if(m.warn("aibot",`reconnect failed agent=${this.config.clientType}:${this.config.agentId} attempt=${this.reconnectAttempts} err=${u}`),c instanceof M){this.agentDeleted=!0,this.reconnecting=!1,m.error("aibot",`reconnect aborted: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}`),this.emit("agentDeleted",{source:"auth_ack",code:A});return}if(/Auth failed/i.test(u)){if(n++,n>=p.MAX_CONSECUTIVE_AUTH_FAILURES){this.reconnecting=!1,m.error("aibot",`reconnect giving up after ${n} consecutive auth failures agent=${this.config.clientType}:${this.config.agentId}`);return}}else n=0}}}sendPacket(e,t,n){const s=this.outboundEventId(e,t);if(s&&this.blockedOutputEvents.has(s))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),m.warn("aibot",`blocked late output after irreversible event failure event=${s} cmd=${e}`),!1;const i=n===void 0?this.createOutboundEntry(e,t):void 0;if(i&&this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized&&this.isConnectionCurrent(this.outboundFlushInFlight.socket,this.outboundFlushInFlight.connectionGeneration)&&!p.DROPPABLE_COMMANDS.has(e))return this.bufferOutboundEntry(i),!1;if(e==="send_msg"&&i&&this.connected&&this.ws?.readyState===k.OPEN&&this.sendMsgDelay(t)>0)return this.bufferOutboundEntry(i),this.startPacedOutboundFlush(),!1;if(this.ws&&this.ws.readyState===k.OPEN&&(e==="auth"||this.connected)){const a=this.ws.bufferedAmount>p.BACKPRESSURE_THRESHOLD;if(!a||!p.DROPPABLE_COMMANDS.has(e)){if(a&&p.DROPPABLE_COMMANDS.has(e))return!1;e==="send_msg"&&this.sendMsgDelay(t,!0);const o=n??++this.seq,c={cmd:e,seq:o,payload:t};this.packetLog?.logOutboundPacket(e,o,t,"sent");const u=this.ws,f=this.connectionGeneration,g=s;g&&this.trackOutboundEventCorrelation(e,o,t),i&&g&&(this.registerPendingOutputWrite(o,g,i,u,f),this.isAckRequiredOutput(e,t)&&this.registerPendingAcceptedOutput(o,g,i,u,f));let b=!1;try{const d=u.readyState,l=u.bufferedAmount;let h=!1;return u.send(JSON.stringify(c),_=>{if(_&&!h&&(b=!0),e==="event_result"){const v=t;_?m.warn("aibot",`event_result ws send callback failed event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`event_result ws send callback ok event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(e==="client_stream_chunk"){const v=t;_?m.warn("aibot",`stream_chunk ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`stream_chunk ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} client_msg_id=${v.client_msg_id??""} quoted_message_id=${v.quoted_message_id??""} readyState=${d} bufferedAmount=${l}`)}else if(e==="event_ack"){const v=t;_?m.warn("aibot",`event_ack ws send failed event=${v.event_id??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`event_ack ws send ok event=${v.event_id??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(e==="send_msg"){const v=t;_?m.warn("aibot",`send_msg ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`send_msg ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(_){const v=t;m.warn("aibot",`${e} ws send failed seq=${o} session=${v.session_id??""} event=${v.event_id??""} client_msg_id=${v.client_msg_id??""} readyState=${d} bufferedAmount=${l} err=${_.message}`)}const O=this.pendingOutputWrites.get(o),y=!!(O&&O.socket===u&&O.connectionGeneration===f);if(!this.isConnectionCurrent(u,f)){y&&(this.settlePendingOutputWrite(o,!1,!1,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f));return}if(!(i&&g&&!y)){if(_)this.removeSeqFromEventCorrelation(o),g?(this.settlePendingOutputWrite(o,!1,!0,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f)):i&&this.bufferOutboundEntry(i),n!==void 0?this.rejectPendingRequestAfterWriteFailure(o,e,_):i&&this.reconnectAfterOutboundWriteFailure(u,`${e} callback failed`);else if(g){const v=y;this.settlePendingOutputWrite(o,!0,!1,u,f),v&&O&&this.trackUnfencedOutput(u,O.entry,o)}}}),h=!0,!b}catch(d){return this.isConnectionCurrent(u,f)?(this.removeSeqFromEventCorrelation(o),g?(this.settlePendingOutputWrite(o,!1,!0,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f)):i&&this.bufferOutboundEntry(i),this.emitClientError(new Error(`sendPacket failed: ${d}`)),i&&this.reconnectAfterOutboundWriteFailure(u,`${e} send threw`),!1):(this.settlePendingOutputWrite(o,!1,!1,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f),!1)}}}if(p.DROPPABLE_COMMANDS.has(e))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),!1;if(n!==void 0)return this.packetLog?.logOutboundPacket(e,n,t,"dropped"),!1;const r=this.bufferOutboundEntry(i??this.createOutboundEntry(e,t));if(this.packetLog?.logOutboundPacket(e,n??0,t,r?"buffered":"dropped"),r&&e==="client_stream_chunk"){const a=t;m.info("aibot",`stream_chunk buffered (ws not open) event=${a.event_id??""} session=${a.session_id??""} chunk_seq=${a.chunk_seq??""} is_finish=${a.is_finish??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}return!1}replayTerminalOutbox(){for(const e of this.terminalOutbox.listPending())this.scheduleTerminalDelivery(e.payload.event_id,{ignoreNotBefore:!0})}outboundEventId(e,t){if(!p.ORDERED_OUTPUT_COMMANDS.has(e)||!t||typeof t!="object")return"";const n=t.event_id;return typeof n=="string"?n.trim():""}blockEventOutput(e){const t=e.trim();if(t)for(this.blockedOutputEvents.delete(t),this.blockedOutputEvents.set(t,Date.now()),this.outboundBuffer=this.outboundBuffer.filter(n=>this.outboundEventId(n.cmd,n.payload)!==t),this.outboundFlushInFlight?.wakePacing?.();this.blockedOutputEvents.size>p.MAX_BLOCKED_OUTPUT_EVENTS;){const n=this.blockedOutputEvents.keys().next().value;if(!n)break;this.blockedOutputEvents.delete(n)}}isAckRequiredOutput(e,t){return e==="send_msg"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish===!0}isNonReplayableOutput(e){return!1}isReplayableStreamDelta(e,t){return e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish!==!0}isReplayableUnfencedOutput(e,t){return this.isReplayableStreamDelta(e,t)?!0:e==="codex_event"}trackUnfencedOutput(e,t,n){const{cmd:s,payload:i}=t;if(!this.isReplayableUnfencedOutput(s,i))return;const a=this.outboundEventId(s,i);if(!a||this.outputIntegrityFailed.has(a)||this.blockedOutputEvents.has(a))return;let o=this.unfencedOutputEventsBySocket.get(e);o||(o=new Map,this.unfencedOutputEventsBySocket.set(e,o));let c=o.get(a);if(c||(c={seq:0,replay:[]},o.set(a,c)),c.seq=Math.max(c.seq,n),!!c.replay){if(c.replay.length>=p.MAX_UNFENCED_REPLAY_CHUNKS_PER_EVENT){c.replay=null;return}c.replay.includes(t)||c.replay.push(t)}}clearUnfencedOutputThrough(e,t,n){if(!e||n<=0)return;const s=this.unfencedOutputEventsBySocket.get(e);if(!s)return;const i=s.get(t)?.seq;i===void 0||i>n||(s.delete(t),s.size===0&&this.unfencedOutputEventsBySocket.delete(e))}clearUnfencedOutputEvent(e){for(const[t,n]of this.unfencedOutputEventsBySocket)n.delete(e),n.size===0&&this.unfencedOutputEventsBySocket.delete(t)}settleUnfencedOutputsForSocket(e,t){const n=this.unfencedOutputEventsBySocket.get(e);if(n){this.unfencedOutputEventsBySocket.delete(e);for(const[s,i]of n){if(!i.replay){this.markOutputIntegrityFailed(s,`connection lost before a complete output acceptance fence: ${t}`);continue}if(this.committedTerminalEvents.has(s)||this.outputIntegrityFailed.has(s)||this.blockedOutputEvents.has(s))continue;let r=0;for(const a of i.replay){if(!this.bufferOutboundEntry(a))break;r++}m.info("aibot",`requeued unfenced stream chunks for replay event=${s} chunks=${r}/${i.replay.length} reason=${t}`)}}}hasUnfencedOutput(e){for(const t of this.unfencedOutputEventsBySocket.values())if(t.has(e))return!0;return!1}hasBufferedEventOutput(e,t=!1){const n=i=>this.outboundEventId(i.cmd,i.payload)===e&&(!t||this.isAckRequiredOutput(i.cmd,i.payload)),s=this.outboundFlushInFlight;return this.outboundBuffer.some(n)||!!s?.activeBatch?.slice(s.nextIndex).some(n)}hasPendingOutputAcceptanceFence(e){return!!(this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.hasBufferedEventOutput(e,!0))}hasUnconfirmedEventOutput(e){return!!(this.pendingOutputSeqsByEvent.get(e)?.size||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.hasBufferedEventOutput(e))}trackOutboundEventCorrelation(e,t,n){const s=this.outboundEventId(e,n);if(!s)return;const i=n,r=typeof i.client_msg_id=="string"?i.client_msg_id.trim():"";this.pruneExpiredEventCorrelations();const a=Date.now();let o=this.eventCorrelations.get(s);if(!o){if(this.eventCorrelations.size>=p.MAX_EVENT_CORRELATIONS){let u;for(const f of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(f.eventId)||(!u||f.touchedAt<u.touchedAt)&&(u=f);u&&this.releaseEventCorrelations(u.eventId)}o={eventId:s,clientMsgIds:new Set,seqRanges:[],touchedAt:a,expiresAt:a+p.EVENT_CORRELATION_TTL_MS},this.eventCorrelations.set(s,o)}o.touchedAt=a,o.expiresAt=a+p.EVENT_CORRELATION_TTL_MS;const c=o.seqRanges[o.seqRanges.length-1];if(c&&t===c.end+1?c.end=t:(!c||t<c.start||t>c.end)&&o.seqRanges.push({start:t,end:t}),r){o.clientMsgIds.add(r);let u=this.clientMsgEventMap.get(r);u||(u=new Set,this.clientMsgEventMap.set(r,u)),u.add(s)}this.scheduleEventCorrelationCleanup()}uniqueEventIdForClientMsgId(e){const t=this.clientMsgEventMap.get(e);if(t?.size===1)return t.values().next().value}eventHasCriticalDeliveryState(e){return!!(this.terminalOutbox.get(e)||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size)}eventIdForSeq(e){if(!(e<=0)){for(const t of this.eventCorrelations.values())if(t.seqRanges.some(n=>e>=n.start&&e<=n.end))return t.eventId}}removeSeqFromEventCorrelation(e){if(!(e<=0))for(const t of this.eventCorrelations.values()){const n=t.seqRanges.findIndex(i=>e>=i.start&&e<=i.end);if(n<0)continue;const s=t.seqRanges[n];s.start===s.end?t.seqRanges.splice(n,1):e===s.start?s.start++:e===s.end?s.end--:t.seqRanges.splice(n,1,{start:s.start,end:e-1},{start:e+1,end:s.end});return}}releaseEventCorrelations(e){const t=e.trim();if(!t)return;const n=this.eventCorrelations.get(t);if(n){for(const s of n.clientMsgIds){const i=this.clientMsgEventMap.get(s);i?.delete(t),i?.size===0&&this.clientMsgEventMap.delete(s)}this.eventCorrelations.delete(t)}this.cancelEventCorrelationCleanupIfEmpty()}clearAllEventCorrelations(){this.eventCorrelationCleanupTimer&&(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null),this.eventCorrelations.clear(),this.clientMsgEventMap.clear(),this.lastCorrelationPruneAt=0}pruneExpiredEventCorrelations(e=Date.now(),t=!1){if(!(!t&&e-this.lastCorrelationPruneAt<1e3)){this.lastCorrelationPruneAt=e;for(const n of[...this.eventCorrelations.values()])n.expiresAt<=e&&!this.eventHasCriticalDeliveryState(n.eventId)&&this.releaseEventCorrelations(n.eventId);this.cancelEventCorrelationCleanupIfEmpty()}}scheduleEventCorrelationCleanup(){if(this.eventCorrelationCleanupTimer||this.eventCorrelations.size===0)return;let e=Number.POSITIVE_INFINITY;for(const t of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(t.eventId)||(e=Math.min(e,t.expiresAt));Number.isFinite(e)&&(this.eventCorrelationCleanupTimer=setTimeout(()=>{this.eventCorrelationCleanupTimer=null,this.pruneExpiredEventCorrelations(Date.now(),!0),this.scheduleEventCorrelationCleanup()},Math.max(1,e-Date.now())),this.eventCorrelationCleanupTimer.unref?.())}cancelEventCorrelationCleanupIfEmpty(){!this.eventCorrelationCleanupTimer||this.eventCorrelations.size>0||(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null)}logUnmatchedNack(e){const t=e.payload??{},n=typeof t.cmd=="string"?t.cmd.trim():"";if(!n||p.OUTPUT_NACK_CMDS.has(n))return;const s=typeof t.session_id=="string"?t.session_id.trim():"",i=typeof t.code=="number"?t.code:Number(t.code??0)||0,r=`${n}|${s}|${i}`,a=Date.now(),o=this.unmatchedNackLoggedAt.get(r)??0;if(o>0&&a-o<p.UNMATCHED_NACK_LOG_WINDOW_MS)return;if(this.unmatchedNackLoggedAt.size>=256){for(const[u,f]of this.unmatchedNackLoggedAt)a-f>=p.UNMATCHED_NACK_LOG_WINDOW_MS&&this.unmatchedNackLoggedAt.delete(u);this.unmatchedNackLoggedAt.size>=256&&this.unmatchedNackLoggedAt.clear()}this.unmatchedNackLoggedAt.set(r,a);const c=typeof t.msg=="string"?t.msg:"";m.warn("aibot",`backend rejected ${n} session=${s||"<none>"} code=${i} msg=${c||"<none>"} seq=${e.seq} (repeats suppressed for ${p.UNMATCHED_NACK_LOG_WINDOW_MS/1e3}s)`)}handleCorrelatedSendResponse(e){if(this.rateLimitedSeqs.has(e.seq))return;if(e.cmd==="send_ack"){const u=e.payload,f=typeof u.client_msg_id=="string"?u.client_msg_id.trim():"";let g=e.seq>0&&this.pendingAcceptedOutputs.has(e.seq)?e.seq:void 0,b;if(g===void 0&&f&&e.seq<=0){const h=this.pendingAcceptedSeqsByClientMsgId.get(f);if(h?.size===1){const _=h.values().next().value,O=this.pendingAcceptedOutputs.get(_),y=this.uniqueEventIdForClientMsgId(f);O&&y&&O.eventId===y&&(g=_,b=y)}}const d=(g!==void 0?this.pendingAcceptedOutputs.get(g)?.eventId:void 0)??b??this.eventIdForSeq(e.seq),l=g??e.seq;if(g!==void 0){const h=this.pendingOutputWrites.get(g);h&&this.settlePendingOutputWrite(g,!0,!1,h.socket,h.connectionGeneration),this.settlePendingAcceptedOutput(g,"accepted",!1),d&&this.clearUnfencedOutputThrough(this.ws,d,l)}else if(e.seq>0){const h=this.pendingOutputWrites.get(e.seq);if(h&&this.settlePendingOutputWrite(e.seq,!0,!1,h.socket,h.connectionGeneration),this.pendingRequests.has(e.seq)){const _=this.eventIdForSeq(e.seq);_&&this.clearUnfencedOutputThrough(this.ws,_,e.seq)}}return}if(e.cmd!=="send_nack"&&e.cmd!=="error")return;this.pruneExpiredEventCorrelations();const t=e.payload;if(Number(t.code)===$&&this.pendingRequests.get(e.seq)?.retryRateLimit){this.rememberRateLimitedSeq(e.seq);return}const n=typeof t.client_msg_id=="string"?t.client_msg_id.trim():"",s=e.cmd==="error"&&typeof t.ref_id=="string"?t.ref_id.trim():"",i=e.cmd==="error"&&typeof t.ref_cmd=="string"?t.ref_cmd.trim():"",r=this.eventIdForSeq(e.seq),a=s&&(!i||p.ORDERED_OUTPUT_COMMANDS.has(i))?this.uniqueEventIdForClientMsgId(s)??(this.eventCorrelations.has(s)?s:void 0):void 0,o=r??(n?this.uniqueEventIdForClientMsgId(n):void 0)??a;if(!o)return;const c=e.seq>0?e.seq:this.pendingAcceptedSeqsByClientMsgId.get(n||s)?.size===1?this.pendingAcceptedSeqsByClientMsgId.get(n||s).values().next().value:0;this.tryRetrySendMsgNack(c,o,Number(t.code??0))||(this.blockEventOutput(o),this.settlePendingOutputWritesForEvent(o,!0),this.clearUnfencedOutputEvent(o),e.seq>0&&this.pendingAcceptedOutputs.get(e.seq)?.eventId===o?this.settlePendingAcceptedOutput(e.seq,"rejected",!1):this.settlePendingAcceptedOutputsForEvent(o,"rejected",!1),t.code===4003&&(this.purgeBufferedStreamChunks(o),m.warn("aibot",`event payload rejected (4003), purging buffered chunks for event=${o}`)),this.promotePendingTerminalAfterOutputRejection(o,Number(t.code??0),t.msg),this.emit("streamRejected",o,Number(t.code??0)))}promotePendingTerminalAfterOutputRejection(e,t,n){this.provisionalRespondedTerminals.delete(e);const s=this.terminalOutbox.get(e);if(!(!s||s.payload.status!=="responded"&&s.payload.code!=="agent_output_unconfirmed"||s.deliveryStartedAt))try{const i=this.terminalOutbox.enqueue({...s.payload,status:"failed",code:"agent_output_rejected",msg:n?`required agent output was rejected: ${n}`:`required agent output was rejected by the server (code=${t})`,updated_at:Date.now()});this.scheduleTerminalDelivery(i.payload.event_id,{ignoreNotBefore:!0})}catch(i){this.emitClientError(new Error(`failed to persist output-rejection terminal promotion: event=${e} code=${t}: ${i instanceof Error?i.message:i}`))}}scheduleTerminalDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN)return;if(this.terminalInFlight.has(e)){t?.ignoreNotBefore&&this.terminalReplayAfterFlight.add(e);return}const n=this.terminalOutbox.get(e);if(!n)return;const s=this.terminalRetryTimers.get(e);s&&(clearTimeout(s),this.terminalRetryTimers.delete(e));const i=t?.ignoreNotBefore?0:Math.max(0,n.nextAttemptAt-Date.now()),r=Math.max(i,t?.minimumDelayMs??0);if(r>0){const a=setTimeout(()=>{this.terminalRetryTimers.delete(e),this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0})},r);this.terminalRetryTimers.set(e,a);return}this.deliverTerminalEntry(n)}async deliverTerminalEntry(e){const t=e.payload.event_id;if(this.terminalInFlight.has(t)||!this.terminalOutbox.isCurrent(e))return;this.terminalInFlight.add(t);let n=0;try{n=await this.sendEventResultReliable(e)}finally{this.terminalInFlight.delete(t);const s=this.terminalReplayAfterFlight.delete(t);this.terminalOutbox.get(t)&&this.scheduleTerminalDelivery(t,s?{ignoreNotBefore:!0}:{minimumDelayMs:n})}}clearTerminalRetryTimers(){for(const e of this.terminalRetryTimers.values())clearTimeout(e);this.terminalRetryTimers.clear()}async sendEventResultReliable(e){const t=e.payload.event_id,n=e.payload.terminal_commit_token?.trim();if(n&&!this.negotiatedCapabilities.has("terminal_commit_v1")){const f=this.ws;return this.emitClientError(new Error(`refusing tokenized event_result on an unnegotiated connection: event=${t}`)),f&&this.reconnectAfterOutboundWriteFailure(f,"terminal_commit_v1 not negotiated"),p.TERMINAL_RETRY_DELAY_MS}if(!await this.awaitOutputDeliveryBarrier(t))return p.TERMINAL_RETRY_DELAY_MS;const s=this.provisionalRespondedTerminals.get(t);if(s&&this.terminalOutbox.isCurrent(e))if(!this.canReplaceUnsentOutputGuard(e))this.provisionalRespondedTerminals.delete(t);else try{return this.terminalOutbox.enqueue(s),this.provisionalRespondedTerminals.delete(t),0}catch(f){return this.emitClientError(new Error(`failed to promote confirmed output terminal to responded: event=${t}: ${f instanceof Error?f.message:f}`)),p.TERMINAL_RETRY_DELAY_MS}const i=e.payload;try{if(!this.terminalOutbox.markDeliveryStarted(e))return 0}catch(f){return this.emitClientError(new Error(`event_result delivery-start persist failed: event=${t}: ${f instanceof Error?f.message:f}`)),p.TERMINAL_RETRY_DELAY_MS}const r=Math.max(1,this.ackPolicy?.max_retries??3),a=this.ackPolicy?.push_ack_timeout_ms??5e3,o=750;let c="unknown delivery failure";for(let f=1;f<=r;f++){if(!this.terminalOutbox.isCurrent(e))return 0;const g=this.ws?.readyState??-1,b=this.ws?.bufferedAmount??0;m.info("aibot",`event_result send attempt event=${i.event_id} status=${i.status} attempt=${f}/${r} readyState=${g} bufferedAmount=${b}`);try{const d=await this.sendEventResultRequest(i,a);if(!this.terminalOutbox.isCurrent(e))return 0;if(d.cmd==="send_ack"){const h=d.payload;if(m.info("aibot",`event_result ack event=${i.event_id} status=${i.status} attempt=${f}/${r} ack_event=${h.event_id??""} ack_status=${h.status??""}`),h.event_id!==i.event_id||h.status!==i.status)throw new Error(`event_result ACK mismatch: expected event=${i.event_id} status=${i.status}, got event=${h.event_id??""} status=${h.status??""}`);if(n&&(h.terminal_commit_token?.trim()!==n||h.terminal_committed!==!0))throw new Error(`event_result terminal commit ACK mismatch: event=${i.event_id}`);if(n)try{this.terminalCommitTokens.remove(i.event_id,n)}catch(_){throw new Error(`terminal commit token cleanup failed: event=${i.event_id}: ${_ instanceof Error?_.message:_}`)}return this.terminalOutbox.acknowledge(e,h.event_id,h.status,h.terminal_commit_token,h.terminal_committed)&&(this.rememberCommittedTerminalEvent(i.event_id),this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.scheduleStopResultsForEvent(i.event_id)),0}const l=d.payload;if(m.warn("aibot",`event_result rejected event=${i.event_id} status=${i.status} attempt=${f}/${r} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}${l.ref_cmd?` ref_cmd=${l.ref_cmd}`:""}${l.ref_id?` ref_id=${l.ref_id}`:""}`),n){c=`tokenized terminal rejected: cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`;const h=(this.tokenizedTerminalRejections.get(i.event_id)??0)+1;if(this.tokenizedTerminalRejections.set(i.event_id,h),h<p.MAX_TOKENIZED_TERMINAL_REJECTIONS)break;this.tokenizedTerminalRejections.delete(i.event_id);try{this.terminalCommitTokens.remove(i.event_id,n),this.terminalOutbox.moveToDeadLetter(e,{responseCmd:d.cmd,code:l.code,message:l.msg})&&(this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`tokenized event_result permanently rejected after ${h} rejections, moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`)))}catch(_){c=`dead-letter persist failed: ${_ instanceof Error?_.message:_}`,this.emitClientError(new Error(`tokenized event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${c}`));break}return 0}try{return this.terminalOutbox.moveToDeadLetter(e,{responseCmd:d.cmd,code:l.code,message:l.msg})&&(this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`event_result rejected and moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`))),0}catch(h){c=`dead-letter persist failed: ${h instanceof Error?h.message:h}`,this.emitClientError(new Error(`event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${c}`));break}}catch(d){const l=d instanceof Error?d.message:String(d);if(c=l,m.warn("aibot",`event_result attempt failed event=${i.event_id} status=${i.status} attempt=${f}/${r} err=${l}`),f===r)break;await new Promise(h=>setTimeout(h,o*f))}}const u=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.terminalOutbox.recordRetry(e,u,c)}catch(f){this.emitClientError(new Error(`event_result retry state persist failed: event=${i.event_id} status=${i.status}: ${f instanceof Error?f.message:f}`))}return this.emitClientError(new Error(`event_result ack failed after ${r} attempts; retained for retry: event=${i.event_id} status=${i.status} err=${c}`)),p.TERMINAL_RETRY_DELAY_MS}purgeBufferedStreamChunks(e){const t=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(n=>n.cmd!=="client_stream_chunk"?!0:n.payload?.event_id!==e),this.outboundBuffer.length<t&&m.info("aibot",`purged ${t-this.outboundBuffer.length} buffered stream chunks for event=${e}`)}emitClientError(e){if(this.listenerCount("error")===0){m.warn("aibot",`Client error (no listeners): ${e.message}`);return}this.emit("error",e)}createOutboundEntry(e,t){const n={cmd:e,payload:t};return this.outboundEntryOrders.set(n,++this.nextOutboundEntryOrder),n}makeOutputIntegrityFailurePayload(e,t){return this.withTerminalCommitToken({event_id:e,status:"failed",code:"agent_output_integrity_failed",msg:`required agent output was discarded before delivery: ${t}`,updated_at:Date.now()})}canReplaceUnsentOutputGuard(e){return e.payload.code==="agent_output_unconfirmed"&&!e.deliveryStartedAt}rememberCommittedTerminalEvent(e){for(this.committedTerminalEvents.delete(e),this.committedTerminalEvents.add(e);this.committedTerminalEvents.size>p.MAX_COMMITTED_TERMINAL_EVENTS;){const t=this.committedTerminalEvents.values().next().value;if(!t)break;this.committedTerminalEvents.delete(t)}}replayStopResultOutbox(){for(const e of this.stopResultOutbox.listPending())this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})}scheduleStopResultsForEvent(e){for(const t of this.stopResultOutbox.listPending())t.payload.event_id===e&&this.scheduleStopResultDelivery(t,{ignoreNotBefore:!0})}scheduleStopResultDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN||!this.stopResultOutbox.isCurrent(e))return;const n=e.payload.event_id;if(this.terminalOutbox.get(n)||this.terminalCommitTokens.get(n))return;const s=this.stopResultRetryTimers.get(e.key);s&&(clearTimeout(s),this.stopResultRetryTimers.delete(e.key));const i=t?.ignoreNotBefore?0:Math.max(0,e.nextAttemptAt-Date.now());if(i>0){const r=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},i);this.stopResultRetryTimers.set(e.key,r);return}this.deliverStopResultEntry(e)}async deliverStopResultEntry(e){if(this.stopResultInFlight.has(e.key)||!this.stopResultOutbox.isCurrent(e))return;this.stopResultInFlight.add(e.key);let t=p.TERMINAL_RETRY_DELAY_MS;try{t=await this.sendStopResultReliable(e)}finally{if(this.stopResultInFlight.delete(e.key),this.stopResultOutbox.isCurrent(e)){const n=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},t);this.stopResultRetryTimers.set(e.key,n)}}}async sendStopResultReliable(e){const t=this.ackPolicy?.push_ack_timeout_ms??5e3;let n="unknown delivery failure";try{const i=await this.request("event_stop_result",e.payload,{expected:["send_ack","send_nack","error"],timeoutMs:t});if(!this.stopResultOutbox.isCurrent(e))return 0;if(i.cmd==="send_ack"){const r=i.payload;if(this.stopResultOutbox.acknowledge(e,r.event_id,r.terminal_commit_token,r.terminal_committed))return 0;n=`event_stop_result ACK mismatch event=${e.payload.event_id}`}else{const r=i.payload;if(n=`event_stop_result rejected: cmd=${i.cmd} code=${r.code??""} msg=${r.msg??""}`,r.code===4001||r.code===4003){try{this.stopResultOutbox.discard(e)&&this.emitClientError(new Error(`event_stop_result permanently rejected and discarded: event=${e.payload.event_id} stop=${e.payload.stop_id} code=${r.code} msg=${r.msg??""}`))}catch(a){this.emitClientError(new Error(`event_stop_result discard persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${a instanceof Error?a.message:a}`))}return 0}}}catch(i){n=i instanceof Error?i.message:String(i)}const s=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.stopResultOutbox.recordRetry(e,s,n)}catch(i){this.emitClientError(new Error(`event_stop_result retry state persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${i instanceof Error?i.message:i}`))}return this.emitClientError(new Error(`event_stop_result retained for retry: event=${e.payload.event_id} stop=${e.payload.stop_id} err=${n}`)),p.TERMINAL_RETRY_DELAY_MS}clearStopResultRetryTimers(){for(const e of this.stopResultRetryTimers.values())clearTimeout(e);this.stopResultRetryTimers.clear()}markOutputIntegrityFailed(e,t){if(this.blockEventOutput(e),this.outputIntegrityFailed.has(e))return;const n={reason:t,terminalObserved:!!(this.provisionalRespondedTerminals.has(e)||this.terminalOutbox.get(e)),terminalSettled:!1};this.outputIntegrityFailed.set(e,n),this.provisionalRespondedTerminals.delete(e),this.clearUnfencedOutputEvent(e);const s=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(a=>this.outboundEventId(a.cmd,a.payload)!==e);const i=this.terminalOutbox.get(e),r=i?this.canReplaceUnsentOutputGuard(i):!1;if(i&&!r)n.terminalObserved=!0,this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0});else if(!this.committedTerminalEvents.has(e))try{const a=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e,t));this.scheduleTerminalDelivery(a.payload.event_id,{ignoreNotBefore:!0})}catch(a){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e}: ${a instanceof Error?a.message:a}`))}for(const a of[...this.pendingOutputSeqsByEvent.get(e)??[]])this.settlePendingOutputWrite(a,!1,!1);this.settlePendingAcceptedOutputsForEvent(e,"rejected",!1),this.emit("streamRejected",e,0),this.emitClientError(new Error(`required output integrity failed: event=${e} removed=${s-this.outboundBuffer.length} reason=${t}`))}settleOutputIntegrityTerminal(e){const t=this.outputIntegrityFailed.get(e);t&&(t.terminalSettled=!0,t.terminalObserved&&this.outputIntegrityFailed.delete(e))}bufferOutboundEntry(e){if(this.outboundEntryOrders.has(e)||this.outboundEntryOrders.set(e,++this.nextOutboundEntryOrder),this.outboundBuffer.includes(e))return!0;const t=this.outboundEventId(e.cmd,e.payload);return t&&(this.outputIntegrityFailed.has(t)||this.blockedOutputEvents.has(t))?!1:(this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&(this.outboundBuffer=this.outboundBuffer.filter(n=>p.BUFFER_OVERFLOW_RETAIN_COMMANDS.has(n.cmd)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&m.warn("aibot",`outbound buffer soft limit exceeded by ${this.outboundBuffer.length} retained packet(s); preserving required output`)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_HARD_SIZE?(t?this.markOutputIntegrityFailed(t,`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached`):this.emitClientError(new Error(`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached; rejected non-event packet cmd=${e.cmd}`)),!1):(this.outboundBuffer.push(e),this.outboundBuffer.sort((n,s)=>(this.outboundEntryOrders.get(n)??Number.MAX_SAFE_INTEGER)-(this.outboundEntryOrders.get(s)??Number.MAX_SAFE_INTEGER)),!0))}registerPendingOutputWrite(e,t,n,s,i){let r;const a=new Promise(u=>{r=u}),o=setTimeout(()=>{const u=this.pendingOutputWrites.get(e);if(!u||u.socket!==s||u.connectionGeneration!==i)return;if(!this.isConnectionCurrent(s,i)){this.settlePendingOutputWrite(e,!1,!1,s,i);return}this.removeSeqFromEventCorrelation(e);const f=this.isNonReplayableOutput(n.cmd);this.settlePendingOutputWrite(e,!1,!f,s,i),f&&this.markOutputIntegrityFailed(t,`websocket write callback timed out for non-replayable ${n.cmd} seq=${e}`),this.emitClientError(new Error(`outbound websocket write callback timeout: cmd=${n.cmd} event=${t} seq=${e} delivery_unknown=${f}`)),this.reconnectAfterOutboundWriteFailure(s,`${n.cmd} callback timeout`)},p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);o.unref?.(),this.pendingOutputWrites.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:a,resolve:r,timer:o});let c=this.pendingOutputSeqsByEvent.get(t);c||(c=new Set,this.pendingOutputSeqsByEvent.set(t,c)),c.add(e)}settlePendingOutputWrite(e,t,n,s,i){const r=this.pendingOutputWrites.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingOutputWrites.delete(e),clearTimeout(r.timer);const a=this.pendingOutputSeqsByEvent.get(r.eventId);a?.delete(e),a?.size===0&&this.pendingOutputSeqsByEvent.delete(r.eventId),n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingOutputWritesForEvent(e,t){const n=this.pendingOutputSeqsByEvent.get(e);if(n)for(const s of[...n]){const i=this.pendingOutputWrites.get(s);i&&this.settlePendingOutputWrite(s,t,!1,i.socket,i.connectionGeneration)}}abortPendingOutputWrites(e,t,n,s){for(const[i,r]of[...this.pendingOutputWrites.entries()])if(!(t&&(r.socket!==t||r.connectionGeneration!==n))){if(this.removeSeqFromEventCorrelation(i),s&&this.isNonReplayableOutput(r.entry.cmd)){this.settlePendingOutputWrite(i,!1,!1,t,n),this.markOutputIntegrityFailed(r.eventId,`connection lost while websocket write completion was unknown: ${s}`);continue}this.settlePendingOutputWrite(i,!1,e,t,n)}}registerPendingAcceptedOutput(e,t,n,s,i){let r;const a=new Promise(h=>{r=h}),o=Math.max(1,this.ackPolicy?.push_ack_timeout_ms??5e3),c=Math.max(1,this.ackPolicy?.max_retries??3),u=Math.max(1e3,Math.ceil(o*.25)),f=Math.max(p.MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS,o*c+u),g=setTimeout(()=>{const h=this.pendingAcceptedOutputs.get(e);if(!(!h||h.socket!==s||h.connectionGeneration!==i)){if(!this.isConnectionCurrent(s,i)){this.settlePendingAcceptedOutput(e,"retry",!1,s,i);return}this.settlePendingAcceptedOutput(e,"retry",!0,s,i),this.emitClientError(new Error(`required output ACK timeout; retained for reconnect retry: event=${t} seq=${e}`)),this.reconnectAfterOutboundWriteFailure(s,"required output ACK timeout")}},f);g.unref?.(),this.pendingAcceptedOutputs.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:a,resolve:r,timer:g});const b=n.payload,d=typeof b.client_msg_id=="string"?b.client_msg_id.trim():"";if(d){let h=this.pendingAcceptedSeqsByClientMsgId.get(d);h||(h=new Set,this.pendingAcceptedSeqsByClientMsgId.set(d,h)),h.add(e)}let l=this.pendingAcceptedOutputSeqsByEvent.get(t);l||(l=new Set,this.pendingAcceptedOutputSeqsByEvent.set(t,l)),l.add(e)}settlePendingAcceptedOutput(e,t,n,s,i){const r=this.pendingAcceptedOutputs.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingAcceptedOutputs.delete(e),clearTimeout(r.timer);const a=this.pendingAcceptedOutputSeqsByEvent.get(r.eventId);a?.delete(e),a?.size===0&&this.pendingAcceptedOutputSeqsByEvent.delete(r.eventId);const o=r.entry.payload,c=typeof o.client_msg_id=="string"?o.client_msg_id.trim():"";if(c){const u=this.pendingAcceptedSeqsByClientMsgId.get(c);u?.delete(e),u?.size===0&&this.pendingAcceptedSeqsByClientMsgId.delete(c)}n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingAcceptedOutputsForEvent(e,t,n){const s=this.pendingAcceptedOutputSeqsByEvent.get(e);if(s)for(const i of[...s])this.settlePendingAcceptedOutput(i,t,n)}abortPendingAcceptedOutputs(e,t,n){for(const[s,i]of this.sendMsgRequestWaiters)(!t||i.socket===t&&i.generation===n)&&s();for(const[s,i]of[...this.pendingAcceptedOutputs.entries()])t&&(i.socket!==t||i.connectionGeneration!==n)||this.settlePendingAcceptedOutput(s,"retry",e,t,n)}rejectPendingRequestAfterWriteFailure(e,t,n){const s=this.pendingRequests.get(e);s&&(this.pendingRequests.delete(e),clearTimeout(s.timer),s.reject(new Error(`websocket write failed: ${t}: ${n.message}`)))}async awaitOutputDeliveryBarrier(e){const t=this.outboundFlushInFlight;if(t&&!await t.promise)return!1;for(;;){const n=this.pendingOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingOutputWrites.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;if((await Promise.all(s)).some(r=>!r))return!1}for(;;){const n=this.pendingAcceptedOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingAcceptedOutputs.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;const i=await Promise.all(s);if(i.includes("retry"))return this.outboundFlushInFlight?this.awaitOutputDeliveryBarrier(e):!1;if(i.includes("rejected")){const r=this.terminalOutbox.get(e);if(!r||r.payload.status==="responded")return!1}}return this.outboundBuffer.some(n=>this.outboundEventId(n.cmd,n.payload)===e)?!1:this.hasUnfencedOutput(e)?(this.markOutputIntegrityFailed(e,"output flush completed without a complete acceptance fence"),!1):!!(this.connected&&this.ws&&this.ws.readyState===k.OPEN)}isConnectionCurrent(e,t){return this.ws===e&&this.connectionGeneration===t}isOutboundFlushCurrent(e){return!e.finalized&&this.outboundFlushInFlight===e&&this.isConnectionCurrent(e.socket,e.connectionGeneration)}flushOutboundBuffer(e=this.ws,t=this.connectionGeneration){if(!e||!this.isConnectionCurrent(e,t))return Promise.resolve(!1);const n=this.outboundFlushInFlight;if(n){if(!n.finalized&&n.socket===e&&n.connectionGeneration===t)return n.promise;this.cancelOutboundFlush(n,"discard","superseded stale flush")}if(this.outboundBuffer.length===0)return Promise.resolve(!0);const s={connectionGeneration:t,flushGeneration:++this.nextOutboundFlushGeneration,socket:e,promise:Promise.resolve(!1),finalized:!1,activeBatch:null,nextIndex:0,currentWritePending:!1,currentWriteOutcome:null,cancelCurrentWrite:null,remainderHandled:!1};return this.outboundFlushInFlight=s,s.promise=this.performOutboundBufferFlush(s),s.promise.finally(()=>{s.finalized=!0,s.cancelCurrentWrite?.(),s.cancelCurrentWrite=null,this.outboundFlushInFlight===s&&(this.outboundFlushInFlight=null)}),s.promise}awaitOutboundPacing(e,t){return new Promise(n=>{const s=r=>{clearTimeout(i),e.cancelCurrentWrite=null,e.wakePacing=void 0,n(r)},i=setTimeout(()=>s(this.isOutboundFlushCurrent(e)),t);i.unref?.(),e.wakePacing=()=>s(this.isOutboundFlushCurrent(e)),e.cancelCurrentWrite=()=>s(!1)})}async performOutboundBufferFlush(e){for(;this.isOutboundFlushCurrent(e)&&this.outboundBuffer.length>0;){const{socket:t}=e;if(t.readyState!==k.OPEN)return!1;const n=this.outboundBuffer;this.outboundBuffer=[],e.activeBatch=n,e.nextIndex=0,e.remainderHandled=!1;for(let s=0;s<n.length;s++){if(!this.isOutboundFlushCurrent(e))return!1;const i=n[s],{cmd:r,payload:a}=i,o=this.outboundEventId(r,a);if(e.nextIndex=s,r==="send_msg"){for(;this.isOutboundFlushCurrent(e)&&!(o&&this.blockedOutputEvents.has(o));){const g=Math.max(this.sendMsgDelay(a),(this.sendMsgRetryAfter.get(i)??0)-Date.now());if(g<=0)break;if(!await this.awaitOutboundPacing(e,g))return!1}if(!this.isOutboundFlushCurrent(e))return!1}if(o&&this.blockedOutputEvents.has(o)){this.packetLog?.logOutboundPacket(r,0,a,"dropped"),e.nextIndex=s+1,e.currentWritePending=!1,e.currentWriteOutcome=null;continue}r==="send_msg"&&this.sendMsgDelay(a,!0);const c=++this.seq,u={cmd:r,seq:c,payload:a};e.nextIndex=s,e.currentWritePending=!0,e.currentWriteOutcome=null,o&&this.isAckRequiredOutput(r,a)&&this.registerPendingAcceptedOutput(c,o,i,t,e.connectionGeneration);const f=await new Promise(g=>{let b=!1;const d=h=>{b||(b=!0,clearTimeout(l),e.currentWriteOutcome=h,g(h))},l=setTimeout(()=>d("uncertain"),p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);l.unref?.(),e.cancelCurrentWrite=()=>d("canceled");try{this.trackOutboundEventCorrelation(r,c,a),t.send(JSON.stringify(u),h=>{d(h?"retry":"written")})}catch{d("retry")}});if(e.cancelCurrentWrite=null,!this.isOutboundFlushCurrent(e))return!1;if(f!=="written"||t.readyState!==k.OPEN){f==="retry"&&this.removeSeqFromEventCorrelation(c),this.settlePendingAcceptedOutput(c,"retry",!1);const g=this.retainOutboundFlushRemainder(e,f,`auth flush write failed for ${r} seq=${c} outcome=${f}`);return this.emitClientError(new Error(`outbound buffer flush failed at cmd=${r} seq=${c} outcome=${f}; ${g} packet(s) retained`)),!1}this.trackUnfencedOutput(t,i,c),e.currentWritePending=!1,e.currentWriteOutcome="written",e.nextIndex=s+1}e.activeBatch=null,e.currentWritePending=!1,e.currentWriteOutcome=null,e.remainderHandled=!0}return this.isOutboundFlushCurrent(e)}retainOutboundFlushRemainder(e,t,n){if(e.remainderHandled||!e.activeBatch)return 0;e.remainderHandled=!0;const s=e.activeBatch,i=Math.min(e.nextIndex,s.length);let r=i;if(e.currentWritePending&&i<s.length){const o=s[i],c=this.outboundEventId(o.cmd,o.payload);t!=="retry"&&this.isNonReplayableOutput(o.cmd)&&c&&(this.markOutputIntegrityFailed(c,n),r=i+1)}let a=0;for(const o of s.slice(r))this.bufferOutboundEntry(o)&&a++;return e.activeBatch=null,e.nextIndex=s.length,e.currentWritePending=!1,a}cancelOutboundFlush(e,t,n){if(e.finalized){this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null);return}e.finalized=!0,this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null),t==="connection_lost"?this.retainOutboundFlushRemainder(e,e.currentWriteOutcome,`connection lost during auth flush: ${n}`):(e.remainderHandled=!0,e.activeBatch=null,e.currentWritePending=!1);const s=e.cancelCurrentWrite;e.cancelCurrentWrite=null,s?.()}reconnectAfterOutboundFlushFailure(e,t){this.agentDeleted||!this.isConnectionCurrent(e,t)||this.reconnectAfterOutboundWriteFailure(e,"outbound flush failed")}reconnectAfterOutboundWriteFailure(e,t){this.abandonSocketAndReconnect(e,this.connectionGeneration,t)}abandonSocketAndReconnect(e,t,n){if(this.agentDeleted||!this.isConnectionCurrent(e,t))return;const s=t,i=e.readyState;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests(n);const r=this.outboundFlushInFlight;r&&r.socket===e&&r.connectionGeneration===s&&this.cancelOutboundFlush(r,"connection_lost",n),this.settleUnfencedOutputsForSocket(e,n),this.abortPendingOutputWrites(!0,e,s,n),this.abortPendingAcceptedOutputs(!0,e,s),this.clearAllEventCorrelations(),this.connectionGeneration++,this.ws===e&&(this.ws=null),this.forceDestroySocket(e,n),m.warn("aibot",`abandon socket and reconnect agent=${this.config.clientType}:${this.config.agentId} reason=${n} readyState=${i}`),this.attemptReconnect()}forceDestroySocket(e,t){try{const n=e;if(typeof n.terminate=="function"){n.terminate();return}}catch{}try{e.close(1011,t)}catch{}}handleInvokeResult(e){const t=this.pendingInvokes.get(e.invoke_id);t&&(this.pendingInvokes.delete(e.invoke_id),clearTimeout(t.timer),e.code===0?t.resolve(e.data??null):t.reject(new Error(`agent_invoke error code=${e.code}: ${e.msg??""}`)))}rejectAllPendingInvokes(e){for(const[,t]of this.pendingInvokes)clearTimeout(t.timer),t.reject(new Error(`agent_invoke canceled: ${e}`));this.pendingInvokes.clear()}rejectAllPendingRequests(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`request canceled: ${e}`));this.pendingRequests.clear()}cleanupSocket(e=this.ws,t=this.connectionGeneration){if(!(!e||!this.isConnectionCurrent(e,t)))try{e.close()}catch{}}startHeartbeat(){this.stopHeartbeat(),this.heartbeatFailures=0,this.heartbeatTimer=setInterval(()=>{const e=this.ws,t=this.connectionGeneration;!this.connected||!e||this.request("ping",{ts:Date.now()},{expected:["pong"],timeoutMs:5e3}).then(()=>{this.isConnectionCurrent(e,t)&&(this.heartbeatFailures=0)}).catch(n=>{if(!this.connected||!this.isConnectionCurrent(e,t))return;this.heartbeatFailures++;const s=n instanceof Error?n.message:String(n),i=/timeout/i.test(s)?"heartbeat timeout":"heartbeat ping failed";if(this.heartbeatFailures<p.HEARTBEAT_MAX_FAILURES){m.warn("aibot",`heartbeat soft-fail agent=${this.config.clientType}:${this.config.agentId} failures=${this.heartbeatFailures}/${p.HEARTBEAT_MAX_FAILURES} kind=${i} readyState=${e.readyState} err=${s}`);return}m.warn("aibot",`heartbeat dead agent=${this.config.clientType}:${this.config.agentId} failures=${this.heartbeatFailures} kind=${i} readyState=${e.readyState} err=${s}`),this.abandonSocketAndReconnect(e,t,i)})},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{p as AibotClient,G as preprocessLargeIntegers,j as withRequiredCapabilities};
1
+ import{EventEmitter as F}from"node:events";import{randomUUID as w}from"node:crypto";import T from"node:os";import k from"ws";import{log as m}from"../log/index.js";import{getMachineName as P}from"../util/index.js";import{detectTailnetIPv4 as q,ensureServerAndGetPort as B,getFileServerHttpsPort as D}from"../files/file-serve.js";import{TerminalOutbox as N}from"../persistence/terminal-outbox.js";import{TerminalCommitTokenStore as U}from"../persistence/terminal-commit-token-store.js";import{StopResultOutbox as W}from"../persistence/stop-result-outbox.js";import{AIBOT_PROTOCOL_SEND_RETRYABLE_CODE as $,computeAibotSendThrottleDelayMs as L,pruneAibotSendWindow as x,resolveAibotSendRetryDelayMs as S,resolveAibotSendRetryMaxAttempts as C}from"../protocol/protocol-send.js";import{AIBOT_PROTOCOL_PAYLOAD_TOO_LARGE_CODE as A}from"../protocol/protocol-text.js";import{AUTH_CODE_AGENT_DELETED as M,KICKED_REASON_AGENT_DELETED as R,AgentDeletedError as I,RequestTimeoutError as G}from"./errors.js";function j(E){let e="",t=0,n=!1,s=!1;for(;t<E.length;){const i=E[t];if(n){e+=i,s?s=!1:i==="\\"?s=!0:i==='"'&&(n=!1),t++;continue}if(i==='"'){n=!0,e+=i,t++;continue}if(i==="-"||i>="0"&&i<="9"){const r=t;i==="-"&&t++;const a=t;for(;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;let o=!1;if(E[t]===".")for(o=!0,t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;if(E[t]==="e"||E[t]==="E")for(o=!0,t++,(E[t]==="+"||E[t]==="-")&&t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;const c=E.slice(r,t),u=t-a;e+=!o&&u>=16?`"${c}"`:c;continue}e+=i,t++}return e}function z(E){const e=[...E??["stream_chunk","local_action_v1","agent_invoke"]];return e.includes("agent_invoke")||e.push("agent_invoke"),e.includes("event_result_ack")||e.push("event_result_ack"),e.includes("terminal_commit_v1")||e.push("terminal_commit_v1"),e.includes("audit_replay_v2")||e.push("audit_replay_v2"),e.includes("session_send_quote_v1")||e.push("session_send_quote_v1"),e}function H(E){const e=[...E??["exec_approve","exec_reject"]];return e.includes("apply_relay_state")||e.push("apply_relay_state"),e.includes("connector_admin")||e.push("connector_admin"),e}const K="aibot-agent-api-v1",X=1;class p extends F{static DROPPABLE_COMMANDS=new Set(["update_binding_card"]);static OUTPUT_NACK_CMDS=new Set(["send_msg","client_stream_chunk"]);static UNMATCHED_NACK_LOG_WINDOW_MS=5*6e4;unmatchedNackLoggedAt=new Map;static BUFFER_OVERFLOW_RETAIN_COMMANDS=new Set(["event_result","codex_event","client_stream_chunk","send_msg","audit_state"]);static MAX_OUTBOUND_BUFFER_SIZE=1e3;static MAX_OUTBOUND_BUFFER_HARD_SIZE=1200;static MAX_UNFENCED_REPLAY_CHUNKS_PER_EVENT=1e3;static BACKPRESSURE_THRESHOLD=64*1024;static TERMINAL_RETRY_DELAY_MS=15e3;static MAX_TOKENIZED_TERMINAL_REJECTIONS=5;static EVENT_CORRELATION_TTL_MS=5*6e4;static MAX_EVENT_CORRELATIONS=1024;static MAX_BLOCKED_OUTPUT_EVENTS=4096;static MAX_COMMITTED_TERMINAL_EVENTS=4096;static OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS=1e4;static MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS=2e4;static ORDERED_OUTPUT_COMMANDS=new Set(["client_stream_chunk","send_msg","codex_event"]);ws=null;seq=0;heartbeatTimer=null;heartbeatSec=30;heartbeatFailures=0;static HEARTBEAT_MAX_FAILURES=2;connected=!1;reconnecting=!1;reconnectAttempts=0;reconnectRunGeneration=0;everConnected=!1;agentDeleted=!1;config;packetLog;pendingInvokes=new Map;eventCorrelations=new Map;clientMsgEventMap=new Map;eventCorrelationCleanupTimer=null;lastCorrelationPruneAt=0;pendingRequests=new Map;outboundBuffer=[];outboundEntryOrders=new WeakMap;nextOutboundEntryOrder=0;connectionGeneration=0;nextOutboundFlushGeneration=0;outboundFlushInFlight=null;pendingOutputWrites=new Map;pendingOutputSeqsByEvent=new Map;pendingAcceptedOutputs=new Map;pendingAcceptedOutputSeqsByEvent=new Map;pendingAcceptedSeqsByClientMsgId=new Map;unfencedOutputEventsBySocket=new Map;provisionalRespondedTerminals=new Map;outputIntegrityFailed=new Map;blockedOutputEvents=new Map;committedTerminalEvents=new Set;ackPolicy=null;negotiatedCapabilities=new Set;terminalOutbox;terminalCommitTokens;stopResultOutbox;terminalInFlight=new Set;terminalRetryTimers=new Map;terminalReplayAfterFlight=new Set;tokenizedTerminalRejections=new Map;stopResultInFlight=new Set;stopResultRetryTimers=new Map;sendMsgWindowBySession=new Map;sendMsgAttempts=new WeakMap;sendMsgRetryAfter=new WeakMap;rateLimitedSeqs=new Set;sendMsgRequestWaiters=new Map;constructor(e,t){super(),this.packetLog=t?.packetLog??null,this.config={url:e.url,agentId:e.agentId,apiKey:e.apiKey,clientType:e.clientType,clientVersion:e.clientVersion??"",adapterHint:e.adapterHint??"",capabilities:z(e.capabilities),localActions:H(e.localActions),skills:e.skills,librarySkills:e.librarySkills,sharedOwnerId:e.sharedOwnerId,concurrency:e.concurrency,terminalOutboxPath:e.terminalOutboxPath,terminalCommitTokenStorePath:e.terminalCommitTokenStorePath,stopResultOutboxPath:e.stopResultOutboxPath},this.terminalOutbox=new N(this.config.terminalOutboxPath),this.terminalCommitTokens=new U(this.config.terminalCommitTokenStorePath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.tokens`:void 0)),this.stopResultOutbox=new W(this.config.stopResultOutboxPath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.stops`:void 0));for(const n of this.terminalOutbox.listPending())n.payload.code==="agent_output_integrity_failed"&&this.blockEventOutput(n.payload.event_id)}get isConnected(){return this.connected}async connect(){this.negotiatedCapabilities.clear();const e=this.ws,t=this.connectionGeneration;if(this.pendingRequests.size>0&&this.rejectAllPendingRequests("connection generation replaced"),e){this.connected=!1,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers();const o=this.outboundFlushInFlight;o&&o.socket===e&&o.connectionGeneration===t&&this.cancelOutboundFlush(o,"connection_lost","connection generation replaced"),this.settleUnfencedOutputsForSocket(e,"connection generation replaced"),this.abortPendingOutputWrites(!0,e,t,"connection generation replaced"),this.abortPendingAcceptedOutputs(!0,e,t),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1012,"connection generation replaced")}catch{}this.ws===e&&(this.ws=null)}else this.outboundFlushInFlight&&this.cancelOutboundFlush(this.outboundFlushInFlight,"discard","detached connection generation replaced");const n=++this.connectionGeneration;let s,i,r;const a=(async()=>{try{if(s=await q(),s!==void 0)try{i=await B(s);const o=D();o>0&&(r=o)}catch(o){m.warn("aibot",`file server pre-start failed: ${o}`)}}catch(o){m.warn("aibot",`tailnet detect failed: ${o}`)}})();return new Promise((o,c)=>{const u=new k(this.config.url);this.ws=u;const f=setTimeout(()=>{if(!this.isConnectionCurrent(u,n))return;const d=this.pendingRequests.get(g);d&&(this.pendingRequests.delete(g),clearTimeout(d.timer),d.reject(new Error("Auth timeout: no auth_ack received within 15s"))),this.cleanupSocket(u,n)},15e3),g=++this.seq,b=setTimeout(()=>{if(!this.isConnectionCurrent(u,n))return;const d=this.pendingRequests.get(g);d&&(this.pendingRequests.delete(g),d.reject(new Error("Auth request timeout"))),this.cleanupSocket(u,n)},15e3);this.pendingRequests.set(g,{expected:["auth_ack"],resolve:d=>{clearTimeout(f);const l=d.payload;if(l.code===0){this.negotiatedCapabilities=new Set(Array.isArray(l.supported_capabilities)?l.supported_capabilities:[]),this.connected=!0,this.everConnected=!0,this.reconnectAttempts=0,l.heartbeat_sec&&(this.heartbeatSec=l.heartbeat_sec),l.ack_policy&&(this.ackPolicy=l.ack_policy,m.info("aibot",`ack_policy received: push_ack_timeout_ms=${l.ack_policy.push_ack_timeout_ms??"default"} max_retries=${l.ack_policy.max_retries??"default"} timeout_action=${l.ack_policy.timeout_action??"default"}`)),this.startHeartbeat();const h=this.flushOutboundBuffer(u,n);this.emit("auth",l),o(l),h.then(_=>{this.isConnectionCurrent(u,n)&&(_?(this.replayTerminalOutbox(),this.replayStopResultOutbox()):this.reconnectAfterOutboundFlushFailure(u,n))})}else l.code===M?(this.agentDeleted=!0,c(new I(`Agent deleted: code=${l.code} msg=${l.msg}`))):c(new Error(`Auth failed: code=${l.code} msg=${l.msg}`))},reject:d=>{clearTimeout(f),c(d)},timer:b}),u.on("open",async()=>{if(await a,!this.isConnectionCurrent(u,n))return;const d={agent_id:this.config.agentId,api_key:this.config.apiKey,client_type:this.config.clientType,protocol_version:K,contract_version:X,capabilities:this.config.capabilities??[],local_actions:this.config.localActions,skills:this.config.skills,library_skills:this.config.librarySkills};this.config.sharedOwnerId&&(d.shared_owner_id=this.config.sharedOwnerId),this.config.clientVersion&&(d.client="grix-connector",d.client_version=this.config.clientVersion,d.host_type=this.config.clientType,d.host_version=this.config.clientVersion),this.config.adapterHint&&(d.adapter_hint=this.config.adapterHint),d.host_meta={hostname:P(),platform:T.platform(),arch:T.arch(),os_release:T.release(),...s!==void 0&&{tailnet_ip:s},...i!==void 0&&i>0&&{file_server_port:i},...r!==void 0&&r>0&&{file_server_https_port:r}},this.config.concurrency&&(d.concurrency=this.config.concurrency),this.sendPacket("auth",d,g)}),u.on("message",d=>{if(!this.isConnectionCurrent(u,n))return;let l;try{l=JSON.parse(j(d.toString()))}catch{return}try{this.handlePacket(l)}catch(h){this.emitClientError(new Error(`handlePacket error: ${h}`))}}),u.on("close",(d,l)=>{if(!this.isConnectionCurrent(u,n))return;const h=this.everConnected&&!this.agentDeleted;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("websocket closed");const _=`websocket closed code=${d} reason=${l.toString()||"<none>"}`,O=this.outboundFlushInFlight;O&&O.socket===u&&O.connectionGeneration===n&&this.cancelOutboundFlush(O,h?"connection_lost":"discard",_),h?this.settleUnfencedOutputsForSocket(u,_):this.unfencedOutputEventsBySocket.delete(u),this.abortPendingOutputWrites(h,u,n,h?_:void 0),this.abortPendingAcceptedOutputs(h,u,n),this.clearAllEventCorrelations(),this.ws===u&&(this.ws=null),this.connectionGeneration++,this.emit("close",d,l.toString());const y=h;m.info("aibot",`ws closed agent=${this.config.clientType}:${this.config.agentId} code=${d} reason=${l.toString()||"<none>"} everConnected=${this.everConnected} reconnecting=${this.reconnecting} agentDeleted=${this.agentDeleted} willReconnect=${y}`),y&&this.attemptReconnect(d===1e3||d===1001)}),u.on("error",d=>{if(this.isConnectionCurrent(u,n)&&(this.emitClientError(d instanceof Error?d:new Error(String(d))),!this.connected)){const l=this.pendingRequests.get(g);l&&(this.pendingRequests.delete(g),clearTimeout(l.timer),l.reject(d instanceof Error?d:new Error(String(d))))}})})}handlePacket(e){if(this.packetLog?.logInboundPacket(e.cmd,e.seq,e.payload),this.handleCorrelatedSendResponse(e),e.seq>0&&this.pendingRequests.has(e.seq)){const t=this.pendingRequests.get(e.seq);this.pendingRequests.delete(e.seq),clearTimeout(t.timer),t.expected.includes(e.cmd)?t.resolve(e):t.reject(new Error(`unexpected response: got ${e.cmd}, expected ${t.expected.join("/")}`));return}switch(e.cmd){case"auth_ack":break;case"ping":{this.sendPacket("pong",e.payload??{});break}case"event_msg":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("event",t);break}case"local_action":{this.emit("localAction",e.payload);break}case"event_stop":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("stop",t);break}case"event_revoke":{this.emit("revoke",e.payload);break}case"event_edit":{this.emit("edit",e.payload);break}case"event_cancel":{this.emit("eventCancel",e.payload);break}case"queue_clear":{this.emit("queueClear",e.payload);break}case"queue_reorder":{this.emit("queueReorder",e.payload);break}case"queue_snapshot_query":{this.emit("queueSnapshotQuery",e.payload);break}case"event_hold":{this.emit("eventHold",e.payload);break}case"queue_edit":{this.emit("queueEdit",e.payload);break}case"control_share_set":{this.emit("shareSet",e.payload);break}case"agent_profile_push":{this.emit("profilePush",e.payload);break}case"skill_sync":{this.emit("skillSync",e.payload);break}case"kicked":{const t=e.payload;this.emit("kicked",t),this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("kicked");const n=this.ws,s=this.connectionGeneration,i=this.outboundFlushInFlight;if(i&&n&&i.socket===n&&i.connectionGeneration===this.connectionGeneration&&this.cancelOutboundFlush(i,t?.reason===R?"discard":"connection_lost",`kicked reason=${t?.reason??"<none>"}`),t?.reason!==R&&n&&this.settleUnfencedOutputsForSocket(n,`kicked reason=${t?.reason??"<none>"}`),this.abortPendingOutputWrites(t?.reason!==R,n??void 0,s,t?.reason!==R?`kicked reason=${t?.reason??"<none>"}`:void 0),this.abortPendingAcceptedOutputs(t?.reason!==R,n??void 0,s),this.clearAllEventCorrelations(),this.connectionGeneration++,t?.reason===R){if(this.agentDeleted=!0,this.reconnecting=!1,this.outboundBuffer.length=0,this.outputIntegrityFailed.clear(),this.unfencedOutputEventsBySocket.clear(),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws=null}m.error("aibot",`kicked: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}, reconnect disabled`),this.emit("agentDeleted",{source:"kicked",reason:t.reason});break}if(this.reconnectAttempts=Math.max(this.reconnectAttempts,3),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws===n&&(this.ws=null)}this.attemptReconnect();break}case"error":{const t=e.payload,n=[t.ref_cmd?`ref_cmd=${t.ref_cmd}`:"",t.ref_id?`ref_id=${t.ref_id}`:""].filter(Boolean).join(" ");this.emitClientError(new Error(`Server error: code=${t.code} msg=${t.msg}${n?` ${n}`:""}`));break}case"agent_invoke_result":{this.handleInvokeResult(e.payload);break}case"mcp_frame":{const t=e.payload;this.emit("mcpFrame",t.session_id??"",t.frame??null);break}case"send_ack":break;case"send_nack":this.logUnmatchedNack(e);break;case"local_action_ack":break;default:break}}captureInboundTerminalCommitToken(e,t){const n=t?.trim();if(!n)return!0;if(!e?.trim())return this.rejectInboundTerminalCommitToken("tokenized event is missing event_id"),!1;if(!this.negotiatedCapabilities.has("terminal_commit_v1"))return this.rejectInboundTerminalCommitToken(`tokenized event received without terminal_commit_v1 negotiation event=${e}`),!1;try{return this.terminalCommitTokens.register(e,n),!0}catch(s){return this.rejectInboundTerminalCommitToken(`terminal commit token persist failed event=${e}: ${s instanceof Error?s.message:s}`),!1}}rejectInboundTerminalCommitToken(e){this.emitClientError(new Error(e));const t=this.ws;if(t)try{t.close(1011,"terminal commit token persistence failed")}catch{}}withTerminalCommitToken(e){const t=e.event_id.trim();if(!t)throw new Error("terminal event_result is missing event_id");const n=e.terminal_commit_token?.trim(),s=this.terminalCommitTokens.get(t);if(n&&s&&n!==s)throw new Error(`terminal commit token mismatch for event=${t}`);n&&!s&&this.terminalCommitTokens.register(t,n);const i=s??n;return i?{...e,event_id:t,terminal_commit_token:i}:{...e,event_id:t}}sendEventAck(e){this.sendPacket("event_ack",e)||m.warn("aibot",`event_ack NOT sent (ws not open) event=${e.event_id} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}sendStreamChunk(e){!e.delta_content&&!e.is_finish&&(m.warn("aibot",`stream_chunk delta_content empty, patched to newline event=${e.event_id??""} session=${e.session_id} chunk_seq=${e.chunk_seq} is_finish=${e.is_finish}`),e={...e,delta_content:`
2
+ `}),this.sendPacket("client_stream_chunk",e)}sendMsg(e){const t={...e,client_msg_id:e.client_msg_id?.trim()||w()};this.sendPacket("send_msg",t)||m.warn("aibot",`send_msg queued or NOT sent event=${t.event_id??""} session=${t.session_id??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}sendMsgDelay(e,t=!1){const n=e.session_id?.trim();if(!n)return 0;const s=Date.now();for(const[a,o]of this.sendMsgWindowBySession){const c=x(o,s);c.length?this.sendMsgWindowBySession.set(a,c):this.sendMsgWindowBySession.delete(a)}const i=this.sendMsgWindowBySession.get(n)??[],r=L(i,s);return t&&r===0&&(i.push(s),this.sendMsgWindowBySession.set(n,i)),r}async awaitSendMsgRequestSlot(e,t,n,s=0){for(;;){if(!this.connected||!this.isConnectionCurrent(t,n))throw new Error("connection changed while waiting for send_msg rate slot");const i=this.outboundFlushInFlight;if(i&&!i.finalized){if(!await i.promise)throw new Error("outbound flush failed before send_msg");continue}const r=Math.max(this.sendMsgDelay(e),s-Date.now());if(r<=0)return;await new Promise((a,o)=>{const c=()=>{clearTimeout(u),this.sendMsgRequestWaiters.delete(c),o(new Error("connection lost while waiting for send_msg rate slot"))},u=setTimeout(()=>{this.sendMsgRequestWaiters.delete(c),a()},r);u.unref?.(),this.sendMsgRequestWaiters.set(c,{socket:t,generation:n})})}}tryRetrySendMsgNack(e,t,n){if(n!==$)return!1;const s=this.pendingAcceptedOutputs.get(e);if(!s||s.entry.cmd!=="send_msg"||s.eventId!==t)return!1;const{entry:i}=s,r=this.sendMsgAttempts.get(i)??1;return r>=C()?!1:(this.sendMsgAttempts.set(i,r+1),this.sendMsgRetryAfter.set(i,Date.now()+S(r)),this.rememberRateLimitedSeq(e),this.settlePendingOutputWrite(e,!0,!1),this.removeSeqFromEventCorrelation(e),this.bufferOutboundEntry(i),this.settlePendingAcceptedOutput(e,"retry",!1),m.warn("aibot",`send_msg rate limited event=${t} seq=${e} retry=${r+1}/${C()}`),this.connected&&this.startPacedOutboundFlush(),!0)}rememberRateLimitedSeq(e){this.rateLimitedSeqs.add(e),this.rateLimitedSeqs.size>p.MAX_BLOCKED_OUTPUT_EVENTS&&this.rateLimitedSeqs.delete(this.rateLimitedSeqs.values().next().value)}startPacedOutboundFlush(){const e=this.ws,t=this.connectionGeneration;this.flushOutboundBuffer().then(n=>{!n&&e&&this.connected&&this.isConnectionCurrent(e,t)&&this.reconnectAfterOutboundFlushFailure(e,t)})}editMsg(e){this.sendPacket("edit_msg",e)}sendEventResult(e){try{e=this.withTerminalCommitToken(e)}catch(o){this.emitClientError(new Error(`event_result token validation failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}const t=this.terminalOutbox.get(e.event_id);let n,s=this.outputIntegrityFailed.get(e.event_id);const i=t;if(!s&&i?.payload.code==="agent_output_integrity_failed"&&(s={reason:i.payload.msg??"required agent output was discarded before delivery",terminalObserved:!1,terminalSettled:!1},this.outputIntegrityFailed.set(e.event_id,s)),s){if(s.terminalObserved=!0,this.provisionalRespondedTerminals.delete(e.event_id),i&&i.payload.code!=="agent_output_integrity_failed"&&!this.canReplaceUnsentOutputGuard(i)){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(i?.payload.code==="agent_output_integrity_failed"){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(s.terminalSettled||this.committedTerminalEvents.has(e.event_id)&&!i){this.outputIntegrityFailed.delete(e.event_id);return}try{n=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e.event_id,s.reason))}catch(o){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0});return}if(this.committedTerminalEvents.has(e.event_id)&&!t){m.info("aibot",`ignored duplicate terminal after committed ACK event=${e.event_id} status=${e.status}`);return}if(t){if(!(this.canReplaceUnsentOutputGuard(t)&&(e.status==="canceled"||e.status==="failed"))){m.info("aibot",`preserving first durable terminal event=${e.event_id} existing_status=${t.payload.status} ignored_status=${e.status}`),this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}this.provisionalRespondedTerminals.delete(e.event_id)}if(e.status==="responded"&&this.hasUnfencedOutput(e.event_id)&&!this.hasPendingOutputAcceptanceFence(e.event_id)){this.markOutputIntegrityFailed(e.event_id,"terminal requested before a complete output acceptance fence");const o=this.outputIntegrityFailed.get(e.event_id);o&&(o.terminalObserved=!0);return}const r=e.status==="responded"&&this.hasUnconfirmedEventOutput(e.event_id),a=r?{...e,status:"failed",code:"agent_output_unconfirmed",msg:"required agent output was not durably confirmed before connector restart",updated_at:Date.now()}:e;r?this.provisionalRespondedTerminals.set(e.event_id,{...e}):this.provisionalRespondedTerminals.delete(e.event_id);try{n=this.terminalOutbox.enqueue(a)}catch(o){this.provisionalRespondedTerminals.delete(e.event_id),this.emitClientError(new Error(`event_result outbox persist failed: event=${e.event_id} status=${e.status}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0})}sendLocalActionResult(e){this.sendPacket("local_action_result",e)}sendEventStopAck(e){this.sendPacket("event_stop_ack",e)}sendEventStopResult(e){const t=e.event_id?.trim(),n=e.terminal_commit_token?.trim(),s=t?this.terminalCommitTokens.get(t):void 0;if(n&&s&&n!==s){this.emitClientError(new Error(`event_stop_result token mismatch event=${t??""}`));return}const i=s??n;if(t&&i&&(e.status==="stopped"||e.status==="already_finished")){try{const r=this.stopResultOutbox.enqueue({...e,event_id:t,terminal_commit_token:i});this.scheduleStopResultDelivery(r,{ignoreNotBefore:!0})}catch(r){this.emitClientError(new Error(`event_stop_result outbox persist failed: event=${t} stop=${e.stop_id}: ${r instanceof Error?r.message:r}`))}return}this.sendPacket("event_stop_result",e)}sendSessionActivitySet(e){this.sendPacket("session_activity_set",e)}sendCodexEvent(e){this.sendPacket("codex_event",e)}sendUpdateBindingCard(e){this.sendPacket("update_binding_card",e)}sendAuditState(e){this.sendPacket("audit_state",e)}sendSkillsUpdate(e){this.sendPacket("agent_skills_update",e)}sendPing(){this.sendPacket("ping",{})}sendEventState(e){this.sendPacket("event_state",e)}sendEventCancelResult(e){this.sendPacket("event_cancel_result",e)}sendQueueClearResult(e){this.sendPacket("queue_clear_result",e)}sendQueueReorderResult(e){this.sendPacket("queue_reorder_result",e)}sendEventHoldResult(e){this.sendPacket("event_hold_result",e)}sendQueueEditResult(e){this.sendPacket("queue_edit_result",e)}sendQueueSnapshot(e){this.sendPacket("queue_snapshot",e)}agentInvoke(e,t,n=15e3){return new Promise((s,i)=>{const r=w(),a=Math.max(1e3,Math.min(n,75e3)),o=setTimeout(()=>{this.pendingInvokes.delete(r),i(new Error(`agent_invoke timeout: ${e}`))},a);this.pendingInvokes.set(r,{resolve:s,reject:i,timer:o}),this.sendPacket("agent_invoke",{invoke_id:r,action:e,params:t,timeout_ms:a})})}sendMcpFrame(e,t){this.sendPacket("mcp_frame",{session_id:e,frame:t})}async request(e,t,n){const s=this.outboundFlushInFlight;if(s){if(!await s.promise)throw new Error(`outbound flush failed before request: ${e}`);if(!this.isConnectionCurrent(s.socket,s.connectionGeneration))throw new Error(`connection changed while waiting for outbound flush: ${e}`)}if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN)throw new Error(`send failed: ${e} (websocket not connected)`);for(;e==="send_msg"&&(this.sendMsgDelay(t)>0||this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized);)await this.awaitSendMsgRequestSlot(t,this.ws,this.connectionGeneration);return new Promise((i,r)=>{const a=++this.seq,o=setTimeout(()=>{this.pendingRequests.delete(a),r(new G(`request timeout: ${e} (expected ${n.expected.join("/")})`))},n.timeoutMs);this.pendingRequests.set(a,{expected:n.expected,resolve:i,reject:r,timer:o,retryRateLimit:n.retryRateLimit}),this.sendPacket(e,t,a)||(this.pendingRequests.delete(a),clearTimeout(o),r(new Error(`send failed: ${e}`)))})}async sendStreamChunkRequest(e,t=2e4){return this.request("client_stream_chunk",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async relayCredentialRequest(e,t=15e3){return this.request("relay_credential_request",e,{expected:["relay_credential_result","error"],timeoutMs:t})}async relayStateSyncRequest(e,t=15e3){return this.request("relay_state_sync_request",e,{expected:["relay_state_sync_result","error"],timeoutMs:t})}sendRelayStateReport(e){this.sendPacket("relay_state_report",e)}async sendText(e,t=2e4){return this.sendMessageRequestWithRetry({msg_type:1,...e,client_msg_id:e.client_msg_id?.trim()||w()},t)}async sendMedia(e,t=2e4){return this.sendMessageRequestWithRetry({...e,msg_type:2,client_msg_id:e.client_msg_id?.trim()||w()},t)}async sendMessageRequestWithRetry(e,t){const n=C();for(let s=1;;s++){const i=await this.request("send_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t,retryRateLimit:s<n});if(i.cmd==="send_ack"||Number(i.payload.code)!==$||s>=n)return i;if(!this.ws)throw new Error("connection lost before send_msg retry");await this.awaitSendMsgRequestSlot(e,this.ws,this.connectionGeneration,Date.now()+S(s))}}async editMessage(e,t=2e4){return this.request("edit_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async deleteMessage(e,t,n=2e4){return this.request("delete_msg",{session_id:e,msg_id:t},{expected:["send_ack","send_nack","error"],timeoutMs:n})}async sendEventResultRequest(e,t=5e3){return this.request("event_result",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}disconnect(){m.info("aibot",`disconnect() agent=${this.config.clientType}:${this.config.agentId} wasConnected=${this.connected} reconnecting=${this.reconnecting} reconnectAttempts=${this.reconnectAttempts}`),this.connected=!1,this.negotiatedCapabilities.clear(),this.everConnected=!1,this.reconnecting=!1,this.reconnectRunGeneration++,this.reconnectAttempts=0,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.sendMsgWindowBySession.clear(),this.rateLimitedSeqs.clear();const e=this.ws,t=this.connectionGeneration,n=this.outboundFlushInFlight;n&&this.cancelOutboundFlush(n,"discard","explicit disconnect"),this.connectionGeneration++,this.rejectAllPendingInvokes("disconnect"),this.rejectAllPendingRequests("disconnect"),this.abortPendingOutputWrites(!1,e??void 0,t),this.abortPendingAcceptedOutputs(!1,e??void 0,t),this.clearAllEventCorrelations(),this.outboundBuffer.length=0,this.provisionalRespondedTerminals.clear(),this.outputIntegrityFailed.clear(),this.unfencedOutputEventsBySocket.clear(),this.ws&&(this.ws.close(1e3,"client disconnect"),this.ws=null)}static MAX_CONSECUTIVE_AUTH_FAILURES=5;async attemptReconnect(e=!1){if(this.reconnecting||this.agentDeleted)return;this.reconnecting=!0;const t=++this.reconnectRunGeneration;m.info("aibot",`attemptReconnect start agent=${this.config.clientType}:${this.config.agentId} fromAttempts=${this.reconnectAttempts} fastFirstAttempt=${e}`),this.emit("disconnected");let n=0;for(;this.reconnecting&&this.reconnectRunGeneration===t;){const s=e&&this.reconnectAttempts===0,i=s?Math.floor(Math.random()*500):Math.min(1e3*2**this.reconnectAttempts,3e4),r=s?0:Math.floor(i*.2*Math.random());if(this.reconnectAttempts++,await new Promise(c=>setTimeout(c,i+r)),!this.reconnecting||this.reconnectRunGeneration!==t)return;let a=null,o=this.connectionGeneration;try{const c=this.connect();if(a=this.ws,o=this.connectionGeneration,await c,this.reconnectRunGeneration!==t)return;if(!a||!this.isConnectionCurrent(a,o)){if(this.connected&&this.ws){this.reconnecting=!1;return}continue}const u=this.reconnectAttempts;this.reconnectAttempts=0,this.reconnecting=!1,m.info("aibot",`reconnect succeeded agent=${this.config.clientType}:${this.config.agentId} attempt=${u}`);return}catch(c){if(this.reconnectRunGeneration!==t)return;if(a&&!this.isConnectionCurrent(a,o)&&this.connected&&this.ws){this.reconnecting=!1;return}if(a&&this.isConnectionCurrent(a,o)){this.connectionGeneration++;try{a.close()}catch{}this.ws===a&&(this.ws=null)}const u=c instanceof Error?c.message:String(c);if(m.warn("aibot",`reconnect failed agent=${this.config.clientType}:${this.config.agentId} attempt=${this.reconnectAttempts} err=${u}`),c instanceof I){this.agentDeleted=!0,this.reconnecting=!1,m.error("aibot",`reconnect aborted: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}`),this.emit("agentDeleted",{source:"auth_ack",code:M});return}if(/Auth failed/i.test(u)){if(n++,n>=p.MAX_CONSECUTIVE_AUTH_FAILURES){this.reconnecting=!1,m.error("aibot",`reconnect giving up after ${n} consecutive auth failures agent=${this.config.clientType}:${this.config.agentId}`);return}}else n=0}}}sendPacket(e,t,n){const s=this.outboundEventId(e,t);if(s&&this.blockedOutputEvents.has(s))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),m.warn("aibot",`blocked late output after irreversible event failure event=${s} cmd=${e}`),!1;const i=n===void 0?this.createOutboundEntry(e,t):void 0;if(i&&this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized&&this.isConnectionCurrent(this.outboundFlushInFlight.socket,this.outboundFlushInFlight.connectionGeneration)&&!p.DROPPABLE_COMMANDS.has(e))return this.bufferOutboundEntry(i),!1;if(e==="send_msg"&&i&&this.connected&&this.ws?.readyState===k.OPEN&&this.sendMsgDelay(t)>0)return this.bufferOutboundEntry(i),this.startPacedOutboundFlush(),!1;if(this.ws&&this.ws.readyState===k.OPEN&&(e==="auth"||this.connected)){const a=this.ws.bufferedAmount>p.BACKPRESSURE_THRESHOLD;if(!a||!p.DROPPABLE_COMMANDS.has(e)){if(a&&p.DROPPABLE_COMMANDS.has(e))return!1;e==="send_msg"&&this.sendMsgDelay(t,!0);const o=n??++this.seq,c={cmd:e,seq:o,payload:t};this.packetLog?.logOutboundPacket(e,o,t,"sent");const u=this.ws,f=this.connectionGeneration,g=s;g&&this.trackOutboundEventCorrelation(e,o,t),i&&g&&(this.registerPendingOutputWrite(o,g,i,u,f),this.isAckRequiredOutput(e,t)&&this.registerPendingAcceptedOutput(o,g,i,u,f));let b=!1;try{const d=u.readyState,l=u.bufferedAmount;let h=!1;return u.send(JSON.stringify(c),_=>{if(_&&!h&&(b=!0),e==="event_result"){const v=t;_?m.warn("aibot",`event_result ws send callback failed event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`event_result ws send callback ok event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(e==="client_stream_chunk"){const v=t;_?m.warn("aibot",`stream_chunk ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`stream_chunk ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} client_msg_id=${v.client_msg_id??""} quoted_message_id=${v.quoted_message_id??""} readyState=${d} bufferedAmount=${l}`)}else if(e==="event_ack"){const v=t;_?m.warn("aibot",`event_ack ws send failed event=${v.event_id??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`event_ack ws send ok event=${v.event_id??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(e==="send_msg"){const v=t;_?m.warn("aibot",`send_msg ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${d} bufferedAmount=${l} err=${_.message}`):m.info("aibot",`send_msg ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${d} bufferedAmount=${l}`)}else if(_){const v=t;m.warn("aibot",`${e} ws send failed seq=${o} session=${v.session_id??""} event=${v.event_id??""} client_msg_id=${v.client_msg_id??""} readyState=${d} bufferedAmount=${l} err=${_.message}`)}const O=this.pendingOutputWrites.get(o),y=!!(O&&O.socket===u&&O.connectionGeneration===f);if(!this.isConnectionCurrent(u,f)){y&&(this.settlePendingOutputWrite(o,!1,!1,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f));return}if(!(i&&g&&!y)){if(_)this.removeSeqFromEventCorrelation(o),g?(this.settlePendingOutputWrite(o,!1,!0,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f)):i&&this.bufferOutboundEntry(i),n!==void 0?this.rejectPendingRequestAfterWriteFailure(o,e,_):i&&this.reconnectAfterOutboundWriteFailure(u,`${e} callback failed`);else if(g){const v=y;this.settlePendingOutputWrite(o,!0,!1,u,f),v&&O&&this.trackUnfencedOutput(u,O.entry,o)}}}),h=!0,!b}catch(d){return this.isConnectionCurrent(u,f)?(this.removeSeqFromEventCorrelation(o),g?(this.settlePendingOutputWrite(o,!1,!0,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f)):i&&this.bufferOutboundEntry(i),this.emitClientError(new Error(`sendPacket failed: ${d}`)),i&&this.reconnectAfterOutboundWriteFailure(u,`${e} send threw`),!1):(this.settlePendingOutputWrite(o,!1,!1,u,f),this.settlePendingAcceptedOutput(o,"retry",!1,u,f),!1)}}}if(p.DROPPABLE_COMMANDS.has(e))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),!1;if(n!==void 0)return this.packetLog?.logOutboundPacket(e,n,t,"dropped"),!1;const r=this.bufferOutboundEntry(i??this.createOutboundEntry(e,t));if(this.packetLog?.logOutboundPacket(e,n??0,t,r?"buffered":"dropped"),r&&e==="client_stream_chunk"){const a=t;m.info("aibot",`stream_chunk buffered (ws not open) event=${a.event_id??""} session=${a.session_id??""} chunk_seq=${a.chunk_seq??""} is_finish=${a.is_finish??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}return!1}replayTerminalOutbox(){for(const e of this.terminalOutbox.listPending())this.scheduleTerminalDelivery(e.payload.event_id,{ignoreNotBefore:!0})}outboundEventId(e,t){if(!p.ORDERED_OUTPUT_COMMANDS.has(e)||!t||typeof t!="object")return"";const n=t.event_id;return typeof n=="string"?n.trim():""}blockEventOutput(e){const t=e.trim();if(t)for(this.blockedOutputEvents.delete(t),this.blockedOutputEvents.set(t,Date.now()),this.outboundBuffer=this.outboundBuffer.filter(n=>this.outboundEventId(n.cmd,n.payload)!==t),this.outboundFlushInFlight?.wakePacing?.();this.blockedOutputEvents.size>p.MAX_BLOCKED_OUTPUT_EVENTS;){const n=this.blockedOutputEvents.keys().next().value;if(!n)break;this.blockedOutputEvents.delete(n)}}isAckRequiredOutput(e,t){return e==="send_msg"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish===!0}isNonReplayableOutput(e){return!1}isReplayableStreamDelta(e,t){return e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish!==!0}isReplayableUnfencedOutput(e,t){return this.isReplayableStreamDelta(e,t)?!0:e==="codex_event"}trackUnfencedOutput(e,t,n){const{cmd:s,payload:i}=t;if(!this.isReplayableUnfencedOutput(s,i))return;const a=this.outboundEventId(s,i);if(!a||this.outputIntegrityFailed.has(a)||this.blockedOutputEvents.has(a))return;let o=this.unfencedOutputEventsBySocket.get(e);o||(o=new Map,this.unfencedOutputEventsBySocket.set(e,o));let c=o.get(a);if(c||(c={seq:0,replay:[]},o.set(a,c)),c.seq=Math.max(c.seq,n),!!c.replay){if(c.replay.length>=p.MAX_UNFENCED_REPLAY_CHUNKS_PER_EVENT){c.replay=null;return}c.replay.includes(t)||c.replay.push(t)}}clearUnfencedOutputThrough(e,t,n){if(!e||n<=0)return;const s=this.unfencedOutputEventsBySocket.get(e);if(!s)return;const i=s.get(t)?.seq;i===void 0||i>n||(s.delete(t),s.size===0&&this.unfencedOutputEventsBySocket.delete(e))}clearUnfencedOutputEvent(e){for(const[t,n]of this.unfencedOutputEventsBySocket)n.delete(e),n.size===0&&this.unfencedOutputEventsBySocket.delete(t)}settleUnfencedOutputsForSocket(e,t){const n=this.unfencedOutputEventsBySocket.get(e);if(n){this.unfencedOutputEventsBySocket.delete(e);for(const[s,i]of n){if(!i.replay){this.markOutputIntegrityFailed(s,`connection lost before a complete output acceptance fence: ${t}`);continue}if(this.committedTerminalEvents.has(s)||this.outputIntegrityFailed.has(s)||this.blockedOutputEvents.has(s))continue;let r=0;for(const a of i.replay){if(!this.bufferOutboundEntry(a))break;r++}m.info("aibot",`requeued unfenced stream chunks for replay event=${s} chunks=${r}/${i.replay.length} reason=${t}`)}}}hasUnfencedOutput(e){for(const t of this.unfencedOutputEventsBySocket.values())if(t.has(e))return!0;return!1}hasBufferedEventOutput(e,t=!1){const n=i=>this.outboundEventId(i.cmd,i.payload)===e&&(!t||this.isAckRequiredOutput(i.cmd,i.payload)),s=this.outboundFlushInFlight;return this.outboundBuffer.some(n)||!!s?.activeBatch?.slice(s.nextIndex).some(n)}hasPendingOutputAcceptanceFence(e){return!!(this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.hasBufferedEventOutput(e,!0))}hasUnconfirmedEventOutput(e){return!!(this.pendingOutputSeqsByEvent.get(e)?.size||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.hasBufferedEventOutput(e))}trackOutboundEventCorrelation(e,t,n){const s=this.outboundEventId(e,n);if(!s)return;const i=n,r=typeof i.client_msg_id=="string"?i.client_msg_id.trim():"";this.pruneExpiredEventCorrelations();const a=Date.now();let o=this.eventCorrelations.get(s);if(!o){if(this.eventCorrelations.size>=p.MAX_EVENT_CORRELATIONS){let u;for(const f of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(f.eventId)||(!u||f.touchedAt<u.touchedAt)&&(u=f);u&&this.releaseEventCorrelations(u.eventId)}o={eventId:s,clientMsgIds:new Set,seqRanges:[],touchedAt:a,expiresAt:a+p.EVENT_CORRELATION_TTL_MS},this.eventCorrelations.set(s,o)}o.touchedAt=a,o.expiresAt=a+p.EVENT_CORRELATION_TTL_MS;const c=o.seqRanges[o.seqRanges.length-1];if(c&&t===c.end+1?c.end=t:(!c||t<c.start||t>c.end)&&o.seqRanges.push({start:t,end:t}),r){o.clientMsgIds.add(r);let u=this.clientMsgEventMap.get(r);u||(u=new Set,this.clientMsgEventMap.set(r,u)),u.add(s)}this.scheduleEventCorrelationCleanup()}uniqueEventIdForClientMsgId(e){const t=this.clientMsgEventMap.get(e);if(t?.size===1)return t.values().next().value}eventHasCriticalDeliveryState(e){return!!(this.terminalOutbox.get(e)||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size)}eventIdForSeq(e){if(!(e<=0)){for(const t of this.eventCorrelations.values())if(t.seqRanges.some(n=>e>=n.start&&e<=n.end))return t.eventId}}removeSeqFromEventCorrelation(e){if(!(e<=0))for(const t of this.eventCorrelations.values()){const n=t.seqRanges.findIndex(i=>e>=i.start&&e<=i.end);if(n<0)continue;const s=t.seqRanges[n];s.start===s.end?t.seqRanges.splice(n,1):e===s.start?s.start++:e===s.end?s.end--:t.seqRanges.splice(n,1,{start:s.start,end:e-1},{start:e+1,end:s.end});return}}releaseEventCorrelations(e){const t=e.trim();if(!t)return;const n=this.eventCorrelations.get(t);if(n){for(const s of n.clientMsgIds){const i=this.clientMsgEventMap.get(s);i?.delete(t),i?.size===0&&this.clientMsgEventMap.delete(s)}this.eventCorrelations.delete(t)}this.cancelEventCorrelationCleanupIfEmpty()}clearAllEventCorrelations(){this.eventCorrelationCleanupTimer&&(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null),this.eventCorrelations.clear(),this.clientMsgEventMap.clear(),this.lastCorrelationPruneAt=0}pruneExpiredEventCorrelations(e=Date.now(),t=!1){if(!(!t&&e-this.lastCorrelationPruneAt<1e3)){this.lastCorrelationPruneAt=e;for(const n of[...this.eventCorrelations.values()])n.expiresAt<=e&&!this.eventHasCriticalDeliveryState(n.eventId)&&this.releaseEventCorrelations(n.eventId);this.cancelEventCorrelationCleanupIfEmpty()}}scheduleEventCorrelationCleanup(){if(this.eventCorrelationCleanupTimer||this.eventCorrelations.size===0)return;let e=Number.POSITIVE_INFINITY;for(const t of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(t.eventId)||(e=Math.min(e,t.expiresAt));Number.isFinite(e)&&(this.eventCorrelationCleanupTimer=setTimeout(()=>{this.eventCorrelationCleanupTimer=null,this.pruneExpiredEventCorrelations(Date.now(),!0),this.scheduleEventCorrelationCleanup()},Math.max(1,e-Date.now())),this.eventCorrelationCleanupTimer.unref?.())}cancelEventCorrelationCleanupIfEmpty(){!this.eventCorrelationCleanupTimer||this.eventCorrelations.size>0||(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null)}logUnmatchedNack(e){const t=e.payload??{},n=typeof t.cmd=="string"?t.cmd.trim():"";if(!n||p.OUTPUT_NACK_CMDS.has(n))return;const s=typeof t.session_id=="string"?t.session_id.trim():"",i=typeof t.code=="number"?t.code:Number(t.code??0)||0,r=`${n}|${s}|${i}`,a=Date.now(),o=this.unmatchedNackLoggedAt.get(r)??0;if(o>0&&a-o<p.UNMATCHED_NACK_LOG_WINDOW_MS)return;if(this.unmatchedNackLoggedAt.size>=256){for(const[u,f]of this.unmatchedNackLoggedAt)a-f>=p.UNMATCHED_NACK_LOG_WINDOW_MS&&this.unmatchedNackLoggedAt.delete(u);this.unmatchedNackLoggedAt.size>=256&&this.unmatchedNackLoggedAt.clear()}this.unmatchedNackLoggedAt.set(r,a);const c=typeof t.msg=="string"?t.msg:"";m.warn("aibot",`backend rejected ${n} session=${s||"<none>"} code=${i} msg=${c||"<none>"} seq=${e.seq} (repeats suppressed for ${p.UNMATCHED_NACK_LOG_WINDOW_MS/1e3}s)`)}handleCorrelatedSendResponse(e){if(this.rateLimitedSeqs.has(e.seq))return;if(e.cmd==="send_ack"){const u=e.payload,f=typeof u.client_msg_id=="string"?u.client_msg_id.trim():"";let g=e.seq>0&&this.pendingAcceptedOutputs.has(e.seq)?e.seq:void 0,b;if(g===void 0&&f&&e.seq<=0){const h=this.pendingAcceptedSeqsByClientMsgId.get(f);if(h?.size===1){const _=h.values().next().value,O=this.pendingAcceptedOutputs.get(_),y=this.uniqueEventIdForClientMsgId(f);O&&y&&O.eventId===y&&(g=_,b=y)}}const d=(g!==void 0?this.pendingAcceptedOutputs.get(g)?.eventId:void 0)??b??this.eventIdForSeq(e.seq),l=g??e.seq;if(g!==void 0){const h=this.pendingOutputWrites.get(g);h&&this.settlePendingOutputWrite(g,!0,!1,h.socket,h.connectionGeneration),this.settlePendingAcceptedOutput(g,"accepted",!1),d&&this.clearUnfencedOutputThrough(this.ws,d,l)}else if(e.seq>0){const h=this.pendingOutputWrites.get(e.seq);if(h&&this.settlePendingOutputWrite(e.seq,!0,!1,h.socket,h.connectionGeneration),this.pendingRequests.has(e.seq)){const _=this.eventIdForSeq(e.seq);_&&this.clearUnfencedOutputThrough(this.ws,_,e.seq)}}return}if(e.cmd!=="send_nack"&&e.cmd!=="error")return;this.pruneExpiredEventCorrelations();const t=e.payload;if(Number(t.code)===$&&this.pendingRequests.get(e.seq)?.retryRateLimit){this.rememberRateLimitedSeq(e.seq);return}const n=typeof t.client_msg_id=="string"?t.client_msg_id.trim():"",s=e.cmd==="error"&&typeof t.ref_id=="string"?t.ref_id.trim():"",i=e.cmd==="error"&&typeof t.ref_cmd=="string"?t.ref_cmd.trim():"",r=this.eventIdForSeq(e.seq),a=s&&(!i||p.ORDERED_OUTPUT_COMMANDS.has(i))?this.uniqueEventIdForClientMsgId(s)??(this.eventCorrelations.has(s)?s:void 0):void 0,o=r??(n?this.uniqueEventIdForClientMsgId(n):void 0)??a;if(!o)return;const c=e.seq>0?e.seq:this.pendingAcceptedSeqsByClientMsgId.get(n||s)?.size===1?this.pendingAcceptedSeqsByClientMsgId.get(n||s).values().next().value:0;if(!this.tryRetrySendMsgNack(c,o,Number(t.code??0))){if(this.shouldDropOversizedStreamChunk(e.seq,t)){const u=this.pendingOutputWrites.get(e.seq);u&&this.settlePendingOutputWrite(e.seq,!0,!1,u.socket,u.connectionGeneration),m.warn("aibot",`oversized stream chunk rejected (code=${A}) and dropped seq=${e.seq} event=${o} msg=${t.msg??""}`);return}this.blockEventOutput(o),this.settlePendingOutputWritesForEvent(o,!0),this.clearUnfencedOutputEvent(o),e.seq>0&&this.pendingAcceptedOutputs.get(e.seq)?.eventId===o?this.settlePendingAcceptedOutput(e.seq,"rejected",!1):this.settlePendingAcceptedOutputsForEvent(o,"rejected",!1),t.code===4003&&(this.purgeBufferedStreamChunks(o),m.warn("aibot",`event payload rejected (4003), purging buffered chunks for event=${o}`)),this.promotePendingTerminalAfterOutputRejection(o,Number(t.code??0),t.msg),this.emit("streamRejected",o,Number(t.code??0))}}shouldDropOversizedStreamChunk(e,t){if(Number(t.code)!==A||e>0&&this.pendingRequests.has(e))return!1;const n=e>0?this.pendingOutputWrites.get(e):void 0;return n?.entry.cmd==="client_stream_chunk"&&n.entry.payload?.is_finish!==!0?!0:(typeof t.client_msg_id=="string"?t.client_msg_id.trim():"").endsWith("_thinking")}promotePendingTerminalAfterOutputRejection(e,t,n){this.provisionalRespondedTerminals.delete(e);const s=this.terminalOutbox.get(e);if(!(!s||s.payload.status!=="responded"&&s.payload.code!=="agent_output_unconfirmed"||s.deliveryStartedAt))try{const i=this.terminalOutbox.enqueue({...s.payload,status:"failed",code:"agent_output_rejected",msg:n?`required agent output was rejected: ${n}`:`required agent output was rejected by the server (code=${t})`,updated_at:Date.now()});this.scheduleTerminalDelivery(i.payload.event_id,{ignoreNotBefore:!0})}catch(i){this.emitClientError(new Error(`failed to persist output-rejection terminal promotion: event=${e} code=${t}: ${i instanceof Error?i.message:i}`))}}scheduleTerminalDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN)return;if(this.terminalInFlight.has(e)){t?.ignoreNotBefore&&this.terminalReplayAfterFlight.add(e);return}const n=this.terminalOutbox.get(e);if(!n)return;const s=this.terminalRetryTimers.get(e);s&&(clearTimeout(s),this.terminalRetryTimers.delete(e));const i=t?.ignoreNotBefore?0:Math.max(0,n.nextAttemptAt-Date.now()),r=Math.max(i,t?.minimumDelayMs??0);if(r>0){const a=setTimeout(()=>{this.terminalRetryTimers.delete(e),this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0})},r);this.terminalRetryTimers.set(e,a);return}this.deliverTerminalEntry(n)}async deliverTerminalEntry(e){const t=e.payload.event_id;if(this.terminalInFlight.has(t)||!this.terminalOutbox.isCurrent(e))return;this.terminalInFlight.add(t);let n=0;try{n=await this.sendEventResultReliable(e)}finally{this.terminalInFlight.delete(t);const s=this.terminalReplayAfterFlight.delete(t);this.terminalOutbox.get(t)&&this.scheduleTerminalDelivery(t,s?{ignoreNotBefore:!0}:{minimumDelayMs:n})}}clearTerminalRetryTimers(){for(const e of this.terminalRetryTimers.values())clearTimeout(e);this.terminalRetryTimers.clear()}async sendEventResultReliable(e){const t=e.payload.event_id,n=e.payload.terminal_commit_token?.trim();if(n&&!this.negotiatedCapabilities.has("terminal_commit_v1")){const f=this.ws;return this.emitClientError(new Error(`refusing tokenized event_result on an unnegotiated connection: event=${t}`)),f&&this.reconnectAfterOutboundWriteFailure(f,"terminal_commit_v1 not negotiated"),p.TERMINAL_RETRY_DELAY_MS}if(!await this.awaitOutputDeliveryBarrier(t))return p.TERMINAL_RETRY_DELAY_MS;const s=this.provisionalRespondedTerminals.get(t);if(s&&this.terminalOutbox.isCurrent(e))if(!this.canReplaceUnsentOutputGuard(e))this.provisionalRespondedTerminals.delete(t);else try{return this.terminalOutbox.enqueue(s),this.provisionalRespondedTerminals.delete(t),0}catch(f){return this.emitClientError(new Error(`failed to promote confirmed output terminal to responded: event=${t}: ${f instanceof Error?f.message:f}`)),p.TERMINAL_RETRY_DELAY_MS}const i=e.payload;try{if(!this.terminalOutbox.markDeliveryStarted(e))return 0}catch(f){return this.emitClientError(new Error(`event_result delivery-start persist failed: event=${t}: ${f instanceof Error?f.message:f}`)),p.TERMINAL_RETRY_DELAY_MS}const r=Math.max(1,this.ackPolicy?.max_retries??3),a=this.ackPolicy?.push_ack_timeout_ms??5e3,o=750;let c="unknown delivery failure";for(let f=1;f<=r;f++){if(!this.terminalOutbox.isCurrent(e))return 0;const g=this.ws?.readyState??-1,b=this.ws?.bufferedAmount??0;m.info("aibot",`event_result send attempt event=${i.event_id} status=${i.status} attempt=${f}/${r} readyState=${g} bufferedAmount=${b}`);try{const d=await this.sendEventResultRequest(i,a);if(!this.terminalOutbox.isCurrent(e))return 0;if(d.cmd==="send_ack"){const h=d.payload;if(m.info("aibot",`event_result ack event=${i.event_id} status=${i.status} attempt=${f}/${r} ack_event=${h.event_id??""} ack_status=${h.status??""}`),h.event_id!==i.event_id||h.status!==i.status)throw new Error(`event_result ACK mismatch: expected event=${i.event_id} status=${i.status}, got event=${h.event_id??""} status=${h.status??""}`);if(n&&(h.terminal_commit_token?.trim()!==n||h.terminal_committed!==!0))throw new Error(`event_result terminal commit ACK mismatch: event=${i.event_id}`);if(n)try{this.terminalCommitTokens.remove(i.event_id,n)}catch(_){throw new Error(`terminal commit token cleanup failed: event=${i.event_id}: ${_ instanceof Error?_.message:_}`)}return this.terminalOutbox.acknowledge(e,h.event_id,h.status,h.terminal_commit_token,h.terminal_committed)&&(this.rememberCommittedTerminalEvent(i.event_id),this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.scheduleStopResultsForEvent(i.event_id)),0}const l=d.payload;if(m.warn("aibot",`event_result rejected event=${i.event_id} status=${i.status} attempt=${f}/${r} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}${l.ref_cmd?` ref_cmd=${l.ref_cmd}`:""}${l.ref_id?` ref_id=${l.ref_id}`:""}`),n){c=`tokenized terminal rejected: cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`;const h=(this.tokenizedTerminalRejections.get(i.event_id)??0)+1;if(this.tokenizedTerminalRejections.set(i.event_id,h),h<p.MAX_TOKENIZED_TERMINAL_REJECTIONS)break;this.tokenizedTerminalRejections.delete(i.event_id);try{this.terminalCommitTokens.remove(i.event_id,n),this.terminalOutbox.moveToDeadLetter(e,{responseCmd:d.cmd,code:l.code,message:l.msg})&&(this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`tokenized event_result permanently rejected after ${h} rejections, moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`)))}catch(_){c=`dead-letter persist failed: ${_ instanceof Error?_.message:_}`,this.emitClientError(new Error(`tokenized event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${c}`));break}return 0}try{return this.terminalOutbox.moveToDeadLetter(e,{responseCmd:d.cmd,code:l.code,message:l.msg})&&(this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearUnfencedOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`event_result rejected and moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${d.cmd} code=${l.code??""} msg=${l.msg??""}`))),0}catch(h){c=`dead-letter persist failed: ${h instanceof Error?h.message:h}`,this.emitClientError(new Error(`event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${c}`));break}}catch(d){const l=d instanceof Error?d.message:String(d);if(c=l,m.warn("aibot",`event_result attempt failed event=${i.event_id} status=${i.status} attempt=${f}/${r} err=${l}`),f===r)break;await new Promise(h=>setTimeout(h,o*f))}}const u=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.terminalOutbox.recordRetry(e,u,c)}catch(f){this.emitClientError(new Error(`event_result retry state persist failed: event=${i.event_id} status=${i.status}: ${f instanceof Error?f.message:f}`))}return this.emitClientError(new Error(`event_result ack failed after ${r} attempts; retained for retry: event=${i.event_id} status=${i.status} err=${c}`)),p.TERMINAL_RETRY_DELAY_MS}purgeBufferedStreamChunks(e){const t=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(n=>n.cmd!=="client_stream_chunk"?!0:n.payload?.event_id!==e),this.outboundBuffer.length<t&&m.info("aibot",`purged ${t-this.outboundBuffer.length} buffered stream chunks for event=${e}`)}emitClientError(e){if(this.listenerCount("error")===0){m.warn("aibot",`Client error (no listeners): ${e.message}`);return}this.emit("error",e)}createOutboundEntry(e,t){const n={cmd:e,payload:t};return this.outboundEntryOrders.set(n,++this.nextOutboundEntryOrder),n}makeOutputIntegrityFailurePayload(e,t){return this.withTerminalCommitToken({event_id:e,status:"failed",code:"agent_output_integrity_failed",msg:`required agent output was discarded before delivery: ${t}`,updated_at:Date.now()})}canReplaceUnsentOutputGuard(e){return e.payload.code==="agent_output_unconfirmed"&&!e.deliveryStartedAt}rememberCommittedTerminalEvent(e){for(this.committedTerminalEvents.delete(e),this.committedTerminalEvents.add(e);this.committedTerminalEvents.size>p.MAX_COMMITTED_TERMINAL_EVENTS;){const t=this.committedTerminalEvents.values().next().value;if(!t)break;this.committedTerminalEvents.delete(t)}}replayStopResultOutbox(){for(const e of this.stopResultOutbox.listPending())this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})}scheduleStopResultsForEvent(e){for(const t of this.stopResultOutbox.listPending())t.payload.event_id===e&&this.scheduleStopResultDelivery(t,{ignoreNotBefore:!0})}scheduleStopResultDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==k.OPEN||!this.stopResultOutbox.isCurrent(e))return;const n=e.payload.event_id;if(this.terminalOutbox.get(n)||this.terminalCommitTokens.get(n))return;const s=this.stopResultRetryTimers.get(e.key);s&&(clearTimeout(s),this.stopResultRetryTimers.delete(e.key));const i=t?.ignoreNotBefore?0:Math.max(0,e.nextAttemptAt-Date.now());if(i>0){const r=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},i);this.stopResultRetryTimers.set(e.key,r);return}this.deliverStopResultEntry(e)}async deliverStopResultEntry(e){if(this.stopResultInFlight.has(e.key)||!this.stopResultOutbox.isCurrent(e))return;this.stopResultInFlight.add(e.key);let t=p.TERMINAL_RETRY_DELAY_MS;try{t=await this.sendStopResultReliable(e)}finally{if(this.stopResultInFlight.delete(e.key),this.stopResultOutbox.isCurrent(e)){const n=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},t);this.stopResultRetryTimers.set(e.key,n)}}}async sendStopResultReliable(e){const t=this.ackPolicy?.push_ack_timeout_ms??5e3;let n="unknown delivery failure";try{const i=await this.request("event_stop_result",e.payload,{expected:["send_ack","send_nack","error"],timeoutMs:t});if(!this.stopResultOutbox.isCurrent(e))return 0;if(i.cmd==="send_ack"){const r=i.payload;if(this.stopResultOutbox.acknowledge(e,r.event_id,r.terminal_commit_token,r.terminal_committed))return 0;n=`event_stop_result ACK mismatch event=${e.payload.event_id}`}else{const r=i.payload;if(n=`event_stop_result rejected: cmd=${i.cmd} code=${r.code??""} msg=${r.msg??""}`,r.code===4001||r.code===4003){try{this.stopResultOutbox.discard(e)&&this.emitClientError(new Error(`event_stop_result permanently rejected and discarded: event=${e.payload.event_id} stop=${e.payload.stop_id} code=${r.code} msg=${r.msg??""}`))}catch(a){this.emitClientError(new Error(`event_stop_result discard persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${a instanceof Error?a.message:a}`))}return 0}}}catch(i){n=i instanceof Error?i.message:String(i)}const s=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.stopResultOutbox.recordRetry(e,s,n)}catch(i){this.emitClientError(new Error(`event_stop_result retry state persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${i instanceof Error?i.message:i}`))}return this.emitClientError(new Error(`event_stop_result retained for retry: event=${e.payload.event_id} stop=${e.payload.stop_id} err=${n}`)),p.TERMINAL_RETRY_DELAY_MS}clearStopResultRetryTimers(){for(const e of this.stopResultRetryTimers.values())clearTimeout(e);this.stopResultRetryTimers.clear()}markOutputIntegrityFailed(e,t){if(this.blockEventOutput(e),this.outputIntegrityFailed.has(e))return;const n={reason:t,terminalObserved:!!(this.provisionalRespondedTerminals.has(e)||this.terminalOutbox.get(e)),terminalSettled:!1};this.outputIntegrityFailed.set(e,n),this.provisionalRespondedTerminals.delete(e),this.clearUnfencedOutputEvent(e);const s=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(a=>this.outboundEventId(a.cmd,a.payload)!==e);const i=this.terminalOutbox.get(e),r=i?this.canReplaceUnsentOutputGuard(i):!1;if(i&&!r)n.terminalObserved=!0,this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0});else if(!this.committedTerminalEvents.has(e))try{const a=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e,t));this.scheduleTerminalDelivery(a.payload.event_id,{ignoreNotBefore:!0})}catch(a){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e}: ${a instanceof Error?a.message:a}`))}for(const a of[...this.pendingOutputSeqsByEvent.get(e)??[]])this.settlePendingOutputWrite(a,!1,!1);this.settlePendingAcceptedOutputsForEvent(e,"rejected",!1),this.emit("streamRejected",e,0),this.emitClientError(new Error(`required output integrity failed: event=${e} removed=${s-this.outboundBuffer.length} reason=${t}`))}settleOutputIntegrityTerminal(e){const t=this.outputIntegrityFailed.get(e);t&&(t.terminalSettled=!0,t.terminalObserved&&this.outputIntegrityFailed.delete(e))}bufferOutboundEntry(e){if(this.outboundEntryOrders.has(e)||this.outboundEntryOrders.set(e,++this.nextOutboundEntryOrder),this.outboundBuffer.includes(e))return!0;const t=this.outboundEventId(e.cmd,e.payload);return t&&(this.outputIntegrityFailed.has(t)||this.blockedOutputEvents.has(t))?!1:(this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&(this.outboundBuffer=this.outboundBuffer.filter(n=>p.BUFFER_OVERFLOW_RETAIN_COMMANDS.has(n.cmd)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&m.warn("aibot",`outbound buffer soft limit exceeded by ${this.outboundBuffer.length} retained packet(s); preserving required output`)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_HARD_SIZE?(t?this.markOutputIntegrityFailed(t,`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached`):this.emitClientError(new Error(`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached; rejected non-event packet cmd=${e.cmd}`)),!1):(this.outboundBuffer.push(e),this.outboundBuffer.sort((n,s)=>(this.outboundEntryOrders.get(n)??Number.MAX_SAFE_INTEGER)-(this.outboundEntryOrders.get(s)??Number.MAX_SAFE_INTEGER)),!0))}registerPendingOutputWrite(e,t,n,s,i){let r;const a=new Promise(u=>{r=u}),o=setTimeout(()=>{const u=this.pendingOutputWrites.get(e);if(!u||u.socket!==s||u.connectionGeneration!==i)return;if(!this.isConnectionCurrent(s,i)){this.settlePendingOutputWrite(e,!1,!1,s,i);return}this.removeSeqFromEventCorrelation(e);const f=this.isNonReplayableOutput(n.cmd);this.settlePendingOutputWrite(e,!1,!f,s,i),f&&this.markOutputIntegrityFailed(t,`websocket write callback timed out for non-replayable ${n.cmd} seq=${e}`),this.emitClientError(new Error(`outbound websocket write callback timeout: cmd=${n.cmd} event=${t} seq=${e} delivery_unknown=${f}`)),this.reconnectAfterOutboundWriteFailure(s,`${n.cmd} callback timeout`)},p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);o.unref?.(),this.pendingOutputWrites.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:a,resolve:r,timer:o});let c=this.pendingOutputSeqsByEvent.get(t);c||(c=new Set,this.pendingOutputSeqsByEvent.set(t,c)),c.add(e)}settlePendingOutputWrite(e,t,n,s,i){const r=this.pendingOutputWrites.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingOutputWrites.delete(e),clearTimeout(r.timer);const a=this.pendingOutputSeqsByEvent.get(r.eventId);a?.delete(e),a?.size===0&&this.pendingOutputSeqsByEvent.delete(r.eventId),n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingOutputWritesForEvent(e,t){const n=this.pendingOutputSeqsByEvent.get(e);if(n)for(const s of[...n]){const i=this.pendingOutputWrites.get(s);i&&this.settlePendingOutputWrite(s,t,!1,i.socket,i.connectionGeneration)}}abortPendingOutputWrites(e,t,n,s){for(const[i,r]of[...this.pendingOutputWrites.entries()])if(!(t&&(r.socket!==t||r.connectionGeneration!==n))){if(this.removeSeqFromEventCorrelation(i),s&&this.isNonReplayableOutput(r.entry.cmd)){this.settlePendingOutputWrite(i,!1,!1,t,n),this.markOutputIntegrityFailed(r.eventId,`connection lost while websocket write completion was unknown: ${s}`);continue}this.settlePendingOutputWrite(i,!1,e,t,n)}}registerPendingAcceptedOutput(e,t,n,s,i){let r;const a=new Promise(h=>{r=h}),o=Math.max(1,this.ackPolicy?.push_ack_timeout_ms??5e3),c=Math.max(1,this.ackPolicy?.max_retries??3),u=Math.max(1e3,Math.ceil(o*.25)),f=Math.max(p.MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS,o*c+u),g=setTimeout(()=>{const h=this.pendingAcceptedOutputs.get(e);if(!(!h||h.socket!==s||h.connectionGeneration!==i)){if(!this.isConnectionCurrent(s,i)){this.settlePendingAcceptedOutput(e,"retry",!1,s,i);return}this.settlePendingAcceptedOutput(e,"retry",!0,s,i),this.emitClientError(new Error(`required output ACK timeout; retained for reconnect retry: event=${t} seq=${e}`)),this.reconnectAfterOutboundWriteFailure(s,"required output ACK timeout")}},f);g.unref?.(),this.pendingAcceptedOutputs.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:a,resolve:r,timer:g});const b=n.payload,d=typeof b.client_msg_id=="string"?b.client_msg_id.trim():"";if(d){let h=this.pendingAcceptedSeqsByClientMsgId.get(d);h||(h=new Set,this.pendingAcceptedSeqsByClientMsgId.set(d,h)),h.add(e)}let l=this.pendingAcceptedOutputSeqsByEvent.get(t);l||(l=new Set,this.pendingAcceptedOutputSeqsByEvent.set(t,l)),l.add(e)}settlePendingAcceptedOutput(e,t,n,s,i){const r=this.pendingAcceptedOutputs.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingAcceptedOutputs.delete(e),clearTimeout(r.timer);const a=this.pendingAcceptedOutputSeqsByEvent.get(r.eventId);a?.delete(e),a?.size===0&&this.pendingAcceptedOutputSeqsByEvent.delete(r.eventId);const o=r.entry.payload,c=typeof o.client_msg_id=="string"?o.client_msg_id.trim():"";if(c){const u=this.pendingAcceptedSeqsByClientMsgId.get(c);u?.delete(e),u?.size===0&&this.pendingAcceptedSeqsByClientMsgId.delete(c)}n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingAcceptedOutputsForEvent(e,t,n){const s=this.pendingAcceptedOutputSeqsByEvent.get(e);if(s)for(const i of[...s])this.settlePendingAcceptedOutput(i,t,n)}abortPendingAcceptedOutputs(e,t,n){for(const[s,i]of this.sendMsgRequestWaiters)(!t||i.socket===t&&i.generation===n)&&s();for(const[s,i]of[...this.pendingAcceptedOutputs.entries()])t&&(i.socket!==t||i.connectionGeneration!==n)||this.settlePendingAcceptedOutput(s,"retry",e,t,n)}rejectPendingRequestAfterWriteFailure(e,t,n){const s=this.pendingRequests.get(e);s&&(this.pendingRequests.delete(e),clearTimeout(s.timer),s.reject(new Error(`websocket write failed: ${t}: ${n.message}`)))}async awaitOutputDeliveryBarrier(e){const t=this.outboundFlushInFlight;if(t&&!await t.promise)return!1;for(;;){const n=this.pendingOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingOutputWrites.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;if((await Promise.all(s)).some(r=>!r))return!1}for(;;){const n=this.pendingAcceptedOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingAcceptedOutputs.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;const i=await Promise.all(s);if(i.includes("retry"))return this.outboundFlushInFlight?this.awaitOutputDeliveryBarrier(e):!1;if(i.includes("rejected")){const r=this.terminalOutbox.get(e);if(!r||r.payload.status==="responded")return!1}}return this.outboundBuffer.some(n=>this.outboundEventId(n.cmd,n.payload)===e)?!1:this.hasUnfencedOutput(e)?(this.markOutputIntegrityFailed(e,"output flush completed without a complete acceptance fence"),!1):!!(this.connected&&this.ws&&this.ws.readyState===k.OPEN)}isConnectionCurrent(e,t){return this.ws===e&&this.connectionGeneration===t}isOutboundFlushCurrent(e){return!e.finalized&&this.outboundFlushInFlight===e&&this.isConnectionCurrent(e.socket,e.connectionGeneration)}flushOutboundBuffer(e=this.ws,t=this.connectionGeneration){if(!e||!this.isConnectionCurrent(e,t))return Promise.resolve(!1);const n=this.outboundFlushInFlight;if(n){if(!n.finalized&&n.socket===e&&n.connectionGeneration===t)return n.promise;this.cancelOutboundFlush(n,"discard","superseded stale flush")}if(this.outboundBuffer.length===0)return Promise.resolve(!0);const s={connectionGeneration:t,flushGeneration:++this.nextOutboundFlushGeneration,socket:e,promise:Promise.resolve(!1),finalized:!1,activeBatch:null,nextIndex:0,currentWritePending:!1,currentWriteOutcome:null,cancelCurrentWrite:null,remainderHandled:!1};return this.outboundFlushInFlight=s,s.promise=this.performOutboundBufferFlush(s),s.promise.finally(()=>{s.finalized=!0,s.cancelCurrentWrite?.(),s.cancelCurrentWrite=null,this.outboundFlushInFlight===s&&(this.outboundFlushInFlight=null)}),s.promise}awaitOutboundPacing(e,t){return new Promise(n=>{const s=r=>{clearTimeout(i),e.cancelCurrentWrite=null,e.wakePacing=void 0,n(r)},i=setTimeout(()=>s(this.isOutboundFlushCurrent(e)),t);i.unref?.(),e.wakePacing=()=>s(this.isOutboundFlushCurrent(e)),e.cancelCurrentWrite=()=>s(!1)})}async performOutboundBufferFlush(e){for(;this.isOutboundFlushCurrent(e)&&this.outboundBuffer.length>0;){const{socket:t}=e;if(t.readyState!==k.OPEN)return!1;const n=this.outboundBuffer;this.outboundBuffer=[],e.activeBatch=n,e.nextIndex=0,e.remainderHandled=!1;for(let s=0;s<n.length;s++){if(!this.isOutboundFlushCurrent(e))return!1;const i=n[s],{cmd:r,payload:a}=i,o=this.outboundEventId(r,a);if(e.nextIndex=s,r==="send_msg"){for(;this.isOutboundFlushCurrent(e)&&!(o&&this.blockedOutputEvents.has(o));){const g=Math.max(this.sendMsgDelay(a),(this.sendMsgRetryAfter.get(i)??0)-Date.now());if(g<=0)break;if(!await this.awaitOutboundPacing(e,g))return!1}if(!this.isOutboundFlushCurrent(e))return!1}if(o&&this.blockedOutputEvents.has(o)){this.packetLog?.logOutboundPacket(r,0,a,"dropped"),e.nextIndex=s+1,e.currentWritePending=!1,e.currentWriteOutcome=null;continue}r==="send_msg"&&this.sendMsgDelay(a,!0);const c=++this.seq,u={cmd:r,seq:c,payload:a};e.nextIndex=s,e.currentWritePending=!0,e.currentWriteOutcome=null,o&&this.isAckRequiredOutput(r,a)&&this.registerPendingAcceptedOutput(c,o,i,t,e.connectionGeneration);const f=await new Promise(g=>{let b=!1;const d=h=>{b||(b=!0,clearTimeout(l),e.currentWriteOutcome=h,g(h))},l=setTimeout(()=>d("uncertain"),p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);l.unref?.(),e.cancelCurrentWrite=()=>d("canceled");try{this.trackOutboundEventCorrelation(r,c,a),t.send(JSON.stringify(u),h=>{d(h?"retry":"written")})}catch{d("retry")}});if(e.cancelCurrentWrite=null,!this.isOutboundFlushCurrent(e))return!1;if(f!=="written"||t.readyState!==k.OPEN){f==="retry"&&this.removeSeqFromEventCorrelation(c),this.settlePendingAcceptedOutput(c,"retry",!1);const g=this.retainOutboundFlushRemainder(e,f,`auth flush write failed for ${r} seq=${c} outcome=${f}`);return this.emitClientError(new Error(`outbound buffer flush failed at cmd=${r} seq=${c} outcome=${f}; ${g} packet(s) retained`)),!1}this.trackUnfencedOutput(t,i,c),e.currentWritePending=!1,e.currentWriteOutcome="written",e.nextIndex=s+1}e.activeBatch=null,e.currentWritePending=!1,e.currentWriteOutcome=null,e.remainderHandled=!0}return this.isOutboundFlushCurrent(e)}retainOutboundFlushRemainder(e,t,n){if(e.remainderHandled||!e.activeBatch)return 0;e.remainderHandled=!0;const s=e.activeBatch,i=Math.min(e.nextIndex,s.length);let r=i;if(e.currentWritePending&&i<s.length){const o=s[i],c=this.outboundEventId(o.cmd,o.payload);t!=="retry"&&this.isNonReplayableOutput(o.cmd)&&c&&(this.markOutputIntegrityFailed(c,n),r=i+1)}let a=0;for(const o of s.slice(r))this.bufferOutboundEntry(o)&&a++;return e.activeBatch=null,e.nextIndex=s.length,e.currentWritePending=!1,a}cancelOutboundFlush(e,t,n){if(e.finalized){this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null);return}e.finalized=!0,this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null),t==="connection_lost"?this.retainOutboundFlushRemainder(e,e.currentWriteOutcome,`connection lost during auth flush: ${n}`):(e.remainderHandled=!0,e.activeBatch=null,e.currentWritePending=!1);const s=e.cancelCurrentWrite;e.cancelCurrentWrite=null,s?.()}reconnectAfterOutboundFlushFailure(e,t){this.agentDeleted||!this.isConnectionCurrent(e,t)||this.reconnectAfterOutboundWriteFailure(e,"outbound flush failed")}reconnectAfterOutboundWriteFailure(e,t){this.abandonSocketAndReconnect(e,this.connectionGeneration,t)}abandonSocketAndReconnect(e,t,n){if(this.agentDeleted||!this.isConnectionCurrent(e,t))return;const s=t,i=e.readyState;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests(n);const r=this.outboundFlushInFlight;r&&r.socket===e&&r.connectionGeneration===s&&this.cancelOutboundFlush(r,"connection_lost",n),this.settleUnfencedOutputsForSocket(e,n),this.abortPendingOutputWrites(!0,e,s,n),this.abortPendingAcceptedOutputs(!0,e,s),this.clearAllEventCorrelations(),this.connectionGeneration++,this.ws===e&&(this.ws=null),this.forceDestroySocket(e,n),m.warn("aibot",`abandon socket and reconnect agent=${this.config.clientType}:${this.config.agentId} reason=${n} readyState=${i}`),this.attemptReconnect()}forceDestroySocket(e,t){try{const n=e;if(typeof n.terminate=="function"){n.terminate();return}}catch{}try{e.close(1011,t)}catch{}}handleInvokeResult(e){const t=this.pendingInvokes.get(e.invoke_id);t&&(this.pendingInvokes.delete(e.invoke_id),clearTimeout(t.timer),e.code===0?t.resolve(e.data??null):t.reject(new Error(`agent_invoke error code=${e.code}: ${e.msg??""}`)))}rejectAllPendingInvokes(e){for(const[,t]of this.pendingInvokes)clearTimeout(t.timer),t.reject(new Error(`agent_invoke canceled: ${e}`));this.pendingInvokes.clear()}rejectAllPendingRequests(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`request canceled: ${e}`));this.pendingRequests.clear()}cleanupSocket(e=this.ws,t=this.connectionGeneration){if(!(!e||!this.isConnectionCurrent(e,t)))try{e.close()}catch{}}startHeartbeat(){this.stopHeartbeat(),this.heartbeatFailures=0,this.heartbeatTimer=setInterval(()=>{const e=this.ws,t=this.connectionGeneration;!this.connected||!e||this.request("ping",{ts:Date.now()},{expected:["pong"],timeoutMs:5e3}).then(()=>{this.isConnectionCurrent(e,t)&&(this.heartbeatFailures=0)}).catch(n=>{if(!this.connected||!this.isConnectionCurrent(e,t))return;this.heartbeatFailures++;const s=n instanceof Error?n.message:String(n),i=/timeout/i.test(s)?"heartbeat timeout":"heartbeat ping failed";if(this.heartbeatFailures<p.HEARTBEAT_MAX_FAILURES){m.warn("aibot",`heartbeat soft-fail agent=${this.config.clientType}:${this.config.agentId} failures=${this.heartbeatFailures}/${p.HEARTBEAT_MAX_FAILURES} kind=${i} readyState=${e.readyState} err=${s}`);return}m.warn("aibot",`heartbeat dead agent=${this.config.clientType}:${this.config.agentId} failures=${this.heartbeatFailures} kind=${i} readyState=${e.readyState} err=${s}`),this.abandonSocketAndReconnect(e,t,i)})},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{p as AibotClient,j as preprocessLargeIntegers,z as withRequiredCapabilities};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1 +1 @@
1
- const A=16384,I=12288,E=1200,M=48;function i(t,r){const n=Number(t);return!Number.isFinite(n)||n<=0?r:Math.floor(n)}function U(t,r=1200){return Math.min(16384,i(t,r))}function f(t){return Math.min(16384,i(t,48))}function B(t,r){const n=String(t??"");if(!n)return[];const s=U(r,1200),o=[];let e="",T=0,_=0;for(const u of n){const O=Buffer.byteLength(u,"utf8"),c=T+1,L=_+O;e&&(c>s||L>12288)&&(o.push(e),e="",T=0,_=0),e+=u,T+=1,_+=O}return e&&o.push(e),o}export{A as AIBOT_PROTOCOL_MAX_RUNES,E as DEFAULT_OUTBOUND_TEXT_CHUNK_LIMIT,U as resolveOutboundTextChunkLimit,f as resolveStreamTextChunkLimit,B as splitTextForAibotProtocol};
1
+ const M=16384,S=12288,R=65536,f=32768,B=1048576,I=4006,L=1200,U=48;function s(n,t){const e=Number(n);return!Number.isFinite(e)||e<=0?t:Math.floor(e)}function E(n,t=1200){return Math.min(16384,s(n,t))}function x(n){return Math.min(16384,s(n,48))}function u(n,t,e){if(!n)return[];const o=[];let _="",O=0,r=0;for(const T of n){const c=Buffer.byteLength(T,"utf8"),A=O+1,i=r+c;_&&(A>t||e!==void 0&&i>e)&&(o.push(_),_="",O=0,r=0),_+=T,O+=1,r+=c}return _&&o.push(_),o}function C(n,t){const e=String(n??""),o=E(t,1200);return u(e,o,12288)}function l(n,t=65536){const e=Math.min(65536,s(t,65536));return u(String(n??""),e)}function p(n,t,e="\u2026[truncated]"){const o=String(n??"");if(t<=0)return"";const _=[...o];if(_.length<=t)return o;const O=[...e],r=O.length<t?O:O.slice(0,Math.max(0,t-1)),T=t-r.length;return`${_.slice(0,T).join("")}${r.join("")}`}export{f as AIBOT_PROTOCOL_MAX_EXTRA_BYTES,R as AIBOT_PROTOCOL_MAX_MESSAGE_RUNES,B as AIBOT_PROTOCOL_MAX_PACKET_BYTES,M as AIBOT_PROTOCOL_MAX_RUNES,I as AIBOT_PROTOCOL_PAYLOAD_TOO_LARGE_CODE,L as DEFAULT_OUTBOUND_TEXT_CHUNK_LIMIT,p as clampProtocolText,E as resolveOutboundTextChunkLimit,x as resolveStreamTextChunkLimit,C as splitTextForAibotProtocol,l as splitTextForSendMsg};
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: grix-agent-dispatch
3
3
  description: "Dispatch work to another agent in a specified directory, stop or redirect a running task, or update an agent name/introduction. If you were dispatched, report back via this skill's `report_dispatch_result` procedure (not a tool), which sends `[dispatch-result]`."
4
- trigger: When the user wants to hand a task to another of the owner's agents, have an agent work in a specific directory, abort or redirect a running dispatched task, or rename an agent / change its introduction; or when you were dispatched yourself and must write back via report_dispatch_result
4
+ trigger: When the user wants to hand a task to another of the owner's agents, have an agent work in a specific directory, add work to an existing dispatched session (check its queue first), abort or redirect a running dispatched task, or rename an agent / change its introduction; or when you were dispatched yourself and must write back via report_dispatch_result
5
5
  ---
6
6
 
7
7
  # Grix Agent Dispatch
@@ -118,6 +118,32 @@ You may call `grix_chat_state_query` **once** for the dispatched session id
118
118
 
119
119
  Never query message history as a substitute for the callback or `final_result`.
120
120
 
121
+ ### Adding work to an existing dispatched session — check the queue first
122
+
123
+ `grix_dispatch_agent` always opens a new session. When you instead send more
124
+ work into a session whose dispatched agent may still be busy, remember that it
125
+ runs its queue **serially**: a new message is only seen after everything ahead
126
+ of it finishes. Never just append to the tail:
127
+
128
+ 1. **Look first.** Call `grix_chat_queue` with `action: "list"` and
129
+ `session_id` = the dispatched work session (tool semantics are in the
130
+ `grix-chat-state` skill). Note what is running and what is queued.
131
+ 2. **Decide by what you see:**
132
+
133
+ | Situation | Action |
134
+ | --- | --- |
135
+ | The new task supersedes or voids a queued instruction | `cancel` the stale item, or `edit` it so old and new become one message |
136
+ | Urgent, or the running task is heading the wrong way | `cancel` stale queued items **first**; then, only if the running task must stop, send a standalone `/stop` (next section) before the new task; if other items remain ahead of it, `reorder` the new task to the front |
137
+ | Unrelated to the current task, and the current task is long | Do not queue — dispatch it into a new session with `grix_dispatch_agent` so it runs in parallel |
138
+ | None of the above | Append normally |
139
+
140
+ 3. **Verify.** Call `list` again and confirm the running task is the one that
141
+ should be running. A `confirmed: false` result is unverified until `list`
142
+ shows it.
143
+
144
+ `cancel`, `edit`, and `reorder` only touch queued tasks; only `/stop` reaches
145
+ the running one.
146
+
121
147
  ### Aborting or redirecting a running dispatched task
122
148
 
123
149
  A dispatched agent that is still working **queues** incoming messages: anything
package/dist/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};