grix-connector 4.17.0 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/agy/agy-adapter.js +8 -8
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/opencode/opencode-adapter.js +1 -1
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.17.0.tgz → grix-dsh-bridge-4.18.0.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -1
- package/dist/core/util/cli-probe.js +2 -2
- package/dist/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{spawn as F}from"node:child_process";import{randomUUID as
|
|
2
|
-
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P($(),".gemini","skills"),d=z(r);d.length>0&&a.info(c,`Synced connector skills to ${r}: [${d.join(", ")}]`)}catch(t){a.warn(c,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,
|
|
1
|
+
import{spawn as F}from"node:child_process";import{randomUUID as N}from"node:crypto";import{EventEmitter as L}from"node:events";import{existsSync as b,readFileSync as I,statSync as B,mkdirSync as G,writeFileSync as K,realpathSync as Y}from"node:fs";import{homedir as $}from"node:os";import{join as P,dirname as V,resolve as Q}from"node:path";import{fileURLToPath as U}from"node:url";import{log as a}from"../../core/log/index.js";import{killProcessGroup as w}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as H,pruneLegacyMcpServerEntries as J}from"../../core/mcp/server-name.js";import{syncDefaultSkillsToDir as z}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{getAgyModelCatalog as Z,resolveAgyModelFlag as tt}from"./model-list.js";import{isGrixInternalToolName as k}from"../../core/mcp/tools.js";import{AgyStreamParser as et}from"./stream-parser.js";const c="agy-adapter";function it(g){return/^API error \(attempt \d+\):/.test(g.trim())}function st(g,t,e,s){return g===0&&it(t)&&(e.trim().length>0||s)}function nt(g){try{return process.kill(g,0),!0}catch(t){return t.code==="EPERM"}}function rt(g){try{return Y(g)}catch{return g}}const O=P($(),".gemini","antigravity-cli","log"),ot="CLI store manager shutting down",at=5e3,_=15e3,j=480*1e3,ct=["fetchAvailableModels","loadCodeAssist","token refreshed","ListExperiments","experiment refresh","Experiments refreshed","Reloading system slash commands","Slash commands unchanged","doRefreshQuota"];function lt(g,t){const e=Number(process.env[g]);return Number.isFinite(e)&&e>0?e:t}const dt="30m",D=P($(),".gemini","antigravity-cli","cache","last_conversations.json"),ht=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001agent_id\uFF08\u5F53\u524D Agent\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u5F53\u524D Turn \u7684\u6B63\u5F0F\u56DE\u7B54\u76F4\u63A5\u4F5C\u4E3A\u6700\u7EC8\u54CD\u5E94\u8F93\u51FA\uFF0C\u7531\u8FDE\u63A5\u5668\u8BFB\u53D6\u5E76\u53D1\u9001\u7ED9\u7528\u6237\u3002","\u4E0D\u8981\u4F7F\u7528 grix_message_send \u56DE\u7B54\u5F53\u524D\u5165\u7AD9\u4E8B\u4EF6\uFF1B\u5B83\u4EC5\u7528\u4E8E\u4E0E\u672C\u6B21\u56DE\u7B54\u65E0\u5173\u7684\u4E3B\u52A8\u6D88\u606F\u3002","\u8FDB\u7A0B\u5B89\u5168\uFF1A\u542F\u52A8\u4E34\u65F6\u6216\u6F14\u793A\u670D\u52A1\u65F6\u5FC5\u987B\u8BB0\u5F55\u5176 PID\uFF0C\u505C\u6B62\u65F6\u53EA\u7EC8\u6B62\u5DF2\u786E\u8BA4\u5C5E\u4E8E\u672C\u4EFB\u52A1\u7684\u8BE5 PID \u6216\u5176\u4E13\u5C5E\u8FDB\u7A0B\u7EC4\u3002","\u7981\u6B62\u4F7F\u7528 `pkill`\u3001`killall` \u6216\u5176\u4ED6\u6309\u540D\u79F0/\u547D\u4EE4\u884C\u6A21\u5F0F\u6279\u91CF\u6740\u8FDB\u7A0B\u7684\u547D\u4EE4\uFF1B\u7EDD\u4E0D\u80FD\u7EC8\u6B62 Grix MCP\u3001\u5F53\u524D agy \u6216\u5176\u7236\u8FDB\u7A0B\u3001connector \u6216\u5176\u4ED6\u65E0\u5173\u8FDB\u7A0B\u3002"].join(""),ut=new Set(["send_msg","grix_reply"]),ft=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);function W(g){try{return structuredClone(g)}catch{return}}class bt extends L{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;auditCaptures=new Map;completedAuditBoundaries=new Map;watchdogPollTimer=null;watchdogGraceTimer=null;watchdogKilledActiveProcess=!1;lastActivityAt=0;watchLogOffset=0;inactivityTimeoutMs=j;inactivityWarned=!1;inFlightToolName=null;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];systemInstructionInjectedSessions=new Set;identityInjectedSessions=new Set;constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),a.info(c,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(o,h,l,u)=>this.handleToolInvoke(o,h,u)),await this.internalApi.start(0),a.info(c,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=P($(),".gemini","config","mcp_config.json");G(V(e),{recursive:!0});let s={};try{b(e)&&(s=JSON.parse(I(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};J(i,this.internalApi.url),i[t.name]={command:t.command,args:t.args},s.mcpServers=i,K(e,`${JSON.stringify(s,null,2)}
|
|
2
|
+
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P($(),".gemini","skills"),d=z(r);d.length>0&&a.info(c,`Synced connector skills to ${r}: [${d.join(", ")}]`)}catch(t){a.warn(c,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){this.touchActivity();let i=e;ft.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const r=this.activeEventId?this.auditCaptures.get(this.activeEventId):void 0,d=r?{sequence:r.toolInvocations.length,observedAt:new Date().toISOString(),action:t,params:W(i)}:void 0;r&&d&&r.toolInvocations.push(d);try{const o=await this.callbacks.agentInvoke(t,i,s);return d&&(d.completedAt=new Date().toISOString(),d.result=W(o)),ut.has(t)&&this.activeEventId&&this.activeEventSessionId&&i.session_id===this.activeEventSessionId&&(this.activeEventSentViaTool=!0),o}catch(o){throw d&&(d.completedAt=new Date().toISOString(),d.error=o instanceof Error?o.message:String(o)),o}}async stop(){if(!this.stopped){if(this.stopped=!0,this.alive=!1,this.stopTurnWatchdog(),this.inFlightToolName=null,this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,this.activeProcess){try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId)try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}if(this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),a.info(c,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??N()}async resumeSession(t,e){}async destroySession(t){this.systemInstructionInjectedSessions.delete(t),this.identityInjectedSessions.delete(t)}onAgentProfileChanged(){this.identityInjectedSessions.clear()}sendPrompt(t){const e=new L;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;a.info(c,`cancelCurrentRun: killing process group for event ${t}`);try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","restarted by user"),this.clearActiveEvent(t),this.drainQueue()}deliverInboundEvent(t){if(!this.stopped){if(this.completedEventIds.has(t.event_id)){a.debug(c,`Skipping duplicate event: ${t.event_id}`);return}if(this.callbacks.sendEventAck(t.event_id,t.session_id),this.activeEventId){a.info(c,`Queuing event ${t.event_id} (active: ${this.activeEventId})`),this.eventQueue.push(t);return}this.processEvent(t)}}deliverStopEvent(t,e){if(this.activeEventId===t&&this.activeProcess){a.info(c,`Stopping event ${t}`);try{w(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActiveEvent(t),this.drainQueue()}}setPermissionHandler(){}async ping(t){if(this.stopped||!this.alive||!this.internalApi)return!1;const e=this.activeProcess;if(!e)return!0;if(!e.pid||!nt(e.pid))return!1;const s=!!(e.stdout&&!e.stdout.destroyed),i=!!(e.stderr&&!e.stderr.destroyed);return s&&i}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return X(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}snapshotAuditBoundary(t){const e=this.auditCaptures.get(t);if(!e)return;this.auditCaptures.delete(t);let s;if(e.logPath)try{s=B(e.logPath).size}catch{}const i=this.sessionConversationMap.get(e.sessionId)??e.conversationId;this.completedAuditBoundaries.set(t,{adapterType:"agy",...i?{providerSessionId:i}:{},...e.cwd?{cwd:e.cwd}:{},...e.logPath?{transcriptPath:e.logPath,transcriptStartOffset:e.logStartOffset??0,transcriptEndOffset:s??0}:{},agyEvidence:{...e.prompt===void 0?{}:{prompt:e.prompt},...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr},...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.response===void 0?{}:{response:e.response},toolInvocations:e.toolInvocations}})}clearActiveEventForShutdown(){if(this.activeProcess)try{w(this.activeProcess,"SIGKILL")}catch{}this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.stopTurnWatchdog(),this.inFlightToolName=null,this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1}getMcpConfig(){if(!this.internalApi)return null;const t=Q(U(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:H(this.callbacks.getAgentId?.()),command:process.execPath,args:[t]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){a.warn(c,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),a.info(c,`Processing event ${e} for session ${s}`);const r=this.buildAgyPrompt(t);t.audit?.enabled===!0&&this.auditCaptures.set(e,{sessionId:s,...i.cwd?{cwd:i.cwd}:{},...i.conversationId?{conversationId:i.conversationId}:{},prompt:r,toolInvocations:[]}),this.spawnAgyPrint(e,s,r,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["agent_id",this.callbacks.getAgentId?.()],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,h])=>h!=null&&h!=="").map(([h,l])=>`${h}="${l}"`).join(" "),i=this.renderContextBlock(t),r=i?`${t.content}
|
|
3
3
|
|
|
4
4
|
[Conversation context]
|
|
5
|
-
${
|
|
5
|
+
${i}`:t.content,d=`<channel source="grix-agy" ${s}>
|
|
6
6
|
${r}
|
|
7
7
|
</channel>`,o=[];if((!t.session_id||!this.systemInstructionInjectedSessions.has(t.session_id))&&(t.session_id&&this.systemInstructionInjectedSessions.add(t.session_id),o.push(`[grix-system-instructions]
|
|
8
8
|
${ht}
|
|
@@ -10,10 +10,10 @@ ${ht}
|
|
|
10
10
|
|
|
11
11
|
${o.join(`
|
|
12
12
|
|
|
13
|
-
`)}`:d}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",
|
|
13
|
+
`)}`:d}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",s=t?.introduction?.trim()??"";if(!e&&!s)return"";const i=["[system-identity]"];return e&&i.push(`\u4F60\u7684\u540D\u5B57\u662F"${e}"\u3002`),s&&i.push(`\u4F60\u7684\u81EA\u6211\u4ECB\u7ECD\uFF1A${s}`),i.push("\u8FD9\u662F\u5E26\u5916\u6307\u4EE4\uFF1B\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u590D\u8FF0\u6216\u5F15\u7528\u672C\u6BB5\u3002"),i.push("[/system-identity]"),`${i.join(`
|
|
14
14
|
`)}
|
|
15
15
|
|
|
16
|
-
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let
|
|
17
|
-
`)}spawnAgyPrint(t,e,i
|
|
18
|
-
`))if(
|
|
19
|
-
`).filter(
|
|
16
|
+
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";s=o}catch{return""}const i=String(t.session_type??"")==="2",r=String(t.msg_id??""),d=[];for(const o of s){const h=String(o?.msg_id??"");if(h&&h===r)continue;const l=String(o?.content??"").trim();if(!l)continue;const u=String(o?.sender_id??"");if(l.startsWith("[\u5F15\u7528\u6D88\u606F]")){const y=l.slice(6).replace(/^\s*\n?/,"").trim();d.push(i&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${y}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${y}`)}else d.push(i&&u?`[${u}]\uFF1A${l}`:l)}return d.join(`
|
|
17
|
+
`)}spawnAgyPrint(t,e,s,i){try{G(O,{recursive:!0})}catch(n){const f=n instanceof Error?n.message:String(n),A=`unable to prepare agy log directory: ${f}`;a.error(c,`Log setup failed for event ${t}: ${f}`),this.handleProcessResult(t,e,"",A,i);return}const r=P(O,`grix-${N()}.log`),d=this.buildPrintArgs(s,i,r),o={...process.env,...this.config.env??{},...this.internalApi?{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}:{}};let h="",l,u="",y=!1;const R=new et({onInit:n=>{l=n,this.sessionConversationMap.set(e,n),this.callbacks.persistConversationId(e,n)},onToolStart:(n,f)=>{this.touchActivity();let A=k(n),p=n,v=f;if(n==="call_mcp_tool"){const m=typeof f.ToolName=="string"?f.ToolName:"";(typeof f.ServerName=="string"?f.ServerName:"").startsWith("grix")||k(m)?A=!0:m&&(p=m,v=f.Arguments||f)}if(A)return;this.inFlightToolName=p;const S=JSON.stringify(v??{});this.callbacks.sendToolUse?.(t,e,p,S)},onToolDone:(n,f,A,p)=>{this.touchActivity();let v=k(n),S=n;if(n==="call_mcp_tool"){const m=typeof f.ToolName=="string"?f.ToolName:"";(typeof f.ServerName=="string"?f.ServerName:"").startsWith("grix")||k(m)?v=!0:m&&(S=m)}(this.inFlightToolName===S||this.inFlightToolName===n)&&(this.inFlightToolName=null),!v&&p&&this.callbacks.sendToolResult?.(t,e,S,`(failed: ${p})`)},onTextDelta:n=>{this.touchActivity()},onResult:n=>{this.touchActivity(),this.inFlightToolName=null,y=!0,typeof n.response=="string"&&n.response.trim()&&(h=n.response),n.status==="ERROR"||n.error!==void 0&&n.error!==""?u=n.error?.trim()||`agy turn failed with status ${n.status??"ERROR"}`:u="",n.conversationId&&(l=n.conversationId,this.sessionConversationMap.set(e,n.conversationId),this.callbacks.persistConversationId(e,n.conversationId)),this.handleTurnResultReceived(t)},onLine:n=>{this.touchActivity()}});a.info(c,`Spawning: agy ${d.map(n=>n.includes(" ")?`"${n}"`:n).join(" ")}`);const T=F(this.config.command,d,{cwd:i.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32"});this.activeProcess=T,this.lastActivityAt=Date.now(),this.watchLogOffset=0,this.inactivityWarned=!1,this.inactivityTimeoutMs=lt("GRIX_AGY_INACTIVITY_TIMEOUT_MS",j);const x=[],M=[];T.stdout?.on("data",n=>{x.push(n),R.feed(n),this.touchActivity()}),T.stderr?.on("data",n=>{M.push(n),this.touchActivity()}),T.on("error",n=>{a.error(c,`Process spawn error for event ${t}: ${n.message}`),this.handleProcessResult(t,e,"",`spawn error: ${n.message}`,i)}),T.on("close",n=>{if(a.info(c,`Process exited for event ${t} with code ${n}`),this.activeEventId!==t)return;R.flush(),this.stopTurnWatchdog();const f=Buffer.concat(x).toString("utf-8"),A=Buffer.concat(M).toString("utf-8"),p=h.trim()?h:y?"":f,v=this.auditCaptures.get(t);v&&(v.stdout=f,v.stderr=A,v.exitCode=n);const S=this.watchdogKilledActiveProcess&&n===null;this.watchdogKilledActiveProcess=!1;const m=st(n,u,p,this.activeEventSentViaTool);if(m&&a.warn(c,`Ignoring retried agy attempt error after delivery for event ${t}: ${u}`),S)p.trim()||this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const E=u||this.extractLogError(r);this.handleProcessResult(t,e,p,E,i,l)},300);else if(u&&!m)this.handleProcessResult(t,e,"",u,i,l);else if(n!==0){const E=A.trim()||`process exited with code ${n}`;this.handleProcessResult(t,e,p,E,i,l)}else p.trim()?this.handleProcessResult(t,e,p,"",i,l):this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const E=this.extractLogError(r);this.handleProcessResult(t,e,p,E,i,l)},300)}),T.stdin?.end();const C=this.auditCaptures.get(t);C&&(C.logPath=r,C.logStartOffset=0),this.startTurnWatchdog(t,r)}startTurnWatchdog(t,e){this.stopTurnWatchdog(),this.watchdogPollTimer=setInterval(()=>{if(this.activeEventId!==t||!this.activeProcess){this.stopTurnWatchdog();return}if(this.watchLogHasTurnEndMarker(e)){this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),this.watchdogGraceTimer||(a.warn(c,`Turn end marker logged for event ${t} but process still alive; grace ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after turn end (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{w(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref());return}if(this.scanTurnLogActivity(e),this.inFlightToolName||this.inactivityWarned)return;const s=Date.now()-this.lastActivityAt;if(s<this.inactivityTimeoutMs)return;this.inactivityWarned=!0;const i=Math.max(1,Math.round(s/6e4));a.warn(c,`No activity for ${Math.round(s/1e3)}s on event ${t} (threshold ${Math.round(this.inactivityTimeoutMs/1e3)}s); upstream turn appears stalled, notifying user (process left running)`),this.callbacks.sendStreamChunk(t,this.activeEventSessionId??"",`\u26A0\uFE0F \u672C\u8F6E\u5DF2\u7EA6 ${i} \u5206\u949F\u6CA1\u6709\u4EFB\u4F55\u54CD\u5E94\uFF0C\u4E0A\u6E38\u7591\u4F3C\u6302\u6B7B\u3002\u8FDB\u7A0B\u4ECD\u5728\u8FD0\u884C\uFF08\u4E0A\u6E38\u6062\u590D\u540E\u4F1A\u7EE7\u7EED\uFF09\uFF0C\u4F60\u53EF\u4EE5\u56DE\u590D /stop \u7EC8\u6B62\uFF0C\u6216\u7EE7\u7EED\u7B49\u5F85\uFF0830 \u5206\u949F\u4E0A\u9650\u540E\u5C06\u81EA\u52A8\u5224\u5931\u8D25\uFF09\u3002`,1,!1,`agy-stall-${t}`)},at),this.watchdogPollTimer.unref()}handleTurnResultReceived(t){this.activeEventId!==t||!this.activeProcess||this.watchdogGraceTimer||(this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),a.info(c,`Stream-json result received for event ${t}; grace ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after result event (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{w(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref())}stopTurnWatchdog(){this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),this.watchdogGraceTimer&&(clearTimeout(this.watchdogGraceTimer),this.watchdogGraceTimer=null)}touchActivity(){this.lastActivityAt=Date.now()}scanTurnLogActivity(t){let e;try{e=I(t)}catch{return}if(e.length<=this.watchLogOffset){this.watchLogOffset=e.length;return}const s=e.subarray(this.watchLogOffset).toString("utf-8");this.watchLogOffset=e.length;for(const i of s.split(`
|
|
18
|
+
`))if(i.trim()&&!ct.some(r=>i.includes(r))){a.debug(c,`turn log activity: ${i.slice(0,120)}`),this.touchActivity();return}}watchLogHasTurnEndMarker(t){try{return I(t,"utf-8").includes(ot)}catch{return!1}}buildPrintArgs(t,e,s){const i=["--print-timeout",dt,"--log-file",s],r=e.modelId?tt(e.modelId,Z()):"";return r&&i.push("--model",r),e.cwd&&i.push("--add-dir",e.cwd),i.push("--dangerously-skip-permissions"),e.conversationId&&i.push("--conversation",e.conversationId),i.push("--output-format","stream-json"),i.push("-p",t),i}readAgyConversationId(t){try{if(b(D)){const e=JSON.parse(I(D,"utf-8"));return e[rt(t)]||e[t]||void 0}}catch(e){a.debug(c,`readAgyConversationId: ${e}`)}}extractLogError(t){try{if(!b(t))return a.info(c,`extractLogError: log file not found: ${t}`),"agy completed without output";const e=I(t,"utf-8");if(!e)return a.info(c,`extractLogError: log file is empty: ${t}`),"agy completed without output";const s=e.split(`
|
|
19
|
+
`).filter(i=>i.startsWith("E")).map(i=>{const r=i.indexOf("] ");return r>=0?i.slice(r+2):i}).filter(i=>i.length>0);if(s.length>0){const i=s[s.length-1];return a.info(c,`Extracted error from agy log: ${i.slice(0,120)}`),i.length>500?i.slice(0,500)+"...":i}return"agy completed without output (possible auth or quota issue)"}catch(e){return a.info(c,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,r,d){if(this.activeEventId===t){if(this.inactivityWarned&&this.callbacks.sendStreamChunk(t,e,"",2,!0,`agy-stall-${t}`),i&&!s.trim()){a.error(c,`Event ${t} failed: ${i}`);const o=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota"),h=i.toLowerCase().includes("authentication failed"),l=o?"The agy API quota has been exhausted. Please try again later.":h?"agy authentication failed or timed out. Please check the agy login status and try again.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const o=s.trim();if(o){const l=r.cwd,u=l?this.extractDelta(o,l):o;l&&this.conversationOutputCache.set(l,o);const y=this.auditCaptures.get(t);y&&(y.response=u),u&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,u,1,!0,`agy-${t}`)}const h=d||(r.cwd?this.readAgyConversationId(r.cwd):void 0);h&&h!==r.conversationId&&(this.sessionConversationMap.set(e,h),this.callbacks.persistConversationId(e,h)),this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e){if(this.completedEventIds.add(e),this.completedEventIds.size>1e3){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.snapshotAuditBoundary(e)}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,this.stopTurnWatchdog(),this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(a.info(c,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{bt as AgyAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const
|
|
1
|
+
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
|
|
1
|
+
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(
|
|
1
|
+
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as
|
|
2
|
-
`),"utf8"),{expectPath:a,pidPath:i}}function h(
|
|
1
|
+
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
|
|
2
|
+
`),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(
|
|
1
|
+
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{collapseHostedOpenCodeModels as te,normalizeOCProviderModels as se,preferredHostedOpenCodeProvider as ie}from"./opencode-types.js";import{buildOpencodeConfigContent as ne}from"./opencode-config.js";import{agentIdOf as oe}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as re,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class ae extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const de=200,ce=2e3,le=12e4,he=90*1e3,M=1800*1e3,O=3e4,k=600*1e3,pe="claude_interaction_reply",ue="set_mode",fe="set_model",me="127.0.0.1",ve=0,ge=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],Ie=[{permission:"*",pattern:"*",action:"allow"}],we=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function _(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Ue extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new re;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??me,s=this.options.port??ve,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",o=>this.handleSseEvent(o)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const n=this.getMcpConfig();await this.transport.configureMcp(n.name,[n.command,...n.args??[]]);try{await this.refreshModels()}catch(o){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${o instanceof Error?o.message:String(o)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const r of s)for(const d of se(r.models)){t.push({id:`${r.id}/${d.id}`,displayName:d.name||d.id});const c=d.limit?.context;typeof c=="number"&&c>0&&i.set(`${r.id}/${d.id}`,c)}const n=te(t,ie(this.options.model)),o=new Set(n.map(r=>r.id));for(const r of i.keys())o.has(r)||i.delete(r);n.sort((r,d)=>{const c=r.displayName.toLowerCase().localeCompare(d.displayName.toLowerCase());return c!==0?c:r.id.localeCompare(d.id)}),this.availableModels=n,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${n.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=null)}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),a.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new ae(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e),o=this.activeRun,r=this.runBarrier.then(async()=>{if(o.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,n,o)});o.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===o&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&(this.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,n,o)=>this.callbacks.agentInvoke(t,i,o)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[e]}}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ue)return this.handleSetModeAction(e);if(s===fe)return this.handleSetModelAction(e);if(s===pe){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(a.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){a.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=_(this.options.permissionPolicy);if(s)return s;if(e){const t=_(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const n=this.resolveModeId(e),o=n===v.fullAuto?Ie:we;try{await this.transport.updateSessionPermission(s,o,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${n}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=_(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};const n=this.sessionModes.get(t);this.sessionModes.set(t,i);const o=this.sessions.get(t);if(o?.ocSessionId)try{await this.applySessionPermission(t,o.ocSessionId,o.cwd)}catch(d){throw n?this.sessionModes.set(t,n):this.sessionModes.delete(t),d}const r=o?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:$.map(d=>({...d}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):o}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",n=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((o,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=ne({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(oe(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(n,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,o(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const n=this.options.bindingStore?.getAcpSessionId(e);if(n)try{return await this.transport.getSession(n,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${n} for aibot=${e}`),await this.applySessionPermission(e,n,i,s),n}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${n} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,o.id),a.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),await this.applySessionPermission(e,o.id,i,s),o.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const n=this.getSessionCwd(e),o=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=o,this.activeRun.cwd=n);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(o,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},n,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(n=>n.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const n=this.auditCaptures.get(this.activeRun.eventId);n&&n.push({sequence:n.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const n=e.part,o=e.delta;if(n.type==="text"){const r=o!==void 0?o:n.text;r&&this.acceptAssistantPartText(n.messageID,"text",r)}else n.type==="reasoning"?o&&this.acceptAssistantPartText(n.messageID,"reasoning",o):n.type==="tool"&&this.handleToolPartUpdate(n,o);break}case"message.updated":{if(!this.activeRun)break;const n=e.info;if(this.rememberMessageRole(n),n.role==="assistant"){const o=n;typeof o.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,o.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,o.providerID,o.modelID,o.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:o.providerID,model_id:o.modelID,...r??{}}),o.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(o.error)}`);const d=this.activeRun.ocSessionId;d&&o.sessionID===d&&(o.error?(this.flushTextBuffer(),this.finishRun("failed",P(o.error,o.error.type||"unknown error"))):!e.nativeEvent&&o.time?.completed&&o.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const n=P(e.error);a.error("opencode-adapter",`Session error: ${n}`),this.flushTextBuffer(),this.finishRun("failed",n);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":{const n=this.pendingPermissions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const n=this.pendingQuestions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{a.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:a.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),k);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(n=>{a.warn("opencode-adapter",`Permission response failed: ${n}`),this.onInteractionFailure(n,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(o=>{a.warn("opencode-adapter",`Orphan question reject failed: ${o}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const n=setTimeout(()=>this.onQuestionTimeout(e.id),k);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:n}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(o=>({header:o.header,prompt:o.question,...o.options.length>0?{options:o.options.map(r=>r.label)}:{},...o.multiple!==void 0?{multi_select:o.multiple}:{},...o.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+k});else{const o=e.questions.map(r=>r.question).join(`
|
|
1
|
+
import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{collapseHostedOpenCodeModels as te,normalizeOCProviderModels as se,preferredHostedOpenCodeProvider as ie}from"./opencode-types.js";import{buildOpencodeConfigContent as ne}from"./opencode-config.js";import{agentIdOf as oe}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as re,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class ae extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const de=200,ce=2e3,le=12e4,he=90*1e3,M=1800*1e3,O=3e4,k=600*1e3,pe="claude_interaction_reply",ue="set_mode",fe="set_model",me="127.0.0.1",ve=0,ge=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],Ie=[{permission:"*",pattern:"*",action:"allow"}],we=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function _(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Ue extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new re;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??me,s=this.options.port??ve,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",o=>this.handleSseEvent(o)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const n=this.getMcpConfig();await this.transport.configureMcp(n.name,[n.command,...n.args??[]]);try{await this.refreshModels()}catch(o){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${o instanceof Error?o.message:String(o)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const r of s)for(const d of se(r.models)){t.push({id:`${r.id}/${d.id}`,displayName:d.name||d.id});const c=d.limit?.context;typeof c=="number"&&c>0&&i.set(`${r.id}/${d.id}`,c)}const n=te(t,ie(this.options.model)),o=new Set(n.map(r=>r.id));for(const r of i.keys())o.has(r)||i.delete(r);n.sort((r,d)=>{const c=r.displayName.toLowerCase().localeCompare(d.displayName.toLowerCase());return c!==0?c:r.id.localeCompare(d.id)}),this.availableModels=n,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${n.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=null)}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),a.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new ae(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e),o=this.activeRun,r=this.runBarrier.then(async()=>{if(o.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,n,o)});o.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===o&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&(this.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,n,o)=>this.callbacks.agentInvoke(t,i,o)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[e]}}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ue)return this.handleSetModeAction(e);if(s===fe)return this.handleSetModelAction(e);if(s===pe){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(a.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){a.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=_(this.options.permissionPolicy);if(s)return s;if(e){const t=_(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const n=this.resolveModeId(e),o=n===v.fullAuto?Ie:we;try{await this.transport.updateSessionPermission(s,o,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${n}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=_(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};const n=this.sessionModes.get(t);this.sessionModes.set(t,i);const o=this.sessions.get(t);if(o?.ocSessionId)try{await this.applySessionPermission(t,o.ocSessionId,o.cwd)}catch(d){throw n?this.sessionModes.set(t,n):this.sessionModes.delete(t),d}const r=o?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:$.map(d=>({...d}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):o}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",n=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((o,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=ne({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(oe(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(n,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,o(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const n=this.options.bindingStore?.getAcpSessionId(e);if(n)try{return await this.transport.getSession(n,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${n} for aibot=${e}`),await this.applySessionPermission(e,n,i,s),n}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${n} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,o.id),a.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),await this.applySessionPermission(e,o.id,i,s),o.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const n=this.getSessionCwd(e),o=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=o,this.activeRun.cwd=n);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(o,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},n,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(n=>n.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer()),this.activeRun){const n=this.auditCaptures.get(this.activeRun.eventId);n&&n.push({sequence:n.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const n=e.part,o=e.delta;if(n.type==="text"){const r=o!==void 0?o:n.text;r&&this.acceptAssistantPartText(n.messageID,"text",r)}else n.type==="reasoning"?o&&this.acceptAssistantPartText(n.messageID,"reasoning",o):n.type==="tool"&&this.handleToolPartUpdate(n,o);break}case"message.updated":{if(!this.activeRun)break;const n=e.info;if(this.rememberMessageRole(n),n.role==="assistant"){const o=n;typeof o.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,o.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,o.providerID,o.modelID,o.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:o.providerID,model_id:o.modelID,...r??{}}),o.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(o.error)}`);const d=this.activeRun.ocSessionId;d&&o.sessionID===d&&(o.error?(this.flushTextBuffer(),this.finishRun("failed",P(o.error,o.error.type||"unknown error"))):!e.nativeEvent&&o.time?.completed&&o.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const n=P(e.error);a.error("opencode-adapter",`Session error: ${n}`),this.flushTextBuffer(),this.finishRun("failed",n);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":{const n=this.pendingPermissions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const n=this.pendingQuestions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{a.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:a.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),k);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(n=>{a.warn("opencode-adapter",`Permission response failed: ${n}`),this.onInteractionFailure(n,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(o=>{a.warn("opencode-adapter",`Orphan question reject failed: ${o}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const n=setTimeout(()=>this.onQuestionTimeout(e.id),k);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:n}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(o=>({header:o.header,prompt:o.question,...o.options.length>0?{options:o.options.map(r=>r.label)}:{},...o.multiple!==void 0?{multi_select:o.multiple}:{},...o.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+k});else{const o=e.questions.map(r=>r.question).join(`
|
|
2
2
|
`);this.callbacks.sendRunError(s,t,`Agent asks: ${o}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},n=String(i.type??""),o=(c,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),c().then(()=>{this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(p=>{a.warn("opencode-adapter",`Question response failed: ${p}`),this.onInteractionFailure(p,t.eventId)}),{delivered:!0,result:l});if(n==="action"){const c=String(i.value??"");if(c==="cancel"||c==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let r=null;if(Array.isArray(e.answers))r=e.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(n==="text"){const c=String(i.value??"");c&&(r=t.questions.map((l,p)=>p===0?[c]:[]))}else if(n==="map"){const c=Array.isArray(i.entries)?i.entries:[];r=t.questions.map((l,p)=>{const u=c.find(h=>h.key===l.header||h.key===String(p+1));return u&&u.value?[u.value]:[]}),r.every(l=>l.length===0)&&c.length>0&&(r=t.questions.map((l,p)=>{const u=c[p]?.value;return u?[String(u)]:[]}))}if(!r||r.every(c=>c.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const d=r;return o(()=>this.transport.replyQuestion(t.requestId,d,t.cwd),{request_id:s,resolution:"answer"})}onInteractionFailure(e,s){this.activeRun?.eventId===s&&(this.transport.protocol==="v2"?this.finishRun("failed",e instanceof Error?e.message:"OpenCode interaction failed"):this.resetIdleTimer())}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}cancelRun(e){if(e.controller?.abort(),e.cancelTask||this.stopped)return;const s=(e.promptTask??Promise.resolve()).catch(()=>{}).then(async()=>{!this.stopped&&e.ocSessionId&&await this.transport.abortSession(e.ocSessionId,e.cwd)});e.cancelTask=s,this.runBarrier=s,s.catch(t=>{if(this.stopped)return;this.cancellationFailure=new Error("OpenCode cancellation not confirmed; replace adapter before sending more prompts"),a.warn("opencode-adapter",`OpenCode cancellation not confirmed: ${t}`),this.alive=!1,(this.activeRun?.promptTask??Promise.resolve()).catch(()=>{}).then(()=>this.stop()).then(()=>this.emit("exit",-1)).catch(()=>{})})}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null,controller:new AbortController},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(e==="responded"?t.controller?.abort():this.cancelRun(t),this.completedEvents.add(t.eventId),this.completedEvents.size>ge){const d=[...this.completedEvents].slice(-500);this.completedEvents=new Set(d)}this.snapshotAuditBoundary(t),t.flushTimer&&clearTimeout(t.flushTimer),t.flushTimer=null,this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,n=t.clientMsgId,o=e==="failed"&&!!s;o&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(d=>{const c=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${d instanceof Error?d.message:String(d)}`:s,p=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,c,l,void 0,p)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,n),this.callbacks.sendEventResult(t.eventId,e,s,void 0,o))};if(t.textBuffer){this.stopTextFlush();for(const d of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,d,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun&&this.cancelRun(this.activeRun),this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ce){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},de))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!D(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<he)return this.livenessExtendStartAt=s,a.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),s-n>M?(a.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(a.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.activeRun;this.idleTimer=setTimeout(()=>{if(this.stopped||this.activeRun!==e)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){a.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const s=this.process?.pid,i=!!(this.alive&&s&&D(s))?`liveness budget exhausted after ${M/6e4}min`:"process not alive";a.error("opencode-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${i}`),this.clearRun()),this.emit("exit",-1)},le)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
|
|
3
3
|
`);s=`${s}
|
|
4
4
|
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
3
|
+
"bridgeVersion": "4.18.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.18.0.tgz",
|
|
5
5
|
"size": 24211,
|
|
6
6
|
"unpackedSize": 96662,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "94f2664cc9d3d5bf89f2630c712fcd85a3009603",
|
|
8
|
+
"integrity": "sha512-vRoYsrouOKlIWlHAGKMGCE9UIS+P2t4sNULXltaPRd3K8R4dpZA0uKuAcABtFt7ptezD1Th9I03cyyNDw1LxTg=="
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sharedProviderQuotaService as _,detectProviderFromModel as m,normalizeProviderId as g,readPiProviderSettings as x,readOpenCodeProviderSettings as q,isOpenaiCodexProviderName as O,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as $,resolveKimiProviderSettings as R,providerQuotaToRateLimits as H,providerQuotaToCodexRateLimits as C,providerQuotaToolbarExtras as E,resolveOpenCodeConsoleQuotaKey as b,OPENCODE_CONSOLE_ORIGIN as K}from"../core/provider-quota/index.js";import{queryKiroQuota as w}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as D}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as M,resolveDshHome as U,readDshCredentials as I}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as N}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as k}from"../adapter/codex/codex-trust.js";import{agentIdOf as A}from"../adapter/shared/native-provider-config.js";import{log as p}from"../core/log/index.js";const T=30*1e3,L=10*1e3,X=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],Z=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function h(e,i){if(i?.disabled||i?.providerId==="openai_codex")return null;let o=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,n=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){const r=U(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);let a={};try{a=await I(r)}catch(t){p.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${t instanceof Error?t.message:String(t)}`)}const c=t=>{const u=a[t];return typeof u=="string"?u.trim():""};if(g(i?.providerId)==="opencode_go"){const t=b({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN??e.config.agent.env?.OPENCODE_GO_API_KEY,providerApiKey:c("OPENCODE_GO_API_KEY")||c("OPENCODE_API_KEY")||n});return t?{baseUrl:K,apiKey:t,providerId:"opencode_go"}:null}if(n??=e.config.agent.env?.DEEPSEEK_API_KEY,o??=e.config.agent.env?.DEEPSEEK_BASE_URL,!n){const t=c("DEEPSEEK_API_KEY");t&&(n=t,o??=c("DEEPSEEK_BASE_URL")||"https://api.deepseek.com",p.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}o??=n?"https://api.deepseek.com":void 0}if((!o||!n)&&(e.config.adapterType??"acp")==="claude"){const r=N();o||(o=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),n||(n=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!o||!n)&&(e.config.adapterType??"acp")==="codex"){const r=k();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await R();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="pi"){const r=x(i,e.config.agent.env?.PI_CODING_AGENT_DIR);!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="opencode"){const r=q(i,void 0,A(e.config.agent.command||"opencode")||"opencode");!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((e.config.adapterType??"acp")==="opencode"){const r=g(i?.providerId);if(!r||r==="opencode_go"){const a=b({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN,providerApiKey:n,vendor:A(e.config.agent.command||"opencode")||"opencode"});if(a)return{baseUrl:K,apiKey:a,providerId:"opencode_go"}}}if(!o||!n)return null;const d=g(i?.providerId)??m(i?.model)?.id??g(e.config.agent.provider?.providerId)??m(e.config.agent.provider?.model)?.id;return{baseUrl:o,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:n,...d?{providerId:d}:{}}}async function ee(e,i=!1,o){if(e.config.aibot.clientType==="kiro"){if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await w();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",p.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return p.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!i&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await D({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),p.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return p.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(o?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return p.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const n=await e.resolveProviderQuotaSource(o);if(!n)return null;const d=_.cacheKey(n);if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===d)return e.cachedProviderQuota;try{const r=await _.query(n,{fresh:i}),a=r.quota;return e.cachedProviderQuota=a,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,p.info(e.name,`[provider-quota] queried: provider=${a.provider} success=${a.success}`+(a.tiers.length>0?` tiers=${a.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(a.balance?` balance=${a.balance.remaining} ${a.balance.unit}`:"")+(a.error?` error=${a.error}`:"")),a}catch(r){return p.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function re(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},T),p.info(e.name,`[provider-quota-timer] started (interval=${T}ms)`))}function ie(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,p.info(e.name,"[provider-quota-timer] stopped"))}async function ae(e,i=!1){try{let o;if(e.config.aibot.clientType==="kiro")o=await w(),e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const n=[...e.sessionBindings.entries()].filter(([d,r])=>!!r&&e.sessionProviderHints.has(d));if(n.length>0&&await Promise.all(n.map(([d,r])=>e.refreshProviderQuotaForSession(d,r,i))),n.length===e.sessionBindings.size&&n.length>0)return;o=await e.maybeQueryProviderQuota(i)}o?.success&&e.pushProviderQuotaToBindings(o,e.sessionProviderHints.size>0)}catch{}}function oe(e,i,o=!1){const n=(e.config.adapterType??"acp")==="claude"&&i.provider==="grix",d=e.providerQuotaToRateLimits(i);for(const[r,a]of e.sessionBindings.entries()){if(!a||o&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const u=e.pool.getSlot(r)?.adapter;if(u instanceof M){u.updateProviderQuotaSnapshot(i);continue}}const c={provider_quota:i};n?c.rate_limits=null:d&&(c.rate_limits=d),Object.assign(c,E(i));const t=e.cachedAcpContextWindow;t&&("usedPercentage"in t?c.context_window={usedPercentage:t.usedPercentage,remainingPercentage:100-t.usedPercentage}:c.context_window=t),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:a,meta:c})}}function ne(e,i,o="standard",n=e.cachedProviderQuota,d=e.cachedProviderQuotaSampledAtMs){const r={...i??{}};if(!n?.success||(r.provider_quota||(r.provider_quota=n),r.rate_limits))return r;if(o==="codex"){const t=C(n,d??Date.now());return t&&(r.rate_limits=t.rateLimits,r.rate_limit_primary_percent=t.primaryPercent,r.rate_limit_secondary_percent=t.secondaryPercent,r.rate_limit_primary_window_min=t.primaryWindowMin,r.rate_limit_secondary_window_min=t.secondaryWindowMin),r}const a=H(n,d??Date.now());a&&(r.rate_limits=a);const c=E(n);return c.credits&&r.credits===void 0&&(r.credits=c.credits),c.extra_limits&&r.extra_limits===void 0&&(r.extra_limits=c.extra_limits),r}function te(e,i,o,n){let d=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,a=!1;if(o){const t=typeof i?.model_provider=="string"?i.model_provider:typeof i?.provider_id=="string"?i.provider_id:void 0,u=typeof i?.model_id=="string"?i.model_id:void 0,v=g(t)??m(t)?.id??m(u)?.id??(O(t)?"openai_codex":null);if(v||u){const s=t?.trim().toLowerCase()??"",l=s==="grix"||s.startsWith("grix-"),P={...v?{providerId:v}:{},...u?{model:u}:{},...!!t&&!l&&!v?{disabled:!0}:{}},y=e.sessionProviderHints.get(o),Q=y?.providerId!==P.providerId||y?.model!==P.model||y?.disabled!==P.disabled;e.sessionProviderHints.set(o,P),e.sessionProviderMeta.set(o,{...i??{}}),Q&&e.sessionProviderQuotas.delete(o),(Q||!e.sessionProviderQuotas.has(o))&&n&&e.refreshProviderQuotaForSession(o,n,!1)}const f=e.sessionProviderQuotas.get(o);a=e.sessionProviderHints.has(o),a&&(d=null,r=null),f&&(d=f.quota,r=f.sampledAt)}const c=e.enrichProviderQuotaMeta(i,"standard",d,r);return a&&(c.provider_quota||(c.provider_quota=null),c.rate_limits||(c.rate_limits=null)),Object.keys(c).length>0?{meta:c}:{}}async function de(e,i,o,n){const d=e.sessionProviderHints.get(i);if(!d)return;if(d.disabled){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=hint_disabled providerId=${d.providerId??""} model=${d.model??""}`);return}const r=`${d.providerId??""}|${d.model??""}|false`;try{let a,c,t;if(d.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(i);if(!n&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))a=s.quota,c=s.sampledAt,t=s.cacheKey;else{const l=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);a=l.quota,c=Date.now(),t=$(l.accountKey)}}else{const s=await e.resolveProviderQuotaSource(d);if(!s){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=no_source providerId=${d.providerId??""} model=${d.model??""}`);return}const l=await _.query(s,{fresh:n});a=l.quota,c=l.sampledAt,t=l.cacheKey}const u=e.sessionProviderHints.get(i);if(`${u?.providerId??""}|${u?.model??""}|${u?.disabled===!0}`!==r)return;if(p.info(e.name,`[provider-quota] queried: provider=${a.provider} success=${a.success}`+(a.tiers.length>0?` tiers=${a.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(a.balance?` balance=${a.balance.remaining} ${a.balance.unit}`:"")+(a.error?` error=${a.error}`:"")+` session=${i}`),!a.success){const s=e.sessionProviderQuotas.get(i);(!s?.quota.success||s.cacheKey!==t)&&e.sessionProviderQuotas.delete(i);return}e.sessionProviderQuotas.set(i,{quota:a,sampledAt:c,cacheKey:t});const f=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(i),"standard",a,c);e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:o,meta:f})}catch(a){p.warn(e.name,`[provider-quota] session query failed: session=${i} ${a instanceof Error?a.message:String(a)}`)}}function ce(e,i,o,n){const d=o.trim();if(!i||!d)return;const r=n?.trim()||void 0,a=`${i}|${r??""}|${d}`,c=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===a&&c-e.lastModelSwitchQuotaRefresh.at<L||(e.lastModelSwitchQuotaRefresh={key:a,at:c},e.doRefreshQuotaAfterModelSwitch(i,d,r).catch(t=>{p.warn(e.name,`[provider-quota] model-switch refresh failed: session=${i} model=${d} ${t instanceof Error?t.message:String(t)}`)}))}async function se(e,i,o,n){const d=e.sessionProviderHints.get(i);if(d||n){const a=n??m(o)?.id??d?.providerId,c={...a?{providerId:a}:{},model:o,...d?.disabled?{disabled:!0}:{}},t=d?.providerId!==c.providerId||d?.model!==c.model||d?.disabled!==c.disabled;e.sessionProviderHints.set(i,c),t&&e.sessionProviderQuotas.delete(i);const u=e.sessionBindings.get(i)??e.bindingStore.get(i)?.cwd??"";(t||!e.sessionProviderQuotas.has(i))&&u&&await e.refreshProviderQuotaForSession(i,u,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:o});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{Z as PROVIDER_QUOTA_HOST_FIELDS,X as PROVIDER_QUOTA_HOST_METHODS,se as doRefreshQuotaAfterModelSwitch,ne as enrichProviderQuotaMeta,ee as maybeQueryProviderQuota,te as providerQuotaMetaPayload,oe as pushProviderQuotaToBindings,ae as refreshAndPushProviderQuota,de as refreshProviderQuotaForSession,ce as refreshQuotaAfterModelSwitch,h as resolveProviderQuotaSource,re as startProviderQuotaTimer,ie as stopProviderQuotaTimer};
|
|
1
|
+
import{sharedProviderQuotaService as _,detectProviderFromModel as g,normalizeProviderId as v,readPiProviderSettings as T,readOpenCodeProviderSettings as q,isOpenaiCodexProviderName as x,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as $,resolveKimiProviderSettings as C,providerQuotaToRateLimits as R,providerQuotaToCodexRateLimits as D,providerQuotaToolbarExtras as K,resolveOpenCodeConsoleQuotaKey as O,resolvePiOpenCodeConsoleQuotaKey as H,OPENCODE_CONSOLE_ORIGIN as Q}from"../core/provider-quota/index.js";import{queryKiroQuota as A}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as I}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as N,resolveDshHome as M,readDshCredentials as U}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as k}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as L}from"../adapter/codex/codex-trust.js";import{agentIdOf as b}from"../adapter/shared/native-provider-config.js";import{log as p}from"../core/log/index.js";const w=30*1e3,B=10*1e3,Z=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],h=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function ee(e,i){if(i?.disabled||i?.providerId==="openai_codex")return null;let n=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,a=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){const r=M(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);let o={};try{o=await U(r)}catch(t){p.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${t instanceof Error?t.message:String(t)}`)}const c=t=>{const u=o[t];return typeof u=="string"?u.trim():""};if(v(i?.providerId)==="opencode_go"){const t=O({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN??e.config.agent.env?.OPENCODE_GO_API_KEY,providerApiKey:c("OPENCODE_GO_API_KEY")||c("OPENCODE_API_KEY")||a});return t?{baseUrl:Q,apiKey:t,providerId:"opencode_go"}:null}if(a??=e.config.agent.env?.DEEPSEEK_API_KEY,n??=e.config.agent.env?.DEEPSEEK_BASE_URL,!a){const t=c("DEEPSEEK_API_KEY");t&&(a=t,n??=c("DEEPSEEK_BASE_URL")||"https://api.deepseek.com",p.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}n??=a?"https://api.deepseek.com":void 0}if((!n||!a)&&(e.config.adapterType??"acp")==="claude"){const r=k();n||(n=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),a||(a=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!n||!a)&&(e.config.adapterType??"acp")==="codex"){const r=L();!n&&r.baseUrl&&(n=r.baseUrl),!a&&r.apiKey&&(a=r.apiKey)}if((!n||!a)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await C();!n&&r.baseUrl&&(n=r.baseUrl),!a&&r.apiKey&&(a=r.apiKey)}if((!n||!a)&&(e.config.adapterType??"acp")==="pi"){const r=T(i,e.config.agent.env?.PI_CODING_AGENT_DIR);!n&&r.baseUrl&&(n=r.baseUrl),!a&&r.apiKey&&(a=r.apiKey)}if((!n||!a)&&(e.config.adapterType??"acp")==="opencode"){const r=q(i,void 0,b(e.config.agent.command||"opencode")||"opencode");!n&&r.baseUrl&&(n=r.baseUrl),!a&&r.apiKey&&(a=r.apiKey)}if((e.config.adapterType??"acp")==="pi"&&v(i?.providerId)==="opencode_go"){const r=H({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN??e.config.agent.env?.OPENCODE_GO_API_KEY??e.config.agent.env?.OPENCODE_API_KEY??process.env.OPENCODE_GO_API_KEY??process.env.OPENCODE_API_KEY,providerApiKey:a,piHome:e.config.agent.env?.PI_CODING_AGENT_DIR});if(r)return{baseUrl:Q,apiKey:r,providerId:"opencode_go"}}if((e.config.adapterType??"acp")==="opencode"){const r=v(i?.providerId);if(!r||r==="opencode_go"){const o=O({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN,providerApiKey:a,vendor:b(e.config.agent.command||"opencode")||"opencode"});if(o)return{baseUrl:Q,apiKey:o,providerId:"opencode_go"}}}if(!n||!a)return null;const d=v(i?.providerId)??g(i?.model)?.id??v(e.config.agent.provider?.providerId)??g(e.config.agent.provider?.model)?.id;return{baseUrl:n,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:a,...d?{providerId:d}:{}}}async function re(e,i=!1,n){if(e.config.aibot.clientType==="kiro"){if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await A();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",p.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return p.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!i&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await I({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),p.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return p.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(n?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return p.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const a=await e.resolveProviderQuotaSource(n);if(!a)return null;const d=_.cacheKey(a);if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===d)return e.cachedProviderQuota;try{const r=await _.query(a,{fresh:i}),o=r.quota;return e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,p.info(e.name,`[provider-quota] queried: provider=${o.provider} success=${o.success}`+(o.tiers.length>0?` tiers=${o.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.error}`:"")),o}catch(r){return p.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function ie(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},w),p.info(e.name,`[provider-quota-timer] started (interval=${w}ms)`))}function oe(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,p.info(e.name,"[provider-quota-timer] stopped"))}async function ae(e,i=!1){try{let n;if(e.config.aibot.clientType==="kiro")n=await A(),e.cachedProviderQuota=n,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const a=[...e.sessionBindings.entries()].filter(([d,r])=>!!r&&e.sessionProviderHints.has(d));if(a.length>0&&await Promise.all(a.map(([d,r])=>e.refreshProviderQuotaForSession(d,r,i))),a.length===e.sessionBindings.size&&a.length>0)return;n=await e.maybeQueryProviderQuota(i)}n?.success&&e.pushProviderQuotaToBindings(n,e.sessionProviderHints.size>0)}catch{}}function ne(e,i,n=!1){const a=(e.config.adapterType??"acp")==="claude"&&i.provider==="grix",d=e.providerQuotaToRateLimits(i);for(const[r,o]of e.sessionBindings.entries()){if(!o||n&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const u=e.pool.getSlot(r)?.adapter;if(u instanceof N){u.updateProviderQuotaSnapshot(i);continue}}const c={provider_quota:i};a?c.rate_limits=null:d&&(c.rate_limits=d),Object.assign(c,K(i));const t=e.cachedAcpContextWindow;t&&("usedPercentage"in t?c.context_window={usedPercentage:t.usedPercentage,remainingPercentage:100-t.usedPercentage}:c.context_window=t),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:o,meta:c})}}function te(e,i,n="standard",a=e.cachedProviderQuota,d=e.cachedProviderQuotaSampledAtMs){const r={...i??{}};if(!a?.success||(r.provider_quota||(r.provider_quota=a),r.rate_limits))return r;if(n==="codex"){const t=D(a,d??Date.now());return t&&(r.rate_limits=t.rateLimits,r.rate_limit_primary_percent=t.primaryPercent,r.rate_limit_secondary_percent=t.secondaryPercent,r.rate_limit_primary_window_min=t.primaryWindowMin,r.rate_limit_secondary_window_min=t.secondaryWindowMin),r}const o=R(a,d??Date.now());o&&(r.rate_limits=o);const c=K(a);return c.credits&&r.credits===void 0&&(r.credits=c.credits),c.extra_limits&&r.extra_limits===void 0&&(r.extra_limits=c.extra_limits),r}function de(e,i,n,a){let d=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,o=!1;if(n){const t=typeof i?.model_provider=="string"?i.model_provider:typeof i?.provider_id=="string"?i.provider_id:void 0,u=typeof i?.model_id=="string"?i.model_id:void 0,f=v(t)??g(t)?.id??g(u)?.id??(x(t)?"openai_codex":null);if(f||u){const s=t?.trim().toLowerCase()??"",l=s==="grix"||s.startsWith("grix-"),P={...f?{providerId:f}:{},...u?{model:u}:{},...!!t&&!l&&!f?{disabled:!0}:{}},y=e.sessionProviderHints.get(n),E=y?.providerId!==P.providerId||y?.model!==P.model||y?.disabled!==P.disabled;e.sessionProviderHints.set(n,P),e.sessionProviderMeta.set(n,{...i??{}}),E&&e.sessionProviderQuotas.delete(n),(E||!e.sessionProviderQuotas.has(n))&&a&&e.refreshProviderQuotaForSession(n,a,!1)}const m=e.sessionProviderQuotas.get(n);o=e.sessionProviderHints.has(n),o&&(d=null,r=null),m&&(d=m.quota,r=m.sampledAt)}const c=e.enrichProviderQuotaMeta(i,"standard",d,r);return o&&(c.provider_quota||(c.provider_quota=null),c.rate_limits||(c.rate_limits=null)),Object.keys(c).length>0?{meta:c}:{}}async function ce(e,i,n,a){const d=e.sessionProviderHints.get(i);if(!d)return;if(d.disabled){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=hint_disabled providerId=${d.providerId??""} model=${d.model??""}`);return}const r=`${d.providerId??""}|${d.model??""}|false`;try{let o,c,t;if(d.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(i);if(!a&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))o=s.quota,c=s.sampledAt,t=s.cacheKey;else{const l=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);o=l.quota,c=Date.now(),t=$(l.accountKey)}}else{const s=await e.resolveProviderQuotaSource(d);if(!s){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=no_source providerId=${d.providerId??""} model=${d.model??""}`);return}const l=await _.query(s,{fresh:a});o=l.quota,c=l.sampledAt,t=l.cacheKey}const u=e.sessionProviderHints.get(i);if(`${u?.providerId??""}|${u?.model??""}|${u?.disabled===!0}`!==r)return;if(p.info(e.name,`[provider-quota] queried: provider=${o.provider} success=${o.success}`+(o.tiers.length>0?` tiers=${o.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.error}`:"")+` session=${i}`),!o.success){const s=e.sessionProviderQuotas.get(i);(!s?.quota.success||s.cacheKey!==t)&&e.sessionProviderQuotas.delete(i);return}e.sessionProviderQuotas.set(i,{quota:o,sampledAt:c,cacheKey:t});const m=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(i),"standard",o,c);e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:n,meta:m})}catch(o){p.warn(e.name,`[provider-quota] session query failed: session=${i} ${o instanceof Error?o.message:String(o)}`)}}function se(e,i,n,a){const d=n.trim();if(!i||!d)return;const r=a?.trim()||void 0,o=`${i}|${r??""}|${d}`,c=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===o&&c-e.lastModelSwitchQuotaRefresh.at<B||(e.lastModelSwitchQuotaRefresh={key:o,at:c},e.doRefreshQuotaAfterModelSwitch(i,d,r).catch(t=>{p.warn(e.name,`[provider-quota] model-switch refresh failed: session=${i} model=${d} ${t instanceof Error?t.message:String(t)}`)}))}async function ue(e,i,n,a){const d=e.sessionProviderHints.get(i);if(d||a){const o=a??g(n)?.id??d?.providerId,c={...o?{providerId:o}:{},model:n,...d?.disabled?{disabled:!0}:{}},t=d?.providerId!==c.providerId||d?.model!==c.model||d?.disabled!==c.disabled;e.sessionProviderHints.set(i,c),t&&e.sessionProviderQuotas.delete(i);const u=e.sessionBindings.get(i)??e.bindingStore.get(i)?.cwd??"";(t||!e.sessionProviderQuotas.has(i))&&u&&await e.refreshProviderQuotaForSession(i,u,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:n});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{h as PROVIDER_QUOTA_HOST_FIELDS,Z as PROVIDER_QUOTA_HOST_METHODS,ue as doRefreshQuotaAfterModelSwitch,te as enrichProviderQuotaMeta,re as maybeQueryProviderQuota,de as providerQuotaMetaPayload,ne as pushProviderQuotaToBindings,ae as refreshAndPushProviderQuota,ce as refreshProviderQuotaForSession,se as refreshQuotaAfterModelSwitch,ee as resolveProviderQuotaSource,ie as startProviderQuotaTimer,oe as stopProviderQuotaTimer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as o,writeJSONFileAtomic as
|
|
1
|
+
import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const
|
|
1
|
+
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProvider as r,detectProviderFromModel as i,normalizeProviderId as a,queryProviderQuota as t,readKimiProviderSettings as d,readOpenCodeProviderSettings as s,readPiProviderSettings as n,resolveKimiProviderSettings as p}from"./providers.js";import{isOpenaiCodexProviderName as C,parseOpenaiCodexUsage as
|
|
1
|
+
import{detectProvider as r,detectProviderFromModel as i,normalizeProviderId as a,queryProviderQuota as t,readKimiProviderSettings as d,readOpenCodeProviderSettings as s,readPiProviderSettings as n,resolveKimiProviderSettings as p}from"./providers.js";import{isOpenaiCodexProviderName as C,parseOpenaiCodexUsage as l,queryOpenaiCodexQuota as u,resolveOpenaiCodexAccessToken as O,openaiCodexQuotaCacheKey as x}from"./openai-codex.js";import{ProviderQuotaService as m,sharedProviderQuotaService as Q,resolveQuotaBaseUrl as y}from"./service.js";import{providerQuotaToRateLimits as f,providerQuotaToCodexRateLimits as K,providerQuotaToolbarExtras as S}from"./presentation.js";import{findOpenCodeConsoleKey as q,isOpenCodeConsoleKey as E,OPENCODE_CONSOLE_ORIGIN as G,parseOpenCodeGoQuota as N,queryOpenCodeGoQuota as R,resolveOpenCodeConsoleQuotaKey as T,resolvePiOpenCodeConsoleQuotaKey as I}from"./opencode-go.js";import{queryGrixRelayWalletBalance as h}from"./grix-relay.js";export{G as OPENCODE_CONSOLE_ORIGIN,m as ProviderQuotaService,r as detectProvider,i as detectProviderFromModel,q as findOpenCodeConsoleKey,E as isOpenCodeConsoleKey,C as isOpenaiCodexProviderName,a as normalizeProviderId,x as openaiCodexQuotaCacheKey,N as parseOpenCodeGoQuota,l as parseOpenaiCodexUsage,K as providerQuotaToCodexRateLimits,f as providerQuotaToRateLimits,S as providerQuotaToolbarExtras,h as queryGrixRelayWalletBalance,R as queryOpenCodeGoQuota,u as queryOpenaiCodexQuota,t as queryProviderQuota,d as readKimiProviderSettings,s as readOpenCodeProviderSettings,n as readPiProviderSettings,p as resolveKimiProviderSettings,T as resolveOpenCodeConsoleQuotaKey,O as resolveOpenaiCodexAccessToken,I as resolvePiOpenCodeConsoleQuotaKey,y as resolveQuotaBaseUrl,Q as sharedProviderQuotaService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as g}from"node:fs";import{homedir as h}from"node:os";import{join as l}from"node:path";const C="https://opencode.ai/console",b=1e4,f=100000000n;function O(e){return typeof e=="string"&&e.trim().startsWith("oc_sk_")}function i(e){return{provider:"opencode_go",providerLabel:"OpenCode Go",planName:null,tiers:[],balance:null,success:!1,error:e}}function c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function p(e){if(typeof e=="bigint")return e;if(typeof e=="number"&&Number.isFinite(e))return BigInt(Math.trunc(e));if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))return null;try{return BigInt(e.trim())}catch{return null}}function _(e,n){return n<=0n?0:e>=n?100:Number((e*200n+n)/(n*2n))}function G(e){const n=e<0n,t=n?-e:e,o=t/f,r=t%f,s=Number(o)+Number(r)/Number(f);return n?-s:s}function k(e){return e==="go"?"Go":e==="go-plus"?"Go Plus":typeof e=="string"&&e.trim()?e:null}function d(e,n,t){const o=c(t);if(!o)return null;const r=p(o.limitMicroCents),s=p(o.usedMicroCents);if(r===null||s===null)return null;const u=typeof o.resetsAt=="string"?o.resetsAt:null;return{name:e,label:n,usedPercent:_(s,r),resetsAt:u}}function E(e,n){const t=c(e);if(!t)return i("Unexpected Go status response");const o=c(t.access),r=c(o?.meters),s=[d("five_hour","Rolling",r?.fiveHour),d("weekly_limit","Weekly",r?.week),d("monthly","Monthly",r?.month)].filter(N=>N!==null),u=c(n),m=u?p(u.availableMicroCents):null,y=m===null?null:{kind:"currency",remaining:G(m),total:null,used:null,unit:"USD"};return s.length===0&&!y?i("Go status did not include usage windows or credits"):{provider:"opencode_go",providerLabel:"OpenCode Go",planName:k(t.product),tiers:s,balance:y,success:!0,error:null}}async function S(e){const n={Authorization:`Bearer ${e.trim()}`,Accept:"application/json"};try{const[t,o]=await Promise.all([fetch(`${C}/api/go/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(b)}),fetch(`${C}/api/billing/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(b)})]);if(t.status===401||t.status===403)return i(`Authentication failed (HTTP ${t.status})`);if(!t.ok)return i(`Go status API error (HTTP ${t.status})`);const r=await t.json(),s=o.ok?await o.json():null;return E(r,s)}catch(t){return i(`Network error: ${t instanceof Error?t.message:String(t)}`)}}function a(e,n){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const o of e)a(o,n);return}const t=e;for(const o of["key","apiKey","api_key"]){const r=t[o],s=typeof r=="string"?r.trim():void 0;O(s)&&n.push(s)}for(const o of Object.values(t))a(o,n)}function T(e,n="opencode"){const t=e||h(),o=[l(t,".local","share",n,"auth.json"),l(t,".config",n,`${n}.json`)],r=[];for(const s of o)try{a(JSON.parse(g(s,"utf8")),r)}catch{}return r[0]}function A(e){for(const n of[e.quotaApiKey,e.envToken,e.providerApiKey]){const t=n?.trim();if(O(t))return t}}function w(e){return A(e)??T(e.home,e.vendor??"opencode")}function I(e){const n=A(e);if(n)return n;const t=e.piHome?.trim()||process.env.PI_CODING_AGENT_DIR?.trim()||l(h(),".pi","agent"),o=[];try{const r=JSON.parse(g(l(t,"auth.json"),"utf8")),s=r&&typeof r=="object"&&!Array.isArray(r)?r["opencode-go"]:void 0;a(s,o)}catch{}return o[0]}export{C as OPENCODE_CONSOLE_ORIGIN,T as findOpenCodeConsoleKey,O as isOpenCodeConsoleKey,_ as openCodeGoUsedPercent,E as parseOpenCodeGoQuota,S as queryOpenCodeGoQuota,w as resolveOpenCodeConsoleQuotaKey,I as resolvePiOpenCodeConsoleQuotaKey};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{
|
|
1
|
+
import{execFile as l}from"node:child_process";import{accessSync as T,constants as $,existsSync as C,statSync as P}from"node:fs";import{join as f,dirname as d,basename as M,delimiter as h,isAbsolute as S}from"node:path";import{promisify as a}from"node:util";import{resolveWindowsExecInvocation as D}from"../runtime/spawn.js";import{log as c}from"../log/logger.js";const F=3e3,W=5e3,w="__GRIX_SHELL_PATH__";function y(n,t){const e=[".cmd",".bat",".exe",""];for(const r of n)if(r)for(const i of e){const o=f(r,`${t}${i}`);if(C(o))return o}return null}const O=1e4,_={cache:null,inflight:null},b={cache:null,inflight:null},v={cache:null,inflight:null};let m=0;function Q(){m++;for(const n of[_,b,v])n.cache=null,n.inflight=null}function g(n,t){if(n.cache&&Date.now()-n.cache.at<O)return Promise.resolve(n.cache.value);if(n.inflight)return n.inflight;const e=m,r=t().then(i=>(m===e&&(n.cache={value:i,at:Date.now()}),n.inflight===r&&(n.inflight=null),i),i=>{throw n.inflight===r&&(n.inflight=null),i});return n.inflight=r,r}function G(){return f(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function R(){return g(_,async()=>{const n=a(l),t=async e=>{try{const{stdout:r}=await n(G(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${e}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return c.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${e} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await t("User"),...await t("Machine")]})}async function k(n){if(process.platform!=="win32")return null;const t=await R(),e=y(t,n)??await H(n);return e&&x(d(e)),e}function E(n){try{return P(n).isFile()?(T(n,$.X_OK),!0):!1}catch{return!1}}function N(n,t=process.platform){if(t==="win32")try{return P(n).isFile()}catch{return!1}return E(n)}function A(n,t){for(const e of n){if(!e)continue;const r=f(e,t);if(E(r))return r}return null}const V=new Set(["sh","bash","zsh","ksh","dash","ash"]);function L(){return g(b,async()=>{const n=process.env.SHELL||"/bin/sh";if(!V.has(M(n)))return c.info("cli-probe",`\u767B\u5F55 shell ${n} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const t=a(l);try{const e=t(n,["-lic",`printf '\\n${w}%s\\n' "$PATH"`],{timeout:W,killSignal:"SIGKILL",encoding:"utf-8"});e.child?.stdin?.end();const{stdout:r}=await e,i=r.split(/\r?\n/).reverse().find(o=>o.startsWith(w));return i?i.slice(w.length).split(h).map(o=>o.trim()).filter(Boolean):[]}catch(e){return c.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`),[]}})}function U(){return g(v,async()=>{const n=a(l),t=process.platform==="win32";try{const{stdout:e}=await n(t?"cmd.exe":"npm",t?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...t?{windowsHide:!0}:{}});return e.trim()||null}catch{return null}})}async function H(n){const t=await U();return t?process.platform==="win32"?y([t],n):A([f(t,"bin"),t],n):null}async function K(n){if(process.platform==="win32")return null;const t=await L(),e=A(t,n)??await H(n);return c.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${n}: \u7ED3\u679C=${e??"\u672A\u627E\u5230"}`),e&&x(d(e))&&c.info("cli-probe",`\u5DF2\u5C06 ${d(e)} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`),e}async function Y(){if(process.platform==="win32")return[];const n=[];for(const t of await L())S(t)&&x(t)&&n.push(t);return n.length>0&&c.info("cli-probe",`\u542F\u52A8\u65F6\u4ECE\u767B\u5F55 shell PATH \u8FFD\u52A0 ${n.length} \u4E2A\u76EE\u5F55: ${n.join(h)}`),n}function x(n){const t=process.env.PATH??"",e=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;return t.split(h).some(r=>e(r,n))?!1:(process.env.PATH=t?`${t}${h}${n}`:n,!0)}async function Z(n){if(S(n))return N(n)?n:null;const t=a(l),e=process.platform==="win32",r=e?"where":"which";try{const{stdout:i}=await t(r,[n],{timeout:3e3,encoding:"utf-8"}),o=i.trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(o.length>0){if(e){const s=o.find(u=>/\.(cmd|bat)$/i.test(u));if(s)return s;const p=o.find(u=>/\.exe$/i.test(u));return p||o[0]}return o[0]}return await I(n)}catch{return await I(n)}}function I(n){return process.platform==="win32"?k(n):K(n)}async function nn(n,t=["--version"],e=F){const r=a(l);try{const i=D(n,t),{stdout:o,stderr:s}=await r(i.command,i.args,{timeout:e,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});return{version:(o||s||"").trim().split(`
|
|
2
|
+
`)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{A as findPosixExecutableInDirs,y as findWindowsExecutableInDirs,nn as getCliVersion,Q as invalidateCliPathCache,N as isUsableExecutablePath,Y as mergeLoginShellPathIntoProcess,Z as resolveCliPath,K as resolvePosixInstalledCli,H as resolveViaNpmGlobalBin,k as resolveWindowsInstalledCli};
|
package/dist/log.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as
|
|
2
|
-
`)},error(o,r,...
|
|
1
|
+
import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
|
|
2
|
+
`)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
|
|
3
3
|
`)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};
|
package/dist/manager.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as b}from"node:path";import{homedir as H}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{isCwdLockedClientType as de,resolveStaticCwd as pe}from"./bridge/cwd-policy.js";import{buildSharedInstanceConfig as he,diffSharedOwners as ue,sharedInstanceKey as me,SharedOwnersCache as ge}from"./manager-share-config.js";import{AgentDeletedError as fe,isAgentDeletedError as E}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as _e}from"./core/util/client-version.js";import{UpgradeChecker as we}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as ye}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as Ae}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as Se}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as ke}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as be}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as ve}from"./core/aibot/types.js";import{buildReportedSkills as Ie,logDefaultSkillsCheck as Ce,cleanupProjectedSkills as W}from"./default-skills/index.js";import{buildProviderEnv as Ee,supportsKiroCwRelay as K,supportsNonMitmRelayConfig as $e}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Pe}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as z,stopKiroRelay as Q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as Te}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as Me}from"./core/runtime/cursor-resolve.js";import{probeInstalledClientCommands as V}from"./core/probe/installed-clients.js";import{AgentInstaller as xe}from"./core/installer/installer.js";import{reportInstallFailure as De}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Re}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as Oe}from"./adapter/codex/config-overrides.js";import{ACP_NEW_SESSION_RESERVED_KEYS as je}from"./protocol/acp-client.js";import{resolveCodexDirectHome as Le}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(a){if(a)return{...a.provider_id?.trim()?{providerId:a.provider_id.trim()}:{},...a.base_url?.trim()?{baseUrl:a.base_url.trim()}:{},...a.quota_base_url?.trim()?{quotaBaseUrl:a.quota_base_url.trim()}:{},...a.api_key?.trim()?{apiKey:a.api_key.trim()}:{},...a.quota_api_key?.trim()?{quotaApiKey:a.quota_api_key.trim()}:{},...a.model?.trim()?{model:a.model.trim()}:{},...a.fast_model?.trim()?{fastModel:a.fast_model.trim()}:{},...a.effort?.trim()?{effort:a.effort.trim()}:{}}}const Ne=8e3,qe=1e4,Ge=8e3;function Ue(a,e){switch(a){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"omp":return{adapterType:"pi",command:"omp",adapterHint:"omp/base",env:{PI_CODING_AGENT_DIR:b(H(),".omp","agent")}};case"cursor":return{adapterType:"cursor",command:Me()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"qodercli":return{adapterType:"acp",command:"qodercli",args:["--yolo","--acp"],enableSessionBinding:!0};case"qoderclicn":return{adapterType:"acp",command:"qoderclicn",args:["--yolo","--acp"],enableSessionBinding:!0};case"mcode":return{adapterType:"acp",command:"mcode",args:["acp"],enableSessionBinding:!0};case"dim":return{adapterType:"acp",command:"dim",args:["acp"],enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"deveco":return{adapterType:"opencode",command:"deveco",args:["serve"],adapterHint:"deveco/base",enableSessionBinding:!0};case"copilot":{const n=Te();return{adapterType:"acp",command:n.command,args:[...n.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};case"traecli":return{adapterType:"acp",command:"traecli",args:["acp","serve"],adapterHint:"traecli/base",options:{initial_mode:"bypass_permissions"},enableSessionBinding:!0};case"codebuddy":return{adapterType:"acp",command:"codebuddy",args:["--acp"],adapterHint:"codebuddy/base",enableSessionBinding:!0};case"grok":return{adapterType:"acp",command:"grok",args:["--no-auto-update","agent","--always-approve","stdio"],enableSessionBinding:!0};case"qwenpaw":return{adapterType:"acp",command:"qwenpaw",args:["acp"],enableSessionBinding:!0};case"zeroclaw":return{adapterType:"acp",command:"zeroclaw",args:["acp"],enableSessionBinding:!0};case"acp":{const n=typeof e?.command=="string"?e.command.trim():"";if(!n)throw new Error(`agent ${e?.name??"<unknown>"}: client_type=acp requires "command" (the ACP CLI executable) in the agent config; put its ACP subcommand or flag in "args"`);return{adapterType:"acp",command:n,adapterHint:"acp/base",enableSessionBinding:!0}}default:throw new Error(`Unsupported client_type: ${a}`)}}function v(a,e){return String(a??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function Be(a){return b(A.data,`session-bindings-${v(a,"unknown")}.json`)}function He(a,e){return b(A.data,`session-bindings-${v(a,e)}.json`)}function Fe(a,e){return b(A.data,`active-events-${v(a,e)}.json`)}function We(a){return b(A.data,`pending-events-${v(a,"unknown")}.json`)}function Ke(a,e){const n=v(a,"agent"),t=v(e,"unknown");return b(A.data,`terminal-outbox-${n}-${t}.json`)}function ze(...a){const e=[],n=new Set;for(const t of a)for(const s of t??[]){const i=String(s??"").trim(),c=i.toLowerCase();!i||n.has(c)||(n.add(c),e.push(i))}return e.length>0?e:void 0}function Qe(a,e){const n={claude:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},"deepseek-harness":{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0}},t=n[a]??n.acp;let s=e?.max_concurrent??t.maxConcurrent??1;return a==="acp"&&s>1&&(m.warn("manager",`ACP adapter supports only one active run at a time; clamping max_concurrent from ${s} to 1`),s=1),{maxConcurrent:s,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function Ve(a,e={}){const n=_e(),t=String(a.client_type??"").trim().toLowerCase(),s=Ue(t,a),i=t==="deepseek"?a.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(a.ws_url??"").trim(),u=typeof a.name=="string"?a.name:"",r=u.trim(),l="get_session_usage",g="get_rate_limits",p="get_agent_global_config",d=ve;if(!r)throw new Error("agent name is required");if(u!==r)throw new Error(`agent name must not contain leading or trailing whitespace: "${u}"`);if(!o)throw new Error(`agent ${a.name}: ws_url is required`);if(!a.agent_id?.trim())throw new Error(`agent ${a.name}: agent_id is required`);if(!a.api_key?.trim())throw new Error(`agent ${a.name}: api_key is required`);const h=s.adapterType,_=h==="acp",w=t==="qwen",y={...s.options??{}};if(h==="deepseek-harness"&&(y.integrationMode=i,y.dshProfile=a.dsh?.profile?.trim()||"web",y.autoInstallBridge=a.dsh?.auto_install_bridge??!c,y.autoStartProfile=a.dsh?.auto_start_profile??!c),h==="deepseek-harness"&&a.provider?.model?.trim()&&(y.defaultModel=a.provider.model.trim()),a.codex_config_overrides!==void 0){if(h!=="codex")throw new Error(`agent ${a.name}: codex_config_overrides is only supported for client_type=codex`);Oe(a.codex_config_overrides,`agent ${a.name}: codex_config_overrides`),y.codexConfigOverrides=a.codex_config_overrides}if(a.acp_new_session_params!==void 0){if(!_)throw new Error(`agent ${a.name}: acp_new_session_params is only supported for ACP-based client types`);const f=a.acp_new_session_params;if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`agent ${a.name}: acp_new_session_params must be a JSON object`);const k=Object.keys(f).find(le=>je.has(le));if(k)throw new Error(`agent ${a.name}: acp_new_session_params cannot set reserved field "${k}" (Grix owns cwd/mcpServers/sessionId/additionalDirectories on every session/new)`);y.newSessionParams=f}if(t==="zeroclaw"){const k=a.acp_new_session_params?.agentAlias;if(typeof k!="string"||!k.trim()||k.trim().startsWith("<REPLACE"))throw new Error(`agent ${a.name}: client_type=zeroclaw requires acp_new_session_params.agentAlias (create one with \`zeroclaw agents create <alias>\` and set it in the agent config); without it session/new fails with -32602 and the connector would silently respawn-retry forever`)}if(h==="codex"&&a.provider?.wire_api!==void 0){const f=a.provider;if(f.wire_api!=="responses"||!f.base_url?.trim()||!f.api_key?.trim()||!f.model?.trim()||!f.catalog_version?.trim()||!f.catalog_sha256?.trim()||!f.catalog_json?.trim())throw Object.assign(new Error(`agent ${a.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const k=Le(A.data,a.name);y.codexHome=k,y.codexDirect={codexHome:k,config:{baseUrl:f.base_url.trim(),model:f.model.trim(),...f.reasoning_effort?.trim()?{reasoningEffort:f.reasoning_effort.trim()}:{},token:f.api_key.trim()},catalog:{version:f.catalog_version.trim(),sha256:f.catalog_sha256.trim(),json:f.catalog_json}}}const S=h==="codex"?{capabilities:["stream_chunk","local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=h==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",l,g]}:null,T=w?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",l],adapterHint:"qwen/base"}:null,M=h==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","get_context","file_list","create_folder",l,g]}:null,x=h==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,D=h==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",g]}:null,N=h==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,R=h==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,O=h==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,j=h==="deepseek-harness"?{adapterHint:c?"deepseek/jsonrpc-v1":"deepseek/grix-bridge-v1",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","set_mode","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile",l,g,"exec_approve","exec_reject","permission_approve","permission_reject","file_list","create_folder","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals"]}:null,q=new Set(["hermes","reasonix","kimi","copilot","acp","qodercli","qoderclicn","mcode","dim","traecli","grok","qwenpaw","zeroclaw","codebuddy"]),ee=_&&!q.has(t),te=_&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder",...ee?[l]:[]]}:null,ne=t==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",l,g]}:null,se=h==="codex"||h==="claude"||h==="opencode"||h==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...h==="deepseek-harness"?["set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill"]:[],...h==="claude"?["set_reasoning_effort"]:[]]:void 0,ae=h==="cursor"||h==="opencode"||h==="openhuman"||h==="agy"||_&&q.has(t)?[g]:[l,g];_&&y.raw_transport===void 0&&(y.raw_transport=t==="gemini");const re=`${t}/base`,C=Se(h,t),ie=C==="kiro"?void 0:process.cwd(),L=Y(a.provider),I={...process.env,...s.env,...a.env};if(C==="hermes"&&!I.HERMES_HOME?.trim()){const f=Ee(t,L);I.HERMES_HOME=Pe({...f,...I},a.name)}const G=Ie({mode:C,projectDir:ie,env:I}),U=G.filter(f=>f.source==="connector").map(f=>f.name);U.length>0&&!e.quiet&&m.info("manager",`[${a.name}] injecting connector skills: [${U.join(", ")}]`);const B=ke(G,A.skills);let oe=B.length>0?B:void 0;const ce=be({skillsDir:A.skills,mode:C,home:H(),env:I});return{name:r,adapterType:h,aibot:{url:o,agentId:a.agent_id,apiKey:a.api_key,clientType:t,clientVersion:n,adapterHint:j?.adapterHint??s.adapterHint??T?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??R?.adapterHint??O?.adapterHint??re,capabilities:j?.capabilities??S?.capabilities??N?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??R?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:ze(j?.localActions??S?.localActions??N?.localActions??Z?.localActions??M?.localActions??x?.localActions??D?.localActions??R?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,ae,["connector_rollback","connector_upgrade_push",p,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:Ke(a.name,a.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...a.args??[]],env:s.env?{...s.env,...a.env}:a.env,clientType:t,...L?{provider:L}:{}},adapterOptions:y,acpAuthMethod:y.auth_method,acpInitialMode:y.initial_mode,acpMcpTools:y.acp_mcp_tools,promptTimeoutMs:a.prompt_timeout_ms,bindingsPath:Be(a.agent_id),legacyBindingsPath:He(a.name,a.agent_id),activeEventStorePath:Fe(a.name,a.agent_id),pendingEventStorePath:We(a.agent_id),...s.enableSessionBinding||_?{enableSessionBinding:!0}:{},...de(t)?{staticCwd:pe(a.cwd)}:{},...s.autoInjectArgs||t==="reasonix"&&a.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&a.provider?.model?.trim()?{model:a.provider.model.trim()}:{}}}:{},poolMaxSize:a.pool?.maxSize??(h==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:a.pool?.idleTimeoutMs,eventQueue:Qe(h,a.event_queue),logDir:A.log,providerBaseUrl:a.provider_base_url?.trim()||void 0,providerApiKey:a.provider_api_key?.trim()||void 0}}function J(){const a=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):Ne}function $(){const a=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):qe}function Xe(){return Math.min($(),Ge)}function P(a){if(a===null||typeof a!="object")return JSON.stringify(a)??"null";if(Array.isArray(a))return`[${a.map(P).join(",")}]`;const e=a;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${P(e[t])}`).join(",")}}`}function Ye(a,e){return P(a)===P(e)}class Pt{options;instances=[];configMap=new Map;rawConfigMap=new Map;mutationTail=Promise.resolve();startingInstances=new Set;failedStartAgents=new Set;removingAgents=new Set;instanceGenerations=new WeakMap;sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;lifecycleAdmissionClosed=!1;deletedAgentCleanups=new Set;pendingPlatformDeletes=new Map;upgradeChecker=null;skillSyncer=null;globalConfigStore;configRepository=new X(A.config);sharedOwnersCache=new ge(A.data);installer=new xe;relaySecretResolver;auditProducer=Re();constructor(e={}){this.options=e}runMutation(e,n=[]){const t=this.mutationTail.catch(()=>{}).then(async()=>{if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});await this.retryPendingPlatformDeletesUnlocked();const s=new Set([...this.pendingPlatformDeletes.values()].map(c=>c.name)),i=n.find(c=>s.has(c.trim()));if(i)throw Object.assign(new Error(`Agent "${i}" is pending permanent platform-deletion cleanup`),{code:"AGENT_DELETE_PENDING"});return e()});return this.mutationTail=t.then(()=>{},()=>{}),t}async startTrackedInstance(e){this.startingInstances.add(e);try{await e.start()}finally{this.startingInstances.delete(e)}}requestStartCancellation(e){const n=e.requestStop;typeof n=="function"&&n.call(e)}async stopInstance(e,n,t=$()){let s;try{await Promise.race([e.stop(n),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`Agent "${e.name}" stop timed out after ${t}ms`),{code:"AGENT_STOP_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForLifecycleDrain(e,n,t=$()){let s;try{await Promise.race([Promise.allSettled([...e]).then(()=>{}),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"LIFECYCLE_DRAIN_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForShutdownOperation(e,n,t){let s;try{return await Promise.race([e,new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"SHUTDOWN_OPERATION_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}isActiveGeneration(e){const n=this.instanceGenerations.get(e);return!!n&&!n.retired&&this.instances.find(t=>t.name===n.name)===e}retireInstance(e){const n=this.instanceGenerations.get(e);n&&(n.retired=!0)}async start(e){return this.runMutation(()=>this.startUnlocked(e))}async startUnlocked(e){const n=e??A.config;this.configRepository=new X(n),m.info("manager",`Loading configs from ${n}`),Ce(),W(),this.globalConfigStore=new Ae(b(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const r of s)m.error("manager",`Failed to load ${r.file}: ${r.error}`);for(const r of i)m.info("manager",`Skipped ${r}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&i.length===0){m.warn("manager",`No agent configurations found in ${n}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const c=[];let o=s.length;for(const{entry:r,file:l}of t)try{const g=this.toRuntimeInstanceConfig(r);c.push({config:g,entry:r,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const p=typeof r?.name=="string"?r.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${p}): ${g}`),o++}let u=0;if(c.length>0){const r=J();m.info("manager",`Starting ${c.length} agent(s), startup wait=${r}ms`);const l=d=>{this.instances=this.instances.filter(h=>h!==d)},g=c.map(({config:d,entry:h,file:_})=>{const w=this.createConfiguredInstance(d);return this.instances.push(w),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:h,file:_}),{config:d,instance:w,startPromise:this.prepareProviderRuntime(d,h).then(()=>{if(this.stopping)throw this.requestStartCancellation(w),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(w)})}}),p=await Promise.all(g.map(async d=>{const h=await new Promise(_=>{let w=!1;const y=setTimeout(()=>{w||(w=!0,_({kind:"timeout"}))},r);d.startPromise.then(()=>{w||(w=!0,clearTimeout(y),_({kind:"started"}))}).catch(S=>{w||(w=!0,clearTimeout(y),_({kind:"failed",error:S}))})});return{task:d,outcome:h}}));for(const{task:d,outcome:h}of p){if(h.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(h.kind==="failed"){if(E(h.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(_){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up partially started ${d.config.name}: ${_}`)}m.error("manager",`Failed to start ${d.config.name}: ${h.error}`);continue}u++,m.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{this.stopping||this.removingAgents.has(d.config.name)||this.isActiveGeneration(d.instance)&&(m.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config))}).catch(async _=>{if(E(_)){this.onAgentDeletedByPlatform(d.instance);return}if(!(this.stopping||this.removingAgents.has(d.config.name))&&this.isActiveGeneration(d.instance)){try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(w){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up delayed start ${d.config.name}: ${w}`)}m.error("manager",`Delayed start failed: ${d.config.name}: ${_}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-u);m.info("manager",`${d}/${c.length} agent(s) running now`)}u>0&&m.warn("manager",`${u} agent(s) still connecting in background`)}if(this.instances.length===0&&c.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.stopping||this.configMap.size===0)return;const e=[...this.configMap.values()].map(n=>({apiKey:n.aibot.apiKey,wsUrl:n.aibot.url}));if(!this.upgradeChecker&&(this.upgradeChecker=new we(e,()=>this.describeAnyPendingOrBackgroundWork(),()=>this.closeAllLifecycleAdmission(),{requestGracefulShutdown:this.options.requestGracefulShutdown,reopenLifecycleAdmission:()=>this.reopenAllLifecycleAdmission(),isConnected:()=>this.instances.length===0||this.instances.some(n=>n.getStatus().wsConnected),onTransactionSettled:this.options.onTransactionSettled}),await this.upgradeChecker.start(),this.stopping)){this.upgradeChecker.stop();return}this.skillSyncer||(this.skillSyncer=new ye(e,A.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start(),this.stopping&&this.skillSyncer.stop())}refreshOwnerLibrarySkills(){const e=new Map,n=t=>{let s;try{s=t.skillsSyncGroupKey()}catch(c){m.warn("manager",`skillsSyncGroupKey failed for ${t.name}: ${c}`);return}const i=e.get(s)??[];i.push(t),e.set(s,i)};for(const t of this.instances)n(t);for(const t of this.sharedInstances.values())n(t);for(const[t,s]of e){let i=!1;const c=[];for(const o of s){if(i){c.push(o);continue}let u=!1;try{u=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(r){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${r}`)}if(u){i=!0;continue}m.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!i){m.warn("manager",`owner library skills: no reporter succeeded group=${t}`);continue}for(const o of c)try{o.adoptSkillsWireHashFromDisk()}catch(u){m.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${u}`)}}}async stop(){m.info("manager","Stopping all agents..."),this.stopping=!0;const e=Xe(),n=Date.now()+e,t=()=>Math.max(1,n-Date.now()),s=new Set([...this.instances,...this.sharedInstances.values(),...this.startingInstances]);for(const o of s)this.requestStartCancellation(o);const i=new Map([...s].map(o=>[o,this.stopInstance(o,void 0,e)])),c=[];this.upgradeChecker?.stop(),this.skillSyncer?.stop();try{await this.waitForLifecycleDrain([this.mutationTail,...this.shareSyncChains.values(),...i.values()],"manager shutdown lifecycle drain",t())}catch(o){c.push(o)}this.upgradeChecker?.stop(),this.skillSyncer?.stop(),this.shareSyncChains.clear(),await Promise.all([...[...this.instances].map(async o=>{try{await(i.get(o)??this.stopInstance(o,void 0,t())),this.retireInstance(o),this.instances=this.instances.filter(u=>u!==o),this.startingInstances.delete(o)}catch(u){c.push(u)}}),...[...this.sharedInstances.entries()].map(async([o,u])=>{try{await(i.get(u)??this.stopInstance(u,void 0,t())),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o),this.startingInstances.delete(u)}catch(r){c.push(r)}})]);try{await this.waitForLifecycleDrain([this.retryPendingPlatformDeletesUnlocked(n)],"platform-delete shutdown drain",t())}catch(o){c.push(o)}try{await this.waitForShutdownOperation(Promise.resolve().then(()=>this.globalConfigStore?.flush()),"global config shutdown flush",t())}catch(o){c.push(o)}if(await this.auditProducer.stop({timeoutMs:Math.min(5e3,t())}).catch(()=>!1),W(),c.length>0)throw new AggregateError(c,"Failed to stop all agents completely");m.info("manager","All stopped")}onShareSet(e,n,t){if(this.stopping||this.removingAgents.has(n.name)||!this.isActiveGeneration(e))return;this.sharedOwnersCache.save(n.name,t);const i=(this.shareSyncChains.get(n.name)??Promise.resolve()).catch(()=>{}).then(()=>{if(!(this.stopping||this.removingAgents.has(n.name))&&this.isActiveGeneration(e))return this.syncSharedInstances(n,t,e)});this.shareSyncChains.set(n.name,i)}async syncSharedInstances(e,n,t){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))return;const{toAdd:s,toRemove:i}=ue(e.name,this.sharedInstances.keys(),n);for(const c of s){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))break;const o=me(e.name,c);let u;try{const r=he(e,c);u=new F(r,this.globalConfigStore,this.auditProducer),u.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),u.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),u.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&u.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&u.closeLifecycleAdmission(),this.sharedInstances.set(o,u),await this.startTrackedInstance(u),u.forceRefreshSkills(void 0,{force:!0}),m.info("manager",`shared instance started: ${o}`)}catch(r){if(u&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(u),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o)}catch(g){m.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=r instanceof Error?r.message:String(r);/Auth failed/i.test(l)?(this.sharedOwnersCache.remove(e.name,c),m.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):m.error("manager",`start shared instance failed ${o}: ${r}`)}}for(const{key:c}of i){const o=this.sharedInstances.get(c);if(o)try{await this.stopInstance(o),this.sharedInstances.get(c)===o&&this.sharedInstances.delete(c),m.info("manager",`shared instance stopped: ${c}`)}catch(u){m.error("manager",`stop shared instance failed ${c}: ${u}`)}}}restoreCachedSharedInstances(e){const n=this.sharedOwnersCache.load(e.name);if(n.length===0)return;const t=this.instances.find(s=>s.name===e.name);!t||!this.isActiveGeneration(t)||(m.info("manager",`restoring ${n.length} cached shared instance(s) for ${e.name}`),this.onShareSet(t,e,n))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){return this.runMutation(()=>this.addAgentUnlocked(e),[String(e.name??"")])}async addAgentUnlocked(e){const n=this.toRuntimeInstanceConfig(e,{quiet:!0});if(this.instances.some(t=>t.name===n.name))throw new Error(`Agent "${n.name}" already exists`);this.configRepository.assertCanAdd(e),await this.addAgentInternal(e,"agents.json",{targetPersisted:!1});try{const t=this.configRepository.insert(e);this.rawConfigMap.set(e.name,t);const s=this.instances.find(c=>c.name===e.name),i=s?this.instanceGenerations.get(s):void 0;if(i){i.persisted=!0;const c=this.configMap.get(e.name);c&&this.restoreCachedSharedInstances(c)}}catch(t){try{await this.removeAgentInternal(e.name)}catch(s){throw new AggregateError([t,s],`Failed to persist and roll back agent "${e.name}"`)}throw t}await this.ensureAuxServices(),m.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,n,t){const s=this.toRuntimeInstanceConfig(e);if(this.instances.some(i=>i.name===s.name))throw new Error(`Agent "${s.name}" already exists`);await this.startInstanceFromConfig(s,e,n,t)}createConfiguredInstance(e,n=!0){const t=new F(e,this.globalConfigStore,this.auditProducer);return this.instanceGenerations.set(t,{name:e.name,agentId:e.aibot.agentId,persisted:n,retired:!1,platformDeletedObserved:!1}),t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),this.options.requestGracefulShutdown&&t.setDaemonShutdownRequester(this.options.requestGracefulShutdown),t.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(s)),t.setRemoteAdminPorts({isEnabled:()=>this.remoteAdminGate?.()??!1,listInstallable:()=>this.listInstallable(),installAgent:s=>this.installAgent(s),getInstallProgress:s=>this.getInstallProgress(s),addAgent:s=>this.addAgent(s),probeAll:s=>this.probeAll(s)}),t.setShareSetHandler(s=>this.onShareSet(t,e,s)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(t)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(s=>this.setAgentProvider(e.name,s)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},getAppliedMode:()=>this.relayStateApplier?.getAppliedMode?.(e.name),applyEnable:(s,i)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,s,i):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const s=this.relayStateApplier;return s?s.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>Y(this.getAgentProvider(e.name))),t}describeAnyPendingOrBackgroundWork(){return[...this.instances.flatMap(e=>e.describePendingOrBackgroundWork()),...[...this.sharedInstances.values()].flatMap(e=>e.describePendingOrBackgroundWork())]}closeAllLifecycleAdmission(){this.lifecycleAdmissionClosed=!0;for(const e of this.instances)e.closeLifecycleAdmission();for(const e of this.sharedInstances.values())e.closeLifecycleAdmission()}reopenAllLifecycleAdmission(){if(!this.stopping){this.lifecycleAdmissionClosed=!1;for(const e of this.instances)e.openLifecycleAdmission();for(const e of this.sharedInstances.values())e.openLifecycleAdmission()}}async prepareProviderRuntime(e,n){const t=this.resolveAgentProvider(n.provider);K(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await z(e.name,{baseUrl:t.base_url.trim(),apiKey:t.api_key.trim(),model:t.model.trim()})}async startInstanceFromConfig(e,n,t,s){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});if(await this.prepareProviderRuntime(e,n),this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});const i=this.createConfiguredInstance(e,s.targetPersisted);this.instances.push(i);const c=this.startTrackedInstance(i),o=J(),u=await new Promise(p=>{let d=!1;const h=setTimeout(()=>{d||(d=!0,p({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(h),p({kind:"started"}))},_=>{d||(d=!0,clearTimeout(h),p({kind:"failed",error:_}))})}),r=this.instanceGenerations.get(i);if(r?.platformDeletedObserved&&!r.persisted){const p=new fe(`Agent "${e.name}" was deleted before its local configuration commit`);try{await this.stopInstance(i),this.retireInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){throw this.failedStartAgents.add(e.name),new AggregateError([p,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw p}if(u.kind==="started"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),this.failedStartAgents.delete(e.name),s.targetPersisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.();return}if(u.kind==="timeout"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),m.warn("manager",`Start pending for ${e.name}, continue retrying in background`),c.then(async()=>{if(!this.removingAgents.has(e.name)&&this.isActiveGeneration(i)){if(this.stopping){try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i)}catch(p){this.failedStartAgents.add(e.name),m.error("manager",`Failed to stop late-started ${e.name}: ${p}`)}return}this.failedStartAgents.delete(e.name),this.instanceGenerations.get(i)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),m.info("manager",`Delayed start succeeded: ${e.name}`)}},async p=>{if(E(p)){this.onAgentDeletedByPlatform(i);return}if(!(this.stopping||this.removingAgents.has(e.name))&&this.isActiveGeneration(i)){try{await this.stopInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){this.failedStartAgents.add(e.name),m.error("manager",`Failed to clean up delayed start ${e.name}: ${d}`)}m.error("manager",`Delayed start failed ${e.name}: ${p}`)}}).catch(p=>{m.error("manager",`Delayed start finalizer failed ${e.name}: ${p}`)});return}const l=u.error;E(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i),this.failedStartAgents.delete(e.name)}catch(p){g=p,this.failedStartAgents.add(e.name)}throw s.targetPersisted&&(this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t})),g!==void 0?new AggregateError([l,g],`Failed to start and clean up agent "${e.name}"`):l}async removeAgent(e){return this.runMutation(()=>this.removeAgentUnlocked(e),[e])}async removeAgentUnlocked(e){if(!(this.instances.some(t=>t.name===e)||this.rawConfigMap.has(e)||[...this.sharedInstances.keys()].some(t=>t.startsWith(`${e}#shared:`))))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});this.configRepository.remove(e),await this.removeAgentInternal(e),m.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,n){this.removingAgents.add(e);try{const t=()=>n?.deadlineMs===void 0?$():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(p=>p.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},u=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&u.set(i,this.stopInstance(i,o,t())));for(const[p,d]of this.sharedInstances)p.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&u.set(d,this.stopInstance(d,o,t())));const r=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...r?[r]:[],...u.values()],`agent "${e}" shared lifecycle drain`,t())}catch(p){l.push(p)}const g=[];for(const[p,d]of[...this.sharedInstances.entries()])p.startsWith(c)&&g.push((u.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(p)===d&&this.sharedInstances.delete(p),this.startingInstances.delete(d)}).catch(h=>{l.push(h),m.error("manager",`stop shared instance failed ${p}: ${h}`)}));if(i)try{await(u.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const p=this.instances.indexOf(i);p!==-1&&this.instances.splice(p,1),this.startingInstances.delete(i)}catch(p){l.push(p)}if(await Promise.all(g),!n?.keepShareCache){const p=Q(e).catch(()=>{});if(n?.deadlineMs===void 0)await p;else try{await this.waitForLifecycleDrain([p],`agent "${e}" relay shutdown`,t())}catch(d){l.push(d)}}if(l.length>0)throw new AggregateError(l,`Failed to stop agent "${e}" completely`);this.configMap.delete(e),this.rawConfigMap.delete(e),this.failedStartAgents.delete(e),n?.keepShareCache||this.sharedOwnersCache.delete(e)}finally{this.removingAgents.delete(e)}}onAgentDeletedByPlatform(e){const n=this.instanceGenerations.get(e);if(!n||(n.platformDeletedObserved=!0,this.requestStartCancellation(e),!n.persisted))return;const t={source:e,name:n.name,agentId:n.agentId};this.pendingPlatformDeletes.set(e,t),!this.stopping&&(this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),this.runMutation(async()=>{}).catch(()=>{}).finally(()=>{this.deletedAgentCleanups.delete(e)})))}async retryPendingPlatformDeletesUnlocked(e){if(this.pendingPlatformDeletes.size!==0)for(const[n,t]of[...this.pendingPlatformDeletes])try{await this.cleanupPlatformDeletedUnlocked(t,e),this.pendingPlatformDeletes.delete(n)}catch(s){m.error("manager",`cleanup for deleted agent "${t.name}" failed: ${s}`)}}async cleanupPlatformDeletedUnlocked(e,n){const{source:t,name:s,agentId:i}=e,c=this.instances.find(g=>g.name===s),o=c?this.instanceGenerations.get(c)?.agentId??String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim():void 0;if(c&&c!==t&&o!==i)return;m.warn("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`);const u=this.rawConfigMap.get(s),r=this.configMap.get(s),l=[];if(c&&o===i)try{await this.removeAgentInternal(s,{deadlineMs:n})}catch(g){l.push(g)}try{const g=this.configRepository.scan();if(g.fileErrors.length>0){const h=g.fileErrors.map(_=>`${_.file}: ${_.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${h}]`)}const p=g.entries.filter(h=>String(h.entry?.name??"").trim()===s);if(!p.some(h=>String(h.entry?.agent_id??"").trim()!==i)&&p.length>0&&this.configRepository.remove(s),l.length===0){const h=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!h||h===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),u&&this.rawConfigMap.set(s,u),r&&this.configMap.set(s,r)}if(l.length>0)throw new AggregateError(l,`Failed to fully clean up deleted agent "${s}"`);m.info("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406`)}isAgentBusy(e){return this.instances.find(t=>t.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const n=this.instances.find(t=>t.name===e);return n?(n.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}remoteAdminGate;setRemoteAdminGate(e){this.remoteAdminGate=e}relayStateApplier;setRelayStateApplier(e){this.relayStateApplier=e}reportRelayStateLocalChange(e){this.instances.find(t=>t.name===e)?.reportRelayStateLocalChange()}setRelaySecretResolver(e){this.relaySecretResolver=e}resolveAgentProvider(e){if(!e?.api_key_ref?.trim())return e;const n=e.api_key_ref.trim(),t=this.relaySecretResolver?.(n);if(!t)throw Object.assign(new Error(`relay credential "${n}" is unavailable`),{code:"RELAY_SECRET_UNAVAILABLE"});return{...e,api_key:t}}toRuntimeInstanceConfig(e,n={}){const t=this.resolveAgentProvider(e.provider);return Ve(t===e.provider?e:{...e,provider:t},n)}getAgentProvider(e){return this.resolveAgentProvider(this.rawConfigMap.get(e)?.entry.provider)}async restartAgent(e){return this.runMutation(()=>this.restartAgentUnlocked(e),[e])}async restartAgentUnlocked(e){const n=this.rawConfigMap.get(e);if(!n)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,n.entry,n.file),m.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,n,t){return this.runMutation(()=>this.setAgentProviderUnlocked(e,n,t),[e])}async setAgentProviderUnlocked(e,n,t){if(!this.rawConfigMap.get(e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const i=n?.api_key_ref?.trim()?Object.fromEntries(Object.entries(n).filter(([r])=>r!=="api_key")):n,c=this.configRepository.updateExisting(e,r=>{const l={...r};if(i===void 0)delete l.provider;else{const g=i.quota_api_key?.trim()||r.provider?.quota_api_key?.trim();l.provider=g?{...i,quota_api_key:g}:i}return this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const u=String(o.client_type??"").trim().toLowerCase();try{K(u)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await z(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await Q(e))}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}if(t?.deferRestart){this.instances.find(r=>r.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}m.info("manager",`Updated provider config for agent: ${e}`)}hasDirectRelayConfig(e){const n=this.rawConfigMap.get(e)?.entry.provider;return!!(n?.api_key_ref?.trim()||n?.api_key?.trim())}getDirectRelayConfigAgentNames(){return[...this.rawConfigMap.entries()].filter(([,e])=>!!e.entry.provider&&($e(e.entry.client_type)||["claude","codex"].includes(String(e.entry.client_type??"").trim().toLowerCase()))).map(([e])=>e)}async fetchRelayCredential(e,n){const t=this.instances.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.fetchRelayCredential(n)}async clearDirectProviderConfigs(){const e=this.getDirectRelayConfigAgentNames(),n=[];for(const t of e)try{await this.setAgentProvider(t,void 0,{deferRestart:this.isAgentBusy(t)}),n.push(t)}catch(s){m.warn("manager",`Failed to clear provider config for "${t}": ${s instanceof Error?s.message:String(s)}`)}return n}async replaceInstance(e,n,t){const s=this.toRuntimeInstanceConfig(n);try{await this.removeAgentInternal(e,{keepShareCache:!0})}catch(o){throw this.failedStartAgents.add(e),o}const i=String(n.agent_id??"").trim();if([...this.pendingPlatformDeletes.values()].some(o=>o.name===e&&o.agentId===i))throw await this.retryPendingPlatformDeletesUnlocked(),Object.assign(new Error(`Agent "${e}" was permanently deleted while its instance was stopping`),{code:"AGENT_DELETE_PENDING"});try{await this.startInstanceFromConfig(s,n,t,{targetPersisted:!0})}catch(o){throw this.configMap.set(e,s),this.rawConfigMap.set(e,{entry:n,file:t}),o}}async reload(){return this.runMutation(()=>this.doReload())}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:n,skipped:t}=this.configRepository.scan();for(const r of t)m.info("manager",`reload: skipped ${r}: not an agent config (no "agents" key)`);if(n.length>0){const r=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${r}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:r}of e)try{this.toRuntimeInstanceConfig(r,{quiet:!0})}catch(l){const g=r?.name,p=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:p,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const r=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${r}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(r=>r.name));for(const r of e){const l=String(r.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,r)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},u=new Set([...this.rawConfigMap.keys()].filter(r=>!c.has(r)));for(const r of u)if(!i.has(r))try{await this.removeAgentInternal(r),o.removed.push(r)}catch(l){o.failed.push({name:r,error:l instanceof Error?l.message:String(l)})}for(const[r,l]of i){const g=this.rawConfigMap.get(r);if(g)if(!Ye(g.entry,l.entry)||!this.instances.some(p=>p.name===r)||this.failedStartAgents.has(r))try{await this.replaceInstance(r,l.entry,l.file),o.restarted.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}else this.rawConfigMap.set(r,l),o.unchanged.push(r);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}}return m.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),await this.ensureAuxServices(),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Je(this.instances,e)}async probeOne(e,n={}){return Ze(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return De(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Je(a,e){const n=e.concurrency??4,t=Date.now(),s=new Array(a.length);await new Promise(r=>{let l=0,g=0;const p=a.length;if(p===0){r();return}function d(w){const y=a[w];y.probe(e).then(S=>{s[w]=S,h()},S=>{s[w]={agent_name:y.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:S?.message??String(S)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},h()})}function h(){g++,l<p?d(l++):g===p&&r()}const _=Math.min(n,p);for(let w=0;w<_;w++)d(l++)});const i=s.filter(r=>r.status==="healthy").length,c=s.filter(r=>r.status==="degraded").length,o=s.filter(r=>r.status==="unavailable").length,u=await V();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:u,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function Ze(a,e,n){const t=a.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{Pt as Manager,Y as normalizeAgentProviderForRuntime,V as probeInstalledClientCommands,Je as probeInstances,Ze as probeOneInstance};
|
|
1
|
+
import{join as b}from"node:path";import{homedir as H}from"node:os";import{AgentInstance as F}from"./bridge/bridge.js";import{isCwdLockedClientType as de,resolveStaticCwd as pe}from"./bridge/cwd-policy.js";import{buildSharedInstanceConfig as he,diffSharedOwners as ue,sharedInstanceKey as me,SharedOwnersCache as ge}from"./manager-share-config.js";import{AgentDeletedError as fe,isAgentDeletedError as E}from"./core/aibot/errors.js";import{GRIX_PATHS as A,log as m}from"./core/log/index.js";import{resolveClientVersion as _e}from"./core/util/client-version.js";import{mergeLoginShellPathIntoProcess as we}from"./core/util/cli-probe.js";import{UpgradeChecker as ye}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as Ae}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as Se}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as ke}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as be}from"./core/skill-sync/sync-state.js";import{buildLibrarySkills as ve}from"./core/skill-sync/library-skills.js";import{AUDIT_LOCAL_ACTION_TYPES as Ie}from"./core/aibot/types.js";import{buildReportedSkills as Ce,logDefaultSkillsCheck as Ee,cleanupProjectedSkills as W}from"./default-skills/index.js";import{buildProviderEnv as $e,supportsKiroCwRelay as K,supportsNonMitmRelayConfig as Pe}from"./core/config/provider-env.js";import{resolveHermesHomeDir as Te}from"./adapter/shared/native-provider-config.js";import{ensureKiroRelay as z,stopKiroRelay as Q}from"./core/proxy/kiro-relay.js";import{resolveCopilotCommand as Me}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as xe}from"./core/runtime/cursor-resolve.js";import{probeInstalledClientCommands as V}from"./core/probe/installed-clients.js";import{AgentInstaller as De}from"./core/installer/installer.js";import{reportInstallFailure as Re}from"./core/observability/sentry.js";import{createDefaultAuditProducer as Oe}from"./audit/runtime/default-audit-recorder.js";import{normalizeCodexConfigOverrides as je}from"./adapter/codex/config-overrides.js";import{ACP_NEW_SESSION_RESERVED_KEYS as Le}from"./protocol/acp-client.js";import{resolveCodexDirectHome as Ne}from"./adapter/codex/direct-home.js";import{AgentConfigRepository as X}from"./core/config/agent-config-repository.js";function Y(a){if(a)return{...a.provider_id?.trim()?{providerId:a.provider_id.trim()}:{},...a.base_url?.trim()?{baseUrl:a.base_url.trim()}:{},...a.quota_base_url?.trim()?{quotaBaseUrl:a.quota_base_url.trim()}:{},...a.api_key?.trim()?{apiKey:a.api_key.trim()}:{},...a.quota_api_key?.trim()?{quotaApiKey:a.quota_api_key.trim()}:{},...a.model?.trim()?{model:a.model.trim()}:{},...a.fast_model?.trim()?{fastModel:a.fast_model.trim()}:{},...a.effort?.trim()?{effort:a.effort.trim()}:{}}}const qe=8e3,Ge=1e4,Ue=8e3;function Be(a,e){switch(a){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"omp":return{adapterType:"pi",command:"omp",adapterHint:"omp/base",env:{PI_CODING_AGENT_DIR:b(H(),".omp","agent")}};case"cursor":return{adapterType:"cursor",command:xe()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"qodercli":return{adapterType:"acp",command:"qodercli",args:["--yolo","--acp"],enableSessionBinding:!0};case"qoderclicn":return{adapterType:"acp",command:"qoderclicn",args:["--yolo","--acp"],enableSessionBinding:!0};case"mcode":return{adapterType:"acp",command:"mcode",args:["acp"],enableSessionBinding:!0};case"dim":return{adapterType:"acp",command:"dim",args:["acp"],enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"deveco":return{adapterType:"opencode",command:"deveco",args:["serve"],adapterHint:"deveco/base",enableSessionBinding:!0};case"copilot":{const n=Me();return{adapterType:"acp",command:n.command,args:[...n.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"deepseek":return{adapterType:"deepseek-harness",command:"dsh",adapterHint:"deepseek/grix-bridge-v1",options:{integrationMode:"profile_bridge",dshProfile:"web",autoInstallBridge:!0,autoStartProfile:!0},enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};case"traecli":return{adapterType:"acp",command:"traecli",args:["acp","serve"],adapterHint:"traecli/base",options:{initial_mode:"bypass_permissions"},enableSessionBinding:!0};case"codebuddy":return{adapterType:"acp",command:"codebuddy",args:["--acp"],adapterHint:"codebuddy/base",enableSessionBinding:!0};case"grok":return{adapterType:"acp",command:"grok",args:["--no-auto-update","agent","--always-approve","stdio"],enableSessionBinding:!0};case"qwenpaw":return{adapterType:"acp",command:"qwenpaw",args:["acp"],enableSessionBinding:!0};case"zeroclaw":return{adapterType:"acp",command:"zeroclaw",args:["acp"],enableSessionBinding:!0};case"acp":{const n=typeof e?.command=="string"?e.command.trim():"";if(!n)throw new Error(`agent ${e?.name??"<unknown>"}: client_type=acp requires "command" (the ACP CLI executable) in the agent config; put its ACP subcommand or flag in "args"`);return{adapterType:"acp",command:n,adapterHint:"acp/base",enableSessionBinding:!0}}default:throw new Error(`Unsupported client_type: ${a}`)}}function v(a,e){return String(a??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function He(a){return b(A.data,`session-bindings-${v(a,"unknown")}.json`)}function Fe(a,e){return b(A.data,`session-bindings-${v(a,e)}.json`)}function We(a,e){return b(A.data,`active-events-${v(a,e)}.json`)}function Ke(a){return b(A.data,`pending-events-${v(a,"unknown")}.json`)}function ze(a,e){const n=v(a,"agent"),t=v(e,"unknown");return b(A.data,`terminal-outbox-${n}-${t}.json`)}function Qe(...a){const e=[],n=new Set;for(const t of a)for(const s of t??[]){const i=String(s??"").trim(),c=i.toLowerCase();!i||n.has(c)||(n.add(c),e.push(i))}return e.length>0?e:void 0}function Ve(a,e){const n={claude:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0},"deepseek-harness":{maxConcurrent:1,maxQueued:99,queueTimeoutMs:0}},t=n[a]??n.acp;let s=e?.max_concurrent??t.maxConcurrent??1;return a==="acp"&&s>1&&(m.warn("manager",`ACP adapter supports only one active run at a time; clamping max_concurrent from ${s} to 1`),s=1),{maxConcurrent:s,maxQueued:e?.max_queued??t.maxQueued??99,queueTimeoutMs:e?.queue_timeout_ms??t.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function Xe(a,e={}){const n=_e(),t=String(a.client_type??"").trim().toLowerCase(),s=Be(t,a),i=t==="deepseek"?a.dsh?.integration_mode??"profile_bridge":void 0,c=i==="embedded_jsonrpc",o=String(a.ws_url??"").trim(),u=typeof a.name=="string"?a.name:"",r=u.trim(),l="get_session_usage",g="get_rate_limits",p="get_agent_global_config",d=Ie;if(!r)throw new Error("agent name is required");if(u!==r)throw new Error(`agent name must not contain leading or trailing whitespace: "${u}"`);if(!o)throw new Error(`agent ${a.name}: ws_url is required`);if(!a.agent_id?.trim())throw new Error(`agent ${a.name}: agent_id is required`);if(!a.api_key?.trim())throw new Error(`agent ${a.name}: api_key is required`);const h=s.adapterType,_=h==="acp",w=t==="qwen",y={...s.options??{}};if(h==="deepseek-harness"&&(y.integrationMode=i,y.dshProfile=a.dsh?.profile?.trim()||"web",y.autoInstallBridge=a.dsh?.auto_install_bridge??!c,y.autoStartProfile=a.dsh?.auto_start_profile??!c),h==="deepseek-harness"&&a.provider?.model?.trim()&&(y.defaultModel=a.provider.model.trim()),a.codex_config_overrides!==void 0){if(h!=="codex")throw new Error(`agent ${a.name}: codex_config_overrides is only supported for client_type=codex`);je(a.codex_config_overrides,`agent ${a.name}: codex_config_overrides`),y.codexConfigOverrides=a.codex_config_overrides}if(a.acp_new_session_params!==void 0){if(!_)throw new Error(`agent ${a.name}: acp_new_session_params is only supported for ACP-based client types`);const f=a.acp_new_session_params;if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`agent ${a.name}: acp_new_session_params must be a JSON object`);const k=Object.keys(f).find(le=>Le.has(le));if(k)throw new Error(`agent ${a.name}: acp_new_session_params cannot set reserved field "${k}" (Grix owns cwd/mcpServers/sessionId/additionalDirectories on every session/new)`);y.newSessionParams=f}if(t==="zeroclaw"){const k=a.acp_new_session_params?.agentAlias;if(typeof k!="string"||!k.trim()||k.trim().startsWith("<REPLACE"))throw new Error(`agent ${a.name}: client_type=zeroclaw requires acp_new_session_params.agentAlias (create one with \`zeroclaw agents create <alias>\` and set it in the agent config); without it session/new fails with -32602 and the connector would silently respawn-retry forever`)}if(h==="codex"&&a.provider?.wire_api!==void 0){const f=a.provider;if(f.wire_api!=="responses"||!f.base_url?.trim()||!f.api_key?.trim()||!f.model?.trim()||!f.catalog_version?.trim()||!f.catalog_sha256?.trim()||!f.catalog_json?.trim())throw Object.assign(new Error(`agent ${a.name}: incomplete Codex direct relay config`),{code:"INVALID_CODEX_DIRECT_CONFIG"});const k=Ne(A.data,a.name);y.codexHome=k,y.codexDirect={codexHome:k,config:{baseUrl:f.base_url.trim(),model:f.model.trim(),...f.reasoning_effort?.trim()?{reasoningEffort:f.reasoning_effort.trim()}:{},token:f.api_key.trim()},catalog:{version:f.catalog_version.trim(),sha256:f.catalog_sha256.trim(),json:f.catalog_json}}}const S=h==="codex"?{capabilities:["stream_chunk","local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",l,g]}:null,Z=h==="claude"?{localActions:["session_control","set_mode","set_model","set_reasoning_effort","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",l,g]}:null,T=w?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",l],adapterHint:"qwen/base"}:null,M=h==="pi"?{adapterHint:"pi/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","get_context","file_list","create_folder",l,g]}:null,x=h==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder"]}:null,D=h==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder","thread_compact","claude_interaction_reply",g]}:null,N=h==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",l]}:null,R=h==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder"]}:null,O=h==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",g]}:null,j=h==="deepseek-harness"?{adapterHint:c?"deepseek/jsonrpc-v1":"deepseek/grix-bridge-v1",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_provider","set_model","set_mode","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile",l,g,"exec_approve","exec_reject","permission_approve","permission_reject","file_list","create_folder","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals"]}:null,q=new Set(["hermes","reasonix","kimi","copilot","acp","qodercli","qoderclicn","mcode","dim","traecli","grok","qwenpaw","zeroclaw","codebuddy"]),ee=_&&!q.has(t),te=_&&!w?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","claude_interaction_reply","file_list","create_folder",...ee?[l]:[]]}:null,ne=t==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",l,g]}:null,se=h==="codex"||h==="claude"||h==="opencode"||h==="deepseek-harness"||t==="gemini"?["session_control","set_model","set_mode",...h==="deepseek-harness"?["set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill"]:[],...h==="claude"?["set_reasoning_effort"]:[]]:void 0,ae=h==="cursor"||h==="opencode"||h==="openhuman"||h==="agy"||_&&q.has(t)?[g]:[l,g];_&&y.raw_transport===void 0&&(y.raw_transport=t==="gemini");const re=`${t}/base`,C=ke(h,t),ie=C==="kiro"?void 0:process.cwd(),L=Y(a.provider),I={...process.env,...s.env,...a.env};if(C==="hermes"&&!I.HERMES_HOME?.trim()){const f=$e(t,L);I.HERMES_HOME=Te({...f,...I},a.name)}const G=Ce({mode:C,projectDir:ie,env:I}),U=G.filter(f=>f.source==="connector").map(f=>f.name);U.length>0&&!e.quiet&&m.info("manager",`[${a.name}] injecting connector skills: [${U.join(", ")}]`);const B=be(G,A.skills);let oe=B.length>0?B:void 0;const ce=ve({skillsDir:A.skills,mode:C,home:H(),env:I});return{name:r,adapterType:h,aibot:{url:o,agentId:a.agent_id,apiKey:a.api_key,clientType:t,clientVersion:n,adapterHint:j?.adapterHint??s.adapterHint??T?.adapterHint??M?.adapterHint??x?.adapterHint??D?.adapterHint??R?.adapterHint??O?.adapterHint??re,capabilities:j?.capabilities??S?.capabilities??N?.capabilities??M?.capabilities??x?.capabilities??D?.capabilities??R?.capabilities??O?.capabilities??T?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:Qe(j?.localActions??S?.localActions??N?.localActions??Z?.localActions??M?.localActions??x?.localActions??D?.localActions??R?.localActions??O?.localActions??T?.localActions??ne?.localActions??te?.localActions??["exec_approve","exec_reject"],se,ae,["connector_rollback","connector_upgrade_push",p,"configure_gateway_provider","skill_upload","skill_delete","skill_enable","skill_disable","skill_refresh",...d]),skills:oe,librarySkills:ce,terminalOutboxPath:ze(a.name,a.agent_id)},agent:{command:c?"dsh-jsonrpc-agent":s.command,args:[...s.args??[],...a.args??[]],env:s.env?{...s.env,...a.env}:a.env,clientType:t,...L?{provider:L}:{}},adapterOptions:y,acpAuthMethod:y.auth_method,acpInitialMode:y.initial_mode,acpMcpTools:y.acp_mcp_tools,promptTimeoutMs:a.prompt_timeout_ms,bindingsPath:He(a.agent_id),legacyBindingsPath:Fe(a.name,a.agent_id),activeEventStorePath:We(a.name,a.agent_id),pendingEventStorePath:Ke(a.agent_id),...s.enableSessionBinding||_?{enableSessionBinding:!0}:{},...de(t)?{staticCwd:pe(a.cwd)}:{},...s.autoInjectArgs||t==="reasonix"&&a.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...t==="reasonix"&&a.provider?.model?.trim()?{model:a.provider.model.trim()}:{}}}:{},poolMaxSize:a.pool?.maxSize??(h==="deepseek-harness"?4:void 0),poolIdleTimeoutMs:a.pool?.idleTimeoutMs,eventQueue:Ve(h,a.event_queue),logDir:A.log,providerBaseUrl:a.provider_base_url?.trim()||void 0,providerApiKey:a.provider_api_key?.trim()||void 0}}function J(){const a=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):qe}function $(){const a=process.env.GRIX_AGENT_STOP_WAIT_MS,e=Number(a);return Number.isFinite(e)&&e>=500?Math.floor(e):Ge}function Ye(){return Math.min($(),Ue)}function P(a){if(a===null||typeof a!="object")return JSON.stringify(a)??"null";if(Array.isArray(a))return`[${a.map(P).join(",")}]`;const e=a;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${P(e[t])}`).join(",")}}`}function Je(a,e){return P(a)===P(e)}class Mt{options;instances=[];configMap=new Map;rawConfigMap=new Map;mutationTail=Promise.resolve();startingInstances=new Set;failedStartAgents=new Set;removingAgents=new Set;instanceGenerations=new WeakMap;sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;lifecycleAdmissionClosed=!1;deletedAgentCleanups=new Set;pendingPlatformDeletes=new Map;upgradeChecker=null;skillSyncer=null;globalConfigStore;configRepository=new X(A.config);sharedOwnersCache=new ge(A.data);installer=new De;relaySecretResolver;auditProducer=Oe();constructor(e={}){this.options=e}runMutation(e,n=[]){const t=this.mutationTail.catch(()=>{}).then(async()=>{if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});await this.retryPendingPlatformDeletesUnlocked();const s=new Set([...this.pendingPlatformDeletes.values()].map(c=>c.name)),i=n.find(c=>s.has(c.trim()));if(i)throw Object.assign(new Error(`Agent "${i}" is pending permanent platform-deletion cleanup`),{code:"AGENT_DELETE_PENDING"});return e()});return this.mutationTail=t.then(()=>{},()=>{}),t}async startTrackedInstance(e){this.startingInstances.add(e);try{await e.start()}finally{this.startingInstances.delete(e)}}requestStartCancellation(e){const n=e.requestStop;typeof n=="function"&&n.call(e)}async stopInstance(e,n,t=$()){let s;try{await Promise.race([e.stop(n),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`Agent "${e.name}" stop timed out after ${t}ms`),{code:"AGENT_STOP_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForLifecycleDrain(e,n,t=$()){let s;try{await Promise.race([Promise.allSettled([...e]).then(()=>{}),new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"LIFECYCLE_DRAIN_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}async waitForShutdownOperation(e,n,t){let s;try{return await Promise.race([e,new Promise((i,c)=>{s=setTimeout(()=>{c(Object.assign(new Error(`${n} timed out after ${t}ms`),{code:"SHUTDOWN_OPERATION_TIMEOUT"}))},t)})])}finally{s!==void 0&&clearTimeout(s)}}isActiveGeneration(e){const n=this.instanceGenerations.get(e);return!!n&&!n.retired&&this.instances.find(t=>t.name===n.name)===e}retireInstance(e){const n=this.instanceGenerations.get(e);n&&(n.retired=!0)}async start(e){return this.runMutation(()=>this.startUnlocked(e))}async startUnlocked(e){const n=e??A.config;this.configRepository=new X(n),m.info("manager",`Loading configs from ${n}`),Ee(),W(),this.globalConfigStore=new Se(b(A.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:t,fileErrors:s,skipped:i}=this.configRepository.scan();for(const r of s)m.error("manager",`Failed to load ${r.file}: ${r.error}`);for(const r of i)m.info("manager",`Skipped ${r}: not an agent config (no "agents" key)`);if(t.length===0&&s.length===0&&i.length===0){m.warn("manager",`No agent configurations found in ${n}; daemon idle (waiting for config). Add agents under this directory then run: grix-connector reload`);return}const c=[];let o=s.length;for(const{entry:r,file:l}of t)try{const g=this.toRuntimeInstanceConfig(r);c.push({config:g,entry:r,file:l}),m.info("manager",`Loaded ${g.name} (${g.adapterType??"acp"}) from ${l}`)}catch(g){const p=typeof r?.name=="string"?r.name:"<unknown>";m.error("manager",`Invalid agent config in ${l} (name=${p}): ${g}`),o++}c.length>0&&await we();let u=0;if(c.length>0){const r=J();m.info("manager",`Starting ${c.length} agent(s), startup wait=${r}ms`);const l=d=>{this.instances=this.instances.filter(h=>h!==d)},g=c.map(({config:d,entry:h,file:_})=>{const w=this.createConfiguredInstance(d);return this.instances.push(w),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:h,file:_}),{config:d,instance:w,startPromise:this.prepareProviderRuntime(d,h).then(()=>{if(this.stopping)throw this.requestStartCancellation(w),Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});return this.startTrackedInstance(w)})}}),p=await Promise.all(g.map(async d=>{const h=await new Promise(_=>{let w=!1;const y=setTimeout(()=>{w||(w=!0,_({kind:"timeout"}))},r);d.startPromise.then(()=>{w||(w=!0,clearTimeout(y),_({kind:"started"}))}).catch(S=>{w||(w=!0,clearTimeout(y),_({kind:"failed",error:S}))})});return{task:d,outcome:h}}));for(const{task:d,outcome:h}of p){if(h.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(h.kind==="failed"){if(E(h.error)){this.onAgentDeletedByPlatform(d.instance);continue}try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(_){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up partially started ${d.config.name}: ${_}`)}m.error("manager",`Failed to start ${d.config.name}: ${h.error}`);continue}u++,m.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{this.stopping||this.removingAgents.has(d.config.name)||this.isActiveGeneration(d.instance)&&(m.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config))}).catch(async _=>{if(E(_)){this.onAgentDeletedByPlatform(d.instance);return}if(!(this.stopping||this.removingAgents.has(d.config.name))&&this.isActiveGeneration(d.instance)){try{await this.stopInstance(d.instance),l(d.instance),this.failedStartAgents.delete(d.config.name)}catch(w){this.failedStartAgents.add(d.config.name),m.error("manager",`Failed to clean up delayed start ${d.config.name}: ${w}`)}m.error("manager",`Delayed start failed: ${d.config.name}: ${_}`)}})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-u);m.info("manager",`${d}/${c.length} agent(s) running now`)}u>0&&m.warn("manager",`${u} agent(s) still connecting in background`)}if(this.instances.length===0&&c.length>0)throw new Error("All agent configurations failed to start");await this.ensureAuxServices()}async ensureAuxServices(){if(this.stopping||this.configMap.size===0)return;const e=[...this.configMap.values()].map(n=>({apiKey:n.aibot.apiKey,wsUrl:n.aibot.url}));if(!this.upgradeChecker&&(this.upgradeChecker=new ye(e,()=>this.describeAnyPendingOrBackgroundWork(),()=>this.closeAllLifecycleAdmission(),{requestGracefulShutdown:this.options.requestGracefulShutdown,reopenLifecycleAdmission:()=>this.reopenAllLifecycleAdmission(),isConnected:()=>this.instances.length===0||this.instances.some(n=>n.getStatus().wsConnected),onTransactionSettled:this.options.onTransactionSettled}),await this.upgradeChecker.start(),this.stopping)){this.upgradeChecker.stop();return}this.skillSyncer||(this.skillSyncer=new Ae(e,A.skills),this.skillSyncer.setOnSyncSuccess(()=>this.refreshOwnerLibrarySkills()),await this.skillSyncer.start(),this.stopping&&this.skillSyncer.stop())}refreshOwnerLibrarySkills(){const e=new Map,n=t=>{let s;try{s=t.skillsSyncGroupKey()}catch(c){m.warn("manager",`skillsSyncGroupKey failed for ${t.name}: ${c}`);return}const i=e.get(s)??[];i.push(t),e.set(s,i)};for(const t of this.instances)n(t);for(const t of this.sharedInstances.values())n(t);for(const[t,s]of e){let i=!1;const c=[];for(const o of s){if(i){c.push(o);continue}let u=!1;try{u=o.forceRefreshSkills(void 0,{force:!0,ownerLibrarySync:!0})===!0}catch(r){m.warn("manager",`owner library skills reporter threw group=${t} agent=${o.name}: ${r}`)}if(u){i=!0;continue}m.warn("manager",`owner library skills reporter failed group=${t} agent=${o.name}; trying next`)}if(!i){m.warn("manager",`owner library skills: no reporter succeeded group=${t}`);continue}for(const o of c)try{o.adoptSkillsWireHashFromDisk()}catch(u){m.warn("manager",`adoptSkillsWireHashFromDisk failed for ${o.name}: ${u}`)}}}async stop(){m.info("manager","Stopping all agents..."),this.stopping=!0;const e=Ye(),n=Date.now()+e,t=()=>Math.max(1,n-Date.now()),s=new Set([...this.instances,...this.sharedInstances.values(),...this.startingInstances]);for(const o of s)this.requestStartCancellation(o);const i=new Map([...s].map(o=>[o,this.stopInstance(o,void 0,e)])),c=[];this.upgradeChecker?.stop(),this.skillSyncer?.stop();try{await this.waitForLifecycleDrain([this.mutationTail,...this.shareSyncChains.values(),...i.values()],"manager shutdown lifecycle drain",t())}catch(o){c.push(o)}this.upgradeChecker?.stop(),this.skillSyncer?.stop(),this.shareSyncChains.clear(),await Promise.all([...[...this.instances].map(async o=>{try{await(i.get(o)??this.stopInstance(o,void 0,t())),this.retireInstance(o),this.instances=this.instances.filter(u=>u!==o),this.startingInstances.delete(o)}catch(u){c.push(u)}}),...[...this.sharedInstances.entries()].map(async([o,u])=>{try{await(i.get(u)??this.stopInstance(u,void 0,t())),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o),this.startingInstances.delete(u)}catch(r){c.push(r)}})]);try{await this.waitForLifecycleDrain([this.retryPendingPlatformDeletesUnlocked(n)],"platform-delete shutdown drain",t())}catch(o){c.push(o)}try{await this.waitForShutdownOperation(Promise.resolve().then(()=>this.globalConfigStore?.flush()),"global config shutdown flush",t())}catch(o){c.push(o)}if(await this.auditProducer.stop({timeoutMs:Math.min(5e3,t())}).catch(()=>!1),W(),c.length>0)throw new AggregateError(c,"Failed to stop all agents completely");m.info("manager","All stopped")}onShareSet(e,n,t){if(this.stopping||this.removingAgents.has(n.name)||!this.isActiveGeneration(e))return;this.sharedOwnersCache.save(n.name,t);const i=(this.shareSyncChains.get(n.name)??Promise.resolve()).catch(()=>{}).then(()=>{if(!(this.stopping||this.removingAgents.has(n.name))&&this.isActiveGeneration(e))return this.syncSharedInstances(n,t,e)});this.shareSyncChains.set(n.name,i)}async syncSharedInstances(e,n,t){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))return;const{toAdd:s,toRemove:i}=ue(e.name,this.sharedInstances.keys(),n);for(const c of s){if(this.stopping||this.removingAgents.has(e.name)||t&&!this.isActiveGeneration(t))break;const o=me(e.name,c);let u;try{const r=he(e,c);u=new F(r,this.globalConfigStore,this.auditProducer),u.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),u.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),u.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.options.requestGracefulShutdown&&u.setDaemonShutdownRequester(this.options.requestGracefulShutdown),this.lifecycleAdmissionClosed&&u.closeLifecycleAdmission(),this.sharedInstances.set(o,u),await this.startTrackedInstance(u),u.forceRefreshSkills(void 0,{force:!0}),m.info("manager",`shared instance started: ${o}`)}catch(r){if(u&&!this.stopping&&!this.removingAgents.has(e.name))try{await this.stopInstance(u),this.sharedInstances.get(o)===u&&this.sharedInstances.delete(o)}catch(g){m.error("manager",`cleanup shared instance failed ${o}: ${g}`)}const l=r instanceof Error?r.message:String(r);/Auth failed/i.test(l)?(this.sharedOwnersCache.remove(e.name,c),m.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):m.error("manager",`start shared instance failed ${o}: ${r}`)}}for(const{key:c}of i){const o=this.sharedInstances.get(c);if(o)try{await this.stopInstance(o),this.sharedInstances.get(c)===o&&this.sharedInstances.delete(c),m.info("manager",`shared instance stopped: ${c}`)}catch(u){m.error("manager",`stop shared instance failed ${c}: ${u}`)}}}restoreCachedSharedInstances(e){const n=this.sharedOwnersCache.load(e.name);if(n.length===0)return;const t=this.instances.find(s=>s.name===e.name);!t||!this.isActiveGeneration(t)||(m.info("manager",`restoring ${n.length} cached shared instance(s) for ${e.name}`),this.onShareSet(t,e,n))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){return this.runMutation(()=>this.addAgentUnlocked(e),[String(e.name??"")])}async addAgentUnlocked(e){const n=this.toRuntimeInstanceConfig(e,{quiet:!0});if(this.instances.some(t=>t.name===n.name))throw new Error(`Agent "${n.name}" already exists`);this.configRepository.assertCanAdd(e),await this.addAgentInternal(e,"agents.json",{targetPersisted:!1});try{const t=this.configRepository.insert(e);this.rawConfigMap.set(e.name,t);const s=this.instances.find(c=>c.name===e.name),i=s?this.instanceGenerations.get(s):void 0;if(i){i.persisted=!0;const c=this.configMap.get(e.name);c&&this.restoreCachedSharedInstances(c)}}catch(t){try{await this.removeAgentInternal(e.name)}catch(s){throw new AggregateError([t,s],`Failed to persist and roll back agent "${e.name}"`)}throw t}await this.ensureAuxServices(),m.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,n,t){const s=this.toRuntimeInstanceConfig(e);if(this.instances.some(i=>i.name===s.name))throw new Error(`Agent "${s.name}" already exists`);await this.startInstanceFromConfig(s,e,n,t)}createConfiguredInstance(e,n=!0){const t=new F(e,this.globalConfigStore,this.auditProducer);return this.instanceGenerations.set(t,{name:e.name,agentId:e.aibot.agentId,persisted:n,retired:!1,platformDeletedObserved:!1}),t.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),this.options.requestGracefulShutdown&&t.setDaemonShutdownRequester(this.options.requestGracefulShutdown),t.setLifecycleBusyChecker(()=>this.describeAnyPendingOrBackgroundWork()),t.setLifecycleAdmissionCloser(()=>this.closeAllLifecycleAdmission()),t.setLifecycleAdmissionRestorer(()=>this.reopenAllLifecycleAdmission()),this.lifecycleAdmissionClosed&&t.closeLifecycleAdmission(),t.setInstallAgentHandler(s=>this.installAgent(s)),t.setRemoteAdminPorts({isEnabled:()=>this.remoteAdminGate?.()??!1,listInstallable:()=>this.listInstallable(),installAgent:s=>this.installAgent(s),getInstallProgress:s=>this.getInstallProgress(s),addAgent:s=>this.addAgent(s),probeAll:s=>this.probeAll(s)}),t.setShareSetHandler(s=>this.onShareSet(t,e,s)),t.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(t)),t.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),t.setProviderConfigHandler(s=>this.setAgentProvider(e.name,s)),t.setRelayStateApplyPorts({getLocalState:()=>this.relayStateApplier?.getLocalState(e.name)??{enabled:!1},getAppliedMode:()=>this.relayStateApplier?.getAppliedMode?.(e.name),applyEnable:(s,i)=>{const c=this.relayStateApplier;return c?c.applyEnable(e.name,s,i):Promise.reject(new Error("relay state applier is not configured"))},applyDisable:()=>{const s=this.relayStateApplier;return s?s.applyDisable(e.name):Promise.reject(new Error("relay state applier is not configured"))}}),t.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),t.setProviderResolver(()=>Y(this.getAgentProvider(e.name))),t}describeAnyPendingOrBackgroundWork(){return[...this.instances.flatMap(e=>e.describePendingOrBackgroundWork()),...[...this.sharedInstances.values()].flatMap(e=>e.describePendingOrBackgroundWork())]}closeAllLifecycleAdmission(){this.lifecycleAdmissionClosed=!0;for(const e of this.instances)e.closeLifecycleAdmission();for(const e of this.sharedInstances.values())e.closeLifecycleAdmission()}reopenAllLifecycleAdmission(){if(!this.stopping){this.lifecycleAdmissionClosed=!1;for(const e of this.instances)e.openLifecycleAdmission();for(const e of this.sharedInstances.values())e.openLifecycleAdmission()}}async prepareProviderRuntime(e,n){const t=this.resolveAgentProvider(n.provider);K(n.client_type)&&t?.base_url?.trim()&&t?.api_key?.trim()&&t?.model?.trim()&&await z(e.name,{baseUrl:t.base_url.trim(),apiKey:t.api_key.trim(),model:t.model.trim()})}async startInstanceFromConfig(e,n,t,s){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});if(await this.prepareProviderRuntime(e,n),this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"MANAGER_STOPPING"});const i=this.createConfiguredInstance(e,s.targetPersisted);this.instances.push(i);const c=this.startTrackedInstance(i),o=J(),u=await new Promise(p=>{let d=!1;const h=setTimeout(()=>{d||(d=!0,p({kind:"timeout"}))},o);c.then(()=>{d||(d=!0,clearTimeout(h),p({kind:"started"}))},_=>{d||(d=!0,clearTimeout(h),p({kind:"failed",error:_}))})}),r=this.instanceGenerations.get(i);if(r?.platformDeletedObserved&&!r.persisted){const p=new fe(`Agent "${e.name}" was deleted before its local configuration commit`);try{await this.stopInstance(i),this.retireInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){throw this.failedStartAgents.add(e.name),new AggregateError([p,d],`Failed to clean up uncommitted deleted agent "${e.name}"`)}throw p}if(u.kind==="started"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),this.failedStartAgents.delete(e.name),s.targetPersisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.();return}if(u.kind==="timeout"){this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t}),m.warn("manager",`Start pending for ${e.name}, continue retrying in background`),c.then(async()=>{if(!this.removingAgents.has(e.name)&&this.isActiveGeneration(i)){if(this.stopping){try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i)}catch(p){this.failedStartAgents.add(e.name),m.error("manager",`Failed to stop late-started ${e.name}: ${p}`)}return}this.failedStartAgents.delete(e.name),this.instanceGenerations.get(i)?.persisted&&this.restoreCachedSharedInstances(e),this.relayEnvSettledHandler?.(),m.info("manager",`Delayed start succeeded: ${e.name}`)}},async p=>{if(E(p)){this.onAgentDeletedByPlatform(i);return}if(!(this.stopping||this.removingAgents.has(e.name))&&this.isActiveGeneration(i)){try{await this.stopInstance(i),this.instances=this.instances.filter(d=>d!==i),this.failedStartAgents.delete(e.name)}catch(d){this.failedStartAgents.add(e.name),m.error("manager",`Failed to clean up delayed start ${e.name}: ${d}`)}m.error("manager",`Delayed start failed ${e.name}: ${p}`)}}).catch(p=>{m.error("manager",`Delayed start finalizer failed ${e.name}: ${p}`)});return}const l=u.error;E(l)&&this.onAgentDeletedByPlatform(i);let g;try{await this.stopInstance(i),this.instances=this.instances.filter(p=>p!==i),this.failedStartAgents.delete(e.name)}catch(p){g=p,this.failedStartAgents.add(e.name)}throw s.targetPersisted&&(this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:n,file:t})),g!==void 0?new AggregateError([l,g],`Failed to start and clean up agent "${e.name}"`):l}async removeAgent(e){return this.runMutation(()=>this.removeAgentUnlocked(e),[e])}async removeAgentUnlocked(e){if(!(this.instances.some(t=>t.name===e)||this.rawConfigMap.has(e)||[...this.sharedInstances.keys()].some(t=>t.startsWith(`${e}#shared:`))))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});this.configRepository.remove(e),await this.removeAgentInternal(e),m.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,n){this.removingAgents.add(e);try{const t=()=>n?.deadlineMs===void 0?$():Math.max(1,n.deadlineMs-Date.now()),s=this.instances.findIndex(p=>p.name===e),i=s===-1?void 0:this.instances[s],c=`${e}#shared:`,o=n?.keepShareCache?void 0:{dropPendingEvents:!0},u=new Map;i&&(this.requestStartCancellation(i),this.startingInstances.has(i)&&u.set(i,this.stopInstance(i,o,t())));for(const[p,d]of this.sharedInstances)p.startsWith(c)&&(this.requestStartCancellation(d),this.startingInstances.has(d)&&u.set(d,this.stopInstance(d,o,t())));const r=this.shareSyncChains.get(e);this.shareSyncChains.delete(e);const l=[];try{await this.waitForLifecycleDrain([...r?[r]:[],...u.values()],`agent "${e}" shared lifecycle drain`,t())}catch(p){l.push(p)}const g=[];for(const[p,d]of[...this.sharedInstances.entries()])p.startsWith(c)&&g.push((u.get(d)??this.stopInstance(d,o,t())).then(()=>{this.sharedInstances.get(p)===d&&this.sharedInstances.delete(p),this.startingInstances.delete(d)}).catch(h=>{l.push(h),m.error("manager",`stop shared instance failed ${p}: ${h}`)}));if(i)try{await(u.get(i)??this.stopInstance(i,o,t())),this.retireInstance(i);const p=this.instances.indexOf(i);p!==-1&&this.instances.splice(p,1),this.startingInstances.delete(i)}catch(p){l.push(p)}if(await Promise.all(g),!n?.keepShareCache){const p=Q(e).catch(()=>{});if(n?.deadlineMs===void 0)await p;else try{await this.waitForLifecycleDrain([p],`agent "${e}" relay shutdown`,t())}catch(d){l.push(d)}}if(l.length>0)throw new AggregateError(l,`Failed to stop agent "${e}" completely`);this.configMap.delete(e),this.rawConfigMap.delete(e),this.failedStartAgents.delete(e),n?.keepShareCache||this.sharedOwnersCache.delete(e)}finally{this.removingAgents.delete(e)}}onAgentDeletedByPlatform(e){const n=this.instanceGenerations.get(e);if(!n||(n.platformDeletedObserved=!0,this.requestStartCancellation(e),!n.persisted))return;const t={source:e,name:n.name,agentId:n.agentId};this.pendingPlatformDeletes.set(e,t),!this.stopping&&(this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),this.runMutation(async()=>{}).catch(()=>{}).finally(()=>{this.deletedAgentCleanups.delete(e)})))}async retryPendingPlatformDeletesUnlocked(e){if(this.pendingPlatformDeletes.size!==0)for(const[n,t]of[...this.pendingPlatformDeletes])try{await this.cleanupPlatformDeletedUnlocked(t,e),this.pendingPlatformDeletes.delete(n)}catch(s){m.error("manager",`cleanup for deleted agent "${t.name}" failed: ${s}`)}}async cleanupPlatformDeletedUnlocked(e,n){const{source:t,name:s,agentId:i}=e,c=this.instances.find(g=>g.name===s),o=c?this.instanceGenerations.get(c)?.agentId??String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim():void 0;if(c&&c!==t&&o!==i)return;m.warn("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`);const u=this.rawConfigMap.get(s),r=this.configMap.get(s),l=[];if(c&&o===i)try{await this.removeAgentInternal(s,{deadlineMs:n})}catch(g){l.push(g)}try{const g=this.configRepository.scan();if(g.fileErrors.length>0){const h=g.fileErrors.map(_=>`${_.file}: ${_.error}`).join("; ");throw new Error(`cannot inspect deleted agent generation [${h}]`)}const p=g.entries.filter(h=>String(h.entry?.name??"").trim()===s);if(!p.some(h=>String(h.entry?.agent_id??"").trim()!==i)&&p.length>0&&this.configRepository.remove(s),l.length===0){const h=String(this.rawConfigMap.get(s)?.entry.agent_id??"").trim();(!h||h===i)&&(this.rawConfigMap.delete(s),this.configMap.delete(s),this.failedStartAgents.delete(s))}}catch(g){l.push(g),u&&this.rawConfigMap.set(s,u),r&&this.configMap.set(s,r)}if(l.length>0)throw new AggregateError(l,`Failed to fully clean up deleted agent "${s}"`);m.info("manager",`Agent "${s}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406`)}isAgentBusy(e){return this.instances.find(t=>t.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const n=this.instances.find(t=>t.name===e);return n?(n.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}remoteAdminGate;setRemoteAdminGate(e){this.remoteAdminGate=e}relayStateApplier;setRelayStateApplier(e){this.relayStateApplier=e}reportRelayStateLocalChange(e){this.instances.find(t=>t.name===e)?.reportRelayStateLocalChange()}setRelaySecretResolver(e){this.relaySecretResolver=e}resolveAgentProvider(e){if(!e?.api_key_ref?.trim())return e;const n=e.api_key_ref.trim(),t=this.relaySecretResolver?.(n);if(!t)throw Object.assign(new Error(`relay credential "${n}" is unavailable`),{code:"RELAY_SECRET_UNAVAILABLE"});return{...e,api_key:t}}toRuntimeInstanceConfig(e,n={}){const t=this.resolveAgentProvider(e.provider);return Xe(t===e.provider?e:{...e,provider:t},n)}getAgentProvider(e){return this.resolveAgentProvider(this.rawConfigMap.get(e)?.entry.provider)}async restartAgent(e){return this.runMutation(()=>this.restartAgentUnlocked(e),[e])}async restartAgentUnlocked(e){const n=this.rawConfigMap.get(e);if(!n)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,n.entry,n.file),m.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,n,t){return this.runMutation(()=>this.setAgentProviderUnlocked(e,n,t),[e])}async setAgentProviderUnlocked(e,n,t){if(!this.rawConfigMap.get(e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const i=n?.api_key_ref?.trim()?Object.fromEntries(Object.entries(n).filter(([r])=>r!=="api_key")):n,c=this.configRepository.updateExisting(e,r=>{const l={...r};if(i===void 0)delete l.provider;else{const g=i.quota_api_key?.trim()||r.provider?.quota_api_key?.trim();l.provider=g?{...i,quota_api_key:g}:i}return this.toRuntimeInstanceConfig(l,{quiet:!0}),l}),o=c.entry;this.rawConfigMap.set(e,c);const u=String(o.client_type??"").trim().toLowerCase();try{K(u)&&(n?.base_url?.trim()&&n?.api_key?.trim()&&n?.model?.trim()?await z(e,{baseUrl:n.base_url.trim(),apiKey:n.api_key.trim(),model:n.model.trim()}):await Q(e))}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}if(t?.deferRestart){this.instances.find(r=>r.name===e)?.markRelayEnvStale(),m.info("manager",`Updated provider config for agent (deferred restart): ${e}`);return}try{await this.replaceInstance(e,o,c.file)}catch(r){throw this.failedStartAgents.add(e),this.instances.find(l=>l.name===e)?.markRelayEnvStale(),r}m.info("manager",`Updated provider config for agent: ${e}`)}hasDirectRelayConfig(e){const n=this.rawConfigMap.get(e)?.entry.provider;return!!(n?.api_key_ref?.trim()||n?.api_key?.trim())}getDirectRelayConfigAgentNames(){return[...this.rawConfigMap.entries()].filter(([,e])=>!!e.entry.provider&&(Pe(e.entry.client_type)||["claude","codex"].includes(String(e.entry.client_type??"").trim().toLowerCase()))).map(([e])=>e)}async fetchRelayCredential(e,n){const t=this.instances.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.fetchRelayCredential(n)}async clearDirectProviderConfigs(){const e=this.getDirectRelayConfigAgentNames(),n=[];for(const t of e)try{await this.setAgentProvider(t,void 0,{deferRestart:this.isAgentBusy(t)}),n.push(t)}catch(s){m.warn("manager",`Failed to clear provider config for "${t}": ${s instanceof Error?s.message:String(s)}`)}return n}async replaceInstance(e,n,t){const s=this.toRuntimeInstanceConfig(n);try{await this.removeAgentInternal(e,{keepShareCache:!0})}catch(o){throw this.failedStartAgents.add(e),o}const i=String(n.agent_id??"").trim();if([...this.pendingPlatformDeletes.values()].some(o=>o.name===e&&o.agentId===i))throw await this.retryPendingPlatformDeletesUnlocked(),Object.assign(new Error(`Agent "${e}" was permanently deleted while its instance was stopping`),{code:"AGENT_DELETE_PENDING"});try{await this.startInstanceFromConfig(s,n,t,{targetPersisted:!0})}catch(o){throw this.configMap.set(e,s),this.rawConfigMap.set(e,{entry:n,file:t}),o}}async reload(){return this.runMutation(()=>this.doReload())}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:n,skipped:t}=this.configRepository.scan();for(const r of t)m.info("manager",`reload: skipped ${r}: not an agent config (no "agents" key)`);if(n.length>0){const r=n.map(l=>`${l.file}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${n.length} config file(s) failed to parse [${r}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:r}of e)try{this.toRuntimeInstanceConfig(r,{quiet:!0})}catch(l){const g=r?.name,p=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:p,error:l instanceof Error?l.message:String(l)})}if(s.length>0){const r=s.map(l=>`${l.name}: ${l.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${r}]`),{code:"RELOAD_UNSAFE"})}const i=new Map,c=new Set([...this.pendingPlatformDeletes.values()].map(r=>r.name));for(const r of e){const l=String(r.entry?.name??"").trim();l&&(c.has(l)||(i.has(l)&&m.warn("manager",`reload: duplicate agent name "${l}", last one wins`),i.set(l,r)))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},u=new Set([...this.rawConfigMap.keys()].filter(r=>!c.has(r)));for(const r of u)if(!i.has(r))try{await this.removeAgentInternal(r),o.removed.push(r)}catch(l){o.failed.push({name:r,error:l instanceof Error?l.message:String(l)})}for(const[r,l]of i){const g=this.rawConfigMap.get(r);if(g)if(!Je(g.entry,l.entry)||!this.instances.some(p=>p.name===r)||this.failedStartAgents.has(r))try{await this.replaceInstance(r,l.entry,l.file),o.restarted.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}else this.rawConfigMap.set(r,l),o.unchanged.push(r);else try{await this.addAgentInternal(l.entry,l.file,{targetPersisted:!0}),o.added.push(r)}catch(p){o.failed.push({name:r,error:p instanceof Error?p.message:String(p)})}}return m.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),await this.ensureAuxServices(),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Ze(this.instances,e)}async probeOne(e,n={}){return et(this.instances,e,n)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const n=await this.installer.install(e);return Re(n),n}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Ze(a,e){const n=e.concurrency??4,t=Date.now(),s=new Array(a.length);await new Promise(r=>{let l=0,g=0;const p=a.length;if(p===0){r();return}function d(w){const y=a[w];y.probe(e).then(S=>{s[w]=S,h()},S=>{s[w]={agent_name:y.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:S?.message??String(S)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},h()})}function h(){g++,l<p?d(l++):g===p&&r()}const _=Math.min(n,p);for(let w=0;w<_;w++)d(l++)});const i=s.filter(r=>r.status==="healthy").length,c=s.filter(r=>r.status==="degraded").length,o=s.filter(r=>r.status==="unavailable").length,u=await V();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:c,unavailable:o,installed_clients:u,agents:s,probed_at:t,duration_ms:Date.now()-t}}async function et(a,e,n){const t=a.find(s=>s.name===e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return t.probe(n)}export{Mt as Manager,Y as normalizeAgentProviderForRuntime,V as probeInstalledClientCommands,Ze as probeInstances,et as probeOneInstance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as i from"node:net";const e={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function n(o){const u={bind:o?.bind??e.bind,port:o?.port??e.port,endpoint:o?.endpoint??e.endpoint,sessionTimeoutMs:o?.sessionTimeoutMs??e.sessionTimeoutMs,invokeTimeoutMs:o?.invokeTimeoutMs??e.invokeTimeoutMs,allowedOrigins:o?.allowedOrigins,allowedHosts:o?.allowedHosts};return s(u.bind),u.port!==0&&t(u.port),r(u.sessionTimeoutMs),u}function s(o){if(!o||!i.isIPv4(o)&&!i.isIPv6(o))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${o}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function t(o){if(!Number.isInteger(o)||o<1||o>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(o){if(!Number.isInteger(o)||o<1e3||o>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{n as createDefaultGatewayConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const r=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(
|
|
1
|
+
import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(t,e,r,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,r);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(t.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${t.status}`);if(p(e))return this.executeEventTool(t,e,r);const o=i(e,r);try{const u=await t.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(t){if(t==null||typeof t!="object")return this.successResult(t??null);const e=t,r=typeof e.code=="number"?e.code:0;if(r===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${r}]: ${n}`)}successResult(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}errorResult(t){return{content:[{type:"text",text:t}],isError:!0}}async executeEventTool(t,e,r){return e==="grix_access_control"?this.executeAccessControl(t,r):d(t,e,r)}async executeAccessControl(t,e){const r=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[r];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${r}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await t.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TOOLS as
|
|
1
|
+
import{TOOLS as s,EVENT_TOOLS as t}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...s.filter(o=>e.has(o.name)),...t.filter(o=>r.has(o.name))],this.toolMap=new Map(this.tools.map(o=>[o.name,o]))}getTools(){return this.tools}getTool(o){return this.toolMap.get(o)}hasTool(o){return this.toolMap.has(o)}}export{a as ToolRegistryImpl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(
|
|
1
|
+
const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(u,t){const e=C[u];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${u}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,r]of Object.entries(t)){if(r==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,r,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(u,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${u} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${u} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const r=t[i];if(e.items.type==="string"&&typeof r!="string")return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.type==="integer"){if(typeof r!="number"||!Number.isInteger(r))return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.enum&&!e.items.enum.includes(r))return`\u53C2\u6570 ${u}[${i}] \u503C ${r} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "grix-connector",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.18.0",
|
|
4
4
|
"description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|