grix-connector 4.6.4 → 4.6.6

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.4",
4
- "tarball": "grix-dsh-bridge-4.6.4.tgz",
5
- "size": 23091,
3
+ "bridgeVersion": "4.6.6",
4
+ "tarball": "grix-dsh-bridge-4.6.6.tgz",
5
+ "size": 23125,
6
6
  "unpackedSize": 92668,
7
- "shasum": "ba8b1a2c48f71e38377475350809210ec559151e",
8
- "integrity": "sha512-alov5oJvXCb2iVwLyNk7xLJ7zgygPQgTCAP7o71a390LtOXJgSiUo2VvBEkAsU56lSJuaCyWAQw5aEa5qm7PoQ=="
7
+ "shasum": "000e7323b27bf2cb218e52f84c3f31d199371300",
8
+ "integrity": "sha512-iBnYnh1qKKFD/NFUuWHv8aNA1V2k/rHzLDAz8+ehpzQuhad5kPzM0RO82ik1LaOg2EG4idZD1XsMgL8tiM3bIA=="
9
9
  }
package/dist/grix.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import D from"node:path";import{writeFileSync as ne}from"node:fs";import{Manager as be}from"./manager.js";import{ensureGrixDirs as Ie,initLogger as Pe,log as i,installProcessLogRotation as Ce,setConsoleOutput as oe}from"./core/log/index.js";import{HealthServer as ke,bindPortOrFail as ae}from"./core/runtime/index.js";import{writePidFile as _e,removePidFile as F,readDaemonPid as Te}from"./core/runtime/index.js";import{resolveRuntimePaths as K}from"./core/config/index.js";import{supportsNonMitmRelayConfig as Ue}from"./core/config/provider-env.js";import{ServiceManager as ie}from"./service/service-manager.js";import{RESTART_EXIT_CODE as $e,UNHEALTHY_EXIT_CODE as Le,markManagedStop as Oe,resolveLauncherStore as se,writeCrashNote as Fe}from"./core/upgrade/version-store.js";import{migrateWindowsWrapper as X}from"./service/windows-wrapper-migration.js";const He=300*1e3;import{killProcessesByCommandLine as Me,isWindowsElevated as Ne,shouldSweepWindowsWrappers as Ge}from"./service/process-control.js";import{buildServiceID as Be}from"./service/service-paths.js";import{acquireDaemonLock as je,isLockHolderSameProcess as We,readDaemonLock as V,releaseDaemonLock as H}from"./runtime/daemon-lock.js";import{writeDaemonStatus as G,removeDaemonStatus as Ke}from"./runtime/service-state.js";import{AdminServer as Xe,generateToken as Ve,writeTokenFile as qe}from"./core/admin/index.js";import{initSentry as Ye,closeSentry as q,reportFatal as Y}from"./core/observability/sentry.js";import{initProxyManager as Je,getProxyManager as f,relayHostsForClientType as ce,RelayStateStore as ze,SecretStore as Qe}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as le,switchAgentRelayMode as J,reconcileRelayStates as de}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as pe,RelayCredentialError as ue}from"./core/proxy/relay-credential.js";import{RelayFetchError as ge,RelayToggleCoordinator as Ze}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as et,clearHermesProfileRelay as tt,discoverHermesProfiles as rt}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as nt,enableRelayCredential as ot,RelayRouteError as fe}from"./core/proxy/relay-credential-router.js";import{upgradeStatusSnapshot as at}from"./core/upgrade/npm-upgrader.js";import{resolveClientVersion as it}from"./core/util/client-version.js";import{parseCliArgs as st}from"./core/util/cli-args.js";const{command:x,flags:S,unknownFlags:z}=st(process.argv.slice(2));if(z.length>0&&(console.error(`Unknown option${z.length>1?"s":""}: ${z.map(r=>`--${r}`).join(", ")}
3
- Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),S.version&&(console.log(it()),process.exit(0)),S.help&&(console.log(`grix-connector \u2014 Unified AI Agent Bridge
2
+ import x from"node:path";import{writeFileSync as oe}from"node:fs";import{Manager as Pe}from"./manager.js";import{ensureGrixDirs as Ie,initLogger as _e,log as i,installProcessLogRotation as Ce,setConsoleOutput as ae}from"./core/log/index.js";import{HealthServer as ke,bindPortOrFail as ie}from"./core/runtime/index.js";import{writePidFile as Te,removePidFile as H,readDaemonPid as $e}from"./core/runtime/index.js";import{resolveRuntimePaths as K}from"./core/config/index.js";import{supportsNonMitmRelayConfig as Ue}from"./core/config/provider-env.js";import{ServiceManager as se}from"./service/service-manager.js";import{RESTART_EXIT_CODE as Le,UNHEALTHY_EXIT_CODE as Oe,markManagedStop as ce,resolveLauncherStore as X,writeCrashNote as He}from"./core/upgrade/version-store.js";import{migrateWindowsWrapper as V}from"./service/windows-wrapper-migration.js";const Fe=300*1e3;import{killProcessesByCommandLine as Me,isWindowsElevated as Ne,shouldSweepWindowsWrappers as Ge,getProcessCommandLine as Be}from"./service/process-control.js";import{buildServiceID as je}from"./service/service-paths.js";import{acquireDaemonLock as We,createHealthzHolderProbe as Ke,DaemonAlreadyServingError as Xe,isLockHolderSameProcess as Ve,readDaemonLock as q,releaseDaemonLock as F}from"./runtime/daemon-lock.js";import{writeDaemonStatus as G,removeDaemonStatus as qe}from"./runtime/service-state.js";import{readDuplicateDaemonRecord as Ye,recordDuplicateDaemon as Je}from"./runtime/duplicate-daemon.js";import{AdminServer as ze,generateToken as Qe,writeTokenFile as Ze}from"./core/admin/index.js";import{initSentry as et,closeSentry as Y,reportFatal as J}from"./core/observability/sentry.js";import{initProxyManager as tt,getProxyManager as m,relayHostsForClientType as le,RelayStateStore as rt,SecretStore as nt}from"./core/proxy/index.js";import{stopProxyIfNobodyNeedsIt as de,switchAgentRelayMode as z,reconcileRelayStates as pe}from"./core/proxy/relay-orchestration.js";import{setAgentRelayCredential as ue,RelayCredentialError as ge}from"./core/proxy/relay-credential.js";import{RelayFetchError as fe,RelayToggleCoordinator as ot}from"./core/proxy/relay-credential-fetch.js";import{applyHermesProfileRelay as at,clearHermesProfileRelay as it,discoverHermesProfiles as st}from"./core/proxy/hermes-profile-relay.js";import{disableRelayCredential as ct,enableRelayCredential as lt,RelayRouteError as me}from"./core/proxy/relay-credential-router.js";import{upgradeStatusSnapshot as dt}from"./core/upgrade/npm-upgrader.js";import{resolveClientVersion as pt}from"./core/util/client-version.js";import{parseCliArgs as ut}from"./core/util/cli-args.js";const{command:b,flags:E,unknownFlags:Q}=ut(process.argv.slice(2));if(Q.length>0&&(console.error(`Unknown option${Q.length>1?"s":""}: ${Q.map(t=>`--${t}`).join(", ")}
3
+ Run \`grix-connector --help\` to see the supported commands and options.`),process.exit(1)),E.version&&(console.log(pt()),process.exit(0)),E.help&&(console.log(`grix-connector \u2014 Unified AI Agent Bridge
4
4
 
5
5
  Usage: grix-connector <command> [options]
6
6
 
@@ -34,9 +34,10 @@ Examples:
34
34
  grix-connector start # Start as system service
35
35
  grix-connector status # Check service status
36
36
  grix-connector restart # Restart the service
37
- `),process.exit(0)),x==="reload"){const r=Te();r||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(r,0)}catch{console.error(`reload failed: daemon process ${r} is not running (stale pid file)`),process.exit(1)}{const c=V(K().daemonLockFile);c&&c.pid===r&&!We(c)&&(console.error(`reload failed: pid ${r} has been reused by another process (stale pid file)`),process.exit(1))}try{process.kill(r,"SIGHUP"),console.log(JSON.stringify({ok:!0,signaled:r},null,2)),process.exit(0)}catch(c){console.error(`reload failed: ${c instanceof Error?c.message:c}`),process.exit(1)}}const me=["start","stop","restart","status"];if(x&&me.includes(x)){process.platform==="win32"&&["start","stop","restart"].includes(x)&&!Ne()&&console.warn(`Warning: Not running as administrator. Task Scheduler registration is skipped;
37
+ `),process.exit(0)),b==="reload"){const t=$e();t||(console.error("reload failed: daemon is not running (no pid file)"),process.exit(1));try{process.kill(t,0)}catch{console.error(`reload failed: daemon process ${t} is not running (stale pid file)`),process.exit(1)}{const c=q(K().daemonLockFile);c&&c.pid===t&&!Ve(c)&&(console.error(`reload failed: pid ${t} has been reused by another process (stale pid file)`),process.exit(1))}try{process.kill(t,"SIGHUP"),console.log(JSON.stringify({ok:!0,signaled:t},null,2)),process.exit(0)}catch(c){console.error(`reload failed: ${c instanceof Error?c.message:c}`),process.exit(1)}}const he=["start","stop","restart","status"];if(b&&he.includes(b)){process.platform==="win32"&&["start","stop","restart"].includes(b)&&!Ne()&&console.warn(`Warning: Not running as administrator. Task Scheduler registration is skipped;
38
38
  using Startup folder auto-start instead. For full Task Scheduler integration,
39
- right-click the terminal and select "Run as administrator".`);const r=K(),c=S["config-dir"]??(S.profile?D.join(r.configDir,S.profile):void 0),m=D.resolve(process.argv[1]||`${r.rootDir}/dist/grix.js`),g=new ie({cliPath:m,nodePath:process.execPath});try{let l;switch(x){case"start":(await g.status({rootDir:r.rootDir})).installed?l=await g.start({rootDir:r.rootDir}):l=await g.install({rootDir:r.rootDir,configDir:c});break;case"stop":l=await g.stop({rootDir:r.rootDir});break;case"restart":(await g.status({rootDir:r.rootDir})).installed?l=await g.restart({rootDir:r.rootDir}):l=await g.install({rootDir:r.rootDir,configDir:c});break;case"status":l=await g.status({rootDir:r.rootDir});break}console.log(JSON.stringify(l,null,2)),process.exit(0)}catch(l){console.error(`${x} failed: ${l instanceof Error?l.message:l}`),process.exit(1)}}else x&&(console.error(`Unknown command: ${x}
40
- Valid commands: ${me.join(", ")}`),process.exit(1));const s=K(),ct=S["config-dir"]??(S.profile?`${s.configDir}/${S.profile}`:void 0),n=new be({requestGracefulShutdown:r=>{I(r)},onTransactionSettled:()=>{X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(r=>{r.handoffStarted&&i.info("main","Wrapper handoff started after the upgrade transaction settled")}).catch(r=>{i.warn("main",`Post-upgrade wrapper migration failed: ${r instanceof Error?r.message:r}`)})}}),M=new ke,he=Ve(),b=new Xe(he);let B=!1,T;function j(r,c){const m=se(),g=process.env.GRIX_LAUNCHER_VERSION;if(!m||!g)return;const l=c instanceof Error?c.stack??c.message:String(c);Fe(m,g,`${r}: ${l}`)}async function ye(r){process.stderr.write(r.message+`
41
- `),i.error("main",r.message.replace(/\n/g," \u2014 ")),j("port_bind",r.message);const c=V(s.daemonLockFile);c?.pid===process.pid&&c.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:T,updated_at:Date.now(),reason:`port_bind_${r.kind}:${r.label}:${r.port}`}).catch(()=>{}),await q(),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(1)}async function I(r){if(B)return;B=!0,i.info("main",`Received ${r}, shutting down...`),M.markShuttingDown();const c=se();c&&Oe(c);const m=r==="upgrade-switch"?$e:r==="launcher-unhealthy"?Le:null,g=m??2,l=r==="uncaughtException"||r==="unhandledRejection",P=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(g)},1e4);try{await n.stop(),await f()?.stop().catch(()=>{}),await b.stop(),await M.stop(),await q(),await H(s.daemonLockFile),await Ke(s.daemonStatusFile).catch(()=>{}),clearTimeout(P),F(),i.info("main","Shutdown complete"),process.exit(m??(l?2:0))}catch(C){i.error("main",`Shutdown error: ${C}`),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(g)}}async function lt(){if(Ie(),Pe(),Ce(s.stdoutLogFile,s.stderrLogFile),oe(!1),Ge()){const e=Be(s.rootDir,"win32");await Me(e,{platform:"win32"})}try{T=(await je(s.daemonLockFile,s.rootDir)).instance_id}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}if(await Ye(),_e(),i.info("main",`grix-connector starting (PID ${process.pid})`),await G(s.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new ie({cliPath:D.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(s.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),(await X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null)))?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{B||X({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(o=>{o.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(o=>{i.warn("main",`Periodic wrapper migration failed: ${o instanceof Error?o.message:o}`)})},He).unref();const c=parseInt(S["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await ae({label:"health",port:c,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:o=>M.start(o)});e&&await ye(e)}const m=D.join(s.dataDir,"health-port");ne(m,String(c),"utf-8"),process.on("SIGINT",()=>I("SIGINT")),process.on("SIGTERM",()=>I("SIGTERM")),process.on("SIGHUP",()=>{B||(i.info("main","Received SIGHUP, reloading config..."),n.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let g="",l=0,P;process.on("uncaughtException",e=>{const o=e instanceof Error?e.stack??e.message:String(e);o===g?(l++,(l<=3||l%100===0)&&i.error("main",`Uncaught exception (x${l}): ${o}`)):(l>3&&i.error("main",`Previous exception repeated ${l} times total`),g=o,l=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),P||(P=setTimeout(()=>{l>3&&i.error("main",`Previous exception repeated ${l} times total`),g="",l=0,P=void 0},1e4).unref())),!we(e)&&(Y(e,"uncaughtException"),j("uncaughtException",e),I("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!we(e)&&(Y(e,"unhandledRejection"),j("unhandledRejection",e),I("unhandledRejection"))});const C=Je(s.dataDir);await C.clearRuntimeState();const k=new ze(D.join(s.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),N=new Qe(D.join(s.dataDir,"secrets"));n.setRelaySecretResolver(e=>N.get(e));const U={hasDirectConfig:e=>n.hasDirectRelayConfig(e),clearDirectConfig:(e,o)=>n.setAgentProvider(e,void 0,{deferRestart:o?.deferRestart===!0})},W=()=>({pm:f(),agents:n,direct:U,store:k,secrets:N}),$=C.getRelayAgents();if($.length>0)try{await C.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${$.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${$.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let L=null;if(f()){const e=async()=>{const t=f();t&&await le(t,n)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};n.setRelayEnvSettledHandler(()=>{const t=f();t&&de(t,U,k),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const o=()=>{const t=f(),a=t.getRelayAgents(),d=t.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:n.getAgentsWithStaleRelayEnv(),degradedRelayAgents:d,relayState:k.list(),runtime:t.getRuntimeInfo(),config:t.getConfigSnapshot()}},p=new Ze,E={status:()=>o(),setAgentRelay:async(t,a,d)=>{const u=f(),R={info:y=>i.info("main",y),warn:y=>i.warn("main",y)},w=y=>n.getAgentsStatus().find(A=>A.name===y),h=w(t);if(!a){p.cancel(t);const y=await p.runExclusive(t,async()=>{const A=await J(W(),R,{agentName:t,target:"off"});return{...o(),restarted:A.restarted,busy:A.busy,...A.pending?{pending:A.pending}:{}}});return n.reportRelayStateLocalChange(t),y}if(!h)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});if(!Ue(h.clientType)&&ce(h.clientType).length===0)throw Object.assign(new Error(`client type "${h.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const O=await p.runExclusive(t,async()=>{const y=p.epoch(t),A=w(t);if(!A)throw Object.assign(new Error(`Agent "${t}" not found`),{code:"NOT_FOUND"});const ee=String(A.agentId??"").trim();if(!ee)throw new ue(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const te=p.waitCancelled(t,y);let _;try{_=await Promise.race([n.fetchRelayCredential(t,{model:d}),te.promise.then(()=>{throw new ge("relay enable cancelled by a later disable","CANCELLED")})])}finally{te.dispose()}p.assertCurrent(t,y);const{restarted:Ee,busy:Ae,pending:re}=await pe(u,n,w,R,{localName:t,agentId:ee,virtualKey:_.apiKey,anthropicBaseUrl:_.anthropicBaseUrl,openaiBaseUrl:_.openaiBaseUrl,model:d,..._.directRelay!==void 0?{directRelay:_.directRelay}:{}},(ve,De,xe)=>n.setAgentProvider(ve,De,{deferRestart:xe?.deferRestart===!0}),{store:k,secrets:N,direct:U});if(p.epoch(t)!==y)throw await J(W(),R,{agentName:t,target:"off"}),new ge("relay enable cancelled by a later disable","CANCELLED");return{...o(),restarted:Ee,busy:Ae,...re?{pending:re}:{}}});return n.reportRelayStateLocalChange(t),O},setAgentRelayCredential:async(t,a)=>{const d=f(),u=n.getAgentsStatus(),{restarted:R,busy:w,pending:h}=await pe(d,n,v=>u.find(O=>O.name===v),{info:v=>i.info("main",v),warn:v=>i.warn("main",v)},{localName:t,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(v,O,y)=>n.setAgentProvider(v,O,{deferRestart:y?.deferRestart===!0}),{store:k,secrets:N,direct:U});return n.reportRelayStateLocalChange(t),{...o(),restarted:R,busy:w,...h?{pending:h}:{}}},disableAll:async()=>{const t=f(),a={info:u=>i.info("main",u),warn:u=>i.warn("main",u)},d=new Set([...t.getRelayAgents(),...n.getDirectRelayConfigAgentNames(),...Object.keys(k.list())]);for(const u of d)p.cancel(u);for(const u of d)await p.runExclusive(u,()=>J(W(),a,{agentName:u,target:"off"})),n.reportRelayStateLocalChange(u);return await le(t,n),o()},setRoute:async(t,a)=>{const d=a,u=f();return u.setRoute({routeKey:t,targetBaseUrl:d.targetBaseUrl,...d.headers?{headers:d.headers}:{},...d.model?{model:d.model}:{},...d.modelMap?{modelMap:d.modelMap}:{},...d.passthrough?{passthrough:!0}:{},...d.relayOnly?{relayOnly:!0}:{},...d.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await u.persistConfig(),o()},deleteRoute:async t=>{const a=f();a.deleteRoute(t),await a.persistConfig()},setDefaultRoute:async t=>{const a=f();return a.setDefaultRouteKey(t),await a.persistConfig(),o()},setInterceptHosts:async t=>{const a=f();return a.setInterceptHosts(t),await a.persistConfig(),o()}};L=E,b.setProxyHandler(E),n.setRelayStateApplier({getLocalState:t=>{const a=f();if(a.getRelayAgents().includes(t)){const u=n.getAgentsStatus().find(h=>h.name===t),R=`grix-gateway-${String(u?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(h=>h.routeKey===R)?.model?.trim()||void 0}}const d=n.getAgentProvider(t);return d?.api_key?.trim()?{enabled:!0,model:d.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(t,a,d)=>{const u=n.getAgentsStatus().find(h=>h.name===t),R=String(u?.agentId??"").trim();if(!R)throw new ue(`local agent "${t}" has no agent_id registered`,"MISSING_AGENT_ID");const w=await E.setAgentRelayCredential(t,{agentId:R,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:d??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:w.restarted===!0,busy:w.busy===!0,...w.pending?{pending:w.pending}:{}}},applyDisable:async t=>{const a=await E.setAgentRelay(t,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}if(M.setStatusProvider(()=>n.getAgentsStatus()),M.setMetaProvider(()=>{const e=n.getAgentsStatus();return{ws:{connected:e.filter(o=>o.wsConnected===!0).length,total:e.length},upgrade:at()}}),await n.start(ct),$.length>0){const e=n.getAgentsStatus();for(const o of $){const p=e.find(t=>t.name===o);if(!p)continue;const E=ce(p.clientType);E.length!==0&&await C.setAgentRelayEnabled(o,!0,{relayHosts:E}).catch(t=>{i.warn("main",`failed to reconcile relay hosts for "${o}": ${t}`)})}}de(C,U,k);const Q=parseInt(S["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);b.setAgentHandler({list:()=>n.getAgentsStatus(),add:e=>n.addAgent(e),remove:e=>n.removeAgent(e),restart:e=>n.restartAgent(e),reload:()=>n.reload()}),b.setUpgradeHandler({check:()=>n.checkUpgrade(),trigger:()=>n.triggerUpgrade()}),b.setProbeHandler({probeAll:e=>n.probeAll(e),probeOne:(e,o)=>n.probeOne(e,o)}),b.setInstallHandler({listInstallable:()=>n.listInstallable(),installAgent:e=>n.installAgent(e),getInstallProgress:e=>n.getInstallProgress(e)});const Z={listAgents:()=>n.getAgentsStatus(),enableManaged:(e,o,p)=>{if(!L)throw new fe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelayCredential(e,{agentId:o,virtualKey:p.virtualKey,anthropicBaseUrl:p.anthropicBaseUrl,openaiBaseUrl:p.openaiBaseUrl,model:p.model,...p.directRelay!==void 0?{directRelay:p.directRelay}:{}})},disableManaged:e=>{if(!L)throw new fe(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelay(e,!1)},enableHermesProfile:(e,o)=>et({agentId:e,baseUrl:o.openaiBaseUrl??"",virtualKey:o.virtualKey,model:o.model??""}),disableHermesProfile:e=>tt(e)};b.setRelayCredentialHandler({listHermesProfiles:()=>rt(),enable:async(e,o)=>{const{target:p,result:E}=await ot(Z,e,o);return{target:p,...E}},disable:async e=>{const{target:o,result:p}=await nt(Z,e);return{target:o,...p}}});{const e=await ae({label:"admin",port:Q,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:o=>b.start(o)});e&&await ye(e)}const Re=D.join(s.dataDir,"admin-token"),Se=D.join(s.dataDir,"admin-port");qe(Re,he),ne(Se,String(Q),"utf-8"),await G(s.daemonStatusFile,{state:"running",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.send&&process.send("ready"),i.info("main","grix-connector ready")}lt().catch(async r=>{const c=`Fatal: ${r instanceof Error?r.stack??r.message:String(r)}`;try{process.stderr.write(`${c}
42
- `)}catch{}oe(!1),i.error("main",c),Y(r,"startup"),j("startup",r);const m=V(s.daemonLockFile);m?.pid===process.pid&&m.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:m.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await q(),H(s.daemonLockFile).catch(()=>{}),F(),process.exit(1)});const dt=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function we(r){return r instanceof Error&&"code"in r?dt.has(r.code):!1}
39
+ right-click the terminal and select "Run as administrator".`);const t=K(),c=E["config-dir"]??(E.profile?x.join(t.configDir,E.profile):void 0),f=x.resolve(process.argv[1]||`${t.rootDir}/dist/grix.js`),g=new se({cliPath:f,nodePath:process.execPath});try{let l;switch(b){case"start":(await g.status({rootDir:t.rootDir})).installed?l=await g.start({rootDir:t.rootDir}):l=await g.install({rootDir:t.rootDir,configDir:c});break;case"stop":l=await g.stop({rootDir:t.rootDir});break;case"restart":(await g.status({rootDir:t.rootDir})).installed?l=await g.restart({rootDir:t.rootDir}):l=await g.install({rootDir:t.rootDir,configDir:c});break;case"status":l=await g.status({rootDir:t.rootDir});{const S=Ye(t.dataDir);S&&(l={...l,duplicate_daemon:S})}break}console.log(JSON.stringify(l,null,2)),process.exit(0)}catch(l){console.error(`${b} failed: ${l instanceof Error?l.message:l}`),process.exit(1)}}else b&&(console.error(`Unknown command: ${b}
40
+ Valid commands: ${he.join(", ")}`),process.exit(1));const s=K(),gt=E["config-dir"]??(E.profile?`${s.configDir}/${E.profile}`:void 0),n=new Pe({requestGracefulShutdown:t=>{I(t)},onTransactionSettled:()=>{V({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(t=>{t.handoffStarted&&i.info("main","Wrapper handoff started after the upgrade transaction settled")}).catch(t=>{i.warn("main",`Post-upgrade wrapper migration failed: ${t instanceof Error?t.message:t}`)})}}),M=new ke,ye=Qe(),P=new ze(ye);let B=!1,T;function j(t,c){const f=X(),g=process.env.GRIX_LAUNCHER_VERSION;if(!f||!g)return;const l=c instanceof Error?c.stack??c.message:String(c);He(f,g,`${t}: ${l}`)}function ft(t){const c=`another grix-connector daemon (pid ${t.pid}) is already serving ${s.rootDir} and answering /healthz; this process yields instead of taking over. A second supervisor is starting duplicate daemons \u2014 check for a leftover wrapper, a duplicate logon task, or a desktop app launching its own copy.`;Je(s.dataDir,{holder_pid:t.pid,holder_command_line:t.command_line,yielded_pid:process.pid,yielded_command_line:Be(process.pid)}),process.stderr.write(`${c}
41
+ `),i.warn("main",c);const f=X();f&&ce(f),process.exit(0)}async function we(t){process.stderr.write(t.message+`
42
+ `),i.error("main",t.message.replace(/\n/g," \u2014 ")),j("port_bind",t.message);const c=q(s.daemonLockFile);c?.pid===process.pid&&c.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:T,updated_at:Date.now(),reason:`port_bind_${t.kind}:${t.label}:${t.port}`}).catch(()=>{}),await Y(),F(s.daemonLockFile).catch(()=>{}),H(),process.exit(1)}async function I(t){if(B)return;B=!0,i.info("main",`Received ${t}, shutting down...`),M.markShuttingDown();const c=X();c&&ce(c);const f=t==="upgrade-switch"?Le:t==="launcher-unhealthy"?Oe:null,g=f??2,l=t==="uncaughtException"||t==="unhandledRejection",S=setTimeout(()=>{i.error("main","Shutdown timed out, forcing exit"),F(s.daemonLockFile).catch(()=>{}),H(),process.exit(g)},1e4);try{await n.stop(),await m()?.stop().catch(()=>{}),await P.stop(),await M.stop(),await Y(),await F(s.daemonLockFile),await qe(s.daemonStatusFile).catch(()=>{}),clearTimeout(S),H(),i.info("main","Shutdown complete"),process.exit(f??(l?2:0))}catch(_){i.error("main",`Shutdown error: ${_}`),F(s.daemonLockFile).catch(()=>{}),H(),process.exit(g)}}async function mt(){Ie(),_e(),Ce(s.stdoutLogFile,s.stderrLogFile),ae(!1);try{T=(await We(s.daemonLockFile,s.rootDir,2,{isHolderServing:Ke(s.dataDir)})).instance_id}catch(e){e instanceof Xe&&ft(e.holder),console.error(e instanceof Error?e.message:e),process.exit(1)}if(Ge()){const e=je(s.rootDir,"win32");await Me(e,{platform:"win32"})}if(await et(),Te(),i.info("main",`grix-connector starting (PID ${process.pid})`),await G(s.daemonStatusFile,{state:"starting",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.env.GRIX_LAUNCHER_MANAGED!=="1"&&await new se({cliPath:x.resolve(process.argv[1]??""),nodePath:process.execPath}).adoptLauncher(s.rootDir).then(e=>{e&&i.info("main","Service definition now points at the version-store launcher")}).catch(e=>{i.warn("main",`Launcher adoption failed: ${e instanceof Error?e.message:e}`)}),(await V({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).catch(e=>(i.warn("main",`Windows wrapper migration failed: ${e instanceof Error?e.message:e}`),null)))?.handoffStarted)return;process.platform==="win32"&&process.env.GRIX_LAUNCHER_MANAGED!=="1"&&setInterval(()=>{B||V({rootDir:s.rootDir,requestGracefulShutdown:()=>{I("wrapper-migration")}}).then(o=>{o.handoffStarted&&i.info("main","Wrapper handoff started by the periodic migration retry")}).catch(o=>{i.warn("main",`Periodic wrapper migration failed: ${o instanceof Error?o.message:o}`)})},Fe).unref();const c=parseInt(E["health-port"]??process.env.GRIX_HEALTH_PORT??"19579",10);{const e=await ie({label:"health",port:c,envVar:"GRIX_HEALTH_PORT",cliFlag:"health-port",start:o=>M.start(o)});e&&await we(e)}const f=x.join(s.dataDir,"health-port");oe(f,String(c),"utf-8"),process.on("SIGINT",()=>I("SIGINT")),process.on("SIGTERM",()=>I("SIGTERM")),process.on("SIGHUP",()=>{B||(i.info("main","Received SIGHUP, reloading config..."),n.reload().then(e=>i.info("main",`reload done: ${JSON.stringify(e)}`)).catch(e=>i.error("main",`reload failed: ${e instanceof Error?e.message:e}`)))});let g="",l=0,S;process.on("uncaughtException",e=>{const o=e instanceof Error?e.stack??e.message:String(e);o===g?(l++,(l<=3||l%100===0)&&i.error("main",`Uncaught exception (x${l}): ${o}`)):(l>3&&i.error("main",`Previous exception repeated ${l} times total`),g=o,l=1,i.error("main",`Uncaught exception: ${e instanceof Error?e.stack:e}`),S||(S=setTimeout(()=>{l>3&&i.error("main",`Previous exception repeated ${l} times total`),g="",l=0,S=void 0},1e4).unref())),!Se(e)&&(J(e,"uncaughtException"),j("uncaughtException",e),I("uncaughtException"))}),process.on("unhandledRejection",e=>{i.error("main",`Unhandled rejection: ${e}`),!Se(e)&&(J(e,"unhandledRejection"),j("unhandledRejection",e),I("unhandledRejection"))});const _=tt(s.dataDir);await _.clearRuntimeState();const C=new rt(x.join(s.dataDir,"proxy","relay-state.json"),{warn:e=>i.warn("main",e)}),N=new nt(x.join(s.dataDir,"secrets"));n.setRelaySecretResolver(e=>N.get(e));const $={hasDirectConfig:e=>n.hasDirectRelayConfig(e),clearDirectConfig:(e,o)=>n.setAgentProvider(e,void 0,{deferRestart:o?.deferRestart===!0})},W=()=>({pm:m(),agents:n,direct:$,store:C,secrets:N}),U=_.getRelayAgents();if(U.length>0)try{await _.startIfAnyRelayAgent(),i.info("main",`mitm proxy started for relay agents: ${U.join(", ")} (per-agent; others stay direct)`)}catch(e){i.error("main",`mitm proxy FAILED to start (relay agents: ${U.join(", ")}): ${e}. These agents will REFUSE to start (they must not silently fall back to your own account). Fix the proxy or turn relay off for them. Other agents are unaffected.`)}else i.info("main",'mitm proxy idle (no agent has Grix relay enabled; enable: PUT /api/proxy/agents/<name>/enabled {"enabled":true})');let L=null;if(m()){const e=async()=>{const r=m();r&&await de(r,n)&&i.info("main","no agent uses Grix relay anymore; mitm proxy stopped")};n.setRelayEnvSettledHandler(()=>{const r=m();r&&pe(r,$,C),e().catch(a=>{i.warn("main",`failed to stop idle mitm proxy: ${a}`)})});const o=()=>{const r=m(),a=r.getRelayAgents(),d=r.getDegradedRelayAgents();return{enabled:a.length>0,relayAgents:a,staleRelayAgents:n.getAgentsWithStaleRelayEnv(),degradedRelayAgents:d,relayState:C.list(),runtime:r.getRuntimeInfo(),config:r.getConfigSnapshot()}},p=new ot,A={status:()=>o(),setAgentRelay:async(r,a,d)=>{const u=m(),R={info:y=>i.info("main",y),warn:y=>i.warn("main",y)},w=y=>n.getAgentsStatus().find(v=>v.name===y),h=w(r);if(!a){p.cancel(r);const y=await p.runExclusive(r,async()=>{const v=await z(W(),R,{agentName:r,target:"off"});return{...o(),restarted:v.restarted,busy:v.busy,...v.pending?{pending:v.pending}:{}}});return n.reportRelayStateLocalChange(r),y}if(!h)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});if(!Ue(h.clientType)&&le(h.clientType).length===0)throw Object.assign(new Error(`client type "${h.clientType??""}" does not support Grix relay`),{code:"UNSUPPORTED_CLIENT_TYPE"});const O=await p.runExclusive(r,async()=>{const y=p.epoch(r),v=w(r);if(!v)throw Object.assign(new Error(`Agent "${r}" not found`),{code:"NOT_FOUND"});const te=String(v.agentId??"").trim();if(!te)throw new ge(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const re=p.waitCancelled(r,y);let k;try{k=await Promise.race([n.fetchRelayCredential(r,{model:d}),re.promise.then(()=>{throw new fe("relay enable cancelled by a later disable","CANCELLED")})])}finally{re.dispose()}p.assertCurrent(r,y);const{restarted:Ae,busy:ve,pending:ne}=await ue(u,n,w,R,{localName:r,agentId:te,virtualKey:k.apiKey,anthropicBaseUrl:k.anthropicBaseUrl,openaiBaseUrl:k.openaiBaseUrl,model:d,...k.directRelay!==void 0?{directRelay:k.directRelay}:{}},(De,xe,be)=>n.setAgentProvider(De,xe,{deferRestart:be?.deferRestart===!0}),{store:C,secrets:N,direct:$});if(p.epoch(r)!==y)throw await z(W(),R,{agentName:r,target:"off"}),new fe("relay enable cancelled by a later disable","CANCELLED");return{...o(),restarted:Ae,busy:ve,...ne?{pending:ne}:{}}});return n.reportRelayStateLocalChange(r),O},setAgentRelayCredential:async(r,a)=>{const d=m(),u=n.getAgentsStatus(),{restarted:R,busy:w,pending:h}=await ue(d,n,D=>u.find(O=>O.name===D),{info:D=>i.info("main",D),warn:D=>i.warn("main",D)},{localName:r,agentId:a.agentId,virtualKey:a.virtualKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}},(D,O,y)=>n.setAgentProvider(D,O,{deferRestart:y?.deferRestart===!0}),{store:C,secrets:N,direct:$});return n.reportRelayStateLocalChange(r),{...o(),restarted:R,busy:w,...h?{pending:h}:{}}},disableAll:async()=>{const r=m(),a={info:u=>i.info("main",u),warn:u=>i.warn("main",u)},d=new Set([...r.getRelayAgents(),...n.getDirectRelayConfigAgentNames(),...Object.keys(C.list())]);for(const u of d)p.cancel(u);for(const u of d)await p.runExclusive(u,()=>z(W(),a,{agentName:u,target:"off"})),n.reportRelayStateLocalChange(u);return await de(r,n),o()},setRoute:async(r,a)=>{const d=a,u=m();return u.setRoute({routeKey:r,targetBaseUrl:d.targetBaseUrl,...d.headers?{headers:d.headers}:{},...d.model?{model:d.model}:{},...d.modelMap?{modelMap:d.modelMap}:{},...d.passthrough?{passthrough:!0}:{},...d.relayOnly?{relayOnly:!0}:{},...d.codexResponsesToChat?{codexResponsesToChat:!0}:{}}),await u.persistConfig(),o()},deleteRoute:async r=>{const a=m();a.deleteRoute(r),await a.persistConfig()},setDefaultRoute:async r=>{const a=m();return a.setDefaultRouteKey(r),await a.persistConfig(),o()},setInterceptHosts:async r=>{const a=m();return a.setInterceptHosts(r),await a.persistConfig(),o()}};L=A,P.setProxyHandler(A),n.setRelayStateApplier({getLocalState:r=>{const a=m();if(a.getRelayAgents().includes(r)){const u=n.getAgentsStatus().find(h=>h.name===r),R=`grix-gateway-${String(u?.clientType??"").trim().toLowerCase()}`;return{enabled:!0,model:a.getConfigSnapshot().routes?.find(h=>h.routeKey===R)?.model?.trim()||void 0}}const d=n.getAgentProvider(r);return d?.api_key?.trim()?{enabled:!0,model:d.model?.trim()||void 0}:{enabled:!1}},applyEnable:async(r,a,d)=>{const u=n.getAgentsStatus().find(h=>h.name===r),R=String(u?.agentId??"").trim();if(!R)throw new ge(`local agent "${r}" has no agent_id registered`,"MISSING_AGENT_ID");const w=await A.setAgentRelayCredential(r,{agentId:R,virtualKey:a.apiKey,anthropicBaseUrl:a.anthropicBaseUrl,openaiBaseUrl:a.openaiBaseUrl,model:d??a.model,...a.directRelay!==void 0?{directRelay:a.directRelay}:{}});return{restarted:w.restarted===!0,busy:w.busy===!0,...w.pending?{pending:w.pending}:{}}},applyDisable:async r=>{const a=await A.setAgentRelay(r,!1);return{restarted:a.restarted===!0,busy:a.busy===!0,...a.pending?{pending:a.pending}:{}}}})}if(M.setStatusProvider(()=>n.getAgentsStatus()),M.setMetaProvider(()=>{const e=n.getAgentsStatus();return{ws:{connected:e.filter(o=>o.wsConnected===!0).length,total:e.length},upgrade:dt()}}),await n.start(gt),U.length>0){const e=n.getAgentsStatus();for(const o of U){const p=e.find(r=>r.name===o);if(!p)continue;const A=le(p.clientType);A.length!==0&&await _.setAgentRelayEnabled(o,!0,{relayHosts:A}).catch(r=>{i.warn("main",`failed to reconcile relay hosts for "${o}": ${r}`)})}}pe(_,$,C);const Z=parseInt(E["admin-port"]??process.env.GRIX_ADMIN_PORT??"19580",10);P.setAgentHandler({list:()=>n.getAgentsStatus(),add:e=>n.addAgent(e),remove:e=>n.removeAgent(e),restart:e=>n.restartAgent(e),reload:()=>n.reload()}),P.setUpgradeHandler({check:()=>n.checkUpgrade(),trigger:()=>n.triggerUpgrade()}),P.setProbeHandler({probeAll:e=>n.probeAll(e),probeOne:(e,o)=>n.probeOne(e,o)}),P.setInstallHandler({listInstallable:()=>n.listInstallable(),installAgent:e=>n.installAgent(e),getInstallProgress:e=>n.getInstallProgress(e)});const ee={listAgents:()=>n.getAgentsStatus(),enableManaged:(e,o,p)=>{if(!L)throw new me(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelayCredential(e,{agentId:o,virtualKey:p.virtualKey,anthropicBaseUrl:p.anthropicBaseUrl,openaiBaseUrl:p.openaiBaseUrl,model:p.model,...p.directRelay!==void 0?{directRelay:p.directRelay}:{}})},disableManaged:e=>{if(!L)throw new me(`agent "${e}" needs the MITM proxy for relay, but it is not running`,"PROXY_UNAVAILABLE");return L.setAgentRelay(e,!1)},enableHermesProfile:(e,o)=>at({agentId:e,baseUrl:o.openaiBaseUrl??"",virtualKey:o.virtualKey,model:o.model??""}),disableHermesProfile:e=>it(e)};P.setRelayCredentialHandler({listHermesProfiles:()=>st(),enable:async(e,o)=>{const{target:p,result:A}=await lt(ee,e,o);return{target:p,...A}},disable:async e=>{const{target:o,result:p}=await ct(ee,e);return{target:o,...p}}});{const e=await ie({label:"admin",port:Z,envVar:"GRIX_ADMIN_PORT",cliFlag:"admin-port",start:o=>P.start(o)});e&&await we(e)}const Re=x.join(s.dataDir,"admin-token"),Ee=x.join(s.dataDir,"admin-port");Ze(Re,ye),oe(Ee,String(Z),"utf-8"),await G(s.daemonStatusFile,{state:"running",pid:process.pid,instance_id:T,updated_at:Date.now()}),process.send&&process.send("ready"),i.info("main","grix-connector ready")}mt().catch(async t=>{const c=`Fatal: ${t instanceof Error?t.stack??t.message:String(t)}`;try{process.stderr.write(`${c}
43
+ `)}catch{}ae(!1),i.error("main",c),J(t,"startup"),j("startup",t);const f=q(s.daemonLockFile);f?.pid===process.pid&&f.instance_id===T&&await G(s.daemonStatusFile,{state:"failed",pid:process.pid,instance_id:f.instance_id,updated_at:Date.now(),reason:"startup_error"}).catch(()=>{}),await Y(),F(s.daemonLockFile).catch(()=>{}),H(),process.exit(1)});const ht=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","EAI_AGAIN","ENOTFOUND","EHOSTUNREACH","ENETUNREACH","EIO"]);function Se(t){return t instanceof Error&&"code"in t?ht.has(t.code):!1}
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(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};
1
+ function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -1,2 +1,2 @@
1
- import{openSync as S,closeSync as D,existsSync as h,readFileSync as l,unlinkSync as s,writeSync as E}from"node:fs";import{mkdir as _}from"node:fs/promises";import{randomUUID as g}from"node:crypto";import f from"node:path";import o from"node:process";import{getProcessCommandLine as u,isProcessRunning as c}from"../service/process-control.js";function m(r){try{const n=JSON.parse(r);if(typeof n?.pid=="number"&&typeof n.acquired_at=="number")return n}catch{}return null}function p(r){if(!h(r))return null;try{return m(l(r,"utf8"))}catch{return null}}function O(r){const n=p(r);return n!==null&&c(n.pid)}function y(r){const n=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(n,0,0,r)}function x(r){const n=typeof r.command_line=="string"&&r.command_line?r.command_line:null;if(n===null)return!0;const t=u(r.pid);return t===null?!0:t===n}function v(r){const n=typeof r.command_line=="string"&&r.command_line?r.command_line:null;if(n===null)return!1;const t=u(r.pid);return t!==null&&t===n}function L(r){try{return o.kill(r,0),!0}catch(n){return n?.code!=="EPERM"}}function k(r){if(r<=0||r===o.pid)return!0;try{o.kill(r,"SIGTERM")}catch(a){return a?.code!=="EPERM"}const n=Date.now()+3e3;for(;Date.now()<n;){if(!c(r))return!0;y(100)}try{o.kill(r,"SIGKILL")}catch{}const t=Date.now()+1e3;for(;Date.now()<t;){if(!c(r))return!0;y(50)}return!c(r)}async function G(r,n,t=2){await _(f.dirname(r),{recursive:!0});const a={pid:o.pid,acquired_at:Date.now(),root_dir:f.resolve(n),instance_id:g(),command_line:u(o.pid)},w=`${JSON.stringify(a,null,2)}
2
- `;for(let d=0;d<=t;d+=1)try{const i=S(r,"wx");try{E(i,w)}finally{D(i)}return a}catch(i){if(!(i instanceof Error)||i.code!=="EEXIST")throw i;let e=null;try{e=m(l(r,"utf8"))}catch{}if(e&&c(e.pid)){if(e.pid===o.pid)throw new Error(`daemon already running (pid ${e.pid}, acquired at ${new Date(e.acquired_at).toISOString()})`);if(L(e.pid)&&x(e)&&!k(e.pid))throw new Error(`\u65E0\u6CD5\u7EC8\u6B62\u8001\u8FDB\u7A0B (pid ${e.pid})\uFF0C\u8BF7\u624B\u52A8\u5904\u7406`)}try{s(r)}catch{}}throw new Error("failed to acquire daemon lock after retries")}async function H(r){const n=p(r);if(n&&n.pid===o.pid)try{s(r)}catch{}}export{G as acquireDaemonLock,O as isDaemonLocked,v as isLockHolderIdentityVerified,x as isLockHolderSameProcess,p as readDaemonLock,H as releaseDaemonLock};
1
+ import{openSync as g,closeSync as D,existsSync as p,readFileSync as s,unlinkSync as y,writeSync as E}from"node:fs";import{mkdir as x}from"node:fs/promises";import{randomUUID as _}from"node:crypto";import f from"node:path";import i from"node:process";import{getProcessCommandLine as m,isProcessRunning as l}from"../service/process-control.js";function h(r){try{const e=JSON.parse(r);if(typeof e?.pid=="number"&&typeof e.acquired_at=="number")return e}catch{}return null}function w(r){if(!p(r))return null;try{return h(s(r,"utf8"))}catch{return null}}function O(r){const e=w(r);return e!==null&&l(e.pid)}class k extends Error{holder;constructor(e){super(`another grix-connector daemon (pid ${e.pid}) is already serving this root; yielding`),this.holder=e,this.name="DaemonAlreadyServingError"}}function j(r,e=2e3,n=2){return async c=>{let u="19579";try{const a=f.join(r,"health-port");p(a)&&(u=s(a,"utf8").trim()||u)}catch{}for(let a=0;a<n;a+=1)try{const d=await fetch(`http://127.0.0.1:${u}/healthz`,{signal:AbortSignal.timeout(e)});if(!d.ok)return!1;const o=await d.json();return o.status==="ok"&&o.pid===c.pid}catch{}return!1}}function S(r){const e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}function L(r){const e=typeof r.command_line=="string"&&r.command_line?r.command_line:null;if(e===null)return!0;const n=m(r.pid);return n===null?!0:n===e}function z(r){const e=typeof r.command_line=="string"&&r.command_line?r.command_line:null;if(e===null)return!1;const n=m(r.pid);return n!==null&&n===e}function I(r){try{return i.kill(r,0),!0}catch(e){return e?.code!=="EPERM"}}function v(r){if(r<=0||r===i.pid)return!0;try{i.kill(r,"SIGTERM")}catch(c){return c?.code!=="EPERM"}const e=Date.now()+3e3;for(;Date.now()<e;){if(!l(r))return!0;S(100)}try{i.kill(r,"SIGKILL")}catch{}const n=Date.now()+1e3;for(;Date.now()<n;){if(!l(r))return!0;S(50)}return!l(r)}async function G(r,e,n=2,c={}){await x(f.dirname(r),{recursive:!0});const u={pid:i.pid,acquired_at:Date.now(),root_dir:f.resolve(e),instance_id:_(),command_line:m(i.pid)},a=`${JSON.stringify(u,null,2)}
2
+ `;for(let d=0;d<=n;d+=1)try{const o=g(r,"wx");try{E(o,a)}finally{D(o)}return u}catch(o){if(!(o instanceof Error)||o.code!=="EEXIST")throw o;let t=null;try{t=h(s(r,"utf8"))}catch{}if(t&&l(t.pid)){if(t.pid===i.pid)throw new Error(`daemon already running (pid ${t.pid}, acquired at ${new Date(t.acquired_at).toISOString()})`);if(I(t.pid)&&L(t)){if(c.isHolderServing&&await c.isHolderServing(t))throw new k(t);if(!v(t.pid))throw new Error(`\u65E0\u6CD5\u7EC8\u6B62\u8001\u8FDB\u7A0B (pid ${t.pid})\uFF0C\u8BF7\u624B\u52A8\u5904\u7406`)}}try{y(r)}catch{}}throw new Error("failed to acquire daemon lock after retries")}async function J(r){const e=w(r);if(e&&e.pid===i.pid)try{y(r)}catch{}}export{k as DaemonAlreadyServingError,G as acquireDaemonLock,j as createHealthzHolderProbe,O as isDaemonLocked,z as isLockHolderIdentityVerified,L as isLockHolderSameProcess,w as readDaemonLock,J as releaseDaemonLock};
@@ -0,0 +1,2 @@
1
+ import{existsSync as o,readFileSync as u,writeFileSync as i}from"node:fs";import l from"node:path";function n(e){return l.join(e,"duplicate-daemon.json")}function a(e){const r=n(e);if(!o(r))return null;try{const t=JSON.parse(u(r,"utf-8"));return typeof t?.occurrences=="number"?t:null}catch{return null}}function f(e,r){const t=a(e),c={...r,occurrences:(t?.occurrences??0)+1,last_yield_at:new Date().toISOString()};try{i(n(e),`${JSON.stringify(c,null,2)}
2
+ `,"utf-8")}catch{}}export{a as readDuplicateDaemonRecord,f as recordDuplicateDaemon,n as resolveDuplicateDaemonRecordPath};