grix-connector 4.19.0 → 5.1.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/README.md +1 -1
- package/dist/adapter/acp/acp-adapter.js +12 -12
- package/dist/adapter/agy/agy-adapter.js +10 -10
- package/dist/adapter/agy/model-list.js +2 -2
- package/dist/adapter/agy/quota.js +5 -5
- package/dist/adapter/claude/claude-adapter.js +20 -20
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/cursor/cursor-adapter.js +12 -11
- package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
- package/dist/adapter/pi/pi-adapter.js +8 -6
- package/dist/adapter/pi/pi-grix-tools-extension.js +2 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-5.1.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/bridge.js +3 -2
- package/dist/bridge/rate-limits.js +1 -1
- package/dist/bridge/send-controller.js +3 -3
- package/dist/bridge/toolbar-meta.js +1 -1
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/installer/registry.js +1 -1
- package/dist/core/protocol/protocol-text.js +1 -1
- package/dist/core/util/home-env.js +1 -0
- package/dist/grix.js +5 -5
- package/dist/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/dist/protocol/acp-client.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +2 -1
- package/openclaw-plugin/index.js +10 -4
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
package/README.md
CHANGED
|
@@ -65,7 +65,7 @@ Two limits of the generic entry are deliberate and will not be changed. Skill di
|
|
|
65
65
|
For DeepSeek Harness, install the official CLI and complete its login/profile setup before starting the connector:
|
|
66
66
|
|
|
67
67
|
```bash
|
|
68
|
-
npm install -g @deepseek-ai/dsh
|
|
68
|
+
npm install -g @deepseek-ai/dsh@latest
|
|
69
69
|
dsh web
|
|
70
70
|
```
|
|
71
71
|
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import{fileURLToPath as
|
|
2
|
-
`)}function Ae(c,e,t){const i=c&&typeof c=="object"?c:{},s=i.toolCall&&typeof i.toolCall=="object"?i.toolCall:{},n=[s.rawInput,s.raw_input,s.input,s.arguments,s.args,D(s.content),s.content,s.description,i.tool_input,i.toolInput,e];for(const o of n){const r=q(o);if(r&&r!==t)return r}return""}const U=/^q\d+_opt_\d+$/,k=/^q\d+_skip$/,Ce=new Set(["allow_once","allow_always","reject_once","reject_always"]);function Se(c){if(!`${c.toolName} ${c.toolTitle}`.toLowerCase().replace(/[^a-z]/g,"").includes("askuserquestion"))return null;const t=c.options;if(t.length===0)return null;const i=t.some(l=>U.test(l.optionId)),s=i?t.filter(l=>U.test(l.optionId)):t.filter(l=>!k.test(l.optionId));if(s.length===0||!i&&s.every(l=>Ce.has(l.kind)))return null;const n=c.rawParams&&typeof c.rawParams=="object"?c.rawParams:{},o=n.toolCall&&typeof n.toolCall=="object"?n.toolCall:{},r=D(o.content).trim();return r?{prompt:r,answerOptions:s}:null}import{scanSkills as B}from"../claude/skill-scanner.js";import{checkKiroSessionActivity as _e,checkKimiSessionActivity as we,checkQoderSessionActivity as F,checkDimSessionActivity as Te,hasRunningKimiDetachedTask as be}from"./session-activity.js";import{evaluateGrokLiveness as L,grokEventsByteSize as ke}from"./grok-liveness.js";import{resolveCliPath as Re,getCliVersion as Pe}from"../../core/util/cli-probe.js";const R=h.dirname(Z(import.meta.url)),j=[{modelId:"deepseek-v4-pro",name:"DeepSeek V4 Pro"},{modelId:"deepseek-v4-flash",name:"DeepSeek V4 Flash"}],P=[{modelId:"kimi-code/kimi-for-coding",name:"K2.7 Coding"},{modelId:"kimi-code/kimi-for-coding-highspeed",name:"K2.7 Coding Highspeed"},{modelId:"kimi-code/k3",name:"K3"}];function E(c,e){const t=Number(process.env[c]);return Number.isFinite(t)&&t>0?t:e}const Ee=200,xe=60*1e3,Me=600*1e3,w=E("GRIX_ACP_TURN_INACTIVITY_TIMEOUT_MS",900*1e3),K=2,H=5e3,G=80,W=600*1e3,Q=1200*1e3,$e=E("GRIX_ACP_BUSY_RETRY_INTERVAL_MS",5e3),z=E("GRIX_ACP_BUSY_WAIT_MAX_MS",1800*1e3),qe=6e4,Ne=2e3,Oe=12e3,X=3e3,V=3e4,De=1e3,Ue=1e4;function Be(c){return new Promise(e=>setTimeout(e,c))}const Fe=["[grix protocol] Markers like [[message_id:<id>]] and [[quoted_message_id:<id>]] are metadata, not user prose \u2014 never repeat them verbatim except as instructed here.","The message you are replying to carries its id in a [[message_id:<id>]] marker.","If (and only if) you want your reply to quote/thread onto that specific message, include [[quoted_message_id:<id>]] anywhere in your reply using that id; otherwise omit it."].join(" ");function Le(c){return!(!(c instanceof Error)||c.code!==-32603||he(c))}function Y(c){if(!(c instanceof Error))return!1;const e=c.data;return e&&typeof e=="object"&&e.code==="turn.agent_busy"?!0:/cannot launch a new turn/i.test(c.message)}function C(c){if(!(c instanceof Error))return String(c);let e=c.message;const t=c.data;return t&&(e+=` data=${JSON.stringify(t)}`),e}function je(c){return c.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"")}class J extends M{type="acp";config;callbacks;agentProcess=null;acpClient=null;internalApi=null;activeRun=null;compacting=!1;compactingTimer=null;compactionDoneResolver=null;pendingAutoCompact=!1;eventResults=null;pendingApprovals=new Map;pendingQuestions=new Map;clientMsgSeq=0;stopped=!1;acpAuthMethod;acpInitialMode;acpInitialModel;newSessionParams;acpMcpTools;terminalAuthChild=null;rawTransport;approvalMode;autoInjectArgs;nativeProviderScope;reasonixAuditTranscriptPath;auditAgentType;trimToolWirePayload;activeAuditEventId=null;auditCaptures=new Map;completedAuditBoundaries=new Map;bindingStore;sessionBindings=new Map;deferredEvents=new Map;currentAibotSessionId;bridgeLog;sessionConnected=!1;sessionContextPending=!1;baselineGroupPids=[];rawEventSeq=0;recoveryContextBySessionId=new Map;quoteProtocolTaughtSessions=new Set;identity;orphanBuffer="";orphanQuotedStream=new S;orphanFlushTimer=null;orphanSessionId=null;orphanSuppressedUntil=0;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.identity=new re("acp-adapter",t.getAgentProfile),this.bridgeLog=i?.bridgeLog??null,this.acpAuthMethod=i?.acpAuthMethod,this.acpInitialMode=i?.acpInitialMode,this.acpInitialModel=i?.acpInitialModel,this.newSessionParams=i?.newSessionParams,this.acpMcpTools=i?.acpMcpTools??!0,this.rawTransport=i?.rawTransport??!1,this.approvalMode=i?.approvalMode??"default",this.autoInjectArgs=i?.autoInjectArgs,this.nativeProviderScope=i?.nativeProviderScope,this.reasonixAuditTranscriptPath=i?.reasonixAuditTranscriptPath,this.auditAgentType=String(i?.agentType??h.basename(e.command)).trim().toLowerCase();const s=h.basename(e.command).toLowerCase(),n=this.auditAgentType==="copilot"||/^copilot(?:\.cmd)?$/i.test(s)||/^gh(?:\.exe)?$/i.test(s)&&(e.args??[]).includes("copilot");if(this.trimToolWirePayload=["kimi","kiro","qwen","reasonix","copilot"].includes(this.auditAgentType)||s.includes("kimi")||s==="kiro-cli"||/^qwen(?:\.cmd)?$/i.test(s)||s.includes("reasonix")||n,this.bindingStore=i?.bindingStore??null,this.currentAibotSessionId=i?.aibotSessionId?String(i.aibotSessionId).trim():void 0,i?.eventResultsPath&&(this.eventResults=new fe(i.eventResultsPath)),this.bindingStore&&this.currentAibotSessionId){const o=this.bindingStore.get(this.currentAibotSessionId);o?.cwd&&this.sessionBindings.set(this.currentAibotSessionId,o.cwd)}}async start(){if(await this.spawnProcess(),!this.bindingStore){await this.connectSession(this.resolveCwd());return}const e=this.currentAibotSessionId?this.sessionBindings.get(this.currentAibotSessionId):void 0;e&&await this.connectSession(e)}async stop(){this.stopped=!0,this.rejectDeferredEvents("adapter stopped"),this.cancelAllDeferredTimers(),this.pendingAutoCompact=!1,this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver("stopped"),this.compactionDoneResolver=null),this.activeRun&&this.finishRun("canceled","adapter stopped"),this.flushOrphanBuffer(),this.acpClient&&(this.acpClient.dispose(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(await this.agentProcess.close(),this.agentProcess=null),this.baselineGroupPids=[],this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.terminalAuthChild&&(this.terminalAuthChild.kill("SIGKILL"),this.terminalAuthChild=null)}isAlive(){return this.agentProcess?.alive??!1}async createSession(e){return this.acpClient?.sessionId??""}async resumeSession(e,t){}async destroySession(e){this.quoteProtocolTaughtSessions.delete(e),this.identity.forgetSession(e)}onAgentProfileChanged(){this.identity.onProfileChanged()}sendPrompt(e){const t=new Ke(e.adapterSessionId);return this.acpClient?.isAlive&&this.acpClient.send(e.text).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),t}async cancel(e){this.activeRun&&this.acpClient&&(await this.acpClient.cancel(),this.flushStream(),this.finishRun("canceled","stopped by user"),this.suppressOrphanOutput(V))}setPermissionHandler(e){}async ping(e){return this.acpClient?.isAlive?this.acpClient.ping(e):this.agentProcess?.alive??!1}getStatus(){return{alive:this.agentProcess?.alive??!1,busy:this.activeRun!==null||this.compacting,sessions:this.sessionConnected?1:0}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.activeRun&&(this.snapshotAuditBoundary(this.activeRun.eventId),this.clearRunTimers(this.activeRun),this.activeRun=null)}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearRunTimers(e){e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null),e.busyRetryTimer&&(clearTimeout(e.busyRetryTimer),e.busyRetryTimer=null)}getMcpConfig(){if(!this.internalApi)return null;this.internalApi.setMcpBridgeUpHandler(t=>this.onMcpBridgeUp(t));const e=h.resolve(R,"../../mcp/mcp-bridge-server.js");return{name:"grix-app-bridge",command:process.execPath,args:[e,"--ws-url",this.internalApi.mcpBridgeWsUrl]}}async hasBackgroundWork(){const e=this.agentProcess?.pid;return e?te(e,[e,...this.baselineGroupPids]):!1}captureBaselineGroupPids(){const e=this.agentProcess?.pid;e&&ie(e).then(t=>{this.baselineGroupPids=t}).catch(()=>{})}async probe(e){const t=this.config.command||"gemini",i=await Re(t),s=i!==null;let n=null,o;if(s){const p=await Pe(t);n=p.version,p.error&&(o=p.error)}else o={code:"cli_not_found",message:`command not found: ${t}`};const r=this.acpClient?.model??null,l=this.getStatus();let d;return e?.conversation?this.acpClient?.isAlive?d={attempted:!0,ok:!0,latency_ms:null}:d={attempted:!0,ok:!1,latency_ms:null,error:{code:"unsupported",message:"ACP session not connected, cannot probe conversation"}}:d={attempted:!1,ok:!1,latency_ms:null},{cli:{command:t,installed:s,path:i,version:n,...o?{error:o}:{}},conversation:d,config:{model:r,base_url:null,source:{model:r?"runtime":"unknown",base_url:"unknown"}},process:{started:!!this.agentProcess,alive:l.alive,busy:l.busy}}}getSupportedCommands(){return this.acpClient?.availableCommands?.length?this.acpClient.availableCommands.map(e=>({name:e.name,description:e.description??"",args:e.args})):[{name:"model",description:"List or set model",args:"[model_id]"},{name:"mode",description:"List or set collaboration mode",args:"[mode_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(e,t,i){return this.acpClient?.supportsCommandsExecute?this.execCommandViaAcp(e,t):this.execCommandFallback(e,t)}async execCommandViaAcp(e,t){if(!this.acpClient)return{status:"failed",message:"No active ACP session"};if(e==="interrupt")return this.activeRun?(await this.cancel(this.activeRun.sessionId),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};if(e==="compact"){if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.activeRun)return{status:"failed",message:"agent busy"};this.compacting=!0;try{const i=await this.acpClient.executeCommand(e,t||void 0,W);return this.finishCompaction("acp-commands-execute"),i.status==="failed"?{status:"failed",message:(i.message??"").includes("timed out")?"Compaction timed out after 10 minutes":i.message??"compact failed",data:i.data}:{status:"ok",message:i.message??"Compacted",data:i.data}}catch(i){return this.finishCompaction("error"),i?.code===-32601?this.execCommandFallback(e,t):{status:"failed",message:`compact failed: ${i instanceof Error?i.message:i}`}}}try{const i=await this.acpClient.executeCommand(e,t||void 0);return{status:i.status??"ok",message:i.message,data:i.options?{command:e,options:i.options}:i.data}}catch(i){return i?.code===-32601?this.execCommandFallback(e,t):{status:"failed",message:`Command failed: ${i instanceof Error?i.message:i}`}}}async execCommandFallback(e,t){try{switch(e){case"model":{const i=t.trim();if(i)return await this.setModel(i)?{status:"ok",message:`Model set to ${i}`}:{status:"failed",message:`Failed to set model: ${i}`};const s=this.buildToolbarContext("model_list");return{status:"ok",message:`Current: ${s.currentModelId||"unknown"}`,data:s}}case"mode":{const i=t.trim();if(i)return await this.setMode(i)?{status:"ok",message:`Mode set to ${i}`}:{status:"failed",message:`Failed to set mode: ${i}`};const s=this.buildToolbarContext("mode_list");return{status:"ok",message:`Current: ${s.currentModeId||"unknown"}`,data:s}}case"interrupt":return this.activeRun?this.acpClient?(await this.cancel(this.activeRun.sessionId),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"Not connected"}:{status:"failed",message:"No active run to interrupt"};case"compact":{if(!this.acpClient)return{status:"failed",message:"No active ACP session"};if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.activeRun)return{status:"failed",message:"agent busy"};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});try{await this.acpClient.send("/compact")}catch(n){throw this.finishCompaction("send-failed"),n}this.compactingTimer=setTimeout(()=>this.finishCompaction("timeout"),W),this.compactingTimer.unref?.();const s=await i;return s==="timeout"?{status:"failed",message:"Compaction timed out after 10 minutes"}:s==="stopped"?{status:"failed",message:"Adapter stopped during compaction"}:{status:"ok",message:"Compacted"}}case"status":{const i=this.getStatus(),s=this.acpClient?.sessionOptions;return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Model: ${s?.currentModelId??"unknown"}, Mode: ${s?.currentModeId??"unknown"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,model:s?.currentModelId??"",mode:s?.currentModeId??""}}}case"skills":{const i=B({mode:this.config.command==="kiro-cli"?"kiro":"gemini",projectDir:process.cwd()}),s=i.map(n=>`- ${n.name}${n.trigger?` (${n.trigger})`:""} [${n.source}]: ${n.description}`);return{status:"ok",message:s.length>0?s.join(`
|
|
3
|
-
`):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}get acpSessionOptions(){const e=this.acpClient?.sessionOptions??null,t=this.isReasonix?j:this.isKimi?P:null;if(!t||e&&e.models.length>0)return e;const i=this.resolveFallbackCurrentModelId(t,e?.currentModelId??"");return{modes:e?.modes??[],currentModeId:e?.currentModeId??"",models:[...t],currentModelId:i}}resolveFallbackCurrentModelId(e,t){if(e.some(s=>s.modelId===t))return t;const i=(this.autoInjectArgs?.model??this.acpInitialModel??"").trim();return i&&e.some(s=>s.modelId===i)?i:e[0]?.modelId??""}get isReasonix(){return(this.config.command??"").includes("reasonix")}get isKimi(){return(this.config.command??"").includes("kimi")}buildToolbarContext(e,t){const i=this.acpClient?.sessionOptions,s=i?.currentModeId??"";let n=i?.currentModelId??"";const o=i?.modes.map(f=>({id:f.id,name:f.name}))??[],r=i?.models&&i.models.length>0,l=r?i.models:this.isReasonix?j:this.isKimi?P:[],d=r?"acp":this.isReasonix?"reasonix_fallback":this.isKimi?"kimi_fallback":"empty";this.isKimi&&!r&&a.warn("acp-adapter",`[toolbar-diag] kimi ACP session returned no models; using static fallback. command=${this.config.command} fallbackIds=${JSON.stringify(P.map(f=>f.modelId))}`),a.info("acp-adapter",`[toolbar-diag] buildToolbarContext outcome=${e} agent=${this.config.command} modelSource=${d} acpModelCount=${i?.models?.length??0} finalModelCount=${l.length}`);const p=l.map(f=>({modelId:f.modelId,name:f.name})),u=l.map(f=>({id:f.modelId,displayName:f.name})),g=i?.modes.map(f=>({id:f.id,displayName:f.name}))??[];u.length>0&&!u.some(f=>f.id===n)&&(n=this.resolveFallbackCurrentModelId(l,n));const v={outcome:e,...t?{cwd:t}:{},model_id:n,mode_id:s,currentModelId:n,currentModeId:s,available_models:u,available_modes:g,availableModels:u,availableModes:g,models:p,modes:o};return a.info("acp-adapter",`[toolbar] buildToolbarContext outcome=${e} model_id="${n}" available_models=${JSON.stringify(u.map(f=>f.id))} currentModelId=${n}`),v}get pendingApprovalEntries(){return this.pendingApprovals}get hasSessionBinding(){return this.bindingStore!==null}setMode(e){return this.acpClient?this.acpClient.setLiveMode(e):Promise.resolve(!1)}setModel(e){return this.acpClient?this.acpClient.setModel(e):Promise.resolve(!1)}handleAcpApprovalAction(e,t){const i=this.pendingApprovals.get(e);return i?(a.info("acp-adapter","handleAcpApprovalAction resolving",{toolCallId:e,requestId:i,behavior:t}),this.pendingApprovals.delete(e),this.acpClient&&this.acpClient.respondPermission(i,{behavior:t}).catch(s=>{a.error("acp-adapter",`Failed to respond to permission: ${s}`)}),this.captureAuditEvent({type:m.PermissionResponse,requestId:i,toolCallId:e,permissionDecision:t}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),!0):(a.warn("acp-adapter","handleAcpApprovalAction: no pending approval",{toolCallId:e,behavior:t,pendingCount:this.pendingApprovals.size}),!1)}handleExecApprovalEvent(e){const t=String(e.tool_call_id??e.approval_command_id??e.approval_id??e.exec_context_id??"");return t?this.handleAcpApprovalAction(t,e.decision)?{delivered:!0}:{delivered:!1,errorCode:"approval_not_found",errorMsg:`no pending approval for tool_call_id: ${t}`}:{delivered:!1,errorCode:"approval_id_required",errorMsg:"approval id is required"}}respondToPermission(e,t){this.acpClient&&this.acpClient.respondPermission(e,t).catch(i=>{a.error("acp-adapter",`Failed to respond to permission: ${i}`)}),this.captureAuditEvent({type:m.PermissionResponse,requestId:e,permissionDecision:t.behavior}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun))}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};if(t==="claude_interaction_reply"&&String(i.kind??"")==="permission"){const s=i.resolution&&typeof i.resolution=="object"?i.resolution:{},n=String(s.value??i.decision??"");return["allow","allow-once","allow-always","deny"].includes(n)?this.handleLocalAction({...e,action_type:n==="deny"?"permission_reject":"permission_approve",params:{...i,approval_command_id:i.request_id,decision:n}}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"permission_decision_invalid","permission decision is invalid"),{handled:!0,kind:"approval"})}if(t==="claude_interaction_reply")return this.handleAcpQuestionReply(e);if(t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject"){const s=String(i.tool_call_id??i.approval_command_id??i.approval_id??i.exec_context_id??""),n=t==="exec_approve"||t==="permission_approve",o=String(i.decision??"");let r;return n&&(o==="allow-once"||o==="allow-always")?r=o:n?r="allow":r="deny",s?this.handleAcpApprovalAction(s,r)?(this.callbacks.sendLocalActionResult(e.action_id,"ok"),{handled:!0,kind:"approval"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_not_found",`no pending approval for tool_call_id: ${s}`),{handled:!0,kind:"approval"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"tool_call_id_required","tool_call_id is required"),{handled:!0,kind:"approval"})}return{handled:!1,kind:""}}async handleQuestionReplyEvent(e){let t;if(e.action)t={type:"action",value:e.action};else if(e.response?.type==="single")t={type:"text",value:e.response.value};else if(e.response?.type==="map")t={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:t})}async handleAcpQuestionReply(e){const t=await this.deliverQuestionReply(e.params??{});return t.delivered?(this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result),{handled:!0,kind:t.kind??"question_reply"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:t.kind??"question_reply_failed"})}async deliverQuestionReply(e){const t=String(e.request_id??"").trim(),i=this.pendingQuestions.get(t);if(!t||!i||!this.acpClient)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered.",kind:"question_reply_not_pending"};const s=e.resolution&&typeof e.resolution=="object"?e.resolution:{},n=String(s.type??"");let o,r="";if(n==="action"&&String(s.value??"")==="cancel")o=i.options.find(d=>/_skip$/.test(d.optionId)||d.kind.toLowerCase().includes("reject"));else{if(n==="text")r=String(s.value??"").trim();else if(n==="map"){const d=Array.isArray(s.entries)?s.entries:[];r=String(d[0]?.value??"").trim()}o=i.options.find(d=>d.name.trim()===r||d.optionId===r)}if(!o){const d=i.options.find(p=>k.test(p.optionId));return r&&d?this.deliverFreeTextAnswer(t,d.optionId,r):{delivered:!1,errorCode:"question_answer_invalid",errorMsg:"The selected answer does not match a pending question option. The question is still open; please tap one of the options on the card (free-text answers are not supported).",kind:"question_reply_invalid"}}try{await this.acpClient.respondPermissionOption(t,o.optionId)}catch(d){return{delivered:!1,errorCode:"question_reply_failed",errorMsg:d instanceof Error?d.message:String(d),kind:"question_reply_failed"}}this.pendingQuestions.delete(t);const l=/_skip$/.test(o.optionId);return this.captureAuditEvent({type:m.PermissionResponse,requestId:t,permissionDecision:l?"deny":"allow"}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),{delivered:!0,result:{request_id:t,resolution:l?"cancel":"answer"},kind:l?"question_reply_cancel":"question_reply"}}async deliverFreeTextAnswer(e,t,i){const s=this.acpClient;if(!s)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered.",kind:"question_reply_not_pending"};try{await s.respondPermissionOption(e,t)}catch(o){return{delivered:!1,errorCode:"question_reply_failed",errorMsg:o instanceof Error?o.message:String(o),kind:"question_reply_failed"}}this.pendingQuestions.delete(e),this.captureAuditEvent({type:m.PermissionResponse,requestId:e,permissionDecision:"deny"});const n=Date.now()+Ue;for(;;)try{await s.send(i);break}catch(o){if(!Y(o)||Date.now()>=n)return a.warn("acp-adapter","free-text answer delivery failed after question dismissed",{requestId:e,error:C(o)}),{delivered:!1,errorCode:"question_free_text_delivery_failed",errorMsg:"The question was dismissed, but the free-text answer could not be delivered while the agent was busy. Please resend it as a normal message.",kind:"question_reply_failed"};await Be(De)}return a.info("acp-adapter","free-text answer delivered via skip + follow-up prompt",{requestId:e}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),{delivered:!0,result:{request_id:e,resolution:"answer"},kind:"question_reply_free_text"}}resolveCwd(){if(this.currentAibotSessionId){const e=this.sessionBindings.get(this.currentAibotSessionId);if(e)return e}if(this.bindingStore&&this.currentAibotSessionId){const e=this.bindingStore.get(this.currentAibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async bindSession(e,t){const i=this.sessionBindings.get(e);if(i)try{return await A.stat(i),!1}catch{a.info("acp-adapter",`Stale binding for session ${e}: ${i} no longer exists, allowing rebind to ${t}`),this.sessionBindings.delete(e)}return this.sessionBindings.set(e,t),this.bindingStore&&this.bindingStore.set(e,t),this.maybeRefreshKiroSkills(t),!this.sessionConnected&&this.agentProcess?.alive?this.connectSession(t).then(()=>!0).catch(s=>{a.error("acp-adapter",`Failed to create session on bind: ${C(s)}`);const n=this.buildToolbarContext("bind_failed",t),o=Array.isArray(n.available_models)&&n.available_models.length>0;return this.callbacks.sendUpdateBindingCard(e,"failed",t,o?n:void 0),!0}):(this.acpClient?.isAlive&&(this.bindingStore&&this.acpClient.sessionId&&this.bindingStore.setAcpSessionId(e,this.acpClient.sessionId),this.callbacks.sendUpdateBindingCard(e,"connected",t,this.buildToolbarContext("binding_ready",t))),Promise.resolve(!0))}getSessionCwd(e){return this.sessionBindings.get(e)}getSessionBindings(){return this.sessionBindings}maybeRefreshKiroSkills(e){if(this.config.command!=="kiro-cli"||!this.callbacks.onSkillsUpdate)return;const t=String(e??"").trim()||void 0;let i=[];try{i=B({mode:"kiro",projectDir:t})}catch(s){a.warn("acp-adapter",`Kiro skills scan failed: ${s instanceof Error?s.message:String(s)}`);return}try{this.callbacks.onSkillsUpdate(i,t)}catch(s){a.warn("acp-adapter",`onSkillsUpdate failed: ${s instanceof Error?s.message:String(s)}`)}}replayDeferredEvents(e){const t=this.deferredEvents.get(e);if(!t||t.length===0)return;if(this.activeRun){a.info("acp-adapter",`Cannot replay deferred events for session ${e}: agent busy`);return}const i=t.shift();i&&(t.length===0?(this.deferredEvents.delete(e),this.cancelDeferredTimer(e)):this.deferredEvents.set(e,t),a.info("acp-adapter",`Replaying deferred event ${i.event.event_id} for session ${e} (remaining: ${t.length})`),this.startRun(i.event,!1))}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.suppressOrphanOutput(V),a.info("acp-adapter",`Compaction finished (${e}); replaying deferred events`),this.replayNextDeferredEvent();const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.(e)}replayNextDeferredEvent(){if(this.activeRun||this.compacting)return;const e=this.deferredEvents.keys().next().value;e&&this.replayDeferredEvents(e)}announceDeferredComposing(e){}sendTerminalEventWithoutRun(e,t,i){this.emit("eventDone",e),this.callbacks.sendEventResult(e,t,i)}deliverInboundEvent(e){if(this.eventResults?.has(e.session_id,e.event_id)){const t=this.eventResults.get(e.session_id,e.event_id);a.info("acp-adapter",`Deduplicating event ${e.event_id} (cached: ${t.status})`),this.sendTerminalEventWithoutRun(e.event_id,t.status,t.msg);return}if(this.compacting){a.info("acp-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.deferEvent(e);return}if(this.activeRun){a.info("acp-adapter",`Event ${e.event_id} rejected: busy`),this.sendTerminalEventWithoutRun(e.event_id,"failed","agent busy");return}if(!this.agentProcess?.alive){a.warn("acp-adapter",`Event ${e.event_id} cannot start: agent process not alive; requesting session recovery`),this.emit("internalError",{eventId:e.event_id,sessionId:e.session_id,errorMsg:"agent not alive",replayOriginalContent:!0});return}e.session_id&&e.session_id!==this.currentAibotSessionId&&(this.currentAibotSessionId=e.session_id),this.startRun(e,!1)}deliverStopEvent(e,t){this.acpClient?(this.acpClient.cancel().catch(()=>{}),this.flushStream()):this.flushStream(),this.activeRun?.eventId===e&&this.finishRun("canceled","stopped by user")}deferEvent(e){const t=this.deferredEvents.get(e.session_id)??[];t.some(i=>i.event.event_id===e.event_id)||(t.push({event:e,queuedAt:Date.now()}),this.deferredEvents.set(e.session_id,t),a.info("acp-adapter",`Deferred event ${e.event_id} for session ${e.session_id} (queue: ${t.length})`),this.scheduleDeferredTimeout(e.session_id))}deferredTimers=new Map;rejectDeferredEvents(e){for(const[t,i]of this.deferredEvents)for(const{event:s}of i)a.info("acp-adapter",`Rejecting deferred event ${s.event_id}: ${e}`),this.sendTerminalEventWithoutRun(s.event_id,"failed",e);this.deferredEvents.clear(),this.cancelAllDeferredTimers()}cancelDeferredTimer(e){const t=this.deferredTimers.get(e);t&&(clearTimeout(t),this.deferredTimers.delete(e))}cancelAllDeferredTimers(){for(const e of this.deferredTimers.values())clearTimeout(e);this.deferredTimers.clear()}scheduleDeferredTimeout(e){if(this.deferredTimers.has(e))return;const t=3e4,i=setTimeout(()=>{this.deferredTimers.delete(e);const s=this.deferredEvents.get(e);if(!(!s||s.length===0)&&!this.acpClient?.isAlive){a.error("acp-adapter",`Deferred events for session ${e} timed out after ${t/1e3}s (no ACP client)`),this.deferredEvents.delete(e);for(const{event:n}of s)this.sendTerminalEventWithoutRun(n.event_id,"failed","agent initialization timed out")}},t);this.deferredTimers.set(e,i)}startRun(e,t){if(!this.acpClient?.isAlive){this.deferEvent(e);return}const i=`acp_${++this.clientMsgSeq}_${Date.now()}`;this.activeRun={eventId:e.event_id,sessionId:e.session_id,threadId:e.thread_id,clientMsgIdBase:i,currentClientMsgId:i,currentSegmentIndex:0,chunkSeq:0,textSegmentInterrupted:!1,buffer:"",quotedStream:new S,markdownSegmenter:new ge,quotedMessageId:void 0,flushTimer:null,idleTimer:null,awaitingToolResult:!1,responded:!1,silent:t,lastProgressAt:Date.now(),lastIdleCheckAt:Date.now(),idleNoProgressCount:0,consecutivePingFailures:0,lastToolProgress:new Map,lastToolProgressSentAt:new Map,toolNamesById:new Map,sentToolUseIds:new Set,lastToolUse:null,lastToolResult:null,busyRetryTimer:null,busyWaitSince:0,busyRetryCount:0,busyWaiting:!1};const s=this.activeRun;this.beginAuditCapture(e);const n=ve(e,this.resolveCwd());this.resetIdleTimer(s),n.modeId&&this.acpClient&&this.acpClient.setLiveMode(n.modeId).catch(()=>{}),n.modelId&&this.acpClient&&this.acpClient.setModel(n.modelId).catch(()=>{});const o=Ie(n.prompt,{messageId:e.msg_id,quotedMessageId:e.quoted_message_id}),r=this.injectQuoteProtocolOnce(s.sessionId,o),l=this.identity.injectOnce(s.sessionId,r);if(this.bindingStore&&s.sessionId){const u=this.callbacks.getAgentProfile?.();this.bindingStore.setIdentitySnapshot(s.sessionId,u?.agentName?.trim()??"",u?.introduction?.trim()??"")}const d=this.injectSessionContextOnce(s.sessionId,l),p=this.injectRecoveryContext(s.sessionId,d);y(this.config.command)==="grok"&&(s.grokEventsOffset=ke(this.acpClient?.sessionId)),this.sendPromptWithRetry(s,p)}injectQuoteProtocolOnce(e,t){return!e||this.quoteProtocolTaughtSessions.has(e)?t:(this.quoteProtocolTaughtSessions.add(e),T(t,Fe))}injectSessionContextOnce(e,t){return!e||!this.sessionContextPending?t:(this.sessionContextPending=!1,a.info("acp-adapter",`Injected Grix session context for session=${e}`),T(t,oe(e,this.callbacks.getAgentId?.())))}injectRecoveryContext(e,t){const i=this.recoveryContextBySessionId.get(e);return i?(this.recoveryContextBySessionId.delete(e),a.info("acp-adapter",`Injecting recovery context for session ${e} (chars=${i.length})`),T(t,`[recovery-context]
|
|
1
|
+
import{fileURLToPath as te}from"node:url";import f from"node:path";import{homedir as I}from"node:os";import{promises as y,statSync as $}from"node:fs";import{EventEmitter as q}from"node:events";import{spawn as O}from"node:child_process";import{AgentProcess as ie}from"../../agent/process.js";import{hasChildProcesses as se,listGroupPids as ne}from"../../core/runtime/spawn.js";import{applyNativeProviderConfig as oe,agentIdOf as A}from"../shared/native-provider-config.js";import{applyMcodeProviderConfig as re}from"./mcode-provider-config.js";import{buildSessionContextBlock as ae}from"../shared/session-context.js";import{IdentityInjector as le}from"../shared/identity-injector.js";import{compactToolInputForWire as N}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as de,resolveKimiCodeHome as ce}from"../../default-skills/index.js";import{resolveHermesHomeDir as ue}from"../shared/native-provider-config.js";import{removeKimiLayerPlugin as he}from"../../kimi-plugins/index.js";import{AcpClient as pe,AcpAuthRequiredError as fe,isAuthRequiredError as me}from"../../protocol/acp-client.js";import{AgentEventType as m}from"../../types/events.js";import{InternalApiServer as ge}from"../../core/mcp/internal-api-server.js";import{EventResultsStore as ve}from"../../core/persistence/event-results-store.js";import{QuotedMessageStream as S}from"../../core/util/quoted-message-stream.js";import{SafeMarkdownStreamSegmenter as Ie}from"../../core/text-segmentation/index.js";import{extractAcpTurnInput as Ae}from"../../core/protocol/payload-parser.js";import{injectMessageMetadata as ye}from"../../core/protocol/message-metadata.js";import{insertBeforeTrailingMessageReferences as k}from"../../core/protocol/message-reference.js";import{log as a}from"../../core/log/index.js";function D(c,e=2e3){let t;try{const i=new WeakSet;t=JSON.stringify(c,(s,n)=>{if(n instanceof Error)return{name:n.name,message:n.message};if(typeof n=="function")return"[function]";if(typeof n=="bigint"||typeof n=="symbol")return n.toString();if(typeof n=="object"&&n!==null){if(i.has(n))return"[circular]";i.add(n)}return n})}catch(i){t=`[stringify failed: ${i instanceof Error?i.message:String(i)}]`}return t===void 0?"[undefined]":t.length<=e?t:`${t.slice(0,e)}...[+${t.length-e}b]`}const Ce=5e3;function L(c,e){const t=e.toolName??"";return e.toolCallId&&(!t||t===e.toolCallId)?c.toolNamesById.get(e.toolCallId)??t:t}function b(c){const e=String(c??"").trim();if(!e)return"";try{const t=JSON.parse(e);return JSON.stringify(R(t))}catch{return e}}function R(c){if(c===null||typeof c!="object")return c;if(Array.isArray(c))return c.map(R);const e=c,t=Object.keys(e).sort(),i={};for(const s of t)i[s]=R(e[s]);return i}function U(c){const e=Array.isArray(c)?c:[c],t=[];for(const i of e){if(!i||typeof i!="object")continue;const s=i;if(typeof s.text=="string"&&s.text.trim()){t.push(s.text.trim());continue}const n=s.content;if(n&&typeof n=="object"&&!Array.isArray(n)){const o=n.text;typeof o=="string"&&o.trim()&&t.push(o.trim())}}return t.join(`
|
|
2
|
+
`)}function _e(c,e,t){const i=c&&typeof c=="object"?c:{},s=i.toolCall&&typeof i.toolCall=="object"?i.toolCall:{},n=[s.rawInput,s.raw_input,s.input,s.arguments,s.args,U(s.content),s.content,s.description,i.tool_input,i.toolInput,e];for(const o of n){const r=N(o);if(r&&r!==t)return r}return""}const B=/^q\d+_opt_\d+$/,P=/^q\d+_skip$/,Se=new Set(["allow_once","allow_always","reject_once","reject_always"]);function be(c){if(!`${c.toolName} ${c.toolTitle}`.toLowerCase().replace(/[^a-z]/g,"").includes("askuserquestion"))return null;const t=c.options;if(t.length===0)return null;const i=t.some(l=>B.test(l.optionId)),s=i?t.filter(l=>B.test(l.optionId)):t.filter(l=>!P.test(l.optionId));if(s.length===0||!i&&s.every(l=>Se.has(l.kind)))return null;const n=c.rawParams&&typeof c.rawParams=="object"?c.rawParams:{},o=n.toolCall&&typeof n.toolCall=="object"?n.toolCall:{},r=U(o.content).trim();return r?{prompt:r,answerOptions:s}:null}import{scanSkills as F}from"../claude/skill-scanner.js";import{checkKiroSessionActivity as Te,checkKimiSessionActivity as we,checkQoderSessionActivity as j,checkDimSessionActivity as ke,hasRunningKimiDetachedTask as Re}from"./session-activity.js";import{evaluateGrokLiveness as K,grokEventsByteSize as Pe}from"./grok-liveness.js";import{resolveCliPath as Ee,getCliVersion as xe}from"../../core/util/cli-probe.js";const E=f.dirname(te(import.meta.url)),H=[{modelId:"deepseek-v4-pro",name:"DeepSeek V4 Pro"},{modelId:"deepseek-v4-flash",name:"DeepSeek V4 Flash"}],x=[{modelId:"kimi-code/kimi-for-coding",name:"K2.7 Coding"},{modelId:"kimi-code/kimi-for-coding-highspeed",name:"K2.7 Coding Highspeed"},{modelId:"kimi-code/k3",name:"K3"}];function M(c,e){const t=Number(process.env[c]);return Number.isFinite(t)&&t>0?t:e}const Me=200,$e=60*1e3,qe=600*1e3,T=M("GRIX_ACP_TURN_INACTIVITY_TIMEOUT_MS",900*1e3),G=2,W=5e3,Q=80,z=600*1e3,X=1200*1e3,Oe=M("GRIX_ACP_BUSY_RETRY_INTERVAL_MS",5e3),V=M("GRIX_ACP_BUSY_WAIT_MAX_MS",1800*1e3),Ne=6e4,De=2e3,Le=12e3,Y=3e3,J=3e4,Ue=1e3,Be=1e4;function Fe(c){return new Promise(e=>setTimeout(e,c))}const je=["[grix protocol] Markers like [[message_id:<id>]] and [[quoted_message_id:<id>]] are metadata, not user prose \u2014 never repeat them verbatim except as instructed here.","The message you are replying to carries its id in a [[message_id:<id>]] marker.","If (and only if) you want your reply to quote/thread onto that specific message, include [[quoted_message_id:<id>]] anywhere in your reply using that id; otherwise omit it."].join(" ");function Ke(c){return!(!(c instanceof Error)||c.code!==-32603||me(c))}function Z(c){if(!(c instanceof Error))return!1;const e=c.data;return e&&typeof e=="object"&&e.code==="turn.agent_busy"?!0:/cannot launch a new turn/i.test(c.message)}function C(c){if(!(c instanceof Error))return String(c);let e=c.message;const t=c.data;return t&&(e+=` data=${JSON.stringify(t)}`),e}function He(c){return c.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"")}class ee extends q{type="acp";config;callbacks;agentProcess=null;acpClient=null;internalApi=null;activeRun=null;compacting=!1;compactingTimer=null;compactionDoneResolver=null;pendingAutoCompact=!1;eventResults=null;pendingApprovals=new Map;pendingQuestions=new Map;clientMsgSeq=0;stopped=!1;acpAuthMethod;acpInitialMode;acpInitialModel;newSessionParams;acpMcpTools;terminalAuthChild=null;rawTransport;approvalMode;autoInjectArgs;nativeProviderScope;reasonixAuditTranscriptPath;auditAgentType;trimToolWirePayload;activeAuditEventId=null;auditCaptures=new Map;completedAuditBoundaries=new Map;bindingStore;sessionBindings=new Map;deferredEvents=new Map;currentAibotSessionId;bridgeLog;sessionConnected=!1;sessionContextPending=!1;baselineGroupPids=[];rawEventSeq=0;recoveryContextBySessionId=new Map;quoteProtocolTaughtSessions=new Set;identity;orphanBuffer="";orphanQuotedStream=new S;orphanFlushTimer=null;orphanSessionId=null;orphanSuppressedUntil=0;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.identity=new le("acp-adapter",t.getAgentProfile),this.bridgeLog=i?.bridgeLog??null,this.acpAuthMethod=i?.acpAuthMethod,this.acpInitialMode=i?.acpInitialMode,this.acpInitialModel=i?.acpInitialModel,this.newSessionParams=i?.newSessionParams,this.acpMcpTools=i?.acpMcpTools??!0,this.rawTransport=i?.rawTransport??!1,this.approvalMode=i?.approvalMode??"default",this.autoInjectArgs=i?.autoInjectArgs,this.nativeProviderScope=i?.nativeProviderScope,this.reasonixAuditTranscriptPath=i?.reasonixAuditTranscriptPath,this.auditAgentType=String(i?.agentType??f.basename(e.command)).trim().toLowerCase();const s=f.basename(e.command).toLowerCase(),n=this.auditAgentType==="copilot"||/^copilot(?:\.cmd)?$/i.test(s)||/^gh(?:\.exe)?$/i.test(s)&&(e.args??[]).includes("copilot");if(this.trimToolWirePayload=["kimi","kiro","qwen","reasonix","copilot"].includes(this.auditAgentType)||s.includes("kimi")||s==="kiro-cli"||/^qwen(?:\.cmd)?$/i.test(s)||s.includes("reasonix")||n,this.bindingStore=i?.bindingStore??null,this.currentAibotSessionId=i?.aibotSessionId?String(i.aibotSessionId).trim():void 0,i?.eventResultsPath&&(this.eventResults=new ve(i.eventResultsPath)),this.bindingStore&&this.currentAibotSessionId){const o=this.bindingStore.get(this.currentAibotSessionId);o?.cwd&&this.sessionBindings.set(this.currentAibotSessionId,o.cwd)}}async start(){if(await this.spawnProcess(),!this.bindingStore){await this.connectSession(this.resolveCwd());return}const e=this.currentAibotSessionId?this.sessionBindings.get(this.currentAibotSessionId):void 0;e&&await this.connectSession(e)}async stop(){this.stopped=!0,this.rejectDeferredEvents("adapter stopped"),this.cancelAllDeferredTimers(),this.pendingAutoCompact=!1,this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver("stopped"),this.compactionDoneResolver=null),this.activeRun&&this.finishRun("canceled","adapter stopped"),this.flushOrphanBuffer(),this.acpClient&&(this.acpClient.dispose(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(await this.agentProcess.close(),this.agentProcess=null),this.baselineGroupPids=[],this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.terminalAuthChild&&(this.terminalAuthChild.kill("SIGKILL"),this.terminalAuthChild=null)}isAlive(){return this.agentProcess?.alive??!1}async createSession(e){return this.acpClient?.sessionId??""}async resumeSession(e,t){}async destroySession(e){this.quoteProtocolTaughtSessions.delete(e),this.identity.forgetSession(e)}onAgentProfileChanged(){this.identity.onProfileChanged()}sendPrompt(e){const t=new Ge(e.adapterSessionId);return this.acpClient?.isAlive&&this.acpClient.send(e.text).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),t}async cancel(e){this.activeRun&&this.acpClient&&(await this.acpClient.cancel(),this.flushStream(),this.finishRun("canceled","stopped by user"),this.suppressOrphanOutput(J))}setPermissionHandler(e){}async ping(e){return this.acpClient?.isAlive?this.acpClient.ping(e):this.agentProcess?.alive??!1}getStatus(){return{alive:this.agentProcess?.alive??!1,busy:this.activeRun!==null||this.compacting,sessions:this.sessionConnected?1:0}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.activeRun&&(this.snapshotAuditBoundary(this.activeRun.eventId),this.clearRunTimers(this.activeRun),this.activeRun=null)}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearRunTimers(e){e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null),e.busyRetryTimer&&(clearTimeout(e.busyRetryTimer),e.busyRetryTimer=null)}getMcpConfig(){if(!this.internalApi)return null;this.internalApi.setMcpBridgeUpHandler(t=>this.onMcpBridgeUp(t));const e=f.resolve(E,"../../mcp/mcp-bridge-server.js");return{name:"grix-app-bridge",command:process.execPath,args:[e,"--ws-url",this.internalApi.mcpBridgeWsUrl]}}async hasBackgroundWork(){const e=this.agentProcess?.pid;return e?se(e,[e,...this.baselineGroupPids]):!1}captureBaselineGroupPids(){const e=this.agentProcess?.pid;e&&ne(e).then(t=>{this.baselineGroupPids=t}).catch(()=>{})}async probe(e){const t=this.config.command||"gemini",i=await Ee(t),s=i!==null;let n=null,o;if(s){const h=await xe(t);n=h.version,h.error&&(o=h.error)}else o={code:"cli_not_found",message:`command not found: ${t}`};const r=this.acpClient?.model??null,l=this.getStatus();let d;return e?.conversation?this.acpClient?.isAlive?d={attempted:!0,ok:!0,latency_ms:null}:d={attempted:!0,ok:!1,latency_ms:null,error:{code:"unsupported",message:"ACP session not connected, cannot probe conversation"}}:d={attempted:!1,ok:!1,latency_ms:null},{cli:{command:t,installed:s,path:i,version:n,...o?{error:o}:{}},conversation:d,config:{model:r,base_url:null,source:{model:r?"runtime":"unknown",base_url:"unknown"}},process:{started:!!this.agentProcess,alive:l.alive,busy:l.busy}}}getSupportedCommands(){return this.acpClient?.availableCommands?.length?this.acpClient.availableCommands.map(e=>({name:e.name,description:e.description??"",args:e.args})):[{name:"model",description:"List or set model",args:"[model_id]"},{name:"mode",description:"List or set collaboration mode",args:"[mode_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(e,t,i){return this.acpClient?.supportsCommandsExecute?this.execCommandViaAcp(e,t):this.execCommandFallback(e,t)}async execCommandViaAcp(e,t){if(!this.acpClient)return{status:"failed",message:"No active ACP session"};if(e==="interrupt")return this.activeRun?(await this.cancel(this.activeRun.sessionId),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};if(e==="compact"){if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.activeRun)return{status:"failed",message:"agent busy"};this.compacting=!0;try{const i=await this.acpClient.executeCommand(e,t||void 0,z);return this.finishCompaction("acp-commands-execute"),i.status==="failed"?{status:"failed",message:(i.message??"").includes("timed out")?"Compaction timed out after 10 minutes":i.message??"compact failed",data:i.data}:{status:"ok",message:i.message??"Compacted",data:i.data}}catch(i){return this.finishCompaction("error"),i?.code===-32601?this.execCommandFallback(e,t):{status:"failed",message:`compact failed: ${i instanceof Error?i.message:i}`}}}try{const i=await this.acpClient.executeCommand(e,t||void 0);return{status:i.status??"ok",message:i.message,data:i.options?{command:e,options:i.options}:i.data}}catch(i){return i?.code===-32601?this.execCommandFallback(e,t):{status:"failed",message:`Command failed: ${i instanceof Error?i.message:i}`}}}async execCommandFallback(e,t){try{switch(e){case"model":{const i=t.trim();if(i)return await this.setModel(i)?{status:"ok",message:`Model set to ${i}`}:{status:"failed",message:`Failed to set model: ${i}`};const s=this.buildToolbarContext("model_list");return{status:"ok",message:`Current: ${s.currentModelId||"unknown"}`,data:s}}case"mode":{const i=t.trim();if(i)return await this.setMode(i)?{status:"ok",message:`Mode set to ${i}`}:{status:"failed",message:`Failed to set mode: ${i}`};const s=this.buildToolbarContext("mode_list");return{status:"ok",message:`Current: ${s.currentModeId||"unknown"}`,data:s}}case"interrupt":return this.activeRun?this.acpClient?(await this.cancel(this.activeRun.sessionId),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"Not connected"}:{status:"failed",message:"No active run to interrupt"};case"compact":{if(!this.acpClient)return{status:"failed",message:"No active ACP session"};if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.activeRun)return{status:"failed",message:"agent busy"};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});try{await this.acpClient.send("/compact")}catch(n){throw this.finishCompaction("send-failed"),n}this.compactingTimer=setTimeout(()=>this.finishCompaction("timeout"),z),this.compactingTimer.unref?.();const s=await i;return s==="timeout"?{status:"failed",message:"Compaction timed out after 10 minutes"}:s==="stopped"?{status:"failed",message:"Adapter stopped during compaction"}:{status:"ok",message:"Compacted"}}case"status":{const i=this.getStatus(),s=this.acpClient?.sessionOptions;return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Model: ${s?.currentModelId??"unknown"}, Mode: ${s?.currentModeId??"unknown"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,model:s?.currentModelId??"",mode:s?.currentModeId??""}}}case"skills":{const i=F({mode:this.config.command==="kiro-cli"?"kiro":"gemini",projectDir:process.cwd()}),s=i.map(n=>`- ${n.name}${n.trigger?` (${n.trigger})`:""} [${n.source}]: ${n.description}`);return{status:"ok",message:s.length>0?s.join(`
|
|
3
|
+
`):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}get acpSessionOptions(){const e=this.acpClient?.sessionOptions??null,t=this.isReasonix?H:this.isKimi?x:null;if(!t||e&&e.models.length>0)return e;const i=this.resolveFallbackCurrentModelId(t,e?.currentModelId??"");return{modes:e?.modes??[],currentModeId:e?.currentModeId??"",models:[...t],currentModelId:i,...e?.thoughtLevels?.length?{thoughtLevels:e.thoughtLevels,currentThoughtLevelId:e.currentThoughtLevelId,thoughtLevelConfigId:e.thoughtLevelConfigId}:{}}}resolveFallbackCurrentModelId(e,t){if(e.some(s=>s.modelId===t))return t;const i=(this.autoInjectArgs?.model??this.acpInitialModel??"").trim();return i&&e.some(s=>s.modelId===i)?i:e[0]?.modelId??""}get isReasonix(){return(this.config.command??"").includes("reasonix")}get isKimi(){return(this.config.command??"").includes("kimi")}buildToolbarContext(e,t){const i=this.acpClient?.sessionOptions,s=i?.currentModeId??"";let n=i?.currentModelId??"";const o=i?.modes.map(p=>({id:p.id,name:p.name}))??[],r=i?.models&&i.models.length>0,l=r?i.models:this.isReasonix?H:this.isKimi?x:[],d=r?"acp":this.isReasonix?"reasonix_fallback":this.isKimi?"kimi_fallback":"empty";this.isKimi&&!r&&a.warn("acp-adapter",`[toolbar-diag] kimi ACP session returned no models; using static fallback. command=${this.config.command} fallbackIds=${JSON.stringify(x.map(p=>p.modelId))}`),a.info("acp-adapter",`[toolbar-diag] buildToolbarContext outcome=${e} agent=${this.config.command} modelSource=${d} acpModelCount=${i?.models?.length??0} finalModelCount=${l.length}`);const h=l.map(p=>({modelId:p.modelId,name:p.name})),u=l.map(p=>({id:p.modelId,displayName:p.name})),v=i?.modes.map(p=>({id:p.id,displayName:p.name}))??[];u.length>0&&!u.some(p=>p.id===n)&&(n=this.resolveFallbackCurrentModelId(l,n));const g={outcome:e,...t?{cwd:t}:{},model_id:n,mode_id:s,currentModelId:n,currentModeId:s,available_models:u,available_modes:v,availableModels:u,availableModes:v,models:h,modes:o},_=i?.thoughtLevels??[];if(_.length>0){let p=i?.currentThoughtLevelId??"";p&&!_.some(w=>w.id===p)&&(p=_[0]?.id??""),g.available_efforts=_.map(w=>w.id),g.effort=p,g.reasoning_effort=p}return a.info("acp-adapter",`[toolbar] buildToolbarContext outcome=${e} model_id="${n}" available_models=${JSON.stringify(u.map(p=>p.id))} currentModelId=${n} efforts=${JSON.stringify(g.available_efforts??[])}`),g}get pendingApprovalEntries(){return this.pendingApprovals}get hasSessionBinding(){return this.bindingStore!==null}setMode(e){return this.acpClient?this.acpClient.setLiveMode(e):Promise.resolve(!1)}setModel(e){return this.acpClient?this.acpClient.setModel(e):Promise.resolve(!1)}setReasoningEffort(e){if(!this.acpClient?.hasThoughtLevel)return Promise.resolve(!1);const t=this.acpClient.sessionOptions.thoughtLevelConfigId||"thinking";return this.acpClient.setConfigOption(t,e)}handleAcpApprovalAction(e,t){const i=this.pendingApprovals.get(e);return i?(a.info("acp-adapter","handleAcpApprovalAction resolving",{toolCallId:e,requestId:i,behavior:t}),this.pendingApprovals.delete(e),this.acpClient&&this.acpClient.respondPermission(i,{behavior:t}).catch(s=>{a.error("acp-adapter",`Failed to respond to permission: ${s}`)}),this.captureAuditEvent({type:m.PermissionResponse,requestId:i,toolCallId:e,permissionDecision:t}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),!0):(a.warn("acp-adapter","handleAcpApprovalAction: no pending approval",{toolCallId:e,behavior:t,pendingCount:this.pendingApprovals.size}),!1)}handleExecApprovalEvent(e){const t=String(e.tool_call_id??e.approval_command_id??e.approval_id??e.exec_context_id??"");return t?this.handleAcpApprovalAction(t,e.decision)?{delivered:!0}:{delivered:!1,errorCode:"approval_not_found",errorMsg:`no pending approval for tool_call_id: ${t}`}:{delivered:!1,errorCode:"approval_id_required",errorMsg:"approval id is required"}}respondToPermission(e,t){this.acpClient&&this.acpClient.respondPermission(e,t).catch(i=>{a.error("acp-adapter",`Failed to respond to permission: ${i}`)}),this.captureAuditEvent({type:m.PermissionResponse,requestId:e,permissionDecision:t.behavior}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun))}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};if(t==="claude_interaction_reply"&&String(i.kind??"")==="permission"){const s=i.resolution&&typeof i.resolution=="object"?i.resolution:{},n=String(s.value??i.decision??"");return["allow","allow-once","allow-always","deny"].includes(n)?this.handleLocalAction({...e,action_type:n==="deny"?"permission_reject":"permission_approve",params:{...i,approval_command_id:i.request_id,decision:n}}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"permission_decision_invalid","permission decision is invalid"),{handled:!0,kind:"approval"})}if(t==="claude_interaction_reply")return this.handleAcpQuestionReply(e);if(t==="set_reasoning_effort")return this.handleSetReasoningEffortAction(e);if(t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject"){const s=String(i.tool_call_id??i.approval_command_id??i.approval_id??i.exec_context_id??""),n=t==="exec_approve"||t==="permission_approve",o=String(i.decision??"");let r;return n&&(o==="allow-once"||o==="allow-always")?r=o:n?r="allow":r="deny",s?this.handleAcpApprovalAction(s,r)?(this.callbacks.sendLocalActionResult(e.action_id,"ok"),{handled:!0,kind:"approval"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_not_found",`no pending approval for tool_call_id: ${s}`),{handled:!0,kind:"approval"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"tool_call_id_required","tool_call_id is required"),{handled:!0,kind:"approval"})}return{handled:!1,kind:""}}async handleSetReasoningEffortAction(e){const t=e.params??{},i=String(t.reasoning_effort??t.reasoning_eff??t.effort??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"set_reasoning_effort_invalid","reasoning_effort is required"),{handled:!0,kind:"set_reasoning_effort_rejected"};if(!this.acpClient?.hasThoughtLevel)return this.callbacks.sendLocalActionResult(e.action_id,"failed",{outcome:"effort_rejected",available_efforts:[]},"unsupported_reasoning_effort","reasoning_effort is not supported by this ACP agent"),{handled:!0,kind:"set_reasoning_effort_rejected"};const s=this.acpClient.sessionOptions.thoughtLevels??[];if(s.length>0&&!s.some(o=>o.id===i)){const o=s.map(r=>r.id);return this.callbacks.sendLocalActionResult(e.action_id,"failed",{outcome:"effort_rejected",available_efforts:o},"unsupported_reasoning_effort",`reasoning_effort must be one of: ${o.join(", ")}`),{handled:!0,kind:"set_reasoning_effort_rejected"}}return await this.setReasoningEffort(i)?(this.callbacks.sendLocalActionResult(e.action_id,"ok",this.buildToolbarContext("effort_set")),{handled:!0,kind:"set_reasoning_effort"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",this.buildToolbarContext("effort_set_failed"),"set_reasoning_effort_failed",`Failed to set reasoning_effort: ${i}`),{handled:!0,kind:"set_reasoning_effort_rejected"})}async handleQuestionReplyEvent(e){let t;if(e.action)t={type:"action",value:e.action};else if(e.response?.type==="single")t={type:"text",value:e.response.value};else if(e.response?.type==="map")t={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:t})}async handleAcpQuestionReply(e){const t=await this.deliverQuestionReply(e.params??{});return t.delivered?(this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result),{handled:!0,kind:t.kind??"question_reply"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:t.kind??"question_reply_failed"})}async deliverQuestionReply(e){const t=String(e.request_id??"").trim(),i=this.pendingQuestions.get(t);if(!t||!i||!this.acpClient)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered.",kind:"question_reply_not_pending"};const s=e.resolution&&typeof e.resolution=="object"?e.resolution:{},n=String(s.type??"");let o,r="";if(n==="action"&&String(s.value??"")==="cancel")o=i.options.find(d=>/_skip$/.test(d.optionId)||d.kind.toLowerCase().includes("reject"));else{if(n==="text")r=String(s.value??"").trim();else if(n==="map"){const d=Array.isArray(s.entries)?s.entries:[];r=String(d[0]?.value??"").trim()}o=i.options.find(d=>d.name.trim()===r||d.optionId===r)}if(!o){const d=i.options.find(h=>P.test(h.optionId));return r&&d?this.deliverFreeTextAnswer(t,d.optionId,r):{delivered:!1,errorCode:"question_answer_invalid",errorMsg:"The selected answer does not match a pending question option. The question is still open; please tap one of the options on the card (free-text answers are not supported).",kind:"question_reply_invalid"}}try{await this.acpClient.respondPermissionOption(t,o.optionId)}catch(d){return{delivered:!1,errorCode:"question_reply_failed",errorMsg:d instanceof Error?d.message:String(d),kind:"question_reply_failed"}}this.pendingQuestions.delete(t);const l=/_skip$/.test(o.optionId);return this.captureAuditEvent({type:m.PermissionResponse,requestId:t,permissionDecision:l?"deny":"allow"}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),{delivered:!0,result:{request_id:t,resolution:l?"cancel":"answer"},kind:l?"question_reply_cancel":"question_reply"}}async deliverFreeTextAnswer(e,t,i){const s=this.acpClient;if(!s)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered.",kind:"question_reply_not_pending"};try{await s.respondPermissionOption(e,t)}catch(o){return{delivered:!1,errorCode:"question_reply_failed",errorMsg:o instanceof Error?o.message:String(o),kind:"question_reply_failed"}}this.pendingQuestions.delete(e),this.captureAuditEvent({type:m.PermissionResponse,requestId:e,permissionDecision:"deny"});const n=Date.now()+Be;for(;;)try{await s.send(i);break}catch(o){if(!Z(o)||Date.now()>=n)return a.warn("acp-adapter","free-text answer delivery failed after question dismissed",{requestId:e,error:C(o)}),{delivered:!1,errorCode:"question_free_text_delivery_failed",errorMsg:"The question was dismissed, but the free-text answer could not be delivered while the agent was busy. Please resend it as a normal message.",kind:"question_reply_failed"};await Fe(Ue)}return a.info("acp-adapter","free-text answer delivered via skip + follow-up prompt",{requestId:e}),this.activeRun&&(this.activeRun.lastProgressAt=Date.now(),this.resetIdleTimer(this.activeRun)),{delivered:!0,result:{request_id:e,resolution:"answer"},kind:"question_reply_free_text"}}resolveCwd(){if(this.currentAibotSessionId){const e=this.sessionBindings.get(this.currentAibotSessionId);if(e)return e}if(this.bindingStore&&this.currentAibotSessionId){const e=this.bindingStore.get(this.currentAibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async bindSession(e,t){const i=this.sessionBindings.get(e);if(i)try{return await y.stat(i),!1}catch{a.info("acp-adapter",`Stale binding for session ${e}: ${i} no longer exists, allowing rebind to ${t}`),this.sessionBindings.delete(e)}return this.sessionBindings.set(e,t),this.bindingStore&&this.bindingStore.set(e,t),this.maybeRefreshKiroSkills(t),!this.sessionConnected&&this.agentProcess?.alive?this.connectSession(t).then(()=>!0).catch(s=>{a.error("acp-adapter",`Failed to create session on bind: ${C(s)}`);const n=this.buildToolbarContext("bind_failed",t),o=Array.isArray(n.available_models)&&n.available_models.length>0;return this.callbacks.sendUpdateBindingCard(e,"failed",t,o?n:void 0),!0}):(this.acpClient?.isAlive&&(this.bindingStore&&this.acpClient.sessionId&&this.bindingStore.setAcpSessionId(e,this.acpClient.sessionId),this.callbacks.sendUpdateBindingCard(e,"connected",t,this.buildToolbarContext("binding_ready",t))),Promise.resolve(!0))}getSessionCwd(e){return this.sessionBindings.get(e)}getSessionBindings(){return this.sessionBindings}maybeRefreshKiroSkills(e){if(this.config.command!=="kiro-cli"||!this.callbacks.onSkillsUpdate)return;const t=String(e??"").trim()||void 0;let i=[];try{i=F({mode:"kiro",projectDir:t})}catch(s){a.warn("acp-adapter",`Kiro skills scan failed: ${s instanceof Error?s.message:String(s)}`);return}try{this.callbacks.onSkillsUpdate(i,t)}catch(s){a.warn("acp-adapter",`onSkillsUpdate failed: ${s instanceof Error?s.message:String(s)}`)}}replayDeferredEvents(e){const t=this.deferredEvents.get(e);if(!t||t.length===0)return;if(this.activeRun){a.info("acp-adapter",`Cannot replay deferred events for session ${e}: agent busy`);return}const i=t.shift();i&&(t.length===0?(this.deferredEvents.delete(e),this.cancelDeferredTimer(e)):this.deferredEvents.set(e,t),a.info("acp-adapter",`Replaying deferred event ${i.event.event_id} for session ${e} (remaining: ${t.length})`),this.startRun(i.event,!1))}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.suppressOrphanOutput(J),a.info("acp-adapter",`Compaction finished (${e}); replaying deferred events`),this.replayNextDeferredEvent();const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.(e)}replayNextDeferredEvent(){if(this.activeRun||this.compacting)return;const e=this.deferredEvents.keys().next().value;e&&this.replayDeferredEvents(e)}announceDeferredComposing(e){}sendTerminalEventWithoutRun(e,t,i){this.emit("eventDone",e),this.callbacks.sendEventResult(e,t,i)}deliverInboundEvent(e){if(this.eventResults?.has(e.session_id,e.event_id)){const t=this.eventResults.get(e.session_id,e.event_id);a.info("acp-adapter",`Deduplicating event ${e.event_id} (cached: ${t.status})`),this.sendTerminalEventWithoutRun(e.event_id,t.status,t.msg);return}if(this.compacting){a.info("acp-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.deferEvent(e);return}if(this.activeRun){a.info("acp-adapter",`Event ${e.event_id} rejected: busy`),this.sendTerminalEventWithoutRun(e.event_id,"failed","agent busy");return}if(!this.agentProcess?.alive){a.warn("acp-adapter",`Event ${e.event_id} cannot start: agent process not alive; requesting session recovery`),this.emit("internalError",{eventId:e.event_id,sessionId:e.session_id,errorMsg:"agent not alive",replayOriginalContent:!0});return}e.session_id&&e.session_id!==this.currentAibotSessionId&&(this.currentAibotSessionId=e.session_id),this.startRun(e,!1)}deliverStopEvent(e,t){this.acpClient?(this.acpClient.cancel().catch(()=>{}),this.flushStream()):this.flushStream(),this.activeRun?.eventId===e&&this.finishRun("canceled","stopped by user")}deferEvent(e){const t=this.deferredEvents.get(e.session_id)??[];t.some(i=>i.event.event_id===e.event_id)||(t.push({event:e,queuedAt:Date.now()}),this.deferredEvents.set(e.session_id,t),a.info("acp-adapter",`Deferred event ${e.event_id} for session ${e.session_id} (queue: ${t.length})`),this.scheduleDeferredTimeout(e.session_id))}deferredTimers=new Map;rejectDeferredEvents(e){for(const[t,i]of this.deferredEvents)for(const{event:s}of i)a.info("acp-adapter",`Rejecting deferred event ${s.event_id}: ${e}`),this.sendTerminalEventWithoutRun(s.event_id,"failed",e);this.deferredEvents.clear(),this.cancelAllDeferredTimers()}cancelDeferredTimer(e){const t=this.deferredTimers.get(e);t&&(clearTimeout(t),this.deferredTimers.delete(e))}cancelAllDeferredTimers(){for(const e of this.deferredTimers.values())clearTimeout(e);this.deferredTimers.clear()}scheduleDeferredTimeout(e){if(this.deferredTimers.has(e))return;const t=3e4,i=setTimeout(()=>{this.deferredTimers.delete(e);const s=this.deferredEvents.get(e);if(!(!s||s.length===0)&&!this.acpClient?.isAlive){a.error("acp-adapter",`Deferred events for session ${e} timed out after ${t/1e3}s (no ACP client)`),this.deferredEvents.delete(e);for(const{event:n}of s)this.sendTerminalEventWithoutRun(n.event_id,"failed","agent initialization timed out")}},t);this.deferredTimers.set(e,i)}startRun(e,t){if(!this.acpClient?.isAlive){this.deferEvent(e);return}const i=`acp_${++this.clientMsgSeq}_${Date.now()}`;this.activeRun={eventId:e.event_id,sessionId:e.session_id,threadId:e.thread_id,clientMsgIdBase:i,currentClientMsgId:i,currentSegmentIndex:0,chunkSeq:0,textSegmentInterrupted:!1,buffer:"",quotedStream:new S,markdownSegmenter:new Ie,quotedMessageId:void 0,flushTimer:null,idleTimer:null,awaitingToolResult:!1,responded:!1,silent:t,lastProgressAt:Date.now(),lastIdleCheckAt:Date.now(),idleNoProgressCount:0,consecutivePingFailures:0,lastToolProgress:new Map,lastToolProgressSentAt:new Map,toolNamesById:new Map,sentToolUseIds:new Set,lastToolUse:null,lastToolResult:null,busyRetryTimer:null,busyWaitSince:0,busyRetryCount:0,busyWaiting:!1};const s=this.activeRun;this.beginAuditCapture(e);const n=Ae(e,this.resolveCwd());this.resetIdleTimer(s),n.modeId&&this.acpClient&&this.acpClient.setLiveMode(n.modeId).catch(()=>{}),n.modelId&&this.acpClient&&this.acpClient.setModel(n.modelId).catch(()=>{});const o=ye(n.prompt,{messageId:e.msg_id,quotedMessageId:e.quoted_message_id}),r=this.injectQuoteProtocolOnce(s.sessionId,o),l=this.identity.injectOnce(s.sessionId,r);if(this.bindingStore&&s.sessionId){const u=this.callbacks.getAgentProfile?.();this.bindingStore.setIdentitySnapshot(s.sessionId,u?.agentName?.trim()??"",u?.introduction?.trim()??"")}const d=this.injectSessionContextOnce(s.sessionId,l),h=this.injectRecoveryContext(s.sessionId,d);A(this.config.command)==="grok"&&(s.grokEventsOffset=Pe(this.acpClient?.sessionId)),this.sendPromptWithRetry(s,h)}injectQuoteProtocolOnce(e,t){return!e||this.quoteProtocolTaughtSessions.has(e)?t:(this.quoteProtocolTaughtSessions.add(e),k(t,je))}injectSessionContextOnce(e,t){return!e||!this.sessionContextPending?t:(this.sessionContextPending=!1,a.info("acp-adapter",`Injected Grix session context for session=${e}`),k(t,ae(e,this.callbacks.getAgentId?.())))}injectRecoveryContext(e,t){const i=this.recoveryContextBySessionId.get(e);return i?(this.recoveryContextBySessionId.delete(e),a.info("acp-adapter",`Injecting recovery context for session ${e} (chars=${i.length})`),k(t,`[recovery-context]
|
|
4
4
|
${i}
|
|
5
|
-
[/recovery-context]`)):t}sendPromptWithRetry(e,t){this.acpClient.send(t).then(()=>{this.activeRun===e&&(e.busyWaiting=!1)}).catch(i=>{if(
|
|
5
|
+
[/recovery-context]`)):t}sendPromptWithRetry(e,t){this.acpClient.send(t).then(()=>{this.activeRun===e&&(e.busyWaiting=!1)}).catch(i=>{if(Z(i)){this.scheduleAgentBusyRetry(e,t,C(i));return}if(a.error("acp-adapter",`Prompt failed: ${C(i)}`),Ke(i)){const n=C(i),o=e.eventId,r=e.sessionId;a.info("acp-adapter",`Internal error escalated to bridge: event=${o} session=${r} err=${n}`),this.silentlyDiscardActiveRun(e),this.emit("internalError",{eventId:o,sessionId:r,errorMsg:n});return}const s=i instanceof Error?i.message:String(i);this.finishRun("failed",s)})}scheduleAgentBusyRetry(e,t,i){if(this.activeRun!==e)return;e.busyWaiting=!0;const s=Date.now();e.busyWaitSince||(e.busyWaitSince=s);const n=s-e.busyWaitSince;if(n>=V){a.error("acp-adapter",`agent busy wait exceeded ${Math.round(V/6e4)}min, giving up event=${e.eventId}: ${i}`),e.buffer+=`
|
|
6
6
|
|
|
7
|
-
The agent's own background turn kept the session busy past the wait limit, so this message was not delivered. Please resend it later.`,this.finishRun("failed");return}const o=Math.min(
|
|
8
|
-
`);return await
|
|
7
|
+
The agent's own background turn kept the session busy past the wait limit, so this message was not delivered. Please resend it later.`,this.finishRun("failed");return}const o=Math.min(Oe*2**e.busyRetryCount,Ne);e.busyRetryCount+=1,a.info("acp-adapter",`agent busy, keeping event queued event=${e.eventId} waited=${Math.round(n/1e3)}s retry_in=${o}ms`),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null),e.lastProgressAt=s,this.refreshGrokLivenessBudget(e,s),e.busyRetryTimer=setTimeout(()=>{if(e.busyRetryTimer=null,this.activeRun===e){if(!this.acpClient?.isAlive){this.finishRun("failed",this.describeUnreachable());return}this.resetIdleTimer(e),this.sendPromptWithRetry(e,t)}},o),e.busyRetryTimer.unref?.()}silentlyDiscardActiveRun(e){this.activeRun===e&&(this.snapshotAuditBoundary(e.eventId),this.activeRun=null,this.acpClient?.clearSettleTimer(),this.clearRunTimers(e),this.emit("eventDone",e.eventId))}async spawnProcess(){const e=[...this.config.args??[]];this.autoInjectArgs?.acp&&e.push("--acp"),this.autoInjectArgs?.model&&e.push("--model",this.autoInjectArgs.model),this.config.command==="gemini"&&!e.includes("--skip-trust")&&e.push("--skip-trust"),A(this.config.command)==="qwenpaw"&&this.config.env?.OPENAI_BASE_URL&&!e.includes("--runtime-provider")&&e.push("--runtime-provider","openai-env"),A(this.config.command)==="qwen"&&!e.includes("--experimental-skills")&&e.push("--experimental-skills"),this.config.command==="kiro-cli"&&!e.includes("--trust-all-tools")&&e.push("--trust-all-tools"),(this.config.command==="copilot"||this.config.command.endsWith("/copilot")||this.config.command==="gh"&&e.includes("copilot"))&&(e.includes("--allow-all-tools")||e.push("--allow-all-tools"),e.includes("--allow-all-paths")||e.push("--allow-all-paths")),this.reasonixAuditTranscriptPath&&!e.includes("--transcript")&&(await y.mkdir(f.dirname(this.reasonixAuditTranscriptPath),{recursive:!0,mode:448}),await(await y.open(this.reasonixAuditTranscriptPath,"a",384)).close(),await y.chmod(this.reasonixAuditTranscriptPath,384),e.push("--transcript",this.reasonixAuditTranscriptPath)),this.agentProcess=new ie(this.bridgeLog),this.baselineGroupPids=[];const i=this.resolveCwd();try{if(!(await y.stat(i)).isDirectory())throw new Error(`Bound path is not a directory: ${i}`)}catch(s){throw String(s?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${i}. Please rebind with /grix open <valid-directory>.`):s}if(A(this.config.command)==="qwenpaw"&&!e.includes("--workspace")&&e.push("--workspace",i),await oe(this.config.command,i,this.config.env,this.nativeProviderScope).catch(s=>{a.warn("acp-adapter",`native provider config skipped: ${s instanceof Error?s.message:String(s)}`)}),A(this.config.command)==="mcode"){const s=this.config.env??{};await re(this.config.command,{baseUrl:s.GRIX_MCODE_BASE_URL,apiKey:s.GRIX_MCODE_API_KEY,model:s.GRIX_MCODE_MODEL}).catch(n=>{a.warn("acp-adapter",`mcode provider config skipped: ${n instanceof Error?n.message:String(n)}`)})}a.info("acp-adapter",`Spawning ACP agent command=${this.config.command} args=${JSON.stringify(e)} cwd=${i} envKeys=${JSON.stringify(Object.keys(this.config.env??{}).sort())}`);try{if(this.isKimi){const s=he({...process.env,...this.config.env});s.registrationChanged&&a.info("acp-adapter",`Removed managed Kimi Layer plugin at ${s.pluginRoot}`)}await this.agentProcess.start({command:this.config.command,args:e.length>0?e:void 0,cwd:i,env:this.config.env})}catch(s){throw a.error("acp-adapter",`Failed to spawn agent process: ${s}`),this.rejectDeferredEvents(`agent spawn failed: ${s instanceof Error?s.message:String(s)}`),this.emit("exit",null),s}a.info("acp-adapter","ACP agent process started"),this.agentProcess.on("error",s=>{this.stopped||(a.error("acp-adapter",`Agent process error: ${s.message}`),this.activeRun&&this.finishRun("failed",`agent process error: ${s.message}`),this.rejectDeferredEvents(`agent process error: ${s.message}`),this.emit("exit",null))}),this.agentProcess.on("exit",s=>{this.lastExitCode=s,!this.stopped&&(a.error("acp-adapter",`Agent process exited unexpectedly (code=${s})`),this.activeRun&&this.finishRun("failed",`agent process exited (code=${s})`),this.rejectDeferredEvents(`agent process exited (code=${s})`),this.emit("exit",s))}),this.agentProcess.on("stderr",()=>{this.activeRun&&this.resetIdleTimer(this.activeRun)})}async connectSession(e){if(this.sessionConnected||!this.agentProcess?.transport)return;let t;this.acpMcpTools&&(t=await this.startInternalApiAndMcp(e||this.resolveCwd())),this.acpClient=new pe,this.acpClient.on("event",l=>this.handleAcpEvent(l)),this.acpClient.on("activity",()=>{this.activeRun&&this.resetIdleTimer(this.activeRun)}),this.acpClient.on("configOptionsUpdated",()=>{const l=this.currentAibotSessionId;if(!l||this.stopped)return;const d=this.bindingStore?.get(l)?.cwd||this.resolveCwd();d&&this.callbacks.sendUpdateBindingCard(l,"ready",d,this.buildToolbarContext("config_options_updated",d))}),this.acpClient.on("session-lost",()=>{this.stopped||this.agentProcess?.alive&&(a.error("acp-adapter","ACP transport closed while agent process still alive, triggering respawn"),this.activeRun&&(this.callbacks.sendRunError(this.activeRun.eventId,this.activeRun.sessionId,"ACP transport closed"),this.finishRun("failed","ACP transport closed")),this.emit("exit",null))});const i=this.currentAibotSessionId&&this.bindingStore?this.bindingStore.getAcpSessionId(this.currentAibotSessionId):void 0,s=!!i&&i!=="__continue__",n=async l=>{const d=this.agentProcess?.transport;if(!d)throw new Error("agent process exited before the ACP session could connect");await this.acpClient.connect({transport:d,authMethod:this.acpAuthMethod,initialMode:this.acpInitialMode,initialModel:this.acpInitialModel,terminal:!0,cwd:e||this.resolveCwd(),mcpServers:t,sessionId:l,newSessionParams:this.newSessionParams})};let o=!1,r;try{await n(i)}catch(l){if(l instanceof fe){await this.handleAuthRequired(l);return}if(!i)throw this.handleConnectFailure(l),l;if(a.warn("acp-adapter",`Failed to load persisted session ${i}, fallback to session/new: ${C(l)}`),o=!0,r=i,this.config.command==="kiro-cli"&&this.currentAibotSessionId){a.info("acp-adapter",`Building kiro recovery summary: aibotSession=${this.currentAibotSessionId} acpSession=${i}`);const d=await this.buildKiroRecoveryContext(this.currentAibotSessionId,i,e||this.resolveCwd());d?(this.recoveryContextBySessionId.set(this.currentAibotSessionId,d),a.info("acp-adapter",`Recovery context prepared for session ${this.currentAibotSessionId} (chars=${d.length})`)):a.warn("acp-adapter",`Recovery context skipped: no summary generated for acpSession=${i}`)}await n(void 0)}if(this.sessionConnected=!0,this.sessionContextPending=!s||o,!this.sessionContextPending){const l=this.callbacks.getAgentProfile?.(),d=l?.agentName?.trim()??"",h=l?.introduction?.trim()??"",u=v=>{const g=this.bindingStore?.getIdentitySnapshot(v);g&&g.name===d&&g.intro===h&&this.identity.markInjected(v)};this.currentAibotSessionId&&u(this.currentAibotSessionId);for(const v of this.sessionBindings.keys())u(v)}this.captureBaselineGroupPids(),a.info("acp-adapter",`ACP session ready: ${this.acpClient.sessionId}`),this.emit("acpSessionReady",this.acpClient.sessionId),this.currentAibotSessionId&&this.bindingStore&&this.bindingStore.setAcpSessionId(this.currentAibotSessionId,this.acpClient.sessionId);for(const[l,d]of this.sessionBindings){this.bindingStore&&this.acpClient.sessionId&&this.bindingStore.setAcpSessionId(l,this.acpClient.sessionId);const h=o?"binding_recreated":"binding_ready",u=this.buildToolbarContext(h,d);o&&r&&(u.previous_session_id=r,u.recreated_session_id=this.acpClient.sessionId),this.callbacks.sendUpdateBindingCard(l,"ready",d,u)}}async buildKiroRecoveryContext(e,t,i){try{const s=f.join(I(),".kiro","sessions","cli",`${t}.json`);await y.access(s),a.info("acp-adapter",`Reading kiro source session file: ${s}`);const n=await this.generateSummaryByKiroCli(s,i);if(!n)return;const o=f.join(I(),".grix","data","session-summaries");await y.mkdir(o,{recursive:!0});const r=f.join(o,`${e}.md`),l=[`SOURCE_KIRO_SESSION_FILE: ${s}`,"",n.trim(),""].join(`
|
|
8
|
+
`);return await y.writeFile(r,l,"utf8"),a.info("acp-adapter",`Recovery summary saved: ${r} (chars=${n.length})`),["[\u5386\u53F2\u4E0A\u4E0B\u6587\u56DE\u704C\u8BF4\u660E]","\u4EE5\u4E0B\u5185\u5BB9\u6765\u81EA\u65E7\u4F1A\u8BDD\u81EA\u52A8\u6458\u8981\uFF0C\u8BF7\u5728\u540E\u7EED\u56DE\u7B54\u4E2D\u5EF6\u7EED\u5176\u4E2D\u7684\u76EE\u6807\u3001\u7EA6\u675F\u548C\u7ED3\u8BBA\u3002",`SOURCE_KIRO_SESSION_FILE: ${s}`,`SUMMARY_FILE: ${r}`,"",n.trim()].join(`
|
|
9
9
|
`)}catch(s){a.warn("acp-adapter",`Failed to build kiro recovery context: ${C(s)}`);return}}async generateSummaryByKiroCli(e,t){const s=["chat","--no-interactive","--trust-tools=read,grep",["\u8BF7\u57FA\u4E8E\u4E0B\u9762\u5F15\u7528\u7684 Kiro \u539F\u59CB\u4F1A\u8BDD\u6587\u4EF6\u751F\u6210\u6458\u8981\uFF0C\u8F93\u51FA\u5FC5\u987B\u4E3A Markdown\u3002","\u8981\u6C42\uFF1A1) \u7B80\u660E\u51C6\u786E\uFF1B2) \u5305\u542B goals/constraints/decisions/open_items \u56DB\u90E8\u5206\uFF1B3) \u4E0D\u8981\u8F93\u51FA\u4EE3\u7801\u5757\u56F4\u680F\u3002",`\u4F1A\u8BDD\u6587\u4EF6\uFF1A@"${e}"`].join(`
|
|
10
|
-
`)],n=await this.runCommandCapture("kiro-cli",s,t,45e3);if(!n)return;const o=
|
|
10
|
+
`)],n=await this.runCommandCapture("kiro-cli",s,t,45e3);if(!n)return;const o=He(n).trim(),r=o.indexOf("> "),l=r>=0?o.slice(r+2).trim():o;if(l)return a.info("acp-adapter",`Kiro summary generated from ${e} (raw_chars=${o.length}, body_chars=${l.length})`),l.split(`
|
|
11
11
|
`).filter(d=>!d.includes("Credits:")&&!d.includes("Time:")).join(`
|
|
12
|
-
`).trim()}runCommandCapture(e,t,i,s){return new Promise((n,o)=>{const r
|
|
12
|
+
`).trim()}runCommandCapture(e,t,i,s){return new Promise((n,o)=>{const r=O(e,t,{cwd:i,stdio:["ignore","pipe","pipe"],windowsHide:!0});let l="",d="";const h=setTimeout(()=>{r.kill("SIGTERM"),o(new Error(`${e} timed out after ${s}ms`))},s);r.stdout.on("data",u=>{l+=String(u)}),r.stderr.on("data",u=>{d+=String(u)}),r.on("error",u=>{clearTimeout(h),o(u)}),r.on("close",u=>{if(clearTimeout(h),u===0){n(l||d);return}o(new Error(`${e} exited with code ${u}: ${d||l}`))})})}handleConnectFailure(e){a.error("acp-adapter",`ACP session creation failed: ${C(e)}`),this.acpClient?.dispose(),this.acpClient?.removeAllListeners(),this.acpClient=null,this.emit("exit",null)}async startInternalApiAndMcp(e=this.resolveCwd()){try{this.internalApi||(this.internalApi=new ge,this.internalApi.setInvokeHandler(async(r,l,d,h)=>{if(r==="toolbar_set"&&!String(l?.session_id??"").trim()){const u=String(this.currentAibotSessionId??"").trim();u&&(l={...l,session_id:u})}return this.callbacks.agentInvoke(r,l,h)}),await this.internalApi.start(0),a.info("acp-adapter",`Internal API started at ${this.internalApi.url}`)),this.internalApi.setMcpBridgeUpHandler(r=>this.onMcpBridgeUp(r));const t=this.config.command??"",i=A(t)==="qwen"?f.join(I(),".qwen","skills"):t.includes("gemini")?f.join(I(),".gemini","skills"):t.includes("kiro")?f.join(I(),".kiro","skills"):this.isReasonix?f.join(I(),".reasonix","skills"):this.isKimi?f.join(ce({...process.env,...this.config.env}),"skills"):this.auditAgentType==="copilot"||/^copilot(?:\.cmd)?$/i.test(f.basename(t).toLowerCase())||/^gh(?:\.exe)?$/i.test(f.basename(t).toLowerCase())&&(this.config.args??[]).includes("copilot")?f.join(I(),".copilot","skills"):this.auditAgentType==="hermes"?f.join(this.config.env?.HERMES_HOME?.trim()||ue({...process.env,...this.config.env},this.nativeProviderScope),"skills"):this.auditAgentType==="qodercli"?f.join(I(),".qoder","skills"):this.auditAgentType==="qoderclicn"?f.join(I(),".qoder-cn","skills"):this.auditAgentType==="traecli"?f.join(I(),".trae","skills"):this.auditAgentType==="codebuddy"?f.join(I(),".codebuddy","skills"):void 0;if(i){const r=de(i);r.length>0&&a.info("acp-adapter",`Synced connector skills to ${i}: [${r.join(", ")}]`)}const s=f.resolve(E,"../../mcp/mcp-bridge-server.js"),n=this.internalApi.mcpBridgeWsUrl,o=f.resolve(E,"../../mcp/acp-mcp-server.js");if(this.isKimi){await this.internalApi.setCodebaseNavigatorCwd(e);const r={Authorization:`Bearer ${this.internalApi.token}`};return[{type:"http",name:"grix-app-bridge",url:this.internalApi.mcpBridgeHttpUrl,headers:r},{type:"http",name:"grix-connector-tools",url:this.internalApi.mcpToolsHttpUrl,headers:r},{type:"http",name:"codebase-navigator",url:this.internalApi.codebaseNavigatorHttpUrl,headers:r}]}return[{name:"grix-app-bridge",command:process.execPath,args:[s,"--ws-url",n],...!this.isReasonix&&{env:{GRIX_CONNECTOR_MCP_BRIDGE_WS:n}}},{name:"grix-connector-tools",command:process.execPath,args:[o,"--api-url",this.internalApi.url],...!this.isReasonix&&{env:{}}}]}catch(t){a.error("acp-adapter",`Failed to start MCP tools: ${t}`);return}}onMcpBridgeUp(e){this.callbacks.sendMcpFrame?.(e)}deliverMcpFrameToAgent(e){this.internalApi?.sendMcpFrameToBridge(e)}cleanup(){this.flushOrphanBuffer(),this.activeRun,this.pendingApprovals.clear(),this.pendingQuestions.clear(),this.pendingAutoCompact=!1,this.rejectDeferredEvents("adapter cleaned up"),this.cancelAllDeferredTimers(),this.sessionConnected=!1,this.acpClient&&(this.acpClient.dispose(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(this.agentProcess.removeAllListeners(),this.agentProcess=null),this.baselineGroupPids=[],this.terminalAuthChild&&(this.terminalAuthChild.kill("SIGKILL"),this.terminalAuthChild=null)}async handleAuthRequired(e){a.info("acp-adapter",`Auth required, methods: ${e.authMethods.map(s=>s.id).join(", ")}`);const t=e.authMethods.find(s=>/oauth|browser/i.test(s.id))??e.authMethods[0];if(!t)throw e;const i=this.currentAibotSessionId??"";this.callbacks.sendAuthNotification(i,`Authentication required (${t.id}). Initiating auth flow...`);for(const[s,n]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(s,"failed",n);if(t.type==="terminal")await this.runTerminalAuth(t,i);else{const s=await this.captureAuthUrl();s&&this.callbacks.sendAuthNotification(i,`Please open this URL to authenticate:
|
|
13
13
|
${s}
|
|
14
14
|
|
|
15
|
-
Waiting for authentication to complete...`)}try{await this.acpClient.authenticate(t.id),a.info("acp-adapter","Authentication successful"),this.callbacks.sendAuthNotification(i,"Authentication successful. Resuming...");const s=this.acpMcpTools?await this.startInternalApiAndMcp():void 0,n=this.agentProcess?.transport;if(!n||!this.acpClient)throw new Error("agent process exited during authentication");await this.acpClient.connect({transport:n,initialMode:this.acpInitialMode,initialModel:this.acpInitialModel,terminal:!0,cwd:this.resolveCwd(),mcpServers:s,newSessionParams:this.newSessionParams}),a.info("acp-adapter",`ACP session ready after auth: ${this.acpClient.sessionId}`),this.captureBaselineGroupPids(),this.emit("acpSessionReady",this.acpClient.sessionId);for(const[o,r]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(o,"ready",r,this.buildToolbarContext("binding_ready",r))}catch(s){throw a.error("acp-adapter",`Auth retry failed: ${s}`),s}}runTerminalAuth(e,t){return new Promise((i,s)=>{const n
|
|
16
|
-
${
|
|
15
|
+
Waiting for authentication to complete...`)}try{await this.acpClient.authenticate(t.id),a.info("acp-adapter","Authentication successful"),this.callbacks.sendAuthNotification(i,"Authentication successful. Resuming...");const s=this.acpMcpTools?await this.startInternalApiAndMcp():void 0,n=this.agentProcess?.transport;if(!n||!this.acpClient)throw new Error("agent process exited during authentication");await this.acpClient.connect({transport:n,initialMode:this.acpInitialMode,initialModel:this.acpInitialModel,terminal:!0,cwd:this.resolveCwd(),mcpServers:s,newSessionParams:this.newSessionParams}),a.info("acp-adapter",`ACP session ready after auth: ${this.acpClient.sessionId}`),this.captureBaselineGroupPids(),this.emit("acpSessionReady",this.acpClient.sessionId);for(const[o,r]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(o,"ready",r,this.buildToolbarContext("binding_ready",r))}catch(s){throw a.error("acp-adapter",`Auth retry failed: ${s}`),s}}runTerminalAuth(e,t){return new Promise((i,s)=>{const n=O(this.config.command,e.args??[],{env:{...process.env,...this.config.env??{}},stdio:["ignore","pipe","pipe"],windowsHide:!0});this.terminalAuthChild=n;const o=/https?:\/\/[^\s"')\]]+/;let r=!1,l=!1;const d=u=>{if(r)return;const g=u.toString().replace(/\x1b\[[0-9;]*m/g,"").match(o);g&&(r=!0,a.info("acp-adapter",`Terminal auth URL captured: ${g[0]}`),this.callbacks.sendAuthNotification(t,`Please open this URL on any device to authenticate:
|
|
16
|
+
${g[0]}
|
|
17
17
|
|
|
18
|
-
Waiting for authentication to complete...`))};n.stdout?.on("data",d),n.stderr?.on("data",d);const p=setTimeout(()=>{l||(l=!0,n.kill("SIGKILL"),this.terminalAuthChild=null,s(new Error(`terminal auth timed out after ${Q}ms`)))},Q);n.on("error",u=>{l||(l=!0,clearTimeout(p),this.terminalAuthChild=null,s(u))}),n.on("exit",u=>{l||(l=!0,clearTimeout(p),this.terminalAuthChild=null,u===0?i():s(new Error(`terminal auth process exited with code ${u}`)))})})}captureAuthUrl(){return new Promise(e=>{if(!this.agentProcess){e(null);return}const t=/https?:\/\/[^\s"')\]]+/;let i=!1;const s=n=>{if(i)return;const r=n.toString().replace(/\x1b\[[0-9;]*m/g,"").match(t);r&&(i=!0,this.agentProcess.removeListener("stderr",s),e(r[0]))};this.agentProcess.on("stderr",s),setTimeout(()=>{i||(i=!0,this.agentProcess.removeListener("stderr",s),e(null))},3e4)})}handleAcpEvent(e){try{a.info("acp-adapter","incoming acp event",{eventType:e.type,sessionId:this.activeRun?.sessionId??null,eventKeys:Object.keys(e),rawEvent:N(e,2e3)})}catch{}if(e.type===m.PermissionRequest){this.activeRun&&this.resetIdleTimer(this.activeRun),this.captureAuditEvent(e),this.handlePermissionRequest(e);return}if(e.type===m.ContextWindowUpdate){e.contextWindow&&this.callbacks.onContextWindowUpdated?.(e.contextWindow),this.compacting?this.finishCompaction("context-window-update"):e.contextWindow&&this.maybeScheduleAutoCompact(e.contextWindow);return}const t=this.activeRun;if(!t){this.handleOrphanAcpEvent(e);return}if(t.busyWaiting){this.handleOrphanAcpEvent(e);return}this.captureAuditEvent(e),t.responded||(t.responded=!0);let i=!1;switch(e.type){case m.Text:{if(t.lastToolUse=null,t.lastToolResult=null,e.content){i=!0;const s=t.quotedStream.consume(e.content);s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),s.deltaContent&&(this.rolloverInterruptedTextSegment(t),this.appendToStream(t,s.deltaContent))}break}case m.ToolUse:{if(i=!0,t.awaitingToolResult=!0,t.lastToolResult=null,e.toolName){if(e.toolCallId&&(t.toolNamesById.set(e.toolCallId,e.toolName),t.sentToolUseIds.has(e.toolCallId)))break;const s=e.toolInput??"",n=_(s);if(t.lastToolUse?.toolName===e.toolName&&_(t.lastToolUse.toolInput)===n)break;t.lastToolUse={toolName:e.toolName,toolInput:s},e.toolCallId&&t.sentToolUseIds.add(e.toolCallId);const o=this.trimToolWirePayload?q(s):s;t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_use",payload:{tool_name:e.toolName,tool_input:o}})||this.callbacks.sendToolUse(t.eventId,t.sessionId,e.toolName,o)}break}case m.ToolResult:{t.awaitingToolResult=!1;{const s=e.toolCallId||e.toolName||"";t.lastToolProgress.delete(s),t.lastToolProgressSentAt.delete(s)}if(t.lastToolUse=null,e.content){i=!0;const s=O(t,e),n=e.content,o=_(n);if(t.lastToolResult?.toolName===s&&_(t.lastToolResult.content)===o)break;if(t.lastToolResult={toolName:s,content:n},!this.trimToolWirePayload||e.toolStatus==="failed"){const r=this.trimToolWirePayload?"(failed)":n;t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_result",payload:{tool_name:s,content:r}})||this.callbacks.sendToolResult(t.eventId,t.sessionId,s,r)}}break}case m.ToolProgress:{if(i=!0,e.content){const s=e.toolCallId||e.toolName||"";if(t.lastToolProgress.get(s)===e.content||(t.lastToolProgress.set(s,e.content),this.trimToolWirePayload))break;const n=Date.now(),o=t.lastToolProgressSentAt.get(s);if(o!==void 0&&n-o<ye)break;t.lastToolProgressSentAt.set(s,n);const r=O(t,e);t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_progress",payload:{tool_name:r,content:e.content}})||this.callbacks.sendToolResult(t.eventId,t.sessionId,r,e.content)}break}case m.Thinking:{t.lastToolUse=null,t.lastToolResult=null,e.content&&(i=!0,t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"thinking",payload:{content:e.content}})||this.callbacks.sendThinking(t.eventId,t.sessionId,e.content));break}case m.Error:{t.lastToolUse=null,t.lastToolResult=null;const s=String(e.error??"unknown error");this.emitRawEventEnvelope(t,{type:"error",payload:{message:s}}),a.error("acp-adapter",`ACP error: ${s}`),this.callbacks.sendRunError(t.eventId,t.sessionId,s);break}case m.Result:{if(e.synthetic&&this.shouldDeferSyntheticResultForDetachedKimiTask(t,e)){a.info("acp-adapter",`Synthetic ACP Result deferred: kimi detached task still running event=${t.eventId} session=${t.sessionId}`),this.acpClient?.deferSettledResult();return}this.emitRawEventEnvelope(t,{type:"result",payload:{done:e.done??!0}});const s=t.quotedStream.flush();s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),s.deltaContent&&this.appendToStream(t,s.deltaContent),this.flushStream(),this.finishRun("responded");break}}i&&(t.lastProgressAt=Date.now(),t.idleNoProgressCount=0),this.resetIdleTimer(t)}handlePermissionRequest(e){const t=e.permissionRequest;if(a.info("acp-adapter","permission_request received",{sessionId:this.activeRun?.sessionId,eventId:this.activeRun?.eventId,requestId:e.requestId??null,toolCallId:t?.toolCallId??null,toolName:t?.toolName??null,toolTitle:t?.toolTitle??null,optionsCount:Array.isArray(t?.options)?t.options.length:0,hasActiveRun:this.activeRun!==null,approvalMode:this.approvalMode,rawTransport:this.rawTransport,hasRawEventEnvelopeCb:typeof this.callbacks.sendRawEventEnvelope=="function",hasSendPermissionCardCb:typeof this.callbacks.sendPermissionCard=="function",rawPr:N(t,3e3)}),!t||!e.requestId||!this.acpClient){a.warn("acp-adapter","permission_request dropped: missing prerequisite",{hasPr:t!=null,hasRequestId:!!e.requestId,hasAcpClient:!!this.acpClient}),e.requestId&&this.captureAuditEvent({type:m.PermissionResponse,requestId:e.requestId,permissionDecision:"dropped"});return}if(this.approvalMode==="yolo"||this.approvalMode==="autoEdit"){a.info("acp-adapter",`Auto-approving (${this.approvalMode}): ${t.toolName}`),this.acpClient.respondPermission(t.requestId,{behavior:"allow"}).catch(()=>{}),this.captureAuditEvent({type:m.PermissionResponse,requestId:t.requestId,toolCallId:t.toolCallId,permissionDecision:"allow"});return}const i=this.activeRun,s=Se(t);if(s&&i&&this.callbacks.sendAgentQuestionCard){this.resetIdleTimer(i),this.pendingQuestions.set(e.requestId,{options:[...t.options]});const r=t.options.some(l=>k.test(l.optionId));i.textSegmentInterrupted=!0,this.callbacks.sendAgentQuestionCard(i.eventId,i.sessionId,{request_id:e.requestId,mode:"form",questions:[{header:s.prompt,prompt:s.prompt,options:s.answerOptions.map(l=>l.name),allow_free_text:r}]}),a.info("acp-adapter","AskUserQuestion forwarded via agent_question card",{sessionId:i.sessionId,eventId:i.eventId,requestId:e.requestId,optionsCount:s.answerOptions.length});return}const n=t.toolCallId,o=Ae(t.rawParams,e.toolInput,t.toolTitle);this.pendingApprovals.set(n,e.requestId),i?(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=null),i.textSegmentInterrupted=!0,this.emitRawEventEnvelope(i,{type:"permission_request",payload:{request_id:t.requestId,tool_call_id:n,tool_name:t.toolName,tool_title:t.toolTitle,...o?{tool_input:o}:{},options:t.options}})?a.info("acp-adapter","permission_request forwarded via rawEventEnvelope",{sessionId:i.sessionId,eventId:i.eventId,toolCallId:n,toolName:t.toolName}):(a.info("acp-adapter","permission_request falling back to sendPermissionCard",{sessionId:i.sessionId,eventId:i.eventId,toolCallId:n,toolName:t.toolName}),this.callbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,toolCallId:n,toolName:t.toolName,toolTitle:t.toolTitle,toolInput:o,options:t.options}))):(a.info("acp-adapter",`Permission request without active run, auto-approving: ${t.toolName}`),this.acpClient.respondPermission(e.requestId,{behavior:"allow"}),this.pendingApprovals.delete(n),this.captureAuditEvent({type:m.PermissionResponse,requestId:e.requestId,toolCallId:n,permissionDecision:"allow"}))}emitRawEventEnvelope(e,t){return!e||!this.rawTransport||!this.callbacks.sendRawEventEnvelope?!1:(this.callbacks.sendRawEventEnvelope(e.eventId,e.sessionId,{type:t.type,payload:t.payload,seq:++this.rawEventSeq,at:new Date().toISOString()}),!0)}resetIdleTimer(e,t){e.idleTimer&&clearTimeout(e.idleTimer),Date.now()-e.lastProgressAt<2e3&&this.refreshGrokLivenessBudget(e,e.lastProgressAt);const i=t??(e.awaitingToolResult?Me:xe),s=Date.now(),n=e.lastProgressAt+w-s,o=e.grokLivenessHoldUntil?e.grokLivenessHoldUntil-s:0,r=Math.max(0,Math.min(i,Math.max(n,o)));e.idleTimer=setTimeout(()=>{this.onIdleTimeout(e)},r)}async readIdleEvidence(e,t,i){if(y(this.config.command)==="grok"){const n=await L({sessionId:t,fromOffset:e.grokEventsOffset,extendStartAt:e.grokLivenessExtendStartAt});return n.kind==="progress"?(e.grokLivenessHoldUntil=void 0,e.grokLivenessExtendStartAt=n.extendStartAt,{fileActivity:!0,grokExtend:!1}):n.kind==="extend"?(e.grokLivenessExtendStartAt=n.extendStartAt,e.grokLivenessHoldUntil=n.extendUntil,a.info("acp-adapter",`Grok liveness: turn open for ${e.eventId} (freshMs=${n.freshMs??"none"}), holding until budget`),{fileActivity:!1,grokExtend:!0}):(e.grokLivenessHoldUntil=void 0,n.turn==="open"&&a.warn("acp-adapter",`Grok liveness budget exhausted for ${e.eventId} (turn still open, session files stale), allowing close`),{fileActivity:!1,grokExtend:!1})}return{fileActivity:await this.checkSessionFileActivity(t,i),grokExtend:!1}}refreshGrokLivenessBudget(e,t){y(this.config.command)==="grok"&&(e.grokLivenessExtendStartAt=t,e.grokLivenessHoldUntil=void 0)}async onIdleTimeout(e){if(this.activeRun?.eventId!==e.eventId)return;const t=this.acpClient,i=Date.now()-e.lastProgressAt;if(i>=w){if(t?.isAlive){const s=e.lastProgressAt,n=await this.readIdleEvidence(e,t.sessionId,e.lastIdleCheckAt);if(this.activeRun?.eventId!==e.eventId)return;const o=e.lastProgressAt>s;if(e.lastIdleCheckAt=Date.now(),o||n.fileActivity){n.fileActivity&&(e.lastProgressAt=Date.now()),e.idleNoProgressCount=0,a.info("acp-adapter",`Hard cap recheck found ${o?"stream progress":"session file activity"}, refreshing watchdog: ${e.eventId}`),this.resetIdleTimer(e);return}if(n.grokExtend){this.resetIdleTimer(e);return}}a.error("acp-adapter",`Turn inactive ${Math.round(i/1e3)}s \u2265 cap ${Math.round(w/1e3)}s, forcing timeout: ${e.eventId}`),this.finishRun("failed",`turn inactivity timeout after ${Math.round(i/1e3)}s with no ACP activity`),this.declareStuck();return}t?.isAlive?t.ping(5e3).then(async s=>{if(this.activeRun?.eventId!==e.eventId)return;if(!s){await this.handlePingFailure(e,t);return}if(e.consecutivePingFailures=0,e.awaitingToolResult){const d=e.lastIdleCheckAt,p=await this.readIdleEvidence(e,t.sessionId,d);if(this.activeRun?.eventId!==e.eventId)return;e.lastIdleCheckAt=Date.now(),p.fileActivity?(e.lastProgressAt=Date.now(),a.info("acp-adapter",`Idle timer: tool running, ping ok, session file active, refreshing watchdog: ${e.eventId}`)):p.grokExtend||a.info("acp-adapter",`Idle timer: tool running, ping ok, continuing until inactivity cap: ${e.eventId}`),e.idleNoProgressCount=0,this.resetIdleTimer(e);return}const n=e.lastIdleCheckAt,o=e.lastProgressAt>n,r=o?{fileActivity:!1,grokExtend:!1}:await this.readIdleEvidence(e,t.sessionId,n);if(this.activeRun?.eventId!==e.eventId)return;const l=o||r.fileActivity;e.lastIdleCheckAt=Date.now(),l?(r.fileActivity&&(a.info("acp-adapter",`Idle timer: no stream progress but session file active, continuing: ${e.eventId}`),e.lastProgressAt=Date.now()),e.idleNoProgressCount=0,this.resetIdleTimer(e)):r.grokExtend?(e.idleNoProgressCount=0,this.resetIdleTimer(e)):(e.idleNoProgressCount++,a.info("acp-adapter",`Idle timer: ping ok, no stream progress (cycle=${e.idleNoProgressCount}), extending until inactivity cap (${Math.round(w/6e4)}min): ${e.eventId}`),this.resetIdleTimer(e))}).catch(()=>{this.activeRun?.eventId===e.eventId&&this.handlePingFailure(e,t)}):(a.error("acp-adapter",`Agent idle (no client), declaring stuck: ${e.eventId}`),this.finishRun("failed",this.describeUnreachable()),this.declareStuck())}async handlePingFailure(e,t){const i=e.lastIdleCheckAt,s=e.lastProgressAt>i,n=s?{fileActivity:!1,grokExtend:!1}:await this.readIdleEvidence(e,t.sessionId,i);if(this.activeRun?.eventId===e.eventId){if(s||n.fileActivity||n.grokExtend||e.awaitingToolResult||this.pendingQuestions.size>0){const o=s?"stream progress":n.fileActivity?"session file activity":n.grokExtend?"grok turn still open":e.awaitingToolResult?"tool in flight":"question pending user answer";a.info("acp-adapter",`Idle timer: ping failed but ${o}, continuing: ${e.eventId}`),e.consecutivePingFailures=0,e.lastIdleCheckAt=Date.now(),n.fileActivity&&(e.lastProgressAt=Date.now()),this.resetIdleTimer(e);return}if(e.consecutivePingFailures++,e.lastIdleCheckAt=Date.now(),e.consecutivePingFailures<K){a.warn("acp-adapter",`Idle timer: ping failed (${e.consecutivePingFailures}/${K}), rechecking in ${H/1e3}s: ${e.eventId}`),this.resetIdleTimer(e,H);return}a.error("acp-adapter",`Ping failed ${e.consecutivePingFailures}x with no activity evidence, declaring stuck: ${e.eventId}`),this.finishRun("failed",this.describeUnreachable()),this.declareStuck()}}async checkSessionFileActivity(e,t){if(!e)return!1;try{if(this.isKimi)return await we(e,t);const i=y(this.config.command);return i==="kiro-cli"?await _e(e,t):i==="qodercli"?await F(".qoder",e,t):i==="qoderclicn"?await F(".qoder-cn",e,t):i==="dim"?await Te(e,t):i==="grok"?(await L({sessionId:e})).kind==="progress":!1}catch{return!1}}shouldDeferSyntheticResultForDetachedKimiTask(e,t){if(!this.isKimi)return!1;try{return be(t.sessionId||this.acpClient?.sessionId||e.sessionId)}catch{return!1}}declareStuck(){this.pendingQuestions.clear(),this.acpClient&&(this.acpClient.dispose(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(this.agentProcess.close().catch(()=>{}),this.agentProcess=null),this.emit("stuck")}rolloverInterruptedTextSegment(e){e.textSegmentInterrupted&&(e.textSegmentInterrupted=!1,this.flushStream(),e.chunkSeq!==0&&(this.callbacks.sendStreamChunk(e.eventId,e.sessionId,"",++e.chunkSeq,!0,e.currentClientMsgId,e.quotedMessageId),e.currentSegmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.currentSegmentIndex}`,e.chunkSeq=0,e.markdownSegmenter.reset(),a.info("acp-adapter",`stream segment rollover event=${e.eventId} segment=${e.currentSegmentIndex} reason=process_boundary`)))}appendToStream(e,t){e.buffer+=t,e.flushTimer||(e.flushTimer=setTimeout(()=>this.flushStream(),Ee))}emitSegmentedStream(e,t){if(!t)return;const i=e.markdownSegmenter.push(t);for(const s of i)s.text&&(this.callbacks.sendStreamChunk(e.eventId,e.sessionId,s.text,++e.chunkSeq,s.closeAfter===!0,e.currentClientMsgId,e.quotedMessageId),s.closeAfter&&(e.currentSegmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.currentSegmentIndex}`,e.chunkSeq=0,a.info("acp-adapter",`stream segment rollover event=${e.eventId} segment=${e.currentSegmentIndex} reason=${s.reason??"threshold"}`)))}handleOrphanAcpEvent(e){if(!(!this.sessionConnected||this.compacting||Date.now()<this.orphanSuppressedUntil)){if(e.type===m.Text&&e.content){this.orphanSessionId===null&&(this.orphanSessionId=this.currentAibotSessionId??"");const t=this.orphanQuotedStream.consume(e.content);t.deltaContent&&(this.orphanBuffer+=t.deltaContent),this.orphanBuffer.length>=Oe?this.flushOrphanBuffer():this.scheduleOrphanFlush();return}e.type===m.Result&&this.flushOrphanBuffer()}}scheduleOrphanFlush(){this.orphanFlushTimer&&clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=setTimeout(()=>{this.orphanFlushTimer=null,this.flushOrphanBuffer()},Ne),this.orphanFlushTimer.unref?.()}flushOrphanBuffer(){if(this.orphanFlushTimer&&(clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=null),this.orphanSessionId===null&&!this.orphanBuffer)return;const e=this.orphanQuotedStream.flush();e.deltaContent&&(this.orphanBuffer+=e.deltaContent),this.orphanQuotedStream=new S;const t=this.orphanSessionId||this.currentAibotSessionId;this.orphanSessionId=null;const i=this.orphanBuffer.trim();if(this.orphanBuffer="",!!i){if(!t||!this.callbacks.sendAgentMessage){a.warn("acp-adapter",`orphan agent output dropped (${t?"no sendAgentMessage callback":"no session id"}) chars=${i.length}`);return}a.info("acp-adapter",`delivering orphan agent output session=${t} chars=${i.length}`);for(let s=0;s<i.length;s+=X)this.callbacks.sendAgentMessage(t,i.slice(s,s+X))}}suppressOrphanOutput(e){this.orphanSuppressedUntil=Date.now()+e,this.orphanFlushTimer&&(clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=null),this.orphanBuffer="",this.orphanQuotedStream=new S,this.orphanSessionId=null}flushStream(){const e=this.activeRun;if(!e||!e.buffer)return;e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null);const t=e.buffer;e.buffer="",this.emitSegmentedStream(e,t)}lastExitCode=null;describeUnreachable(){return this.agentProcess?.alive?"agent unreachable: no response while its process is still running":this.lastExitCode===null?"agent unreachable: its process is no longer running":`agent unreachable: its process exited (code=${this.lastExitCode})`}static sanitizeFailureReasonForUser(e){return e.replace(/\bunreachable\b/gi,"unresponsive").replace(/\bidle cycles?\b/gi,"consecutive checks")}finishRun(e,t){const i=this.activeRun;if(!i)return;this.snapshotAuditBoundary(i.eventId),this.activeRun=null,this.acpClient?.clearSettleTimer(),this.emit("eventDone",i.eventId),this.clearRunTimers(i);const s=i.quotedStream.flush();s.quotedMessageId&&(i.quotedMessageId=s.quotedMessageId),s.deltaContent&&(i.buffer+=s.deltaContent);let n=!1;if(t)if(e==="failed"){a.error("acp-adapter",`finishRun failed: ${t} event=${i.eventId}`);const r=J.sanitizeFailureReasonForUser(t);i.buffer+=`
|
|
18
|
+
Waiting for authentication to complete...`))};n.stdout?.on("data",d),n.stderr?.on("data",d);const h=setTimeout(()=>{l||(l=!0,n.kill("SIGKILL"),this.terminalAuthChild=null,s(new Error(`terminal auth timed out after ${X}ms`)))},X);n.on("error",u=>{l||(l=!0,clearTimeout(h),this.terminalAuthChild=null,s(u))}),n.on("exit",u=>{l||(l=!0,clearTimeout(h),this.terminalAuthChild=null,u===0?i():s(new Error(`terminal auth process exited with code ${u}`)))})})}captureAuthUrl(){return new Promise(e=>{if(!this.agentProcess){e(null);return}const t=/https?:\/\/[^\s"')\]]+/;let i=!1;const s=n=>{if(i)return;const r=n.toString().replace(/\x1b\[[0-9;]*m/g,"").match(t);r&&(i=!0,this.agentProcess.removeListener("stderr",s),e(r[0]))};this.agentProcess.on("stderr",s),setTimeout(()=>{i||(i=!0,this.agentProcess.removeListener("stderr",s),e(null))},3e4)})}handleAcpEvent(e){try{a.info("acp-adapter","incoming acp event",{eventType:e.type,sessionId:this.activeRun?.sessionId??null,eventKeys:Object.keys(e),rawEvent:D(e,2e3)})}catch{}if(e.type===m.PermissionRequest){this.activeRun&&this.resetIdleTimer(this.activeRun),this.captureAuditEvent(e),this.handlePermissionRequest(e);return}if(e.type===m.ContextWindowUpdate){e.contextWindow&&this.callbacks.onContextWindowUpdated?.(e.contextWindow),this.compacting?this.finishCompaction("context-window-update"):e.contextWindow&&this.maybeScheduleAutoCompact(e.contextWindow);return}const t=this.activeRun;if(!t){this.handleOrphanAcpEvent(e);return}if(t.busyWaiting){this.handleOrphanAcpEvent(e);return}this.captureAuditEvent(e),t.responded||(t.responded=!0);let i=!1;switch(e.type){case m.Text:{if(t.lastToolUse=null,t.lastToolResult=null,e.content){i=!0;const s=t.quotedStream.consume(e.content);s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),s.deltaContent&&(this.rolloverInterruptedTextSegment(t),this.appendToStream(t,s.deltaContent))}break}case m.ToolUse:{if(i=!0,t.awaitingToolResult=!0,t.lastToolResult=null,e.toolName){if(e.toolCallId&&(t.toolNamesById.set(e.toolCallId,e.toolName),t.sentToolUseIds.has(e.toolCallId)))break;const s=e.toolInput??"",n=b(s);if(t.lastToolUse?.toolName===e.toolName&&b(t.lastToolUse.toolInput)===n)break;t.lastToolUse={toolName:e.toolName,toolInput:s},e.toolCallId&&t.sentToolUseIds.add(e.toolCallId);const o=this.trimToolWirePayload?N(s):s;t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_use",payload:{tool_name:e.toolName,tool_input:o}})||this.callbacks.sendToolUse(t.eventId,t.sessionId,e.toolName,o)}break}case m.ToolResult:{t.awaitingToolResult=!1;{const s=e.toolCallId||e.toolName||"";t.lastToolProgress.delete(s),t.lastToolProgressSentAt.delete(s)}if(t.lastToolUse=null,e.content){i=!0;const s=L(t,e),n=e.content,o=b(n);if(t.lastToolResult?.toolName===s&&b(t.lastToolResult.content)===o)break;if(t.lastToolResult={toolName:s,content:n},!this.trimToolWirePayload||e.toolStatus==="failed"){const r=this.trimToolWirePayload?"(failed)":n;t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_result",payload:{tool_name:s,content:r}})||this.callbacks.sendToolResult(t.eventId,t.sessionId,s,r)}}break}case m.ToolProgress:{if(i=!0,e.content){const s=e.toolCallId||e.toolName||"";if(t.lastToolProgress.get(s)===e.content||(t.lastToolProgress.set(s,e.content),this.trimToolWirePayload))break;const n=Date.now(),o=t.lastToolProgressSentAt.get(s);if(o!==void 0&&n-o<Ce)break;t.lastToolProgressSentAt.set(s,n);const r=L(t,e);t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"tool_progress",payload:{tool_name:r,content:e.content}})||this.callbacks.sendToolResult(t.eventId,t.sessionId,r,e.content)}break}case m.Thinking:{t.lastToolUse=null,t.lastToolResult=null,e.content&&(i=!0,t.textSegmentInterrupted=!0,this.emitRawEventEnvelope(t,{type:"thinking",payload:{content:e.content}})||this.callbacks.sendThinking(t.eventId,t.sessionId,e.content));break}case m.Error:{t.lastToolUse=null,t.lastToolResult=null;const s=String(e.error??"unknown error");this.emitRawEventEnvelope(t,{type:"error",payload:{message:s}}),a.error("acp-adapter",`ACP error: ${s}`),this.callbacks.sendRunError(t.eventId,t.sessionId,s);break}case m.Result:{if(e.synthetic&&this.shouldDeferSyntheticResultForDetachedKimiTask(t,e)){a.info("acp-adapter",`Synthetic ACP Result deferred: kimi detached task still running event=${t.eventId} session=${t.sessionId}`),this.acpClient?.deferSettledResult();return}this.emitRawEventEnvelope(t,{type:"result",payload:{done:e.done??!0}});const s=t.quotedStream.flush();s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),s.deltaContent&&this.appendToStream(t,s.deltaContent),this.flushStream(),this.finishRun("responded");break}}i&&(t.lastProgressAt=Date.now(),t.idleNoProgressCount=0),this.resetIdleTimer(t)}handlePermissionRequest(e){const t=e.permissionRequest;if(a.info("acp-adapter","permission_request received",{sessionId:this.activeRun?.sessionId,eventId:this.activeRun?.eventId,requestId:e.requestId??null,toolCallId:t?.toolCallId??null,toolName:t?.toolName??null,toolTitle:t?.toolTitle??null,optionsCount:Array.isArray(t?.options)?t.options.length:0,hasActiveRun:this.activeRun!==null,approvalMode:this.approvalMode,rawTransport:this.rawTransport,hasRawEventEnvelopeCb:typeof this.callbacks.sendRawEventEnvelope=="function",hasSendPermissionCardCb:typeof this.callbacks.sendPermissionCard=="function",rawPr:D(t,3e3)}),!t||!e.requestId||!this.acpClient){a.warn("acp-adapter","permission_request dropped: missing prerequisite",{hasPr:t!=null,hasRequestId:!!e.requestId,hasAcpClient:!!this.acpClient}),e.requestId&&this.captureAuditEvent({type:m.PermissionResponse,requestId:e.requestId,permissionDecision:"dropped"});return}if(this.approvalMode==="yolo"||this.approvalMode==="autoEdit"){a.info("acp-adapter",`Auto-approving (${this.approvalMode}): ${t.toolName}`),this.acpClient.respondPermission(t.requestId,{behavior:"allow"}).catch(()=>{}),this.captureAuditEvent({type:m.PermissionResponse,requestId:t.requestId,toolCallId:t.toolCallId,permissionDecision:"allow"});return}const i=this.activeRun,s=be(t);if(s&&i&&this.callbacks.sendAgentQuestionCard){this.resetIdleTimer(i),this.pendingQuestions.set(e.requestId,{options:[...t.options]});const r=t.options.some(l=>P.test(l.optionId));i.textSegmentInterrupted=!0,this.callbacks.sendAgentQuestionCard(i.eventId,i.sessionId,{request_id:e.requestId,mode:"form",questions:[{header:s.prompt,prompt:s.prompt,options:s.answerOptions.map(l=>l.name),allow_free_text:r}]}),a.info("acp-adapter","AskUserQuestion forwarded via agent_question card",{sessionId:i.sessionId,eventId:i.eventId,requestId:e.requestId,optionsCount:s.answerOptions.length});return}const n=t.toolCallId,o=_e(t.rawParams,e.toolInput,t.toolTitle);this.pendingApprovals.set(n,e.requestId),i?(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=null),i.textSegmentInterrupted=!0,this.emitRawEventEnvelope(i,{type:"permission_request",payload:{request_id:t.requestId,tool_call_id:n,tool_name:t.toolName,tool_title:t.toolTitle,...o?{tool_input:o}:{},options:t.options}})?a.info("acp-adapter","permission_request forwarded via rawEventEnvelope",{sessionId:i.sessionId,eventId:i.eventId,toolCallId:n,toolName:t.toolName}):(a.info("acp-adapter","permission_request falling back to sendPermissionCard",{sessionId:i.sessionId,eventId:i.eventId,toolCallId:n,toolName:t.toolName}),this.callbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,toolCallId:n,toolName:t.toolName,toolTitle:t.toolTitle,toolInput:o,options:t.options}))):(a.info("acp-adapter",`Permission request without active run, auto-approving: ${t.toolName}`),this.acpClient.respondPermission(e.requestId,{behavior:"allow"}),this.pendingApprovals.delete(n),this.captureAuditEvent({type:m.PermissionResponse,requestId:e.requestId,toolCallId:n,permissionDecision:"allow"}))}emitRawEventEnvelope(e,t){return!e||!this.rawTransport||!this.callbacks.sendRawEventEnvelope?!1:(this.callbacks.sendRawEventEnvelope(e.eventId,e.sessionId,{type:t.type,payload:t.payload,seq:++this.rawEventSeq,at:new Date().toISOString()}),!0)}resetIdleTimer(e,t){e.idleTimer&&clearTimeout(e.idleTimer),Date.now()-e.lastProgressAt<2e3&&this.refreshGrokLivenessBudget(e,e.lastProgressAt);const i=t??(e.awaitingToolResult?qe:$e),s=Date.now(),n=e.lastProgressAt+T-s,o=e.grokLivenessHoldUntil?e.grokLivenessHoldUntil-s:0,r=Math.max(0,Math.min(i,Math.max(n,o)));e.idleTimer=setTimeout(()=>{this.onIdleTimeout(e)},r)}async readIdleEvidence(e,t,i){if(A(this.config.command)==="grok"){const n=await K({sessionId:t,fromOffset:e.grokEventsOffset,extendStartAt:e.grokLivenessExtendStartAt});return n.kind==="progress"?(e.grokLivenessHoldUntil=void 0,e.grokLivenessExtendStartAt=n.extendStartAt,{fileActivity:!0,grokExtend:!1}):n.kind==="extend"?(e.grokLivenessExtendStartAt=n.extendStartAt,e.grokLivenessHoldUntil=n.extendUntil,a.info("acp-adapter",`Grok liveness: turn open for ${e.eventId} (freshMs=${n.freshMs??"none"}), holding until budget`),{fileActivity:!1,grokExtend:!0}):(e.grokLivenessHoldUntil=void 0,n.turn==="open"&&a.warn("acp-adapter",`Grok liveness budget exhausted for ${e.eventId} (turn still open, session files stale), allowing close`),{fileActivity:!1,grokExtend:!1})}return{fileActivity:await this.checkSessionFileActivity(t,i),grokExtend:!1}}refreshGrokLivenessBudget(e,t){A(this.config.command)==="grok"&&(e.grokLivenessExtendStartAt=t,e.grokLivenessHoldUntil=void 0)}async onIdleTimeout(e){if(this.activeRun?.eventId!==e.eventId)return;const t=this.acpClient,i=Date.now()-e.lastProgressAt;if(i>=T){if(t?.isAlive){const s=e.lastProgressAt,n=await this.readIdleEvidence(e,t.sessionId,e.lastIdleCheckAt);if(this.activeRun?.eventId!==e.eventId)return;const o=e.lastProgressAt>s;if(e.lastIdleCheckAt=Date.now(),o||n.fileActivity){n.fileActivity&&(e.lastProgressAt=Date.now()),e.idleNoProgressCount=0,a.info("acp-adapter",`Hard cap recheck found ${o?"stream progress":"session file activity"}, refreshing watchdog: ${e.eventId}`),this.resetIdleTimer(e);return}if(n.grokExtend){this.resetIdleTimer(e);return}}a.error("acp-adapter",`Turn inactive ${Math.round(i/1e3)}s \u2265 cap ${Math.round(T/1e3)}s, forcing timeout: ${e.eventId}`),this.finishRun("failed",`turn inactivity timeout after ${Math.round(i/1e3)}s with no ACP activity`),this.declareStuck();return}t?.isAlive?t.ping(5e3).then(async s=>{if(this.activeRun?.eventId!==e.eventId)return;if(!s){await this.handlePingFailure(e,t);return}if(e.consecutivePingFailures=0,e.awaitingToolResult){const d=e.lastIdleCheckAt,h=await this.readIdleEvidence(e,t.sessionId,d);if(this.activeRun?.eventId!==e.eventId)return;e.lastIdleCheckAt=Date.now(),h.fileActivity?(e.lastProgressAt=Date.now(),a.info("acp-adapter",`Idle timer: tool running, ping ok, session file active, refreshing watchdog: ${e.eventId}`)):h.grokExtend||a.info("acp-adapter",`Idle timer: tool running, ping ok, continuing until inactivity cap: ${e.eventId}`),e.idleNoProgressCount=0,this.resetIdleTimer(e);return}const n=e.lastIdleCheckAt,o=e.lastProgressAt>n,r=o?{fileActivity:!1,grokExtend:!1}:await this.readIdleEvidence(e,t.sessionId,n);if(this.activeRun?.eventId!==e.eventId)return;const l=o||r.fileActivity;e.lastIdleCheckAt=Date.now(),l?(r.fileActivity&&(a.info("acp-adapter",`Idle timer: no stream progress but session file active, continuing: ${e.eventId}`),e.lastProgressAt=Date.now()),e.idleNoProgressCount=0,this.resetIdleTimer(e)):r.grokExtend?(e.idleNoProgressCount=0,this.resetIdleTimer(e)):(e.idleNoProgressCount++,a.info("acp-adapter",`Idle timer: ping ok, no stream progress (cycle=${e.idleNoProgressCount}), extending until inactivity cap (${Math.round(T/6e4)}min): ${e.eventId}`),this.resetIdleTimer(e))}).catch(()=>{this.activeRun?.eventId===e.eventId&&this.handlePingFailure(e,t)}):(a.error("acp-adapter",`Agent idle (no client), declaring stuck: ${e.eventId}`),this.finishRun("failed",this.describeUnreachable()),this.declareStuck())}async handlePingFailure(e,t){const i=e.lastIdleCheckAt,s=e.lastProgressAt>i,n=s?{fileActivity:!1,grokExtend:!1}:await this.readIdleEvidence(e,t.sessionId,i);if(this.activeRun?.eventId===e.eventId){if(s||n.fileActivity||n.grokExtend||e.awaitingToolResult||this.pendingQuestions.size>0){const o=s?"stream progress":n.fileActivity?"session file activity":n.grokExtend?"grok turn still open":e.awaitingToolResult?"tool in flight":"question pending user answer";a.info("acp-adapter",`Idle timer: ping failed but ${o}, continuing: ${e.eventId}`),e.consecutivePingFailures=0,e.lastIdleCheckAt=Date.now(),n.fileActivity&&(e.lastProgressAt=Date.now()),this.resetIdleTimer(e);return}if(e.consecutivePingFailures++,e.lastIdleCheckAt=Date.now(),e.consecutivePingFailures<G){a.warn("acp-adapter",`Idle timer: ping failed (${e.consecutivePingFailures}/${G}), rechecking in ${W/1e3}s: ${e.eventId}`),this.resetIdleTimer(e,W);return}a.error("acp-adapter",`Ping failed ${e.consecutivePingFailures}x with no activity evidence, declaring stuck: ${e.eventId}`),this.finishRun("failed",this.describeUnreachable()),this.declareStuck()}}async checkSessionFileActivity(e,t){if(!e)return!1;try{if(this.isKimi)return await we(e,t);const i=A(this.config.command);return i==="kiro-cli"?await Te(e,t):i==="qodercli"?await j(".qoder",e,t):i==="qoderclicn"?await j(".qoder-cn",e,t):i==="dim"?await ke(e,t):i==="grok"?(await K({sessionId:e})).kind==="progress":!1}catch{return!1}}shouldDeferSyntheticResultForDetachedKimiTask(e,t){if(!this.isKimi)return!1;try{return Re(t.sessionId||this.acpClient?.sessionId||e.sessionId)}catch{return!1}}declareStuck(){this.pendingQuestions.clear(),this.acpClient&&(this.acpClient.dispose(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(this.agentProcess.close().catch(()=>{}),this.agentProcess=null),this.emit("stuck")}rolloverInterruptedTextSegment(e){e.textSegmentInterrupted&&(e.textSegmentInterrupted=!1,this.flushStream(),e.chunkSeq!==0&&(this.callbacks.sendStreamChunk(e.eventId,e.sessionId,"",++e.chunkSeq,!0,e.currentClientMsgId,e.quotedMessageId),e.currentSegmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.currentSegmentIndex}`,e.chunkSeq=0,e.markdownSegmenter.reset(),a.info("acp-adapter",`stream segment rollover event=${e.eventId} segment=${e.currentSegmentIndex} reason=process_boundary`)))}appendToStream(e,t){e.buffer+=t,e.flushTimer||(e.flushTimer=setTimeout(()=>this.flushStream(),Me))}emitSegmentedStream(e,t){if(!t)return;const i=e.markdownSegmenter.push(t);for(const s of i)s.text&&(this.callbacks.sendStreamChunk(e.eventId,e.sessionId,s.text,++e.chunkSeq,s.closeAfter===!0,e.currentClientMsgId,e.quotedMessageId),s.closeAfter&&(e.currentSegmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.currentSegmentIndex}`,e.chunkSeq=0,a.info("acp-adapter",`stream segment rollover event=${e.eventId} segment=${e.currentSegmentIndex} reason=${s.reason??"threshold"}`)))}handleOrphanAcpEvent(e){if(!(!this.sessionConnected||this.compacting||Date.now()<this.orphanSuppressedUntil)){if(e.type===m.Text&&e.content){this.orphanSessionId===null&&(this.orphanSessionId=this.currentAibotSessionId??"");const t=this.orphanQuotedStream.consume(e.content);t.deltaContent&&(this.orphanBuffer+=t.deltaContent),this.orphanBuffer.length>=Le?this.flushOrphanBuffer():this.scheduleOrphanFlush();return}e.type===m.Result&&this.flushOrphanBuffer()}}scheduleOrphanFlush(){this.orphanFlushTimer&&clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=setTimeout(()=>{this.orphanFlushTimer=null,this.flushOrphanBuffer()},De),this.orphanFlushTimer.unref?.()}flushOrphanBuffer(){if(this.orphanFlushTimer&&(clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=null),this.orphanSessionId===null&&!this.orphanBuffer)return;const e=this.orphanQuotedStream.flush();e.deltaContent&&(this.orphanBuffer+=e.deltaContent),this.orphanQuotedStream=new S;const t=this.orphanSessionId||this.currentAibotSessionId;this.orphanSessionId=null;const i=this.orphanBuffer.trim();if(this.orphanBuffer="",!!i){if(!t||!this.callbacks.sendAgentMessage){a.warn("acp-adapter",`orphan agent output dropped (${t?"no sendAgentMessage callback":"no session id"}) chars=${i.length}`);return}a.info("acp-adapter",`delivering orphan agent output session=${t} chars=${i.length}`);for(let s=0;s<i.length;s+=Y)this.callbacks.sendAgentMessage(t,i.slice(s,s+Y))}}suppressOrphanOutput(e){this.orphanSuppressedUntil=Date.now()+e,this.orphanFlushTimer&&(clearTimeout(this.orphanFlushTimer),this.orphanFlushTimer=null),this.orphanBuffer="",this.orphanQuotedStream=new S,this.orphanSessionId=null}flushStream(){const e=this.activeRun;if(!e||!e.buffer)return;e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null);const t=e.buffer;e.buffer="",this.emitSegmentedStream(e,t)}lastExitCode=null;describeUnreachable(){return this.agentProcess?.alive?"agent unreachable: no response while its process is still running":this.lastExitCode===null?"agent unreachable: its process is no longer running":`agent unreachable: its process exited (code=${this.lastExitCode})`}static sanitizeFailureReasonForUser(e){return e.replace(/\bunreachable\b/gi,"unresponsive").replace(/\bidle cycles?\b/gi,"consecutive checks")}finishRun(e,t){const i=this.activeRun;if(!i)return;this.snapshotAuditBoundary(i.eventId),this.activeRun=null,this.acpClient?.clearSettleTimer(),this.emit("eventDone",i.eventId),this.clearRunTimers(i);const s=i.quotedStream.flush();s.quotedMessageId&&(i.quotedMessageId=s.quotedMessageId),s.deltaContent&&(i.buffer+=s.deltaContent);let n=!1;if(t)if(e==="failed"){a.error("acp-adapter",`finishRun failed: ${t} event=${i.eventId}`);const r=ee.sanitizeFailureReasonForUser(t);i.buffer+=`
|
|
19
19
|
|
|
20
|
-
The task was interrupted (${r}). Please resend your instruction.`,n=!0}else a.info("acp-adapter",`finishRun ${e}: ${t} event=${i.eventId}`);i.buffer&&(this.emitSegmentedStream(i,i.buffer),i.buffer="");const o=++i.chunkSeq;if(this.callbacks.sendFinalStreamChunkReliable){const r=i.quotedMessageId;(r?this.callbacks.sendFinalStreamChunkReliable(i.eventId,i.sessionId,i.currentClientMsgId,r):this.callbacks.sendFinalStreamChunkReliable(i.eventId,i.sessionId,i.currentClientMsgId)).then(()=>{i.silent||this.callbacks.sendEventResult(i.eventId,e,t,void 0,n),this.persistEventResult(i,e,t),this.replayNextDeferredEvent(),this.tryRunPendingAutoCompact()}).catch(d=>{const
|
|
20
|
+
The task was interrupted (${r}). Please resend your instruction.`,n=!0}else a.info("acp-adapter",`finishRun ${e}: ${t} event=${i.eventId}`);i.buffer&&(this.emitSegmentedStream(i,i.buffer),i.buffer="");const o=++i.chunkSeq;if(this.callbacks.sendFinalStreamChunkReliable){const r=i.quotedMessageId;(r?this.callbacks.sendFinalStreamChunkReliable(i.eventId,i.sessionId,i.currentClientMsgId,r):this.callbacks.sendFinalStreamChunkReliable(i.eventId,i.sessionId,i.currentClientMsgId)).then(()=>{i.silent||this.callbacks.sendEventResult(i.eventId,e,t,void 0,n),this.persistEventResult(i,e,t),this.replayNextDeferredEvent(),this.tryRunPendingAutoCompact()}).catch(d=>{const h=`final output delivery failed: ${d instanceof Error?d.message:String(d)}`,u=e==="responded"?"failed":e,v=e==="responded"?h:t,g=e==="responded"?!1:n;a.warn("acp-adapter",`finalStreamChunk rejected/failed event=${i.eventId}: ${h}`),i.silent||this.callbacks.sendEventResult(i.eventId,u,v,void 0,g),this.persistEventResult(i,u,v),this.replayNextDeferredEvent(),this.tryRunPendingAutoCompact()})}else this.callbacks.sendStreamChunk(i.eventId,i.sessionId,"",o,!0,i.currentClientMsgId,i.quotedMessageId),i.silent||this.callbacks.sendEventResult(i.eventId,e,t,void 0,n),this.persistEventResult(i,e,t),this.replayNextDeferredEvent(),this.tryRunPendingAutoCompact()}beginAuditCapture(e){if(!e.audit?.enabled||this.auditCaptures.has(e.event_id))return;let t;if(this.reasonixAuditTranscriptPath)try{t=$(this.reasonixAuditTranscriptPath).size}catch{t=0}this.auditCaptures.set(e.event_id,{...t===void 0?{}:{transcriptStartOffset:t},events:[]}),this.activeAuditEventId=e.event_id}captureAuditEvent(e){if(this.isKimi)return;const t=this.activeRun?.eventId??this.activeAuditEventId;if(!t)return;const i=this.auditCaptures.get(t);i&&i.events.push({sequence:i.events.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e);if(!t)return;let i=t.transcriptStartOffset;if(this.reasonixAuditTranscriptPath)try{i=$(this.reasonixAuditTranscriptPath).size}catch{}this.completedAuditBoundaries.set(e,{adapterType:"acp",agentType:this.auditAgentType,cwd:this.resolveCwd(),...this.reasonixAuditTranscriptPath?{transcriptPath:this.reasonixAuditTranscriptPath,transcriptStartOffset:t.transcriptStartOffset??0,transcriptEndOffset:i??0}:{},providerSessionId:this.acpClient?.sessionId,...this.isKimi?{}:{acpEvidence:{events:t.events}}}),this.auditCaptures.delete(e),this.activeAuditEventId===e&&(this.activeAuditEventId=null)}getContextWindowUsedPercentage(e){return"usedPercentage"in e?Number.isFinite(e.usedPercentage)?e.usedPercentage:null:!Number.isFinite(e.used)||!Number.isFinite(e.size)||e.size<=0?null:Math.min(100,e.used/e.size*100)}maybeScheduleAutoCompact(e){const t=this.getContextWindowUsedPercentage(e);t===null||t<Q||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,a.info("acp-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${Q}%, scheduling compact`),this.tryRunPendingAutoCompact())}tryRunPendingAutoCompact(){this.pendingAutoCompact&&(this.stopped||!this.acpClient?.isAlive||this.activeRun||this.compacting||(this.pendingAutoCompact=!1,this.execCommand("compact","",this.currentAibotSessionId??"").then(e=>{a.info("acp-adapter",`[auto-compact] compact done status=${e.status} msg=${e.message??""}`)}).catch(e=>{a.warn("acp-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:String(e)}`)})))}persistEventResult(e,t,i){this.eventResults&&!e.silent&&this.eventResults.set({sessionId:e.sessionId,eventId:e.eventId,status:t,msg:i,updatedAt:Date.now()})}}class Ge extends q{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){a.warn("acp-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}export{ee as AcpAdapter};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P(
|
|
1
|
+
import{spawn as U}from"node:child_process";import{randomUUID as N}from"node:crypto";import{EventEmitter as L}from"node:events";import{existsSync as M,readFileSync as w,statSync as H,mkdirSync as O,writeFileSync as Q,realpathSync as q}from"node:fs";import{homedir as C}from"node:os";import{join as P,dirname as J,resolve as z}from"node:path";import{fileURLToPath as X}from"node:url";import{log as a}from"../../core/log/index.js";import{killProcessGroup as A}from"../../core/runtime/spawn.js";import{withUserHomeEnv as Z}from"../../core/util/home-env.js";import{InternalApiServer as tt}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as et,pruneLegacyMcpServerEntries as it}from"../../core/mcp/server-name.js";import{syncDefaultSkillsToDir as st}from"../../default-skills/index.js";import{buildSimpleProbeReport as nt}from"../shared/probe-util.js";import{getAgyModelCatalog as rt,resolveAgyModelFlag as ot}from"./model-list.js";import{isGrixInternalToolName as k}from"../../core/mcp/tools.js";import{AgyStreamParser as at}from"./stream-parser.js";const c="agy-adapter",ct=/The following is a <SYSTEM_MESSAGE> not actually sent by the user\. It is provided by the system as important information to pay attention to\.\s*<SYSTEM_MESSAGE>[\s\S]*?<\/SYSTEM_MESSAGE>/g;function lt(v){return v.replace(ct,"").trim()}function ht(v){return/^API error \(attempt \d+\):/.test(v.trim())}function dt(v,t,e,s){return v===0&&ht(t)&&(e.trim().length>0||s)}function W(v){try{return process.kill(v,0),!0}catch(t){return t.code==="EPERM"}}function ut(v){try{return q(v)}catch{return v}}const j=P(C(),".gemini","antigravity-cli","log"),ft="CLI store manager shutting down",D=5e3,_=15e3,Y=480*1e3,F=1800*1e3,pt=["fetchAvailableModels","loadCodeAssist","token refreshed","ListExperiments","experiment refresh","Experiments refreshed","Reloading system slash commands","Slash commands unchanged","doRefreshQuota"];function B(v,t){const e=Number(process.env[v]);return Number.isFinite(e)&&e>0?e:t}const vt="0",K=P(C(),".gemini","antigravity-cli","cache","last_conversations.json"),gt=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001agent_id\uFF08\u5F53\u524D Agent\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u5F53\u524D Turn \u7684\u6B63\u5F0F\u56DE\u7B54\u76F4\u63A5\u4F5C\u4E3A\u6700\u7EC8\u54CD\u5E94\u8F93\u51FA\uFF0C\u7531\u8FDE\u63A5\u5668\u8BFB\u53D6\u5E76\u53D1\u9001\u7ED9\u7528\u6237\u3002","\u4E0D\u8981\u4F7F\u7528 grix_message_send \u56DE\u7B54\u5F53\u524D\u5165\u7AD9\u4E8B\u4EF6\uFF1B\u5B83\u4EC5\u7528\u4E8E\u4E0E\u672C\u6B21\u56DE\u7B54\u65E0\u5173\u7684\u4E3B\u52A8\u6D88\u606F\u3002","\u8FDB\u7A0B\u5B89\u5168\uFF1A\u542F\u52A8\u4E34\u65F6\u6216\u6F14\u793A\u670D\u52A1\u65F6\u5FC5\u987B\u8BB0\u5F55\u5176 PID\uFF0C\u505C\u6B62\u65F6\u53EA\u7EC8\u6B62\u5DF2\u786E\u8BA4\u5C5E\u4E8E\u672C\u4EFB\u52A1\u7684\u8BE5 PID \u6216\u5176\u4E13\u5C5E\u8FDB\u7A0B\u7EC4\u3002","\u7981\u6B62\u4F7F\u7528 `pkill`\u3001`killall` \u6216\u5176\u4ED6\u6309\u540D\u79F0/\u547D\u4EE4\u884C\u6A21\u5F0F\u6279\u91CF\u6740\u8FDB\u7A0B\u7684\u547D\u4EE4\uFF1B\u7EDD\u4E0D\u80FD\u7EC8\u6B62 Grix MCP\u3001\u5F53\u524D agy \u6216\u5176\u7236\u8FDB\u7A0B\u3001connector \u6216\u5176\u4ED6\u65E0\u5173\u8FDB\u7A0B\u3002"].join(""),mt=new Set(["send_msg","grix_reply"]),yt=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);function V(v){try{return structuredClone(v)}catch{return}}class Lt extends L{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;auditCaptures=new Map;completedAuditBoundaries=new Map;watchdogPollTimer=null;watchdogGraceTimer=null;watchdogKilledActiveProcess=!1;lastActivityAt=0;watchLogOffset=0;inactivityTimeoutMs=Y;inactivityCapMs=F;inactivityTimeoutError=null;inactivityWarned=!1;inFlightToolName=null;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];systemInstructionInjectedSessions=new Set;identityInjectedSessions=new Set;constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),a.info(c,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new tt,this.internalApi.setInvokeHandler(async(o,d,l,u)=>this.handleToolInvoke(o,d,u)),await this.internalApi.start(0),a.info(c,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=P(C(),".gemini","config","mcp_config.json");O(J(e),{recursive:!0});let s={};try{M(e)&&(s=JSON.parse(w(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};it(i,this.internalApi.url),i[t.name]={command:t.command,args:t.args},s.mcpServers=i,Q(e,`${JSON.stringify(s,null,2)}
|
|
2
|
+
`,"utf8"),a.info(c,`MCP config injected into ${e}`);const r=P(C(),".gemini","skills"),h=st(r);h.length>0&&a.info(c,`Synced connector skills to ${r}: [${h.join(", ")}]`)}catch(t){a.warn(c,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){this.touchActivity();let i=e;yt.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const r=this.activeEventId?this.auditCaptures.get(this.activeEventId):void 0,h=r?{sequence:r.toolInvocations.length,observedAt:new Date().toISOString(),action:t,params:V(i)}:void 0;r&&h&&r.toolInvocations.push(h);try{const o=await this.callbacks.agentInvoke(t,i,s);return h&&(h.completedAt=new Date().toISOString(),h.result=V(o)),mt.has(t)&&this.activeEventId&&this.activeEventSessionId&&i.session_id===this.activeEventSessionId&&(this.activeEventSentViaTool=!0),o}catch(o){throw h&&(h.completedAt=new Date().toISOString(),h.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.activeProcess){try{A(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId){this.finishInactivityWarning(this.activeEventId,this.activeEventSessionId);try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}}if(this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),a.info(c,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??N()}async resumeSession(t,e){}async destroySession(t){this.systemInstructionInjectedSessions.delete(t),this.identityInjectedSessions.delete(t)}onAgentProfileChanged(){this.identityInjectedSessions.clear()}sendPrompt(t){const e=new L;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;a.info(c,`cancelCurrentRun: killing process group for event ${t}`);try{A(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.finishInactivityWarning(t,this.activeEventSessionId??""),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{A(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.finishInactivityWarning(t,this.activeEventSessionId??""),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||!W(e.pid))return!1;const s=!!(e.stdout&&!e.stdout.destroyed),i=!!(e.stderr&&!e.stderr.destroyed);return s&&i}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return nt(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}snapshotAuditBoundary(t){const e=this.auditCaptures.get(t);if(!e)return;this.auditCaptures.delete(t);let s;if(e.logPath)try{s=H(e.logPath).size}catch{}const i=this.sessionConversationMap.get(e.sessionId)??e.conversationId;this.completedAuditBoundaries.set(t,{adapterType:"agy",...i?{providerSessionId:i}:{},...e.cwd?{cwd:e.cwd}:{},...e.logPath?{transcriptPath:e.logPath,transcriptStartOffset:e.logStartOffset??0,transcriptEndOffset:s??0}:{},agyEvidence:{...e.prompt===void 0?{}:{prompt:e.prompt},...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr},...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.response===void 0?{}:{response:e.response},toolInvocations:e.toolInvocations}})}clearActiveEventForShutdown(){if(this.activeProcess)try{A(this.activeProcess,"SIGKILL")}catch{}this.activeEventId&&(this.finishInactivityWarning(this.activeEventId,this.activeEventSessionId??""),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=z(X(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:et(this.callbacks.getAgentId?.()),command:process.execPath,args:[t]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){a.warn(c,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),a.info(c,`Processing event ${e} for session ${s}`);const r=this.buildAgyPrompt(t);t.audit?.enabled===!0&&this.auditCaptures.set(e,{sessionId:s,...i.cwd?{cwd:i.cwd}:{},...i.conversationId?{conversationId:i.conversationId}:{},prompt:r,toolInvocations:[]}),this.spawnAgyPrint(e,s,r,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["agent_id",this.callbacks.getAgentId?.()],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,d])=>d!=null&&d!=="").map(([d,l])=>`${d}="${l}"`).join(" "),i=this.renderContextBlock(t),r=i?`${t.content}
|
|
3
3
|
|
|
4
4
|
[Conversation context]
|
|
5
|
-
${i}`:t.content,
|
|
5
|
+
${i}`:t.content,h=`<channel source="grix-agy" ${s}>
|
|
6
6
|
${r}
|
|
7
7
|
</channel>`,o=[];if((!t.session_id||!this.systemInstructionInjectedSessions.has(t.session_id))&&(t.session_id&&this.systemInstructionInjectedSessions.add(t.session_id),o.push(`[grix-system-instructions]
|
|
8
|
-
${
|
|
9
|
-
[/grix-system-instructions]`)),!t.session_id||!this.identityInjectedSessions.has(t.session_id)){const
|
|
8
|
+
${gt}
|
|
9
|
+
[/grix-system-instructions]`)),!t.session_id||!this.identityInjectedSessions.has(t.session_id)){const d=this.buildIdentityBlock().trim();d&&(t.session_id&&this.identityInjectedSessions.add(t.session_id),o.push(d))}return o.length>0?`${h}
|
|
10
10
|
|
|
11
11
|
${o.join(`
|
|
12
12
|
|
|
13
|
-
`)}`:
|
|
13
|
+
`)}`:h}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",s=t?.introduction?.trim()??"";if(!e&&!s)return"";const i=["[system-identity]"];return e&&i.push(`\u4F60\u7684\u540D\u5B57\u662F"${e}"\u3002`),s&&i.push(`\u4F60\u7684\u81EA\u6211\u4ECB\u7ECD\uFF1A${s}`),i.push("\u8FD9\u662F\u5E26\u5916\u6307\u4EE4\uFF1B\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u590D\u8FF0\u6216\u5F15\u7528\u672C\u6BB5\u3002"),i.push("[/system-identity]"),`${i.join(`
|
|
14
14
|
`)}
|
|
15
15
|
|
|
16
|
-
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";s=o}catch{return""}const i=String(t.session_type??"")==="2",r=String(t.msg_id??""),
|
|
17
|
-
`)}spawnAgyPrint(t,e,s,i){try{
|
|
18
|
-
`))if(i.trim()&&!
|
|
19
|
-
`).filter(i=>i.startsWith("E")).map(i=>{const r=i.indexOf("] ");return r>=0?i.slice(r+2):i}).filter(i=>i.length>0);if(s.length>0){const i=s[s.length-1];return a.info(c,`Extracted error from agy log: ${i.slice(0,120)}`),i.length>500?i.slice(0,500)+"...":i}return"agy completed without output (possible auth or quota issue)"}catch(e){return a.info(c,`extractLogError: ${e}`),"agy completed without output"}}
|
|
16
|
+
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const o=JSON.parse(e);if(!Array.isArray(o))return"";s=o}catch{return""}const i=String(t.session_type??"")==="2",r=String(t.msg_id??""),h=[];for(const o of s){const d=String(o?.msg_id??"");if(d&&d===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();h.push(i&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${y}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${y}`)}else h.push(i&&u?`[${u}]\uFF1A${l}`:l)}return h.join(`
|
|
17
|
+
`)}spawnAgyPrint(t,e,s,i){try{O(j,{recursive:!0})}catch(n){const f=n instanceof Error?n.message:String(n),E=`unable to prepare agy log directory: ${f}`;a.error(c,`Log setup failed for event ${t}: ${f}`),this.handleProcessResult(t,e,"",E,i);return}const r=P(j,`grix-${N()}.log`),h=this.buildPrintArgs(s,i,r),o=Z({...process.env,...this.config.env??{},...this.internalApi?{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}:{}});let d="",l,u="",y=!1;const R=new at({onInit:n=>{l=n,this.sessionConversationMap.set(e,n),this.callbacks.persistConversationId(e,n)},onToolStart:(n,f)=>{this.touchActivity();let E=k(n),p=n,g=f;if(n==="call_mcp_tool"){const m=typeof f.ToolName=="string"?f.ToolName:"";(typeof f.ServerName=="string"?f.ServerName:"").startsWith("grix")||k(m)?E=!0:m&&(p=m,g=f.Arguments||f)}if(E)return;this.inFlightToolName=p;const S=JSON.stringify(g??{});this.callbacks.sendToolUse?.(t,e,p,S)},onToolDone:(n,f,E,p)=>{this.touchActivity();let g=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)?g=!0:m&&(S=m)}(this.inFlightToolName===S||this.inFlightToolName===n)&&(this.inFlightToolName=null),!g&&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()&&(d=lt(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 ${h.map(n=>n.includes(" ")?`"${n}"`:n).join(" ")}`);const T=U(this.config.command,h,{cwd:i.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32"});this.activeProcess=T,this.lastActivityAt=Date.now(),this.watchLogOffset=0,this.inactivityWarned=!1,this.inactivityTimeoutError=null,this.inactivityTimeoutMs=B("GRIX_AGY_INACTIVITY_TIMEOUT_MS",Y),this.inactivityCapMs=Math.max(B("GRIX_AGY_INACTIVITY_CAP_MS",F),this.inactivityTimeoutMs+D);const G=[],x=[];T.stdout?.on("data",n=>{G.push(n),R.feed(n),this.touchActivity()}),T.stderr?.on("data",n=>{x.push(n),this.touchActivity()}),T.on("error",n=>{a.error(c,`Process spawn error for event ${t}: ${n.message}`),this.handleProcessResult(t,e,"",`spawn error: ${n.message}`,i)}),T.on("close",n=>{if(a.info(c,`Process exited for event ${t} with code ${n}`),this.activeEventId!==t)return;R.flush(),this.stopTurnWatchdog();const f=Buffer.concat(G).toString("utf-8"),E=Buffer.concat(x).toString("utf-8"),p=d.trim()?d:y?"":f,g=this.auditCaptures.get(t);g&&(g.stdout=f,g.stderr=E,g.exitCode=n);const S=this.watchdogKilledActiveProcess&&n===null;this.watchdogKilledActiveProcess=!1;const m=n===null?this.inactivityTimeoutError:null;this.inactivityTimeoutError=null;const $=dt(n,u,p,this.activeEventSentViaTool);if($&&a.warn(c,`Ignoring retried agy attempt error after delivery for event ${t}: ${u}`),S)p.trim()||this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const I=u||this.extractLogError(r);this.handleProcessResult(t,e,p,I,i,l)},300);else if(m)this.handleProcessResult(t,e,"",m,i,l);else if(u&&!$)this.handleProcessResult(t,e,"",u,i,l);else if(n!==0){const I=E.trim()||`process exited with code ${n}`;this.handleProcessResult(t,e,p,I,i,l)}else p.trim()?this.handleProcessResult(t,e,p,"",i,l):this.activeEventSentViaTool?this.handleProcessResult(t,e,p,"",i,l):setTimeout(()=>{const I=this.extractLogError(r);this.handleProcessResult(t,e,p,I,i,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 ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after turn end (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{A(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref());return}this.scanTurnLogActivity(e);const s=Date.now()-this.lastActivityAt,i=!!this.activeProcess.pid&&W(this.activeProcess.pid);if(!i&&s>=this.inactivityCapMs){const o=Math.round(s/1e3);this.inactivityTimeoutError=`turn inactivity timeout after ${o}s with no agy activity`,a.error(c,`Turn inactive ${o}s \u2265 cap ${Math.round(this.inactivityCapMs/1e3)}s with process not alive, killing process group for event ${t}`),this.stopTurnWatchdog();try{A(this.activeProcess,"SIGKILL")}catch{}return}if(this.inFlightToolName||this.inactivityWarned||s<this.inactivityTimeoutMs)return;this.inactivityWarned=!0;const r=Math.max(1,Math.round(s/6e4)),h=i?"AGY \u8FDB\u7A0B\u4ECD\u5728\u8FD0\u884C\uFF0C\u6309\u5B58\u6D3B\u72B6\u6001\u7EE7\u7EED\u7B49\u5F85":"\u6682\u672A\u68C0\u6D4B\u5230 AGY \u8FDB\u7A0B\u5B58\u6D3B\uFF0C\u6B63\u5728\u7B49\u5F85\u9000\u51FA\u6536\u53E3";a.warn(c,`No observable activity for ${Math.round(s/1e3)}s on event ${t} (threshold ${Math.round(this.inactivityTimeoutMs/1e3)}s, processAlive=${i}); notifying user`),this.callbacks.sendStreamChunk(t,this.activeEventSessionId??"",`\u26A0\uFE0F \u672C\u8F6E\u5DF2\u7EA6 ${r} \u5206\u949F\u6CA1\u6709\u53EF\u89C2\u6D4B\u54CD\u5E94\u3002${h}\uFF1B\u4F60\u53EF\u4EE5\u56DE\u590D /stop \u7EC8\u6B62\u3002`,1,!1,`agy-stall-${t}`)},D),this.watchdogPollTimer.unref()}handleTurnResultReceived(t){this.activeEventId!==t||!this.activeProcess||this.watchdogGraceTimer||(this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),a.info(c,`Stream-json result received for event ${t}; grace ${_}ms before kill`),this.watchdogGraceTimer=setTimeout(()=>{if(this.watchdogGraceTimer=null,!(this.activeEventId!==t||!this.activeProcess)){a.warn(c,`agy process still alive ${_}ms after result event (shutdown deadlock); killing process group for event ${t}`),this.watchdogKilledActiveProcess=!0;try{A(this.activeProcess,"SIGKILL")}catch{}}},_),this.watchdogGraceTimer.unref())}stopTurnWatchdog(){this.watchdogPollTimer&&(clearInterval(this.watchdogPollTimer),this.watchdogPollTimer=null),this.watchdogGraceTimer&&(clearTimeout(this.watchdogGraceTimer),this.watchdogGraceTimer=null)}touchActivity(){this.lastActivityAt=Date.now()}scanTurnLogActivity(t){let e;try{e=w(t)}catch{return}if(e.length<=this.watchLogOffset){this.watchLogOffset=e.length;return}const s=e.subarray(this.watchLogOffset).toString("utf-8");this.watchLogOffset=e.length;for(const i of s.split(`
|
|
18
|
+
`))if(i.trim()&&!pt.some(r=>i.includes(r))){a.debug(c,`turn log activity: ${i.slice(0,120)}`),this.touchActivity();return}}watchLogHasTurnEndMarker(t){try{return w(t,"utf-8").includes(ft)}catch{return!1}}buildPrintArgs(t,e,s){const i=["--print-timeout",vt,"--log-file",s],r=e.modelId?ot(e.modelId,rt()):"";return r&&i.push("--model",r),e.cwd&&i.push("--add-dir",e.cwd),i.push("--dangerously-skip-permissions"),e.conversationId&&i.push("--conversation",e.conversationId),i.push("--output-format","stream-json"),i.push("-p",t),i}readAgyConversationId(t){try{if(M(K)){const e=JSON.parse(w(K,"utf-8"));return e[ut(t)]||e[t]||void 0}}catch(e){a.debug(c,`readAgyConversationId: ${e}`)}}extractLogError(t){try{if(!M(t))return a.info(c,`extractLogError: log file not found: ${t}`),"agy completed without output";const e=w(t,"utf-8");if(!e)return a.info(c,`extractLogError: log file is empty: ${t}`),"agy completed without output";const s=e.split(`
|
|
19
|
+
`).filter(i=>i.startsWith("E")).map(i=>{const r=i.indexOf("] ");return r>=0?i.slice(r+2):i}).filter(i=>i.length>0);if(s.length>0){const i=s[s.length-1];return a.info(c,`Extracted error from agy log: ${i.slice(0,120)}`),i.length>500?i.slice(0,500)+"...":i}return"agy completed without output (possible auth or quota issue)"}catch(e){return a.info(c,`extractLogError: ${e}`),"agy completed without output"}}finishInactivityWarning(t,e){this.inactivityWarned&&(this.callbacks.sendStreamChunk(t,e,"",2,!0,`agy-stall-${t}`),this.inactivityWarned=!1)}handleProcessResult(t,e,s,i,r,h){if(this.activeEventId===t){if(this.finishInactivityWarning(t,e),i&&!s.trim()){a.error(c,`Event ${t} failed: ${i}`);const o=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota"),d=i.toLowerCase().includes("authentication failed"),l=o?"The agy API quota has been exhausted. Please try again later.":d?"agy authentication failed or timed out. Please check the agy login status and try again.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const o=s.trim();if(o){const l=r.cwd,u=l?this.extractDelta(o,l):o;l&&this.conversationOutputCache.set(l,o);const y=this.auditCaptures.get(t);y&&(y.response=u),u&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,u,1,!0,`agy-${t}`)}const d=h||(r.cwd?this.readAgyConversationId(r.cwd):void 0);d&&d!==r.conversationId&&(this.sessionConversationMap.set(e,d),this.callbacks.persistConversationId(e,d)),this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e){if(this.completedEventIds.add(e),this.completedEventIds.size>1e3){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.snapshotAuditBoundary(e)}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,this.stopTurnWatchdog(),this.watchdogKilledActiveProcess=!1,this.inactivityWarned=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(a.info(c,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{Lt as AgyAdapter};
|
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
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
|
|
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 E}from"../../core/config/paths.js";import{log as d}from"../../core/log/index.js";import{readJSONFile as S,writeJSONFileAtomic as T}from"../../core/util/json-file.js";import{withUserHomeEnv as b}from"../../core/util/home-env.js";const u="agy-model-list",p=3600*1e3,v=1e4,C="agy-models-cache.json";let c=null,f=0,l=null;function y(t){return N(E(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=S(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 T(n,{models:o,updatedAt:Date.now()})}function D(t){return new Promise((e,o)=>{const n=w(t,["models"],{stdio:["ignore","pipe","pipe"],windowsHide:!0,env:b()});let r="",s="";const a=setTimeout(()=>{n.kill("SIGKILL"),o(new Error("agy models timed out"))},v);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 j(t,e=[]){const o=h(t,e);return o?o.displayName:m(t).displayName}function z(t,e){const o=h(t,e);return o?o.id:m(t).slug}function P(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 D(t),o=P(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 J(t){return(!c||Date.now()-f>=p)&&t&&A(t),L()}function L(){return c??F()}async function K(t,e=!1){if(!t)return;const o=!c||Date.now()-f>=p;!e&&!o||await A(t)}function R(t=null){c=t,f=t?Date.now():0,l=null}export{L as getAgyModelCatalog,J as getCachedAgyModels,h as matchAgyModel,P as parseAgyModels,K as primeAgyModels,F as readPersistedAgyModels,R as resetAgyModelCacheForTests,y as resolveAgyModelCachePath,j as resolveAgyModelFlag,z as resolveAgyToolbarModelId,_ as writePersistedAgyModels};
|