grix-connector 4.16.2 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/acp/acp-adapter.js +8 -8
- package/dist/adapter/agy/agy-adapter.js +8 -8
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/codex/codex-bridge.js +10 -10
- package/dist/adapter/codex/rollout-import.js +1 -0
- package/dist/adapter/codex/thread-archive.js +6 -0
- package/dist/adapter/codex/thread-resume.js +1 -0
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
- package/dist/adapter/deepseek-harness/prompt-builder.js +4 -4
- package/dist/adapter/deepseek-harness/workspace-attachments.js +3 -0
- package/dist/adapter/opencode/opencode-adapter.js +1 -1
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.16.2.tgz → grix-dsh-bridge-4.18.0.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/send-controller.js +3 -3
- package/dist/bridge/session-list.js +2 -2
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -1
- package/dist/core/util/cli-probe.js +2 -2
- package/dist/kimi-plugins/index.js +2 -2
- package/dist/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
- package/dist/kimi-plugins/grix-layer/SKILL.md +0 -68
- package/dist/kimi-plugins/grix-layer/SYSTEM.md +0 -16
- package/dist/kimi-plugins/grix-layer/kimi.plugin.json +0 -10
- package/dist/kimi-plugins/grix-layer/references/gateway-architecture.md +0 -157
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EventEmitter as I}from"node:events";import{randomUUID as R}from"node:crypto";import T from"node:os";import k from"ws";import{log as g}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 w,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 u=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),a=t-u;e+=!o&&a>=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 m 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 u=(async()=>{try{if(s=await P(),s!==void 0)try{i=await q(s);const o=B();o>0&&(r=o)}catch(o){g.warn("aibot",`file server pre-start failed: ${o}`)}}catch(o){g.warn("aibot",`tailnet detect failed: ${o}`)}})();return new Promise((o,c)=>{const a=new k(this.config.url);this.ws=a;const f=setTimeout(()=>{if(!this.isConnectionCurrent(a,n))return;const l=this.pendingRequests.get(p);l&&(this.pendingRequests.delete(p),clearTimeout(l.timer),l.reject(new Error("Auth timeout: no auth_ack received within 15s"))),this.cleanupSocket(a,n)},15e3),p=++this.seq,b=setTimeout(()=>{if(!this.isConnectionCurrent(a,n))return;const l=this.pendingRequests.get(p);l&&(this.pendingRequests.delete(p),l.reject(new Error("Auth request timeout"))),this.cleanupSocket(a,n)},15e3);this.pendingRequests.set(p,{expected:["auth_ack"],resolve:l=>{clearTimeout(f);const d=l.payload;if(d.code===0){this.negotiatedCapabilities=new Set(Array.isArray(d.supported_capabilities)?d.supported_capabilities:[]),this.connected=!0,this.everConnected=!0,this.reconnectAttempts=0,d.heartbeat_sec&&(this.heartbeatSec=d.heartbeat_sec),d.ack_policy&&(this.ackPolicy=d.ack_policy,g.info("aibot",`ack_policy received: push_ack_timeout_ms=${d.ack_policy.push_ack_timeout_ms??"default"} max_retries=${d.ack_policy.max_retries??"default"} timeout_action=${d.ack_policy.timeout_action??"default"}`)),this.startHeartbeat();const h=this.flushOutboundBuffer(a,n);this.emit("auth",d),o(d),h.then(_=>{this.isConnectionCurrent(a,n)&&(_?(this.replayTerminalOutbox(),this.replayStopResultOutbox()):this.reconnectAfterOutboundFlushFailure(a,n))})}else d.code===A?(this.agentDeleted=!0,c(new M(`Agent deleted: code=${d.code} msg=${d.msg}`))):c(new Error(`Auth failed: code=${d.code} msg=${d.msg}`))},reject:l=>{clearTimeout(f),c(l)},timer:b}),a.on("open",async()=>{if(await u,!this.isConnectionCurrent(a,n))return;const l={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&&(l.shared_owner_id=this.config.sharedOwnerId),this.config.clientVersion&&(l.client="grix-connector",l.client_version=this.config.clientVersion,l.host_type=this.config.clientType,l.host_version=this.config.clientVersion),this.config.adapterHint&&(l.adapter_hint=this.config.adapterHint),l.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&&(l.concurrency=this.config.concurrency),this.sendPacket("auth",l,p)}),a.on("message",l=>{if(!this.isConnectionCurrent(a,n))return;let d;try{d=JSON.parse(G(l.toString()))}catch{return}try{this.handlePacket(d)}catch(h){this.emitClientError(new Error(`handlePacket error: ${h}`))}}),a.on("close",(l,d)=>{if(!this.isConnectionCurrent(a,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=${l} reason=${d.toString()||"<none>"}`,O=this.outboundFlushInFlight;O&&O.socket===a&&O.connectionGeneration===n&&this.cancelOutboundFlush(O,h?"connection_lost":"discard",_),h?this.settleUnfencedOutputsForSocket(a,_):this.unfencedOutputEventsBySocket.delete(a),this.abortPendingOutputWrites(h,a,n,h?_:void 0),this.abortPendingAcceptedOutputs(h,a,n),this.clearAllEventCorrelations(),this.ws===a&&(this.ws=null),this.connectionGeneration++,this.emit("close",l,d.toString());const y=h;g.info("aibot",`ws closed agent=${this.config.clientType}:${this.config.agentId} code=${l} reason=${d.toString()||"<none>"} everConnected=${this.everConnected} reconnecting=${this.reconnecting} agentDeleted=${this.agentDeleted} willReconnect=${y}`),y&&this.attemptReconnect(l===1e3||l===1001)}),a.on("error",l=>{if(this.isConnectionCurrent(a,n)&&(this.emitClientError(l instanceof Error?l:new Error(String(l))),!this.connected)){const d=this.pendingRequests.get(p);d&&(this.pendingRequests.delete(p),clearTimeout(d.timer),d.reject(l instanceof Error?l:new Error(String(l))))}})})}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===w?"discard":"connection_lost",`kicked reason=${t?.reason??"<none>"}`),t?.reason!==w&&n&&this.settleUnfencedOutputsForSocket(n,`kicked reason=${t?.reason??"<none>"}`),this.abortPendingOutputWrites(t?.reason!==w,n??void 0,s,t?.reason!==w?`kicked reason=${t?.reason??"<none>"}`:void 0),this.abortPendingAcceptedOutputs(t?.reason!==w,n??void 0,s),this.clearAllEventCorrelations(),this.connectionGeneration++,t?.reason===w){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}g.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)||g.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&&(g.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()||R()};this.sendPacket("send_msg",t)||g.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[u,o]of this.sendMsgWindowBySession){const c=L(o,s);c.length?this.sendMsgWindowBySession.set(u,c):this.sendMsgWindowBySession.delete(u)}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((u,o)=>{const c=()=>{clearTimeout(a),this.sendMsgRequestWaiters.delete(c),o(new Error("connection lost while waiting for send_msg rate slot"))},a=setTimeout(()=>{this.sendMsgRequestWaiters.delete(c),u()},r);a.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),g.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>m.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){g.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"))){g.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),u=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(u)}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=R(),u=Math.max(1e3,Math.min(n,75e3)),o=setTimeout(()=>{this.pendingInvokes.delete(r),i(new Error(`agent_invoke timeout: ${e}`))},u);this.pendingInvokes.set(r,{resolve:s,reject:i,timer:o}),this.sendPacket("agent_invoke",{invoke_id:r,action:e,params:t,timeout_ms:u})})}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 u=++this.seq,o=setTimeout(()=>{this.pendingRequests.delete(u),r(new x(`request timeout: ${e} (expected ${n.expected.join("/")})`))},n.timeoutMs);this.pendingRequests.set(u,{expected:n.expected,resolve:i,reject:r,timer:o,retryRateLimit:n.retryRateLimit}),this.sendPacket(e,t,u)||(this.pendingRequests.delete(u),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()||R()},t)}async sendMedia(e,t=2e4){return this.sendMessageRequestWithRetry({...e,msg_type:2,client_msg_id:e.client_msg_id?.trim()||R()},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(){g.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;g.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 u=null,o=this.connectionGeneration;try{const c=this.connect();if(u=this.ws,o=this.connectionGeneration,await c,this.reconnectRunGeneration!==t)return;if(!u||!this.isConnectionCurrent(u,o)){if(this.connected&&this.ws){this.reconnecting=!1;return}continue}const a=this.reconnectAttempts;this.reconnectAttempts=0,this.reconnecting=!1,g.info("aibot",`reconnect succeeded agent=${this.config.clientType}:${this.config.agentId} attempt=${a}`);return}catch(c){if(this.reconnectRunGeneration!==t)return;if(u&&!this.isConnectionCurrent(u,o)&&this.connected&&this.ws){this.reconnecting=!1;return}if(u&&this.isConnectionCurrent(u,o)){this.connectionGeneration++;try{u.close()}catch{}this.ws===u&&(this.ws=null)}const a=c instanceof Error?c.message:String(c);if(g.warn("aibot",`reconnect failed agent=${this.config.clientType}:${this.config.agentId} attempt=${this.reconnectAttempts} err=${a}`),c instanceof M){this.agentDeleted=!0,this.reconnecting=!1,g.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(a)){if(n++,n>=m.MAX_CONSECUTIVE_AUTH_FAILURES){this.reconnecting=!1,g.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"),g.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)&&!m.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 u=this.ws.bufferedAmount>m.BACKPRESSURE_THRESHOLD;if(!u||!m.DROPPABLE_COMMANDS.has(e)){if(u&&m.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 a=this.ws,f=this.connectionGeneration,p=s;p&&this.trackOutboundEventCorrelation(e,o,t),i&&p&&(this.registerPendingOutputWrite(o,p,i,a,f),this.isAckRequiredOutput(e,t)&&this.registerPendingAcceptedOutput(o,p,i,a,f));let b=!1;try{const l=a.readyState,d=a.bufferedAmount;let h=!1;return a.send(JSON.stringify(c),_=>{if(_&&!h&&(b=!0),e==="event_result"){const v=t;_?g.warn("aibot",`event_result ws send callback failed event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${l} bufferedAmount=${d} err=${_.message}`):g.info("aibot",`event_result ws send callback ok event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${l} bufferedAmount=${d}`)}else if(e==="client_stream_chunk"){const v=t;_?g.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=${l} bufferedAmount=${d} err=${_.message}`):g.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=${l} bufferedAmount=${d}`)}else if(e==="event_ack"){const v=t;_?g.warn("aibot",`event_ack ws send failed event=${v.event_id??""} seq=${o} readyState=${l} bufferedAmount=${d} err=${_.message}`):g.info("aibot",`event_ack ws send ok event=${v.event_id??""} seq=${o} readyState=${l} bufferedAmount=${d}`)}else if(e==="send_msg"){const v=t;_?g.warn("aibot",`send_msg ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${l} bufferedAmount=${d} err=${_.message}`):g.info("aibot",`send_msg ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${l} bufferedAmount=${d}`)}else if(_){const v=t;g.warn("aibot",`${e} ws send failed seq=${o} session=${v.session_id??""} event=${v.event_id??""} client_msg_id=${v.client_msg_id??""} readyState=${l} bufferedAmount=${d} err=${_.message}`)}const O=this.pendingOutputWrites.get(o),y=!!(O&&O.socket===a&&O.connectionGeneration===f);if(!this.isConnectionCurrent(a,f)){y&&(this.settlePendingOutputWrite(o,!1,!1,a,f),this.settlePendingAcceptedOutput(o,"retry",!1,a,f));return}if(!(i&&p&&!y)){if(_)this.removeSeqFromEventCorrelation(o),p?(this.settlePendingOutputWrite(o,!1,!0,a,f),this.settlePendingAcceptedOutput(o,"retry",!1,a,f)):i&&this.bufferOutboundEntry(i),n!==void 0?this.rejectPendingRequestAfterWriteFailure(o,e,_):i&&this.reconnectAfterOutboundWriteFailure(a,`${e} callback failed`);else if(p){const v=y;this.settlePendingOutputWrite(o,!0,!1,a,f),v&&O&&this.trackUnfencedOutput(a,O.entry,o)}}}),h=!0,!b}catch(l){return this.isConnectionCurrent(a,f)?(this.removeSeqFromEventCorrelation(o),p?(this.settlePendingOutputWrite(o,!1,!0,a,f),this.settlePendingAcceptedOutput(o,"retry",!1,a,f)):i&&this.bufferOutboundEntry(i),this.emitClientError(new Error(`sendPacket failed: ${l}`)),i&&this.reconnectAfterOutboundWriteFailure(a,`${e} send threw`),!1):(this.settlePendingOutputWrite(o,!1,!1,a,f),this.settlePendingAcceptedOutput(o,"retry",!1,a,f),!1)}}}if(m.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 u=t;g.info("aibot",`stream_chunk buffered (ws not open) event=${u.event_id??""} session=${u.session_id??""} chunk_seq=${u.chunk_seq??""} is_finish=${u.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(!m.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>m.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 e==="codex_event"}isReplayableStreamDelta(e,t){return e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish!==!0}trackUnfencedOutput(e,t,n){const{cmd:s,payload:i}=t,r=this.isReplayableStreamDelta(s,i);if(!r&&!this.isNonReplayableOutput(s))return;const u=this.outboundEventId(s,i);if(!u||this.outputIntegrityFailed.has(u)||this.blockedOutputEvents.has(u))return;let o=this.unfencedOutputEventsBySocket.get(e);o||(o=new Map,this.unfencedOutputEventsBySocket.set(e,o));let c=o.get(u);if(c||(c={seq:0,replay:[]},o.set(u,c)),c.seq=Math.max(c.seq,n),!!c.replay){if(!r||c.replay.length>=m.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 u of i.replay){if(!this.bufferOutboundEntry(u))break;r++}g.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 u=Date.now();let o=this.eventCorrelations.get(s);if(!o){if(this.eventCorrelations.size>=m.MAX_EVENT_CORRELATIONS){let a;for(const f of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(f.eventId)||(!a||f.touchedAt<a.touchedAt)&&(a=f);a&&this.releaseEventCorrelations(a.eventId)}o={eventId:s,clientMsgIds:new Set,seqRanges:[],touchedAt:u,expiresAt:u+m.EVENT_CORRELATION_TTL_MS},this.eventCorrelations.set(s,o)}o.touchedAt=u,o.expiresAt=u+m.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 a=this.clientMsgEventMap.get(r);a||(a=new Set,this.clientMsgEventMap.set(r,a)),a.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||m.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}`,u=Date.now(),o=this.unmatchedNackLoggedAt.get(r)??0;if(o>0&&u-o<m.UNMATCHED_NACK_LOG_WINDOW_MS)return;if(this.unmatchedNackLoggedAt.size>=256){for(const[a,f]of this.unmatchedNackLoggedAt)u-f>=m.UNMATCHED_NACK_LOG_WINDOW_MS&&this.unmatchedNackLoggedAt.delete(a);this.unmatchedNackLoggedAt.size>=256&&this.unmatchedNackLoggedAt.clear()}this.unmatchedNackLoggedAt.set(r,u);const c=typeof t.msg=="string"?t.msg:"";g.warn("aibot",`backend rejected ${n} session=${s||"<none>"} code=${i} msg=${c||"<none>"} seq=${e.seq} (repeats suppressed for ${m.UNMATCHED_NACK_LOG_WINDOW_MS/1e3}s)`)}handleCorrelatedSendResponse(e){if(this.rateLimitedSeqs.has(e.seq))return;if(e.cmd==="send_ack"){const a=e.payload,f=typeof a.client_msg_id=="string"?a.client_msg_id.trim():"";let p=e.seq>0&&this.pendingAcceptedOutputs.has(e.seq)?e.seq:void 0,b;if(p===void 0&&f){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&&(p=_,b=y)}}const l=(p!==void 0?this.pendingAcceptedOutputs.get(p)?.eventId:void 0)??b??this.eventIdForSeq(e.seq),d=p??e.seq;if(p!==void 0){const h=this.pendingOutputWrites.get(p);h&&this.settlePendingOutputWrite(p,!0,!1,h.socket,h.connectionGeneration),this.settlePendingAcceptedOutput(p,"accepted",!1)}else if(e.seq>0){const h=this.pendingOutputWrites.get(e.seq);h&&this.settlePendingOutputWrite(e.seq,!0,!1,h.socket,h.connectionGeneration)}l&&this.clearUnfencedOutputThrough(this.ws,l,d);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),u=s&&(!i||m.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)??u;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),g.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 u=setTimeout(()=>{this.terminalRetryTimers.delete(e),this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0})},r);this.terminalRetryTimers.set(e,u);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"),m.TERMINAL_RETRY_DELAY_MS}if(!await this.awaitOutputDeliveryBarrier(t))return m.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}`)),m.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}`)),m.TERMINAL_RETRY_DELAY_MS}const r=Math.max(1,this.ackPolicy?.max_retries??3),u=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 p=this.ws?.readyState??-1,b=this.ws?.bufferedAmount??0;g.info("aibot",`event_result send attempt event=${i.event_id} status=${i.status} attempt=${f}/${r} readyState=${p} bufferedAmount=${b}`);try{const l=await this.sendEventResultRequest(i,u);if(!this.terminalOutbox.isCurrent(e))return 0;if(l.cmd==="send_ack"){const h=l.payload;if(g.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 d=l.payload;if(g.warn("aibot",`event_result rejected event=${i.event_id} status=${i.status} attempt=${f}/${r} cmd=${l.cmd} code=${d.code??""} msg=${d.msg??""}${d.ref_cmd?` ref_cmd=${d.ref_cmd}`:""}${d.ref_id?` ref_id=${d.ref_id}`:""}`),n){c=`tokenized terminal rejected: cmd=${l.cmd} code=${d.code??""} msg=${d.msg??""}`;const h=(this.tokenizedTerminalRejections.get(i.event_id)??0)+1;if(this.tokenizedTerminalRejections.set(i.event_id,h),h<m.MAX_TOKENIZED_TERMINAL_REJECTIONS)break;this.tokenizedTerminalRejections.delete(i.event_id);try{this.terminalCommitTokens.remove(i.event_id,n),this.terminalOutbox.moveToDeadLetter(e,{responseCmd:l.cmd,code:d.code,message:d.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=${l.cmd} code=${d.code??""} msg=${d.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:l.cmd,code:d.code,message:d.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=${l.cmd} code=${d.code??""} msg=${d.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(l){const d=l instanceof Error?l.message:String(l);if(c=d,g.warn("aibot",`event_result attempt failed event=${i.event_id} status=${i.status} attempt=${f}/${r} err=${d}`),f===r)break;await new Promise(h=>setTimeout(h,o*f))}}const a=Date.now()+m.TERMINAL_RETRY_DELAY_MS;try{this.terminalOutbox.recordRetry(e,a,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}`)),m.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&&g.info("aibot",`purged ${t-this.outboundBuffer.length} buffered stream chunks for event=${e}`)}emitClientError(e){if(this.listenerCount("error")===0){g.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>m.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=m.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(u){this.emitClientError(new Error(`event_stop_result discard persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${u instanceof Error?u.message:u}`))}return 0}}}catch(i){n=i instanceof Error?i.message:String(i)}const s=Date.now()+m.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}`)),m.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(u=>this.outboundEventId(u.cmd,u.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 u=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e,t));this.scheduleTerminalDelivery(u.payload.event_id,{ignoreNotBefore:!0})}catch(u){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e}: ${u instanceof Error?u.message:u}`))}for(const u of[...this.pendingOutputSeqsByEvent.get(e)??[]])this.settlePendingOutputWrite(u,!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>=m.MAX_OUTBOUND_BUFFER_SIZE&&(this.outboundBuffer=this.outboundBuffer.filter(n=>m.BUFFER_OVERFLOW_RETAIN_COMMANDS.has(n.cmd)),this.outboundBuffer.length>=m.MAX_OUTBOUND_BUFFER_SIZE&&g.warn("aibot",`outbound buffer soft limit exceeded by ${this.outboundBuffer.length} retained packet(s); preserving required output`)),this.outboundBuffer.length>=m.MAX_OUTBOUND_BUFFER_HARD_SIZE?(t?this.markOutputIntegrityFailed(t,`outbound buffer hard limit ${m.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached`):this.emitClientError(new Error(`outbound buffer hard limit ${m.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 u=new Promise(a=>{r=a}),o=setTimeout(()=>{const a=this.pendingOutputWrites.get(e);if(!a||a.socket!==s||a.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`)},m.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);o.unref?.(),this.pendingOutputWrites.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,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 u=this.pendingOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.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 u=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),a=Math.max(1e3,Math.ceil(o*.25)),f=Math.max(m.MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS,o*c+a),p=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);p.unref?.(),this.pendingAcceptedOutputs.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,resolve:r,timer:p});const b=n.payload,l=typeof b.client_msg_id=="string"?b.client_msg_id.trim():"";if(l){let h=this.pendingAcceptedSeqsByClientMsgId.get(l);h||(h=new Set,this.pendingAcceptedSeqsByClientMsgId.set(l,h)),h.add(e)}let d=this.pendingAcceptedOutputSeqsByEvent.get(t);d||(d=new Set,this.pendingAcceptedOutputSeqsByEvent.set(t,d)),d.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 u=this.pendingAcceptedOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.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 a=this.pendingAcceptedSeqsByClientMsgId.get(c);a?.delete(e),a?.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:u}=i,o=this.outboundEventId(r,u);if(e.nextIndex=s,r==="send_msg"){for(;this.isOutboundFlushCurrent(e)&&!(o&&this.blockedOutputEvents.has(o));){const p=Math.max(this.sendMsgDelay(u),(this.sendMsgRetryAfter.get(i)??0)-Date.now());if(p<=0)break;if(!await this.awaitOutboundPacing(e,p))return!1}if(!this.isOutboundFlushCurrent(e))return!1}if(o&&this.blockedOutputEvents.has(o)){this.packetLog?.logOutboundPacket(r,0,u,"dropped"),e.nextIndex=s+1,e.currentWritePending=!1,e.currentWriteOutcome=null;continue}r==="send_msg"&&this.sendMsgDelay(u,!0);const c=++this.seq,a={cmd:r,seq:c,payload:u};e.nextIndex=s,e.currentWritePending=!0,e.currentWriteOutcome=null,o&&this.isAckRequiredOutput(r,u)&&this.registerPendingAcceptedOutput(c,o,i,t,e.connectionGeneration);const f=await new Promise(p=>{let b=!1;const l=h=>{b||(b=!0,clearTimeout(d),e.currentWriteOutcome=h,p(h))},d=setTimeout(()=>l("uncertain"),m.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);d.unref?.(),e.cancelCurrentWrite=()=>l("canceled");try{this.trackOutboundEventCorrelation(r,c,u),t.send(JSON.stringify(a),h=>{l(h?"retry":"written")})}catch{l("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 p=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}; ${p} 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 u=0;for(const o of s.slice(r))this.bufferOutboundEntry(o)&&u++;return e.activeBatch=null,e.nextIndex=s.length,e.currentWritePending=!1,u}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){if(this.agentDeleted||this.ws!==e)return;const n=this.connectionGeneration;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests(t);const s=this.outboundFlushInFlight;s&&s.socket===e&&s.connectionGeneration===n&&this.cancelOutboundFlush(s,"connection_lost",t),this.settleUnfencedOutputsForSocket(e,t),this.abortPendingOutputWrites(!0,e,n,t),this.abortPendingAcceptedOutputs(!0,e,n),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1011,t)}catch{}this.ws===e&&(this.ws=null),this.attemptReconnect()}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(()=>{!this.connected||!this.isConnectionCurrent(e,t)||(this.heartbeatFailures++,!(this.heartbeatFailures<m.HEARTBEAT_MAX_FAILURES)&&(this.cleanupSocket(e,t),this.attemptReconnect()))})},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{m as AibotClient,G as preprocessLargeIntegers,j as withRequiredCapabilities};
|
|
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 +1 @@
|
|
|
1
|
-
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const
|
|
1
|
+
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProvider as r,detectProviderFromModel as i,normalizeProviderId as a,queryProviderQuota as t,readKimiProviderSettings as d,readOpenCodeProviderSettings as s,readPiProviderSettings as n,resolveKimiProviderSettings as p}from"./providers.js";import{isOpenaiCodexProviderName as C,parseOpenaiCodexUsage as
|
|
1
|
+
import{detectProvider as r,detectProviderFromModel as i,normalizeProviderId as a,queryProviderQuota as t,readKimiProviderSettings as d,readOpenCodeProviderSettings as s,readPiProviderSettings as n,resolveKimiProviderSettings as p}from"./providers.js";import{isOpenaiCodexProviderName as C,parseOpenaiCodexUsage as l,queryOpenaiCodexQuota as u,resolveOpenaiCodexAccessToken as O,openaiCodexQuotaCacheKey as x}from"./openai-codex.js";import{ProviderQuotaService as m,sharedProviderQuotaService as Q,resolveQuotaBaseUrl as y}from"./service.js";import{providerQuotaToRateLimits as f,providerQuotaToCodexRateLimits as K,providerQuotaToolbarExtras as S}from"./presentation.js";import{findOpenCodeConsoleKey as q,isOpenCodeConsoleKey as E,OPENCODE_CONSOLE_ORIGIN as G,parseOpenCodeGoQuota as N,queryOpenCodeGoQuota as R,resolveOpenCodeConsoleQuotaKey as T,resolvePiOpenCodeConsoleQuotaKey as I}from"./opencode-go.js";import{queryGrixRelayWalletBalance as h}from"./grix-relay.js";export{G as OPENCODE_CONSOLE_ORIGIN,m as ProviderQuotaService,r as detectProvider,i as detectProviderFromModel,q as findOpenCodeConsoleKey,E as isOpenCodeConsoleKey,C as isOpenaiCodexProviderName,a as normalizeProviderId,x as openaiCodexQuotaCacheKey,N as parseOpenCodeGoQuota,l as parseOpenaiCodexUsage,K as providerQuotaToCodexRateLimits,f as providerQuotaToRateLimits,S as providerQuotaToolbarExtras,h as queryGrixRelayWalletBalance,R as queryOpenCodeGoQuota,u as queryOpenaiCodexQuota,t as queryProviderQuota,d as readKimiProviderSettings,s as readOpenCodeProviderSettings,n as readPiProviderSettings,p as resolveKimiProviderSettings,T as resolveOpenCodeConsoleQuotaKey,O as resolveOpenaiCodexAccessToken,I as resolvePiOpenCodeConsoleQuotaKey,y as resolveQuotaBaseUrl,Q as sharedProviderQuotaService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as g}from"node:fs";import{homedir as h}from"node:os";import{join as l}from"node:path";const C="https://opencode.ai/console",b=1e4,f=100000000n;function O(e){return typeof e=="string"&&e.trim().startsWith("oc_sk_")}function i(e){return{provider:"opencode_go",providerLabel:"OpenCode Go",planName:null,tiers:[],balance:null,success:!1,error:e}}function c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function p(e){if(typeof e=="bigint")return e;if(typeof e=="number"&&Number.isFinite(e))return BigInt(Math.trunc(e));if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))return null;try{return BigInt(e.trim())}catch{return null}}function _(e,n){return n<=0n?0:e>=n?100:Number((e*200n+n)/(n*2n))}function G(e){const n=e<0n,t=n?-e:e,o=t/f,r=t%f,s=Number(o)+Number(r)/Number(f);return n?-s:s}function k(e){return e==="go"?"Go":e==="go-plus"?"Go Plus":typeof e=="string"&&e.trim()?e:null}function d(e,n,t){const o=c(t);if(!o)return null;const r=p(o.limitMicroCents),s=p(o.usedMicroCents);if(r===null||s===null)return null;const u=typeof o.resetsAt=="string"?o.resetsAt:null;return{name:e,label:n,usedPercent:_(s,r),resetsAt:u}}function E(e,n){const t=c(e);if(!t)return i("Unexpected Go status response");const o=c(t.access),r=c(o?.meters),s=[d("five_hour","Rolling",r?.fiveHour),d("weekly_limit","Weekly",r?.week),d("monthly","Monthly",r?.month)].filter(N=>N!==null),u=c(n),m=u?p(u.availableMicroCents):null,y=m===null?null:{kind:"currency",remaining:G(m),total:null,used:null,unit:"USD"};return s.length===0&&!y?i("Go status did not include usage windows or credits"):{provider:"opencode_go",providerLabel:"OpenCode Go",planName:k(t.product),tiers:s,balance:y,success:!0,error:null}}async function S(e){const n={Authorization:`Bearer ${e.trim()}`,Accept:"application/json"};try{const[t,o]=await Promise.all([fetch(`${C}/api/go/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(b)}),fetch(`${C}/api/billing/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(b)})]);if(t.status===401||t.status===403)return i(`Authentication failed (HTTP ${t.status})`);if(!t.ok)return i(`Go status API error (HTTP ${t.status})`);const r=await t.json(),s=o.ok?await o.json():null;return E(r,s)}catch(t){return i(`Network error: ${t instanceof Error?t.message:String(t)}`)}}function a(e,n){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const o of e)a(o,n);return}const t=e;for(const o of["key","apiKey","api_key"]){const r=t[o],s=typeof r=="string"?r.trim():void 0;O(s)&&n.push(s)}for(const o of Object.values(t))a(o,n)}function T(e,n="opencode"){const t=e||h(),o=[l(t,".local","share",n,"auth.json"),l(t,".config",n,`${n}.json`)],r=[];for(const s of o)try{a(JSON.parse(g(s,"utf8")),r)}catch{}return r[0]}function A(e){for(const n of[e.quotaApiKey,e.envToken,e.providerApiKey]){const t=n?.trim();if(O(t))return t}}function w(e){return A(e)??T(e.home,e.vendor??"opencode")}function I(e){const n=A(e);if(n)return n;const t=e.piHome?.trim()||process.env.PI_CODING_AGENT_DIR?.trim()||l(h(),".pi","agent"),o=[];try{const r=JSON.parse(g(l(t,"auth.json"),"utf8")),s=r&&typeof r=="object"&&!Array.isArray(r)?r["opencode-go"]:void 0;a(s,o)}catch{}return o[0]}export{C as OPENCODE_CONSOLE_ORIGIN,T as findOpenCodeConsoleKey,O as isOpenCodeConsoleKey,_ as openCodeGoUsedPercent,E as parseOpenCodeGoQuota,S as queryOpenCodeGoQuota,w as resolveOpenCodeConsoleQuotaKey,I as resolvePiOpenCodeConsoleQuotaKey};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{
|
|
1
|
+
import{execFile as l}from"node:child_process";import{accessSync as T,constants as $,existsSync as C,statSync as P}from"node:fs";import{join as f,dirname as d,basename as M,delimiter as h,isAbsolute as S}from"node:path";import{promisify as a}from"node:util";import{resolveWindowsExecInvocation as D}from"../runtime/spawn.js";import{log as c}from"../log/logger.js";const F=3e3,W=5e3,w="__GRIX_SHELL_PATH__";function y(n,t){const e=[".cmd",".bat",".exe",""];for(const r of n)if(r)for(const i of e){const o=f(r,`${t}${i}`);if(C(o))return o}return null}const O=1e4,_={cache:null,inflight:null},b={cache:null,inflight:null},v={cache:null,inflight:null};let m=0;function Q(){m++;for(const n of[_,b,v])n.cache=null,n.inflight=null}function g(n,t){if(n.cache&&Date.now()-n.cache.at<O)return Promise.resolve(n.cache.value);if(n.inflight)return n.inflight;const e=m,r=t().then(i=>(m===e&&(n.cache={value:i,at:Date.now()}),n.inflight===r&&(n.inflight=null),i),i=>{throw n.inflight===r&&(n.inflight=null),i});return n.inflight=r,r}function G(){return f(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function R(){return g(_,async()=>{const n=a(l),t=async e=>{try{const{stdout:r}=await n(G(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${e}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return c.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${e} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await t("User"),...await t("Machine")]})}async function k(n){if(process.platform!=="win32")return null;const t=await R(),e=y(t,n)??await H(n);return e&&x(d(e)),e}function E(n){try{return P(n).isFile()?(T(n,$.X_OK),!0):!1}catch{return!1}}function N(n,t=process.platform){if(t==="win32")try{return P(n).isFile()}catch{return!1}return E(n)}function A(n,t){for(const e of n){if(!e)continue;const r=f(e,t);if(E(r))return r}return null}const V=new Set(["sh","bash","zsh","ksh","dash","ash"]);function L(){return g(b,async()=>{const n=process.env.SHELL||"/bin/sh";if(!V.has(M(n)))return c.info("cli-probe",`\u767B\u5F55 shell ${n} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const t=a(l);try{const e=t(n,["-lic",`printf '\\n${w}%s\\n' "$PATH"`],{timeout:W,killSignal:"SIGKILL",encoding:"utf-8"});e.child?.stdin?.end();const{stdout:r}=await e,i=r.split(/\r?\n/).reverse().find(o=>o.startsWith(w));return i?i.slice(w.length).split(h).map(o=>o.trim()).filter(Boolean):[]}catch(e){return c.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),[]}})}function U(){return g(v,async()=>{const n=a(l),t=process.platform==="win32";try{const{stdout:e}=await n(t?"cmd.exe":"npm",t?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...t?{windowsHide:!0}:{}});return e.trim()||null}catch{return null}})}async function H(n){const t=await U();return t?process.platform==="win32"?y([t],n):A([f(t,"bin"),t],n):null}async function K(n){if(process.platform==="win32")return null;const t=await L(),e=A(t,n)??await H(n);return c.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${n}: \u7ED3\u679C=${e??"\u672A\u627E\u5230"}`),e&&x(d(e))&&c.info("cli-probe",`\u5DF2\u5C06 ${d(e)} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`),e}async function Y(){if(process.platform==="win32")return[];const n=[];for(const t of await L())S(t)&&x(t)&&n.push(t);return n.length>0&&c.info("cli-probe",`\u542F\u52A8\u65F6\u4ECE\u767B\u5F55 shell PATH \u8FFD\u52A0 ${n.length} \u4E2A\u76EE\u5F55: ${n.join(h)}`),n}function x(n){const t=process.env.PATH??"",e=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;return t.split(h).some(r=>e(r,n))?!1:(process.env.PATH=t?`${t}${h}${n}`:n,!0)}async function Z(n){if(S(n))return N(n)?n:null;const t=a(l),e=process.platform==="win32",r=e?"where":"which";try{const{stdout:i}=await t(r,[n],{timeout:3e3,encoding:"utf-8"}),o=i.trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(o.length>0){if(e){const s=o.find(u=>/\.(cmd|bat)$/i.test(u));if(s)return s;const p=o.find(u=>/\.exe$/i.test(u));return p||o[0]}return o[0]}return await I(n)}catch{return await I(n)}}function I(n){return process.platform==="win32"?k(n):K(n)}async function nn(n,t=["--version"],e=F){const r=a(l);try{const i=D(n,t),{stdout:o,stderr:s}=await r(i.command,i.args,{timeout:e,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});return{version:(o||s||"").trim().split(`
|
|
2
|
+
`)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{A as findPosixExecutableInDirs,y as findWindowsExecutableInDirs,nn as getCliVersion,Q as invalidateCliPathCache,N as isUsableExecutablePath,Y as mergeLoginShellPathIntoProcess,Z as resolveCliPath,K as resolvePosixInstalledCli,H as resolveViaNpmGlobalBin,k as resolveWindowsInstalledCli};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`,{encoding:"utf8",mode:384}),
|
|
1
|
+
import{existsSync as c,readFileSync as d,renameSync as m,rmSync as p,writeFileSync as f}from"node:fs";import{join as s}from"node:path";import{resolveKimiCodeHome as y}from"../default-skills/index.js";const u="grix-layer",v=".grix-managed";function S(e){const n=JSON.parse(d(e,"utf8"));if(n.version!==1||!Array.isArray(n.plugins))throw new Error(`Invalid Kimi plugin registry: ${e}`);return n}function E(e=process.env){const n=y(e),o=s(n,"plugins",u),i=s(n,"plugins","installed.json"),r=c(i)?S(i):void 0,l=c(s(o,v));l&&p(o,{recursive:!0,force:!0});let g=!1;if(r){const a=r.plugins.filter(t=>t.id!==u);if(a.length!==r.plugins.length){const t=`${i}.grix-${process.pid}.tmp`;f(t,`${JSON.stringify({...r,version:1,plugins:a},null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384}),m(t,i),g=!0}}return{kimiHome:n,pluginRoot:o,installedFile:i,registrationChanged:g||l}}export{E as removeKimiLayerPlugin};
|
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
|
|
2
|
-
`)},error(o,r,...
|
|
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};
|