grix-connector 4.14.0 → 4.15.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 +7 -7
- package/dist/adapter/agy/model-list.js +2 -2
- package/dist/adapter/agy/quota.js +5 -5
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.15.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/bridge.js +2 -2
- package/dist/bridge/toolbar-meta.js +1 -1
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.14.0.tgz +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{spawn as F}from"node:child_process";import{randomUUID as
|
|
2
|
-
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=
|
|
1
|
+
import{spawn as F}from"node:child_process";import{randomUUID as L}from"node:crypto";import{EventEmitter as G}from"node:events";import{existsSync as C,readFileSync as I,statSync as B,mkdirSync as N,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 _}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 st(g){return/^API error \(attempt \d+\):/.test(g.trim())}function it(g,t,e,i){return g===0&&st(t)&&(e.trim().length>0||i)}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,w=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","\u91CD\u8981\uFF1A\u4F60\u7684\u56DE\u590D\u5FC5\u987B\u8C03\u7528 grix \u7684 `grix_message_send` \u5DE5\u5177\u53D1\u9001\uFF08sessionId \u53D6\u81EA channel \u7684 chat_id\uFF0Ccontent \u4E3A\u4F60\u7684\u56DE\u590D\u5185\u5BB9\uFF09\uFF0C","\u4E0D\u8981\u53EA\u628A\u7B54\u6848\u6253\u5370\u5230\u6807\u51C6\u8F93\u51FA\u2014\u2014\u53EA\u6709\u8C03\u7528\u5DE5\u5177\u624D\u4F1A\u628A\u6D88\u606F\u771F\u6B63\u53D1\u7ED9\u7528\u6237\u3002","grix_message_send \u4F1A\u8FD4\u56DE\u4F60\u521A\u53D1\u51FA\u6D88\u606F\u7684 msg_id\u3002\u9700\u8981\u65F6\u4F60\u53EF\u4EE5\u7528\u8FD9\u4E2A ID \u505A\u540E\u7EED\u64CD\u4F5C\uFF0C\u4F8B\u5982\u8C03\u7528 grix_message_unsend\uFF08\u4F20 msgId\uFF09\u64A4\u56DE\u67D0\u6761\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 Ct extends G{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,i){super(),this.config=t,this.callbacks=e,this.runtimeResolver=i}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");N(V(e),{recursive:!0});let i={};try{C(e)&&(i=JSON.parse(I(e,"utf8")))}catch{}const s=i.mcpServers&&typeof i.mcpServers=="object"?i.mcpServers:{};J(s,this.internalApi.url),s[t.name]={command:t.command,args:t.args},i.mcpServers=s,K(e,`${JSON.stringify(i,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,i){this.touchActivity();let s=e;ft.has(t)&&this.activeEventSessionId&&(s.session_id==null||s.session_id==="")&&(s={...s,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(s)}:void 0;r&&d&&r.toolInvocations.push(d);try{const o=await this.callbacks.agentInvoke(t,s,i);return d&&(d.completedAt=new Date().toISOString(),d.result=W(o)),ut.has(t)&&this.activeEventId&&(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{_(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??L()}async resumeSession(t,e){}async destroySession(t){this.systemInstructionInjectedSessions.delete(t),this.identityInjectedSessions.delete(t)}onAgentProfileChanged(){this.identityInjectedSessions.clear()}sendPrompt(t){const e=new G;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{_(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{_(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 i=!!(e.stdout&&!e.stdout.destroyed),s=!!(e.stderr&&!e.stderr.destroyed);return i&&s}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 i;if(e.logPath)try{i=B(e.logPath).size}catch{}const s=this.sessionConversationMap.get(e.sessionId)??e.conversationId;this.completedAuditBoundaries.set(t,{adapterType:"agy",...s?{providerSessionId:s}:{},...e.cwd?{cwd:e.cwd}:{},...e.logPath?{transcriptPath:e.logPath,transcriptStartOffset:e.logStartOffset??0,transcriptEndOffset:i??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{_(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,"--api-url",this.internalApi.url]}}processEvent(t){const{event_id:e,session_id:i}=t,s=this.runtimeResolver(i);if(!s.cwd){a.warn(c,`No working directory for session ${i}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,i);return}this.activeEventId=e,this.activeEventSessionId=i,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,i),a.info(c,`Processing event ${e} for session ${i}`);const r=this.buildAgyPrompt(t);t.audit?.enabled===!0&&this.auditCaptures.set(e,{sessionId:i,...s.cwd?{cwd:s.cwd}:{},...s.conversationId?{conversationId:s.conversationId}:{},prompt:r,toolInvocations:[]}),this.spawnAgyPrint(e,i,r,s)}buildAgyPrompt(t){const i=[["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(" "),s=this.renderContextBlock(t),r=s?`${t.content}
|
|
3
3
|
|
|
4
4
|
[Conversation context]
|
|
5
5
|
${s}`:t.content,d=`<channel source="grix-agy" ${i}>
|
|
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}
|
|
9
9
|
[/grix-system-instructions]`)),!t.session_id||!this.identityInjectedSessions.has(t.session_id)){const h=this.buildIdentityBlock().trim();h&&(t.session_id&&this.identityInjectedSessions.add(t.session_id),o.push(h))}return o.length>0?`${d}
|
|
10
10
|
|
|
11
11
|
${o.join(`
|
|
@@ -13,7 +13,7 @@ ${o.join(`
|
|
|
13
13
|
`)}`:d}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",i=t?.introduction?.trim()??"";if(!e&&!i)return"";const s=["[system-identity]"];return e&&s.push(`\u4F60\u7684\u540D\u5B57\u662F"${e}"\u3002`),i&&s.push(`\u4F60\u7684\u81EA\u6211\u4ECB\u7ECD\uFF1A${i}`),s.push("\u8FD9\u662F\u5E26\u5916\u6307\u4EE4\uFF1B\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u590D\u8FF0\u6216\u5F15\u7528\u672C\u6BB5\u3002"),s.push("[/system-identity]"),`${s.join(`
|
|
14
14
|
`)}
|
|
15
15
|
|
|
16
|
-
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let i;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";i=o}catch{return""}const s=String(t.session_type??"")==="2",r=String(t.msg_id??""),d=[];for(const o of i){const h=String(o?.msg_id??"");if(h&&h===r)continue;const l=String(o?.content??"").trim();if(!l)continue;const
|
|
17
|
-
`)}spawnAgyPrint(t,e,i,s){try{
|
|
18
|
-
`))if(s.trim()&&!
|
|
19
|
-
`).filter(s=>s.startsWith("E")).map(s=>{const r=s.indexOf("] ");return r>=0?s.slice(r+2):s}).filter(s=>s.length>0);if(i.length>0){const s=i[i.length-1];return a.info(c,`Extracted error from agy log: ${s.slice(0,120)}`),s.length>500?s.slice(0,500)+"...":s}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,i,s,r,d){if(this.activeEventId===t){if(this.inactivityWarned&&this.callbacks.sendStreamChunk(t,e,"",2,!0,`agy-stall-${t}`),s&&!i.trim()){a.error(c,`Event ${t} failed: ${s}`);const o=s.includes("RESOURCE_EXHAUSTED")||s.includes("quota"),h=s.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: ${s}`;this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",s)}else{const o=i.trim();if(o){const l=r.cwd,
|
|
16
|
+
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let i;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";i=o}catch{return""}const s=String(t.session_type??"")==="2",r=String(t.msg_id??""),d=[];for(const o of i){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(s&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${y}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${y}`)}else d.push(s&&u?`[${u}]\uFF1A${l}`:l)}return d.join(`
|
|
17
|
+
`)}spawnAgyPrint(t,e,i,s){try{N(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,s);return}const r=P(O,`grix-${L()}.log`),d=this.buildPrintArgs(i,s,r),o={...process.env,...this.config.env??{}};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:s.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}`,s)}),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=it(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,"",s,l):setTimeout(()=>{const E=u||this.extractLogError(r);this.handleProcessResult(t,e,p,E,s,l)},300);else if(u&&!m)this.handleProcessResult(t,e,"",u,s,l);else if(n!==0){const E=A.trim()||`process exited with code ${n}`;this.handleProcessResult(t,e,p,E,s,l)}else p.trim()?this.handleProcessResult(t,e,p,"",s,l):this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",s,l):setTimeout(()=>{const E=this.extractLogError(r);this.handleProcessResult(t,e,p,E,s,l)},300)}),T.stdin?.end();const b=this.auditCaptures.get(t);b&&(b.logPath=r,b.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 ${w}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${w}ms after turn end (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{_(this.activeProcess,"SIGKILL")}catch{}}},w),this.watchdogGraceTimer.unref());return}if(this.scanTurnLogActivity(e),this.inFlightToolName||this.inactivityWarned)return;const i=Date.now()-this.lastActivityAt;if(i<this.inactivityTimeoutMs)return;this.inactivityWarned=!0;const s=Math.max(1,Math.round(i/6e4));a.warn(c,`No activity for ${Math.round(i/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 ${s} \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 ${w}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${w}ms after result event (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{_(this.activeProcess,"SIGKILL")}catch{}}},w),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 i=e.subarray(this.watchLogOffset).toString("utf-8");this.watchLogOffset=e.length;for(const s of i.split(`
|
|
18
|
+
`))if(s.trim()&&!ct.some(r=>s.includes(r))){a.debug(c,`turn log activity: ${s.slice(0,120)}`),this.touchActivity();return}}watchLogHasTurnEndMarker(t){try{return I(t,"utf-8").includes(ot)}catch{return!1}}buildPrintArgs(t,e,i){const s=["--print-timeout",dt,"--log-file",i],r=e.modelId?tt(e.modelId,Z()):"";return r&&s.push("--model",r),e.cwd&&s.push("--add-dir",e.cwd),s.push("--dangerously-skip-permissions"),e.conversationId&&s.push("--conversation",e.conversationId),s.push("--output-format","stream-json"),s.push("-p",t),s}readAgyConversationId(t){try{if(C(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(!C(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 i=e.split(`
|
|
19
|
+
`).filter(s=>s.startsWith("E")).map(s=>{const r=s.indexOf("] ");return r>=0?s.slice(r+2):s}).filter(s=>s.length>0);if(i.length>0){const s=i[i.length-1];return a.info(c,`Extracted error from agy log: ${s.slice(0,120)}`),s.length>500?s.slice(0,500)+"...":s}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,i,s,r,d){if(this.activeEventId===t){if(this.inactivityWarned&&this.callbacks.sendStreamChunk(t,e,"",2,!0,`agy-stall-${t}`),s&&!i.trim()){a.error(c,`Event ${t} failed: ${s}`);const o=s.includes("RESOURCE_EXHAUSTED")||s.includes("quota"),h=s.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: ${s}`;this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",s)}else{const o=i.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 i=this.conversationOutputCache.get(e);return i&&t.startsWith(i)?t.slice(i.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e){if(this.completedEventIds.add(e),this.completedEventIds.size>1e3){const i=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let s=500;s<i.length;s++)this.completedEventIds.add(i[s])}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{Ct as AgyAdapter};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)){const
|
|
1
|
+
import{spawn as w}from"node:child_process";import{mkdirSync as M}from"node:fs";import{dirname as x,join as N}from"node:path";import{resolveRuntimePaths as S}from"../../core/config/paths.js";import{log as d}from"../../core/log/index.js";import{readJSONFile as T,writeJSONFileAtomic as E}from"../../core/util/json-file.js";const u="agy-model-list",p=3600*1e3,b=1e4,C="agy-models-cache.json";let c=null,f=0,l=null;function y(t){return N(S(t).dataDir,C)}function g(t){if(!Array.isArray(t))return[];const e=new Set,o=[];for(const n of t){if(!n||typeof n!="object")continue;const r=n,s=String(r.id??"").trim(),a=String(r.displayName??"").trim();!s||!a||e.has(s)||(e.add(s),o.push({id:s,displayName:a}))}return o}function F(t){const e=T(y(t));return e?Array.isArray(e)?g(e):typeof e=="object"?g(e.models):[]:[]}async function _(t,e){const o=g(t);if(o.length===0)return;const n=y(e);M(x(n),{recursive:!0,mode:448}),await E(n,{models:o,updatedAt:Date.now()})}function v(t){return new Promise((e,o)=>{const n=w(t,["models"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});let r="",s="";const a=setTimeout(()=>{n.kill("SIGKILL"),o(new Error("agy models timed out"))},b);n.stdout?.on("data",i=>{r+=i.toString("utf-8")}),n.stderr?.on("data",i=>{s+=i.toString("utf-8")}),n.on("error",i=>{clearTimeout(a),o(i)}),n.on("close",i=>{clearTimeout(a),i===0?e(r):o(new Error(s.trim()||`agy models exited with code ${i}`))})})}function m(t){const e=t.trim(),o=e.indexOf(" ");if(o<0)return{slug:e,displayName:e};const n=e.slice(0,o).trim(),r=e.slice(o+1).trim();return{slug:n||r,displayName:r||n}}function h(t,e){const{slug:o,displayName:n}=m(t);if(!(!o&&!n))return e.find(r=>r.id===o||r.displayName===o||r.id===n||r.displayName===n)}function G(t,e=[]){const o=h(t,e);return o?o.displayName:m(t).displayName}function j(t,e){const o=h(t,e);return o?o.id:m(t).slug}function D(t){const e=new Set,o=[];for(const n of t.split(`
|
|
2
|
+
`)){const r=n.trim();if(!r||/^(Usage|Error|Flags|Available|Fetching)/i.test(r))continue;const{slug:s,displayName:a}=m(r);if(!a)continue;const i=s||a;e.has(i)||(e.add(i),o.push({id:i,displayName:a}))}return o}function A(t){return l||(l=(async()=>{try{const e=await v(t),o=D(e);o.length>0?(c=o,f=Date.now(),await _(o).catch(n=>{d.warn(u,`failed to persist agy models cache: ${n instanceof Error?n.message:n}`)}),d.info(u,`refreshed agy models: ${o.length} entries`)):d.info(u,"agy models returned no parsable entries, keeping cached/persisted fallback")}catch(e){d.info(u,`agy models failed, using cached/persisted fallback: ${e instanceof Error?e.message:e}`)}finally{l=null}})(),l)}function z(t){return(!c||Date.now()-f>=p)&&t&&A(t),P()}function P(){return c??F()}async function J(t,e=!1){if(!t)return;const o=!c||Date.now()-f>=p;!e&&!o||await A(t)}function U(t=null){c=t,f=t?Date.now():0,l=null}export{P as getAgyModelCatalog,z as getCachedAgyModels,h as matchAgyModel,D as parseAgyModels,J as primeAgyModels,F as readPersistedAgyModels,U as resetAgyModelCacheForTests,y as resolveAgyModelCachePath,G as resolveAgyModelFlag,j as resolveAgyToolbarModelId,_ as writePersistedAgyModels};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`)[0]??"",10);return Number.isFinite(t)?t:null}catch{return null}}async function
|
|
3
|
-
`)){const r=n.match(/:(\d+)\s+\(LISTEN\)/);if(r)return parseInt(r[1],10)}}catch{}return null}async function
|
|
4
|
-
`)){if(!n.includes(`pid=${e}`))continue;const r=n.match(/[*\d.]+:(\d+)\s/);if(r)return parseInt(r[1],10)}}catch{}return null}async function
|
|
5
|
-
`);for(let r=n.length-1;r>=0;r--){const s=n[r];if(!s.includes("RESOURCE_EXHAUSTED"))continue;const i=s.match(
|
|
1
|
+
import{execFile as W}from"node:child_process";import{existsSync as $,readdirSync as v,readFileSync as H}from"node:fs";import*as Q from"node:https";import{homedir as N}from"node:os";import{join as T}from"node:path";import{promisify as Y}from"node:util";import{log as x}from"../../core/log/index.js";const h=Y(W),S="agy-quota",I=300*1e3,X=35e3,j=5e3,z="Claude/GPT 5H",J="Claude/GPT weekly",K="Gemini 4 Argon 5H",V="Gemini 4 Argon weekly";let p=null,A=0,g=null;function Fe(e="agy"){return(!p||Date.now()-A>=I)&&P(e),p??{}}async function Ue(e="agy"){await P(e)}async function P(e="agy",t=!1){return!t&&p&&Date.now()-A<I?p:g||(g=(async()=>{try{const n=await Z(e);return p=n,A=Date.now(),n}catch(n){x.info(S,`fetch failed: ${n instanceof Error?n.message:n}`);const r=await ce();return p=r,A=Date.now(),r}finally{g=null}})(),g)}async function Z(e){const{stdout:t}=await h(e||"agy",["--print-timeout","30s","--output-format","json","-p","/usage"],{timeout:X,maxBuffer:1048576});return ee(t,Date.now())}function ee(e,t=Date.now()){let n;try{n=JSON.parse(e)}catch{throw new Error("agy usage output is not valid JSON")}const r=w(n),s=w(r.command);if(r.status!=="SUCCESS"||s.name!=="usage")throw new Error("agy usage output is not a successful usage command");const i=w(s.data),o=te(i.groups),c=ne(o);if(!c)throw new Error("agy usage output has no usable rate-limit buckets");return{rateLimits:c,sampledAt:t}}function te(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=w(n),s=String(r.name??"").trim(),i=r.buckets;if(Array.isArray(i))for(const o of i){const c=w(o),u=String(c.id??"").trim(),f=String(c.name??"").trim(),a=Number(c.remaining_fraction);!u||!Number.isFinite(a)||t.push({id:u,name:f,...s?{groupName:s}:{},window:c.window,remaining_fraction:a,reset_time:c.reset_time})}}return t}function ne(e){const t=e.find(s=>C(s)&&E(s)),n=e.find(s=>C(s)&&M(s));if(!t||!n)return null;const r=[];for(const s of e){if(s===t||s===n)continue;const i=se(s);i&&r.push({id:s.id,label:i,...b(s,E(s)?300:10080)})}return{primary:b(t,300),secondary:b(n,10080),credits:{hasCredits:!1,unlimited:!1,balance:null},...r.length>0?{extras:r}:{}}}function b(e,t){return{usedPercent:ie((1-e.remaining_fraction)*100),windowMinutes:t,resetsAt:re(e.reset_time)}}function re(e){if(typeof e=="string")return e.trim()||null;if(typeof e=="number"&&Number.isFinite(e)){const t=e>1e10?e:e*1e3;return new Date(t).toISOString()}return null}function ie(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Number(e.toFixed(2)))):0}function se(e){const t=E(e),n=M(e);return!t&&!n?null:oe(e)?t?z:J:D(e)?t?K:V:null}function C(e){return y(e).includes("gemini")&&!D(e)}function D(e){return y(e).includes("argon")}function oe(e){const t=y(e);return t.includes("claude")||t.includes("gpt")||t.includes("openai")}function E(e){if(R(e.window)===300)return!0;const n=y(e);return/\b5\s*h(?:our)?s?\b/.test(n)||n.includes("five_hour")||n.includes("5h")}function M(e){if(R(e.window)===10080)return!0;const n=y(e);return n.includes("weekly")||n.includes("week")||n.includes("7d")||n.includes("seven_day")}function R(e){if(typeof e=="number"&&Number.isFinite(e))return e>10080?Math.round(e/60):Math.round(e);if(typeof e!="string")return null;const t=e.trim().toLowerCase(),n=Number(t);if(Number.isFinite(n))return n>10080?Math.round(n/60):Math.round(n);const r=t.match(/^(\d+(?:\.\d+)?)\s*(m|min|minute|minutes|h|hr|hour|hours|d|day|days|w|week|weeks)$/);if(!r)return null;const s=Number(r[1]),i=r[2];return Number.isFinite(s)?i.startsWith("m")?Math.round(s):i==="h"||i==="hr"||i.startsWith("hour")?Math.round(s*60):i==="d"||i.startsWith("day")?Math.round(s*24*60):Math.round(s*7*24*60):null}function y(e){return`${e.groupName??""} ${e.id} ${e.name} ${String(e.window??"")}`.toLowerCase()}function w(e){return e&&typeof e=="object"?e:{}}async function ce(){const e=await ue().catch(r=>(x.info(S,`legacy fallback failed: ${r instanceof Error?r.message:r}`),{})),t=ke(),n={...e};return Object.keys(e).length>0?n.quota_exhausted=t.exhausted:t.exhausted&&(n.quota_exhausted=!0),t.resetAt&&(n.quota_reset_at=t.resetAt),n}async function ue(){const e=await le();if(!e)return{};const t=await pe(e.port,e.csrfToken);return t?(x.info(S,`language server fallback: plan=${t.plan}, reset_at=${t.quota_reset_at}`),t):{}}async function le(){if(process.platform==="win32")return null;try{const e=await fe();if(!e)return null;const t=await ae(e);if(!t)return null;const n=t.match(/--csrf_token\s+([0-9a-f-]+)/i);if(!n)return null;const r=await me(e);return r?{pid:e,port:r,csrfToken:n[1]}:null}catch{return null}}async function fe(){try{const{stdout:e}=await h("pgrep",["-f","language_server.*--csrf_token"],{timeout:3e3}),t=parseInt(e.trim().split(`
|
|
2
|
+
`)[0]??"",10);return Number.isFinite(t)?t:null}catch{return null}}async function ae(e){try{const{stdout:t}=await h("ps",["-p",String(e),"-o","args="],{timeout:3e3});return t.trim()||null}catch{return null}}async function me(e){return process.platform==="darwin"?F(e):await de(e)??F(e)}async function F(e){try{const{stdout:t}=await h("lsof",["-p",String(e),"-a","-i","TCP","-s","TCP:LISTEN"],{timeout:3e3});for(const n of t.split(`
|
|
3
|
+
`)){const r=n.match(/:(\d+)\s+\(LISTEN\)/);if(r)return parseInt(r[1],10)}}catch{}return null}async function de(e){try{const{stdout:t}=await h("ss",["-tlnp"],{timeout:3e3});for(const n of t.split(`
|
|
4
|
+
`)){if(!n.includes(`pid=${e}`))continue;const r=n.match(/[*\d.]+:(\d+)\s/);if(r)return parseInt(r[1],10)}}catch{}return null}async function pe(e,t){const n=he(new Uint8Array(0));return new Promise(r=>{let s=!1,i;const o=u=>{s||(s=!0,clearTimeout(c),r(u))},c=setTimeout(()=>{i.destroy(),o(null)},j);i=Q.request({hostname:"localhost",port:e,path:"/exa.language_server_pb.LanguageServerService/GetUserStatus",method:"POST",headers:{"Content-Type":"application/grpc-web+proto",Accept:"application/grpc-web+proto","x-codeium-csrf-token":t,"Content-Length":n.length},rejectUnauthorized:!1},u=>{const f=[];u.on("data",a=>f.push(a)),u.on("end",()=>{if(u.statusCode!==200){o(null);return}o(ge(new Uint8Array(Buffer.concat(f))))}),u.on("error",()=>o(null))}),i.on("error",()=>o(null)),i.write(Buffer.from(n)),i.end()})}function he(e){const t=new Uint8Array(5+e.length);return t[0]=0,new DataView(t.buffer).setUint32(1,e.length,!1),t.set(e,5),t}function ge(e){try{if(e.length<6)return null;const t=e[1]<<24|e[2]<<16|e[3]<<8|e[4];if(t<=0||5+t>e.length)return null;const n=e.slice(5,5+t),[r,s,i]=m(n,0);if(r!==1||s!==2)return null;const[o,c]=l(n,i),u=n.slice(c,c+o);return ye(u)}catch{return null}}function ye(e){const t={};let n=0;for(;n<e.length;){const[r,s,i]=m(e,n);if(n=i,n>=e.length&&s!==0)break;if(s===0){const[,o]=l(e,n);n=o}else if(s===2){const[o,c]=l(e,n),u=e.slice(c,c+o);if(n=c+o,r===36){const f=we(u);f[3]&&(t.plan=f[3])}else if(r===33){if(!t.quota_reset_at){const a=_e(u);a&&(t.quota_reset_at=a)}const f=xe(u);f!==void 0&&(t.available_credits=f)}}else if(s===1)n+=8;else if(s===5)n+=4;else break}return t}function we(e){const t={};let n=0;for(;n<e.length;){const[r,s,i]=m(e,n);if(n=i,s===2){const[o,c]=l(e,n),u=e.slice(c,c+o);n=c+o;try{t[r]=new TextDecoder().decode(u)}catch{}}else if(s===0){const[,o]=l(e,n);n=o}else if(s===1)n+=8;else if(s===5)n+=4;else break}return t}function _e(e){let t=0;for(;t<e.length;){const[n,r,s]=m(e,t);if(t=s,r===2){const[i,o]=l(e,t),c=e.slice(o,o+i);if(t=o+i,n===1){const u=Ae(c);if(u)return u}}else if(r===0){const[,i]=l(e,t);t=i}else if(r===1)t+=8;else if(r===5)t+=4;else break}}function Ae(e){let t=0;for(;t<e.length;){const[n,r,s]=m(e,t);if(t=s,r===2){const[i,o]=l(e,t),c=e.slice(o,o+i);if(t=o+i,n===15)return Te(c)}else if(r===0){const[,i]=l(e,t);t=i}else if(r===1)t+=8;else if(r===5)t+=4;else break}}function Te(e){let t=0;for(;t<e.length;){const[n,r,s]=m(e,t);if(t=s,r===2){const[i,o]=l(e,t),c=e.slice(o,o+i);if(t=o+i,n===2){const[u,f,a]=m(c,0);if(u===1&&f===0){const[d]=l(c,a);if(d>1e9)return d}}}else if(r===0){const[,i]=l(e,t);t=i}else if(r===1)t+=8;else if(r===5)t+=4;else break}}function xe(e){let t=0;for(;t<e.length;){const[n,r,s]=m(e,t);if(t=s,r===2){const[i,o]=l(e,t),c=e.slice(o,o+i);if(t=o+i,n===3){const u=Se(c);if(u!==void 0)return u}}else if(r===0){const[,i]=l(e,t);t=i}else if(r===1)t+=8;else if(r===5)t+=4;else break}}function Se(e){let t=0;for(;t<e.length;){const[n,r,s]=m(e,t);if(t=s,r===2){const[i,o]=l(e,t),c=e.slice(o,o+i);if(t=o+i,n===1){const{creditType:u,creditAmount:f}=be(c);if(u===1&&f!==void 0)return f}}else if(r===0){const[,i]=l(e,t);t=i}else if(r===1)t+=8;else if(r===5)t+=4;else break}}function be(e){let t,n,r=0;for(;r<e.length;){const[s,i,o]=m(e,r);if(r=o,i===0){const[c,u]=l(e,r);r=u,s===1?t=c:s===2&&(n=c)}else if(i===2){const[c,u]=l(e,r);r=u+c}else if(i===1)r+=8;else if(i===5)r+=4;else break}return{creditType:t,creditAmount:n}}function l(e,t){let n=0,r=0;for(;t<e.length;){const s=e[t++];if(n|=(s&127)<<r,r+=7,!(s&128))break}return[n,t]}function m(e,t){const[n,r]=l(e,t);return[n>>3,n&7,r]}const L=process.platform==="win32"?T(process.env.APPDATA??N(),".gemini","antigravity-cli","log"):T(N(),".gemini","antigravity-cli","log"),Ee=/RESOURCE_EXHAUSTED.*?Resets in (?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/,Le=/^[EWID](\d{2})(\d{2})\s+(\d{2}):(\d{2}):(\d{2})/;function ke(){try{if(!$(L))return{exhausted:!1};const e=v(L).filter(t=>t.endsWith(".log")).sort().reverse().slice(0,3);for(const t of e){const n=Ne(T(L,t));if(n.exhausted)return n}}catch{}return{exhausted:!1}}function Ne(e){try{const n=H(e,"utf-8").split(`
|
|
5
|
+
`);for(let r=n.length-1;r>=0;r--){const s=n[r];if(!s.includes("RESOURCE_EXHAUSTED"))continue;const i=s.match(Ee);if(!i)continue;const o=parseInt(i[1]??"0",10),c=parseInt(i[2]??"0",10),u=parseInt(i[3]??"0",10),f=o*3600+c*60+u,a=s.match(Le);let d;if(a&&f>0){const U=parseInt(a[1],10),B=parseInt(a[2],10),G=parseInt(a[3],10),O=parseInt(a[4],10),q=parseInt(a[5],10),k=new Date,_=new Date(k.getFullYear(),U-1,B,G,O,q);_.getTime()>k.getTime()+6e4&&_.setFullYear(_.getFullYear()-1),d=Math.floor(_.getTime()/1e3)+f}return d!==void 0&&d<=Math.floor(Date.now()/1e3)?{exhausted:!1}:{exhausted:!0,resetAt:d}}}catch{}return{exhausted:!1}}export{Fe as getCachedAgyQuotaInfo,ne as mapAgyUsageBuckets,ee as parseAgyUsageCliOutput,ge as parseLegacyAgyGetUserStatusResponse,Ue as primeAgyQuotaInfo,P as refreshAgyQuotaInfo};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
3
|
+
"bridgeVersion": "4.15.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.15.0.tgz",
|
|
5
5
|
"size": 24182,
|
|
6
6
|
"unpackedSize": 96521,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "f602c51e1df47e47f999ae96253875585b1465d2",
|
|
8
|
+
"integrity": "sha512-TwUJlnnT9/IvxMf+p3Hn1vDDaK8WDIXa//TOYeLrm1HAxMD9cLTGlD9TV0GhB2CPH7orURS3RY28QejAvd3nuQ=="
|
|
9
9
|
}
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import k from"node:path";import{tmpdir as F}from"node:os";import{createHash as M,randomUUID as T}from"node:crypto";import{ConnectionManager as U}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as q}from"../core/aibot/types.js";import{ClaudeAdapter as $}from"../adapter/claude/index.js";import{CodexAdapter as H}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as W}from"../adapter/pi/index.js";import{AcpAdapter as S}from"../adapter/acp/index.js";import{OpenHumanAdapter as N}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as G}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as P}from"../adapter/opencode/index.js";import{AgyAdapter as D}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as K}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as w,SESSION_MODE_IDS as z}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as J}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as Y}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as X}from"../adapter/claude/model-list.js";import{applyProxyEnv as Z,getProxyManager as ee}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as te}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as ne}from"../core/config/provider-env.js";import{buildProviderEnv as ie}from"../core/config/provider-env.js";import{isClaudeDirectEnv as se,stripGrixRelayEnv as oe}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as re}from"./native-provider-sweep.js";import{scanCodexSessions as ae}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as de}from"../adapter/claude/session-scanner.js";import{resolveAcpAgentTypes as le,scanAcpSessions as ce,scanReasonixSessionTitles as he}from"../adapter/acp/session-scanner.js";import{scanPiSessions as ue}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as pe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as ge}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as fe}from"../adapter/opencode/session-scanner.js";import{agentIdOf as me}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as ve}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as _e,resolveClaudeLeafDirs as Se,resolveAcpLeafDirs as Ce,resolvePiLeafDirs as be,resolveCodeWhaleLeafDirs as Ae,resolveCursorLeafDirs as Ee,resolveOpenCodeLeafDirs as we,resolveDshLeafDirs as ye,resolveReasonixLeafDirs as Re}from"./session-scan-cache.js";import{log as h,ConversationLog as ke,AgentApiPacketLog as Te,BridgeEventLog as Pe,GRIX_PATHS as y}from"../core/log/index.js";import{routeSessionControlCommand as xe,routeSessionControlLocalAction as Le}from"./session-control-router.js";import{maybeOfferCliInstall as Me,handleCliInstallQuestionReply as $e,handleCliInstallInteractionReply as He,runConfirmedCliInstall as De}from"./cli-install-flow.js";import{handleEventCancel as Qe,waitForEventDone as Oe,handleAibotStop as Ie,killAndResumeStopSlot as Be,handleAibotRevoke as Fe}from"./event-stop.js";import{handleConfigureGatewayProvider as Ue,getAuditLocalActionHandler as qe,handleAuditLocalAction as We,handleConnectorRollback as Ne,getRelayStateSyncer as je,relayStateSyncOnConnect as Ge,reportRelayStateLocalChange as Ke,handleApplyRelayState as ze,fetchRelayCredential as Je,isSharedInstance as Ye}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as Ve,handleConnectorAdminLocalAction as Xe}from"./remote-admin.js";import{unbindSession as Ze,handleUnbindTextCommand as et,handleUnbindLocalAction as tt,handleListSessionsTextCommand as nt,handleListSessionsLocalAction as it,handleSyncHistoryLocalAction as st}from"./session-list.js";import{handleCodexSessionControlOpen as ot,handleSessionControlForPool as rt,handleSessionControlLocalActionForPool as at,handleCodexSessionControlLocalActionOpen as dt,handleCursorSessionControlLocalActionOpen as lt,handlePiSessionControlOpen as ct,handlePiSessionControlRestart as ht,handlePiSessionControlRestartLocalAction as ut,syncOpenCodeBinding as pt,isWorkspaceFreeClient as gt,isCwdLockedClient as ft,ensureDefaultBindingForWorkspaceFreeClient as mt,bindSessionForPool as vt,deferredCallbacks as _t,handleOpenHumanSessionControlOpen as St,handleCodeWhaleSessionControlOpen as Ct,handleCodeWhaleSessionControlLocalActionOpen as bt,handleDeepSeekSessionControlLocalActionOpen as At}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as Et}from"./cwd-policy.js";import{normalizeCustomToolbarItems as wt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as yt,handleThreadCompact as Rt}from"./session-usage.js";import{handleSkillDeleteLocalAction as kt,handleSkillUploadLocalAction as Tt,handleSkillEnableLocalAction as Pt,handleSkillRefreshLocalAction as xt,handleSkillDisableLocalAction as Lt,computeSkillReport as Mt,reportSessionSkills as $t,skillsSyncGroupKey as Ht,forceRefreshSkills as Dt,adoptSkillsWireHashFromDisk as Qt,buildLibrarySkillsReport as Ot,skillLookupEnv as It}from"./skill-actions.js";import{resolveToolbarSelection as Bt,persistToolbarSelection as O}from"./toolbar-selection.js";import{normalizeClaudeModeId as Ft,handleExecCommandOptions as Ut,resolveSessionModelId as qt,resolveSessionModeId as Wt,resolveCursorSessionModeId as Nt,resolveClaudeSessionEffort as jt,resolveClaudeSessionModeId as Gt,currentClaudeModeId as Kt,buildCursorToolbarMeta as zt,buildAgyToolbarMeta as Jt,buildAgyQuotaMeta as Yt,sendAgyBindingCard as Vt,refreshAndPushAgyQuota as Xt,handleAgySetModel as Zt,buildClaudeToolbarMeta as en}from"./toolbar-meta.js";import{resolveProviderQuotaSource as tn,maybeQueryProviderQuota as nn,startProviderQuotaTimer as sn,stopProviderQuotaTimer as on,refreshAndPushProviderQuota as rn,pushProviderQuotaToBindings as an,enrichProviderQuotaMeta as dn,providerQuotaMetaPayload as ln,refreshProviderQuotaForSession as cn,refreshQuotaAfterModelSwitch as hn,doRefreshQuotaAfterModelSwitch as un}from"./provider-quota.js";import{handleGetRateLimits as pn,resolveRateLimitWakeSessionId as gn,wakeRateLimitSlot as fn}from"./rate-limits.js";import{RevokeHandler as mn}from"./revoke-handler.js";import{AdapterPool as vn}from"./adapter-pool.js";import{parseSessionControlCommand as _n}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Sn,parseExecApprovalResolutionMessage as Cn,parseAgentQuestionReplyMessage as bn}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as An}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as En}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as wn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as yn}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as Rn,handleFileListLocalAction as kn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Tn,persistToolbarSelection as Pn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as xn,ensureImportedAgentSession as Ln,hasDiskScanner as Mn,normalizePathForCompare as $n,providerKeyForAdapter as Hn,resolveAgentSessionId as Dn,resolveOrphanTitle as Qn,setResolvedAgentSessionId as On}from"./session-identity.js";import{buildDshOpenedToolbarMeta as In,dshCatalogDataRoot as Bn}from"./dsh-toolbar.js";import{ensureSlotStarted as Fn,failSessionOpen as Un,getClaudeWorkerStatus as qn,refreshClaudeWorkerStatusCard as Wn,resolveCwdForBinding as Nn}from"./session-open-helpers.js";import{handleAcpSetModel as jn,handleAcpSetMode as Gn,resolveAcpInitialDefaults as Kn}from"./acp-toolbar-persist.js";import{SessionBindingStore as zn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as Jn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Yn}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as Vn,buildInboundAttachmentsJson as Xn,materializeInboundAttachments as Zn}from"../core/protocol/inbound-attachments.js";import{ActiveEventStore as ei}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as ti}from"./pending-event-coordinator.js";import{LifecycleBarrier as ni}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ii}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as si,applyConnectorRuntimeConfigPatch as oi,extractConnectorRuntimeConfigPatch as ri}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ai,SendController as di}from"./send-controller.js";import{providerQuotaToRateLimits as li,providerQuotaToCodexRateLimits as ci}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as hi,buildLocalGrixCardLink as x}from"./tool-card-utils.js";import{planRawEventDelivery as ui,buildAuxiliaryDetailText as pi}from"./raw-event-delivery.js";import{DeferredEventManager as gi}from"./deferred-events.js";import{buildAgentProbeResult as fi,PROBE_CACHE_TTL_STATIC_MS as mi,PROBE_CACHE_TTL_FULL_MS as vi}from"./probe-helper.js";import{BridgeAuditController as _i}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Si,NoopAuditProducer as Ci}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as I,AuditPreparationFailedError as bi,AuditTurnScopeUnsupportedError as Ai}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as Ei,stripAuditOptions as wi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as yi}from"../audit/core/audit-session-registry.js";import{waitForIdle as Ri,formatWaitDuration as ki}from"../core/upgrade/idle-wait.js";const Ti=600*1e3,Pi=1800*1e3,xi=5*6e4,Li=60*1e3,Mi=4e3;function $i(L,e,t){const r=M("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return k.join(y.data,"audit-source","reasonix",`${r}.jsonl`)}const Hi=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),R=3;class Eo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new mn;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new di(si);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new ni;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;rejectedOutputEvents=new Set;blockedDispatchEvents=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=Li}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return tn(this,e)}maybeQueryProviderQuota(e=!1,t){return nn(this,e,t)}startProviderQuotaTimer(){sn(this)}stopProviderQuotaTimer(){on(this)}refreshAndPushProviderQuota(e=!1){return rn(this,e)}pushProviderQuotaToBindings(e,t=!1){an(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return dn(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return ln(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return cn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){hn(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return un(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||r)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>xi?{suspect:`admission held for ${ki(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return Ri({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:Pi,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let o=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,o=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),o||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),r?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",r=e.conversation?vi:mi;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",o=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(o,e.timeoutMs??1e4):void 0;let i;try{i=await fi({adapter:o,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{o.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",o=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||F(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof S)try{await e.bindSession(n,s)}catch{}let a=null;const l=new Promise(u=>{a=p=>{p===o&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:o,session_id:n,content:"ping",msg_id:o}),e.deliverStopEvent(o,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new Ci){this.config=e,this.auditController=new _i(r,{onAuditState:o=>{try{this.aibotHandle.sendAuditState(I(o,Date.now()))}catch{}}}),Si(r)&&r.addJobSettledHandler((o,s)=>{this.auditController.handleJobSettled(o,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ai[n]),this.aibotConfig={...e.aibot,...n==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...q]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new ke(e.logDir):null,this.packetLog=e.logDir?new Te(e.logDir):null,this.bindingStore=new zn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new gi(this.name),this.activeEventStore=e.activeEventStorePath?new ei(e.activeEventStorePath):null,this.pendingEvents=new ti(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(ae,_e);else if(n==="claude")this.sessionScanCache=new v(de,Se);else if(n==="pi"){const o=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>ue(void 0,o),()=>be(void 0,o))}else if(n==="codewhale")this.sessionScanCache=new v(pe,Ae);else if(n==="cursor")this.sessionScanCache=new v(ge,Ee);else if(n==="opencode"){const o=me(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new v(()=>fe(void 0,o),()=>we(void 0,o))}else if(n==="deepseek-harness"){const o=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>ve(o),()=>ye(o))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(he,Re));const o=le(e.aibot.clientType);this.sessionScanCache=o?new v(()=>ce(void 0,o),()=>Ce(void 0,o)):new v(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await re({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,s])=>String(s.cwd??""))}).then(s=>{s.length>0&&h.info(this.name,`restored native provider config after relay disable: ${s.join(", ")}`)}).catch(s=>{h.warn(this.name,`native provider residue sweep failed: ${s instanceof Error?s.message:String(s)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await X().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||r)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const o=this.config.adapterType??"acp";if(this.pool=new vn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},s=>{const i=this.createAdapter(o,s);return i instanceof S&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(s,a),this.sessionScanCache.invalidate()}),i},(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((s,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${s} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:s,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(s),this.pendingEvents.remove(s).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${s}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:s,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(s,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(s),this.pendingEvents.remove(s).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${s}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((s,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:i,...i?{ttl_ms:ii,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(s=>{this.handleSessionInternalError(s).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${s.eventId} session=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((s,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((s,i)=>{this.markAuditAdapterClosed(s,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((s,i,a)=>{const l=this.selfDrivenSessions.has(s),d=this.selfDrivenLabels.get(s);i?(this.selfDrivenSessions.add(s),a&&this.selfDrivenLabels.set(s,a),this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(s),this.selfDrivenLabels.delete(s),l&&this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(s)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${o}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],o=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{s=await this.pendingEvents.mergeForShutdown(o)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!s)for(const i of o){const a=i.event;h.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){h.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=ie(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(se(t)){const o=ee()?.getRuntimeInfo(),s={...r??{},...t},i=oe(s,{proxyUrl:o?.proxyUrl,caCertPath:o?.caCertPath,caBundlePath:o?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(ne(this.config.agent.clientType)){const o=te(this.name);o&&(n={...n??{},...o})}return Z(n,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(o,s,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(o,s,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Mi),sendThinking:(o,s,i)=>this.sendThinkingByRuntimeConfig(o,s,i),sendEventResult:(o,s,i,a)=>{this.sendEventResultWithCleanup(o,s,i,void 0,a)},sendRawEventEnvelope:(o,s,i,a)=>{const l=hi(i);if(l){this.sendToolExecutionCard(o,s,l);return}this.deliverRawEventEnvelope(o,s,i,"deepseek",a)},sendLocalActionResult:(o,s,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:o,status:s,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:o=>{this.sendGrixApprovalCard(o,"deepseek")},sendUpdateBindingCard:(o,s,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:s,cwd:i,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:o=>this.maybeQueryProviderQuota(o===!0,{providerId:"deepseek"}),agentInvoke:async(o,s,i)=>this.platformInvoke(o,s,i),eventToolInvoke:async(o,s)=>this.invokeDshEventTool(o,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:k.join(y.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const o=this.resolveCursorSessionModeId(e),s=o??"full_auto";o||this.bindingStore.setCursorModeId(e,s),t.mode=s,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,p,g)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,p,g)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{const c=d.questions.map(p=>p.header).join(", "),u=x(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:l,content:u,msg_type:1,extra:{card_type:"agent_question",summary_text:c}})},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new j({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,E.bindingMissing,!0),this.pool.removeSlot(e).catch(d=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${d instanceof Error?d.message:String(d)}`)});const l=this.resolveBindingChannelKey("claude");this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:x(i.message,"agent_open_session",{summary_text:i.message,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,p)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,p)},sendMedia:(i,a,l,d,c,u,p)=>{this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:p?{media_caption:d,...p}:{media_caption:d}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,C(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},o=this.config.adapterOptions??{},s={...o,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??z.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:o.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new $({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_terminal_fence_${i}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:i=>{if(!i)return;this.cachedCodexContextWindow=i,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},o=this.auditController.getAdapterPreparation(e),s=i=>Bt(this,"codex",e,i);return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:s("model")??n.model,collaborationMode:s("mode")??n.collaborationMode,reasoningEffort:s("reasoningEffort")??n.reasoningEffort,serviceTier:s("serviceTier")??n.serviceTier,sandboxMode:s("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:k.join(y.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),sendLocalActionResult:(n,o,s,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s,i,a)=>{this.sendRunErrorAsChunk(n,o,s,i,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:async(n,o,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,o,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s,0)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,o,s)=>{this.sendGrixAgentQuestionCard(n,o,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new P({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),forceCompleteInternalEvent:(n,o)=>{this.pool.eventComplete(n,o),this.pushQueueSnapshotForSession(o)},persistConversationId:(n,o)=>{this.bindingStore.setAgyConversationId(n,o)},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const o=this.bindingStore.get(n);return{cwd:o?.cwd,modelId:this.resolveSessionModelId(n),conversationId:o?.agyConversationId}};return new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,p,g,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,p,g,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,p,g)=>{this.sendEventResultWithCleanup(d,c,u,p,g)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,p,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...p?{error_code:p}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,p)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:p??""}});return}this.sendToolExecutionCard(d,c,C(u,p))},sendToolResult:(d,c,u,p)=>{this.sendToolExecutionCard(d,c,b(u,p))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(t){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${T()}`,p={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:p.content.length});try{this.aibotHandle.sendMsg(p),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(g){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:g instanceof Error?g.message:String(g)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,p)=>{const g={...p??{}};if(!g.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}!g.provider_quota&&this.cachedProviderQuota?.success&&(g.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Y(d,y.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const p="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:p,remainingPercentage:100-p}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),g.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,o=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&o?$i(this.name,e,o.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=Kn({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new S({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Pe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new U().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(o=>{h.error(this.name,`handleAibotEvent failed: ${o}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=o instanceof Error?o.message:String(o);this.handleStaleCwdError(n,s)||this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:s,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(o){h.error(this.name,`handleAibotStop failed: ${o}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(o){h.error(this.name,`agentDeletedHandler failed: ${o}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(o){h.error(this.name,`onShareSet failed: ${o}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(o){h.error(this.name,`onProfilePush failed: ${o}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(o){h.error(this.name,`onSkillSync failed: ${o}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(o=>{h.error(this.name,`handleAibotRevoke failed: ${o}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(o=>{h.error(this.name,`handleAibotLocalAction failed: ${o}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(o=>{h.error(this.name,`handleEventCancel failed: ${o}`)})}),this.aibotHandle.onMcpFrame((n,o)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(o):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const o=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const o=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],s=this.pool.reorderQueue(n.session_id,o);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${o} hold=${i} reason=${n.reason??""}`),!o||!s){this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(o,s,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${s} session_id=${o}`),!o||!s){this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(o,s,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const o of n)h.info(this.name,`Failing stale event on startup: ${o}`),this.aibotHandle.sendEventResult({event_id:o,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,o)=>{this.handleStreamRejected(n,o)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${o}`)});try{this.pool?.rejectEventOutput(e,r)}catch(o){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${o}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const o=String(e??"").trim(),s=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=o!==this.agentProfile.agentName||s!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:o,introduction:s},this.agentSystemPrompt=i,o||s?h.info(this.name,`agent profile (${r.source}): GOT name="${o}" intro_len=${s.length} system_prompt_len=${i.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof $),o=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-o.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${o.length} idle Claude slot(s), skipping ${s} busy`);for(const i of o)this.pool.removeSlot(i.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=t?t.running_items.map(s=>({event_id:s.event_id,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"stop"}]})):[],o=t?t.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...typeof s.content=="string"?{content:s.content}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},held:s.held===!0,held_reason:s.held_reason??"",actions:[{type:"cancel"}]})):[];if(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:o}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,r){if(e==="file_link")return Jn(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const o of n)this.rejectedOutputEvents.has(o)||this.blockedDispatchEvents.set(o,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=wt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=V(this.aibotHandle,e,t),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),o=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Yn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${T()}`,...o?{quoted_message_id:o}:{},extra:s.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.payload??{};return{ok:!0,file_name:s.file_name,attachment_type:s.attachment_type,access_url:s.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,r,n,o){const s=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,o),r&&this.conversationLog?.logOutbound?.(s,e,"reply",r)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:s,...i}=e;return i}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const n=t.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(r,n,o,s)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,o,t,!1,!1,s)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,o,s,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,o,s,i),(r||o)&&this.conversationLog?.logOutbound?.(a,e,o?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,o){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
|
|
1
|
+
import k from"node:path";import{tmpdir as F}from"node:os";import{createHash as M,randomUUID as T}from"node:crypto";import{ConnectionManager as U}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as q}from"../core/aibot/types.js";import{ClaudeAdapter as $}from"../adapter/claude/index.js";import{CodexAdapter as H}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as W}from"../adapter/pi/index.js";import{AcpAdapter as S}from"../adapter/acp/index.js";import{OpenHumanAdapter as N}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as G}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as P}from"../adapter/opencode/index.js";import{AgyAdapter as D}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as K}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as w,SESSION_MODE_IDS as z}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as J}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as Y}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as X}from"../adapter/claude/model-list.js";import{primeAgyModels as Z}from"../adapter/agy/model-list.js";import{applyProxyEnv as ee,getProxyManager as te}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ne}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as ie}from"../core/config/provider-env.js";import{buildProviderEnv as se}from"../core/config/provider-env.js";import{isClaudeDirectEnv as oe,stripGrixRelayEnv as re}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as ae}from"./native-provider-sweep.js";import{scanCodexSessions as de}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as le}from"../adapter/claude/session-scanner.js";import{resolveAcpAgentTypes as ce,scanAcpSessions as he,scanReasonixSessionTitles as ue}from"../adapter/acp/session-scanner.js";import{scanPiSessions as pe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as ge}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as fe}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as me}from"../adapter/opencode/session-scanner.js";import{agentIdOf as ve}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as _e}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as Se,resolveClaudeLeafDirs as Ce,resolveAcpLeafDirs as be,resolvePiLeafDirs as Ae,resolveCodeWhaleLeafDirs as Ee,resolveCursorLeafDirs as we,resolveOpenCodeLeafDirs as ye,resolveDshLeafDirs as Re,resolveReasonixLeafDirs as ke}from"./session-scan-cache.js";import{log as h,ConversationLog as Te,AgentApiPacketLog as Pe,BridgeEventLog as xe,GRIX_PATHS as y}from"../core/log/index.js";import{routeSessionControlCommand as Le,routeSessionControlLocalAction as Me}from"./session-control-router.js";import{maybeOfferCliInstall as $e,handleCliInstallQuestionReply as He,handleCliInstallInteractionReply as De,runConfirmedCliInstall as Qe}from"./cli-install-flow.js";import{handleEventCancel as Oe,waitForEventDone as Ie,handleAibotStop as Be,killAndResumeStopSlot as Fe,handleAibotRevoke as Ue}from"./event-stop.js";import{handleConfigureGatewayProvider as qe,getAuditLocalActionHandler as We,handleAuditLocalAction as Ne,handleConnectorRollback as je,getRelayStateSyncer as Ge,relayStateSyncOnConnect as Ke,reportRelayStateLocalChange as ze,handleApplyRelayState as Je,fetchRelayCredential as Ye,isSharedInstance as Ve}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as Xe,handleConnectorAdminLocalAction as Ze}from"./remote-admin.js";import{unbindSession as et,handleUnbindTextCommand as tt,handleUnbindLocalAction as nt,handleListSessionsTextCommand as it,handleListSessionsLocalAction as st,handleSyncHistoryLocalAction as ot}from"./session-list.js";import{handleCodexSessionControlOpen as rt,handleSessionControlForPool as at,handleSessionControlLocalActionForPool as dt,handleCodexSessionControlLocalActionOpen as lt,handleCursorSessionControlLocalActionOpen as ct,handlePiSessionControlOpen as ht,handlePiSessionControlRestart as ut,handlePiSessionControlRestartLocalAction as pt,syncOpenCodeBinding as gt,isWorkspaceFreeClient as ft,isCwdLockedClient as mt,ensureDefaultBindingForWorkspaceFreeClient as vt,bindSessionForPool as _t,deferredCallbacks as St,handleOpenHumanSessionControlOpen as Ct,handleCodeWhaleSessionControlOpen as bt,handleCodeWhaleSessionControlLocalActionOpen as At,handleDeepSeekSessionControlLocalActionOpen as Et}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as wt}from"./cwd-policy.js";import{normalizeCustomToolbarItems as yt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as Rt,handleThreadCompact as kt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Tt,handleSkillUploadLocalAction as Pt,handleSkillEnableLocalAction as xt,handleSkillRefreshLocalAction as Lt,handleSkillDisableLocalAction as Mt,computeSkillReport as $t,reportSessionSkills as Ht,skillsSyncGroupKey as Dt,forceRefreshSkills as Qt,adoptSkillsWireHashFromDisk as Ot,buildLibrarySkillsReport as It,skillLookupEnv as Bt}from"./skill-actions.js";import{resolveToolbarSelection as Ft,persistToolbarSelection as O}from"./toolbar-selection.js";import{normalizeClaudeModeId as Ut,handleExecCommandOptions as qt,resolveSessionModelId as Wt,resolveSessionModeId as Nt,resolveCursorSessionModeId as jt,resolveClaudeSessionEffort as Gt,resolveClaudeSessionModeId as Kt,currentClaudeModeId as zt,buildCursorToolbarMeta as Jt,buildAgyToolbarMeta as Yt,buildAgyQuotaMeta as Vt,sendAgyBindingCard as Xt,refreshAndPushAgyQuota as Zt,handleAgySetModel as en,buildClaudeToolbarMeta as tn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as nn,maybeQueryProviderQuota as sn,startProviderQuotaTimer as on,stopProviderQuotaTimer as rn,refreshAndPushProviderQuota as an,pushProviderQuotaToBindings as dn,enrichProviderQuotaMeta as ln,providerQuotaMetaPayload as cn,refreshProviderQuotaForSession as hn,refreshQuotaAfterModelSwitch as un,doRefreshQuotaAfterModelSwitch as pn}from"./provider-quota.js";import{handleGetRateLimits as gn,resolveRateLimitWakeSessionId as fn,wakeRateLimitSlot as mn}from"./rate-limits.js";import{RevokeHandler as vn}from"./revoke-handler.js";import{AdapterPool as _n}from"./adapter-pool.js";import{parseSessionControlCommand as Sn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Cn,parseExecApprovalResolutionMessage as bn,parseAgentQuestionReplyMessage as An}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as En}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as wn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as yn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as Rn}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as kn,handleFileListLocalAction as Tn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Pn,persistToolbarSelection as xn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as Ln,ensureImportedAgentSession as Mn,hasDiskScanner as $n,normalizePathForCompare as Hn,providerKeyForAdapter as Dn,resolveAgentSessionId as Qn,resolveOrphanTitle as On,setResolvedAgentSessionId as In}from"./session-identity.js";import{buildDshOpenedToolbarMeta as Bn,dshCatalogDataRoot as Fn}from"./dsh-toolbar.js";import{ensureSlotStarted as Un,failSessionOpen as qn,getClaudeWorkerStatus as Wn,refreshClaudeWorkerStatusCard as Nn,resolveCwdForBinding as jn}from"./session-open-helpers.js";import{handleAcpSetModel as Gn,handleAcpSetMode as Kn,resolveAcpInitialDefaults as zn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Jn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as Yn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Vn}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as Xn,buildInboundAttachmentsJson as Zn,materializeInboundAttachments as ei}from"../core/protocol/inbound-attachments.js";import{ActiveEventStore as ti}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as ni}from"./pending-event-coordinator.js";import{LifecycleBarrier as ii}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as si}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as oi,applyConnectorRuntimeConfigPatch as ri,extractConnectorRuntimeConfigPatch as ai}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as di,SendController as li}from"./send-controller.js";import{providerQuotaToRateLimits as ci,providerQuotaToCodexRateLimits as hi}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as ui,buildLocalGrixCardLink as x}from"./tool-card-utils.js";import{planRawEventDelivery as pi,buildAuxiliaryDetailText as gi}from"./raw-event-delivery.js";import{DeferredEventManager as fi}from"./deferred-events.js";import{buildAgentProbeResult as mi,PROBE_CACHE_TTL_STATIC_MS as vi,PROBE_CACHE_TTL_FULL_MS as _i}from"./probe-helper.js";import{BridgeAuditController as Si}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Ci,NoopAuditProducer as bi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as I,AuditPreparationFailedError as Ai,AuditTurnScopeUnsupportedError as Ei}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as wi,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Ri}from"../audit/core/audit-session-registry.js";import{waitForIdle as ki,formatWaitDuration as Ti}from"../core/upgrade/idle-wait.js";const Pi=600*1e3,xi=1800*1e3,Li=5*6e4,Mi=60*1e3,$i=4e3;function Hi(L,e,t){const r=M("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return k.join(y.data,"audit-source","reasonix",`${r}.jsonl`)}const Di=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),R=3;class yo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new vn;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new li(oi);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new ii;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;rejectedOutputEvents=new Set;blockedDispatchEvents=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=Mi}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return nn(this,e)}maybeQueryProviderQuota(e=!1,t){return sn(this,e,t)}startProviderQuotaTimer(){on(this)}stopProviderQuotaTimer(){rn(this)}refreshAndPushProviderQuota(e=!1){return an(this,e)}pushProviderQuotaToBindings(e,t=!1){dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return ln(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return cn(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return hn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){un(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return pn(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||r)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>Li?{suspect:`admission held for ${Ti(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return ki({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:xi,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let o=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,o=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),o||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),r?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",r=e.conversation?_i:vi;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",o=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(o,e.timeoutMs??1e4):void 0;let i;try{i=await mi({adapter:o,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{o.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",o=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||F(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof S)try{await e.bindSession(n,s)}catch{}let a=null;const l=new Promise(u=>{a=p=>{p===o&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:o,session_id:n,content:"ping",msg_id:o}),e.deliverStopEvent(o,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new bi){this.config=e,this.auditController=new Si(r,{onAuditState:o=>{try{this.aibotHandle.sendAuditState(I(o,Date.now()))}catch{}}}),Ci(r)&&r.addJobSettledHandler((o,s)=>{this.auditController.handleJobSettled(o,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(di[n]),this.aibotConfig={...e.aibot,...n==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...q]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new Te(e.logDir):null,this.packetLog=e.logDir?new Pe(e.logDir):null,this.bindingStore=new Jn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new fi(this.name),this.activeEventStore=e.activeEventStorePath?new ti(e.activeEventStorePath):null,this.pendingEvents=new ni(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(de,Se);else if(n==="claude")this.sessionScanCache=new v(le,Ce);else if(n==="pi"){const o=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>pe(void 0,o),()=>Ae(void 0,o))}else if(n==="codewhale")this.sessionScanCache=new v(ge,Ee);else if(n==="cursor")this.sessionScanCache=new v(fe,we);else if(n==="opencode"){const o=ve(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new v(()=>me(void 0,o),()=>ye(void 0,o))}else if(n==="deepseek-harness"){const o=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>_e(o),()=>Re(o))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(ue,ke));const o=ce(e.aibot.clientType);this.sessionScanCache=o?new v(()=>he(void 0,o),()=>be(void 0,o)):new v(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await ae({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,s])=>String(s.cwd??""))}).then(s=>{s.length>0&&h.info(this.name,`restored native provider config after relay disable: ${s.join(", ")}`)}).catch(s=>{h.warn(this.name,`native provider residue sweep failed: ${s instanceof Error?s.message:String(s)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await X().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}else(this.config.adapterType??"acp")==="agy"&&Z(this.config.agent.command).catch(()=>{});if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||r)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const o=this.config.adapterType??"acp";if(this.pool=new _n({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},s=>{const i=this.createAdapter(o,s);return i instanceof S&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(s,a),this.sessionScanCache.invalidate()}),i},(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((s,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${s} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:s,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(s),this.pendingEvents.remove(s).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${s}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:s,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(s,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(s),this.pendingEvents.remove(s).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${s}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((s,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:i,...i?{ttl_ms:si,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(s=>{this.handleSessionInternalError(s).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${s.eventId} session=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((s,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((s,i)=>{this.markAuditAdapterClosed(s,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((s,i,a)=>{const l=this.selfDrivenSessions.has(s),d=this.selfDrivenLabels.get(s);i?(this.selfDrivenSessions.add(s),a&&this.selfDrivenLabels.set(s,a),this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(s),this.selfDrivenLabels.delete(s),l&&this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(s)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${o}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],o=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{s=await this.pendingEvents.mergeForShutdown(o)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!s)for(const i of o){const a=i.event;h.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){h.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=se(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(oe(t)){const o=te()?.getRuntimeInfo(),s={...r??{},...t},i=re(s,{proxyUrl:o?.proxyUrl,caCertPath:o?.caCertPath,caBundlePath:o?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(ie(this.config.agent.clientType)){const o=ne(this.name);o&&(n={...n??{},...o})}return ee(n,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(o,s,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(o,s,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",$i),sendThinking:(o,s,i)=>this.sendThinkingByRuntimeConfig(o,s,i),sendEventResult:(o,s,i,a)=>{this.sendEventResultWithCleanup(o,s,i,void 0,a)},sendRawEventEnvelope:(o,s,i,a)=>{const l=ui(i);if(l){this.sendToolExecutionCard(o,s,l);return}this.deliverRawEventEnvelope(o,s,i,"deepseek",a)},sendLocalActionResult:(o,s,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:o,status:s,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:o=>{this.sendGrixApprovalCard(o,"deepseek")},sendUpdateBindingCard:(o,s,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:s,cwd:i,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:o=>this.maybeQueryProviderQuota(o===!0,{providerId:"deepseek"}),agentInvoke:async(o,s,i)=>this.platformInvoke(o,s,i),eventToolInvoke:async(o,s)=>this.invokeDshEventTool(o,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:k.join(y.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const o=this.resolveCursorSessionModeId(e),s=o??"full_auto";o||this.bindingStore.setCursorModeId(e,s),t.mode=s,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,p,g)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,p,g)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{const c=d.questions.map(p=>p.header).join(", "),u=x(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:l,content:u,msg_type:1,extra:{card_type:"agent_question",summary_text:c}})},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new j({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,E.bindingMissing,!0),this.pool.removeSlot(e).catch(d=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${d instanceof Error?d.message:String(d)}`)});const l=this.resolveBindingChannelKey("claude");this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:x(i.message,"agent_open_session",{summary_text:i.message,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,p)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,p)},sendMedia:(i,a,l,d,c,u,p)=>{this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:p?{media_caption:d,...p}:{media_caption:d}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,C(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},o=this.config.adapterOptions??{},s={...o,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??z.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:o.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new $({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_terminal_fence_${i}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:i=>{if(!i)return;this.cachedCodexContextWindow=i,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},o=this.auditController.getAdapterPreparation(e),s=i=>Ft(this,"codex",e,i);return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:s("model")??n.model,collaborationMode:s("mode")??n.collaborationMode,reasoningEffort:s("reasoningEffort")??n.reasoningEffort,serviceTier:s("serviceTier")??n.serviceTier,sandboxMode:s("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:k.join(y.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),sendLocalActionResult:(n,o,s,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s,i,a)=>{this.sendRunErrorAsChunk(n,o,s,i,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:async(n,o,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,o,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s,0)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,o,s)=>{this.sendGrixAgentQuestionCard(n,o,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new P({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),forceCompleteInternalEvent:(n,o)=>{this.pool.eventComplete(n,o),this.pushQueueSnapshotForSession(o)},persistConversationId:(n,o)=>{this.bindingStore.setAgyConversationId(n,o)},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const o=this.bindingStore.get(n);return{cwd:o?.cwd,modelId:this.resolveSessionModelId(n),conversationId:o?.agyConversationId}};return new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,p,g,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,p,g,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,p,g)=>{this.sendEventResultWithCleanup(d,c,u,p,g)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,p,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...p?{error_code:p}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,p)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:p??""}});return}this.sendToolExecutionCard(d,c,C(u,p))},sendToolResult:(d,c,u,p)=>{this.sendToolExecutionCard(d,c,b(u,p))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(t){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${T()}`,p={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:p.content.length});try{this.aibotHandle.sendMsg(p),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(g){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:g instanceof Error?g.message:String(g)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,p)=>{const g={...p??{}};if(!g.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}!g.provider_quota&&this.cachedProviderQuota?.success&&(g.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Y(d,y.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const p="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:p,remainingPercentage:100-p}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),g.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,o=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&o?Hi(this.name,e,o.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=zn({sessionBinding:n,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new S({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new xe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new U().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(o=>{h.error(this.name,`handleAibotEvent failed: ${o}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=o instanceof Error?o.message:String(o);this.handleStaleCwdError(n,s)||this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:s,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(o){h.error(this.name,`handleAibotStop failed: ${o}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(o){h.error(this.name,`agentDeletedHandler failed: ${o}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(o){h.error(this.name,`onShareSet failed: ${o}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(o){h.error(this.name,`onProfilePush failed: ${o}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(o){h.error(this.name,`onSkillSync failed: ${o}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(o=>{h.error(this.name,`handleAibotRevoke failed: ${o}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(o=>{h.error(this.name,`handleAibotLocalAction failed: ${o}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(o=>{h.error(this.name,`handleEventCancel failed: ${o}`)})}),this.aibotHandle.onMcpFrame((n,o)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(o):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const o=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const o=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],s=this.pool.reorderQueue(n.session_id,o);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${o} hold=${i} reason=${n.reason??""}`),!o||!s){this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(o,s,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${s} session_id=${o}`),!o||!s){this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(o,s,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const o of n)h.info(this.name,`Failing stale event on startup: ${o}`),this.aibotHandle.sendEventResult({event_id:o,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,o)=>{this.handleStreamRejected(n,o)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${o}`)});try{this.pool?.rejectEventOutput(e,r)}catch(o){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${o}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const o=String(e??"").trim(),s=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=o!==this.agentProfile.agentName||s!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:o,introduction:s},this.agentSystemPrompt=i,o||s?h.info(this.name,`agent profile (${r.source}): GOT name="${o}" intro_len=${s.length} system_prompt_len=${i.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof $),o=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-o.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${o.length} idle Claude slot(s), skipping ${s} busy`);for(const i of o)this.pool.removeSlot(i.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=t?t.running_items.map(s=>({event_id:s.event_id,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"stop"}]})):[],o=t?t.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...typeof s.content=="string"?{content:s.content}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},held:s.held===!0,held_reason:s.held_reason??"",actions:[{type:"cancel"}]})):[];if(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:o}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,r){if(e==="file_link")return Yn(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const o of n)this.rejectedOutputEvents.has(o)||this.blockedDispatchEvents.set(o,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=yt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=V(this.aibotHandle,e,t),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),o=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Vn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${T()}`,...o?{quoted_message_id:o}:{},extra:s.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.payload??{};return{ok:!0,file_name:s.file_name,attachment_type:s.attachment_type,access_url:s.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,r,n,o){const s=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,o),r&&this.conversationLog?.logOutbound?.(s,e,"reply",r)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:s,...i}=e;return i}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const n=t.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(r,n,o,s)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,o,t,!1,!1,s)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,o,s,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,o,s,i),(r||o)&&this.conversationLog?.logOutbound?.(a,e,o?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,o){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
|
|
2
2
|
|
|
3
|
-
Error: ${r}`,n,!1,o))}sendEventResultWithCleanup(e,t,r,n,o=!1){if(this.rejectedOutputEvents?.has(e))return;const s=this.blockedDispatchEvents?.get(e);this.blockedDispatchEvents?.delete(e),s&&t==="responded"&&(t="canceled",n=`agent_blocked_${s}`,r=`${s}: dispatch checkpoint saved; awaiting owner input`);const i=this.pool.getEventSessionId(e)??this.eventSessionIndex.get(e),a=r?.trim()??"";o&&this.markRunErrorSurfaced(e,a),t==="failed"&&i&&a&&this.sendRunErrorAsChunk(e,i,a);const l=t==="failed"&&a!==""&&(this.surfacedRunErrorTexts.get(e)?.has(a)??!1);if(this.auditController.markResponded(e,t,r),this.sendCtrl.finalizeOpenStreams(e),this.sendCtrl.sendEventResult(e,t,r,n,l),this.rejectedOutputEvents?.has(e))return;this.pool.cleanupEvent(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i??"-"} status=${t}`),i&&(this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,t,r)),this.eventSessionIndex.delete(e),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(c=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${c instanceof Error?c.message:String(c)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:r,errorMsg:n}=e;if(this.stopped||this.rejectedOutputEvents?.has(t))return;const o=this.inflightEvents.get(t);if(!o){h.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(t,r,n),this.sendEventResultWithCleanup(t,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,s);const i=this.config.adapterType??"acp";if(s>R){h.error(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} outcome=give-up err=${n}`);const c=`${i} agent kept failing after ${R} automatic restarts: ${n}`;this.sendRunErrorAsChunk(t,r,c),this.sendEventResultWithCleanup(t,"failed",c,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped||this.rejectedOutputEvents?.has(t)){for(const c of a)this.stopped||await this.pool.deliverInboundEvent(c);return}const l=e.replayOriginalContent?o.content:this.resolveRecoveryPrompt(i,o),d={...o,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${t} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(t,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,r){this.sendCtrl.sendThinking(e,t,r)}bufferStreamChunk(e,t,r,n,o){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,t,r,n,o)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const o=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const s=this.bindingStore.get(n.sessionId);s?.cwd?(await this.prepareBoundDeferredReplay(n,s.cwd),await this.deliverPendingReplayEvent(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(o),this.deferredMgr.defer(n.channel,n.sessionId,o),r.push(n))}else await this.deliverPendingReplayEvent(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)}catch(s){const i=s instanceof Error?s.message:String(s);h.error(this.name,`Pending event replay failed event=${o.event_id}: ${i}`),this.sendEventResultWithCleanup(o.event_id,"failed",i),this.pendingEvents.markCanceled(o.event_id),await this.pendingEvents.remove(o.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(t,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,r))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const r=Ei({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),o=this.auditController.startTurn({session:n,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});o&&(e.audit={...t,auditId:o.auditId,turnId:o.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const r=this.eventSessionIndex.get(e);return r?(r!==t&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${t}`),r):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,t,r,"acp",this.buildAcpRawEventFallbackText(r))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,r,n,o){const s=ui({envelope:r,fallbackText:o,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),i=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s.fallbackText,extra:{channel_data:{[n]:{raw_event:s.envelope}},agent_api_origin:!0}})};if(!s.sharded){i();return}h.info("bridge",`${n} raw_event oversized, sharded delivery: event=${e} fields=${s.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of s.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,pi({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);i()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,r,n){this.sendCtrl.sendToolExecutionCard(e,t,r,n)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${T()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,r){const n=r.questions.map(s=>s.header).join(", "),o=x(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:t,content:o,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const t=bn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,o=n instanceof S?"acp":n instanceof P?"opencode":this.config.adapterType??"unknown",s=n instanceof P?n.handleQuestionReplyEvent(t):n instanceof S?await n.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return s.delivered?(h.info(this.name,`[${o}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${o}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${s.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:s.errorCode??"interaction_reply_failed",msg:s.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=Cn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,o=t.params,s=String(o.tool_call_id??o.approval_command_id??o.approval_id??o.exec_context_id??""),i=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...o,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return i.delivered?(h.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${s||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${s||"-"} code=${i.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i.errorCode,msg:i.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.rejectedOutputEvents?.has(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const t=this.config.adapterType??"acp",r=_n(e);if(t==="claude"&&this.sendCtrl.hasTerminalResult(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}let n;if(r&&(n=this.lifecycleBarrier.tryEnter(`session-control:${r.verb}`)??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const o=ri(e.extra);if(o.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:o.error,updated_at:Date.now()});return}const s=o.patch,i=B(e.extra);if(An(this,e,t,i))return;if(r){await wn(this,r,e,t,i,this.config.agent.clientType??this.config.aibot.clientType);return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(c){this.sendAuditConfigurationError(e,c);return}if(await En(this,e,t,Hi.has(t),s,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,p,g]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(m=>m.name===p||m.name===`/${p}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await A.execCommand(p,g.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,p,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&Q(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof H&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,s,a);d.attachments_json=await Zn(d.attachments_json,{extraAllowedHosts:Vn(this.aibotConfig.url),logTag:this.name});try{const c=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!c)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}handleStaleCwdError(e,t){if(!/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(t)||!e.session_id)return!1;this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const n=this.pool.getSlot(e.session_id);n?.adapter instanceof S&&n.adapter.getSessionBindings().delete(e.session_id);const o=this.config.adapterType??"acp",s=this.resolveBindingChannelKey(o);return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:t,extra:{channel_data:{[s]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:e.msg_id}),!0}failUndeliveredInboundEvent(e,t){const r=t instanceof Error?t.message:String(t);h.warn(this.name,`Inbound event undelivered event=${e.event_id} session=${e.session_id}: ${r}`),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),!this.handleStaleCwdError(e,r)&&this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return ot(this,e,t)}handleSessionControlForPool(e,t){return rt(this,e,t)}handleSessionControlLocalActionForPool(e){return at(this,e)}handleCodexSessionControlLocalActionOpen(e){return dt(this,e)}handleCursorSessionControlLocalActionOpen(e){return lt(this,e)}handlePiSessionControlOpen(e,t){return ct(this,e,t)}handlePiSessionControlRestart(e){return ht(this,e)}handlePiSessionControlRestartLocalAction(e){return ut(this,e)}syncOpenCodeBinding(e,t){return pt(this,e,t)}isWorkspaceFreeClient(){return gt(this)}isCwdLockedClient(){return ft(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return mt(this,e,t)}bindSessionForPool(e,t){return vt(this,e,t)}deferredCallbacks(){return _t(this)}handleOpenHumanSessionControlOpen(e,t){return St(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Ct(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return bt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return At(this,e)}normalizeClaudeModeId(e){return Ft(this,e)}handleExecCommandOptions(e,t,r){Ut(this,e,t,r)}resolveSessionModelId(e){return qt(this,e)}resolveSessionModeId(e){return Wt(this,e)}resolveCursorSessionModeId(e){return Nt(this,e)}resolveClaudeSessionEffort(e){return jt(this,e)}resolveClaudeSessionModeId(e){return Gt(this,e)}currentClaudeModeId(e){return Kt(this,e)}buildCursorToolbarMeta(e){return zt(this,e)}buildAgyToolbarMeta(e,t){return Jt(this,e,t)}buildAgyQuotaMeta(e){return Yt(this,e)}sendAgyBindingCard(e,t,r){return Vt(this,e,t,r)}refreshAndPushAgyQuota(e,t=!1){return Xt(this,e,t)}handleAgySetModel(e,t){return Zt(this,e,t)}buildClaudeToolbarMeta(e){return en(this,e)}providerQuotaToCodexRateLimits(e){return ci(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return li(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return Nn(e)}failSessionOpen(e,t){return Un(this,e,t)}getClaudeWorkerStatus(e){return qn(this,e)}refreshClaudeWorkerStatusCard(e,t){return Wn(this,e,t)}async ensureSlotStarted(e,t=6e4){return Fn(this,e,t)}maybeOfferCliInstall(e){Me(this,e)}handleCliInstallQuestionReply(e){return $e(this,e)}handleCliInstallInteractionReply(e){return He(this,e)}runConfirmedCliInstall(e,t){return De(this,e,t)}handleSkillDeleteLocalAction(e){return kt(this,e)}handleSkillUploadLocalAction(e){return Tt(this,e)}handleSkillEnableLocalAction(e){return Pt(this,e)}handleSkillRefreshLocalAction(e){xt(this,e)}handleSkillDisableLocalAction(e){return Lt(this,e)}computeSkillReport(e){return Mt(this,e)}reportSessionSkills(e){$t(this,e)}skillsSyncGroupKey(){return Ht(this)}forceRefreshSkills(e,t){return Dt(this,e,t)}adoptSkillsWireHashFromDisk(){Qt(this)}buildLibrarySkillsReport(e){return Ot(this,e)}skillLookupEnv(){return It(this)}resolveOrphanTitle(e){return Qn(this,e)}resolveAgentSessionId(e){return Dn(this,e)}providerKeyForAdapter(){return Hn(this)}setResolvedAgentSessionId(e,t){On(this,e,t)}normalizePathForCompare(e){return $n(e)}ensureImportedAgentSession(e,t){Ln(this,e,t)}buildOpenedBindingResult(e,t,r="ready"){return xn(this,e,t,r)}buildDshOpenedToolbarMeta(e){return In(this,e)}dshCatalogDataRoot(){return Bn(this)}hasDiskScanner(){return Mn(this)}unbindSession(e){return Ze(this,e)}handleUnbindTextCommand(e){return et(this,e)}handleUnbindLocalAction(e){return tt(this,e)}handleListSessionsTextCommand(e){return nt(this,e)}handleListSessionsLocalAction(e){return it(this,e)}handleSyncHistoryLocalAction(e){return st(this,e)}handleSessionControlCommand(e,t){return xe(this,e,t)}handleSessionControlLocalAction(e){return Le(this,e)}handleEventCancel(e){return Qe(this,e)}waitForEventDone(e,t,r){return Oe(this,e,t,r)}handleAibotStop(e){Ie(this,e)}killAndResumeStopSlot(e,t){return Be(this,e,t)}handleAibotRevoke(e){return Fe(this,e)}handleConfigureGatewayProvider(e){return Ue(this,e)}getAuditLocalActionHandler(){return qe(this)}handleAuditLocalAction(e){return We(this,e)}handleConnectorRollback(e){return Ne(this,e)}getRelayStateSyncer(){return je(this)}relayStateSyncOnConnect(){Ge(this)}reportRelayStateLocalChange(){Ke(this)}handleApplyRelayState(e){return ze(this,e)}fetchRelayCredential(e){return Je(this,e)}handleConnectorAdminLocalAction(e){return Xe(this,e)}isSharedInstance(){return Ye(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${t} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let o;if(t===f.sessionControl&&(o=this.lifecycleBarrier.tryEnter(`local-action:${n||t}`)??void 0,!o)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===f.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(J(t)){await this.handleAuditLocalAction(e);return}const s=(this.config.adapterType??"acp")==="claude";if(t===f.sessionControl&&n===w.exec&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl&&n===w.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===f.sessionControl&&n===w.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===f.sessionControl&&n===w.unbind){if(this.isCwdLockedClient()){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.verbInvalid,error_msg:Et});return}await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const i=(this.config.adapterType??"acp")==="opencode";if((s&&(t===f.interactionReply||t==="exec_approve"||t==="exec_reject")||i&&t===f.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||s&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl){await yn(this,e,r);return}if(t==="file_list"){await kn(this,e,r);return}if(t==="create_folder"){await Rn(this,e,r);return}if(t===f.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(t===f.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(t===f.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((s||a||l)&&t===f.threadCompact){await this.handleThreadCompact(e,r);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===f.getAgentGlobalConfig){const g=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...g?{config:g}:{config:null}}});return}if(t===Ve){await this.handleConnectorAdminLocalAction(e);return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){Pn(this,e,r,d,u);return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){await Tn(this,e,r,t);return}const p=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:p?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{o?.()}}handleGetSessionUsage(e,t){return yt(this,e,t)}handleThreadCompact(e,t){return Rt(this,e,t)}handleGetRateLimits(e,t){return pn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return gn(this,e,t)}wakeRateLimitSlot(e,t){return fn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),r=t?.adapter instanceof S?t.adapter:null,n=(this.config.adapterType??"acp")==="acp",o={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const s=this.sessionBindings;if(e&&!s.has(e)){const i=this.bindingStore.get(e);i?.cwd&&s.set(e,i.cwd)}return s},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:s=>r?r.setMode(s):Promise.resolve(!1),setModel:s=>r?r.setModel(s):Promise.resolve(!1),acpSetMode:n?(s,i)=>Gn(o,s,i):void 0,acpSetModel:n?(s,i)=>jn(o,s,i):void 0,getPendingApproval:s=>{const i=r?.pendingApprovalEntries.get(s);return i?{requestId:i}:void 0},deletePendingApproval:s=>r?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,i)=>(r&&r.respondToPermission(s,i),Promise.resolve()),onSessionBound:(s,i)=>{this.bindingStore.set(s,i)},onSessionUnbound:s=>{this.unbindSession(s).catch(i=>{h.warn(this.name,`session unbind cleanup failed: ${i instanceof Error?i.message:String(i)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof D?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{O(this,this.config.adapterType??"acp",e,"mode",s)},onModelSet:s=>{O(this,this.config.adapterType??"acp",e,"model",s),this.refreshQuotaAfterModelSwitch(e,s)}}}sessionControlSenders(e){return{sendEventAck:(t,r)=>this.aibotHandle.sendEventAck({event_id:t,session_id:r,received_at:Date.now()}),sendEventResult:(t,r,n)=>this.aibotHandle.sendEventResult({event_id:t,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,r,n,o,s)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:r,...n?{result:n}:{},...o?{error_code:o}:{},...s?{error_msg:s}:{}},e)}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const r=t instanceof Error?t.message:String(t),n=(()=>{const a=B(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),o=t instanceof Ai||t instanceof bi,s=t instanceof yi&&n,i=s?"audit_config_invalid":o?t.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i,msg:r,updated_at:Date.now()}),o||s)try{this.aibotHandle.sendAuditState(I({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const n=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,t,r){const n=this.buildInboundEvent(e,t),o=this.bindingStore.get(e.session_id),s=o?this.resolveAgentSessionId(o):void 0,i=Number(e.created_at),a=Number.isFinite(i)&&i>0?new Date(i).toISOString():void 0,l=this.auditController.startTurn({session:r,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...s?{providerSessionId:s}:{}}});return l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,t){const r=oi(this.sendCtrl.getGlobalRuntimeConfig(),t),n=wi(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:n===void 0?void 0:JSON.stringify(n),attachments_json:Xn(e.attachments),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(r=>!Sn(String(r?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Ti}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{h.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setRemoteAdminPorts(e){this.remoteAdminPorts=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{Eo as AgentInstance};
|
|
3
|
+
Error: ${r}`,n,!1,o))}sendEventResultWithCleanup(e,t,r,n,o=!1){if(this.rejectedOutputEvents?.has(e))return;const s=this.blockedDispatchEvents?.get(e);this.blockedDispatchEvents?.delete(e),s&&t==="responded"&&(t="canceled",n=`agent_blocked_${s}`,r=`${s}: dispatch checkpoint saved; awaiting owner input`);const i=this.pool.getEventSessionId(e)??this.eventSessionIndex.get(e),a=r?.trim()??"";o&&this.markRunErrorSurfaced(e,a),t==="failed"&&i&&a&&this.sendRunErrorAsChunk(e,i,a);const l=t==="failed"&&a!==""&&(this.surfacedRunErrorTexts.get(e)?.has(a)??!1);if(this.auditController.markResponded(e,t,r),this.sendCtrl.finalizeOpenStreams(e),this.sendCtrl.sendEventResult(e,t,r,n,l),this.rejectedOutputEvents?.has(e))return;this.pool.cleanupEvent(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i??"-"} status=${t}`),i&&(this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,t,r)),this.eventSessionIndex.delete(e),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(c=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${c instanceof Error?c.message:String(c)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:r,errorMsg:n}=e;if(this.stopped||this.rejectedOutputEvents?.has(t))return;const o=this.inflightEvents.get(t);if(!o){h.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(t,r,n),this.sendEventResultWithCleanup(t,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,s);const i=this.config.adapterType??"acp";if(s>R){h.error(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} outcome=give-up err=${n}`);const c=`${i} agent kept failing after ${R} automatic restarts: ${n}`;this.sendRunErrorAsChunk(t,r,c),this.sendEventResultWithCleanup(t,"failed",c,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped||this.rejectedOutputEvents?.has(t)){for(const c of a)this.stopped||await this.pool.deliverInboundEvent(c);return}const l=e.replayOriginalContent?o.content:this.resolveRecoveryPrompt(i,o),d={...o,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${t} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(t,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,r){this.sendCtrl.sendThinking(e,t,r)}bufferStreamChunk(e,t,r,n,o){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,t,r,n,o)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const o=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const s=this.bindingStore.get(n.sessionId);s?.cwd?(await this.prepareBoundDeferredReplay(n,s.cwd),await this.deliverPendingReplayEvent(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(o),this.deferredMgr.defer(n.channel,n.sessionId,o),r.push(n))}else await this.deliverPendingReplayEvent(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)}catch(s){const i=s instanceof Error?s.message:String(s);h.error(this.name,`Pending event replay failed event=${o.event_id}: ${i}`),this.sendEventResultWithCleanup(o.event_id,"failed",i),this.pendingEvents.markCanceled(o.event_id),await this.pendingEvents.remove(o.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(t,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,r))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const r=wi({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),o=this.auditController.startTurn({session:n,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});o&&(e.audit={...t,auditId:o.auditId,turnId:o.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const r=this.eventSessionIndex.get(e);return r?(r!==t&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${t}`),r):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,t,r,"acp",this.buildAcpRawEventFallbackText(r))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,r,n,o){const s=pi({envelope:r,fallbackText:o,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),i=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s.fallbackText,extra:{channel_data:{[n]:{raw_event:s.envelope}},agent_api_origin:!0}})};if(!s.sharded){i();return}h.info("bridge",`${n} raw_event oversized, sharded delivery: event=${e} fields=${s.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of s.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,gi({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);i()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,r,n){this.sendCtrl.sendToolExecutionCard(e,t,r,n)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${T()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,r){const n=r.questions.map(s=>s.header).join(", "),o=x(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:t,content:o,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const t=An(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,o=n instanceof S?"acp":n instanceof P?"opencode":this.config.adapterType??"unknown",s=n instanceof P?n.handleQuestionReplyEvent(t):n instanceof S?await n.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return s.delivered?(h.info(this.name,`[${o}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${o}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${s.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:s.errorCode??"interaction_reply_failed",msg:s.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=bn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,o=t.params,s=String(o.tool_call_id??o.approval_command_id??o.approval_id??o.exec_context_id??""),i=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...o,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return i.delivered?(h.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${s||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${s||"-"} code=${i.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i.errorCode,msg:i.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.rejectedOutputEvents?.has(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const t=this.config.adapterType??"acp",r=Sn(e);if(t==="claude"&&this.sendCtrl.hasTerminalResult(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}let n;if(r&&(n=this.lifecycleBarrier.tryEnter(`session-control:${r.verb}`)??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const o=ai(e.extra);if(o.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:o.error,updated_at:Date.now()});return}const s=o.patch,i=B(e.extra);if(En(this,e,t,i))return;if(r){await yn(this,r,e,t,i,this.config.agent.clientType??this.config.aibot.clientType);return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(c){this.sendAuditConfigurationError(e,c);return}if(await wn(this,e,t,Di.has(t),s,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,p,g]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(m=>m.name===p||m.name===`/${p}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await A.execCommand(p,g.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,p,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&Q(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof H&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,s,a);d.attachments_json=await ei(d.attachments_json,{extraAllowedHosts:Xn(this.aibotConfig.url),logTag:this.name});try{const c=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!c)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}handleStaleCwdError(e,t){if(!/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(t)||!e.session_id)return!1;this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const n=this.pool.getSlot(e.session_id);n?.adapter instanceof S&&n.adapter.getSessionBindings().delete(e.session_id);const o=this.config.adapterType??"acp",s=this.resolveBindingChannelKey(o);return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:t,extra:{channel_data:{[s]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:e.msg_id}),!0}failUndeliveredInboundEvent(e,t){const r=t instanceof Error?t.message:String(t);h.warn(this.name,`Inbound event undelivered event=${e.event_id} session=${e.session_id}: ${r}`),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),!this.handleStaleCwdError(e,r)&&this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return rt(this,e,t)}handleSessionControlForPool(e,t){return at(this,e,t)}handleSessionControlLocalActionForPool(e){return dt(this,e)}handleCodexSessionControlLocalActionOpen(e){return lt(this,e)}handleCursorSessionControlLocalActionOpen(e){return ct(this,e)}handlePiSessionControlOpen(e,t){return ht(this,e,t)}handlePiSessionControlRestart(e){return ut(this,e)}handlePiSessionControlRestartLocalAction(e){return pt(this,e)}syncOpenCodeBinding(e,t){return gt(this,e,t)}isWorkspaceFreeClient(){return ft(this)}isCwdLockedClient(){return mt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return vt(this,e,t)}bindSessionForPool(e,t){return _t(this,e,t)}deferredCallbacks(){return St(this)}handleOpenHumanSessionControlOpen(e,t){return Ct(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return bt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return At(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return Et(this,e)}normalizeClaudeModeId(e){return Ut(this,e)}handleExecCommandOptions(e,t,r){qt(this,e,t,r)}resolveSessionModelId(e){return Wt(this,e)}resolveSessionModeId(e){return Nt(this,e)}resolveCursorSessionModeId(e){return jt(this,e)}resolveClaudeSessionEffort(e){return Gt(this,e)}resolveClaudeSessionModeId(e){return Kt(this,e)}currentClaudeModeId(e){return zt(this,e)}buildCursorToolbarMeta(e){return Jt(this,e)}buildAgyToolbarMeta(e,t){return Yt(this,e,t)}buildAgyQuotaMeta(e){return Vt(this,e)}sendAgyBindingCard(e,t,r){return Xt(this,e,t,r)}refreshAndPushAgyQuota(e,t=!1){return Zt(this,e,t)}handleAgySetModel(e,t){return en(this,e,t)}buildClaudeToolbarMeta(e){return tn(this,e)}providerQuotaToCodexRateLimits(e){return hi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ci(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return jn(e)}failSessionOpen(e,t){return qn(this,e,t)}getClaudeWorkerStatus(e){return Wn(this,e)}refreshClaudeWorkerStatusCard(e,t){return Nn(this,e,t)}async ensureSlotStarted(e,t=6e4){return Un(this,e,t)}maybeOfferCliInstall(e){$e(this,e)}handleCliInstallQuestionReply(e){return He(this,e)}handleCliInstallInteractionReply(e){return De(this,e)}runConfirmedCliInstall(e,t){return Qe(this,e,t)}handleSkillDeleteLocalAction(e){return Tt(this,e)}handleSkillUploadLocalAction(e){return Pt(this,e)}handleSkillEnableLocalAction(e){return xt(this,e)}handleSkillRefreshLocalAction(e){Lt(this,e)}handleSkillDisableLocalAction(e){return Mt(this,e)}computeSkillReport(e){return $t(this,e)}reportSessionSkills(e){Ht(this,e)}skillsSyncGroupKey(){return Dt(this)}forceRefreshSkills(e,t){return Qt(this,e,t)}adoptSkillsWireHashFromDisk(){Ot(this)}buildLibrarySkillsReport(e){return It(this,e)}skillLookupEnv(){return Bt(this)}resolveOrphanTitle(e){return On(this,e)}resolveAgentSessionId(e){return Qn(this,e)}providerKeyForAdapter(){return Dn(this)}setResolvedAgentSessionId(e,t){In(this,e,t)}normalizePathForCompare(e){return Hn(e)}ensureImportedAgentSession(e,t){Mn(this,e,t)}buildOpenedBindingResult(e,t,r="ready"){return Ln(this,e,t,r)}buildDshOpenedToolbarMeta(e){return Bn(this,e)}dshCatalogDataRoot(){return Fn(this)}hasDiskScanner(){return $n(this)}unbindSession(e){return et(this,e)}handleUnbindTextCommand(e){return tt(this,e)}handleUnbindLocalAction(e){return nt(this,e)}handleListSessionsTextCommand(e){return it(this,e)}handleListSessionsLocalAction(e){return st(this,e)}handleSyncHistoryLocalAction(e){return ot(this,e)}handleSessionControlCommand(e,t){return Le(this,e,t)}handleSessionControlLocalAction(e){return Me(this,e)}handleEventCancel(e){return Oe(this,e)}waitForEventDone(e,t,r){return Ie(this,e,t,r)}handleAibotStop(e){Be(this,e)}killAndResumeStopSlot(e,t){return Fe(this,e,t)}handleAibotRevoke(e){return Ue(this,e)}handleConfigureGatewayProvider(e){return qe(this,e)}getAuditLocalActionHandler(){return We(this)}handleAuditLocalAction(e){return Ne(this,e)}handleConnectorRollback(e){return je(this,e)}getRelayStateSyncer(){return Ge(this)}relayStateSyncOnConnect(){Ke(this)}reportRelayStateLocalChange(){ze(this)}handleApplyRelayState(e){return Je(this,e)}fetchRelayCredential(e){return Ye(this,e)}handleConnectorAdminLocalAction(e){return Ze(this,e)}isSharedInstance(){return Ve(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${t} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let o;if(t===f.sessionControl&&(o=this.lifecycleBarrier.tryEnter(`local-action:${n||t}`)??void 0,!o)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===f.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(J(t)){await this.handleAuditLocalAction(e);return}const s=(this.config.adapterType??"acp")==="claude";if(t===f.sessionControl&&n===w.exec&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl&&n===w.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===f.sessionControl&&n===w.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===f.sessionControl&&n===w.unbind){if(this.isCwdLockedClient()){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.verbInvalid,error_msg:wt});return}await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const i=(this.config.adapterType??"acp")==="opencode";if((s&&(t===f.interactionReply||t==="exec_approve"||t==="exec_reject")||i&&t===f.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||s&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl){await Rn(this,e,r);return}if(t==="file_list"){await Tn(this,e,r);return}if(t==="create_folder"){await kn(this,e,r);return}if(t===f.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(t===f.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(t===f.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((s||a||l)&&t===f.threadCompact){await this.handleThreadCompact(e,r);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===f.getAgentGlobalConfig){const g=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...g?{config:g}:{config:null}}});return}if(t===Xe){await this.handleConnectorAdminLocalAction(e);return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){xn(this,e,r,d,u);return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){await Pn(this,e,r,t);return}const p=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:p?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{o?.()}}handleGetSessionUsage(e,t){return Rt(this,e,t)}handleThreadCompact(e,t){return kt(this,e,t)}handleGetRateLimits(e,t){return gn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return fn(this,e,t)}wakeRateLimitSlot(e,t){return mn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),r=t?.adapter instanceof S?t.adapter:null,n=(this.config.adapterType??"acp")==="acp",o={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const s=this.sessionBindings;if(e&&!s.has(e)){const i=this.bindingStore.get(e);i?.cwd&&s.set(e,i.cwd)}return s},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:s=>r?r.setMode(s):Promise.resolve(!1),setModel:s=>r?r.setModel(s):Promise.resolve(!1),acpSetMode:n?(s,i)=>Kn(o,s,i):void 0,acpSetModel:n?(s,i)=>Gn(o,s,i):void 0,getPendingApproval:s=>{const i=r?.pendingApprovalEntries.get(s);return i?{requestId:i}:void 0},deletePendingApproval:s=>r?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,i)=>(r&&r.respondToPermission(s,i),Promise.resolve()),onSessionBound:(s,i)=>{this.bindingStore.set(s,i)},onSessionUnbound:s=>{this.unbindSession(s).catch(i=>{h.warn(this.name,`session unbind cleanup failed: ${i instanceof Error?i.message:String(i)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof D?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{O(this,this.config.adapterType??"acp",e,"mode",s)},onModelSet:s=>{O(this,this.config.adapterType??"acp",e,"model",s),this.refreshQuotaAfterModelSwitch(e,s)}}}sessionControlSenders(e){return{sendEventAck:(t,r)=>this.aibotHandle.sendEventAck({event_id:t,session_id:r,received_at:Date.now()}),sendEventResult:(t,r,n)=>this.aibotHandle.sendEventResult({event_id:t,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,r,n,o,s)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:r,...n?{result:n}:{},...o?{error_code:o}:{},...s?{error_msg:s}:{}},e)}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const r=t instanceof Error?t.message:String(t),n=(()=>{const a=B(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),o=t instanceof Ei||t instanceof Ai,s=t instanceof Ri&&n,i=s?"audit_config_invalid":o?t.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i,msg:r,updated_at:Date.now()}),o||s)try{this.aibotHandle.sendAuditState(I({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const n=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,t,r){const n=this.buildInboundEvent(e,t),o=this.bindingStore.get(e.session_id),s=o?this.resolveAgentSessionId(o):void 0,i=Number(e.created_at),a=Number.isFinite(i)&&i>0?new Date(i).toISOString():void 0,l=this.auditController.startTurn({session:r,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...s?{providerSessionId:s}:{}}});return l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,t){const r=ri(this.sendCtrl.getGlobalRuntimeConfig(),t),n=yi(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:n===void 0?void 0:JSON.stringify(n),attachments_json:Zn(e.attachments),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(r=>!Cn(String(r?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Pi}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{h.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setRemoteAdminPorts(e){this.remoteAdminPorts=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{yo as AgentInstance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ClaudeAdapter as
|
|
1
|
+
import{ClaudeAdapter as x}from"../adapter/claude/index.js";import{getCachedModels as L}from"../adapter/claude/model-list.js";import{SESSION_CONTROL_ERROR_CODES as R,SESSION_MODE_IDS as _}from"../adapter/claude/protocol-contract.js";import{CursorAdapter as I,CURSOR_MODE_OPTIONS as Q}from"../adapter/cursor/index.js";import{getCachedAgyModels as b,primeAgyModels as T,resolveAgyToolbarModelId as p}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as S,refreshAgyQuotaInfo as y}from"../adapter/agy/quota.js";import{normalizeClaudeEffort as P,CLAUDE_EFFORT_LEVELS as w}from"../core/config/claude-direct-env.js";import{resolveToolbarSelection as m}from"./toolbar-selection.js";import{log as M}from"../core/log/index.js";const U=["isRateLimitsCacheFresh","isGrixRelayActive","getFreshClaudeRateLimitState","maybeQueryProviderQuota","providerQuotaToRateLimits","normalizeClaudeModeId","resolveSessionModelId","resolveCursorSessionModeId","resolveClaudeSessionEffort","resolveClaudeSessionModeId","currentClaudeModeId","buildAgyToolbarMeta","buildAgyQuotaMeta","sendAgyBindingCard"],$=["name","config","aibotHandle","pool","bindingStore","globalConfigStore","providerResolver","cachedClaudeRateLimitState","cachedProviderQuota","cachedProviderQuotaSampledAtMs"];function G(e,i){return String(i??"").trim().toLowerCase()===_.approval?_.approval:_.fullAuto}function J(e,i,t,a){const r=Array.isArray(a?.options)?a.options:[];if(r.length===0)return;const l=e.bindingStore.get(i)?.cwd??"",u={};if(t==="model"){u.available_models=r.map(d=>({id:d.id,displayName:d.label}));const c=r.find(d=>d.current);c&&(u.model_id=c.id)}else if(t==="mode"){u.available_modes=r.map(d=>({id:d.id,displayName:d.label}));const c=r.find(d=>d.current);c&&(u.mode_id=c.id)}else u[`${t}_options`]=r;e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l,meta:u})}function A(e){return e.config.adapterType??"acp"}function q(e,i){return m(e,A(e),i,"model")}function V(e,i){return m(e,A(e),i,"mode")}function W(e,i){return m(e,"cursor",i,"mode")}function j(e,i){return m(e,"claude",i,"effort")}function K(e,i){return m(e,"claude",i,"mode")}function X(e,i){return e.normalizeClaudeModeId(e.resolveClaudeSessionModeId(i))}function Y(e,i){const t=e.pool.getSlot(i);if(t?.adapter instanceof I)return t.adapter.getToolbarMeta(i);const a=e.bindingStore.getModelId(i)??"auto",r=e.resolveCursorSessionModeId(i)??"full_auto";return{model_id:a,mode_id:r,currentModelId:a,currentModeId:r,available_models:[],available_modes:Q.map(n=>({...n}))}}function C(e){return!e?.agyConversationId}function Z(e,i,t){const a=e.bindingStore.get(i);if(!a)return;const r=b(e.config.agent.command),n=r.length>0?r[0].id:"";let l=p(e.resolveSessionModelId(i)||"",r)||n;r.length>0&&!r.some(c=>c.id===l)&&(l=n);const u=t??S(e.config.agent.command);return{model_id:l,currentModelId:l,model_switchable:C(a),available_models:r.map(c=>({id:c.id,displayName:c.displayName})),...e.buildAgyQuotaMeta(u)}}function h(e,i){const t={rate_limits:null,extra_limits:null};return i.rateLimits&&(t.rate_limits={primary:i.rateLimits.primary,secondary:i.rateLimits.secondary,sampledAt:i.sampledAt??Date.now()},i.rateLimits.extras&&i.rateLimits.extras.length>0&&(t.extra_limits=i.rateLimits.extras)),{...t,...i.plan!==void 0&&{plan:i.plan},...i.quota_exhausted!==void 0&&{quota_exhausted:i.quota_exhausted},...i.quota_reset_at!==void 0&&{quota_reset_at:i.quota_reset_at},...i.available_credits!==void 0&&{available_credits:i.available_credits}}}function ee(e,i,t,a){const r=a??e.buildAgyToolbarMeta(i);return e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:t,...r?{meta:r}:{}}),r}async function ie(e,i,t=!1){const[a]=await Promise.all([y(e.config.agent.command,t),T(e.config.agent.command)]),r=e.bindingStore.get(i);return r?.cwd&&e.sendAgyBindingCard(i,r.cwd,e.buildAgyToolbarMeta(i,a)),a}async function re(e,i,t){const a=i.params??{},r=b(e.config.agent.command),n=p(String(a.model_id??a.modelId??""),r);if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!n){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const l=e.bindingStore.get(t);if(!l?.cwd){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:R.bindingMissing,error_msg:"session binding was not found"});return}if(!C(l)){const c=p(e.resolveSessionModelId(t)||l.modelId||"",r)||l.modelId||"";if(n!==c){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:"set_model_locked",error_msg:"\u5F53\u524D\u4F1A\u8BDD\u5DF2\u5F00\u59CB\uFF0Cagy \u6A21\u578B\u4E0D\u53EF\u4E2D\u9014\u5207\u6362\uFF1B\u8BF7\u65B0\u5F00\u8BDD\u9898\u540E\u518D\u9009\u6A21\u578B"}),e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t));return}}l.modelId!==n&&(e.bindingStore.setModelId(t,n),e.globalConfigStore?.set(e.name,{modelId:n}));const u=await y(e.config.agent.command,!0).catch(()=>S(e.config.agent.command));e.sendAgyBindingCard(t,l.cwd,e.buildAgyToolbarMeta(t,u)),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"model_set",model_id:n,binding:{cwd:l.cwd,model_id:n}}})}function te(e,i){if(!e.bindingStore.get(i))return;const a=L(),r=a.length>0?a[0].id:"";let n=e.resolveSessionModelId(i)||r;a.length>0&&!a.some(o=>o.id===n)&&(n=r);const l=e.currentClaudeModeId(i);let u;try{const o=e.providerResolver?e.providerResolver():e.config.agent.provider;u=P(o?.effort)}catch{}const c=e.resolveClaudeSessionEffort(i)??u??"auto",d={model_id:n,mode_id:l,currentModelId:n,currentModeId:l,available_efforts:[...w],effort:c,reasoning_effort:c,available_models:a.map(o=>({id:o.id,displayName:o.displayName}))},v=e.pool.getSlot(i),s=v?.adapter instanceof x?v.adapter.getSessionState():null;(s?.rateLimits?.fiveHour||s?.rateLimits?.sevenDay)&&(e.cachedClaudeRateLimitState=s);const f=e.isGrixRelayActive(),g=f?null:s??e.getFreshClaudeRateLimitState();if(g){const o=g.rateLimits;o&&(o.fiveHour||o.sevenDay)&&(d.rate_limits={...o.fiveHour?{fiveHour:o.fiveHour}:{},...o.sevenDay?{sevenDay:o.sevenDay}:{},sampledAt:g.sampledAt||Date.now()})}if(f){d.rate_limits=null;const o=e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider==="grix"?e.cachedProviderQuota:null;d.provider_quota=o,(!o||!e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs))&&e.maybeQueryProviderQuota().catch(()=>{})}else d.provider_quota=null;if(s){const o=s.contextWindow;o.usedPercentage!=null&&(d.context_window={usedPercentage:o.usedPercentage,remainingPercentage:o.remainingPercentage})}if(!f&&!d.rate_limits&&e.cachedProviderQuota?.success&&e.cachedProviderQuota.provider!=="grix"){e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)||e.maybeQueryProviderQuota().catch(()=>{});const o=e.providerQuotaToRateLimits(e.cachedProviderQuota);o&&(d.rate_limits=o),M.info(e.name,`[toolbar-meta] provider quota fallback: hasCached=${!!e.cachedProviderQuota} fromProvider=${JSON.stringify(o)}`)}return d.rate_limits&&M.info(e.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(d.rate_limits)}`),d}export{$ as TOOLBAR_META_HOST_FIELDS,U as TOOLBAR_META_HOST_METHODS,h as buildAgyQuotaMeta,Z as buildAgyToolbarMeta,te as buildClaudeToolbarMeta,Y as buildCursorToolbarMeta,X as currentClaudeModeId,re as handleAgySetModel,J as handleExecCommandOptions,C as isAgyModelSwitchable,G as normalizeClaudeModeId,ie as refreshAndPushAgyQuota,j as resolveClaudeSessionEffort,K as resolveClaudeSessionModeId,W as resolveCursorSessionModeId,V as resolveSessionModeId,q as resolveSessionModelId,ee as sendAgyBindingCard};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "grix-connector",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.15.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",
|
|
Binary file
|