grix-connector 3.26.7 → 3.26.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/deepseek-harness/audit-boundary.js +2 -0
- package/dist/adapter/deepseek-harness/bridge-installer.js +5 -0
- package/dist/adapter/deepseek-harness/bridge-session-reliability.js +1 -0
- package/dist/adapter/deepseek-harness/dsh-provider-config.js +8 -0
- package/dist/adapter/deepseek-harness/dsml-text-filter.js +1 -0
- package/dist/adapter/deepseek-harness/event-mapper.js +1 -0
- package/dist/adapter/deepseek-harness/grix-jsonrpc.cordis.yml +61 -0
- package/dist/adapter/deepseek-harness/index.js +1 -0
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -0
- package/dist/adapter/deepseek-harness/jsonrpc-client.js +4 -0
- package/dist/adapter/deepseek-harness/plugin-manager.js +2 -0
- package/dist/adapter/deepseek-harness/probe.js +1 -0
- package/dist/adapter/deepseek-harness/process-runtime.js +1 -0
- package/dist/adapter/deepseek-harness/profile-bridge-protocol.js +1 -0
- package/dist/adapter/deepseek-harness/profile-catalog.js +1 -0
- package/dist/adapter/deepseek-harness/profile-resolver.js +1 -0
- package/dist/adapter/deepseek-harness/profile-runtime.js +3 -0
- package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -0
- package/dist/adapter/deepseek-harness/prompt-builder.js +5 -0
- package/dist/adapter/deepseek-harness/runtime.js +0 -0
- package/dist/adapter/deepseek-harness/system-prompt.js +2 -0
- package/dist/adapter/deepseek-harness/toolbar-actions.js +1 -0
- package/dist/adapter/deepseek-harness/toolbar-state.js +1 -0
- package/dist/adapter/deepseek-harness/turn-correlator.js +1 -0
- package/dist/adapter/deepseek-harness/types.js +0 -0
- package/dist/adapter/deepseek-harness/usage.js +1 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-3.26.12.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +9 -0
- package/dist/audit/adapters/deepseek-harness/deepseek-harness-audit-adapter.js +2 -0
- package/dist/audit/core/audit-state.js +1 -1
- package/dist/audit/worker/audit-recorder-worker-entry.js +1 -1
- package/dist/bridge/bridge.js +9 -9
- package/dist/bridge/deferred-events.js +1 -1
- package/dist/bridge/native-provider-sweep.js +1 -1
- package/dist/bridge/send-controller.js +1 -1
- package/dist/bridge/tool-card-utils.js +1 -1
- package/dist/core/aibot/binding-card-meta-cache.js +1 -1
- package/dist/core/config/provider-env.js +1 -1
- package/dist/core/installer/installer.js +9 -9
- package/dist/core/installer/manual-guide.js +2 -2
- package/dist/core/installer/registry.js +1 -1
- package/dist/core/persistence/session-binding-store.js +2 -2
- package/dist/core/skill-sync/enable-roots.js +1 -1
- package/dist/default-skills/index.js +1 -1
- package/dist/manager.js +2 -2
- package/dist/mcp/stream-http/security.js +1 -1
- package/package.json +5 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as l}from"../core/log/index.js";const v=2,E=3e3,C=h=>{const e=h.toLowerCase();return e.includes("claude channel listener not ready")||e.includes("notify port")||e.includes("mcp stdio server not available")||e.includes("mcp server startup failed")},y={claude:{announceComposing:!1,retriable:C,retryMax:v,retryDelayMs:E},codex:{announceComposing:!0,composingOptsOverridable:!0},codewhale:{announceComposing:!0,composingOptsOverridable:!0},cursor:{announceComposing:!1},pi:{announceComposing:!0,composingTtlMs:3e4,stopComposingOnError:!0},openhuman:{announceComposing:!0},opencode:{announceComposing:!0},agy:{announceComposing:!0},acp:{announceComposing:!0}},g=["claude","codex","cursor","acp","pi","openhuman","codewhale","opencode","agy"];class _{name;deferredClaudeEvents=new Map;deferredClaudeReplayRetries=new Map;deferredCodexEvents=new Map;deferredCursorEvents=new Map;deferredAcpEvents=new Map;deferredPiEvents=new Map;deferredOpenHumanEvents=new Map;deferredCodeWhaleEvents=new Map;deferredOpenCodeEvents=new Map;deferredAgyEvents=new Map;constructor(e){this.name=e}defer(e,r,t){if(!r)return;const n=this.getMap(e),
|
|
1
|
+
import{log as l}from"../core/log/index.js";const v=2,E=3e3,C=h=>{const e=h.toLowerCase();return e.includes("claude channel listener not ready")||e.includes("notify port")||e.includes("mcp stdio server not available")||e.includes("mcp server startup failed")},y={claude:{announceComposing:!1,retriable:C,retryMax:v,retryDelayMs:E},codex:{announceComposing:!0,composingOptsOverridable:!0},codewhale:{announceComposing:!0,composingOptsOverridable:!0},cursor:{announceComposing:!1},pi:{announceComposing:!0,composingTtlMs:3e4,stopComposingOnError:!0},openhuman:{announceComposing:!0},opencode:{announceComposing:!0},agy:{announceComposing:!0},acp:{announceComposing:!0},"deepseek-harness":{announceComposing:!0}},g=["claude","codex","cursor","acp","pi","openhuman","codewhale","opencode","agy","deepseek-harness"];class _{name;deferredClaudeEvents=new Map;deferredClaudeReplayRetries=new Map;deferredCodexEvents=new Map;deferredCursorEvents=new Map;deferredAcpEvents=new Map;deferredPiEvents=new Map;deferredOpenHumanEvents=new Map;deferredCodeWhaleEvents=new Map;deferredOpenCodeEvents=new Map;deferredAgyEvents=new Map;deferredDeepSeekHarnessEvents=new Map;constructor(e){this.name=e}defer(e,r,t){if(!r)return;const n=this.getMap(e),s=n.get(r)??[];s.some(i=>i.event_id===t.event_id)||(l.info(this.name,`defer channel=${e} session_id=${r} event_id=${t.event_id} queue_len=${s.length}`),s.push(t),n.set(r,s))}deferClaudeEvent(e,r){this.defer("claude",e,r)}deferCodexEvent(e,r){this.defer("codex",e,r)}deferCursorEvent(e,r){this.defer("cursor",e,r)}deferAcpEvent(e,r){this.defer("acp",e,r)}deferPiEvent(e,r){this.defer("pi",e,r)}deferOpenHumanEvent(e,r){this.defer("openhuman",e,r)}deferCodeWhaleEvent(e,r){this.defer("codewhale",e,r)}deferOpenCodeEvent(e,r){this.defer("opencode",e,r)}deferAgyEvent(e,r){this.defer("agy",e,r)}async replayChannel(e,r,t,n={}){const s=this.getMap(e),i=s.get(r);if(!i||i.length===0)return;s.delete(r);const a=y[e];((a.composingOptsOverridable?n.announceComposing:void 0)??a.announceComposing)&&t.sendSessionComposing?.(r,!0,a.composingTtlMs?{ttlMs:a.composingTtlMs}:void 0);for(const d of i)try{t.captureEventRuntimeConfig(d),await t.deliverInboundEvent(d),this.deferredClaudeReplayRetries.delete(d.event_id)}catch(p){const f=p instanceof Error?p.message:String(p),u=this.deferredClaudeReplayRetries.get(d.event_id)??0;if(a.retriable?.(f)&&u<(a.retryMax??0)){this.deferredClaudeReplayRetries.set(d.event_id,u+1);const c=s.get(r)??[];c.some(o=>o.event_id===d.event_id)||(c.push(d),s.set(r,c)),l.warn(this.name,`replay retry ${u+1}/${a.retryMax} channel=${e} session_id=${r} event_id=${d.event_id} reason=${f}`),setTimeout(()=>{this.replayChannel(e,r,t,n).catch(o=>{l.warn(this.name,`replay async retry failed channel=${e} session_id=${r}: ${o instanceof Error?o.message:String(o)}`)})},a.retryDelayMs??0).unref();continue}this.deferredClaudeReplayRetries.delete(d.event_id),a.stopComposingOnError&&t.sendSessionComposing?.(r,!1),t.sendEventResult(d.event_id,"failed",f)}}async replayDeferredClaudeEvents(e,r){await this.replayChannel("claude",e,r)}async replayDeferredCodexEvents(e,r,t={}){await this.replayChannel("codex",e,r,t)}async replayDeferredCursorEvents(e,r,t={}){await this.replayChannel("cursor",e,r,t)}async replayDeferredPiEvents(e,r){await this.replayChannel("pi",e,r)}async replayDeferredOpenHumanEvents(e,r){await this.replayChannel("openhuman",e,r)}async replayDeferredOpenCodeEvents(e,r){await this.replayChannel("opencode",e,r)}async replayDeferredAgyEvents(e,r){await this.replayChannel("agy",e,r)}async replayDeferredAcpEvents(e,r){await this.replayChannel("acp",e,r)}async replayDeferredCodeWhaleEvents(e,r,t={}){await this.replayChannel("codewhale",e,r,t)}async release(e,r,t={}){for(const n of g)this.getMap(n).has(e)&&await this.replayChannel(n,e,r,t)}sendCodexDeferredReplayComposing(e,r){const t=this.deferredCodexEvents.get(e);!t||t.length===0||r.sendSessionComposing?.(e,!0,{ttlMs:12e4,activity:"preparing"})}sendCursorDeferredReplayComposing(e,r){const t=this.deferredCursorEvents.get(e);!t||t.length===0||r.sendSessionComposing?.(e,!0)}hasDeferred(e,r){return this.getMap(e).has(r)}getAllDeferredEvents(){return[...this.deferredClaudeEvents.values(),...this.deferredCodexEvents.values(),...this.deferredCursorEvents.values(),...this.deferredPiEvents.values(),...this.deferredAcpEvents.values(),...this.deferredOpenHumanEvents.values(),...this.deferredCodeWhaleEvents.values(),...this.deferredOpenCodeEvents.values(),...this.deferredAgyEvents.values(),...this.deferredDeepSeekHarnessEvents.values()].flat()}clearAll(){this.deferredClaudeEvents.clear(),this.deferredClaudeReplayRetries.clear(),this.deferredCodexEvents.clear(),this.deferredCursorEvents.clear(),this.deferredPiEvents.clear(),this.deferredOpenHumanEvents.clear(),this.deferredCodeWhaleEvents.clear(),this.deferredOpenCodeEvents.clear(),this.deferredAgyEvents.clear(),this.deferredDeepSeekHarnessEvents.clear(),this.deferredAcpEvents.clear()}removeEvent(e){for(const r of[this.deferredClaudeEvents,this.deferredCodexEvents,this.deferredCursorEvents,this.deferredAcpEvents,this.deferredPiEvents,this.deferredOpenHumanEvents,this.deferredCodeWhaleEvents,this.deferredOpenCodeEvents,this.deferredAgyEvents,this.deferredDeepSeekHarnessEvents])for(const[t,n]of r.entries()){const s=n.findIndex(i=>i.event_id===e);if(s>=0)return n.splice(s,1),n.length===0&&r.delete(t),this.deferredClaudeReplayRetries.delete(e),l.info(this.name,`removeEvent event_id=${e} from deferred queue`),!0}return!1}clearSession(e){const r=this.deferredClaudeEvents.get(e)??[];for(const t of r)this.deferredClaudeReplayRetries.delete(t.event_id);this.deferredClaudeEvents.delete(e),this.deferredCodexEvents.delete(e),this.deferredCursorEvents.delete(e),this.deferredAcpEvents.delete(e),this.deferredPiEvents.delete(e),this.deferredOpenHumanEvents.delete(e),this.deferredCodeWhaleEvents.delete(e),this.deferredOpenCodeEvents.delete(e),this.deferredAgyEvents.delete(e),this.deferredDeepSeekHarnessEvents.delete(e)}getMap(e){switch(e){case"claude":return this.deferredClaudeEvents;case"codex":return this.deferredCodexEvents;case"cursor":return this.deferredCursorEvents;case"acp":return this.deferredAcpEvents;case"pi":return this.deferredPiEvents;case"openhuman":return this.deferredOpenHumanEvents;case"codewhale":return this.deferredCodeWhaleEvents;case"opencode":return this.deferredOpenCodeEvents;case"agy":return this.deferredAgyEvents;case"deepseek-harness":return this.deferredDeepSeekHarnessEvents}}}export{_ as DeferredEventManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as
|
|
1
|
+
import{join as i}from"node:path";import{homedir as n}from"node:os";import{restoreNativeProviderConfig as d}from"../adapter/shared/native-provider-config.js";import{piGrixProviderId as f,removePiGrixProvider as m}from"../adapter/pi/pi-provider-config.js";import{DSH_GRIX_PROVIDER_ID as s,DSH_SETTINGS_FILE as c,removeDshGrixProvider as p}from"../adapter/deepseek-harness/dsh-provider-config.js";import{resolveDshHome as h}from"../adapter/deepseek-harness/profile-resolver.js";async function g(r){if(r.hasProvider)return[];const o=[];if(r.adapterType==="pi"){const e=String(r.piConfigDir??"").trim()||i(n(),".pi","agent");return await m(e,f(r.agentName))&&o.push(i(e,"models.json")),o}if(r.adapterType==="deepseek-harness"){const e=h(r.dshHome);return await p(e,s)&&o.push(i(e,c)),o}const t=new Set(r.boundCwds.map(e=>e.trim()).filter(Boolean));for(const e of t)try{await d(r.command,e)&&o.push(e)}catch{}return o}export{g as sweepNativeProviderResidue};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const q={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();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);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,r,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${r} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents})}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.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)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);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}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(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,n,r,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&D(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...r?{extra:r}:{}})}sendStreamChunk(e,t,s,n,r,a,o){if(this.isEventClosed(e))return;if(o=o??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,r,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,o);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,r,a,o);return}this.coalesceStreamChunk(e,t,s,r,a,o)}async sendFinalStreamChunkReliable(e,t,s,n,r=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const o=this.resolveEventRuntimeConfig(e);if(!r&&o.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const o=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&o?{quoted_message_id:o}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const o of a)this.sendStreamChunk(e,t,o,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,r,a){if(!s&&!n)return;const o=`${e}:${r??"default"}`;let i=this.streamCoalesce.get(o);if(i||(i={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,i)),s&&(i.text+=s),i.sessionId=t,r!==void 0&&(i.clientMsgId=r),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(o,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}i.timer||(i.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 n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}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,n,r,a,o){const i=s||(r?`
|
|
1
|
+
import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const q={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();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);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,r,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${r} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents})}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.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)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);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}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(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,n,r,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&D(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...r?{extra:r}:{}})}sendStreamChunk(e,t,s,n,r,a,o){if(this.isEventClosed(e))return;if(o=o??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,r,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,o);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,r,a,o);return}this.coalesceStreamChunk(e,t,s,r,a,o)}async sendFinalStreamChunkReliable(e,t,s,n,r=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const o=this.resolveEventRuntimeConfig(e);if(!r&&o.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const o=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&o?{quoted_message_id:o}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const o of a)this.sendStreamChunk(e,t,o,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,r,a){if(!s&&!n)return;const o=`${e}:${r??"default"}`;let i=this.streamCoalesce.get(o);if(i||(i={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,i)),s&&(i.text+=s),i.sessionId=t,r!==void 0&&(i.clientMsgId=r),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(o,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}i.timer||(i.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 n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}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,n,r,a,o){const i=s||(r?`
|
|
2
2
|
`:"");if(!i&&!r)return;const l=p(i,C);l.length===0&&l.push(i||`
|
|
3
3
|
`);const u=`${e}:${a??"default"}`;for(let c=0;c<l.length;c++){const m=c===l.length-1,h=this.chunkSeqMap.get(u)??0,g=c===0&&n>h?n:h+1;this.chunkSeqMap.set(u,g),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:l[c],chunk_seq:g,is_finish:m&&r,...a?{client_msg_id:a}:{},...o?{quoted_message_id:o}:{}})}}sendEventResult(e,t,s,n){this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const r=this.ensureSingleMessageDelivery(e),a=(o,i=s,l=n)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",l=l||"agent_output_rejected",i=i||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...i?{msg:i}:{},...l?{code:l}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!r){a(t);return}r.then(()=>a(t),o=>{const i=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?i:s,t==="responded"?"agent_output_delivery_failed":n)})}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 n=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,n),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:n,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,n){if(this.shouldDropToolDisplayEvent(e)){f.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),o=`${e}:${s.summaryText}:${s.detailText??""}`,i=this.recentToolCards.get(o);if(i!==void 0&&a-i<_.TOOL_CARD_DEDUP_MS){f.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(o,a);const l={summary_text:s.summaryText};s.detailText&&(l.detail_text=s.detailText),f.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:n??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:l}},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,n,r){r=r??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,n,r)}bufferStreamChunk(e,t,s,n,r){const a=this.bufferedEventTexts.get(e);a?(s&&(a.text+=s),!a.quotedMessageId&&r&&(a.quotedMessageId=r)):this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:r||void 0}),n&&this.ensureSingleMessageDelivery(e)?.catch(i=>{f.warn("send-ctrl",`single-message output delivery failed event=${e}: ${i instanceof Error?i.message:String(i)}`)})}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const n=this.bufferedEventTexts.get(e);if(!n||(this.bufferedEventTexts.delete(e),!n.text))return;const r=(async()=>{const a={event_id:e,session_id:n.sessionId,content:n.text,client_msg_id:`agent_single_${e}`,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}},o=async()=>{const i=t===void 0?await this.handle.sendText(a):await this.handle.sendText(a,t);if(i.cmd!=="send_ack"){const l=i.payload;throw new Error(`single-message output rejected: cmd=${i.cmd} code=${l?.code??""} msg=${l?.msg??""}`)}};try{await o()}catch(i){if(!E(i))throw i;f.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${a.client_msg_id} event=${e}`),await o()}})();return this.singleMessageDeliveries.set(e,r),r}}function T(){const d=process.env.GRIX_STREAM_COALESCE_MS;if(d===void 0||d==="")return 500;const e=Number(d);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function D(d,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(d)||/^\[tool result\]/.test(d)}export{q as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const _=500,y=140;function i(t){return typeof t=="string"?t.trim().replace(/\s+/g," "):t==null?"":typeof t=="number"||typeof t=="boolean"?String(t):""}function n(t,o){const r=i(t);return r.length<=o?r:o<=3?r.slice(0,o):`${r.slice(0,o-3)}...`}function T(t){const o=i(t);if(!o)return"";try{const r=JSON.parse(o),e=s(r);if(e)return e}catch{}return o}function u(t){const o=i(t);if(!o)return"";try{return s(JSON.parse(o))}catch{return""}}function s(t){if(!t||typeof t!="object"||Array.isArray(t))return"";const o=t;for(const r of["command","file_path","path","pattern","query","description","url","text"]){const e=i(o[r]);if(e)return e}return""}function d(t,o){const r=i(t)||"tool",e=T(o);return{summaryText:e?`${r}: ${n(e,140)}`:r,...e?{detailText:n(e,500)}:{}}}function p(t,o){const r=i(o);if(r==="(failed)")return{summaryText:"(failed)"};if(r.startsWith("(failed) ")){const f=r.slice(9),l=u(f);return{summaryText:l?`${n(l,140)} (failed)`:"(failed)",...l?{detailText:n(l,500)}:{}}}const e=u(r);if(e)return{summaryText:n(e,140),detailText:n(e,500)};const c=n(r,500);return{summaryText:t||"result",...c?{detailText:c}:{}}}function a(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)}catch{return String(t)}}function m(t){const o=String(t.type??""),r=t.payload&&typeof t.payload=="object"?t.payload:{};return o==="tool_call"||o==="tool_use"?d(String(r.tool_name??r.toolName??"tool"),a(r.tool_input??r.input)):o==="tool_result"?p(String(r.tool_name??r.toolName??"result"),a(r.result??r.content??r.output)):null}function I(t,o,r){const e=new URLSearchParams;return e.set("d",JSON.stringify(r)),`[${t}](grix://card/${o}?${e.toString()})`}export{m as buildDshOnlineToolCard,I as buildLocalGrixCardLink,p as buildToolResultCard,d as buildToolUseCard,n as compactToolCardText,i as normalizeToolCardText,a as stringifyToolField};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const c=["available_models","available_modes","available_presets","available_profiles","model_id","mode_id","agent_preset_id","agent_preset_locked","dsh_profile","dsh_profile_locked","dsh_profile_create","dsh_plugins","dsh_plugin_restart_required","available_efforts","effort","reasoning_effort","currentEffort","currentModelId","currentModeId","availableModels","availableModes","models","modes"],_=["available_presets","available_profiles","agent_preset_id","agent_preset_locked","dsh_profile","dsh_profile_locked","dsh_profile_create"],p=[["model_id","currentModelId"],["mode_id","currentModeId"],["effort","reasoning_effort"]];function d(s,o,e){for(const t of o)t in s&&(e[t]=s[t])}function f(s,o){return Object.prototype.hasOwnProperty.call(s,o)&&Array.isArray(s[o])}class b{toolbarMetaBySession=new Map;merge(o,e){if(!o)return e;if(e&&f(e,"available_models")){const r=this.toolbarMetaBySession.get(o),l={};if(d(e,c,l),r)for(const i of _)!(i in l)&&i in r&&(l[i]=r[i]);return this.toolbarMetaBySession.set(o,l),e}if(e&&f(e,"available_profiles")){const r=this.toolbarMetaBySession.get(o)??{};d(e,_,r),this.toolbarMetaBySession.set(o,r)}const t=this.toolbarMetaBySession.get(o);if(!t)return e;if(e)for(const[r,l]of p){const i=e[r],n=e[l],a=typeof i=="string"&&i||typeof n=="string"&&n||null;a&&(t[r]=a,t[l]=a)}return{...t,...e??{}}}delete(o){this.toolbarMetaBySession.delete(o)}}export{b as BindingCardMetaCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildClaudeDirectEnv as
|
|
1
|
+
import{buildClaudeDirectEnv as p,normalizeClaudeEnvEffort as c}from"./claude-direct-env.js";const m={qwen:{baseUrl:"OPENAI_BASE_URL",apiKey:"OPENAI_API_KEY",model:"OPENAI_MODEL"},kimi:{baseUrl:"KIMI_MODEL_BASE_URL",apiKey:"KIMI_MODEL_API_KEY",model:"KIMI_MODEL_NAME",fixed:{KIMI_MODEL_PROVIDER_TYPE:"openai",KIMI_MODEL_CAPABILITIES:"tool_use",KIMI_MODEL_MAX_CONTEXT_SIZE:"262144"}},reasonix:{baseUrl:"DEEPSEEK_BASE_URL",apiKey:"DEEPSEEK_API_KEY"},deepseek:{baseUrl:"DEEPSEEK_BASE_URL",apiKey:"DEEPSEEK_API_KEY"},codewhale:{apiKey:"OPENAI_API_KEY"},hermes:{baseUrl:"GRIX_HERMES_BASE_URL",apiKey:"GRIX_PROVIDER_API_KEY",model:"HERMES_INFERENCE_MODEL",fixed:{HERMES_INFERENCE_PROVIDER:"grix"}},pi:{apiKey:"GRIX_PROVIDER_API_KEY"}},R=["qwen","kimi","reasonix","deepseek","codewhale","hermes","pi","opencode"],f=["kiro"];function i(E){return E?.trim().toLowerCase().split("/",1)[0]??""}function u(E){const e=i(E);return!!e&&R.includes(e)}function P(E){const e=i(E);return!!e&&f.includes(e)}function M(E){return u(E)||P(E)}function A(E){const e=i(E);return!!e&&e in m}function D(E,e){if(!e)return{};const s=i(E);if(s==="claude"){const a=e.baseUrl?.trim(),l=e.apiKey?.trim(),I=e.model?.trim();if(!a||!l||!I)return{};const K=c(e.effort);return p({baseUrl:a,primaryModel:I,...e.fastModel?.trim()?{fastModel:e.fastModel.trim()}:{},...K?{effort:K}:{}},l)}const t=m[s];if(!t)return{};const r=e.baseUrl?.trim(),n=e.apiKey?.trim(),_=e.model?.trim();if(!r&&!n&&!_)return{};const o={...t.fixed??{}};return t.baseUrl&&r&&(o[t.baseUrl]=r),t.apiKey&&n&&(o[t.apiKey]=n),t.model&&_&&(o[t.model]=_),o}export{R as DIRECT_PROVIDER_CLIENT_TYPES,f as KIRO_CW_RELAY_CLIENT_TYPES,m as PROVIDER_ENV_SPECS,D as buildProviderEnv,u as supportsDirectProviderConfig,P as supportsKiroCwRelay,M as supportsNonMitmRelayConfig,A as supportsProviderEnv};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{execFile as R,spawn as _}from"node:child_process";import{log as m}from"../log/logger.js";import{resolveCliPath as P,getCliVersion as
|
|
2
|
-
${F(i)}`);const o=q(i);if(!o.supported)return this.fail(
|
|
3
|
-
${f}`}catch(a){const g=s.message,I=a instanceof u?a.message:String(a),$=a instanceof u?a.output:void 0,L=X(s.output,$);return this.fail(
|
|
1
|
+
import{execFile as R,spawn as _}from"node:child_process";import{log as m}from"../log/logger.js";import{resolveCliPath as P,getCliVersion as k,invalidateCliPathCache as x}from"../util/cli-probe.js";import{getInstallCommand as S,getCliBinary as O,isKnownAgent as D,detectPlatformOS as A,formatInstallCommand as U}from"./registry.js";import{checkPrerequisites as y,getMissingPrerequisites as v}from"./preflight.js";import{installMissingPrerequisites as C}from"./prereq-installer.js";import{detectEnvironment as V,formatEnvironmentInfo as F,isEnvironmentSupported as q}from"./env-detect.js";import{generateManualGuide as b}from"./manual-guide.js";import{npmInstallWithMirror as j,isTransientInstallError as G}from"./npm-registry.js";import{getAllAgentInstallInfo as B}from"./registry.js";class u extends Error{code;output;constructor(n,t,e){super(t),this.name="InstallerError",this.code=n,this.output=e}}const T=64*1024,H=20,N=2,W=3e3;class le{os;activeInstalls=new Map;constructor(){this.os=A()}listInstallable(){return{platform:this.os,agents:B(this.os)}}getProgress(n){return this.activeInstalls.get(n)}isInProgress(n){return this.activeInstalls.has(n)}async install(n){const{agentType:t}=n,e=Date.now();if(this.activeInstalls.has(t))return this.fail(t,"preflight",e,new u("INSTALL_IN_PROGRESS",`${t} is already being installed`));try{return await this._doInstall(n,e)}catch(i){this.activeInstalls.delete(t);const o=i instanceof Error?i.message:String(i);return m.error("installer",`${t} install unexpected error: ${o}`),{agentType:t,ok:!1,phase:"failed",error:{code:"INTERNAL",message:`Unexpected error: ${o}`},durationMs:Date.now()-e,output:""}}}async _doInstall(n,t){const{agentType:e}=n;let i;try{i=await V()}catch(s){const a=s instanceof Error?s.message:String(s);return this.fail(e,"preflight",t,new u("INTERNAL",`Environment detection failed: ${a}`))}m.info("installer",`Install request: ${e}
|
|
2
|
+
${F(i)}`);const o=q(i);if(!o.supported)return this.fail(e,"preflight",t,new u("ENVIRONMENT_UNSUPPORTED",`Current environment is not supported for automatic installation: ${o.reason}. Please install ${e} manually.`),i);if(this.setProgress(e,"preflight",t),!D(e))return this.fail(e,"preflight",t,new u("UNKNOWN_AGENT",`Unknown agent type: ${e}`),i);const l=S(e,this.os);if(!l){const s=this.getManualHint(e,this.os),a=s?`Installation of ${e} is not supported on ${this.os}. ${s}`:`Installation of ${e} is not supported on ${this.os}`;return this.fail(e,"preflight",t,new u("UNSUPPORTED_OS",a),i)}const c=O(e),p=await P(c),d=p?(await k(p)).version:null;if(p&&!n.force&&!n.dryRun){this.activeInstalls.delete(e);const s=Date.now()-t;return m.info("installer",`${e} already installed at ${p}${d?` (v${d})`:""}`),{agentType:e,ok:!0,phase:"completed",installedPath:p,installedVersion:d,durationMs:s,output:"",environment:i}}const h=l.prerequisites??[];let r=[];if(h.length>0){m.info("installer",`Checking prerequisites for ${e}: ${h.join(", ")}`),r=await y(h,this.os),m.info("installer",`Prerequisites: ${r.map(a=>`${a.label}=${a.met?a.version:"missing"}`).join(", ")}`);const s=v(r);if(s.length>0){const a=s.map(g=>`${g.label}${g.minVersion?` >= ${g.minVersion}`:""}`).join(", ");if(!n.dryRun){if(n.skipPrereqInstall)return this.fail(e,"preflight",t,new u("PREREQ_MISSING",`Missing prerequisites: ${a}. Install them first or retry without skipPrereqInstall.`),i,r);const g=s.map($=>`${$.label}${$.minVersion?` >= ${$.minVersion}`:""}`);m.info("installer",`Will auto-install prerequisites: ${g.join(", ")}`),this.setProgress(e,"installing_prereq",t,s[0].label,g);const I=await C(s,this.os);if(!I.allOk){const $=I.results.find(M=>!M.ok),L=$?`Failed to install prerequisite ${$.prereq.label}: ${$.output}`:"Prerequisite installation failed";return this.fail(e,"installing_prereq",t,new u("PREREQ_INSTALL_FAILED",L),i,r)}m.info("installer",`All prerequisites installed for ${e}`),r=await y(h,this.os)}}}if(n.dryRun){this.activeInstalls.delete(e);const s=v(r),a=this.getManualHint(e,this.os),g={agentType:e,environment:i,canInstall:!0,alreadyInstalled:!!p,installedPath:p,installedVersion:d,installCommand:U(l),installMode:l.mode,prerequisites:r,missingPrerequisites:s,fallbackCommand:l.fallback?.command??null,manualHint:a},I=b({agentType:e,os:this.os,env:i,missingPrereqs:s});return{agentType:e,ok:!0,phase:"completed",durationMs:Date.now()-t,output:"dry-run: no commands executed",environment:i,dryRun:g,manualGuide:I}}this.setProgress(e,"installing",t),m.info("installer",`Installing ${e}: ${l.command}`);let f;try{f=await this.executeWithRetry(l,e,t,n.timeoutMs)}catch(s){if(l.fallback&&s instanceof u&&(s.code==="INSTALL_FAILED"||s.code==="INSTALL_TIMEOUT")){m.info("installer",`Primary install (${l.command}) failed: ${s.message}`),m.info("installer",`Trying fallback: ${l.fallback.command}`),this.setProgress(e,"installing",t);try{f=await this.executeWithRetry(l.fallback,e,t,n.timeoutMs),f=`[primary failed, fallback succeeded]
|
|
3
|
+
${f}`}catch(a){const g=s.message,I=a instanceof u?a.message:String(a),$=a instanceof u?a.output:void 0,L=X(s.output,$);return this.fail(e,"installing",t,new u("FALLBACK_EXHAUSTED",`Both primary and fallback install methods failed.
|
|
4
4
|
Primary: ${g}
|
|
5
|
-
Fallback: ${I}`,L),i,r)}}else return s instanceof u?this.fail(
|
|
5
|
+
Fallback: ${I}`,L),i,r)}}else return s instanceof u?this.fail(e,"installing",t,new u(s.code,s.message,s.output),i,r):this.fail(e,"installing",t,new u("INTERNAL",s instanceof Error?s.message:String(s)),i,r)}{const s=(f??"").trim().split(`
|
|
6
6
|
`).slice(-12).join(`
|
|
7
|
-
`);m.info("installer",`${
|
|
8
|
-
${s||"<\u7A7A>"}`)}if(x(),!n.skipVerify&&!l.skipVerification){this.setProgress(
|
|
9
|
-
${r??""}`.trim();if(f&&this.updateOutputTail(i,o,f),d){if(d.killed)c(new u("INSTALL_TIMEOUT",`${n} timed out after ${
|
|
7
|
+
`);m.info("installer",`${e} \u5B89\u88C5\u547D\u4EE4\u8F93\u51FA(\u5C3E\u90E8):
|
|
8
|
+
${s||"<\u7A7A>"}`)}if(x(),!n.skipVerify&&!l.skipVerification){this.setProgress(e,"verifying",t),m.info("installer",`Verifying ${e} installation...`);const s=await P(c);if(!s)return this.fail(e,"verifying",t,new u("VERIFICATION_FAILED",`${c} not found on PATH after installation. You may need to open a new terminal or run: source ~/.zshrc (or ~/.bashrc)`),i,r);let{version:a,error:g}=await k(s);a===null&&g&&(await this.sleep(1e3),{version:a,error:g}=await k(s));const I=Date.now()-t;return this.activeInstalls.delete(e),m.info("installer",`${e} installed successfully at ${s} (v${a??"unknown"}, ${I}ms)`),{agentType:e,ok:!0,phase:"completed",installedPath:s,installedVersion:a,durationMs:I,output:f,prerequisites:r.length>0?r:void 0,environment:i}}const E=Date.now()-t;return this.activeInstalls.delete(e),m.info("installer",`${e} install command completed (${E}ms, verification skipped)`),{agentType:e,ok:!0,phase:"completed",installedPath:null,installedVersion:null,durationMs:E,output:f,prerequisites:r.length>0?r:void 0,environment:i}}getManualHint(n,t){const i=S(n,t)?.fallback,l={claude:"https://docs.anthropic.com/en/docs/claude-code/overview",codex:"https://github.com/openai/codex",qwen:"https://github.com/QwenLM/qwen-code",cursor:"https://cursor.com/docs/cli/installation",copilot:"https://github.com/github/copilot-cli",kiro:"https://kiro.dev/docs/cli/",openclaw:"https://github.com/openclaw/openclaw",reasonix:"https://github.com/esengine/DeepSeek-Reasonix",deepseek:"https://www.npmjs.com/package/@deepseek-ai/dsh"}[n],c=[];return l&&c.push(`Docs: ${l}`),i&&c.push(`Alternative: ${i.command}`),c.length>0?c.join(" | "):null}setProgress(n,t,e,i,o){this.activeInstalls.set(n,{agentType:n,phase:t,startedAt:e,elapsedMs:Date.now()-e,...i?{currentPrereq:i}:{},...o?{pendingPrereqs:o}:{}})}fail(n,t,e,i,o,l,c){const p=c??i.output??this.activeInstalls.get(n)?.outputTail??"";this.activeInstalls.delete(n),m.error("installer",`${n} install failed at ${t}: ${i.message}`);const d=l?v(l):[],h=b({agentType:n,os:this.os,env:o??{platform:this.os,osVersion:"unknown",arch:process.arch,shell:process.env.SHELL??null,nodeVersion:null,npmVersion:null,isDocker:!1,isCI:!1},missingPrereqs:d,primaryFailed:t==="installing",fallbackFailed:i.code==="FALLBACK_EXHAUSTED",error:i.message});return{agentType:n,ok:!1,phase:"failed",error:{code:i.code,message:i.message},durationMs:Date.now()-e,output:p,environment:o,prerequisites:l,manualGuide:h}}async executeWithRetry(n,t,e,i){let o=null;for(let l=0;l<=N;l++)try{return l>0&&(m.info("installer",`Retry ${l}/${N} for ${t}...`),await this.sleep(W)),await this.executeCommand(n,t,e,i)}catch(c){if(o=c instanceof u?c:new u("INTERNAL",String(c)),!(o.code==="INSTALL_TIMEOUT"||o.code==="INSTALL_FAILED"&&G(o.message))||l>=N)throw o;m.info("installer",`Attempt ${l+1} failed (retryable): ${o.message}`)}throw o??new u("INTERNAL","Unexpected retry loop exit")}sleep(n){return new Promise(t=>setTimeout(t,n))}executeCommand(n,t,e,i){const o=i??n.timeoutMs;switch(n.mode){case"npm":return this.executeNpm(n.npmPackage,o,t,e);case"shell":return this.executeShell(n.command,o,t,e);case"exec":return this.executeExec(n.command,n.execArgs??[],o,t,e);default:return Promise.reject(new u("INTERNAL",`Unknown install mode: ${n.mode}`))}}async executeNpm(n,t,e,i){try{const{output:o,registry:l}=await j(n,t,T);return m.info("installer",`npm install ${n} succeeded via ${l}`),o}catch(o){const l=o instanceof Error?o.message:String(o),c=K(o);throw c&&this.updateOutputTail(e,i,c),l.includes("timed out")||l.includes("ETIMEDOUT")?new u("INSTALL_TIMEOUT",`npm install timed out (tried all mirrors): ${l}`,c):new u("INSTALL_FAILED",`npm install failed (tried all mirrors): ${l}`,c)}}executeShell(n,t,e,i){return new Promise((o,l)=>{const c=process.platform==="win32",p=c?"cmd.exe":"bash",d=c?["/d","/c",n]:["-c",`set -o pipefail; ${n}`];m.info("installer",`exec: ${p} ${d.join(" ")}`);const h=_(p,d,{timeout:t,stdio:["ignore","pipe","pipe"],...c?{windowsVerbatimArguments:!0}:{},env:{...process.env,NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}});let r="",f=!1;const E=setTimeout(()=>{f=!0;try{h.kill("SIGTERM")}catch{}setTimeout(()=>{try{h.kill("SIGKILL")}catch{}},5e3).unref()},t);h.stdout?.on("data",s=>{const a=s.toString("utf-8");r+=a,r.length>T&&(r=r.slice(-T)),this.updateOutputTail(e,i,r)}),h.stderr?.on("data",s=>{const a=s.toString("utf-8");r+=a,r.length>T&&(r=r.slice(-T)),this.updateOutputTail(e,i,r)}),h.on("error",s=>{clearTimeout(E),l(new u("INSTALL_FAILED",`Spawn error: ${s.message}`))}),h.on("close",s=>{if(clearTimeout(E),f){l(new u("INSTALL_TIMEOUT",`Install timed out after ${t/1e3}s`,r.trim()));return}if(s!==0){const a=r.slice(-1024);l(new u("INSTALL_FAILED",`Process exited with code ${s}: ${a}`,r.trim()));return}o(r.trim())})})}executeExec(n,t,e,i,o){return new Promise((l,c)=>{m.info("installer",`exec: ${n} ${t.join(" ")}`);const p=R(n,t,{timeout:e,maxBuffer:T},(d,h,r)=>{const f=`${h??""}
|
|
9
|
+
${r??""}`.trim();if(f&&this.updateOutputTail(i,o,f),d){if(d.killed)c(new u("INSTALL_TIMEOUT",`${n} timed out after ${e/1e3}s`,f));else{const E=f||d.message;c(new u("INSTALL_FAILED",`${n} failed: ${E}`,f))}return}l(f)});this.trackOutput(p,i,o)})}trackOutput(n,t,e){n.on("close",()=>{const i=this.activeInstalls.get(t);i&&(i.elapsedMs=Date.now()-e)})}updateOutputTail(n,t,e){const o=e.split(`
|
|
10
10
|
`).slice(-H).join(`
|
|
11
|
-
`),l=this.activeInstalls.get(n);l&&(l.outputTail=o,l.elapsedMs=Date.now()-
|
|
12
|
-
`)||void 0}export{
|
|
11
|
+
`),l=this.activeInstalls.get(n);l&&(l.outputTail=o,l.elapsedMs=Date.now()-t)}}function K(w){if(w&&typeof w=="object"&&"output"in w){const n=w.output;return typeof n=="string"?n:""}return""}function X(...w){return w.map(t=>t?.trim()).filter(t=>!!t).join(`
|
|
12
|
+
`)||void 0}export{le as AgentInstaller,u as InstallerError};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getInstallCommand as f,getCliBinary as g}from"./registry.js";import{getPrereqManualInstructions as $}from"./prereq-installer.js";import{getMirrorInstallCommands as r}from"./npm-registry.js";function v(
|
|
2
|
-
`)}function b(
|
|
1
|
+
import{getInstallCommand as f,getCliBinary as g}from"./registry.js";import{getPrereqManualInstructions as $}from"./prereq-installer.js";import{getMirrorInstallCommands as r}from"./npm-registry.js";function v(h){const{agentType:n,os:i,env:u,missingPrereqs:c}=h,s=[],a=g(n)??n,o=f(n,i),m=b(i);if(s.push(`=== ${n} \u4EBA\u5DE5\u5B89\u88C5\u6307\u5357 (${m}) ===`),s.push(""),s.push("\u5F53\u524D\u73AF\u5883:"),s.push(` \u7CFB\u7EDF: ${u.osVersion} (${u.arch})`),s.push(` Node.js: ${u.nodeVersion??"\u672A\u5B89\u88C5"}`),s.push(` npm: ${u.npmVersion??"\u672A\u5B89\u88C5"}`),s.push(""),h.error&&(s.push("\u81EA\u52A8\u5B89\u88C5\u5931\u8D25\u539F\u56E0:"),s.push(` ${h.error}`),s.push("")),c.length>0){s.push("--- \u6B65\u9AA4 1: \u5B89\u88C5\u524D\u7F6E\u4F9D\u8D56 ---"),s.push("");for(const e of c){const p=$(e.id,i);s.push(`\u25B8 ${e.label}${e.minVersion?` (\u9700\u8981 >= ${e.minVersion})`:""}`),p&&s.push(` \u5B89\u88C5\u65B9\u6CD5: ${p}`),s.push(` \u9A8C\u8BC1: ${e.id==="node"?"node --version":e.id==="npm"?"npm --version":`${e.id} --version`}`),s.push("")}}const l=c.length>0?"2":"1";if(s.push(`--- \u6B65\u9AA4 ${l}: \u5B89\u88C5 ${n} ---`),s.push(""),o){if(s.push(" \u63A8\u8350\u65B9\u5F0F:"),s.push(` ${o.command}`),s.push(""),o.mode==="npm"&&o.npmPackage){const e=r(o.npmPackage);s.push(" \u955C\u50CF\u5B89\u88C5\uFF08\u56FD\u5185\u7F51\u7EDC\u6162\u6216\u88AB\u5899\u65F6\u4F7F\u7528\uFF09:");for(const p of e)s.push(` # ${p.label}`),s.push(` ${p.command}`);s.push("")}if(o.fallback){if(s.push(" \u5907\u9009\u65B9\u5F0F\uFF08\u63A8\u8350\u5B89\u88C5\u5931\u8D25\u65F6\u4F7F\u7528\uFF09:"),s.push(` ${o.fallback.command}`),o.fallback.mode==="npm"&&o.fallback.npmPackage){const e=r(o.fallback.npmPackage);for(const p of e)s.push(` # ${p.label}`),s.push(` ${p.command}`)}s.push("")}}const d=c.length>0?"3":"2";s.push(`--- \u6B65\u9AA4 ${d}: \u9A8C\u8BC1\u5B89\u88C5 ---`),s.push(""),s.push(` ${a} --version`),s.push(""),s.push(" \u5982\u679C\u663E\u793A\u7248\u672C\u53F7\uFF0C\u8BF4\u660E\u5B89\u88C5\u6210\u529F\u3002"),s.push(""),s.push("--- \u5E38\u89C1\u95EE\u9898 ---"),s.push(""),s.push(" Q: \u5B89\u88C5\u540E\u547D\u4EE4\u627E\u4E0D\u5230\uFF1F"),s.push(" A: \u53EF\u80FD\u9700\u8981\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\uFF0C\u6216\u8FD0\u884C:"),i==="macos"||i==="linux"?(s.push(" source ~/.zshrc # zsh"),s.push(" source ~/.bashrc # bash")):s.push(" \u91CD\u65B0\u6253\u5F00 PowerShell \u6216 CMD \u7A97\u53E3"),s.push(""),o?.mode==="npm"&&(s.push(" Q: npm install -g \u62A5\u6743\u9650\u9519\u8BEF\uFF1F"),i==="macos"||i==="linux"?(s.push(" A: \u4E0D\u8981\u7528 sudo npm install -g\u3002\u5EFA\u8BAE\u7528\u4EE5\u4E0B\u65B9\u5F0F\u4E4B\u4E00:"),s.push(" 1. brew install node (macOS\uFF0C\u63A8\u8350)"),s.push(" 2. \u4F7F\u7528 fnm/nvm \u7BA1\u7406 Node.js (Linux)"),s.push(" 3. \u914D\u7F6E npm \u5168\u5C40\u76EE\u5F55: npm config set prefix ~/.npm-global")):s.push(" A: \u4EE5\u7BA1\u7406\u5458\u8EAB\u4EFD\u6253\u5F00 PowerShell \u540E\u91CD\u8BD5"),s.push("")),s.push("--- \u5B98\u65B9\u6587\u6863 ---"),s.push("");const t={claude:"https://docs.anthropic.com/en/docs/claude-code/overview",codex:"https://github.com/openai/codex",qwen:"https://github.com/QwenLM/qwen-code",cursor:"https://cursor.com/docs/cli/installation",copilot:"https://github.com/github/copilot-cli",kiro:"https://kiro.dev/docs/cli/",kimi:"https://moonshotai.github.io/kimi-cli/",openclaw:"https://github.com/openclaw/openclaw",reasonix:"https://github.com/esengine/DeepSeek-Reasonix",deepseek:"https://www.npmjs.com/package/@deepseek-ai/dsh"};return t[n]&&s.push(` ${n}: ${t[n]}`),s.join(`
|
|
2
|
+
`)}function b(h){switch(h){case"macos":return"macOS";case"linux":return"Linux";case"windows":return"Windows"}}export{v as generateManualGuide};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(i,s){return{command:`npm install -g ${i}`,mode:"npm",npmPackage:i,timeoutMs:s?.timeoutMs??12e4,prerequisites:["node","npm"],minNodeVersion:s?.minNodeVersion}}function n(i,s){return{command:i,mode:"shell",timeoutMs:s?.timeoutMs??12e4,prerequisites:s?.prerequisites}}function c(i,s,o){return{command:i,mode:"exec",execArgs:s,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:{...n("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:{...n("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:{...n(`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:n("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),linux:n("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),windows:n(`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:n("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),linux:n("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),windows:null},kimi:{cliBinary:"kimi",macos:n("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),linux:n("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),windows:n('powershell -ExecutionPolicy ByPass -c "irm https://code.kimi.com/install.ps1 | iex"',{timeoutMs:3e5})},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:n("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),linux:n("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),windows:n('powershell -ExecutionPolicy ByPass -c "irm https://antigravity.google/cli/install.ps1 | iex"')},hermes:{cliBinary:"hermes",macos:null,linux:null,windows:null},codewhale:{cliBinary:"codewhale",macos:e("codewhale"),linux:e("codewhale"),windows:e("codewhale")},opencode:{cliBinary:"opencode",macos:{...n("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},linux:{...n("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},windows:e("opencode-ai")}};function u(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"linux"}}function r(i){return i.mode==="exec"&&i.execArgs&&i.execArgs.length>0?[i.command,...i.execArgs].join(" "):i.command}function d(i,s){const o=l[i];return o?o[s]:null}function
|
|
1
|
+
function e(i,s){return{command:`npm install -g ${i}`,mode:"npm",npmPackage:i,timeoutMs:s?.timeoutMs??12e4,prerequisites:["node","npm"],minNodeVersion:s?.minNodeVersion}}function n(i,s){return{command:i,mode:"shell",timeoutMs:s?.timeoutMs??12e4,prerequisites:s?.prerequisites}}function c(i,s,o){return{command:i,mode:"exec",execArgs:s,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:{...n("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:{...n("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:{...n(`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:n("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),linux:n("curl https://cursor.com/install -fsS | bash",{prerequisites:["curl"]}),windows:n(`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:n("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),linux:n("curl -fsSL https://cli.kiro.dev/install | bash",{prerequisites:["curl"]}),windows:null},kimi:{cliBinary:"kimi",macos:n("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),linux:n("curl -LsSf https://code.kimi.com/install.sh | bash",{prerequisites:["curl"],timeoutMs:3e5}),windows:n('powershell -ExecutionPolicy ByPass -c "irm https://code.kimi.com/install.ps1 | iex"',{timeoutMs:3e5})},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:n("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),linux:n("curl -fsSL https://antigravity.google/cli/install.sh | bash",{prerequisites:["curl"]}),windows:n('powershell -ExecutionPolicy ByPass -c "irm https://antigravity.google/cli/install.ps1 | iex"')},hermes:{cliBinary:"hermes",macos:null,linux:null,windows:null},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")},opencode:{cliBinary:"opencode",macos:{...n("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},linux:{...n("curl -fsSL https://opencode.ai/install | bash",{prerequisites:["curl"]}),fallback:e("opencode-ai")},windows:e("opencode-ai")}};function u(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"linux"}}function r(i){return i.mode==="exec"&&i.execArgs&&i.execArgs.length>0?[i.command,...i.execArgs].join(" "):i.command}function d(i,s){const o=l[i];return o?o[s]:null}function p(i){return l[i]?.cliBinary??null}function a(i,s){const o=l[i];if(!o)return null;const t=o[s];return{agentType:i,cliBinary:o.cliBinary,supported:t!==null,installCommand:t?r(t):null,prerequisites:t?.prerequisites}}function m(i){return Object.keys(l).sort().map(s=>a(s,i)).filter(s=>s!==null)}function w(i){return i in l}export{u as detectPlatformOS,r as formatInstallCommand,a as getAgentInstallInfo,m as getAllAgentInstallInfo,p as getCliBinary,d as getInstallCommand,w as isKnownAgent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readJSONFile as l,writeJSONFileAtomic as u}from"../util/json-file.js";import{log as r}from"../log/index.js";import{SESSION_MODE_IDS as c}from"../../adapter/claude/protocol-contract.js";import{normalizeClaudeEffort as s}from"../config/claude-direct-env.js";import{chmodSync as I,copyFileSync as x,existsSync as a,renameSync as m,rmSync as p,writeFileSync as b}from"node:fs";import{randomUUID as y}from"node:crypto";const h=c.fullAuto;function o(g){const e=String(g??"").trim().toLowerCase();return e===c.approval||e===c.fullAuto?e:h}class T{bindings=new Map;filePath;legacyFilePath;writePromise=Promise.resolve();constructor(e,t){this.filePath=e??null,this.legacyFilePath=t&&t!==e?t:null}load(){if(!this.filePath)return;const e=a(this.filePath);let t=l(this.filePath),i=!1;if(e&&!Array.isArray(t)){const d=this.quarantineUnreadablePrimary();throw new Error(`Refusing to start with unreadable session bindings: primary=${this.filePath}`+(d?` quarantined=${d}`:"")+(this.legacyFilePath?` legacy=${this.legacyFilePath}`:"")+" (legacy fallback disabled to avoid clobbering newer bindings)")}if(!e&&this.legacyFilePath){i=a(this.legacyFilePath);const d=l(this.legacyFilePath);Array.isArray(d)&&(this.writeMigratedSnapshot(d),t=d,r.info("session-binding-store",`Migrated legacy bindings from ${this.legacyFilePath} to ${this.filePath}; legacy file retained`))}if(!Array.isArray(t)){if(e||i)throw new Error(`Refusing to start with unreadable session bindings: primary=${this.filePath}${this.legacyFilePath?` legacy=${this.legacyFilePath}`:""}`);return}this.bindings.clear();for(const d of t)d.aibotSessionId&&this.bindings.set(d.aibotSessionId,{...d,modeId:o(d.modeId),effort:s(d.effort)})}set(e,t,i){const d=this.bindings.get(e),n=o(i?.modeId??d?.modeId),f=t!==void 0?t:d?.cwd;this.bindings.set(e,{aibotSessionId:e,cwd:f,acpSessionId:d?.acpSessionId,claudeSessionId:d?.claudeSessionId,codexThreadId:d?.codexThreadId,codexModelId:d?.codexModelId,codexModeId:d?.codexModeId,codewhaleThreadId:d?.codewhaleThreadId,agyConversationId:d?.agyConversationId,codexReasoningEffort:d?.codexReasoningEffort,codexServiceTier:d?.codexServiceTier,codexSandboxMode:d?.codexSandboxMode,piSessionPath:d?.piSessionPath,modeId:n,modelId:d?.modelId,effort:d?.effort,cursorModeId:d?.cursorModeId,acpModelId:d?.acpModelId,acpModeId:d?.acpModeId,updatedAt:Date.now()}),this.scheduleWrite()}setAcpSessionId(e,t){this.updateBinding(e,{acpSessionId:t})}setClaudeSessionId(e,t){this.updateBinding(e,{claudeSessionId:t})}getClaudeSessionId(e){return this.bindings.get(e)?.claudeSessionId}setCodexThreadId(e,t){this.updateBinding(e,{codexThreadId:t})}getCodexThreadId(e){return this.bindings.get(e)?.codexThreadId}setAgyConversationId(e,t){this.updateBinding(e,{agyConversationId:t})}getAgyConversationId(e){return this.bindings.get(e)?.agyConversationId}setCodexContext(e,t){this.updateBinding(e,{codexModelId:t.modelId,codexModeId:t.modeId,codexReasoningEffort:t.reasoningEffort,codexServiceTier:t.serviceTier,codexSandboxMode:t.sandboxMode})}getCodexModelId(e){return this.bindings.get(e)?.codexModelId}setCodexModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexModelId===d||(this.bindings.set(e,{...i,codexModelId:d,updatedAt:Date.now()}),this.scheduleWrite())}setCodexModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexModeId===d||(this.bindings.set(e,{...i,codexModeId:d,updatedAt:Date.now()}),this.scheduleWrite())}setCodexServiceTier(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexServiceTier===d||(this.bindings.set(e,{...i,codexServiceTier:d,updatedAt:Date.now()}),this.scheduleWrite())}getCodexModeId(e){return this.bindings.get(e)?.codexModeId}getCodexReasoningEffort(e){return this.bindings.get(e)?.codexReasoningEffort}getCodexServiceTier(e){return this.bindings.get(e)?.codexServiceTier}getCodexSandboxMode(e){return this.bindings.get(e)?.codexSandboxMode}setPiSessionPath(e,t){this.updateBinding(e,{piSessionPath:t})}getPiSessionPath(e){return this.bindings.get(e)?.piSessionPath}setCodeWhaleThreadId(e,t){this.updateBinding(e,{codewhaleThreadId:t})}getCodeWhaleThreadId(e){return this.bindings.get(e)?.codewhaleThreadId}setModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=o(t);i.modeId!==d&&(this.bindings.set(e,{...i,modeId:d,updatedAt:Date.now()}),this.scheduleWrite())}ensureModeId(e,t=h){const i=this.bindings.get(e);i&&(i.modeId||(this.bindings.set(e,{...i,modeId:o(t),updatedAt:Date.now()}),this.scheduleWrite()))}getAcpSessionId(e){return this.bindings.get(e)?.acpSessionId}getModeId(e){const t=this.bindings.get(e)?.modeId;return t?o(t):void 0}setModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=t.trim();i.modelId!==d&&(this.bindings.set(e,{...i,modelId:d,updatedAt:Date.now()}),this.scheduleWrite())}getModelId(e){return this.bindings.get(e)?.modelId}setEffort(e,t){const i=this.bindings.get(e);if(!i)return;const d=s(t);d&&i.effort!==d&&(this.bindings.set(e,{...i,effort:d,updatedAt:Date.now()}),this.scheduleWrite())}getEffort(e){return s(this.bindings.get(e)?.effort)}setCursorModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim().toLowerCase(),n=d===""?void 0:d;i.cursorModeId!==n&&(this.bindings.set(e,{...i,cursorModeId:n,updatedAt:Date.now()}),this.scheduleWrite())}getCursorModeId(e){return this.bindings.get(e)?.cursorModeId}setAcpModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim(),n=d===""?void 0:d;i.acpModelId!==n&&(this.bindings.set(e,{...i,acpModelId:n,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModelId(e){return this.bindings.get(e)?.acpModelId}setAcpModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim(),n=d===""?void 0:d;i.acpModeId!==n&&(this.bindings.set(e,{...i,acpModeId:n,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModeId(e){return this.bindings.get(e)?.acpModeId}get(e){return this.bindings.get(e)}getMostRecentlyUpdatedSessionId(e){const t=e?.requireCwd!==!1;let i,d=-1;for(const n of this.bindings.values())t&&!String(n.cwd??"").trim()||n.updatedAt>d&&(d=n.updatedAt,i=n.aibotSessionId);return i}delete(e){const t=this.bindings.get(e);t&&(r.info("session-binding-store",`delete binding session_id=${e} cwd=${t.cwd??""} codexThreadId=${t.codexThreadId??""}`),this.bindings.delete(e),this.scheduleWrite())}quarantineUnreadablePrimary(){if(!this.filePath||!a(this.filePath))return;const e=`${this.filePath}.corrupt.${Date.now()}`;try{return x(this.filePath,e),r.error("session-binding-store",`Copied unreadable primary bindings to ${e} (original retained to block legacy clobber)`),e}catch(t){r.error("session-binding-store",`Failed to copy unreadable primary ${this.filePath}: ${t instanceof Error?t.message:String(t)}`);return}}entries(){return this.bindings.entries()}async flush(){await this.writePromise}scheduleWrite(){this.filePath&&(this.writePromise=this.writePromise.then(()=>this.write()).catch(e=>{r.error("session-binding-store",`Persist failed: ${e instanceof Error?e.message:e}`)}))}async write(){if(!this.filePath)return;const e=Array.from(this.bindings.values());await u(this.filePath,e)}writeMigratedSnapshot(e){if(!this.filePath)return;const t=`${this.filePath}.${y()}.migration.tmp`;try{b(t,`${JSON.stringify(e,null,2)}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),
|
|
1
|
+
import{readJSONFile as I,writeJSONFileAtomic as m}from"../util/json-file.js";import{log as o}from"../log/index.js";import{SESSION_MODE_IDS as l}from"../../adapter/claude/protocol-contract.js";import{normalizeClaudeEffort as a}from"../config/claude-direct-env.js";import{chmodSync as x,copyFileSync as p,existsSync as h,renameSync as S,rmSync as M,writeFileSync as b}from"node:fs";import{randomUUID as y}from"node:crypto";const P=l.fullAuto;function n(g){const e=String(g??"").trim().toLowerCase();return e===l.approval||e===l.fullAuto?e:P}class E{bindings=new Map;filePath;legacyFilePath;writePromise=Promise.resolve();constructor(e,t){this.filePath=e??null,this.legacyFilePath=t&&t!==e?t:null}load(){if(!this.filePath)return;const e=h(this.filePath);let t=I(this.filePath),i=!1;if(e&&!Array.isArray(t)){const d=this.quarantineUnreadablePrimary();throw new Error(`Refusing to start with unreadable session bindings: primary=${this.filePath}`+(d?` quarantined=${d}`:"")+(this.legacyFilePath?` legacy=${this.legacyFilePath}`:"")+" (legacy fallback disabled to avoid clobbering newer bindings)")}if(!e&&this.legacyFilePath){i=h(this.legacyFilePath);const d=I(this.legacyFilePath);Array.isArray(d)&&(this.writeMigratedSnapshot(d),t=d,o.info("session-binding-store",`Migrated legacy bindings from ${this.legacyFilePath} to ${this.filePath}; legacy file retained`))}if(!Array.isArray(t)){if(e||i)throw new Error(`Refusing to start with unreadable session bindings: primary=${this.filePath}${this.legacyFilePath?` legacy=${this.legacyFilePath}`:""}`);return}this.bindings.clear();for(const d of t)d.aibotSessionId&&this.bindings.set(d.aibotSessionId,{...d,modeId:n(d.modeId),effort:a(d.effort),dshProviderId:typeof d.dshProviderId=="string"&&d.dshProviderId.trim()?d.dshProviderId.trim():void 0,dshModelId:typeof d.dshModelId=="string"&&d.dshModelId.trim()?d.dshModelId.trim():void 0,dshModeId:d.dshModeId===void 0?void 0:d.dshModeId==="full_auto"?"full_auto":"approval",dshMaxTokens:Number.isSafeInteger(d.dshMaxTokens)&&Number(d.dshMaxTokens)>0?Number(d.dshMaxTokens):void 0,dshAgentPreset:typeof d.dshAgentPreset=="string"&&d.dshAgentPreset.trim()?d.dshAgentPreset.trim():void 0,dshSettingsRevision:d.dshSettingsRevision===void 0?void 0:Number.isSafeInteger(d.dshSettingsRevision)&&Number(d.dshSettingsRevision)>=0?Number(d.dshSettingsRevision):0,dshProfileName:typeof d.dshProfileName=="string"&&d.dshProfileName.trim()?d.dshProfileName.trim():void 0,dshProfileSessionId:typeof d.dshProfileSessionId=="string"&&d.dshProfileSessionId.trim()?d.dshProfileSessionId.trim():void 0,dshProfileSessionCreated:d.dshProfileSessionCreated===!0,dshProfileEventCursor:Number.isSafeInteger(d.dshProfileEventCursor)&&Number(d.dshProfileEventCursor)>=0?Number(d.dshProfileEventCursor):0})}set(e,t,i){const d=this.bindings.get(e),s=n(i?.modeId??d?.modeId),r=t!==void 0?t:d?.cwd;this.bindings.set(e,{aibotSessionId:e,cwd:r,acpSessionId:d?.acpSessionId,claudeSessionId:d?.claudeSessionId,codexThreadId:d?.codexThreadId,codexModelId:d?.codexModelId,codexModeId:d?.codexModeId,codewhaleThreadId:d?.codewhaleThreadId,agyConversationId:d?.agyConversationId,codexReasoningEffort:d?.codexReasoningEffort,codexServiceTier:d?.codexServiceTier,codexSandboxMode:d?.codexSandboxMode,piSessionPath:d?.piSessionPath,modeId:s,modelId:d?.modelId,effort:d?.effort,cursorModeId:d?.cursorModeId,acpModelId:d?.acpModelId,acpModeId:d?.acpModeId,dshProviderId:d?.dshProviderId,dshModelId:d?.dshModelId,dshModeId:d?.dshModeId,dshMaxTokens:d?.dshMaxTokens,dshAgentPreset:d?.dshAgentPreset,dshSettingsRevision:d?.dshSettingsRevision,dshSettingsUpdatedAt:d?.dshSettingsUpdatedAt,dshProfileName:d?.dshProfileName,dshProfileSessionId:d?.dshProfileSessionId,dshProfileSessionCreated:d?.dshProfileSessionCreated,dshProfileEventCursor:d?.dshProfileEventCursor,updatedAt:Date.now()}),this.scheduleWrite()}setAcpSessionId(e,t){this.updateBinding(e,{acpSessionId:t})}setClaudeSessionId(e,t){this.updateBinding(e,{claudeSessionId:t})}getClaudeSessionId(e){return this.bindings.get(e)?.claudeSessionId}setCodexThreadId(e,t){this.updateBinding(e,{codexThreadId:t})}getCodexThreadId(e){return this.bindings.get(e)?.codexThreadId}setAgyConversationId(e,t){this.updateBinding(e,{agyConversationId:t})}getAgyConversationId(e){return this.bindings.get(e)?.agyConversationId}setCodexContext(e,t){this.updateBinding(e,{codexModelId:t.modelId,codexModeId:t.modeId,codexReasoningEffort:t.reasoningEffort,codexServiceTier:t.serviceTier,codexSandboxMode:t.sandboxMode})}getCodexModelId(e){return this.bindings.get(e)?.codexModelId}setCodexModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexModelId===d||(this.bindings.set(e,{...i,codexModelId:d,updatedAt:Date.now()}),this.scheduleWrite())}setCodexModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexModeId===d||(this.bindings.set(e,{...i,codexModeId:d,updatedAt:Date.now()}),this.scheduleWrite())}setCodexServiceTier(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim();!d||i.codexServiceTier===d||(this.bindings.set(e,{...i,codexServiceTier:d,updatedAt:Date.now()}),this.scheduleWrite())}getCodexModeId(e){return this.bindings.get(e)?.codexModeId}getCodexReasoningEffort(e){return this.bindings.get(e)?.codexReasoningEffort}getCodexServiceTier(e){return this.bindings.get(e)?.codexServiceTier}getCodexSandboxMode(e){return this.bindings.get(e)?.codexSandboxMode}setPiSessionPath(e,t){this.updateBinding(e,{piSessionPath:t})}getPiSessionPath(e){return this.bindings.get(e)?.piSessionPath}setCodeWhaleThreadId(e,t){this.updateBinding(e,{codewhaleThreadId:t})}getCodeWhaleThreadId(e){return this.bindings.get(e)?.codewhaleThreadId}setModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=n(t);i.modeId!==d&&(this.bindings.set(e,{...i,modeId:d,updatedAt:Date.now()}),this.scheduleWrite())}ensureModeId(e,t=P){const i=this.bindings.get(e);i&&(i.modeId||(this.bindings.set(e,{...i,modeId:n(t),updatedAt:Date.now()}),this.scheduleWrite()))}getAcpSessionId(e){return this.bindings.get(e)?.acpSessionId}getModeId(e){const t=this.bindings.get(e)?.modeId;return t?n(t):void 0}setModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=t.trim();i.modelId!==d&&(this.bindings.set(e,{...i,modelId:d,updatedAt:Date.now()}),this.scheduleWrite())}getModelId(e){return this.bindings.get(e)?.modelId}setEffort(e,t){const i=this.bindings.get(e);if(!i)return;const d=a(t);d&&i.effort!==d&&(this.bindings.set(e,{...i,effort:d,updatedAt:Date.now()}),this.scheduleWrite())}getEffort(e){return a(this.bindings.get(e)?.effort)}setCursorModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim().toLowerCase(),s=d===""?void 0:d;i.cursorModeId!==s&&(this.bindings.set(e,{...i,cursorModeId:s,updatedAt:Date.now()}),this.scheduleWrite())}getCursorModeId(e){return this.bindings.get(e)?.cursorModeId}setAcpModelId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim(),s=d===""?void 0:d;i.acpModelId!==s&&(this.bindings.set(e,{...i,acpModelId:s,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModelId(e){return this.bindings.get(e)?.acpModelId}setAcpModeId(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t??"").trim(),s=d===""?void 0:d;i.acpModeId!==s&&(this.bindings.set(e,{...i,acpModeId:s,updatedAt:Date.now()}),this.scheduleWrite())}getAcpModeId(e){return this.bindings.get(e)?.acpModeId}getDshSettings(e){const t=this.bindings.get(e);if(t)return{...t.dshProviderId?{providerId:t.dshProviderId}:{},...t.dshModelId?{modelId:t.dshModelId}:{},modeId:t.dshModeId==="full_auto"?"full_auto":"approval",...t.dshMaxTokens?{maxTokens:t.dshMaxTokens}:{},...t.dshAgentPreset?{agentPreset:t.dshAgentPreset}:{},revision:t.dshSettingsRevision??0,...t.dshSettingsUpdatedAt?{updatedAt:t.dshSettingsUpdatedAt}:{}}}updateDshSettings(e,t){const i=this.bindings.get(e);if(!i)return;const d=Object.prototype.hasOwnProperty.call(t,"providerId")?String(t.providerId??"").trim()||void 0:i.dshProviderId,s=Object.prototype.hasOwnProperty.call(t,"modelId")?String(t.modelId??"").trim()||void 0:i.dshModelId,r=Object.prototype.hasOwnProperty.call(t,"modeId")?t.modeId==="full_auto"?"full_auto":"approval":i.dshModeId==="full_auto"?"full_auto":"approval",f=Object.prototype.hasOwnProperty.call(t,"maxTokens")?Number.isSafeInteger(t.maxTokens)&&Number(t.maxTokens)>0?Number(t.maxTokens):void 0:i.dshMaxTokens;if(d===i.dshProviderId&&s===i.dshModelId&&r===(i.dshModeId==="full_auto"?"full_auto":"approval")&&f===i.dshMaxTokens)return i.dshSettingsRevision??0;const u=Date.now(),c=(i.dshSettingsRevision??0)+1;return this.bindings.set(e,{...i,dshProviderId:d,dshModelId:s,dshModeId:r,dshMaxTokens:f,dshSettingsRevision:c,dshSettingsUpdatedAt:u,updatedAt:u}),this.scheduleWrite(),c}getDshSelectedProfile(e){const t=this.bindings.get(e)?.dshProfileName;return typeof t=="string"&&t.trim()?t.trim():void 0}isDshProfileLocked(e){return this.bindings.get(e)?.dshProfileSessionCreated===!0}setDshSelectedProfile(e,t){const i=this.bindings.get(e);if(!i)return!1;const d=String(t??"").trim();return d?i.dshProfileName===d?!0:i.dshProfileSessionCreated===!0?!1:(this.bindings.set(e,{...i,dshProfileName:d,dshProfileSessionId:void 0,dshProfileSessionCreated:!1,dshProfileEventCursor:0,updatedAt:Date.now()}),this.scheduleWrite(),!0):!1}getDshAgentPreset(e){const t=this.bindings.get(e)?.dshAgentPreset;return typeof t=="string"&&t.trim()?t.trim():void 0}isDshAgentPresetLocked(e){return this.bindings.get(e)?.dshProfileSessionCreated===!0}setDshAgentPreset(e,t){const i=this.bindings.get(e);if(!i||i.dshProfileSessionCreated===!0)return!1;const d=String(t??"").trim();return!d||i.dshAgentPreset===d?i.dshAgentPreset===d:(this.bindings.set(e,{...i,dshAgentPreset:d,updatedAt:Date.now()}),this.scheduleWrite(),!0)}getDshProfileBinding(e,t){const i=this.bindings.get(e);if(!(!i?.dshProfileSessionId||i.dshProfileName!==t))return{profileName:t,sessionId:i.dshProfileSessionId,sessionCreated:i.dshProfileSessionCreated===!0,eventCursor:i.dshProfileEventCursor??0}}setDshProfileBinding(e,t){const i=this.bindings.get(e);if(!i)return;const d=String(t.profileName).trim(),s=String(t.sessionId).trim();if(!d||!s)return;const r=Number.isSafeInteger(t.eventCursor)&&t.eventCursor>=0?t.eventCursor:0;i.dshProfileName===d&&i.dshProfileSessionId===s&&i.dshProfileSessionCreated===t.sessionCreated&&(i.dshProfileEventCursor??0)===r||(this.bindings.set(e,{...i,dshProfileName:d,dshProfileSessionId:s,dshProfileSessionCreated:t.sessionCreated,dshProfileEventCursor:r,updatedAt:Date.now()}),this.scheduleWrite())}get(e){return this.bindings.get(e)}getMostRecentlyUpdatedSessionId(e){const t=e?.requireCwd!==!1;let i,d=-1;for(const s of this.bindings.values())t&&!String(s.cwd??"").trim()||s.updatedAt>d&&(d=s.updatedAt,i=s.aibotSessionId);return i}delete(e){const t=this.bindings.get(e);t&&(o.info("session-binding-store",`delete binding session_id=${e} cwd=${t.cwd??""} codexThreadId=${t.codexThreadId??""}`),this.bindings.delete(e),this.scheduleWrite())}quarantineUnreadablePrimary(){if(!this.filePath||!h(this.filePath))return;const e=`${this.filePath}.corrupt.${Date.now()}`;try{return p(this.filePath,e),o.error("session-binding-store",`Copied unreadable primary bindings to ${e} (original retained to block legacy clobber)`),e}catch(t){o.error("session-binding-store",`Failed to copy unreadable primary ${this.filePath}: ${t instanceof Error?t.message:String(t)}`);return}}entries(){return this.bindings.entries()}async flush(){await this.writePromise}scheduleWrite(){this.filePath&&(this.writePromise=this.writePromise.then(()=>this.write()).catch(e=>{o.error("session-binding-store",`Persist failed: ${e instanceof Error?e.message:e}`)}))}async write(){if(!this.filePath)return;const e=Array.from(this.bindings.values());await m(this.filePath,e)}writeMigratedSnapshot(e){if(!this.filePath)return;const t=`${this.filePath}.${y()}.migration.tmp`;try{b(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),S(t,this.filePath);try{x(this.filePath,384)}catch{}}catch(i){if(h(t))try{M(t)}catch{}throw new Error(`Failed to migrate legacy session bindings from ${this.legacyFilePath} to ${this.filePath}: ${i instanceof Error?i.message:String(i)}`)}}updateBinding(e,t){const i=this.bindings.get(e),d={aibotSessionId:e,acpSessionId:Object.prototype.hasOwnProperty.call(t,"acpSessionId")?t.acpSessionId:i?.acpSessionId,claudeSessionId:Object.prototype.hasOwnProperty.call(t,"claudeSessionId")?t.claudeSessionId:i?.claudeSessionId,codexThreadId:Object.prototype.hasOwnProperty.call(t,"codexThreadId")?t.codexThreadId:i?.codexThreadId,codexModelId:Object.prototype.hasOwnProperty.call(t,"codexModelId")?t.codexModelId:i?.codexModelId,codexModeId:Object.prototype.hasOwnProperty.call(t,"codexModeId")?t.codexModeId:i?.codexModeId,codewhaleThreadId:Object.prototype.hasOwnProperty.call(t,"codewhaleThreadId")?t.codewhaleThreadId:i?.codewhaleThreadId,agyConversationId:Object.prototype.hasOwnProperty.call(t,"agyConversationId")?t.agyConversationId:i?.agyConversationId,codexReasoningEffort:Object.prototype.hasOwnProperty.call(t,"codexReasoningEffort")?t.codexReasoningEffort:i?.codexReasoningEffort,codexServiceTier:Object.prototype.hasOwnProperty.call(t,"codexServiceTier")?t.codexServiceTier:i?.codexServiceTier,codexSandboxMode:Object.prototype.hasOwnProperty.call(t,"codexSandboxMode")?t.codexSandboxMode:i?.codexSandboxMode,piSessionPath:Object.prototype.hasOwnProperty.call(t,"piSessionPath")?t.piSessionPath:i?.piSessionPath,cwd:i?.cwd,modeId:n(i?.modeId),modelId:i?.modelId,effort:Object.prototype.hasOwnProperty.call(t,"effort")?a(t.effort):a(i?.effort),cursorModeId:i?.cursorModeId,acpModelId:i?.acpModelId,acpModeId:i?.acpModeId,dshProviderId:i?.dshProviderId,dshModelId:i?.dshModelId,dshModeId:i?.dshModeId,dshMaxTokens:i?.dshMaxTokens,dshAgentPreset:i?.dshAgentPreset,dshSettingsRevision:i?.dshSettingsRevision,dshSettingsUpdatedAt:i?.dshSettingsUpdatedAt,dshProfileName:i?.dshProfileName,dshProfileSessionId:i?.dshProfileSessionId,dshProfileSessionCreated:i?.dshProfileSessionCreated,dshProfileEventCursor:i?.dshProfileEventCursor,updatedAt:Date.now()};this.bindings.set(e,d),this.scheduleWrite()}}export{E as SessionBindingStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as o}from"node:path";function i(n,
|
|
1
|
+
import{join as o}from"node:path";function i(n,r){const{home:e}=r,l=r.cwd?.trim()||void 0,t=r.env??process.env;switch(n){case"claude":return{globalRoot:o(e,".claude","skills"),projectRoot:l?o(l,".claude","skills"):null};case"codex":{const s=t.CODEX_HOME?.trim()||o(e,".codex");return{globalRoot:o(s,"skills"),projectRoot:l?o(l,".codex","skills"):null}}case"gemini":return{globalRoot:o(e,".gemini","skills"),projectRoot:l?o(l,".gemini","skills"):null};case"qwen":return{globalRoot:o(e,".qwen","skills"),projectRoot:l?o(l,".qwen","skills"):null};case"pi":return{globalRoot:o(e,".pi","agent","skills"),projectRoot:l?o(l,".pi","skills"):null};case"kiro":return{globalRoot:o(e,".kiro","skills"),projectRoot:l?o(l,".kiro","skills"):null};case"cursor":return{globalRoot:o(e,".cursor","skills"),projectRoot:l?o(l,".cursor","skills"):null};case"codewhale":return{globalRoot:o(e,".codewhale","skills"),projectRoot:l?o(l,".codewhale","skills"):null};case"opencode":{const s=t.XDG_CONFIG_HOME?.trim()||o(e,".config");return{globalRoot:o(s,"opencode","skills"),projectRoot:null}}case"reasonix":return{globalRoot:o(e,".reasonix","skills"),projectRoot:null};case"kimi":{const s=t.KIMI_CODE_HOME?.trim()||o(e,".kimi-code");return{globalRoot:o(s,"skills"),projectRoot:null}}case"deepseek":{const s=t.DSH_HOME?.trim()||o(e,".dsh");return{globalRoot:o(s,"skills"),projectRoot:l?o(l,".dsh","skills"):null}}default:return{globalRoot:null,projectRoot:null}}}export{i as resolveEnableRoots};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as p,readdirSync as c,existsSync as
|
|
1
|
+
import{readFileSync as p,readdirSync as c,existsSync as m,mkdirSync as k,cpSync as h,writeFileSync as y,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as u}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as H,MANAGED_MARKER as f}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as F}from"../core/config/index.js";import{log as a}from"../core/log/index.js";const l=S(D(import.meta.url));function d(){const e=[];let n;try{n=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of n){if(!r.isDirectory())continue;const i=t(l,r.name,"SKILL.md");try{const s=p(i,"utf-8"),o=v(s);o?.name&&e.push({name:o.name,description:o.description,trigger:o.trigger,source:"connector",managed:!0})}catch{}}return e}function T(e){let n=[];try{n=x(e)}catch{n=[]}return H([...n,...d()])}function j(e){const n=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return n}for(const i of r){if(!i.isDirectory())continue;const s=t(l,i.name);if(m(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,i.name);h(s,o,{recursive:!0}),y(t(o,f),"","utf8"),n.push(i.name)}catch{}}return n}function _(e=process.env){return(e.KIMI_CODE_HOME||"").trim()||t(u(),".kimi-code")}function w(e=process.env){return(e.DSH_HOME||"").trim()||t(u(),".dsh")}function C(){const e=u(),n=process.env.XDG_CONFIG_HOME||t(e,".config");return[t(F().dataDir,"claude-plugin","skills"),t(e,".codex","skills"),t(e,".gemini","skills"),t(e,".qwen","skills"),t(e,".pi","agent","skills"),t(e,".codewhale","skills"),t(n,"opencode","skills"),t(e,".cursor","skills"),t(e,".openhuman","skills"),t(e,".kiro","skills"),t(e,".reasonix","skills"),t(_(),"skills"),t(w(),"skills")]}function b(){const e=[];for(const n of C()){let r;try{r=c(n,{withFileTypes:!0,encoding:"utf8"})}catch{continue}for(const i of r){if(!i.isDirectory())continue;const s=t(n,i.name);if(m(t(s,f)))try{g(s,{recursive:!0,force:!0}),e.push(s)}catch{}}}return e.length>0&&a.info("default-skills",`Cleaned ${e.length} projected skill dir(s)`),e}function A(){const e=d();if(e.length===0){a.warn("default-skills","No connector system skills found \u2014 dist/default-skills/ may be missing SKILL.md files");return}a.info("default-skills",`Connector system skills available: [${e.map(n=>n.name).join(", ")}]`)}export{T as buildReportedSkills,b as cleanupProjectedSkills,A as logDefaultSkillsCheck,w as resolveDshSkillHome,_ as resolveKimiCodeHome,d as scanDefaultSkills,j as syncDefaultSkillsToDir};
|
package/dist/manager.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as Z,readdirSync as ee,writeFileSync as te}from"node:fs";import{join as A}from"node:path";import{homedir as ne}from"node:os";import{AgentInstance as D}from"./bridge/bridge.js";import{buildSharedInstanceConfig as re,diffSharedOwners as ae,sharedInstanceKey as ie,SharedOwnersCache as se}from"./manager-share-config.js";import{isAgentDeletedError as O}from"./core/aibot/errors.js";import{GRIX_PATHS as _,log as d}from"./core/log/index.js";import{resolveClientVersion as oe}from"./core/util/client-version.js";import{UpgradeChecker as ce}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as le}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as de}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as pe}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as me}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as ue}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as ge}from"./core/aibot/types.js";import{buildReportedSkills as fe,logDefaultSkillsCheck as he,cleanupProjectedSkills as L}from"./default-skills/index.js";import{supportsKiroCwRelay as N,supportsNonMitmRelayConfig as _e}from"./core/config/provider-env.js";import{ensureKiroRelay as H,stopKiroRelay as q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as U}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as B}from"./core/runtime/cursor-resolve.js";import{getCliVersion as ye,resolveCliPath as we}from"./core/util/cli-probe.js";import{AgentInstaller as Se}from"./core/installer/installer.js";import{reportInstallFailure as ve}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Ae}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as ke}from"./adapter/codex/config-overrides.js";import{resolveCodexDirectHome as be}from"./adapter/codex/direct-home.js";const Ce=8e3;function $e(){const r=U();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:B()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:r.command},{clientType:"agy",command:"agy"}]}async function xe(){return Promise.all($e().map(async r=>{const e=await we(r.command);if(!e)return{client_type:r.clientType,command:r.command,installed:!1,path:null,version:null};const t=await ye(e,r.versionArgs??["--version"]);return{client_type:r.clientType,command:r.command,installed:!0,path:e,version:t.version,error:t.error}}))}function Ie(r){switch(r){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:B()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=U();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${r}`)}}function k(r,e){return String(r??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function Te(r){return A(_.data,`session-bindings-${k(r,"unknown")}.json`)}function Ee(r,e){return A(_.data,`session-bindings-${k(r,e)}.json`)}function Pe(r,e){return A(_.data,`active-events-${k(r,e)}.json`)}function Re(r,e){const t=k(r,"agent"),n=k(e,"unknown");return A(_.data,`terminal-outbox-${t}-${n}.json`)}function je(...r){const e=[],t=new Set;for(const n of r)for(const a of n??[]){const s=String(a??"").trim(),i=s.toLowerCase();!s||t.has(i)||(t.add(i),e.push(s))}return e.length>0?e:void 0}function Me(r,e){const t={claude:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0}},n=t[r]??t.acp;return{maxConcurrent:e?.max_concurrent??n.maxConcurrent??1,maxQueued:e?.max_queued??n.maxQueued??3,queueTimeoutMs:e?.queue_timeout_ms??n.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function De(r,e={}){const t=oe(),n=String(r.client_type??"").trim().toLowerCase(),a=Ie(n),s=String(r.ws_url??"").trim(),i="get_session_usage",l="get_rate_limits",c="get_agent_global_config",o=ge;if(!r.name?.trim())throw new Error("agent name is required");if(!s)throw new Error(`agent ${r.name}: ws_url is required`);if(!r.agent_id?.trim())throw new Error(`agent ${r.name}: agent_id is required`);if(!r.api_key?.trim())throw new Error(`agent ${r.name}: api_key is required`);const p=a.adapterType,u=p==="acp",w=n==="qwen",m={...a.options??{}};if(r.codex_config_overrides!==void 0){if(p!=="codex")throw new Error(`agent ${r.name}: codex_config_overrides is only supported for client_type=codex`);ke(r.codex_config_overrides,`agent ${r.name}: codex_config_overrides`),m.codexConfigOverrides=r.codex_config_overrides}if(p==="codex"&&r.provider?.wire_api!==void 0){const f=r.provider;if(f.wire_api!=="responses"||!f.base_url?.trim()||!f.api_key?.trim()||!f.model?.trim()||!f.catalog_version?.trim()||!f.catalog_sha256?.trim()||!f.catalog_json?.trim())throw Object.assign(new Error(`agent ${r.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const M=be(_.data,r.name);m.codexHome=M,m.codexDirect={codexHome:M,config:{baseUrl:f.base_url.trim(),model:f.model.trim(),...f.reasoning_effort?.trim()?{reasoningEffort:f.reasoning_effort.trim()}:{},token:f.api_key.trim()},catalog:{version:f.catalog_version.trim(),sha256:f.catalog_sha256.trim(),json:f.catalog_json}}}const h=p==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",i,l]}:null,y=p==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",i,l]}:null,g=w?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",i],adapterHint:"qwen/base"}:null,v=p==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","get_context","file_list","create_folder",i,l]}:null,S=p==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,C=p==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",l]}:null,T=p==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",i]}:null,$=p==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,x=p==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,E=new Set(["hermes","reasonix","kimi","copilot"]),K=u&&!E.has(n),Q=u&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",...K?[i]:[]]}:null,W=n==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",i,l]}:null,G=p==="codex"||p==="claude"||p==="opencode"||n==="gemini"?["session_control","set_model","set_mode",...p==="claude"?["set_reasoning_effort"]:[]]:void 0,z=p==="cursor"||p==="opencode"||p==="openhuman"||p==="agy"||u&&E.has(n)?[l]:[i,l];u&&m.raw_transport===void 0&&(m.raw_transport=n==="gemini");const V=`${n}/base`,I=pe(p,n),J=I==="kiro"?void 0:process.cwd(),P=fe({mode:I,projectDir:J}),R=P.filter(f=>f.source==="connector").map(f=>f.name);R.length>0&&!e.quiet&&d.info("manager",`[${r.name}] injecting connector skills: [${R.join(", ")}]`);const j=me(P,_.skills);let X=j.length>0?j:void 0;const Y=ue({skillsDir:_.skills,mode:I,home:ne()});return{name:r.name,adapterType:p,aibot:{url:s,agentId:r.agent_id,apiKey:r.api_key,clientType:n,clientVersion:t,adapterHint:a.adapterHint??g?.adapterHint??v?.adapterHint??S?.adapterHint??C?.adapterHint??$?.adapterHint??x?.adapterHint??V,capabilities:h?.capabilities??T?.capabilities??v?.capabilities??S?.capabilities??C?.capabilities??$?.capabilities??x?.capabilities??g?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:je(h?.localActions??T?.localActions??y?.localActions??v?.localActions??S?.localActions??C?.localActions??$?.localActions??x?.localActions??g?.localActions??W?.localActions??Q?.localActions??["exec_approve","exec_reject"],G,z,["connector_rollback","connector_upgrade_push",c,"configure_gateway_provider","skill_upload","skill_enable","skill_disable","skill_refresh",...o]),skills:X,librarySkills:Y,terminalOutboxPath:Re(r.name,r.agent_id)},agent:{command:a.command,args:[...a.args??[],...r.args??[]],env:r.env,clientType:n,...r.provider?{provider:{...r.provider.provider_id?.trim()?{providerId:r.provider.provider_id.trim()}:{},...r.provider.base_url?.trim()?{baseUrl:r.provider.base_url.trim()}:{},...r.provider.quota_base_url?.trim()?{quotaBaseUrl:r.provider.quota_base_url.trim()}:{},...r.provider.api_key?.trim()?{apiKey:r.provider.api_key.trim()}:{},...r.provider.model?.trim()?{model:r.provider.model.trim()}:{},...r.provider.fast_model?.trim()?{fastModel:r.provider.fast_model.trim()}:{},...r.provider.effort?.trim()?{effort:r.provider.effort.trim()}:{}}}:{}},adapterOptions:m,acpAuthMethod:m.auth_method,acpInitialMode:m.initial_mode,acpMcpTools:m.acp_mcp_tools,promptTimeoutMs:r.prompt_timeout_ms,bindingsPath:Te(r.agent_id),legacyBindingsPath:Ee(r.name,r.agent_id),activeEventStorePath:Pe(r.name,r.agent_id),...a.enableSessionBinding||u?{enableSessionBinding:!0}:{},...a.autoInjectArgs||n==="reasonix"&&r.provider?.model?.trim()?{autoInjectArgs:{...a.autoInjectArgs??{},...n==="reasonix"&&r.provider?.model?.trim()?{model:r.provider.model.trim()}:{}}}:{},poolMaxSize:r.pool?.maxSize,poolIdleTimeoutMs:r.pool?.idleTimeoutMs,eventQueue:Me(p,r.event_queue),logDir:_.log,providerBaseUrl:r.provider_base_url?.trim()||void 0,providerApiKey:r.provider_api_key?.trim()||void 0}}function Oe(){const r=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(r);return Number.isFinite(e)&&e>=500?Math.floor(e):Ce}function F(r){const e=[],t=[],n=[],a=ee(r).filter(s=>s.endsWith(".json")).sort();for(const s of a)try{const i=JSON.parse(Z(A(r,s),"utf-8"));if(i===null||typeof i!="object"||Array.isArray(i)||!("agents"in i)){n.push(s);continue}if(!Array.isArray(i.agents)){t.push({file:s,error:"agents is not an array"});continue}if(i.agents.length===0){t.push({file:s,error:"agents array is empty"});continue}for(const l of i.agents)e.push({entry:l,file:s})}catch(i){t.push({file:s,error:i instanceof Error?i.message:String(i)})}return{entries:e,fileErrors:t,skipped:n}}function b(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map(b).join(",")}]`;const e=r;return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${b(e[n])}`).join(",")}}`}function Le(r,e){return b(r)===b(e)}class mt{instances=[];configMap=new Map;rawConfigMap=new Map;reloadChain=Promise.resolve();sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;deletedAgentCleanups=new Set;upgradeChecker=null;skillSyncer=null;globalConfigStore;configDir=_.config;sharedOwnersCache=new se(_.data);installer=new Se;relaySecretResolver;auditProducer=Ae();async start(e){const t=e??_.config;this.configDir=t,d.info("manager",`Loading configs from ${t}`),he(),L(),this.globalConfigStore=new de(A(_.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:n,fileErrors:a,skipped:s}=F(t);for(const o of a)d.error("manager",`Failed to load ${o.file}: ${o.error}`);for(const o of s)d.info("manager",`Skipped ${o}: not an agent config (no "agents" key)`);if(n.length===0&&a.length===0&&s.length===0){d.warn("manager",`No config files found in ${t}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const i=[];let l=a.length;for(const{entry:o,file:p}of n)try{const u=this.toRuntimeInstanceConfig(o);i.push({config:u,entry:o,file:p}),d.info("manager",`Loaded ${u.name} (${u.adapterType??"acp"}) from ${p}`)}catch(u){const w=typeof o?.name=="string"?o.name:"<unknown>";d.error("manager",`Invalid agent config in ${p} (name=${w}): ${u}`),l++}let c=0;if(i.length>0){const o=Oe();d.info("manager",`Starting ${i.length} agent(s), startup wait=${o}ms`);const p=m=>{this.instances=this.instances.filter(h=>h!==m)},u=i.map(({config:m,entry:h,file:y})=>{const g=this.createConfiguredInstance(m);return this.instances.push(g),this.configMap.set(m.name,m),this.rawConfigMap.set(m.name,{entry:h,file:y}),{config:m,instance:g,startPromise:this.prepareProviderRuntime(m,h).then(()=>g.start())}}),w=await Promise.all(u.map(async m=>{const h=await new Promise(y=>{let g=!1;const v=setTimeout(()=>{g||(g=!0,y({kind:"timeout"}))},o);m.startPromise.then(()=>{g||(g=!0,clearTimeout(v),y({kind:"started"}))}).catch(S=>{g||(g=!0,clearTimeout(v),y({kind:"failed",error:S}))})});return{task:m,outcome:h}}));for(const{task:m,outcome:h}of w){if(h.kind==="started"){this.restoreCachedSharedInstances(m.config);continue}if(h.kind==="failed"){if(O(h.error)){this.onAgentDeletedByPlatform(m.config.name);continue}p(m.instance),d.error("manager",`Failed to start ${m.config.name}: ${h.error}`);continue}c++,d.warn("manager",`Startup pending for ${m.config.name}, continue retrying in background`),m.startPromise.then(()=>{d.info("manager",`Delayed start succeeded: ${m.config.name}`),this.restoreCachedSharedInstances(m.config)}).catch(y=>{if(O(y)){this.onAgentDeletedByPlatform(m.config.name);return}p(m.instance),d.error("manager",`Delayed start failed: ${m.config.name}: ${y}`)})}if(this.instances.length>0){const m=Math.max(0,this.instances.length-c);d.info("manager",`${m}/${i.length} agent(s) running now`)}c>0&&d.warn("manager",`${c} agent(s) still connecting in background`)}if(this.instances.length===0&&i.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.configMap.size===0)return;const e=[...this.configMap.values()].map(t=>({apiKey:t.aibot.apiKey,wsUrl:t.aibot.url}));this.upgradeChecker||(this.upgradeChecker=new ce(e,()=>this.instances.some(t=>t.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(t=>t.hasPendingOrBackgroundWork())),await this.upgradeChecker.start()),this.skillSyncer||(this.skillSyncer=new le(e,_.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start())}refreshOwnerLibrarySkills(){const e=new Map,t=n=>{let a;try{a=n.skillsSyncGroupKey()}catch(i){d.warn("manager",`skillsSyncGroupKey failed for ${n.name}: ${i}`);return}const s=e.get(a)??[];s.push(n),e.set(a,s)};for(const n of this.instances)t(n);for(const n of this.sharedInstances.values())t(n);for(const[n,a]of e){let s=!1;const i=[];for(const l of a){if(s){i.push(l);continue}let c=!1;try{c=l.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(o){d.warn("manager",`owner library skills reporter threw group=${n} agent=${l.name}: ${o}`)}if(c){s=!0;continue}d.warn("manager",`owner library skills reporter failed group=${n} agent=${l.name}; trying next`)}if(!s){d.warn("manager",`owner library skills: no reporter succeeded group=${n}`);continue}for(const l of i)try{l.adoptSkillsWireHashFromDisk()}catch(c){d.warn("manager",`adoptSkillsWireHashFromDisk failed for ${l.name}: ${c}`)}}}async stop(){d.info("manager","Stopping all agents..."),this.stopping=!0,this.upgradeChecker?.stop(),this.skillSyncer?.stop(),await Promise.allSettled([...this.shareSyncChains.values()]),this.shareSyncChains.clear();const e=[...this.sharedInstances.values()];this.sharedInstances.clear(),await Promise.allSettled([...this.instances.map(t=>t.stop()),...e.map(t=>t.stop())]),await this.globalConfigStore?.flush(),await this.auditProducer.stop({timeoutMs:5e3}).catch(()=>!1),this.instances=[],L(),d.info("manager","All stopped")}onShareSet(e,t){this.sharedOwnersCache.save(e.name,t);const a=(this.shareSyncChains.get(e.name)??Promise.resolve()).catch(()=>{}).then(()=>this.syncSharedInstances(e,t));this.shareSyncChains.set(e.name,a)}async syncSharedInstances(e,t){if(this.stopping)return;const{toAdd:n,toRemove:a}=ae(e.name,this.sharedInstances.keys(),t);for(const s of n){if(this.stopping)break;const i=ie(e.name,s);try{const l=re(e,s),c=new D(l,this.globalConfigStore,this.auditProducer);this.sharedInstances.set(i,c),await c.start(),c.forceRefreshSkills(void 0,{force:!0}),d.info("manager",`shared instance started: ${i}`)}catch(l){this.sharedInstances.delete(i);const c=l instanceof Error?l.message:String(l);/Auth failed/i.test(c)?(this.sharedOwnersCache.remove(e.name,s),d.warn("manager",`shared instance auth rejected, removed from cache: ${i}`)):d.error("manager",`start shared instance failed ${i}: ${l}`)}}for(const{key:s}of a){const i=this.sharedInstances.get(s);i&&(this.sharedInstances.delete(s),i.stop().catch(l=>d.error("manager",`stop shared instance failed ${s}: ${l}`)),d.info("manager",`shared instance stopped: ${s}`))}}restoreCachedSharedInstances(e){const t=this.sharedOwnersCache.load(e.name);t.length!==0&&(d.info("manager",`restoring ${t.length} cached shared instance(s) for ${e.name}`),this.onShareSet(e,t))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){await this.addAgentInternal(e,"agents.json"),this.persistAgentsConfig(),await this.ensureAuxServices(),d.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,t){const n=this.toRuntimeInstanceConfig(e);if(this.instances.some(a=>a.name===n.name))throw new Error(`Agent "${n.name}" already exists`);await this.startInstanceFromConfig(n,e,t)}createConfiguredInstance(e){const t=new D(e,this.globalConfigStore,this.auditProducer);return t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),t.setShareSetHandler(n=>this.onShareSet(e,n)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(e.name)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(n=>this.setAgentProvider(e.name,n)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},applyEnable:(n,a)=>{const s=this.relayStateApplier;return s?s.applyEnable(e.name,n,a):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const n=this.relayStateApplier;return n?n.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>this.getAgentProvider(e.name)),t}async prepareProviderRuntime(e,t){const n=this.resolveAgentProvider(t.provider);N(t.client_type)&&n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()&&await H(e.name,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()})}async startInstanceFromConfig(e,t,n){await this.prepareProviderRuntime(e,t);const a=this.createConfiguredInstance(e);await a.start(),this.instances.push(a),this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:t,file:n}),this.relayEnvSettledHandler?.()}async removeAgent(e){if(!this.instances.some(t=>t.name===e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.removeAgentInternal(e),this.persistAgentsConfig(),d.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,t){const n=this.instances.findIndex(l=>l.name===e),a=n===-1?void 0:this.instances[n];n!==-1&&this.instances.splice(n,1),this.configMap.delete(e),this.rawConfigMap.delete(e);const s=this.shareSyncChains.get(e);this.shareSyncChains.delete(e),s&&await s.catch(()=>{});const i=`${e}#shared:`;for(const[l,c]of[...this.sharedInstances.entries()])l.startsWith(i)&&(this.sharedInstances.delete(l),c.stop().catch(o=>d.error("manager",`stop shared instance failed ${l}: ${o}`)));t?.keepShareCache||this.sharedOwnersCache.delete(e),a&&await a.stop(),t?.keepShareCache||await q(e).catch(()=>{})}onAgentDeletedByPlatform(e){this.stopping||this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),(async()=>{try{if(!(this.rawConfigMap.has(e)||this.instances.some(n=>n.name===e)))return;d.warn("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`),await this.removeAgentInternal(e),this.persistAgentsConfig(),d.info("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406\uFF08agents.json \u5DF2\u79FB\u9664\u8BE5\u6761\u76EE\uFF09`)}catch(t){d.error("manager",`cleanup for deleted agent "${e}" failed: ${t}`)}finally{this.deletedAgentCleanups.delete(e)}})())}persistAgentsConfig(){const e=A(this.configDir,"agents.json");try{const t=[];for(const[,a]of this.configMap){const s=this.rawConfigMap.get(a.name)?.entry.provider;t.push({name:a.name,ws_url:a.aibot.url,agent_id:a.aibot.agentId,api_key:a.aibot.apiKey,client_type:a.aibot.clientType,...s?{provider:s}:{}})}te(e,JSON.stringify({agents:t},null,4)+`
|
|
2
|
-
`,"utf-8")}catch(t){
|
|
1
|
+
import{readFileSync as se,readdirSync as ie,writeFileSync as oe}from"node:fs";import{join as b}from"node:path";import{homedir as ce}from"node:os";import{AgentInstance as q}from"./bridge/bridge.js";import{buildSharedInstanceConfig as le,diffSharedOwners as de,sharedInstanceKey as pe,SharedOwnersCache as ue}from"./manager-share-config.js";import{isAgentDeletedError as B}from"./core/aibot/errors.js";import{GRIX_PATHS as w,log as l}from"./core/log/index.js";import{resolveClientVersion as me}from"./core/util/client-version.js";import{UpgradeChecker as ge}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as fe}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as he}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as _e}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as ye}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as we}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as Se}from"./core/aibot/types.js";import{buildReportedSkills as ke,logDefaultSkillsCheck as be,cleanupProjectedSkills as U}from"./default-skills/index.js";import{supportsKiroCwRelay as F,supportsNonMitmRelayConfig as ve}from"./core/config/provider-env.js";import{ensureKiroRelay as K,stopKiroRelay as Q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as W}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as G}from"./core/runtime/cursor-resolve.js";import{getCliVersion as Ae,resolveCliPath as Ce}from"./core/util/cli-probe.js";import{AgentInstaller as xe}from"./core/installer/installer.js";import{reportInstallFailure as $e}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Ie}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as Te}from"./adapter/codex/config-overrides.js";import{resolveCodexDirectHome as Ee}from"./adapter/codex/direct-home.js";function z(n){if(n)return{...n.provider_id?.trim()?{providerId:n.provider_id.trim()}:{},...n.base_url?.trim()?{baseUrl:n.base_url.trim()}:{},...n.quota_base_url?.trim()?{quotaBaseUrl:n.quota_base_url.trim()}:{},...n.api_key?.trim()?{apiKey:n.api_key.trim()}:{},...n.model?.trim()?{model:n.model.trim()}:{},...n.fast_model?.trim()?{fastModel:n.fast_model.trim()}:{},...n.effort?.trim()?{effort:n.effort.trim()}:{}}}const Pe=8e3;function je(){const n=W();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:G()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:n.command},{clientType:"agy",command:"agy"},{clientType:"deepseek",command:"dsh"}]}async function Me(){return Promise.all(je().map(async n=>{const e=await Ce(n.command);if(!e)return{client_type:n.clientType,command:n.command,installed:!1,path:null,version:null};const t=await Ae(e,n.versionArgs??["--version"]);return{client_type:n.clientType,command:n.command,installed:!0,path:e,version:t.version,error:t.error}}))}function Re(n){switch(n){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:G()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=W();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${n}`)}}function v(n,e){return String(n??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function De(n){return b(w.data,`session-bindings-${v(n,"unknown")}.json`)}function Oe(n,e){return b(w.data,`session-bindings-${v(n,e)}.json`)}function He(n,e){return b(w.data,`active-events-${v(n,e)}.json`)}function Le(n,e){const t=v(n,"agent"),r=v(e,"unknown");return b(w.data,`terminal-outbox-${t}-${r}.json`)}function Ne(...n){const e=[],t=new Set;for(const r of n)for(const a of r??[]){const c=String(a??"").trim(),s=c.toLowerCase();!c||t.has(s)||(t.add(s),e.push(c))}return e.length>0?e:void 0}function qe(n,e){const t={claude:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},"deepseek-harness":{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0}},r=t[n]??t.acp;return{maxConcurrent:e?.max_concurrent??r.maxConcurrent??1,maxQueued:e?.max_queued??r.maxQueued??3,queueTimeoutMs:e?.queue_timeout_ms??r.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function Be(n,e={}){const t=me(),r=String(n.client_type??"").trim().toLowerCase(),a=Re(r),c=r==="deepseek"?n.dsh?.integration_mode??"profile_bridge":void 0,s=c==="embedded_jsonrpc",p=String(n.ws_url??"").trim(),o="get_session_usage",i="get_rate_limits",h="get_agent_global_config",g=Se;if(!n.name?.trim())throw new Error("agent name is required");if(!p)throw new Error(`agent ${n.name}: ws_url is required`);if(!n.agent_id?.trim())throw new Error(`agent ${n.name}: agent_id is required`);if(!n.api_key?.trim())throw new Error(`agent ${n.name}: api_key is required`);const d=a.adapterType,u=d==="acp",y=r==="qwen",m={...a.options??{}};if(d==="deepseek-harness"&&(m.integrationMode=c,m.dshProfile=n.dsh?.profile?.trim()||"web",m.autoInstallBridge=n.dsh?.auto_install_bridge??!s,m.autoStartProfile=n.dsh?.auto_start_profile??!s),d==="deepseek-harness"&&n.provider?.model?.trim()&&(m.defaultModel=n.provider.model.trim()),n.codex_config_overrides!==void 0){if(d!=="codex")throw new Error(`agent ${n.name}: codex_config_overrides is only supported for client_type=codex`);Te(n.codex_config_overrides,`agent ${n.name}: codex_config_overrides`),m.codexConfigOverrides=n.codex_config_overrides}if(d==="codex"&&n.provider?.wire_api!==void 0){const _=n.provider;if(_.wire_api!=="responses"||!_.base_url?.trim()||!_.api_key?.trim()||!_.model?.trim()||!_.catalog_version?.trim()||!_.catalog_sha256?.trim()||!_.catalog_json?.trim())throw Object.assign(new Error(`agent ${n.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const N=Ee(w.data,n.name);m.codexHome=N,m.codexDirect={codexHome:N,config:{baseUrl:_.base_url.trim(),model:_.model.trim(),..._.reasoning_effort?.trim()?{reasoningEffort:_.reasoning_effort.trim()}:{},token:_.api_key.trim()},catalog:{version:_.catalog_version.trim(),sha256:_.catalog_sha256.trim(),json:_.catalog_json}}}const f=d==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",o,i]}:null,k=d==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",o,i]}:null,S=y?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o],adapterHint:"qwen/base"}:null,C=d==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","get_context","file_list","create_folder",o,i]}:null,x=d==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,$=d==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",i]}:null,j=d==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,I=d==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,T=d==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,E=d==="deepseek-harness"?{adapterHint:s?"deepseek/jsonrpc-v1":"deepseek/grix-bridge-v1",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","set_mode","set_preset","set_profile","create_profile",o,i,"exec_approve","exec_reject","permission_approve","permission_reject","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals"]}:null,M=new Set(["hermes","reasonix","kimi","copilot"]),J=u&&!M.has(r),X=u&&!y?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",...J?[o]:[]]}:null,Y=r==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",o,i]}:null,Z=d==="codex"||d==="claude"||d==="opencode"||d==="deepseek-harness"||r==="gemini"?["session_control","set_model","set_mode",...d==="deepseek-harness"?["set_provider","set_preset","set_profile","create_profile","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins"]:[],...d==="claude"?["set_reasoning_effort"]:[]]:void 0,ee=d==="cursor"||d==="opencode"||d==="openhuman"||d==="agy"||u&&M.has(r)?[i]:[o,i];u&&m.raw_transport===void 0&&(m.raw_transport=r==="gemini");const te=`${r}/base`,P=_e(d,r),ne=P==="kiro"?void 0:process.cwd(),R={...process.env,...n.env},D=ke({mode:P,projectDir:ne,env:R}),O=D.filter(_=>_.source==="connector").map(_=>_.name);O.length>0&&!e.quiet&&l.info("manager",`[${n.name}] injecting connector skills: [${O.join(", ")}]`);const H=ye(D,w.skills);let re=H.length>0?H:void 0;const ae=we({skillsDir:w.skills,mode:P,home:ce(),env:R}),L=z(n.provider);return{name:n.name,adapterType:d,aibot:{url:p,agentId:n.agent_id,apiKey:n.api_key,clientType:r,clientVersion:t,adapterHint:E?.adapterHint??a.adapterHint??S?.adapterHint??C?.adapterHint??x?.adapterHint??$?.adapterHint??I?.adapterHint??T?.adapterHint??te,capabilities:E?.capabilities??f?.capabilities??j?.capabilities??C?.capabilities??x?.capabilities??$?.capabilities??I?.capabilities??T?.capabilities??S?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Ne(E?.localActions??f?.localActions??j?.localActions??k?.localActions??C?.localActions??x?.localActions??$?.localActions??I?.localActions??T?.localActions??S?.localActions??Y?.localActions??X?.localActions??["exec_approve","exec_reject"],Z,ee,["connector_rollback","connector_upgrade_push",h,"configure_gateway_provider","skill_upload","skill_enable","skill_disable","skill_refresh",...g]),skills:re,librarySkills:ae,terminalOutboxPath:Le(n.name,n.agent_id)},agent:{command:s?"dsh-jsonrpc-agent":a.command,args:[...a.args??[],...n.args??[]],env:n.env,clientType:r,...L?{provider:L}:{}},adapterOptions:m,acpAuthMethod:m.auth_method,acpInitialMode:m.initial_mode,acpMcpTools:m.acp_mcp_tools,promptTimeoutMs:n.prompt_timeout_ms,bindingsPath:De(n.agent_id),legacyBindingsPath:Oe(n.name,n.agent_id),activeEventStorePath:He(n.name,n.agent_id),...a.enableSessionBinding||u?{enableSessionBinding:!0}:{},...a.autoInjectArgs||r==="reasonix"&&n.provider?.model?.trim()?{autoInjectArgs:{...a.autoInjectArgs??{},...r==="reasonix"&&n.provider?.model?.trim()?{model:n.provider.model.trim()}:{}}}:{},poolMaxSize:n.pool?.maxSize??(d==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:n.pool?.idleTimeoutMs,eventQueue:qe(d,n.event_queue),logDir:w.log,providerBaseUrl:n.provider_base_url?.trim()||void 0,providerApiKey:n.provider_api_key?.trim()||void 0}}function Ue(){const n=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(n);return Number.isFinite(e)&&e>=500?Math.floor(e):Pe}function V(n){const e=[],t=[],r=[],a=ie(n).filter(c=>c.endsWith(".json")).sort();for(const c of a)try{const s=JSON.parse(se(b(n,c),"utf-8"));if(s===null||typeof s!="object"||Array.isArray(s)||!("agents"in s)){r.push(c);continue}if(!Array.isArray(s.agents)){t.push({file:c,error:"agents is not an array"});continue}if(s.agents.length===0){t.push({file:c,error:"agents array is empty"});continue}for(const p of s.agents)e.push({entry:p,file:c})}catch(s){t.push({file:c,error:s instanceof Error?s.message:String(s)})}return{entries:e,fileErrors:t,skipped:r}}function A(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(A).join(",")}]`;const e=n;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${A(e[r])}`).join(",")}}`}function Fe(n,e){return A(n)===A(e)}class yt{instances=[];configMap=new Map;rawConfigMap=new Map;reloadChain=Promise.resolve();sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;deletedAgentCleanups=new Set;upgradeChecker=null;skillSyncer=null;globalConfigStore;configDir=w.config;sharedOwnersCache=new ue(w.data);installer=new xe;relaySecretResolver;auditProducer=Ie();async start(e){const t=e??w.config;this.configDir=t,l.info("manager",`Loading configs from ${t}`),be(),U(),this.globalConfigStore=new he(b(w.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:r,fileErrors:a,skipped:c}=V(t);for(const i of a)l.error("manager",`Failed to load ${i.file}: ${i.error}`);for(const i of c)l.info("manager",`Skipped ${i}: not an agent config (no "agents" key)`);if(r.length===0&&a.length===0&&c.length===0){l.warn("manager",`No config files found in ${t}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const s=[];let p=a.length;for(const{entry:i,file:h}of r)try{const g=this.toRuntimeInstanceConfig(i);s.push({config:g,entry:i,file:h}),l.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${h}`)}catch(g){const d=typeof i?.name=="string"?i.name:"<unknown>";l.error("manager",`Invalid agent config in ${h} (name=${d}): ${g}`),p++}let o=0;if(s.length>0){const i=Ue();l.info("manager",`Starting ${s.length} agent(s), startup wait=${i}ms`);const h=u=>{this.instances=this.instances.filter(y=>y!==u)},g=s.map(({config:u,entry:y,file:m})=>{const f=this.createConfiguredInstance(u);return this.instances.push(f),this.configMap.set(u.name,u),this.rawConfigMap.set(u.name,{entry:y,file:m}),{config:u,instance:f,startPromise:this.prepareProviderRuntime(u,y).then(()=>f.start())}}),d=await Promise.all(g.map(async u=>{const y=await new Promise(m=>{let f=!1;const k=setTimeout(()=>{f||(f=!0,m({kind:"timeout"}))},i);u.startPromise.then(()=>{f||(f=!0,clearTimeout(k),m({kind:"started"}))}).catch(S=>{f||(f=!0,clearTimeout(k),m({kind:"failed",error:S}))})});return{task:u,outcome:y}}));for(const{task:u,outcome:y}of d){if(y.kind==="started"){this.restoreCachedSharedInstances(u.config);continue}if(y.kind==="failed"){if(B(y.error)){this.onAgentDeletedByPlatform(u.config.name);continue}h(u.instance),l.error("manager",`Failed to start ${u.config.name}: ${y.error}`);continue}o++,l.warn("manager",`Startup pending for ${u.config.name}, continue retrying in background`),u.startPromise.then(()=>{l.info("manager",`Delayed start succeeded: ${u.config.name}`),this.restoreCachedSharedInstances(u.config)}).catch(m=>{if(B(m)){this.onAgentDeletedByPlatform(u.config.name);return}h(u.instance),l.error("manager",`Delayed start failed: ${u.config.name}: ${m}`)})}if(this.instances.length>0){const u=Math.max(0,this.instances.length-o);l.info("manager",`${u}/${s.length} agent(s) running now`)}o>0&&l.warn("manager",`${o} agent(s) still connecting in background`)}if(this.instances.length===0&&s.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.configMap.size===0)return;const e=[...this.configMap.values()].map(t=>({apiKey:t.aibot.apiKey,wsUrl:t.aibot.url}));this.upgradeChecker||(this.upgradeChecker=new ge(e,()=>this.instances.some(t=>t.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(t=>t.hasPendingOrBackgroundWork())),await this.upgradeChecker.start()),this.skillSyncer||(this.skillSyncer=new fe(e,w.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start())}refreshOwnerLibrarySkills(){const e=new Map,t=r=>{let a;try{a=r.skillsSyncGroupKey()}catch(s){l.warn("manager",`skillsSyncGroupKey failed for ${r.name}: ${s}`);return}const c=e.get(a)??[];c.push(r),e.set(a,c)};for(const r of this.instances)t(r);for(const r of this.sharedInstances.values())t(r);for(const[r,a]of e){let c=!1;const s=[];for(const p of a){if(c){s.push(p);continue}let o=!1;try{o=p.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(i){l.warn("manager",`owner library skills reporter threw group=${r} agent=${p.name}: ${i}`)}if(o){c=!0;continue}l.warn("manager",`owner library skills reporter failed group=${r} agent=${p.name}; trying next`)}if(!c){l.warn("manager",`owner library skills: no reporter succeeded group=${r}`);continue}for(const p of s)try{p.adoptSkillsWireHashFromDisk()}catch(o){l.warn("manager",`adoptSkillsWireHashFromDisk failed for ${p.name}: ${o}`)}}}async stop(){l.info("manager","Stopping all agents..."),this.stopping=!0,this.upgradeChecker?.stop(),this.skillSyncer?.stop(),await Promise.allSettled([...this.shareSyncChains.values()]),this.shareSyncChains.clear();const e=[...this.sharedInstances.values()];this.sharedInstances.clear(),await Promise.allSettled([...this.instances.map(t=>t.stop()),...e.map(t=>t.stop())]),await this.globalConfigStore?.flush(),await this.auditProducer.stop({timeoutMs:5e3}).catch(()=>!1),this.instances=[],U(),l.info("manager","All stopped")}onShareSet(e,t){this.sharedOwnersCache.save(e.name,t);const a=(this.shareSyncChains.get(e.name)??Promise.resolve()).catch(()=>{}).then(()=>this.syncSharedInstances(e,t));this.shareSyncChains.set(e.name,a)}async syncSharedInstances(e,t){if(this.stopping)return;const{toAdd:r,toRemove:a}=de(e.name,this.sharedInstances.keys(),t);for(const c of r){if(this.stopping)break;const s=pe(e.name,c);try{const p=le(e,c),o=new q(p,this.globalConfigStore,this.auditProducer);this.sharedInstances.set(s,o),await o.start(),o.forceRefreshSkills(void 0,{force:!0}),l.info("manager",`shared instance started: ${s}`)}catch(p){this.sharedInstances.delete(s);const o=p instanceof Error?p.message:String(p);/Auth failed/i.test(o)?(this.sharedOwnersCache.remove(e.name,c),l.warn("manager",`shared instance auth rejected, removed from cache: ${s}`)):l.error("manager",`start shared instance failed ${s}: ${p}`)}}for(const{key:c}of a){const s=this.sharedInstances.get(c);s&&(this.sharedInstances.delete(c),s.stop().catch(p=>l.error("manager",`stop shared instance failed ${c}: ${p}`)),l.info("manager",`shared instance stopped: ${c}`))}}restoreCachedSharedInstances(e){const t=this.sharedOwnersCache.load(e.name);t.length!==0&&(l.info("manager",`restoring ${t.length} cached shared instance(s) for ${e.name}`),this.onShareSet(e,t))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){await this.addAgentInternal(e,"agents.json"),this.persistAgentsConfig(),await this.ensureAuxServices(),l.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,t){const r=this.toRuntimeInstanceConfig(e);if(this.instances.some(a=>a.name===r.name))throw new Error(`Agent "${r.name}" already exists`);await this.startInstanceFromConfig(r,e,t)}createConfiguredInstance(e){const t=new q(e,this.globalConfigStore,this.auditProducer);return t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),t.setShareSetHandler(r=>this.onShareSet(e,r)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(e.name)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(r=>this.setAgentProvider(e.name,r)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},applyEnable:(r,a)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,r,a):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const r=this.relayStateApplier;return r?r.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>z(this.getAgentProvider(e.name))),t}async prepareProviderRuntime(e,t){const r=this.resolveAgentProvider(t.provider);F(t.client_type)&&r?.base_url?.trim()&&r?.api_key?.trim()&&r?.model?.trim()&&await K(e.name,{baseUrl:r.base_url.trim(),apiKey:r.api_key.trim(),model:r.model.trim()})}async startInstanceFromConfig(e,t,r){await this.prepareProviderRuntime(e,t);const a=this.createConfiguredInstance(e);await a.start(),this.instances.push(a),this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:t,file:r}),this.relayEnvSettledHandler?.()}async removeAgent(e){if(!this.instances.some(t=>t.name===e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,t){const r=this.instances.findIndex(p=>p.name===e),a=r===-1?void 0:this.instances[r];r!==-1&&this.instances.splice(r,1),this.configMap.delete(e),this.rawConfigMap.delete(e);const c=this.shareSyncChains.get(e);this.shareSyncChains.delete(e),c&&await c.catch(()=>{});const s=`${e}#shared:`;for(const[p,o]of[...this.sharedInstances.entries()])p.startsWith(s)&&(this.sharedInstances.delete(p),o.stop().catch(i=>l.error("manager",`stop shared instance failed ${p}: ${i}`)));t?.keepShareCache||this.sharedOwnersCache.delete(e),a&&await a.stop(),t?.keepShareCache||await Q(e).catch(()=>{})}onAgentDeletedByPlatform(e){this.stopping||this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),(async()=>{try{if(!(this.rawConfigMap.has(e)||this.instances.some(r=>r.name===e)))return;l.warn("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`),await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406\uFF08agents.json \u5DF2\u79FB\u9664\u8BE5\u6761\u76EE\uFF09`)}catch(t){l.error("manager",`cleanup for deleted agent "${e}" failed: ${t}`)}finally{this.deletedAgentCleanups.delete(e)}})())}persistAgentsConfig(){const e=b(this.configDir,"agents.json");try{const t=[];for(const[,a]of this.configMap){const c=this.rawConfigMap.get(a.name)?.entry.provider;t.push({name:a.name,ws_url:a.aibot.url,agent_id:a.aibot.agentId,api_key:a.aibot.apiKey,client_type:a.aibot.clientType,...c?{provider:c}:{}})}oe(e,JSON.stringify({agents:t},null,4)+`
|
|
2
|
+
`,"utf-8")}catch(t){l.error("manager",`Failed to persist agents config: ${t}`)}}isAgentBusy(e){return this.instances.find(r=>r.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const t=this.instances.find(r=>r.name===e);return t?(t.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}relayStateApplier;setRelayStateApplier(e){this.relayStateApplier=e}reportRelayStateLocalChange(e){this.instances.find(r=>r.name===e)?.reportRelayStateLocalChange()}setRelaySecretResolver(e){this.relaySecretResolver=e}resolveAgentProvider(e){if(!e?.api_key_ref?.trim())return e;const t=e.api_key_ref.trim(),r=this.relaySecretResolver?.(t);if(!r)throw Object.assign(new Error(`relay credential "${t}" is unavailable`),{code:"RELAY_SECRET_UNAVAILABLE"});return{...e,api_key:r}}toRuntimeInstanceConfig(e,t={}){const r=this.resolveAgentProvider(e.provider);return Be(r===e.provider?e:{...e,provider:r},t)}getAgentProvider(e){return this.resolveAgentProvider(this.rawConfigMap.get(e)?.entry.provider)}async restartAgent(e){const t=this.rawConfigMap.get(e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,t.entry,t.file),l.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,t,r){const a=this.rawConfigMap.get(e);if(!a)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const c=String(a.entry.client_type??"").trim().toLowerCase();F(c)&&(t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()?await K(e,{baseUrl:t.base_url.trim(),apiKey:t.api_key.trim(),model:t.model.trim()}):await Q(e));const s=t?.api_key_ref?.trim()?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="api_key")):t,p={...a.entry,provider:s};if(r?.deferRestart){this.rawConfigMap.set(e,{...a,entry:p}),this.instances.find(o=>o.name===e)?.markRelayEnvStale(),this.persistAgentsConfig(),l.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}await this.replaceInstance(e,p,a.file),this.persistAgentsConfig(),l.info("manager",`Updated provider config for agent: ${e}`)}hasDirectRelayConfig(e){const t=this.rawConfigMap.get(e)?.entry.provider;return!!(t?.api_key_ref?.trim()||t?.api_key?.trim())}getDirectRelayConfigAgentNames(){return[...this.rawConfigMap.entries()].filter(([,e])=>!!e.entry.provider&&(ve(e.entry.client_type)||["claude","codex"].includes(String(e.entry.client_type??"").trim().toLowerCase()))).map(([e])=>e)}async fetchRelayCredential(e,t){const r=this.instances.find(a=>a.name===e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return r.fetchRelayCredential(t)}async clearDirectProviderConfigs(){const e=this.getDirectRelayConfigAgentNames(),t=[];for(const r of e)try{await this.setAgentProvider(r,void 0,{deferRestart:this.isAgentBusy(r)}),t.push(r)}catch(a){l.warn("manager",`Failed to clear provider config for "${r}": ${a instanceof Error?a.message:String(a)}`)}return t}async replaceInstance(e,t,r){const a=this.toRuntimeInstanceConfig(t);await this.removeAgentInternal(e,{keepShareCache:!0}),await this.startInstanceFromConfig(a,t,r),this.restoreCachedSharedInstances(a)}async reload(){const e=this.reloadChain.catch(()=>{}).then(()=>this.doReload());return this.reloadChain=e.catch(()=>{}),e}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:t,skipped:r}=V(this.configDir);for(const o of r)l.info("manager",`reload: skipped ${o}: not an agent config (no "agents" key)`);if(t.length>0){const o=t.map(i=>`${i.file}: ${i.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${t.length} config file(s) failed to parse [${o}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const a=[];for(const{entry:o}of e)try{this.toRuntimeInstanceConfig(o,{quiet:!0})}catch(i){const h=o?.name,g=typeof h=="string"&&h.trim()?h:"<unknown>";a.push({name:g,error:i instanceof Error?i.message:String(i)})}if(a.length>0){const o=a.map(i=>`${i.name}: ${i.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${a.length} agent config(s) invalid [${o}]`),{code:"RELOAD_UNSAFE"})}const c=new Map;for(const o of e){const i=String(o.entry?.name??"").trim();i&&(c.has(i)&&l.warn("manager",`reload: duplicate agent name "${i}", last one wins`),c.set(i,o))}const s={added:[],removed:[],restarted:[],unchanged:[],failed:[]},p=new Set(this.rawConfigMap.keys());for(const o of p)if(!c.has(o))try{await this.removeAgentInternal(o),s.removed.push(o)}catch(i){s.failed.push({name:o,error:i instanceof Error?i.message:String(i)})}for(const[o,i]of c){const h=this.rawConfigMap.get(o);if(h)if(Fe(h.entry,i.entry))this.rawConfigMap.set(o,i),s.unchanged.push(o);else try{await this.replaceInstance(o,i.entry,i.file),s.restarted.push(o)}catch(g){s.failed.push({name:o,error:g instanceof Error?g.message:String(g)})}else try{await this.addAgentInternal(i.entry,i.file),s.added.push(o)}catch(g){s.failed.push({name:o,error:g instanceof Error?g.message:String(g)})}}return l.info("manager",`reload done: +${s.added.length} -${s.removed.length} ~${s.restarted.length} =${s.unchanged.length} !${s.failed.length}`),await this.ensureAuxServices(),s}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Ke(this.instances,e)}async probeOne(e,t={}){return Qe(this.instances,e,t)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const t=await this.installer.install(e);return $e(t),t}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Ke(n,e){const t=e.concurrency??4,r=Date.now(),a=new Array(n.length);await new Promise(i=>{let h=0,g=0;const d=n.length;if(d===0){i();return}function u(f){const k=n[f];k.probe(e).then(S=>{a[f]=S,y()},S=>{a[f]={agent_name:k.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:S?.message??String(S)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},y()})}function y(){g++,h<d?u(h++):g===d&&i()}const m=Math.min(t,d);for(let f=0;f<m;f++)u(h++)});const c=a.filter(i=>i.status==="healthy").length,s=a.filter(i=>i.status==="degraded").length,p=a.filter(i=>i.status==="unavailable").length,o=await Me();return{ok:c===a.length&&a.length>0,total:a.length,healthy:c,degraded:s,unavailable:p,installed_clients:o,agents:a,probed_at:r,duration_ms:Date.now()-r}}async function Qe(n,e,t){const r=n.find(a=>a.name===e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return r.probe(t)}export{yt as Manager,z as normalizeAgentProviderForRuntime,Me as probeInstalledClientCommands,Ke as probeInstances,Qe as probeOneInstance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(
|
|
1
|
+
function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
|