grix-connector 4.11.9 → 4.11.10
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/claude/claude-adapter.js +21 -21
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -2
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.11.10.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +5 -5
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/core/log/index.js +1 -1
- package/dist/core/log/logger.js +9 -6
- package/dist/core/proxy/capture/writer.js +2 -2
- package/dist/grix.js +8 -8
- package/dist/launcher.mjs +119 -8
- package/dist/log.js +2 -2
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/dist/service/service-manager.js +3 -3
- package/openclaw-plugin/audit-recorder-worker.js +150 -18
- package/openclaw-plugin/index.js +167 -35
- package/package.json +1 -1
- package/scripts/launcher.mjs +119 -8
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.11.9.tgz +0 -0
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{spawn as ne,spawnSync as re,execSync as ae,execFile as dt}from"node:child_process";import{promisify as ut}from"node:util";import{randomUUID as Y}from"node:crypto";import{killProcessGroup as q,hasChildProcesses as ht,resolveCommandPath as ft,resolveWindowsExecInvocation as we}from"../../core/runtime/spawn.js";import{chmodSync as oe,readdirSync as le,readFileSync as j,realpathSync as Pe,rmSync as pt,statSync as k,truncateSync as mt,existsSync as y,openSync as vt,writeSync as gt,closeSync as Et,renameSync as Ce,mkdirSync as Te,constants as Ae,watch as _t}from"node:fs";import{appendFile as St,mkdir as F,readFile as I,rm as Ie,stat as be,writeFile as D}from"node:fs/promises";import{dirname as yt,isAbsolute as wt,join as f,resolve as Pt}from"node:path";import{homedir as R,tmpdir as Ct}from"node:os";import ce from"node:net";import{EventEmitter as ke}from"node:events";import{fileURLToPath as Tt}from"node:url";let V=null;if(process.platform==="win32")try{V=await import("node-pty")}catch{V=null}import{resolveRuntimePaths as w}from"../../core/config/index.js";import{normalizeClaudeEffort as At,normalizeClaudeEnvEffort as It}from"../../core/config/claude-direct-env.js";import{SESSION_MODE_IDS as G}from"./protocol-contract.js";import{buildSessionContextBlock as bt}from"../shared/session-context.js";import{log as o}from"../../core/log/index.js";import{ActivityStatusManager as kt}from"./activity-status-manager.js";import{HookSignalStore as Rt}from"../../core/hooks/hook-signal-store.js";import{QuestionStore as Re}from"../../core/persistence/question-store.js";import{PermissionStore as z}from"../../core/persistence/permission-store.js";import{InternalApiServer as Dt}from"../../core/mcp/internal-api-server.js";import{executeEventTool as De,isEventTool as $t}from"../../core/mcp/event-tool-executor.js";import{validateToolArgs as Ot}from"../../core/mcp/tool-schemas.js";import{isGrixInternalToolName as xt,normalizeEventToolArgs as Lt}from"../../core/mcp/tools.js";import{scanSkills as Mt}from"./skill-scanner.js";import{syncDefaultSkillsToDir as Ft}from"../../default-skills/index.js";import{clearSessionJsonlDriftCache as Nt,countPendingBackgroundTasks as jt,noteSessionJsonlPath as Bt,extractLastAssistantEntry as W,extractTextBlocksAfterOffset as $e,hasTerminalToolResultAfterOffset as Oe,probeSessionTurnState as de,resolveSessionJsonlPath as x}from"./usage-parser.js";import{readSettingsEnv as Ut}from"./model-list.js";import{resolveCliPath as Ht,getCliVersion as qt}from"../../core/util/cli-probe.js";import{GRIX_RELAY_ANTHROPIC_API_KEY as xe}from"../../core/proxy/index.js";const N="grix",K={developmentChannels:!0,maxTurns:!0};function Gt(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 Le(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}`,l=String(r.header??r.question??a).trim()||a,c=String(r.prompt??r.question??"").trim();if(!c)continue;const u=Gt(r.options),h=r.multiSelect===!0||r.multi_select===!0;i.push({header:l,prompt:c,...u?{options:u}:{},...h?{multi_select:!0}:{}})}return i.length>0?i:null}function zt(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 Wt=[/Please run \/login/,/API Error:\s*401/,/authentication_error/,/OAuth token has expired/],Jt=[/API Error:\s*401/,/authentication_error/],Yt=[/You're out of extra usage/i,/Stop and wait for limit to reset/i,/Add funds to continue with extra usage/i],Vt=/API Error:\s*400.*(server_tool_use\.id|messages\.\d+\.content)/;function ue(d){const e=d?.trim();return e&&!e.startsWith("API Error:")?e:"Claude hit an API format error. Please start a new conversation (/grix open <dir>)."}const Me=300*1e3,Fe=300*1e3,Ne=Fe+30*1e3,je=3e3,Kt=50,Qt=1800*1e3,Xt=["CLAUDE_CODE_ENABLE_TELEMETRY","CLAUDE_CODE_ENHANCED_TELEMETRY_BETA","OTEL_LOGS_EXPORTER","OTEL_TRACES_EXPORTER","OTEL_METRICS_EXPORTER","OTEL_EXPORTER_OTLP_PROTOCOL","OTEL_EXPORTER_OTLP_ENDPOINT","OTEL_EXPORTER_OTLP_HEADERS","OTEL_LOGS_EXPORT_INTERVAL","OTEL_TRACES_EXPORT_INTERVAL","OTEL_LOG_USER_PROMPTS","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_RAW_API_BODIES"];function Q(d=process.env){const e={...d},t=new Set(Xt.map(i=>i.toLowerCase()));for(const i of Object.keys(e))t.has(i.toLowerCase())&&delete e[i];return e}const Be=60*1e3,Ue="lost injection respawn",He=600*1e3,Zt=250;function qe(d,e){const t=Number(process.env[d]);return Number.isFinite(t)&&t>0?t:e}function Ge(d){return d.trim().replace(/[^a-zA-Z0-9._-]+/gu,"_")||"unknown"}function ei(d){const e=ft("expect",d);return wt(e)?e:null}function X(d){try{return y(d)?k(d).size:0}catch{return 0}}function ze(d){const e=[],t=i=>{let s;try{s=le(i,{withFileTypes:!0})}catch{return}for(const n of s){const r=f(i,n.name);n.isDirectory()?t(r):n.isFile()&&e.push(r)}};return t(d),e.sort((i,s)=>We(i)-We(s)||i.localeCompare(s))}function We(d){try{return k(d).mtimeMs}catch{return 0}}const Je=qe("GRIX_RESCUE_SETTLE_POLL_MS",2e3),Ye=qe("GRIX_RESCUE_SETTLE_BUDGET_MS",12e4),ti=300*1e3,ii="The model's tool call could not be parsed (retry also failed).",si="[\u7CFB\u7EDF\u81EA\u52A8\u91CD\u8BD5] \u4F60\u4E0A\u4E00\u6761\u56DE\u590D\u7684\u5DE5\u5177\u8C03\u7528\u89E3\u6790\u5931\u8D25\uFF0C\u6CA1\u6709\u53D1\u51FA\u53BB\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6267\u884C\u5DF2\u7ECF\u5B8C\u6210\u7684\u64CD\u4F5C\uFF0C\u76F4\u63A5\u91CD\u65B0\u8C03\u7528 reply \u5DE5\u5177\uFF0C\u628A\u4F60\u4E0A\u4E00\u6761\u60F3\u53D1\u7ED9\u7528\u6237\u7684\u7ED3\u8BBA\u539F\u6837\u91CD\u65B0\u53D1\u9001\u4E00\u6B21\u3002",ni="Sorry, the previous reply could not be generated properly (the model's tool call failed to parse). Please send it again, and use /grix restart to restart the session if needed.",ri=2*1e3,he=90*1e3,Ve=1800*1e3,Ke=15*1e3,ai=60*1e3,Qe=10*1e3,oi=30*1e3,Xe=30*1e3,li=2e3,ci=3e4;function di(d){const e=d.tool_name||"";if(e==="mcp__grix__grix_dispatch_agent")return"\u540E\u53F0\u534F\u8C03\u5B50 agent";if(e.startsWith("mcp__grix__"))return"\u540E\u53F0\u8C03\u7528 Grix \u5DE5\u5177";if(e.startsWith("mcp__"))return"\u540E\u53F0\u8C03\u7528\u5DE5\u5177";switch(e){case"Bash":return"\u540E\u53F0\u6267\u884C\u547D\u4EE4";case"Read":case"Edit":case"Write":case"NotebookEdit":return"\u540E\u53F0\u8BFB\u5199\u6587\u4EF6";case"Task":return"\u540E\u53F0\u8FD0\u884C\u5B50\u4EFB\u52A1";default:return e?`\u540E\u53F0\u8FD0\u884C\uFF1A${e}`:"\u540E\u53F0\u4EFB\u52A1\u8FDB\u884C\u4E2D"}}function ui(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}const hi=12e4,fi=3e4,pi=6e4,mi=3e3,Z=1e3,Ze=45e3,vi=18e3,fe=8192,gi=1e3,Ei=2e3,et=300,_i=3e4,Si=2e3,yi=2e3,wi=/(do you want to proceed\?[\s\S]*?\d\.\s*yes)|(only you can approve)/i,Pi=/(do you want to proceed)|(only you can approve)|(\d\.\s*yes)|(\d\.\s*no)|(esc to cancel)|(tab to amend)/i,Ci=/^[✳✶✻✽✵❋✺✴❈❖✦✧✢◉◎⬥⬦◇◆▸▹►▻→←↑↓⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·…\d]*still\s+thinking/i,pe="__grix_key__ ";let tt=!1;const me=new Set;async function Ti(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=ce.createServer();r.once("error",n),r.listen(0,"127.0.0.1",()=>{const a=r.address(),l=typeof a=="object"&&a?a.port:0;r.close(c=>{if(c){n(c);return}s(l)})})});if(i>0&&!e.has(i)&&!me.has(i))return me.add(i),i}throw new Error("\u65E0\u6CD5\u5206\u914D MCP \u901A\u77E5\u7AEF\u53E3")}function Ai(d){d>0&&me.delete(d)}const Ii=["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>.',"When present, the channel metadata includes context_messages_json \u2014 a JSON array of earlier visible messages for this trigger; each entry carries sender_id and content. An entry whose content starts with [\u5F15\u7528\u6D88\u606F] is the quoted (replied-to) message being responded to. Use these records as context (prefer them over inferring from quoted_message_id alone), in group chats use sender_id to tell who said what, and only answer the current message.","Local transcript availability, session binding, recovery mode, and connector history-loss diagnostics are internal operational details. Do not mention them, ask the user to choose a recovery mode, or say that history/context was lost unless the user explicitly asks to debug that mechanism.",'Both your plain text and the reply tool are delivered to the user. You are talking directly to the user, so address them in the second person ("you"); do not slip into third-person narration about them (e.g. "\u5DF2\u7ECF\u628A\u7ED3\u8BBA\u56DE\u590D\u7ED9\u8001\u90ED\u4E86") \u2014 say it straight to them ("\u7ED3\u8BBA\u662F\u2026\u2026").',"While you work, use plain text for short progress notes. Deliver your final conclusion \u2014 the answer the user is waiting for \u2014 through the reply tool; that is the message the user treats as your result and the one the connector quotes. Your plain text reaches the user too \u2014 it is not private scratch space, so it is a real channel for progress and for anything the user needs mid-turn; you just need not restate the full conclusion as plain text once it is in the reply. The connector automatically quotes the message you are answering, so you normally do not need to set reply_to (set it only to quote a different earlier message).","Make the reply tool call the last thing you do in a turn and put your whole conclusion inside it: once you have called reply, any further text you write in the same turn is dropped, not delivered. Progress notes go before the reply; the reply ends the turn.",'Never explain the delivery mechanics to the user or tell them you "already sent it via the reply tool" \u2014 that is internal plumbing they neither see nor care about. If the user says they did not receive or cannot read something, do not insist you already sent it; assume the delivery or the format failed and send it again, switching format when that is the likely cause (e.g. render a diagram to an image, strip code fences, upload a file).',"If you intentionally do not want to send any visible message, call the complete tool with event_id and a final status.",'Do not send a bare acknowledgement or "got it / on it / starting now" message before doing the work; do the work first, then deliver the actual result through the reply tool. During a long-running task, write a short plain-text progress note when you reach a meaningful milestone so the user can see progress as it happens.',"You only run while handling a turn; once your turn ends you are frozen and cannot send anything until the user messages you again.",'Unbreakable rule: never end a turn having promised something you cannot deliver. In particular, never start a task, detach it (nohup, a trailing &, any background process or watcher), end the turn, and promise to "notify when it finishes" \u2014 that notification can never happen, so do not promise it.',"For any task whose result the user is waiting on (deploy, build, rollout, tests), run it in the foreground and wait for it to finish within this same turn, then report the real outcome. You may launch several in the background at once for parallelism, but you must still collect all of their results within this same turn before you reply and finish.","Two cases where leaving a process running is correct: a long-lived service that is meant to keep running (dev server, daemon) \u2014 background it, then report that it started plus how to check or stop it; and a task too long to finish in one turn \u2014 you may leave it running, but state plainly that you cannot auto-notify and give the user a concrete way to retrieve the result later (a log path, a PID, or asking them to ping you to re-check)."];function bi(d,e,t){const i=[...Ii];e&&i.unshift(bt(e,t));try{const s=d?.agentName?.trim().slice(0,200),n=d?.introduction?.trim().slice(0,2e3);if(s||n){const r=[s?`Your name is "${s}".`:"",n?`Your self-introduction: ${n}`:""].filter(Boolean).join(" ");i.unshift(r)}}catch{}return i.join(" ")}function it(d){return String(d??"").trim().toLowerCase()===G.approval?G.approval:G.fullAuto}class ys extends ke{type="claude";config;bridgeCallbacks;mcpServerProcess=null;internalApi=null;claudeProcess=null;claudePty=null;singleTurnFallbackProcesses=new WeakSet;singleTurnFallbackPtys=new WeakSet;lostInjectionKilledProcesses=new WeakSet;lostInjectionKilledPtys=new WeakSet;singleTurnFallbackChild=null;spawnPromise=null;lifecycleVersion=0;sessionId="";alive=!1;stopped=!1;activeEvent=null;completedAuditBoundaries=new Map;activeEventIdleTimer=null;activeEventHardTimer=null;activeEventPostReplyTimer=null;activeEventPostReplyWatcher=null;activeEventPostReplyPoll=null;rescueSettleTimer=null;stopHookBarrierSessionId=null;stopHookBarrierTimer=null;selfDrivenActive=!1;selfDrivenLastSignalAt=0;selfDrivenSweepTimer=null;selfDrivenReported=!1;selfDrivenReportTimer=null;selfDrivenLabel=null;selfDrivenTextOffset=null;selfDrivenDeliverTimer=null;selfDrivenReplied=!1;compacting=!1;compactingTimer=null;compactionDoneResolver=null;mcpServerReady=!1;mcpStartupFailureHandled=!1;mcpChannelBroken=!1;channelGateClosed=!1;startupChannelListening=!1;startupChannelListeningAt=0;startupDialogSeenAt=0;windowsTrustDialogAnswered=!1;windowsTrustDialogTimer=null;devChannelsConfirmTimer=null;ptyDialogBusy=!1;pendingMcpFailureTimer=null;sessionIdConflictDetected=!1;sessionIdConflictRetriedEventIds=new Set;malformedToolRetriedEventIds=new Set;lostInjectionRetriedEventIds=new Set;runtimeResolver=null;activityManager=null;deferredModelId=null;claudeCliCapabilities=null;claudeChildPid=0;claudeCliSessionId="";claudeSessionCwd="";claudeMcpConfigPath="";expectRunDir="";auditEvidencePaths=null;sessionState=null;authFailureUntil=0;usageLimitUntil=0;completedEventIds=new Map;pendingQuestion=new Map;pendingPermissions=new Map;lastClearedEvent=null;textForwardSeq=0;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 Dt,this.internalApi.setInvokeHandler(async(e,t,i,s)=>this.handleInternalInvoke(e,t,i,s)),this.internalApi.setStatusLineHandler(async e=>{this.handleStatusLineUpdate(e)}),await this.internalApi.start(0),this.internalApi.setMcpBridgeUpHandler(e=>this.onMcpBridgeUp(e)),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})`)}onMcpBridgeUp(e){this.bridgeCallbacks.sendMcpFrame?.(e)}deliverMcpFrameToAgent(e){this.internalApi?.sendMcpFrameToBridge(e)}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.claudeCliSessionId&&Nt(this.claudeCliSessionId),this.stopSelfDriven(),this.clearSelfDrivenDeliverTimer(),this.clearStopHookBarrier(),this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver("stopped"),this.compactionDoneResolver=null),this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.startupDialogSeenAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.clearDevChannelsConfirmTimer(),this.ptyDialogBusy=!1,this.terminalPermissionKeyTimer&&(clearTimeout(this.terminalPermissionKeyTimer),this.terminalPermissionKeyTimer=null),this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1,this.pendingPermissions.size>0){const s=w(),n=new z(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&&(q(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{}q(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.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 ki(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&&!ui(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,backgroundBusy:this.selfDrivenReported,sessions:0,details:this.sessionState?{sessionState:this.sessionState}:void 0}}getActiveEventIds(){return this.activeEvent?[this.activeEvent.eventId]:[]}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.activeEvent&&this.clearActiveEvent()}getSessionState(){return this.sessionState}getMcpConfig(){return null}async hasBackgroundWork(){const e=this.claudeProcess?.pid??this.claudePty?.pid;if(!e)return!1;const t=[this.claudeProcess?.pid,this.claudeChildPid||void 0,this.claudePty?.pid].filter(i=>!!i&&i>0);return ht(e,t)}async probe(e){const t=this.config.command||"claude",i=await Ht(t),s=i!==null;let n=null,r;if(s){const h=await qt(t);n=h.version,h.error&&(r=h.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const l=(Ut().ANTHROPIC_BASE_URL??process.env.ANTHROPIC_BASE_URL??"").trim()||null,c=(this.sessionState?.model?.id??(process.env.ANTHROPIC_MODEL??"").trim())||null;let u={attempted:!1,ok:!1,latency_ms:null};if(e?.conversation&&s){const h=Date.now();try{const p=ut(dt),m=["-p","ping","--output-format","json"];this.getClaudeCliCapabilities(t).maxTurns&&m.push("--max-turns","1");const v=we(t,m);await p(v.command,v.args,{timeout:e.timeoutMs??8e3,encoding:"utf-8",windowsVerbatimArguments:v.windowsVerbatimArguments,env:Q()}),u={attempted:!0,ok:!0,latency_ms:Date.now()-h}}catch(p){const m=p,v=m.killed?"conversation_timeout":"conversation_failed";u={attempted:!0,ok:!1,latency_ms:Date.now()-h,error:{code:v,message:m.message??String(p)}}}}return{cli:{command:t,installed:s,path:i,version:n,...r?{error:r}:{}},conversation:u,config:{model:c,base_url:l,source:{model:this.sessionState?.model?.id?"runtime":process.env.ANTHROPIC_MODEL?"env":"unknown",base_url:l?"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=x(e,this.claudeSessionCwd);try{const i=k(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=Mt({mode:"claude",projectDir:this.claudeSessionCwd}),r=n.map(a=>{const l=a.trigger?` (${a.trigger})`:"",c=a.pluginName?` [plugin:${a.pluginName}]`:` [${a.source}]`;return`- ${a.name}${l}${c}: ${a.description}`});return{status:"ok",message:r.length>0?r.join(`
|
|
1
|
+
import{spawn as re,spawnSync as ae,execSync as oe,execFile as pt}from"node:child_process";import{promisify as mt}from"node:util";import{randomUUID as K}from"node:crypto";import{killProcessGroup as N,hasChildProcesses as vt,resolveCommandPath as gt,resolveWindowsExecInvocation as Ce}from"../../core/runtime/spawn.js";import{chmodSync as le,readdirSync as ce,readFileSync as B,realpathSync as Ae,rmSync as Et,statSync as k,truncateSync as _t,existsSync as P,openSync as St,writeSync as yt,closeSync as wt,renameSync as Ie,mkdirSync as be,constants as ke,watch as Pt}from"node:fs";import{appendFile as Tt,mkdir as O,readFile as I,rm as Re,stat as De,writeFile as R}from"node:fs/promises";import{dirname as $e,isAbsolute as Ct,join as f,resolve as At}from"node:path";import{homedir as D,tmpdir as It}from"node:os";import de from"node:net";import{EventEmitter as Oe}from"node:events";import{fileURLToPath as bt}from"node:url";let Y=null;if(process.platform==="win32")try{Y=await import("node-pty")}catch{Y=null}import{resolveRuntimePaths as S}from"../../core/config/index.js";import{normalizeClaudeEffort as kt,normalizeClaudeEnvEffort as Rt}from"../../core/config/claude-direct-env.js";import{SESSION_MODE_IDS as U}from"./protocol-contract.js";import{buildSessionContextBlock as Dt}from"../shared/session-context.js";import{log as o}from"../../core/log/index.js";import{ActivityStatusManager as $t}from"./activity-status-manager.js";import{HookSignalStore as Ot}from"../../core/hooks/hook-signal-store.js";import{QuestionStore as xe}from"../../core/persistence/question-store.js";import{PermissionStore as W}from"../../core/persistence/permission-store.js";import{InternalApiServer as xt}from"../../core/mcp/internal-api-server.js";import{executeEventTool as Le,isEventTool as Lt}from"../../core/mcp/event-tool-executor.js";import{validateToolArgs as Mt}from"../../core/mcp/tool-schemas.js";import{isGrixInternalToolName as Ft,normalizeEventToolArgs as Nt}from"../../core/mcp/tools.js";import{scanSkills as jt}from"./skill-scanner.js";import{syncDefaultSkillsToDir as Bt}from"../../default-skills/index.js";import{clearSessionJsonlDriftCache as Ut,countPendingBackgroundTasks as Ht,noteSessionJsonlPath as qt,extractLastAssistantEntry as z,extractTextBlocksAfterOffset as Me,hasTerminalToolResultAfterOffset as Fe,probeSessionTurnState as ue,resolveSessionJsonlPath as x}from"./usage-parser.js";import{readSettingsEnv as Gt}from"./model-list.js";import{resolveCliPath as Wt,getCliVersion as zt}from"../../core/util/cli-probe.js";import{GRIX_RELAY_ANTHROPIC_API_KEY as Ne}from"../../core/proxy/index.js";const j="grix",V={developmentChannels:!0,maxTurns:!0};function Jt(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 je(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}`,l=String(r.header??r.question??a).trim()||a,c=String(r.prompt??r.question??"").trim();if(!c)continue;const u=Jt(r.options),h=r.multiSelect===!0||r.multi_select===!0;i.push({header:l,prompt:c,...u?{options:u}:{},...h?{multi_select:!0}:{}})}return i.length>0?i:null}function Kt(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 Yt=[/Please run \/login/,/API Error:\s*401/,/authentication_error/,/OAuth token has expired/],Vt=[/API Error:\s*401/,/authentication_error/],Qt=[/You're out of extra usage/i,/Stop and wait for limit to reset/i,/Add funds to continue with extra usage/i],Xt=/API Error:\s*400.*(server_tool_use\.id|messages\.\d+\.content)/;function he(d){const e=d?.trim();return e&&!e.startsWith("API Error:")?e:"Claude hit an API format error. Please start a new conversation (/grix open <dir>)."}const Be=300*1e3,Ue=300*1e3,He=Ue+30*1e3,qe=3e3,Zt=50,ei=1800*1e3,ti=["CLAUDE_CODE_ENABLE_TELEMETRY","CLAUDE_CODE_ENHANCED_TELEMETRY_BETA","OTEL_LOGS_EXPORTER","OTEL_TRACES_EXPORTER","OTEL_METRICS_EXPORTER","OTEL_EXPORTER_OTLP_PROTOCOL","OTEL_EXPORTER_OTLP_ENDPOINT","OTEL_EXPORTER_OTLP_HEADERS","OTEL_LOGS_EXPORT_INTERVAL","OTEL_TRACES_EXPORT_INTERVAL","OTEL_LOG_USER_PROMPTS","OTEL_LOG_ASSISTANT_RESPONSES","OTEL_LOG_TOOL_DETAILS","OTEL_LOG_TOOL_CONTENT","OTEL_LOG_RAW_API_BODIES"];function Q(d=process.env){const e={...d},t=new Set(ti.map(i=>i.toLowerCase()));for(const i of Object.keys(e))t.has(i.toLowerCase())&&delete e[i];return e}const Ge=60*1e3,We="lost injection respawn",ze=600*1e3,fe=10800*1e3,ii=5e3,si=250;function Je(d,e){const t=Number(process.env[d]);return Number.isFinite(t)&&t>0?t:e}function Ke(d){return d.trim().replace(/[^a-zA-Z0-9._-]+/gu,"_")||"unknown"}function ni(d){const e=gt("expect",d);return Ct(e)?e:null}function X(d){try{return P(d)?k(d).size:0}catch{return 0}}function Ye(d){const e=[],t=i=>{let s;try{s=ce(i,{withFileTypes:!0})}catch{return}for(const n of s){const r=f(i,n.name);n.isDirectory()?t(r):n.isFile()&&e.push(r)}};return t(d),e.sort((i,s)=>Ve(i)-Ve(s)||i.localeCompare(s))}function Ve(d){try{return k(d).mtimeMs}catch{return 0}}const Qe=Je("GRIX_RESCUE_SETTLE_POLL_MS",2e3),Xe=Je("GRIX_RESCUE_SETTLE_BUDGET_MS",12e4),ri=300*1e3,ai="The model's tool call could not be parsed (retry also failed).",oi="[\u7CFB\u7EDF\u81EA\u52A8\u91CD\u8BD5] \u4F60\u4E0A\u4E00\u6761\u56DE\u590D\u7684\u5DE5\u5177\u8C03\u7528\u89E3\u6790\u5931\u8D25\uFF0C\u6CA1\u6709\u53D1\u51FA\u53BB\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6267\u884C\u5DF2\u7ECF\u5B8C\u6210\u7684\u64CD\u4F5C\uFF0C\u76F4\u63A5\u91CD\u65B0\u8C03\u7528 reply \u5DE5\u5177\uFF0C\u628A\u4F60\u4E0A\u4E00\u6761\u60F3\u53D1\u7ED9\u7528\u6237\u7684\u7ED3\u8BBA\u539F\u6837\u91CD\u65B0\u53D1\u9001\u4E00\u6B21\u3002",li="Sorry, the previous reply could not be generated properly (the model's tool call failed to parse). Please send it again, and use /grix restart to restart the session if needed.",ci=2*1e3,pe=90*1e3,Ze=1800*1e3,et=15*1e3,di=60*1e3,tt=10*1e3,ui=30*1e3,it=30*1e3,hi=2e3,fi=3e4;function pi(d){const e=d.tool_name||"";if(e==="mcp__grix__grix_dispatch_agent")return"\u540E\u53F0\u534F\u8C03\u5B50 agent";if(e.startsWith("mcp__grix__"))return"\u540E\u53F0\u8C03\u7528 Grix \u5DE5\u5177";if(e.startsWith("mcp__"))return"\u540E\u53F0\u8C03\u7528\u5DE5\u5177";switch(e){case"Bash":return"\u540E\u53F0\u6267\u884C\u547D\u4EE4";case"Read":case"Edit":case"Write":case"NotebookEdit":return"\u540E\u53F0\u8BFB\u5199\u6587\u4EF6";case"Task":return"\u540E\u53F0\u8FD0\u884C\u5B50\u4EFB\u52A1";default:return e?`\u540E\u53F0\u8FD0\u884C\uFF1A${e}`:"\u540E\u53F0\u4EFB\u52A1\u8FDB\u884C\u4E2D"}}function mi(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}const vi=12e4,gi=3e4,Ei=6e4,_i=3e3,Z=1e3,st=45e3,Si=18e3,me=8192,yi=1e3,wi=2e3,nt=300,Pi=3e4,Ti=2e3,Ci=2e3,Ai=/(do you want to proceed\?[\s\S]*?\d\.\s*yes)|(only you can approve)/i,Ii=/(do you want to proceed)|(only you can approve)|(\d\.\s*yes)|(\d\.\s*no)|(esc to cancel)|(tab to amend)/i,bi=/^[✳✶✻✽✵❋✺✴❈❖✦✧✢◉◎⬥⬦◇◆▸▹►▻→←↑↓⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·…\d]*still\s+thinking/i,ve="__grix_key__ ";let rt=!1;const ge=new Set;async function ki(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=de.createServer();r.once("error",n),r.listen(0,"127.0.0.1",()=>{const a=r.address(),l=typeof a=="object"&&a?a.port:0;r.close(c=>{if(c){n(c);return}s(l)})})});if(i>0&&!e.has(i)&&!ge.has(i))return ge.add(i),i}throw new Error("\u65E0\u6CD5\u5206\u914D MCP \u901A\u77E5\u7AEF\u53E3")}function Ri(d){d>0&&ge.delete(d)}const Di=["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>.',"When present, the channel metadata includes context_messages_json \u2014 a JSON array of earlier visible messages for this trigger; each entry carries sender_id and content. An entry whose content starts with [\u5F15\u7528\u6D88\u606F] is the quoted (replied-to) message being responded to. Use these records as context (prefer them over inferring from quoted_message_id alone), in group chats use sender_id to tell who said what, and only answer the current message.","Local transcript availability, session binding, recovery mode, and connector history-loss diagnostics are internal operational details. Do not mention them, ask the user to choose a recovery mode, or say that history/context was lost unless the user explicitly asks to debug that mechanism.",'Both your plain text and the reply tool are delivered to the user. You are talking directly to the user, so address them in the second person ("you"); do not slip into third-person narration about them (e.g. "\u5DF2\u7ECF\u628A\u7ED3\u8BBA\u56DE\u590D\u7ED9\u8001\u90ED\u4E86") \u2014 say it straight to them ("\u7ED3\u8BBA\u662F\u2026\u2026").',"While you work, use plain text for short progress notes. Deliver your final conclusion \u2014 the answer the user is waiting for \u2014 through the reply tool; that is the message the user treats as your result and the one the connector quotes. Your plain text reaches the user too \u2014 it is not private scratch space, so it is a real channel for progress and for anything the user needs mid-turn; you just need not restate the full conclusion as plain text once it is in the reply. The connector automatically quotes the message you are answering, so you normally do not need to set reply_to (set it only to quote a different earlier message).","Make the reply tool call the last thing you do in a turn and put your whole conclusion inside it: once you have called reply, any further text you write in the same turn is dropped, not delivered. Progress notes go before the reply; the reply ends the turn.",'Never explain the delivery mechanics to the user or tell them you "already sent it via the reply tool" \u2014 that is internal plumbing they neither see nor care about. If the user says they did not receive or cannot read something, do not insist you already sent it; assume the delivery or the format failed and send it again, switching format when that is the likely cause (e.g. render a diagram to an image, strip code fences, upload a file).',"If you intentionally do not want to send any visible message, call the complete tool with event_id and a final status.",'Do not send a bare acknowledgement or "got it / on it / starting now" message before doing the work; do the work first, then deliver the actual result through the reply tool. During a long-running task, write a short plain-text progress note when you reach a meaningful milestone so the user can see progress as it happens.',"You only run while handling a turn; once your turn ends you are frozen and cannot send anything until the user messages you again.",'Unbreakable rule: never end a turn having promised something you cannot deliver. In particular, never start a task, detach it (nohup, a trailing &, any background process or watcher), end the turn, and promise to "notify when it finishes" \u2014 that notification can never happen, so do not promise it.',"For any task whose result the user is waiting on (deploy, build, rollout, tests), run it in the foreground and wait for it to finish within this same turn, then report the real outcome. You may launch several in the background at once for parallelism, but you must still collect all of their results within this same turn before you reply and finish.","Two cases where leaving a process running is correct: a long-lived service that is meant to keep running (dev server, daemon) \u2014 background it, then report that it started plus how to check or stop it; and a task too long to finish in one turn \u2014 you may leave it running, but state plainly that you cannot auto-notify and give the user a concrete way to retrieve the result later (a log path, a PID, or asking them to ping you to re-check)."];function $i(d,e,t){const i=[...Di];e&&i.unshift(Dt(e,t));try{const s=d?.agentName?.trim().slice(0,200),n=d?.introduction?.trim().slice(0,2e3);if(s||n){const r=[s?`Your name is "${s}".`:"",n?`Your self-introduction: ${n}`:""].filter(Boolean).join(" ");i.unshift(r)}}catch{}return i.join(" ")}function at(d){return String(d??"").trim().toLowerCase()===U.approval?U.approval:U.fullAuto}class As extends Oe{type="claude";config;bridgeCallbacks;mcpServerProcess=null;internalApi=null;claudeProcess=null;claudePty=null;singleTurnFallbackProcesses=new WeakSet;singleTurnFallbackPtys=new WeakSet;lostInjectionKilledProcesses=new WeakSet;lostInjectionKilledPtys=new WeakSet;singleTurnFallbackChild=null;singleTurnFallbackEventId=null;spawnPromise=null;lifecycleVersion=0;sessionId="";alive=!1;stopped=!1;activeEvent=null;completedAuditBoundaries=new Map;activeEventIdleTimer=null;activeEventHardTimer=null;activeEventPostReplyTimer=null;activeEventPostReplyWatcher=null;activeEventPostReplyPoll=null;rescueSettleTimer=null;stopHookBarrierSessionId=null;stopHookBarrierTimer=null;selfDrivenActive=!1;selfDrivenLastSignalAt=0;selfDrivenSweepTimer=null;selfDrivenReported=!1;selfDrivenReportTimer=null;selfDrivenLabel=null;selfDrivenTextOffset=null;selfDrivenDeliverTimer=null;selfDrivenReplied=!1;compacting=!1;compactingTimer=null;compactionDoneResolver=null;mcpServerReady=!1;mcpStartupFailureHandled=!1;mcpChannelBroken=!1;channelGateClosed=!1;startupChannelListening=!1;startupChannelListeningAt=0;startupDialogSeenAt=0;windowsTrustDialogAnswered=!1;windowsTrustDialogTimer=null;devChannelsConfirmTimer=null;ptyDialogBusy=!1;pendingMcpFailureTimer=null;sessionIdConflictDetected=!1;sessionIdConflictRetriedEventIds=new Set;malformedToolRetriedEventIds=new Set;lostInjectionRetriedEventIds=new Set;runtimeResolver=null;activityManager=null;deferredModelId=null;claudeCliCapabilities=null;claudeChildPid=0;claudeCliSessionId="";claudeSessionCwd="";claudeMcpConfigPath="";expectRunDir="";auditEvidencePaths=null;sessionState=null;authFailureUntil=0;usageLimitUntil=0;completedEventIds=new Map;pendingQuestion=new Map;pendingPermissions=new Map;lastClearedEvent=null;textForwardSeq=0;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 xt,this.internalApi.setInvokeHandler(async(e,t,i,s)=>this.handleInternalInvoke(e,t,i,s)),this.internalApi.setStatusLineHandler(async e=>{this.handleStatusLineUpdate(e)}),await this.internalApi.start(0),this.internalApi.setMcpBridgeUpHandler(e=>this.onMcpBridgeUp(e)),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})`)}onMcpBridgeUp(e){this.bridgeCallbacks.sendMcpFrame?.(e)}deliverMcpFrameToAgent(e){this.internalApi?.sendMcpFrameToBridge(e)}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.singleTurnFallbackChild&&this.killSingleTurnFallbackChild(this.singleTurnFallbackChild),this.activeEvent&&(this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"canceled","adapter stopped"),this.clearActiveEvent()),this.stopComposing(),this.claudeCliSessionId&&Ut(this.claudeCliSessionId),this.stopSelfDriven(),this.clearSelfDrivenDeliverTimer(),this.clearStopHookBarrier(),this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null),this.compactionDoneResolver&&(this.compactionDoneResolver("stopped"),this.compactionDoneResolver=null),this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.startupDialogSeenAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.clearDevChannelsConfirmTimer(),this.ptyDialogBusy=!1,this.terminalPermissionKeyTimer&&(clearTimeout(this.terminalPermissionKeyTimer),this.terminalPermissionKeyTimer=null),this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1,this.pendingPermissions.size>0){const s=S(),n=new W(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();Re(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&&(N(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{}N(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.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 Oi(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&&!mi(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,backgroundBusy:this.selfDrivenReported,sessions:0,details:this.sessionState?{sessionState:this.sessionState}:void 0}}getActiveEventIds(){return this.activeEvent?[this.activeEvent.eventId]:[]}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.activeEvent&&this.clearActiveEvent()}getSessionState(){return this.sessionState}getMcpConfig(){return null}async hasBackgroundWork(){const e=this.claudeProcess?.pid??this.claudePty?.pid;if(!e)return!1;const t=[this.claudeProcess?.pid,this.claudeChildPid||void 0,this.claudePty?.pid].filter(i=>!!i&&i>0);return vt(e,t)}async probe(e){const t=this.config.command||"claude",i=await Wt(t),s=i!==null;let n=null,r;if(s){const h=await zt(t);n=h.version,h.error&&(r=h.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const l=(Gt().ANTHROPIC_BASE_URL??process.env.ANTHROPIC_BASE_URL??"").trim()||null,c=(this.sessionState?.model?.id??(process.env.ANTHROPIC_MODEL??"").trim())||null;let u={attempted:!1,ok:!1,latency_ms:null};if(e?.conversation&&s){const h=Date.now();try{const p=mt(pt),m=["-p","ping","--output-format","json"];this.getClaudeCliCapabilities(t).maxTurns&&m.push("--max-turns","1");const v=Ce(t,m);await p(v.command,v.args,{timeout:e.timeoutMs??8e3,encoding:"utf-8",windowsVerbatimArguments:v.windowsVerbatimArguments,env:Q()}),u={attempted:!0,ok:!0,latency_ms:Date.now()-h}}catch(p){const m=p,v=m.killed?"conversation_timeout":"conversation_failed";u={attempted:!0,ok:!1,latency_ms:Date.now()-h,error:{code:v,message:m.message??String(p)}}}}return{cli:{command:t,installed:s,path:i,version:n,...r?{error:r}:{}},conversation:u,config:{model:c,base_url:l,source:{model:this.sessionState?.model?.id?"runtime":process.env.ANTHROPIC_MODEL?"env":"unknown",base_url:l?"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=x(e,this.claudeSessionCwd);try{const i=k(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=jt({mode:"claude",projectDir:this.claudeSessionCwd}),r=n.map(a=>{const l=a.trigger?` (${a.trigger})`:"",c=a.pluginName?` [plugin:${a.pluginName}]`:` [${a.source}]`;return`- ${a.name}${l}${c}: ${a.description}`});return{status:"ok",message:r.length>0?r.join(`
|
|
2
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)if(e==="compact"){try{await this.ensureClaudeProcessReady()}catch(n){return{status:"failed",message:`Failed to start Claude for compact: ${n instanceof Error?n.message:n}`}}if(await new Promise(n=>setTimeout(n,2e3)),!this.claudeProcess&&!this.claudePty)return{status:"failed",message:"Claude process exited during startup"};try{await this.waitForChannelReady()}catch(n){return{status:"failed",message:`Claude channel not ready for compact: ${n instanceof Error?n.message:n}`}}}else 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.expectRunDir?this.writeExpectFifoLine(this.expectRunDir,s):this.claudeProcess?.stdin?.write(`${s}
|
|
3
|
-
`),e==="compact"){const n=new Promise(a=>{this.compactionDoneResolver=a});this.beginCompaction();const r=await n;return r==="process-exit"?{status:"failed",message:"Claude exited during compaction"}:r==="stopped"?{status:"failed",message:"Adapter stopped during compaction"}:{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}`}}}writeExpectFifoLine(e,t){const i=f(e,"cmd.fifo");let s;try{s=
|
|
4
|
-
`)}finally{Et(s)}}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?P(t.used_percentage):null,remainingPercentage:t?.remaining_percentage!=null?P(t.remaining_percentage):null,totalInputTokens:P(t?.total_input_tokens),totalOutputTokens:P(t?.total_output_tokens),contextWindowSize:P(t?.context_window_size)||2e5,currentUsage:r?{inputTokens:P(r.input_tokens),outputTokens:P(r.output_tokens),cacheCreationInputTokens:P(r.cache_creation_input_tokens),cacheReadInputTokens:P(r.cache_read_input_tokens)}:null},cost:{totalCostUsd:P(i?.total_cost_usd),totalDurationMs:P(i?.total_duration_ms),totalApiDurationMs:P(i?.total_api_duration_ms),totalLinesAdded:P(i?.total_lines_added),totalLinesRemoved:P(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,l=this.sessionState.rateLimits?.sevenDay;o.info("claude-adapter",`[rate-limits] statusLine parsed: fiveHour=${a?`${a.usedPercentage}% resetsAt=${a.resetsAt}`:"n/a"} sevenDay=${l?`${l.usedPercentage}% resetsAt=${l.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=P(r.used_percentage??r.usedPercent),l=P(r.resets_at??r.resetsAt);if(!(a<=0&&l<=0))return{usedPercentage:a,resetsAt:l}},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?.eventId===e.event_id){o.info("claude-adapter",`Event ${e.event_id} ignored: same as active event`);return}if(this.activeEvent||this.compacting||this.stopHookBarrierSessionId===e.session_id){o.error("claude-adapter",`Scheduler invariant violated: event ${e.event_id} delivered while busy (active=${this.activeEvent?.eventId??"none"}, compacting=${this.compacting}, barrier=${this.stopHookBarrierSessionId===e.session_id}) \u2014 failing event to release slot`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent busy (scheduler invariant violated)");return}this.activeEvent={eventId:e.event_id,sessionId:e.session_id,rawEvent:e},this.stopSelfDriven(),this.clearSelfDrivenDeliverTimer(),this.lastClearedEvent=null,this.markActiveEventActivity(e.event_id,e.session_id),this.resetActiveEventHardTimer(e.event_id),this.emit("eventStarted",e.event_id,e.session_id),this.ensureClaudeAndPushEvent(e)}deliverStopEvent(e,t){if(this.activeEvent?.eventId!==e){o.info("claude-adapter",`Stop for non-active event=${e} (active=${this.activeEvent?.eventId??"none"}, compacting=${this.compacting}) \u2014 emitting eventDone to unblock platform`),this.emit("eventDone",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:Y()}),(this.claudeProcess||this.claudePty)&&this.emit("pauseIntake","restart"),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??"");if(t==="claude_interaction_reply"){const i=e.params??{};if(String(i.kind??"")==="permission"){const n=i.resolution??{},r=String(n.value??""),a={...e,action_type:r==="allow"?"exec_approve":"exec_reject",params:{...i,approval_command_id:i.request_id}};return this.handlePermissionApproval(a)}return this.handleQuestionReply(e)}return 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=w(),n=new Re(s.questionRequestsDir),r=await n.getRequest(i),a=Number(r?.created_at??0),l=a>0&&Date.now()-a>Ne;if(!r||r.resolved||l){o.warn("claude-adapter",`Question reply has no pending waiter: request_id=${i} exists=${!!r} resolved=${r?.resolved===!0} expired=${l}`);const v=this.pendingQuestion.get(i);return v&&this.activeEvent?.eventId===v.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"}}const c=t.resolution??{},u=String(c.type??""),h=c;if(u==="action"&&String(c.value??"")==="cancel"){o.info("claude-adapter",`Question cancelled by user: request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,h);const g=this.pendingQuestion.get(i);return g&&this.activeEvent?.eventId===g.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 p="";if(u==="text"?p=String(c.value??""):u==="map"&&(p=(Array.isArray(c.entries)?c.entries:[]).map(g=>g.value).join(", ")),!p){o.warn("claude-adapter",`Empty answer for question reply request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,h);const v=this.pendingQuestion.get(i);return v&&this.activeEvent?.eventId===v.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=${p.slice(0,80)}`),await n.resolveRequest(i,"answer",p,h);const m=this.pendingQuestion.get(i);return m&&this.activeEvent?.eventId===m.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=w(),a=new z(r.permissionRequestsDir),l=s?"allow":"deny";return await a.resolveRequest(i,l),this.pendingPermissions.delete(i),this.scheduleTerminalPermissionKey(i,l),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok"),o.info("claude-adapter",`Permission ${l}: approvalId=${i}`),{handled:!0,kind:"permission_approval"}}async handleExecApprovalEvent(e){const t=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");if(!t)return{delivered:!1,errorCode:"approval_id_required",errorMsg:"approval_id is required"};if(!this.pendingPermissions.get(t))return{delivered:!1,errorCode:"approval_not_found",errorMsg:`no pending permission for approval_id: ${t}`};const i=e.decision==="deny"?"deny":"allow",s=w();return await new z(s.permissionRequestsDir).resolveRequest(t,i),this.pendingPermissions.delete(t),this.scheduleTerminalPermissionKey(t,i),o.info("claude-adapter",`Permission ${i} (text event): approvalId=${t}`),{delivered:!0}}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.isChannelGateClosed()){await this.runSingleTurnFallback(e,"channel gate closed: tengu_harbor not enabled in cachedGrowthBookFeatures");return}if(!this.getClaudeCliCapabilities(this.config.command||"claude").developmentChannels){await this.runSingleTurnFallback(e,"claude CLI does not support development channels");return}if(await this.ensureClaudeProcessReady(),await this.waitForChannelReady(),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",this.bridgeCallbacks.getAgentId?.()],["attachments_json",e.attachments_json],["context_messages_json",st(e.context_messages_json)??e.context_messages_json]];for(const[a,l]of n)l!=null&&l!==""&&(s[a]=l);this.captureEventJsonlBaseOffset(e.event_id,this.activeEvent?.textForwardOffset===void 0?{force:!0}:void 0);const r=e.content??"";this.pushNotification("notifications/claude/channel",{content:r,meta:s}),this.activeEvent?.eventId===e.event_id&&(this.activeEvent.channelPushedAt=Date.now()),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(),ve(this.claudeCliSessionId,[]),await new Promise(a=>setTimeout(a,(t+1)*2e3)),this.ensureClaudeAndPushEvent(e,t+1);o.error("claude-adapter",`Failed to deliver event ${e.event_id}: ${s}`);let r=s;if(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(a){o.error("claude-adapter",`Single-turn fallback failed for ${e.event_id}: ${a instanceof Error?a.message:String(a)}`),r=a}}this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"failed",r instanceof Error?r.message:String(r)),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("channel ready check timed out")||t.includes("channels are not currently available")||t.includes("does not support development channels")||t.includes("unknown option")||t.includes("unknown or unexpected option")||t.includes("mcp stdio server not available")||/notify port\b.*\bnot ready/.test(t)||t.includes("file not found:"):!1}getClaudeCliCapabilities(e){return this.claudeCliCapabilities?this.claudeCliCapabilities:(this.claudeCliCapabilities=Bi(e),this.claudeCliCapabilities)}buildSingleTurnPrompt(e,t=!0){const i=t&&e.context_messages_json?st(e.context_messages_json)??String(e.context_messages_json):"",s=[e.content??""];return i&&(s.push("","Conversation context (JSON):"),s.push(i)),s.join(`
|
|
5
|
-
`)}extractSingleTurnDelta(e){const t=e.trim();if(!t)return null;let i;try{i=JSON.parse(t)}catch{return o.warn("claude-adapter",`Single-turn fallback: dropping non-JSON stdout noise: ${t.slice(0,200)}`),null}const s=i.type==="stream_event"&&i.event&&typeof i.event=="object"?i.event:i,n=String(s.type??"");if(n==="content_block_delta"){const r=s.delta;if(r&&typeof r=="object"){const a=String(r.text??"");if(a)return{text:a,final:!1}}return null}if(n==="result"){const r=String(s.subtype??""),a=String(s.terminal_reason??""),l=s.is_error===!0||a==="api_error";if(r&&r!=="success"||l){const u=Array.isArray(s.errors)?s.errors.join("; "):"",h=String(s.result??"").trim(),p=u||h||a;throw new Error(`claude single-turn result ${r||"error"}${p?`: ${p}`:""}`)}const c=String(s.result??"");return c?{text:c,final:!0}:null}return null}resolveEventAuditConfig(e,t){if(e.audit?.enabled===!0)return e.audit;const i=t?.audit;if(i?.enabled!==!0)return;const s=i.profile??"full";return{enabled:!0,profile:s,capture:i.capture??(s==="usage"?{inputOutput:!1,tools:!1,subagents:!0,thinking:!1,rawProviderBody:i.rawProviderBody===!0}:{inputOutput:!0,tools:!0,subagents:!0,thinking:!1,rawProviderBody:i.rawProviderBody===!0})}}buildClaudeRuntimeEnv(e=this.resolveSessionRuntime()){const t={...Q(),...this.config.env};if(delete t.CLAUDECODE,t.CLAUDE_PLUGIN_DATA=
|
|
6
|
-
`,{encoding:"utf8",mode:384}),
|
|
7
|
-
`);for(;A>=0;){const
|
|
8
|
-
`)}}),E.stderr?.setEncoding("utf8"),E.stderr?.on("data",b=>{$.length>=fe||($+=b,$.length>fe&&($=$.slice(0,fe)))}),E.on("error",b=>{M(),T(b)}),E.on("close",b=>{if(M(),O.trim()&&ye(O),se){T(se);return}if(b!==0&&!U){const A=$.trim();T(new Error(A||`claude single-turn exited with code ${b}`));return}if(!U&&this.activeEvent?.eventId===e.event_id&&!this.isEventAnswered()){const A=$.trim();T(new Error(A||"claude single-turn produced no output"));return}U&&(J+=1,this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,"",J,!0,_e,Se)),_()})}),this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"responded"),this.clearActiveEvent())}async waitForChannelReady(){if(!this.mcpServerReady)throw new Error("MCP stdio server not available");await this.waitForNotifyPort(3e4),process.platform==="win32"?await this.waitForWindowsChannelReady(Ze):await this.waitForChannelListening(Ze)}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=it(s.modeId),l=String(s.modelId??"").trim(),c=String(s.cwd??"").trim();this.claudeSessionCwd=c;const u=String(s.claudeSessionId??"").trim()||Y();this.claudeCliSessionId=u,!s.claudeSessionId&&s.onSessionIdAssigned&&s.onSessionIdAssigned(u);const h=this.buildClaudeRuntimeEnv((()=>{const C=this.resolveEventAuditConfig(s,this.activeEvent?.rawEvent);return C?{...s,audit:C}:s})());let p=ot(u,c||void 0);if(p&<(u,c||void 0)&&(p=!1),String(s.claudeSessionId??"").trim()!==""&&!p&&o.warn("claude-adapter",`Claude local transcript missing for session ${u}; continuing silently with platform context`),p?ct(u,c||void 0):(ve(u,[]),ge(u)),this.runtimeResolver&&!c)throw new Error("Claude session binding missing cwd \u2014 run /grix open <working-directory> first");if(!c)throw new Error("Claude runtime cwd is required");await this.ensureWorkspaceTrust(c),await this.ensureClaudeOnboardingFlags(c),await this.ensureSkipDangerousPermissionPrompt(),await this.injectStatusLineSettings(c);let m=!1,v="",g=null;try{t(),this.notifyPort=await Ti([this.internalApiPort]),m=!0,t(),o.info("claude-adapter",`Allocated MCP notify port ${this.notifyPort} (internal API ${this.internalApiPort})`),await this.ensureStdioMcpServer(),t();const C=i.pluginDir||await this.ensureClaudePluginDir(),B=p?["--resume",u]:["--session-id",u],_=[...r,"--name",`grix-${this.sessionId}`,...B,"--plugin-dir",C,"--strict-mcp-config","--mcp-config",this.claudeMcpConfigPath];l&&(/^claude/i.test(l)?_.push("--model",l):(o.warn("claude-adapter",`Skipping --model ${l}: 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=l)),a===G.fullAuto&&_.push("--dangerously-skip-permissions"),_.push("--dangerously-load-development-channels",`server:${N}`);const T=bi(this.bridgeCallbacks.getAgentProfile?.(),p?void 0:this.sessionId,this.bridgeCallbacks.getAgentId?.());if(process.platform==="win32"){const S=T.replace(/</g,"[").replace(/>/g,"]").replace(/"/g,"'"),E=ji(this.claudeCliSessionId);await qi(E,S),_.push("--append-system-prompt-file",E)}else _.push("--append-system-prompt",T);if(process.platform==="win32")if(V){const S=Gi(),E=["/c",n,..._];o.info("claude-adapter",`Spawning Claude via PTY on win32: cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`);const M=V.spawn(S,E,{name:"xterm-256color",cols:120,rows:30,cwd:c,env:h,useConpty:!0,conptyInheritCursor:!1});this.claudePty=M,this.claudeChildPid=M.pid,g=null}else o.info("claude-adapter",`Spawning Claude via shell on win32 (node-pty unavailable): cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`),g=ne(n,_,{cwd:c,env:h,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",shell:!0,windowsHide:!0});else{o.info("claude-adapter",`Spawning via expect PTY: cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`);const S=ei(typeof h.PATH=="string"?h.PATH:void 0);if(!S)throw new Error("expect not found in PATH. Install it with: apt install expect / dnf install expect / brew install expect");const E=f(Ct(),`grix-claude-${Y()}`);await F(E,{recursive:!0}),this.expectRunDir=E;const{expectPath:M,pidPath:$}=await Li(E,n,_);v=$,t(),g=ne(S,[M],{cwd:c,env:h,stdio:["pipe","pipe","pipe"],detached:!0})}if(this.claudeProcess=g,this.clearPendingMcpFailureTimer(),this.mcpStartupFailureHandled=!1,this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.startupDialogSeenAt=0,this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.clearDevChannelsConfirmTimer(),this.ptyDialogBusy=!1,g&&g.on("error",S=>{o.error("claude-adapter","Claude process spawn error: "+S),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=g?.pid??0;else{const S=await Fi(g,v);if(t(),!Number.isFinite(S)||S<=0)throw new Error("failed to determine spawned Claude pid");this.claudeChildPid=S}if(!this.claudeChildPid||this.claudeChildPid<=0)throw new Error("failed to determine spawned Claude pid")}catch(C){if(g?.pid&&q(g,"SIGTERM"),this.claudePty){try{this.claudePty.kill()}catch{}this.claudePty=null}throw this.claudeProcess===g&&(this.claudeProcess=null),this.claudeChildPid=0,m&&this.releaseNotifyPortReservation(),this.stopMcpServer(),C}const L=this.claudeChildPid;o.info("claude-adapter","Claude child PID: "+L+(this.claudePty?" (via PTY)":"")),this.setupProcessOrPtyHandlers(),this.alive=!0}finalizeActiveEventOnProcessExit(e){if(!this.activeEvent||this.stopped)return;const t=this.isEventAnswered(),i=t?"responded":"failed",s=!t&&this.activeEvent.apiFormatError?ue(this.activeEvent.apiErrorText):void 0,n=t?void 0:s??`Claude process exited before completing its reply (${e})`;o.error("claude-adapter",`Claude process exited with active event ${this.activeEvent.eventId}, answered=${t}, sending ${i}`),s&&(this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,s,1,!1,`err_${this.activeEvent.eventId}`),this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,"",2,!0,`err_${this.activeEvent.eventId}`)),s?this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,n,void 0,!0):this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,n),this.clearActiveEvent()}setupProcessOrPtyHandlers(){if(this.claudeProcess){const e=this.claudeProcess;e.on("exit",(t,i)=>{if(o.info("claude-adapter",`Claude process exited (code=${t}, signal=${i})`),this.singleTurnFallbackProcesses.delete(e)){o.info("claude-adapter","Ignoring stale Claude process exit after lifecycle ownership transfer");return}if(this.lostInjectionKilledProcesses.delete(e)){o.info("claude-adapter","Ignoring expected Claude process exit after lost-injection respawn");return}this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()&&(this.activeEvent&&!this.stopped&&this.finalizeActiveEventOnProcessExit(`code=${t}, signal=${i}`),this.stopped||this.emit("exit",t),this.compacting&&this.finishCompaction("process-exit"))}),e.stdout?.on("data",t=>{this.claudeProcess===e&&this.handleClaudeOutput(t.toString())}),e.stderr?.on("data",t=>{if(this.claudeProcess!==e)return;const i=t.toString().trim();i&&o.info("claude-adapter",`[claude stderr] ${i}`),this.checkFailurePatterns(i,"stderr")})}if(this.claudePty){const e=this.claudePty;e.onExit(({exitCode:t,signal:i})=>{if(o.info("claude-adapter",`Claude PTY process exited (code=${t}, signal=${i})`),this.singleTurnFallbackPtys.delete(e)){o.info("claude-adapter","Ignoring stale Claude PTY exit after lifecycle ownership transfer");return}if(this.lostInjectionKilledPtys.delete(e)){o.info("claude-adapter","Ignoring expected Claude PTY exit after lost-injection respawn");return}this.claudePty=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()&&(this.activeEvent&&!this.stopped&&this.finalizeActiveEventOnProcessExit(`code=${t}, signal=${i}`),this.stopped||this.emit("exit",t),this.compacting&&this.finishCompaction("process-exit"))}),e.onData(t=>{this.claudePty===e&&(this.handleClaudeOutput(t),this.checkFailurePatterns(t,"pty"))})}}lastPtyOutputAt=0;ptyProbe={title:0,spinner:0,meaningful:0,lastLogAt:0,lastMeaningfulAt:0};recordPtyProbe(e){const t=Date.now();this.lastPtyOutputAt=t;const i=e.includes("]0;"),s=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").trim(),n=s.length<=3||/^[✳✶✻✽✵❋✺✴❈❖✦✧✢◉◎⬥⬦◇◆▸▹►▻→←↑↓⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·…\d]*still\s+thinking/i.test(s);if(i?this.ptyProbe.title++:!s||n?this.ptyProbe.spinner++:(this.ptyProbe.meaningful++,this.ptyProbe.lastMeaningfulAt=t),t-this.ptyProbe.lastLogAt>=2e3){const r=this.activeEvent?this.isEventAnswered()?"replied":"running":"none",a=this.ptyProbe.lastMeaningfulAt?t-this.ptyProbe.lastMeaningfulAt:-1;o.debug("claude-adapter",`[pty-probe] session=${this.sessionId??"?"} event=${r} win2s title=${this.ptyProbe.title} spinner=${this.ptyProbe.spinner} meaningful=${this.ptyProbe.meaningful} meaningfulGapMs=${a}`),this.ptyProbe.title=0,this.ptyProbe.spinner=0,this.ptyProbe.meaningful=0,this.ptyProbe.lastLogAt=t}}terminalPermissionPromptTail="";terminalPermissionPromptVisible=!1;terminalPermissionKeyTimer=null;trackTerminalPermissionPrompt(e){const t=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g," ").replace(/[\x00-\x1f\x7f-\x9f]/g," ").trim();if(t){if(Pi.test(t)){this.terminalPermissionPromptTail=`${this.terminalPermissionPromptTail} ${t}`.slice(-yi),wi.test(this.terminalPermissionPromptTail)&&(this.terminalPermissionPromptVisible=!0);return}t.length<=3||Ci.test(t)||(this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1)}}sendTerminalKey(e){const t=e==="enter"?"\r":"\x1B";try{if(this.claudePty)return this.claudePty.write(t),!0;if(this.expectRunDir)return this.writeExpectFifoLine(this.expectRunDir,`${pe}${e}`),!0}catch(i){o.warn("claude-adapter",`Failed to send terminal key ${e}: ${i instanceof Error?i.message:i}`)}return!1}scheduleTerminalPermissionKey(e,t){this.terminalPermissionKeyTimer&&clearTimeout(this.terminalPermissionKeyTimer),this.terminalPermissionKeyTimer=setTimeout(()=>{if(this.terminalPermissionKeyTimer=null,this.stopped||!this.terminalPermissionPromptVisible)return;const i=t==="allow"?"enter":"esc";this.sendTerminalKey(i)&&(this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1,o.info("claude-adapter",`Permission prompt still on terminal after ${t}, sent ${i} key: approvalId=${e}`))},Si),this.terminalPermissionKeyTimer.unref()}handleClaudeOutput(e){this.recordPtyProbe(e),this.trackTerminalPermissionPrompt(e),this.compacting&&this.resetCompactingActivityTimer();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,l=>`\\x${l.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 l=[this.claudeProcess?.pid,this.claudeChildPid,this.claudePty?.pid].filter(c=>!!c&&c>0);ve(a,l)}const s=t.replace(/\[[0-9;?]*[ -/]*[@-~]/g," ").replace(/[^a-zA-Z]+/g," ").toLowerCase(),n=s.replace(/ /g,"");if(this.claudePty&&!this.startupChannelListening&&!this.windowsTrustDialogAnswered&&/trust.*folder|quick.*safety.*check/.test(n)&&this.respondToWindowsTrustDialog(t),!this.startupDialogSeenAt&&!this.startupChannelListening&&/loadingdevelopmentchannels|usingthisforlocaldevelopment/.test(n)&&(this.startupDialogSeenAt=Date.now(),o.info("claude-adapter","Dev channels dialog rendered; restarting notify port wait window"),this.claudePty&&this.scheduleDevChannelsConfirm()),(/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)&&(this.channelGateClosed=!0,o.warn("claude-adapter",'Claude reports "Channels are not currently available" \u2014 channel gate (tengu_harbor) is closed for this account/model; switching to single-turn fallback')),!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()},mi))}}clearWindowsTrustDialogTimer(){this.windowsTrustDialogTimer&&(clearTimeout(this.windowsTrustDialogTimer),this.windowsTrustDialogTimer=null)}respondToWindowsTrustDialog(e){if(this.windowsTrustDialogAnswered||this.windowsTrustDialogTimer)return;const t=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,""),i=Oi.test(t),s=!i&&xi.test(t);!i&&!s||(this.windowsTrustDialogAnswered=!0,o.info("claude-adapter",`Auto-accepting workspace trust dialog (layout=${i?"noFirst":"yesFirst"})`),this.scheduleTrustDialogWrite(i,1e3))}scheduleTrustDialogWrite(e,t){this.windowsTrustDialogTimer=setTimeout(()=>{if(this.windowsTrustDialogTimer=null,this.stopped||!this.claudePty)return;if(this.ptyDialogBusy){this.scheduleTrustDialogWrite(e,et);return}this.ptyDialogBusy=!0;const i=e?"noFirst":"yesFirst";e?(this.writePtyKey(this.claudePty,"\x1B[B","Down","trust",i),this.windowsTrustDialogTimer=setTimeout(()=>{this.windowsTrustDialogTimer=null,this.claudePty&&!this.stopped&&this.writePtyKey(this.claudePty,"\r","Enter","trust",i),this.ptyDialogBusy=!1},400),this.windowsTrustDialogTimer.unref()):(this.writePtyKey(this.claudePty,"\r","Enter","trust",i),this.ptyDialogBusy=!1)},t),this.windowsTrustDialogTimer.unref()}writePtyKey(e,t,i,s,n){try{e.write(t),o.info("claude-adapter",`PTY key sent: ${i} (dialog=${s}${n?`, layout=${n}`:""})`)}catch(r){o.warn("claude-adapter",`Failed to write PTY key ${i} for dialog=${s}: ${r instanceof Error?r.message:r}`)}}scheduleDevChannelsConfirm(){this.devChannelsConfirmTimer||(this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),gi),this.devChannelsConfirmTimer.unref())}tryDevChannelsConfirm(){if(this.devChannelsConfirmTimer=null,this.stopped||!this.claudePty||this.startupChannelListening)return;if(this.ptyDialogBusy){this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),et),this.devChannelsConfirmTimer.unref();return}this.ptyDialogBusy=!0,this.writePtyKey(this.claudePty,"\r","Enter","devChannels"),this.ptyDialogBusy=!1,Date.now()-(this.startupDialogSeenAt||Date.now())<_i&&(this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),Ei),this.devChannelsConfirmTimer.unref())}clearDevChannelsConfirmTimer(){this.devChannelsConfirmTimer&&(clearTimeout(this.devChannelsConfirmTimer),this.devChannelsConfirmTimer=null)}checkFailurePatterns(e,t="stderr"){/Session ID (\S+) is already in use/i.test(e)&&(this.sessionIdConflictDetected=!0);const s=(t==="pty"?Jt:Wt).some(n=>n.test(e));s&&this.isEventAnswered()?o.warn("claude-adapter",`Ignoring ${t} auth failure text after current event was answered`):s&&(o.error("claude-adapter",`Auth failure: ${e}`),this.authFailureUntil=Date.now()+Me,this.activeEvent&&(this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,`
|
|
3
|
+
`),e==="compact"){const n=new Promise(a=>{this.compactionDoneResolver=a});this.beginCompaction();const r=await n;return r==="process-exit"?{status:"failed",message:"Claude exited during compaction"}:r==="stopped"?{status:"failed",message:"Adapter stopped during compaction"}:{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}`}}}writeExpectFifoLine(e,t){const i=f(e,"cmd.fifo");let s;try{s=St(i,ke.O_WRONLY|ke.O_NONBLOCK)}catch(n){const r=n.code;throw new Error(r==="ENXIO"?"expect process is not running \u2014 cannot inject command":`FIFO open failed: ${n instanceof Error?n.message:n}`)}try{yt(s,`${t}
|
|
4
|
+
`)}finally{wt(s)}}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(t.used_percentage):null,remainingPercentage:t?.remaining_percentage!=null?T(t.remaining_percentage):null,totalInputTokens:T(t?.total_input_tokens),totalOutputTokens:T(t?.total_output_tokens),contextWindowSize:T(t?.context_window_size)||2e5,currentUsage:r?{inputTokens:T(r.input_tokens),outputTokens:T(r.output_tokens),cacheCreationInputTokens:T(r.cache_creation_input_tokens),cacheReadInputTokens:T(r.cache_read_input_tokens)}:null},cost:{totalCostUsd:T(i?.total_cost_usd),totalDurationMs:T(i?.total_duration_ms),totalApiDurationMs:T(i?.total_api_duration_ms),totalLinesAdded:T(i?.total_lines_added),totalLinesRemoved:T(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,l=this.sessionState.rateLimits?.sevenDay;o.info("claude-adapter",`[rate-limits] statusLine parsed: fiveHour=${a?`${a.usedPercentage}% resetsAt=${a.resetsAt}`:"n/a"} sevenDay=${l?`${l.usedPercentage}% resetsAt=${l.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=T(r.used_percentage??r.usedPercent),l=T(r.resets_at??r.resetsAt);if(!(a<=0&&l<=0))return{usedPercentage:a,resetsAt:l}},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?.eventId===e.event_id){o.info("claude-adapter",`Event ${e.event_id} ignored: same as active event`);return}if(this.activeEvent||this.compacting||this.stopHookBarrierSessionId===e.session_id){o.error("claude-adapter",`Scheduler invariant violated: event ${e.event_id} delivered while busy (active=${this.activeEvent?.eventId??"none"}, compacting=${this.compacting}, barrier=${this.stopHookBarrierSessionId===e.session_id}) \u2014 failing event to release slot`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","agent busy (scheduler invariant violated)");return}this.activeEvent={eventId:e.event_id,sessionId:e.session_id,rawEvent:e},this.stopSelfDriven(),this.clearSelfDrivenDeliverTimer(),this.lastClearedEvent=null,this.markActiveEventActivity(e.event_id,e.session_id),this.resetActiveEventHardTimer(e.event_id),this.emit("eventStarted",e.event_id,e.session_id),this.ensureClaudeAndPushEvent(e)}deliverStopEvent(e,t){if(this.activeEvent?.eventId!==e){o.info("claude-adapter",`Stop for non-active event=${e} (active=${this.activeEvent?.eventId??"none"}, compacting=${this.compacting}) \u2014 emitting eventDone to unblock platform`),this.emit("eventDone",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:K()}),(this.claudeProcess||this.claudePty)&&this.emit("pauseIntake","restart"),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??"");if(t==="claude_interaction_reply"){const i=e.params??{};if(String(i.kind??"")==="permission"){const n=i.resolution??{},r=String(n.value??""),a={...e,action_type:r==="allow"?"exec_approve":"exec_reject",params:{...i,approval_command_id:i.request_id}};return this.handlePermissionApproval(a)}return this.handleQuestionReply(e)}return 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 xe(s.questionRequestsDir),r=await n.getRequest(i),a=Number(r?.created_at??0),l=a>0&&Date.now()-a>He;if(!r||r.resolved||l){o.warn("claude-adapter",`Question reply has no pending waiter: request_id=${i} exists=${!!r} resolved=${r?.resolved===!0} expired=${l}`);const v=this.pendingQuestion.get(i);return v&&this.activeEvent?.eventId===v.eventId&&(this.activeEvent.awaitingUserQuestion=!1),this.pendingQuestion.delete(i),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"}}const c=t.resolution??{},u=String(c.type??""),h=c;if(u==="action"&&String(c.value??"")==="cancel"){o.info("claude-adapter",`Question cancelled by user: request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,h);const E=this.pendingQuestion.get(i);return E&&this.activeEvent?.eventId===E.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 p="";if(u==="text"?p=String(c.value??""):u==="map"&&(p=(Array.isArray(c.entries)?c.entries:[]).map(E=>E.value).join(", ")),!p){o.warn("claude-adapter",`Empty answer for question reply request_id=${i}`),await n.resolveRequest(i,"cancel",void 0,h);const v=this.pendingQuestion.get(i);return v&&this.activeEvent?.eventId===v.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=${p.slice(0,80)}`),await n.resolveRequest(i,"answer",p,h);const m=this.pendingQuestion.get(i);return m&&this.activeEvent?.eventId===m.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 W(r.permissionRequestsDir),l=s?"allow":"deny";return await a.resolveRequest(i,l),this.pendingPermissions.delete(i),this.scheduleTerminalPermissionKey(i,l),this.bridgeCallbacks.sendLocalActionResult(e.action_id,"ok"),o.info("claude-adapter",`Permission ${l}: approvalId=${i}`),{handled:!0,kind:"permission_approval"}}async handleExecApprovalEvent(e){const t=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");if(!t)return{delivered:!1,errorCode:"approval_id_required",errorMsg:"approval_id is required"};if(!this.pendingPermissions.get(t))return{delivered:!1,errorCode:"approval_not_found",errorMsg:`no pending permission for approval_id: ${t}`};const i=e.decision==="deny"?"deny":"allow",s=S();return await new W(s.permissionRequestsDir).resolveRequest(t,i),this.pendingPermissions.delete(t),this.scheduleTerminalPermissionKey(t,i),o.info("claude-adapter",`Permission ${i} (text event): approvalId=${t}`),{delivered:!0}}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.isChannelGateClosed()){await this.runSingleTurnFallback(e,"channel gate closed: tengu_harbor not enabled in cachedGrowthBookFeatures");return}if(!this.getClaudeCliCapabilities(this.config.command||"claude").developmentChannels){await this.runSingleTurnFallback(e,"claude CLI does not support development channels");return}if(await this.ensureClaudeProcessReady(),await this.waitForChannelReady(),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",this.bridgeCallbacks.getAgentId?.()],["attachments_json",e.attachments_json],["context_messages_json",ot(e.context_messages_json)??e.context_messages_json]];for(const[a,l]of n)l!=null&&l!==""&&(s[a]=l);this.captureEventJsonlBaseOffset(e.event_id,this.activeEvent?.textForwardOffset===void 0?{force:!0}:void 0);const r=e.content??"";this.pushNotification("notifications/claude/channel",{content:r,meta:s}),this.activeEvent?.eventId===e.event_id&&(this.activeEvent.channelPushedAt=Date.now()),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(),Ee(this.claudeCliSessionId,[]),await new Promise(a=>setTimeout(a,(t+1)*2e3)),this.ensureClaudeAndPushEvent(e,t+1);o.error("claude-adapter",`Failed to deliver event ${e.event_id}: ${s}`);let r=s;if(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(a){o.error("claude-adapter",`Single-turn fallback failed for ${e.event_id}: ${a instanceof Error?a.message:String(a)}`),r=a}}this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"failed",r instanceof Error?r.message:String(r)),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("channel ready check timed out")||t.includes("channels are not currently available")||t.includes("does not support development channels")||t.includes("unknown option")||t.includes("unknown or unexpected option")||t.includes("mcp stdio server not available")||/notify port\b.*\bnot ready/.test(t)||t.includes("file not found:"):!1}getClaudeCliCapabilities(e){return this.claudeCliCapabilities?this.claudeCliCapabilities:(this.claudeCliCapabilities=Wi(e),this.claudeCliCapabilities)}buildSingleTurnPrompt(e,t=!0){const i=t&&e.context_messages_json?ot(e.context_messages_json)??String(e.context_messages_json):"",s=[e.content??""];return i&&(s.push("","Conversation context (JSON):"),s.push(i)),s.join(`
|
|
5
|
+
`)}extractSingleTurnDelta(e){const t=e.trim();if(!t)return null;let i;try{i=JSON.parse(t)}catch{return o.warn("claude-adapter",`Single-turn fallback: dropping non-JSON stdout noise: ${t.slice(0,200)}`),null}const s=i.type==="stream_event"&&i.event&&typeof i.event=="object"?i.event:i,n=String(s.type??"");if(n==="content_block_delta"){const r=s.delta;if(r&&typeof r=="object"){const a=String(r.text??"");if(a)return{text:a,final:!1}}return null}if(n==="result"){const r=String(s.subtype??""),a=String(s.terminal_reason??""),l=s.is_error===!0||a==="api_error";if(r&&r!=="success"||l){const u=Array.isArray(s.errors)?s.errors.join("; "):"",h=String(s.result??"").trim(),p=u||h||a;throw new Error(`claude single-turn result ${r||"error"}${p?`: ${p}`:""}`)}const c=String(s.result??"");return c?{text:c,final:!0}:null}return null}resolveEventAuditConfig(e,t){if(e.audit?.enabled===!0)return e.audit;const i=t?.audit;if(i?.enabled!==!0)return;const s=i.profile??"full";return{enabled:!0,profile:s,capture:i.capture??(s==="usage"?{inputOutput:!1,tools:!1,subagents:!0,thinking:!1,rawProviderBody:i.rawProviderBody===!0}:{inputOutput:!0,tools:!0,subagents:!0,thinking:!1,rawProviderBody:i.rawProviderBody===!0})}}buildClaudeRuntimeEnv(e=this.resolveSessionRuntime()){const t={...Q(),...this.config.env};if(delete t.CLAUDECODE,t.CLAUDE_PLUGIN_DATA=S().dataDir,t.GRIX_HOOK_SIGNALS_PATH=this.resolveHookSignalsPath(),this.internalApi&&(t.GRIX_CLAUDE_INTERNAL_API_URL=this.internalApi.baseUrl,t.GRIX_CLAUDE_INTERNAL_API_TOKEN=this.internalApi.token),e.audit?.enabled===!0&&!this.internalApi&&o.error("claude-adapter","Audit enabled but internal API not started; OTEL capture env will not be injected"),e.audit?.enabled===!0&&this.internalApi){const s=this.ensureClaudeAuditEvidence(e.audit);t.CLAUDE_CODE_ENABLE_TELEMETRY="1",t.CLAUDE_CODE_ENHANCED_TELEMETRY_BETA="1",t.OTEL_LOGS_EXPORTER="otlp",t.OTEL_TRACES_EXPORTER="otlp",t.OTEL_METRICS_EXPORTER="none",t.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",t.OTEL_EXPORTER_OTLP_ENDPOINT=this.internalApi.baseUrl,t.OTEL_EXPORTER_OTLP_HEADERS=`Authorization=Bearer ${this.internalApi.token}`,t.OTEL_LOGS_EXPORT_INTERVAL="1000",t.OTEL_TRACES_EXPORT_INTERVAL="1000",t.OTEL_LOG_USER_PROMPTS=e.audit.capture.inputOutput?"1":"0",t.OTEL_LOG_ASSISTANT_RESPONSES=e.audit.capture.inputOutput?"1":"0",t.OTEL_LOG_TOOL_DETAILS=e.audit.capture.tools?"1":"0",t.OTEL_LOG_TOOL_CONTENT=e.audit.capture.tools?"1":"0",e.audit.capture.rawProviderBody&&(t.OTEL_LOG_RAW_API_BODIES=`file:${s.rawBodyDir}`)}const i=kt(e.effort);if(i==="auto")delete t.CLAUDE_CODE_EFFORT_LEVEL;else{const s=Rt(i);s&&(t.CLAUDE_CODE_EFFORT_LEVEL=s)}return t}ensureClaudeAuditEvidence(e){if(this.auditEvidencePaths)return this.auditEvidencePaths;const t=this.config.options??{},s=String(t.auditEvidenceRoot??"").trim()||f(S().dataDir,"audit-evidence"),n=Ke(this.sessionId),r=Ke(this.claudeCliSessionId||"pending"),a=f(s,"claude",n,r),l=f(a,"raw-api-bodies");be(l,{recursive:!0,mode:448}),le(a,448),le(l,448);const c={rootDir:a,logsPath:f(a,"otel-logs.jsonl"),tracesPath:f(a,"otel-traces.jsonl"),rawBodyDir:l,rawProviderBody:e.capture.rawProviderBody};return this.internalApi?.setOtelHandler(async(u,h,p)=>{const m=u==="logs"?c.logsPath:c.tracesPath;await Tt(m,`${JSON.stringify({observedAt:new Date().toISOString(),signal:u,payload:h,rawBody:p})}
|
|
6
|
+
`,{encoding:"utf8",mode:384}),le(m,384)}),this.auditEvidencePaths=c,c}async runSingleTurnFallback(e,t){const i=this.resolveSessionRuntime(),s=this.resolveEventAuditConfig(i,e);if(s&&!this.internalApi){o.error("claude-adapter",`Audit capture unavailable for event ${e.event_id}: internal API not started`),this.bridgeCallbacks.sendEventResult(e.event_id,"failed","audit capture unavailable: internal API not started","audit_capture_unavailable");return}if(this.activeEvent?.eventId===e.event_id&&(this.activeEvent.singleTurnFallback=!0,s&&(this.activeEvent.auditSingleTurnFallback=!0)),this.claudeProcess||this.claudePty){const _=this.mcpChannelBroken,C=this.channelGateClosed;this.killClaudeProcess("single-turn fallback isolation"),this.mcpChannelBroken=_,this.channelGateClosed=C}const n=this.config.options??{},r=this.config.command||"claude",a=(this.config.args??[]).filter(_=>{const C=String(_).trim().toLowerCase();return C!=="--dangerously-load-development-channels"&&C!=="--session-id"&&C!=="--resume"}),l=String(i.cwd??"").trim(),c=String(i.modelId??"").trim(),u=at(i.modeId);await this.ensureWorkspaceTrust(l),await this.ensureClaudeOnboardingFlags(l),await this.ensureSkipDangerousPermissionPrompt(),await this.injectStatusLineSettings(l);const h=String(i.claudeSessionId??"").trim()||this.claudeCliSessionId||K();this.claudeCliSessionId=h,this.claudeSessionCwd=l,!i.claudeSessionId&&i.onSessionIdAssigned&&i.onSessionIdAssigned(h),await this.ensureStdioMcpServer();const p=this.buildClaudeRuntimeEnv(s?{...i,audit:s}:i);p.GRIX_CLAUDE_SINGLE_TURN="1";const m=i.pluginDir??n.pluginDir??await this.ensureClaudePluginDir();let v=ut(h,l||void 0);v&&ht(h,l||void 0)&&(v=!1);const E=String(i.claudeSessionId??"").trim()!==""&&!v;v&&ft(h,l||void 0),this.captureSingleTurnFallbackJsonlBaseOffset(e.event_id),E&&o.warn("claude-adapter",`Claude local transcript missing for session ${h}; continuing silently with platform context`);const L=this.buildSingleTurnPrompt(e,!v),y=[...a,"-p","--output-format","stream-json","--verbose","--include-partial-messages",...v?["--resume",h]:["--session-id",h]];y.push("--plugin-dir",m,"--strict-mcp-config","--mcp-config",this.claudeMcpConfigPath,"--permission-mode",u===U.fullAuto?"bypassPermissions":"default"),u===U.fullAuto&&y.push(...await this.buildFullAutoSettingsArgs(a)),c&&y.push("--model",c);const H=process.platform==="win32";H||y.push(L),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((_,C)=>{const w=Ce(r,y),g=re(w.command,w.args,{cwd:l||process.cwd(),env:p,stdio:[H?"pipe":"ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0,windowsVerbatimArguments:w.windowsVerbatimArguments});this.singleTurnFallbackChild=g,this.singleTurnFallbackEventId=e.event_id;let M=!1;const se=setTimeout(()=>{M=!0,o.error("claude-adapter",`Single-turn fallback exceeded ${fe/1e3}s for ${e.event_id}, killing process tree`),this.killSingleTurnFallbackChild(g)},fe),ye=()=>{clearTimeout(se),this.singleTurnFallbackChild===g&&(this.singleTurnFallbackChild=null,this.singleTurnFallbackEventId=null)};H&&(g.stdin?.on("error",b=>{o.warn("claude-adapter",`Single-turn fallback stdin error: ${b.message}`)}),g.stdin?.write(L),g.stdin?.end());let F="",J=0,q=!1,ne=null;const we=`fallback_${e.event_id}_${Date.now()}`,Pe=String(e.msg_id??"").trim()||void 0;let $="";const Te=b=>{let A;try{A=this.extractSingleTurnDelta(b)}catch(G){ne=G instanceof Error?G:new Error(String(G));return}A&&(A.final&&q||this.activeEvent?.eventId===e.event_id&&this.isEventAnswered()||(J+=1,q=!0,this.markActiveEventActivity(e.event_id,e.session_id),this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,A.text,J,!1,we,Pe)))};g.stdout?.setEncoding("utf8"),g.stdout?.on("data",b=>{$+=b;let A=$.indexOf(`
|
|
7
|
+
`);for(;A>=0;){const G=$.slice(0,A);$=$.slice(A+1),Te(G),A=$.indexOf(`
|
|
8
|
+
`)}}),g.stderr?.setEncoding("utf8"),g.stderr?.on("data",b=>{F.length>=me||(F+=b,F.length>me&&(F=F.slice(0,me)))}),g.on("error",b=>{ye(),C(b)}),g.on("close",b=>{if(ye(),$.trim()&&Te($),M){C(new Error(`agent exceeded max duration ${fe/1e3}s`));return}if(ne){C(ne);return}if(b!==0&&!q){const A=F.trim();C(new Error(A||`claude single-turn exited with code ${b}`));return}if(!q&&this.activeEvent?.eventId===e.event_id&&!this.isEventAnswered()){const A=F.trim();C(new Error(A||"claude single-turn produced no output"));return}q&&(J+=1,this.bridgeCallbacks.sendStreamChunk(e.event_id,e.session_id,"",J,!0,we,Pe)),_()})}),this.activeEvent?.eventId===e.event_id&&(this.bridgeCallbacks.sendEventResult(e.event_id,"responded"),this.clearActiveEvent())}async waitForChannelReady(){if(!this.mcpServerReady)throw new Error("MCP stdio server not available");await this.waitForNotifyPort(3e4),process.platform==="win32"?await this.waitForWindowsChannelReady(st):await this.waitForChannelListening(st)}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=at(s.modeId),l=String(s.modelId??"").trim(),c=String(s.cwd??"").trim();this.claudeSessionCwd=c;const u=String(s.claudeSessionId??"").trim()||K();this.claudeCliSessionId=u,!s.claudeSessionId&&s.onSessionIdAssigned&&s.onSessionIdAssigned(u);const h=this.buildClaudeRuntimeEnv((()=>{const y=this.resolveEventAuditConfig(s,this.activeEvent?.rawEvent);return y?{...s,audit:y}:s})());let p=ut(u,c||void 0);if(p&&ht(u,c||void 0)&&(p=!1),String(s.claudeSessionId??"").trim()!==""&&!p&&o.warn("claude-adapter",`Claude local transcript missing for session ${u}; continuing silently with platform context`),p?ft(u,c||void 0):(Ee(u,[]),_e(u)),this.runtimeResolver&&!c)throw new Error("Claude session binding missing cwd \u2014 run /grix open <working-directory> first");if(!c)throw new Error("Claude runtime cwd is required");await this.ensureWorkspaceTrust(c),await this.ensureClaudeOnboardingFlags(c),await this.ensureSkipDangerousPermissionPrompt(),await this.injectStatusLineSettings(c);let m=!1,v="",E=null;try{t(),this.notifyPort=await ki([this.internalApiPort]),m=!0,t(),o.info("claude-adapter",`Allocated MCP notify port ${this.notifyPort} (internal API ${this.internalApiPort})`),await this.ensureStdioMcpServer(),t();const y=i.pluginDir||await this.ensureClaudePluginDir(),H=p?["--resume",u]:["--session-id",u],_=[...r,"--name",`grix-${this.sessionId}`,...H,"--plugin-dir",y,"--strict-mcp-config","--mcp-config",this.claudeMcpConfigPath];l&&(/^claude/i.test(l)?_.push("--model",l):(o.warn("claude-adapter",`Skipping --model ${l}: 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=l)),a===U.fullAuto&&(_.push("--dangerously-skip-permissions"),_.push(...await this.buildFullAutoSettingsArgs(r))),_.push("--dangerously-load-development-channels",`server:${j}`);const C=$i(this.bridgeCallbacks.getAgentProfile?.(),p?void 0:this.sessionId,this.bridgeCallbacks.getAgentId?.());if(process.platform==="win32"){const w=C.replace(/</g,"[").replace(/>/g,"]").replace(/"/g,"'"),g=qi(this.claudeCliSessionId);await Ki(g,w),_.push("--append-system-prompt-file",g)}else _.push("--append-system-prompt",C);if(process.platform==="win32")if(Y){const w=Yi(),g=["/c",n,..._];o.info("claude-adapter",`Spawning Claude via PTY on win32: cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`);const M=Y.spawn(w,g,{name:"xterm-256color",cols:120,rows:30,cwd:c,env:h,useConpty:!0,conptyInheritCursor:!1});this.claudePty=M,this.claudeChildPid=M.pid,E=null}else o.info("claude-adapter",`Spawning Claude via shell on win32 (node-pty unavailable): cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`),E=re(n,_,{cwd:c,env:h,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",shell:!0,windowsHide:!0});else{o.info("claude-adapter",`Spawning via expect PTY: cwd=${c} mode=${a} ${p?"resume":"new"} ${n} ${_.join(" ")}`);const w=ni(typeof h.PATH=="string"?h.PATH:void 0);if(!w)throw new Error("expect not found in PATH. Install it with: apt install expect / dnf install expect / brew install expect");const g=f(It(),`grix-claude-${K()}`);await O(g,{recursive:!0}),this.expectRunDir=g;const{expectPath:M,pidPath:se}=await ji(g,n,_);v=se,t(),E=re(w,[M],{cwd:c,env:h,stdio:["pipe","pipe","pipe"],detached:!0})}if(this.claudeProcess=E,this.clearPendingMcpFailureTimer(),this.mcpStartupFailureHandled=!1,this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.startupDialogSeenAt=0,this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.clearDevChannelsConfirmTimer(),this.ptyDialogBusy=!1,E&&E.on("error",w=>{o.error("claude-adapter","Claude process spawn error: "+w),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=E?.pid??0;else{const w=await Ui(E,v);if(t(),!Number.isFinite(w)||w<=0)throw new Error("failed to determine spawned Claude pid");this.claudeChildPid=w}if(!this.claudeChildPid||this.claudeChildPid<=0)throw new Error("failed to determine spawned Claude pid")}catch(y){if(E?.pid&&N(E,"SIGTERM"),this.claudePty){try{this.claudePty.kill()}catch{}this.claudePty=null}throw this.claudeProcess===E&&(this.claudeProcess=null),this.claudeChildPid=0,m&&this.releaseNotifyPortReservation(),this.stopMcpServer(),y}const L=this.claudeChildPid;o.info("claude-adapter","Claude child PID: "+L+(this.claudePty?" (via PTY)":"")),this.setupProcessOrPtyHandlers(),this.alive=!0}finalizeActiveEventOnProcessExit(e){if(!this.activeEvent||this.stopped)return;const t=this.isEventAnswered(),i=t?"responded":"failed",s=!t&&this.activeEvent.apiFormatError?he(this.activeEvent.apiErrorText):void 0,n=t?void 0:s??`Claude process exited before completing its reply (${e})`;o.error("claude-adapter",`Claude process exited with active event ${this.activeEvent.eventId}, answered=${t}, sending ${i}`),s&&(this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,s,1,!1,`err_${this.activeEvent.eventId}`),this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,"",2,!0,`err_${this.activeEvent.eventId}`)),s?this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,n,void 0,!0):this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,i,n),this.clearActiveEvent()}setupProcessOrPtyHandlers(){if(this.claudeProcess){const e=this.claudeProcess;e.on("exit",(t,i)=>{if(o.info("claude-adapter",`Claude process exited (code=${t}, signal=${i})`),this.singleTurnFallbackProcesses.delete(e)){o.info("claude-adapter","Ignoring stale Claude process exit after lifecycle ownership transfer");return}if(this.lostInjectionKilledProcesses.delete(e)){o.info("claude-adapter","Ignoring expected Claude process exit after lost-injection respawn");return}this.claudeProcess=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()&&(this.activeEvent&&!this.stopped&&this.finalizeActiveEventOnProcessExit(`code=${t}, signal=${i}`),this.stopped||this.emit("exit",t),this.compacting&&this.finishCompaction("process-exit"))}),e.stdout?.on("data",t=>{this.claudeProcess===e&&this.handleClaudeOutput(t.toString())}),e.stderr?.on("data",t=>{if(this.claudeProcess!==e)return;const i=t.toString().trim();i&&o.info("claude-adapter",`[claude stderr] ${i}`),this.checkFailurePatterns(i,"stderr")})}if(this.claudePty){const e=this.claudePty;e.onExit(({exitCode:t,signal:i})=>{if(o.info("claude-adapter",`Claude PTY process exited (code=${t}, signal=${i})`),this.singleTurnFallbackPtys.delete(e)){o.info("claude-adapter","Ignoring stale Claude PTY exit after lifecycle ownership transfer");return}if(this.lostInjectionKilledPtys.delete(e)){o.info("claude-adapter","Ignoring expected Claude PTY exit after lost-injection respawn");return}this.claudePty=null,this.claudeChildPid=0,this.alive=!1,this.releaseNotifyPortReservation(),this.stopMcpServer(),this.clearPendingMcpFailureTimer(),!this.tryRecoverSessionIdConflict()&&(this.activeEvent&&!this.stopped&&this.finalizeActiveEventOnProcessExit(`code=${t}, signal=${i}`),this.stopped||this.emit("exit",t),this.compacting&&this.finishCompaction("process-exit"))}),e.onData(t=>{this.claudePty===e&&(this.handleClaudeOutput(t),this.checkFailurePatterns(t,"pty"))})}}lastPtyOutputAt=0;ptyProbe={title:0,spinner:0,meaningful:0,lastLogAt:0,lastMeaningfulAt:0};recordPtyProbe(e){const t=Date.now();this.lastPtyOutputAt=t;const i=e.includes("]0;"),s=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").trim(),n=s.length<=3||/^[✳✶✻✽✵❋✺✴❈❖✦✧✢◉◎⬥⬦◇◆▸▹►▻→←↑↓⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·…\d]*still\s+thinking/i.test(s);if(i?this.ptyProbe.title++:!s||n?this.ptyProbe.spinner++:(this.ptyProbe.meaningful++,this.ptyProbe.lastMeaningfulAt=t),t-this.ptyProbe.lastLogAt>=2e3){const r=this.activeEvent?this.isEventAnswered()?"replied":"running":"none",a=this.ptyProbe.lastMeaningfulAt?t-this.ptyProbe.lastMeaningfulAt:-1;o.debug("claude-adapter",`[pty-probe] session=${this.sessionId??"?"} event=${r} win2s title=${this.ptyProbe.title} spinner=${this.ptyProbe.spinner} meaningful=${this.ptyProbe.meaningful} meaningfulGapMs=${a}`),this.ptyProbe.title=0,this.ptyProbe.spinner=0,this.ptyProbe.meaningful=0,this.ptyProbe.lastLogAt=t}}terminalPermissionPromptTail="";terminalPermissionPromptVisible=!1;terminalPermissionKeyTimer=null;trackTerminalPermissionPrompt(e){const t=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g," ").replace(/[\x00-\x1f\x7f-\x9f]/g," ").trim();if(t){if(Ii.test(t)){this.terminalPermissionPromptTail=`${this.terminalPermissionPromptTail} ${t}`.slice(-Ci),Ai.test(this.terminalPermissionPromptTail)&&(this.terminalPermissionPromptVisible=!0);return}t.length<=3||bi.test(t)||(this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1)}}sendTerminalKey(e){const t=e==="enter"?"\r":"\x1B";try{if(this.claudePty)return this.claudePty.write(t),!0;if(this.expectRunDir)return this.writeExpectFifoLine(this.expectRunDir,`${ve}${e}`),!0}catch(i){o.warn("claude-adapter",`Failed to send terminal key ${e}: ${i instanceof Error?i.message:i}`)}return!1}scheduleTerminalPermissionKey(e,t){this.terminalPermissionKeyTimer&&clearTimeout(this.terminalPermissionKeyTimer),this.terminalPermissionKeyTimer=setTimeout(()=>{if(this.terminalPermissionKeyTimer=null,this.stopped||!this.terminalPermissionPromptVisible)return;const i=t==="allow"?"enter":"esc";this.sendTerminalKey(i)&&(this.terminalPermissionPromptTail="",this.terminalPermissionPromptVisible=!1,o.info("claude-adapter",`Permission prompt still on terminal after ${t}, sent ${i} key: approvalId=${e}`))},Ti),this.terminalPermissionKeyTimer.unref()}handleClaudeOutput(e){this.recordPtyProbe(e),this.trackTerminalPermissionPrompt(e),this.compacting&&this.resetCompactingActivityTimer();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,l=>`\\x${l.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 l=[this.claudeProcess?.pid,this.claudeChildPid,this.claudePty?.pid].filter(c=>!!c&&c>0);Ee(a,l)}const s=t.replace(/\[[0-9;?]*[ -/]*[@-~]/g," ").replace(/[^a-zA-Z]+/g," ").toLowerCase(),n=s.replace(/ /g,"");if(this.claudePty&&!this.startupChannelListening&&!this.windowsTrustDialogAnswered&&/trust.*folder|quick.*safety.*check/.test(n)&&this.respondToWindowsTrustDialog(t),!this.startupDialogSeenAt&&!this.startupChannelListening&&/loadingdevelopmentchannels|usingthisforlocaldevelopment/.test(n)&&(this.startupDialogSeenAt=Date.now(),o.info("claude-adapter","Dev channels dialog rendered; restarting notify port wait window"),this.claudePty&&this.scheduleDevChannelsConfirm()),(/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)&&(this.channelGateClosed=!0,o.warn("claude-adapter",'Claude reports "Channels are not currently available" \u2014 channel gate (tengu_harbor) is closed for this account/model; switching to single-turn fallback')),!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()},_i))}}clearWindowsTrustDialogTimer(){this.windowsTrustDialogTimer&&(clearTimeout(this.windowsTrustDialogTimer),this.windowsTrustDialogTimer=null)}respondToWindowsTrustDialog(e){if(this.windowsTrustDialogAnswered||this.windowsTrustDialogTimer)return;const t=e.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,""),i=Fi.test(t),s=!i&&Ni.test(t);!i&&!s||(this.windowsTrustDialogAnswered=!0,o.info("claude-adapter",`Auto-accepting workspace trust dialog (layout=${i?"noFirst":"yesFirst"})`),this.scheduleTrustDialogWrite(i,1e3))}scheduleTrustDialogWrite(e,t){this.windowsTrustDialogTimer=setTimeout(()=>{if(this.windowsTrustDialogTimer=null,this.stopped||!this.claudePty)return;if(this.ptyDialogBusy){this.scheduleTrustDialogWrite(e,nt);return}this.ptyDialogBusy=!0;const i=e?"noFirst":"yesFirst";e?(this.writePtyKey(this.claudePty,"\x1B[B","Down","trust",i),this.windowsTrustDialogTimer=setTimeout(()=>{this.windowsTrustDialogTimer=null,this.claudePty&&!this.stopped&&this.writePtyKey(this.claudePty,"\r","Enter","trust",i),this.ptyDialogBusy=!1},400),this.windowsTrustDialogTimer.unref()):(this.writePtyKey(this.claudePty,"\r","Enter","trust",i),this.ptyDialogBusy=!1)},t),this.windowsTrustDialogTimer.unref()}writePtyKey(e,t,i,s,n){try{e.write(t),o.info("claude-adapter",`PTY key sent: ${i} (dialog=${s}${n?`, layout=${n}`:""})`)}catch(r){o.warn("claude-adapter",`Failed to write PTY key ${i} for dialog=${s}: ${r instanceof Error?r.message:r}`)}}scheduleDevChannelsConfirm(){this.devChannelsConfirmTimer||(this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),yi),this.devChannelsConfirmTimer.unref())}tryDevChannelsConfirm(){if(this.devChannelsConfirmTimer=null,this.stopped||!this.claudePty||this.startupChannelListening)return;if(this.ptyDialogBusy){this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),nt),this.devChannelsConfirmTimer.unref();return}this.ptyDialogBusy=!0,this.writePtyKey(this.claudePty,"\r","Enter","devChannels"),this.ptyDialogBusy=!1,Date.now()-(this.startupDialogSeenAt||Date.now())<Pi&&(this.devChannelsConfirmTimer=setTimeout(()=>this.tryDevChannelsConfirm(),wi),this.devChannelsConfirmTimer.unref())}clearDevChannelsConfirmTimer(){this.devChannelsConfirmTimer&&(clearTimeout(this.devChannelsConfirmTimer),this.devChannelsConfirmTimer=null)}checkFailurePatterns(e,t="stderr"){/Session ID (\S+) is already in use/i.test(e)&&(this.sessionIdConflictDetected=!0);const s=(t==="pty"?Vt:Yt).some(n=>n.test(e));s&&this.isEventAnswered()?o.warn("claude-adapter",`Ignoring ${t} auth failure text after current event was answered`):s&&(o.error("claude-adapter",`Auth failure: ${e}`),this.authFailureUntil=Date.now()+Be,this.activeEvent&&(this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,`
|
|
9
9
|
|
|
10
|
-
Error: Claude authentication failed -- please re-login`,1,!1),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"failed","Claude authentication failed -- please re-login"),this.clearActiveEvent())),
|
|
10
|
+
Error: Claude authentication failed -- please re-login`,1,!1),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"failed","Claude authentication failed -- please re-login"),this.clearActiveEvent())),Qt.some(n=>n.test(e))&&(o.error("claude-adapter",`Usage limit: ${e}`),this.usageLimitUntil=Date.now()+Be,this.activeEvent&&(this.bridgeCallbacks.sendStreamChunk(this.activeEvent.eventId,this.activeEvent.sessionId,`
|
|
11
11
|
|
|
12
|
-
Error: Claude usage limit reached -- waiting for reset`,1,!1),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"failed","Claude usage limit reached -- waiting for reset"),this.clearActiveEvent())),
|
|
13
|
-
`}let a="";try{a=await I(s,"utf8")}catch{}a!==r&&(await
|
|
14
|
-
`,p=f(t,"hooks"),m=f(p,"hooks.json");await
|
|
15
|
-
`;"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=null;if(!this.claudePty){let s=!1;i=setInterval(()=>{if(this.startupChannelListening){i&&clearInterval(i);return}try{this.claudeProcess?.stdin?.writable&&(this.claudeProcess.stdin.write("\r"),s||(o.info("claude-adapter","Windows shell: sending Enter to auto-confirm dev channels dialog"),s=!0))}catch{}},3e3)}try{for(;Date.now()-t<e;){if(this.channelGateClosed)throw new Error("channels are not currently available (tengu_harbor gate closed)");if(this.startupChannelListening){const r=this.startupChannelListeningAt||Date.now(),a=Date.now()-r;if(a>=Z)return;await new Promise(l=>setTimeout(l,Z-a));return}const s=Date.now()-t,n=this.claudePty?
|
|
12
|
+
Error: Claude usage limit reached -- waiting for reset`,1,!1),this.bridgeCallbacks.sendEventResult(this.activeEvent.eventId,"failed","Claude usage limit reached -- waiting for reset"),this.clearActiveEvent())),Xt.test(e)&&this.activeEvent&&(o.error("claude-adapter",`API format error (400 server_tool_use.id): ${e.slice(0,200)}`),this.activeEvent.apiFormatError=!0)}async ensureClaudePluginDir(){const e=this.resolveProjectRoot(),t=f(S().dataDir,"claude-plugin"),i=f(t,".claude-plugin"),s=f(i,"plugin.json"),n=f(e,".claude-plugin","plugin.json");await O(i,{recursive:!0});let r="";try{r=await I(n,"utf8")}catch{r=`${JSON.stringify({name:"grix-connector",version:"0.1.0",description:"Claude Code channel plugin for grix-connector.",license:"Apache-2.0"},null,2)}
|
|
13
|
+
`}let a="";try{a=await I(s,"utf8")}catch{}a!==r&&(await R(s,r,"utf8"),o.info("claude-adapter",`Wrote Claude plugin manifest: ${s}`));const l=f(e,"dist","scripts"),c=y=>`"${String(y).replace(/"/g,'\\"')}"`,u=y=>`${c(process.execPath)} ${c(f(l,y))}`,h=`${JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],Elicitation:[{hooks:[{type:"command",command:u("elicitation-hook.js"),timeout:630}]}],ElicitationResult:[{matcher:"",hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],UserPromptSubmit:[{hooks:[{type:"command",command:u("user-prompt-submit-hook.js")}]}],PreToolUse:[{matcher:"ExitPlanMode",hooks:[{type:"command",command:u("approve-plan-hook.js")}]},{matcher:"",hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],PostToolUseFailure:[{matcher:"",hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],PermissionRequest:[{matcher:"",hooks:[{type:"command",command:u("permission-hook.js"),timeout:330}]}],Notification:[{matcher:"idle_prompt",hooks:[{type:"command",command:u("notification-hook.js")}]}],PermissionDenied:[{matcher:"",hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],Stop:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],StopFailure:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],PreCompact:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],PostCompact:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}],ConfigChange:[{hooks:[{type:"command",command:u("lifecycle-hook.js")}]}]}},null,2)}
|
|
14
|
+
`,p=f(t,"hooks"),m=f(p,"hooks.json");await O(p,{recursive:!0});let v="";try{v=await I(m,"utf8")}catch{}v!==h&&(await R(m,h,"utf8"),o.info("claude-adapter",`Wrote Claude hooks config: ${m}`));const E=f(t,"skills"),L=Bt(E);return L.length>0&&o.info("claude-adapter",`Synced connector skills to plugin: [${L.join(", ")}]`),t}async ensureStdioMcpServer(){const e=this.resolveProjectRoot(),t=this.resolveStdioServerPath(e);if(this.ensureStdioServerArtifact(e,t),!P(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=f(e,"dist","mcp","mcp-bridge-server.js"),a=this.internalApi?.mcpBridgeWsUrl,l=P(r)&&a?[r,"--ws-url",a]:void 0;l||o.warn("claude-adapter",`APP MCP bridge skipped (path=${P(r)} ws=${!!a})`);const c=Hi(this.claudeCliSessionId);await Ji(c,n,l),this.claudeMcpConfigPath=c,this.mcpServerReady=!0,this.startActivityTracking()}resolveProjectRoot(){const e=bt(import.meta.url);return At(e,"..","..","..","..")}resolveStdioServerPath(e=this.resolveProjectRoot()){return f(e,"dist","mcp","stdio","server.js")}ensureStdioServerArtifact(e,t){if(P(t)||rt)return;rt=!0;const i=f(e,"node_modules","typescript","bin","tsc"),s=f(e,"tsconfig.json");if(!P(i)||!P(s))return;o.warn("claude-adapter",`MCP stdio server artifact missing, attempting build: ${t}`);const n=ae(process.execPath,[i,"-p",s],{cwd:e,env:process.env,encoding:"utf8",timeout:6e4,windowsHide:!0});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();let i=t+e,s=!1;const n=()=>{s||this.startupDialogSeenAt<=t||(s=!0,i=this.startupDialogSeenAt+e,o.info("claude-adapter",`Notify port wait extended: dialog appeared ${this.startupDialogSeenAt-t}ms after spawn, allowing ${e}ms from there`))};for(;n(),!(Date.now()>=i);)try{await new Promise((a,l)=>{const c=de.createConnection({host:"127.0.0.1",port:this.notifyPort},()=>{c.destroy(),a()});c.on("error",l),setTimeout(()=>{c.destroy(),l(new Error("probe timeout"))},2e3)});return}catch{await new Promise(a=>setTimeout(a,500))}const r=Date.now()-t;throw new Error(`Notify port ${this.notifyPort} not ready within ${r}ms${s?" (window restarted at dev channels dialog)":""}`)}async waitForChannelListening(e){const t=Date.now(),i=8e3;for(;Date.now()-t<e;){if(this.channelGateClosed)throw new Error("channels are not currently available (tengu_harbor gate closed)");if(this.startupChannelListening){const s=this.startupChannelListeningAt||Date.now(),n=Date.now()-s;if(n>=Z)return;await new Promise(r=>setTimeout(r,Z-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`)}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}
|
|
15
|
+
`;"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=null;if(!this.claudePty){let s=!1;i=setInterval(()=>{if(this.startupChannelListening){i&&clearInterval(i);return}try{this.claudeProcess?.stdin?.writable&&(this.claudeProcess.stdin.write("\r"),s||(o.info("claude-adapter","Windows shell: sending Enter to auto-confirm dev channels dialog"),s=!0))}catch{}},3e3)}try{for(;Date.now()-t<e;){if(this.channelGateClosed)throw new Error("channels are not currently available (tengu_harbor gate closed)");if(this.startupChannelListening){const r=this.startupChannelListeningAt||Date.now(),a=Date.now()-r;if(a>=Z)return;await new Promise(l=>setTimeout(l,Z-a));return}const s=Date.now()-t,n=this.claudePty?Si:12e3;if(this.alive&&this.mcpServerReady&&s>n){o.info("claude-adapter",`Windows ${this.claudePty?"PTY":"shell"} fallback: assuming channel ready after ${s}ms (no stdout detection, MCP server connected)`),this.startupChannelListeningAt=Date.now(),this.startupChannelListening=!0,this.clearPendingMcpFailureTimer(),this.sendDeferredModelSwitch();return}await new Promise(r=>setTimeout(r,500))}}finally{i&&clearInterval(i)}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=de.createConnection({host:"127.0.0.1",port:this.notifyPort},()=>{this.notifySocket.write(i+`
|
|
16
16
|
`)}),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+`
|
|
17
|
-
`)}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(){Ai(this.notifyPort),this.notifyPort=0}killClaudeProcess(e){const t=this.claudeProcess,i=this.claudePty,s=this.claudeChildPid;if(e==="single-turn fallback isolation"&&(t&&this.singleTurnFallbackProcesses.add(t),i&&this.singleTurnFallbackPtys.add(i)),e===Ue&&(t&&this.lostInjectionKilledProcesses.add(t),i&&this.lostInjectionKilledPtys.add(i)),this.claudeProcess=null,this.claudePty=null,this.claudeChildPid=0,this.spawnPromise=null,this.alive=!1,this.stopMcpServer(),this.releaseNotifyPortReservation(),this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.sessionIdConflictDetected=!1,this.pendingPermissions.size>0){const n=w(),r=new z(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&&q(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&&q(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.isEventAnswered())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}recoverMalformedToolCall(e){if(this.stopped||!this.activeEvent||this.isEventAnswered()||!this.claudeCliSessionId||!this.claudeSessionCwd)return"none";const t=W(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(!t||t.stopReason!=="stop_sequence"||t.text.trim()!==ii)return"none";if(this.malformedToolRetriedEventIds.has(e))return o.warn("claude-adapter",`Malformed tool-call retry exhausted for ${e}, sending clean fallback`),"exhausted";this.malformedToolRetriedEventIds.add(e);const i={...this.activeEvent.rawEvent,content:si};return o.warn("claude-adapter",`Detected malformed tool-call, silently retrying event once: ${e}`),this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),this.activeEvent=null,this.stopComposing(),this.deliverInboundEvent(i),"retried"}async handleInternalInvoke(e,t,i,s){if(e==="mcp_stdio_log")return o.info("claude-mcp-stdio",String(t.message??"")),{ok:!0};if(e==="event_tool_call"){const n=String(t.tool_name??""),r=Lt(n,{...t.arguments??{}}),a=this.getEventToolHandle();if(this.activeEvent){const c=this.activeEvent,u=String(r.event_id??"").trim();u===""?r.event_id=c.eventId:(n==="grix_reply"||n==="grix_complete")&&u!==c.eventId&&(o.warn("claude-adapter",`${n}: event_id mismatch, correcting: supplied=${u}, active=${c.eventId}`),r.event_id=c.eventId);const h=String(r.session_id??"").trim();if(n==="grix_reply"?(h&&h!==c.sessionId&&o.warn("claude-adapter",`${n}: session_id mismatch, correcting: supplied=${h}, active=${c.sessionId}`),r.session_id=c.sessionId):h===""&&(r.session_id=c.sessionId),n==="grix_reply"&&String(r.quoted_message_id??"").trim()===""){const p=String(c.rawEvent?.msg_id??"").trim();p&&(r.quoted_message_id=p)}n==="grix_reply"&&o.info("claude-adapter",`grix_reply quote: rawEvent.msg_id=${String(c.rawEvent?.msg_id??"")||"(none)"} -> quoted_message_id=${String(r.quoted_message_id??"")||"(none)"}`)}else if(this.lastClearedEvent&&n==="grix_reply"){const c=this.lastClearedEvent;Date.now()-c.ts<hi&&(String(r.session_id??"").trim()===""&&(r.session_id=c.sessionId),r.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)`))}!this.activeEvent&&n==="grix_reply"&&(this.selfDrivenReplied=!0),n==="grix_reply"&&String(r.event_id??"").trim()!==""&&this.completedEventIds.has(String(r.event_id??"").trim())&&(o.info("claude-adapter",`Late grix_reply fallback: sending direct message for completed event ${String(r.event_id??"").trim()}`),r.event_id="");const l=Ot(n,r);if(!l.valid)throw new Error(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${l.error}`);if(a.status!=="ready")throw new Error(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${a.status}`);if($t(n)){const c=this.activeEvent;c&&(c.toolCallInFlight=!0);try{if(i?.aborted)throw new Error("invoke aborted by timeout");const u=De(a,n,r);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(n,r),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: ${n}`)}return this.bridgeCallbacks.agentInvoke(e,t,s)}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"){const s=!this.activeEvent.replied;this.activeEvent.replied=!0;const n=String(t.text??"");n.length>0&&(this.activeEvent.lastReplyText=n),this.markActiveEventActivity(i,String(t.session_id??"").trim()||void 0),s&&(this.activeEvent.repliedAt=Date.now(),this.startPostReplyDeadline(i),this.startPostReplyJsonlWatcher(i))}}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 be(t)}catch{throw new Error(`pluginDir is not accessible: ${t}`)}if(!i.isDirectory())throw new Error(`pluginDir is not a directory: ${t}`);const s=f(t,".mcp.json");try{(await be(s)).isFile()&&(await Ie(s),o.info("claude-adapter",`Removed conflicting .mcp.json from pluginDir: ${s}`))}catch{}}async ensureWorkspaceTrust(e){const t=f(R(),".claude.json");let i=e;try{i=Pe(e)}catch{}const s=i===e?[e]:[e,i];try{const n=await I(t,"utf8"),r=JSON.parse(n.replace(/^\uFEFF/,""));r.projects||(r.projects={});let a=!1;for(const l of s)r.projects[l]?.hasTrustDialogAccepted!==!0&&(r.projects[l]||(r.projects[l]={}),r.projects[l].hasTrustDialogAccepted=!0,a=!0);if(!a)return;await D(t,JSON.stringify(r),"utf8"),o.info("claude-adapter",`Pre-trusted workspace: ${s.join(", ")}`)}catch(n){o.warn("claude-adapter",`Failed to pre-trust workspace ${e}: ${n}`)}}async ensureSkipDangerousPermissionPrompt(){const e=f(R(),".claude","settings.json");try{let t={};try{t=JSON.parse(await I(e,"utf8"))}catch{}if(t.skipDangerousModePermissionPrompt===!0)return;t.skipDangerousModePermissionPrompt=!0,await F(f(R(),".claude"),{recursive:!0}),await D(e,JSON.stringify(t,null,2),"utf8"),o.info("claude-adapter","Set skipDangerousModePermissionPrompt=true in user settings to skip BypassPermissions dialog")}catch(t){o.warn("claude-adapter",`Failed to set skipDangerousModePermissionPrompt: ${t}`)}}async isChannelGateClosed(){if(this.channelGateClosed)return!0;try{const e=await I(f(R(),".claude.json"),"utf8"),i=JSON.parse(e).cachedGrowthBookFeatures;return!i||Object.keys(i).length===0?!1:i.tengu_harbor!==!0}catch{return!1}}async ensureClaudeOnboardingFlags(e){const t=f(R(),".claude.json");try{let i;try{const r=await I(t,"utf8");i=JSON.parse(r)}catch{i={}}let s=!1;i.hasCompletedOnboarding||(i.hasCompletedOnboarding=!0,i.lastOnboardingVersion||(i.lastOnboardingVersion="2.1.31"),s=!0),i.projects||(i.projects={});const n=i.projects;if(n[e]||(n[e]={}),n[e].hasCompletedProjectOnboarding||(n[e].hasCompletedProjectOnboarding=!0,s=!0),this.config.env?.ANTHROPIC_API_KEY===xe){const r=xe.slice(-20),a=i.customApiKeyResponses??{},l=a.approved??[],c=a.rejected??[];(!l.includes(r)||c.includes(r))&&(i.customApiKeyResponses={...a,approved:[...l.filter(u=>u!==r),r],rejected:c.filter(u=>u!==r)},s=!0)}if(!s)return;await D(t,JSON.stringify(i,null,2),"utf8"),o.info("claude-adapter",`Marked Claude onboarding complete: ${e}`)}catch(i){o.warn("claude-adapter",`Failed to mark Claude onboarding complete: ${i}`)}}async injectStatusLineSettings(e){try{const t=this.resolveProjectRoot(),i=f(t,"dist","scripts","status-line-forwarder.js"),s=f(e,".claude"),n=f(s,"settings.json");await F(s,{recursive:!0});let r={};try{r=JSON.parse(await I(n,"utf8"))}catch{}const l={type:"command",command:`node "${i.replace(/\\/g,"/")}"`,refreshInterval:10};r.statusLine=l;const c=`${JSON.stringify(r,null,2)}
|
|
18
|
-
`;await D(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=f(R(),".claude.json");let l=null;try{const p=await I(a,"utf8");l=JSON.parse(p)?.mcpServers?.[N]??null}catch{}if(l&&String(l.type||"stdio").trim()==="stdio"&&String(l.command??"").trim()===n&&Array.isArray(l.args)&&l.args.length===r.length&&l.args.every((p,m)=>p===r[m]))return;o.info("claude-adapter",`Registering user-scoped MCP server: ${N} -> ${n} ${r.join(" ")}`);try{ae(`${e} mcp remove -s user ${N}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe",windowsHide:!0})}catch{}const c=["mcp","add","--scope","user",N,"--",n,...r],u=process.platform==="win32"?'"':"'",h=ae(`${e} ${c.map(p=>`${u}${p}${u}`).join(" ")}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe",windowsHide:!0});o.info("claude-adapter",`MCP server registered: ${h.trim()||"ok"}`)}resolveServerEntryPath(e){const t=f(e,"server","main.js");try{if(j(t))return t}catch{}const i=f(e,"dist","index.js");try{if(j(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(),this.clearActiveEventPostReplyTimer(),this.clearActiveEventPostReplyWatcher(),this.clearRescueSettleTimer(),e&&(this.snapshotAuditBoundary(e),this.sessionIdConflictRetriedEventIds.delete(e.eventId),this.malformedToolRetriedEventIds.delete(e.eventId),this.lostInjectionRetriedEventIds.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.resetSelfDrivenTextBaseline()}startComposing(e,t){}stopComposing(){}clearComposingTimer(){}resolveHookSignalsPath(){const e=w(),t=this.claudeCliSessionId||this.sessionId;return f(e.dataDir,`hook-signals-${t}.json`)}startActivityTracking(){this.activityManager&&this.activityManager.stop();const e=this.resolveHookSignalsPath(),t=w().hookSignalsLogPath,i=new Rt(e,t);o.info("claude-adapter",`Activity tracking started: watching ${e}`),this.activityManager=new kt({hookSignalStore:i,onActivity:s=>this.onHookActivity(s),onTranscriptPath:s=>this.onHookTranscriptPath(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),onUserPromptSubmit:s=>this.onUserPromptSubmit(s)}),this.activityManager.start()}onHookTranscriptPath(e){this.claudeCliSessionId&&Bt(this.claudeCliSessionId,e)}onUserPromptSubmit(e){const t=this.activeEvent;!t||!e||e!==t.eventId||t.promptSubmittedAt!==void 0||(t.promptSubmittedAt=Date.now(),o.info("claude-adapter",`Prompt submitted for ${t.eventId}${t.channelPushedAt?` (${t.promptSubmittedAt-t.channelPushedAt}ms after push)`:""}`))}isChannelEventPrePush(e){return!e.singleTurnFallback&&e.channelPushedAt===void 0&&e.jsonlBaseOffset===void 0}isStopBeforePromptSubmit(e){return e.singleTurnFallback?!1:e.channelPushedAt===void 0?e.jsonlBaseOffset===void 0:e.promptSubmittedAt!==void 0?!1:Date.now()-e.channelPushedAt<pi}onClaudeTurnEnd(e){if(o.info("claude-adapter",`Hook activity: ${e}`),!this.activeEvent){this.stopHookBarrierSessionId&&(o.info("claude-adapter",`Late Stop hook after end_turn finalize \u2014 releasing barrier (session=${this.stopHookBarrierSessionId})`),this.clearStopHookBarrier()),this.deliverSelfDrivenText(e);return}if(this.activeEvent.toolCallInFlight){o.info("claude-adapter",`Stop hook deferred: toolCallInFlight for ${this.activeEvent.eventId}`),this.activeEvent.pendingStopHook=e;return}if(!this.isEventAnswered()&&this.isStopBeforePromptSubmit(this.activeEvent)){o.warn("claude-adapter",`${e} hook ignored for ${this.activeEvent.eventId}: arrived before this event's prompt was submitted (${Date.now()-(this.activeEvent.channelPushedAt??0)}ms after push) \u2014 startup/resume turn tail`);return}if(this.activeEvent.singleTurnFallback&&!this.isEventAnswered()){o.info("claude-adapter",`${e} hook ignored for ${this.activeEvent.eventId}: single-turn fallback owns finalization`);return}this.finalizeActiveEvent(e)}resolveIncrementalTextFromOffset(e,t){if(!this.isChannelEventPrePush(t)){if(t.textForwardOffset!==void 0)return t.textForwardOffset;if(t.jsonlBaseOffset!==void 0)return t.jsonlBaseOffset;if(t.singleTurnFallback){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return;const i=x(this.claudeCliSessionId,this.claudeSessionCwd);return y(i)?0:void 0}}}forwardIncrementalText(e){const t=this.activeEvent;if(!t||t.eventId!==e||this.isChannelEventPrePush(t)||t.replied||!this.claudeCliSessionId||!this.claudeSessionCwd)return;const i=this.resolveIncrementalTextFromOffset(e,t);if(i===void 0)return;const{segments:s,newOffset:n,apiError:r,apiErrorText:a}=$e(this.claudeCliSessionId,this.claudeSessionCwd,i);if(t.textForwardOffset=n,r&&(a&&(t.apiErrorText=a),t.apiFormatError||(t.apiFormatError=!0,o.error("claude-adapter",`API error entry detected in JSONL for ${e} (isApiErrorMessage), not forwarding its text as reply`))),s.length===0)return;const l=t.sessionId;for(const c of s){const u=c.trim();if(!u)continue;const h=`txt_${e}_${this.textForwardSeq++}`;this.bridgeCallbacks.sendStreamChunk(e,l,u,1,!1,h),this.bridgeCallbacks.sendStreamChunk(e,l,"",2,!0,h),t.textForwarded||(t.textForwarded=!0,t.repliedAt===void 0&&(t.repliedAt=Date.now()),this.startPostReplyDeadline(e),this.startPostReplyJsonlWatcher(e))}this.markActiveEventActivity(e,l),o.info("claude-adapter",`Forwarded ${s.length} plain-text segment(s) for ${e}`)}flushForwardedTail(e){this.activeEvent?.eventId===e&&this.activeEvent.textForwarded&&this.forwardIncrementalText(e)}isEventAnswered(e=this.activeEvent){return!!(e&&(e.replied||e.textForwarded))}attemptRescueFromJsonl(e,t){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return o.info("claude-adapter",`Rescue skipped: no claudeCliSessionId or claudeSessionCwd for ${e}`),"none";const i=this.activeEvent?.jsonlBaseOffset,s=W(this.claudeCliSessionId,this.claudeSessionCwd,i);if(s?.apiError)return o.error("claude-adapter",`Rescue aborted for ${e}: turn ended with a CLI API error entry (isApiErrorMessage)`),this.activeEvent?.eventId===e&&(this.activeEvent.apiFormatError=!0,s.apiErrorText&&(this.activeEvent.apiErrorText=s.apiErrorText)),"none";if(s?.metaOnly)return i===void 0?(o.warn("claude-adapter",`Rescue for ${e}: only CLI meta text found but jsonlBaseOffset is unset \u2014 cannot attribute it to this turn, treating as unanswered`),"none"):(o.info("claude-adapter",`Rescue skipped for ${e}: this turn wrote only CLI meta text, finalizing silently`),"silent");const n=s?.text||null;if(!n)return o.info("claude-adapter",`Rescue failed: no assistant text found in JSONL for ${e}`),"none";const r=`rescue_${e}_${Date.now()}`;return this.bridgeCallbacks.sendStreamChunk(e,t,n,1,!1,r),this.bridgeCallbacks.sendStreamChunk(e,t,"",2,!0,r),o.info("claude-adapter",`Rescue succeeded for event ${e}: sent ${n.length} chars from JSONL`),"sent"}warnUnsentFinalIfAny(e){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=this.activeEvent?.jsonlBaseOffset,i=W(this.claudeCliSessionId,this.claudeSessionCwd,t);if(!i||i.stopReason!=="end_turn")return;const s=i.text?.trim()??"";if(!s)return;const n=(this.activeEvent?.lastReplyText??"").trim();n&&(s===n||n.includes(s))||o.warn("claude-adapter",`Unsent final end_turn text for ${e} (${s.length} chars) not delivered \u2014 \u5DF2\u5E94\u7B54\u8FC7\uFF0C\u6309\u7B56\u7565\u4E0D\u8865\u53D1\uFF08\u7591\u4F3C\u56DE\u5408\u6536\u5C3E\u81EA\u8FF0\uFF1B\u82E5\u786E\u4E3A\u6F0F\u53D1\u7ED3\u8BBA\u53EF\u636E\u6B64\u6392\u67E5\uFF09`)}finalizeActiveEvent(e){if(!this.activeEvent)return;const t=this.activeEvent.eventId,i=this.activeEvent.sessionId;if(this.isEventAnswered()&&this.activeEvent.jsonlBaseOffset!==void 0&&this.claudeCliSessionId&&this.claudeSessionCwd){const s=W(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(s?.apiError)o.warn("claude-adapter",`Stop hook for ${t}: turn ended with a CLI API error entry, finalizing without waiting for end_turn`);else if(!s||s.stopReason!=="end_turn")if(Oe(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset))o.info("claude-adapter",`Stop hook: terminal tool_result detected for ${t} (grix_reply as final action, no end_turn expected), finalizing as responded`);else{o.info("claude-adapter",`Stop hook suppressed for ${t}: no end_turn in JSONL after offset=${this.activeEvent.jsonlBaseOffset} \u2014 likely resume-drain hook, waiting for JSONL watcher`),this.markActiveEventActivity(t,i);return}}if(this.flushForwardedTail(t),!this.activeEvent.apiFormatError){if(this.activeEvent.replied||this.activeEvent.textForwarded){this.activeEvent.replied&&!this.activeEvent.textForwarded&&this.warnUnsentFinalIfAny(t),this.finishTurnEnd(t,i,e,!0,`replied=${this.activeEvent.replied}, textForwarded=${this.activeEvent.textForwarded}`);return}if(this.activeEvent.rescueSettleInFlight){o.info("claude-adapter",`${e} ignored for ${t}: rescue retry already in flight`);return}const s=this.recoverMalformedToolCall(t);if(s==="retried")return;if(s==="exhausted"){this.bridgeCallbacks.sendStreamChunk(t,i,ni,1,!1,`mtc_${t}`),this.bridgeCallbacks.sendStreamChunk(t,i,"",2,!0,`mtc_${t}`),this.finishTurnEnd(t,i,e,!0,"malformed-toolcall-fallback");return}const n=this.attemptRescueFromJsonl(t,i);if(n!=="none"){this.finishTurnEnd(t,i,e,!0,n==="silent"?"no-response-requested":"rescued");return}if(this.activeEvent?.apiFormatError){this.finishTurnEnd(t,i,e,!1,"apiFormatError (detected during rescue)");return}this.beginRescueSettleWait(t,i,e);return}this.finishTurnEnd(t,i,e,!1,"apiFormatError")}beginRescueSettleWait(e,t,i){if(!this.activeEvent||this.activeEvent.eventId!==e)return;this.activeEvent.rescueSettleInFlight=!0;const s=Math.max(1,Math.ceil(Ye/Je));let n=0;const r=()=>{if(this.rescueSettleTimer=null,this.stopped)return;const a=this.activeEvent;if(!a||a.eventId!==e)return;if(n++,a.replied||a.textForwarded){this.finishTurnEnd(e,t,i,!0,`replied=${a.replied}, textForwarded=${a.textForwarded} (settled during flush wait)`);return}if(a.apiFormatError){this.finishTurnEnd(e,t,i,!1,"apiFormatError (settled during flush wait)");return}const l=this.attemptRescueFromJsonl(e,t);if(l!=="none"){this.finishTurnEnd(e,t,i,!0,l==="silent"?"no-response-requested-after-settle":"rescued-after-settle");return}if(a.apiFormatError){this.finishTurnEnd(e,t,i,!1,"apiFormatError (detected during rescue after settle)");return}if(i==="Stop"&&this.isToolOnlyTurnConcluded(a)){this.finishTurnEnd(e,t,i,!0,`tool-only-turn (toolCalls=${a.toolActivityCount??0})`);return}if(n>=s){this.finishTurnEnd(e,t,i,!1,`rescue-failed-after-settle (waited ~${Math.round(Ye/1e3)}s, no transcript output for this turn)`);return}this.markActiveEventActivity(e,t),this.rescueSettleTimer=setTimeout(r,Je)};this.rescueSettleTimer=setTimeout(r,Zt)}isToolOnlyTurnConcluded(e){return!e.toolActivityCount||e.jsonlBaseOffset===void 0||!this.claudeCliSessionId||!this.claudeSessionCwd?!1:de(this.claudeCliSessionId,this.claudeSessionCwd,e.jsonlBaseOffset).lastStopReason==="end_turn"}clearRescueSettleTimer(){this.rescueSettleTimer&&(clearTimeout(this.rescueSettleTimer),this.rescueSettleTimer=null)}finishTurnEnd(e,t,i,s,n){if(s)o.info("claude-adapter",`Stop hook received, finalizing event ${e} as responded (${n})`),this.bridgeCallbacks.sendEventResult(e,"responded");else{o.warn("claude-adapter",`Active event not confirmed when ${i}: ${e} (${n}), sending failed result`);const r=this.activeEvent?.apiFormatError?ue(this.activeEvent.apiErrorText):"Claude exited before completing its reply. Please try again.";this.bridgeCallbacks.sendStreamChunk(e,t,r,1,!1,`err_${e}`),this.bridgeCallbacks.sendStreamChunk(e,t,"",2,!0,`err_${e}`),this.bridgeCallbacks.sendEventResult(e,"failed",r,"agent_stop_failure",!0)}this.clearActiveEvent(),this.armStopHookBarrier(t)}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.isChannelEventPrePush(this.activeEvent)&&(this.activeEvent.toolActivityCount=(this.activeEvent.toolActivityCount??0)+1,this.markActiveEventActivity(this.activeEvent.eventId,this.activeEvent.sessionId),this.forwardIncrementalText(this.activeEvent.eventId),(this.activeEvent.replied||this.activeEvent.textForwarded)&&this.startPostReplyDeadline(this.activeEvent.eventId)),e&&!this.activeEvent&&!this.compacting&&this.noteSelfDrivenActivity(e),!!t)if(e){this.startComposing(t,e);const i=this.activeEvent;if(i&&!this.isChannelEventPrePush(i)){const s=e.event_name,n=e.tool_name,r=e.tool_input??"",a=n?xt(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)a||this.bridgeCallbacks.sendToolUse(i.eventId,i.sessionId,n,r);else if((s==="PostToolUse"||s==="PostToolUseFailure")&&n){if(n==="AskUserQuestion")return;!a&&s==="PostToolUseFailure"&&this.bridgeCallbacks.sendToolResult(i.eventId,i.sessionId,n,"(failed)")}}}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=w();new z(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 l=a.request_id;this.pendingPermissions.set(l,{eventId:i.eventId,sessionId:i.sessionId});const c=typeof t=="string"?t:"";if(e==="ExitPlanMode"){const p=zt(c);p&&this.bridgeCallbacks.sendReply(i.eventId,i.sessionId,p)}const u=e==="ExitPlanMode"?"":c.slice(0,100),h=u?`${e}: ${u}`:e;this.bridgeCallbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,approvalId:l,toolName:e,toolTitle:h}),o.info("claude-adapter",`Sent permission card: approvalId=${l} tool=${e}`)}).catch(r=>{o.warn("claude-adapter",`Failed to send permission card: ${r}`)})}async awaitPendingQuestionRequest(e,t){const i=Date.now()+je;for(;;){const s=await e.listPending(),n=Date.now(),r=[...s].reverse().filter(l=>String(l.session_id??"").trim()===this.claudeCliSessionId&&n-Number(l.created_at??0)<=Ne),a=r.find(l=>String(l.event_id??"").trim()===t)??r.find(l=>String(l.event_id??"").trim()==="")??r[0]??null;if(a||Date.now()>=i)return a;await new Promise(l=>setTimeout(l,Kt))}}handleAskUserQuestion(e,t){const i=Le(t);if(!i){o.warn("claude-adapter","Failed to parse AskUserQuestion input, skipping agent_question card");return}const s=w(),n=new Re(s.questionRequestsDir);this.awaitPendingQuestionRequest(n,e.eventId).then(async r=>{const a=r?.request_id??`fallback-${Date.now()}`;r||o.warn("claude-adapter",`No pending question waiter after ${je}ms; sending card with ${a}. Submitting it will report not_pending and fall back to a plain message.`),r&&String(r.event_id??"").trim()===""&&await n.updateRequest(r.request_id,{event_id:e.eventId}),this.pendingQuestion.set(a,{eventId:e.eventId,sessionId:e.sessionId}),e.awaitingUserQuestion=!0;const c=(Number(r?.created_at??0)>0?Number(r?.created_at):Date.now())+Fe;this.bridgeCallbacks.sendAgentQuestionCard(e.eventId,e.sessionId,{request_id:a,mode:"form",questions:i,expires_at:c}),o.info("claude-adapter",`Sent agent_question card: request_id=${a} questions=${i.length}`)}).catch(()=>{o.warn("claude-adapter","Failed to list pending questions from store")})}parseAskUserQuestions(e){return Le(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}`),l=String(r.prompt??""),c=Array.isArray(r.options)?r.options:void 0,u=r.multiSelect===!0;i.push({header:a,prompt:l,...c&&c.length>0?{options:c}:{},...u?{multi_select:!0}:{}})}return i.length>0?{questions:i}:null}pruneCompletedEvents(){const e=Date.now()-Qt;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.isEventAnswered(i)||this.resetActiveEventHardTimer(i.eventId)))}clearActiveEventIdleTimer(){this.activeEventIdleTimer&&(clearTimeout(this.activeEventIdleTimer),this.activeEventIdleTimer=null)}clearActiveEventHardTimer(){this.activeEventHardTimer&&(clearTimeout(this.activeEventHardTimer),this.activeEventHardTimer=null)}shouldExtendByLiveness(e){const t=this.activeEvent;if(!t||t.eventId!==e||!this.claudeCliSessionId||!this.claudeSessionCwd)return!1;const i=this.singleTurnFallbackChild,s=!!i&&i.exitCode===null&&!i.killed;if(!this.claudeProcess&&!this.claudePty&&!s)return!1;if(this.lastPtyOutputAt>0&&Date.now()-this.lastPtyOutputAt<Ke)return t.livenessExtendStartAt=Date.now(),!0;const n=de(this.claudeCliSessionId,this.claudeSessionCwd,t.jsonlBaseOffset);if(n.freshMs===null||!(t.jsonlBaseOffset===void 0?n.freshMs<he:n.lastStopReason!==null?n.lastStopReason!=="end_turn":n.freshMs<he))return!1;if(n.freshMs<he)t.livenessExtendStartAt=Date.now();else{const a=t.livenessExtendStartAt??Date.now();if(t.livenessExtendStartAt===void 0&&(t.livenessExtendStartAt=a),Date.now()-a>Ve)return o.warn("claude-adapter",`Liveness extension budget exhausted for ${e} (no JSONL writes for ${Math.round((Date.now()-a)/6e4)}min), allowing close`),!1}return o.info("claude-adapter",`Liveness check: turn in progress for ${e} (lastStopReason=${n.lastStopReason??"none"}, freshMs=${n.freshMs}), extending`),!0}captureEventJsonlBaseOffset(e,t){this.captureAuditTranscriptStart(e);const i=this.activeEvent;if(!(!i||i.eventId!==e)&&!(!t?.force&&i.jsonlBaseOffset!==void 0)&&!(!this.claudeCliSessionId||!this.claudeSessionCwd))try{const s=x(this.claudeCliSessionId,this.claudeSessionCwd);if(i.auditTranscriptPath===s&&i.auditTranscriptStartOffset!==void 0){i.jsonlBaseOffset=i.auditTranscriptStartOffset;return}i.jsonlBaseOffset=y(s)?k(s).size:0}catch{i.jsonlBaseOffset=0}}captureSingleTurnFallbackJsonlBaseOffset(e){this.captureAuditTranscriptStart(e);const t=this.activeEvent;if(!(!t||t.eventId!==e||t.jsonlBaseOffset!==void 0)&&!(!this.claudeCliSessionId||!this.claudeSessionCwd))try{const i=x(this.claudeCliSessionId,this.claudeSessionCwd);if(!y(i))return;if(t.auditTranscriptPath===i&&t.auditTranscriptStartOffset!==void 0){t.jsonlBaseOffset=t.auditTranscriptStartOffset;return}t.jsonlBaseOffset=k(i).size}catch{}}captureAuditTranscriptStart(e){const t=this.activeEvent;if(!t||t.eventId!==e||t.rawEvent?.audit?.enabled!==!0||t.auditTranscriptStartOffset!==void 0||!this.claudeCliSessionId)return;const i=this.claudeSessionCwd||process.cwd(),s=x(this.claudeCliSessionId,i);t.auditTranscriptPath=s,t.auditClaudeSessionId=this.claudeCliSessionId;try{t.auditTranscriptStartOffset=y(s)?k(s).size:0}catch{t.auditTranscriptStartOffset=0}const n=this.auditEvidencePaths;n&&(t.auditOtelLogsStartOffset=X(n.logsPath),t.auditOtelTracesStartOffset=X(n.tracesPath),n.rawProviderBody&&(t.auditRawBodyFilesBefore=ze(n.rawBodyDir)))}snapshotAuditBoundary(e){if(e.rawEvent?.audit?.enabled!==!0)return;if(e.auditTranscriptStartOffset===void 0||!e.auditTranscriptPath||!e.auditClaudeSessionId){this.completedAuditBoundaries.set(e.eventId,Object.freeze({adapterType:this.type}));return}const t=this.claudeSessionCwd?x(e.auditClaudeSessionId,this.claudeSessionCwd):e.auditTranscriptPath,i=y(t)?t:e.auditTranscriptPath;let s=e.auditTranscriptStartOffset;try{s=y(i)?k(i).size:e.auditTranscriptStartOffset}catch{}const n=yt(i),r=this.auditEvidencePaths,a=new Set(e.auditRawBodyFilesBefore??[]),l=r?.rawProviderBody?ze(r.rawBodyDir).filter(u=>!a.has(u)):[],c=Object.freeze({adapterType:this.type,providerSessionId:e.auditClaudeSessionId,transcriptPath:i,transcriptStartOffset:e.auditTranscriptStartOffset,transcriptEndOffset:s,...e.auditSingleTurnFallback?{singleTurnFallback:!0}:{},subagentRoot:f(n,e.auditClaudeSessionId,"subagents"),...r?{otelLogsPath:r.logsPath,otelLogsStartOffset:e.auditOtelLogsStartOffset??0,otelLogsEndOffset:X(r.logsPath),otelTracesPath:r.tracesPath,otelTracesStartOffset:e.auditOtelTracesStartOffset??0,otelTracesEndOffset:X(r.tracesPath),rawApiBodyDirectory:r.rawBodyDir,rawApiBodyPaths:l}:{}});this.completedAuditBoundaries.set(e.eventId,c)}noteSelfDrivenActivity(e){!this.selfDrivenActive&&this.lastClearedEvent&&Date.now()-this.lastClearedEvent.ts<Xe||(this.selfDrivenLastSignalAt=Date.now(),e&&(this.selfDrivenLabel=di(e)),!this.selfDrivenActive&&(this.selfDrivenActive=!0,o.info("claude-adapter",`Self-driven activity detected for session ${this.sessionId} (no active event), debouncing before reporting working state`),this.selfDrivenReportTimer=setTimeout(()=>{this.selfDrivenReportTimer=null,!(!this.selfDrivenActive||this.stopped||this.activeEvent)&&(this.selfDrivenReported=!0,o.info("claude-adapter",`Self-driven working state confirmed for session ${this.sessionId} (sustained >${Qe/1e3}s), reporting`),this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0))},Qe),this.selfDrivenReportTimer.unref(),this.selfDrivenSweepTimer=setInterval(()=>this.sweepSelfDriven(),oi),this.selfDrivenSweepTimer.unref()))}sweepSelfDriven(){if(!this.selfDrivenActive)return;if(this.stopped||this.activeEvent){this.stopSelfDriven();return}const e=Date.now()-this.selfDrivenLastSignalAt;if(this.claudeCliSessionId&&this.claudeSessionCwd){const t=de(this.claudeCliSessionId,this.claudeSessionCwd),i=t.lastStopReason!==null&&t.lastStopReason!=="end_turn",s=t.freshMs!==null&&t.freshMs<Ve,n=jt(this.claudeCliSessionId,this.claudeSessionCwd)>0;if((i||n)&&s){this.selfDrivenReported&&this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0);return}}if(e<ai){this.selfDrivenReported&&this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0);return}o.info("claude-adapter",`Self-driven activity ended for session ${this.sessionId} (quiet for ${Math.round(e/1e3)}s, no pending work)`),this.stopSelfDriven()}stopSelfDriven(){this.selfDrivenSweepTimer&&(clearInterval(this.selfDrivenSweepTimer),this.selfDrivenSweepTimer=null),this.selfDrivenReportTimer&&(clearTimeout(this.selfDrivenReportTimer),this.selfDrivenReportTimer=null),this.selfDrivenActive&&(this.selfDrivenActive=!1,this.selfDrivenLabel=null,this.selfDrivenReported&&(this.selfDrivenReported=!1,this.emit("sessionActivity",this.sessionId??"",!1)))}currentTranscriptSize(){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return null;try{return k(x(this.claudeCliSessionId,this.claudeSessionCwd)).size}catch{return null}}resetSelfDrivenTextBaseline(){this.clearSelfDrivenDeliverTimer(),this.selfDrivenReplied=!1,this.selfDrivenTextOffset=this.currentTranscriptSize()}clearSelfDrivenDeliverTimer(){this.selfDrivenDeliverTimer&&(clearTimeout(this.selfDrivenDeliverTimer),this.selfDrivenDeliverTimer=null)}deliverSelfDrivenText(e){if(this.stopped||this.activeEvent)return;this.clearSelfDrivenDeliverTimer();const t=this.currentTranscriptSize();if(t===null)return;if(this.selfDrivenTextOffset===null){this.selfDrivenTextOffset=t;return}if(this.lastClearedEvent&&Date.now()-this.lastClearedEvent.ts<Xe){this.selfDrivenTextOffset=t;return}if(this.selfDrivenReplied){this.selfDrivenReplied=!1,this.selfDrivenTextOffset=t;return}const i=Date.now()+ci,s=()=>{if(this.selfDrivenDeliverTimer=null,!(this.stopped||this.activeEvent)&&!this.flushSelfDrivenText(e)){if(Date.now()>=i){o.info("claude-adapter",`Self-driven ${e}: no new transcript text to deliver for session ${this.sessionId}`);return}this.selfDrivenDeliverTimer=setTimeout(s,li),this.selfDrivenDeliverTimer.unref()}};s()}flushSelfDrivenText(e){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return!1;const t=this.selfDrivenTextOffset??0,{segments:i,newOffset:s}=$e(this.claudeCliSessionId,this.claudeSessionCwd,t);this.selfDrivenTextOffset=s;const n=i.map(a=>a.trim()).filter(a=>a.length>0);if(n.length===0)return!1;const r=this.sessionId;if(!r)return o.warn("claude-adapter",`Self-driven ${e}: ${n.length} text segment(s) ready but session id is unknown, dropping`),!0;for(const a of n)De(this.getEventToolHandle(),"grix_reply",{session_id:r,text:a});return o.info("claude-adapter",`Self-driven ${e}: delivered ${n.length} text segment(s) to session ${r}`),!0}tryRecoverLostInjection(e){const t=this.activeEvent;if(this.stopped||!t||t.eventId!==e||this.isEventAnswered(t)||t.channelPushedAt===void 0||t.promptSubmittedAt!==void 0||this.compacting||this.stopHookBarrierSessionId===t.sessionId||this.lostInjectionRetriedEventIds.has(e))return!1;this.lostInjectionRetriedEventIds.add(e);const i=t.rawEvent;return o.warn("claude-adapter",`Lost injection for ${e}: pushed ${Date.now()-t.channelPushedAt}ms ago but prompt never submitted \u2014 respawning Claude and re-pushing the event once`),this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),this.activeEvent=null,this.stopComposing(),this.killClaudeProcess(Ue),this.deliverInboundEvent(i),!0}resetActiveEventIdleTimer(e){this.clearActiveEventIdleTimer(),this.activeEventIdleTimer=setTimeout(()=>{if(!this.stopped&&this.activeEvent?.eventId===e){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}if(this.shouldExtendByLiveness(e)){this.resetActiveEventIdleTimer(e);return}this.tryRecoverLostInjection(e)||this.finalizeStuckActiveEvent(e,"idle")}},Be)}finalizeStuckActiveEvent(e,t){const i=this.isEventAnswered(),s=i?"responded":"failed",n=t==="idle"?Be:He,r=!i&&this.activeEvent?.apiFormatError?ue(this.activeEvent.apiErrorText):void 0,a=i?void 0:r??(t==="idle"?`agent idle for ${n/1e3}s`:`agent exceeded max duration ${n/1e3}s`),l=i?void 0:t==="idle"?"agent_idle_timeout":"agent_hard_timeout",c=this.lostInjectionRetriedEventIds.has(e)?", after lost-injection retry":"";o.error("claude-adapter",`Active event ${t} timeout (${n/1e3}s): ${e}, answered=${i}${c}, sending ${s}`),this.flushForwardedTail(e),this.completedEventIds.set(e,Date.now());let u=!1;r&&this.activeEvent&&(this.bridgeCallbacks.sendStreamChunk(e,this.activeEvent.sessionId,r,1,!1,`err_${e}`),this.bridgeCallbacks.sendStreamChunk(e,this.activeEvent.sessionId,"",2,!0,`err_${e}`),u=!0),u?this.bridgeCallbacks.sendEventResult(e,s,a,l,!0):this.bridgeCallbacks.sendEventResult(e,s,a,l),this.clearActiveEvent(),s==="failed"&&this.emit("stuck")}resetActiveEventHardTimer(e){this.clearActiveEventHardTimer(),this.activeEventHardTimer=setTimeout(()=>{if(!this.stopped&&this.activeEvent?.eventId===e){if(this.shouldExtendByLiveness(e)){this.resetActiveEventHardTimer(e);return}this.finalizeStuckActiveEvent(e,"hard")}},He)}clearActiveEventPostReplyTimer(){this.activeEventPostReplyTimer&&(clearTimeout(this.activeEventPostReplyTimer),this.activeEventPostReplyTimer=null)}clearActiveEventPostReplyWatcher(){if(this.activeEventPostReplyWatcher){try{this.activeEventPostReplyWatcher.close()}catch{}this.activeEventPostReplyWatcher=null}this.activeEventPostReplyPoll&&(clearInterval(this.activeEventPostReplyPoll),this.activeEventPostReplyPoll=null)}startPostReplyJsonlWatcher(e){if(this.clearActiveEventPostReplyWatcher(),!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=x(this.claudeCliSessionId,this.claudeSessionCwd);if(!this.activeEvent?.sessionId)return;if(!y(t)){o.info("claude-adapter",`JSONL watcher skipped: file not yet available for ${e}`);return}const s=k(t).size;this.activeEvent&&(this.activeEvent.jsonlBaseOffset=s);let n=null;try{this.activeEventPostReplyWatcher=_t(t,()=>{n&&clearTimeout(n),n=setTimeout(()=>this.finalizeIfEndTurn(e),300)}),this.activeEventPostReplyPoll=setInterval(()=>this.finalizeIfEndTurn(e),ri),o.info("claude-adapter",`JSONL watcher started for ${e} at ${t} (baseOffset=${s})`)}catch(r){o.warn("claude-adapter",`JSONL watcher start failed for ${e}: ${r}`)}}finalizeIfEndTurn(e){if(this.stopped||this.activeEvent?.eventId!==e||this.isChannelEventPrePush(this.activeEvent)||!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=W(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(t?.apiError){this.activeEvent.apiFormatError=!0,t.apiErrorText&&(this.activeEvent.apiErrorText=t.apiErrorText);return}if(t&&t.stopReason==="end_turn"){o.info("claude-adapter",`JSONL watcher: end_turn detected for ${e}, finalizing as responded`);const i=this.activeEvent.sessionId;this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent(),this.armStopHookBarrier(i);return}if(this.activeEvent?.replied&&this.activeEvent.jsonlBaseOffset!==void 0&&Oe(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset,!0)){if(this.lastPtyOutputAt>0&&Date.now()-this.lastPtyOutputAt<Ke)return;o.info("claude-adapter",`JSONL poll: terminal tool_result detected for ${e} (file quiet, no end_turn), finalizing as responded`),this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent()}}startPostReplyDeadline(e){this.clearActiveEventPostReplyTimer(),this.clearActiveEventHardTimer(),this.activeEventPostReplyTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e||!this.activeEvent?.replied&&!this.activeEvent?.textForwarded)return;if(this.shouldExtendByLiveness(e)){this.startPostReplyDeadline(e);return}const t=this.activeEvent.repliedAt,i=Math.round((Date.now()-t)/1e3);o.info("claude-adapter",`Post-reply deadline reached for ${e} (${i}s since reply), completing as responded`),this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent()},ti)}beginCompaction(){this.compacting||(this.compacting=!0,o.info("claude-adapter","Compaction started; gating input"),this.emit("pauseIntake","compaction"),this.resetCompactingActivityTimer())}resetCompactingActivityTimer(){this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{o.warn("claude-adapter","Compaction stall: no PTY activity for 90s, emitting stuck"),this.emit("stuck")},9e4),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}); resuming intake`),this.emit("resumeIntake","compaction");const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.(e)}armStopHookBarrier(e){this.stopHookBarrierTimer&&clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierSessionId=e,this.emit("pauseIntake","barrier"),this.stopHookBarrierTimer=setTimeout(()=>{this.stopHookBarrierSessionId===e&&(o.warn("claude-adapter",`Stop hook barrier timeout for session=${e}`),this.clearStopHookBarrier())},fi)}clearStopHookBarrier(){const e=this.stopHookBarrierSessionId!==null;this.stopHookBarrierSessionId=null,this.stopHookBarrierTimer&&(clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierTimer=null),e&&this.emit("resumeIntake","barrier")}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,t=this.activeEvent.sessionId;this.bridgeCallbacks.sendStreamChunk(e,t,`
|
|
17
|
+
`)}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(){Ri(this.notifyPort),this.notifyPort=0}killClaudeProcess(e){const t=this.claudeProcess,i=this.claudePty,s=this.claudeChildPid;if(e==="single-turn fallback isolation"&&(t&&this.singleTurnFallbackProcesses.add(t),i&&this.singleTurnFallbackPtys.add(i)),e===We&&(t&&this.lostInjectionKilledProcesses.add(t),i&&this.lostInjectionKilledPtys.add(i)),this.claudeProcess=null,this.claudePty=null,this.claudeChildPid=0,this.spawnPromise=null,this.alive=!1,this.stopMcpServer(),this.releaseNotifyPortReservation(),this.mcpChannelBroken=!1,this.channelGateClosed=!1,this.startupChannelListening=!1,this.startupChannelListeningAt=0,this.deferredModelId=null,this.clearPendingMcpFailureTimer(),this.clearWindowsTrustDialogTimer(),this.windowsTrustDialogAnswered=!1,this.sessionIdConflictDetected=!1,this.pendingPermissions.size>0){const n=S(),r=new W(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&&N(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&&N(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.isEventAnswered())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}recoverMalformedToolCall(e){if(this.stopped||!this.activeEvent||this.isEventAnswered()||!this.claudeCliSessionId||!this.claudeSessionCwd)return"none";const t=z(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(!t||t.stopReason!=="stop_sequence"||t.text.trim()!==ai)return"none";if(this.malformedToolRetriedEventIds.has(e))return o.warn("claude-adapter",`Malformed tool-call retry exhausted for ${e}, sending clean fallback`),"exhausted";this.malformedToolRetriedEventIds.add(e);const i={...this.activeEvent.rawEvent,content:oi};return o.warn("claude-adapter",`Detected malformed tool-call, silently retrying event once: ${e}`),this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),this.activeEvent=null,this.stopComposing(),this.deliverInboundEvent(i),"retried"}async handleInternalInvoke(e,t,i,s){if(e==="mcp_stdio_log")return o.info("claude-mcp-stdio",String(t.message??"")),{ok:!0};if(e==="event_tool_call"){const n=String(t.tool_name??""),r=Nt(n,{...t.arguments??{}}),a=this.getEventToolHandle();if(this.activeEvent){const c=this.activeEvent,u=String(r.event_id??"").trim();u===""?r.event_id=c.eventId:(n==="grix_reply"||n==="grix_complete")&&u!==c.eventId&&(o.warn("claude-adapter",`${n}: event_id mismatch, correcting: supplied=${u}, active=${c.eventId}`),r.event_id=c.eventId);const h=String(r.session_id??"").trim();if(n==="grix_reply"?(h&&h!==c.sessionId&&o.warn("claude-adapter",`${n}: session_id mismatch, correcting: supplied=${h}, active=${c.sessionId}`),r.session_id=c.sessionId):h===""&&(r.session_id=c.sessionId),n==="grix_reply"&&String(r.quoted_message_id??"").trim()===""){const p=String(c.rawEvent?.msg_id??"").trim();p&&(r.quoted_message_id=p)}n==="grix_reply"&&o.info("claude-adapter",`grix_reply quote: rawEvent.msg_id=${String(c.rawEvent?.msg_id??"")||"(none)"} -> quoted_message_id=${String(r.quoted_message_id??"")||"(none)"}`)}else if(this.lastClearedEvent&&n==="grix_reply"){const c=this.lastClearedEvent;Date.now()-c.ts<vi&&(String(r.session_id??"").trim()===""&&(r.session_id=c.sessionId),r.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)`))}!this.activeEvent&&n==="grix_reply"&&(this.selfDrivenReplied=!0),n==="grix_reply"&&String(r.event_id??"").trim()!==""&&this.completedEventIds.has(String(r.event_id??"").trim())&&(o.info("claude-adapter",`Late grix_reply fallback: sending direct message for completed event ${String(r.event_id??"").trim()}`),r.event_id="");const l=Mt(n,r);if(!l.valid)throw new Error(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${l.error}`);if(a.status!=="ready")throw new Error(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${a.status}`);if(Lt(n)){const c=this.activeEvent;c&&(c.toolCallInFlight=!0);try{if(i?.aborted)throw new Error("invoke aborted by timeout");const u=Le(a,n,r);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(n,r),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: ${n}`)}return this.bridgeCallbacks.agentInvoke(e,t,s)}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"){const s=!this.activeEvent.replied;this.activeEvent.replied=!0;const n=String(t.text??"");n.length>0&&(this.activeEvent.lastReplyText=n),this.markActiveEventActivity(i,String(t.session_id??"").trim()||void 0),s&&(this.activeEvent.repliedAt=Date.now(),this.startPostReplyDeadline(i),this.startPostReplyJsonlWatcher(i))}}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 De(t)}catch{throw new Error(`pluginDir is not accessible: ${t}`)}if(!i.isDirectory())throw new Error(`pluginDir is not a directory: ${t}`);const s=f(t,".mcp.json");try{(await De(s)).isFile()&&(await Re(s),o.info("claude-adapter",`Removed conflicting .mcp.json from pluginDir: ${s}`))}catch{}}async ensureWorkspaceTrust(e){const t=f(D(),".claude.json");let i=e;try{i=Ae(e)}catch{}const s=i===e?[e]:[e,i];try{const n=await I(t,"utf8"),r=JSON.parse(n.replace(/^\uFEFF/,""));r.projects||(r.projects={});let a=!1;for(const l of s)r.projects[l]?.hasTrustDialogAccepted!==!0&&(r.projects[l]||(r.projects[l]={}),r.projects[l].hasTrustDialogAccepted=!0,a=!0);if(!a)return;await R(t,JSON.stringify(r),"utf8"),o.info("claude-adapter",`Pre-trusted workspace: ${s.join(", ")}`)}catch(n){o.warn("claude-adapter",`Failed to pre-trust workspace ${e}: ${n}`)}}async ensureSkipDangerousPermissionPrompt(){const e=f(D(),".claude","settings.json");try{let t={};try{t=JSON.parse(await I(e,"utf8"))}catch{}if(t.skipDangerousModePermissionPrompt===!0)return;t.skipDangerousModePermissionPrompt=!0,await O(f(D(),".claude"),{recursive:!0}),await R(e,JSON.stringify(t,null,2),"utf8"),o.info("claude-adapter","Set skipDangerousModePermissionPrompt=true in user settings to skip BypassPermissions dialog")}catch(t){o.warn("claude-adapter",`Failed to set skipDangerousModePermissionPrompt: ${t}`)}}async buildFullAutoSettingsArgs(e){if(e.some(i=>String(i).trim().toLowerCase().startsWith("--settings")))return[];const t=Gi();try{return await O($e(t),{recursive:!0}),await R(t,JSON.stringify({permissions:{blockReadsOutsideWorkingDirectories:!1}},null,2),"utf8"),["--settings",t]}catch(i){return o.warn("claude-adapter",`Failed to write full_auto settings override: ${i}`),[]}}async isChannelGateClosed(){if(this.channelGateClosed)return!0;try{const e=await I(f(D(),".claude.json"),"utf8"),i=JSON.parse(e).cachedGrowthBookFeatures;return!i||Object.keys(i).length===0?!1:i.tengu_harbor!==!0}catch{return!1}}async ensureClaudeOnboardingFlags(e){const t=f(D(),".claude.json");try{let i;try{const r=await I(t,"utf8");i=JSON.parse(r)}catch{i={}}let s=!1;i.hasCompletedOnboarding||(i.hasCompletedOnboarding=!0,i.lastOnboardingVersion||(i.lastOnboardingVersion="2.1.31"),s=!0),i.projects||(i.projects={});const n=i.projects;if(n[e]||(n[e]={}),n[e].hasCompletedProjectOnboarding||(n[e].hasCompletedProjectOnboarding=!0,s=!0),this.config.env?.ANTHROPIC_API_KEY===Ne){const r=Ne.slice(-20),a=i.customApiKeyResponses??{},l=a.approved??[],c=a.rejected??[];(!l.includes(r)||c.includes(r))&&(i.customApiKeyResponses={...a,approved:[...l.filter(u=>u!==r),r],rejected:c.filter(u=>u!==r)},s=!0)}if(!s)return;await R(t,JSON.stringify(i,null,2),"utf8"),o.info("claude-adapter",`Marked Claude onboarding complete: ${e}`)}catch(i){o.warn("claude-adapter",`Failed to mark Claude onboarding complete: ${i}`)}}async injectStatusLineSettings(e){try{const t=this.resolveProjectRoot(),i=f(t,"dist","scripts","status-line-forwarder.js"),s=f(e,".claude"),n=f(s,"settings.json");await O(s,{recursive:!0});let r={};try{r=JSON.parse(await I(n,"utf8"))}catch{}const l={type:"command",command:`node "${i.replace(/\\/g,"/")}"`,refreshInterval:10};r.statusLine=l;const c=`${JSON.stringify(r,null,2)}
|
|
18
|
+
`;await R(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=f(D(),".claude.json");let l=null;try{const p=await I(a,"utf8");l=JSON.parse(p)?.mcpServers?.[j]??null}catch{}if(l&&String(l.type||"stdio").trim()==="stdio"&&String(l.command??"").trim()===n&&Array.isArray(l.args)&&l.args.length===r.length&&l.args.every((p,m)=>p===r[m]))return;o.info("claude-adapter",`Registering user-scoped MCP server: ${j} -> ${n} ${r.join(" ")}`);try{oe(`${e} mcp remove -s user ${j}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe",windowsHide:!0})}catch{}const c=["mcp","add","--scope","user",j,"--",n,...r],u=process.platform==="win32"?'"':"'",h=oe(`${e} ${c.map(p=>`${u}${p}${u}`).join(" ")}`,{encoding:"utf8",timeout:1e4,env:i,stdio:"pipe",windowsHide:!0});o.info("claude-adapter",`MCP server registered: ${h.trim()||"ok"}`)}resolveServerEntryPath(e){const t=f(e,"server","main.js");try{if(B(t))return t}catch{}const i=f(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(),this.clearActiveEventPostReplyTimer(),this.clearActiveEventPostReplyWatcher(),this.clearRescueSettleTimer(),e&&(this.snapshotAuditBoundary(e),this.sessionIdConflictRetriedEventIds.delete(e.eventId),this.malformedToolRetriedEventIds.delete(e.eventId),this.lostInjectionRetriedEventIds.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.resetSelfDrivenTextBaseline()}startComposing(e,t){}stopComposing(){}clearComposingTimer(){}resolveHookSignalsPath(){const e=S(),t=this.claudeCliSessionId||this.sessionId;return f(e.dataDir,`hook-signals-${t}.json`)}startActivityTracking(){this.activityManager&&this.activityManager.stop();const e=this.resolveHookSignalsPath(),t=S().hookSignalsLogPath,i=new Ot(e,t);o.info("claude-adapter",`Activity tracking started: watching ${e}`),this.activityManager=new $t({hookSignalStore:i,onActivity:s=>this.onHookActivity(s),onTranscriptPath:s=>this.onHookTranscriptPath(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),onUserPromptSubmit:s=>this.onUserPromptSubmit(s)}),this.activityManager.start()}onHookTranscriptPath(e){this.claudeCliSessionId&&qt(this.claudeCliSessionId,e)}onUserPromptSubmit(e){const t=this.activeEvent;!t||!e||e!==t.eventId||t.promptSubmittedAt!==void 0||(t.promptSubmittedAt=Date.now(),o.info("claude-adapter",`Prompt submitted for ${t.eventId}${t.channelPushedAt?` (${t.promptSubmittedAt-t.channelPushedAt}ms after push)`:""}`))}isChannelEventPrePush(e){return!e.singleTurnFallback&&e.channelPushedAt===void 0&&e.jsonlBaseOffset===void 0}isStopBeforePromptSubmit(e){return e.singleTurnFallback?!1:e.channelPushedAt===void 0?e.jsonlBaseOffset===void 0:e.promptSubmittedAt!==void 0?!1:Date.now()-e.channelPushedAt<Ei}onClaudeTurnEnd(e){if(o.info("claude-adapter",`Hook activity: ${e}`),!this.activeEvent){this.stopHookBarrierSessionId&&(o.info("claude-adapter",`Late Stop hook after end_turn finalize \u2014 releasing barrier (session=${this.stopHookBarrierSessionId})`),this.clearStopHookBarrier()),this.deliverSelfDrivenText(e);return}if(this.activeEvent.toolCallInFlight){o.info("claude-adapter",`Stop hook deferred: toolCallInFlight for ${this.activeEvent.eventId}`),this.activeEvent.pendingStopHook=e;return}if(!this.isEventAnswered()&&this.isStopBeforePromptSubmit(this.activeEvent)){o.warn("claude-adapter",`${e} hook ignored for ${this.activeEvent.eventId}: arrived before this event's prompt was submitted (${Date.now()-(this.activeEvent.channelPushedAt??0)}ms after push) \u2014 startup/resume turn tail`);return}if(this.activeEvent.singleTurnFallback&&!this.isEventAnswered()){o.info("claude-adapter",`${e} hook ignored for ${this.activeEvent.eventId}: single-turn fallback owns finalization`);return}this.finalizeActiveEvent(e)}resolveIncrementalTextFromOffset(e,t){if(!this.isChannelEventPrePush(t)){if(t.textForwardOffset!==void 0)return t.textForwardOffset;if(t.jsonlBaseOffset!==void 0)return t.jsonlBaseOffset;if(t.singleTurnFallback){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return;const i=x(this.claudeCliSessionId,this.claudeSessionCwd);return P(i)?0:void 0}}}forwardIncrementalText(e){const t=this.activeEvent;if(!t||t.eventId!==e||this.isChannelEventPrePush(t)||t.replied||!this.claudeCliSessionId||!this.claudeSessionCwd)return;const i=this.resolveIncrementalTextFromOffset(e,t);if(i===void 0)return;const{segments:s,newOffset:n,apiError:r,apiErrorText:a}=Me(this.claudeCliSessionId,this.claudeSessionCwd,i);if(t.textForwardOffset=n,r&&(a&&(t.apiErrorText=a),t.apiFormatError||(t.apiFormatError=!0,o.error("claude-adapter",`API error entry detected in JSONL for ${e} (isApiErrorMessage), not forwarding its text as reply`))),s.length===0)return;const l=t.sessionId;for(const c of s){const u=c.trim();if(!u)continue;const h=`txt_${e}_${this.textForwardSeq++}`;this.bridgeCallbacks.sendStreamChunk(e,l,u,1,!1,h),this.bridgeCallbacks.sendStreamChunk(e,l,"",2,!0,h),t.textForwarded||(t.textForwarded=!0,t.repliedAt===void 0&&(t.repliedAt=Date.now()),this.startPostReplyDeadline(e),this.startPostReplyJsonlWatcher(e))}this.markActiveEventActivity(e,l),o.info("claude-adapter",`Forwarded ${s.length} plain-text segment(s) for ${e}`)}flushForwardedTail(e){this.activeEvent?.eventId===e&&this.activeEvent.textForwarded&&this.forwardIncrementalText(e)}isEventAnswered(e=this.activeEvent){return!!(e&&(e.replied||e.textForwarded))}attemptRescueFromJsonl(e,t){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return o.info("claude-adapter",`Rescue skipped: no claudeCliSessionId or claudeSessionCwd for ${e}`),"none";const i=this.activeEvent?.jsonlBaseOffset,s=z(this.claudeCliSessionId,this.claudeSessionCwd,i);if(s?.apiError)return o.error("claude-adapter",`Rescue aborted for ${e}: turn ended with a CLI API error entry (isApiErrorMessage)`),this.activeEvent?.eventId===e&&(this.activeEvent.apiFormatError=!0,s.apiErrorText&&(this.activeEvent.apiErrorText=s.apiErrorText)),"none";if(s?.metaOnly)return i===void 0?(o.warn("claude-adapter",`Rescue for ${e}: only CLI meta text found but jsonlBaseOffset is unset \u2014 cannot attribute it to this turn, treating as unanswered`),"none"):(o.info("claude-adapter",`Rescue skipped for ${e}: this turn wrote only CLI meta text, finalizing silently`),"silent");const n=s?.text||null;if(!n)return o.info("claude-adapter",`Rescue failed: no assistant text found in JSONL for ${e}`),"none";const r=`rescue_${e}_${Date.now()}`;return this.bridgeCallbacks.sendStreamChunk(e,t,n,1,!1,r),this.bridgeCallbacks.sendStreamChunk(e,t,"",2,!0,r),o.info("claude-adapter",`Rescue succeeded for event ${e}: sent ${n.length} chars from JSONL`),"sent"}warnUnsentFinalIfAny(e){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=this.activeEvent?.jsonlBaseOffset,i=z(this.claudeCliSessionId,this.claudeSessionCwd,t);if(!i||i.stopReason!=="end_turn")return;const s=i.text?.trim()??"";if(!s)return;const n=(this.activeEvent?.lastReplyText??"").trim();n&&(s===n||n.includes(s))||o.warn("claude-adapter",`Unsent final end_turn text for ${e} (${s.length} chars) not delivered \u2014 \u5DF2\u5E94\u7B54\u8FC7\uFF0C\u6309\u7B56\u7565\u4E0D\u8865\u53D1\uFF08\u7591\u4F3C\u56DE\u5408\u6536\u5C3E\u81EA\u8FF0\uFF1B\u82E5\u786E\u4E3A\u6F0F\u53D1\u7ED3\u8BBA\u53EF\u636E\u6B64\u6392\u67E5\uFF09`)}finalizeActiveEvent(e){if(!this.activeEvent)return;const t=this.activeEvent.eventId,i=this.activeEvent.sessionId;if(this.isEventAnswered()&&this.activeEvent.jsonlBaseOffset!==void 0&&this.claudeCliSessionId&&this.claudeSessionCwd){const s=z(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(s?.apiError)o.warn("claude-adapter",`Stop hook for ${t}: turn ended with a CLI API error entry, finalizing without waiting for end_turn`);else if(!s||s.stopReason!=="end_turn")if(Fe(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset))o.info("claude-adapter",`Stop hook: terminal tool_result detected for ${t} (grix_reply as final action, no end_turn expected), finalizing as responded`);else{o.info("claude-adapter",`Stop hook suppressed for ${t}: no end_turn in JSONL after offset=${this.activeEvent.jsonlBaseOffset} \u2014 likely resume-drain hook, waiting for JSONL watcher`),this.markActiveEventActivity(t,i);return}}if(this.flushForwardedTail(t),!this.activeEvent.apiFormatError){if(this.activeEvent.replied||this.activeEvent.textForwarded){this.activeEvent.replied&&!this.activeEvent.textForwarded&&this.warnUnsentFinalIfAny(t),this.finishTurnEnd(t,i,e,!0,`replied=${this.activeEvent.replied}, textForwarded=${this.activeEvent.textForwarded}`);return}if(this.activeEvent.rescueSettleInFlight){o.info("claude-adapter",`${e} ignored for ${t}: rescue retry already in flight`);return}const s=this.recoverMalformedToolCall(t);if(s==="retried")return;if(s==="exhausted"){this.bridgeCallbacks.sendStreamChunk(t,i,li,1,!1,`mtc_${t}`),this.bridgeCallbacks.sendStreamChunk(t,i,"",2,!0,`mtc_${t}`),this.finishTurnEnd(t,i,e,!0,"malformed-toolcall-fallback");return}const n=this.attemptRescueFromJsonl(t,i);if(n!=="none"){this.finishTurnEnd(t,i,e,!0,n==="silent"?"no-response-requested":"rescued");return}if(this.activeEvent?.apiFormatError){this.finishTurnEnd(t,i,e,!1,"apiFormatError (detected during rescue)");return}this.beginRescueSettleWait(t,i,e);return}this.finishTurnEnd(t,i,e,!1,"apiFormatError")}beginRescueSettleWait(e,t,i){if(!this.activeEvent||this.activeEvent.eventId!==e)return;this.activeEvent.rescueSettleInFlight=!0;const s=Math.max(1,Math.ceil(Xe/Qe));let n=0;const r=()=>{if(this.rescueSettleTimer=null,this.stopped)return;const a=this.activeEvent;if(!a||a.eventId!==e)return;if(n++,a.replied||a.textForwarded){this.finishTurnEnd(e,t,i,!0,`replied=${a.replied}, textForwarded=${a.textForwarded} (settled during flush wait)`);return}if(a.apiFormatError){this.finishTurnEnd(e,t,i,!1,"apiFormatError (settled during flush wait)");return}const l=this.attemptRescueFromJsonl(e,t);if(l!=="none"){this.finishTurnEnd(e,t,i,!0,l==="silent"?"no-response-requested-after-settle":"rescued-after-settle");return}if(a.apiFormatError){this.finishTurnEnd(e,t,i,!1,"apiFormatError (detected during rescue after settle)");return}if(i==="Stop"&&this.isToolOnlyTurnConcluded(a)){this.finishTurnEnd(e,t,i,!0,`tool-only-turn (toolCalls=${a.toolActivityCount??0})`);return}if(n>=s){this.finishTurnEnd(e,t,i,!1,`rescue-failed-after-settle (waited ~${Math.round(Xe/1e3)}s, no transcript output for this turn)`);return}this.markActiveEventActivity(e,t),this.rescueSettleTimer=setTimeout(r,Qe)};this.rescueSettleTimer=setTimeout(r,si)}isToolOnlyTurnConcluded(e){return!e.toolActivityCount||e.jsonlBaseOffset===void 0||!this.claudeCliSessionId||!this.claudeSessionCwd?!1:ue(this.claudeCliSessionId,this.claudeSessionCwd,e.jsonlBaseOffset).lastStopReason==="end_turn"}clearRescueSettleTimer(){this.rescueSettleTimer&&(clearTimeout(this.rescueSettleTimer),this.rescueSettleTimer=null)}finishTurnEnd(e,t,i,s,n){if(s)o.info("claude-adapter",`Stop hook received, finalizing event ${e} as responded (${n})`),this.bridgeCallbacks.sendEventResult(e,"responded");else{o.warn("claude-adapter",`Active event not confirmed when ${i}: ${e} (${n}), sending failed result`);const r=this.activeEvent?.apiFormatError?he(this.activeEvent.apiErrorText):"Claude exited before completing its reply. Please try again.";this.bridgeCallbacks.sendStreamChunk(e,t,r,1,!1,`err_${e}`),this.bridgeCallbacks.sendStreamChunk(e,t,"",2,!0,`err_${e}`),this.bridgeCallbacks.sendEventResult(e,"failed",r,"agent_stop_failure",!0)}this.clearActiveEvent(),this.armStopHookBarrier(t)}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.isChannelEventPrePush(this.activeEvent)&&(this.activeEvent.toolActivityCount=(this.activeEvent.toolActivityCount??0)+1,this.markActiveEventActivity(this.activeEvent.eventId,this.activeEvent.sessionId),this.forwardIncrementalText(this.activeEvent.eventId),(this.activeEvent.replied||this.activeEvent.textForwarded)&&this.startPostReplyDeadline(this.activeEvent.eventId)),e&&!this.activeEvent&&!this.compacting&&this.noteSelfDrivenActivity(e),!!t)if(e){this.startComposing(t,e);const i=this.activeEvent;if(i&&!this.isChannelEventPrePush(i)){const s=e.event_name,n=e.tool_name,r=e.tool_input??"",a=n?Ft(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)a||this.bridgeCallbacks.sendToolUse(i.eventId,i.sessionId,n,r);else if((s==="PostToolUse"||s==="PostToolUseFailure")&&n){if(n==="AskUserQuestion")return;!a&&s==="PostToolUseFailure"&&this.bridgeCallbacks.sendToolResult(i.eventId,i.sessionId,n,"(failed)")}}}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 W(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 l=a.request_id;this.pendingPermissions.set(l,{eventId:i.eventId,sessionId:i.sessionId});const c=typeof t=="string"?t:"";if(e==="ExitPlanMode"){const p=Kt(c);p&&this.bridgeCallbacks.sendReply(i.eventId,i.sessionId,p)}const u=e==="ExitPlanMode"?"":c.slice(0,100),h=u?`${e}: ${u}`:e;this.bridgeCallbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,approvalId:l,toolName:e,toolTitle:h}),o.info("claude-adapter",`Sent permission card: approvalId=${l} tool=${e}`)}).catch(r=>{o.warn("claude-adapter",`Failed to send permission card: ${r}`)})}async awaitPendingQuestionRequest(e,t){const i=Date.now()+qe;for(;;){const s=await e.listPending(),n=Date.now(),r=[...s].reverse().filter(l=>String(l.session_id??"").trim()===this.claudeCliSessionId&&n-Number(l.created_at??0)<=He),a=r.find(l=>String(l.event_id??"").trim()===t)??r.find(l=>String(l.event_id??"").trim()==="")??r[0]??null;if(a||Date.now()>=i)return a;await new Promise(l=>setTimeout(l,Zt))}}handleAskUserQuestion(e,t){const i=je(t);if(!i){o.warn("claude-adapter","Failed to parse AskUserQuestion input, skipping agent_question card");return}const s=S(),n=new xe(s.questionRequestsDir);this.awaitPendingQuestionRequest(n,e.eventId).then(async r=>{const a=r?.request_id??`fallback-${Date.now()}`;r||o.warn("claude-adapter",`No pending question waiter after ${qe}ms; sending card with ${a}. Submitting it will report not_pending and fall back to a plain message.`),r&&String(r.event_id??"").trim()===""&&await n.updateRequest(r.request_id,{event_id:e.eventId}),this.pendingQuestion.set(a,{eventId:e.eventId,sessionId:e.sessionId}),e.awaitingUserQuestion=!0;const c=(Number(r?.created_at??0)>0?Number(r?.created_at):Date.now())+Ue;this.bridgeCallbacks.sendAgentQuestionCard(e.eventId,e.sessionId,{request_id:a,mode:"form",questions:i,expires_at:c}),o.info("claude-adapter",`Sent agent_question card: request_id=${a} questions=${i.length}`)}).catch(()=>{o.warn("claude-adapter","Failed to list pending questions from store")})}parseAskUserQuestions(e){return je(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}`),l=String(r.prompt??""),c=Array.isArray(r.options)?r.options:void 0,u=r.multiSelect===!0;i.push({header:a,prompt:l,...c&&c.length>0?{options:c}:{},...u?{multi_select:!0}:{}})}return i.length>0?{questions:i}:null}pruneCompletedEvents(){const e=Date.now()-ei;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.isEventAnswered(i)||this.resetActiveEventHardTimer(i.eventId)))}clearActiveEventIdleTimer(){this.activeEventIdleTimer&&(clearTimeout(this.activeEventIdleTimer),this.activeEventIdleTimer=null)}clearActiveEventHardTimer(){this.activeEventHardTimer&&(clearTimeout(this.activeEventHardTimer),this.activeEventHardTimer=null)}killSingleTurnFallbackChild(e){if(e.exitCode!==null||e.signalCode!==null)return;N(e,"SIGTERM");const t=setTimeout(()=>{e.exitCode===null&&e.signalCode===null&&N(e,"SIGKILL")},ii);t.unref?.(),e.once("exit",()=>clearTimeout(t))}shouldExtendByLiveness(e){const t=this.activeEvent;if(!t||t.eventId!==e)return!1;const i=this.singleTurnFallbackChild;if(i&&this.singleTurnFallbackEventId===e&&i.exitCode===null&&i.signalCode===null)return!0;if(!this.claudeCliSessionId||!this.claudeSessionCwd||!this.claudeProcess&&!this.claudePty)return!1;if(this.lastPtyOutputAt>0&&Date.now()-this.lastPtyOutputAt<et)return t.livenessExtendStartAt=Date.now(),!0;const s=ue(this.claudeCliSessionId,this.claudeSessionCwd,t.jsonlBaseOffset);if(s.freshMs===null||!(t.jsonlBaseOffset===void 0?s.freshMs<pe:s.lastStopReason!==null?s.lastStopReason!=="end_turn":s.freshMs<pe))return!1;if(s.freshMs<pe)t.livenessExtendStartAt=Date.now();else{const r=t.livenessExtendStartAt??Date.now();if(t.livenessExtendStartAt===void 0&&(t.livenessExtendStartAt=r),Date.now()-r>Ze)return o.warn("claude-adapter",`Liveness extension budget exhausted for ${e} (no JSONL writes for ${Math.round((Date.now()-r)/6e4)}min), allowing close`),!1}return o.info("claude-adapter",`Liveness check: turn in progress for ${e} (lastStopReason=${s.lastStopReason??"none"}, freshMs=${s.freshMs}), extending`),!0}captureEventJsonlBaseOffset(e,t){this.captureAuditTranscriptStart(e);const i=this.activeEvent;if(!(!i||i.eventId!==e)&&!(!t?.force&&i.jsonlBaseOffset!==void 0)&&!(!this.claudeCliSessionId||!this.claudeSessionCwd))try{const s=x(this.claudeCliSessionId,this.claudeSessionCwd);if(i.auditTranscriptPath===s&&i.auditTranscriptStartOffset!==void 0){i.jsonlBaseOffset=i.auditTranscriptStartOffset;return}i.jsonlBaseOffset=P(s)?k(s).size:0}catch{i.jsonlBaseOffset=0}}captureSingleTurnFallbackJsonlBaseOffset(e){this.captureAuditTranscriptStart(e);const t=this.activeEvent;if(!(!t||t.eventId!==e||t.jsonlBaseOffset!==void 0)&&!(!this.claudeCliSessionId||!this.claudeSessionCwd))try{const i=x(this.claudeCliSessionId,this.claudeSessionCwd);if(!P(i))return;if(t.auditTranscriptPath===i&&t.auditTranscriptStartOffset!==void 0){t.jsonlBaseOffset=t.auditTranscriptStartOffset;return}t.jsonlBaseOffset=k(i).size}catch{}}captureAuditTranscriptStart(e){const t=this.activeEvent;if(!t||t.eventId!==e||t.rawEvent?.audit?.enabled!==!0||t.auditTranscriptStartOffset!==void 0||!this.claudeCliSessionId)return;const i=this.claudeSessionCwd||process.cwd(),s=x(this.claudeCliSessionId,i);t.auditTranscriptPath=s,t.auditClaudeSessionId=this.claudeCliSessionId;try{t.auditTranscriptStartOffset=P(s)?k(s).size:0}catch{t.auditTranscriptStartOffset=0}const n=this.auditEvidencePaths;n&&(t.auditOtelLogsStartOffset=X(n.logsPath),t.auditOtelTracesStartOffset=X(n.tracesPath),n.rawProviderBody&&(t.auditRawBodyFilesBefore=Ye(n.rawBodyDir)))}snapshotAuditBoundary(e){if(e.rawEvent?.audit?.enabled!==!0)return;if(e.auditTranscriptStartOffset===void 0||!e.auditTranscriptPath||!e.auditClaudeSessionId){this.completedAuditBoundaries.set(e.eventId,Object.freeze({adapterType:this.type}));return}const t=this.claudeSessionCwd?x(e.auditClaudeSessionId,this.claudeSessionCwd):e.auditTranscriptPath,i=P(t)?t:e.auditTranscriptPath;let s=e.auditTranscriptStartOffset;try{s=P(i)?k(i).size:e.auditTranscriptStartOffset}catch{}const n=$e(i),r=this.auditEvidencePaths,a=new Set(e.auditRawBodyFilesBefore??[]),l=r?.rawProviderBody?Ye(r.rawBodyDir).filter(u=>!a.has(u)):[],c=Object.freeze({adapterType:this.type,providerSessionId:e.auditClaudeSessionId,transcriptPath:i,transcriptStartOffset:e.auditTranscriptStartOffset,transcriptEndOffset:s,...e.auditSingleTurnFallback?{singleTurnFallback:!0}:{},subagentRoot:f(n,e.auditClaudeSessionId,"subagents"),...r?{otelLogsPath:r.logsPath,otelLogsStartOffset:e.auditOtelLogsStartOffset??0,otelLogsEndOffset:X(r.logsPath),otelTracesPath:r.tracesPath,otelTracesStartOffset:e.auditOtelTracesStartOffset??0,otelTracesEndOffset:X(r.tracesPath),rawApiBodyDirectory:r.rawBodyDir,rawApiBodyPaths:l}:{}});this.completedAuditBoundaries.set(e.eventId,c)}noteSelfDrivenActivity(e){!this.selfDrivenActive&&this.lastClearedEvent&&Date.now()-this.lastClearedEvent.ts<it||(this.selfDrivenLastSignalAt=Date.now(),e&&(this.selfDrivenLabel=pi(e)),!this.selfDrivenActive&&(this.selfDrivenActive=!0,o.info("claude-adapter",`Self-driven activity detected for session ${this.sessionId} (no active event), debouncing before reporting working state`),this.selfDrivenReportTimer=setTimeout(()=>{this.selfDrivenReportTimer=null,!(!this.selfDrivenActive||this.stopped||this.activeEvent)&&(this.selfDrivenReported=!0,o.info("claude-adapter",`Self-driven working state confirmed for session ${this.sessionId} (sustained >${tt/1e3}s), reporting`),this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0))},tt),this.selfDrivenReportTimer.unref(),this.selfDrivenSweepTimer=setInterval(()=>this.sweepSelfDriven(),ui),this.selfDrivenSweepTimer.unref()))}sweepSelfDriven(){if(!this.selfDrivenActive)return;if(this.stopped||this.activeEvent){this.stopSelfDriven();return}const e=Date.now()-this.selfDrivenLastSignalAt;if(this.claudeCliSessionId&&this.claudeSessionCwd){const t=ue(this.claudeCliSessionId,this.claudeSessionCwd),i=t.lastStopReason!==null&&t.lastStopReason!=="end_turn",s=t.freshMs!==null&&t.freshMs<Ze,n=Ht(this.claudeCliSessionId,this.claudeSessionCwd)>0;if((i||n)&&s){this.selfDrivenReported&&this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0);return}}if(e<di){this.selfDrivenReported&&this.emit("sessionActivity",this.sessionId??"",!0,this.selfDrivenLabel??void 0);return}o.info("claude-adapter",`Self-driven activity ended for session ${this.sessionId} (quiet for ${Math.round(e/1e3)}s, no pending work)`),this.stopSelfDriven()}stopSelfDriven(){this.selfDrivenSweepTimer&&(clearInterval(this.selfDrivenSweepTimer),this.selfDrivenSweepTimer=null),this.selfDrivenReportTimer&&(clearTimeout(this.selfDrivenReportTimer),this.selfDrivenReportTimer=null),this.selfDrivenActive&&(this.selfDrivenActive=!1,this.selfDrivenLabel=null,this.selfDrivenReported&&(this.selfDrivenReported=!1,this.emit("sessionActivity",this.sessionId??"",!1)))}currentTranscriptSize(){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return null;try{return k(x(this.claudeCliSessionId,this.claudeSessionCwd)).size}catch{return null}}resetSelfDrivenTextBaseline(){this.clearSelfDrivenDeliverTimer(),this.selfDrivenReplied=!1,this.selfDrivenTextOffset=this.currentTranscriptSize()}clearSelfDrivenDeliverTimer(){this.selfDrivenDeliverTimer&&(clearTimeout(this.selfDrivenDeliverTimer),this.selfDrivenDeliverTimer=null)}deliverSelfDrivenText(e){if(this.stopped||this.activeEvent)return;this.clearSelfDrivenDeliverTimer();const t=this.currentTranscriptSize();if(t===null)return;if(this.selfDrivenTextOffset===null){this.selfDrivenTextOffset=t;return}if(this.lastClearedEvent&&Date.now()-this.lastClearedEvent.ts<it){this.selfDrivenTextOffset=t;return}if(this.selfDrivenReplied){this.selfDrivenReplied=!1,this.selfDrivenTextOffset=t;return}const i=Date.now()+fi,s=()=>{if(this.selfDrivenDeliverTimer=null,!(this.stopped||this.activeEvent)&&!this.flushSelfDrivenText(e)){if(Date.now()>=i){o.info("claude-adapter",`Self-driven ${e}: no new transcript text to deliver for session ${this.sessionId}`);return}this.selfDrivenDeliverTimer=setTimeout(s,hi),this.selfDrivenDeliverTimer.unref()}};s()}flushSelfDrivenText(e){if(!this.claudeCliSessionId||!this.claudeSessionCwd)return!1;const t=this.selfDrivenTextOffset??0,{segments:i,newOffset:s}=Me(this.claudeCliSessionId,this.claudeSessionCwd,t);this.selfDrivenTextOffset=s;const n=i.map(a=>a.trim()).filter(a=>a.length>0);if(n.length===0)return!1;const r=this.sessionId;if(!r)return o.warn("claude-adapter",`Self-driven ${e}: ${n.length} text segment(s) ready but session id is unknown, dropping`),!0;for(const a of n)Le(this.getEventToolHandle(),"grix_reply",{session_id:r,text:a});return o.info("claude-adapter",`Self-driven ${e}: delivered ${n.length} text segment(s) to session ${r}`),!0}tryRecoverLostInjection(e){const t=this.activeEvent;if(this.stopped||!t||t.eventId!==e||this.isEventAnswered(t)||t.channelPushedAt===void 0||t.promptSubmittedAt!==void 0||this.compacting||this.stopHookBarrierSessionId===t.sessionId||this.lostInjectionRetriedEventIds.has(e))return!1;this.lostInjectionRetriedEventIds.add(e);const i=t.rawEvent;return o.warn("claude-adapter",`Lost injection for ${e}: pushed ${Date.now()-t.channelPushedAt}ms ago but prompt never submitted \u2014 respawning Claude and re-pushing the event once`),this.clearActiveEventIdleTimer(),this.clearActiveEventHardTimer(),this.activeEvent=null,this.stopComposing(),this.killClaudeProcess(We),this.deliverInboundEvent(i),!0}resetActiveEventIdleTimer(e){this.clearActiveEventIdleTimer(),this.activeEventIdleTimer=setTimeout(()=>{if(!this.stopped&&this.activeEvent?.eventId===e){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}if(this.shouldExtendByLiveness(e)){this.resetActiveEventIdleTimer(e);return}this.tryRecoverLostInjection(e)||this.finalizeStuckActiveEvent(e,"idle")}},Ge)}finalizeStuckActiveEvent(e,t){const i=this.isEventAnswered(),s=i?"responded":"failed",n=t==="idle"?Ge:ze,r=!i&&this.activeEvent?.apiFormatError?he(this.activeEvent.apiErrorText):void 0,a=i?void 0:r??(t==="idle"?`agent idle for ${n/1e3}s`:`agent exceeded max duration ${n/1e3}s`),l=i?void 0:t==="idle"?"agent_idle_timeout":"agent_hard_timeout",c=this.lostInjectionRetriedEventIds.has(e)?", after lost-injection retry":"";o.error("claude-adapter",`Active event ${t} timeout (${n/1e3}s): ${e}, answered=${i}${c}, sending ${s}`),this.flushForwardedTail(e),this.completedEventIds.set(e,Date.now());let u=!1;r&&this.activeEvent&&(this.bridgeCallbacks.sendStreamChunk(e,this.activeEvent.sessionId,r,1,!1,`err_${e}`),this.bridgeCallbacks.sendStreamChunk(e,this.activeEvent.sessionId,"",2,!0,`err_${e}`),u=!0),u?this.bridgeCallbacks.sendEventResult(e,s,a,l,!0):this.bridgeCallbacks.sendEventResult(e,s,a,l),this.clearActiveEvent(),s==="failed"&&this.emit("stuck")}resetActiveEventHardTimer(e){this.clearActiveEventHardTimer(),this.activeEventHardTimer=setTimeout(()=>{if(!this.stopped&&this.activeEvent?.eventId===e){if(this.shouldExtendByLiveness(e)){this.resetActiveEventHardTimer(e);return}this.finalizeStuckActiveEvent(e,"hard")}},ze)}clearActiveEventPostReplyTimer(){this.activeEventPostReplyTimer&&(clearTimeout(this.activeEventPostReplyTimer),this.activeEventPostReplyTimer=null)}clearActiveEventPostReplyWatcher(){if(this.activeEventPostReplyWatcher){try{this.activeEventPostReplyWatcher.close()}catch{}this.activeEventPostReplyWatcher=null}this.activeEventPostReplyPoll&&(clearInterval(this.activeEventPostReplyPoll),this.activeEventPostReplyPoll=null)}startPostReplyJsonlWatcher(e){if(this.clearActiveEventPostReplyWatcher(),!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=x(this.claudeCliSessionId,this.claudeSessionCwd);if(!this.activeEvent?.sessionId)return;if(!P(t)){o.info("claude-adapter",`JSONL watcher skipped: file not yet available for ${e}`);return}const s=k(t).size;this.activeEvent&&(this.activeEvent.jsonlBaseOffset=s);let n=null;try{this.activeEventPostReplyWatcher=Pt(t,()=>{n&&clearTimeout(n),n=setTimeout(()=>this.finalizeIfEndTurn(e),300)}),this.activeEventPostReplyPoll=setInterval(()=>this.finalizeIfEndTurn(e),ci),o.info("claude-adapter",`JSONL watcher started for ${e} at ${t} (baseOffset=${s})`)}catch(r){o.warn("claude-adapter",`JSONL watcher start failed for ${e}: ${r}`)}}finalizeIfEndTurn(e){if(this.stopped||this.activeEvent?.eventId!==e||this.isChannelEventPrePush(this.activeEvent)||!this.claudeCliSessionId||!this.claudeSessionCwd)return;const t=z(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset);if(t?.apiError){this.activeEvent.apiFormatError=!0,t.apiErrorText&&(this.activeEvent.apiErrorText=t.apiErrorText);return}if(t&&t.stopReason==="end_turn"){o.info("claude-adapter",`JSONL watcher: end_turn detected for ${e}, finalizing as responded`);const i=this.activeEvent.sessionId;this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent(),this.armStopHookBarrier(i);return}if(this.activeEvent?.replied&&this.activeEvent.jsonlBaseOffset!==void 0&&Fe(this.claudeCliSessionId,this.claudeSessionCwd,this.activeEvent.jsonlBaseOffset,!0)){if(this.lastPtyOutputAt>0&&Date.now()-this.lastPtyOutputAt<et)return;o.info("claude-adapter",`JSONL poll: terminal tool_result detected for ${e} (file quiet, no end_turn), finalizing as responded`),this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent()}}startPostReplyDeadline(e){this.clearActiveEventPostReplyTimer(),this.clearActiveEventHardTimer(),this.activeEventPostReplyTimer=setTimeout(()=>{if(this.stopped||this.activeEvent?.eventId!==e||!this.activeEvent?.replied&&!this.activeEvent?.textForwarded)return;if(this.shouldExtendByLiveness(e)){this.startPostReplyDeadline(e);return}const t=this.activeEvent.repliedAt,i=Math.round((Date.now()-t)/1e3);o.info("claude-adapter",`Post-reply deadline reached for ${e} (${i}s since reply), completing as responded`),this.flushForwardedTail(e),this.bridgeCallbacks.sendEventResult(e,"responded",void 0,void 0),this.clearActiveEvent()},ri)}beginCompaction(){this.compacting||(this.compacting=!0,o.info("claude-adapter","Compaction started; gating input"),this.emit("pauseIntake","compaction"),this.resetCompactingActivityTimer())}resetCompactingActivityTimer(){this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{o.warn("claude-adapter","Compaction stall: no PTY activity for 90s, emitting stuck"),this.emit("stuck")},9e4),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}); resuming intake`),this.emit("resumeIntake","compaction");const t=this.compactionDoneResolver;this.compactionDoneResolver=null,t?.(e)}armStopHookBarrier(e){this.stopHookBarrierTimer&&clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierSessionId=e,this.emit("pauseIntake","barrier"),this.stopHookBarrierTimer=setTimeout(()=>{this.stopHookBarrierSessionId===e&&(o.warn("claude-adapter",`Stop hook barrier timeout for session=${e}`),this.clearStopHookBarrier())},gi)}clearStopHookBarrier(){const e=this.stopHookBarrierSessionId!==null;this.stopHookBarrierSessionId=null,this.stopHookBarrierTimer&&(clearTimeout(this.stopHookBarrierTimer),this.stopHookBarrierTimer=null),e&&this.emit("resumeIntake","barrier")}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,t=this.activeEvent.sessionId;this.bridgeCallbacks.sendStreamChunk(e,t,`
|
|
19
19
|
|
|
20
|
-
Error: MCP server startup failed`,1,!1),this.bridgeCallbacks.sendEventResult(e,"failed","MCP server startup failed"),this.completedEventIds.set(e,Date.now()),this.clearActiveEvent()}}}class
|
|
21
|
-
`)){const t=e.trim();if(!t)continue;let i;try{i=JSON.parse(t)}catch{continue}if(!(!i||typeof i!="object")){for(const s of
|
|
22
|
-
`),"utf8"),{expectPath:i,pidPath:s}}async function
|
|
23
|
-
${i.stderr??""}`;return s.trim()?{developmentChannels:e,maxTurns:s.includes("--max-turns")}:{...
|
|
24
|
-
`;let l="";try{l=await I(d,"utf8")}catch{}l!==a&&(await
|
|
25
|
-
`;let i="";try{i=await I(d,"utf8")}catch{}i!==t&&await
|
|
26
|
-
`)){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||
|
|
20
|
+
Error: MCP server startup failed`,1,!1),this.bridgeCallbacks.sendEventResult(e,"failed","MCP server startup failed"),this.completedEventIds.set(e,Date.now()),this.clearActiveEvent()}}}class Oi extends Oe{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 T(d){if(d==null)return 0;const e=Number(d);return Number.isFinite(e)?e:0}function ot(d){if(typeof d!="string"||!d.trim())return;let e;try{e=JSON.parse(d)}catch{return}if(!Array.isArray(e))return;const t=e.filter(i=>{if(!i||typeof i!="object")return!0;const s=String(i.content??"");return!lt(s)});return JSON.stringify(t)}const xi=600;function lt(d){const e=d.trim();return e?e.includes("\u4ECE\u7EBF\u4E0A\u8BB0\u5F55\u6062\u590D")||e.includes("\u672C\u4F1A\u8BDD\u7684\u672C\u5730\u5386\u53F2\u8BB0\u5F55\u5DF2\u4E22\u5931")||e.includes("\u672C\u5730\u5386\u53F2\u8BB0\u5F55\u5DF2\u4E22\u5931")||e.includes("\u65E0\u6CD5\u7EED\u63A5\u4E4B\u524D\u7684\u4E0A\u4E0B\u6587")?!0:e.length>xi?!1:/历史[^\n]{0,40}丢失/.test(e)&&/新建话题|恢复|怎么处理|如何继续|选哪个/.test(e):!1}function Li(d){const e=d.type;if(e!=="user"&&e!=="assistant")return[];const t=d.message,i=t&&typeof t=="object"?t.content:d.content;if(typeof i=="string")return[i];if(!Array.isArray(i))return[];const s=[];for(const n of i){if(!n||typeof n!="object")continue;const r=n;r.type==="text"&&typeof r.text=="string"&&s.push(r.text)}return s}function Mi(d){for(const e of d.split(`
|
|
21
|
+
`)){const t=e.trim();if(!t)continue;let i;try{i=JSON.parse(t)}catch{continue}if(!(!i||typeof i!="object")){for(const s of Li(i))if(lt(s))return!0}}return!1}function ee(d){return String(d).replace(/\\/g,"\\\\").replace(/\{/g,"\\{").replace(/\}/g,"\\}")}const te={noFirst:"(?i)No,.{0,48}exit.*Yes,.{0,48}I.{0,48}trust(?:.*confirm)?",yesFirst:"(?i)Yes,.{0,48}(proceed|I.{0,48}trust).*No,.{0,48}exit(?:.*confirm)?"};function ct(d){return new RegExp(d.replace(/^\(\?i\)/,""),"is")}const Fi=ct(te.noFirst),Ni=ct(te.yesFirst);async function ji(d,e,t){const i=f(d,"claude.expect"),s=f(d,"claude.pid"),n=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set cmd_fifo {${ee(f(d,"cmd.fifo"))}}`,"file delete -force $cmd_fifo","exec mkfifo $cmd_fifo","set cmd_fd [open $cmd_fifo r+]","fconfigure $cmd_fd -blocking 0 -buffering line",`set claude_command [list {${ee(e)}}${t.map(r=>` {${ee(r)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${ee(s)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","after 500",'send -- "\\r"',"expect {",` -re {${te.noFirst}} {`,' if {$startup_prompt_armed} { after 1000; send -- "\\033\\[B"; after 400; send -- "\\r"; after 300 }; exp_continue'," }",` -re {${te.yesFirst}} {`,' if {$startup_prompt_armed} { after 1000; send -- "\\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} { after 1000; send -- "\\r"; after 600; 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 {}","}","proc handle_cmd {} {"," upvar cmd_fd cmd_fd cmd_fifo cmd_fifo"," if {[catch {gets $cmd_fd} __line]} { return }"," if {[eof $cmd_fd]} {"," catch {close $cmd_fd}"," if {[catch {set cmd_fd [open $cmd_fifo r+]} err]} { return }"," fconfigure $cmd_fd -blocking 0 -buffering line"," fileevent $cmd_fd readable handle_cmd",` } elseif {$__line eq "${ve}enter"} {`,' send -- "\\r"',` } elseif {$__line eq "${ve}esc"} {`,' send -- "\\033"',' } elseif {$__line ne ""} {',' send -- "$__line\\r"'," }","}","fileevent $cmd_fd readable handle_cmd","expect_background {"," -re .+ { }"," eof { set ::__done 1 }","}","set ::__done 0","vwait ::__done",""];return await R(s,"","utf8"),await R(i,n.join(`
|
|
22
|
+
`),"utf8"),{expectPath:i,pidPath:s}}async function Bi(d,e=50,t=100){for(let i=0;i<e;i++){try{const s=await I(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 Ui(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),Bi(e).then(a=>n(()=>t(a))).catch(a=>n(()=>i(a)))})}function dt(d){return d.replace(/[/\\]/g,"-")}function Hi(d){const e=S();return f(e.dataDir,"claude-mcp-configs",`${dt(d)}.json`)}function qi(d){const e=S();return f(e.dataDir,"claude-system-prompts",`${dt(d)}.txt`)}function Gi(){return f(S().dataDir,"claude-full-auto-settings.json")}function Wi(d){let e=V.developmentChannels;const t=ae(d,["--dangerously-load-development-channels",`server:${j}`,"--version"],{encoding:"utf8",timeout:3e3,windowsHide:!0,env:Q(),...process.platform==="win32"?{shell:!0}:{}});t&&!t.error&&typeof t.status=="number"&&(e=t.status===0);try{const i=ae(d,["--help"],{encoding:"utf8",timeout:3e3,windowsHide:!0,env:Q(),...process.platform==="win32"?{shell:!0}:{}});if(!i)return{...V,developmentChannels:e};const s=`${i.stdout??""}
|
|
23
|
+
${i.stderr??""}`;return s.trim()?{developmentChannels:e,maxTurns:s.includes("--max-turns")}:{...V,developmentChannels:e}}catch(i){return o.warn("claude-adapter",`Claude capability probe failed, assuming modern CLI: ${i instanceof Error?i.message:String(i)}`),{...V,developmentChannels:e}}}async function zi(d){const e=f(d,"claude-extra-mcp-servers.json");let t;try{t=await I(e,"utf8")}catch{return{}}try{const s=JSON.parse(t)?.mcpServers;if(!s||typeof s!="object"||Array.isArray(s))return o.warn("claude-adapter",`Ignoring ${e}: missing "mcpServers" object`),{};const n={};for(const[r,a]of Object.entries(s)){const l=a;if(!l||typeof l!="object"||typeof l.command!="string"||!P(l.command)){o.warn("claude-adapter",`Skipping extra MCP server "${r}": command missing or not found`);continue}n[r]=a}return n}catch(i){return o.warn("claude-adapter",`Ignoring ${e}: invalid JSON (${i instanceof Error?i.message:String(i)})`),{}}}async function Ji(d,e,t){const i=S();await O(f(i.dataDir,"claude-mcp-configs"),{recursive:!0});const n={...await zi(i.configDir),[j]:{type:"stdio",command:process.execPath,args:e}};t&&(n["grix-app-bridge"]={type:"stdio",command:process.execPath,args:t});const a=`${JSON.stringify({mcpServers:n},null,2)}
|
|
24
|
+
`;let l="";try{l=await I(d,"utf8")}catch{}l!==a&&(await R(d,a,"utf8"),o.info("claude-adapter",`Wrote MCP config: ${d}`))}async function Ki(d,e){await O(f(S().dataDir,"claude-system-prompts"),{recursive:!0});const t=`${e}
|
|
25
|
+
`;let i="";try{i=await I(d,"utf8")}catch{}i!==t&&await R(d,t,"utf8")}function Ee(d,e){if(process.platform==="win32")return;let t=!1;try{const i=oe(`ps ax -o pid,command | grep -E -- '--(session-id|resume) ${d}' | grep -v grep`,{encoding:"utf8",timeout:5e3,windowsHide:!0}).trim();if(i)for(const s of i.split(`
|
|
26
|
+
`)){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||_e(d)}function _e(d){const e=f(D(),".claude"),t=[f(e,"session-env",d)];try{const i=f(e,"sessions");for(const s of ce(i))if(s.endsWith(".json"))try{const n=f(i,s),r=JSON.parse(B(n,"utf8"));r&&r.sessionId===d&&t.push(n)}catch{}}catch{}for(const i of t)try{k(i),Et(i,{recursive:!0,force:!0}),o.info("claude-adapter",`Removed stale session file: ${i}`)}catch{}}function Is(d,e){if(!e)return!1;const t=f(D(),".claude"),i=ie(e),s=f(t,"projects",i,`${d}.jsonl`);try{return k(s),!0}catch{return!1}}function ut(d,e){if(!e)return!1;const t=f(D(),".claude","projects"),i=ie(e),s=f(t,i),n=f(s,`${d}.jsonl`),r=`${d}.jsonl`,a=[];let l;try{l=ce(t)}catch{return!1}for(const h of l){const p=f(t,h,r);try{const m=k(p);m.isFile()&&m.size>0&&a.push({path:p,size:m.size,mtimeMs:m.mtimeMs,lines:-1})}catch{}}if(a.length===0)return!1;let c=a[0];if(a.length>1){for(const h of a)h.lines=Se(h.path);a.sort((h,p)=>p.lines-h.lines||p.size-h.size||p.mtimeMs-h.mtimeMs),c=a[0]}if(c.path===n)return!0;const u=a.find(h=>h.path===n);if(u){const h=u.lines>=0?u.lines:Se(u.path),p=c.lines>=0?c.lines:Se(c.path);if(h>=p)return!0}try{return be(s,{recursive:!0}),Ie(c.path,n),o.info("claude-adapter",`Reclaimed session ${d} history ${c.path} -> ${n} (${a.length} copies; cwd drift recovered via move)`),!0}catch(h){return o.warn("claude-adapter",`Reclaim session ${d} from ${c.path} failed: ${h.message}`),P(n)}}function ht(d,e){if(!e)return!1;const t=f(D(),".claude","projects",ie(e),`${d}.jsonl`);let i="";try{i=B(t,"utf8")}catch{return!1}if(!Mi(i))return!1;const s=`${t}.polluted-history-recovery-${Date.now()}`;try{return Ie(t,s),_e(d),o.warn("claude-adapter",`Quarantined polluted Claude transcript ${t} -> ${s}; continuing without local resume`),!0}catch(n){return o.warn("claude-adapter",`Failed to quarantine polluted Claude transcript ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function Se(d){try{const e=B(d);let t=0;for(let i=0;i<e.length;i++)e[i]===10&&t++;return t}catch{return 0}}function ft(d,e){if(!e)return;const t=f(D(),".claude"),i=ie(e),s=f(t,"projects",i,`${d}.jsonl`);let n;try{n=B(s)}catch{return}if(n.length===0)return;let r=-1;for(let c=n.length-1;c>=0;c--)if(n[c]===10){r=c;break}const a=r+1,l=n.subarray(a).toString("utf8").trim();if(l)try{JSON.parse(l)}catch{try{_t(s,a),o.warn("claude-adapter",`repairJsonl: stripped ${n.length-a}B invalid trailing data from ${d}`)}catch(c){o.error("claude-adapter",`repairJsonl: failed to truncate ${d}: ${c instanceof Error?c.message:c}`)}}}function Yi(){return process.env.ComSpec||f(process.env.SystemRoot||"C:\\Windows","System32","cmd.exe")}function ie(d){const e=d.replace(/\\/g,"/").replace(/:\/\//g,"/");if(/^[a-zA-Z]:\//.test(e)||e.startsWith("//"))return e.replace(/[^a-zA-Z0-9]/g,"-");let i=e;try{i=Ae(e)}catch{}return i.replace(/[^a-zA-Z0-9]/g,"-")}export{Fi as CLAUDE_TRUST_DIALOG_NO_FIRST_RE,te as CLAUDE_TRUST_DIALOG_PATTERNS,Ni as CLAUDE_TRUST_DIALOG_YES_FIRST_RE,As as ClaudeAdapter,ji as createExpectScript,ie as deriveClaudeProjectDirName,lt as isLostHistoryRecoveryNotice,zi as loadClaudeExtraMcpServers,je as parseAskUserQuestionPayload,ni as resolveExpectPath,Yi as resolveWindowsShellCommand,Mi as transcriptHasLostHistoryRecoveryNotice};
|