grix-connector 4.19.0 → 5.0.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.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/acp/acp-adapter.js +12 -12
  3. package/dist/adapter/agy/agy-adapter.js +10 -10
  4. package/dist/adapter/agy/model-list.js +2 -2
  5. package/dist/adapter/agy/quota.js +5 -5
  6. package/dist/adapter/claude/claude-adapter.js +20 -20
  7. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  8. package/dist/adapter/claude/claude-tools.js +1 -1
  9. package/dist/adapter/claude/claude-worker-client.js +1 -1
  10. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  11. package/dist/adapter/claude/result-timeout.js +1 -1
  12. package/dist/adapter/cursor/cursor-adapter.js +12 -11
  13. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  14. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
  15. package/dist/adapter/pi/pi-adapter.js +5 -4
  16. package/dist/adapter/pi/pi-grix-tools-extension.js +2 -0
  17. package/dist/assets/dsh-bridge/grix-dsh-bridge-5.0.0.tgz +0 -0
  18. package/dist/assets/dsh-bridge/manifest.json +6 -6
  19. package/dist/bridge/bridge.js +1 -1
  20. package/dist/bridge/rate-limits.js +1 -1
  21. package/dist/bridge/send-controller.js +3 -3
  22. package/dist/bridge/toolbar-meta.js +1 -1
  23. package/dist/core/access/allowlist-store.js +1 -1
  24. package/dist/core/file-ops/list-files.js +1 -1
  25. package/dist/core/installer/registry.js +1 -1
  26. package/dist/core/util/home-env.js +1 -0
  27. package/dist/grix.js +5 -5
  28. package/dist/log.js +2 -2
  29. package/dist/manager.js +1 -1
  30. package/dist/mcp/stream-http/config.js +1 -1
  31. package/dist/mcp/stream-http/connection-binding.js +1 -1
  32. package/dist/mcp/stream-http/tool-executor.js +1 -1
  33. package/dist/mcp/stream-http/tool-registry.js +1 -1
  34. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  35. package/dist/protocol/acp-client.js +1 -1
  36. package/openclaw-plugin/audit-recorder-worker.js +2 -1
  37. package/package.json +1 -1
  38. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
@@ -1,3 +1,3 @@
1
- import{isRequestTimeoutError as C}from"../core/aibot/errors.js";import{log as h}from"../core/log/index.js";import{splitTextForAibotProtocol as _,AIBOT_PROTOCOL_MAX_RUNES as y}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as S,isToolEventDropped as T,normalizeRuntimeConfigSnapshot as M}from"./runtime-config.js";const b={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class p{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;eventTriggerQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;openStreams=new Map;rejectedEvents=new Set;terminalEvents=new Set;terminalResultEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=$();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e),this.rejectedEvents.size>p.MAX_TERMINAL_EVENTS&&this.rejectedEvents.delete(this.rejectedEvents.values().next().value);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const i=this.streamCoalesce.get(s);i.timer&&clearTimeout(i.timer),this.streamCoalesce.delete(s)}h.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}hasTerminalResult(e){return!!e&&(this.terminalResultEvents.has(e)||this.terminalEvents.has(e))}rememberTerminalResult(e){if(e&&(this.terminalResultEvents.add(e),this.terminalResultEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalResultEvents.values().next().value;t!==void 0&&this.terminalResultEvents.delete(t)}}markEventStopped(e){e&&(this.stoppedEvents.add(e),h.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,i,r,l){!e||!this.stoppedEvents.has(e)||h.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${i} is_finish=${r} len=${l}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id),this.terminalResultEvents.delete(e.event_id);const t=M(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const i=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:i.responseDelivery,toolEvents:i.toolEvents,thinkingEvents:i.thinkingEvents}),h.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${i.responseDelivery} tool_events=${i.toolEvents} thinking_events=${i.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id);const s=typeof e.quoted_message_id=="string"?e.quoted_message_id.trim():"";s&&!this.eventTriggerQuotedMessageIds.has(e.event_id)&&this.eventTriggerQuotedMessageIds.set(e.event_id,s)}discardEventState(e){e&&(this.rememberTerminalResult(e),this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.eventTriggerQuotedMessageIds.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&h.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of[...this.openStreams.keys()])t.startsWith(`${e}:`)&&this.openStreams.delete(t);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}applyExplicitFinalQuote(e,t,s){const i=typeof s=="string"?s.trim():"";if(!i)return;const r=this.bufferedEventTexts.get(e);r&&!r.quotedMessageId&&(r.quotedMessageId=i);const l=this.streamCoalesce.get(`${e}:${t??"default"}`);return l&&!l.quotedMessageId&&(l.quotedMessageId=i),i}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}getCodexDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventTriggerQuotedMessageIds.get(e)??this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return T(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return S(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,i,r,l){if(!l?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&R(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const o=_(s),n=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(o.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:i||void 0});return}for(let u=0;u<o.length;u++){const f=u===o.length-1;this.sendStreamChunk(e,t,o[u],u+1,f,n,i)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:i||void 0,...r?{extra:r}:{}})}sendStreamChunk(e,t,s,i,r,l,a,o){if(this.isEventClosed(e))return;a=a??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",i,r,(s||"").length);const n=this.resolveEventRuntimeConfig(e);if(!o?.forceStream&&n.responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,a,l);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,i,r,l,a,o?.threadId);return}this.coalesceStreamChunk(e,t,s,r,l,a,o?.threadId)}async sendFinalStreamChunkReliable(e,t,s,i,r=!1,l=!1,a){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);l||this.finalizeThinking(e,t);const o=this.applyExplicitFinalQuote(e,s,a),n=this.resolveEventRuntimeConfig(e);if(!r&&n.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,i),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const u=`${e}:${s??"default"}`;this.flushCoalesce(u,!1),this.streamCoalesce.delete(u);const f=(this.chunkSeqMap.get(u)??0)+1;this.chunkSeqMap.set(u,f),this.openStreams.delete(u);const d=o||this.getDefaultQuotedMessageId(e),E={event_id:e,session_id:t,delta_content:"",chunk_seq:f,is_finish:!0,...s?{client_msg_id:s}:{},...d?{quoted_message_id:d}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",f,!0,0);const m=async()=>{const c=await this.handle.sendStreamChunkRequest(E,i);if(c.cmd!=="send_ack"){const k=c.payload;throw new Error(`final chunk rejected: cmd=${c.cmd} code=${k?.code??""} msg=${k?.msg??""}`)}};try{await m()}catch(c){if(C(c))h.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${f} event=${e}`),await m();else throw h.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${c}`),c}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,i){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const a=this.getDefaultQuotedMessageId(e),o=_(s);for(let n=0;n<o.length;n++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",n+1,!1,o[n].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o[n],...n===0&&a?{quoted_message_id:a}:{},client_msg_id:o.length>1?`${i}_p${n+1}`:i});return!0}const l=_(s);for(const a of l)this.sendStreamChunk(e,t,a,0,!1,i);return await this.sendFinalStreamChunkReliable(e,t,i,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,i,r,l,a){if(!s&&!i)return;const o=`${e}:${r??"default"}`;let n=this.streamCoalesce.get(o);if(n||(n={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:l,threadId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,n)),s&&(n.text+=s),n.sessionId=t,r!==void 0&&(n.clientMsgId=r),!n.quotedMessageId&&l&&(n.quotedMessageId=l),!n.threadId&&a&&(n.threadId=a),i){this.flushCoalesce(o,!0);return}if(!n.flushedOnce||n.text.length>=p.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}n.timer||(n.timer=setTimeout(()=>this.flushCoalesce(o,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const i=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!i&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,i,0,t,s.clientMsgId,s.quotedMessageId,s.threadId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,i,r,l,a,o){const n=s||(r?`
2
- `:"");if(!n&&!r)return;const u=_(n,y);u.length===0&&u.push(n||`
3
- `);const f=`${e}:${l??"default"}`;for(let d=0;d<u.length;d++){const E=d===u.length-1,m=this.chunkSeqMap.get(f)??0,c=d===0&&i>m?i:m+1;this.chunkSeqMap.set(f,c),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:u[d],chunk_seq:c,is_finish:E&&r,...l?{client_msg_id:l}:{},...a?{quoted_message_id:a}:{},...o?{thread_id:o}:{}})}e&&(r?this.openStreams.delete(f):this.openStreams.set(f,{eventId:e,sessionId:t,clientMsgId:l,quotedMessageId:a}))}finalizeOpenStreams(e){if(!e||this.isEventClosed(e))return;this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const t=`${e}:`;for(const[s,i]of[...this.openStreams]){if(!s.startsWith(t))continue;this.openStreams.delete(s);const r=(this.chunkSeqMap.get(s)??0)+1;this.chunkSeqMap.set(s,r),this.handle.sendStreamChunk({event_id:i.eventId,session_id:i.sessionId,delta_content:"",chunk_seq:r,is_finish:!0,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}}),h.info("send-ctrl",`appended missing stream fence before terminal event=${i.eventId} client_msg_id=${i.clientMsgId??"default"} chunk_seq=${r}`)}}sendEventResult(e,t,s,i,r=!1){if(!e||this.hasTerminalResult(e))return;this.rememberTerminalResult(e),this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const l=this.ensureSingleMessageDelivery(e),a=(o,n=s,u=i)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",u=u||"agent_output_rejected",n=n||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...n?{msg:n}:{},...u?{code:u}:{},...r&&o===t?{error_surfaced:!0}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!l){a(t);return}l.then(()=>a(t),o=>{const n=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?n:s,t==="responded"?"agent_output_delivery_failed":i)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const i=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,i),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:i,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,i){if(this.shouldDropToolDisplayEvent(e)){h.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const l=Date.now(),a=`${e}:${s.summaryText}:${s.detailText??""}`,o=this.recentToolCards.get(a);if(o!==void 0&&l-o<p.TOOL_CARD_DEDUP_MS){h.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(a,l);const n={summary_text:s.summaryText};s.detailText&&(n.detail_text=s.detailText),h.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:i??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:n}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,i,r){r=r??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,r)}bufferStreamChunk(e,t,s,i,r){const l=typeof r=="string"&&r.startsWith("reply_"),a=this.bufferedEventTexts.get(e);if(!a){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:i||void 0,replyReceived:l});return}l?a.replyReceived?s&&(a.text+=s):(a.text=s??"",a.replyReceived=!0):!a.replyReceived&&s&&(a.text+=s),!a.quotedMessageId&&i&&(a.quotedMessageId=i)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const i=this.bufferedEventTexts.get(e);if(!i||(this.bufferedEventTexts.delete(e),!i.text))return;const r=(async()=>{const l={event_id:e,session_id:i.sessionId,content:i.text,client_msg_id:`agent_single_${e}`,...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}},a=async()=>{const o=t===void 0?await this.handle.sendText(l):await this.handle.sendText(l,t);if(o.cmd!=="send_ack"){const n=o.payload;throw new Error(`single-message output rejected: cmd=${o.cmd} code=${n?.code??""} msg=${n?.msg??""}`)}};try{await a()}catch(o){if(!C(o))throw o;h.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${l.client_msg_id} event=${e}`),await a()}})();return this.singleMessageDeliveries.set(e,r),r}}function $(){const g=process.env.GRIX_STREAM_COALESCE_MS;if(g===void 0||g==="")return 500;const e=Number(g);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function R(g,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(g)||/^\[tool result\]/.test(g)}export{b as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,p as SendController};
1
+ import{isRequestTimeoutError as C}from"../core/aibot/errors.js";import{log as h}from"../core/log/index.js";import{splitTextForAibotProtocol as _,AIBOT_PROTOCOL_MAX_RUNES as y}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as S,isToolEventDropped as T,normalizeRuntimeConfigSnapshot as M}from"./runtime-config.js";const b={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class p{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;eventTriggerQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;openStreams=new Map;rejectedEvents=new Set;terminalEvents=new Set;terminalResultEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=$();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e),this.rejectedEvents.size>p.MAX_TERMINAL_EVENTS&&this.rejectedEvents.delete(this.rejectedEvents.values().next().value);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const i=this.streamCoalesce.get(s);i.timer&&clearTimeout(i.timer),this.streamCoalesce.delete(s)}h.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}hasTerminalResult(e){return!!e&&(this.terminalResultEvents.has(e)||this.terminalEvents.has(e))}rememberTerminalResult(e){if(e&&(this.terminalResultEvents.add(e),this.terminalResultEvents.size>p.MAX_TERMINAL_EVENTS)){const t=this.terminalResultEvents.values().next().value;t!==void 0&&this.terminalResultEvents.delete(t)}}markEventStopped(e){e&&(this.stoppedEvents.add(e),h.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,i,n,l){!e||!this.stoppedEvents.has(e)||h.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${i} is_finish=${n} len=${l}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id),this.terminalResultEvents.delete(e.event_id);const t=M(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const i=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:i.responseDelivery,toolEvents:i.toolEvents,thinkingEvents:i.thinkingEvents}),h.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${i.responseDelivery} tool_events=${i.toolEvents} thinking_events=${i.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id);const s=typeof e.quoted_message_id=="string"?e.quoted_message_id.trim():"";s&&!this.eventTriggerQuotedMessageIds.has(e.event_id)&&this.eventTriggerQuotedMessageIds.set(e.event_id,s)}discardEventState(e){e&&(this.rememberTerminalResult(e),this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.eventTriggerQuotedMessageIds.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&h.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of[...this.openStreams.keys()])t.startsWith(`${e}:`)&&this.openStreams.delete(t);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}applyExplicitFinalQuote(e,t,s){const i=typeof s=="string"?s.trim():"";if(!i)return;const n=this.bufferedEventTexts.get(e);n&&!n.quotedMessageId&&(n.quotedMessageId=i);const l=this.streamCoalesce.get(`${e}:${t??"default"}`);return l&&!l.quotedMessageId&&(l.quotedMessageId=i),i}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}getCodexDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventTriggerQuotedMessageIds.get(e)??this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return T(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return S(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,i,n,l){if(!l?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&R(s,n)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!n){const o=_(s),r=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(o.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:i||void 0});return}for(let u=0;u<o.length;u++){const f=u===o.length-1;this.sendStreamChunk(e,t,o[u],u+1,f,r,i)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:i||void 0,...n?{extra:n}:{}})}sendStreamChunk(e,t,s,i,n,l,a,o){if(this.isEventClosed(e))return;a=a??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",i,n,(s||"").length);const r=this.resolveEventRuntimeConfig(e);if(!o?.forceStream&&r.responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,a,l);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,i,n,l,a,o?.threadId);return}this.coalesceStreamChunk(e,t,s,n,l,a,o?.threadId)}async sendFinalStreamChunkReliable(e,t,s,i,n=!1,l=!1,a){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);l||this.finalizeThinking(e,t);const o=this.applyExplicitFinalQuote(e,s,a),r=this.resolveEventRuntimeConfig(e);if(!n&&r.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,i),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const u=`${e}:${s??"default"}`;this.flushCoalesce(u,!1),this.streamCoalesce.delete(u);const f=(this.chunkSeqMap.get(u)??0)+1;this.chunkSeqMap.set(u,f),this.openStreams.delete(u);const d=o||this.getDefaultQuotedMessageId(e),E={event_id:e,session_id:t,delta_content:"",chunk_seq:f,is_finish:!0,...s?{client_msg_id:s}:{},...d?{quoted_message_id:d}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",f,!0,0);const m=async()=>{const c=await this.handle.sendStreamChunkRequest(E,i);if(c.cmd!=="send_ack"){const k=c.payload;throw new Error(`final chunk rejected: cmd=${c.cmd} code=${k?.code??""} msg=${k?.msg??""}`)}};try{await m()}catch(c){if(C(c))h.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${f} event=${e}`),await m();else throw h.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${c}`),c}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,i){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const a=this.getDefaultQuotedMessageId(e),o=_(s);for(let r=0;r<o.length;r++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",r+1,!1,o[r].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o[r],...r===0&&a?{quoted_message_id:a}:{},client_msg_id:o.length>1?`${i}_p${r+1}`:i});return!0}const l=_(s);for(const a of l)this.sendStreamChunk(e,t,a,0,!1,i);return await this.sendFinalStreamChunkReliable(e,t,i,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,i,n,l,a){if(!s&&!i)return;const o=`${e}:${n??"default"}`;let r=this.streamCoalesce.get(o);if(r||(r={eventId:e,sessionId:t,clientMsgId:n,quotedMessageId:l,threadId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,r)),s&&(r.text+=s),r.sessionId=t,n!==void 0&&(r.clientMsgId=n),!r.quotedMessageId&&l&&(r.quotedMessageId=l),!r.threadId&&a&&(r.threadId=a),i){this.flushCoalesce(o,!0);return}if(!r.flushedOnce||r.text.length>=p.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}r.timer||(r.timer=setTimeout(()=>this.flushCoalesce(o,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const i=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!i&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,i,0,t,s.clientMsgId,s.quotedMessageId,s.threadId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,i,n,l,a,o){const r=s||(n?`
2
+ `:"");if(!r&&!n)return;const u=_(r,y);u.length===0&&u.push(r||`
3
+ `);const f=`${e}:${l??"default"}`;for(let d=0;d<u.length;d++){const E=d===u.length-1,m=this.chunkSeqMap.get(f)??0,c=d===0&&i>m?i:m+1;this.chunkSeqMap.set(f,c),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:u[d],chunk_seq:c,is_finish:E&&n,...l?{client_msg_id:l}:{},...a?{quoted_message_id:a}:{},...o?{thread_id:o}:{}})}e&&(n?this.openStreams.delete(f):this.openStreams.set(f,{eventId:e,sessionId:t,clientMsgId:l,quotedMessageId:a}))}finalizeOpenStreams(e){if(!e||this.isEventClosed(e))return;this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const t=`${e}:`;for(const[s,i]of[...this.openStreams]){if(!s.startsWith(t))continue;this.openStreams.delete(s);const n=(this.chunkSeqMap.get(s)??0)+1;this.chunkSeqMap.set(s,n),this.handle.sendStreamChunk({event_id:i.eventId,session_id:i.sessionId,delta_content:"",chunk_seq:n,is_finish:!0,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}}),h.info("send-ctrl",`appended missing stream fence before terminal event=${i.eventId} client_msg_id=${i.clientMsgId??"default"} chunk_seq=${n}`)}}sendEventResult(e,t,s,i,n=!1){if(!e||this.hasTerminalResult(e))return;this.rememberTerminalResult(e),this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const l=this.ensureSingleMessageDelivery(e),a=(o,r=s,u=i)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",u=u||"agent_output_rejected",r=r||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...r?{msg:r}:{},...u?{code:u}:{},...n&&o===t?{error_surfaced:!0}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!l){a(t);return}l.then(()=>a(t),o=>{const r=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?r:s,t==="responded"?"agent_output_delivery_failed":i)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const i=_(s,y);i.length===0&&i.push(s),this.thinkingSessionMap.set(e,t);for(const n of i){const l=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,l),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:n,chunk_seq:l,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}}sendToolExecutionCard(e,t,s,i){if(this.shouldDropToolDisplayEvent(e)){h.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const l=Date.now(),a=`${e}:${s.summaryText}:${s.detailText??""}`,o=this.recentToolCards.get(a);if(o!==void 0&&l-o<p.TOOL_CARD_DEDUP_MS){h.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(a,l);const r={summary_text:s.summaryText};s.detailText&&(r.detail_text=s.detailText),h.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:i??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:r}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,i,n){n=n??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,n)}bufferStreamChunk(e,t,s,i,n){const l=typeof n=="string"&&n.startsWith("reply_"),a=this.bufferedEventTexts.get(e);if(!a){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:i||void 0,replyReceived:l});return}l?a.replyReceived?s&&(a.text+=s):(a.text=s??"",a.replyReceived=!0):!a.replyReceived&&s&&(a.text+=s),!a.quotedMessageId&&i&&(a.quotedMessageId=i)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const i=this.bufferedEventTexts.get(e);if(!i||(this.bufferedEventTexts.delete(e),!i.text))return;const n=(async()=>{const l={event_id:e,session_id:i.sessionId,content:i.text,client_msg_id:`agent_single_${e}`,...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}},a=async()=>{const o=t===void 0?await this.handle.sendText(l):await this.handle.sendText(l,t);if(o.cmd!=="send_ack"){const r=o.payload;throw new Error(`single-message output rejected: cmd=${o.cmd} code=${r?.code??""} msg=${r?.msg??""}`)}};try{await a()}catch(o){if(!C(o))throw o;h.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${l.client_msg_id} event=${e}`),await a()}})();return this.singleMessageDeliveries.set(e,n),n}}function $(){const g=process.env.GRIX_STREAM_COALESCE_MS;if(g===void 0||g==="")return 500;const e=Number(g);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function R(g,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(g)||/^\[tool result\]/.test(g)}export{b as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,p as SendController};
@@ -1 +1 @@
1
- import{ClaudeAdapter as x}from"../adapter/claude/index.js";import{getCachedModels as L}from"../adapter/claude/model-list.js";import{SESSION_CONTROL_ERROR_CODES as R,SESSION_MODE_IDS as _}from"../adapter/claude/protocol-contract.js";import{CursorAdapter as I,CURSOR_MODE_OPTIONS as Q}from"../adapter/cursor/index.js";import{getCachedAgyModels as b,primeAgyModels as P,resolveAgyToolbarModelId as p}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as S,refreshAgyQuotaInfo as y}from"../adapter/agy/quota.js";import{normalizeClaudeEffort as T,CLAUDE_EFFORT_LEVELS as w}from"../core/config/claude-direct-env.js";import{resolveToolbarSelection as m}from"./toolbar-selection.js";import{log as M}from"../core/log/index.js";const U=["isRateLimitsCacheFresh","isGrixRelayActive","getFreshClaudeRateLimitState","maybeQueryProviderQuota","providerQuotaToRateLimits","normalizeClaudeModeId","resolveSessionModelId","resolveCursorSessionModeId","resolveClaudeSessionEffort","resolveClaudeSessionModeId","currentClaudeModeId","buildAgyToolbarMeta","buildAgyQuotaMeta","sendAgyBindingCard"],$=["name","config","aibotHandle","pool","bindingStore","globalConfigStore","providerResolver","cachedClaudeRateLimitState","cachedProviderQuota","cachedProviderQuotaSampledAtMs"];function G(e,i){return String(i??"").trim().toLowerCase()===_.approval?_.approval:_.fullAuto}function J(e,i,t,a){const r=Array.isArray(a?.options)?a.options:[];if(r.length===0)return;const l=e.bindingStore.get(i)?.cwd??"",u={};if(t==="model"){u.available_models=r.map(d=>({id:d.id,displayName:d.label}));const c=r.find(d=>d.current);c&&(u.model_id=c.id)}else if(t==="mode"){u.available_modes=r.map(d=>({id:d.id,displayName:d.label}));const c=r.find(d=>d.current);c&&(u.mode_id=c.id)}else u[`${t}_options`]=r;e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l,meta:u})}function A(e){return e.config.adapterType??"acp"}function q(e,i){return m(e,A(e),i,"model")}function V(e,i){return m(e,A(e),i,"mode")}function W(e,i){return m(e,"cursor",i,"mode")}function j(e,i){return m(e,"claude",i,"effort")}function K(e,i){return m(e,"claude",i,"mode")}function X(e,i){return e.normalizeClaudeModeId(e.resolveClaudeSessionModeId(i))}function Y(e,i){const t=e.pool.getSlot(i);if(t?.adapter instanceof I)return t.adapter.getToolbarMeta(i);const a=e.bindingStore.getModelId(i)??"auto",r=e.resolveCursorSessionModeId(i)??"full_auto";return{model_id:a,mode_id:r,currentModelId:a,currentModeId:r,available_models:[],available_modes:Q.map(n=>({...n}))}}function C(e){return!e?.agyConversationId}function Z(e,i,t){const a=e.bindingStore.get(i);if(!a)return;const r=b(e.config.agent.command),n=r.length>0?r[0].id:"";let l=p(e.resolveSessionModelId(i)||"",r)||n;r.length>0&&!r.some(c=>c.id===l)&&(l=n);const u=t??S(e.config.agent.command);return{model_id:l,currentModelId:l,model_switchable:C(a),available_models:r.map(c=>({id:c.id,displayName:c.displayName})),...e.buildAgyQuotaMeta(u)}}function h(e,i){const t={rate_limits:null,extra_limits:null};return i.rateLimits&&(t.rate_limits={primary:i.rateLimits.primary,secondary:i.rateLimits.secondary,sampledAt:i.sampledAt??Date.now()},i.rateLimits.extras&&i.rateLimits.extras.length>0&&(t.extra_limits=i.rateLimits.extras)),{...t,...i.plan!==void 0&&{plan:i.plan},...i.quota_exhausted!==void 0&&{quota_exhausted:i.quota_exhausted},...i.quota_reset_at!==void 0&&{quota_reset_at:i.quota_reset_at},...i.available_credits!==void 0&&{available_credits:i.available_credits}}}function ee(e,i,t,a){const r=a??e.buildAgyToolbarMeta(i);return e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:t,...r?{meta:r}:{}}),r}async function ie(e,i,t=!1){const[a]=await Promise.all([y(e.config.agent.command,t),P(e.config.agent.command)]),r=e.bindingStore.get(i);return r?.cwd&&e.sendAgyBindingCard(i,r.cwd,e.buildAgyToolbarMeta(i,a)),a}async function re(e,i,t){const a=i.params??{},r=b(e.config.agent.command),n=p(String(a.model_id??a.modelId??""),r);if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!n){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const l=e.bindingStore.get(t);if(!l?.cwd){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:R.bindingMissing,error_msg:"session binding was not found"});return}if(!C(l)){const c=p(e.resolveSessionModelId(t)||l.modelId||"",r)||l.modelId||"";if(n!==c){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_locked",error_msg:"\u5F53\u524D\u4F1A\u8BDD\u5DF2\u5F00\u59CB\uFF0Cagy \u6A21\u578B\u4E0D\u53EF\u4E2D\u9014\u5207\u6362\uFF1B\u8BF7\u65B0\u5F00\u8BDD\u9898\u540E\u518D\u9009\u6A21\u578B"}),e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t));return}}l.modelId!==n&&(e.bindingStore.setModelId(t,n),e.globalConfigStore?.set(e.name,{modelId:n}));const u=await y(e.config.agent.command,!0).catch(()=>S(e.config.agent.command));e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t,u)),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"model_set",model_id:n,binding:{cwd:l.cwd,model_id:n}}})}function te(e,i){if(!e.bindingStore.get(i))return;const a=L(e.config.claudeConfigPaths),r=a.length>0?a[0].id:"";let n=e.resolveSessionModelId(i)||r;a.length>0&&!a.some(o=>o.id===n)&&(n=r);const l=e.currentClaudeModeId(i);let u;try{const o=e.providerResolver?e.providerResolver():e.config.agent.provider;u=T(o?.effort)}catch{}const c=e.resolveClaudeSessionEffort(i)??u??"auto",d={model_id:n,mode_id:l,currentModelId:n,currentModeId:l,available_efforts:[...w],effort:c,reasoning_effort:c,available_models:a.map(o=>({id:o.id,displayName:o.displayName}))},v=e.pool.getSlot(i),s=v?.adapter instanceof x?v.adapter.getSessionState():null;(s?.rateLimits?.fiveHour||s?.rateLimits?.sevenDay)&&(e.cachedClaudeRateLimitState=s);const f=e.isGrixRelayActive(),g=f?null:s??e.getFreshClaudeRateLimitState();if(g){const o=g.rateLimits;o&&(o.fiveHour||o.sevenDay)&&(d.rate_limits={...o.fiveHour?{fiveHour:o.fiveHour}:{},...o.sevenDay?{sevenDay:o.sevenDay}:{},sampledAt:g.sampledAt||Date.now()})}if(f){d.rate_limits=null;const o=e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider==="grix"?e.cachedProviderQuota:null;d.provider_quota=o,(!o||!e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs))&&e.maybeQueryProviderQuota().catch(()=>{})}else d.provider_quota=null;if(s){const o=s.contextWindow;o.usedPercentage!=null&&(d.context_window={usedPercentage:o.usedPercentage,remainingPercentage:o.remainingPercentage})}if(!f&&!d.rate_limits&&e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider!=="grix"){e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)||e.maybeQueryProviderQuota().catch(()=>{});const o=e.providerQuotaToRateLimits(e.cachedProviderQuota);o&&(d.rate_limits=o),M.info(e.name,`[toolbar-meta] provider quota fallback: hasCached=${!!e.cachedProviderQuota} fromProvider=${JSON.stringify(o)}`)}return d.rate_limits&&M.info(e.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(d.rate_limits)}`),d}export{$ as TOOLBAR_META_HOST_FIELDS,U as TOOLBAR_META_HOST_METHODS,h as buildAgyQuotaMeta,Z as buildAgyToolbarMeta,te as buildClaudeToolbarMeta,Y as buildCursorToolbarMeta,X as currentClaudeModeId,re as handleAgySetModel,J as handleExecCommandOptions,C as isAgyModelSwitchable,G as normalizeClaudeModeId,ie as refreshAndPushAgyQuota,j as resolveClaudeSessionEffort,K as resolveClaudeSessionModeId,W as resolveCursorSessionModeId,V as resolveSessionModeId,q as resolveSessionModelId,ee as sendAgyBindingCard};
1
+ import{ClaudeAdapter as x}from"../adapter/claude/index.js";import{getCachedModels as L}from"../adapter/claude/model-list.js";import{SESSION_CONTROL_ERROR_CODES as R,SESSION_MODE_IDS as _}from"../adapter/claude/protocol-contract.js";import{CursorAdapter as I,CURSOR_MODE_OPTIONS as Q}from"../adapter/cursor/index.js";import{getCachedAgyModels as b,primeAgyModels as P,resolveAgyToolbarModelId as p}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as S,refreshAgyQuotaInfo as y}from"../adapter/agy/quota.js";import{normalizeClaudeEffort as T,CLAUDE_EFFORT_LEVELS as w}from"../core/config/claude-direct-env.js";import{resolveToolbarSelection as m}from"./toolbar-selection.js";import{log as M}from"../core/log/index.js";const U=["isRateLimitsCacheFresh","isGrixRelayActive","getFreshClaudeRateLimitState","maybeQueryProviderQuota","providerQuotaToRateLimits","normalizeClaudeModeId","resolveSessionModelId","resolveCursorSessionModeId","resolveClaudeSessionEffort","resolveClaudeSessionModeId","currentClaudeModeId","buildAgyToolbarMeta","buildAgyQuotaMeta","sendAgyBindingCard"],$=["name","config","aibotHandle","pool","bindingStore","globalConfigStore","providerResolver","cachedClaudeRateLimitState","cachedProviderQuota","cachedProviderQuotaSampledAtMs"];function G(e,i){return String(i??"").trim().toLowerCase()===_.approval?_.approval:_.fullAuto}function J(e,i,t,d){const r=Array.isArray(d?.options)?d.options:[];if(r.length===0)return;const l=e.bindingStore.get(i)?.cwd??"",u={};if(t==="model"){u.available_models=r.map(a=>({id:a.id,displayName:a.label}));const c=r.find(a=>a.current);c&&(u.model_id=c.id)}else if(t==="mode"){u.available_modes=r.map(a=>({id:a.id,displayName:a.label}));const c=r.find(a=>a.current);c&&(u.mode_id=c.id)}else u[`${t}_options`]=r;e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l,meta:u})}function A(e){return e.config.adapterType??"acp"}function q(e,i){return m(e,A(e),i,"model")}function V(e,i){return m(e,A(e),i,"mode")}function W(e,i){return m(e,"cursor",i,"mode")}function j(e,i){return m(e,"claude",i,"effort")}function K(e,i){return m(e,"claude",i,"mode")}function X(e,i){return e.normalizeClaudeModeId(e.resolveClaudeSessionModeId(i))}function Y(e,i){const t=e.pool.getSlot(i);if(t?.adapter instanceof I)return t.adapter.getToolbarMeta(i);const d=e.bindingStore.getModelId(i)??"auto",r=e.resolveCursorSessionModeId(i)??"full_auto";return{model_id:d,mode_id:r,currentModelId:d,currentModeId:r,available_models:[],available_modes:Q.map(n=>({...n}))}}function C(e){return!e?.agyConversationId}function Z(e,i,t){const d=e.bindingStore.get(i);if(!d)return;const r=b(e.config.agent.command),n=r.length>0?r[0].id:"";let l=p(e.resolveSessionModelId(i)||"",r)||n;r.length>0&&!r.some(c=>c.id===l)&&(l=n);const u=t??S(e.config.agent.command);return{model_id:l,currentModelId:l,model_switchable:C(d),available_models:r.map(c=>({id:c.id,displayName:c.displayName})),...e.buildAgyQuotaMeta(u)}}function h(e,i){const t={rate_limits:null,extra_limits:null};return i.rateLimits&&(t.rate_limits={primary:i.rateLimits.primary,secondary:i.rateLimits.secondary,sampledAt:i.sampledAt??Date.now()},i.rateLimits.extras&&i.rateLimits.extras.length>0&&(t.extra_limits=i.rateLimits.extras)),{...t,...i.plan!==void 0&&{plan:i.plan},...i.quota_exhausted!==void 0&&{quota_exhausted:i.quota_exhausted},...i.quota_reset_at!==void 0&&{quota_reset_at:i.quota_reset_at},...i.available_credits!==void 0&&{available_credits:i.available_credits}}}function ee(e,i,t,d){const r=d??e.buildAgyToolbarMeta(i);return e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:t,...r?{meta:r}:{}}),r}async function ie(e,i,t=!1){const[d]=await Promise.all([y(e.config.agent.command,t),P(e.config.agent.command)]),r=e.bindingStore.get(i);return r?.cwd&&e.sendAgyBindingCard(i,r.cwd,e.buildAgyToolbarMeta(i,d)),d}async function re(e,i,t){const d=i.params??{},r=b(e.config.agent.command),n=p(String(d.model_id??d.modelId??""),r);if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!n){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const l=e.bindingStore.get(t);if(!l?.cwd){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:R.bindingMissing,error_msg:"session binding was not found"});return}if(!C(l)){const c=p(e.resolveSessionModelId(t)||l.modelId||"",r)||l.modelId||"";if(n!==c){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_locked",error_msg:"\u5F53\u524D\u4F1A\u8BDD\u5DF2\u5F00\u59CB\uFF0Cagy \u6A21\u578B\u4E0D\u53EF\u4E2D\u9014\u5207\u6362\uFF1B\u8BF7\u65B0\u5F00\u8BDD\u9898\u540E\u518D\u9009\u6A21\u578B"}),e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t));return}}l.modelId!==n&&(e.bindingStore.setModelId(t,n),e.globalConfigStore?.set(e.name,{modelId:n}));const u=await y(e.config.agent.command,!0).catch(()=>S(e.config.agent.command));e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t,u)),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"model_set",model_id:n,binding:{cwd:l.cwd,model_id:n}}})}function oe(e,i){if(!e.bindingStore.get(i))return;const d=L(e.config.claudeConfigPaths),r=d.length>0?d[0].id:"";let n=e.resolveSessionModelId(i)||r;d.length>0&&!d.some(o=>o.id===n)&&(n=r);const l=e.currentClaudeModeId(i);let u;try{const o=e.providerResolver?e.providerResolver():e.config.agent.provider;u=T(o?.effort)}catch{}const c=e.resolveClaudeSessionEffort(i)??u??"auto",a={model_id:n,mode_id:l,currentModelId:n,currentModeId:l,available_efforts:[...w],effort:c,reasoning_effort:c,available_models:d.map(o=>({id:o.id,displayName:o.displayName}))},v=e.pool.getSlot(i),s=v?.adapter instanceof x?v.adapter.getSessionState():null;(s?.rateLimits?.fiveHour||s?.rateLimits?.sevenDay||(s?.rateLimits?.modelScoped?.length??0)>0)&&(e.cachedClaudeRateLimitState=s);const f=e.isGrixRelayActive(),g=f?null:s??e.getFreshClaudeRateLimitState();if(g){const o=g.rateLimits;o&&(o.fiveHour||o.sevenDay||(o.modelScoped?.length??0)>0)&&(a.rate_limits={...o.fiveHour?{fiveHour:o.fiveHour}:{},...o.sevenDay?{sevenDay:o.sevenDay}:{},...o.modelScoped&&o.modelScoped.length>0?{modelScoped:o.modelScoped}:{},sampledAt:g.sampledAt||Date.now()})}if(f){a.rate_limits=null;const o=e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider==="grix"?e.cachedProviderQuota:null;a.provider_quota=o,(!o||!e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs))&&e.maybeQueryProviderQuota().catch(()=>{})}else a.provider_quota=null;if(s){const o=s.contextWindow;o.usedPercentage!=null&&(a.context_window={usedPercentage:o.usedPercentage,remainingPercentage:o.remainingPercentage})}if(!f&&!a.rate_limits&&e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider!=="grix"){e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)||e.maybeQueryProviderQuota().catch(()=>{});const o=e.providerQuotaToRateLimits(e.cachedProviderQuota);o&&(a.rate_limits=o),M.info(e.name,`[toolbar-meta] provider quota fallback: hasCached=${!!e.cachedProviderQuota} fromProvider=${JSON.stringify(o)}`)}return a.rate_limits&&M.info(e.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(a.rate_limits)}`),a}export{$ as TOOLBAR_META_HOST_FIELDS,U as TOOLBAR_META_HOST_METHODS,h as buildAgyQuotaMeta,Z as buildAgyToolbarMeta,oe as buildClaudeToolbarMeta,Y as buildCursorToolbarMeta,X as currentClaudeModeId,re as handleAgySetModel,J as handleExecCommandOptions,C as isAgyModelSwitchable,G as normalizeClaudeModeId,ie as refreshAndPushAgyQuota,j as resolveClaudeSessionEffort,K as resolveClaudeSessionModeId,W as resolveCursorSessionModeId,V as resolveSessionModeId,q as resolveSessionModelId,ee as sendAgyBindingCard};
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +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 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
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1 +1 @@
1
- function e(s,n){return{command:`npm install -g ${s}`,mode:"npm",npmPackage:s,timeoutMs:n?.timeoutMs??12e4,prerequisites:["node","npm",...n?.extraPrerequisites??[]],minNodeVersion:n?.minNodeVersion}}function i(s,n){return{command:s,mode:"shell",timeoutMs:n?.timeoutMs??12e4,prerequisites:n?.prerequisites}}function a(s,n,o){return{command:s,mode:"exec",execArgs:n,timeoutMs:o?.timeoutMs??6e4,prerequisites:o?.prerequisites,skipVerification:o?.skipVerification}}const l={claude:{cliBinary:"claude",macos:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"}),linux:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"}),windows:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"})},codex:{cliBinary:"codex",macos:e("@openai/codex"),linux:e("@openai/codex"),windows:e("@openai/codex")},qwen:{cliBinary:"qwen",macos:{...i("curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.sh | bash",{prerequisites:["curl"]}),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})},linux:{...i("curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.sh | bash",{prerequisites:["curl"]}),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})},windows:{...i(`powershell -Command "Invoke-WebRequest 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.bat' -OutFile (Join-Path $env:TEMP 'install-qwen.bat'); & (Join-Path $env:TEMP 'install-qwen.bat')"`),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})}},cursor:{cliBinary:"agent",macos:i("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),linux:i("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),windows:i(`powershell -ExecutionPolicy ByPass -c "irm 'https://cursor.com/install?win32=true' | iex"`)},copilot:{cliBinary:"copilot",macos:e("@github/copilot",{minNodeVersion:"22.0"}),linux:e("@github/copilot",{minNodeVersion:"22.0"}),windows:e("@github/copilot",{minNodeVersion:"22.0"})},kiro:{cliBinary:"kiro-cli",macos:i("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://cli.kiro.dev/install.ps1 | iex"',{timeoutMs:3e5})},qodercli:{cliBinary:"qodercli",macos:{...i("curl -fsSL https://qoder.com/install | bash",{prerequisites:["curl"]}),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})},linux:{...i("curl -fsSL https://qoder.com/install | bash",{prerequisites:["curl"]}),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})},windows:{...i('powershell -Command "irm https://qoder.com/install.ps1 | iex"'),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})}},qoderclicn:{cliBinary:"qoderclicn",macos:{...i("curl -fsSL https://static.qoder.com.cn/qoder-cli-cn/install.sh | bash",{prerequisites:["curl"]}),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})},linux:{...i("curl -fsSL https://static.qoder.com.cn/qoder-cli-cn/install.sh | bash",{prerequisites:["curl"]}),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})},windows:{...i('powershell -Command "irm https://static.qoder.com.cn/qoder-cli-cn/install.ps1 | iex"'),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})}},mcode:{cliBinary:"mcode",macos:e("@minimax-ai/code"),linux:e("@minimax-ai/code"),windows:e("@minimax-ai/code")},dim:{cliBinary:"dim",macos:e("dimcode"),linux:e("dimcode"),windows:e("dimcode")},kimi:{cliBinary:"kimi",macos:i("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),linux:i("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://code.kimi.com/install.ps1 | iex"',{timeoutMs:3e5})},grok:{cliBinary:"grok",macos:i("brew install --cask grok-build",{prerequisites:["brew"],timeoutMs:18e4}),linux:i("curl -fsSL https://x.ai/cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://x.ai/cli/install.ps1 | iex"')},qwenpaw:{cliBinary:"qwenpaw",macos:i('export PATH="$HOME/.local/bin:$PATH" && uv tool install qwenpaw',{prerequisites:["uv"],timeoutMs:18e4}),linux:i('export PATH="$HOME/.local/bin:$PATH" && uv tool install qwenpaw',{prerequisites:["uv"],timeoutMs:18e4}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://qwenpaw.agentscope.io/install.ps1 | iex"',{timeoutMs:3e5})},zeroclaw:{cliBinary:"zeroclaw",macos:i('. "$HOME/.cargo/env" 2>/dev/null; cargo install zeroclaw',{prerequisites:["cargo"],timeoutMs:6e5}),linux:i('. "$HOME/.cargo/env" 2>/dev/null; cargo install zeroclaw',{prerequisites:["cargo"],timeoutMs:6e5}),windows:i(`powershell -ExecutionPolicy ByPass -c "$env:Path = (Join-Path $env:USERPROFILE '.cargo\\bin') + ';' + $env:Path; cargo install zeroclaw"`,{prerequisites:["cargo"],timeoutMs:6e5})},openclaw:{cliBinary:"openclaw",macos:e("openclaw@latest",{minNodeVersion:"22.0"}),linux:e("openclaw@latest",{minNodeVersion:"22.0"}),windows:e("openclaw@latest",{minNodeVersion:"22.0"})},reasonix:{cliBinary:"reasonix",macos:e("reasonix"),linux:e("reasonix"),windows:e("reasonix")},pi:{cliBinary:"pi",macos:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"}),linux:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"}),windows:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"})},agy:{cliBinary:"agy",macos:i("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://antigravity.google/cli/install.ps1 | iex"')},hermes:{cliBinary:"hermes",macos:i("curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:9e5}),linux:i("curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:9e5}),windows:i(`powershell -ExecutionPolicy ByPass -c "$p = Join-Path $env:TEMP 'hermes-install.ps1'; Invoke-WebRequest 'https://hermes-agent.nousresearch.com/install.ps1' -OutFile $p -UseBasicParsing; & $p -NonInteractive"`,{timeoutMs:9e5})},codewhale:{cliBinary:"codewhale",macos:e("codewhale"),linux:e("codewhale"),windows:e("codewhale")},deepseek:{cliBinary:"dsh",macos:e("@deepseek-ai/dsh"),linux:e("@deepseek-ai/dsh"),windows:e("@deepseek-ai/dsh")},traecli:{cliBinary:"traecli",macos:i("curl -fsSL https://trae.cn/trae-cli/install.sh | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://trae.cn/trae-cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://trae.cn/trae-cli/install.ps1 | iex"')},opencode:{cliBinary:"opencode",macos:{...i("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},linux:{...i("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},windows:e("opencode-ai")},omp:{cliBinary:"omp",macos:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]}),linux:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]}),windows:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]})},codebuddy:{cliBinary:"codebuddy",macos:e("@tencent-ai/codebuddy-code"),linux:e("@tencent-ai/codebuddy-code"),windows:e("@tencent-ai/codebuddy-code")},deveco:{cliBinary:"deveco",macos:e("@deveco/deveco-code"),linux:e("@deveco/deveco-code"),windows:e("@deveco/deveco-code")}};function u(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"linux"}}function c(s){return s.mode==="exec"&&s.execArgs&&s.execArgs.length>0?[s.command,...s.execArgs].join(" "):s.command}function d(s,n){const o=l[s];return o?o[n]:null}function m(s){return l[s]?.cliBinary??null}function t(s,n){const o=l[s];if(!o)return null;const r=o[n];return{agentType:s,cliBinary:o.cliBinary,supported:r!==null,installCommand:r?c(r):null,prerequisites:r?.prerequisites}}function p(s){return Object.keys(l).sort().map(n=>t(n,s)).filter(n=>n!==null)}function h(s){return s in l}export{u as detectPlatformOS,c as formatInstallCommand,t as getAgentInstallInfo,p as getAllAgentInstallInfo,m as getCliBinary,d as getInstallCommand,h as isKnownAgent};
1
+ function e(s,o){return{command:`npm install -g ${s}`,mode:"npm",npmPackage:s,timeoutMs:o?.timeoutMs??12e4,prerequisites:["node","npm",...o?.extraPrerequisites??[]],minNodeVersion:o?.minNodeVersion}}function i(s,o){return{command:s,mode:"shell",timeoutMs:o?.timeoutMs??12e4,prerequisites:o?.prerequisites}}function a(s,o,n){return{command:s,mode:"exec",execArgs:o,timeoutMs:n?.timeoutMs??6e4,prerequisites:n?.prerequisites,skipVerification:n?.skipVerification}}const l={claude:{cliBinary:"claude",macos:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"}),linux:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"}),windows:e("@anthropic-ai/claude-code",{minNodeVersion:"18.0"})},codex:{cliBinary:"codex",macos:e("@openai/codex"),linux:e("@openai/codex"),windows:e("@openai/codex")},qwen:{cliBinary:"qwen",macos:{...i("curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.sh | bash",{prerequisites:["curl"]}),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})},linux:{...i("curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.sh | bash",{prerequisites:["curl"]}),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})},windows:{...i(`powershell -Command "Invoke-WebRequest 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen.bat' -OutFile (Join-Path $env:TEMP 'install-qwen.bat'); & (Join-Path $env:TEMP 'install-qwen.bat')"`),fallback:e("@qwen-code/qwen-code@latest",{minNodeVersion:"22.0"})}},cursor:{cliBinary:"agent",macos:i("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),linux:i("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),windows:i(`powershell -ExecutionPolicy ByPass -c "irm 'https://cursor.com/install?win32=true' | iex"`)},copilot:{cliBinary:"copilot",macos:e("@github/copilot",{minNodeVersion:"22.0"}),linux:e("@github/copilot",{minNodeVersion:"22.0"}),windows:e("@github/copilot",{minNodeVersion:"22.0"})},kiro:{cliBinary:"kiro-cli",macos:i("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://cli.kiro.dev/install.ps1 | iex"',{timeoutMs:3e5})},qodercli:{cliBinary:"qodercli",macos:{...i("curl -fsSL https://qoder.com/install | bash",{prerequisites:["curl"]}),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})},linux:{...i("curl -fsSL https://qoder.com/install | bash",{prerequisites:["curl"]}),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})},windows:{...i('powershell -Command "irm https://qoder.com/install.ps1 | iex"'),fallback:e("@qoder-ai/qodercli",{minNodeVersion:"20.0"})}},qoderclicn:{cliBinary:"qoderclicn",macos:{...i("curl -fsSL https://static.qoder.com.cn/qoder-cli-cn/install.sh | bash",{prerequisites:["curl"]}),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})},linux:{...i("curl -fsSL https://static.qoder.com.cn/qoder-cli-cn/install.sh | bash",{prerequisites:["curl"]}),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})},windows:{...i('powershell -Command "irm https://static.qoder.com.cn/qoder-cli-cn/install.ps1 | iex"'),fallback:e("@qodercn-ai/qoderclicn",{minNodeVersion:"20.0"})}},mcode:{cliBinary:"mcode",macos:e("@minimax-ai/code"),linux:e("@minimax-ai/code"),windows:e("@minimax-ai/code")},dim:{cliBinary:"dim",macos:e("dimcode"),linux:e("dimcode"),windows:e("dimcode")},kimi:{cliBinary:"kimi",macos:i("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),linux:i("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://code.kimi.com/install.ps1 | iex"',{timeoutMs:3e5})},grok:{cliBinary:"grok",macos:i("brew install --cask grok-build",{prerequisites:["brew"],timeoutMs:18e4}),linux:i("curl -fsSL https://x.ai/cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://x.ai/cli/install.ps1 | iex"')},qwenpaw:{cliBinary:"qwenpaw",macos:i('export PATH="$HOME/.local/bin:$PATH" && uv tool install qwenpaw',{prerequisites:["uv"],timeoutMs:18e4}),linux:i('export PATH="$HOME/.local/bin:$PATH" && uv tool install qwenpaw',{prerequisites:["uv"],timeoutMs:18e4}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://qwenpaw.agentscope.io/install.ps1 | iex"',{timeoutMs:3e5})},zeroclaw:{cliBinary:"zeroclaw",macos:i('. "$HOME/.cargo/env" 2>/dev/null; cargo install zeroclaw',{prerequisites:["cargo"],timeoutMs:6e5}),linux:i('. "$HOME/.cargo/env" 2>/dev/null; cargo install zeroclaw',{prerequisites:["cargo"],timeoutMs:6e5}),windows:i(`powershell -ExecutionPolicy ByPass -c "$env:Path = (Join-Path $env:USERPROFILE '.cargo\\bin') + ';' + $env:Path; cargo install zeroclaw"`,{prerequisites:["cargo"],timeoutMs:6e5})},openclaw:{cliBinary:"openclaw",macos:e("openclaw@latest",{minNodeVersion:"22.0"}),linux:e("openclaw@latest",{minNodeVersion:"22.0"}),windows:e("openclaw@latest",{minNodeVersion:"22.0"})},reasonix:{cliBinary:"reasonix",macos:e("reasonix"),linux:e("reasonix"),windows:e("reasonix")},pi:{cliBinary:"pi",macos:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"}),linux:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"}),windows:e("@earendil-works/pi-coding-agent",{minNodeVersion:"22.19"})},agy:{cliBinary:"agy",macos:i("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://antigravity.google/cli/install.ps1 | iex"')},hermes:{cliBinary:"hermes",macos:i("curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:9e5}),linux:i("curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:9e5}),windows:i(`powershell -ExecutionPolicy ByPass -c "$p = Join-Path $env:TEMP 'hermes-install.ps1'; Invoke-WebRequest 'https://hermes-agent.nousresearch.com/install.ps1' -OutFile $p -UseBasicParsing; & $p -NonInteractive"`,{timeoutMs:9e5})},codewhale:{cliBinary:"codewhale",macos:e("codewhale"),linux:e("codewhale"),windows:e("codewhale")},deepseek:{cliBinary:"dsh",macos:e("@deepseek-ai/dsh@latest",{timeoutMs:6e5}),linux:e("@deepseek-ai/dsh@latest",{timeoutMs:6e5}),windows:e("@deepseek-ai/dsh@latest",{timeoutMs:6e5})},traecli:{cliBinary:"traecli",macos:i("curl -fsSL https://trae.cn/trae-cli/install.sh | bash",{prerequisites:["curl"]}),linux:i("curl -fsSL https://trae.cn/trae-cli/install.sh | bash",{prerequisites:["curl"]}),windows:i('powershell -ExecutionPolicy ByPass -c "irm https://trae.cn/trae-cli/install.ps1 | iex"')},opencode:{cliBinary:"opencode",macos:{...i("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},linux:{...i("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},windows:e("opencode-ai")},omp:{cliBinary:"omp",macos:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]}),linux:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]}),windows:e("@oh-my-pi/pi-coding-agent",{minNodeVersion:"18.0",extraPrerequisites:["bun"]})},codebuddy:{cliBinary:"codebuddy",macos:e("@tencent-ai/codebuddy-code"),linux:e("@tencent-ai/codebuddy-code"),windows:e("@tencent-ai/codebuddy-code")},deveco:{cliBinary:"deveco",macos:e("@deveco/deveco-code"),linux:e("@deveco/deveco-code"),windows:e("@deveco/deveco-code")}};function u(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"linux"}}function r(s){return s.mode==="exec"&&s.execArgs&&s.execArgs.length>0?[s.command,...s.execArgs].join(" "):s.command}function d(s,o){const n=l[s];return n?n[o]:null}function m(s){return l[s]?.cliBinary??null}function c(s,o){const n=l[s];if(!n)return null;const t=n[o];return{agentType:s,cliBinary:n.cliBinary,supported:t!==null,installCommand:t?r(t):null,prerequisites:t?.prerequisites}}function p(s){return Object.keys(l).sort().map(o=>c(o,s)).filter(o=>o!==null)}function h(s){return s in l}export{u as detectPlatformOS,r as formatInstallCommand,c as getAgentInstallInfo,p as getAllAgentInstallInfo,m as getCliBinary,d as getInstallCommand,h as isKnownAgent};
@@ -0,0 +1 @@
1
+ import{homedir as i}from"node:os";function e(){try{return i().trim()||null}catch{return null}}function s(r=process.env){if(!r.HOME?.trim()){const t=e();t&&(r.HOME=t)}if(process.platform==="win32"&&!r.USERPROFILE?.trim()){const t=e();t&&(r.USERPROFILE=t)}}function m(r=process.env){if(r.HOME?.trim())return r;const t=e();if(!t)return r;const o={...r,HOME:t};return process.platform==="win32"&&!o.USERPROFILE?.trim()&&(o.USERPROFILE=t),o}export{s as ensureUserHomeEnv,m as withUserHomeEnv};
package/dist/grix.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import b from"node:path";import{writeFileSync as se}from"node:fs";import{Manager as $e}from"./manager.js";import{ensureGrixDirs as Le,initLogger as Ue,getLoggerStatus as He,log as i,installProcessLogRotation as Oe,setConsoleOutput as ce}from"./core/log/index.js";import{HealthServer as Fe,bindPortOrFail as le}from"./core/runtime/index.js";import{writePidFile as Me,removePidFile as T,readDaemonPid as de}from"./core/runtime/index.js";import{killOrphanedClaudeProcesses as Ne}from"./core/runtime/index.js";import{resolveRuntimePaths as Y}from"./core/config/index.js";import{supportsNonMitmRelayConfig as Ge}from"./core/config/provider-env.js";import{ServiceManager as pe}from"./service/service-manager.js";import{RESTART_EXIT_CODE as Be,UNHEALTHY_EXIT_CODE as je,markManagedStop as ge,resolveLauncherStore as q,writeCrashNote as We}from"./core/upgrade/version-store.js";import{migrateWindowsWrapper as J}from"./service/windows-wrapper-migration.js";const Ke=300*1e3;import{killProcessesByCommandLine as Xe,isWindowsElevated as Ve,shouldSweepWindowsWrappers as Ye,getProcessCommandLine as qe}from"./service/process-control.js";import{buildServiceID as Je}from"./service/service-paths.js";import{isInsideManagedDaemonTree as ze}from"./service/platform-adapter.js";import{acquireDaemonLock as Qe,createHealthzHolderProbe as Ze,DaemonAlreadyServingError as et,findLiveLockHolder as tt,isLockHolderSameProcess as rt,readDaemonLock as z,releaseDaemonLock as M}from"./runtime/daemon-lock.js";import{writeDaemonStatus as B,removeDaemonStatus as nt}from"./runtime/service-state.js";import{readRecentDuplicateDaemonRecord as ot,recordDuplicateDaemon as at}from"./runtime/duplicate-daemon.js";import{createStartupPhaseTimer as it}from"./runtime/startup-phases.js";import{RemoteAdminSettingsStore as st}from"./core/config/remote-admin-settings.js";import{AdminServer as ct,generateToken as lt,writeTokenFile as dt}from"./core/admin/index.js";import{initSentry as pt,whenSentryReady as Q,closeSentry as j,reportFatal as Z,isWindowsWmicProbeError as gt}from"./core/observability/sentry.js";import{initProxyManager as mt,getProxyManager as h,relayHostsForClientType as me,RelayStateStore as ut,SecretStore as ft}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as ue,switchAgentRelayMode as ee,reconcileRelayStates as fe}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as he,RelayCredentialError as ye}from"./core/proxy/relay-credential.js";import{RelayFetchError as we,RelayToggleCoordinator as ht}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as yt,clearHermesProfileRelay as wt,discoverHermesProfiles as St}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as Rt,enableRelayCredential as Et,RelayRouteError as Se}from"./core/proxy/relay-credential-router.js";import{upgradeStatusSnapshot as Dt}from"./core/upgrade/npm-upgrader.js";import{resolveClientVersion as At}from"./core/util/client-version.js";import{parseCliArgs as vt}from"./core/util/cli-args.js";const{command:k,flags:E,unknownFlags:te}=vt(process.argv.slice(2));if(te.length>0&&(console.error(`Unknown option${te.length>1?"s":""}: ${te.map(t=>`--${t}`).join(", ")}
2
+ import b from"node:path";import{writeFileSync as se}from"node:fs";import{Manager as $e}from"./manager.js";import{ensureGrixDirs as Le,initLogger as Ue,getLoggerStatus as He,log as i,installProcessLogRotation as Oe,setConsoleOutput as ce}from"./core/log/index.js";import{HealthServer as Fe,bindPortOrFail as le}from"./core/runtime/index.js";import{writePidFile as Me,removePidFile as T,readDaemonPid as de}from"./core/runtime/index.js";import{killOrphanedClaudeProcesses as Ne}from"./core/runtime/index.js";import{resolveRuntimePaths as Y}from"./core/config/index.js";import{supportsNonMitmRelayConfig as Ge}from"./core/config/provider-env.js";import{ServiceManager as pe}from"./service/service-manager.js";import{RESTART_EXIT_CODE as Be,UNHEALTHY_EXIT_CODE as je,markManagedStop as ge,resolveLauncherStore as q,writeCrashNote as We}from"./core/upgrade/version-store.js";import{migrateWindowsWrapper as J}from"./service/windows-wrapper-migration.js";const Ke=300*1e3;import{killProcessesByCommandLine as Xe,isWindowsElevated as Ve,shouldSweepWindowsWrappers as Ye,getProcessCommandLine as qe}from"./service/process-control.js";import{buildServiceID as Je}from"./service/service-paths.js";import{isInsideManagedDaemonTree as ze}from"./service/platform-adapter.js";import{acquireDaemonLock as Qe,createHealthzHolderProbe as Ze,DaemonAlreadyServingError as et,findLiveLockHolder as tt,isLockHolderSameProcess as rt,readDaemonLock as z,releaseDaemonLock as M}from"./runtime/daemon-lock.js";import{writeDaemonStatus as B,removeDaemonStatus as nt}from"./runtime/service-state.js";import{readRecentDuplicateDaemonRecord as ot,recordDuplicateDaemon as at}from"./runtime/duplicate-daemon.js";import{createStartupPhaseTimer as it}from"./runtime/startup-phases.js";import{RemoteAdminSettingsStore as st}from"./core/config/remote-admin-settings.js";import{AdminServer as ct,generateToken as lt,writeTokenFile as dt}from"./core/admin/index.js";import{initSentry as pt,whenSentryReady as Q,closeSentry as j,reportFatal as Z,isWindowsWmicProbeError as gt}from"./core/observability/sentry.js";import{initProxyManager as mt,getProxyManager as h,relayHostsForClientType as me,RelayStateStore as ut,SecretStore as ft}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as ue,switchAgentRelayMode as ee,reconcileRelayStates as fe}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as he,RelayCredentialError as ye}from"./core/proxy/relay-credential.js";import{RelayFetchError as we,RelayToggleCoordinator as ht}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as yt,clearHermesProfileRelay as wt,discoverHermesProfiles as St}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as Rt,enableRelayCredential as Et,RelayRouteError as Se}from"./core/proxy/relay-credential-router.js";import{upgradeStatusSnapshot as Dt}from"./core/upgrade/npm-upgrader.js";import{resolveClientVersion as At}from"./core/util/client-version.js";import{parseCliArgs as vt}from"./core/util/cli-args.js";import{ensureUserHomeEnv as bt}from"./core/util/home-env.js";bt();const{command:k,flags:E,unknownFlags:te}=vt(process.argv.slice(2));if(te.length>0&&(console.error(`Unknown option${te.length>1?"s":""}: ${te.map(t=>`--${t}`).join(", ")}
3
3
  Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),E.version&&(console.log(At()),process.exit(0)),E.help&&(console.log(`grix-connector \u2014 Unified AI Agent Bridge
4
4
 
5
5
  Usage: grix-connector <command> [options]
@@ -37,7 +37,7 @@ Examples:
37
37
  `),process.exit(0)),k==="reload"){const t=de();t||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(t,0)}catch{console.error(`reload failed: daemon process ${t} is not running (stale pid file)`),process.exit(1)}{const s=z(Y().daemonLockFile);s&&s.pid===t&&!rt(s)&&(console.error(`reload failed: pid ${t} has been reused by another process (stale pid file)`),process.exit(1))}try{process.kill(t,"SIGHUP"),console.log(JSON.stringify({ok:!0,signaled:t},null,2)),process.exit(0)}catch(s){console.error(`reload failed: ${s instanceof Error?s.message:s}`),process.exit(1)}}const Re="detected connector-managed session; restart delegated to launchd, this process may be terminated by the restart",Ee=["start","stop","restart","status"];if(k&&Ee.includes(k)){process.platform==="win32"&&["start","stop","restart"].includes(k)&&!Ve()&&console.warn(`Warning: Not running as administrator. Task Scheduler registration is skipped;
38
38
  using Startup folder auto-start instead. For full Task Scheduler integration,
39
39
  right-click the terminal and select "Run as administrator".`);const t=Y(),s=E["config-dir"]??(E.profile?b.join(t.configDir,E.profile):void 0),g=b.resolve(process.argv[1]||`${t.rootDir}/dist/grix.js`),f=new pe({cliPath:g,nodePath:process.execPath});try{let l;switch(k){case"start":{const m=await f.healLegacyState({rootDir:t.rootDir});(await f.status({rootDir:t.rootDir})).installed?l=await f.start({rootDir:t.rootDir}):l=await f.install({rootDir:t.rootDir,configDir:s??m.configDir}),m.healed&&(l={...l,legacy_heal:m.reasons})}break;case"stop":l=await f.stop({rootDir:t.rootDir});break;case"restart":if(!(await f.status({rootDir:t.rootDir})).installed)l=await f.install({rootDir:t.rootDir,configDir:s});else{const D=process.platform==="darwin"&&ze();D&&console.warn(Re),l=await f.restart({rootDir:t.rootDir}),D&&(l={...l,mode:"kickstart",note:Re})}break;case"status":l=await f.status({rootDir:t.rootDir});{const m=ot(t.dataDir);m&&(l={...l,duplicate_daemon:m})}break}console.log(JSON.stringify(l,null,2)),process.exit(0)}catch(l){console.error(`${k} failed: ${l instanceof Error?l.message:l}`),process.exit(1)}}else k&&(console.error(`Unknown command: ${k}
40
- Valid commands: ${Ee.join(", ")}`),process.exit(1));const c=Y(),bt=E["config-dir"]??(E.profile?`${c.configDir}/${E.profile}`:void 0),o=new $e({requestGracefulShutdown:t=>{_(t)},onTransactionSettled:()=>{J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).then(t=>{t.handoffStarted&&i.info("main","Wrapper handoff started after the upgrade transaction settled")}).catch(t=>{i.warn("main",`Post-upgrade wrapper migration failed: ${t instanceof Error?t.message:t}`)})}}),N=new Fe,De=lt(),x=new ct(De);let W=!1,$;function K(t,s){const g=q(),f=process.env.GRIX_LAUNCHER_VERSION;if(!g||!f)return;const l=s instanceof Error?s.stack??s.message:String(s);We(g,f,`${t}: ${l}`)}function Ae(t,s){at(c.dataDir,{holder_pid:t.pid,holder_command_line:t.command_line,yielded_pid:process.pid,yielded_command_line:qe(process.pid)}),process.stderr.write(`${s}
41
- `),i.warn("main",s);const g=q();g&&ge(g)}function xt(t){const s=`another grix-connector daemon (pid ${t.pid}) is already serving ${c.rootDir} and answering /healthz; this process yields instead of taking over. A second supervisor is starting duplicate daemons \u2014 check for a leftover wrapper, a duplicate logon task, or a desktop app launching its own copy.`;Ae(t,s),process.exit(0)}function Pt(t,s){const g=`${s.label} \u7AEF\u53E3 ${s.port} \u5DF2\u88AB\u5360\u7528\uFF0C\u4E14 daemon \u9501\u4ECD\u7531\u53E6\u4E00\u4E2A\u5B58\u6D3B\u5B9E\u4F8B (pid ${t.pid}) \u6301\u6709\uFF1A\u672C\u8FDB\u7A0B\u6309\u7BA1\u7406\u6027\u9000\u51FA\u8BA9\u4F4D\uFF0C\u4E0D\u8BA1\u4E3A\u5D29\u6E83\u3002 \u8FD9\u53F0\u673A\u5668\u4E0A\u6709\u7B2C\u4E8C\u4E2A supervisor \u5728\u91CD\u590D\u62C9\u8D77 daemon\u2014\u2014\u68C0\u67E5\u6B8B\u7559\u7684 wrapper\u3001\u91CD\u590D\u7684\u767B\u5F55\u4EFB\u52A1\uFF0C\u6216\u684C\u9762\u7AEF\u53E6\u8D77\u7684\u526F\u672C\u3002`;Ae(t,g),de()===process.pid&&T(),process.exit(0)}async function ve(t){if(t.kind==="in_use"){const g=tt(c.daemonLockFile);g&&(await j(),Pt(g,t))}process.stderr.write(t.message+`
42
- `),i.error("main",t.message.replace(/\n/g," \u2014 ")),K("port_bind",t.message);const s=z(c.daemonLockFile);s?.pid===process.pid&&s.instance_id===$&&await B(c.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:$,updated_at:Date.now(),reason:`port_bind_${t.kind}:${t.label}:${t.port}`}).catch(()=>{}),await j(),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(1)}async function _(t){if(W)return;W=!0,i.info("main",`Received ${t}, shutting down...`),N.markShuttingDown();const s=q();s&&ge(s);const g=t==="upgrade-switch"?Be:t==="launcher-unhealthy"?je:null,f=g??2,l=t==="uncaughtException"||t==="unhandledRejection",m=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(f)},1e4);try{await o.stop(),await h()?.stop().catch(()=>{}),await x.stop(),await N.stop(),await j(),await M(c.daemonLockFile),await nt(c.daemonStatusFile).catch(()=>{}),clearTimeout(m),T(),i.info("main","Shutdown complete"),process.exit(g??(l?2:0))}catch(D){i.error("main",`Shutdown error: ${D}`),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(f)}}async function It(){const t=it();t.lap("boot"),Le(),Ue(),Oe(c.stdoutLogFile,c.stderrLogFile),ce(!1);try{$=(await Qe(c.daemonLockFile,c.rootDir,2,{isHolderServing:Ze(c.dataDir)})).instance_id}catch(e){e instanceof et&&xt(e.holder),console.error(e instanceof Error?e.message:e),process.exit(1)}if(t.lap("lock"),Ye()){const e=Je(c.rootDir,"win32");await Xe(e,{platform:"win32"})}t.lap("sweep"),pt(),Me(),t.lap("pidfile"),i.info("main",`grix-connector starting (PID ${process.pid})`);try{Ne({info:e=>i.info("main",e),warn:e=>i.warn("main",e)})}catch(e){i.warn("main",`orphan Claude cleanup failed: ${e instanceof Error?e.message:String(e)}`)}t.lap("orphan"),await B(c.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:$,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new pe({cliPath:b.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(c.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),t.lap("adopt");const s=await J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null));if(t.lap("migrate"),s?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{W||J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).then(n=>{n.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(n=>{i.warn("main",`Periodic wrapper migration failed: ${n instanceof Error?n.message:n}`)})},Ke).unref();const g=parseInt(E["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await le({label:"health",port:g,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:n=>N.start(n)});e&&await ve(e)}const f=b.join(c.dataDir,"health-port");se(f,String(g),"utf-8"),t.lap("health"),process.on("SIGINT",()=>_("SIGINT")),process.on("SIGTERM",()=>_("SIGTERM")),process.on("SIGHUP",()=>{W||(i.info("main","Received SIGHUP, reloading config..."),o.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let l="",m=0,D;process.on("uncaughtException",e=>{const n=e instanceof Error?e.stack??e.message:String(e);n===l?(m++,(m<=3||m%100===0)&&i.error("main",`Uncaught exception (x${m}): ${n}`)):(m>3&&i.error("main",`Previous exception repeated ${m} times total`),l=n,m=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),D||(D=setTimeout(()=>{m>3&&i.error("main",`Previous exception repeated ${m} times total`),l="",m=0,D=void 0},1e4).unref())),!be(e)&&(Q().then(()=>Z(e,"uncaughtException")),K("uncaughtException",e),_("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!be(e)&&(Q().then(()=>Z(e,"unhandledRejection")),K("unhandledRejection",e),_("unhandledRejection"))});const L=mt(c.dataDir);await L.clearRuntimeState();const P=new ut(b.join(c.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),G=new ft(b.join(c.dataDir,"secrets"));o.setRelaySecretResolver(e=>G.get(e));const U={hasDirectConfig:e=>o.hasDirectRelayConfig(e),clearDirectConfig:(e,n)=>o.setAgentProvider(e,void 0,{deferRestart:n?.deferRestart===!0})},X=()=>({pm:h(),agents:o,direct:U,store:P,secrets:G}),H=L.getRelayAgents();if(H.length>0)try{await L.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${H.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${H.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let O=null;if(h()){const e=async()=>{const r=h();r&&await ue(r,o)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};o.setRelayEnvSettledHandler(()=>{const r=h();r&&fe(r,U,P),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const n=()=>{const r=h(),a=r.getRelayAgents(),p=r.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:o.getAgentsWithStaleRelayEnv(),degradedRelayAgents:p,relayState:P.list(),runtime:r.getRuntimeInfo(),config:r.getConfigSnapshot()}},d=new ht,A={status:()=>n(),setAgentRelay:async(r,a,p)=>{const u=h(),R={info:w=>i.info("main",w),warn:w=>i.warn("main",w)},S=w=>o.getAgentsStatus().find(v=>v.name===w),y=S(r);if(!a){d.cancel(r);const w=await d.runExclusive(r,async()=>{const v=await ee(X(),R,{agentName:r,target:"off"});return{...n(),restarted:v.restarted,busy:v.busy,...v.pending?{pending:v.pending}:{}}});return o.reportRelayStateLocalChange(r),w}if(!y)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});if(!Ge(y.clientType)&&me(y.clientType).length===0)throw Object.assign(new Error(`client type "${y.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const F=await d.runExclusive(r,async()=>{const w=d.epoch(r),v=S(r);if(!v)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});const oe=String(v.agentId??"").trim();if(!oe)throw new ye(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const ae=d.waitCancelled(r,w);let C;try{C=await Promise.race([o.fetchRelayCredential(r,{model:p}),ae.promise.then(()=>{throw new we("relay enable cancelled by a later disable","CANCELLED")})])}finally{ae.dispose()}d.assertCurrent(r,w);const{restarted:Ie,busy:ke,pending:ie}=await he(u,o,S,R,{localName:r,agentId:oe,virtualKey:C.apiKey,anthropicBaseUrl:C.anthropicBaseUrl,openaiBaseUrl:C.openaiBaseUrl,model:p,...C.directRelay!==void 0?{directRelay:C.directRelay}:{}},(_e,Ce,Te)=>o.setAgentProvider(_e,Ce,{deferRestart:Te?.deferRestart===!0}),{store:P,secrets:G,direct:U});if(d.epoch(r)!==w)throw await ee(X(),R,{agentName:r,target:"off"}),new we("relay enable cancelled by a later disable","CANCELLED");return{...n(),restarted:Ie,busy:ke,...ie?{pending:ie}:{}}});return o.reportRelayStateLocalChange(r),F},setAgentRelayCredential:async(r,a)=>{const p=h(),u=o.getAgentsStatus(),{restarted:R,busy:S,pending:y}=await he(p,o,I=>u.find(F=>F.name===I),{info:I=>i.info("main",I),warn:I=>i.warn("main",I)},{localName:r,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(I,F,w)=>o.setAgentProvider(I,F,{deferRestart:w?.deferRestart===!0}),{store:P,secrets:G,direct:U});return o.reportRelayStateLocalChange(r),{...n(),restarted:R,busy:S,...y?{pending:y}:{}}},disableAll:async()=>{const r=h(),a={info:u=>i.info("main",u),warn:u=>i.warn("main",u)},p=new Set([...r.getRelayAgents(),...o.getDirectRelayConfigAgentNames(),...Object.keys(P.list())]);for(const u of p)d.cancel(u);for(const u of p)await d.runExclusive(u,()=>ee(X(),a,{agentName:u,target:"off"})),o.reportRelayStateLocalChange(u);return await ue(r,o),n()},setRoute:async(r,a)=>{const p=a,u=h();return u.setRoute({routeKey:r,targetBaseUrl:p.targetBaseUrl,...p.headers?{headers:p.headers}:{},...p.model?{model:p.model}:{},...p.modelMap?{modelMap:p.modelMap}:{},...p.passthrough?{passthrough:!0}:{},...p.relayOnly?{relayOnly:!0}:{},...p.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await u.persistConfig(),n()},deleteRoute:async r=>{const a=h();a.deleteRoute(r),await a.persistConfig()},setDefaultRoute:async r=>{const a=h();return a.setDefaultRouteKey(r),await a.persistConfig(),n()},setInterceptHosts:async r=>{const a=h();return a.setInterceptHosts(r),await a.persistConfig(),n()}};O=A,x.setProxyHandler(A),o.setRelayStateApplier({getAppliedMode:r=>P.get(r)?.applied,getLocalState:r=>{const a=h();if(a.getRelayAgents().includes(r)){const u=o.getAgentsStatus().find(y=>y.name===r),R=`grix-gateway-${String(u?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(y=>y.routeKey===R)?.model?.trim()||void 0}}const p=o.getAgentProvider(r);return p?.api_key?.trim()?{enabled:!0,model:p.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(r,a,p)=>{const u=o.getAgentsStatus().find(y=>y.name===r),R=String(u?.agentId??"").trim();if(!R)throw new ye(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const S=await A.setAgentRelayCredential(r,{agentId:R,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:p??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:S.restarted===!0,busy:S.busy===!0,...S.pending?{pending:S.pending}:{}}},applyDisable:async r=>{const a=await A.setAgentRelay(r,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}N.setStatusProvider(()=>o.getAgentsStatus()),N.setMetaProvider(()=>{const e=o.getAgentsStatus(),n=He();return{ws:{connected:e.filter(d=>d.wsConnected===!0).length,total:e.length},upgrade:Dt(),log:{dir:n.logDir,file:n.logFile,primary_dir:n.primaryLogDir,degraded:n.degraded,using_fallback:n.usingFallback,...n.degradeReason?{degrade_reason:n.degradeReason}:{}}}});const V=new st(b.join(c.dataDir,"remote-admin.json"));if(o.setRemoteAdminGate(()=>V.isEnabled()),t.lap("setup"),await o.start(bt),t.lap("agents"),H.length>0){const e=o.getAgentsStatus();for(const n of H){const d=e.find(r=>r.name===n);if(!d)continue;const A=me(d.clientType);A.length!==0&&await L.setAgentRelayEnabled(n,!0,{relayHosts:A}).catch(r=>{i.warn("main",`failed to reconcile relay hosts for "${n}": ${r}`)})}}fe(L,U,P);const re=parseInt(E["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);x.setAgentHandler({list:()=>o.getAgentsStatus(),add:e=>o.addAgent(e),remove:e=>o.removeAgent(e),restart:e=>o.restartAgent(e),reload:()=>o.reload()}),x.setUpgradeHandler({check:()=>o.checkUpgrade(),trigger:()=>o.triggerUpgrade()}),x.setProbeHandler({probeAll:e=>o.probeAll(e),probeOne:(e,n)=>o.probeOne(e,n)}),x.setRemoteAdminHandler({isEnabled:()=>V.isEnabled(),setEnabled:e=>{const n=V.setEnabled(e);return i.info("main",`remote admin ${n?"enabled":"disabled"} via admin API`),n}}),x.setInstallHandler({listInstallable:()=>o.listInstallable(),installAgent:e=>o.installAgent(e),getInstallProgress:e=>o.getInstallProgress(e)});const ne={listAgents:()=>o.getAgentsStatus(),enableManaged:(e,n,d)=>{if(!O)throw new Se(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return O.setAgentRelayCredential(e,{agentId:n,virtualKey:d.virtualKey,anthropicBaseUrl:d.anthropicBaseUrl,openaiBaseUrl:d.openaiBaseUrl,model:d.model,...d.directRelay!==void 0?{directRelay:d.directRelay}:{}})},disableManaged:e=>{if(!O)throw new Se(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return O.setAgentRelay(e,!1)},enableHermesProfile:(e,n)=>yt({agentId:e,baseUrl:n.openaiBaseUrl??"",virtualKey:n.virtualKey,model:n.model??""}),disableHermesProfile:e=>wt(e)};x.setRelayCredentialHandler({listHermesProfiles:()=>St(),enable:async(e,n)=>{const{target:d,result:A}=await Et(ne,e,n);return{target:d,...A}},disable:async e=>{const{target:n,result:d}=await Rt(ne,e);return{target:n,...d}}});{const e=await le({label:"admin",port:re,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:n=>x.start(n)});e&&await ve(e)}const xe=b.join(c.dataDir,"admin-token"),Pe=b.join(c.dataDir,"admin-port");dt(xe,De),se(Pe,String(re),"utf-8"),t.lap("admin"),await B(c.daemonStatusFile,{state:"running",pid:process.pid,instance_id:$,updated_at:Date.now()}),i.info("main",`startup phases: ${t.summary()}`),process.send&&process.send("ready"),i.info("main","grix-connector ready")}It().catch(async t=>{const s=`Fatal: ${t instanceof Error?t.stack??t.message:String(t)}`;try{process.stderr.write(`${s}
43
- `)}catch{}ce(!1),i.error("main",s),K("startup",t);const g=z(c.daemonLockFile);g?.pid===process.pid&&g.instance_id===$&&await B(c.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:g.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await Q(),Z(t,"startup"),await j(),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(1)});const kt=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function be(t){return gt(t)?!0:t instanceof Error&&"code"in t?kt.has(t.code):!1}
40
+ Valid commands: ${Ee.join(", ")}`),process.exit(1));const c=Y(),xt=E["config-dir"]??(E.profile?`${c.configDir}/${E.profile}`:void 0),o=new $e({requestGracefulShutdown:t=>{_(t)},onTransactionSettled:()=>{J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).then(t=>{t.handoffStarted&&i.info("main","Wrapper handoff started after the upgrade transaction settled")}).catch(t=>{i.warn("main",`Post-upgrade wrapper migration failed: ${t instanceof Error?t.message:t}`)})}}),N=new Fe,De=lt(),x=new ct(De);let W=!1,$;function K(t,s){const g=q(),f=process.env.GRIX_LAUNCHER_VERSION;if(!g||!f)return;const l=s instanceof Error?s.stack??s.message:String(s);We(g,f,`${t}: ${l}`)}function Ae(t,s){at(c.dataDir,{holder_pid:t.pid,holder_command_line:t.command_line,yielded_pid:process.pid,yielded_command_line:qe(process.pid)}),process.stderr.write(`${s}
41
+ `),i.warn("main",s);const g=q();g&&ge(g)}function Pt(t){const s=`another grix-connector daemon (pid ${t.pid}) is already serving ${c.rootDir} and answering /healthz; this process yields instead of taking over. A second supervisor is starting duplicate daemons \u2014 check for a leftover wrapper, a duplicate logon task, or a desktop app launching its own copy.`;Ae(t,s),process.exit(0)}function It(t,s){const g=`${s.label} \u7AEF\u53E3 ${s.port} \u5DF2\u88AB\u5360\u7528\uFF0C\u4E14 daemon \u9501\u4ECD\u7531\u53E6\u4E00\u4E2A\u5B58\u6D3B\u5B9E\u4F8B (pid ${t.pid}) \u6301\u6709\uFF1A\u672C\u8FDB\u7A0B\u6309\u7BA1\u7406\u6027\u9000\u51FA\u8BA9\u4F4D\uFF0C\u4E0D\u8BA1\u4E3A\u5D29\u6E83\u3002 \u8FD9\u53F0\u673A\u5668\u4E0A\u6709\u7B2C\u4E8C\u4E2A supervisor \u5728\u91CD\u590D\u62C9\u8D77 daemon\u2014\u2014\u68C0\u67E5\u6B8B\u7559\u7684 wrapper\u3001\u91CD\u590D\u7684\u767B\u5F55\u4EFB\u52A1\uFF0C\u6216\u684C\u9762\u7AEF\u53E6\u8D77\u7684\u526F\u672C\u3002`;Ae(t,g),de()===process.pid&&T(),process.exit(0)}async function ve(t){if(t.kind==="in_use"){const g=tt(c.daemonLockFile);g&&(await j(),It(g,t))}process.stderr.write(t.message+`
42
+ `),i.error("main",t.message.replace(/\n/g," \u2014 ")),K("port_bind",t.message);const s=z(c.daemonLockFile);s?.pid===process.pid&&s.instance_id===$&&await B(c.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:$,updated_at:Date.now(),reason:`port_bind_${t.kind}:${t.label}:${t.port}`}).catch(()=>{}),await j(),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(1)}async function _(t){if(W)return;W=!0,i.info("main",`Received ${t}, shutting down...`),N.markShuttingDown();const s=q();s&&ge(s);const g=t==="upgrade-switch"?Be:t==="launcher-unhealthy"?je:null,f=g??2,l=t==="uncaughtException"||t==="unhandledRejection",m=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(f)},1e4);try{await o.stop(),await h()?.stop().catch(()=>{}),await x.stop(),await N.stop(),await j(),await M(c.daemonLockFile),await nt(c.daemonStatusFile).catch(()=>{}),clearTimeout(m),T(),i.info("main","Shutdown complete"),process.exit(g??(l?2:0))}catch(D){i.error("main",`Shutdown error: ${D}`),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(f)}}async function kt(){const t=it();t.lap("boot"),Le(),Ue(),Oe(c.stdoutLogFile,c.stderrLogFile),ce(!1);try{$=(await Qe(c.daemonLockFile,c.rootDir,2,{isHolderServing:Ze(c.dataDir)})).instance_id}catch(e){e instanceof et&&Pt(e.holder),console.error(e instanceof Error?e.message:e),process.exit(1)}if(t.lap("lock"),Ye()){const e=Je(c.rootDir,"win32");await Xe(e,{platform:"win32"})}t.lap("sweep"),pt(),Me(),t.lap("pidfile"),i.info("main",`grix-connector starting (PID ${process.pid})`);try{Ne({info:e=>i.info("main",e),warn:e=>i.warn("main",e)})}catch(e){i.warn("main",`orphan Claude cleanup failed: ${e instanceof Error?e.message:String(e)}`)}t.lap("orphan"),await B(c.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:$,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new pe({cliPath:b.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(c.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),t.lap("adopt");const s=await J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null));if(t.lap("migrate"),s?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{W||J({rootDir:c.rootDir,requestGracefulShutdown:()=>{_("wrapper-migration")}}).then(n=>{n.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(n=>{i.warn("main",`Periodic wrapper migration failed: ${n instanceof Error?n.message:n}`)})},Ke).unref();const g=parseInt(E["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await le({label:"health",port:g,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:n=>N.start(n)});e&&await ve(e)}const f=b.join(c.dataDir,"health-port");se(f,String(g),"utf-8"),t.lap("health"),process.on("SIGINT",()=>_("SIGINT")),process.on("SIGTERM",()=>_("SIGTERM")),process.on("SIGHUP",()=>{W||(i.info("main","Received SIGHUP, reloading config..."),o.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let l="",m=0,D;process.on("uncaughtException",e=>{const n=e instanceof Error?e.stack??e.message:String(e);n===l?(m++,(m<=3||m%100===0)&&i.error("main",`Uncaught exception (x${m}): ${n}`)):(m>3&&i.error("main",`Previous exception repeated ${m} times total`),l=n,m=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),D||(D=setTimeout(()=>{m>3&&i.error("main",`Previous exception repeated ${m} times total`),l="",m=0,D=void 0},1e4).unref())),!be(e)&&(Q().then(()=>Z(e,"uncaughtException")),K("uncaughtException",e),_("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!be(e)&&(Q().then(()=>Z(e,"unhandledRejection")),K("unhandledRejection",e),_("unhandledRejection"))});const L=mt(c.dataDir);await L.clearRuntimeState();const P=new ut(b.join(c.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),G=new ft(b.join(c.dataDir,"secrets"));o.setRelaySecretResolver(e=>G.get(e));const U={hasDirectConfig:e=>o.hasDirectRelayConfig(e),clearDirectConfig:(e,n)=>o.setAgentProvider(e,void 0,{deferRestart:n?.deferRestart===!0})},X=()=>({pm:h(),agents:o,direct:U,store:P,secrets:G}),H=L.getRelayAgents();if(H.length>0)try{await L.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${H.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${H.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let O=null;if(h()){const e=async()=>{const r=h();r&&await ue(r,o)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};o.setRelayEnvSettledHandler(()=>{const r=h();r&&fe(r,U,P),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const n=()=>{const r=h(),a=r.getRelayAgents(),p=r.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:o.getAgentsWithStaleRelayEnv(),degradedRelayAgents:p,relayState:P.list(),runtime:r.getRuntimeInfo(),config:r.getConfigSnapshot()}},d=new ht,A={status:()=>n(),setAgentRelay:async(r,a,p)=>{const u=h(),R={info:w=>i.info("main",w),warn:w=>i.warn("main",w)},S=w=>o.getAgentsStatus().find(v=>v.name===w),y=S(r);if(!a){d.cancel(r);const w=await d.runExclusive(r,async()=>{const v=await ee(X(),R,{agentName:r,target:"off"});return{...n(),restarted:v.restarted,busy:v.busy,...v.pending?{pending:v.pending}:{}}});return o.reportRelayStateLocalChange(r),w}if(!y)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});if(!Ge(y.clientType)&&me(y.clientType).length===0)throw Object.assign(new Error(`client type "${y.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const F=await d.runExclusive(r,async()=>{const w=d.epoch(r),v=S(r);if(!v)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});const oe=String(v.agentId??"").trim();if(!oe)throw new ye(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const ae=d.waitCancelled(r,w);let C;try{C=await Promise.race([o.fetchRelayCredential(r,{model:p}),ae.promise.then(()=>{throw new we("relay enable cancelled by a later disable","CANCELLED")})])}finally{ae.dispose()}d.assertCurrent(r,w);const{restarted:Ie,busy:ke,pending:ie}=await he(u,o,S,R,{localName:r,agentId:oe,virtualKey:C.apiKey,anthropicBaseUrl:C.anthropicBaseUrl,openaiBaseUrl:C.openaiBaseUrl,model:p,...C.directRelay!==void 0?{directRelay:C.directRelay}:{}},(_e,Ce,Te)=>o.setAgentProvider(_e,Ce,{deferRestart:Te?.deferRestart===!0}),{store:P,secrets:G,direct:U});if(d.epoch(r)!==w)throw await ee(X(),R,{agentName:r,target:"off"}),new we("relay enable cancelled by a later disable","CANCELLED");return{...n(),restarted:Ie,busy:ke,...ie?{pending:ie}:{}}});return o.reportRelayStateLocalChange(r),F},setAgentRelayCredential:async(r,a)=>{const p=h(),u=o.getAgentsStatus(),{restarted:R,busy:S,pending:y}=await he(p,o,I=>u.find(F=>F.name===I),{info:I=>i.info("main",I),warn:I=>i.warn("main",I)},{localName:r,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(I,F,w)=>o.setAgentProvider(I,F,{deferRestart:w?.deferRestart===!0}),{store:P,secrets:G,direct:U});return o.reportRelayStateLocalChange(r),{...n(),restarted:R,busy:S,...y?{pending:y}:{}}},disableAll:async()=>{const r=h(),a={info:u=>i.info("main",u),warn:u=>i.warn("main",u)},p=new Set([...r.getRelayAgents(),...o.getDirectRelayConfigAgentNames(),...Object.keys(P.list())]);for(const u of p)d.cancel(u);for(const u of p)await d.runExclusive(u,()=>ee(X(),a,{agentName:u,target:"off"})),o.reportRelayStateLocalChange(u);return await ue(r,o),n()},setRoute:async(r,a)=>{const p=a,u=h();return u.setRoute({routeKey:r,targetBaseUrl:p.targetBaseUrl,...p.headers?{headers:p.headers}:{},...p.model?{model:p.model}:{},...p.modelMap?{modelMap:p.modelMap}:{},...p.passthrough?{passthrough:!0}:{},...p.relayOnly?{relayOnly:!0}:{},...p.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await u.persistConfig(),n()},deleteRoute:async r=>{const a=h();a.deleteRoute(r),await a.persistConfig()},setDefaultRoute:async r=>{const a=h();return a.setDefaultRouteKey(r),await a.persistConfig(),n()},setInterceptHosts:async r=>{const a=h();return a.setInterceptHosts(r),await a.persistConfig(),n()}};O=A,x.setProxyHandler(A),o.setRelayStateApplier({getAppliedMode:r=>P.get(r)?.applied,getLocalState:r=>{const a=h();if(a.getRelayAgents().includes(r)){const u=o.getAgentsStatus().find(y=>y.name===r),R=`grix-gateway-${String(u?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(y=>y.routeKey===R)?.model?.trim()||void 0}}const p=o.getAgentProvider(r);return p?.api_key?.trim()?{enabled:!0,model:p.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(r,a,p)=>{const u=o.getAgentsStatus().find(y=>y.name===r),R=String(u?.agentId??"").trim();if(!R)throw new ye(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const S=await A.setAgentRelayCredential(r,{agentId:R,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:p??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:S.restarted===!0,busy:S.busy===!0,...S.pending?{pending:S.pending}:{}}},applyDisable:async r=>{const a=await A.setAgentRelay(r,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}N.setStatusProvider(()=>o.getAgentsStatus()),N.setMetaProvider(()=>{const e=o.getAgentsStatus(),n=He();return{ws:{connected:e.filter(d=>d.wsConnected===!0).length,total:e.length},upgrade:Dt(),log:{dir:n.logDir,file:n.logFile,primary_dir:n.primaryLogDir,degraded:n.degraded,using_fallback:n.usingFallback,...n.degradeReason?{degrade_reason:n.degradeReason}:{}}}});const V=new st(b.join(c.dataDir,"remote-admin.json"));if(o.setRemoteAdminGate(()=>V.isEnabled()),t.lap("setup"),await o.start(xt),t.lap("agents"),H.length>0){const e=o.getAgentsStatus();for(const n of H){const d=e.find(r=>r.name===n);if(!d)continue;const A=me(d.clientType);A.length!==0&&await L.setAgentRelayEnabled(n,!0,{relayHosts:A}).catch(r=>{i.warn("main",`failed to reconcile relay hosts for "${n}": ${r}`)})}}fe(L,U,P);const re=parseInt(E["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);x.setAgentHandler({list:()=>o.getAgentsStatus(),add:e=>o.addAgent(e),remove:e=>o.removeAgent(e),restart:e=>o.restartAgent(e),reload:()=>o.reload()}),x.setUpgradeHandler({check:()=>o.checkUpgrade(),trigger:()=>o.triggerUpgrade()}),x.setProbeHandler({probeAll:e=>o.probeAll(e),probeOne:(e,n)=>o.probeOne(e,n)}),x.setRemoteAdminHandler({isEnabled:()=>V.isEnabled(),setEnabled:e=>{const n=V.setEnabled(e);return i.info("main",`remote admin ${n?"enabled":"disabled"} via admin API`),n}}),x.setInstallHandler({listInstallable:()=>o.listInstallable(),installAgent:e=>o.installAgent(e),getInstallProgress:e=>o.getInstallProgress(e)});const ne={listAgents:()=>o.getAgentsStatus(),enableManaged:(e,n,d)=>{if(!O)throw new Se(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return O.setAgentRelayCredential(e,{agentId:n,virtualKey:d.virtualKey,anthropicBaseUrl:d.anthropicBaseUrl,openaiBaseUrl:d.openaiBaseUrl,model:d.model,...d.directRelay!==void 0?{directRelay:d.directRelay}:{}})},disableManaged:e=>{if(!O)throw new Se(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return O.setAgentRelay(e,!1)},enableHermesProfile:(e,n)=>yt({agentId:e,baseUrl:n.openaiBaseUrl??"",virtualKey:n.virtualKey,model:n.model??""}),disableHermesProfile:e=>wt(e)};x.setRelayCredentialHandler({listHermesProfiles:()=>St(),enable:async(e,n)=>{const{target:d,result:A}=await Et(ne,e,n);return{target:d,...A}},disable:async e=>{const{target:n,result:d}=await Rt(ne,e);return{target:n,...d}}});{const e=await le({label:"admin",port:re,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:n=>x.start(n)});e&&await ve(e)}const xe=b.join(c.dataDir,"admin-token"),Pe=b.join(c.dataDir,"admin-port");dt(xe,De),se(Pe,String(re),"utf-8"),t.lap("admin"),await B(c.daemonStatusFile,{state:"running",pid:process.pid,instance_id:$,updated_at:Date.now()}),i.info("main",`startup phases: ${t.summary()}`),process.send&&process.send("ready"),i.info("main","grix-connector ready")}kt().catch(async t=>{const s=`Fatal: ${t instanceof Error?t.stack??t.message:String(t)}`;try{process.stderr.write(`${s}
43
+ `)}catch{}ce(!1),i.error("main",s),K("startup",t);const g=z(c.daemonLockFile);g?.pid===process.pid&&g.instance_id===$&&await B(c.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:g.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await Q(),Z(t,"startup"),await j(),M(c.daemonLockFile).catch(()=>{}),T(),process.exit(1)});const _t=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function be(t){return gt(t)?!0:t instanceof Error&&"code"in t?_t.has(t.code):!1}
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 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+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};