grix-connector 4.16.2 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/acp/acp-adapter.js +8 -8
- package/dist/adapter/agy/agy-adapter.js +8 -8
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/codex/codex-bridge.js +10 -10
- package/dist/adapter/codex/rollout-import.js +1 -0
- package/dist/adapter/codex/thread-archive.js +6 -0
- package/dist/adapter/codex/thread-resume.js +1 -0
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
- package/dist/adapter/deepseek-harness/prompt-builder.js +4 -4
- package/dist/adapter/deepseek-harness/workspace-attachments.js +3 -0
- package/dist/adapter/opencode/opencode-adapter.js +1 -1
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.16.2.tgz → grix-dsh-bridge-4.18.0.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/send-controller.js +3 -3
- package/dist/bridge/session-list.js +2 -2
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -1
- package/dist/core/util/cli-probe.js +2 -2
- package/dist/kimi-plugins/index.js +2 -2
- package/dist/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
- package/dist/kimi-plugins/grix-layer/SKILL.md +0 -68
- package/dist/kimi-plugins/grix-layer/SYSTEM.md +0 -16
- package/dist/kimi-plugins/grix-layer/kimi.plugin.json +0 -10
- package/dist/kimi-plugins/grix-layer/references/gateway-architecture.md +0 -157
package/dist/manager.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as b}from"node:path";import{homedir as H}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{isCwdLockedClientType as de,resolveStaticCwd as pe}from"./bridge/cwd-policy.js";import{buildSharedInstanceConfig as he,diffSharedOwners as ue,sharedInstanceKey as me,SharedOwnersCache as ge}from"./manager-share-config.js";import{AgentDeletedError as fe,isAgentDeletedError as E}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as _e}from"./core/util/client-version.js";import{UpgradeChecker as we}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as ye}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as Ae}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as Se}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as ke}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as be}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as ve}from"./core/aibot/types.js";import{buildReportedSkills as Ie,logDefaultSkillsCheck as Ce,cleanupProjectedSkills as W}from"./default-skills/index.js";import{buildProviderEnv as Ee,supportsKiroCwRelay as K,supportsNonMitmRelayConfig as $e}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Pe}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as z,stopKiroRelay as Q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as Te}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as Me}from"./core/runtime/cursor-resolve.js";import{probeInstalledClientCommands as V}from"./core/probe/installed-clients.js";import{AgentInstaller as xe}from"./core/installer/installer.js";import{reportInstallFailure as De}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Re}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as Oe}from"./adapter/codex/config-overrides.js";import{ACP_NEW_SESSION_RESERVED_KEYS as je}from"./protocol/acp-client.js";import{resolveCodexDirectHome as Le}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(a){if(a)return{...a.provider_id?.trim()?{providerId:a.provider_id.trim()}:{},...a.base_url?.trim()?{baseUrl:a.base_url.trim()}:{},...a.quota_base_url?.trim()?{quotaBaseUrl:a.quota_base_url.trim()}:{},...a.api_key?.trim()?{apiKey:a.api_key.trim()}:{},...a.quota_api_key?.trim()?{quotaApiKey:a.quota_api_key.trim()}:{},...a.model?.trim()?{model:a.model.trim()}:{},...a.fast_model?.trim()?{fastModel:a.fast_model.trim()}:{},...a.effort?.trim()?{effort:a.effort.trim()}:{}}}const Ne=8e3,qe=1e4,Ge=8e3;function Ue(a,e){switch(a){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"omp":return{adapterType:"pi",command:"omp",adapterHint:"omp/base",env:{PI_CODING_AGENT_DIR:b(H(),".omp","agent")}};case"cursor":return{adapterType:"cursor",command:Me()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"qodercli":return{adapterType:"acp",command:"qodercli",args:["--yolo","--acp"],enableSessionBinding:!0};case"qoderclicn":return{adapterType:"acp",command:"qoderclicn",args:["--yolo","--acp"],enableSessionBinding:!0};case"mcode":return{adapterType:"acp",command:"mcode",args:["acp"],enableSessionBinding:!0};case"dim":return{adapterType:"acp",command:"dim",args:["acp"],enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"deveco":return{adapterType:"opencode",command:"deveco",args:["serve"],adapterHint:"deveco/base",enableSessionBinding:!0};case"copilot":{const n=Te();return{adapterType:"acp",command:n.command,args:[...n.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};case"traecli":return{adapterType:"acp",command:"traecli",args:["acp","serve"],adapterHint:"traecli/base",options:{initial_mode:"bypass_permissions"},enableSessionBinding:!0};case"codebuddy":return{adapterType:"acp",command:"codebuddy",args:["--acp"],adapterHint:"codebuddy/base",enableSessionBinding:!0};case"grok":return{adapterType:"acp",command:"grok",args:["--no-auto-update","agent","--always-approve","stdio"],enableSessionBinding:!0};case"qwenpaw":return{adapterType:"acp",command:"qwenpaw",args:["acp"],enableSessionBinding:!0};case"zeroclaw":return{adapterType:"acp",command:"zeroclaw",args:["acp"],enableSessionBinding:!0};case"acp":{const n=typeof e?.command=="string"?e.command.trim():"";if(!n)throw new Error(`agent ${e?.name??"<unknown>"}: client_type=acp requires "command" (the ACP CLI executable) in the agent config; put its ACP subcommand or flag in "args"`);return{adapterType:"acp",command:n,adapterHint:"acp/base",enableSessionBinding:!0}}default:throw new Error(`Unsupported client_type: ${a}`)}}function v(a,e){return String(a??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function Be(a){return b(A.data,`session-bindings-${v(a,"unknown")}.json`)}function He(a,e){return b(A.data,`session-bindings-${v(a,e)}.json`)}function Fe(a,e){return b(A.data,`active-events-${v(a,e)}.json`)}function We(a){return b(A.data,`pending-events-${v(a,"unknown")}.json`)}function Ke(a,e){const n=v(a,"agent"),t=v(e,"unknown");return b(A.data,`terminal-outbox-${n}-${t}.json`)}function ze(...a){const e=[],n=new Set;for(const t of a)for(const s of t??[]){const i=String(s??"").trim(),c=i.toLowerCase();!i||n.has(c)||(n.add(c),e.push(i))}return e.length>0?e:void 0}function Qe(a,e){const n={claude:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},"deepseek-harness":{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0}},t=n[a]??n.acp;let s=e?.max_concurrent??t.maxConcurrent??1;return a==="acp"&&s>1&&(m.warn("manager",`ACP adapter supports only one active run at a time; clamping max_concurrent from ${s} to 1`),s=1),{maxConcurrent:s,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function Ve(a,e={}){const n=_e(),t=String(a.client_type??"").trim().toLowerCase(),s=Ue(t,a),i=t==="deepseek"?a.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(a.ws_url??"").trim(),u=typeof a.name=="string"?a.name:"",r=u.trim(),l="get_session_usage",g="get_rate_limits",p="get_agent_global_config",d=ve;if(!r)throw new Error("agent name is required");if(u!==r)throw new Error(`agent name must not contain leading or trailing whitespace: "${u}"`);if(!o)throw new Error(`agent ${a.name}: ws_url is required`);if(!a.agent_id?.trim())throw new Error(`agent ${a.name}: agent_id is required`);if(!a.api_key?.trim())throw new Error(`agent ${a.name}: api_key is required`);const h=s.adapterType,_=h==="acp",w=t==="qwen",y={...s.options??{}};if(h==="deepseek-harness"&&(y.integrationMode=i,y.dshProfile=a.dsh?.profile?.trim()||"web",y.autoInstallBridge=a.dsh?.auto_install_bridge??!c,y.autoStartProfile=a.dsh?.auto_start_profile??!c),h==="deepseek-harness"&&a.provider?.model?.trim()&&(y.defaultModel=a.provider.model.trim()),a.codex_config_overrides!==void 0){if(h!=="codex")throw new Error(`agent ${a.name}: codex_config_overrides is only supported for client_type=codex`);Oe(a.codex_config_overrides,`agent ${a.name}: codex_config_overrides`),y.codexConfigOverrides=a.codex_config_overrides}if(a.acp_new_session_params!==void 0){if(!_)throw new Error(`agent ${a.name}: acp_new_session_params is only supported for ACP-based client types`);const f=a.acp_new_session_params;if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`agent ${a.name}: acp_new_session_params must be a JSON object`);const k=Object.keys(f).find(le=>je.has(le));if(k)throw new Error(`agent ${a.name}: acp_new_session_params cannot set reserved field "${k}" (Grix owns cwd/mcpServers/sessionId/additionalDirectories on every session/new)`);y.newSessionParams=f}if(t==="zeroclaw"){const k=a.acp_new_session_params?.agentAlias;if(typeof k!="string"||!k.trim()||k.trim().startsWith("<REPLACE"))throw new Error(`agent ${a.name}: client_type=zeroclaw requires acp_new_session_params.agentAlias (create one with \`zeroclaw agents create <alias>\` and set it in the agent config); without it session/new fails with -32602 and the connector would silently respawn-retry forever`)}if(h==="codex"&&a.provider?.wire_api!==void 0){const f=a.provider;if(f.wire_api!=="responses"||!f.base_url?.trim()||!f.api_key?.trim()||!f.model?.trim()||!f.catalog_version?.trim()||!f.catalog_sha256?.trim()||!f.catalog_json?.trim())throw Object.assign(new Error(`agent ${a.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const k=Le(A.data,a.name);y.codexHome=k,y.codexDirect={codexHome:k,config:{baseUrl:f.base_url.trim(),model:f.model.trim(),...f.reasoning_effort?.trim()?{reasoningEffort:f.reasoning_effort.trim()}:{},token:f.api_key.trim()},catalog:{version:f.catalog_version.trim(),sha256:f.catalog_sha256.trim(),json:f.catalog_json}}}const S=h==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=h==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",l,g]}:null,T=w?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",l],adapterHint:"qwen/base"}:null,M=h==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","get_context","file_list","create_folder",l,g]}:null,x=h==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,D=h==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",g]}:null,N=h==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,R=h==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,O=h==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,j=h==="deepseek-harness"?{adapterHint:c?"deepseek/jsonrpc-v1":"deepseek/grix-bridge-v1",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","set_mode","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile",l,g,"exec_approve","exec_reject","permission_approve","permission_reject","file_list","create_folder","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals"]}:null,q=new Set(["hermes","reasonix","kimi","copilot","acp","qodercli","qoderclicn","mcode","dim","traecli","grok","qwenpaw","zeroclaw","codebuddy"]),ee=_&&!q.has(t),te=_&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder",...ee?[l]:[]]}:null,ne=t==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",l,g]}:null,se=h==="codex"||h==="claude"||h==="opencode"||h==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...h==="deepseek-harness"?["set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill"]:[],...h==="claude"?["set_reasoning_effort"]:[]]:void 0,ae=h==="cursor"||h==="opencode"||h==="openhuman"||h==="agy"||_&&q.has(t)?[g]:[l,g];_&&y.raw_transport===void 0&&(y.raw_transport=t==="gemini");const re=`${t}/base`,C=Se(h,t),ie=C==="kiro"?void 0:process.cwd(),L=Y(a.provider),I={...process.env,...s.env,...a.env};if(C==="hermes"&&!I.HERMES_HOME?.trim()){const f=Ee(t,L);I.HERMES_HOME=Pe({...f,...I},a.name)}const G=Ie({mode:C,projectDir:ie,env:I}),U=G.filter(f=>f.source==="connector").map(f=>f.name);U.length>0&&!e.quiet&&m.info("manager",`[${a.name}] injecting connector skills: [${U.join(", ")}]`);const B=ke(G,A.skills);let oe=B.length>0?B:void 0;const ce=be({skillsDir:A.skills,mode:C,home:H(),env:I});return{name:r,adapterType:h,aibot:{url:o,agentId:a.agent_id,apiKey:a.api_key,clientType:t,clientVersion:n,adapterHint:j?.adapterHint??s.adapterHint??T?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??R?.adapterHint??O?.adapterHint??re,capabilities:j?.capabilities??S?.capabilities??N?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??R?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:ze(j?.localActions??S?.localActions??N?.localActions??Z?.localActions??M?.localActions??x?.localActions??D?.localActions??R?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,ae,["connector_rollback","connector_upgrade_push",p,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:Ke(a.name,a.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...a.args??[]],env:s.env?{...s.env,...a.env}:a.env,clientType:t,...L?{provider:L}:{}},adapterOptions:y,acpAuthMethod:y.auth_method,acpInitialMode:y.initial_mode,acpMcpTools:y.acp_mcp_tools,promptTimeoutMs:a.prompt_timeout_ms,bindingsPath:Be(a.agent_id),legacyBindingsPath:He(a.name,a.agent_id),activeEventStorePath:Fe(a.name,a.agent_id),pendingEventStorePath:We(a.agent_id),...s.enableSessionBinding||_?{enableSessionBinding:!0}:{},...de(t)?{staticCwd:pe(a.cwd)}:{},...s.autoInjectArgs||t==="reasonix"&&a.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&a.provider?.model?.trim()?{model:a.provider.model.trim()}:{}}}:{},poolMaxSize:a.pool?.maxSize??(h==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:a.pool?.idleTimeoutMs,eventQueue:Qe(h,a.event_queue),logDir:A.log,providerBaseUrl:a.provider_base_url?.trim()||void 0,providerApiKey:a.provider_api_key?.trim()||void 0}}function J(){const a=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):Ne}function $(){const a=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):qe}function Xe(){return Math.min($(),Ge)}function P(a){if(a===null||typeof a!="object")return JSON.stringify(a)??"null";if(Array.isArray(a))return`[${a.map(P).join(",")}]`;const e=a;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${P(e[t])}`).join(",")}}`}function Ye(a,e){return P(a)===P(e)}class Pt{options;instances=[];configMap=new Map;rawConfigMap=new Map;mutationTail=Promise.resolve();startingInstances=new Set;failedStartAgents=new Set;removingAgents=new Set;instanceGenerations=new WeakMap;sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;lifecycleAdmissionClosed=!1;deletedAgentCleanups=new Set;pendingPlatformDeletes=new Map;upgradeChecker=null;skillSyncer=null;globalConfigStore;configRepository=new X(A.config);sharedOwnersCache=new ge(A.data);installer=new xe;relaySecretResolver;auditProducer=Re();constructor(e={}){this.options=e}runMutation(e,n=[]){const t=this.mutationTail.catch(()=>{}).then(async()=>{if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});await this.retryPendingPlatformDeletesUnlocked();const s=new Set([...this.pendingPlatformDeletes.values()].map(c=>c.name)),i=n.find(c=>s.has(c.trim()));if(i)throw Object.assign(new Error(`Agent "${i}" is pending permanent platform-deletion cleanup`),{code:"AGENT_DELETE_PENDING"});return e()});return this.mutationTail=t.then(()=>{},()=>{}),t}async startTrackedInstance(e){this.startingInstances.add(e);try{await e.start()}finally{this.startingInstances.delete(e)}}requestStartCancellation(e){const n=e.requestStop;typeof n=="function"&&n.call(e)}async stopInstance(e,n,t=$()){let s;try{await Promise.race([e.stop(n),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`Agent "${e.name}" stop timed out after ${t}ms`),{code:"AGENT_STOP_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForLifecycleDrain(e,n,t=$()){let s;try{await Promise.race([Promise.allSettled([...e]).then(()=>{}),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"LIFECYCLE_DRAIN_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForShutdownOperation(e,n,t){let s;try{return await Promise.race([e,new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"SHUTDOWN_OPERATION_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}isActiveGeneration(e){const n=this.instanceGenerations.get(e);return!!n&&!n.retired&&this.instances.find(t=>t.name===n.name)===e}retireInstance(e){const n=this.instanceGenerations.get(e);n&&(n.retired=!0)}async start(e){return this.runMutation(()=>this.startUnlocked(e))}async startUnlocked(e){const n=e??A.config;this.configRepository=new X(n),m.info("manager",`Loading configs from ${n}`),Ce(),W(),this.globalConfigStore=new Ae(b(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const r of s)m.error("manager",`Failed to load ${r.file}: ${r.error}`);for(const r of i)m.info("manager",`Skipped ${r}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&i.length===0){m.warn("manager",`No agent configurations found in ${n}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const c=[];let o=s.length;for(const{entry:r,file:l}of t)try{const g=this.toRuntimeInstanceConfig(r);c.push({config:g,entry:r,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const p=typeof r?.name=="string"?r.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${p}): ${g}`),o++}let u=0;if(c.length>0){const r=J();m.info("manager",`Starting ${c.length} agent(s), startup wait=${r}ms`);const l=d=>{this.instances=this.instances.filter(h=>h!==d)},g=c.map(({config:d,entry:h,file:_})=>{const w=this.createConfiguredInstance(d);return this.instances.push(w),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:h,file:_}),{config:d,instance:w,startPromise:this.prepareProviderRuntime(d,h).then(()=>{if(this.stopping)throw this.requestStartCancellation(w),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(w)})}}),p=await Promise.all(g.map(async d=>{const h=await new Promise(_=>{let w=!1;const y=setTimeout(()=>{w||(w=!0,_({kind:"timeout"}))},r);d.startPromise.then(()=>{w||(w=!0,clearTimeout(y),_({kind:"started"}))}).catch(S=>{w||(w=!0,clearTimeout(y),_({kind:"failed",error:S}))})});return{task:d,outcome:h}}));for(const{task:d,outcome:h}of p){if(h.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(h.kind==="failed"){if(E(h.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(_){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up partially started ${d.config.name}: ${_}`)}m.error("manager",`Failed to start ${d.config.name}: ${h.error}`);continue}u++,m.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{this.stopping||this.removingAgents.has(d.config.name)||this.isActiveGeneration(d.instance)&&(m.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config))}).catch(async _=>{if(E(_)){this.onAgentDeletedByPlatform(d.instance);return}if(!(this.stopping||this.removingAgents.has(d.config.name))&&this.isActiveGeneration(d.instance)){try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(w){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up delayed start ${d.config.name}: ${w}`)}m.error("manager",`Delayed start failed: ${d.config.name}: ${_}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-u);m.info("manager",`${d}/${c.length} agent(s) running now`)}u>0&&m.warn("manager",`${u} agent(s) still connecting in background`)}if(this.instances.length===0&&c.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.stopping||this.configMap.size===0)return;const e=[...this.configMap.values()].map(n=>({apiKey:n.aibot.apiKey,wsUrl:n.aibot.url}));if(!this.upgradeChecker&&(this.upgradeChecker=new we(e,()=>this.describeAnyPendingOrBackgroundWork(),()=>this.closeAllLifecycleAdmission(),{requestGracefulShutdown:this.options.requestGracefulShutdown,reopenLifecycleAdmission:()=>this.reopenAllLifecycleAdmission(),isConnected:()=>this.instances.length===0||this.instances.some(n=>n.getStatus().wsConnected),onTransactionSettled:this.options.onTransactionSettled}),await this.upgradeChecker.start(),this.stopping)){this.upgradeChecker.stop();return}this.skillSyncer||(this.skillSyncer=new ye(e,A.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start(),this.stopping&&this.skillSyncer.stop())}refreshOwnerLibrarySkills(){const e=new Map,n=t=>{let s;try{s=t.skillsSyncGroupKey()}catch(c){m.warn("manager",`skillsSyncGroupKey failed for ${t.name}: ${c}`);return}const i=e.get(s)??[];i.push(t),e.set(s,i)};for(const t of this.instances)n(t);for(const t of this.sharedInstances.values())n(t);for(const[t,s]of e){let i=!1;const c=[];for(const o of s){if(i){c.push(o);continue}let u=!1;try{u=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(r){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${r}`)}if(u){i=!0;continue}m.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!i){m.warn("manager",`owner library skills: no reporter succeeded group=${t}`);continue}for(const o of c)try{o.adoptSkillsWireHashFromDisk()}catch(u){m.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${u}`)}}}async stop(){m.info("manager","Stopping all agents..."),this.stopping=!0;const e=Xe(),n=Date.now()+e,t=()=>Math.max(1,n-Date.now()),s=new Set([...this.instances,...this.sharedInstances.values(),...this.startingInstances]);for(const o of s)this.requestStartCancellation(o);const i=new Map([...s].map(o=>[o,this.stopInstance(o,void 0,e)])),c=[];this.upgradeChecker?.stop(),this.skillSyncer?.stop();try{await this.waitForLifecycleDrain([this.mutationTail,...this.shareSyncChains.values(),...i.values()],"manager shutdown lifecycle drain",t())}catch(o){c.push(o)}this.upgradeChecker?.stop(),this.skillSyncer?.stop(),this.shareSyncChains.clear(),await Promise.all([...[...this.instances].map(async o=>{try{await(i.get(o)??this.stopInstance(o,void 0,t())),this.retireInstance(o),this.instances=this.instances.filter(u=>u!==o),this.startingInstances.delete(o)}catch(u){c.push(u)}}),...[...this.sharedInstances.entries()].map(async([o,u])=>{try{await(i.get(u)??this.stopInstance(u,void 0,t())),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o),this.startingInstances.delete(u)}catch(r){c.push(r)}})]);try{await this.waitForLifecycleDrain([this.retryPendingPlatformDeletesUnlocked(n)],"platform-delete shutdown drain",t())}catch(o){c.push(o)}try{await this.waitForShutdownOperation(Promise.resolve().then(()=>this.globalConfigStore?.flush()),"global config shutdown flush",t())}catch(o){c.push(o)}if(await this.auditProducer.stop({timeoutMs:Math.min(5e3,t())}).catch(()=>!1),W(),c.length>0)throw new AggregateError(c,"Failed to stop all agents completely");m.info("manager","All stopped")}onShareSet(e,n,t){if(this.stopping||this.removingAgents.has(n.name)||!this.isActiveGeneration(e))return;this.sharedOwnersCache.save(n.name,t);const i=(this.shareSyncChains.get(n.name)??Promise.resolve()).catch(()=>{}).then(()=>{if(!(this.stopping||this.removingAgents.has(n.name))&&this.isActiveGeneration(e))return this.syncSharedInstances(n,t,e)});this.shareSyncChains.set(n.name,i)}async syncSharedInstances(e,n,t){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))return;const{toAdd:s,toRemove:i}=ue(e.name,this.sharedInstances.keys(),n);for(const c of s){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))break;const o=me(e.name,c);let u;try{const r=he(e,c);u=new F(r,this.globalConfigStore,this.auditProducer),u.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),u.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),u.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&u.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&u.closeLifecycleAdmission(),this.sharedInstances.set(o,u),await this.startTrackedInstance(u),u.forceRefreshSkills(void 0,{force:!0}),m.info("manager",`shared instance started: ${o}`)}catch(r){if(u&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(u),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o)}catch(g){m.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=r instanceof Error?r.message:String(r);/Auth failed/i.test(l)?(this.sharedOwnersCache.remove(e.name,c),m.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):m.error("manager",`start shared instance failed ${o}: ${r}`)}}for(const{key:c}of i){const o=this.sharedInstances.get(c);if(o)try{await this.stopInstance(o),this.sharedInstances.get(c)===o&&this.sharedInstances.delete(c),m.info("manager",`shared instance stopped: ${c}`)}catch(u){m.error("manager",`stop shared instance failed ${c}: ${u}`)}}}restoreCachedSharedInstances(e){const n=this.sharedOwnersCache.load(e.name);if(n.length===0)return;const t=this.instances.find(s=>s.name===e.name);!t||!this.isActiveGeneration(t)||(m.info("manager",`restoring ${n.length} cached shared instance(s) for ${e.name}`),this.onShareSet(t,e,n))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){return this.runMutation(()=>this.addAgentUnlocked(e),[String(e.name??"")])}async addAgentUnlocked(e){const n=this.toRuntimeInstanceConfig(e,{quiet:!0});if(this.instances.some(t=>t.name===n.name))throw new Error(`Agent "${n.name}" already exists`);this.configRepository.assertCanAdd(e),await this.addAgentInternal(e,"agents.json",{targetPersisted:!1});try{const t=this.configRepository.insert(e);this.rawConfigMap.set(e.name,t);const s=this.instances.find(c=>c.name===e.name),i=s?this.instanceGenerations.get(s):void 0;if(i){i.persisted=!0;const c=this.configMap.get(e.name);c&&this.restoreCachedSharedInstances(c)}}catch(t){try{await this.removeAgentInternal(e.name)}catch(s){throw new AggregateError([t,s],`Failed to persist and roll back agent "${e.name}"`)}throw t}await this.ensureAuxServices(),m.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,n,t){const s=this.toRuntimeInstanceConfig(e);if(this.instances.some(i=>i.name===s.name))throw new Error(`Agent "${s.name}" already exists`);await this.startInstanceFromConfig(s,e,n,t)}createConfiguredInstance(e,n=!0){const t=new F(e,this.globalConfigStore,this.auditProducer);return this.instanceGenerations.set(t,{name:e.name,agentId:e.aibot.agentId,persisted:n,retired:!1,platformDeletedObserved:!1}),t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),this.options.requestGracefulShutdown&&t.setDaemonShutdownRequester(this.options.requestGracefulShutdown),t.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(s)),t.setRemoteAdminPorts({isEnabled:()=>this.remoteAdminGate?.()??!1,listInstallable:()=>this.listInstallable(),installAgent:s=>this.installAgent(s),getInstallProgress:s=>this.getInstallProgress(s),addAgent:s=>this.addAgent(s),probeAll:s=>this.probeAll(s)}),t.setShareSetHandler(s=>this.onShareSet(t,e,s)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(t)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(s=>this.setAgentProvider(e.name,s)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},getAppliedMode:()=>this.relayStateApplier?.getAppliedMode?.(e.name),applyEnable:(s,i)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,s,i):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const s=this.relayStateApplier;return s?s.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>Y(this.getAgentProvider(e.name))),t}describeAnyPendingOrBackgroundWork(){return[...this.instances.flatMap(e=>e.describePendingOrBackgroundWork()),...[...this.sharedInstances.values()].flatMap(e=>e.describePendingOrBackgroundWork())]}closeAllLifecycleAdmission(){this.lifecycleAdmissionClosed=!0;for(const e of this.instances)e.closeLifecycleAdmission();for(const e of this.sharedInstances.values())e.closeLifecycleAdmission()}reopenAllLifecycleAdmission(){if(!this.stopping){this.lifecycleAdmissionClosed=!1;for(const e of this.instances)e.openLifecycleAdmission();for(const e of this.sharedInstances.values())e.openLifecycleAdmission()}}async prepareProviderRuntime(e,n){const t=this.resolveAgentProvider(n.provider);K(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await z(e.name,{baseUrl:t.base_url.trim(),apiKey:t.api_key.trim(),model:t.model.trim()})}async startInstanceFromConfig(e,n,t,s){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});if(await this.prepareProviderRuntime(e,n),this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});const i=this.createConfiguredInstance(e,s.targetPersisted);this.instances.push(i);const c=this.startTrackedInstance(i),o=J(),u=await new Promise(p=>{let d=!1;const h=setTimeout(()=>{d||(d=!0,p({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(h),p({kind:"started"}))},_=>{d||(d=!0,clearTimeout(h),p({kind:"failed",error:_}))})}),r=this.instanceGenerations.get(i);if(r?.platformDeletedObserved&&!r.persisted){const p=new fe(`Agent "${e.name}" was deleted before its local configuration commit`);try{await this.stopInstance(i),this.retireInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){throw this.failedStartAgents.add(e.name),new AggregateError([p,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw p}if(u.kind==="started"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),this.failedStartAgents.delete(e.name),s.targetPersisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.();return}if(u.kind==="timeout"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),m.warn("manager",`Start pending for ${e.name}, continue retrying in background`),c.then(async()=>{if(!this.removingAgents.has(e.name)&&this.isActiveGeneration(i)){if(this.stopping){try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i)}catch(p){this.failedStartAgents.add(e.name),m.error("manager",`Failed to stop late-started ${e.name}: ${p}`)}return}this.failedStartAgents.delete(e.name),this.instanceGenerations.get(i)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),m.info("manager",`Delayed start succeeded: ${e.name}`)}},async p=>{if(E(p)){this.onAgentDeletedByPlatform(i);return}if(!(this.stopping||this.removingAgents.has(e.name))&&this.isActiveGeneration(i)){try{await this.stopInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){this.failedStartAgents.add(e.name),m.error("manager",`Failed to clean up delayed start ${e.name}: ${d}`)}m.error("manager",`Delayed start failed ${e.name}: ${p}`)}}).catch(p=>{m.error("manager",`Delayed start finalizer failed ${e.name}: ${p}`)});return}const l=u.error;E(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i),this.failedStartAgents.delete(e.name)}catch(p){g=p,this.failedStartAgents.add(e.name)}throw s.targetPersisted&&(this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t})),g!==void 0?new AggregateError([l,g],`Failed to start and clean up agent "${e.name}"`):l}async removeAgent(e){return this.runMutation(()=>this.removeAgentUnlocked(e),[e])}async removeAgentUnlocked(e){if(!(this.instances.some(t=>t.name===e)||this.rawConfigMap.has(e)||[...this.sharedInstances.keys()].some(t=>t.startsWith(`${e}#shared:`))))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});this.configRepository.remove(e),await this.removeAgentInternal(e),m.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,n){this.removingAgents.add(e);try{const t=()=>n?.deadlineMs===void 0?$():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(p=>p.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},u=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&u.set(i,this.stopInstance(i,o,t())));for(const[p,d]of this.sharedInstances)p.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&u.set(d,this.stopInstance(d,o,t())));const r=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...r?[r]:[],...u.values()],`agent "${e}" shared lifecycle drain`,t())}catch(p){l.push(p)}const g=[];for(const[p,d]of[...this.sharedInstances.entries()])p.startsWith(c)&&g.push((u.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(p)===d&&this.sharedInstances.delete(p),this.startingInstances.delete(d)}).catch(h=>{l.push(h),m.error("manager",`stop shared instance failed ${p}: ${h}`)}));if(i)try{await(u.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const p=this.instances.indexOf(i);p!==-1&&this.instances.splice(p,1),this.startingInstances.delete(i)}catch(p){l.push(p)}if(await Promise.all(g),!n?.keepShareCache){const p=Q(e).catch(()=>{});if(n?.deadlineMs===void 0)await p;else try{await this.waitForLifecycleDrain([p],`agent "${e}" relay shutdown`,t())}catch(d){l.push(d)}}if(l.length>0)throw new AggregateError(l,`Failed to stop agent "${e}" completely`);this.configMap.delete(e),this.rawConfigMap.delete(e),this.failedStartAgents.delete(e),n?.keepShareCache||this.sharedOwnersCache.delete(e)}finally{this.removingAgents.delete(e)}}onAgentDeletedByPlatform(e){const n=this.instanceGenerations.get(e);if(!n||(n.platformDeletedObserved=!0,this.requestStartCancellation(e),!n.persisted))return;const t={source:e,name:n.name,agentId:n.agentId};this.pendingPlatformDeletes.set(e,t),!this.stopping&&(this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),this.runMutation(async()=>{}).catch(()=>{}).finally(()=>{this.deletedAgentCleanups.delete(e)})))}async retryPendingPlatformDeletesUnlocked(e){if(this.pendingPlatformDeletes.size!==0)for(const[n,t]of[...this.pendingPlatformDeletes])try{await this.cleanupPlatformDeletedUnlocked(t,e),this.pendingPlatformDeletes.delete(n)}catch(s){m.error("manager",`cleanup for deleted agent "${t.name}" failed: ${s}`)}}async cleanupPlatformDeletedUnlocked(e,n){const{source:t,name:s,agentId:i}=e,c=this.instances.find(g=>g.name===s),o=c?this.instanceGenerations.get(c)?.agentId??String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim():void 0;if(c&&c!==t&&o!==i)return;m.warn("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`);const u=this.rawConfigMap.get(s),r=this.configMap.get(s),l=[];if(c&&o===i)try{await this.removeAgentInternal(s,{deadlineMs:n})}catch(g){l.push(g)}try{const g=this.configRepository.scan();if(g.fileErrors.length>0){const h=g.fileErrors.map(_=>`${_.file}: ${_.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${h}]`)}const p=g.entries.filter(h=>String(h.entry?.name??"").trim()===s);if(!p.some(h=>String(h.entry?.agent_id??"").trim()!==i)&&p.length>0&&this.configRepository.remove(s),l.length===0){const h=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!h||h===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),u&&this.rawConfigMap.set(s,u),r&&this.configMap.set(s,r)}if(l.length>0)throw new AggregateError(l,`Failed to fully clean up deleted agent "${s}"`);m.info("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406`)}isAgentBusy(e){return this.instances.find(t=>t.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const n=this.instances.find(t=>t.name===e);return n?(n.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}remoteAdminGate;setRemoteAdminGate(e){this.remoteAdminGate=e}relayStateApplier;setRelayStateApplier(e){this.relayStateApplier=e}reportRelayStateLocalChange(e){this.instances.find(t=>t.name===e)?.reportRelayStateLocalChange()}setRelaySecretResolver(e){this.relaySecretResolver=e}resolveAgentProvider(e){if(!e?.api_key_ref?.trim())return e;const n=e.api_key_ref.trim(),t=this.relaySecretResolver?.(n);if(!t)throw Object.assign(new Error(`relay credential "${n}" is unavailable`),{code:"RELAY_SECRET_UNAVAILABLE"});return{...e,api_key:t}}toRuntimeInstanceConfig(e,n={}){const t=this.resolveAgentProvider(e.provider);return Ve(t===e.provider?e:{...e,provider:t},n)}getAgentProvider(e){return this.resolveAgentProvider(this.rawConfigMap.get(e)?.entry.provider)}async restartAgent(e){return this.runMutation(()=>this.restartAgentUnlocked(e),[e])}async restartAgentUnlocked(e){const n=this.rawConfigMap.get(e);if(!n)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,n.entry,n.file),m.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,n,t){return this.runMutation(()=>this.setAgentProviderUnlocked(e,n,t),[e])}async setAgentProviderUnlocked(e,n,t){if(!this.rawConfigMap.get(e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const i=n?.api_key_ref?.trim()?Object.fromEntries(Object.entries(n).filter(([r])=>r!=="api_key")):n,c=this.configRepository.updateExisting(e,r=>{const l={...r};if(i===void 0)delete l.provider;else{const g=i.quota_api_key?.trim()||r.provider?.quota_api_key?.trim();l.provider=g?{...i,quota_api_key:g}:i}return this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const u=String(o.client_type??"").trim().toLowerCase();try{K(u)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await z(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await Q(e))}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}if(t?.deferRestart){this.instances.find(r=>r.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}m.info("manager",`Updated provider config for agent: ${e}`)}hasDirectRelayConfig(e){const n=this.rawConfigMap.get(e)?.entry.provider;return!!(n?.api_key_ref?.trim()||n?.api_key?.trim())}getDirectRelayConfigAgentNames(){return[...this.rawConfigMap.entries()].filter(([,e])=>!!e.entry.provider&&($e(e.entry.client_type)||["claude","codex"].includes(String(e.entry.client_type??"").trim().toLowerCase()))).map(([e])=>e)}async fetchRelayCredential(e,n){const t=this.instances.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.fetchRelayCredential(n)}async clearDirectProviderConfigs(){const e=this.getDirectRelayConfigAgentNames(),n=[];for(const t of e)try{await this.setAgentProvider(t,void 0,{deferRestart:this.isAgentBusy(t)}),n.push(t)}catch(s){m.warn("manager",`Failed to clear provider config for "${t}": ${s instanceof Error?s.message:String(s)}`)}return n}async replaceInstance(e,n,t){const s=this.toRuntimeInstanceConfig(n);try{await this.removeAgentInternal(e,{keepShareCache:!0})}catch(o){throw this.failedStartAgents.add(e),o}const i=String(n.agent_id??"").trim();if([...this.pendingPlatformDeletes.values()].some(o=>o.name===e&&o.agentId===i))throw await this.retryPendingPlatformDeletesUnlocked(),Object.assign(new Error(`Agent "${e}" was permanently deleted while its instance was stopping`),{code:"AGENT_DELETE_PENDING"});try{await this.startInstanceFromConfig(s,n,t,{targetPersisted:!0})}catch(o){throw this.configMap.set(e,s),this.rawConfigMap.set(e,{entry:n,file:t}),o}}async reload(){return this.runMutation(()=>this.doReload())}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:n,skipped:t}=this.configRepository.scan();for(const r of t)m.info("manager",`reload: skipped ${r}: not an agent config (no "agents" key)`);if(n.length>0){const r=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${r}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:r}of e)try{this.toRuntimeInstanceConfig(r,{quiet:!0})}catch(l){const g=r?.name,p=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:p,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const r=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${r}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(r=>r.name));for(const r of e){const l=String(r.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,r)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},u=new Set([...this.rawConfigMap.keys()].filter(r=>!c.has(r)));for(const r of u)if(!i.has(r))try{await this.removeAgentInternal(r),o.removed.push(r)}catch(l){o.failed.push({name:r,error:l instanceof Error?l.message:String(l)})}for(const[r,l]of i){const g=this.rawConfigMap.get(r);if(g)if(!Ye(g.entry,l.entry)||!this.instances.some(p=>p.name===r)||this.failedStartAgents.has(r))try{await this.replaceInstance(r,l.entry,l.file),o.restarted.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}else this.rawConfigMap.set(r,l),o.unchanged.push(r);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}}return m.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),await this.ensureAuxServices(),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Je(this.instances,e)}async probeOne(e,n={}){return Ze(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return De(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Je(a,e){const n=e.concurrency??4,t=Date.now(),s=new Array(a.length);await new Promise(r=>{let l=0,g=0;const p=a.length;if(p===0){r();return}function d(w){const y=a[w];y.probe(e).then(S=>{s[w]=S,h()},S=>{s[w]={agent_name:y.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:S?.message??String(S)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},h()})}function h(){g++,l<p?d(l++):g===p&&r()}const _=Math.min(n,p);for(let w=0;w<_;w++)d(l++)});const i=s.filter(r=>r.status==="healthy").length,c=s.filter(r=>r.status==="degraded").length,o=s.filter(r=>r.status==="unavailable").length,u=await V();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:u,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function Ze(a,e,n){const t=a.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{Pt as Manager,Y as normalizeAgentProviderForRuntime,V as probeInstalledClientCommands,Je as probeInstances,Ze as probeOneInstance};
|
|
1
|
+
import{join as b}from"node:path";import{homedir as H}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{isCwdLockedClientType as de,resolveStaticCwd as pe}from"./bridge/cwd-policy.js";import{buildSharedInstanceConfig as he,diffSharedOwners as ue,sharedInstanceKey as me,SharedOwnersCache as ge}from"./manager-share-config.js";import{AgentDeletedError as fe,isAgentDeletedError as E}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as _e}from"./core/util/client-version.js";import{mergeLoginShellPathIntoProcess as we}from"./core/util/cli-probe.js";import{UpgradeChecker as ye}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as Ae}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as Se}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as ke}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as be}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as ve}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as Ie}from"./core/aibot/types.js";import{buildReportedSkills as Ce,logDefaultSkillsCheck as Ee,cleanupProjectedSkills as W}from"./default-skills/index.js";import{buildProviderEnv as $e,supportsKiroCwRelay as K,supportsNonMitmRelayConfig as Pe}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Te}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as z,stopKiroRelay as Q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as Me}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as xe}from"./core/runtime/cursor-resolve.js";import{probeInstalledClientCommands as V}from"./core/probe/installed-clients.js";import{AgentInstaller as De}from"./core/installer/installer.js";import{reportInstallFailure as Re}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Oe}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as je}from"./adapter/codex/config-overrides.js";import{ACP_NEW_SESSION_RESERVED_KEYS as Le}from"./protocol/acp-client.js";import{resolveCodexDirectHome as Ne}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(a){if(a)return{...a.provider_id?.trim()?{providerId:a.provider_id.trim()}:{},...a.base_url?.trim()?{baseUrl:a.base_url.trim()}:{},...a.quota_base_url?.trim()?{quotaBaseUrl:a.quota_base_url.trim()}:{},...a.api_key?.trim()?{apiKey:a.api_key.trim()}:{},...a.quota_api_key?.trim()?{quotaApiKey:a.quota_api_key.trim()}:{},...a.model?.trim()?{model:a.model.trim()}:{},...a.fast_model?.trim()?{fastModel:a.fast_model.trim()}:{},...a.effort?.trim()?{effort:a.effort.trim()}:{}}}const qe=8e3,Ge=1e4,Ue=8e3;function Be(a,e){switch(a){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"omp":return{adapterType:"pi",command:"omp",adapterHint:"omp/base",env:{PI_CODING_AGENT_DIR:b(H(),".omp","agent")}};case"cursor":return{adapterType:"cursor",command:xe()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"qodercli":return{adapterType:"acp",command:"qodercli",args:["--yolo","--acp"],enableSessionBinding:!0};case"qoderclicn":return{adapterType:"acp",command:"qoderclicn",args:["--yolo","--acp"],enableSessionBinding:!0};case"mcode":return{adapterType:"acp",command:"mcode",args:["acp"],enableSessionBinding:!0};case"dim":return{adapterType:"acp",command:"dim",args:["acp"],enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"deveco":return{adapterType:"opencode",command:"deveco",args:["serve"],adapterHint:"deveco/base",enableSessionBinding:!0};case"copilot":{const n=Me();return{adapterType:"acp",command:n.command,args:[...n.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};case"traecli":return{adapterType:"acp",command:"traecli",args:["acp","serve"],adapterHint:"traecli/base",options:{initial_mode:"bypass_permissions"},enableSessionBinding:!0};case"codebuddy":return{adapterType:"acp",command:"codebuddy",args:["--acp"],adapterHint:"codebuddy/base",enableSessionBinding:!0};case"grok":return{adapterType:"acp",command:"grok",args:["--no-auto-update","agent","--always-approve","stdio"],enableSessionBinding:!0};case"qwenpaw":return{adapterType:"acp",command:"qwenpaw",args:["acp"],enableSessionBinding:!0};case"zeroclaw":return{adapterType:"acp",command:"zeroclaw",args:["acp"],enableSessionBinding:!0};case"acp":{const n=typeof e?.command=="string"?e.command.trim():"";if(!n)throw new Error(`agent ${e?.name??"<unknown>"}: client_type=acp requires "command" (the ACP CLI executable) in the agent config; put its ACP subcommand or flag in "args"`);return{adapterType:"acp",command:n,adapterHint:"acp/base",enableSessionBinding:!0}}default:throw new Error(`Unsupported client_type: ${a}`)}}function v(a,e){return String(a??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function He(a){return b(A.data,`session-bindings-${v(a,"unknown")}.json`)}function Fe(a,e){return b(A.data,`session-bindings-${v(a,e)}.json`)}function We(a,e){return b(A.data,`active-events-${v(a,e)}.json`)}function Ke(a){return b(A.data,`pending-events-${v(a,"unknown")}.json`)}function ze(a,e){const n=v(a,"agent"),t=v(e,"unknown");return b(A.data,`terminal-outbox-${n}-${t}.json`)}function Qe(...a){const e=[],n=new Set;for(const t of a)for(const s of t??[]){const i=String(s??"").trim(),c=i.toLowerCase();!i||n.has(c)||(n.add(c),e.push(i))}return e.length>0?e:void 0}function Ve(a,e){const n={claude:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},"deepseek-harness":{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0}},t=n[a]??n.acp;let s=e?.max_concurrent??t.maxConcurrent??1;return a==="acp"&&s>1&&(m.warn("manager",`ACP adapter supports only one active run at a time; clamping max_concurrent from ${s} to 1`),s=1),{maxConcurrent:s,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function Xe(a,e={}){const n=_e(),t=String(a.client_type??"").trim().toLowerCase(),s=Be(t,a),i=t==="deepseek"?a.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(a.ws_url??"").trim(),u=typeof a.name=="string"?a.name:"",r=u.trim(),l="get_session_usage",g="get_rate_limits",p="get_agent_global_config",d=Ie;if(!r)throw new Error("agent name is required");if(u!==r)throw new Error(`agent name must not contain leading or trailing whitespace: "${u}"`);if(!o)throw new Error(`agent ${a.name}: ws_url is required`);if(!a.agent_id?.trim())throw new Error(`agent ${a.name}: agent_id is required`);if(!a.api_key?.trim())throw new Error(`agent ${a.name}: api_key is required`);const h=s.adapterType,_=h==="acp",w=t==="qwen",y={...s.options??{}};if(h==="deepseek-harness"&&(y.integrationMode=i,y.dshProfile=a.dsh?.profile?.trim()||"web",y.autoInstallBridge=a.dsh?.auto_install_bridge??!c,y.autoStartProfile=a.dsh?.auto_start_profile??!c),h==="deepseek-harness"&&a.provider?.model?.trim()&&(y.defaultModel=a.provider.model.trim()),a.codex_config_overrides!==void 0){if(h!=="codex")throw new Error(`agent ${a.name}: codex_config_overrides is only supported for client_type=codex`);je(a.codex_config_overrides,`agent ${a.name}: codex_config_overrides`),y.codexConfigOverrides=a.codex_config_overrides}if(a.acp_new_session_params!==void 0){if(!_)throw new Error(`agent ${a.name}: acp_new_session_params is only supported for ACP-based client types`);const f=a.acp_new_session_params;if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`agent ${a.name}: acp_new_session_params must be a JSON object`);const k=Object.keys(f).find(le=>Le.has(le));if(k)throw new Error(`agent ${a.name}: acp_new_session_params cannot set reserved field "${k}" (Grix owns cwd/mcpServers/sessionId/additionalDirectories on every session/new)`);y.newSessionParams=f}if(t==="zeroclaw"){const k=a.acp_new_session_params?.agentAlias;if(typeof k!="string"||!k.trim()||k.trim().startsWith("<REPLACE"))throw new Error(`agent ${a.name}: client_type=zeroclaw requires acp_new_session_params.agentAlias (create one with \`zeroclaw agents create <alias>\` and set it in the agent config); without it session/new fails with -32602 and the connector would silently respawn-retry forever`)}if(h==="codex"&&a.provider?.wire_api!==void 0){const f=a.provider;if(f.wire_api!=="responses"||!f.base_url?.trim()||!f.api_key?.trim()||!f.model?.trim()||!f.catalog_version?.trim()||!f.catalog_sha256?.trim()||!f.catalog_json?.trim())throw Object.assign(new Error(`agent ${a.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const k=Ne(A.data,a.name);y.codexHome=k,y.codexDirect={codexHome:k,config:{baseUrl:f.base_url.trim(),model:f.model.trim(),...f.reasoning_effort?.trim()?{reasoningEffort:f.reasoning_effort.trim()}:{},token:f.api_key.trim()},catalog:{version:f.catalog_version.trim(),sha256:f.catalog_sha256.trim(),json:f.catalog_json}}}const S=h==="codex"?{capabilities:["stream_chunk","local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=h==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",l,g]}:null,T=w?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",l],adapterHint:"qwen/base"}:null,M=h==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","get_context","file_list","create_folder",l,g]}:null,x=h==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,D=h==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",g]}:null,N=h==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,R=h==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,O=h==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,j=h==="deepseek-harness"?{adapterHint:c?"deepseek/jsonrpc-v1":"deepseek/grix-bridge-v1",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","set_mode","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile",l,g,"exec_approve","exec_reject","permission_approve","permission_reject","file_list","create_folder","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals"]}:null,q=new Set(["hermes","reasonix","kimi","copilot","acp","qodercli","qoderclicn","mcode","dim","traecli","grok","qwenpaw","zeroclaw","codebuddy"]),ee=_&&!q.has(t),te=_&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder",...ee?[l]:[]]}:null,ne=t==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",l,g]}:null,se=h==="codex"||h==="claude"||h==="opencode"||h==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...h==="deepseek-harness"?["set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill"]:[],...h==="claude"?["set_reasoning_effort"]:[]]:void 0,ae=h==="cursor"||h==="opencode"||h==="openhuman"||h==="agy"||_&&q.has(t)?[g]:[l,g];_&&y.raw_transport===void 0&&(y.raw_transport=t==="gemini");const re=`${t}/base`,C=ke(h,t),ie=C==="kiro"?void 0:process.cwd(),L=Y(a.provider),I={...process.env,...s.env,...a.env};if(C==="hermes"&&!I.HERMES_HOME?.trim()){const f=$e(t,L);I.HERMES_HOME=Te({...f,...I},a.name)}const G=Ce({mode:C,projectDir:ie,env:I}),U=G.filter(f=>f.source==="connector").map(f=>f.name);U.length>0&&!e.quiet&&m.info("manager",`[${a.name}] injecting connector skills: [${U.join(", ")}]`);const B=be(G,A.skills);let oe=B.length>0?B:void 0;const ce=ve({skillsDir:A.skills,mode:C,home:H(),env:I});return{name:r,adapterType:h,aibot:{url:o,agentId:a.agent_id,apiKey:a.api_key,clientType:t,clientVersion:n,adapterHint:j?.adapterHint??s.adapterHint??T?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??R?.adapterHint??O?.adapterHint??re,capabilities:j?.capabilities??S?.capabilities??N?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??R?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Qe(j?.localActions??S?.localActions??N?.localActions??Z?.localActions??M?.localActions??x?.localActions??D?.localActions??R?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,ae,["connector_rollback","connector_upgrade_push",p,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:ze(a.name,a.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...a.args??[]],env:s.env?{...s.env,...a.env}:a.env,clientType:t,...L?{provider:L}:{}},adapterOptions:y,acpAuthMethod:y.auth_method,acpInitialMode:y.initial_mode,acpMcpTools:y.acp_mcp_tools,promptTimeoutMs:a.prompt_timeout_ms,bindingsPath:He(a.agent_id),legacyBindingsPath:Fe(a.name,a.agent_id),activeEventStorePath:We(a.name,a.agent_id),pendingEventStorePath:Ke(a.agent_id),...s.enableSessionBinding||_?{enableSessionBinding:!0}:{},...de(t)?{staticCwd:pe(a.cwd)}:{},...s.autoInjectArgs||t==="reasonix"&&a.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&a.provider?.model?.trim()?{model:a.provider.model.trim()}:{}}}:{},poolMaxSize:a.pool?.maxSize??(h==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:a.pool?.idleTimeoutMs,eventQueue:Ve(h,a.event_queue),logDir:A.log,providerBaseUrl:a.provider_base_url?.trim()||void 0,providerApiKey:a.provider_api_key?.trim()||void 0}}function J(){const a=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):qe}function $(){const a=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):Ge}function Ye(){return Math.min($(),Ue)}function P(a){if(a===null||typeof a!="object")return JSON.stringify(a)??"null";if(Array.isArray(a))return`[${a.map(P).join(",")}]`;const e=a;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${P(e[t])}`).join(",")}}`}function Je(a,e){return P(a)===P(e)}class Mt{options;instances=[];configMap=new Map;rawConfigMap=new Map;mutationTail=Promise.resolve();startingInstances=new Set;failedStartAgents=new Set;removingAgents=new Set;instanceGenerations=new WeakMap;sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;lifecycleAdmissionClosed=!1;deletedAgentCleanups=new Set;pendingPlatformDeletes=new Map;upgradeChecker=null;skillSyncer=null;globalConfigStore;configRepository=new X(A.config);sharedOwnersCache=new ge(A.data);installer=new De;relaySecretResolver;auditProducer=Oe();constructor(e={}){this.options=e}runMutation(e,n=[]){const t=this.mutationTail.catch(()=>{}).then(async()=>{if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});await this.retryPendingPlatformDeletesUnlocked();const s=new Set([...this.pendingPlatformDeletes.values()].map(c=>c.name)),i=n.find(c=>s.has(c.trim()));if(i)throw Object.assign(new Error(`Agent "${i}" is pending permanent platform-deletion cleanup`),{code:"AGENT_DELETE_PENDING"});return e()});return this.mutationTail=t.then(()=>{},()=>{}),t}async startTrackedInstance(e){this.startingInstances.add(e);try{await e.start()}finally{this.startingInstances.delete(e)}}requestStartCancellation(e){const n=e.requestStop;typeof n=="function"&&n.call(e)}async stopInstance(e,n,t=$()){let s;try{await Promise.race([e.stop(n),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`Agent "${e.name}" stop timed out after ${t}ms`),{code:"AGENT_STOP_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForLifecycleDrain(e,n,t=$()){let s;try{await Promise.race([Promise.allSettled([...e]).then(()=>{}),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"LIFECYCLE_DRAIN_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForShutdownOperation(e,n,t){let s;try{return await Promise.race([e,new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"SHUTDOWN_OPERATION_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}isActiveGeneration(e){const n=this.instanceGenerations.get(e);return!!n&&!n.retired&&this.instances.find(t=>t.name===n.name)===e}retireInstance(e){const n=this.instanceGenerations.get(e);n&&(n.retired=!0)}async start(e){return this.runMutation(()=>this.startUnlocked(e))}async startUnlocked(e){const n=e??A.config;this.configRepository=new X(n),m.info("manager",`Loading configs from ${n}`),Ee(),W(),this.globalConfigStore=new Se(b(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const r of s)m.error("manager",`Failed to load ${r.file}: ${r.error}`);for(const r of i)m.info("manager",`Skipped ${r}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&i.length===0){m.warn("manager",`No agent configurations found in ${n}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const c=[];let o=s.length;for(const{entry:r,file:l}of t)try{const g=this.toRuntimeInstanceConfig(r);c.push({config:g,entry:r,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const p=typeof r?.name=="string"?r.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${p}): ${g}`),o++}c.length>0&&await we();let u=0;if(c.length>0){const r=J();m.info("manager",`Starting ${c.length} agent(s), startup wait=${r}ms`);const l=d=>{this.instances=this.instances.filter(h=>h!==d)},g=c.map(({config:d,entry:h,file:_})=>{const w=this.createConfiguredInstance(d);return this.instances.push(w),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:h,file:_}),{config:d,instance:w,startPromise:this.prepareProviderRuntime(d,h).then(()=>{if(this.stopping)throw this.requestStartCancellation(w),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(w)})}}),p=await Promise.all(g.map(async d=>{const h=await new Promise(_=>{let w=!1;const y=setTimeout(()=>{w||(w=!0,_({kind:"timeout"}))},r);d.startPromise.then(()=>{w||(w=!0,clearTimeout(y),_({kind:"started"}))}).catch(S=>{w||(w=!0,clearTimeout(y),_({kind:"failed",error:S}))})});return{task:d,outcome:h}}));for(const{task:d,outcome:h}of p){if(h.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(h.kind==="failed"){if(E(h.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(_){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up partially started ${d.config.name}: ${_}`)}m.error("manager",`Failed to start ${d.config.name}: ${h.error}`);continue}u++,m.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{this.stopping||this.removingAgents.has(d.config.name)||this.isActiveGeneration(d.instance)&&(m.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config))}).catch(async _=>{if(E(_)){this.onAgentDeletedByPlatform(d.instance);return}if(!(this.stopping||this.removingAgents.has(d.config.name))&&this.isActiveGeneration(d.instance)){try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(w){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up delayed start ${d.config.name}: ${w}`)}m.error("manager",`Delayed start failed: ${d.config.name}: ${_}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-u);m.info("manager",`${d}/${c.length} agent(s) running now`)}u>0&&m.warn("manager",`${u} agent(s) still connecting in background`)}if(this.instances.length===0&&c.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.stopping||this.configMap.size===0)return;const e=[...this.configMap.values()].map(n=>({apiKey:n.aibot.apiKey,wsUrl:n.aibot.url}));if(!this.upgradeChecker&&(this.upgradeChecker=new ye(e,()=>this.describeAnyPendingOrBackgroundWork(),()=>this.closeAllLifecycleAdmission(),{requestGracefulShutdown:this.options.requestGracefulShutdown,reopenLifecycleAdmission:()=>this.reopenAllLifecycleAdmission(),isConnected:()=>this.instances.length===0||this.instances.some(n=>n.getStatus().wsConnected),onTransactionSettled:this.options.onTransactionSettled}),await this.upgradeChecker.start(),this.stopping)){this.upgradeChecker.stop();return}this.skillSyncer||(this.skillSyncer=new Ae(e,A.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start(),this.stopping&&this.skillSyncer.stop())}refreshOwnerLibrarySkills(){const e=new Map,n=t=>{let s;try{s=t.skillsSyncGroupKey()}catch(c){m.warn("manager",`skillsSyncGroupKey failed for ${t.name}: ${c}`);return}const i=e.get(s)??[];i.push(t),e.set(s,i)};for(const t of this.instances)n(t);for(const t of this.sharedInstances.values())n(t);for(const[t,s]of e){let i=!1;const c=[];for(const o of s){if(i){c.push(o);continue}let u=!1;try{u=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(r){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${r}`)}if(u){i=!0;continue}m.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!i){m.warn("manager",`owner library skills: no reporter succeeded group=${t}`);continue}for(const o of c)try{o.adoptSkillsWireHashFromDisk()}catch(u){m.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${u}`)}}}async stop(){m.info("manager","Stopping all agents..."),this.stopping=!0;const e=Ye(),n=Date.now()+e,t=()=>Math.max(1,n-Date.now()),s=new Set([...this.instances,...this.sharedInstances.values(),...this.startingInstances]);for(const o of s)this.requestStartCancellation(o);const i=new Map([...s].map(o=>[o,this.stopInstance(o,void 0,e)])),c=[];this.upgradeChecker?.stop(),this.skillSyncer?.stop();try{await this.waitForLifecycleDrain([this.mutationTail,...this.shareSyncChains.values(),...i.values()],"manager shutdown lifecycle drain",t())}catch(o){c.push(o)}this.upgradeChecker?.stop(),this.skillSyncer?.stop(),this.shareSyncChains.clear(),await Promise.all([...[...this.instances].map(async o=>{try{await(i.get(o)??this.stopInstance(o,void 0,t())),this.retireInstance(o),this.instances=this.instances.filter(u=>u!==o),this.startingInstances.delete(o)}catch(u){c.push(u)}}),...[...this.sharedInstances.entries()].map(async([o,u])=>{try{await(i.get(u)??this.stopInstance(u,void 0,t())),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o),this.startingInstances.delete(u)}catch(r){c.push(r)}})]);try{await this.waitForLifecycleDrain([this.retryPendingPlatformDeletesUnlocked(n)],"platform-delete shutdown drain",t())}catch(o){c.push(o)}try{await this.waitForShutdownOperation(Promise.resolve().then(()=>this.globalConfigStore?.flush()),"global config shutdown flush",t())}catch(o){c.push(o)}if(await this.auditProducer.stop({timeoutMs:Math.min(5e3,t())}).catch(()=>!1),W(),c.length>0)throw new AggregateError(c,"Failed to stop all agents completely");m.info("manager","All stopped")}onShareSet(e,n,t){if(this.stopping||this.removingAgents.has(n.name)||!this.isActiveGeneration(e))return;this.sharedOwnersCache.save(n.name,t);const i=(this.shareSyncChains.get(n.name)??Promise.resolve()).catch(()=>{}).then(()=>{if(!(this.stopping||this.removingAgents.has(n.name))&&this.isActiveGeneration(e))return this.syncSharedInstances(n,t,e)});this.shareSyncChains.set(n.name,i)}async syncSharedInstances(e,n,t){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))return;const{toAdd:s,toRemove:i}=ue(e.name,this.sharedInstances.keys(),n);for(const c of s){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))break;const o=me(e.name,c);let u;try{const r=he(e,c);u=new F(r,this.globalConfigStore,this.auditProducer),u.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),u.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),u.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&u.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&u.closeLifecycleAdmission(),this.sharedInstances.set(o,u),await this.startTrackedInstance(u),u.forceRefreshSkills(void 0,{force:!0}),m.info("manager",`shared instance started: ${o}`)}catch(r){if(u&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(u),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o)}catch(g){m.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=r instanceof Error?r.message:String(r);/Auth failed/i.test(l)?(this.sharedOwnersCache.remove(e.name,c),m.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):m.error("manager",`start shared instance failed ${o}: ${r}`)}}for(const{key:c}of i){const o=this.sharedInstances.get(c);if(o)try{await this.stopInstance(o),this.sharedInstances.get(c)===o&&this.sharedInstances.delete(c),m.info("manager",`shared instance stopped: ${c}`)}catch(u){m.error("manager",`stop shared instance failed ${c}: ${u}`)}}}restoreCachedSharedInstances(e){const n=this.sharedOwnersCache.load(e.name);if(n.length===0)return;const t=this.instances.find(s=>s.name===e.name);!t||!this.isActiveGeneration(t)||(m.info("manager",`restoring ${n.length} cached shared instance(s) for ${e.name}`),this.onShareSet(t,e,n))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){return this.runMutation(()=>this.addAgentUnlocked(e),[String(e.name??"")])}async addAgentUnlocked(e){const n=this.toRuntimeInstanceConfig(e,{quiet:!0});if(this.instances.some(t=>t.name===n.name))throw new Error(`Agent "${n.name}" already exists`);this.configRepository.assertCanAdd(e),await this.addAgentInternal(e,"agents.json",{targetPersisted:!1});try{const t=this.configRepository.insert(e);this.rawConfigMap.set(e.name,t);const s=this.instances.find(c=>c.name===e.name),i=s?this.instanceGenerations.get(s):void 0;if(i){i.persisted=!0;const c=this.configMap.get(e.name);c&&this.restoreCachedSharedInstances(c)}}catch(t){try{await this.removeAgentInternal(e.name)}catch(s){throw new AggregateError([t,s],`Failed to persist and roll back agent "${e.name}"`)}throw t}await this.ensureAuxServices(),m.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,n,t){const s=this.toRuntimeInstanceConfig(e);if(this.instances.some(i=>i.name===s.name))throw new Error(`Agent "${s.name}" already exists`);await this.startInstanceFromConfig(s,e,n,t)}createConfiguredInstance(e,n=!0){const t=new F(e,this.globalConfigStore,this.auditProducer);return this.instanceGenerations.set(t,{name:e.name,agentId:e.aibot.agentId,persisted:n,retired:!1,platformDeletedObserved:!1}),t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),this.options.requestGracefulShutdown&&t.setDaemonShutdownRequester(this.options.requestGracefulShutdown),t.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(s)),t.setRemoteAdminPorts({isEnabled:()=>this.remoteAdminGate?.()??!1,listInstallable:()=>this.listInstallable(),installAgent:s=>this.installAgent(s),getInstallProgress:s=>this.getInstallProgress(s),addAgent:s=>this.addAgent(s),probeAll:s=>this.probeAll(s)}),t.setShareSetHandler(s=>this.onShareSet(t,e,s)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(t)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(s=>this.setAgentProvider(e.name,s)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},getAppliedMode:()=>this.relayStateApplier?.getAppliedMode?.(e.name),applyEnable:(s,i)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,s,i):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const s=this.relayStateApplier;return s?s.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>Y(this.getAgentProvider(e.name))),t}describeAnyPendingOrBackgroundWork(){return[...this.instances.flatMap(e=>e.describePendingOrBackgroundWork()),...[...this.sharedInstances.values()].flatMap(e=>e.describePendingOrBackgroundWork())]}closeAllLifecycleAdmission(){this.lifecycleAdmissionClosed=!0;for(const e of this.instances)e.closeLifecycleAdmission();for(const e of this.sharedInstances.values())e.closeLifecycleAdmission()}reopenAllLifecycleAdmission(){if(!this.stopping){this.lifecycleAdmissionClosed=!1;for(const e of this.instances)e.openLifecycleAdmission();for(const e of this.sharedInstances.values())e.openLifecycleAdmission()}}async prepareProviderRuntime(e,n){const t=this.resolveAgentProvider(n.provider);K(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await z(e.name,{baseUrl:t.base_url.trim(),apiKey:t.api_key.trim(),model:t.model.trim()})}async startInstanceFromConfig(e,n,t,s){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});if(await this.prepareProviderRuntime(e,n),this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});const i=this.createConfiguredInstance(e,s.targetPersisted);this.instances.push(i);const c=this.startTrackedInstance(i),o=J(),u=await new Promise(p=>{let d=!1;const h=setTimeout(()=>{d||(d=!0,p({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(h),p({kind:"started"}))},_=>{d||(d=!0,clearTimeout(h),p({kind:"failed",error:_}))})}),r=this.instanceGenerations.get(i);if(r?.platformDeletedObserved&&!r.persisted){const p=new fe(`Agent "${e.name}" was deleted before its local configuration commit`);try{await this.stopInstance(i),this.retireInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){throw this.failedStartAgents.add(e.name),new AggregateError([p,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw p}if(u.kind==="started"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),this.failedStartAgents.delete(e.name),s.targetPersisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.();return}if(u.kind==="timeout"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),m.warn("manager",`Start pending for ${e.name}, continue retrying in background`),c.then(async()=>{if(!this.removingAgents.has(e.name)&&this.isActiveGeneration(i)){if(this.stopping){try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i)}catch(p){this.failedStartAgents.add(e.name),m.error("manager",`Failed to stop late-started ${e.name}: ${p}`)}return}this.failedStartAgents.delete(e.name),this.instanceGenerations.get(i)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),m.info("manager",`Delayed start succeeded: ${e.name}`)}},async p=>{if(E(p)){this.onAgentDeletedByPlatform(i);return}if(!(this.stopping||this.removingAgents.has(e.name))&&this.isActiveGeneration(i)){try{await this.stopInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){this.failedStartAgents.add(e.name),m.error("manager",`Failed to clean up delayed start ${e.name}: ${d}`)}m.error("manager",`Delayed start failed ${e.name}: ${p}`)}}).catch(p=>{m.error("manager",`Delayed start finalizer failed ${e.name}: ${p}`)});return}const l=u.error;E(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i),this.failedStartAgents.delete(e.name)}catch(p){g=p,this.failedStartAgents.add(e.name)}throw s.targetPersisted&&(this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t})),g!==void 0?new AggregateError([l,g],`Failed to start and clean up agent "${e.name}"`):l}async removeAgent(e){return this.runMutation(()=>this.removeAgentUnlocked(e),[e])}async removeAgentUnlocked(e){if(!(this.instances.some(t=>t.name===e)||this.rawConfigMap.has(e)||[...this.sharedInstances.keys()].some(t=>t.startsWith(`${e}#shared:`))))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});this.configRepository.remove(e),await this.removeAgentInternal(e),m.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,n){this.removingAgents.add(e);try{const t=()=>n?.deadlineMs===void 0?$():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(p=>p.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},u=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&u.set(i,this.stopInstance(i,o,t())));for(const[p,d]of this.sharedInstances)p.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&u.set(d,this.stopInstance(d,o,t())));const r=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...r?[r]:[],...u.values()],`agent "${e}" shared lifecycle drain`,t())}catch(p){l.push(p)}const g=[];for(const[p,d]of[...this.sharedInstances.entries()])p.startsWith(c)&&g.push((u.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(p)===d&&this.sharedInstances.delete(p),this.startingInstances.delete(d)}).catch(h=>{l.push(h),m.error("manager",`stop shared instance failed ${p}: ${h}`)}));if(i)try{await(u.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const p=this.instances.indexOf(i);p!==-1&&this.instances.splice(p,1),this.startingInstances.delete(i)}catch(p){l.push(p)}if(await Promise.all(g),!n?.keepShareCache){const p=Q(e).catch(()=>{});if(n?.deadlineMs===void 0)await p;else try{await this.waitForLifecycleDrain([p],`agent "${e}" relay shutdown`,t())}catch(d){l.push(d)}}if(l.length>0)throw new AggregateError(l,`Failed to stop agent "${e}" completely`);this.configMap.delete(e),this.rawConfigMap.delete(e),this.failedStartAgents.delete(e),n?.keepShareCache||this.sharedOwnersCache.delete(e)}finally{this.removingAgents.delete(e)}}onAgentDeletedByPlatform(e){const n=this.instanceGenerations.get(e);if(!n||(n.platformDeletedObserved=!0,this.requestStartCancellation(e),!n.persisted))return;const t={source:e,name:n.name,agentId:n.agentId};this.pendingPlatformDeletes.set(e,t),!this.stopping&&(this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),this.runMutation(async()=>{}).catch(()=>{}).finally(()=>{this.deletedAgentCleanups.delete(e)})))}async retryPendingPlatformDeletesUnlocked(e){if(this.pendingPlatformDeletes.size!==0)for(const[n,t]of[...this.pendingPlatformDeletes])try{await this.cleanupPlatformDeletedUnlocked(t,e),this.pendingPlatformDeletes.delete(n)}catch(s){m.error("manager",`cleanup for deleted agent "${t.name}" failed: ${s}`)}}async cleanupPlatformDeletedUnlocked(e,n){const{source:t,name:s,agentId:i}=e,c=this.instances.find(g=>g.name===s),o=c?this.instanceGenerations.get(c)?.agentId??String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim():void 0;if(c&&c!==t&&o!==i)return;m.warn("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`);const u=this.rawConfigMap.get(s),r=this.configMap.get(s),l=[];if(c&&o===i)try{await this.removeAgentInternal(s,{deadlineMs:n})}catch(g){l.push(g)}try{const g=this.configRepository.scan();if(g.fileErrors.length>0){const h=g.fileErrors.map(_=>`${_.file}: ${_.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${h}]`)}const p=g.entries.filter(h=>String(h.entry?.name??"").trim()===s);if(!p.some(h=>String(h.entry?.agent_id??"").trim()!==i)&&p.length>0&&this.configRepository.remove(s),l.length===0){const h=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!h||h===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),u&&this.rawConfigMap.set(s,u),r&&this.configMap.set(s,r)}if(l.length>0)throw new AggregateError(l,`Failed to fully clean up deleted agent "${s}"`);m.info("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406`)}isAgentBusy(e){return this.instances.find(t=>t.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const n=this.instances.find(t=>t.name===e);return n?(n.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}remoteAdminGate;setRemoteAdminGate(e){this.remoteAdminGate=e}relayStateApplier;setRelayStateApplier(e){this.relayStateApplier=e}reportRelayStateLocalChange(e){this.instances.find(t=>t.name===e)?.reportRelayStateLocalChange()}setRelaySecretResolver(e){this.relaySecretResolver=e}resolveAgentProvider(e){if(!e?.api_key_ref?.trim())return e;const n=e.api_key_ref.trim(),t=this.relaySecretResolver?.(n);if(!t)throw Object.assign(new Error(`relay credential "${n}" is unavailable`),{code:"RELAY_SECRET_UNAVAILABLE"});return{...e,api_key:t}}toRuntimeInstanceConfig(e,n={}){const t=this.resolveAgentProvider(e.provider);return Xe(t===e.provider?e:{...e,provider:t},n)}getAgentProvider(e){return this.resolveAgentProvider(this.rawConfigMap.get(e)?.entry.provider)}async restartAgent(e){return this.runMutation(()=>this.restartAgentUnlocked(e),[e])}async restartAgentUnlocked(e){const n=this.rawConfigMap.get(e);if(!n)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,n.entry,n.file),m.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,n,t){return this.runMutation(()=>this.setAgentProviderUnlocked(e,n,t),[e])}async setAgentProviderUnlocked(e,n,t){if(!this.rawConfigMap.get(e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const i=n?.api_key_ref?.trim()?Object.fromEntries(Object.entries(n).filter(([r])=>r!=="api_key")):n,c=this.configRepository.updateExisting(e,r=>{const l={...r};if(i===void 0)delete l.provider;else{const g=i.quota_api_key?.trim()||r.provider?.quota_api_key?.trim();l.provider=g?{...i,quota_api_key:g}:i}return this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const u=String(o.client_type??"").trim().toLowerCase();try{K(u)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await z(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await Q(e))}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}if(t?.deferRestart){this.instances.find(r=>r.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}m.info("manager",`Updated provider config for agent: ${e}`)}hasDirectRelayConfig(e){const n=this.rawConfigMap.get(e)?.entry.provider;return!!(n?.api_key_ref?.trim()||n?.api_key?.trim())}getDirectRelayConfigAgentNames(){return[...this.rawConfigMap.entries()].filter(([,e])=>!!e.entry.provider&&(Pe(e.entry.client_type)||["claude","codex"].includes(String(e.entry.client_type??"").trim().toLowerCase()))).map(([e])=>e)}async fetchRelayCredential(e,n){const t=this.instances.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.fetchRelayCredential(n)}async clearDirectProviderConfigs(){const e=this.getDirectRelayConfigAgentNames(),n=[];for(const t of e)try{await this.setAgentProvider(t,void 0,{deferRestart:this.isAgentBusy(t)}),n.push(t)}catch(s){m.warn("manager",`Failed to clear provider config for "${t}": ${s instanceof Error?s.message:String(s)}`)}return n}async replaceInstance(e,n,t){const s=this.toRuntimeInstanceConfig(n);try{await this.removeAgentInternal(e,{keepShareCache:!0})}catch(o){throw this.failedStartAgents.add(e),o}const i=String(n.agent_id??"").trim();if([...this.pendingPlatformDeletes.values()].some(o=>o.name===e&&o.agentId===i))throw await this.retryPendingPlatformDeletesUnlocked(),Object.assign(new Error(`Agent "${e}" was permanently deleted while its instance was stopping`),{code:"AGENT_DELETE_PENDING"});try{await this.startInstanceFromConfig(s,n,t,{targetPersisted:!0})}catch(o){throw this.configMap.set(e,s),this.rawConfigMap.set(e,{entry:n,file:t}),o}}async reload(){return this.runMutation(()=>this.doReload())}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:n,skipped:t}=this.configRepository.scan();for(const r of t)m.info("manager",`reload: skipped ${r}: not an agent config (no "agents" key)`);if(n.length>0){const r=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${r}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:r}of e)try{this.toRuntimeInstanceConfig(r,{quiet:!0})}catch(l){const g=r?.name,p=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:p,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const r=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${r}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(r=>r.name));for(const r of e){const l=String(r.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,r)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},u=new Set([...this.rawConfigMap.keys()].filter(r=>!c.has(r)));for(const r of u)if(!i.has(r))try{await this.removeAgentInternal(r),o.removed.push(r)}catch(l){o.failed.push({name:r,error:l instanceof Error?l.message:String(l)})}for(const[r,l]of i){const g=this.rawConfigMap.get(r);if(g)if(!Je(g.entry,l.entry)||!this.instances.some(p=>p.name===r)||this.failedStartAgents.has(r))try{await this.replaceInstance(r,l.entry,l.file),o.restarted.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}else this.rawConfigMap.set(r,l),o.unchanged.push(r);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}}return m.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),await this.ensureAuxServices(),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Ze(this.instances,e)}async probeOne(e,n={}){return et(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return Re(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Ze(a,e){const n=e.concurrency??4,t=Date.now(),s=new Array(a.length);await new Promise(r=>{let l=0,g=0;const p=a.length;if(p===0){r();return}function d(w){const y=a[w];y.probe(e).then(S=>{s[w]=S,h()},S=>{s[w]={agent_name:y.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:S?.message??String(S)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},h()})}function h(){g++,l<p?d(l++):g===p&&r()}const _=Math.min(n,p);for(let w=0;w<_;w++)d(l++)});const i=s.filter(r=>r.status==="healthy").length,c=s.filter(r=>r.status==="degraded").length,o=s.filter(r=>r.status==="unavailable").length,u=await V();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:u,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function et(a,e,n){const t=a.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{Mt as Manager,Y as normalizeAgentProviderForRuntime,V as probeInstalledClientCommands,Ze as probeInstances,et as probeOneInstance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as i from"node:net";const e={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function n(o){const u={bind:o?.bind??e.bind,port:o?.port??e.port,endpoint:o?.endpoint??e.endpoint,sessionTimeoutMs:o?.sessionTimeoutMs??e.sessionTimeoutMs,invokeTimeoutMs:o?.invokeTimeoutMs??e.invokeTimeoutMs,allowedOrigins:o?.allowedOrigins,allowedHosts:o?.allowedHosts};return s(u.bind),u.port!==0&&t(u.port),r(u.sessionTimeoutMs),u}function s(o){if(!o||!i.isIPv4(o)&&!i.isIPv6(o))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${o}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function t(o){if(!Number.isInteger(o)||o<1||o>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(o){if(!Number.isInteger(o)||o<1e3||o>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{n as createDefaultGatewayConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const r=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(
|
|
1
|
+
function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(
|
|
1
|
+
import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(t,e,r,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,r);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(t.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${t.status}`);if(p(e))return this.executeEventTool(t,e,r);const o=i(e,r);try{const u=await t.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(t){if(t==null||typeof t!="object")return this.successResult(t??null);const e=t,r=typeof e.code=="number"?e.code:0;if(r===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${r}]: ${n}`)}successResult(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}errorResult(t){return{content:[{type:"text",text:t}],isError:!0}}async executeEventTool(t,e,r){return e==="grix_access_control"?this.executeAccessControl(t,r):d(t,e,r)}async executeAccessControl(t,e){const r=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[r];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${r}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await t.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TOOLS as
|
|
1
|
+
import{TOOLS as s,EVENT_TOOLS as t}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...s.filter(o=>e.has(o.name)),...t.filter(o=>r.has(o.name))],this.toolMap=new Map(this.tools.map(o=>[o.name,o]))}getTools(){return this.tools}getTool(o){return this.toolMap.get(o)}hasTool(o){return this.toolMap.has(o)}}export{a as ToolRegistryImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(
|
|
1
|
+
const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(u,t){const e=C[u];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${u}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,r]of Object.entries(t)){if(r==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,r,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(u,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${u} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${u} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const r=t[i];if(e.items.type==="string"&&typeof r!="string")return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.type==="integer"){if(typeof r!="number"||!Number.isInteger(r))return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.enum&&!e.items.enum.includes(r))return`\u53C2\u6570 ${u}[${i}] \u503C ${r} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "grix-connector",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.18.0",
|
|
4
4
|
"description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: locate-code-by-layer
|
|
3
|
-
description: "Token-bounded, architecture-first code location through a private codebase-memory Gateway. Use whenever an Agent must understand or change implementation code: diagnose bugs, add features, refactor, review code, locate routes/controllers/services/models/views, find symbol definitions, or trace call paths and dependencies. It selects a layer and module before symbol lookup, returns compact metadata and file/line ranges instead of source, and replaces direct use of raw codebase-memory MCP tools. Do not use it for a pure documentation/configuration lookup when an exact literal and narrow path are already known."
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Locate Code By Layer
|
|
7
|
-
|
|
8
|
-
Use the `codebase-navigator` MCP as the only routine code-discovery interface. It privately calls codebase-memory, enforces layer-first navigation, and returns a compact location packet.
|
|
9
|
-
|
|
10
|
-
## Agent decision
|
|
11
|
-
|
|
12
|
-
Before reading implementation files, ask whether the task requires finding where behavior is defined or connected. If yes, invoke this skill and start with `locate_code`. Do not attempt a repository-wide search first.
|
|
13
|
-
|
|
14
|
-
Provide the whole problem in one request. Include the observed behavior, expected behavior, exact error text, known symbol, route, or path hint when available. More discriminating input produces a smaller result.
|
|
15
|
-
|
|
16
|
-
## Required workflow
|
|
17
|
-
|
|
18
|
-
1. Call `locate_code` once with the complete problem. Include an exact error, known symbol, or path hint when available.
|
|
19
|
-
2. Follow the returned status:
|
|
20
|
-
- `located`: read only `recommended_reads`, beginning with the first range.
|
|
21
|
-
- `ambiguous`: call `refine_location` with one returned layer or candidate. Do not restart a global search.
|
|
22
|
-
- `architecture_uncertain`: follow `next_action`. If it is `refine_location`, reuse the returned `locator_id` with one exact symbol/path clue. Otherwise call `get_project_outline`, choose a layer, then call `locate_code` with that layer.
|
|
23
|
-
- `insufficient_coverage`: use `refine_location` with one discriminating hint. If still unresolved, report the indexed scope gap.
|
|
24
|
-
- `dependency_missing`: stop discovery, explain that Codebase is required, and ask whether the user wants it installed. Never install it without explicit approval.
|
|
25
|
-
- `dependency_misconfigured`, `dependency_not_executable`, or `dependency_unhealthy`: stop discovery, report the exact dependency repair action, and ask before changing system configuration or permissions. Do not misdiagnose these states as a narrower-problem issue.
|
|
26
|
-
- `not_indexed`: stop discovery, explain that the resolved project has no usable Codebase index, and ask whether the user wants it indexed with the official Codebase tooling.
|
|
27
|
-
- `stale_index`: stop discovery and ask whether the user wants the project index refreshed.
|
|
28
|
-
3. After reading at most the recommended ranges, form a concrete hypothesis. Read one directly related symbol only if the first range is insufficient.
|
|
29
|
-
4. Modify code and run the narrowest relevant test only after the target is established.
|
|
30
|
-
|
|
31
|
-
Installation, dependency repair, first-time indexing, and index refresh are external mutations and require explicit user confirmation. The read-only Gateway only detects these states and returns a consent-aware `next_action`; it never installs Codebase, changes system configuration or permissions, or changes an index itself.
|
|
32
|
-
|
|
33
|
-
For a location-only question, the first direct definition, assignment, or registration matching the requested construct is terminal evidence. Stop immediately and report that file/range; do not inspect callers, callees, adjacent implementations, or alternative files unless the user asked for behavior analysis.
|
|
34
|
-
|
|
35
|
-
## Tool rules
|
|
36
|
-
|
|
37
|
-
- Treat `locate_code` as the default entry point.
|
|
38
|
-
- When a path or symbol is known, pass it as `fileHint` or `knownSymbol`; the Gateway uses one compact, source-free exact search before falling back to architecture routing.
|
|
39
|
-
- Use `get_project_outline` only when architecture is uncertain or the user explicitly asks for an architecture view.
|
|
40
|
-
- Refine a locator at most twice. If two refinements fail, ask for a symbol, error text, or path clue.
|
|
41
|
-
- Never request pagination or expand all matches.
|
|
42
|
-
- Never ask the Gateway for source; open the returned repository-relative line ranges using the local filesystem.
|
|
43
|
-
- Do not call raw `search_graph`, `trace_path`, `get_code_snippet`, `query_graph`, or `get_architecture` from the hidden downstream MCP.
|
|
44
|
-
- Do not automatically install Codebase, create an index, or refresh an index. Ask the user first, then use only the official Codebase installation and indexing workflow after approval.
|
|
45
|
-
|
|
46
|
-
## Narrow fallback
|
|
47
|
-
|
|
48
|
-
Use shell search only for an exact error string, configuration key, generated file, Markdown, shell script, or a path explicitly reported as uncovered. Limit it to the selected module. Never run repository-wide broad search or read whole source files as a substitute for the Gateway.
|
|
49
|
-
|
|
50
|
-
After the Gateway exhausts its refinements, the entire shell fallback budget is one exact-literal search inside the selected layer/module and at most two exact line-range reads. Do not issue a second `rg`, widen the path, scan directories, or read a whole source file. If that budget does not establish the target, report the unresolved index/scope gap. For a location-only task, stop after the first matching definition, assignment, or registration.
|
|
51
|
-
|
|
52
|
-
## Result contract
|
|
53
|
-
|
|
54
|
-
The Gateway returns a location packet, never source code. The Agent receives:
|
|
55
|
-
|
|
56
|
-
- `status` and `next_action`, telling the Agent whether to read, refine, inspect the outline, or refresh the index;
|
|
57
|
-
- dependency failures use `offer_install`, `repair_dependency_config`, `repair_dependency_permissions`, or `repair_dependency`;
|
|
58
|
-
- missing and stale indexes use `offer_index` or `offer_index_refresh`;
|
|
59
|
-
- `selected_layer` and bounded module scopes, explaining which architectural area was chosen;
|
|
60
|
-
- at most three ranked symbol candidates with stable candidate IDs and confidence evidence;
|
|
61
|
-
- `recommended_reads`, containing at most two repository-relative files and exact line ranges;
|
|
62
|
-
- at most five one-hop callers, callees, or dependencies needed to validate the target;
|
|
63
|
-
- `locator_id` for at most two bounded refinements;
|
|
64
|
-
- an index fingerprint and response-budget record for freshness and token auditing.
|
|
65
|
-
|
|
66
|
-
After receiving `located`, read only the first recommended range. The packet is a navigation decision, not an instruction to load every candidate.
|
|
67
|
-
|
|
68
|
-
For installation, architecture, policy limits, configuration, and status meanings, read [references/gateway-architecture.md](references/gateway-architecture.md).
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
# Layered code discovery
|
|
2
|
-
|
|
3
|
-
For any task that requires understanding, locating, diagnosing, reviewing, or
|
|
4
|
-
modifying implementation code, you MUST invoke the `locate-code-by-layer`
|
|
5
|
-
Skill before using file reads, Grep, Glob, or shell commands for discovery.
|
|
6
|
-
|
|
7
|
-
Use `mcp__codebase-navigator__locate_code` with the complete problem and any
|
|
8
|
-
known symbol, path, or exact error. Follow its `status` and `next_action`;
|
|
9
|
-
refine with the same `locator_id`. After `located`, read only the first
|
|
10
|
-
recommended file and exact line range, then form a concrete hypothesis.
|
|
11
|
-
|
|
12
|
-
Never call or configure raw codebase-memory graph tools. They are private
|
|
13
|
-
downstream dependencies of `codebase-navigator`. Repository-wide search is
|
|
14
|
-
forbidden for implementation discovery. Narrow shell search is allowed only
|
|
15
|
-
for exact literals, logs, generated files, documentation, scripts, or paths
|
|
16
|
-
the Gateway explicitly reports as uncovered.
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "grix-layer",
|
|
3
|
-
"version": "1.0.0",
|
|
4
|
-
"description": "Token-bounded, architecture-first code discovery for Grix Kimi agents",
|
|
5
|
-
"systemPromptPath": "./SYSTEM.md",
|
|
6
|
-
"interface": {
|
|
7
|
-
"displayName": "Grix Layer",
|
|
8
|
-
"shortDescription": "Bounded code discovery through codebase-navigator"
|
|
9
|
-
}
|
|
10
|
-
}
|
|
@@ -1,157 +0,0 @@
|
|
|
1
|
-
# Codebase Navigator Gateway
|
|
2
|
-
|
|
3
|
-
## Purpose
|
|
4
|
-
|
|
5
|
-
The Gateway is a JavaScript MCP server that sits between an Agent and `codebase-memory-mcp`. The Agent cannot see or invoke raw graph tools. The Gateway performs deterministic routing, bounds every fan-out, discards raw graph payloads, and returns only a small location packet.
|
|
6
|
-
|
|
7
|
-
```mermaid
|
|
8
|
-
flowchart LR
|
|
9
|
-
A[Agent] -->|3 bounded MCP tools| G[JS Codebase Navigator]
|
|
10
|
-
G --> D[Codebase dependency check]
|
|
11
|
-
D --> P[Project and index resolver]
|
|
12
|
-
P --> M[Cached architecture map]
|
|
13
|
-
P -->|architecture empty or file hint| E[One bounded exact search]
|
|
14
|
-
M --> C[Layer classifier]
|
|
15
|
-
C --> S[Scoped symbol search]
|
|
16
|
-
C -->|refinement literal| E
|
|
17
|
-
E -->|no exact hit| S
|
|
18
|
-
E -->|exact symbol metadata| B
|
|
19
|
-
S --> V[One-hop relation verifier]
|
|
20
|
-
V --> B[Response budget filter]
|
|
21
|
-
B -->|symbols and line ranges only| A
|
|
22
|
-
D -. private stdio .-> R[codebase-memory-mcp analysis profile]
|
|
23
|
-
P -. private calls .-> R
|
|
24
|
-
M -. private calls .-> R
|
|
25
|
-
S -. private calls .-> R
|
|
26
|
-
E -. private call .-> R
|
|
27
|
-
V -. private calls .-> R
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
The Gateway has no embedded LLM. Layer selection is explainable and deterministic. When confidence is low, it returns a short list of choices for the calling Agent instead of widening the graph search.
|
|
31
|
-
|
|
32
|
-
## Public MCP surface
|
|
33
|
-
|
|
34
|
-
| Tool | Use | Hard behavior |
|
|
35
|
-
| --- | --- | --- |
|
|
36
|
-
| `locate_code` | Default entry for a bug, feature, or navigation question | Use one exact hinted search when architecture is empty or a file hint is present; otherwise classify a layer and search at most three scopes |
|
|
37
|
-
| `refine_location` | Resolve a returned ambiguity | Session-bound, index-bound, maximum two refinements; one exact compact search inside the selected layer |
|
|
38
|
-
| `get_project_outline` | Inspect compact layers | Use only when architecture is uncertain |
|
|
39
|
-
|
|
40
|
-
Raw downstream tools are absent from the public tool list.
|
|
41
|
-
|
|
42
|
-
## Budgets
|
|
43
|
-
|
|
44
|
-
- Public response: 8 KiB maximum.
|
|
45
|
-
- Candidates: 3.
|
|
46
|
-
- Recommended reads: 2.
|
|
47
|
-
- Related symbols: 5.
|
|
48
|
-
- Architecture layers: 7.
|
|
49
|
-
- Modules in an outline: 12.
|
|
50
|
-
- Search scopes per layer: 3.
|
|
51
|
-
- Internal search results per scope: 20; discarded after ranking.
|
|
52
|
-
- Exact hinted/refinement search: one call, compact metadata only, 5 results maximum, zero source context. A file hint limits the path filter; an empty architecture uses a bounded project-wide exact search.
|
|
53
|
-
- Relation depth: exactly one hop and one direction.
|
|
54
|
-
- Locator lifetime: 15 minutes; maximum two refinements.
|
|
55
|
-
- Downstream MCP message: 4 MiB safety ceiling.
|
|
56
|
-
|
|
57
|
-
The Gateway never auto-paginates, never requests an all-aspects architecture dump, never traces both directions, and never returns source code. If a refinement leaves the graph candidate signature unchanged, it stops and returns `progress: unchanged` instead of repeating the same candidate packet.
|
|
58
|
-
|
|
59
|
-
## Architecture maps
|
|
60
|
-
|
|
61
|
-
Maps are inferred from indexed folders and the explicit `layers`, `packages`, `boundaries`, `entry_points`, and `languages` architecture aspects. The result is cached by project and index fingerprint under:
|
|
62
|
-
|
|
63
|
-
`~/.cache/codebase-navigator/maps`
|
|
64
|
-
|
|
65
|
-
The directory and files use owner-only permissions. Cache entries contain paths and layer metadata, not source.
|
|
66
|
-
|
|
67
|
-
Keep the built-in layer vocabulary platform-neutral. Put repository-, product-, protocol-, or framework-specific routing terms in the optional project override instead of hard-coding them into the Gateway.
|
|
68
|
-
|
|
69
|
-
For nonstandard repositories, add `.codebase-navigator.json` at the indexed project root:
|
|
70
|
-
|
|
71
|
-
```json
|
|
72
|
-
{
|
|
73
|
-
"style": "hexagonal",
|
|
74
|
-
"layers": [
|
|
75
|
-
{
|
|
76
|
-
"id": "inbound",
|
|
77
|
-
"purpose": "HTTP and message entry adapters",
|
|
78
|
-
"paths": ["src/adapters/inbound"],
|
|
79
|
-
"keywords": ["route", "request", "consumer"]
|
|
80
|
-
},
|
|
81
|
-
{
|
|
82
|
-
"id": "domain",
|
|
83
|
-
"purpose": "Core rules and entities",
|
|
84
|
-
"paths": ["src/domain"],
|
|
85
|
-
"keywords": ["policy", "entity", "validation"]
|
|
86
|
-
}
|
|
87
|
-
]
|
|
88
|
-
}
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
Keep configured paths repository-relative. The Gateway reads at most 64 KiB and accepts at most seven layers and three search paths per layer.
|
|
92
|
-
|
|
93
|
-
## Installation
|
|
94
|
-
|
|
95
|
-
Grix-managed Kimi sessions receive this Gateway through the connector's authenticated loopback HTTP MCP endpoint. Do not add a plugin-level stdio MCP entry for those sessions: Kimi 0.38 routes stdio children through its Bash-only ACP runtime.
|
|
96
|
-
|
|
97
|
-
For standalone Agents that execute MCP children locally, configure the stdio server directly:
|
|
98
|
-
|
|
99
|
-
Install dependencies in the skill directory:
|
|
100
|
-
|
|
101
|
-
```bash
|
|
102
|
-
npm install
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
Configure only this MCP server:
|
|
106
|
-
|
|
107
|
-
```json
|
|
108
|
-
{
|
|
109
|
-
"mcpServers": {
|
|
110
|
-
"codebase-navigator": {
|
|
111
|
-
"command": "node",
|
|
112
|
-
"args": ["/absolute/path/to/locate-code-by-layer/scripts/gateway.mjs"]
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Ensure `codebase-memory-mcp` is on `PATH`, or set `CODEBASE_MEMORY_BINARY` to its absolute executable path. Do not also expose the raw codebase-memory server to the same Agent.
|
|
119
|
-
|
|
120
|
-
The Gateway does not install this dependency. If startup reports `dependency_missing`, the Agent must explain that Codebase is required and ask the user whether to install it. Only after explicit approval may the Agent use the official Codebase installation workflow and verify that the MCP process starts successfully.
|
|
121
|
-
|
|
122
|
-
Treat other startup failures separately and ask before changing configuration or permissions:
|
|
123
|
-
|
|
124
|
-
- `dependency_misconfigured`: the configured `CODEBASE_MEMORY_BINARY` cannot be found;
|
|
125
|
-
- `dependency_not_executable`: the binary exists but cannot be executed;
|
|
126
|
-
- `dependency_unhealthy`: the process was found but startup or MCP handshake failed.
|
|
127
|
-
|
|
128
|
-
Do not offer a reinstall for every startup error and do not expose raw downstream stderr, which may contain source paths or code.
|
|
129
|
-
|
|
130
|
-
## First-time indexing
|
|
131
|
-
|
|
132
|
-
The Gateway detects index state but remains read-only. When the current directory is not contained by any indexed project, it returns `not_indexed` even if exactly one unrelated indexed project exists. It never falls back to that unrelated project.
|
|
133
|
-
|
|
134
|
-
For `not_indexed`, the Agent must identify the intended project root and ask whether the user wants an index created with the official Codebase tooling. For `stale_index`, ask whether the existing index should be refreshed. Creating or refreshing an index requires explicit approval; after the operation succeeds, start a new locator rather than reusing the old one.
|
|
135
|
-
|
|
136
|
-
## Status handling
|
|
137
|
-
|
|
138
|
-
| Status | Agent action |
|
|
139
|
-
| --- | --- |
|
|
140
|
-
| `located` | Read only the returned line ranges |
|
|
141
|
-
| `ambiguous` | Select one layer or candidate with `refine_location` |
|
|
142
|
-
| `architecture_uncertain` | Follow `next_action`: refine the returned locator when present; otherwise inspect the outline |
|
|
143
|
-
| `insufficient_coverage` | Add one narrow hint; if `progress` is `unchanged`, provide an exact symbol/path or report the gap |
|
|
144
|
-
| `dependency_missing` | Explain the dependency and ask whether to install it; `next_action` is `offer_install` |
|
|
145
|
-
| `dependency_misconfigured` | Repair `CODEBASE_MEMORY_BINARY`; `next_action` is `repair_dependency_config` |
|
|
146
|
-
| `dependency_not_executable` | Repair executable permissions or configuration; `next_action` is `repair_dependency_permissions` |
|
|
147
|
-
| `dependency_unhealthy` | Diagnose startup or MCP handshake health; `next_action` is `repair_dependency` |
|
|
148
|
-
| `not_indexed` | Ask whether to index the project outside this read-only Gateway; `next_action` is `offer_index` |
|
|
149
|
-
| `stale_index` | Ask whether to refresh the index and start a new locator; `next_action` is `offer_index_refresh` |
|
|
150
|
-
| `needs_user_input` | Ask for a symbol, error, or path clue |
|
|
151
|
-
| `internal_error` | Inspect Gateway stderr; raw downstream content is intentionally suppressed |
|
|
152
|
-
|
|
153
|
-
## Agent prompt
|
|
154
|
-
|
|
155
|
-
Use this concise policy in Agent configuration:
|
|
156
|
-
|
|
157
|
-
> For code discovery, use only `codebase-navigator`. Start with `locate_code`; refine only a returned locator. Read only `recommended_reads`. For a location-only request, stop at the first direct match. Never call raw codebase-memory tools, auto-page results, perform broad repository search, or read whole source files. If Codebase is missing, ask before installing it. Ask before repairing dependency configuration or permissions. If the index is missing or stale, ask before creating or refreshing it. Never perform these mutations without explicit user approval.
|