grix-connector 4.18.0 → 4.19.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/claude/claude-adapter.js +22 -22
- package/dist/adapter/claude/config-paths.js +1 -0
- package/dist/adapter/claude/model-list.js +1 -1
- package/dist/adapter/claude/session-history.js +2 -2
- package/dist/adapter/claude/session-scanner.js +1 -1
- package/dist/adapter/claude/skill-scanner.js +2 -2
- package/dist/adapter/claude/usage-parser.js +8 -8
- package/dist/adapter/deepseek-harness/dsh-version.js +1 -1
- package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
- package/dist/adapter/opencode/opencode-transport.js +1 -1
- package/dist/adapter/opencode/opencode-v2-events.js +1 -1
- package/dist/adapter/pi/pi-adapter.js +4 -4
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/cli-install-flow.js +1 -1
- package/dist/bridge/cli-install-offer.js +1 -1
- package/dist/bridge/local-action-session-control.js +1 -1
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/bridge/session-control-open.js +1 -1
- package/dist/bridge/session-control-router.js +2 -2
- package/dist/bridge/session-list.js +2 -2
- package/dist/bridge/session-scan-cache.js +1 -1
- package/dist/bridge/session-usage.js +1 -1
- package/dist/bridge/skill-actions.js +1 -1
- package/dist/bridge/toolbar-meta.js +1 -1
- package/dist/core/config/index.js +1 -1
- package/dist/core/config/paths.js +1 -1
- package/dist/core/mcp/tools.js +1 -1
- package/dist/core/skill-sync/enable-roots.js +1 -1
- package/dist/core/skill-sync/library-skills.js +1 -1
- package/dist/core/skill-sync/skill-enable.js +1 -1
- package/dist/default-skills/grix-chat-state/SKILL.md +34 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +52 -52
- package/openclaw-plugin/index.js +164 -65
- package/openclaw-plugin/skills/grix-chat-state/SKILL.md +33 -1
- package/openclaw.plugin.json +1 -0
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.18.0.tgz +0 -0
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{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
|
+
import{join as b}from"node:path";import{homedir as W}from"node:os";import{AgentInstance as K}from"./bridge/bridge.js";import{isCwdLockedClientType as he,resolveStaticCwd as ue}from"./bridge/cwd-policy.js";import{buildSharedInstanceConfig as me,diffSharedOwners as ge,sharedInstanceKey as fe,SharedOwnersCache as _e}from"./manager-share-config.js";import{AgentDeletedError as we,isAgentDeletedError as $}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as ye}from"./core/util/client-version.js";import{mergeLoginShellPathIntoProcess as Ae}from"./core/util/cli-probe.js";import{UpgradeChecker as Se}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as ke}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as be}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as ve}from"./adapter/claude/skill-scanner.js";import{resolveClaudeConfigPaths as Ce}from"./adapter/claude/config-paths.js";import{buildWireSkills as Ie}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as Ee}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as $e}from"./core/aibot/types.js";import{buildReportedSkills as Pe,logDefaultSkillsCheck as Te,cleanupProjectedSkills as z}from"./default-skills/index.js";import{buildProviderEnv as Me,supportsKiroCwRelay as Q,supportsNonMitmRelayConfig as xe}from"./core/config/provider-env.js";import{resolveHermesHomeDir as De}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as V,stopKiroRelay as X}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as Oe}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as Re}from"./core/runtime/cursor-resolve.js";import{probeInstalledClientCommands as Y}from"./core/probe/installed-clients.js";import{AgentInstaller as je}from"./core/installer/installer.js";import{reportInstallFailure as Le}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Ne}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as qe}from"./adapter/codex/config-overrides.js";import{ACP_NEW_SESSION_RESERVED_KEYS as Ge}from"./protocol/acp-client.js";import{resolveCodexDirectHome as Ue}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as J}from"./core/config/agent-config-repository.js";import{expandHomePath as Be}from"./core/config/paths.js";function Z(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 He=8e3,Fe=1e4,We=8e3;function Ke(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(W(),".omp","agent")}};case"cursor":return{adapterType:"cursor",command:Re()};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=Oe();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 C(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 ze(a){return b(A.data,`session-bindings-${C(a,"unknown")}.json`)}function Qe(a,e){return b(A.data,`session-bindings-${C(a,e)}.json`)}function Ve(a,e){return b(A.data,`active-events-${C(a,e)}.json`)}function Xe(a){return b(A.data,`pending-events-${C(a,"unknown")}.json`)}function Ye(a,e){const n=C(a,"agent"),t=C(e,"unknown");return b(A.data,`terminal-outbox-${n}-${t}.json`)}function Je(a,e,n={}){const t=a?{...a,...e}:e;if(t)return Object.fromEntries(Object.entries(t).map(([s,r])=>[s,Be(r,n)]))}function Ze(...a){const e=[],n=new Set;for(const t of a)for(const s of t??[]){const r=String(s??"").trim(),c=r.toLowerCase();!r||n.has(c)||(n.add(c),e.push(r))}return e.length>0?e:void 0}function et(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 tt(a,e={}){const n=ye(),t=String(a.client_type??"").trim().toLowerCase(),s=Ke(t,a),r=t==="deepseek"?a.dsh?.integration_mode??"profile_bridge":void 0,c=r==="embedded_jsonrpc",o=String(a.ws_url??"").trim(),u=typeof a.name=="string"?a.name:"",i=u.trim(),l="get_session_usage",g="get_rate_limits",p="get_agent_global_config",d=$e;if(!i)throw new Error("agent name is required");if(u!==i)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=r,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`);qe(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(pe=>Ge.has(pe));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=Ue(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,te=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,M=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,x=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,D=h==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,O=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,q=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,j=h==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,L=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,G=new Set(["hermes","reasonix","kimi","copilot","acp","qodercli","qoderclicn","mcode","dim","traecli","grok","qwenpaw","zeroclaw","codebuddy"]),ne=_&&!G.has(t),se=_&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder",...ne?[l]:[]]}:null,ae=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,re=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,ie=h==="cursor"||h==="opencode"||h==="openhuman"||h==="agy"||_&&G.has(t)?[g]:[l,g];_&&y.raw_transport===void 0&&(y.raw_transport=t==="gemini");const oe=`${t}/base`,I=ve(h,t),ce=I==="kiro"?void 0:process.cwd(),N=Z(a.provider),U=Je(s.env,a.env),v={...process.env,...U};if(I==="hermes"&&!v.HERMES_HOME?.trim()){const f=Me(t,N);v.HERMES_HOME=De({...f,...v},a.name)}const E=h==="claude"?Ce(v):void 0,B=Pe({mode:I,projectDir:ce,env:v,claudeConfigPaths:E}),H=B.filter(f=>f.source==="connector").map(f=>f.name);H.length>0&&!e.quiet&&m.info("manager",`[${a.name}] injecting connector skills: [${H.join(", ")}]`);const F=Ie(B,A.skills);let le=F.length>0?F:void 0;const de=Ee({skillsDir:A.skills,mode:I,home:W(),env:v,claudeConfigPaths:E});return{name:i,adapterType:h,...E?{claudeConfigPaths:E}:{},aibot:{url:o,agentId:a.agent_id,apiKey:a.api_key,clientType:t,clientVersion:n,adapterHint:L?.adapterHint??s.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??O?.adapterHint??R?.adapterHint??j?.adapterHint??oe,capabilities:L?.capabilities??S?.capabilities??q?.capabilities??x?.capabilities??D?.capabilities??O?.capabilities??R?.capabilities??j?.capabilities??M?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Ze(L?.localActions??S?.localActions??q?.localActions??te?.localActions??x?.localActions??D?.localActions??O?.localActions??R?.localActions??j?.localActions??M?.localActions??ae?.localActions??se?.localActions??["exec_approve","exec_reject"],re,ie,["connector_rollback","connector_upgrade_push",p,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:le,librarySkills:de,terminalOutboxPath:Ye(a.name,a.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...a.args??[]],env:U,clientType:t,...N?{provider:N}:{}},adapterOptions:y,acpAuthMethod:y.auth_method,acpInitialMode:y.initial_mode,acpMcpTools:y.acp_mcp_tools,promptTimeoutMs:a.prompt_timeout_ms,bindingsPath:ze(a.agent_id),legacyBindingsPath:Qe(a.name,a.agent_id),activeEventStorePath:Ve(a.name,a.agent_id),pendingEventStorePath:Xe(a.agent_id),...s.enableSessionBinding||_?{enableSessionBinding:!0}:{},...he(t)?{staticCwd:ue(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:et(h,a.event_queue),logDir:A.log,providerBaseUrl:a.provider_base_url?.trim()||void 0,providerApiKey:a.provider_api_key?.trim()||void 0}}function ee(){const a=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):He}function P(){const a=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):Fe}function nt(){return Math.min(P(),We)}function T(a){if(a===null||typeof a!="object")return JSON.stringify(a)??"null";if(Array.isArray(a))return`[${a.map(T).join(",")}]`;const e=a;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${T(e[t])}`).join(",")}}`}function st(a,e){return T(a)===T(e)}class Nt{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 J(A.config);sharedOwnersCache=new _e(A.data);installer=new je;relaySecretResolver;auditProducer=Ne();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)),r=n.find(c=>s.has(c.trim()));if(r)throw Object.assign(new Error(`Agent "${r}" 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=P()){let s;try{await Promise.race([e.stop(n),new Promise((r,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=P()){let s;try{await Promise.race([Promise.allSettled([...e]).then(()=>{}),new Promise((r,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((r,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 J(n),m.info("manager",`Loading configs from ${n}`),Te(),z(),this.globalConfigStore=new be(b(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:r}=this.configRepository.scan();for(const i of s)m.error("manager",`Failed to load ${i.file}: ${i.error}`);for(const i of r)m.info("manager",`Skipped ${i}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&r.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:i,file:l}of t)try{const g=this.toRuntimeInstanceConfig(i);c.push({config:g,entry:i,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const p=typeof i?.name=="string"?i.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${p}): ${g}`),o++}c.length>0&&await Ae();let u=0;if(c.length>0){const i=ee();m.info("manager",`Starting ${c.length} agent(s), startup wait=${i}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"}))},i);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($(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($(_)){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 Se(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 ke(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 r=e.get(s)??[];r.push(t),e.set(s,r)};for(const t of this.instances)n(t);for(const t of this.sharedInstances.values())n(t);for(const[t,s]of e){let r=!1;const c=[];for(const o of s){if(r){c.push(o);continue}let u=!1;try{u=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(i){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${i}`)}if(u){r=!0;continue}m.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!r){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=nt(),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 r=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(),...r.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(r.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(r.get(u)??this.stopInstance(u,void 0,t())),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o),this.startingInstances.delete(u)}catch(i){c.push(i)}})]);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),z(),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 r=(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,r)}async syncSharedInstances(e,n,t){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))return;const{toAdd:s,toRemove:r}=ge(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=fe(e.name,c);let u;try{const i=me(e,c);u=new K(i,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(i){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=i instanceof Error?i.message:String(i);/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}: ${i}`)}}for(const{key:c}of r){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),r=s?this.instanceGenerations.get(s):void 0;if(r){r.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(r=>r.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 K(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,r)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,s,r):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(()=>Z(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);Q(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await V(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 r=this.createConfiguredInstance(e,s.targetPersisted);this.instances.push(r);const c=this.startTrackedInstance(r),o=ee(),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:_}))})}),i=this.instanceGenerations.get(r);if(i?.platformDeletedObserved&&!i.persisted){const p=new we(`Agent "${e.name}" was deleted before its local configuration commit`);try{await this.stopInstance(r),this.retireInstance(r),this.instances=this.instances.filter(d=>d!==r),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(r)){if(this.stopping){try{await this.stopInstance(r),this.instances=this.instances.filter(p=>p!==r)}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(r)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),m.info("manager",`Delayed start succeeded: ${e.name}`)}},async p=>{if($(p)){this.onAgentDeletedByPlatform(r);return}if(!(this.stopping||this.removingAgents.has(e.name))&&this.isActiveGeneration(r)){try{await this.stopInstance(r),this.instances=this.instances.filter(d=>d!==r),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;$(l)&&this.onAgentDeletedByPlatform(r);let g;try{await this.stopInstance(r),this.instances=this.instances.filter(p=>p!==r),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?P():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(p=>p.name===e),r=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},u=new Map;r&&(this.requestStartCancellation(r),this.startingInstances.has(r)&&u.set(r,this.stopInstance(r,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 i=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...i?[i]:[],...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(r)try{await(u.get(r)??this.stopInstance(r,o,t())),this.retireInstance(r);const p=this.instances.indexOf(r);p!==-1&&this.instances.splice(p,1),this.startingInstances.delete(r)}catch(p){l.push(p)}if(await Promise.all(g),!n?.keepShareCache){const p=X(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:r}=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!==r)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),i=this.configMap.get(s),l=[];if(c&&o===r)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()!==r)&&p.length>0&&this.configRepository.remove(s),l.length===0){const h=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!h||h===r)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),u&&this.rawConfigMap.set(s,u),i&&this.configMap.set(s,i)}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 tt(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 r=n?.api_key_ref?.trim()?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="api_key")):n,c=this.configRepository.updateExisting(e,i=>{const l={...i};if(r===void 0)delete l.provider;else{const g=r.quota_api_key?.trim()||i.provider?.quota_api_key?.trim();l.provider=g?{...r,quota_api_key:g}:r}return this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const u=String(o.client_type??"").trim().toLowerCase();try{Q(u)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await V(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await X(e))}catch(i){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),i}if(t?.deferRestart){this.instances.find(i=>i.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(i){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),i}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&&(xe(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 r=String(n.agent_id??"").trim();if([...this.pendingPlatformDeletes.values()].some(o=>o.name===e&&o.agentId===r))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 i of t)m.info("manager",`reload: skipped ${i}: not an agent config (no "agents" key)`);if(n.length>0){const i=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${i}]`),{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:i}of e)try{this.toRuntimeInstanceConfig(i,{quiet:!0})}catch(l){const g=i?.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 i=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${i}]`),{code:"RELOAD_UNSAFE"})}const r=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(i=>i.name));for(const i of e){const l=String(i.entry?.name??"").trim();l&&(c.has(l)||(r.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),r.set(l,i)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},u=new Set([...this.rawConfigMap.keys()].filter(i=>!c.has(i)));for(const i of u)if(!r.has(i))try{await this.removeAgentInternal(i),o.removed.push(i)}catch(l){o.failed.push({name:i,error:l instanceof Error?l.message:String(l)})}for(const[i,l]of r){const g=this.rawConfigMap.get(i);if(g)if(!st(g.entry,l.entry)||!this.instances.some(p=>p.name===i)||this.failedStartAgents.has(i))try{await this.replaceInstance(i,l.entry,l.file),o.restarted.push(i)}catch(p){o.failed.push({name:i,error:p instanceof Error?p.message:String(p)})}else this.rawConfigMap.set(i,l),o.unchanged.push(i);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(i)}catch(p){o.failed.push({name:i,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 at(this.instances,e)}async probeOne(e,n={}){return rt(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return Le(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function at(a,e){const n=e.concurrency??4,t=Date.now(),s=new Array(a.length);await new Promise(i=>{let l=0,g=0;const p=a.length;if(p===0){i();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&&i()}const _=Math.min(n,p);for(let w=0;w<_;w++)d(l++)});const r=s.filter(i=>i.status==="healthy").length,c=s.filter(i=>i.status==="degraded").length,o=s.filter(i=>i.status==="unavailable").length,u=await Y();return{ok:r===s.length&&s.length>0,total:s.length,healthy:r,degraded:c,unavailable:o,installed_clients:u,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function rt(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{Nt as Manager,Je as mergeAgentEnv,Z as normalizeAgentProviderForRuntime,Y as probeInstalledClientCommands,at as probeInstances,rt as probeOneInstance,tt as toInstanceConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(
|
|
1
|
+
function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
|
|
@@ -687,11 +687,11 @@ async function findSubagentFiles(root) {
|
|
|
687
687
|
async function visit(directory) {
|
|
688
688
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
689
689
|
for (const entry of entries) {
|
|
690
|
-
const
|
|
690
|
+
const path2 = join(directory, entry.name);
|
|
691
691
|
if (entry.isDirectory()) {
|
|
692
|
-
await visit(
|
|
692
|
+
await visit(path2);
|
|
693
693
|
} else if (entry.isFile() && /^agent-.*\.jsonl$/u.test(basename(entry.name))) {
|
|
694
|
-
found.push(
|
|
694
|
+
found.push(path2);
|
|
695
695
|
}
|
|
696
696
|
}
|
|
697
697
|
}
|
|
@@ -789,15 +789,15 @@ async function collectClaudeTranscript(boundary, includeSubagents) {
|
|
|
789
789
|
return evidence;
|
|
790
790
|
}
|
|
791
791
|
const offsets = isRecord(boundary.subagentOffsets) ? boundary.subagentOffsets : {};
|
|
792
|
-
for (const
|
|
793
|
-
const fileBoundary = subagentBoundary(offsets[
|
|
792
|
+
for (const path2 of paths2) {
|
|
793
|
+
const fileBoundary = subagentBoundary(offsets[path2] ?? offsets[basename(path2)]);
|
|
794
794
|
const result = await readJsonlRange(
|
|
795
|
-
|
|
795
|
+
path2,
|
|
796
796
|
fileBoundary.startOffset,
|
|
797
797
|
fileBoundary.endOffset,
|
|
798
798
|
true
|
|
799
799
|
);
|
|
800
|
-
evidence.sourcePaths.push(
|
|
800
|
+
evidence.sourcePaths.push(path2);
|
|
801
801
|
evidence.lines.push(...result.lines);
|
|
802
802
|
evidence.anomalies.push(...result.anomalies);
|
|
803
803
|
evidence.gaps.push(...result.gaps);
|
|
@@ -2413,8 +2413,8 @@ function rawExchangeResponseId(exchange) {
|
|
|
2413
2413
|
function isCodexInferenceExchange(exchange) {
|
|
2414
2414
|
const method = exchange.downstream.method.toUpperCase();
|
|
2415
2415
|
if (method !== "POST" && method !== "WEBSOCKET") return false;
|
|
2416
|
-
const
|
|
2417
|
-
return
|
|
2416
|
+
const path2 = exchange.downstream.path.toLowerCase().replace(/\/+$/, "");
|
|
2417
|
+
return path2.endsWith("/responses") || path2.endsWith("/responses/compact") || path2.endsWith("/chat/completions") || path2.endsWith("/completions");
|
|
2418
2418
|
}
|
|
2419
2419
|
function exactRawExchangeSpan(requests, exchange, responseId, usedSpanIds) {
|
|
2420
2420
|
const providerRequestId = exchange.correlation.providerRequestId;
|
|
@@ -5187,20 +5187,20 @@ async function locateSessionDirectory(job) {
|
|
|
5187
5187
|
const candidates = [];
|
|
5188
5188
|
for (const workspace of workspaces) {
|
|
5189
5189
|
if (!workspace.isDirectory()) continue;
|
|
5190
|
-
const
|
|
5191
|
-
const wirePath = join3(
|
|
5190
|
+
const path2 = join3(root, workspace.name, providerSessionId);
|
|
5191
|
+
const wirePath = join3(path2, "agents", "main", "wire.jsonl");
|
|
5192
5192
|
try {
|
|
5193
5193
|
const wireStat = await stat5(wirePath);
|
|
5194
5194
|
let cwdMatches = false;
|
|
5195
5195
|
const cwd = stringValue5(job.boundary.cwd);
|
|
5196
5196
|
if (cwd) {
|
|
5197
5197
|
try {
|
|
5198
|
-
const state = JSON.parse(await readFile4(join3(
|
|
5198
|
+
const state = JSON.parse(await readFile4(join3(path2, "state.json"), "utf8"));
|
|
5199
5199
|
cwdMatches = isRecord7(state) && (state.workDir === cwd || state.cwd === cwd);
|
|
5200
5200
|
} catch {
|
|
5201
5201
|
}
|
|
5202
5202
|
}
|
|
5203
|
-
candidates.push({ path, cwdMatches, modifiedAt: wireStat.mtimeMs });
|
|
5203
|
+
candidates.push({ path: path2, cwdMatches, modifiedAt: wireStat.mtimeMs });
|
|
5204
5204
|
} catch {
|
|
5205
5205
|
}
|
|
5206
5206
|
}
|
|
@@ -8113,13 +8113,13 @@ function addContent10(contents, content) {
|
|
|
8113
8113
|
var DeepSeekHarnessAuditAdapter = class {
|
|
8114
8114
|
provider = "deepseek-harness";
|
|
8115
8115
|
async collect(job) {
|
|
8116
|
-
const
|
|
8116
|
+
const path2 = String(job.boundary.wirePath ?? "");
|
|
8117
8117
|
const start = Number(job.boundary.wireStartOffset ?? 0);
|
|
8118
8118
|
const end = Number(job.boundary.wireEndOffset ?? start);
|
|
8119
|
-
if (!
|
|
8119
|
+
if (!path2 || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start || end - start > 32 * 1024 * 1024) return [];
|
|
8120
8120
|
let fd;
|
|
8121
8121
|
try {
|
|
8122
|
-
fd = openSync(
|
|
8122
|
+
fd = openSync(path2, "r");
|
|
8123
8123
|
} catch {
|
|
8124
8124
|
return [];
|
|
8125
8125
|
}
|
|
@@ -8487,7 +8487,7 @@ import { join as join5 } from "node:path";
|
|
|
8487
8487
|
import { homedir as homedir4, tmpdir } from "node:os";
|
|
8488
8488
|
|
|
8489
8489
|
// src/core/config/paths.ts
|
|
8490
|
-
import { join as join4 } from "node:path";
|
|
8490
|
+
import path, { join as join4 } from "node:path";
|
|
8491
8491
|
import { homedir as homedir3 } from "node:os";
|
|
8492
8492
|
var GRIX_HOME_ENV = "GRIX_CONNECTOR_HOME";
|
|
8493
8493
|
var DEFAULT_GRIX_HOME = join4(homedir3(), ".grix");
|
|
@@ -9377,9 +9377,9 @@ function replaceTranscriptPath(boundary, transcriptPath) {
|
|
|
9377
9377
|
delete next.transcriptPrefixFingerprint;
|
|
9378
9378
|
return next;
|
|
9379
9379
|
}
|
|
9380
|
-
async function fileIdentity(
|
|
9380
|
+
async function fileIdentity(path2) {
|
|
9381
9381
|
try {
|
|
9382
|
-
const source = await stat7(
|
|
9382
|
+
const source = await stat7(path2);
|
|
9383
9383
|
return `${source.dev}:${source.ino}`;
|
|
9384
9384
|
} catch {
|
|
9385
9385
|
return void 0;
|
|
@@ -9820,9 +9820,9 @@ var FileAuditReplayStore = class {
|
|
|
9820
9820
|
const directory = join8(root, auditKey);
|
|
9821
9821
|
for (const name of await readDirectory(directory)) {
|
|
9822
9822
|
if (!name.endsWith(".json")) continue;
|
|
9823
|
-
const
|
|
9824
|
-
const manifest = await this.readManifest(
|
|
9825
|
-
if (manifest) manifests.push({ path, manifest });
|
|
9823
|
+
const path2 = join8(directory, name);
|
|
9824
|
+
const manifest = await this.readManifest(path2);
|
|
9825
|
+
if (manifest) manifests.push({ path: path2, manifest });
|
|
9826
9826
|
}
|
|
9827
9827
|
}
|
|
9828
9828
|
return manifests;
|
|
@@ -9880,8 +9880,8 @@ var FileAuditReplayStore = class {
|
|
|
9880
9880
|
}
|
|
9881
9881
|
const plaintext = Buffer.from(content.value, "utf8");
|
|
9882
9882
|
const contentId = sha256(plaintext);
|
|
9883
|
-
const
|
|
9884
|
-
await this.storePlaintextBlob(
|
|
9883
|
+
const path2 = this.blobPath(contentId);
|
|
9884
|
+
await this.storePlaintextBlob(path2, contentId, plaintext);
|
|
9885
9885
|
const reference = {
|
|
9886
9886
|
contentId,
|
|
9887
9887
|
role: content.role,
|
|
@@ -9893,31 +9893,31 @@ var FileAuditReplayStore = class {
|
|
|
9893
9893
|
truncated: false,
|
|
9894
9894
|
redacted: false,
|
|
9895
9895
|
captureLevel: content.captureLevel ?? "reconstructed",
|
|
9896
|
-
storagePath: this.relativePath(
|
|
9896
|
+
storagePath: this.relativePath(path2)
|
|
9897
9897
|
};
|
|
9898
9898
|
return { ...metadata, reference };
|
|
9899
9899
|
}
|
|
9900
|
-
async storePlaintextBlob(
|
|
9901
|
-
if (await pathExists(
|
|
9902
|
-
const existing = await readFile7(
|
|
9900
|
+
async storePlaintextBlob(path2, contentId, plaintext) {
|
|
9901
|
+
if (await pathExists(path2)) {
|
|
9902
|
+
const existing = await readFile7(path2);
|
|
9903
9903
|
if (sha256(existing) === contentId) return;
|
|
9904
9904
|
}
|
|
9905
|
-
await this.atomicWrite(
|
|
9905
|
+
await this.atomicWrite(path2, plaintext);
|
|
9906
9906
|
}
|
|
9907
|
-
async writeImmutable(
|
|
9908
|
-
if (await pathExists(
|
|
9909
|
-
await this.atomicWrite(
|
|
9907
|
+
async writeImmutable(path2, body) {
|
|
9908
|
+
if (await pathExists(path2)) return;
|
|
9909
|
+
await this.atomicWrite(path2, body);
|
|
9910
9910
|
}
|
|
9911
|
-
async atomicWrite(
|
|
9912
|
-
const directory = dirname3(
|
|
9911
|
+
async atomicWrite(path2, body) {
|
|
9912
|
+
const directory = dirname3(path2);
|
|
9913
9913
|
await mkdir(directory, { recursive: true, mode: 448 });
|
|
9914
9914
|
const temporary = join8(
|
|
9915
9915
|
directory,
|
|
9916
|
-
`.${basename7(
|
|
9916
|
+
`.${basename7(path2)}.${process.pid}.${randomUUID()}.tmp`
|
|
9917
9917
|
);
|
|
9918
9918
|
try {
|
|
9919
9919
|
await writeFile(temporary, body, { mode: 384, flag: "wx" });
|
|
9920
|
-
await rename(temporary,
|
|
9920
|
+
await rename(temporary, path2);
|
|
9921
9921
|
} finally {
|
|
9922
9922
|
await rm(temporary, { force: true });
|
|
9923
9923
|
}
|
|
@@ -9959,29 +9959,29 @@ var FileAuditReplayStore = class {
|
|
|
9959
9959
|
`${contentId}.blob`
|
|
9960
9960
|
);
|
|
9961
9961
|
}
|
|
9962
|
-
relativePath(
|
|
9963
|
-
return relative(this.rootDir,
|
|
9962
|
+
relativePath(path2) {
|
|
9963
|
+
return relative(this.rootDir, path2).split(sep3).join("/");
|
|
9964
9964
|
}
|
|
9965
|
-
resolveStoredPath(
|
|
9966
|
-
const resolved = resolve3(this.rootDir,
|
|
9965
|
+
resolveStoredPath(path2) {
|
|
9966
|
+
const resolved = resolve3(this.rootDir, path2);
|
|
9967
9967
|
if (resolved !== this.rootDir && !resolved.startsWith(`${this.rootDir}${sep3}`)) {
|
|
9968
9968
|
throw new Error("Audit replay path escapes the storage root");
|
|
9969
9969
|
}
|
|
9970
9970
|
return resolved;
|
|
9971
9971
|
}
|
|
9972
|
-
async readManifest(
|
|
9973
|
-
const value = await readJsonIfPresent(
|
|
9972
|
+
async readManifest(path2) {
|
|
9973
|
+
const value = await readJsonIfPresent(path2);
|
|
9974
9974
|
if (!value) return void 0;
|
|
9975
9975
|
return value;
|
|
9976
9976
|
}
|
|
9977
|
-
async readIndex(
|
|
9978
|
-
const value = await readJsonIfPresent(
|
|
9977
|
+
async readIndex(path2) {
|
|
9978
|
+
const value = await readJsonIfPresent(path2);
|
|
9979
9979
|
if (!value) return void 0;
|
|
9980
9980
|
return value;
|
|
9981
9981
|
}
|
|
9982
9982
|
async readReplay(manifest) {
|
|
9983
|
-
const
|
|
9984
|
-
const bytes = await readFile7(
|
|
9983
|
+
const path2 = this.resolveStoredPath(manifest.replayPath);
|
|
9984
|
+
const bytes = await readFile7(path2);
|
|
9985
9985
|
if (sha256(bytes) !== manifest.replaySha256) {
|
|
9986
9986
|
throw new Error("Audit replay document hash mismatch");
|
|
9987
9987
|
}
|
|
@@ -10050,26 +10050,26 @@ function sha256(value) {
|
|
|
10050
10050
|
function idKey(id) {
|
|
10051
10051
|
return sha256(Buffer.from(id, "utf8"));
|
|
10052
10052
|
}
|
|
10053
|
-
async function pathExists(
|
|
10053
|
+
async function pathExists(path2) {
|
|
10054
10054
|
try {
|
|
10055
|
-
await access(
|
|
10055
|
+
await access(path2);
|
|
10056
10056
|
return true;
|
|
10057
10057
|
} catch (error) {
|
|
10058
10058
|
if (isNotFound(error)) return false;
|
|
10059
10059
|
throw error;
|
|
10060
10060
|
}
|
|
10061
10061
|
}
|
|
10062
|
-
async function readDirectory(
|
|
10062
|
+
async function readDirectory(path2) {
|
|
10063
10063
|
try {
|
|
10064
|
-
return await readdir5(
|
|
10064
|
+
return await readdir5(path2);
|
|
10065
10065
|
} catch (error) {
|
|
10066
10066
|
if (isNotFound(error)) return [];
|
|
10067
10067
|
throw error;
|
|
10068
10068
|
}
|
|
10069
10069
|
}
|
|
10070
|
-
async function readJsonIfPresent(
|
|
10070
|
+
async function readJsonIfPresent(path2) {
|
|
10071
10071
|
try {
|
|
10072
|
-
return JSON.parse(await readFile7(
|
|
10072
|
+
return JSON.parse(await readFile7(path2, "utf8"));
|
|
10073
10073
|
} catch (error) {
|
|
10074
10074
|
if (isNotFound(error)) return void 0;
|
|
10075
10075
|
throw error;
|