grix-connector 4.6.5 → 4.6.7

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.
@@ -1,7 +1,7 @@
1
- import{execFile as P}from"node:child_process";import{promisify as b}from"node:util";import{EventEmitter as I}from"node:events";import{stat as $}from"node:fs/promises";import{mkdirSync as T,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,resolveWindowsExecInvocation as N,spawnCommand as G,killProcessGroup as E,hasChildProcesses as L}from"../../core/runtime/spawn.js";import{InternalApiServer as O}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{compactToolInputForWire as q}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as z}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as K}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as X,removePiGrixProvider as J,writePiGrixProvider as Q}from"./pi-provider-config.js";const y=new Map;function Z(){const c=m(g(),".pi","agent","mcp.json");try{if(!C(c))return{};const e=JSON.parse(R(c,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${c}: ${t instanceof Error?t.message:String(t)}`),{}}}async function tt(c){const t=y.get(c);if(t!==void 0)return t;let e=!1;try{const s=b(P),i=N(c,["--help"]),{stdout:n,stderr:r}=await s(i.command,i.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return y.set(c,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${c})`),e}class et extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const st=12e4,it=90*1e3,x=1800*1e3;function _(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const nt=500,rt=2e3,v=3,ot=500;function at(c){return new Promise(t=>setTimeout(t,c))}function u(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class w extends I{type="pi";config;callbacks;process=null;transport=new z;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new K;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new j("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await at(ot);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(d=>({id:d.id,display_name:d.name??d.id,...d.provider?{provider:d.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new et(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?L(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const d=i.indexOf(":");if(d<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,d),h=i.slice(d+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
1
+ import{execFile as b}from"node:child_process";import{promisify as P}from"node:util";import{EventEmitter as I}from"node:events";import{stat as A}from"node:fs/promises";import{mkdirSync as $,writeFileSync as T,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as B}from"node:url";import{tmpdir as F,homedir as v}from"node:os";import{resolveCommandPath as D,resolveWindowsExecInvocation as N,spawnCommand as G,killProcessGroup as E,hasChildProcesses as L}from"../../core/runtime/spawn.js";import{InternalApiServer as O}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{compactToolInputForWire as q}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as z}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as K}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as X,removePiGrixProvider as J,writePiGrixProvider as Q}from"./pi-provider-config.js";const _=new Map;function Z(){const d=m(v(),".pi","agent","mcp.json");try{if(!C(d))return{};const e=JSON.parse(R(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function tt(d){const t=_.get(d);if(t!==void 0)return t;let e=!1;try{const s=P(b),i=N(d,["--help"]),{stdout:n,stderr:r}=await s(i.command,i.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return _.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class et extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const st=12e4,it=90*1e3,y=1800*1e3;function x(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const nt=500,rt=2e3,g=3,ot=500;function at(d){return new Promise(t=>setTimeout(t,d))}function dt(d){const t=new Set,e=[];for(const s of d){const i=s.provider?.trim();!i||t.has(i)||(t.add(i),e.push({id:i,display_name:i}))}return e}function u(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class w extends I{type="pi";config;callbacks;process=null;transport=new z;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new K;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new j("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=g;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<g){await at(ot);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${g} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(l=>({id:l.id,display_name:l.name??l.id,...l.provider?{provider:l.provider}:{}}))},c=dt(i);c.length>0&&(r.available_providers=c),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_id=n.provider,r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new et(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();if(!n){const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===i&&h.provider?.trim());if(l.length>1){const h=(await this.currentModel())?.provider?.trim();n=l.find(p=>p.provider?.trim()===h)?.provider?.trim()}n=n??l[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const s=t.params??{},i=(s.provider_id??s.provider??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===i);if(c.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${i}`),{handled:!0,kind:"set_provider_error"};const l=(await this.currentModel())?.id,h=c.find(p=>p.id===l)?.id??c[0].id;return await this.transport.send("set_model",{provider:i,modelId:h}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:i,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(B(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?L(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
2
  ${r.map(l=>` ${l.provider??"unknown"}:${l.id} (${l.name??l.id})`).join(`
3
3
  `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=V({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new O,this.internalApi.setInvokeHandler(async(r,d,l,h)=>this.callbacks.agentInvoke(r,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Z(),s=m(B(),"grix-pi-mcp");T(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=U(i);n.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),d=X(this.agentName);this.provider?await Q(r,d,this.provider)?(n.includes("--provider")||n.push("--provider",d),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await J(r,d).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${d}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await tt(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await $(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=G(e,n,{env:l,cwd:p}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const S=a.toString().trim();S&&o.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=q(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=rt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},nt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Y(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
4
+ `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new O,this.internalApi.setInvokeHandler(async(r,c,l,h)=>this.callbacks.agentInvoke(r,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Z(),s=m(F(),"grix-pi-mcp");$(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),T(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(v(),".pi","agent","skills"),n=U(i);n.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(v(),".pi","agent"),c=X(this.agentName);this.provider?await Q(r,c,this.provider)?(n.includes("--provider")||n.push("--provider",c),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await J(r,c).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${c}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await tt(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await A(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=G(e,n,{env:l,cwd:p}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const S=a.toString().trim();S&&o.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=q(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=rt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},nt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Y(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
5
  `);e=`${e}
6
6
 
7
7
  [Conversation context]
@@ -9,4 +9,4 @@ ${n}`}}catch{}const s=this.identity.injectOnce(t.session_id,e);return this.inbou
9
9
  `);e=`${e}
10
10
 
11
11
  [Conversation context]
12
- ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},w.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<it)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},st))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{w as PiAdapter};
12
+ ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(c=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},w.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!x(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<it)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>y?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&x(t))?`liveness budget exhausted after ${y/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},st))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{w as PiAdapter};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.6.5",
4
- "tarball": "grix-dsh-bridge-4.6.5.tgz",
3
+ "bridgeVersion": "4.6.7",
4
+ "tarball": "grix-dsh-bridge-4.6.7.tgz",
5
5
  "size": 23091,
6
6
  "unpackedSize": 92668,
7
- "shasum": "a947e68d766922f2b9b7d802cfe24408911aff2e",
8
- "integrity": "sha512-Vy3CvmiKogOYvPoi8eJ+1FvzrWoJNd/qjaAeQB5E4eMNkcHX/Ga0Hpk9jCQLMbJA7+8vzKpGv4Lod9XhrtUhTg=="
7
+ "shasum": "3f4850cd8bf049b0ae74e903c7f6b490df2546d7",
8
+ "integrity": "sha512-13RZFWVRBcXfgG53K5jL0KvDeZ/p0hPWGUraqAr754AX1b0x2GT1En2i7mUsj1qLWnkd/5jvAsohngJoAagodA=="
9
9
  }
package/dist/manager.js CHANGED
@@ -1 +1 @@
1
- import{join as k}from"node:path";import{homedir as le}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{buildSharedInstanceConfig as de,diffSharedOwners as he,sharedInstanceKey as ue,SharedOwnersCache as me}from"./manager-share-config.js";import{AgentDeletedError as pe,isAgentDeletedError as I}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as p}from"./core/log/index.js";import{resolveClientVersion as ge}from"./core/util/client-version.js";import{UpgradeChecker as fe}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as _e}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as ye}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as we}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as Ae}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as Se}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as ke}from"./core/aibot/types.js";import{buildReportedSkills as ve,logDefaultSkillsCheck as be,cleanupProjectedSkills as B}from"./default-skills/index.js";import{buildProviderEnv as Ce,supportsKiroCwRelay as W,supportsNonMitmRelayConfig as Ie}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Ee}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as Q,stopKiroRelay as K}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as z}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as V}from"./core/runtime/cursor-resolve.js";import{getCliVersion as $e,resolveCliPath as Te}from"./core/util/cli-probe.js";import{AgentInstaller as Pe}from"./core/installer/installer.js";import{reportInstallFailure as Me}from"./core/observability/sentry.js";import{createDefaultAuditProducer as xe}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as De}from"./adapter/codex/config-overrides.js";import{resolveCodexDirectHome as Oe}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(r){if(r)return{...r.provider_id?.trim()?{providerId:r.provider_id.trim()}:{},...r.base_url?.trim()?{baseUrl:r.base_url.trim()}:{},...r.quota_base_url?.trim()?{quotaBaseUrl:r.quota_base_url.trim()}:{},...r.api_key?.trim()?{apiKey:r.api_key.trim()}:{},...r.model?.trim()?{model:r.model.trim()}:{},...r.fast_model?.trim()?{fastModel:r.fast_model.trim()}:{},...r.effort?.trim()?{effort:r.effort.trim()}:{}}}const Re=8e3,je=1e4,Le=8e3;function Ne(){const r=z();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:V()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:r.command},{clientType:"agy",command:"agy"},{clientType:"deepseek",command:"dsh"}]}async function Ue(){return Promise.all(Ne().map(async r=>{const e=await Te(r.command);if(!e)return{client_type:r.clientType,command:r.command,installed:!1,path:null,version:null};const n=await $e(e,r.versionArgs??["--version"]);return{client_type:r.clientType,command:r.command,installed:!0,path:e,version:n.version,error:n.error}}))}function Ge(r){switch(r){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:V()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=z();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${r}`)}}function v(r,e){return String(r??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function qe(r){return k(A.data,`session-bindings-${v(r,"unknown")}.json`)}function He(r,e){return k(A.data,`session-bindings-${v(r,e)}.json`)}function Fe(r,e){return k(A.data,`active-events-${v(r,e)}.json`)}function Be(r){return k(A.data,`pending-events-${v(r,"unknown")}.json`)}function We(r,e){const n=v(r,"agent"),t=v(e,"unknown");return k(A.data,`terminal-outbox-${n}-${t}.json`)}function Qe(...r){const e=[],n=new Set;for(const t of r)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 Ke(r,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[r]??n.acp;return{maxConcurrent:e?.max_concurrent??t.maxConcurrent??1,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function ze(r,e={}){const n=ge(),t=String(r.client_type??"").trim().toLowerCase(),s=Ge(t),i=t==="deepseek"?r.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(r.ws_url??"").trim(),m=typeof r.name=="string"?r.name:"",a=m.trim(),l="get_session_usage",g="get_rate_limits",h="get_agent_global_config",d=ke;if(!a)throw new Error("agent name is required");if(m!==a)throw new Error(`agent name must not contain leading or trailing whitespace: "${m}"`);if(!o)throw new Error(`agent ${r.name}: ws_url is required`);if(!r.agent_id?.trim())throw new Error(`agent ${r.name}: agent_id is required`);if(!r.api_key?.trim())throw new Error(`agent ${r.name}: api_key is required`);const u=s.adapterType,f=u==="acp",_=t==="qwen",w={...s.options??{}};if(u==="deepseek-harness"&&(w.integrationMode=i,w.dshProfile=r.dsh?.profile?.trim()||"web",w.autoInstallBridge=r.dsh?.auto_install_bridge??!c,w.autoStartProfile=r.dsh?.auto_start_profile??!c),u==="deepseek-harness"&&r.provider?.model?.trim()&&(w.defaultModel=r.provider.model.trim()),r.codex_config_overrides!==void 0){if(u!=="codex")throw new Error(`agent ${r.name}: codex_config_overrides is only supported for client_type=codex`);De(r.codex_config_overrides,`agent ${r.name}: codex_config_overrides`),w.codexConfigOverrides=r.codex_config_overrides}if(u==="codex"&&r.provider?.wire_api!==void 0){const y=r.provider;if(y.wire_api!=="responses"||!y.base_url?.trim()||!y.api_key?.trim()||!y.model?.trim()||!y.catalog_version?.trim()||!y.catalog_sha256?.trim()||!y.catalog_json?.trim())throw Object.assign(new Error(`agent ${r.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const H=Oe(A.data,r.name);w.codexHome=H,w.codexDirect={codexHome:H,config:{baseUrl:y.base_url.trim(),model:y.model.trim(),...y.reasoning_effort?.trim()?{reasoningEffort:y.reasoning_effort.trim()}:{},token:y.api_key.trim()},catalog:{version:y.catalog_version.trim(),sha256:y.catalog_sha256.trim(),json:y.catalog_json}}}const S=u==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=u==="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=_?{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,P=u==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","get_context","file_list","create_folder",l,g]}:null,M=u==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,x=u==="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,L=u==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,D=u==="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=u==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,R=u==="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,N=new Set(["hermes","reasonix","kimi","copilot"]),ee=f&&!N.has(t),te=f&&!_?{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=u==="codex"||u==="claude"||u==="opencode"||u==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...u==="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"]:[],...u==="claude"?["set_reasoning_effort"]:[]]:void 0,re=u==="cursor"||u==="opencode"||u==="openhuman"||u==="agy"||f&&N.has(t)?[g]:[l,g];f&&w.raw_transport===void 0&&(w.raw_transport=t==="gemini");const ae=`${t}/base`,C=we(u,t),ie=C==="kiro"?void 0:process.cwd(),j=Y(r.provider),b={...process.env,...r.env};if(C==="hermes"&&!b.HERMES_HOME?.trim()){const y=Ce(t,j);b.HERMES_HOME=Ee({...y,...b},r.name)}const U=ve({mode:C,projectDir:ie,env:b}),G=U.filter(y=>y.source==="connector").map(y=>y.name);G.length>0&&!e.quiet&&p.info("manager",`[${r.name}] injecting connector skills: [${G.join(", ")}]`);const q=Ae(U,A.skills);let oe=q.length>0?q:void 0;const ce=Se({skillsDir:A.skills,mode:C,home:le(),env:b});return{name:a,adapterType:u,aibot:{url:o,agentId:r.agent_id,apiKey:r.api_key,clientType:t,clientVersion:n,adapterHint:R?.adapterHint??s.adapterHint??T?.adapterHint??P?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??O?.adapterHint??ae,capabilities:R?.capabilities??S?.capabilities??L?.capabilities??P?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Qe(R?.localActions??S?.localActions??L?.localActions??Z?.localActions??P?.localActions??M?.localActions??x?.localActions??D?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,re,["connector_rollback","connector_upgrade_push",h,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:We(r.name,r.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...r.args??[]],env:r.env,clientType:t,...j?{provider:j}:{}},adapterOptions:w,acpAuthMethod:w.auth_method,acpInitialMode:w.initial_mode,acpMcpTools:w.acp_mcp_tools,promptTimeoutMs:r.prompt_timeout_ms,bindingsPath:qe(r.agent_id),legacyBindingsPath:He(r.name,r.agent_id),activeEventStorePath:Fe(r.name,r.agent_id),pendingEventStorePath:Be(r.agent_id),...s.enableSessionBinding||f?{enableSessionBinding:!0}:{},...s.autoInjectArgs||t==="reasonix"&&r.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&r.provider?.model?.trim()?{model:r.provider.model.trim()}:{}}}:{},poolMaxSize:r.pool?.maxSize??(u==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:r.pool?.idleTimeoutMs,eventQueue:Ke(u,r.event_queue),logDir:A.log,providerBaseUrl:r.provider_base_url?.trim()||void 0,providerApiKey:r.provider_api_key?.trim()||void 0}}function J(){const r=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(r);return Number.isFinite(e)&&e>=500?Math.floor(e):Re}function E(){const r=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(r);return Number.isFinite(e)&&e>=500?Math.floor(e):je}function Ve(){return Math.min(E(),Le)}function $(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map($).join(",")}]`;const e=r;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${$(e[t])}`).join(",")}}`}function Xe(r,e){return $(r)===$(e)}class It{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 me(A.data);installer=new Pe;relaySecretResolver;auditProducer=xe();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=E()){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=E()){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),p.info("manager",`Loading configs from ${n}`),be(),B(),this.globalConfigStore=new ye(k(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const a of s)p.error("manager",`Failed to load ${a.file}: ${a.error}`);for(const a of i)p.info("manager",`Skipped ${a}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&i.length===0){p.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:a,file:l}of t)try{const g=this.toRuntimeInstanceConfig(a);c.push({config:g,entry:a,file:l}),p.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const h=typeof a?.name=="string"?a.name:"<unknown>";p.error("manager",`Invalid agent config in ${l} (name=${h}): ${g}`),o++}let m=0;if(c.length>0){const a=J();p.info("manager",`Starting ${c.length} agent(s), startup wait=${a}ms`);const l=d=>{this.instances=this.instances.filter(u=>u!==d)},g=c.map(({config:d,entry:u,file:f})=>{const _=this.createConfiguredInstance(d);return this.instances.push(_),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:u,file:f}),{config:d,instance:_,startPromise:this.prepareProviderRuntime(d,u).then(()=>{if(this.stopping)throw this.requestStartCancellation(_),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(_)})}}),h=await Promise.all(g.map(async d=>{const u=await new Promise(f=>{let _=!1;const w=setTimeout(()=>{_||(_=!0,f({kind:"timeout"}))},a);d.startPromise.then(()=>{_||(_=!0,clearTimeout(w),f({kind:"started"}))}).catch(S=>{_||(_=!0,clearTimeout(w),f({kind:"failed",error:S}))})});return{task:d,outcome:u}}));for(const{task:d,outcome:u}of h){if(u.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(u.kind==="failed"){if(I(u.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(f){this.failedStartAgents.add(d.config.name),p.error("manager",`Failed to clean up partially started ${d.config.name}: ${f}`)}p.error("manager",`Failed to start ${d.config.name}: ${u.error}`);continue}m++,p.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)&&(p.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config))}).catch(async f=>{if(I(f)){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(_){this.failedStartAgents.add(d.config.name),p.error("manager",`Failed to clean up delayed start ${d.config.name}: ${_}`)}p.error("manager",`Delayed start failed: ${d.config.name}: ${f}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-m);p.info("manager",`${d}/${c.length} agent(s) running now`)}m>0&&p.warn("manager",`${m} 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 fe(e,()=>this.hasAnyPendingOrBackgroundWork(),()=>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 _e(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){p.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 m=!1;try{m=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(a){p.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${a}`)}if(m){i=!0;continue}p.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!i){p.warn("manager",`owner library skills: no reporter succeeded group=${t}`);continue}for(const o of c)try{o.adoptSkillsWireHashFromDisk()}catch(m){p.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${m}`)}}}async stop(){p.info("manager","Stopping all agents..."),this.stopping=!0;const e=Ve(),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(m=>m!==o),this.startingInstances.delete(o)}catch(m){c.push(m)}}),...[...this.sharedInstances.entries()].map(async([o,m])=>{try{await(i.get(m)??this.stopInstance(m,void 0,t())),this.sharedInstances.get(o)===m&&this.sharedInstances.delete(o),this.startingInstances.delete(m)}catch(a){c.push(a)}})]);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),B(),c.length>0)throw new AggregateError(c,"Failed to stop all agents completely");p.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}=he(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=ue(e.name,c);let m;try{const a=de(e,c);m=new F(a,this.globalConfigStore,this.auditProducer),m.setLifecycleBusyChecker(()=>this.hasAnyPendingOrBackgroundWork()),m.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),m.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&m.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&m.closeLifecycleAdmission(),this.sharedInstances.set(o,m),await this.startTrackedInstance(m),m.forceRefreshSkills(void 0,{force:!0}),p.info("manager",`shared instance started: ${o}`)}catch(a){if(m&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(m),this.sharedInstances.get(o)===m&&this.sharedInstances.delete(o)}catch(g){p.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=a instanceof Error?a.message:String(a);/Auth failed/i.test(l)?(this.sharedOwnersCache.remove(e.name,c),p.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):p.error("manager",`start shared instance failed ${o}: ${a}`)}}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),p.info("manager",`shared instance stopped: ${c}`)}catch(m){p.error("manager",`stop shared instance failed ${c}: ${m}`)}}}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)||(p.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(),p.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.hasAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(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},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}hasAnyPendingOrBackgroundWork(){return this.instances.some(e=>e.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(e=>e.hasPendingOrBackgroundWork())}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);W(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await Q(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(),m=await new Promise(h=>{let d=!1;const u=setTimeout(()=>{d||(d=!0,h({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(u),h({kind:"started"}))},f=>{d||(d=!0,clearTimeout(u),h({kind:"failed",error:f}))})}),a=this.instanceGenerations.get(i);if(a?.platformDeletedObserved&&!a.persisted){const h=new pe(`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([h,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw h}if(m.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(m.kind==="timeout"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),p.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(h=>h!==i)}catch(h){this.failedStartAgents.add(e.name),p.error("manager",`Failed to stop late-started ${e.name}: ${h}`)}return}this.failedStartAgents.delete(e.name),this.instanceGenerations.get(i)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),p.info("manager",`Delayed start succeeded: ${e.name}`)}},async h=>{if(I(h)){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),p.error("manager",`Failed to clean up delayed start ${e.name}: ${d}`)}p.error("manager",`Delayed start failed ${e.name}: ${h}`)}}).catch(h=>{p.error("manager",`Delayed start finalizer failed ${e.name}: ${h}`)});return}const l=m.error;I(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(h=>h!==i),this.failedStartAgents.delete(e.name)}catch(h){g=h,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),p.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,n){this.removingAgents.add(e);try{const t=()=>n?.deadlineMs===void 0?E():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(h=>h.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},m=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&m.set(i,this.stopInstance(i,o,t())));for(const[h,d]of this.sharedInstances)h.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&m.set(d,this.stopInstance(d,o,t())));const a=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...a?[a]:[],...m.values()],`agent "${e}" shared lifecycle drain`,t())}catch(h){l.push(h)}const g=[];for(const[h,d]of[...this.sharedInstances.entries()])h.startsWith(c)&&g.push((m.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(h)===d&&this.sharedInstances.delete(h),this.startingInstances.delete(d)}).catch(u=>{l.push(u),p.error("manager",`stop shared instance failed ${h}: ${u}`)}));if(i)try{await(m.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const h=this.instances.indexOf(i);h!==-1&&this.instances.splice(h,1),this.startingInstances.delete(i)}catch(h){l.push(h)}if(await Promise.all(g),!n?.keepShareCache){const h=K(e).catch(()=>{});if(n?.deadlineMs===void 0)await h;else try{await this.waitForLifecycleDrain([h],`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){p.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;p.warn("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`);const m=this.rawConfigMap.get(s),a=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 u=g.fileErrors.map(f=>`${f.file}: ${f.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${u}]`)}const h=g.entries.filter(u=>String(u.entry?.name??"").trim()===s);if(!h.some(u=>String(u.entry?.agent_id??"").trim()!==i)&&h.length>0&&this.configRepository.remove(s),l.length===0){const u=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!u||u===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),m&&this.rawConfigMap.set(s,m),a&&this.configMap.set(s,a)}if(l.length>0)throw new AggregateError(l,`Failed to fully clean up deleted agent "${s}"`);p.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}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 ze(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),p.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(([a])=>a!=="api_key")):n,c=this.configRepository.updateExisting(e,a=>{const l={...a};return i===void 0?delete l.provider:l.provider=i,this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const m=String(o.client_type??"").trim().toLowerCase();try{W(m)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await Q(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await K(e))}catch(a){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),a}if(t?.deferRestart){this.instances.find(a=>a.name===e)?.markRelayEnvStale(),p.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(a){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),a}p.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&&(Ie(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){p.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 a of t)p.info("manager",`reload: skipped ${a}: not an agent config (no "agents" key)`);if(n.length>0){const a=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${a}]`),{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:a}of e)try{this.toRuntimeInstanceConfig(a,{quiet:!0})}catch(l){const g=a?.name,h=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:h,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const a=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${a}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(a=>a.name));for(const a of e){const l=String(a.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&p.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,a)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},m=new Set([...this.rawConfigMap.keys()].filter(a=>!c.has(a)));for(const a of m)if(!i.has(a))try{await this.removeAgentInternal(a),o.removed.push(a)}catch(l){o.failed.push({name:a,error:l instanceof Error?l.message:String(l)})}for(const[a,l]of i){const g=this.rawConfigMap.get(a);if(g)if(!Xe(g.entry,l.entry)||!this.instances.some(h=>h.name===a)||this.failedStartAgents.has(a))try{await this.replaceInstance(a,l.entry,l.file),o.restarted.push(a)}catch(h){o.failed.push({name:a,error:h instanceof Error?h.message:String(h)})}else this.rawConfigMap.set(a,l),o.unchanged.push(a);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(a)}catch(h){o.failed.push({name:a,error:h instanceof Error?h.message:String(h)})}}return p.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 Ye(this.instances,e)}async probeOne(e,n={}){return Je(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return Me(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Ye(r,e){const n=e.concurrency??4,t=Date.now(),s=new Array(r.length);await new Promise(a=>{let l=0,g=0;const h=r.length;if(h===0){a();return}function d(_){const w=r[_];w.probe(e).then(S=>{s[_]=S,u()},S=>{s[_]={agent_name:w.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}},u()})}function u(){g++,l<h?d(l++):g===h&&a()}const f=Math.min(n,h);for(let _=0;_<f;_++)d(l++)});const i=s.filter(a=>a.status==="healthy").length,c=s.filter(a=>a.status==="degraded").length,o=s.filter(a=>a.status==="unavailable").length,m=await Ue();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:m,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function Je(r,e,n){const t=r.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{It as Manager,Y as normalizeAgentProviderForRuntime,Ue as probeInstalledClientCommands,Ye as probeInstances,Je as probeOneInstance};
1
+ import{join as k}from"node:path";import{homedir as le}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{buildSharedInstanceConfig as de,diffSharedOwners as he,sharedInstanceKey as ue,SharedOwnersCache as pe}from"./manager-share-config.js";import{AgentDeletedError as me,isAgentDeletedError as I}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as ge}from"./core/util/client-version.js";import{UpgradeChecker as fe}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as _e}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as ye}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as we}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as Ae}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as Se}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as ke}from"./core/aibot/types.js";import{buildReportedSkills as ve,logDefaultSkillsCheck as be,cleanupProjectedSkills as B}from"./default-skills/index.js";import{buildProviderEnv as Ce,supportsKiroCwRelay as W,supportsNonMitmRelayConfig as Ie}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Ee}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as Q,stopKiroRelay as K}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as z}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as V}from"./core/runtime/cursor-resolve.js";import{getCliVersion as $e,resolveCliPath as Te}from"./core/util/cli-probe.js";import{AgentInstaller as Pe}from"./core/installer/installer.js";import{reportInstallFailure as Me}from"./core/observability/sentry.js";import{createDefaultAuditProducer as xe}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as De}from"./adapter/codex/config-overrides.js";import{resolveCodexDirectHome as Oe}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(r){if(r)return{...r.provider_id?.trim()?{providerId:r.provider_id.trim()}:{},...r.base_url?.trim()?{baseUrl:r.base_url.trim()}:{},...r.quota_base_url?.trim()?{quotaBaseUrl:r.quota_base_url.trim()}:{},...r.api_key?.trim()?{apiKey:r.api_key.trim()}:{},...r.model?.trim()?{model:r.model.trim()}:{},...r.fast_model?.trim()?{fastModel:r.fast_model.trim()}:{},...r.effort?.trim()?{effort:r.effort.trim()}:{}}}const Re=8e3,je=1e4,Le=8e3;function Ne(){const r=z();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:V()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:r.command},{clientType:"agy",command:"agy"},{clientType:"deepseek",command:"dsh"}]}async function Ue(){return Promise.all(Ne().map(async r=>{const e=await Te(r.command);if(!e)return{client_type:r.clientType,command:r.command,installed:!1,path:null,version:null};const n=await $e(e,r.versionArgs??["--version"]);return{client_type:r.clientType,command:r.command,installed:!0,path:e,version:n.version,error:n.error}}))}function Ge(r){switch(r){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:V()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=z();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${r}`)}}function v(r,e){return String(r??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function qe(r){return k(A.data,`session-bindings-${v(r,"unknown")}.json`)}function He(r,e){return k(A.data,`session-bindings-${v(r,e)}.json`)}function Fe(r,e){return k(A.data,`active-events-${v(r,e)}.json`)}function Be(r){return k(A.data,`pending-events-${v(r,"unknown")}.json`)}function We(r,e){const n=v(r,"agent"),t=v(e,"unknown");return k(A.data,`terminal-outbox-${n}-${t}.json`)}function Qe(...r){const e=[],n=new Set;for(const t of r)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 Ke(r,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[r]??n.acp;return{maxConcurrent:e?.max_concurrent??t.maxConcurrent??1,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function ze(r,e={}){const n=ge(),t=String(r.client_type??"").trim().toLowerCase(),s=Ge(t),i=t==="deepseek"?r.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(r.ws_url??"").trim(),p=typeof r.name=="string"?r.name:"",a=p.trim(),l="get_session_usage",g="get_rate_limits",h="get_agent_global_config",d=ke;if(!a)throw new Error("agent name is required");if(p!==a)throw new Error(`agent name must not contain leading or trailing whitespace: "${p}"`);if(!o)throw new Error(`agent ${r.name}: ws_url is required`);if(!r.agent_id?.trim())throw new Error(`agent ${r.name}: agent_id is required`);if(!r.api_key?.trim())throw new Error(`agent ${r.name}: api_key is required`);const u=s.adapterType,f=u==="acp",_=t==="qwen",w={...s.options??{}};if(u==="deepseek-harness"&&(w.integrationMode=i,w.dshProfile=r.dsh?.profile?.trim()||"web",w.autoInstallBridge=r.dsh?.auto_install_bridge??!c,w.autoStartProfile=r.dsh?.auto_start_profile??!c),u==="deepseek-harness"&&r.provider?.model?.trim()&&(w.defaultModel=r.provider.model.trim()),r.codex_config_overrides!==void 0){if(u!=="codex")throw new Error(`agent ${r.name}: codex_config_overrides is only supported for client_type=codex`);De(r.codex_config_overrides,`agent ${r.name}: codex_config_overrides`),w.codexConfigOverrides=r.codex_config_overrides}if(u==="codex"&&r.provider?.wire_api!==void 0){const y=r.provider;if(y.wire_api!=="responses"||!y.base_url?.trim()||!y.api_key?.trim()||!y.model?.trim()||!y.catalog_version?.trim()||!y.catalog_sha256?.trim()||!y.catalog_json?.trim())throw Object.assign(new Error(`agent ${r.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const H=Oe(A.data,r.name);w.codexHome=H,w.codexDirect={codexHome:H,config:{baseUrl:y.base_url.trim(),model:y.model.trim(),...y.reasoning_effort?.trim()?{reasoningEffort:y.reasoning_effort.trim()}:{},token:y.api_key.trim()},catalog:{version:y.catalog_version.trim(),sha256:y.catalog_sha256.trim(),json:y.catalog_json}}}const S=u==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=u==="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=_?{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,P=u==="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,M=u==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,x=u==="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,L=u==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,D=u==="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=u==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,R=u==="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,N=new Set(["hermes","reasonix","kimi","copilot"]),ee=f&&!N.has(t),te=f&&!_?{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=u==="codex"||u==="claude"||u==="opencode"||u==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...u==="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"]:[],...u==="claude"?["set_reasoning_effort"]:[]]:void 0,re=u==="cursor"||u==="opencode"||u==="openhuman"||u==="agy"||f&&N.has(t)?[g]:[l,g];f&&w.raw_transport===void 0&&(w.raw_transport=t==="gemini");const ae=`${t}/base`,C=we(u,t),ie=C==="kiro"?void 0:process.cwd(),j=Y(r.provider),b={...process.env,...r.env};if(C==="hermes"&&!b.HERMES_HOME?.trim()){const y=Ce(t,j);b.HERMES_HOME=Ee({...y,...b},r.name)}const U=ve({mode:C,projectDir:ie,env:b}),G=U.filter(y=>y.source==="connector").map(y=>y.name);G.length>0&&!e.quiet&&m.info("manager",`[${r.name}] injecting connector skills: [${G.join(", ")}]`);const q=Ae(U,A.skills);let oe=q.length>0?q:void 0;const ce=Se({skillsDir:A.skills,mode:C,home:le(),env:b});return{name:a,adapterType:u,aibot:{url:o,agentId:r.agent_id,apiKey:r.api_key,clientType:t,clientVersion:n,adapterHint:R?.adapterHint??s.adapterHint??T?.adapterHint??P?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??O?.adapterHint??ae,capabilities:R?.capabilities??S?.capabilities??L?.capabilities??P?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Qe(R?.localActions??S?.localActions??L?.localActions??Z?.localActions??P?.localActions??M?.localActions??x?.localActions??D?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,re,["connector_rollback","connector_upgrade_push",h,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:We(r.name,r.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...r.args??[]],env:r.env,clientType:t,...j?{provider:j}:{}},adapterOptions:w,acpAuthMethod:w.auth_method,acpInitialMode:w.initial_mode,acpMcpTools:w.acp_mcp_tools,promptTimeoutMs:r.prompt_timeout_ms,bindingsPath:qe(r.agent_id),legacyBindingsPath:He(r.name,r.agent_id),activeEventStorePath:Fe(r.name,r.agent_id),pendingEventStorePath:Be(r.agent_id),...s.enableSessionBinding||f?{enableSessionBinding:!0}:{},...s.autoInjectArgs||t==="reasonix"&&r.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&r.provider?.model?.trim()?{model:r.provider.model.trim()}:{}}}:{},poolMaxSize:r.pool?.maxSize??(u==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:r.pool?.idleTimeoutMs,eventQueue:Ke(u,r.event_queue),logDir:A.log,providerBaseUrl:r.provider_base_url?.trim()||void 0,providerApiKey:r.provider_api_key?.trim()||void 0}}function J(){const r=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(r);return Number.isFinite(e)&&e>=500?Math.floor(e):Re}function E(){const r=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(r);return Number.isFinite(e)&&e>=500?Math.floor(e):je}function Ve(){return Math.min(E(),Le)}function $(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map($).join(",")}]`;const e=r;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${$(e[t])}`).join(",")}}`}function Xe(r,e){return $(r)===$(e)}class It{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 pe(A.data);installer=new Pe;relaySecretResolver;auditProducer=xe();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=E()){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=E()){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}`),be(),B(),this.globalConfigStore=new ye(k(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const a of s)m.error("manager",`Failed to load ${a.file}: ${a.error}`);for(const a of i)m.info("manager",`Skipped ${a}: 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:a,file:l}of t)try{const g=this.toRuntimeInstanceConfig(a);c.push({config:g,entry:a,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const h=typeof a?.name=="string"?a.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${h}): ${g}`),o++}let p=0;if(c.length>0){const a=J();m.info("manager",`Starting ${c.length} agent(s), startup wait=${a}ms`);const l=d=>{this.instances=this.instances.filter(u=>u!==d)},g=c.map(({config:d,entry:u,file:f})=>{const _=this.createConfiguredInstance(d);return this.instances.push(_),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:u,file:f}),{config:d,instance:_,startPromise:this.prepareProviderRuntime(d,u).then(()=>{if(this.stopping)throw this.requestStartCancellation(_),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(_)})}}),h=await Promise.all(g.map(async d=>{const u=await new Promise(f=>{let _=!1;const w=setTimeout(()=>{_||(_=!0,f({kind:"timeout"}))},a);d.startPromise.then(()=>{_||(_=!0,clearTimeout(w),f({kind:"started"}))}).catch(S=>{_||(_=!0,clearTimeout(w),f({kind:"failed",error:S}))})});return{task:d,outcome:u}}));for(const{task:d,outcome:u}of h){if(u.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(u.kind==="failed"){if(I(u.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(f){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up partially started ${d.config.name}: ${f}`)}m.error("manager",`Failed to start ${d.config.name}: ${u.error}`);continue}p++,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 f=>{if(I(f)){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(_){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up delayed start ${d.config.name}: ${_}`)}m.error("manager",`Delayed start failed: ${d.config.name}: ${f}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-p);m.info("manager",`${d}/${c.length} agent(s) running now`)}p>0&&m.warn("manager",`${p} 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 fe(e,()=>this.hasAnyPendingOrBackgroundWork(),()=>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 _e(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 p=!1;try{p=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(a){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${a}`)}if(p){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(p){m.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${p}`)}}}async stop(){m.info("manager","Stopping all agents..."),this.stopping=!0;const e=Ve(),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(p=>p!==o),this.startingInstances.delete(o)}catch(p){c.push(p)}}),...[...this.sharedInstances.entries()].map(async([o,p])=>{try{await(i.get(p)??this.stopInstance(p,void 0,t())),this.sharedInstances.get(o)===p&&this.sharedInstances.delete(o),this.startingInstances.delete(p)}catch(a){c.push(a)}})]);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),B(),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}=he(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=ue(e.name,c);let p;try{const a=de(e,c);p=new F(a,this.globalConfigStore,this.auditProducer),p.setLifecycleBusyChecker(()=>this.hasAnyPendingOrBackgroundWork()),p.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),p.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&p.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&p.closeLifecycleAdmission(),this.sharedInstances.set(o,p),await this.startTrackedInstance(p),p.forceRefreshSkills(void 0,{force:!0}),m.info("manager",`shared instance started: ${o}`)}catch(a){if(p&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(p),this.sharedInstances.get(o)===p&&this.sharedInstances.delete(o)}catch(g){m.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=a instanceof Error?a.message:String(a);/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}: ${a}`)}}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(p){m.error("manager",`stop shared instance failed ${c}: ${p}`)}}}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.hasAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(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},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}hasAnyPendingOrBackgroundWork(){return this.instances.some(e=>e.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(e=>e.hasPendingOrBackgroundWork())}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);W(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await Q(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(),p=await new Promise(h=>{let d=!1;const u=setTimeout(()=>{d||(d=!0,h({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(u),h({kind:"started"}))},f=>{d||(d=!0,clearTimeout(u),h({kind:"failed",error:f}))})}),a=this.instanceGenerations.get(i);if(a?.platformDeletedObserved&&!a.persisted){const h=new me(`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([h,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw h}if(p.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(p.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(h=>h!==i)}catch(h){this.failedStartAgents.add(e.name),m.error("manager",`Failed to stop late-started ${e.name}: ${h}`)}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 h=>{if(I(h)){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}: ${h}`)}}).catch(h=>{m.error("manager",`Delayed start finalizer failed ${e.name}: ${h}`)});return}const l=p.error;I(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(h=>h!==i),this.failedStartAgents.delete(e.name)}catch(h){g=h,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?E():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(h=>h.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},p=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&p.set(i,this.stopInstance(i,o,t())));for(const[h,d]of this.sharedInstances)h.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&p.set(d,this.stopInstance(d,o,t())));const a=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...a?[a]:[],...p.values()],`agent "${e}" shared lifecycle drain`,t())}catch(h){l.push(h)}const g=[];for(const[h,d]of[...this.sharedInstances.entries()])h.startsWith(c)&&g.push((p.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(h)===d&&this.sharedInstances.delete(h),this.startingInstances.delete(d)}).catch(u=>{l.push(u),m.error("manager",`stop shared instance failed ${h}: ${u}`)}));if(i)try{await(p.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const h=this.instances.indexOf(i);h!==-1&&this.instances.splice(h,1),this.startingInstances.delete(i)}catch(h){l.push(h)}if(await Promise.all(g),!n?.keepShareCache){const h=K(e).catch(()=>{});if(n?.deadlineMs===void 0)await h;else try{await this.waitForLifecycleDrain([h],`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 p=this.rawConfigMap.get(s),a=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 u=g.fileErrors.map(f=>`${f.file}: ${f.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${u}]`)}const h=g.entries.filter(u=>String(u.entry?.name??"").trim()===s);if(!h.some(u=>String(u.entry?.agent_id??"").trim()!==i)&&h.length>0&&this.configRepository.remove(s),l.length===0){const u=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!u||u===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),p&&this.rawConfigMap.set(s,p),a&&this.configMap.set(s,a)}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}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 ze(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(([a])=>a!=="api_key")):n,c=this.configRepository.updateExisting(e,a=>{const l={...a};return i===void 0?delete l.provider:l.provider=i,this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const p=String(o.client_type??"").trim().toLowerCase();try{W(p)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await Q(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await K(e))}catch(a){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),a}if(t?.deferRestart){this.instances.find(a=>a.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(a){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),a}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&&(Ie(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 a of t)m.info("manager",`reload: skipped ${a}: not an agent config (no "agents" key)`);if(n.length>0){const a=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${a}]`),{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:a}of e)try{this.toRuntimeInstanceConfig(a,{quiet:!0})}catch(l){const g=a?.name,h=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:h,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const a=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${a}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(a=>a.name));for(const a of e){const l=String(a.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,a)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},p=new Set([...this.rawConfigMap.keys()].filter(a=>!c.has(a)));for(const a of p)if(!i.has(a))try{await this.removeAgentInternal(a),o.removed.push(a)}catch(l){o.failed.push({name:a,error:l instanceof Error?l.message:String(l)})}for(const[a,l]of i){const g=this.rawConfigMap.get(a);if(g)if(!Xe(g.entry,l.entry)||!this.instances.some(h=>h.name===a)||this.failedStartAgents.has(a))try{await this.replaceInstance(a,l.entry,l.file),o.restarted.push(a)}catch(h){o.failed.push({name:a,error:h instanceof Error?h.message:String(h)})}else this.rawConfigMap.set(a,l),o.unchanged.push(a);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(a)}catch(h){o.failed.push({name:a,error:h instanceof Error?h.message:String(h)})}}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 Ye(this.instances,e)}async probeOne(e,n={}){return Je(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return Me(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Ye(r,e){const n=e.concurrency??4,t=Date.now(),s=new Array(r.length);await new Promise(a=>{let l=0,g=0;const h=r.length;if(h===0){a();return}function d(_){const w=r[_];w.probe(e).then(S=>{s[_]=S,u()},S=>{s[_]={agent_name:w.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}},u()})}function u(){g++,l<h?d(l++):g===h&&a()}const f=Math.min(n,h);for(let _=0;_<f;_++)d(l++)});const i=s.filter(a=>a.status==="healthy").length,c=s.filter(a=>a.status==="degraded").length,o=s.filter(a=>a.status==="unavailable").length,p=await Ue();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:p,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function Je(r,e,n){const t=r.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{It as Manager,Y as normalizeAgentProviderForRuntime,Ue as probeInstalledClientCommands,Ye as probeInstances,Je as probeOneInstance};
@@ -1 +1 @@
1
- function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};