grix-connector 3.26.7 → 3.26.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  2. package/dist/adapter/claude/claude-tools.js +1 -1
  3. package/dist/adapter/claude/claude-worker-client.js +1 -1
  4. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  5. package/dist/adapter/claude/result-timeout.js +1 -1
  6. package/dist/adapter/claude/skill-scanner.js +2 -2
  7. package/dist/adapter/deepseek-harness/audit-boundary.js +2 -0
  8. package/dist/adapter/deepseek-harness/bridge-installer.js +5 -0
  9. package/dist/adapter/deepseek-harness/bridge-session-reliability.js +1 -0
  10. package/dist/adapter/deepseek-harness/dsh-provider-config.js +8 -0
  11. package/dist/adapter/deepseek-harness/dsml-text-filter.js +1 -0
  12. package/dist/adapter/deepseek-harness/event-mapper.js +1 -0
  13. package/dist/adapter/deepseek-harness/grix-jsonrpc.cordis.yml +61 -0
  14. package/dist/adapter/deepseek-harness/index.js +1 -0
  15. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -0
  16. package/dist/adapter/deepseek-harness/jsonrpc-client.js +4 -0
  17. package/dist/adapter/deepseek-harness/plugin-manager.js +2 -0
  18. package/dist/adapter/deepseek-harness/probe.js +1 -0
  19. package/dist/adapter/deepseek-harness/process-runtime.js +1 -0
  20. package/dist/adapter/deepseek-harness/profile-bridge-protocol.js +1 -0
  21. package/dist/adapter/deepseek-harness/profile-catalog.js +1 -0
  22. package/dist/adapter/deepseek-harness/profile-resolver.js +1 -0
  23. package/dist/adapter/deepseek-harness/profile-runtime.js +3 -0
  24. package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -0
  25. package/dist/adapter/deepseek-harness/prompt-builder.js +5 -0
  26. package/dist/adapter/deepseek-harness/runtime.js +0 -0
  27. package/dist/adapter/deepseek-harness/system-prompt.js +2 -0
  28. package/dist/adapter/deepseek-harness/toolbar-actions.js +1 -0
  29. package/dist/adapter/deepseek-harness/toolbar-state.js +1 -0
  30. package/dist/adapter/deepseek-harness/turn-correlator.js +1 -0
  31. package/dist/adapter/deepseek-harness/types.js +0 -0
  32. package/dist/adapter/deepseek-harness/usage.js +1 -0
  33. package/dist/assets/dsh-bridge/grix-dsh-bridge-3.26.11.tgz +0 -0
  34. package/dist/assets/dsh-bridge/manifest.json +9 -0
  35. package/dist/audit/adapters/deepseek-harness/deepseek-harness-audit-adapter.js +2 -0
  36. package/dist/audit/core/audit-state.js +1 -1
  37. package/dist/audit/worker/audit-recorder-worker-entry.js +1 -1
  38. package/dist/bridge/bridge.js +9 -9
  39. package/dist/bridge/deferred-events.js +1 -1
  40. package/dist/bridge/native-provider-sweep.js +1 -1
  41. package/dist/bridge/send-controller.js +1 -1
  42. package/dist/bridge/tool-card-utils.js +1 -1
  43. package/dist/core/access/allowlist-store.js +1 -1
  44. package/dist/core/aibot/binding-card-meta-cache.js +1 -1
  45. package/dist/core/config/provider-env.js +1 -1
  46. package/dist/core/file-ops/list-files.js +1 -1
  47. package/dist/core/installer/installer.js +9 -9
  48. package/dist/core/installer/manual-guide.js +2 -2
  49. package/dist/core/installer/registry.js +1 -1
  50. package/dist/core/persistence/session-binding-store.js +2 -2
  51. package/dist/core/skill-sync/enable-roots.js +1 -1
  52. package/dist/default-skills/index.js +1 -1
  53. package/dist/log.js +2 -2
  54. package/dist/manager.js +2 -2
  55. package/dist/mcp/stream-http/config.js +1 -1
  56. package/dist/mcp/stream-http/connection-binding.js +1 -1
  57. package/dist/mcp/stream-http/security.js +1 -1
  58. package/dist/mcp/stream-http/tool-executor.js +1 -1
  59. package/dist/mcp/stream-http/tool-registry.js +1 -1
  60. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  61. 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),d=n.get(r)??[];d.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=${d.length}`),d.push(t),n.set(r,d))}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 d=this.getMap(e),i=d.get(r);if(!i||i.length===0)return;d.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 s of i)try{t.captureEventRuntimeConfig(s),await t.deliverInboundEvent(s),this.deferredClaudeReplayRetries.delete(s.event_id)}catch(f){const p=f instanceof Error?f.message:String(f),u=this.deferredClaudeReplayRetries.get(s.event_id)??0;if(a.retriable?.(p)&&u<(a.retryMax??0)){this.deferredClaudeReplayRetries.set(s.event_id,u+1);const c=d.get(r)??[];c.some(o=>o.event_id===s.event_id)||(c.push(s),d.set(r,c)),l.warn(this.name,`replay retry ${u+1}/${a.retryMax} channel=${e} session_id=${r} event_id=${s.event_id} reason=${p}`),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(s.event_id),a.stopComposingOnError&&t.sendSessionComposing?.(r,!1),t.sendEventResult(s.event_id,"failed",p)}}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()].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.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])for(const[t,n]of r.entries()){const d=n.findIndex(i=>i.event_id===e);if(d>=0)return n.splice(d,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)}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}}}export{_ as DeferredEventManager};
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 e}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 c}from"../adapter/pi/pi-provider-config.js";async function u(r){if(r.hasProvider)return[];const o=[];if(r.adapterType==="pi"){const i=String(r.piConfigDir??"").trim()||e(n(),".pi","agent");return await c(i,f(r.agentName))&&o.push(e(i,"models.json")),o}const t=new Set(r.boundCwds.map(i=>i.trim()).filter(Boolean));for(const i of t)try{await d(r.command,i)&&o.push(i)}catch{}return o}export{u as sweepNativeProviderResidue};
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 f=500,d=140;function o(t){return typeof t=="string"?t.trim().replace(/\s+/g," "):t==null?"":typeof t=="number"||typeof t=="boolean"?String(t):""}function i(t,r){const e=o(t);return e.length<=r?e:r<=3?e.slice(0,r):`${e.slice(0,r-3)}...`}function l(t){const r=o(t);if(!r)return"";try{const e=JSON.parse(r),n=T(e);if(n)return n}catch{}return r}function a(t){const r=o(t);if(!r)return"";try{return T(JSON.parse(r))}catch{return""}}function T(t){if(!t||typeof t!="object"||Array.isArray(t))return"";const r=t;for(const e of["command","file_path","path","pattern","query","description","url","text"]){const n=o(r[e]);if(n)return n}return""}function _(t,r){const e=o(t)||"tool",n=l(r);return{summaryText:n?`${e}: ${i(n,140)}`:e,...n?{detailText:i(n,500)}:{}}}function p(t,r){const e=o(r);if(e==="(failed)")return{summaryText:"(failed)"};if(e.startsWith("(failed) ")){const u=e.slice(9),c=a(u);return{summaryText:c?`${i(c,140)} (failed)`:"(failed)",...c?{detailText:i(c,500)}:{}}}const n=a(e);if(n)return{summaryText:i(n,140),detailText:i(n,500)};const s=i(e,500);return{summaryText:t||"result",...s?{detailText:s}:{}}}function I(t,r,e){const n=new URLSearchParams;return n.set("d",JSON.stringify(e)),`[${t}](grix://card/${r}?${n.toString()})`}export{I as buildLocalGrixCardLink,p as buildToolResultCard,_ as buildToolUseCard,i as compactToolCardText,o as normalizeToolCardText};
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
- import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- const i=["available_models","available_modes","model_id","mode_id","available_efforts","effort","reasoning_effort","currentEffort","currentModelId","currentModeId","availableModels","availableModes","models","modes"],d=[["model_id","currentModelId"],["mode_id","currentModeId"],["effort","reasoning_effort"]];class c{toolbarMetaBySession=new Map;merge(r,e){if(!r)return e;if(e&&Array.isArray(e.available_models)&&e.available_models.length>0){const t={};for(const o of i)o in e&&(t[o]=e[o]);return this.toolbarMetaBySession.set(r,t),e}const l=this.toolbarMetaBySession.get(r);if(!l)return e;if(e)for(const[t,o]of d){const s=e[t],a=e[o],n=typeof s=="string"&&s||typeof a=="string"&&a||null;n&&(l[t]=n,l[o]=n)}return{...l,...e??{}}}delete(r){this.toolbarMetaBySession.delete(r)}}export{c as BindingCardMetaCache};
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 f,normalizeClaudeEnvEffort as u}from"./claude-direct-env.js";const c={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"},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","codewhale","hermes","pi","opencode"],p=["kiro"];function i(t){return t?.trim().toLowerCase().split("/",1)[0]??""}function K(t){const e=i(t);return!!e&&R.includes(e)}function P(t){const e=i(t);return!!e&&p.includes(e)}function d(t){return K(t)||P(t)}function O(t){const e=i(t);return!!e&&e in c}function A(t,e){if(!e)return{};const s=i(t);if(s==="claude"){const a=e.baseUrl?.trim(),l=e.apiKey?.trim(),I=e.model?.trim();if(!a||!l||!I)return{};const m=u(e.effort);return f({baseUrl:a,primaryModel:I,...e.fastModel?.trim()?{fastModel:e.fastModel.trim()}:{},...m?{effort:m}:{}},l)}const o=c[s];if(!o)return{};const r=e.baseUrl?.trim(),n=e.apiKey?.trim(),_=e.model?.trim();if(!r&&!n&&!_)return{};const E={...o.fixed??{}};return o.baseUrl&&r&&(E[o.baseUrl]=r),o.apiKey&&n&&(E[o.apiKey]=n),o.model&&_&&(E[o.model]=_),E}export{R as DIRECT_PROVIDER_CLIENT_TYPES,p as KIRO_CW_RELAY_CLIENT_TYPES,c as PROVIDER_ENV_SPECS,A as buildProviderEnv,K as supportsDirectProviderConfig,P as supportsKiroCwRelay,d as supportsNonMitmRelayConfig,O as supportsProviderEnv};
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 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1,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 v,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 k}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,e,t){super(e),this.name="InstallerError",this.code=n,this.output=t}}const T=64*1024,H=20,N=2,W=3e3;class lt{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:e}=n,t=Date.now();if(this.activeInstalls.has(e))return this.fail(e,"preflight",t,new u("INSTALL_IN_PROGRESS",`${e} is already being installed`));try{return await this._doInstall(n,t)}catch(i){this.activeInstalls.delete(e);const o=i instanceof Error?i.message:String(i);return m.error("installer",`${e} install unexpected error: ${o}`),{agentType:e,ok:!1,phase:"failed",error:{code:"INTERNAL",message:`Unexpected error: ${o}`},durationMs:Date.now()-t,output:""}}}async _doInstall(n,e){const{agentType:t}=n;let i;try{i=await V()}catch(s){const a=s instanceof Error?s.message:String(s);return this.fail(t,"preflight",e,new u("INTERNAL",`Environment detection failed: ${a}`))}m.info("installer",`Install request: ${t}
2
- ${F(i)}`);const o=q(i);if(!o.supported)return this.fail(t,"preflight",e,new u("ENVIRONMENT_UNSUPPORTED",`Current environment is not supported for automatic installation: ${o.reason}. Please install ${t} manually.`),i);if(this.setProgress(t,"preflight",e),!D(t))return this.fail(t,"preflight",e,new u("UNKNOWN_AGENT",`Unknown agent type: ${t}`),i);const l=S(t,this.os);if(!l){const s=this.getManualHint(t,this.os),a=s?`Installation of ${t} is not supported on ${this.os}. ${s}`:`Installation of ${t} is not supported on ${this.os}`;return this.fail(t,"preflight",e,new u("UNSUPPORTED_OS",a),i)}const c=O(t),p=await P(c),d=p?(await v(p)).version:null;if(p&&!n.force&&!n.dryRun){this.activeInstalls.delete(t);const s=Date.now()-e;return m.info("installer",`${t} already installed at ${p}${d?` (v${d})`:""}`),{agentType:t,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 ${t}: ${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=k(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(t,"preflight",e,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(t,"installing_prereq",e,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(t,"installing_prereq",e,new u("PREREQ_INSTALL_FAILED",L),i,r)}m.info("installer",`All prerequisites installed for ${t}`),r=await y(h,this.os)}}}if(n.dryRun){this.activeInstalls.delete(t);const s=k(r),a=this.getManualHint(t,this.os),g={agentType:t,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:t,os:this.os,env:i,missingPrereqs:s});return{agentType:t,ok:!0,phase:"completed",durationMs:Date.now()-e,output:"dry-run: no commands executed",environment:i,dryRun:g,manualGuide:I}}this.setProgress(t,"installing",e),m.info("installer",`Installing ${t}: ${l.command}`);let f;try{f=await this.executeWithRetry(l,t,e,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(t,"installing",e);try{f=await this.executeWithRetry(l.fallback,t,e,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(t,"installing",e,new u("FALLBACK_EXHAUSTED",`Both primary and fallback install methods failed.
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(t,"installing",e,new u(s.code,s.message,s.output),i,r):this.fail(t,"installing",e,new u("INTERNAL",s instanceof Error?s.message:String(s)),i,r)}{const s=(f??"").trim().split(`
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",`${t} \u5B89\u88C5\u547D\u4EE4\u8F93\u51FA(\u5C3E\u90E8):
8
- ${s||"<\u7A7A>"}`)}if(x(),!n.skipVerify&&!l.skipVerification){this.setProgress(t,"verifying",e),m.info("installer",`Verifying ${t} installation...`);const s=await P(c);if(!s)return this.fail(t,"verifying",e,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 v(s);a===null&&g&&(await this.sleep(1e3),{version:a,error:g}=await v(s));const I=Date.now()-e;return this.activeInstalls.delete(t),m.info("installer",`${t} installed successfully at ${s} (v${a??"unknown"}, ${I}ms)`),{agentType:t,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()-e;return this.activeInstalls.delete(t),m.info("installer",`${t} install command completed (${E}ms, verification skipped)`),{agentType:t,ok:!0,phase:"completed",installedPath:null,installedVersion:null,durationMs:E,output:f,prerequisites:r.length>0?r:void 0,environment:i}}getManualHint(n,e){const i=S(n,e)?.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"}[n],c=[];return l&&c.push(`Docs: ${l}`),i&&c.push(`Alternative: ${i.command}`),c.length>0?c.join(" | "):null}setProgress(n,e,t,i,o){this.activeInstalls.set(n,{agentType:n,phase:e,startedAt:t,elapsedMs:Date.now()-t,...i?{currentPrereq:i}:{},...o?{pendingPrereqs:o}:{}})}fail(n,e,t,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 ${e}: ${i.message}`);const d=l?k(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:e==="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()-t,output:p,environment:o,prerequisites:l,manualGuide:h}}async executeWithRetry(n,e,t,i){let o=null;for(let l=0;l<=N;l++)try{return l>0&&(m.info("installer",`Retry ${l}/${N} for ${e}...`),await this.sleep(W)),await this.executeCommand(n,e,t,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(e=>setTimeout(e,n))}executeCommand(n,e,t,i){const o=i??n.timeoutMs;switch(n.mode){case"npm":return this.executeNpm(n.npmPackage,o,e,t);case"shell":return this.executeShell(n.command,o,e,t);case"exec":return this.executeExec(n.command,n.execArgs??[],o,e,t);default:return Promise.reject(new u("INTERNAL",`Unknown install mode: ${n.mode}`))}}async executeNpm(n,e,t,i){try{const{output:o,registry:l}=await j(n,e,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(t,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,e,t,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:e,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()},e);h.stdout?.on("data",s=>{const a=s.toString("utf-8");r+=a,r.length>T&&(r=r.slice(-T)),this.updateOutputTail(t,i,r)}),h.stderr?.on("data",s=>{const a=s.toString("utf-8");r+=a,r.length>T&&(r=r.slice(-T)),this.updateOutputTail(t,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 ${e/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,e,t,i,o){return new Promise((l,c)=>{m.info("installer",`exec: ${n} ${e.join(" ")}`);const p=R(n,e,{timeout:t,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 ${t/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,e,t){n.on("close",()=>{const i=this.activeInstalls.get(e);i&&(i.elapsedMs=Date.now()-t)})}updateOutputTail(n,e,t){const o=t.split(`
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()-e)}}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(e=>e?.trim()).filter(e=>!!e).join(`
12
- `)||void 0}export{lt as AgentInstaller,u as InstallerError};
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(u){const{agentType:e,os:i,env:h,missingPrereqs:c}=u,s=[],a=g(e)??e,o=f(e,i),m=b(i);if(s.push(`=== ${e} \u4EBA\u5DE5\u5B89\u88C5\u6307\u5357 (${m}) ===`),s.push(""),s.push("\u5F53\u524D\u73AF\u5883:"),s.push(` \u7CFB\u7EDF: ${h.osVersion} (${h.arch})`),s.push(` Node.js: ${h.nodeVersion??"\u672A\u5B89\u88C5"}`),s.push(` npm: ${h.npmVersion??"\u672A\u5B89\u88C5"}`),s.push(""),u.error&&(s.push("\u81EA\u52A8\u5B89\u88C5\u5931\u8D25\u539F\u56E0:"),s.push(` ${u.error}`),s.push("")),c.length>0){s.push("--- \u6B65\u9AA4 1: \u5B89\u88C5\u524D\u7F6E\u4F9D\u8D56 ---"),s.push("");for(const n of c){const p=$(n.id,i);s.push(`\u25B8 ${n.label}${n.minVersion?` (\u9700\u8981 >= ${n.minVersion})`:""}`),p&&s.push(` \u5B89\u88C5\u65B9\u6CD5: ${p}`),s.push(` \u9A8C\u8BC1: ${n.id==="node"?"node --version":n.id==="npm"?"npm --version":`${n.id} --version`}`),s.push("")}}const l=c.length>0?"2":"1";if(s.push(`--- \u6B65\u9AA4 ${l}: \u5B89\u88C5 ${e} ---`),s.push(""),o){if(s.push(" \u63A8\u8350\u65B9\u5F0F:"),s.push(` ${o.command}`),s.push(""),o.mode==="npm"&&o.npmPackage){const n=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 n)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 n=r(o.fallback.npmPackage);for(const p of n)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"};return t[e]&&s.push(` ${e}: ${t[e]}`),s.join(`
2
- `)}function b(u){switch(u){case"macos":return"macOS";case"linux":return"Linux";case"windows":return"Windows"}}export{v as generateManualGuide};
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 m(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 p(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,p as getAllAgentInstallInfo,m as getCliBinary,d as getInstallCommand,w as isKnownAgent};
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"}),m(t,this.filePath);try{I(this.filePath,384)}catch{}}catch(i){if(a(t))try{p(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:o(i?.modeId),modelId:i?.modelId,effort:Object.prototype.hasOwnProperty.call(t,"effort")?s(t.effort):s(i?.effort),cursorModeId:i?.cursorModeId,acpModelId:i?.acpModelId,acpModeId:i?.acpModeId,updatedAt:Date.now()};this.bindings.set(e,d),this.scheduleWrite()}}export{T as SessionBindingStore};
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,t){const{home:e}=t,l=t.cwd?.trim()||void 0,r=t.env??process.env;switch(n){case"claude":return{globalRoot:o(e,".claude","skills"),projectRoot:l?o(l,".claude","skills"):null};case"codex":{const s=r.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=r.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=r.KIMI_CODE_HOME?.trim()||o(e,".kimi-code");return{globalRoot:o(s,"skills"),projectRoot:null}}default:return{globalRoot:null,projectRoot:null}}}export{i as resolveEnableRoots};
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 a,mkdirSync as k,cpSync as y,writeFileSync as h,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as m}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as F,MANAGED_MARKER as f}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as w}from"../core/config/index.js";import{log as u}from"../core/log/index.js";const l=S(D(import.meta.url));function d(){const e=[];let i;try{i=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of i){if(!r.isDirectory())continue;const n=t(l,r.name,"SKILL.md");try{const s=p(n,"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 i=[];try{i=x(e)}catch{i=[]}return F([...i,...d()])}function j(e){const i=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return i}for(const n of r){if(!n.isDirectory())continue;const s=t(l,n.name);if(a(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,n.name);y(s,o,{recursive:!0}),h(t(o,f),"","utf8"),i.push(n.name)}catch{}}return i}function C(e=process.env){return(e.KIMI_CODE_HOME||"").trim()||t(m(),".kimi-code")}function L(){const e=m(),i=process.env.XDG_CONFIG_HOME||t(e,".config");return[t(w().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(i,"opencode","skills"),t(e,".cursor","skills"),t(e,".openhuman","skills"),t(e,".kiro","skills"),t(e,".reasonix","skills"),t(C(),"skills")]}function O(){const e=[];for(const i of L()){let r;try{r=c(i,{withFileTypes:!0,encoding:"utf8"})}catch{continue}for(const n of r){if(!n.isDirectory())continue;const s=t(i,n.name);if(a(t(s,f)))try{g(s,{recursive:!0,force:!0}),e.push(s)}catch{}}}return e.length>0&&u.info("default-skills",`Cleaned ${e.length} projected skill dir(s)`),e}function b(){const e=d();if(e.length===0){u.warn("default-skills","No connector system skills found \u2014 dist/default-skills/ may be missing SKILL.md files");return}u.info("default-skills",`Connector system skills available: [${e.map(i=>i.name).join(", ")}]`)}export{T as buildReportedSkills,O as cleanupProjectedSkills,b as logDefaultSkillsCheck,C as resolveKimiCodeHome,d as scanDefaultSkills,j as syncDefaultSkillsToDir};
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/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};