grix-connector 1.0.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/acp/acp-adapter.js +8 -8
- package/dist/adapter/claude/activity-status-manager.js +1 -1
- package/dist/adapter/claude/claude-adapter.js +14 -14
- package/dist/adapter/claude/claude-bridge-server.js +1 -0
- package/dist/adapter/claude/claude-tools.js +1 -0
- package/dist/adapter/claude/claude-worker-client.js +1 -0
- package/dist/adapter/claude/mcp-http-launcher.js +2 -0
- package/dist/adapter/claude/result-timeout.js +1 -0
- package/dist/adapter/codewhale/codewhale-adapter.js +2 -2
- package/dist/adapter/codex/codex-bridge.js +6 -6
- package/dist/adapter/codex/lock-monitor.js +1 -0
- package/dist/adapter/codex/rollout-locator.js +1 -0
- package/dist/adapter/codex/session-activity.js +1 -0
- package/dist/adapter/codex/usage-parser.js +1 -1
- package/dist/adapter/cursor/cursor-adapter.js +5 -5
- package/dist/adapter/deepseek/deepseek-adapter.js +6 -0
- package/dist/adapter/deepseek/index.js +1 -0
- package/dist/adapter/opencode/opencode-adapter.js +4 -4
- package/dist/adapter/openhuman/openhuman-adapter.js +3 -3
- package/dist/adapter/pi/pi-adapter.js +4 -4
- package/dist/adapter/pi/pi-transport.js +2 -2
- package/dist/adapter/qwen/index.js +1 -0
- package/dist/adapter/qwen/qwen-adapter.js +4 -0
- package/dist/adapter/shared/probe-util.js +1 -0
- package/dist/aibot/client.js +1 -0
- package/dist/aibot/index.js +1 -0
- package/dist/aibot/types.js +0 -0
- package/dist/bridge/adapter-pool.js +1 -1
- package/dist/bridge/bridge.js +6 -6
- package/dist/bridge/deferred-events.js +1 -1
- package/dist/bridge/event-queue.js +1 -1
- package/dist/bridge/probe-helper.js +1 -0
- package/dist/bridge/send-controller.js +3 -3
- package/dist/core/admin/admin-server.js +1 -1
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/aibot/connection-handle.js +1 -1
- package/dist/core/file-ops/handler.js +1 -0
- package/dist/core/file-ops/list-files.js +1 -0
- package/dist/core/file-ops/types.js +0 -0
- package/dist/core/files/file-serve.js +1 -0
- package/dist/core/files/index.js +1 -1
- package/dist/core/files/list-handler.js +1 -1
- package/dist/core/mcp/event-tool-executor.js +1 -1
- package/dist/core/mcp/tool-schemas.js +1 -1
- package/dist/core/mcp/tools.js +1 -1
- package/dist/core/persistence/session-binding-store.js +1 -1
- package/dist/core/probe/index.js +0 -0
- package/dist/core/probe/types.js +0 -0
- package/dist/core/provider-quota/providers.js +1 -1
- package/dist/core/text-segmentation/safe-markdown-stream-segmenter.js +8 -6
- package/dist/core/transport/json-rpc.js +1 -1
- package/dist/core/util/cli-probe.js +3 -0
- package/dist/grix.js +3 -3
- package/dist/log.js +3 -0
- package/dist/main.js +31 -0
- package/dist/manager.js +2 -2
- package/dist/mcp/acp-mcp-server.js +2 -2
- package/dist/mcp/stdio/server.js +6 -6
- package/dist/mcp/stream-http/config.js +1 -0
- package/dist/mcp/stream-http/connection-binding.js +1 -0
- package/dist/mcp/stream-http/event-tool-executor.js +1 -0
- package/dist/mcp/stream-http/gateway.js +1 -0
- package/dist/mcp/stream-http/index.js +1 -0
- package/dist/mcp/stream-http/security.js +1 -0
- package/dist/mcp/stream-http/session-manager.js +1 -0
- package/dist/mcp/stream-http/tool-executor.js +1 -0
- package/dist/mcp/stream-http/tool-registry.js +1 -0
- package/dist/mcp/stream-http/tool-schemas.js +1 -0
- package/dist/protocol/acp-client.js +1 -1
- package/dist/protocol/event-mapper.js +5 -5
- package/dist/session/index.js +1 -0
- package/dist/session/manager.js +1 -0
- package/dist/transport/index.js +1 -0
- package/dist/transport/json-rpc.js +3 -0
- package/dist/types/events.js +1 -1
- package/openclaw-plugin/index.js +476 -197
- package/openclaw-plugin/skills/grix-admin/SKILL.md +134 -134
- package/openclaw-plugin/skills/grix-admin/references/api-contract.md +56 -56
- package/openclaw-plugin/skills/grix-egg/SKILL.md +43 -43
- package/openclaw-plugin/skills/grix-group/references/api-contract.md +1 -1
- package/openclaw-plugin/skills/grix-register/SKILL.md +34 -34
- package/openclaw-plugin/skills/grix-register/references/api-contract.md +7 -7
- package/openclaw-plugin/skills/grix-register/references/grix-concepts.md +8 -8
- package/openclaw-plugin/skills/grix-register/references/handoff-contract.md +6 -6
- package/openclaw-plugin/skills/grix-register/references/openclaw-setup.md +3 -3
- package/openclaw-plugin/skills/grix-register/references/user-replies.md +6 -6
- package/openclaw-plugin/skills/grix-update/SKILL.md +132 -132
- package/openclaw-plugin/skills/grix-update/references/cron-setup.md +17 -17
- package/openclaw-plugin/skills/grix-update/references/update-contract.md +68 -68
- package/openclaw-plugin/skills/message-send/SKILL.md +94 -94
- package/openclaw-plugin/skills/message-unsend/SKILL.md +63 -63
- package/openclaw-plugin/skills/message-unsend/flowchart.mermaid +11 -11
- package/package.json +1 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{fileURLToPath as
|
|
2
|
-
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}get acpSessionOptions(){return this.acpClient?.sessionOptions??null}buildToolbarContext(e,t){const i=this.acpClient?.sessionOptions,s=i?.currentModeId??"",n=i?.currentModelId??"",
|
|
1
|
+
import{fileURLToPath as b}from"node:url";import p from"node:path";import{homedir as v}from"node:os";import{promises as f}from"node:fs";import{EventEmitter as C}from"node:events";import{spawn as A}from"node:child_process";import{AgentProcess as R}from"../../agent/process.js";import{AcpClient as w,AcpAuthRequiredError as T,isAuthRequiredError as y}from"../../protocol/acp-client.js";import{AgentEventType as m}from"../../types/events.js";import{InternalApiServer as k}from"../../core/mcp/internal-api-server.js";import{EventResultsStore as _}from"../../core/persistence/event-results-store.js";import{QuotedMessageStream as $}from"../../core/util/quoted-message-stream.js";import{SafeMarkdownStreamSegmenter as E}from"../../core/text-segmentation/index.js";import{extractAcpTurnInput as M}from"../../core/protocol/payload-parser.js";import{injectMessageMetadata as P}from"../../core/protocol/message-metadata.js";import{log as r}from"../../core/log/index.js";import{scanSkills as S}from"../claude/skill-scanner.js";import{resolveCliPath as x,getCliVersion as q}from"../../core/util/cli-probe.js";const I=p.dirname(b(import.meta.url)),D=200,N=60*1e3,j=600*1e3;function B(h){return!(!(h instanceof Error)||h.code!==-32603||y(h))}function g(h){if(!(h instanceof Error))return String(h);let e=h.message;const t=h.data;return t&&(e+=` data=${JSON.stringify(t)}`),e}async function L(h,e){if(!h)return!1;const t=p.join(v(),".kiro","sessions","cli",`${h}.jsonl`);try{return(await f.stat(t)).mtimeMs>e}catch{return!1}}function U(h){return h.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"")}class oe extends C{type="acp";config;callbacks;agentProcess=null;acpClient=null;internalApi=null;activeRun=null;compacting=!1;compactingTimer=null;compactionDoneResolver=null;eventResults=null;pendingApprovals=new Map;clientMsgSeq=0;stopped=!1;acpAuthMethod;acpInitialMode;acpInitialModel;acpMcpTools;rawTransport;approvalMode;autoInjectArgs;bindingStore;sessionBindings=new Map;deferredEvents=new Map;currentAibotSessionId;sessionConnected=!1;rawEventSeq=0;recoveryContextBySessionId=new Map;constructor(e,t,i){if(super(),this.config=e,this.callbacks=t,this.acpAuthMethod=i?.acpAuthMethod,this.acpInitialMode=i?.acpInitialMode,this.acpInitialModel=i?.acpInitialModel,this.acpMcpTools=!1,this.rawTransport=i?.rawTransport??!1,this.approvalMode=i?.approvalMode??"default",this.autoInjectArgs=i?.autoInjectArgs,this.bindingStore=i?.bindingStore??null,this.currentAibotSessionId=i?.aibotSessionId?String(i.aibotSessionId).trim():void 0,i?.eventResultsPath&&(this.eventResults=new _(i.eventResultsPath)),this.bindingStore&&this.currentAibotSessionId){const s=this.bindingStore.get(this.currentAibotSessionId);s?.cwd&&this.sessionBindings.set(this.currentAibotSessionId,s.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.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver(),this.compactionDoneResolver=null),this.activeRun&&(this.activeRun.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null),this.activeRun.idleTimer&&(clearTimeout(this.activeRun.idleTimer),this.activeRun.idleTimer=null),this.activeRun=null),this.acpClient&&(this.acpClient.clearSettleTimer(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(await this.agentProcess.close(),this.agentProcess=null),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.agentProcess?.alive??!1}async createSession(e){return this.acpClient?.sessionId??""}async resumeSession(e,t){}async destroySession(e){}sendPrompt(e){const t=new O(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"))}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.activeRun.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null),this.activeRun.idleTimer&&(clearTimeout(this.activeRun.idleTimer),this.activeRun.idleTimer=null),this.activeRun=null)}getMcpConfig(){if(!this.internalApi)return null;const e=p.resolve(I,"../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async probe(e){const t=this.config.command||"gemini",i=await x(t),s=i!==null;let n=null,o;if(s){const u=await q(t);n=u.version,u.error&&(o=u.error)}else o={code:"cli_not_found",message:`command not found: ${t}`};const a=this.acpClient?.model??null,c=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:a,base_url:null,source:{model:a?"runtime":"unknown",base_url:"unknown"}},process:{started:!!this.agentProcess,alive:c.alive,busy:c.busy}}}getSupportedCommands(){return[{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){try{switch(e){case"model":{const s=t.trim();if(s)return await this.setModel(s)?{status:"ok",message:`Model set to ${s}`}:{status:"failed",message:`Failed to set model: ${s}`};const n=this.buildToolbarContext("model_list");return{status:"ok",message:`Current: ${n.currentModelId||"unknown"}`,data:n}}case"mode":{const s=t.trim();if(s)return await this.setMode(s)?{status:"ok",message:`Mode set to ${s}`}:{status:"failed",message:`Failed to set mode: ${s}`};const n=this.buildToolbarContext("mode_list");return{status:"ok",message:`Current: ${n.currentModeId||"unknown"}`,data:n}}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 s=new Promise(n=>{this.compactionDoneResolver=n});try{await this.acpClient.send("/compact")}catch(n){throw this.finishCompaction("send-failed"),n}return this.compactingTimer=setTimeout(()=>this.finishCompaction("timeout"),15e3),this.compactingTimer.unref?.(),await s,{status:"ok",message:"Compacted"}}case"status":{const s=this.getStatus(),n=this.acpClient?.sessionOptions;return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Model: ${n?.currentModelId??"unknown"}, Mode: ${n?.currentModeId??"unknown"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,model:n?.currentModelId??"",mode:n?.currentModeId??""}}}case"skills":{const s=S({mode:this.config.command==="kiro-cli"?"kiro":"gemini",projectDir:process.cwd()}),n=s.map(o=>`- ${o.name}${o.trigger?` (${o.trigger})`:""} [${o.source}]: ${o.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
2
|
+
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}get acpSessionOptions(){return this.acpClient?.sessionOptions??null}buildToolbarContext(e,t){const i=this.acpClient?.sessionOptions,s=i?.currentModeId??"",n=i?.currentModelId??"",o=i?.modes.map(l=>({id:l.id,name:l.name}))??[],a=i?.models.map(l=>({modelId:l.modelId,name:l.name}))??[],c=i?.models.map(l=>({id:l.modelId,displayName:l.name}))??[],d=i?.modes.map(l=>({id:l.id,displayName:l.name}))??[],u={outcome:e,...t?{cwd:t}:{},model_id:n,mode_id:s,currentModelId:n,currentModeId:s,available_models:c,available_modes:d,availableModels:c,availableModes:d,models:a,modes:o};return r.info("acp-adapter",`[toolbar] buildToolbarContext outcome=${e} model_id="${n}" available_models=${JSON.stringify(c.map(l=>l.id))} currentModelId=${n}`),u}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?(this.pendingApprovals.delete(e),this.acpClient&&this.acpClient.respondPermission(i,{behavior:t}).catch(s=>{r.error("acp-adapter",`Failed to respond to permission: ${s}`)}),this.activeRun&&this.resetIdleTimer(this.activeRun),!0):!1}respondToPermission(e,t){this.acpClient&&this.acpClient.respondPermission(e,t).catch(i=>{r.error("acp-adapter",`Failed to respond to permission: ${i}`)}),this.activeRun&&this.resetIdleTimer(this.activeRun)}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};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 a;return n&&(o==="allow-once"||o==="allow-always")?a=o:n?a="allow":a="deny",s?this.handleAcpApprovalAction(s,a)?(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:""}}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 f.stat(i),!1}catch{r.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=>(r.error("acp-adapter",`Failed to create session on bind: ${g(s)}`),this.callbacks.sendUpdateBindingCard(e,"failed",t),!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=S({mode:"kiro",projectDir:t})}catch(s){r.warn("acp-adapter",`Kiro skills scan failed: ${s instanceof Error?s.message:String(s)}`);return}try{this.callbacks.onSkillsUpdate(i)}catch(s){r.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)){this.deferredEvents.delete(e),this.cancelDeferredTimer(e),r.info("acp-adapter",`Replaying ${t.length} deferred events for session ${e}`);for(const{event:i}of t){if(this.activeRun){r.info("acp-adapter",`Cannot replay ${i.event_id}: agent busy, dropping`);continue}this.startRun(i,!1)}}}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),r.info("acp-adapter",`Compaction finished (${e}); replaying deferred events`);for(const i of[...this.deferredEvents.keys()])this.replayDeferredEvents(i);const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.()}announceDeferredComposing(e){}deliverInboundEvent(e){if(this.eventResults?.has(e.session_id,e.event_id)){const t=this.eventResults.get(e.session_id,e.event_id);r.info("acp-adapter",`Deduplicating event ${e.event_id} (cached: ${t.status})`),this.callbacks.sendEventResult(e.event_id,t.status,t.msg);return}if(this.compacting){r.info("acp-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.deferEvent(e);return}if(this.activeRun){r.info("acp-adapter",`Event ${e.event_id} rejected: busy`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}if(!this.agentProcess?.alive){this.callbacks.sendEventResult(e.event_id,"failed","agent not alive");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),r.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)r.info("acp-adapter",`Rejecting deferred event ${s.event_id}: ${e}`),this.callbacks.sendEventResult(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){r.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.callbacks.sendEventResult(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,buffer:"",quotedStream:new $,markdownSegmenter:new E,quotedMessageId:void 0,flushTimer:null,idleTimer:null,awaitingToolResult:!1,responded:!1,silent:t,lastProgressAt:Date.now(),lastIdleCheckAt:Date.now(),idleNoProgressCount:0};const s=this.activeRun,n=M(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=P(n.prompt,{messageId:e.msg_id,quotedMessageId:e.quoted_message_id}),a=this.injectRecoveryContext(s.sessionId,o);this.sendPromptWithRetry(s,a)}injectRecoveryContext(e,t){const i=this.recoveryContextBySessionId.get(e);return i?(this.recoveryContextBySessionId.delete(e),r.info("acp-adapter",`Injecting recovery context for session ${e} (chars=${i.length})`),`${i}
|
|
3
3
|
|
|
4
4
|
[\u5F53\u524D\u7528\u6237\u6D88\u606F]
|
|
5
|
-
${t}`):t}sendPromptWithRetry(e,t
|
|
6
|
-
`);return await
|
|
5
|
+
${t}`):t}sendPromptWithRetry(e,t){this.acpClient.send(t).catch(i=>{if(r.error("acp-adapter",`Prompt failed: ${g(i)}`),B(i)){const n=i instanceof Error?i.message:String(i),o=e.eventId,a=e.sessionId;r.info("acp-adapter",`Internal error escalated to bridge: event=${o} session=${a} err=${n}`),this.silentlyDiscardActiveRun(e),this.emit("internalError",{eventId:o,sessionId:a,errorMsg:n});return}const s=i instanceof Error?i.message:String(i);this.finishRun("failed",s)})}silentlyDiscardActiveRun(e){this.activeRun===e&&(this.activeRun=null,this.acpClient?.clearSettleTimer(),e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null),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"),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.agentProcess=new R;const i=this.resolveCwd();try{if(!(await f.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}try{await this.agentProcess.start({command:this.config.command,args:e.length>0?e:void 0,cwd:i,env:this.config.env})}catch(s){throw r.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}r.info("acp-adapter","ACP agent process started"),this.agentProcess.on("error",s=>{this.stopped||(r.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.stopped||(r.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()),this.acpClient=new w,this.acpClient.on("event",a=>this.handleAcpEvent(a)),this.acpClient.on("activity",()=>{this.activeRun&&this.resetIdleTimer(this.activeRun)}),this.acpClient.on("session-lost",()=>{this.stopped||this.agentProcess?.alive&&(r.error("acp-adapter","ACP transport closed while agent process still alive, triggering respawn"),this.emit("exit",null))});const i=this.currentAibotSessionId&&this.bindingStore?this.bindingStore.getAcpSessionId(this.currentAibotSessionId):void 0,s=async a=>{await this.acpClient.connect({transport:this.agentProcess.transport,authMethod:this.acpAuthMethod,initialMode:this.acpInitialMode,initialModel:this.acpInitialModel,cwd:e||this.resolveCwd(),mcpServers:t,sessionId:a})};let n=!1,o;try{await s(i)}catch(a){if(a instanceof T){await this.handleAuthRequired(a);return}if(!i)throw this.handleConnectFailure(a),a;if(r.warn("acp-adapter",`Failed to load persisted session ${i}, fallback to session/new: ${g(a)}`),n=!0,o=i,this.config.command==="kiro-cli"&&this.currentAibotSessionId){r.info("acp-adapter",`Building kiro recovery summary: aibotSession=${this.currentAibotSessionId} acpSession=${i}`);const c=await this.buildKiroRecoveryContext(this.currentAibotSessionId,i,e||this.resolveCwd());c?(this.recoveryContextBySessionId.set(this.currentAibotSessionId,c),r.info("acp-adapter",`Recovery context prepared for session ${this.currentAibotSessionId} (chars=${c.length})`)):r.warn("acp-adapter",`Recovery context skipped: no summary generated for acpSession=${i}`)}await s(void 0)}this.sessionConnected=!0,r.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[a,c]of this.sessionBindings){this.bindingStore&&this.acpClient.sessionId&&this.bindingStore.setAcpSessionId(a,this.acpClient.sessionId);const d=n?"binding_recreated":"binding_ready",u=this.buildToolbarContext(d,c);n&&o&&(u.previous_session_id=o,u.recreated_session_id=this.acpClient.sessionId),this.callbacks.sendUpdateBindingCard(a,"ready",c,u)}}async buildKiroRecoveryContext(e,t,i){try{const s=p.join(v(),".kiro","sessions","cli",`${t}.json`);await f.access(s),r.info("acp-adapter",`Reading kiro source session file: ${s}`);const n=await this.generateSummaryByKiroCli(s,i);if(!n)return;const o=p.join(v(),".grix","data","session-summaries");await f.mkdir(o,{recursive:!0});const a=p.join(o,`${e}.md`),c=[`SOURCE_KIRO_SESSION_FILE: ${s}`,"",n.trim(),""].join(`
|
|
6
|
+
`);return await f.writeFile(a,c,"utf8"),r.info("acp-adapter",`Recovery summary saved: ${a} (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: ${a}`,"",n.trim()].join(`
|
|
7
7
|
`)}catch(s){r.warn("acp-adapter",`Failed to build kiro recovery context: ${g(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(`
|
|
8
|
-
`)],n=await this.runCommandCapture("kiro-cli",s,t,45e3);if(!n)return;const
|
|
9
|
-
`).filter(
|
|
10
|
-
`).trim()}runCommandCapture(e,t,i,s){return new Promise((n,
|
|
8
|
+
`)],n=await this.runCommandCapture("kiro-cli",s,t,45e3);if(!n)return;const o=U(n).trim(),a=o.indexOf("> "),c=a>=0?o.slice(a+2).trim():o;if(c)return r.info("acp-adapter",`Kiro summary generated from ${e} (raw_chars=${o.length}, body_chars=${c.length})`),c.split(`
|
|
9
|
+
`).filter(d=>!d.includes("Credits:")&&!d.includes("Time:")).join(`
|
|
10
|
+
`).trim()}runCommandCapture(e,t,i,s){return new Promise((n,o)=>{const a=A(e,t,{cwd:i,stdio:["ignore","pipe","pipe"]});let c="",d="";const u=setTimeout(()=>{a.kill("SIGTERM"),o(new Error(`${e} timed out after ${s}ms`))},s);a.stdout.on("data",l=>{c+=String(l)}),a.stderr.on("data",l=>{d+=String(l)}),a.on("error",l=>{clearTimeout(u),o(l)}),a.on("close",l=>{if(clearTimeout(u),l===0){n(c||d);return}o(new Error(`${e} exited with code ${l}: ${d||c}`))})})}handleConnectFailure(e){r.error("acp-adapter",`ACP session creation failed: ${g(e)}`),this.acpClient?.removeAllListeners(),this.acpClient=null,this.emit("exit",null)}async startInternalApiAndMcp(){try{this.internalApi||(this.internalApi=new k,this.internalApi.setInvokeHandler(async(t,i)=>this.callbacks.agentInvoke(t,i)),await this.internalApi.start(0),r.info("acp-adapter",`Internal API started at ${this.internalApi.url}`));const e=p.resolve(I,"../../mcp/acp-mcp-server.js");return[{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url],env:{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}}]}catch(e){r.error("acp-adapter",`Failed to start MCP tools: ${e}`);return}}cleanup(){this.activeRun,this.pendingApprovals.clear(),this.rejectDeferredEvents("adapter cleaned up"),this.cancelAllDeferredTimers(),this.sessionConnected=!1,this.acpClient&&(this.acpClient.clearSettleTimer(),this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(this.agentProcess.removeAllListeners(),this.agentProcess=null)}async handleAuthRequired(e){r.info("acp-adapter",`Auth required, methods: ${e.authMethods.map(n=>n.id).join(", ")}`);const t=e.authMethods.find(n=>/oauth|browser/i.test(n.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[n,o]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(n,"failed",o);const s=await this.captureAuthUrl();s&&this.callbacks.sendAuthNotification(i,`Please open this URL to authenticate:
|
|
11
11
|
${s}
|
|
12
12
|
|
|
13
|
-
Waiting for authentication to complete...`);try{await this.acpClient.authenticate(t.id),r.info("acp-adapter","Authentication successful"),this.callbacks.sendAuthNotification(i,"Authentication successful. Resuming...");const n=this.internalApi?[{name:"grix-connector-tools",command:process.execPath,args:[p.resolve(
|
|
13
|
+
Waiting for authentication to complete...`);try{await this.acpClient.authenticate(t.id),r.info("acp-adapter","Authentication successful"),this.callbacks.sendAuthNotification(i,"Authentication successful. Resuming...");const n=this.internalApi?[{name:"grix-connector-tools",command:process.execPath,args:[p.resolve(I,"../../mcp/acp-mcp-server.js"),"--api-url",this.internalApi.url],env:{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}}]:void 0;await this.acpClient.connect({transport:this.agentProcess.transport,initialMode:this.acpInitialMode,initialModel:this.acpInitialModel,cwd:this.resolveCwd(),mcpServers:n}),r.info("acp-adapter",`ACP session ready after auth: ${this.acpClient.sessionId}`),this.emit("acpSessionReady",this.acpClient.sessionId);for(const[o,a]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(o,"ready",a,this.buildToolbarContext("binding_ready",a))}catch(n){throw r.error("acp-adapter",`Auth retry failed: ${n}`),n}}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 a=n.toString().replace(/\x1b\[[0-9;]*m/g,"").match(t);a&&(i=!0,this.agentProcess.removeListener("stderr",s),e(a[0]))};this.agentProcess.on("stderr",s),setTimeout(()=>{i||(i=!0,this.agentProcess.removeListener("stderr",s),e(null))},3e4)})}handleAcpEvent(e){if(e.type===m.PermissionRequest){this.activeRun&&this.resetIdleTimer(this.activeRun),this.handlePermissionRequest(e);return}if(e.type===m.ContextWindowUpdate){e.contextWindow&&this.callbacks.onContextWindowUpdated?.(e.contextWindow),this.compacting&&this.finishCompaction("context-window-update");return}const t=this.activeRun;if(!t)return;t.responded||(t.responded=!0);let i=!1;switch(e.type){case m.Text:{if(e.content){i=!0;const s=t.quotedStream.consume(e.content);s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),s.deltaContent&&this.appendToStream(t,s.deltaContent)}break}case m.ToolUse:{i=!0,t.awaitingToolResult=!0,e.toolName&&(this.emitRawEventEnvelope(t,{type:"tool_use",payload:{tool_name:e.toolName,tool_input:e.toolInput??""}})||this.callbacks.sendToolUse(t.eventId,t.sessionId,e.toolName,e.toolInput??""));break}case m.ToolResult:{t.awaitingToolResult=!1,e.content&&(i=!0,this.emitRawEventEnvelope(t,{type:"tool_result",payload:{tool_name:e.toolName??"",content:e.content}})||this.callbacks.sendToolResult(t.eventId,t.sessionId,e.toolName??"",e.content));break}case m.Thinking:{e.content&&(i=!0,this.emitRawEventEnvelope(t,{type:"thinking",payload:{content:e.content}})||this.callbacks.sendThinking(t.eventId,t.sessionId,e.content));break}case m.Error:{this.emitRawEventEnvelope(t,{type:"error",payload:{message:String(e.error??"unknown error")}}),r.error("acp-adapter",`ACP error: ${e.error}`);break}case m.Result:{this.emitRawEventEnvelope(t,{type:"result",payload:{done:e.done??!0}});const s=t.quotedStream.flush();s.deltaContent&&this.appendToStream(t,s.deltaContent),s.quotedMessageId&&(t.quotedMessageId=s.quotedMessageId),this.flushStream(),this.finishRun("responded");break}}i&&(t.lastProgressAt=Date.now(),t.idleNoProgressCount=0),this.resetIdleTimer(t)}handlePermissionRequest(e){const t=e.permissionRequest;if(!t||!e.requestId||!this.acpClient)return;if(this.approvalMode==="yolo"||this.approvalMode==="autoEdit"){r.info("acp-adapter",`Auto-approving (${this.approvalMode}): ${t.toolName}`),this.acpClient.respondPermission(t.requestId,{behavior:"allow"}).catch(()=>{});return}const i=t.toolCallId;this.pendingApprovals.set(i,e.requestId);const s=this.activeRun;s?(s.idleTimer&&(clearTimeout(s.idleTimer),s.idleTimer=null),this.emitRawEventEnvelope(s,{type:"permission_request",payload:{request_id:t.requestId,tool_call_id:i,tool_name:t.toolName,tool_title:t.toolTitle,options:t.options}})||this.callbacks.sendPermissionCard({eventId:s.eventId,sessionId:s.sessionId,toolCallId:i,toolName:t.toolName,toolTitle:t.toolTitle,options:t.options})):(r.info("acp-adapter",`Permission request without active run, auto-approving: ${t.toolName}`),this.acpClient.respondPermission(e.requestId,{behavior:"allow"}),this.pendingApprovals.delete(i))}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){e.idleTimer&&clearTimeout(e.idleTimer);const t=e.awaitingToolResult?j:N;e.idleTimer=setTimeout(()=>{if(this.activeRun?.eventId!==e.eventId)return;const i=this.acpClient;i?.isAlive?i.ping(5e3).then(async s=>{if(this.activeRun?.eventId===e.eventId)if(s){const n=e.lastIdleCheckAt,o=e.lastProgressAt>n,a=o?!1:await L(i.sessionId,n),c=o||a;e.lastIdleCheckAt=Date.now(),c?(a&&r.info("acp-adapter",`Idle timer: no stream progress but kiro session active, continuing: ${e.eventId}`),e.idleNoProgressCount=0,this.resetIdleTimer(e)):(e.idleNoProgressCount++,e.idleNoProgressCount>=2?(r.error("acp-adapter",`Agent alive but no progress for ${e.idleNoProgressCount} idle cycles, declaring stuck: ${e.eventId}`),this.finishRun("failed",`agent alive but no progress for ${e.idleNoProgressCount} idle cycles`),this.emit("stuck")):(r.warn("acp-adapter",`Idle timer fired, ping ok, no progress (${e.idleNoProgressCount}/2): ${e.eventId}`),this.resetIdleTimer(e)))}else r.error("acp-adapter",`Agent idle for ${t/1e3}s and ping failed, declaring stuck: ${e.eventId}`),this.finishRun("failed",`agent idle for ${t/1e3}s`),this.emit("stuck")}).catch(()=>{this.activeRun?.eventId===e.eventId&&(r.error("acp-adapter",`Agent idle for ${t/1e3}s and ping error, declaring stuck: ${e.eventId}`),this.finishRun("failed",`agent idle for ${t/1e3}s`),this.emit("stuck"))}):(r.error("acp-adapter",`Agent idle for ${t/1e3}s (no client), declaring stuck: ${e.eventId}`),this.finishRun("failed",`agent idle for ${t/1e3}s`),this.emit("stuck"))},t)}appendToStream(e,t){e.buffer+=t,e.flushTimer||(e.flushTimer=setTimeout(()=>this.flushStream(),D))}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),s.closeAfter&&(e.currentSegmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.currentSegmentIndex}`,e.chunkSeq=0,r.info("acp-adapter",`stream segment rollover event=${e.eventId} segment=${e.currentSegmentIndex} reason=${s.reason??"threshold"}`)))}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)}finishRun(e,t){const i=this.activeRun;if(!i)return;this.activeRun=null,this.acpClient?.clearSettleTimer(),this.emit("eventDone",i.eventId),i.flushTimer&&(clearTimeout(i.flushTimer),i.flushTimer=null),i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=null);const s=i.quotedStream.flush();s.deltaContent&&(i.buffer+=s.deltaContent),s.quotedMessageId&&(i.quotedMessageId=s.quotedMessageId),i.buffer&&(this.emitSegmentedStream(i,i.buffer),i.buffer=""),t&&this.callbacks.sendRunError(i.eventId,i.sessionId,t);const n=++i.chunkSeq;this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(i.eventId,i.sessionId,n,i.currentClientMsgId).then(()=>{i.silent||this.callbacks.sendEventResult(i.eventId,e,t),this.persistEventResult(i,e,t)}).catch(o=>{r.error("acp-adapter",`finalStreamChunk ACK failed event=${i.eventId}: ${o}`),this.callbacks.sendStreamChunk(i.eventId,i.sessionId,"",n,!0,i.currentClientMsgId),i.silent||this.callbacks.sendEventResult(i.eventId,e,t),this.persistEventResult(i,e,t)}):(this.callbacks.sendStreamChunk(i.eventId,i.sessionId,"",n,!0,i.currentClientMsgId),i.silent||this.callbacks.sendEventResult(i.eventId,e,t),this.persistEventResult(i,e,t))}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 O extends C{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){r.warn("acp-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}export{oe as AcpAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{watch as
|
|
1
|
+
import{watch as s}from"node:fs";class r{store;onActivity;onStop;onStopFailure;onCompactResult;onCompactStart;onConfigChange;onPermissionRequest;debounceMs;pollIntervalMs;watcher=null;pollTimer=null;debounceTimer=null;lastObservedAt=0;currentActivity=null;constructor(t){this.store=t.hookSignalStore,this.onActivity=t.onActivity,this.onStop=t.onStop,this.onStopFailure=t.onStopFailure,this.onCompactResult=t.onCompactResult,this.onCompactStart=t.onCompactStart,this.onConfigChange=t.onConfigChange,this.onPermissionRequest=t.onPermissionRequest,this.debounceMs=t.debounceMs??200,this.pollIntervalMs=t.watchIntervalMs??500}start(){this.stop(),this.lastObservedAt=Date.now();try{this.watcher=s(this.store.filePath,()=>{this.onFileChange().catch(()=>{})}),this.watcher.on("error",()=>{})}catch{}this.pollTimer=setInterval(()=>{this.onFileChange().catch(()=>{})},this.pollIntervalMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}async onFileChange(){const e=(await this.store.readState()).recent_events.filter(i=>i.event_at>this.lastObservedAt).sort((i,o)=>i.event_at-o.event_at);if(e.length!==0){this.lastObservedAt=e[e.length-1].event_at;for(const i of e)this.processEvent(i)}}processEvent(t){switch(t.hook_event_name){case"Stop":this.clearActivity(),this.onStop?.();break;case"StopFailure":this.clearActivity(),this.onStopFailure?.();break;case"PreToolUse":case"PostToolUse":case"PostToolUseFailure":{const e={event_name:t.hook_event_name,tool_name:t.detail};t.tool_input&&(e.tool_input=t.tool_input),this.applyActivity(e);break}case"PreCompact":this.onCompactStart?.(t.detail);break;case"PostCompact":this.onCompactResult?.(t.detail,t.tool_input??"");break;case"ConfigChange":this.onConfigChange?.(t.detail);break;case"PermissionRequest":this.onPermissionRequest?.(t.detail,t.tool_input);break;default:break}}applyActivity(t){this.currentActivity=t,this.onActivity(t)}clearActivity(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.currentActivity=null,this.onActivity(null)}}export{r as ActivityStatusManager};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{spawn as H,spawnSync as fe,execSync as L}from"node:child_process";import{randomUUID as O}from"node:crypto";import{killProcessGroup as D}from"../../core/runtime/spawn.js";import{readdirSync as me,readFileSync as Q,rmSync as ve,statSync as B,existsSync as F,watchFile as ge,unwatchFile as ee}from"node:fs";import{mkdir as b,readFile as P,rm as te,stat as ie,writeFile as k}from"node:fs/promises";import{join as h,resolve as _e}from"node:path";import{homedir as R,tmpdir as ye}from"node:os";import G from"node:net";import{EventEmitter as se}from"node:events";import{fileURLToPath as we}from"node:url";let j=null;if(process.platform==="win32")try{j=await import("node-pty")}catch{j=null}import{resolveRuntimePaths as S}from"../../core/config/index.js";import{SESSION_MODE_IDS as M}from"./protocol-contract.js";import{log as o}from"../../core/log/index.js";import{ActivityStatusManager as Ee}from"./activity-status-manager.js";import{HookSignalStore as Se}from"../../core/hooks/hook-signal-store.js";import{QuestionStore as ne}from"../../core/persistence/question-store.js";import{PermissionStore as q}from"../../core/persistence/permission-store.js";import{InternalApiServer as Pe}from"../../core/mcp/internal-api-server.js";import{executeEventTool as Ce,isEventTool as ke}from"../../core/mcp/event-tool-executor.js";import{validateToolArgs as Ie}from"../../core/mcp/tool-schemas.js";import{ACCESS_CONTROL_ACTION_MAP as Ae,isGrixInternalToolName as $e,normalizeEventToolArgs as Te}from"../../core/mcp/tools.js";import{scanSkills as be}from"./skill-scanner.js";import{extractLastAssistantText as Re}from"./usage-parser.js";const x="grix";function xe(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const i=t,s=String(i.label??"").trim();if(s)return s;const n=String(i.value??"").trim();if(n)return n;const r=String(i.text??"").trim();return r||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function re(d){let e;try{e=JSON.parse(d)}catch{return null}const t=e.questions;if(!Array.isArray(t)||t.length===0)return null;const i=[];for(let s=0;s<t.length;s++){const n=t[s];if(!n||typeof n!="object")continue;const r=n,a=`Question ${s+1}`,c=String(r.header??r.question??a).trim()||a,u=String(r.prompt??r.question??"").trim();if(!u)continue;const l=xe(r.options),p=r.multiSelect===!0||r.multi_select===!0;i.push({header:c,prompt:u,...l?{options:l}:{},...p?{multi_select:!0}:{}})}return i.length>0?i:null}function De(d){if(!d||typeof d!="string")return null;try{const e=JSON.parse(d);return(typeof e.plan=="string"?e.plan.trim():"")||null}catch{return null}}const Me=[/Please run \/login/,/API Error:\s*401/,/authentication_error/,/OAuth token has expired/],Le=[/You're out of extra usage/i,/Stop and wait for limit to reset/i,/Add funds to continue with extra usage/i],ae=300*1e3,Fe=1800*1e3,z=60*1e3,J=600*1e3,je=12e4,qe=3e4,Ne=3e3,N=1e3,oe=45e3,Ue=18e3,V=8192,ce=50;let le=!1;const W=new Set;async function He(d=[]){const e=new Set(d.filter(t=>Number.isInteger(t)&&t>0));for(let t=0;t<20;t++){const i=await new Promise((s,n)=>{const r=G.createServer();r.once("error",n),r.listen(0,"127.0.0.1",()=>{const a=r.address(),c=typeof a=="object"&&a?a.port:0;r.close(u=>{if(u){n(u);return}s(c)})})});if(i>0&&!e.has(i)&&!W.has(i))return W.add(i),i}throw new Error("\u65E0\u6CD5\u5206\u914D MCP \u901A\u77E5\u7AEF\u53E3")}function Oe(d){d>0&&W.delete(d)}const de=["You are connected to a chat via the grix-claude MCP server.",'Messages arrive as <channel source="grix-claude" chat_id="..." event_id="..." message_id="..." user_id="...">text</channel>.',"IMPORTANT: You MUST use the reply tool to send any response to the user.","Your plain text output is NOT delivered to the chat \u2014 only the reply tool delivers messages.","Always call the reply tool with chat_id, event_id, and your response text.","If you intentionally do not want to send a visible reply, you must call the complete tool with event_id and a final status."].join(" ");function ue(d){return String(d??"").trim().toLowerCase()===M.approval?M.approval:M.fullAuto}class X extends se{type="claude";config;bridgeCallbacks;mcpServerProcess=null;internalApi=null;claudeProcess=null;claudePty=null;spawnPromise=null;lifecycleVersion=0;sessionId="";alive=!1;stopped=!1;activeEvent=null;activeEventIdleTimer=null;activeEventHardTimer=null;queuedEvents=[];queuedEventIds=new Set;stopHookBarrierSessionId=null;stopHookBarrierTimer=null;mcpServerReady=!1;mcpStartupFailureHandled=!1;mcpChannelBroken=!1;startupChannelListening=!1;startupChannelListeningAt=0;pendingMcpFailureTimer=null;sessionIdConflictDetected=!1;sessionIdConflictRetriedEventIds=new Set;cachedCliVersion=null;runtimeResolver=null;activityManager=null;lastPreToolInput="";deferredModelId=null;claudeChildPid=0;claudeCliSessionId="";claudeSessionCwd="";claudeMcpConfigPath="";sessionState=null;authFailureUntil=0;usageLimitUntil=0;completedEventIds=new Map;pendingQuestion=new Map;pendingPermissions=new Map;lastClearedEvent=null;constructor(e,t){super(),this.config=e,this.bridgeCallbacks=t;const s=(e.options??{}).sessionRuntimeResolver;typeof s=="function"&&(this.runtimeResolver=s)}async start(){this.lifecycleVersion+=1,this.stopped=!1,this.alive=!0,this.internalApi=new Pe,this.internalApi.setInvokeHandler(async(e,t,i)=>this.handleInternalInvoke(e,t,i)),this.internalApi.setStatusLineHandler(async e=>{this.handleStatusLineUpdate(e)}),await this.internalApi.start(0),this.internalApiPort=parseInt(new URL(this.internalApi.baseUrl).port,10),this.notifyPort=0,o.info("claude-adapter",`Adapter started (stdio MCP mode, internal API at ${this.internalApi.baseUrl})`)}async stop(){if(o.info("claude-adapter",`Stopping adapter (sessionId=${this.sessionId}, alive=${this.alive}, activeEvent=${this.activeEvent?.eventId??"none"})`),this.lifecycleVersion+=1,this.stopped=!0,this.alive=!1,this.activeEvent&&(this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"canceled","adapter stopped"),this.clearActiveEvent()),this.stopComposing(),this.rejectQueuedEvents("adapter stopped","canceled"),this.clearStopHookBarrier(),this.mcpChannelBroken=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.ptyAutoConfirmTimer&&(clearInterval(this.ptyAutoConfirmTimer),this.ptyAutoConfirmTimer=null),this.pendingPermissions.size>0){const s=S(),n=new q(s.permissionRequestsDir);for(const[r]of this.pendingPermissions)n.resolveRequest(r,"deny").catch(()=>{});this.pendingPermissions.clear()}if(this.activityManager&&(this.activityManager.stop(),this.activityManager=null),this.sessionId){const s=this.resolveHookSignalsPath();te(s).catch(()=>{})}this.stopMcpServer();const e=this.claudeChildPid;this.claudeChildPid=0;const t=this.claudeProcess,i=this.claudePty;if(this.claudeProcess=null,this.claudePty=null,this.spawnPromise=null,i)try{i.kill()}catch{}if(e>0)try{process.kill(e,"SIGTERM")}catch{}if(t?.pid&&(D(t,"SIGTERM"),!await Promise.race([new Promise(n=>{t.once("exit",()=>n(!0))}),new Promise(n=>{setTimeout(()=>n(!1),5e3)})]))){if(e>0)try{process.kill(e,"SIGKILL")}catch{}D(t,"SIGKILL")}if(e>0){const s=Date.now();for(;Date.now()-s<5e3;)try{process.kill(e,0),await new Promise(n=>setTimeout(n,100))}catch{break}try{process.kill(e,"SIGKILL")}catch{}}this.releaseNotifyPortReservation(),this.claudeCliSessionId&&U(this.claudeCliSessionId),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){return`claude-session-${Date.now()}`}async resumeSession(e,t){}async destroySession(e){}sendPrompt(e){const t=new Qe(e.adapterSessionId),i={event_id:e.adapterSessionId,session_id:e.adapterSessionId,content:e.text,context_messages_json:e.contextMessages?JSON.stringify(e.contextMessages):void 0};return this.deliverInboundEvent(i),this.once(`reply:${e.adapterSessionId}`,s=>{t.emitDone(s.status==="completed"?{status:"completed"}:{status:"failed",error:"failed"})}),t}async cancel(e){}setPermissionHandler(e){}async ping(e){return this.stopped?!1:!this.claudeProcess&&!this.claudePty?this.alive&&this.internalApi!==null:this.alive&&this.mcpServerReady&&(this.startupChannelListening||process.platform==="win32")}getStatus(){return{alive:this.alive,busy:this.activeEvent!==null,sessions:0,details:this.sessionState?{sessionState:this.sessionState}:void 0}}getActiveEventIds(){return this.activeEvent?[this.activeEvent.eventId]:[]}clearActiveEventForShutdown(){this.activeEvent&&this.clearActiveEvent()}getSessionState(){return this.sessionState}getMcpConfig(){return null}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"},{name:"clear",description:"\u6E05\u9664\u5BF9\u8BDD"},{name:"model",description:"\u5207\u6362\u6A21\u578B",args:"<model-id>"},{name:"cost",description:"\u663E\u793A\u8D39\u7528"},{name:"rewind",description:"\u56DE\u9000\u5BF9\u8BDD"},{name:"memory",description:"\u8BB0\u5FC6\u7BA1\u7406"},{name:"doctor",description:"\u8BCA\u65AD"},{name:"status",description:"\u72B6\u6001\u663E\u793A"},{name:"skills",description:"\u83B7\u53D6 skills \u6E05\u5355"}]}async execCommand(e,t,i){if(e==="skills")try{const n=be({mode:"claude",projectDir:this.claudeSessionCwd}),r=n.map(a=>{const c=a.trigger?` (${a.trigger})`:"",u=a.pluginName?` [plugin:${a.pluginName}]`:` [${a.source}]`;return`- ${a.name}${c}${u}: ${a.description}`});return{status:"ok",message:r.length>0?r.join(`
|
|
2
|
-
`):"No skills found",data:n}}catch(n){return{status:"failed",message:`Failed to scan skills: ${n instanceof Error?n.message:n}`}}if(!this.claudeProcess&&!this.claudePty)return{status:"failed",message:"Claude process is not running"};if(this.getStatus().busy)return{status:"failed",message:"Claude is busy, try again later"};const s=t?`/${e} ${t}`:`/${e}`;try{return this.claudePty?this.claudePty.write(`${s}\r`):this.claudeProcess?.stdin?.write(`${s}\r`),{status:"ok",message:`Sent: ${s}`}}catch(n){return{status:"failed",message:`Failed to send: ${n instanceof Error?n.message:n}`}}}handleStatusLineUpdate(e){try{const t=e.context_window,i=e.cost,s=e.model,n=e.rate_limits??e.rateLimits,r=t?.current_usage;if(this.sessionState={contextWindow:{usedPercentage:t?.used_percentage!=null?g(t.used_percentage):null,remainingPercentage:t?.remaining_percentage!=null?g(t.remaining_percentage):null,totalInputTokens:g(t?.total_input_tokens),totalOutputTokens:g(t?.total_output_tokens),contextWindowSize:g(t?.context_window_size)||2e5,currentUsage:r?{inputTokens:g(r.input_tokens),outputTokens:g(r.output_tokens),cacheCreationInputTokens:g(r.cache_creation_input_tokens),cacheReadInputTokens:g(r.cache_read_input_tokens)}:null},cost:{totalCostUsd:g(i?.total_cost_usd),totalDurationMs:g(i?.total_duration_ms),totalApiDurationMs:g(i?.total_api_duration_ms),totalLinesAdded:g(i?.total_lines_added),totalLinesRemoved:g(i?.total_lines_removed)},rateLimits:this.parseStatusRateLimits(n),model:{id:String(s?.id??""),displayName:String(s?.display_name??"")},fastMode:e.fast_mode===!0,effort:e.effort!=null?String(e.effort):void 0,thinkingEnabled:e.thinking_enabled===!0,exceeds200kTokens:e.exceeds_200k_tokens===!0,version:String(e.version??""),sampledAt:Date.now()},n){const a=this.sessionState.rateLimits?.fiveHour,c=this.sessionState.rateLimits?.sevenDay;o.info("claude-adapter",`[rate-limits] statusLine parsed: fiveHour=${a?`${a.usedPercentage}% resetsAt=${a.resetsAt}`:"n/a"} sevenDay=${c?`${c.usedPercentage}% resetsAt=${c.resetsAt}`:"n/a"}`)}else o.debug("claude-adapter","[rate-limits] statusLine: no rate_limits in payload");try{this.bridgeCallbacks.onStatusLineUpdated?.(this.sessionState)}catch(a){o.warn("claude-adapter",`onStatusLineUpdated callback error: ${a instanceof Error?a.message:a}`)}}catch(t){o.warn("claude-adapter",`Failed to parse statusLine payload: ${t instanceof Error?t.message:t}`)}}parseStatusRateLimits(e){if(!e)return;const t=n=>{if(!n||typeof n!="object")return;const r=n,a=g(r.used_percentage??r.usedPercent),c=g(r.resets_at??r.resetsAt);if(!(a<=0&&c<=0))return{usedPercentage:a,resetsAt:c}},i=t(e.five_hour??e.fiveHour),s=t(e.seven_day??e.sevenDay);if(!(!i&&!s))return{...i?{fiveHour:i}:{},...s?{sevenDay:s}:{}}}deliverInboundEvent(e){if(this.sessionId||(this.sessionId=e.session_id),this.pruneCompletedEvents(),this.completedEventIds.has(e.event_id)){o.info("claude-adapter",`Event ${e.event_id} rejected: duplicate`),this.bridgeCallbacks.sendEventResult(e.event_id,"responded","duplicate event");return}if(Date.now()<this.authFailureUntil){o.info("claude-adapter",`Event ${e.event_id} rejected: auth cooldown`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","Claude authentication failed \u2014 please re-login");return}if(Date.now()<this.usageLimitUntil){o.info("claude-adapter",`Event ${e.event_id} rejected: usage limit cooldown`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","Claude usage limit reached \u2014 waiting for reset");return}if(this.activeEvent){if(this.activeEvent.eventId===e.event_id){o.info("claude-adapter",`Event ${e.event_id} ignored: same as active event`);return}if(this.queuedEventIds.has(e.event_id))return;if(this.queuedEvents.length>=ce){o.warn("claude-adapter",`Event ${e.event_id} rejected: queue full (size=${this.queuedEvents.length})`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent queue full");return}this.queuedEvents.push(e),this.queuedEventIds.add(e.event_id),o.info("claude-adapter",`Queue event ${e.event_id} (active=${this.activeEvent.eventId}, size=${this.queuedEvents.length})`);return}if(this.stopHookBarrierSessionId===e.session_id){if(this.queuedEventIds.has(e.event_id))return;if(this.queuedEvents.length>=ce){o.warn("claude-adapter",`Event ${e.event_id} rejected: queue full during barrier (size=${this.queuedEvents.length})`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent queue full");return}this.queuedEvents.push(e),this.queuedEventIds.add(e.event_id),o.info("claude-adapter",`Queue event ${e.event_id} (barrier session=${e.session_id})`);return}this.activeEvent={eventId:e.event_id,sessionId:e.session_id,rawEvent:e},this.lastClearedEvent=null,this.markActiveEventActivity(e.event_id,e.session_id),this.resetActiveEventHardTimer(e.event_id),this.ensureClaudeAndPushEvent(e)}deliverStopEvent(e,t){if(this.activeEvent?.eventId!==e)return;const i=this.activeEvent.sessionId;o.info("claude-adapter",`Stop requested for active event=${e} \u2014 killing Claude process`),this.mcpServerReady&&this.pushNotification("notifications/event_stop",{event_id:e,session_id:i,stop_id:O()}),this.bridgeCallbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActiveEvent(),this.killClaudeProcess("stop")}async handleLocalAction(e){if(!this.mcpServerReady)return{handled:!1,kind:""};const t=String(e.action_type??"");return t==="claude_interaction_reply"?this.handleQuestionReply(e):t==="exec_approve"||t==="exec_reject"?this.handlePermissionApproval(e):(this.pushNotification("notifications/local_action",e),{handled:!0,kind:""})}async handleQuestionReply(e){const t=e.params??{},i=String(t.request_id??"");if(!i)return o.warn("claude-adapter","Question reply missing request_id"),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"request_id_required","request_id is required"),{handled:!0,kind:"question_reply_no_id"};const s=S(),n=new ne(s.questionRequestsDir),r=t.resolution??{},a=String(r.type??""),c=r;if(a==="action"&&String(r.value??"")==="cancel"){o.info("claude-adapter",`Question cancelled by user: request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,c);const f=this.pendingQuestion.get(i);return f&&this.activeEvent?.eventId===f.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"}}let u="";if(a==="text"?u=String(r.value??""):a==="map"&&(u=(Array.isArray(r.entries)?r.entries:[]).map(f=>f.value).join(", ")),!u){o.warn("claude-adapter",`Empty answer for question reply request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,c);const p=this.pendingQuestion.get(i);return p&&this.activeEvent?.eventId===p.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"cancel"}),{handled:!0,kind:"question_reply_empty"}}o.info("claude-adapter",`Resolving question in store: request_id=${i} answer=${u.slice(0,80)}`),await n.resolveRequest(i,"answer",u,c);const l=this.pendingQuestion.get(i);return l&&this.activeEvent?.eventId===l.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"answer"}),{handled:!0,kind:"question_reply"}}async handlePermissionApproval(e){const t=e.params??{},i=String(t.approval_id??t.approval_command_id??t.tool_call_id??""),s=String(e.action_type??"")==="exec_approve";if(!i)return this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_id_required","approval_id is required"),{handled:!0,kind:"permission_approval"};if(!this.pendingPermissions.get(i))return this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_not_found",`no pending permission for approval_id: ${i}`),{handled:!0,kind:"permission_approval"};const r=S(),a=new q(r.permissionRequestsDir),c=s?"allow":"deny";return await a.resolveRequest(i,c),this.pendingPermissions.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok"),o.info("claude-adapter",`Permission ${c}: approvalId=${i}`),{handled:!0,kind:"permission_approval"}}async ensureClaudeAndPushEvent(e,t=0){t===0&&!this.claudeProcess&&this.startComposing(e.session_id,"preparing");try{if(this.mcpChannelBroken){await this.runSingleTurnFallback(e,"mcp channel unavailable");return}if(await this.ensureClaudeProcessReady(),!this.mcpServerReady)throw new Error("MCP stdio server not available");if(await this.waitForNotifyPort(3e4),process.platform==="win32"?await this.waitForWindowsChannelReady(oe):await this.waitForChannelListening(oe),this.activeEvent?.eventId!==e.event_id||this.mcpChannelBroken)return;const s={},n=[["chat_id",e.session_id],["event_id",e.event_id],["event_type","user_chat"],["message_id",e.msg_id],["sender_id",e.sender_id],["user",e.sender_id],["user_id",e.sender_id],["msg_id",e.msg_id],["session_type",e.session_type!=null?String(e.session_type):void 0],["msg_type",e.msg_type!=null?String(e.msg_type):void 0],["quoted_message_id",e.quoted_message_id],["ts",e.created_at!=null?new Date(Number(e.created_at)).toISOString():void 0],["owner_id",e.owner_id],["agent_id",e.agent_id],["attachments_json",e.attachments_json],["context_messages_json",e.context_messages_json]];for(const[r,a]of n)a!=null&&a!==""&&(s[r]=a);this.pushNotification("notifications/claude/channel",{content:e.content??"",meta:s}),o.info("claude-adapter",`Event ${e.event_id} pushed to MCP stdio server`)}catch(s){if(this.stopped){this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"canceled","adapter stopped"),this.clearActiveEvent());return}if(s instanceof Error&&(s.message.includes("exited before")||s.message.includes("timeout")||s.message.includes("spawn failed"))&&t<3)return o.warn("claude-adapter",`Spawn failed (attempt ${t+1}/4), retrying: ${s}`),this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),U(this.claudeCliSessionId),K(this.claudeCliSessionId,[]),await new Promise(r=>setTimeout(r,(t+1)*2e3)),this.ensureClaudeAndPushEvent(e,t+1);if(o.error("claude-adapter",`Failed to deliver event ${e.event_id}: ${s}`),this.shouldFallbackToSingleTurn(s)){o.warn("claude-adapter",`Channel path failed, switching to single-turn fallback: ${s instanceof Error?s.message:String(s)}`);try{await this.runSingleTurnFallback(e,s instanceof Error?s.message:String(s));return}catch(r){o.error("claude-adapter",`Single-turn fallback failed for ${e.event_id}: ${r instanceof Error?r.message:String(r)}`)}}this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"failed",s instanceof Error?s.message:String(s)),this.clearActiveEvent())}}shouldFallbackToSingleTurn(e){const t=(e instanceof Error?e.message:String(e)).toLowerCase();return t?t.includes("mcp server startup failed")||t.includes("claude channel listener not ready")||t.includes("channels are not currently available")||t.includes("mcp stdio server not available")||t.includes("notify port not ready"):!1}buildSingleTurnPrompt(e){const t=e.context_messages_json?String(e.context_messages_json):"",i=["Reply to the latest user message directly and concisely."];return t&&(i.push("Conversation context (JSON):"),i.push(t)),i.push("Latest user message:"),i.push(e.content??""),i.join(`
|
|
3
|
-
`)}extractSingleTurnDelta(e){const t=e.trim();if(!t)return"";try{const i=JSON.parse(t),s=String(i.type??"");if(s==="content_block_delta"){const n=i.delta;if(n&&typeof n=="object"){const r=String(n.text??"");if(r)return r}}return s==="result"?String(i.result??""):typeof i.text=="string"&&i.text?i.text:""}catch{return t}}getCliVersion(){if(this.cachedCliVersion)return this.cachedCliVersion;const e=this.config.command||"claude";try{const i=L(`${e} --version`,{encoding:"utf-8",timeout:5e3}).trim().match(/^([\d.]+)/);this.cachedCliVersion=i?.[1]??"0.0.0"}catch{this.cachedCliVersion="0.0.0"}return this.cachedCliVersion}static versionGte(e,t){const i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<Math.max(i.length,s.length);n++){const r=i[n]??0,a=s[n]??0;if(r>a)return!0;if(r<a)return!1}return!0}buildClaudeRuntimeEnv(){const e={...process.env,...this.config.env};return delete e.CLAUDECODE,e.CLAUDE_PLUGIN_DATA=S().dataDir,e.GRIX_HOOK_SIGNALS_PATH=this.resolveHookSignalsPath(),this.internalApi&&(e.GRIX_CLAUDE_INTERNAL_API_URL=this.internalApi.baseUrl,e.GRIX_CLAUDE_INTERNAL_API_TOKEN=this.internalApi.token),e}async runSingleTurnFallback(e,t){const i=this.resolveSessionRuntime(),s=this.config.options??{},n=this.config.command||"claude",r=(this.config.args??[]).filter(
|
|
4
|
-
`);for(;A>=0;){const pe=w.slice(0,A);w=w.slice(A+1);const
|
|
5
|
-
`)}})
|
|
6
|
-
`}let a="";try{a=await
|
|
7
|
-
`,f=h(t,"hooks"),
|
|
8
|
-
`;"write"in t?t.write(i):t.write(i,()=>{}),o.info("claude-adapter",`Deferred model switch: /model ${e}`)}catch{}},3e3)}async waitForWindowsChannelReady(e){const t=Date.now();let i=!1;const s=setInterval(()=>{if(this.startupChannelListening){clearInterval(s);return}try{this.claudePty?(this.claudePty.write("\r"),i||(o.info("claude-adapter","Windows PTY: sending Enter to auto-confirm dev channels dialog"),i=!0)):this.claudeProcess?.stdin?.writable&&(this.claudeProcess.stdin.write("\r"),i||(o.info("claude-adapter","Windows shell: sending Enter to auto-confirm dev channels dialog"),i=!0))}catch{}},3e3);try{for(;Date.now()-t<e;){if(this.startupChannelListening){const a=this.startupChannelListeningAt||Date.now(),c=Date.now()-a;if(c>=
|
|
1
|
+
import{spawn as H,spawnSync as fe,execSync as L,execFile as me}from"node:child_process";import{promisify as ve}from"node:util";import{randomUUID as Q}from"node:crypto";import{killProcessGroup as M}from"../../core/runtime/spawn.js";import{readdirSync as ge,readFileSync as B,rmSync as _e,statSync as q,existsSync as F,watchFile as ye,unwatchFile as te}from"node:fs";import{mkdir as b,readFile as C,rm as ie,stat as se,writeFile as I}from"node:fs/promises";import{join as h,resolve as we}from"node:path";import{homedir as R,tmpdir as Ee}from"node:os";import G from"node:net";import{EventEmitter as ne}from"node:events";import{fileURLToPath as Se}from"node:url";let j=null;if(process.platform==="win32")try{j=await import("node-pty")}catch{j=null}import{resolveRuntimePaths as S}from"../../core/config/index.js";import{SESSION_MODE_IDS as x}from"./protocol-contract.js";import{log as o}from"../../core/log/index.js";import{ActivityStatusManager as Pe}from"./activity-status-manager.js";import{HookSignalStore as Ce}from"../../core/hooks/hook-signal-store.js";import{QuestionStore as re}from"../../core/persistence/question-store.js";import{PermissionStore as N}from"../../core/persistence/permission-store.js";import{InternalApiServer as ke}from"../../core/mcp/internal-api-server.js";import{executeEventTool as Ie,isEventTool as Ae}from"../../core/mcp/event-tool-executor.js";import{validateToolArgs as Te}from"../../core/mcp/tool-schemas.js";import{ACCESS_CONTROL_ACTION_MAP as $e,isGrixInternalToolName as be,normalizeEventToolArgs as Re}from"../../core/mcp/tools.js";import{scanSkills as De}from"./skill-scanner.js";import{extractLastAssistantText as Me,resolveSessionJsonlPath as xe}from"./usage-parser.js";import{readSettingsEnv as Le}from"./model-list.js";import{resolveCliPath as qe,getCliVersion as Fe}from"../../core/util/cli-probe.js";const D="grix";function je(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const i=t,s=String(i.label??"").trim();if(s)return s;const n=String(i.value??"").trim();if(n)return n;const r=String(i.text??"").trim();return r||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function oe(d){let e;try{e=JSON.parse(d)}catch{return null}const t=e.questions;if(!Array.isArray(t)||t.length===0)return null;const i=[];for(let s=0;s<t.length;s++){const n=t[s];if(!n||typeof n!="object")continue;const r=n,a=`Question ${s+1}`,c=String(r.header??r.question??a).trim()||a,u=String(r.prompt??r.question??"").trim();if(!u)continue;const l=je(r.options),p=r.multiSelect===!0||r.multi_select===!0;i.push({header:c,prompt:u,...l?{options:l}:{},...p?{multi_select:!0}:{}})}return i.length>0?i:null}function Ne(d){if(!d||typeof d!="string")return null;try{const e=JSON.parse(d);return(typeof e.plan=="string"?e.plan.trim():"")||null}catch{return null}}const Oe=[/Please run \/login/,/API Error:\s*401/,/authentication_error/,/OAuth token has expired/],Ue=[/You're out of extra usage/i,/Stop and wait for limit to reset/i,/Add funds to continue with extra usage/i],ae=300*1e3,He=1800*1e3,z=60*1e3,J=600*1e3;function Qe(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}const Be=12e4,Ge=3e4,ze=3e3,O=1e3,ce=45e3,Je=18e3,V=8192,W=50;let le=!1;const Y=new Set;async function Ve(d=[]){const e=new Set(d.filter(t=>Number.isInteger(t)&&t>0));for(let t=0;t<20;t++){const i=await new Promise((s,n)=>{const r=G.createServer();r.once("error",n),r.listen(0,"127.0.0.1",()=>{const a=r.address(),c=typeof a=="object"&&a?a.port:0;r.close(u=>{if(u){n(u);return}s(c)})})});if(i>0&&!e.has(i)&&!Y.has(i))return Y.add(i),i}throw new Error("\u65E0\u6CD5\u5206\u914D MCP \u901A\u77E5\u7AEF\u53E3")}function We(d){d>0&&Y.delete(d)}const de=["You are connected to a chat via the grix-claude MCP server.",'Messages arrive as <channel source="grix-claude" chat_id="..." event_id="..." message_id="..." user_id="...">text</channel>.',"IMPORTANT: You MUST use the reply tool to send any response to the user.","Your plain text output is NOT delivered to the chat \u2014 only the reply tool delivers messages.","Always call the reply tool with chat_id, event_id, and your response text.","If you intentionally do not want to send a visible reply, you must call the complete tool with event_id and a final status."].join(" ");function ue(d){return String(d??"").trim().toLowerCase()===x.approval?x.approval:x.fullAuto}class Z extends ne{type="claude";config;bridgeCallbacks;mcpServerProcess=null;internalApi=null;claudeProcess=null;claudePty=null;spawnPromise=null;lifecycleVersion=0;sessionId="";alive=!1;stopped=!1;activeEvent=null;activeEventIdleTimer=null;activeEventHardTimer=null;queuedEvents=[];queuedEventIds=new Set;stopHookBarrierSessionId=null;stopHookBarrierTimer=null;compacting=!1;compactingTimer=null;compactionDoneResolver=null;mcpServerReady=!1;mcpStartupFailureHandled=!1;mcpChannelBroken=!1;startupChannelListening=!1;startupChannelListeningAt=0;pendingMcpFailureTimer=null;sessionIdConflictDetected=!1;sessionIdConflictRetriedEventIds=new Set;cachedCliVersion=null;runtimeResolver=null;activityManager=null;lastPreToolInput="";deferredModelId=null;claudeChildPid=0;claudeCliSessionId="";claudeSessionCwd="";claudeMcpConfigPath="";sessionState=null;authFailureUntil=0;usageLimitUntil=0;completedEventIds=new Map;pendingQuestion=new Map;pendingPermissions=new Map;lastClearedEvent=null;constructor(e,t){super(),this.config=e,this.bridgeCallbacks=t;const s=(e.options??{}).sessionRuntimeResolver;typeof s=="function"&&(this.runtimeResolver=s)}async start(){this.lifecycleVersion+=1,this.stopped=!1,this.alive=!0,this.internalApi=new ke,this.internalApi.setInvokeHandler(async(e,t,i)=>this.handleInternalInvoke(e,t,i)),this.internalApi.setStatusLineHandler(async e=>{this.handleStatusLineUpdate(e)}),await this.internalApi.start(0),this.internalApiPort=parseInt(new URL(this.internalApi.baseUrl).port,10),this.notifyPort=0,o.info("claude-adapter",`Adapter started (stdio MCP mode, internal API at ${this.internalApi.baseUrl})`)}async stop(){if(o.info("claude-adapter",`Stopping adapter (sessionId=${this.sessionId}, alive=${this.alive}, activeEvent=${this.activeEvent?.eventId??"none"})`),this.lifecycleVersion+=1,this.stopped=!0,this.alive=!1,this.activeEvent&&(this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"canceled","adapter stopped"),this.clearActiveEvent()),this.stopComposing(),this.rejectQueuedEvents("adapter stopped","canceled"),this.clearStopHookBarrier(),this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver(),this.compactionDoneResolver=null),this.mcpChannelBroken=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.ptyAutoConfirmTimer&&(clearInterval(this.ptyAutoConfirmTimer),this.ptyAutoConfirmTimer=null),this.pendingPermissions.size>0){const s=S(),n=new N(s.permissionRequestsDir);for(const[r]of this.pendingPermissions)n.resolveRequest(r,"deny").catch(()=>{});this.pendingPermissions.clear()}if(this.activityManager&&(this.activityManager.stop(),this.activityManager=null),this.sessionId){const s=this.resolveHookSignalsPath();ie(s).catch(()=>{})}this.stopMcpServer();const e=this.claudeChildPid;this.claudeChildPid=0;const t=this.claudeProcess,i=this.claudePty;if(this.claudeProcess=null,this.claudePty=null,this.spawnPromise=null,i)try{i.kill()}catch{}if(e>0)try{process.kill(e,"SIGTERM")}catch{}if(t?.pid&&(M(t,"SIGTERM"),!await Promise.race([new Promise(n=>{t.once("exit",()=>n(!0))}),new Promise(n=>{setTimeout(()=>n(!1),5e3)})]))){if(e>0)try{process.kill(e,"SIGKILL")}catch{}M(t,"SIGKILL")}if(e>0){const s=Date.now();for(;Date.now()-s<5e3;)try{process.kill(e,0),await new Promise(n=>setTimeout(n,100))}catch{break}try{process.kill(e,"SIGKILL")}catch{}}this.releaseNotifyPortReservation(),this.claudeCliSessionId&&U(this.claudeCliSessionId),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){return`claude-session-${Date.now()}`}async resumeSession(e,t){}async destroySession(e){}sendPrompt(e){const t=new Ye(e.adapterSessionId),i={event_id:e.adapterSessionId,session_id:e.adapterSessionId,content:e.text,context_messages_json:e.contextMessages?JSON.stringify(e.contextMessages):void 0};return this.deliverInboundEvent(i),this.once(`reply:${e.adapterSessionId}`,s=>{t.emitDone(s.status==="completed"?{status:"completed"}:{status:"failed",error:"failed"})}),t}async cancel(e){}setPermissionHandler(e){}async ping(e){if(this.stopped)return!1;if(!this.claudeProcess&&!this.claudePty)return this.alive&&this.internalApi!==null;if(!(this.alive&&this.mcpServerReady&&(this.startupChannelListening||process.platform==="win32")))return!1;const t=this.claudeProcess?.pid??this.claudePty?.pid;if(t&&!Qe(t))return!1;const i=this.claudeProcess;if(i){const s=!!(i.stdin&&!i.stdin.destroyed),n=!!(i.stdout&&!i.stdout.destroyed);if(!s||!n)return!1}return!0}getStatus(){return{alive:this.alive,busy:this.activeEvent!==null||this.compacting,sessions:0,details:this.sessionState?{sessionState:this.sessionState}:void 0}}getActiveEventIds(){return this.activeEvent?[this.activeEvent.eventId]:[]}clearActiveEventForShutdown(){this.activeEvent&&this.clearActiveEvent()}getSessionState(){return this.sessionState}getMcpConfig(){return null}async probe(e){const t=this.config.command||"claude",i=await qe(t),s=i!==null;let n=null,r;if(s){const p=await Fe(t);n=p.version,p.error&&(r=p.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const c=(Le().ANTHROPIC_BASE_URL??process.env.ANTHROPIC_BASE_URL??"").trim()||null,u=(this.sessionState?.model?.id??(process.env.ANTHROPIC_MODEL??"").trim())||null;let l={attempted:!1,ok:!1,latency_ms:null};if(e?.conversation&&s){const p=Date.now();try{await ve(me)(t,["-p","ping","--output-format","json","--max-turns","1"],{timeout:e.timeoutMs??8e3,encoding:"utf-8"}),l={attempted:!0,ok:!0,latency_ms:Date.now()-p}}catch(f){const v=f,P=v.killed?"conversation_timeout":"conversation_failed";l={attempted:!0,ok:!1,latency_ms:Date.now()-p,error:{code:P,message:v.message??String(f)}}}}return{cli:{command:t,installed:s,path:i,version:n,...r?{error:r}:{}},conversation:l,config:{model:u,base_url:c,source:{model:this.sessionState?.model?.id?"runtime":process.env.ANTHROPIC_MODEL?"env":"unknown",base_url:c?"env":"unknown"}},process:{started:!!(this.claudeProcess||this.claudePty),alive:this.alive,busy:this.activeEvent!==null},...this.probeSessionRecord()}}probeSessionRecord(){const e=this.claudeCliSessionId;if(!e||!this.claudeSessionCwd)return{session:{recordPath:null,lastActivityMs:null,freshMs:null}};const t=xe(e,this.claudeSessionCwd);try{const i=q(t);return{session:{recordPath:t,lastActivityMs:i.mtimeMs,freshMs:Date.now()-i.mtimeMs}}}catch{return{session:{recordPath:t,lastActivityMs:null,freshMs:null}}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"},{name:"clear",description:"\u6E05\u9664\u5BF9\u8BDD"},{name:"model",description:"\u5207\u6362\u6A21\u578B",args:"<model-id>"},{name:"cost",description:"\u663E\u793A\u8D39\u7528"},{name:"rewind",description:"\u56DE\u9000\u5BF9\u8BDD"},{name:"memory",description:"\u8BB0\u5FC6\u7BA1\u7406"},{name:"doctor",description:"\u8BCA\u65AD"},{name:"status",description:"\u72B6\u6001\u663E\u793A"},{name:"skills",description:"\u83B7\u53D6 skills \u6E05\u5355"}]}async execCommand(e,t,i){if(e==="skills")try{const n=De({mode:"claude",projectDir:this.claudeSessionCwd}),r=n.map(a=>{const c=a.trigger?` (${a.trigger})`:"",u=a.pluginName?` [plugin:${a.pluginName}]`:` [${a.source}]`;return`- ${a.name}${c}${u}: ${a.description}`});return{status:"ok",message:r.length>0?r.join(`
|
|
2
|
+
`):"No skills found",data:n}}catch(n){return{status:"failed",message:`Failed to scan skills: ${n instanceof Error?n.message:n}`}}if(!this.claudeProcess&&!this.claudePty)return{status:"failed",message:"Claude process is not running"};if(this.getStatus().busy)return{status:"failed",message:"Claude is busy, try again later"};const s=t?`/${e} ${t}`:`/${e}`;try{if(this.claudePty?this.claudePty.write(`${s}\r`):this.claudeProcess?.stdin?.write(`${s}\r`),e==="compact"){const n=new Promise(r=>{this.compactionDoneResolver=r});return this.beginCompaction(),await n,{status:"ok",message:"Compacted"}}return{status:"ok",message:`Sent: ${s}`}}catch(n){return{status:"failed",message:`Failed to send: ${n instanceof Error?n.message:n}`}}}handleStatusLineUpdate(e){try{const t=e.context_window,i=e.cost,s=e.model,n=e.rate_limits??e.rateLimits,r=t?.current_usage;if(this.sessionState={contextWindow:{usedPercentage:t?.used_percentage!=null?_(t.used_percentage):null,remainingPercentage:t?.remaining_percentage!=null?_(t.remaining_percentage):null,totalInputTokens:_(t?.total_input_tokens),totalOutputTokens:_(t?.total_output_tokens),contextWindowSize:_(t?.context_window_size)||2e5,currentUsage:r?{inputTokens:_(r.input_tokens),outputTokens:_(r.output_tokens),cacheCreationInputTokens:_(r.cache_creation_input_tokens),cacheReadInputTokens:_(r.cache_read_input_tokens)}:null},cost:{totalCostUsd:_(i?.total_cost_usd),totalDurationMs:_(i?.total_duration_ms),totalApiDurationMs:_(i?.total_api_duration_ms),totalLinesAdded:_(i?.total_lines_added),totalLinesRemoved:_(i?.total_lines_removed)},rateLimits:this.parseStatusRateLimits(n),model:{id:String(s?.id??""),displayName:String(s?.display_name??"")},fastMode:e.fast_mode===!0,effort:e.effort!=null?String(e.effort):void 0,thinkingEnabled:e.thinking_enabled===!0,exceeds200kTokens:e.exceeds_200k_tokens===!0,version:String(e.version??""),sampledAt:Date.now()},n){const a=this.sessionState.rateLimits?.fiveHour,c=this.sessionState.rateLimits?.sevenDay;o.info("claude-adapter",`[rate-limits] statusLine parsed: fiveHour=${a?`${a.usedPercentage}% resetsAt=${a.resetsAt}`:"n/a"} sevenDay=${c?`${c.usedPercentage}% resetsAt=${c.resetsAt}`:"n/a"}`)}else o.debug("claude-adapter","[rate-limits] statusLine: no rate_limits in payload");try{this.bridgeCallbacks.onStatusLineUpdated?.(this.sessionState)}catch(a){o.warn("claude-adapter",`onStatusLineUpdated callback error: ${a instanceof Error?a.message:a}`)}}catch(t){o.warn("claude-adapter",`Failed to parse statusLine payload: ${t instanceof Error?t.message:t}`)}}parseStatusRateLimits(e){if(!e)return;const t=n=>{if(!n||typeof n!="object")return;const r=n,a=_(r.used_percentage??r.usedPercent),c=_(r.resets_at??r.resetsAt);if(!(a<=0&&c<=0))return{usedPercentage:a,resetsAt:c}},i=t(e.five_hour??e.fiveHour),s=t(e.seven_day??e.sevenDay);if(!(!i&&!s))return{...i?{fiveHour:i}:{},...s?{sevenDay:s}:{}}}deliverInboundEvent(e){if(this.sessionId||(this.sessionId=e.session_id),this.pruneCompletedEvents(),this.completedEventIds.has(e.event_id)){o.info("claude-adapter",`Event ${e.event_id} rejected: duplicate`),this.bridgeCallbacks.sendEventResult(e.event_id,"responded","duplicate event");return}if(Date.now()<this.authFailureUntil){o.info("claude-adapter",`Event ${e.event_id} rejected: auth cooldown`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","Claude authentication failed \u2014 please re-login");return}if(Date.now()<this.usageLimitUntil){o.info("claude-adapter",`Event ${e.event_id} rejected: usage limit cooldown`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","Claude usage limit reached \u2014 waiting for reset");return}if(this.compacting){if(this.queuedEventIds.has(e.event_id))return;if(this.queuedEvents.length>=W){o.warn("claude-adapter",`Event ${e.event_id} rejected: queue full during compaction (size=${this.queuedEvents.length})`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent queue full");return}this.queuedEvents.push(e),this.queuedEventIds.add(e.event_id),o.info("claude-adapter",`Queue event ${e.event_id} (compacting, size=${this.queuedEvents.length})`);return}if(this.activeEvent){if(this.activeEvent.eventId===e.event_id){o.info("claude-adapter",`Event ${e.event_id} ignored: same as active event`);return}if(this.queuedEventIds.has(e.event_id))return;if(this.queuedEvents.length>=W){o.warn("claude-adapter",`Event ${e.event_id} rejected: queue full (size=${this.queuedEvents.length})`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent queue full");return}this.queuedEvents.push(e),this.queuedEventIds.add(e.event_id),o.info("claude-adapter",`Queue event ${e.event_id} (active=${this.activeEvent.eventId}, size=${this.queuedEvents.length})`);return}if(this.stopHookBarrierSessionId===e.session_id){if(this.queuedEventIds.has(e.event_id))return;if(this.queuedEvents.length>=W){o.warn("claude-adapter",`Event ${e.event_id} rejected: queue full during barrier (size=${this.queuedEvents.length})`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent queue full");return}this.queuedEvents.push(e),this.queuedEventIds.add(e.event_id),o.info("claude-adapter",`Queue event ${e.event_id} (barrier session=${e.session_id})`);return}this.activeEvent={eventId:e.event_id,sessionId:e.session_id,rawEvent:e},this.lastClearedEvent=null,this.markActiveEventActivity(e.event_id,e.session_id),this.resetActiveEventHardTimer(e.event_id),this.ensureClaudeAndPushEvent(e)}deliverStopEvent(e,t){if(this.activeEvent?.eventId!==e)return;const i=this.activeEvent.sessionId;o.info("claude-adapter",`Stop requested for active event=${e} \u2014 killing Claude process`),this.mcpServerReady&&this.pushNotification("notifications/event_stop",{event_id:e,session_id:i,stop_id:Q()}),this.bridgeCallbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActiveEvent(),this.killClaudeProcess("stop")}async handleLocalAction(e){if(!this.mcpServerReady)return{handled:!1,kind:""};const t=String(e.action_type??"");return t==="claude_interaction_reply"?this.handleQuestionReply(e):t==="exec_approve"||t==="exec_reject"?this.handlePermissionApproval(e):(this.pushNotification("notifications/local_action",e),{handled:!0,kind:""})}async handleQuestionReply(e){const t=e.params??{},i=String(t.request_id??"");if(!i)return o.warn("claude-adapter","Question reply missing request_id"),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"request_id_required","request_id is required"),{handled:!0,kind:"question_reply_no_id"};const s=S(),n=new re(s.questionRequestsDir),r=t.resolution??{},a=String(r.type??""),c=r;if(a==="action"&&String(r.value??"")==="cancel"){o.info("claude-adapter",`Question cancelled by user: request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,c);const f=this.pendingQuestion.get(i);return f&&this.activeEvent?.eventId===f.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"}}let u="";if(a==="text"?u=String(r.value??""):a==="map"&&(u=(Array.isArray(r.entries)?r.entries:[]).map(f=>f.value).join(", ")),!u){o.warn("claude-adapter",`Empty answer for question reply request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,c);const p=this.pendingQuestion.get(i);return p&&this.activeEvent?.eventId===p.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"cancel"}),{handled:!0,kind:"question_reply_empty"}}o.info("claude-adapter",`Resolving question in store: request_id=${i} answer=${u.slice(0,80)}`),await n.resolveRequest(i,"answer",u,c);const l=this.pendingQuestion.get(i);return l&&this.activeEvent?.eventId===l.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok",{request_id:i,resolution:"answer"}),{handled:!0,kind:"question_reply"}}async handlePermissionApproval(e){const t=e.params??{},i=String(t.approval_id??t.approval_command_id??t.tool_call_id??""),s=String(e.action_type??"")==="exec_approve";if(!i)return this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_id_required","approval_id is required"),{handled:!0,kind:"permission_approval"};if(!this.pendingPermissions.get(i))return this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_not_found",`no pending permission for approval_id: ${i}`),{handled:!0,kind:"permission_approval"};const r=S(),a=new N(r.permissionRequestsDir),c=s?"allow":"deny";return await a.resolveRequest(i,c),this.pendingPermissions.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok"),o.info("claude-adapter",`Permission ${c}: approvalId=${i}`),{handled:!0,kind:"permission_approval"}}async ensureClaudeAndPushEvent(e,t=0){t===0&&!this.claudeProcess&&this.startComposing(e.session_id,"preparing");try{if(this.mcpChannelBroken){await this.runSingleTurnFallback(e,"mcp channel unavailable");return}if(await this.ensureClaudeProcessReady(),!this.mcpServerReady)throw new Error("MCP stdio server not available");if(await this.waitForNotifyPort(3e4),process.platform==="win32"?await this.waitForWindowsChannelReady(ce):await this.waitForChannelListening(ce),this.activeEvent?.eventId!==e.event_id||this.mcpChannelBroken)return;const s={},n=[["chat_id",e.session_id],["event_id",e.event_id],["event_type","user_chat"],["message_id",e.msg_id],["sender_id",e.sender_id],["user",e.sender_id],["user_id",e.sender_id],["msg_id",e.msg_id],["session_type",e.session_type!=null?String(e.session_type):void 0],["msg_type",e.msg_type!=null?String(e.msg_type):void 0],["quoted_message_id",e.quoted_message_id],["ts",e.created_at!=null?new Date(Number(e.created_at)).toISOString():void 0],["owner_id",e.owner_id],["agent_id",e.agent_id],["attachments_json",e.attachments_json],["context_messages_json",e.context_messages_json]];for(const[r,a]of n)a!=null&&a!==""&&(s[r]=a);this.pushNotification("notifications/claude/channel",{content:e.content??"",meta:s}),o.info("claude-adapter",`Event ${e.event_id} pushed to MCP stdio server`)}catch(s){if(this.stopped){this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"canceled","adapter stopped"),this.clearActiveEvent());return}if(s instanceof Error&&(s.message.includes("exited before")||s.message.includes("timeout")||s.message.includes("spawn failed"))&&t<3)return o.warn("claude-adapter",`Spawn failed (attempt ${t+1}/4), retrying: ${s}`),this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),U(this.claudeCliSessionId),X(this.claudeCliSessionId,[]),await new Promise(r=>setTimeout(r,(t+1)*2e3)),this.ensureClaudeAndPushEvent(e,t+1);if(o.error("claude-adapter",`Failed to deliver event ${e.event_id}: ${s}`),this.shouldFallbackToSingleTurn(s)){o.warn("claude-adapter",`Channel path failed, switching to single-turn fallback: ${s instanceof Error?s.message:String(s)}`);try{await this.runSingleTurnFallback(e,s instanceof Error?s.message:String(s));return}catch(r){o.error("claude-adapter",`Single-turn fallback failed for ${e.event_id}: ${r instanceof Error?r.message:String(r)}`)}}this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"failed",s instanceof Error?s.message:String(s)),this.clearActiveEvent())}}shouldFallbackToSingleTurn(e){const t=(e instanceof Error?e.message:String(e)).toLowerCase();return t?t.includes("mcp server startup failed")||t.includes("claude channel listener not ready")||t.includes("channels are not currently available")||t.includes("mcp stdio server not available")||t.includes("notify port not ready")||t.includes("file not found:"):!1}buildSingleTurnPrompt(e){const t=e.context_messages_json?String(e.context_messages_json):"",i=["Reply to the latest user message directly and concisely."];return t&&(i.push("Conversation context (JSON):"),i.push(t)),i.push("Latest user message:"),i.push(e.content??""),i.join(`
|
|
3
|
+
`)}extractSingleTurnDelta(e){const t=e.trim();if(!t)return"";try{const i=JSON.parse(t),s=String(i.type??"");if(s==="content_block_delta"){const n=i.delta;if(n&&typeof n=="object"){const r=String(n.text??"");if(r)return r}}return s==="result"?String(i.result??""):typeof i.text=="string"&&i.text?i.text:""}catch{return t}}getCliVersion(){if(this.cachedCliVersion)return this.cachedCliVersion;const e=this.config.command||"claude";try{const i=L(`${e} --version`,{encoding:"utf-8",timeout:5e3}).trim().match(/^([\d.]+)/);this.cachedCliVersion=i?.[1]??"0.0.0"}catch{this.cachedCliVersion="0.0.0"}return this.cachedCliVersion}static versionGte(e,t){const i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<Math.max(i.length,s.length);n++){const r=i[n]??0,a=s[n]??0;if(r>a)return!0;if(r<a)return!1}return!0}buildClaudeRuntimeEnv(){const e={...process.env,...this.config.env};return delete e.CLAUDECODE,e.CLAUDE_PLUGIN_DATA=S().dataDir,e.GRIX_HOOK_SIGNALS_PATH=this.resolveHookSignalsPath(),this.internalApi&&(e.GRIX_CLAUDE_INTERNAL_API_URL=this.internalApi.baseUrl,e.GRIX_CLAUDE_INTERNAL_API_TOKEN=this.internalApi.token),e}async runSingleTurnFallback(e,t){const i=this.resolveSessionRuntime(),s=this.config.options??{},n=this.config.command||"claude",r=(this.config.args??[]).filter(P=>{const m=String(P).trim().toLowerCase();return m!=="--dangerously-load-development-channels"&&m!=="--session-id"&&m!=="--resume"}),a=String(i.cwd??"").trim(),c=String(i.modelId??"").trim(),u=ue(i.modeId);await this.ensureWorkspaceTrust(a),await this.ensureGrowthBookFeatures(a),await this.injectStatusLineSettings(a),await this.ensureStdioMcpServer();const l=this.buildClaudeRuntimeEnv(),p=i.pluginDir??s.pluginDir??await this.ensureClaudePluginDir(),f=this.buildSingleTurnPrompt(e),v=[...r,"-p","--output-format","stream-json","--include-partial-messages","--no-session-persistence"];Z.versionGte(this.getCliVersion(),"2.1.150")&&v.push("--verbose"),v.push("--tools","","--plugin-dir",p,"--strict-mcp-config","--mcp-config",this.claudeMcpConfigPath,"--permission-mode",u===x.fullAuto?"bypassPermissions":"default"),c&&v.push("--model",c),v.push(f),o.warn("claude-adapter",`Running single-turn fallback for event ${e.event_id}: ${t}`),this.bridgeCallbacks.sendEventAck(e.event_id,e.session_id),this.startComposing(e.session_id,"fallback_single_turn"),await new Promise((P,m)=>{const T=H(n,v,{cwd:a||process.cwd(),env:l,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});let k="",$=0,y=!1;const g=`fallback_${e.event_id}_${Date.now()}`;let w="";T.stdout?.setEncoding("utf8"),T.stdout?.on("data",E=>{w+=E;let A=w.indexOf(`
|
|
4
|
+
`);for(;A>=0;){const pe=w.slice(0,A);w=w.slice(A+1);const ee=this.extractSingleTurnDelta(pe);ee&&($+=1,y=!0,this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,ee,$,!1,g,e.quoted_message_id)),A=w.indexOf(`
|
|
5
|
+
`)}}),T.stderr?.setEncoding("utf8"),T.stderr?.on("data",E=>{k.length>=V||(k+=E,k.length>V&&(k=k.slice(0,V)))}),T.on("error",E=>m(E)),T.on("close",E=>{if(w.trim()){const A=this.extractSingleTurnDelta(w);A&&($+=1,y=!0,this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,A,$,!1,g,e.quoted_message_id))}if(E!==0&&!y){const A=k.trim();m(new Error(A||`claude single-turn exited with code ${E}`));return}$+=1,this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,"",$,!0,g,e.quoted_message_id),P()})}),this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"responded"),this.clearActiveEvent())}async ensureClaudeProcessReady(){this.claudeProcess||this.claudePty||(this.spawnPromise||(this.spawnPromise=this.spawnClaude().finally(()=>{this.spawnPromise=null})),await this.spawnPromise)}async spawnClaude(){if(this.claudeProcess)return;const e=this.lifecycleVersion,t=()=>{if(this.stopped||e!==this.lifecycleVersion)throw new Error("adapter stopped")},i=this.config.options??{};this.sessionIdConflictDetected=!1;const s=this.resolveSessionRuntime(),n=this.config.command||"claude",r=this.config.args??[],a=this.buildClaudeRuntimeEnv(),c=ue(s.modeId),u=String(s.modelId??"").trim(),l=String(s.cwd??"").trim();this.claudeSessionCwd=l;const p=String(s.claudeSessionId??"").trim()||Q();this.claudeCliSessionId=p,!s.claudeSessionId&&s.onSessionIdAssigned&&s.onSessionIdAssigned(p);const f=nt(p,l||void 0);if(f||(X(p,[]),U(p)),this.runtimeResolver&&!l)throw new Error("Claude session binding missing cwd \u2014 run /grix open <working-directory> first");if(!l)throw new Error("Claude runtime cwd is required");await this.ensureWorkspaceTrust(l),await this.ensureGrowthBookFeatures(l),await this.injectStatusLineSettings(l);let v=!1,P="",m=null;try{t(),this.notifyPort=await Ve([this.internalApiPort]),v=!0,t(),o.info("claude-adapter",`Allocated MCP notify port ${this.notifyPort} (internal API ${this.internalApiPort})`),await this.ensureStdioMcpServer(),t();const k=i.pluginDir||await this.ensureClaudePluginDir(),$=f?["--resume",p]:["--session-id",p],y=[...r,"--name",`grix-${this.sessionId}`,...$,"--plugin-dir",k,"--strict-mcp-config","--mcp-config",this.claudeMcpConfigPath];if(u&&(/^claude/i.test(u)?y.push("--model",u):(o.warn("claude-adapter",`Skipping --model ${u}: non-Anthropic models are incompatible with development channels. Using default model so channels can load. Switch models after startup via /model if needed.`),this.deferredModelId=u)),c===x.fullAuto&&y.push("--dangerously-skip-permissions"),y.push("--dangerously-load-development-channels",`server:${D}`),process.platform==="win32"){const g=de.replace(/</g,"[").replace(/>/g,"]").replace(/"/g,"'"),w=tt(this.claudeCliSessionId);await st(w,g),y.push("--append-system-prompt-file",w)}else y.push("--append-system-prompt",de);if(process.platform==="win32")if(j){const g="cmd.exe",w=["/c",n,...y];o.info("claude-adapter",`Spawning Claude via PTY on win32: cwd=${l} mode=${c} ${f?"resume":"new"} ${n} ${y.join(" ")}`);const E=j.spawn(g,w,{name:"xterm-256color",cols:120,rows:30,cwd:l,env:a,useConpty:!0,conptyInheritCursor:!1});this.claudePty=E,this.claudeChildPid=E.pid,this.startPtyAutoConfirm(E),m=null}else o.info("claude-adapter",`Spawning Claude via shell on win32 (node-pty unavailable): cwd=${l} mode=${c} ${f?"resume":"new"} ${n} ${y.join(" ")}`),m=H(n,y,{cwd:l,env:a,stdio:["pipe","pipe","pipe"],detached:!0,shell:!0,windowsHide:!0});else{o.info("claude-adapter",`Spawning via expect PTY: cwd=${l} mode=${c} ${f?"resume":"new"} ${n} ${y.join(" ")}`);try{q("/usr/bin/expect")}catch{throw new Error("/usr/bin/expect not found. Install it with: apt install expect / dnf install expect / brew install expect")}const g=h(Ee(),`grix-claude-${Q()}`);await b(g,{recursive:!0});const{expectPath:w,pidPath:E}=await Ke(g,n,y);P=E,t(),m=H("/usr/bin/expect",[w],{cwd:l,env:a,stdio:["pipe","pipe","pipe"],detached:!0})}if(this.claudeProcess=m,this.clearPendingMcpFailureTimer(),this.mcpStartupFailureHandled=!1,this.mcpChannelBroken=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,m&&m.on("error",g=>{o.error("claude-adapter","Claude process spawn error: "+g),this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),this.activeEvent&&(this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"failed","Claude process spawn failed"),this.clearActiveEvent())}),t(),!this.claudePty)if(process.platform==="win32")this.claudeChildPid=m?.pid??0;else{const g=await Ze(m,P);if(t(),!Number.isFinite(g)||g<=0)throw new Error("failed to determine spawned Claude pid");this.claudeChildPid=g}if(!this.claudeChildPid||this.claudeChildPid<=0)throw new Error("failed to determine spawned Claude pid")}catch(k){if(m?.pid&&M(m,"SIGTERM"),this.claudePty){try{this.claudePty.kill()}catch{}this.claudePty=null}throw this.claudeProcess===m&&(this.claudeProcess=null),this.claudeChildPid=0,v&&this.releaseNotifyPortReservation(),this.stopMcpServer(),k}const T=this.claudeChildPid;o.info("claude-adapter","Claude child PID: "+T+(this.claudePty?" (via PTY)":"")),this.setupProcessOrPtyHandlers(),this.alive=!0}setupProcessOrPtyHandlers(){this.claudeProcess&&(this.claudeProcess.on("exit",(e,t)=>{if(o.info("claude-adapter",`Claude process exited (code=${e}, signal=${t})`),this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()){if(this.activeEvent&&!this.stopped){const i=this.activeEvent.replied?"responded":"failed",s=this.activeEvent.replied?void 0:"Claude process exited";o.error("claude-adapter",`Claude process exited with active event ${this.activeEvent.eventId}, replied=${!!this.activeEvent.replied}, sending ${i}`),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,s),this.clearActiveEvent()}this.stopped||this.emit("exit",e)}}),this.claudeProcess.stdout?.on("data",e=>{this.handleClaudeOutput(e.toString())}),this.claudeProcess.stderr?.on("data",e=>{const t=e.toString().trim();t&&o.info("claude-adapter",`[claude stderr] ${t}`),this.checkFailurePatterns(t)})),this.claudePty&&(this.claudePty.onExit(({exitCode:e,signal:t})=>{if(o.info("claude-adapter",`Claude PTY process exited (code=${e}, signal=${t})`),this.claudePty=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()){if(this.activeEvent&&!this.stopped){const i=this.activeEvent.replied?"responded":"failed",s=this.activeEvent.replied?void 0:"Claude process exited";o.error("claude-adapter",`Claude PTY exited with active event ${this.activeEvent.eventId}, replied=${!!this.activeEvent.replied}, sending ${i}`),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,s),this.clearActiveEvent()}this.stopped||this.emit("exit",e)}}),this.claudePty.onData(e=>{this.handleClaudeOutput(e),this.checkFailurePatterns(e)})),this.watchGrowthBookCache()}handleClaudeOutput(e){const t=e.trim();if(t){const a=t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202f\ufeff]/g,"").trim();a?a.length<=3||/^[✳✶✻✽✵❋✺✴❈❖✦✧✢◉◎⬥⬦◇◆▸▹►▻→←↑↓⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·…\d]*still\s+thinking/i.test(a)?o.debug("claude-adapter",`[claude output] ${a}`):o.info("claude-adapter",`[claude output] ${a.slice(0,500)}`):o.debug("claude-adapter",`[claude output] ${t.slice(0,200).replace(/[^\x20-\x7e]/g,c=>`\\x${c.charCodeAt(0).toString(16).padStart(2,"0")}`)}`)}this.activeEvent&&this.markActiveEventActivity(this.activeEvent.eventId,this.activeEvent.sessionId);const i=t.match(/Session ID (\S+) is already in use/i);if(i){const a=i[1];this.sessionIdConflictDetected=!0;const c=[this.claudeProcess?.pid,this.claudeChildPid,this.claudePty?.pid].filter(u=>!!u&&u>0);X(a,c)}const s=t.replace(/\[[0-9;?]*[ -/]*[@-~]/g," ").replace(/[^a-zA-Z]+/g," ").toLowerCase(),n=s.replace(/ /g,"");if(this.claudePty&&!this.startupChannelListening&&/trust.*folder|quick.*safety.*check/.test(n)&&(o.info("claude-adapter","Auto-accepting workspace trust dialog"),this.claudePty.write("1\r")),(/listeningforch\w*nelmessages/.test(n)||/nnelmessagesfrom/.test(n)||/inboundmessageswillbepushedintothissession/.test(n))&&(this.startupChannelListening||(this.startupChannelListeningAt=Date.now(),this.startupChannelListening=!0,this.sendDeferredModelSwitch()),this.clearPendingMcpFailureTimer()),!this.startupChannelListening&&/channels?arenotcurrentlyavailable/.test(n)&&o.warn("claude-adapter",'Claude reports "Channels are not currently available" \u2014 development channels require an Anthropic model (e.g. claude-*). If using a non-Anthropic model, the --model flag was skipped to allow channels to load.'),!this.mcpStartupFailureHandled&&s.includes("mcp server failed")){if(this.startupChannelListening){o.warn("claude-adapter","Claude reported MCP server failed for one channel, but channel listening is active; ignoring non-blocking failure");return}this.pendingMcpFailureTimer||(this.pendingMcpFailureTimer=setTimeout(()=>{this.pendingMcpFailureTimer=null,!(this.startupChannelListening||this.mcpStartupFailureHandled)&&this.markMcpStartupFailure()},ze))}}checkFailurePatterns(e){/Session ID (\S+) is already in use/i.test(e)&&(this.sessionIdConflictDetected=!0),Oe.some(t=>t.test(e))&&(o.error("claude-adapter",`Auth failure: ${e}`),this.authFailureUntil=Date.now()+ae),Ue.some(t=>t.test(e))&&(o.error("claude-adapter",`Usage limit: ${e}`),this.usageLimitUntil=Date.now()+ae)}async ensureClaudePluginDir(){const e=this.resolveProjectRoot(),t=h(S().dataDir,"claude-plugin"),i=h(t,".claude-plugin"),s=h(i,"plugin.json"),n=h(e,".claude-plugin","plugin.json");await b(i,{recursive:!0});let r="";try{r=await C(n,"utf8")}catch{r=`${JSON.stringify({name:"grix-connector",version:"0.1.0",description:"Claude Code channel plugin for grix-connector.",license:"MIT"},null,2)}
|
|
6
|
+
`}let a="";try{a=await C(s,"utf8")}catch{}a!==r&&(await I(s,r,"utf8"),o.info("claude-adapter",`Wrote Claude plugin manifest: ${s}`));const c=h(e,"dist","scripts"),u=m=>`"${String(m).replace(/"/g,'\\"')}"`,l=m=>`${u(process.execPath)} ${u(h(c,m))}`,p=`${JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],Elicitation:[{hooks:[{type:"command",command:l("elicitation-hook.js")}]}],ElicitationResult:[{matcher:"",hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],UserPromptSubmit:[{hooks:[{type:"command",command:l("user-prompt-submit-hook.js")}]}],PreToolUse:[{matcher:"ExitPlanMode",hooks:[{type:"command",command:l("approve-plan-hook.js")}]},{matcher:"",hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],PostToolUseFailure:[{matcher:"",hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],PermissionRequest:[{matcher:"",hooks:[{type:"command",command:l("permission-hook.js")}]}],Notification:[{matcher:"idle_prompt",hooks:[{type:"command",command:l("notification-hook.js")}]}],PermissionDenied:[{matcher:"",hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],Stop:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],StopFailure:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],PreCompact:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],PostCompact:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}],ConfigChange:[{hooks:[{type:"command",command:l("lifecycle-hook.js")}]}]}},null,2)}
|
|
7
|
+
`,f=h(t,"hooks"),v=h(f,"hooks.json");await b(f,{recursive:!0});let P="";try{P=await C(v,"utf8")}catch{}return P!==p&&(await I(v,p,"utf8"),o.info("claude-adapter",`Wrote Claude hooks config: ${v}`)),t}async ensureStdioMcpServer(){const e=this.resolveProjectRoot(),t=this.resolveStdioServerPath(e);if(this.ensureStdioServerArtifact(e,t),!F(t))throw new Error(`MCP stdio server entry point not found: ${t}`);const i=this.getInternalApiUrl(),s=this.notifyPort,n=[t,"--handle-url",i,"--notify-port",String(s)],r=et(this.claudeCliSessionId);await it(r,n),this.claudeMcpConfigPath=r,this.mcpServerReady=!0,this.startActivityTracking()}resolveProjectRoot(){const e=Se(import.meta.url);return we(e,"..","..","..","..")}resolveStdioServerPath(e=this.resolveProjectRoot()){return h(e,"dist","mcp","stdio","server.js")}ensureStdioServerArtifact(e,t){if(F(t)||le)return;le=!0;const i=h(e,"node_modules","typescript","bin","tsc"),s=h(e,"tsconfig.json");if(!F(i)||!F(s))return;o.warn("claude-adapter",`MCP stdio server artifact missing, attempting build: ${t}`);const n=fe(process.execPath,[i,"-p",s],{cwd:e,env:process.env,encoding:"utf8",timeout:6e4});if(n.status!==0){const r=`${n.stderr??""}${n.stdout??""}`.trim();throw new Error(`MCP stdio server build failed: ${r||`exit ${n.status??"unknown"}`}`)}}getInternalApiUrl(){return this.internalApi?this.internalApi.url:process.env.GRIX_CONNECTOR_INTERNAL_API?process.env.GRIX_CONNECTOR_INTERNAL_API:`http://127.0.0.1:${this.internalApiPort}`}internalApiPort=0;notifyPort=0;notifySocket=null;async waitForNotifyPort(e){if(this.notifyPort<=0)return;const t=Date.now();for(;Date.now()-t<e;)try{await new Promise((i,s)=>{const n=G.createConnection({host:"127.0.0.1",port:this.notifyPort},()=>{n.destroy(),i()});n.on("error",s),setTimeout(()=>{n.destroy(),s(new Error("probe timeout"))},2e3)});return}catch{await new Promise(i=>setTimeout(i,500))}throw new Error(`Notify port ${this.notifyPort} not ready within ${e}ms`)}async waitForChannelListening(e){const t=Date.now(),i=8e3;for(;Date.now()-t<e;){if(this.startupChannelListening){const s=this.startupChannelListeningAt||Date.now(),n=Date.now()-s;if(n>=O)return;await new Promise(r=>setTimeout(r,O-n));return}if(this.alive&&this.notifyPort>0&&Date.now()-t>i){o.info("claude-adapter",`Channel listener fallback: notify port connected, assuming ready after ${Date.now()-t}ms (resume mode may skip "Listening" output)`),this.startupChannelListeningAt=Date.now(),this.startupChannelListening=!0,this.clearPendingMcpFailureTimer(),this.sendDeferredModelSwitch();return}await new Promise(s=>setTimeout(s,200))}throw new Error(`Claude channel listener not ready within ${e}ms`)}ptyAutoConfirmTimer=null;startPtyAutoConfirm(e){this.ptyAutoConfirmTimer&&clearInterval(this.ptyAutoConfirmTimer);let t=!1;const i=()=>{if(this.startupChannelListening||this.stopped){this.ptyAutoConfirmTimer&&(clearInterval(this.ptyAutoConfirmTimer),this.ptyAutoConfirmTimer=null);return}try{e.write("\r"),t||(o.info("claude-adapter","PTY auto-confirm: sending Enter for dev channels dialog"),t=!0)}catch{}};setTimeout(i,1e3),this.ptyAutoConfirmTimer=setInterval(i,2e3),setTimeout(()=>{this.ptyAutoConfirmTimer&&(clearInterval(this.ptyAutoConfirmTimer),this.ptyAutoConfirmTimer=null)},3e4).unref()}sendDeferredModelSwitch(){if(!this.deferredModelId)return;const e=this.deferredModelId;this.deferredModelId=null,setTimeout(()=>{const t=this.claudePty??this.claudeProcess?.stdin;if(!(!t||this.stopped))try{const i=`/model ${e}
|
|
8
|
+
`;"write"in t?t.write(i):t.write(i,()=>{}),o.info("claude-adapter",`Deferred model switch: /model ${e}`)}catch{}},3e3)}async waitForWindowsChannelReady(e){const t=Date.now();let i=!1;const s=setInterval(()=>{if(this.startupChannelListening){clearInterval(s);return}try{this.claudePty?(this.claudePty.write("\r"),i||(o.info("claude-adapter","Windows PTY: sending Enter to auto-confirm dev channels dialog"),i=!0)):this.claudeProcess?.stdin?.writable&&(this.claudeProcess.stdin.write("\r"),i||(o.info("claude-adapter","Windows shell: sending Enter to auto-confirm dev channels dialog"),i=!0))}catch{}},3e3);try{for(;Date.now()-t<e;){if(this.startupChannelListening){const a=this.startupChannelListeningAt||Date.now(),c=Date.now()-a;if(c>=O)return;await new Promise(u=>setTimeout(u,O-c));return}const n=Date.now()-t,r=this.claudePty?Je:12e3;if(this.alive&&this.mcpServerReady&&n>r){o.info("claude-adapter",`Windows ${this.claudePty?"PTY":"shell"} fallback: assuming channel ready after ${n}ms (no stdout detection, MCP server connected)`),this.startupChannelListeningAt=Date.now(),this.startupChannelListening=!0,this.clearPendingMcpFailureTimer(),this.sendDeferredModelSwitch();return}await new Promise(a=>setTimeout(a,500))}}finally{clearInterval(s)}throw new Error(`Windows channel ready check timed out within ${e}ms`)}pushNotification(e,t){if(!this.mcpServerReady||this.notifyPort<=0)return;const i=JSON.stringify({jsonrpc:"2.0",method:e,params:t});!this.notifySocket||this.notifySocket.destroyed?(this.notifySocket=G.createConnection({host:"127.0.0.1",port:this.notifyPort},()=>{this.notifySocket.write(i+`
|
|
9
9
|
`)}),this.notifySocket.on("error",s=>{o.error("claude-adapter",`Notify socket error: ${s.message}`),this.notifySocket=null}),this.notifySocket.on("close",()=>{this.notifySocket=null})):this.notifySocket.write(i+`
|
|
10
|
-
`)}stopMcpServer(){if(this.mcpServerReady=!1,this.notifySocket){try{this.notifySocket.destroy()}catch{}this.notifySocket=null}if(this.mcpServerProcess){try{this.mcpServerProcess.kill("SIGTERM")}catch{}this.mcpServerProcess=null}}releaseNotifyPortReservation(){
|
|
11
|
-
`;await k(n,c,"utf8"),o.info("claude-adapter",`Injected statusLine settings: ${n}`)}catch(t){o.warn("claude-adapter",`Failed to inject statusLine settings: ${t instanceof Error?t.message:t}`)}}async ensureUserMcpServer(e,t,i){const s=this.resolveServerEntryPath(t),n=process.execPath,r=[s],a=h(R(),".claude.json");let c=null;try{const f=await P(a,"utf8");c=JSON.parse(f)?.mcpServers?.[x]??null}catch{}if(c&&String(c.type||"stdio").trim()==="stdio"&&String(c.command??"").trim()===n&&Array.isArray(c.args)&&c.args.length===r.length&&c.args.every((f,_)=>f===r[_]))return;o.info("claude-adapter",`Registering user-scoped MCP server: ${x} -> ${n} ${r.join(" ")}`);try{L(`${e} mcp remove -s user ${x}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe"})}catch{}const u=["mcp","add","--scope","user",x,"--",n,...r],l=process.platform==="win32"?'"':"'",p=L(`${e} ${u.map(f=>`${l}${f}${l}`).join(" ")}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe"});o.info("claude-adapter",`MCP server registered: ${p.trim()||"ok"}`)}resolveServerEntryPath(e){const t=h(e,"server","main.js");try{if(Q(t))return t}catch{}const i=h(e,"dist","index.js");try{if(Q(i))return i}catch{}throw new Error(`Cannot find grix-claude server entry in pluginDir: ${e}`)}clearActiveEvent(){const e=this.activeEvent;this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),e&&(this.sessionIdConflictRetriedEventIds.delete(e.eventId),this.completedEventIds.set(e.eventId,Date.now()),this.lastClearedEvent={eventId:e.eventId,sessionId:e.sessionId,ts:Date.now()},this.emit(`reply:${e.sessionId}`,{status:"completed"}),this.emit("eventDone",e.eventId)),this.activeEvent=null,this.stopComposing(),this.tryDeliverQueuedEvent()}startComposing(e,t){}stopComposing(){}clearComposingTimer(){}resolveHookSignalsPath(){const e=S();return h(e.dataDir,`hook-signals-${this.sessionId}.json`)}startActivityTracking(){this.activityManager&&this.activityManager.stop();const e=this.resolveHookSignalsPath(),t=S().hookSignalsLogPath,i=new Se(e,t);o.info("claude-adapter",`Activity tracking started: watching ${e}`),this.activityManager=new Ee({hookSignalStore:i,onActivity:s=>this.onHookActivity(s),onStop:()=>this.onClaudeTurnEnd("Stop"),onStopFailure:()=>this.onClaudeTurnEnd("StopFailure"),onPermissionRequest:(s,n)=>this.handlePermissionHookEvent(s,n)}),this.activityManager.start()}onClaudeTurnEnd(e){if(o.info("claude-adapter",`Hook activity: ${e}`),!!this.activeEvent){if(this.activeEvent.toolCallInFlight){o.info("claude-adapter",`Stop hook deferred: toolCallInFlight for ${this.activeEvent.eventId}`),this.activeEvent.pendingStopHook=e;return}this.finalizeActiveEvent(e)}}attemptRescueFromJsonl(e,t){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return o.info("claude-adapter",`Rescue skipped: no claudeCliSessionId or claudeSessionCwd for ${e}`),!1;const i=Re(this.claudeCliSessionId,this.claudeSessionCwd);if(!i)return o.info("claude-adapter",`Rescue failed: no assistant text found in JSONL for ${e}`),!1;const s=`rescue_${e}_${Date.now()}`;return this.bridgeCallbacks.sendStreamChunk(e,t,i,1,!0,s),o.info("claude-adapter",`Rescue succeeded for event ${e}: sent ${i.length} chars from JSONL`),!0}finalizeActiveEvent(e){if(!this.activeEvent)return;const t=this.activeEvent.eventId,i=this.activeEvent.sessionId,s=!this.activeEvent.replied&&this.attemptRescueFromJsonl(t,i);this.activeEvent.replied||s?(o.info("claude-adapter",`Stop hook received, finalizing event ${t} as responded (replied=${this.activeEvent.replied}, rescued=${s})`),this.bridgeCallbacks.sendEventResult(t,"responded")):(o.warn("claude-adapter",`Active event not confirmed when ${e}: ${t}, sending failed result`),this.bridgeCallbacks.sendEventResult(t,"failed",`agent completed without confirming reply (${e})`,"reply_unconfirmed")),this.clearActiveEvent(),this.armStopHookBarrier(i)}onHookActivity(e){const t=this.activeEvent?.sessionId;if(o.info("claude-adapter",`Hook activity: tool=${e?.tool_name??"(clear)"} session=${t??"(none)"}`),e&&this.activeEvent&&this.markActiveEventActivity(this.activeEvent.eventId,this.activeEvent.sessionId),!!t)if(e){this.startComposing(t,e);const i=this.activeEvent;if(i){const s=e.event_name,n=e.tool_name,r=e.tool_input??"",a=n?$e(n):!1;if(n==="ExitPlanMode"&&s==="PreToolUse")o.info("claude-adapter","ExitPlanMode detected; waiting for user decision via permission card");else if(n==="AskUserQuestion"&&s==="PreToolUse")this.handleAskUserQuestion(i,r);else if(s==="PreToolUse"&&n)r&&(this.lastPreToolInput=r),a||this.bridgeCallbacks.sendToolUse(i.eventId,i.sessionId,n,r);else if((s==="PostToolUse"||s==="PostToolUseFailure")&&n){if(n==="AskUserQuestion")return;const c=r||this.lastPreToolInput;if(this.lastPreToolInput="",!a){const u=s==="PostToolUseFailure"?`(failed) ${c}`:c;this.bridgeCallbacks.sendToolResult(i.eventId,i.sessionId,n,u)}}}}else this.startComposing(t)}handlePermissionHookEvent(e,t){if(!this.activeEvent){o.warn("claude-adapter","PermissionRequest without active event, ignoring");return}if(e==="AskUserQuestion"){o.info("claude-adapter","Skip permission card for AskUserQuestion; handled by agent_question card flow");return}const i=this.activeEvent,s=S();new q(s.permissionRequestsDir).listPending().then(r=>{const a=r.length>0?r[r.length-1]:null;if(!a){o.warn("claude-adapter","No pending permission request found in store");return}const c=a.request_id;this.pendingPermissions.set(c,{eventId:i.eventId,sessionId:i.sessionId});const u=typeof t=="string"?t:"";if(e==="ExitPlanMode"){const f=De(u);f&&this.bridgeCallbacks.sendReply(i.eventId,i.sessionId,f)}const l=e==="ExitPlanMode"?"":u.slice(0,100),p=l?`${e}: ${l}`:e;this.bridgeCallbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,approvalId:c,toolName:e,toolTitle:p}),o.info("claude-adapter",`Sent permission card: approvalId=${c} tool=${e}`)}).catch(r=>{o.warn("claude-adapter",`Failed to send permission card: ${r}`)})}handleAskUserQuestion(e,t){const i=re(t);if(!i){o.warn("claude-adapter","Failed to parse AskUserQuestion input, skipping agent_question card");return}const s=S(),n=new ne(s.questionRequestsDir);n.listPending().then(async r=>{const a=[...r].reverse().filter(l=>String(l.session_id??"").trim()===this.claudeCliSessionId),c=a.find(l=>String(l.event_id??"").trim()===e.eventId)??a.find(l=>String(l.event_id??"").trim()==="")??a[0]??null,u=c?.request_id??`fallback-${Date.now()}`;c&&String(c.event_id??"").trim()===""&&await n.updateRequest(c.request_id,{event_id:e.eventId}),this.pendingQuestion.set(u,{eventId:e.eventId,sessionId:e.sessionId}),e.awaitingUserQuestion=!0,this.bridgeCallbacks.sendAgentQuestionCard(e.eventId,e.sessionId,{request_id:u,mode:"form",questions:i}),o.info("claude-adapter",`Sent agent_question card: request_id=${u} questions=${i.length}`)}).catch(()=>{o.warn("claude-adapter","Failed to list pending questions from store")})}parseAskUserQuestions(e){return re(e)}parseAskUserQuestionInput(e){let t;try{t=JSON.parse(e)}catch{return null}const i=[],s=t.questions;if(!Array.isArray(s)||s.length===0)return null;for(let n=0;n<s.length;n++){const r=s[n];if(!r||typeof r!="object")continue;const a=String(r.header??r.question??`Question ${n+1}`),c=String(r.prompt??""),u=Array.isArray(r.options)?r.options:void 0,l=r.multiSelect===!0;i.push({header:a,prompt:c,...u&&u.length>0?{options:u}:{},...l?{multi_select:!0}:{}})}return i.length>0?{questions:i}:null}pruneCompletedEvents(){const e=Date.now()-Fe;for(const[t,i]of this.completedEventIds.entries())i<e&&this.completedEventIds.delete(t)}markActiveEventActivity(e,t){const i=this.activeEvent;i&&(e&&i.eventId!==e||t&&i.sessionId!==t||(this.resetActiveEventIdleTimer(i.eventId),this.resetActiveEventHardTimer(i.eventId)))}clearActiveEventIdleTimer(){this.activeEventIdleTimer&&(clearTimeout(this.activeEventIdleTimer),this.activeEventIdleTimer=null)}clearActiveEventHardTimer(){this.activeEventHardTimer&&(clearTimeout(this.activeEventHardTimer),this.activeEventHardTimer=null)}resetActiveEventIdleTimer(e){this.clearActiveEventIdleTimer(),this.activeEventIdleTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e)return;if(this.activeEvent?.toolCallInFlight){o.info("claude-adapter",`Idle timeout skipped: toolCallInFlight for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}if(this.activeEvent?.awaitingUserQuestion){o.info("claude-adapter",`Idle timeout skipped: awaitingUserQuestion for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}if(this.pendingPermissions.size>0){o.info("claude-adapter",`Idle timeout skipped: pendingPermissions=${this.pendingPermissions.size} for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}const t=this.activeEvent?.replied?"responded":"failed",i=this.activeEvent?.replied?void 0:`agent idle for ${z/1e3}s`,s=this.activeEvent?.replied?void 0:"agent_idle_timeout";o.error("claude-adapter",`Active event idle timeout (${z/1e3}s): ${e}, replied=${!!this.activeEvent?.replied}, sending ${t}`),this.completedEventIds.set(e,Date.now()),this.bridgeCallbacks.sendEventResult(e,t,i,s),this.clearActiveEvent()},z)}resetActiveEventHardTimer(e){this.clearActiveEventHardTimer(),this.activeEventHardTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e)return;const t=this.activeEvent?.replied?"responded":"failed",i=this.activeEvent?.replied?void 0:`agent exceeded max duration ${J/1e3}s`,s=this.activeEvent?.replied?void 0:"agent_hard_timeout";o.error("claude-adapter",`Active event hard timeout (${J/1e3}s): ${e}, replied=${!!this.activeEvent?.replied}, sending ${t}`),this.completedEventIds.set(e,Date.now()),this.bridgeCallbacks.sendEventResult(e,t,i,s),this.clearActiveEvent()},J)}tryDeliverQueuedEvent(){if(this.activeEvent||this.queuedEvents.length===0)return;const e=this.queuedEvents.shift();this.queuedEventIds.delete(e.event_id),this.deliverInboundEvent(e)}rejectQueuedEvents(e,t="failed"){if(this.queuedEvents.length===0)return;const i=this.queuedEvents.splice(0);this.queuedEventIds.clear();for(const s of i)this.bridgeCallbacks.sendEventResult(s.event_id,t,e)}armStopHookBarrier(e){this.stopHookBarrierSessionId=e,this.stopHookBarrierTimer=setTimeout(()=>{this.stopHookBarrierSessionId===e&&(o.warn("claude-adapter",`Stop hook barrier timeout for session=${e}`),this.clearStopHookBarrier(),this.tryDeliverQueuedEvent())},qe)}clearStopHookBarrier(){this.stopHookBarrierSessionId=null,this.stopHookBarrierTimer&&(clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierTimer=null)}clearPendingMcpFailureTimer(){this.pendingMcpFailureTimer&&(clearTimeout(this.pendingMcpFailureTimer),this.pendingMcpFailureTimer=null)}markMcpStartupFailure(){if(!this.mcpStartupFailureHandled&&(this.mcpStartupFailureHandled=!0,this.mcpChannelBroken=!0,o.error("claude-adapter","Claude reported blocking MCP server startup failure"),this.activeEvent)){const e=this.activeEvent.eventId;this.completedEventIds.set(e,Date.now()),this.clearActiveEvent()}}}class Qe extends se{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("claude-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function g(d){if(d==null)return 0;const e=Number(d);return Number.isFinite(e)?e:0}function Y(d){return String(d).replace(/\\/g,"\\\\").replace(/\{/g,"\\{").replace(/\}/g,"\\}")}async function Be(d,e,t){const i=h(d,"claude.expect"),s=h(d,"claude.pid"),n=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${Y(e)}}${t.map(r=>` {${Y(r)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${Y(s)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","after 500",'send -- "\\r"',"expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(I am using this for local development|Please use --channels|dangerously-load-development-channels)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter|Continue.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {(?i)Listening.*channel messages.*server:grix} {"," set startup_prompt_armed 0"," }"," eof {}","}","interact",""];return await k(s,"","utf8"),await k(i,n.join(`
|
|
12
|
-
`),"utf8"),{expectPath:i,pidPath:s}}async function
|
|
13
|
-
`;let s="";try{s=await
|
|
14
|
-
`;let i="";try{i=await
|
|
15
|
-
`)){const n=parseInt(s.trim(),10);if(n>0&&n!==process.pid&&!e.includes(n)){o.info("claude-adapter",`Killing stale Claude process PID=${n} holding session ${d}`);try{process.kill(n,"SIGTERM"),t=!0}catch{}}}}catch{}t||U(d)}function U(d){const e=h(R(),".claude"),t=[h(e,"session-env",d)];try{const i=h(e,"sessions");for(const s of
|
|
10
|
+
`)}stopMcpServer(){if(this.mcpServerReady=!1,this.notifySocket){try{this.notifySocket.destroy()}catch{}this.notifySocket=null}if(this.mcpServerProcess){try{this.mcpServerProcess.kill("SIGTERM")}catch{}this.mcpServerProcess=null}}releaseNotifyPortReservation(){We(this.notifyPort),this.notifyPort=0}killClaudeProcess(e){const t=this.claudeProcess,i=this.claudePty,s=this.claudeChildPid;if(this.claudeProcess=null,this.claudePty=null,this.claudeChildPid=0,this.spawnPromise=null,this.alive=!1,this.stopMcpServer(),this.releaseNotifyPortReservation(),this.mcpChannelBroken=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.sessionIdConflictDetected=!1,this.pendingPermissions.size>0){const n=S(),r=new N(n.permissionRequestsDir);for(const[a]of this.pendingPermissions)r.resolveRequest(a,"deny").catch(()=>{});this.pendingPermissions.clear()}if(i)try{i.kill()}catch{}if(t?.pid&&M(t,"SIGTERM"),s>0)try{process.kill(s,"SIGTERM")}catch{}if(t?.pid||i||s>0){const n=s,r=t,a=i;setTimeout(()=>{if(a)try{a.kill()}catch{}if(r?.pid&&M(r,"SIGKILL"),n>0)try{process.kill(n,"SIGKILL")}catch{}},5e3).unref()}o.info("claude-adapter",`Claude process killed (reason=${e}, pid=${s}, expectPid=${t?.pid})`)}tryRecoverSessionIdConflict(){if(!this.sessionIdConflictDetected||this.stopped||!this.activeEvent||this.activeEvent.replied)return!1;const e=this.activeEvent.eventId;if(this.sessionIdConflictRetriedEventIds.has(e))return this.sessionIdConflictDetected=!1,!1;this.sessionIdConflictRetriedEventIds.add(e),this.sessionIdConflictDetected=!1;const t=this.activeEvent.rawEvent;return o.warn("claude-adapter",`Detected Claude session-id conflict, auto-retrying event once: ${e}`),this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),this.activeEvent=null,this.stopComposing(),this.deliverInboundEvent(t),!0}async handleInternalInvoke(e,t,i){if(e==="event_tool_call"){const s=String(t.tool_name??""),n=Re(s,{...t.arguments??{}}),r=this.getEventToolHandle();if(this.activeEvent){const c=this.activeEvent;String(n.event_id??"").trim()===""&&(n.event_id=c.eventId),String(n.session_id??"").trim()===""&&(n.session_id=c.sessionId)}else if(this.lastClearedEvent&&s==="grix_reply"){const c=this.lastClearedEvent;Date.now()-c.ts<Be&&(String(n.session_id??"").trim()===""&&(n.session_id=c.sessionId),n.event_id="",o.info("claude-adapter",`Late grix_reply fallback: sending direct message for cleared event ${c.eventId} (cleared ${(Date.now()-c.ts)/1e3}s ago)`))}s==="grix_reply"&&String(n.event_id??"").trim()!==""&&this.completedEventIds.has(String(n.event_id??"").trim())&&(o.info("claude-adapter",`Late grix_reply fallback: sending direct message for completed event ${String(n.event_id??"").trim()}`),n.event_id="");const a=Te(s,n);if(!a.valid)throw new Error(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${a.error}`);if(r.status!=="ready")throw new Error(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${r.status}`);if(s==="grix_access_control")return this.executeAccessControl(n);if(Ae(s)){const c=this.activeEvent;c&&(c.toolCallInFlight=!0);try{if(i?.aborted)throw new Error("invoke aborted by timeout");const u=await Ie(r,s,n);if(u.isError)throw new Error(u.content[0]?.text??"event tool failed");if(i?.aborted)throw new Error("invoke aborted by timeout after send");return this.postProcessEventToolCall(s,n),JSON.parse(u.content[0]?.text??"null")}finally{if(c&&(c.toolCallInFlight=!1,c.pendingStopHook&&this.activeEvent===c)){const u=c.pendingStopHook;c.pendingStopHook=void 0,this.finalizeActiveEvent(u)}}}throw new Error(`\u672A\u77E5\u4E8B\u4EF6\u5DE5\u5177: ${s}`)}return this.bridgeCallbacks.agentInvoke(e,t)}getEventToolHandle(){const e=this;return{status:"ready",getStatusSnapshot:()=>({status:"ready",connectedAt:Date.now(),reconnectAttempts:0}),sendEventAck:t=>{e.bridgeCallbacks.sendEventAck(t.event_id,t.session_id??"")},sendStreamChunk:t=>{e.bridgeCallbacks.sendStreamChunk(t.event_id??"",t.session_id,t.delta_content??"",Number(t.chunk_seq??0)||1,t.is_finish===!0,t.client_msg_id,t.quoted_message_id)},sendMsg:t=>{if(typeof e.bridgeCallbacks.sendDirectMessage!="function"){o.warn("claude-adapter","sendDirectMessage callback not provided, dropping direct message");return}e.bridgeCallbacks.sendDirectMessage({sessionId:t.session_id,clientMsgId:t.client_msg_id,content:t.content,quotedMessageId:t.quoted_message_id})},sendEventResult:t=>{e.bridgeCallbacks.sendEventResult(t.event_id,t.status,t.msg,t.code)},sendSessionActivitySet:t=>{}}}postProcessEventToolCall(e,t){const i=String(t.event_id??"").trim();if(!i||this.activeEvent?.eventId!==i){o.warn("claude-adapter",`postProcessEventToolCall: event_id mismatch (tool=${e}, eventId=${i}, activeEventId=${this.activeEvent?.eventId??"none"})`);return}if(e==="grix_complete"){this.completedEventIds.set(i,Date.now()),this.clearActiveEvent();return}if(e==="grix_reply"){this.activeEvent.replied=!0;const s=String(t.text??"");s.length>0&&(this.activeEvent.lastReplyTextLen=s.length),this.markActiveEventActivity(i,String(t.session_id??"").trim()||void 0)}}async executeAccessControl(e){const t=String(e.action??""),i=$e[t];if(!i)throw new Error(`\u672A\u77E5 access_control action: ${t}`);const s={};return e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy),this.bridgeCallbacks.agentInvoke("claude_access_control",{verb:i,payload:s},3e4)}resolveSessionRuntime(){if(!this.runtimeResolver)return{};try{return this.runtimeResolver(this.sessionId)??{}}catch(e){throw new Error(`resolve session runtime failed: ${e instanceof Error?e.message:String(e)}`)}}async validatePluginDir(e){const t=String(e??"").trim();if(!t)return;let i;try{i=await se(t)}catch{throw new Error(`pluginDir is not accessible: ${t}`)}if(!i.isDirectory())throw new Error(`pluginDir is not a directory: ${t}`);const s=h(t,".mcp.json");try{(await se(s)).isFile()&&(await ie(s),o.info("claude-adapter",`Removed conflicting .mcp.json from pluginDir: ${s}`))}catch{}}async ensureWorkspaceTrust(e){const t=h(R(),".claude.json");try{const i=await C(t,"utf8"),s=JSON.parse(i);if(s.projects?.[e]?.hasTrustDialogAccepted===!0)return;s.projects||(s.projects={}),s.projects[e]||(s.projects[e]={}),s.projects[e].hasTrustDialogAccepted=!0,await I(t,JSON.stringify(s),"utf8"),o.info("claude-adapter",`Pre-trusted workspace: ${e}`)}catch(i){o.warn("claude-adapter",`Failed to pre-trust workspace ${e}: ${i}`)}}static REQUIRED_GROWTHBOOK_FEATURES={tengu_harbor:!0,tengu_harbor_permissions:!0,tengu_harbor_prism:!0,tengu_harbor_ledger:[{marketplace:"claude-plugins-official",plugin:"discord"},{marketplace:"claude-plugins-official",plugin:"telegram"},{marketplace:"claude-plugins-official",plugin:"fakechat"},{marketplace:"claude-plugins-official",plugin:"imessage"},{marketplace:"claude-plugins-official",plugin:"grix"}],tengu_flint_harbor:!0,tengu_quill_harbor:"acceptEdits"};async ensureGrowthBookFeatures(e){const t=h(R(),".claude.json");try{let i;try{const a=await C(t,"utf8");i=JSON.parse(a)}catch{i={}}i.cachedGrowthBookFeatures||(i.cachedGrowthBookFeatures={});const s=i.cachedGrowthBookFeatures;let n=!1;for(const[a,c]of Object.entries(Z.REQUIRED_GROWTHBOOK_FEATURES))s[a]!==c&&(s[a]=c,n=!0);i.hasCompletedOnboarding||(i.hasCompletedOnboarding=!0,i.lastOnboardingVersion||(i.lastOnboardingVersion="2.1.31"),n=!0),i.projects||(i.projects={});const r=i.projects;if(r[e]||(r[e]={}),r[e].hasCompletedProjectOnboarding||(r[e].hasCompletedProjectOnboarding=!0,n=!0),r[e]?.hasTrustDialogAccepted&&(delete r[e].hasTrustDialogAccepted,n=!0),!n)return;await I(t,JSON.stringify(i,null,2),"utf8"),o.info("claude-adapter",`Injected GrowthBook features, onboarding flags, and deferred trust: ${e}`)}catch(i){o.warn("claude-adapter",`Failed to inject GrowthBook features: ${i}`)}}watchGrowthBookCache(){const e=h(R(),".claude.json"),i=Object.entries({tengu_harbor:!0,tengu_flint_harbor:!0,tengu_harbor_prism:!0});let s=0;const n=async()=>{try{const r=await C(e,"utf8"),a=JSON.parse(r),c=a.cachedGrowthBookFeatures;if(!c)return;let u=!1;for(const[l,p]of i)c[l]!==p&&(c[l]=p,u=!0);if(!u)return;await I(e,JSON.stringify(a),"utf8"),s++,o.info("claude-adapter",`Re-injected GrowthBook features after Claude cache update (attempt ${s})`)}catch{}};ye(e,{interval:500},()=>{if(this.startupChannelListening||this.stopped||s>=5){te(e);return}n()}),setTimeout(()=>te(e),3e4).unref()}async injectStatusLineSettings(e){try{const t=this.resolveProjectRoot(),i=h(t,"dist","scripts","status-line-forwarder.js"),s=h(e,".claude"),n=h(s,"settings.json");await b(s,{recursive:!0});let r={};try{r=JSON.parse(await C(n,"utf8"))}catch{}const a={type:"command",command:`node ${i}`,refreshInterval:10};r.statusLine=a;const c=`${JSON.stringify(r,null,2)}
|
|
11
|
+
`;await I(n,c,"utf8"),o.info("claude-adapter",`Injected statusLine settings: ${n}`)}catch(t){o.warn("claude-adapter",`Failed to inject statusLine settings: ${t instanceof Error?t.message:t}`)}}async ensureUserMcpServer(e,t,i){const s=this.resolveServerEntryPath(t),n=process.execPath,r=[s],a=h(R(),".claude.json");let c=null;try{const f=await C(a,"utf8");c=JSON.parse(f)?.mcpServers?.[D]??null}catch{}if(c&&String(c.type||"stdio").trim()==="stdio"&&String(c.command??"").trim()===n&&Array.isArray(c.args)&&c.args.length===r.length&&c.args.every((f,v)=>f===r[v]))return;o.info("claude-adapter",`Registering user-scoped MCP server: ${D} -> ${n} ${r.join(" ")}`);try{L(`${e} mcp remove -s user ${D}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe"})}catch{}const u=["mcp","add","--scope","user",D,"--",n,...r],l=process.platform==="win32"?'"':"'",p=L(`${e} ${u.map(f=>`${l}${f}${l}`).join(" ")}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe"});o.info("claude-adapter",`MCP server registered: ${p.trim()||"ok"}`)}resolveServerEntryPath(e){const t=h(e,"server","main.js");try{if(B(t))return t}catch{}const i=h(e,"dist","index.js");try{if(B(i))return i}catch{}throw new Error(`Cannot find grix-claude server entry in pluginDir: ${e}`)}clearActiveEvent(){const e=this.activeEvent;this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),e&&(this.sessionIdConflictRetriedEventIds.delete(e.eventId),this.completedEventIds.set(e.eventId,Date.now()),this.lastClearedEvent={eventId:e.eventId,sessionId:e.sessionId,ts:Date.now()},this.emit(`reply:${e.sessionId}`,{status:"completed"}),this.emit("eventDone",e.eventId)),this.activeEvent=null,this.stopComposing(),this.tryDeliverQueuedEvent()}startComposing(e,t){}stopComposing(){}clearComposingTimer(){}resolveHookSignalsPath(){const e=S();return h(e.dataDir,`hook-signals-${this.sessionId}.json`)}startActivityTracking(){this.activityManager&&this.activityManager.stop();const e=this.resolveHookSignalsPath(),t=S().hookSignalsLogPath,i=new Ce(e,t);o.info("claude-adapter",`Activity tracking started: watching ${e}`),this.activityManager=new Pe({hookSignalStore:i,onActivity:s=>this.onHookActivity(s),onStop:()=>this.onClaudeTurnEnd("Stop"),onStopFailure:()=>this.onClaudeTurnEnd("StopFailure"),onCompactStart:()=>this.beginCompaction(),onCompactResult:()=>this.finishCompaction("post-compact-hook"),onPermissionRequest:(s,n)=>this.handlePermissionHookEvent(s,n)}),this.activityManager.start()}onClaudeTurnEnd(e){if(o.info("claude-adapter",`Hook activity: ${e}`),!!this.activeEvent){if(this.activeEvent.toolCallInFlight){o.info("claude-adapter",`Stop hook deferred: toolCallInFlight for ${this.activeEvent.eventId}`),this.activeEvent.pendingStopHook=e;return}this.finalizeActiveEvent(e)}}attemptRescueFromJsonl(e,t){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return o.info("claude-adapter",`Rescue skipped: no claudeCliSessionId or claudeSessionCwd for ${e}`),!1;const i=Me(this.claudeCliSessionId,this.claudeSessionCwd);if(!i)return o.info("claude-adapter",`Rescue failed: no assistant text found in JSONL for ${e}`),!1;const s=`rescue_${e}_${Date.now()}`;return this.bridgeCallbacks.sendStreamChunk(e,t,i,1,!1,s),this.bridgeCallbacks.sendStreamChunk(e,t,"",2,!0,s),o.info("claude-adapter",`Rescue succeeded for event ${e}: sent ${i.length} chars from JSONL`),!0}finalizeActiveEvent(e){if(!this.activeEvent)return;const t=this.activeEvent.eventId,i=this.activeEvent.sessionId,s=!this.activeEvent.replied&&this.attemptRescueFromJsonl(t,i);this.activeEvent.replied||s?(o.info("claude-adapter",`Stop hook received, finalizing event ${t} as responded (replied=${this.activeEvent.replied}, rescued=${s})`),this.bridgeCallbacks.sendEventResult(t,"responded")):(o.warn("claude-adapter",`Active event not confirmed when ${e}: ${t}, sending failed result`),this.bridgeCallbacks.sendEventResult(t,"failed",`agent completed without confirming reply (${e})`,"reply_unconfirmed")),this.clearActiveEvent(),this.armStopHookBarrier(i)}onHookActivity(e){const t=this.activeEvent?.sessionId;if(o.info("claude-adapter",`Hook activity: tool=${e?.tool_name??"(clear)"} session=${t??"(none)"}`),e&&this.activeEvent&&this.markActiveEventActivity(this.activeEvent.eventId,this.activeEvent.sessionId),!!t)if(e){this.startComposing(t,e);const i=this.activeEvent;if(i){const s=e.event_name,n=e.tool_name,r=e.tool_input??"",a=n?be(n):!1;if(n==="ExitPlanMode"&&s==="PreToolUse")o.info("claude-adapter","ExitPlanMode detected; waiting for user decision via permission card");else if(n==="AskUserQuestion"&&s==="PreToolUse")this.handleAskUserQuestion(i,r);else if(s==="PreToolUse"&&n)r&&(this.lastPreToolInput=r),a||this.bridgeCallbacks.sendToolUse(i.eventId,i.sessionId,n,r);else if((s==="PostToolUse"||s==="PostToolUseFailure")&&n){if(n==="AskUserQuestion")return;const c=r||this.lastPreToolInput;if(this.lastPreToolInput="",!a){const u=s==="PostToolUseFailure"?`(failed) ${c}`:c;this.bridgeCallbacks.sendToolResult(i.eventId,i.sessionId,n,u)}}}}else this.startComposing(t)}handlePermissionHookEvent(e,t){if(!this.activeEvent){o.warn("claude-adapter","PermissionRequest without active event, ignoring");return}if(e==="AskUserQuestion"){o.info("claude-adapter","Skip permission card for AskUserQuestion; handled by agent_question card flow");return}const i=this.activeEvent,s=S();new N(s.permissionRequestsDir).listPending().then(r=>{const a=r.length>0?r[r.length-1]:null;if(!a){o.warn("claude-adapter","No pending permission request found in store");return}const c=a.request_id;this.pendingPermissions.set(c,{eventId:i.eventId,sessionId:i.sessionId});const u=typeof t=="string"?t:"";if(e==="ExitPlanMode"){const f=Ne(u);f&&this.bridgeCallbacks.sendReply(i.eventId,i.sessionId,f)}const l=e==="ExitPlanMode"?"":u.slice(0,100),p=l?`${e}: ${l}`:e;this.bridgeCallbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,approvalId:c,toolName:e,toolTitle:p}),o.info("claude-adapter",`Sent permission card: approvalId=${c} tool=${e}`)}).catch(r=>{o.warn("claude-adapter",`Failed to send permission card: ${r}`)})}handleAskUserQuestion(e,t){const i=oe(t);if(!i){o.warn("claude-adapter","Failed to parse AskUserQuestion input, skipping agent_question card");return}const s=S(),n=new re(s.questionRequestsDir);n.listPending().then(async r=>{const a=[...r].reverse().filter(l=>String(l.session_id??"").trim()===this.claudeCliSessionId),c=a.find(l=>String(l.event_id??"").trim()===e.eventId)??a.find(l=>String(l.event_id??"").trim()==="")??a[0]??null,u=c?.request_id??`fallback-${Date.now()}`;c&&String(c.event_id??"").trim()===""&&await n.updateRequest(c.request_id,{event_id:e.eventId}),this.pendingQuestion.set(u,{eventId:e.eventId,sessionId:e.sessionId}),e.awaitingUserQuestion=!0,this.bridgeCallbacks.sendAgentQuestionCard(e.eventId,e.sessionId,{request_id:u,mode:"form",questions:i}),o.info("claude-adapter",`Sent agent_question card: request_id=${u} questions=${i.length}`)}).catch(()=>{o.warn("claude-adapter","Failed to list pending questions from store")})}parseAskUserQuestions(e){return oe(e)}parseAskUserQuestionInput(e){let t;try{t=JSON.parse(e)}catch{return null}const i=[],s=t.questions;if(!Array.isArray(s)||s.length===0)return null;for(let n=0;n<s.length;n++){const r=s[n];if(!r||typeof r!="object")continue;const a=String(r.header??r.question??`Question ${n+1}`),c=String(r.prompt??""),u=Array.isArray(r.options)?r.options:void 0,l=r.multiSelect===!0;i.push({header:a,prompt:c,...u&&u.length>0?{options:u}:{},...l?{multi_select:!0}:{}})}return i.length>0?{questions:i}:null}pruneCompletedEvents(){const e=Date.now()-He;for(const[t,i]of this.completedEventIds.entries())i<e&&this.completedEventIds.delete(t)}markActiveEventActivity(e,t){const i=this.activeEvent;i&&(e&&i.eventId!==e||t&&i.sessionId!==t||(this.resetActiveEventIdleTimer(i.eventId),this.resetActiveEventHardTimer(i.eventId)))}clearActiveEventIdleTimer(){this.activeEventIdleTimer&&(clearTimeout(this.activeEventIdleTimer),this.activeEventIdleTimer=null)}clearActiveEventHardTimer(){this.activeEventHardTimer&&(clearTimeout(this.activeEventHardTimer),this.activeEventHardTimer=null)}resetActiveEventIdleTimer(e){this.clearActiveEventIdleTimer(),this.activeEventIdleTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e)return;if(this.activeEvent?.toolCallInFlight){o.info("claude-adapter",`Idle timeout skipped: toolCallInFlight for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}if(this.activeEvent?.awaitingUserQuestion){o.info("claude-adapter",`Idle timeout skipped: awaitingUserQuestion for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}if(this.pendingPermissions.size>0){o.info("claude-adapter",`Idle timeout skipped: pendingPermissions=${this.pendingPermissions.size} for ${e}, resetting timer`),this.resetActiveEventIdleTimer(e);return}const t=this.activeEvent?.replied?"responded":"failed",i=this.activeEvent?.replied?void 0:`agent idle for ${z/1e3}s`,s=this.activeEvent?.replied?void 0:"agent_idle_timeout";o.error("claude-adapter",`Active event idle timeout (${z/1e3}s): ${e}, replied=${!!this.activeEvent?.replied}, sending ${t}`),this.completedEventIds.set(e,Date.now()),this.bridgeCallbacks.sendEventResult(e,t,i,s),this.clearActiveEvent(),t==="failed"&&this.emit("stuck")},z)}resetActiveEventHardTimer(e){this.clearActiveEventHardTimer(),this.activeEventHardTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e)return;const t=this.activeEvent?.replied?"responded":"failed",i=this.activeEvent?.replied?void 0:`agent exceeded max duration ${J/1e3}s`,s=this.activeEvent?.replied?void 0:"agent_hard_timeout";o.error("claude-adapter",`Active event hard timeout (${J/1e3}s): ${e}, replied=${!!this.activeEvent?.replied}, sending ${t}`),this.completedEventIds.set(e,Date.now()),this.bridgeCallbacks.sendEventResult(e,t,i,s),this.clearActiveEvent(),t==="failed"&&this.emit("stuck")},J)}beginCompaction(){this.compacting||(this.compacting=!0,o.info("claude-adapter","Compaction started; gating input"),this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>this.finishCompaction("fallback-timeout"),6e4),this.compactingTimer.unref?.())}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),o.info("claude-adapter",`Compaction finished (${e}); draining ${this.queuedEvents.length} queued events`),this.tryDeliverQueuedEvent();const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.()}tryDeliverQueuedEvent(){if(this.activeEvent||this.queuedEvents.length===0)return;const e=this.queuedEvents.shift();this.queuedEventIds.delete(e.event_id),this.deliverInboundEvent(e)}rejectQueuedEvents(e,t="failed"){if(this.queuedEvents.length===0)return;const i=this.queuedEvents.splice(0);this.queuedEventIds.clear();for(const s of i)this.bridgeCallbacks.sendEventResult(s.event_id,t,e)}armStopHookBarrier(e){this.stopHookBarrierSessionId=e,this.stopHookBarrierTimer=setTimeout(()=>{this.stopHookBarrierSessionId===e&&(o.warn("claude-adapter",`Stop hook barrier timeout for session=${e}`),this.clearStopHookBarrier(),this.tryDeliverQueuedEvent())},Ge)}clearStopHookBarrier(){this.stopHookBarrierSessionId=null,this.stopHookBarrierTimer&&(clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierTimer=null)}clearPendingMcpFailureTimer(){this.pendingMcpFailureTimer&&(clearTimeout(this.pendingMcpFailureTimer),this.pendingMcpFailureTimer=null)}markMcpStartupFailure(){if(!this.mcpStartupFailureHandled&&(this.mcpStartupFailureHandled=!0,this.mcpChannelBroken=!0,o.error("claude-adapter","Claude reported blocking MCP server startup failure"),this.activeEvent)){const e=this.activeEvent.eventId;this.completedEventIds.set(e,Date.now()),this.clearActiveEvent()}}}class Ye extends ne{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("claude-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function _(d){if(d==null)return 0;const e=Number(d);return Number.isFinite(e)?e:0}function K(d){return String(d).replace(/\\/g,"\\\\").replace(/\{/g,"\\{").replace(/\}/g,"\\}")}async function Ke(d,e,t){const i=h(d,"claude.expect"),s=h(d,"claude.pid"),n=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${K(e)}}${t.map(r=>` {${K(r)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${K(s)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","after 500",'send -- "\\r"',"expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(I am using this for local development|Please use --channels|dangerously-load-development-channels)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter|Continue.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {(?i)Listening.*channel messages.*server:grix} {"," set startup_prompt_armed 0"," }"," eof {}","}","interact",""];return await I(s,"","utf8"),await I(i,n.join(`
|
|
12
|
+
`),"utf8"),{expectPath:i,pidPath:s}}async function Xe(d,e=50,t=100){for(let i=0;i<e;i++){try{const s=await C(d,"utf8"),n=parseInt(String(s).trim(),10);if(Number.isFinite(n)&&n>0)return n}catch{}await new Promise(s=>setTimeout(s,t))}return 0}function Ze(d,e){return new Promise((t,i)=>{let s=!1;const n=a=>{s||(s=!0,d.off("error",r),a())},r=a=>n(()=>i(a));d.once("error",r),Xe(e).then(a=>n(()=>t(a))).catch(a=>n(()=>i(a)))})}function he(d){return d.replace(/[/\\]/g,"-")}function et(d){const e=S();return h(e.dataDir,"claude-mcp-configs",`${he(d)}.json`)}function tt(d){const e=S();return h(e.dataDir,"claude-system-prompts",`${he(d)}.txt`)}async function it(d,e){await b(h(S().dataDir,"claude-mcp-configs"),{recursive:!0});const t={mcpServers:{[D]:{type:"stdio",command:process.execPath,args:e}}},i=`${JSON.stringify(t,null,2)}
|
|
13
|
+
`;let s="";try{s=await C(d,"utf8")}catch{}s!==i&&(await I(d,i,"utf8"),o.info("claude-adapter",`Wrote MCP config: ${d}`))}async function st(d,e){await b(h(S().dataDir,"claude-system-prompts"),{recursive:!0});const t=`${e}
|
|
14
|
+
`;let i="";try{i=await C(d,"utf8")}catch{}i!==t&&await I(d,t,"utf8")}function X(d,e){if(process.platform==="win32")return;let t=!1;try{const i=L(`ps ax -o pid,command | grep -E -- '--(session-id|resume) ${d}' | grep -v grep`,{encoding:"utf8",timeout:5e3}).trim();if(i)for(const s of i.split(`
|
|
15
|
+
`)){const n=parseInt(s.trim(),10);if(n>0&&n!==process.pid&&!e.includes(n)){o.info("claude-adapter",`Killing stale Claude process PID=${n} holding session ${d}`);try{process.kill(n,"SIGTERM"),t=!0}catch{}}}}catch{}t||U(d)}function U(d){const e=h(R(),".claude"),t=[h(e,"session-env",d)];try{const i=h(e,"sessions");for(const s of ge(i))if(s.endsWith(".json"))try{const n=h(i,s),r=JSON.parse(B(n,"utf8"));r&&r.sessionId===d&&t.push(n)}catch{}}catch{}for(const i of t)try{q(i),_e(i,{recursive:!0,force:!0}),o.info("claude-adapter",`Removed stale session file: ${i}`)}catch{}}function nt(d,e){if(!e)return!1;const t=h(R(),".claude"),i=rt(e),s=h(t,"projects",i,`${d}.jsonl`);try{return q(s),!0}catch{return!1}}function rt(d){const e=d.replace(/\\/g,"/").replace(/:\/\//g,"/");return/^[a-zA-Z]:\//.test(e)||e.startsWith("//")?e.toLowerCase().replace(/:/g,"-").replace(/^\//,"").replace(/\//g,"-"):e.replace(/:/g,"-").replace(/\//g,"-")}export{Z as ClaudeAdapter,rt as deriveClaudeProjectDirName,oe as parseAskUserQuestionPayload};
|