@trymesh/cli 0.3.23 → 0.3.24

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.
@@ -1 +1 @@
1
- function e(e,t){return Array.from(new Set(e.filter(Boolean))).slice(0,t)}function t(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>0?t:"tool"}function s(e){const t=JSON.stringify(e);return t?t.length<=100?t:`${t.slice(0,97)}...`:"{}"}function i(e){const t=Y.find(t=>e.includes(t.value)||t.value.includes(e));if(t)return t.label;const s=e.split(".");return s[s.length-1].includes("claude-sonnet")?"Claude Sonnet":e.split(":").pop()||e}function n(e){const t=e.trim().toLowerCase();if(!t)return"";for(const e of Y)if(e.aliases.includes(t)||t===e.value.toLowerCase())return e.value;return e.trim()}function a(e,t=140){const s=e.replace(/\s+/g," ").trim();return s?s.length>t?`${s.slice(0,t-3)}...`:s:""}function o(e){return e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function r(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-60))}\n[trimmed ${e.length-t} chars]`}function c(e){const t=[],s={};for(const i of e){const e=i.indexOf("=");if(e>0){const t=i.slice(0,e).trim().toLowerCase(),n=i.slice(e+1).trim();t&&(s[t]=n)}else i.trim()&&t.push(i.trim())}return{positionals:t,keyValues:s}}function l(e){const t=e.trim().toLowerCase();return t?Y.find(e=>e.value.toLowerCase()===t||e.aliases.includes(t)||e.label.toLowerCase()===t)??null:null}function d(e){return/LLM streaming failed/i.test(e)&&/(?:->|status\s*)\s*(404|405)\b/i.test(e)}import u from"node:fs/promises";import{readFileSync as h}from"node:fs";import p from"node:path";import m from"node:readline/promises";import{stdin as g,stdout as f}from"node:process";import{fileURLToPath as w}from"node:url";import y from"picocolors";import $ from"ora";import v from"enquirer";import k from"node:os";import b from"node:http";import{spawn as x}from"node:child_process";import C from"node:crypto";import{marked as S}from"marked";import{markedTerminal as T}from"marked-terminal";import{MODEL_CATALOG as I}from"./model-catalog.js";import{routeMeshTask as E}from"./model-router.js";S.use(T());const{Select:A,Confirm:_,Input:M}=v;import{loadUserSettings as R,saveUserSettings as j,shortPathLabel as D}from"./config.js";import{BedrockLlmClient as L}from"./llm-client.js";import{ContextAssembler as P}from"./context-assembler.js";import{ContextArtifactStore as F}from"./context-artifacts.js";import{SessionCapsuleStore as N}from"./session-capsule-store.js";import{buildSessionManager as U}from"./session-manager.js";import{MeshPortal as H}from"./mesh-portal.js";import{MeshDoctorEngine as O}from"./doctor.js";import{VoiceManager as q}from"./voice-manager.js";const V=["# Identity","You are Mesh — a senior engineering partner embedded directly in the developer's workspace.","You are a professional coding agent focused on verified, high-quality changes.","","# Communication","- Match the user's language exactly (German if they write German, English if English).","- Be terse. Lead with the result or the next action.","- No greetings, no filler, no emojis.","- When something is broken, say what broke and what fixes it.","","# Result Enforcement","Every time you complete a code change or a task, you MUST conclude with a 'Verification Report':","- CHANGED FILES: <list>","- VERIFICATION: <command run & result (pass/fail)>","- RESIDUAL RISK: <potential side effects>","- NEXT RECOMMENDED STEP: <one sentence>","","# How to read the codebase","You have a fully indexed, live capsule of this workspace. Use it correctly:","- For durable company context, decisions, ownership signals, risk memory, and repo-specific lessons: use 'workspace.company_brain' first.","- For questions about code, behavior, or structure: 'workspace.semantic_search' first (RAG — uses vector embeddings for conceptual queries), then 'workspace.ask_codebase' for deep analysis.","- For symbol definitions, callers, and usages: 'workspace.explain_symbol' or 'workspace.find_references'.","- For data flow across files: 'workspace.trace_symbol'.","- For recent background changes: 'workspace.get_recent_changes' — never re-read files you've already seen.","- For file contents only when you need to edit: 'workspace.read_file_raw'.","- For directory structure: 'workspace.read_dir_overview'.","- NEVER call 'workspace.open_artifact' automatically after another tool. The result is already in context. Only use it when the user explicitly asks for more detail or the result was truncated.","","# How to make changes","- Check impact before any edit that touches shared symbols: 'workspace.impact_map'.","- For surgical single-symbol changes: 'workspace.rename_symbol' or 'workspace.inline_symbol'.","- For function extraction or structural refactors: 'workspace.extract_function' or 'workspace.move_to_module'.","- For large multi-file changes, use alien-patch for maximum token efficiency:"," 1. 'workspace.session_index_symbols' to get symbol IDs"," 2. 'workspace.alien_patch' with opcodes: e:(export) s:(async) f:(func) c:(const) l:(let) r:(return) a:(await) i:(if) p:(Promise)"," Format: !ID > { [code] }","- For risky changes: create a ghost timeline first ('workspace.timeline_create'), run and verify there, then promote.","- Before promoting: run 'workspace.validate_patch' and 'workspace.ghost_verify'.","- Before production-ready handoff or PR preparation: run 'workspace.production_readiness' with action='gate'. It checks model routing, RAG quality, timelines, runtime learning, visual evidence, memory, and review gates.","","# How to debug","- For a failing test or command: 'runtime.start' → 'runtime.capture_failure' → 'runtime.explain_failure'.","- For deeper root cause: 'runtime.capture_deep_autopsy' or 'workspace.symptom_bisect'.","- For tracing a specific request through the system: 'runtime.trace_request'.","- For reproducing intermittent bugs: 'workspace.schrodingers_ast' or 'workspace.reality_fork'.","- For diagnosing why something broke after a change: 'workspace.causal_autopsy'.","","# How to work on complex tasks","- For issue-to-PR work: use 'workspace.issue_autopilot' to plan, patch in an isolated timeline, verify, review, write a proof bundle, and optionally create the PR.","- For tasks that touch many files or need parallel exploration: spawn sub-agents with 'agent.spawn' or 'agent.spawn_swarm'.","- For competing fix approaches: 'agent.race_fixes' — run both in ghost timelines, compare results, promote the winner.","- For multi-step plans before execution: 'agent.plan' to validate the approach first.","- Always match the user's style using 'workspace.ghost_engineer' memory before writing new code.","","# Proactive behaviors — do these without being asked","- After fixing a bug: check for the same pattern elsewhere with 'workspace.grep_ripgrep' or 'workspace.find_edge_cases'.","- Before a major edit: run 'workspace.predictive_repair' to surface related fragile areas.","- When the user describes a problem: immediately use 'workspace.ask_codebase' or 'workspace.causal_intelligence' to locate the root cause before responding.","- When you see TODOs or known gaps while working: note them or resolve with 'workspace.todo_resolver'.","- When tests are missing for a changed file: proactively offer to generate property tests via 'workspace.generate_properties'.","- For broad production hardening: use 'workspace.model_route' first, then 'workspace.production_readiness' to keep work aligned with the right specialist models and gates.","","# Safety","- Never run destructive shell commands (rm -rf, drop table, git reset --hard, force push) without explicit user confirmation.","- For dangerous operations, always use shadow/timeline execution first: 'workspace.run_in_shadow' or 'workspace.timeline_run'.","- Token budget is finite. Prefer capsule-based reads. Avoid re-reading files already in context."].join("\\n"),z=["# Voice Mode Active","Respond for spoken conversation, not for markdown reading.","","## Voice Contract","- **Short & Natural**: Use short natural sentences. Reply in plain text only.","- **No Formatting**: Never use emojis, bullet lists, markdown formatting, headings, code fences, or decorative symbols.","- **Conciseness**: Keep answers very short unless the user explicitly asks for more detail.","- **Readability**: Avoid reading punctuation-heavy structures aloud.","- **Code**: If the user asks a coding question, answer briefly first and only give commands or code when truly necessary."].join("\\n"),B=[{name:"auto",message:"Auto-detect",hint:"Detect language from audio"},{name:"de",message:"Deutsch",hint:"de"},{name:"en",message:"English",hint:"en"},{name:"ar",message:"Arabic",hint:"ar"},{name:"es",message:"Spanish",hint:"es"},{name:"fr",message:"French",hint:"fr"},{name:"it",message:"Italian",hint:"it"},{name:"ja",message:"Japanese",hint:"ja"},{name:"pt",message:"Portuguese",hint:"pt"}],W=[{name:"auto",message:"Auto",hint:"Pick best voice for language"},{name:"Puck",message:"Puck",hint:"Neutral English default"},{name:"Kore",message:"Kore",hint:"Clear — good for German, Japanese"},{name:"Aoede",message:"Aoede",hint:"Warm — good for French, Portuguese"},{name:"Charon",message:"Charon",hint:"Good for Spanish"},{name:"Fenrir",message:"Fenrir",hint:"Alternative voice"},{name:"Zephyr",message:"Zephyr",hint:"Alternative voice"}],G={ar:"Arabic",de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",ja:"Japanese",pt:"Portuguese"},J=[/^\/voice off$/,/(voice|sprachmodus|stimmmodus)\s*(aus|off|beenden|beendet|stoppen|stoppt)/i,/(beende|beendet|beenden|stoppe|stoppen|stopp|verlasse|verlassen)\s*(den\s*)?(voice|sprachmodus|stimmmodus)/i,/(stop|exit|quit|disable)\s+(voice)/i,/(voice|voice mode|voice chat)\s+(off|stop|exit|quit|disable)/i,/stop listening/i,/stop recording/i,/textmodus\s*(an|zuruck|bitte)/i,/zuruck zum text/i],Y=I,K=new Set(["cyan","magenta","yellow","green","blue","white"]);export class AgentLoop{config;backend;ghostTextListener=null;llm;useAnsi=f.isTTY;sessionStore;artifactStore;contextAssembler=new P;currentModelId;currentBranch="nogit";localInstructions="";transcript=[];sessionCapsule=null;lastToolEventAt=null;sessionTokens={inputTokens:0,outputTokens:0};workspaceContext="";abortController=null;autoApproveTools=!1;dynamicMaxSteps;themeColor=y.cyan;persistentHistory=[];historyPath=p.join(k.homedir(),".mesh_history");voiceManager;voiceMode=!1;voiceLanguage="en";prefetchQueue=[];pendingPrefetchQueue=[];currentTurnPreferredTools=[];dashboardEventWrite=Promise.resolve();dashboardActionTimer=null;dashboardActionRunning=!1;dashboardToken=null;toolEventsExpanded=!1;turnToolCalls=0;turnToolErrors=0;turnToolNames=new Map;turnArtifactCharsStored=0;turnArtifactEnvelopeChars=0;sessionRawSaved=0;turnContextReports=[];lastContextReport=null;currentTurnRouteContext=null;entangledWorkspaces=[];gitStatusContext="";consecutiveErrors=new Map;portal;headlessInitialized=!1;streamingUnavailable=!1;sessionManager;constructor(e,t,s){this.config=e,this.backend=t,this.sessionStore=new N(e.agent.workspaceRoot),this.artifactStore=new F(e.agent.workspaceRoot),this.dynamicMaxSteps=e.agent.maxSteps,this.portal=new H(e.agent.workspaceRoot),this.currentModelId=e.bedrock.modelId,this.llm=new L({endpointBase:e.bedrock.endpointBase,modelId:this.currentModelId,fallbackModelIds:e.bedrock.fallbackModelIds,bearerToken:e.bedrock.bearerToken,googleApiKey:e.bedrock.googleApiKey,temperature:e.bedrock.temperature,maxTokens:e.bedrock.maxTokens}),this.sessionManager=s??U(e.agent.workspaceRoot);const i=e.agent.themeColor||"cyan",n=y[i];"function"==typeof n&&(this.themeColor=n),this.voiceManager=this.buildVoiceManager(),this.syncVoiceLanguage(),this.startDashboardActionPump()}buildVoiceManager(){return new q({voiceLanguage:this.config.agent.voice.language,voiceSpeed:this.config.agent.voice.speed,voiceName:this.config.agent.voice.voice,voiceInput:this.config.agent.voice.microphone,googleApiKey:this.config.bedrock?.googleApiKey})}applyVoiceSettings(e){this.config.agent.voice={...e},this.voiceManager.updateConfig({voiceLanguage:e.language,voiceSpeed:e.speed,voiceName:e.voice,voiceInput:e.microphone}),this.syncVoiceLanguage(e.language)}normalizeLanguageCode(e){return String(e||"auto").trim().toLowerCase().replace(/_/g,"-")}getConfiguredVoiceLanguage(){return this.normalizeLanguageCode(this.config.agent.voice.language)}syncVoiceLanguage(e){const t=this.getConfiguredVoiceLanguage();this.voiceLanguage="auto"===t?this.normalizeLanguageCode(e||this.voiceLanguage||"en"):t}getVoiceReplyLanguage(){const e=this.getConfiguredVoiceLanguage();return"auto"===e?this.normalizeLanguageCode(this.voiceLanguage||"en"):e}buildVoiceLanguageInstruction(){const e=this.getVoiceReplyLanguage(),t=G[e.split("-")[0]]||e;return"auto"===this.getConfiguredVoiceLanguage()?`Reply in the same language as the user's last spoken message. Current detected language: ${t}.`:`Always reply in ${t} unless the user explicitly asks to switch languages.`}sanitizeVoiceAssistantText(e){return e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*>\s+/gm,"").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/\p{Extended_Pictographic}/gu,"").replace(/[•▪◦●○◆◇★☆]/g," ").replace(/\s+/g," ").trim()||e.replace(/\s+/g," ").trim()}normalizeVoiceCommand(e){return e.trim().toLowerCase().normalize("NFKD").replace(/\p{Diacritic}/gu,"").replace(/[^\p{L}\p{N}\/\s]+/gu," ").replace(/\s+/g," ").trim()}isVoiceExitCommand(e){const t=this.normalizeVoiceCommand(e);return!!t&&J.some(e=>e.test(t))}getVoiceExitHint(){const e=this.getVoiceReplyLanguage().split("-")[0];return"de"===e?'Sage "Voice aus" oder "beende Sprachmodus", um Voice zu verlassen.':"en"===e?'Say "voice off" or "stop voice mode" to leave voice mode.':'Say "voice off" or "Voice aus" to leave voice mode.'}async refreshGitStatus(){try{const e=await this.backend.callTool("workspace.git_status",{});e.ok&&(this.gitStatusContext=`${e.branch}\nFiles:\n${e.status||"Clean (no uncommitted changes)"}`)}catch{this.gitStatusContext=""}}normalizeInspectUrl(e){const t=e.trim()||"http://localhost:3000";return/^https?:\/\//i.test(t)?t:`http://${t}`}async isUrlReachable(e,t=700){return await new Promise(s=>{let i;try{i=new URL(e)}catch{return void s(!1)}const n=b.request({hostname:i.hostname,port:i.port||("https:"===i.protocol?443:80),path:i.pathname||"/",method:"HEAD",timeout:t},e=>{e.resume(),s(Boolean(e.statusCode&&e.statusCode<500))});n.on("error",()=>s(!1)),n.on("timeout",()=>{n.destroy(),s(!1)}),n.end()})}async findReachableDevUrl(t){if(await this.isUrlReachable(t))return t;const s=new URL(t),i="0.0.0.0"===s.hostname?"127.0.0.1":s.hostname,n=e([s.port||("https:"===s.protocol?"443":"80"),"5173","5174","3000","3001","4173","8080"],8);for(const e of n){const t=`${s.protocol}//${i}:${e}`;if(await this.isUrlReachable(t,450))return t}return null}async handleInspect(e){let t=this.normalizeInspectUrl(e),s=await this.findReachableDevUrl(t);if(!s){f.write(y.yellow(`\n[Mesh Portal] No dev server detected near ${t}. Starting the workspace dev script...\n`));try{const e=p.join(this.config.agent.workspaceRoot,"package.json");let i={};try{i=JSON.parse(await u.readFile(e,"utf8"))}catch{}if(!(i.scripts?.dev||i.scripts?.start))throw new Error("No 'dev' or 'start' script found in package.json");{const{spawn:e}=await import("node:child_process");e("npm",["run",i.scripts?.dev?"dev":"start"],{cwd:this.config.agent.workspaceRoot,stdio:"ignore",detached:!0}).unref(),f.write(y.green("[Mesh Portal] Dev server launched in background. Probing common local ports...\n"));for(let e=0;e<25&&(await new Promise(e=>setTimeout(e,1e3)),s=await this.findReachableDevUrl(t),!s);e++);}}catch(e){f.write(y.red(`[Mesh Portal] Could not start server: ${e.message}\n`))}}s&&(t=s);const i=$({text:`Connecting visual inspector to ${t}...`,color:"cyan"}).start();try{await this.portal.start(t,async e=>{"meshEmit"===e.name&&await this.handlePortalMutation(e.payload)});const e=p.join(p.dirname(new URL(import.meta.url).pathname),"mesh-canvas-overlay.js"),s=await u.readFile(e,"utf8");await this.portal.evaluate(s),i.succeed(y.green(`Visual inspector active on ${t}. Alt+Click an element to describe a UI change.`))}catch(e){i.fail(y.red(`Visual inspector failed: ${e.message}`)),f.write(y.dim(`Tip: run your app manually, then use /inspect http://localhost:<port> or /preview ${t}.\n`))}}async handlePortalMutation(e){let t;try{t=JSON.parse(e)}catch{return}const{type:s,file:i,line:n,prompt:a,context:o,xray:r}=t,c=r?.source?.fileName||i,l=r?.source?.lineNumber||n;if(!c||"unknown"===c)return;const d=p.relative(this.config.agent.workspaceRoot,c),h=r?.component||this.extractComponentName(o?.tag,o?.classes)||"Anonymous",m=Array.isArray(r?.requests)?r.requests.slice(0,5):[],g=await Promise.all(m.map(async e=>{const t=`${String(e.method||"GET").toUpperCase()} ${e.route||e.url||""}`.trim();if(!t)return null;const s=await this.backend.callTool("workspace.ask_codebase",{query:t,mode:"runtime-path",limit:2}).catch(()=>null);return{request:e,matches:Array.isArray(s?.results)?s.results.slice(0,2).map(e=>({file:e.file,purpose:e.purpose,citations:Array.isArray(e.citations)?e.citations.slice(0,2).map(e=>({file:e.file,symbol:e.symbol,lines:e.lines,whyMatched:e.whyMatched})):[]})):[]}})),w=h&&"Anonymous"!==h?await this.backend.callTool("workspace.trace_symbol",{path:d,symbol:h}).catch(()=>null):null,$=g.filter(Boolean);if("PROMPT"===s){process.stdout.write(y.cyan(`\n[Visual AI] Designing for ${y.bold(d)}:${l||n||0}...\n`)),process.stdout.write(y.dim(` " ${a} "\n`));const e=await u.access(p.join(this.config.agent.workspaceRoot,"tailwind.config.js")).then(()=>!0).catch(()=>u.access(p.join(this.config.agent.workspaceRoot,"tailwind.config.ts")).then(()=>!0).catch(()=>!1)),t=`The user clicked an element in the browser and provided a visual instruction.\nEvidence:\n${[`Source: ${d}:${l||0}`,`Component: ${h}`,m.length>0?`Requests:\n${m.map(e=>`- ${String(e.method||"GET").toUpperCase()} ${e.route||e.url} -> ${e.status}${e.durationMs?` (${e.durationMs}ms)`:""}`).join("\n")}`:"Requests: none captured",$.length>0?`Route matches:\n${$.map(e=>{const t=e.matches.length>0?e.matches.map(e=>`- ${e.file}: ${e.purpose}`).join("\n"):"- no strong matches";return`${e.request.method} ${e.request.route||e.request.url}\n${t}`}).join("\n")}`:"Route matches: none",w&&w.ok?`Symbol trace:\n${JSON.stringify(w,null,2)}`:"Symbol trace: unavailable",`DOM:\n${o.html}`,`Parent DOM:\n${o.parentHtml}`].join("\n\n")}\n\nUser Instruction: "${a}"\nStyling Paradigm: ${e?"TAILWIND CSS (Use utility classes, avoid inline styles)":"STANDARD CSS/INLINE"}\n\nYour mission is a two-step process:\n1. IMMEDIATELY output a JSON block labeled 'PREVIEW_STYLE' with CSS properties for instant preview.\n2. Then, proceed to apply the PERMANENT code patch to the file using your tools.\n\nEnsure the final code is clean, idiomatic, and adheres to the styling paradigm. Finalize once done.`;let s=!1;const i={onDelta:async e=>{if(!s&&e.includes("PREVIEW_STYLE"))try{const t=e.match(/PREVIEW_STYLE\s*(\{.*?\})/);if(t){try{const e=JSON.parse(t[1]);await this.portal.applyGhostStyles(e)}catch{f.write(y.red("[Mesh] Error: Ghost styles parse failed — skipping live preview update.\n"))}s=!0,process.stdout.write(y.green("\n[Ghost Sync] Live preview applied. Capturing for Vision check...\n")),await new Promise(e=>setTimeout(e,300));const e=await this.portal.captureElementScreenshot();e&&(this.transcript.push({role:"user",content:[{text:"Here is a live screenshot of the element after your PREVIEW_STYLE was applied. Visual check: Does this match the user intent? If yes, finalize the code patch. If not, output a corrected PREVIEW_STYLE or adjust your patch."},{image:{format:"png",source:{bytes:e}}}]}),process.stdout.write(y.cyan("[Vision] Screenshot sent to Agent for verification.\n")))}}catch(e){}process.stdout.write(e)}};try{await this.runSingleTurn(t,i)}catch(e){process.stdout.write(y.red(`\n[Visual AI] Error: ${e.message}\n`))}}}extractComponentName(e,t){if(!e)return"Anonymous";const s=String(t||"").trim(),i=s?s.split(/\s+/)[0]:"";return i?`${e}.${i}`:e}async runCli(e){this.llm.logEndpoint(),await this.checkInit(),this.sessionCapsule=await this.sessionStore.load();try{const e=await u.readFile(this.historyPath,"utf-8");this.persistentHistory=e.split("\n").filter(Boolean).reverse(),this.persistentHistory=e.split("\n").filter(Boolean)}catch{this.persistentHistory=[]}try{const{execFile:e}=await import("node:child_process"),{promisify:t}=await import("node:util"),s=t(e),i=this.config.agent.workspaceRoot,[n,a]=await Promise.allSettled([s("git",["branch","--show-current"],{cwd:i}),s("git",["status","--short"],{cwd:i})]),o="fulfilled"===n.status?n.value.stdout.trim():"",r="fulfilled"===a.status?a.value.stdout.trim():"";o&&(this.currentBranch=o,this.workspaceContext=`Workspace context:\n- Git branch: ${o}\n- Git status:\n${r||"clean"}`)}catch{}try{const e=p.join(this.config.agent.workspaceRoot,".mesh","instructions.md");this.localInstructions=await u.readFile(e,"utf-8")}catch{}if(e?.trim()){const t=await this.tryLocalIntentAnswer(e);if(t)return void await this.renderLocalQuickAnswer(t);const s=await this.runSingleTurn(e);return void f.write(`${s}\n`)}if(this.printBanner(),await this.printStatus(),this.sessionManager.hasInterruptedSession()){const e=this.sessionManager.getInterruptedSession();if(e&&e.length>0){f.write(y.yellow("\n[Session] Found interrupted session from previous run.\n"));const t=new _({name:"resume",message:"Resume previous session?",initial:!0,stdin:g,stdout:f});if(await t.run()){for(const t of e)if("user"===t.role)this.transcript.push({role:"user",content:[{text:t.content}]});else{const e=[{text:t.content}];if(t.toolCalls?.length)for(const s of t.toolCalls)e.push({toolUse:{toolUseId:s.id,name:s.name,input:s.input}});this.transcript.push({role:"assistant",content:e})}f.write(y.green(`[Session] Resumed ${e.length} turns.\n`))}this.sessionManager.clearInterruptedSession()}}let t=0;for(;;){const e=m.createInterface({input:g,output:f,terminal:!0,completer:e=>this.completeInput(e),history:[...this.persistentHistory]});this.setupGhostText(e,g,f),e.on("SIGINT",()=>{if(this.abortController)this.abortController.abort(),this.abortController=null,f.write("\n\n"+y.dim("Request aborted. Returning to prompt.")+"\n");else{const s=Date.now();s-t<2e3?(e.close(),process.exit(0)):(t=s,f.write("\n"+this.themeColor(y.bold("Press Ctrl+C again within 2s to exit"))+"\n"),e.line="",e.write("\n"))}});const i=this.buildPrompt();let n="";try{if(this.voiceMode){f.write(this.themeColor(y.bold("\n[LISTENING]"))+y.dim(" (stops after silence...)\n"));try{const e=await this.voiceManager.record();f.write(y.dim("Transcribing...\n"));const t=await this.voiceManager.transcribe(e);n=t.text,this.syncVoiceLanguage(t.language),f.write(y.bold(`❯ ${n}\n`))}catch(t){f.write(y.red(`Voice error: ${t.message}\n`)),this.voiceMode=!1,e.close();continue}}else n=(await e.question(i)).trim();n&&!n.startsWith("/")&&n!==this.persistentHistory[this.persistentHistory.length-1]&&(this.persistentHistory.push(n),this.persistentHistory.length>1e3&&this.persistentHistory.shift(),await u.writeFile(this.historyPath,this.persistentHistory.join("\n"),"utf-8"))}catch(t){e.close();break}if(!n){e.close();continue}if(this.voiceMode&&this.isVoiceExitCommand(n)){this.voiceMode=!1,this.renderSystemMessage(y.green("Voice mode disabled. Back to text input.")),e.close();continue}if("exit"===n.toLowerCase()||"quit"===n.toLowerCase()){e.close();break}if(n.startsWith("/")){const t=await this.handleSlashCommand(n,e);if(e.close(),t.shouldExit)break;if(t.wasHandled)continue}const a=await this.tryLocalIntentAnswer(n);if(a)e.close(),await this.renderLocalQuickAnswer(a);else{await this.refreshGitStatus();try{const e=this.useAnsi?$({text:"Thinking...",color:"cyan",stream:f}).start():void 0;let t;this.sessionTokens;this.resetToolSummary();try{const i={onToolStart:(t,i,n,a)=>{if(e){const o=`[${n+1}/${a}]`;e.text=`${y.dim(o)} ${y.cyan(t)} ${y.dim(s(i))}`}this.renderToolEvent("start",t,s(i))},onToolEnd:(t,s,i)=>{e&&(e.text=s?`done ${y.cyan(t)}`:`failed ${y.cyan(t)}`),this.renderToolEvent(s?"success":"error",t,i)},onCommandChunk:t=>{e&&(e.stop(),e.clear()),f.write(t)},askPermission:async t=>{e&&e.stop();const s=this.useAnsi?y.yellow(`\n[Action Required]\n${t}\n[y/N/A]: `):`\n[Action Required]\n${t}\n[y/N/A]: `,i=m.createInterface({input:g,output:f}),n=(await i.question(s)).trim().toLowerCase();if(i.close(),"a"===n)return this.autoApproveTools=!0,e&&e.start(),!0;const a="y"===n||"yes"===n;return e&&e.start(),a}};if(this.voiceMode){t=await this.runSingleTurn(n,i);const s=this.sanitizeVoiceAssistantText(t);e&&(e.stop(),e.clear()),this.renderAssistantTurn(s),await this.voiceManager.speak(s,this.getVoiceReplyLanguage()).catch(e=>{this.renderSystemMessage(y.red(`Voice output failed: ${e.message}`))})}else{let s=!1;t=await this.runSingleTurn(n,{...i,onDelta:t=>{e&&(e.stop(),e.clear()),s||(s=!0,f.write("\n"+this.themeColor(y.bold("assistant"))+y.dim(" › ")+"\n")),f.write(t)}}),s?f.write("\n"):t&&this.renderAssistantTurn(t)}}finally{e&&(e.stop(),e.clear())}this.printToolSummary();const i=await this.autoCompactIfNeeded();i&&this.renderSystemMessage(i)}catch(e){this.renderSystemMessage(y.red(`Error: ${e.message}`))}finally{e.close()}}}}async runInit(e=[],t){if(this.llm.logEndpoint(),await this.checkInit(),this.sessionCapsule=await this.sessionStore.load(),f.write(this.themeColor(`\n${y.bold("Mesh Agent - Private Alpha")}\n`)),f.write(y.dim("Thank you for participating in the early access program.\n\n")),void 0===this.config.telemetry.contribute){const e=new _({name:"telemetry",message:"Can we collect anonymous telemetry to help improve Mesh?",initial:!0}),t=Boolean(await e.run().catch(()=>!1)),s=await R();await j({...s,telemetry:t}),this.config.telemetry.contribute=t,f.write(y.dim(t?"Telemetry enabled. Thank you!\n":"Telemetry disabled.\n"))}f.write(this.themeColor(`${y.bold("\nFirst-Run System Check")}\n`)),await this.runDoctor(["fix"]),t&&!await t.restoreAuthenticated()&&(f.write(y.yellow("\n[Mesh] Initial setup complete. Login is required for model access.\n")),await t.ensureAuthenticated(),this.config.bedrock.bearerToken||=t.getAccessToken()),f.write(y.green(y.bold('\n✓ All set! Start by asking: "What can you do here?"\n\n')))}async runDoctorCli(e=[]){this.llm.logEndpoint(),await this.runDoctor(e)}async runHeadlessTurn(e,t){await this.initializeHeadlessSession();const s=e.trim();if(!s)throw new Error("Headless turn requires non-empty input");const i=await this.tryLocalIntentAnswer(s);if(i)return{text:i,modelId:this.currentModelId,usageDelta:{inputTokens:0,outputTokens:0,totalTokens:0},totalUsage:{...this.sessionTokens}};await this.refreshGitStatus(),this.resetToolSummary();const n={...this.sessionTokens};return{text:await this.runSingleTurn(s,{...t,silent:!1,askPermission:t?.askPermission??(async()=>!1)}),modelId:this.currentModelId,usageDelta:{inputTokens:this.sessionTokens.inputTokens-n.inputTokens,outputTokens:this.sessionTokens.outputTokens-n.outputTokens,totalTokens:this.sessionTokens.inputTokens-n.inputTokens+this.sessionTokens.outputTokens-n.outputTokens},totalUsage:{...this.sessionTokens}}}async initializeHeadlessSession(){if(!this.headlessInitialized){await this.checkInit(),this.sessionCapsule=await this.sessionStore.load();try{const e=p.join(this.config.agent.workspaceRoot,".mesh","instructions.md");this.localInstructions=await u.readFile(e,"utf-8")}catch{this.localInstructions=""}this.headlessInitialized=!0}}async runSingleTurn(e,i){const n=i?.silent,a=await this.autoCompactIfNeeded();a&&!n&&this.renderSystemMessage(a),this.pendingPrefetchQueue.length>0&&this.prefetchQueue.push(...this.pendingPrefetchQueue.splice(0));const o=function(e){const s=new Set,i=[];for(const n of e){const e=t(n.name);let a=e,o=2;for(;s.has(a);)a=`${e}_${o}`,o+=1;s.add(a),i.push({wireName:a,tool:n})}return i}(await this.backend.listTools()),r=function(e,t){const s=t.toLowerCase(),i=new Set,n=(...e)=>{for(const t of e)i.add(t)};n("workspace.open_artifact","workspace.ask_codebase","workspace.get_diagnostics","workspace.git_status","workspace.list_files","workspace.list_directory","workspace.semantic_search","workspace.search_files","workspace.grep_ripgrep","workspace.read_file","workspace.get_file_graph","workspace.read_dir_overview","agent.plan"),/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|fehler|beheb|änder|aender|bau|mach)/i.test(s)&&n("workspace.write_file","workspace.patch_file","workspace.patch_surgical","workspace.run_command","workspace.read_file_raw","workspace.read_multiple_files","workspace.validate_patch","workspace.git_diff","workspace.impact_map","workspace.company_brain","workspace.explain_symbol","workspace.list_symbols","workspace.finalize_task"),/(dashboard|ui|frontend|browser|screenshot|inspect|visual|react|css|html)/i.test(s)&&n("web.inspect_ui","frontend.preview","workspace.trace_symbol","workspace.expand_execution_path"),/(runtime|crash|exception|stack|trace|debug|hologram|server|request|autopsy)/i.test(s)&&n("workspace.run_with_telemetry","runtime.start","runtime.capture_failure","runtime.capture_deep_autopsy","runtime.trace_request","runtime.explain_failure","runtime.fix_failure"),/(offene probleme|problem|bug|issue|ticket|pr|pull request|risk|risiko|audit|review|diagnos|causal|lab|repair|twin|ghost|fork|intent|memory|brain|cockpit)/i.test(s)&&n("workspace.digital_twin","workspace.predictive_repair","workspace.engineering_memory","workspace.company_brain","workspace.issue_autopilot","workspace.production_readiness","workspace.model_route","workspace.intent_compile","workspace.cockpit_snapshot","workspace.causal_intelligence","workspace.discovery_lab","workspace.reality_fork","workspace.ghost_engineer"),/(timeline|race|future|fork|parallel|promote|merge|swarm|agent)/i.test(s)&&n("workspace.timeline_create","workspace.timeline_apply_patch","workspace.timeline_run","workspace.timeline_compare","workspace.timeline_promote","workspace.timeline_list","agent.race_fixes","agent.spawn","agent.review","agent.merge_verified","agent.status");const a=e.filter(({tool:e})=>i.has(e.name));return a.length>0?a:e.slice(0,16)}(o,e);this.currentTurnPreferredTools=r.map(e=>e.tool.name);const c=function(e){return e.map(({wireName:e,tool:t})=>({name:e,description:t.description??"",inputSchema:t.inputSchema??{type:"object",properties:{}}}))}(o),l=new Map(o.map(e=>[e.wireName,e])),u=this.transcript.length;this.currentTurnRouteContext=await this.buildTurnRouteContext(e).catch(()=>null),this.transcript.push({role:"user",content:[{text:e}]}),this.sessionManager.addMessage("user",e);let h="";this.abortController=new AbortController;const p=this.maxStepsForInput(e),m=this.toolBudgetForInput(e),g=this.maxTokensForInput(e);let w=0;const v=new Set,k=new Map,b=!this.useAnsi||n||i?void 0:$({text:"Thinking...",color:"cyan",stream:f}).start();try{for(let e=0;e<p;e+=1){let t;if(i?.onDelta&&!this.streamingUnavailable){let e="";const s=[];try{const a=this.prepareModelInput(u,c),o=this.llm.converseStream(a.messages,a.tools,a.systemPromptArray,this.currentModelId,this.abortController.signal,g);for await(const t of o)"text"===t.kind&&t.text?(e+=t.text,n||i.onDelta(t.text)):"tool_use"===t.kind?s.push(t.toolUse):"stop"===t.kind&&t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0);t=s.length>0?{kind:"tool_use",toolUses:s.map(e=>({toolUseId:e.toolUseId,name:e.name,input:e.input??{}})),text:e||void 0,stopReason:"tool_use"}:{kind:"text",text:e,stopReason:"end_turn"}}catch(e){if(!d(e instanceof Error?e.message:String(e)))throw e;this.streamingUnavailable=!0;const s=this.prepareModelInput(u,c);t=await this.llm.converse(s.messages,s.tools,s.systemPromptArray,this.currentModelId,this.abortController.signal,g),t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0),t.text&&i.onDelta(t.text)}}else{const e=this.prepareModelInput(u,c);t=await this.llm.converse(e.messages,e.tools,e.systemPromptArray,this.currentModelId,this.abortController.signal,g),t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0),i?.onDelta&&t.text&&i.onDelta(t.text)}if("text"===t.kind)return this.transcript.push({role:"assistant",content:[{text:t.text}]}),this.sessionManager.addMessage("assistant",t.text||""),t.text||h||"(no answer)";h=t.text??h;const a=[];t.text&&a.push({text:t.text});for(const e of t.toolUses)a.push({toolUse:{toolUseId:e.toolUseId,name:e.name,input:e.input}});this.transcript.push({role:"assistant",content:a}),this.sessionManager.addMessage("assistant",t.text||"",t.toolUses.map(e=>({id:e.toolUseId,name:e.name,input:e.input})));const o=new Map;for(const e of t.toolUses){const t=l.get(e.name);if(t)if(n)o.set(e.toolUseId,!0);else if(t.tool.requiresApproval&&!this.autoApproveTools){const s=this.buildApprovalPreview(t.tool.name,e.input),n=!i?.askPermission||!await i.askPermission(s);o.set(e.toolUseId,!n)}else o.set(e.toolUseId,!0);else o.set(e.toolUseId,!1)}const r=t.toolUses.map(e=>{const t=w<m;return w+=1,{tu:e,allowed:t}}),f=await Promise.all(r.map(async({tu:t,allowed:a})=>{const r=l.get(t.name),c=`${t.name}:${JSON.stringify(t.input)}`,d=this.toolFamilyFor(t.name);if(!a)return{toolUseId:t.toolUseId,status:"error",text:"Tool budget reached for this turn. Stop using tools and answer with the evidence already gathered."};if(v.has(c))return{toolUseId:t.toolUseId,status:"error",text:"Duplicate tool call blocked by Mesh Stop-Law. Use existing evidence or ask for a narrower artifact slice."};v.add(c);const u=k.get(d)??0;if(u>=("read"===d?4:"search"===d?3:2)&&"workspace_open_artifact"!==t.name)return{toolUseId:t.toolUseId,status:"error",text:`Repeated ${d} tools blocked by Mesh Stop-Law. Stop tool use and answer from gathered evidence.`};if(k.set(d,u+1),!r)return{toolUseId:t.toolUseId,status:"error",text:`Tool '${t.name}' is not available.`};if(!o.get(t.toolUseId))return{toolUseId:t.toolUseId,status:"error",text:"Tool requires interactive approval but no TTY is available."};if(this.emitPulse("tool_start",t.input.path,t.name),!n){if(b){const i=`[${e+1}/${p}]`;b.text=`${y.dim(i)} ${y.cyan(t.name)} ${y.dim(s(t.input))}`}i?.onToolStart?.(t.name,t.input,e,p)}try{if(("workspace.write_file"===r.tool.name||"workspace.patch_file"===r.tool.name||"workspace.alien_patch"===r.tool.name)&&this.transcript.length>=10){const e=`CRITICAL PRE-FLIGHT CHECK: You are about to modify a file (${t.input.path||"unknown"}). Based on the long context history, is there any contradictory fact or limitation that makes this edit unsafe or incorrect? Reply with ONLY 'SAFE' or 'UNSAFE: [reason]'.`;try{const s=await this.llm.converse([{role:"user",content:[{text:e}]}],[],"You are a Fact Verification Module."),i="text"===s.kind?s.text.trim().toUpperCase():"";if(i.startsWith("UNSAFE"))return!n&&b&&b.fail(y.red(`Fact Verification Blocked Edit: ${i}`)),{toolUseId:t.toolUseId,status:"error",text:`Fact Verification Pre-flight failed: ${i}`}}catch(e){}}const e=await this.backend.callTool(r.tool.name,t.input,{onProgress:n?void 0:i?.onCommandChunk});if("workspace.read_file"===r.tool.name||"workspace.expand_execution_path"===r.tool.name){const e=String(t.input.path??"");e&&(async()=>{const t=await this.backend.callTool("workspace.get_file_graph",{path:e}).catch(()=>null);t?.ok&&t.dependencies&&(await Promise.all(t.dependencies.slice(0,2).map(async e=>{const t=await this.backend.callTool("workspace.read_file",{path:e,tier:"low"}).catch(()=>null),s=t?.capsule??t?.content;s&&this.pendingPrefetchQueue.push(`File: ${e}\n${s}`)})),this.pendingPrefetchQueue.length>6&&(this.pendingPrefetchQueue=this.pendingPrefetchQueue.slice(-6)))})().catch(()=>{})}const s="workspace.open_artifact"===r.tool.name?this.clampToolResultText(r.tool.name,[`Tool called: ${r.tool.name}`,`Arguments: ${JSON.stringify(t.input)}`,`Result: ${JSON.stringify(e)}`].join("\n")):await this.buildToolEnvelopeText(r.tool.name,t.input,e);return n||i?.onToolEnd?.(t.name,!0,this.normalizeCapsuleLine(s,120)),this.consecutiveErrors.delete(c),{toolUseId:t.toolUseId,status:"success",text:s}}catch(e){const s=e.message,a=`${c} -> ${s}`,o=(this.consecutiveErrors.get(a)||0)+1;this.consecutiveErrors.set(a,o);const l=r.tool.name;let d="Try /doctor to diagnose.";s.includes("ENOENT")||s.includes("no such file")?d="Check that the file path exists, or run /index to rebuild workspace state.":s.includes("EACCES")||s.includes("permission denied")?d="Check file permissions with your OS.":(s.includes("timed out")||s.includes("AbortError"))&&(d="The operation timed out — try /compact to reduce context.");let u=`[Mesh] Error: ${l} failed — ${s.slice(0,200)}. ${d}`;return o>=2&&(u+="\n\n[MESH SYSTEM WARNING] This exact error has occurred multiple times. DO NOT retry the same action. Either try a different approach or stop and ask the user for clarification."),n||i?.onToolEnd?.(t.name,!1,this.normalizeCapsuleLine(u,120)),{toolUseId:t.toolUseId,status:"error",text:this.clampToolResultText(r.tool.name,u)}}}));this.transcript.push({role:"user",content:f.map(e=>({toolResult:{toolUseId:e.toolUseId,status:e.status,content:[{text:e.text}]}}))})}}catch(e){if(this.transcript=this.transcript.slice(0,u),"AbortError"===e.name||e.message?.includes("aborted"))return h||"Request aborted.";throw e}finally{b&&(b.stop(),b.clear()),this.abortController=null,this.currentTurnRouteContext=null,this.currentTurnPreferredTools=[]}return await this.forceFinalAnswer(h,u,c)}prepareModelInput(e,t){const s=V,i=[this.buildDynamicRuntimeContext(),this.currentTurnRouteContext].filter(Boolean).join("\n\n"),n=this.contextAssembler.assemble({transcript:this.transcript,currentTurnStart:e,tools:t,systemPrompt:s,sessionSummary:this.sessionCapsule?.summary??null,runtimeContext:i});if(this.lastContextReport=n.report,this.turnContextReports.push(n.report),n.report.totalTokens>n.report.maxInputTokens)throw new Error(`Context firewall blocked oversized request (${n.report.totalTokens}/${n.report.maxInputTokens} estimated tokens). Narrow the request or run /clear.`);return{messages:n.messages,tools:n.tools,systemPromptArray:n.systemPromptArray,report:n.report}}async forceFinalAnswer(e,t,s){const i=["Stop using tools now.","Answer the user with the evidence already gathered.","Be concise. If evidence is incomplete, say what is missing in one sentence."].join(" ");this.transcript.push({role:"user",content:[{text:i}]});const n=this.prepareModelInput(t,s),a=await this.llm.converse(n.messages,n.tools,n.systemPromptArray,this.currentModelId,this.abortController?.signal);a.usage&&(this.sessionTokens.inputTokens+=a.usage.inputTokens??0,this.sessionTokens.outputTokens+=a.usage.outputTokens??0);const o=a.text||e||"Kein belastbarer Befund.";return this.transcript.push({role:"assistant",content:[{text:o}]}),o}maxStepsForInput(e){const t=e.toLowerCase();return this.isSimpleLocalCandidate(e)?1:/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|beheb|änder|aender|bau|mach)/i.test(t)?Math.min(this.dynamicMaxSteps,4):/(runtime|crash|exception|stack|trace|debug|server|request|diagnos)/i.test(t)?Math.min(this.dynamicMaxSteps,3):(/(offene probleme|problem.*code|bug|bugs|issue|issues|diagnos|risiko|risk|audit|review|siehst du|findest du)/i.test(t),Math.min(this.dynamicMaxSteps,2))}toolBudgetForInput(e){const t=e.toLowerCase();return this.isSimpleLocalCandidate(e)?0:/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|beheb|änder|aender|bau|mach)/i.test(t)?10:/(runtime|crash|exception|stack|trace|debug|server|request|diagnos)/i.test(t)?6:/(offene probleme|problem.*code|bug|bugs|issue|issues|diagnos|risiko|risk|audit|review|siehst du|findest du)/i.test(t)?5:3}maxTokensForInput(e){const t=e.toLowerCase();return/(fix|edit|change|patch|implement|build|add|remove|refactor|write|commit|beheb|änder|aender|bau|mach)/i.test(t)?4096:/(list|read|grep|search|find|show|status|explain|summarize|zeige|lies|suche|liste)/i.test(t)?800:this.config.bedrock.maxTokens}toolFamilyFor(e){const t=e.replace(/_/g,".");return/read|open.artifact|expand/.test(t)?"read":/search|grep|ask.codebase|list/.test(t)?"search":/diagnostic|repair|causal|lab|twin|ghost|cockpit/.test(t)?"analysis":/write|patch|move|delete|run|timeline|agent/.test(t)?"action":"other"}clampToolResultText(e,t){const s=/read_file_raw|read_multiple_files|grep|ask_codebase|causal|discovery/i.test(e)?5e3:3500;return t.length<=s?t:`${t.slice(0,s)}\n\n[truncated ${t.length-s} chars; answer from available evidence or request a narrower read]`}async buildToolEnvelopeText(e,t,s){const i=await this.artifactStore.saveToolResult(e,t,s),n=this.artifactStore.buildEnvelopeText(i,s);return this.turnArtifactCharsStored+=i.originalChars,this.turnArtifactEnvelopeChars+=n.length,this.clampToolResultText(e,n)}buildApprovalPreview(e,t){if("workspace.write_file"===e){const e=String(t.path??"?"),s=String(t.content??"").split("\n").slice(0,10).join("\n");return`write_file → ${e}\n${y.dim("────────────────────")}\n${s}${String(t.content??"").split("\n").length>10?"\n…":""}`}if("workspace.patch_file"===e){const e=String(t.path??"?"),s=String(t.search??"").split("\n").slice(0,4).join("\n"),i=String(t.replace??"").split("\n").slice(0,4).join("\n");return`patch_file → ${e}\n${y.red("--- "+s)}\n${y.green("+++ "+i)}`}if("workspace.patch_surgical"===e){const e=String(t.path??"?"),s=String(t.searchBlock??"").split("\n").slice(0,6).join("\n"),i=String(t.replaceBlock??"").split("\n").slice(0,6).join("\n");return`patch_surgical → ${e}\n${y.red("SEARCH:\n"+s)}${String(t.searchBlock??"").split("\n").length>6?"\n…":""}\n${y.green("REPLACE:\n"+i)}${String(t.replaceBlock??"").split("\n").length>6?"\n…":""}`}return"workspace.run_command"===e?`run_command\n$ ${y.bold(String(t.command??"?"))}`:"workspace.delete_file"===e?`delete_file → ${y.red(String(t.path??"?"))}`:"workspace.move_file"===e?`move_file ${String(t.sourcePath??"?")} → ${String(t.destinationPath??"?")}`:`Allow ${e} to run?`}isSimpleLocalCandidate(e){const t=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");return/^(hi|hello|hey|hallo|servus|moin|guten morgen|guten tag|guten abend|wie gehts|wie geht es dir|alles gut|na wie gehts|how are you|how is it going|bist du da|da|online|ready|bereit|danke|thx|thanks|merci|dankeschoen|dankeschön|ok|okay|alles klar|passt|verstanden|got it|was kannst du|help|hilfe)$/.test(t)}async tryLocalIntentAnswer(e){const t=this.getLocalQuickAnswer(e);if(t)return t;const s=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");if(/^(status|repo status|git status|wie ist der status|was ist der status)$/.test(s)){const[e,t]=await Promise.allSettled([this.backend.callTool("workspace.git_status",{}),this.backend.callTool("workspace.get_index_status",{})]),s="fulfilled"===e.status?e.value:null,i="fulfilled"===t.status?t.value:null,n=s?.branch?`branch ${s.branch}`:"branch unbekannt",a=s?.status?String(s.status).split(/\r?\n/g).filter(Boolean).length:0;return`${n}. ${a?`${a} offene Dateiänderungen`:"Working tree sauber"}. ${null!=i?.cachedFiles&&null!=i?.totalFiles?`index ${i.cachedFiles}/${i.totalFiles}`:"index unbekannt"}.`}if(/^(welcher branch|branch|git branch)$/.test(s)){const e=await this.backend.callTool("workspace.git_status",{}).catch(()=>null);return e?.branch?`Branch: ${e.branch}.`:"Branch unbekannt."}if(/^(token status|tokens|kosten|cost|context status|context)$/.test(s)){const e=this.peakContextReport();return e?`Letzter Kontext: ca. ${o(e.totalTokens)}/${o(e.maxInputTokens)} Tokens, Tools ${e.toolsOut}/${e.toolsIn}, Messages ${e.messagesOut}/${e.messagesIn}.`:"Noch kein Modell-Call in diesem Turn."}return null}async buildTurnRouteContext(e){if(!this.shouldAttachRepoRouteContext(e))return null;const t=this.inferIndexMode(e),[s,i]=await Promise.allSettled([this.backend.callTool("workspace.ask_codebase",{query:e,mode:t,limit:5}),this.backend.callTool("workspace.git_status",{})]),n=["Purpose: pre-routed local index context. Prefer these refs before more search tools.",`Query mode: ${t}`],o=E(e);if(n.push(`Model route: ${o.taskType} confidence=${o.confidence} primary=${o.primaryChatModel}`,`Required gates: ${o.requiredGates.join(", ")}`),"fulfilled"===s.status){const e=s.value,t=Array.isArray(e?.topMatches)?e.topMatches:[];if(t.length>0){n.push("Likely relevant files:");for(const e of t.slice(0,5))n.push(`- ${e.path} :: ${a(String(e.snippet??""),160)}`)}e?.indexStatus&&n.push(`Index: ${e.indexStatus.cachedFiles}/${e.indexStatus.totalFiles} fresh (${e.indexStatus.percent}%)`)}if("fulfilled"===i.status){const e=i.value;e?.branch&&n.push(`Git branch: ${e.branch}`),e?.status&&n.push(`Dirty files: ${String(e.status).split(/\r?\n/g).filter(Boolean).slice(0,8).join("; ")}`)}return n.length>2?n.join("\n"):null}shouldAttachRepoRouteContext(e){return!this.isSimpleLocalCandidate(e)&&/(code|file|datei|src\/|test|bug|fix|edit|patch|implement|build|dashboard|graph|crash|fehler|problem|repo|commit|push|package|json|ts|js|css|html|api|tool|token|context|performance|diagnos|review|audit)/i.test(e)}inferIndexMode(e){return/(bug|fehler|crash|exception|diagnos|risk|risiko|problem)/i.test(e)?"bug":/(test|spec|coverage|verify|prüf|pruef)/i.test(e)?"test-impact":/(edit|patch|change|änder|aender|refactor|implement|mach|fix)/i.test(e)?"edit-impact":/(route|request|server|runtime|api)/i.test(e)?"runtime-path":/(commit|history|changed|dirty|recent)/i.test(e)?"recent-change":"architecture"}getLocalQuickAnswer(e){const t=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");return/^(hi|hello|hey|hallo|servus|moin|guten morgen|guten tag|guten abend)$/.test(t)?"Bin da.":/^(wie gehts|wie geht es dir|alles gut|na wie gehts|how are you|how is it going)$/.test(t)?"Läuft.":/^(bist du da|da|online|ready|bereit)$/.test(t)?"Ja.":/^(danke|thx|thanks|merci|dankeschoen|dankeschön)$/.test(t)?"Gerne.":/^(ok|okay|alles klar|passt|verstanden|got it)$/.test(t)?"Ok.":/^(was kannst du|help|hilfe)$/.test(t)?"Kurz: Code lesen, ändern, testen, Git/Dashboard/Diagnose lokal steuern. Frag direkt nach der Aufgabe.":null}async renderLocalQuickAnswer(e){const t=this.useAnsi?$({text:"Thinking...",color:"cyan",stream:f}).start():null;await new Promise(e=>setTimeout(e,260+Math.floor(180*Math.random()))),t&&(t.stop(),t.clear()),this.renderAssistantTurn(e)}printBanner(){const e=f.columns||80,t="═".repeat(e),s=[{mesh:"███╗ ███╗███████╗███████╗██╗ ██╗",left:" ▄██ ",right:" ██▄ "},{mesh:"████╗ ████║██╔════╝██╔════╝██║ ██║",left:" ▄██▀ ",right:" ▀██▄ "},{mesh:"██╔████╔██║█████╗ ███████╗███████║",left:"▄██▀ ",right:" ▀██▄"},{mesh:"██║╚██╔╝██║██╔══╝ ╚════██║██╔══██║",left:"▀██▄ ",right:" ▄██▀"},{mesh:"██║ ╚═╝ ██║███████╗███████║██║ ██║",left:" ▀██▄ ",right:" ▄██▀ "},{mesh:"╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝",left:" ▀██ ",right:" ██▀ "}],n=" ",a=" ",o=this.config.agent.accentColor||"magenta",r=y,c="function"==typeof r[o]?r[o]:y.magenta,l=[`mesh ${this.config.agent.mode} ${D(this.config.agent.workspaceRoot)}`,`branch: ${this.currentBranch} model: ${i(this.currentModelId)}`,"commands: /help for groups, /dashboard for local repo UI, /exit to quit","tip: Ask normal questions directly; slash commands are shortcuts"];if(!this.useAnsi)return f.write("\n"+t+"\n"),f.write(s.map(e=>e.mesh+n+e.left+a+e.right).join("\n")+"\n"),void f.write(l.join("\n")+"\n");f.write("\n"+this.themeColor(t)+"\n"),f.write(s.map(e=>this.themeColor(y.bold(e.mesh+n+e.left))+a+c(y.bold(e.right))).join("\n")+"\n"),f.write([`${this.themeColor(y.bold("mesh"))} ${y.dim(this.config.agent.mode)} ${y.dim(D(this.config.agent.workspaceRoot))}`,`${y.dim("branch:")} ${this.themeColor(this.currentBranch)} ${y.dim("model:")} ${this.themeColor(i(this.currentModelId))}`,`${y.dim("commands:")} ${y.magenta("/help")} ${y.dim("for groups")} ${y.magenta("/dashboard")} ${y.dim("for local repo UI")} ${y.magenta("/exit")}`,`${y.dim("tip:")} ${y.dim("Ask normal questions directly; slash commands are shortcuts")}`].join("\n")+"\n"),f.write(this.themeColor(t)+"\n")}buildPrompt(){if(!this.useAnsi)return`\n${y.cyan("◈")} ${y.bold("mesh")} // ${y.dim(this.currentBranch)} ${y.cyan("›")} `;const e=Math.max(48,Math.min(f.columns||80,140)),t=` mesh/${this.currentBranch} `,s=e-3-t.length,i=s>0?"─".repeat(s):"",n=`${this.themeColor("───")}${y.white(y.bold(t))}${this.themeColor(i)}`,a=`${this.themeColor("❯")} `;return`\n${n}\n${this.buildSessionStatsLine()}${a}`}buildSessionStatsLine(){const e=this.sessionTokens.inputTokens,t=this.sessionTokens.outputTokens;if(0===e&&0===t)return"";const s=Y.find(e=>this.currentModelId.includes(e.value)||e.value.includes(this.currentModelId)),{inputPer1k:i,outputPer1k:n}=s?.pricing??{inputPer1k:.003,outputPer1k:.015},a=e*i/1e3+t*n/1e3,r=this.lastContextReport,c=r?` · ctx ${o(r.totalTokens)}/${o(r.maxInputTokens)}`:"",l=this.sessionRawSaved>0?` · saved ~${o(Math.ceil(this.sessionRawSaved/4))}`:"";return y.dim(`↑${o(e)} ↓${o(t)} · $${a.toFixed(4)}${c}${l}\n`)}async printSync(){const e=await this.backend.callTool("workspace.check_sync",{});e.l2Enabled?f.write(["",`${this.themeColor(y.bold("Cloud Sync Status"))}`,`${y.dim("L2 Capsules:")} ${y.green(e.l2Count)}`,`${y.dim("L2 Status:")} ${y.green("Connected")}`,""].join("\n")):f.write(y.yellow("\nCloud (L2) cache is disabled. Enable it in /setup.\n"))}async printStatusLine(){const e=this.config.bedrock.modelId.split(".").pop()?.split(":")[0]||"unknown",t=this.turnContextReports.length,s=this.sessionTokens.inputTokens+this.sessionTokens.outputTokens,i=s>1e3?`${(s/1e3).toFixed(1)}k`:`${s}`;let n="0k";const a=this.turnContextReports[this.turnContextReports.length-1];if(a){const e=a.totalTokens;n=e>1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}f.write(y.dim(`[Mesh] Model: ${y.cyan(e)} | Turns: ${y.cyan(t)} | Context: ${y.cyan(n)} | Usage: ${y.yellow(i)} tk`)+"\n")}async printStatus(){const e=await this.backend.callTool("workspace.get_index_status",{}),t=this.estimateTranscriptChars();f.write(["",`${y.dim("mode:")} ${this.config.agent.mode}`,`${y.dim("workspace:")} ${D(this.config.agent.workspaceRoot)}`,`${y.dim("model:")} ${this.currentModelId}`,`${y.dim("cloud:")} ${this.config.agent.enableCloudCache?y.green("on"):y.red("off")}`,`${y.dim("index:")} ${e.cachedFiles}/${e.totalFiles} files cached (${e.percent}%)`,`${y.dim("session:")} ${this.transcript.length} messages / ${t} chars`,`${y.dim("capsule:")} ${this.sessionCapsule?y.green(`active (${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages})`):y.dim("none")}`,""].join("\n"))}emitPulse(e,t,s){const i={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,path:t,msg:s,at:(new Date).toISOString()};this.dashboardEventWrite=this.dashboardEventWrite.then(()=>this.appendDashboardEvent(i)).catch(()=>{})}startDashboardActionPump(){if(this.dashboardActionTimer)return;const e=async()=>{await this.processDashboardActions(),this.dashboardActionTimer=setTimeout(()=>{e()},900),this.dashboardActionTimer.unref()};this.dashboardActionTimer=setTimeout(()=>{e()},0),this.dashboardActionTimer.unref()}getDashboardActionsPath(){return p.join(this.getDashboardDir(),"actions.json")}async processDashboardActions(){if(!this.dashboardActionRunning){this.dashboardActionRunning=!0;try{const e=await this.readDashboardActions(),t=e.map(e=>e.status).lastIndexOf("pending");if(t<0)return;const s={...e[t],status:"running",startedAt:(new Date).toISOString()};e[t]=s,await this.writeDashboardActions(e),await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`running ${s.action}`,at:(new Date).toISOString()});try{const i=await this.executeDashboardAction(String(s.action));e[t]={...s,status:"done",finishedAt:(new Date).toISOString(),result:i},await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`done ${s.action}`,at:(new Date).toISOString()})}catch(i){e[t]={...s,status:"error",finishedAt:(new Date).toISOString(),error:i.message},await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`failed ${s.action}`,at:(new Date).toISOString()})}await this.writeDashboardActions(e.slice(0,100))}finally{this.dashboardActionRunning=!1}}}async executeDashboardAction(e){switch(e){case"repair":return await this.backend.callTool("workspace.predictive_repair",{action:"analyze"});case"causal":return await this.backend.callTool("workspace.causal_intelligence",{action:"build"});case"lab":return await this.backend.callTool("workspace.discovery_lab",{action:"run"});case"twin":return await this.backend.callTool("workspace.digital_twin",{action:"build"});case"ghost_learn":return await this.backend.callTool("workspace.ghost_engineer",{action:"learn"});default:throw new Error(`Unsupported dashboard action: ${e}`)}}async readDashboardActions(){const e=await u.readFile(this.getDashboardActionsPath(),"utf8").catch(()=>"");if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}async writeDashboardActions(e){const t=this.getDashboardActionsPath();await u.mkdir(p.dirname(t),{recursive:!0}),await u.writeFile(t,JSON.stringify(e,null,2),"utf8")}async runSetup(e){f.write(this.themeColor("\n"+"═".repeat(40)+"\n")),f.write(this.themeColor(y.bold(" MESH SETUP WIZARD\n"))),f.write(this.themeColor("═".repeat(40)+"\n"));const t=await R();try{const s=Y.map(e=>({name:e.value,message:`${y.bold(e.label)} ${y.dim(e.note)}`,hint:e.value===t.modelId?y.green("(current)"):y.dim(e.value)})),i=new A({name:"modelId",message:"Select Default Model",choices:s,initial:Y.findIndex(e=>e.value===t.modelId),stdin:g,stdout:f}),n=await i.run();e.resume();const a=new _({name:"enableCloudCache",message:"Enable Cloud (L2) Sync?",initial:t.enableCloudCache,stdin:g,stdout:f}),o=await a.run();e.resume();const r=Array.from(K).map(e=>({name:e,message:e,hint:e===t.themeColor?y.green("(current)"):""})),c=new A({name:"themeColor",message:"Select Theme Color",choices:r,initial:Array.from(K).indexOf(t.themeColor),stdin:g,stdout:f}),l=await c.run();e.resume();const d=new M({name:"customApiKey",message:"Custom API Key (Enter to keep current, '-' to clear)",initial:"",stdin:g,stdout:f}),u=await d.run();e.resume();const h=""===u?t.customApiKey:"-"===u?void 0:u,p=await this.runVoiceSetupWizard(e,t.voice);if(!p)return void f.write(y.dim("\nSetup cancelled.\n"));const m={modelId:n,enableCloudCache:o,themeColor:l,customApiKey:h,customEndpoint:t.customEndpoint,voice:p};await j(m),this.currentModelId=n;const w=y[l];"function"==typeof w&&(this.themeColor=w),this.config.agent.enableCloudCache=o,this.config.agent.themeColor=l,this.applyVoiceSettings(p),f.write(y.green("\n✔ Settings saved and applied!\n")),f.write(this.useAnsi?"":"\n"),this.printBanner(),await this.printStatus()}catch{f.write(y.dim("\nSetup cancelled.\n"))}}async runVoiceSetupWizard(e,t){try{const s=new A({name:"voiceLanguage",message:"Voice language",choices:B.map(e=>({name:e.name,message:e.message,hint:e.name===t.language?y.green("(current)"):y.dim(e.hint)})),initial:Math.max(0,B.findIndex(e=>e.name===t.language)),stdin:g,stdout:f}),i=await s.run();e.resume();const n=this.voiceManager.listAudioInputDevices(),a=[{name:"default",message:"Default microphone",hint:"default"===t.microphone?y.green("(current)"):y.dim("Use system default input")},...n.map(e=>({name:e.id,message:`${e.name} ${y.dim(`#${e.id}`)}`,hint:e.id===t.microphone?y.green("(current)"):y.dim("Specific audio input")}))],o=new A({name:"voiceMicrophone",message:"Microphone",choices:a,initial:Math.max(0,a.findIndex(e=>e.name===t.microphone)),stdin:g,stdout:f}),r=await o.run();e.resume();const c=W.map(e=>({name:e.name,message:e.message,hint:e.name===t.voice?y.green("(current)"):y.dim(e.hint)})),l=new A({name:"voiceName",message:"Gemini voice",choices:c,initial:Math.max(0,c.findIndex(e=>e.name===t.voice)),stdin:g,stdout:f}),d=await l.run();return e.resume(),this.setupGhostText(e,g,f),{configured:!0,language:i,speed:t.speed,voice:d,microphone:r}}catch{return e.resume(),this.setupGhostText(e,g,f),null}}async checkInit(){const e=p.join(this.config.agent.workspaceRoot,".mesh"),t=p.join(e,"workspace.json"),s=await u.access(e).then(()=>!0).catch(()=>!1),i=await u.access(t).then(()=>!0).catch(()=>!1);if(!s){await u.mkdir(e,{recursive:!0}),await u.mkdir(p.join(e,"index"),{recursive:!0}),await u.mkdir(p.join(e,"history"),{recursive:!0});const t=["# Mesh Project Instructions 🛸","","This file defines the engineering soul of this project.","","## 🧠 System Architecture & Intelligence","* **Capsule Cache:** All transient file summaries (L1 Cache) are stored outside this repository.","* **Project Intelligence:** The `.mesh/` folder contains high-level artifacts.","","## 📏 Coding Standards","1. **DRY & KISS:** Favor simplicity over clever abstractions.","2. **Type Safety:** Strive for 100% type coverage.","3. **Mesh Optimization:** Use `patch_file` for small changes.",""].join("\n");await u.writeFile(p.join(e,"instructions.md"),t),await u.writeFile(p.join(e,"architecture.md"),"# Architecture\n\n*Generated during indexing...*"),await u.writeFile(p.join(e,"dependency_graph.md"),"# Dependency Graph\n\n*Generated during indexing...*")}const n=p.join(e,"config.json");let a={};try{const e=await u.readFile(n,"utf-8");a=JSON.parse(e)}catch{}const o={...a,modelId:this.config.bedrock.modelId,themeColor:this.config.agent.themeColor,enableCloudCache:this.config.agent.enableCloudCache,voice:this.config.agent.voice,updatedAt:(new Date).toISOString()};if(await u.writeFile(n,JSON.stringify(o,null,2)),!i){f.write(`${y.cyan("◈")} ${y.bold("New workspace detected. Initializing intelligence...")}\n`),await this.runIndexing();const e={firstIndexedAt:(new Date).toISOString(),lastIndexedAt:(new Date).toISOString(),status:"indexed"};await u.writeFile(t,JSON.stringify(e,null,2))}}async runIndexing(){if(!this.backend.indexEverything)return void f.write(y.red("\nIndexing is only available in local mode.\n"));const e=$({text:"Scanning workspace...",color:"cyan"}).start();try{for await(const t of this.backend.indexEverything())e.text=`Indexing [${t.current}/${t.total}] ${y.dim(t.path)}`;e.succeed(y.green("Workspace indexed successfully."))}catch(t){e.fail(y.red(`Indexing failed: ${t.message}`))}}async getWorkspaceIndexStatus(){try{return await this.backend.callTool("workspace.get_index_status",{})}catch{return null}}async runStart(e=[]){const t=e.includes("fix")||e.includes("--fix"),s=e.includes("reindex")||e.includes("--reindex");f.write(this.themeColor(`\n${y.bold("Mesh Start")}\n`)),await this.runDoctor(t?["brief","fix"]:["brief"]);const i=await this.getWorkspaceIndexStatus(),n=Number.parseFloat(String(i?.percent??"0"));s||!Number.isFinite(n)||n<100?await this.runIndexing():f.write(y.green(`Workspace index already fresh enough (${i?.percent??"100"}%).\n`)),await this.printStatus(),await this.printFirstRunRepoSummary()}async printFirstRunRepoSummary(){const e=$({text:"Building first repo briefing...",color:"cyan"}).start();try{const t=await this.backend.callTool("workspace.ask_codebase",{query:"main runtime path architecture entrypoints tests verification",mode:"runtime-path",limit:5});e.succeed(y.cyan("First repo briefing ready."));const s=Array.isArray(t.results)?t.results.slice(0,5):[];0===s.length?f.write(y.yellow("\nNo strong codebase matches yet. Ask a normal repo question or run /index --rebuild after adding files.\n")):f.write(["",y.bold("Best starting points"),...s.map((e,t)=>{const s=e.file??e.path??"unknown",i=a(String(e.purpose??e.snippet??""),110);return`${t+1}. ${y.cyan(s)}${i?y.dim(` - ${i}`):""}`}),""].join("\n"));const i=await this.detectVerificationCommand();f.write([y.bold("Recommended next commands"),`${y.magenta("/change")} fix the smallest failing test or implement a tiny improvement`,`${y.magenta('mesh "explain the main runtime path with citations"')}`,i?`${y.magenta(i)} ${y.dim("(detected verification command)")}`:y.dim("No package verification command detected yet."),""].join("\n"))}catch(t){e.fail(y.red(`First repo briefing failed: ${t.message}`)),f.write(y.dim("You can still ask a normal repo question, for example: explain the main runtime path with citations\n"))}}async detectVerificationCommand(){const e=p.join(this.config.agent.workspaceRoot,"package.json");try{const t=await u.readFile(e,"utf8"),s=JSON.parse(t).scripts??{};return"string"==typeof s.test&&!/no test specified|exit 1/i.test(s.test)?"npm test":"string"==typeof s.typecheck?"npm run typecheck":"string"==typeof s.build?"npm run build":"string"==typeof s.lint?"npm run lint":null}catch{return null}}async distillProjectBrain(){const e=$({text:"Distilling Session into Project Brain...",color:"magenta"}).start();try{const t=this.transcript.map(e=>`${e.role}: ${JSON.stringify(e.content)}`).join("\n").slice(-24e3),s=await this.llm.converse([{role:"user",content:[{text:`Analyze this recent conversation and extract any clear architectural decisions, learned project rules, or strict user preferences (e.g. "use Vanilla CSS", "always use functional components", "use path aliases"). Ignore normal code edits or bug fixes. Output ONLY a valid JSON array of strings, each string being a concise, imperative rule. If absolutely nothing was decided, output [].\n\n<conversation>\n${t}\n</conversation>`}]}],[],"You are a specialized JSON-only extractor.",this.currentModelId);let i=[];try{const e=(s.text||"").match(/\[.*\]/s);i=e?JSON.parse(e[0]):[]}catch{throw new Error("Model did not return a valid JSON array.")}if(Array.isArray(i)&&i.length>0){for(const e of i)await this.backend.callTool("workspace.engineering_memory",{action:"record",outcome:"positive",rule:e,note:"Distilled automatically from session conversation."});e.succeed(y.magenta(`Distilled ${i.length} new rules into Engineering Memory.`))}else e.info(y.dim("No clear new project-wide rules found to distill in this session."))}catch(t){e.fail(y.red(`Distillation failed: ${t.message}`))}}async runSynthesize(){const e=p.join(this.config.agent.workspaceRoot,".mesh","latest_intent.json");try{const t=await u.readFile(e,"utf8");let s;try{s=JSON.parse(t)}catch{return void f.write(y.red("\n[Mesh] Error: Intent file is corrupted. Try /index first to rebuild workspace state.\n"))}f.write(y.cyan(`\n[Predictive Synthesis] Analyzing your recent change: ${s.message}\n`));const i=`You are a Predictive Synthesis orchestrator. I recently modified '${s.file}'.\nThe heuristic engine detected this intent: "${s.message}".\nHere is the git diff:\n${s.diff}\n\nYour task:\n1. Understand the broader architectural implications of this change (e.g., if a DB field was added, it likely needs UI, API, and test updates).\n2. DO NOT write code manually in your response.\n3. Instead, aggressively use 'agent.spawn_swarm' to delegate the updates across the stack in parallel, or use 'workspace.ghost_verify' to implement them safely.\n4. Finish by running 'workspace.finalize_task' to wrap these synthesized changes into a new branch.`;await u.unlink(e).catch(()=>{}),await this.runSingleTurn(i)}catch(e){f.write(y.yellow("\nNo recent structural intent detected by the watcher. Save a file with significant changes first.\n"))}}async runHologram(e){if("start"!==e[0]||!e[1])return void f.write(y.yellow("Usage: /hologram start <command>\nExample: /hologram start npm run dev\n"));const t=e.slice(1).join(" ");f.write(y.cyan(`\n[Live Memory Hologram] Injecting telemetry proxy into '${t}'...\n`)),await this.runSingleTurn(`Execute the command '${t}' using 'workspace.run_with_telemetry'. If the process crashes and you receive a memory dump of the V8 engine, analyze the exact variable states, find the root cause, and fix it using 'workspace.alien_patch' or 'workspace.patch_surgical'.`)}async runEntangle(e){const t=e[0];if(!t)return void f.write(y.yellow("Usage: /entangle <relative-path>\nExample: /entangle ../frontend-repo\n"));const s=p.resolve(this.config.agent.workspaceRoot,t);try{if(!(await u.stat(s)).isDirectory())throw new Error("Not a directory");this.backend.entangledWorkspaces&&this.backend.entangledWorkspaces.push(s),this.entangledWorkspaces.push(s),f.write(y.cyan(`\n[Quantum Entanglement] Workspace '${p.basename(s)}' is now entangled. AST mutations will sync automatically.\n`))}catch{f.write(y.red(`\nFailed to entangle: Directory '${s}' does not exist.\n`))}}async runInspect(e){f.write(y.cyan("\n[Neuro-Kinetic UI] Please open the /dashboard. Mouse movements on the canvas will now be translated to AST edits via the LLM.\n(Note: This requires an active dashboard session).\n"))}async runFrontendPreview(e){const t=e[0]?.trim();if(!t)return void f.write(y.yellow("Usage: /preview <url> [widthxheight] [protocol=auto|kitty|iterm2|sixel|none]\n"));const s=e.find(e=>/^\d+x\d+$/i.test(e)),[i,n]=s?s.toLowerCase().split("x"):["1280","800"],a=e.find(e=>e.startsWith("protocol=")),o=a?.split("=")[1]||"auto",r=this.useAnsi?$({text:"Capturing frontend preview via Chrome CDP...",color:"cyan",stream:f}).start():void 0;try{const e=await this.backend.callTool("frontend.preview",{url:t,width:Number(i),height:Number(n),protocol:o,render:!0},{onProgress:e=>{r&&(r.stop(),r.clear()),f.write(e)}});r&&r.succeed("Frontend preview captured."),f.write(["",`${y.dim("url:")} ${e.url}`,`${y.dim("viewport:")} ${e.width}x${e.height}`,`${y.dim("screenshot:")} ${e.screenshotPath}`,`${y.dim("protocol:")} ${e.protocol}${e.rendered?"":" (not rendered inline)"}`,""].join("\n"))}catch(e){r&&r.fail("Frontend preview failed."),f.write(y.red(`\nPreview failed: ${e.message}\n`))}}async runFix(){const e=this.backend;if(e.speculativeFixes&&e.speculativeFixes.size>0){const t=e.speculativeFixes.entries().next().value,s=t[0],i=t[1];f.write(y.cyan(`\n[🧠 Mesh Resolving] Applying pre-computed fix for '${s}'...\n`));const n=`I have a pre-computed speculative fix for the error in '${s}'.\nPlease review this patch and apply it using 'workspace.alien_patch' if it looks correct:\n${i}\n\nFinish by running 'workspace.finalize_task' with the commit message "Fix linter error in ${s} (Auto-Resolved)".`;e.speculativeFixes.delete(s),await this.runSingleTurn(n)}else f.write(y.yellow("\nNo background fixes currently available. Try introducing an error or running /doctor.\n"))}async runSlashCommandSafe(e,t){const s=$({text:`${e}...`,color:"cyan"}).start();try{await t(s)}catch(t){const i=t instanceof Error?t.message:String(t);let n,a;i.includes("429")||i.includes("rate_limit")||i.includes("ThrottlingException")?(n="LLM rate limit hit",a="Wait a moment, then try again. Run /doctor to check connectivity."):i.includes("LLM request failed")||i.includes("fetch failed")||i.includes("ECONNREFUSED")?(n="LLM backend unavailable",a="Run /doctor to diagnose. Check network connectivity."):i.includes("Context")&&i.includes("firewall")?(n="Context too large for this operation",a="Run /compact first to reduce context size."):i.includes("ENOENT")||i.includes("no such file")?(n="Required file not found",a="Run /index first to initialize workspace state."):i.includes("AbortError")||i.includes("aborted")||i.includes("timed out")?(n="Operation timed out after 60 seconds",a="Try /compact to reduce context, then retry."):(n=i.slice(0,200),a="Run /doctor to diagnose or try /reset if the session is corrupted.");const o=`${e} -> ${i.slice(0,80)}`,r=(this.consecutiveErrors.get(o)||0)+1;this.consecutiveErrors.set(o,r),s.fail(y.red(`[Mesh] Error: ${e} failed — ${n}. Try: ${a}`))}}async runDigitalTwin(e){const t=e[0]||"build",s=$({text:`Digital Twin ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.digital_twin",{action:t});s.succeed(y.cyan(`Digital Twin ${t} complete.`));const i=e.twin??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("files:")} ${i.files?.total??i.files??"n/a"}`,`${y.dim("symbols:")} ${i.symbols?.length??i.symbols??"n/a"}`,`${y.dim("routes:")} ${i.routes?.length??i.routes??"n/a"}`,`${y.dim("risk hotspots:")} ${i.riskHotspots?.length??i.riskHotspots??"n/a"}`,""].join("\n"))}catch(e){s.fail(y.red(`Digital Twin failed: ${e.message}`))}}async runPredictiveRepair(e){const t=e[0]||"analyze",s=$({text:`Predictive Repair ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.predictive_repair",{action:t});s.succeed(y.yellow(`Predictive Repair ${t} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("diagnostics:")} ${e.diagnosticsOk?y.green("clean"):y.red("attention")}`,`${y.dim("queue:")} ${Array.isArray(e.queue)?e.queue.length:0}`,...Array.isArray(e.queue)?e.queue.slice(0,5).map(e=>`${y.yellow("•")} ${e.summary} ${y.dim((e.files??[]).join(", "))}`):[],""].join("\n"))}catch(e){s.fail(y.red(`Predictive Repair failed: ${e.message}`))}}async runDaemon(e){const t=(e[0]||"status").toLowerCase(),s=$({text:`Daemon ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.daemon",{action:t});s.succeed(y.cyan(`Daemon ${t} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.message?[`${y.dim("message:")} ${e.message}`]:[],...e.digest?[`${y.dim("digest:")} ${e.digest}`]:[],...e.state?[`${y.dim("state:")} ${JSON.stringify(e.state,null,2)}`]:[],""].join("\n"))}catch(e){s.fail(y.red(`Daemon command failed: ${e.message}`))}}async runIssuePipeline(e){const t=(e[0]||"scan").toLowerCase(),s=e[1]?.toLowerCase();if(["plan","run","pr","create-pr"].includes(t))return void await this.runIssueAutopilot(e);const i=$({text:`Issue pipeline ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.issue_pipeline",{action:t,provider:s});i.succeed(y.yellow(`Issue pipeline ${t} complete.`)),f.write(["",`${y.dim("queued:")} ${e.queued??0}`,`${y.dim("processed:")} ${(e.processed??[]).length}`,...(e.processed??[]).slice(0,5).map(e=>`${y.yellow("•")} ${e.provider}:${e.issueId} -> ${e.prTitle}`),""].join("\n"))}catch(e){i.fail(y.red(`Issue pipeline failed: ${e.message}`))}}async runIssueAutopilot(e){const t=(e[0]||"status").toLowerCase().replace("-","_"),s=e.slice(1),i=s.join(" ").trim(),n={action:"create_pr"===t?"pr":t};/^https?:\/\//i.test(s[0]??"")?n.issueUrl=s[0]:i&&(n.title=i,n.body=i);const a=$({text:`Issue Autopilot ${n.action}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.issue_autopilot",n);a.succeed(y.yellow(`Issue Autopilot ${e.status??e.action} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.runId?[`${y.dim("run:")} ${e.runId}`]:[],...e.issue?[`${y.dim("issue:")} ${e.issue.provider}:${e.issue.id} ${e.issue.title}`]:[],...e.plan?.branchName?[`${y.dim("branch:")} ${e.plan.branchName}`]:[],...e.plan?.verificationCommand?[`${y.dim("verify:")} ${e.plan.verificationCommand}`]:[],...e.timeline?.id?[`${y.dim("timeline:")} ${e.timeline.id}`]:[],...e.proof?.verdict?[`${y.dim("proof:")} ${e.proof.verdict} ${e.proof.proofId??""}`]:[],...e.pr?.url?[`${y.dim("pr:")} ${e.pr.url}`]:[],...(e.plan?.likelyFiles??[]).slice(0,8).map(e=>`${y.yellow("•")} ${e}`),""].join("\n"))}catch(e){a.fail(y.red(`Issue Autopilot failed: ${e.message}`))}}async runChange(e,t){const i=e.join(" ").trim();if(!i)return f.write(y.yellow("\nUsage: /change <small goal>\n")),void f.write(y.dim("Example: /change fix the failing auth test\n"));const n=await this.detectVerificationCommand(),a=$({text:"Scoping narrow change...",color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.ask_codebase",{query:i,mode:"edit-impact",limit:6}),t=Array.isArray(e.results)?e.results.slice(0,6).map(e=>e.file??e.path).filter(Boolean):[];a.succeed(y.yellow("Change scope prepared.")),t.length>0&&f.write(["",y.bold("Likely files"),...t.map(e=>`${y.yellow("•")} ${e}`),""].join("\n"))}catch(e){a.warn(y.yellow(`Scope lookup skipped: ${e.message}`))}const o=["Execute Mesh /change for this narrow goal:",i,"","Hard constraints:","- Make the smallest safe code change that satisfies the goal.","- Prefer reading indexed/capsule context before raw files.","- Inspect impact before editing shared symbols.","- Do not publish, tag, push, create a PR, or run destructive commands.","- If the change is risky or multi-file, create a timeline first and verify there before touching the main workspace.","- After editing, run the detected verification command if it is available.",n?`- Detected verification command: ${n}`:"- No verification command was detected; explain what verification was skipped and why.","- Finish with exactly: changed files, verification result, residual risk, next action."].join("\n"),r=this.useAnsi?$({text:"Applying narrow change...",color:"cyan",stream:f}).start():void 0;let c=!1;try{this.resetToolSummary();const e=await this.runSingleTurn(o,{onToolStart:(e,t,i,n)=>{r&&(r.text=`${y.dim(`[${i+1}/${n}]`)} ${y.cyan(e)} ${y.dim(s(t))}`),this.renderToolEvent("start",e,s(t))},onToolEnd:(e,t,s)=>{r&&(r.text=t?`done ${y.cyan(e)}`:`failed ${y.cyan(e)}`),this.renderToolEvent(t?"success":"error",e,s)},onCommandChunk:e=>{r&&(r.stop(),r.clear()),f.write(e)},onDelta:e=>{r&&(r.stop(),r.clear()),c||(c=!0,f.write("\n"+this.themeColor(y.bold("change"))+y.dim(" › ")+"\n")),f.write(e)},askPermission:async e=>{r&&r.stop();const t=new _({name:"approve",message:e,initial:!1,stdin:g,stdout:f}),s=Boolean(await t.run().catch(()=>!1));return r&&r.start(),s}});!c&&e?this.renderAssistantTurn(e):c&&f.write("\n"),this.printToolSummary()}catch(e){r?r.fail(y.red(`Change failed: ${e.message}`)):f.write(y.red(`\nChange failed: ${e.message}\n`))}finally{r&&(r.stop(),r.clear())}}async runChatops(e){const t=(e[0]||"investigate").toLowerCase(),s=(e[1]||"slack").toLowerCase(),i=e.slice(2).join(" ").trim(),n=$({text:`ChatOps ${t}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.chatops",{action:t,platform:s,channel:"general",message:i});n.succeed(y.magenta(`ChatOps ${t} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.threadId?[`${y.dim("thread:")} ${e.threadId}`]:[],...e.status?[`${y.dim("status:")} ${e.status}`]:[],...(e.updates??[]).slice(0,4).map(e=>`${y.magenta("•")} ${e}`),...e.prDraft?[`${y.dim("pr draft:")}\n${e.prDraft}`]:[],""].join("\n"))}catch(e){n.fail(y.red(`ChatOps failed: ${e.message}`))}}async runProductionStatus(e){const t=(e[0]||"status").toLowerCase();if(["audit","gate","review","readiness"].includes(t)){const s=e.slice(1).join(" ").trim()||"production readiness",i=$({text:`Production readiness ${t}...`,color:"red"}).start();try{const e=await this.backend.callTool("workspace.production_readiness",{action:"readiness"===t?"audit":t,intent:s});i.succeed(y.red(`Production readiness ${e.status}.`)),f.write(["",`${y.dim("score:")} ${e.score}/100`,`${y.dim("ledger:")} ${e.ledgerPath}`,...(e.dimensions??[]).map(e=>`${"pass"===e.status?y.green("•"):"warn"===e.status?y.yellow("•"):y.red("•")} ${e.title}: ${e.score}/100`),...(e.blockers??[]).slice(0,5).map(e=>`${y.red("blocker:")} ${e}`),""].join("\n"))}catch(e){i.fail(y.red(`Production readiness failed: ${e.message}`))}return}const s=$({text:`Production ${t}...`,color:"red"}).start();try{const e=await this.backend.callTool("workspace.production_status",{action:t});s.succeed(y.red(`Production ${t} complete.`)),f.write(["",`${y.dim("updated:")} ${e.updatedAt??"never"}`,`${y.dim("signals:")} ${e.totalSignals??0}`,...(e.topErrors??[]).slice(0,8).map(e=>`${y.red("•")} ${e.file} req=${e.requestVolume} err=${e.errorRate} p99=${e.p99Ms}ms impact=$${e.revenueImpactDaily}/day`),""].join("\n"))}catch(e){s.fail(y.red(`Production telemetry failed: ${e.message}`))}}async runReplayTrace(e){const t=e[0],s=e[1];if(!t)return void f.write(y.yellow("Usage: /replay <traceId|sentryEventId> [commitRange]\n"));const i=$({text:"Replaying production trace...",color:"cyan"}).start();try{const e=await this.backend.callTool("runtime.replay_trace",{traceId:t,commitRange:s});i.succeed(y.cyan("Trace replay complete.")),f.write(["",`${y.dim("trace:")} ${e.traceId}`,`${y.dim("path:")} ${e.reconstructedRequest?.method} ${e.reconstructedRequest?.path}`,...e.divergence?[`${y.dim("divergence:")} ${e.divergence.span} ${e.divergence.file??""}:${e.divergence.line??""}`]:[],...e.commitAnalysis?[`${y.dim("likely introduced by:")} ${e.commitAnalysis.likelyIntroducedBy}`]:[],""].join("\n"))}catch(e){i.fail(y.red(`Trace replay failed: ${e.message}`))}}async runSymptomBisect(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /bisect <symptom> [verificationCommand]\n"));const s=$({text:"Running symptom bisect...",color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.symptom_bisect",{symptom:t});s.succeed(y.yellow("Symptom bisect complete.")),f.write(["",`${y.dim("symptom:")} ${e.symptom}`,`${y.dim("verification:")} ${e.verificationCommand??"n/a"}`,`${y.dim("culprit:")} ${e.culpritCommit??"undetermined"}`,...e.authorHint?[`${y.dim("author:")} ${e.authorHint}`]:[],...e.message?[e.message]:[],""].join("\n"))}catch(e){s.fail(y.red(`Symptom bisect failed: ${e.message}`))}}async runWhatIf(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /whatif <hypothesis>\n"));const s=$({text:"Running what-if analysis...",color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.what_if",{hypothesis:t});s.succeed(y.magenta("What-if report generated.")),f.write(["",`${y.dim("hypothesis:")} ${e.hypothesis}`,`${y.dim("verdict:")} ${e.verdict}`,`${y.dim("timeline:")} ${e.timelineId}`,`${y.dim("changed files:")} ${(e.changedFiles??[]).length}`,`${y.dim("changed lines:")} ${e.changedLineCount??0}`,`${y.dim("type errors:")} ${e.typeErrorsEstimate??0}`,`${y.dim("tests broken:")} ${e.testsBrokenEstimate??0}`,`${y.dim("bundle delta:")} ${e.bundleSizeDeltaKb??0} KB`,`${y.dim("note:")} ${e.note??""}`,""].join("\n"))}catch(e){s.fail(y.red(`What-if failed: ${e.message}`))}}async runAudit(e){const t=(e[0]||"verify").toLowerCase(),s=$({text:`Audit ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.audit",{action:t});if(s.succeed(y.yellow(`Audit ${t} complete.`)),"replay"===t)return void f.write(["",`${y.dim("entries:")} ${(e.entries??[]).length}`,...(e.entries??[]).slice(0,5).map(e=>`${y.yellow("•")} ${e.ts} ${e.tool}`),""].join("\n"));f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,`${y.dim("total:")} ${e.total??0}`,`${y.dim("invalid:")} ${e.invalid??0}`,""].join("\n"))}catch(e){s.fail(y.red(`Audit command failed: ${e.message}`))}}async runMeshBrain(e){const t=(e[0]||"stats").replace("-","_"),s=$({text:`Mesh Brain ${t}...`,color:"blue"}).start();try{if("query"===t){const i=e.slice(1).join(" ").trim();if(!i)return s.stop(),void f.write(y.yellow("Usage: /brain query <error signature>\n"));const n=await this.backend.callTool("workspace.brain",{action:t,error:i,limit:5});return s.succeed(y.blue("Mesh Brain query complete.")),void f.write(["",`${y.dim("source:")} ${n.source??"unknown"}`,`${y.dim("patterns:")} ${(n.patterns??[]).length}`,...(n.patterns??[]).slice(0,5).map(e=>`${y.blue("•")} score=${Number(e.score??0).toFixed(2)} usage=${e.usageCount??0} ${e.fixSummary??"Pattern match"}`),""].join("\n"))}if("opt_out"===t)return await this.backend.callTool("workspace.brain",{action:t}),s.succeed(y.blue("Mesh Brain contributions disabled.")),void f.write(y.dim("You can still query global patterns; local contributions are now off.\n"));const i=await this.backend.callTool("workspace.brain",{action:"stats"});s.succeed(y.blue("Mesh Brain stats loaded.")),f.write(["",`${y.dim("contribute:")} ${i.telemetryContribute?y.green("enabled"):y.red("disabled")}`,`${y.dim("endpoint:")} ${i.endpoint??"local-only"}`,`${y.dim("contributions:")} ${i.contributions??0}`,`${y.dim("last contribution:")} ${i.lastContributionAt??"never"}`,""].join("\n"))}catch(e){s.fail(y.red(`Mesh Brain failed: ${e.message}`))}}async runCompanyBrain(e){const t=(e[0]||"status").toLowerCase().replace("-","_"),s=e.slice(1).join(" ").trim(),i={action:t};["query","ask","search"].includes(t)&&(i.query=s),["record","ingest"].includes(t)&&(i.kind="ingest"===t?"lesson":"decision",i.title=s.slice(0,160),i.body=s);const n=$({text:`Company Brain ${t}...`,color:"blue"}).start();try{const e=await this.backend.callTool("workspace.company_brain",i);if(n.succeed(y.blue(`Company Brain ${e.status??e.action} complete.`)),e.citations)return void f.write(["",`${y.dim("query:")} ${e.query}`,`${y.dim("answer:")} ${e.answer}`,...(e.citations??[]).slice(0,8).map(e=>`${y.blue("•")} ${e.file??e.title} ${e.lineStart?`L${e.lineStart}`:""} score=${e.score}`),""].join("\n"));f.write(["",`${y.dim("path:")} ${e.path??e.summaryPath??"n/a"}`,...e.summaryPath?[`${y.dim("summary:")} ${e.summaryPath}`]:[],...void 0!==e.files?[`${y.dim("files:")} ${e.files}`]:[],...void 0!==e.documents?[`${y.dim("documents:")} ${e.documents}`]:[],...void 0!==e.rules?[`${y.dim("rules:")} ${e.rules}`]:[],...void 0!==e.decisions?[`${y.dim("decisions:")} ${e.decisions}`]:[],...(e.domains??[]).slice(0,8).map(e=>`${y.blue("•")} ${e.name}: ${e.files} files, ${e.risks} risks`),""].join("\n"))}catch(e){n.fail(y.red(`Company Brain failed: ${e.message}`))}}async runEngineeringMemory(e){const t=e[0]||"read",s=$({text:`Engineering Memory ${t}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.engineering_memory",{action:t});s.succeed(y.magenta(`Engineering Memory ${t} complete.`));const i=e.memory??{};f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("rules:")} ${(i.rules??[]).length}`,`${y.dim("risk modules:")} ${(i.riskModules??[]).length}`,...(i.rules??[]).slice(0,6).map(e=>`${y.magenta("•")} ${e}`),""].join("\n"))}catch(e){s.fail(y.red(`Engineering Memory failed: ${e.message}`))}}async runIntentCompile(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /intent <product intent>\n"));const s=$({text:"Compiling intent...",color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.intent_compile",{intent:t});s.succeed(y.cyan("Intent compiled."));const i=e.contract;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("likely files:")} ${i.likelyFiles.join(", ")||"none"}`,`${y.dim("verification:")} ${i.rollout.verificationCommand}`,...i.phases.map((e,t)=>`${y.cyan(`${t+1}.`)} ${e}`),""].join("\n"))}catch(e){s.fail(y.red(`Intent compile failed: ${e.message}`))}}async runCausalIntelligence(e){const t=e[0]||"build",s="query"===t?e.slice(1).join(" ").trim():"";if("query"===t&&!s)return void f.write(y.yellow("Usage: /causal query <question>\n"));const i=$({text:`Causal Intelligence ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.causal_intelligence",{action:t,query:s});if(i.succeed(y.cyan(`Causal Intelligence ${t} complete.`)),"query"===t)return void f.write(["",`${y.dim("answer:")} ${e.answer}`,...(e.topInsights??[]).slice(0,5).map(e=>`${y.cyan("•")} ${e.severity} ${e.title}`),""].join("\n"));const n=e.graph??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("nodes:")} ${n.nodes?.length??n.nodes??"n/a"}`,`${y.dim("edges:")} ${n.edges?.length??n.edges??"n/a"}`,`${y.dim("insights:")} ${n.insights?.length??n.insights??"n/a"}`,...(n.insights??[]).slice(0,5).map(e=>`${y.cyan("•")} ${e.severity} ${e.title}`),""].join("\n"))}catch(e){i.fail(y.red(`Causal Intelligence failed: ${e.message}`))}}async runDiscoveryLab(e){const t=e[0]||"run",s=$({text:`Discovery Lab ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.discovery_lab",{action:t});s.succeed(y.yellow(`Discovery Lab ${t} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("discoveries:")} ${Array.isArray(e.discoveries)?e.discoveries.length:0}`,...(e.discoveries??[]).slice(0,6).map(e=>`${y.yellow("•")} ${e.severity} ${e.hypothesis}`),""].join("\n"))}catch(e){s.fail(y.red(`Discovery Lab failed: ${e.message}`))}}async runRealityFork(e){const t=new Set(["plan","fork","status","clear"]),s=e[0]||"plan",i=t.has(s)?s:"plan",n=t.has(s)?e.slice(1).join(" ").trim():e.join(" ").trim();if(("plan"===i||"fork"===i)&&!n)return void f.write(y.yellow("Usage: /fork [plan|fork] <intent>\n"));const a=$({text:`Reality Fork ${i}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.reality_fork",{action:i,intent:n});a.succeed(y.magenta(`Reality Fork ${i} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("intent:")} ${e.intent??"n/a"}`,`${y.dim("proposals:")} ${Array.isArray(e.proposals)?e.proposals.length:e.proposals??0}`,...(e.proposals??[]).slice(0,5).map(e=>{const t=e.timelineId?y.dim(` timeline=${e.timelineId}`):"";return`${y.magenta("•")} ${e.score} ${e.strategy}${t}`}),""].join("\n"))}catch(e){a.fail(y.red(`Reality Fork failed: ${e.message}`))}}async runGhostEngineer(e){const t=new Set(["learn","profile","status","predict","divergence","patch","clear"]),s=e[0]||"profile",i=t.has(s)?s:"predict",n=t.has(s)?e.slice(1).join(" ").trim():e.join(" ").trim();if(("predict"===i||"patch"===i)&&!n)return void f.write(y.yellow("Usage: /ghost predict <goal> or /ghost patch <goal>\n"));if("divergence"===i&&!n)return void f.write(y.yellow("Usage: /ghost divergence <plan>\n"));const a=$({text:`Ghost Engineer ${i}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.ghost_engineer",{action:i,goal:"predict"===i||"patch"===i?n:void 0,plan:"divergence"===i?n:void 0});if(a.succeed(y.cyan(`Ghost Engineer ${i} complete.`)),"predict"===i){const t=e.prediction;return void f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("prediction:")} ${t.prediction}`,`${y.dim("verification:")} ${t.predictedApproach.verificationCommand}`,`${y.dim("alignment:")} ${t.divergence.verdict} / ${t.divergence.alignmentScore}`,...t.predictedApproach.firstReads.slice(0,6).map(e=>`${y.cyan("•")} read ${e}`),""].join("\n"))}if("divergence"===i){const t=e.divergence;return void f.write(["",`${y.dim("alignment:")} ${t.verdict} / ${t.alignmentScore}`,...(t.warnings??[]).map(e=>`${y.yellow("•")} ${e.severity} ${e.message}`),""].join("\n"))}if("patch"===i)return void f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("timeline:")} ${e.timelineId}`,`${y.dim("verification:")} ${e.autopilot.predictedApproach.verificationCommand}`,...e.autopilot.autopilotPatch.suggestedPatchOrder.slice(0,5).map(e=>`${y.cyan("•")} ${e}`),""].join("\n"));const t=e.profile??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("learned:")} ${t.learnedAt??"n/a"}`,`${y.dim("confidence:")} ${t.confidence??"n/a"}`,`${y.dim("patch shape:")} ${t.habits?.patchShape??"n/a"}`,...(t.habits?.firstReadFiles??[]).slice(0,6).map(e=>`${y.cyan("•")} ${e}`),""].join("\n"))}catch(e){a.fail(y.red(`Ghost Engineer failed: ${e.message}`))}}async runTribunal(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /tribunal <problem or engineering decision to adjudicate>\n"));const s=$({text:"Convening tribunal (3 panelists deliberating in parallel)...",color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.tribunal",{action:"convene",problem:t});if(!e.ok)return void s.fail(y.red(`Tribunal failed: ${e.reason??"unknown error"}`));s.succeed(y.magenta(`Tribunal complete — verdict: ${e.synthesis?.verdict??"n/a"}`));const i=e.synthesis;f.write(["",`${y.dim("winner:")} ${i.winningPanelistId} (score ${i.scores?.[i.winningPanelistId]??"?"})`,`${y.dim("verdict:")} ${i.verdict}`,"",`${y.magenta("▶ Dominant Solution:")}`,i.dominantSolution,"",`${y.dim("rationale:")} ${i.rationale}`,...i.incorporated?.length>0?[`${y.dim("incorporated:")} ${i.incorporated.slice(0,3).join(" | ")}`]:[],...i.dissent?[`${y.dim("dissent:")} ${i.dissent}`]:[],`${y.dim("artifact:")} ${e.decisionArtifactPath}`,""].join("\n"))}catch(e){s.fail(y.red(`Tribunal failed: ${e.message}`))}}async runSessionResurrection(e){const t=e[0]?.toLowerCase()??"resurrect",s=e.slice(1);if("capture"===t)return f.write(y.cyan('\nTo capture your session state, ask the agent:\n "capture my session state" or use workspace.session_resurrection directly\n The agent will extract your intent, open questions, and next actions.\n\n')),void f.write(y.dim("Tip: The agent uses workspace.session_resurrection action=capture with your context.\n\n"));if("checkpoint"===t){const e=s.join(" ").trim();if(!e)return void f.write(y.yellow("Usage: /resurrect checkpoint <note>\n"));const t=$({text:"Saving checkpoint...",color:"cyan"}).start();try{const s=await this.backend.callTool("workspace.session_resurrection",{action:"checkpoint",note:e});t.succeed(y.cyan(`Checkpoint saved (${s.totalCheckpoints} total)`))}catch(e){t.fail(y.red(`Checkpoint failed: ${e.message}`))}return}if("status"===t){const e=$({text:"Reading session state...",color:"cyan"}).start();try{const t=await this.backend.callTool("workspace.session_resurrection",{action:"status"});e.succeed(y.cyan("Session resurrection status")),t.exists?f.write(["",`${y.dim("session:")} ${t.sessionId}`,`${y.dim("captured:")} ${t.capturedAt} (${t.age} ago)`,`${y.dim("intent:")} ${t.intent}`,`${y.dim("questions:")} ${t.openQuestionsCount} ${y.dim("next-actions:")} ${t.nextActionsCount} ${y.dim("checkpoints:")} ${t.checkpointsCount}`,""].join("\n")):f.write(y.dim("\nNo captured session.\n\n"))}catch(t){e.fail(y.red(`Status failed: ${t.message}`))}return}if("clear"===t){const e=$({text:"Clearing session state...",color:"cyan"}).start();try{await this.backend.callTool("workspace.session_resurrection",{action:"clear"}),e.succeed(y.cyan("Session resurrection state cleared."))}catch(t){e.fail(y.red(`Clear failed: ${t.message}`))}return}const i=$({text:"Reconstructing session state...",color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.session_resurrection",{action:"resurrect"});i.succeed(y.cyan("Session resurrected.")),e.exists||e.snapshot?f.write("\n"+e.brief+"\n\n"):f.write(y.dim("\nNo previous session to resurrect. Work on something then run /resurrect capture.\n\n"))}catch(e){i.fail(y.red(`Resurrection failed: ${e.message}`))}}async runSemanticSheriff(e){const t=new Set(["scan","verify","lock","unlock","drift","status","clear"]),s=e[0]?.toLowerCase()??"verify",i=t.has(s)?s:"verify",n="lock"===i||"unlock"===i||"verify"===i?e[1]?.trim():void 0;if(("lock"===i||"unlock"===i)&&!n)return void f.write(y.yellow(`Usage: /sheriff ${i} <file>\n`));const a=$({text:"scan"===i?"Scanning and fingerprinting codebase...":"verify"===i?"Verifying semantic contracts...":"lock"===i?`Locking contract for ${n}...`:"drift"===i?"Loading drift report...":`Sheriff ${i}...`,color:"yellow"}).start();try{const e={action:i};n&&(e.file=n);const t=await this.backend.callTool("workspace.semantic_sheriff",e);if(a.succeed(y.yellow(`Sheriff ${i} complete.`)),"scan"===i)return void f.write(["",`${y.dim("scanned:")} ${t.scanned} ${y.dim("updated:")} ${t.updated} ${y.dim("total:")} ${t.totalContracts}`,`${y.dim("path:")} ${t.path}`,""].join("\n"));if("verify"===i||"drift"===i){const e=t.driftAlerts??[];return void f.write(["",`${y.dim("contracts:")} ${t.contracts} ${y.dim("locked:")} ${t.lockedContracts}`,`${y.dim("summary:")} ${t.summary}`,...e.slice(0,8).map(e=>{const t="critical"===e.severity?y.red:"high"===e.severity?y.yellow:y.dim,s=[...e.changes.removedExports.length>0?[`-exports: ${e.changes.removedExports.join(", ")}`]:[],...e.changes.addedExports.length>0?[`+exports: ${e.changes.addedExports.join(", ")}`]:[],...e.changes.purposeShift?["purpose shifted"]:[],...e.changes.behavioralShift?["behavioral patterns changed"]:[]].join("; ");return t(` ${e.severity.toUpperCase()} ${e.file} — ${s}`)}),""].join("\n"))}if("lock"===i)return void f.write(["",`${y.yellow("⬡")} ${t.file} locked`,`${y.dim("fingerprint:")} ${t.fingerprint}`,`${y.dim("message:")} ${t.message}`,""].join("\n"));f.write(`\n${y.dim(t.message??JSON.stringify(t))}\n\n`)}catch(e){a.fail(y.red(`Sheriff ${i} failed: ${e.message}`))}}async launchDashboard(){const e=$({text:"Starting dashboard...",color:"cyan"}).start();try{const t=this.getDashboardDir();await u.mkdir(t,{recursive:!0}),await this.appendDashboardEvent({id:`${Date.now()}-dashboard-open`,type:"dashboard",msg:"Dashboard opened",at:(new Date).toISOString()});const s=await this.readDashboardServerInfo();let i=s?.port;this.dashboardToken&&i&&"react-live-dashboard-v1"===s?.version&&await this.isDashboardReachable(i)||(this.dashboardToken=C.randomBytes(32).toString("hex"),i=await this.startDashboardServer(t,this.dashboardToken));const n=`http://127.0.0.1:${i}/#token=${this.dashboardToken}`;this.openDashboardUrl(n),e.succeed(y.green(`Dashboard live at http://127.0.0.1:${i}`))}catch(t){e.fail(y.red(`Interface initialization failed: ${t.message}`))}}getDashboardDir(){return p.join(this.config.agent.workspaceRoot,".mesh","dashboard")}getDashboardEventsPath(){return p.join(this.getDashboardDir(),"events.json")}getDashboardContextMetricsPath(){return p.join(this.getDashboardDir(),"context-metrics.json")}getDashboardServerInfoPath(){return p.join(this.getDashboardDir(),"server.json")}async writeContextMetrics(e,t){const s=this.getDashboardContextMetricsPath(),i={updatedAt:(new Date).toISOString(),report:e,rawCharsStored:this.turnArtifactCharsStored,envelopeCharsSent:this.turnArtifactEnvelopeChars,rawCharsSaved:t,rawTokensSavedEstimate:Math.ceil(Math.max(0,t)/4),toolCalls:this.turnToolCalls,toolErrors:this.turnToolErrors};await u.mkdir(p.dirname(s),{recursive:!0}),await u.writeFile(s,JSON.stringify(i,null,2),"utf8")}async appendDashboardEvent(e){const t=this.getDashboardEventsPath();await u.mkdir(p.dirname(t),{recursive:!0});const s=await u.readFile(t,"utf8").catch(()=>"[]");let i=[];try{i=JSON.parse(s)}catch{i=[]}i.unshift(e),await u.writeFile(t,JSON.stringify(i.slice(0,200),null,2),"utf8")}async readDashboardServerInfo(){const e=await u.readFile(this.getDashboardServerInfoPath(),"utf8").catch(()=>"");if(!e)return null;try{const t=JSON.parse(e);return Number.isFinite(t.port)?{port:Number(t.port),pid:t.pid,version:t.version}:null}catch{return null}}async isDashboardReachable(e){return await new Promise(t=>{const s=b.get({host:"127.0.0.1",port:e,path:"/health",timeout:700},e=>{e.resume(),t(200===e.statusCode)});s.on("error",()=>t(!1)),s.on("timeout",()=>{s.destroy(),t(!1)})})}async startDashboardServer(e,t){x(process.execPath,[p.join(p.dirname(w(import.meta.url)),"dashboard-server.js"),this.config.agent.workspaceRoot],{detached:!0,stdio:"ignore",env:{...process.env,MESH_DASHBOARD_TOKEN:t}}).unref();this.getDashboardServerInfoPath();for(let e=0;e<40;e++){await new Promise(e=>setTimeout(e,100));const e=await this.readDashboardServerInfo();if(e?.port&&await this.isDashboardReachable(e.port))return e.port}throw new Error(`Dashboard server did not start. Expected info at ${p.join(e,"server.json")}`)}openDashboardUrl(e){const t="darwin"===process.platform?{bin:"open",args:[e]}:"win32"===process.platform?{bin:"cmd",args:["/c","start","",e]}:{bin:"xdg-open",args:[e]};x(t.bin,t.args,{detached:!0,stdio:"ignore"}).unref()}printCost(){const e=this.sessionTokens.inputTokens,t=this.sessionTokens.outputTokens,s=Y.find(e=>this.currentModelId.includes(e.value)||e.value.includes(this.currentModelId)),{inputPer1k:i,outputPer1k:n}=s?.pricing??{inputPer1k:.003,outputPer1k:.015},a=e*i/1e3+t*n/1e3;f.write(["",`${y.dim("session usage:")} ${this.themeColor(e.toLocaleString())} ${y.dim("input /")} ${this.themeColor(t.toLocaleString())} ${y.dim("output tokens")}`,`${y.dim("session cost:")} ${y.green("$"+a.toFixed(4))}`,""].join("\n"))}setupGhostText(e,t,s){if(!this.useAnsi)return;this.ghostTextListener&&t.removeListener("keypress",this.ghostTextListener);let i="",n=!1;this.ghostTextListener=(t,a)=>{if(this.useAnsi&&a){if(a.ctrl&&"o"===a.name)return this.toolEventsExpanded=!this.toolEventsExpanded,void s.write(y.dim(`\ntool output: ${this.toolEventsExpanded?"expanded":"collapsed"}\n`));if("return"!==a.name&&"enter"!==a.name){if(!n){if(("tab"===a.name||"right"===a.name&&i)&&i){const t=i;i="",n=!0;const s=e;return"function"==typeof s._refreshLine?(s.line=(s.line||"")+t,s.cursor=s.line.length,s._refreshLine()):e.write(t),void setTimeout(()=>{n=!1},20)}setTimeout(()=>{if(n)return;const t=e.line||"";if(t.startsWith("/")&&!t.includes(" ")){const e=this.getSlashCommands().flatMap(e=>[e.name,...e.aliases||[]]).find(e=>e.startsWith(t)&&e!==t);if(e){const n=e.slice(t.length);n!==i&&(i&&s.write(" ".repeat(i.length)+"["+i.length+"D"),s.write(y.dim(n)+"["+n.length+"D"),i=n)}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")},5)}}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")}},t.on("keypress",this.ghostTextListener)}renderUserTurn(e){const t=this.useAnsi?y.bold(y.white("you")):"you";f.write(`\n${t}> ${e}\n`)}renderAssistantTurn(e){const t=this.sanitizeLlmOutput(e),s=S.parse(t);this.useAnsi?f.write("\n"+this.themeColor(y.bold("assistant"))+y.dim(" › ")+"\n"+s+"\n"):f.write(`\nassistant> ${t}\n`)}sanitizeLlmOutput(e){return sanitizeLlmOutput(e)}renderSystemMessage(e){const t=this.useAnsi?y.yellow("system>"):"system>";f.write(`\n${t} ${e}\n`)}renderToolEvent(e,t,s){if(this.lastToolEventAt=(new Date).toISOString(),"start"===e?(this.turnToolCalls+=1,this.turnToolNames.set(t,(this.turnToolNames.get(t)??0)+1)):"error"===e&&(this.turnToolErrors+=1),!this.toolEventsExpanded&&"error"!==e)return;const i="start"===e?y.dim("tool>"):"success"===e?y.green("tool<"):y.red("tool<");f.write(`\n${i} ${y.cyan(t)}${s?` ${y.dim(s)}`:""}\n`)}resetToolSummary(){this.turnToolCalls=0,this.turnToolErrors=0,this.turnToolNames.clear(),this.turnArtifactCharsStored=0,this.turnArtifactEnvelopeChars=0,this.turnContextReports=[],this.lastContextReport=null}printToolSummary(){if(this.turnToolCalls>0){const e=Array.from(this.turnToolNames.entries()).sort((e,t)=>t[1]-e[1]).slice(0,4).map(([e,t])=>`${e}${t>1?` x${t}`:""}`).join(", "),t=this.toolEventsExpanded?"expanded":"collapsed",s=this.turnToolErrors>0?` · ${this.turnToolErrors} errors`:"";f.write(y.dim(`\ntools: ${this.turnToolCalls} calls · ${e}${s} · ${t} (Ctrl+O)`))}const e=this.peakContextReport();if(e){const t=Math.max(0,this.turnArtifactCharsStored-this.turnArtifactEnvelopeChars);this.sessionRawSaved+=t,this.writeContextMetrics(e,t)}(this.turnToolCalls>0||e)&&f.write("\n")}peakContextReport(){return 0===this.turnContextReports.length?this.lastContextReport:[...this.turnContextReports].sort((e,t)=>t.totalTokens-e.totalTokens)[0]??null}printHelp(e=[]){const t=this.getSlashCommands(),s=e.includes("--all")||e.includes("advanced"),i=e[0]?.toLowerCase().replace(/^([^/])/,"/$1");if(i&&!["/all","advanced"].includes(i)){const e=t.find(e=>e.name===i||e.aliases?.includes(i));if(!e)return void f.write(y.yellow(`\nNo command named ${i}. Run /help for the command groups.\n`));const s=this.commandExamples(e.name);return void f.write(["",`${y.magenta(y.bold(e.name))}${e.aliases?.length?y.dim(` (${e.aliases.join(", ")})`):""}`,`${y.dim("what:")} ${e.description}`,`${y.dim("usage:")} ${e.usage}`,...s.length?[`${y.dim("examples:")}`,...s.map(e=>` ${e}`)]:[],""].join("\n"))}const n=new Map(t.map(e=>[e.name,e]));f.write(["",`${this.themeColor(y.bold("Mesh CLI - Private Alpha"))}`,`${y.dim("Run /help <command> for examples. Most things work as plain questions — slash commands are shortcuts.")}`,s?"":y.dim("Showing core commands. Run /help --all to see all groups."),"",...[{title:"Getting Started",names:["/start","/status","/index","/doctor"]},{title:"Making Changes",names:["/change","/intent","/autopilot","/issues","/fix","/ghost","/fork"]},{title:"Understand the Codebase",names:["/causal","/brain","/company","/learn","/lab","/twin","/distill","/synthesize","/repair"],advanced:!0},{title:"Quality & Safety",names:["/audit","/production","/sheriff","/tribunal","/bisect","/replay","/whatif"],advanced:!0},{title:"Session",names:["/model","/setup","/compact","/capsule","/cost","/undo","/approvals","/steps","/clear","/exit"]},{title:"Tools & Integrations",names:["/dashboard","/inspect","/stop-inspect","/preview","/hologram","/entangle","/chatops","/daemon","/sync","/voice","/resurrect"],advanced:!0}].flatMap(e=>e.advanced&&!s?[]:[this.themeColor(y.bold(e.title)),...e.names.map(e=>n.get(e)).filter(e=>Boolean(e)).map(e=>`${y.magenta(e.name.padEnd(15," "))}${e.description}`),""])].join("\n")+"\n")}commandExamples(e){return{"/start":["/start","/start fix","/start reindex"],"/status":["/status"],"/index":["/index"],"/dashboard":["/dashboard"],"/twin":["/twin","/twin status"],"/repair":["/repair","/repair status","/repair clear"],"/company":["/company build","/company query auth flow","/company record API clients must validate env tokens"],"/autopilot":["/autopilot plan https://github.com/org/repo/issues/123","/autopilot run fix the failing auth test","/autopilot pr https://github.com/org/repo/issues/123"],"/change":["/change fix the failing auth test","/change add validation for empty project names"],"/causal":["/causal","/causal query why is auth risky?"],"/lab":["/lab","/lab status"],"/inspect":["/inspect","/inspect http://localhost:5173"],"/preview":["/preview http://localhost:5173 1280x800"],"/model":["/model list","/model sonnet4.6","/model save"],"/capsule":["/capsule show","/capsule stats","/capsule clear"],"/ghost":["/ghost learn","/ghost predict add billing settings"],"/fork":["/fork plan migrate dashboard to React"],"/sheriff":["/sheriff scan","/sheriff verify"],"/doctor":["/doctor","/doctor fix","/doctor full","/doctor voice"]}[e]??[this.getSlashCommands().find(t=>t.name===e)?.usage??e]}getSlashCommands(){return[{name:"/help",aliases:["/commands"],usage:"/help [command]",description:"show command groups and examples"},{name:"/start",usage:"/start [fix|reindex]",description:"onboarding golden path: doctor + index + status + repo briefing"},{name:"/status",usage:"/status",description:"show runtime, session, and index state"},{name:"/index",usage:"/index",description:"re-index workspace and generate file capsules"},{name:"/doctor",usage:"/doctor [brief|full|fix|voice [fix]]",description:"run diagnostics and optional auto-fixes"},{name:"/change",usage:"/change <goal>",description:"make a focused code change, run verification, summarize the diff"},{name:"/intent",usage:"/intent <product intent>",description:"compile a product intent into a phased implementation contract"},{name:"/autopilot",usage:"/autopilot [status|plan|run|pr] <issueUrl|title>",description:"turn an issue into a verified patch with proof bundle and optional PR"},{name:"/issues",usage:"/issues [scan|status] [provider]",description:"scan and run GitHub/Linear/Jira issues through the PR pipeline"},{name:"/fix",usage:"/fix",description:"apply a background-resolved fix for a current linter/compiler error"},{name:"/ghost",usage:"/ghost [learn|profile|predict|divergence|patch] <input>",description:"learn your implementation style and predict how you would write new code"},{name:"/fork",usage:"/fork [plan|fork|status|clear] <intent>",description:"plan and run two competing implementations in isolated branches, compare results"},{name:"/causal",usage:"/causal [build|read|status|query <question>]",description:"build a causal dependency graph of the codebase and query it"},{name:"/brain",usage:"/brain [stats|query <error>|opt-out]",description:"query Mesh Brain for known fix patterns across all workspaces"},{name:"/company",aliases:["/company-brain"],usage:"/company [build|status|query <question>|record <decision>]",description:"build and query a durable memory of architectural decisions and ownership"},{name:"/learn",usage:"/learn [read|learn]",description:"read or refresh the Engineering Memory (coding rules, risk modules)"},{name:"/lab",usage:"/lab [run|status|clear]",description:"run autonomous hypothesis generation to surface hidden bugs and patterns"},{name:"/twin",usage:"/twin [build|read|status]",description:"build a structural model of the codebase for deep cross-file analysis"},{name:"/distill",usage:"/distill",description:"analyze recent changes and update the project brain context"},{name:"/synthesize",usage:"/synthesize",description:"detect structural intent in the last save and auto-propagate changes across the stack"},{name:"/repair",usage:"/repair [analyze|status|clear]",description:"inspect the predictive repair queue for fragile areas near recent changes"},{name:"/audit",usage:"/audit [verify|replay]",description:"verify or replay the audit trail for enterprise compliance"},{name:"/production",usage:"/production [refresh|status|audit|gate|review] [intent]",description:"show production telemetry or run the readiness gate before shipping"},{name:"/sheriff",usage:"/sheriff [scan|verify|lock <file>|drift|status|clear]",description:"fingerprint module semantics and alert when a refactor silently changes behavior"},{name:"/tribunal",usage:"/tribunal <problem>",description:"debate a hard engineering decision across 3 AI perspectives: correctness, performance, resilience"},{name:"/bisect",usage:"/bisect <symptom> [verificationCommand]",description:"autonomous git bisect to find the commit that introduced a symptom"},{name:"/replay",usage:"/replay <traceId|sentryEventId> [commitRange]",description:"replay a production trace locally and find where behavior diverges"},{name:"/whatif",usage:"/whatif <hypothesis>",description:"run a counterfactual analysis of a migration or refactor in an isolated timeline"},{name:"/model",usage:"/model [pick|list|id|save]",description:"switch or save the active model"},{name:"/setup",usage:"/setup [noninteractive key=value ...]",description:"interactive or scripted settings wizard"},{name:"/compact",usage:"/compact",description:"compress transcript into a session capsule to free context"},{name:"/capsule",aliases:["/memory"],usage:"/capsule [show|compact|clear|export [path]|stats|path]",description:"inspect or manage session capsule"},{name:"/cost",usage:"/cost",description:"show token usage and estimated cost for this session"},{name:"/undo",usage:"/undo",description:"revert the last file change made by the agent"},{name:"/approvals",usage:"/approvals [status|on|off]",description:"control tool auto-approval mode"},{name:"/steps",usage:"/steps [<n>|reset]",description:"set max tool steps for this session"},{name:"/clear",usage:"/clear",description:"clear the terminal"},{name:"/exit",aliases:["/quit"],usage:"/exit",description:"quit"},{name:"/dashboard",usage:"/dashboard",description:"open the local repo operations dashboard in the browser"},{name:"/inspect",usage:"/inspect [url]",description:"attach a visual inspector to a local dev server — Alt+Click elements to describe changes"},{name:"/stop-inspect",usage:"/stop-inspect",description:"detach the visual inspector"},{name:"/preview",usage:"/preview <url> [widthxheight] [protocol]",description:"render a frontend screenshot in the terminal via Chrome CDP"},{name:"/hologram",usage:"/hologram start <cmd>",description:"run a process with V8 memory telemetry — if it crashes, get the exact variable states"},{name:"/entangle",usage:"/entangle <path>",description:"link a second repository so the agent can read and cross-reference both workspaces"},{name:"/chatops",usage:"/chatops [investigate|approve|status] [platform] [message|threadId]",description:"run a Slack/Discord investigation or approval flow from the terminal"},{name:"/daemon",usage:"/daemon [start|status|digest|stop]",description:"control the Mesh background daemon"},{name:"/sync",usage:"/sync",description:"check cloud cache synchronization status"},{name:"/voice",usage:"/voice [on|off|setup]",description:"toggle or configure Speech-to-Speech mode"},{name:"/resurrect",usage:"/resurrect [capture|checkpoint <note>|status|clear]",description:"capture session intent and restore full context in a future session"}]}async handleSlashCommand(e,t){const s=e.trim();if(!s.startsWith("/"))return{wasHandled:!1,shouldExit:!1};const[i,...n]=s.split(/\s+/g),a=i.toLowerCase(),o=["/help","/start","/status","/index","/dashboard","/sync","/setup","/clear","/model","/cost","/compact","/capsule","/memory","/approvals","/steps","/undo","/doctor","/exit","/quit","/reset","/debug","/commands","/voice","/distill","/synthesize","/company","/company-brain","/twin","/repair","/daemon","/issues","/autopilot","/change","/chatops","/production","/replay","/bisect","/whatif","/audit","/brain","/learn","/intent","/causal","/lab","/fork","/ghost","/hologram","/entangle","/inspect","/stop-inspect","/preview","/fix","/tribunal","/resurrect","/sheriff"];let r=a;if(o.includes(a))r=a;else{const e=o.filter(e=>e.startsWith(a));e.length>0&&(r=e[0])}try{switch(r){case"/undo":{const e=$({text:"Undoing last change...",color:"yellow"}).start();try{const t=await this.backend.callTool("workspace.undo",{});t.ok?e.succeed(y.green(t.message)):e.fail(y.red(t.error))}catch(t){e.fail(y.red(`Undo failed: ${t.message}`))}return{wasHandled:!0,shouldExit:!1}}case"/inspect":{const e=n[0]||"http://localhost:3000";return await this.handleInspect(e),{wasHandled:!0,shouldExit:!1}}case"/stop-inspect":return await this.portal.stop(),f.write(y.green("\n[Mesh Portal] Browser detached and overlay removed.\n")),{wasHandled:!0,shouldExit:!1};case"/help":case"/commands":return this.printHelp(n),{wasHandled:!0,shouldExit:!1};case"/start":return await this.runStart(n),{wasHandled:!0,shouldExit:!1};case"/status":return await this.printStatus(),{wasHandled:!0,shouldExit:!1};case"/index":return await this.runIndexing(),{wasHandled:!0,shouldExit:!1};case"/distill":return await this.distillProjectBrain(),{wasHandled:!0,shouldExit:!1};case"/synthesize":return await this.runSynthesize(),{wasHandled:!0,shouldExit:!1};case"/company":case"/company-brain":return await this.runCompanyBrain(n),{wasHandled:!0,shouldExit:!1};case"/twin":return await this.runDigitalTwin(n),{wasHandled:!0,shouldExit:!1};case"/repair":return await this.runPredictiveRepair(n),{wasHandled:!0,shouldExit:!1};case"/daemon":return await this.runDaemon(n),{wasHandled:!0,shouldExit:!1};case"/issues":return await this.runIssuePipeline(n),{wasHandled:!0,shouldExit:!1};case"/autopilot":return await this.runIssueAutopilot(n),{wasHandled:!0,shouldExit:!1};case"/change":return await this.runChange(n,t),{wasHandled:!0,shouldExit:!1};case"/chatops":return await this.runChatops(n),{wasHandled:!0,shouldExit:!1};case"/production":return await this.runProductionStatus(n),{wasHandled:!0,shouldExit:!1};case"/replay":return await this.runReplayTrace(n),{wasHandled:!0,shouldExit:!1};case"/bisect":return await this.runSymptomBisect(n),{wasHandled:!0,shouldExit:!1};case"/whatif":return await this.runWhatIf(n),{wasHandled:!0,shouldExit:!1};case"/audit":return await this.runAudit(n),{wasHandled:!0,shouldExit:!1};case"/brain":return await this.runMeshBrain(n),{wasHandled:!0,shouldExit:!1};case"/learn":return await this.runEngineeringMemory(n),{wasHandled:!0,shouldExit:!1};case"/intent":return await this.runIntentCompile(n),{wasHandled:!0,shouldExit:!1};case"/causal":return await this.runCausalIntelligence(n),{wasHandled:!0,shouldExit:!1};case"/lab":return await this.runDiscoveryLab(n),{wasHandled:!0,shouldExit:!1};case"/fork":return await this.runRealityFork(n),{wasHandled:!0,shouldExit:!1};case"/ghost":return await this.runGhostEngineer(n),{wasHandled:!0,shouldExit:!1};case"/fix":return await this.runFix(),{wasHandled:!0,shouldExit:!1};case"/tribunal":return await this.runTribunal(n),{wasHandled:!0,shouldExit:!1};case"/resurrect":return await this.runSessionResurrection(n),{wasHandled:!0,shouldExit:!1};case"/sheriff":return await this.runSemanticSheriff(n),{wasHandled:!0,shouldExit:!1};case"/hologram":return await this.runHologram(n),{wasHandled:!0,shouldExit:!1};case"/entangle":return await this.runEntangle(n),{wasHandled:!0,shouldExit:!1};case"/preview":return await this.runFrontendPreview(n),{wasHandled:!0,shouldExit:!1};case"/dashboard":return await this.launchDashboard(),{wasHandled:!0,shouldExit:!1};case"/sync":return await this.printSync(),{wasHandled:!0,shouldExit:!1};case"/setup":return{wasHandled:!0,shouldExit:(await this.handleSetupCommand(n,t)).shouldExit};case"/clear":return f.write(this.useAnsi?"":"\n"),this.printBanner(),{wasHandled:!0,shouldExit:!1};case"/model":return{wasHandled:!0,shouldExit:(await this.handleModelCommand(n,t)).shouldExit};case"/cost":return this.printCost(),{wasHandled:!0,shouldExit:!1};case"/compact":return f.write(this.themeColor(`\n${await this.compactTranscript()}\n`)),{wasHandled:!0,shouldExit:!1};case"/capsule":case"/memory":return await this.handleCapsuleCommand(n),{wasHandled:!0,shouldExit:!1};case"/approvals":return this.handleApprovalsCommand(n),{wasHandled:!0,shouldExit:!1};case"/steps":return this.handleStepsCommand(n),{wasHandled:!0,shouldExit:!1};case"/doctor":return await this.runDoctor(n),{wasHandled:!0,shouldExit:!1};case"/exit":case"exit":case"/quit":return{wasHandled:!0,shouldExit:!0};case"/reset":return this.transcript=[],f.write(y.green("\nTranscript reset.\n")),{wasHandled:!0,shouldExit:!1};case"/voice":const e=n[0]?.toLowerCase();if("setup"===e){const e=await R(),s=await this.runVoiceSetupWizard(t,e.voice);if(!s)return f.write(y.dim("\nVoice setup cancelled.\n")),{wasHandled:!0,shouldExit:!1};const i={...e,voice:s};return await j(i),this.applyVoiceSettings(s),f.write(["",y.green("Voice settings saved."),`${y.dim("language:")} ${s.language}`,`${y.dim("mic:")} ${s.microphone}`,`${y.dim("voice:")} ${s.voice}`,""].join("\n")),{wasHandled:!0,shouldExit:!1}}if(this.voiceMode="on"===e||"off"!==e&&!this.voiceMode,this.voiceMode){if(this.syncVoiceLanguage(),!this.config.agent.voice.configured){const e=await R(),s=await this.runVoiceSetupWizard(t,e.voice);if(!s)return this.voiceMode=!1,f.write(y.dim("\nVoice setup cancelled.\n")),{wasHandled:!0,shouldExit:!1};const i={...e,voice:s};await j(i),this.applyVoiceSettings(s)}const e=await this.voiceManager.checkDependencies(),s=e.filter(e=>!e.ok&&e.required);if(s.length>0){f.write(y.yellow("\nVoice dependencies missing.\n"));s.filter(e=>"ffmpeg"===e.name).length>0&&await this.ensureVoiceCoreDependencies(e);const t=(await this.voiceManager.checkDependencies()).filter(e=>!e.ok&&e.required);t.length>0&&(this.voiceMode=!1,f.write(y.red(`Voice mode remains OFF. Missing: ${t.map(e=>e.name).join(", ")}\n`)))}}return f.write(`\nVoice mode: ${this.voiceMode?y.green("ON"):y.red("OFF")}\n`),this.voiceMode&&f.write(`${y.dim(this.getVoiceExitHint())}\n`),{wasHandled:!0,shouldExit:!1};default:return f.write(`\nUnknown command: ${a} (resolved to ${r}). Use /help.\n`),{wasHandled:!0,shouldExit:!1}}}catch(e){const t=e instanceof Error?e.message:String(e);return f.write(y.red(`\n[Mesh] Error: Command "${r}" failed — ${t.slice(0,200)}. Try /doctor to diagnose.\n`)),{wasHandled:!0,shouldExit:!1}}}async handleModelCommand(e,t){const s=c(e),a=[...s.positionals,s.keyValues.model??""].join(" ").trim();if(!a||"pick"===a||"choose"===a)return await this.chooseModelInteractive(t),{shouldExit:!1};if("list"===a||"ls"===a)return f.write(["",`${this.themeColor(y.bold("Available Models"))}`,...Y.map(e=>{const t=e.aliases.join(", "),s=e.value===this.currentModelId?y.green(" active"):"";return`${e.label} ${y.dim(e.value)}${s}\n${y.dim(`aliases: ${t} | ${e.note}`)}`}),""].join("\n")),{shouldExit:!1};if("current"===a)return f.write(`\ncurrent model: ${this.currentModelId}\n`),{shouldExit:!1};if("save"===a){const e=await R();return await j({...e,modelId:this.currentModelId}),f.write(`\ndefault model saved: ${this.themeColor(i(this.currentModelId))}\n`),{shouldExit:!1}}const o=l(a);return!o&&a.startsWith("/")?(f.write(`\nInvalid model argument: ${a}\n`),{shouldExit:!1}):(this.currentModelId=o?.value??n(a),f.write(`\nmodel switched: ${this.themeColor(i(this.currentModelId))}\n`),{shouldExit:!1})}async chooseModelInteractive(e){const t=Y.map(e=>({name:e.value,message:`${y.bold(e.label)} ${y.dim(e.note)}`,hint:e.value===this.currentModelId?y.green("(active)"):y.dim(e.value)})),s=new A({name:"model",message:"Select an AI model",choices:t,stdin:g,stdout:f});try{const t=await s.run();e.resume(),this.setupGhostText(e,g,f);const i=Y.find(e=>e.value===t);this.currentModelId=i.value,f.write(`\nmodel switched: ${this.themeColor(i.label)}\n`);const n=new _({name:"save",message:"Save as default model?",stdin:g,stdout:f}),a=await n.run();if(e.resume(),this.setupGhostText(e,g,f),a){const e=await R();await j({...e,modelId:i.value}),f.write(y.green("Default model saved.\n"))}}catch{e.resume(),this.setupGhostText(e,g,f),f.write(y.dim("\nSelection cancelled.\n"))}}completeInput(e){const t=this.getSlashCommands().flatMap(e=>[e.name,...e.aliases??[]]),s=e.trimStart();if(!s.startsWith("/"))return[[],e];const i=s.split(/\s+/g),n=i[0].toLowerCase(),a=i[i.length-1]?.toLowerCase()??"";if(i.length<=1&&!e.endsWith(" ")){const e=t.filter(e=>e.startsWith(n));return e.length>1?[[e[0]],n]:[e.length?e:t,n]}const o=["list","current","save","pick",...Y.flatMap(e=>e.aliases)],r=["show","compact","clear","export","stats","path"],c=["status","on","off"],l=["brief","full","voice","fix"],d=["fix","reindex"],u=["fix","add","remove","refactor","validate"],h=["noninteractive","model=","cloud=","theme=","key=","endpoint=","voice_lang=","voice_speed=","voice_voice="],p=["on","off","setup"],m=["build","read","status"],g=["analyze","status","clear"],f=["read","learn"],w=["build","read","status","query"],y=["run","status","clear"],$=["plan","fork","status","clear"],v=["learn","profile","status","predict","divergence","patch","clear"];let k=[];switch(n){case"/model":k=o;break;case"/capsule":case"/memory":k=r;break;case"/approvals":k=c;break;case"/doctor":k=l;break;case"/start":k=d;break;case"/change":k=u;break;case"/setup":k=h;break;case"/voice":k=p;break;case"/twin":k=m;break;case"/repair":k=g;break;case"/learn":k=f;break;case"/causal":k=w;break;case"/lab":k=y;break;case"/fork":k=$;break;case"/ghost":k=v;break;default:k=[]}const b=e.endsWith(" ")?"":a,x=k.filter(e=>e.toLowerCase().startsWith(b));return[x.length?x:k,b]}async handleCapsuleCommand(e){const t=(e[0]||"show").toLowerCase();if("clear"===t)return this.sessionCapsule=null,await this.sessionStore.clear(),void f.write("\nSession capsule cleared.\n");if("compact"===t)return void f.write(this.themeColor(`\n${await this.compactTranscript()}\n`));if("export"===t)return void await this.exportSessionCapsule(e[1]);if("path"===t)return void f.write(`\n${this.getDefaultCapsuleExportPath()}\n`);if(!this.sessionCapsule)return void f.write("\nNo active session capsule.\n");const s=this.parseSessionCapsule(this.sessionCapsule.summary);"stats"!==t?f.write(["",`${this.themeColor(y.bold("Session Capsule"))}`,`${y.dim("generated:")} ${this.sessionCapsule.generatedAt}`,`${y.dim("scope:")} ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,"",this.formatStructuredCapsule(s),""].join("\n")):f.write(["",`${this.themeColor(y.bold("Capsule Stats"))}`,`${y.dim("generated:")} ${this.sessionCapsule.generatedAt}`,`${y.dim("scope:")} ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,`${y.dim("decisions:")} ${s.decisions.length}`,`${y.dim("open threads:")} ${s.openThreads.length}`,`${y.dim("next actions:")} ${s.nextActions.length}`,`${y.dim("files:")} ${s.filesTouched.length}`,`${y.dim("tools:")} ${s.toolActivity.length}`,""].join("\n"))}handleApprovalsCommand(e){const t=(e[0]||"status").toLowerCase();return"on"===t?(this.autoApproveTools=!0,void f.write("\nAuto-approval enabled for write/run tools.\n")):"off"===t?(this.autoApproveTools=!1,void f.write("\nAuto-approval disabled.\n")):void f.write(`\nAuto-approval: ${this.autoApproveTools?"on":"off"}\n`)}handleStepsCommand(e){const t=(e[0]||"").toLowerCase();if(!t||"status"===t)return void f.write(`\nMax steps: ${this.dynamicMaxSteps} (default: ${this.config.agent.maxSteps})\n`);if("reset"===t)return this.dynamicMaxSteps=this.config.agent.maxSteps,void f.write(`\nMax steps reset to ${this.dynamicMaxSteps}.\n`);const s=parseInt(t,10);isNaN(s)||s<1||s>100?f.write("\nUsage: /steps <1-100> | reset\n"):(this.dynamicMaxSteps=s,f.write(`\nMax steps set to ${this.dynamicMaxSteps}.\n`))}async handleSetupCommand(e,t){const s=c(e);if("noninteractive"!==s.positionals[0]?.toLowerCase())return await this.runSetup(t),{shouldExit:!1};const a=await R(),o=s.keyValues;if(0===Object.keys(o).length)return f.write(["","Usage: /setup noninteractive model=sonnet4.6 cloud=on theme=cyan key=- endpoint=- voice_lang=auto voice_mic=default voice_voice=auto","Keys: model, cloud, theme, key, endpoint, voice_lang, voice_mic, voice_voice",""].join("\n")),{shouldExit:!1};const r=o.model?l(String(o.model)):null;if(o.model&&!r&&!String(o.model).includes("."))return f.write(`\nUnknown model alias: ${o.model}. Use /model list.\n`),{shouldExit:!1};if(o.theme&&!K.has(String(o.theme)))return f.write(`\nInvalid theme: ${o.theme}. Allowed: ${Array.from(K).join(", ")}\n`),{shouldExit:!1};if(o.voice_speed&&(!Number.isFinite(Number(o.voice_speed))||Number(o.voice_speed)<120||Number(o.voice_speed)>420))return f.write(`\nInvalid voice_speed: ${o.voice_speed}. Use a value between 120 and 420.\n`),{shouldExit:!1};const d={modelId:o.model?r?.value??n(String(o.model)):a.modelId,enableCloudCache:o.cloud?["1","true","on","yes","y"].includes(String(o.cloud).toLowerCase()):a.enableCloudCache,themeColor:o.theme?String(o.theme):a.themeColor,customApiKey:"-"===o.key?void 0:void 0!==o.key?String(o.key):a.customApiKey,customEndpoint:"-"===o.endpoint?void 0:void 0!==o.endpoint?String(o.endpoint):a.customEndpoint,voice:{configured:a.voice.configured||void 0!==o.voice_lang||void 0!==o.voice_mic||void 0!==o.voice_speed||void 0!==o.voice_voice,language:o.voice_lang?String(o.voice_lang):a.voice.language,microphone:o.voice_mic?String(o.voice_mic):a.voice.microphone,speed:o.voice_speed?Number(o.voice_speed):a.voice.speed,voice:o.voice_voice?String(o.voice_voice):a.voice.voice}};return await j(d),this.applyVoiceSettings(d.voice),f.write(["",`${y.green("Settings updated.")}`,`${y.dim("model:")} ${i(d.modelId)}`,`${y.dim("cloud:")} ${d.enableCloudCache?"on":"off"}`,`${y.dim("theme:")} ${d.themeColor}`,`${y.dim("voice:")} ${d.voice.language} / ${d.voice.microphone} / ${d.voice.voice}`,""].join("\n")),{shouldExit:!1}}async runDoctor(e=[]){const t=e.includes("full"),s=e.includes("voice"),i=e.includes("fix");if(s){let e=await this.voiceManager.checkDependencies();f.write(this.themeColor(`\n${y.bold("Voice Diagnostics")}\n`));for(const t of e){const e=!1!==t.required,s=t.ok?y.green("✔"):e?y.red("✘"):y.yellow("•"),i=t.ok?y.green("Available"):e?y.red("Missing"):y.yellow("Optional");f.write(`${s} ${t.name.padEnd(15)} ${i}\n`),!t.ok&&t.hint&&f.write(` ${y.dim(`Hint: ${t.hint}`)}\n`)}return this.voiceManager.hasGeminiStt()?f.write(`${y.green("✔")} ${"stt/tts".padEnd(15)} ${y.green("Gemini Flash")} ${y.dim("(via GOOGLE_API_KEY)")}\n`):f.write(`${y.red("✘")} ${"stt/tts".padEnd(15)} ${y.red("GOOGLE_API_KEY not set")} ${y.dim("— run /setup to configure")}\n`),f.write(`${y.dim("•")} ${"voice config".padEnd(15)} ${y.dim(`lang:${this.config.agent.voice.language} voice:${this.config.agent.voice.voice} mic:${this.config.agent.voice.microphone}`)}\n`),void(i&&(e=await this.ensureVoiceCoreDependencies(e)))}const n=(e[0]||"brief").toLowerCase();f.write(this.themeColor(`\n${y.bold("Mesh System Diagnostics")}\n`));const a=$({text:"Running doctor checks...",color:"cyan"}).start();try{const e=new O(this.config);let s=await e.run(),o=[];if(i&&(a.text="Applying safe doctor fixes...",o=await e.autoFix(),s=await e.run()),a.stop(),o.length>0){f.write(y.bold("\nApplied safe fixes\n"));for(const e of o){const t=e.ok?y.green("✔"):y.red("✘");f.write(`${t} ${e.message}\n`);for(const t of e.details??[])f.write(` ${y.dim(t)}\n`)}f.write("\n")}for(const e of s.checks){const s="pass"===e.status?y.green("✔"):"warn"===e.status?y.yellow("⚠"):y.red("✘"),i="pass"===e.status?y.white:"warn"===e.status?y.yellow:y.red;if(f.write(`${s} ${y.bold(i(e.title.padEnd(25)))} ${e.message}\n`),(t||"brief"===n||"pass"!==e.status)&&e.details&&e.details.length>0)for(const t of e.details)f.write(` ${y.dim(t)}\n`);const a=(e.fixes??[]).filter(t=>!t.automatic||"pass"!==e.status);if(a.length>0&&"pass"!==e.status)for(const e of a){const t=e.automatic?"auto":"manual";f.write(` ${y.dim(`fix (${t}): ${e.title} - ${e.description}`)}\n`),e.command&&f.write(` ${y.dim(`command: ${e.command}`)}\n`)}f.write("\n")}s.ok?f.write(y.green(y.bold("All systems operational. Mesh is ready for duty.\n"))):f.write(y.red(y.bold("Some systems are failing. Check the warnings above to restore full functionality.\n")));const r=await this.backend.callTool("workspace.get_index_status",{});f.write(`\n${y.dim("Workspace index: ")} ${r?.percent??0}% (${r?.indexedFiles??0} files)\n\n`)}catch(e){a.fail(y.red(`Doctor failed unexpectedly: ${e.message}`))}}async ensureVoiceCoreDependencies(e){const t=e??await this.voiceManager.checkDependencies(),s=t.filter(e=>!e.ok&&"ffmpeg"===e.name).map(e=>e.name);if(0===s.length)return f.write(y.green("\nCore voice dependencies are already installed.\n")),t;if(!this.voiceManager.hasHomebrew())return f.write(y.red("\nHomebrew is not installed. Install it from https://brew.sh and rerun /doctor voice fix.\n")),t;const i=new _({name:"installVoiceDeps",message:`Install missing voice dependencies with Homebrew? (${s.join(", ")})`,initial:!0});if(!Boolean(await i.run().catch(()=>!1)))return f.write(y.dim("\nInstallation cancelled.\n")),t;const n=this.useAnsi?$({text:`Installing voice dependencies (${s.join(", ")})...`,color:"cyan",stream:f}).start():void 0;n||f.write(this.themeColor(`\nInstalling voice dependencies (${s.join(", ")})...\n`));try{await this.voiceManager.installCoreDependencies(s,{quiet:!0});const e=await this.voiceManager.checkDependencies();n?n.succeed(`Voice dependencies installed: ${s.join(", ")}`):f.write(y.green("\nVoice dependency installation complete.\n"));for(const t of e.filter(e=>!1!==e.required)){const e=t.ok?y.green("✔"):y.red("✘");f.write(`${e} ${t.name.padEnd(15)} ${t.ok?y.green("Available"):y.red("Missing")}\n`)}return e}catch(e){n&&n.fail("Voice dependency installation failed.");const s=e instanceof Error?e.message:String(e);return f.write(y.red(`\nVoice dependency installation failed: ${s}\n`)),t}}async exportSessionCapsule(e){if(!this.sessionCapsule)return void f.write("\nNo active session capsule to export.\n");const t=e?p.resolve(this.config.agent.workspaceRoot,e):this.getDefaultCapsuleExportPath(),s=this.parseSessionCapsule(this.sessionCapsule.summary),i=["# Session Capsule","",`- Generated: ${this.sessionCapsule.generatedAt}`,`- Workspace: ${this.config.agent.workspaceRoot}`,`- Scope: ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,"",this.formatStructuredCapsule(s),""].join("\n");await u.mkdir(p.dirname(t),{recursive:!0}),await u.writeFile(t,i,"utf8"),f.write(`\nSession capsule exported to ${t}\n`)}buildDynamicRuntimeContext(){const e=[];this.currentTurnPreferredTools.length>0&&e.push(`[TOOL ROUTING]\nFor this turn, prefer these tools when useful: ${this.currentTurnPreferredTools.slice(0,24).join(", ")}`),this.gitStatusContext&&e.push(`\n[GIT REPOSITORY STATUS]\nCurrent branch: ${r(this.gitStatusContext,1200)}`),this.prefetchQueue.length>0&&(e.push("\n[PREDICTIVE CONTEXT PREFETCH]\nThe following file capsules were pre-loaded because they are highly likely to be relevant to your current task:"),e.push(...this.prefetchQueue.slice(0,2).map(e=>r(e,1200))),this.prefetchQueue=[]);try{const t=p.join(this.config.agent.workspaceRoot,".mesh","project-brain.md"),s=h(t,"utf8");s&&e.push(`\n[FRACTAL PROJECT CONTEXT (Project Brain)]\nAdhere to these distilled architectural rules and conventions specific to this project:\n${r(s,2400)}`)}catch{}try{const t=p.join(this.config.agent.workspaceRoot,".mesh","company-brain","summary.md"),s=h(t,"utf8");s&&e.push(`\n[COMPANY CODEBASE BRAIN]\nUse these durable repo facts, rules, risks, and decisions before proposing changes:\n${r(s,3200)}`)}catch{}try{const t=p.join(this.config.agent.workspaceRoot,".mesh","engineering-memory.json"),s=h(t,"utf8"),i=JSON.parse(s);if(i&&(i.rules?.length||i.decisions?.length)){const t=["Rules:",...(i.rules||[]).map(e=>`- ${e.rule||e}`),"Decisions:",...(i.decisions||i.acceptedPatterns||[]).map(e=>`- ${e.pattern||e}`)].join("\n");e.push(`\n[ENGINEERING MEMORY (Session Distiller)]\nApply these distilled project decisions and rules learned from previous sessions:\n${r(t,2400)}`)}}catch{}return this.voiceMode&&(e.push(`\nVoice Instructions:\n${z}`),e.push(`Voice Language:\n${this.buildVoiceLanguageInstruction()}`)),this.localInstructions&&e.push(`\nLocal Project Instructions:\n${r(this.localInstructions,2400)}`),this.workspaceContext&&e.push(r(this.workspaceContext,1200)),e.join("\n\n")}async autoCompactIfNeeded(){return this.transcript.length<30&&this.estimateTranscriptChars()<22e4?null:this.compactTranscript({reason:"auto"})}async compactTranscript(e){if(0===this.transcript.length)return"Transcript already empty. No compaction needed.";const t=this.transcript.length,s=Math.min(12,t),i=this.transcript.slice(-s),n=this.transcript.slice(0,Math.max(0,t-s)),a=await this.buildSessionCapsuleSummary(n,i);this.sessionCapsule={summary:a,generatedAt:(new Date).toISOString(),sourceMessages:t,retainedMessages:s},this.transcript=i,await this.sessionStore.save(this.sessionCapsule);return`${"auto"===e?.reason?"Auto-compacted session.":"Session compacted."} Retained ${s} recent messages, compressed ${Math.max(0,t-s)} older messages into capsule.`}async buildSessionCapsuleSummary(e,t){const s=this.buildHeuristicSessionCapsuleSummary(e,t),i=`You are a memory compression module for an autonomous AI agent.\nYour task is to refine the following raw heuristic session summary into a highly condensed, intent-preserving "Session Capsule".\nCRITICAL RULES:\n1. Preserve Tone, User Intent, Key Decisions, and Emotional Register.\n2. Maintain the structure: Summary, Decisions, Open Threads, Next Actions, Files Touched.\n3. Keep it terse and under 800 words.\n4. Output ONLY the refined capsule text. Do not add conversational filler.\n\nRaw Heuristic Summary:\n${s}`;try{const e=await this.llm.converse([{role:"user",content:[{text:i}]}],[],"You are a memory compression module.");if("text"===e.kind&&e.text.trim())return e.text}catch(e){}return s}buildHeuristicSessionCapsuleSummary(t,i){const n=[],a=[],o=[],r=[],c=[];for(const e of t)for(const t of e.content){if("text"in t&&t.text.trim()){const s=this.normalizeCapsuleLine(t.text);if(!s)continue;"user"===e.role?n.length<8&&n.push(s):a.length<8&&a.push(s)}if("toolUse"in t){const e=s(t.toolUse.input);o.push(`${t.toolUse.name} ${e}`);const i=t.toolUse.input;"string"==typeof i.path&&i.path.trim()&&c.push(i.path.trim())}if("toolResult"in t){const e=t.toolResult.content.find(e=>"text"in e&&"string"==typeof e.text);if(e&&"text"in e){const t=this.normalizeCapsuleLine(e.text);t&&r.push(t)}}}const l=this.sessionCapsule?this.parseSessionCapsule(this.sessionCapsule.summary):null,d={summary:this.normalizeCapsuleLine(a[a.length-1]||n[n.length-1]||`Conversation progressed through ${t.length} summarized messages.`,220),decisions:e([...l?.decisions??[],...a.slice(-4),...r.filter(e=>/saved|updated|created|switched|cleared|exported|connected|indexed/i.test(e))].map(e=>this.normalizeCapsuleLine(e,160)),20),openThreads:e([...l?.openThreads??[],...n.slice(-5),...r.filter(e=>/error|failed|denied|omitted|unknown/i.test(e))].map(e=>this.normalizeCapsuleLine(e,160)),20),nextActions:e([...l?.nextActions??[],...a.filter(e=>/next|should|can|recommend|suggest/i.test(e)),i.length?`Continue from ${i.length} preserved recent messages.`:""].map(e=>this.normalizeCapsuleLine(e,160)),15),filesTouched:e([...l?.filesTouched??[],...c].map(e=>this.normalizeCapsuleLine(e,120)),50),toolActivity:e([...l?.toolActivity??[],...o.slice(-8),...r.slice(-4)].map(e=>this.normalizeCapsuleLine(e,160)),20)};return this.serializeStructuredCapsule(d)}serializeStructuredCapsule(e){return[`summary: ${e.summary}`,...this.serializeCapsuleSection("decisions",e.decisions),...this.serializeCapsuleSection("open_threads",e.openThreads),...this.serializeCapsuleSection("next_actions",e.nextActions),...this.serializeCapsuleSection("files_touched",e.filesTouched),...this.serializeCapsuleSection("tool_activity",e.toolActivity)].join("\n")}serializeCapsuleSection(e,t){return[`${e}:`,...t.length?t.map(e=>`- ${e}`):["- none"]]}parseSessionCapsule(e){const t=String(e||"").split("\n"),s={summary:"",decisions:[],openThreads:[],nextActions:[],filesTouched:[],toolActivity:[]};let i=null;for(const e of t){const t=e.trim();if(t)if(t.startsWith("summary:"))s.summary=t.slice(8).trim(),i=null;else if("decisions:"!==t)if("open_threads:"!==t)if("next_actions:"!==t)if("files_touched:"!==t)if("tool_activity:"!==t){if(t.startsWith("- ")&&i){const e=t.slice(2).trim();e&&"none"!==e&&s[i].push(e)}}else i="toolActivity";else i="filesTouched";else i="nextActions";else i="openThreads";else i="decisions"}return s.summary||(s.summary=this.normalizeCapsuleLine(e,220)),s}formatStructuredCapsule(e){return[`Summary: ${e.summary}`,...this.formatCapsuleSection("Decisions",e.decisions),...this.formatCapsuleSection("Open Threads",e.openThreads),...this.formatCapsuleSection("Next Actions",e.nextActions),...this.formatCapsuleSection("Files Touched",e.filesTouched),...this.formatCapsuleSection("Tool Activity",e.toolActivity)].join("\n")}formatCapsuleSection(e,t){return["",e,...t.length?t.map(e=>`- ${e}`):["- none"]]}getDefaultCapsuleExportPath(){return p.join(this.config.agent.workspaceRoot,".mesh","session-capsule.md")}normalizeCapsuleLine(e,t=180){const s=e.replace(/\s+/g," ").trim();return s?s.length>t?`${s.slice(0,t-3)}...`:s:""}estimateTranscriptChars(){return this.transcript.reduce((e,t)=>e+t.content.reduce((e,t)=>"text"in t?e+t.text.length:"toolUse"in t?e+JSON.stringify(t.toolUse.input).length+t.toolUse.name.length:"toolResult"in t?e+JSON.stringify(t.toolResult).length:e,0),0)}}export function sanitizeLlmOutput(e){const t=function(e){const t=e.match(/[^\n]*\n|[^\n]+/g)??(e?[e]:[]),s=[];let i="",n=!1;const a=e=>{i&&(s.push({text:i,isCode:e}),i="")};for(const e of t)/^\s*```/.test(e)?n?(i+=e,a(!0),n=!1):(a(!1),i+=e,n=!0):i+=e;return a(n),s}(String(e??""));if(0===t.length)return"";const s=t.findIndex(e=>!e.isCode),i=t.findLastIndex(e=>!e.isCode),n=t.map((e,t)=>{if(e.isCode)return e.text;let n=function(e){return e.replace(/<thinking>[\s\S]*?<\/thinking>/g,"").replace(/<thought>[\s\S]*?<\/thought>/g,"").replace(/<reflection>[\s\S]*?<\/reflection>/g,"").replace(/<scratchpad>[\s\S]*?<\/scratchpad>/g,"").replace(/<\/?(artifact|result|answer)[^>]*>/g,"").replace(/<\/?(thinking|thought|reflection|scratchpad)[^>]*>/g,"").replace(/\\n/g,"\n").replace(/\n{4,}/g,"\n\n").replace(/^\s*\|\s*$/gm,"")}(e.text);return t===s&&(n=n.trimStart()),t===i&&(n=n.trimEnd()),n}).join("");return(n.match(/^```/gm)||[]).length%2==0?n:`${n}\n\`\`\``}
1
+ function e(e,t){return Array.from(new Set(e.filter(Boolean))).slice(0,t)}function t(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t.length>0?t:"tool"}function s(e){const t=JSON.stringify(e);return t?t.length<=100?t:`${t.slice(0,97)}...`:"{}"}function i(e){const t=J.find(t=>e.includes(t.value)||t.value.includes(e));if(t)return t.label;const s=e.split(".");return s[s.length-1].includes("claude-sonnet")?"Claude Sonnet":e.split(":").pop()||e}function n(e){const t=e.trim().toLowerCase();if(!t)return"";for(const e of J)if(e.aliases.includes(t)||t===e.value.toLowerCase())return e.value;return e.trim()}function a(e,t=140){const s=e.replace(/\s+/g," ").trim();return s?s.length>t?`${s.slice(0,t-3)}...`:s:""}function o(e){return e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function r(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-60))}\n[trimmed ${e.length-t} chars]`}function c(e){const t=[],s={};for(const i of e){const e=i.indexOf("=");if(e>0){const t=i.slice(0,e).trim().toLowerCase(),n=i.slice(e+1).trim();t&&(s[t]=n)}else i.trim()&&t.push(i.trim())}return{positionals:t,keyValues:s}}function l(e){const t=e.trim().toLowerCase();return t?J.find(e=>e.value.toLowerCase()===t||e.aliases.includes(t)||e.label.toLowerCase()===t)??null:null}function d(e){return/LLM streaming failed/i.test(e)&&/(?:->|status\s*)\s*(404|405)\b/i.test(e)}import u from"node:fs/promises";import{readFileSync as h}from"node:fs";import p from"node:path";import m from"node:readline/promises";import{stdin as g,stdout as f}from"node:process";import{fileURLToPath as w}from"node:url";import y from"picocolors";import $ from"ora";import k from"enquirer";import v from"node:os";import b from"node:http";import{spawn as x}from"node:child_process";import C from"node:crypto";import{marked as S}from"marked";import{markedTerminal as T}from"marked-terminal";import{MODEL_CATALOG as I}from"./model-catalog.js";import{routeMeshTask as A}from"./model-router.js";S.use(T());const{Select:E,Confirm:_,Input:M}=k;import{loadUserSettings as R,saveUserSettings as j,shortPathLabel as D}from"./config.js";import{BedrockLlmClient as L}from"./llm-client.js";import{ContextAssembler as P}from"./context-assembler.js";import{ContextArtifactStore as F}from"./context-artifacts.js";import{SessionCapsuleStore as N}from"./session-capsule-store.js";import{buildSessionManager as U}from"./session-manager.js";import{MeshPortal as H}from"./mesh-portal.js";import{MeshDoctorEngine as O}from"./doctor.js";import{VoiceManager as q}from"./voice-manager.js";const V=["# Identity","You are Mesh — a senior engineering partner embedded directly in the developer's workspace.","You are a professional coding agent focused on verified, high-quality changes.","","# Communication","- Match the user's language exactly (German if they write German, English if English).","- Be terse. Lead with the result or the next action.","- No greetings, no filler, no emojis.","- When something is broken, say what broke and what fixes it.","","# Result Enforcement","Every time you complete a code change or a task, you MUST conclude with a 'Verification Report':","- CHANGED FILES: <list>","- VERIFICATION: <command run & result (pass/fail)>","- RESIDUAL RISK: <potential side effects>","- NEXT RECOMMENDED STEP: <one sentence>","","# How to read the codebase","You have a fully indexed, live capsule of this workspace. Use it correctly:","- For durable company context, decisions, ownership signals, risk memory, and repo-specific lessons: use 'workspace.company_brain' first.","- For questions about code, behavior, or structure: 'workspace.semantic_search' first (RAG — uses vector embeddings for conceptual queries), then 'workspace.ask_codebase' for deep analysis.","- For symbol definitions, callers, and usages: 'workspace.explain_symbol' or 'workspace.find_references'.","- For data flow across files: 'workspace.trace_symbol'.","- For recent background changes: 'workspace.get_recent_changes' — never re-read files you've already seen.","- For file contents only when you need to edit: 'workspace.read_file_raw'.","- For directory structure: 'workspace.read_dir_overview'.","- NEVER call 'workspace.open_artifact' automatically after another tool. The result is already in context. Only use it when the user explicitly asks for more detail or the result was truncated.","","# How to make changes","- Check impact before any edit that touches shared symbols: 'workspace.impact_map'.","- For surgical single-symbol changes: 'workspace.rename_symbol' or 'workspace.inline_symbol'.","- For function extraction or structural refactors: 'workspace.extract_function' or 'workspace.move_to_module'.","- For large multi-file changes, use alien-patch for maximum token efficiency:"," 1. 'workspace.session_index_symbols' to get symbol IDs"," 2. 'workspace.alien_patch' with opcodes: e:(export) s:(async) f:(func) c:(const) l:(let) r:(return) a:(await) i:(if) p:(Promise)"," Format: !ID > { [code] }","- For risky changes: create a ghost timeline first ('workspace.timeline_create'), run and verify there, then promote.","- Before promoting: run 'workspace.validate_patch' and 'workspace.ghost_verify'.","- Before production-ready handoff or PR preparation: run 'workspace.production_readiness' with action='gate'. It checks model routing, RAG quality, timelines, runtime learning, visual evidence, memory, and review gates.","","# How to debug","- For a failing test or command: 'runtime.start' → 'runtime.capture_failure' → 'runtime.explain_failure'.","- For deeper root cause: 'runtime.capture_deep_autopsy' or 'workspace.symptom_bisect'.","- For tracing a specific request through the system: 'runtime.trace_request'.","- For reproducing intermittent bugs: 'workspace.schrodingers_ast' or 'workspace.reality_fork'.","- For diagnosing why something broke after a change: 'workspace.causal_autopsy'.","","# How to work on complex tasks","- For issue-to-PR work: use 'workspace.issue_autopilot' to plan, patch in an isolated timeline, verify, review, write a proof bundle, and optionally create the PR.","- For tasks that touch many files or need parallel exploration: spawn sub-agents with 'agent.spawn' or 'agent.spawn_swarm'.","- For competing fix approaches: 'agent.race_fixes' — run both in ghost timelines, compare results, promote the winner.","- For multi-step plans before execution: 'agent.plan' to validate the approach first.","- Always match the user's style using 'workspace.ghost_engineer' memory before writing new code.","","# Proactive behaviors — do these without being asked","- After fixing a bug: check for the same pattern elsewhere with 'workspace.grep_ripgrep' or 'workspace.find_edge_cases'.","- Before a major edit: run 'workspace.predictive_repair' to surface related fragile areas.","- When the user describes a problem: immediately use 'workspace.ask_codebase' or 'workspace.causal_intelligence' to locate the root cause before responding.","- When you see TODOs or known gaps while working: note them or resolve with 'workspace.todo_resolver'.","- When tests are missing for a changed file: proactively offer to generate property tests via 'workspace.generate_properties'.","- For broad production hardening: use 'workspace.model_route' first, then 'workspace.production_readiness' to keep work aligned with the right specialist models and gates.","","# Safety","- Never run destructive shell commands (rm -rf, drop table, git reset --hard, force push) without explicit user confirmation.","- For dangerous operations, always use shadow/timeline execution first: 'workspace.run_in_shadow' or 'workspace.timeline_run'.","- Token budget is finite. Prefer capsule-based reads. Avoid re-reading files already in context."].join("\\n"),z=["# Voice Mode Active","Respond for spoken conversation, not for markdown reading.","","## Voice Contract","- **Short & Natural**: Use short natural sentences. Reply in plain text only.","- **No Formatting**: Never use emojis, bullet lists, markdown formatting, headings, code fences, or decorative symbols.","- **Conciseness**: Keep answers very short unless the user explicitly asks for more detail.","- **Readability**: Avoid reading punctuation-heavy structures aloud.","- **Code**: If the user asks a coding question, answer briefly first and only give commands or code when truly necessary."].join("\\n"),G=[{name:"auto",message:"Auto-detect",hint:"Detect language from audio"},{name:"de",message:"Deutsch",hint:"de"},{name:"en",message:"English",hint:"en"},{name:"ar",message:"Arabic",hint:"ar"},{name:"es",message:"Spanish",hint:"es"},{name:"fr",message:"French",hint:"fr"},{name:"it",message:"Italian",hint:"it"},{name:"ja",message:"Japanese",hint:"ja"},{name:"pt",message:"Portuguese",hint:"pt"}],B=[{name:"auto",message:"Auto",hint:"Pick best voice for language"},{name:"Puck",message:"Puck",hint:"Neutral English default"},{name:"Kore",message:"Kore",hint:"Clear — good for German, Japanese"},{name:"Aoede",message:"Aoede",hint:"Warm — good for French, Portuguese"},{name:"Charon",message:"Charon",hint:"Good for Spanish"},{name:"Fenrir",message:"Fenrir",hint:"Alternative voice"},{name:"Zephyr",message:"Zephyr",hint:"Alternative voice"}],K={ar:"Arabic",de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",ja:"Japanese",pt:"Portuguese"},W=[/^\/voice off$/,/(voice|sprachmodus|stimmmodus)\s*(aus|off|beenden|beendet|stoppen|stoppt)/i,/(beende|beendet|beenden|stoppe|stoppen|stopp|verlasse|verlassen)\s*(den\s*)?(voice|sprachmodus|stimmmodus)/i,/(stop|exit|quit|disable)\s+(voice)/i,/(voice|voice mode|voice chat)\s+(off|stop|exit|quit|disable)/i,/stop listening/i,/stop recording/i,/textmodus\s*(an|zuruck|bitte)/i,/zuruck zum text/i],J=I,Y=new Set(["cyan","magenta","yellow","green","blue","white"]);export class AgentLoop{config;backend;ghostTextListener=null;llm;useAnsi=f.isTTY;sessionStore;artifactStore;contextAssembler=new P;currentModelId;currentBranch="nogit";localInstructions="";transcript=[];sessionCapsule=null;lastToolEventAt=null;sessionTokens={inputTokens:0,outputTokens:0};workspaceContext="";abortController=null;autoApproveTools=!1;dynamicMaxSteps;themeColor=y.cyan;persistentHistory=[];historyPath=p.join(v.homedir(),".mesh_history");voiceManager;voiceMode=!1;voiceLanguage="en";prefetchQueue=[];pendingPrefetchQueue=[];currentTurnPreferredTools=[];dashboardEventWrite=Promise.resolve();dashboardActionTimer=null;dashboardActionRunning=!1;dashboardToken=null;toolEventsExpanded=!1;turnToolCalls=0;turnToolErrors=0;turnToolNames=new Map;turnArtifactCharsStored=0;turnArtifactEnvelopeChars=0;sessionRawSaved=0;turnContextReports=[];lastContextReport=null;currentTurnRouteContext=null;entangledWorkspaces=[];gitStatusContext="";consecutiveErrors=new Map;portal;headlessInitialized=!1;streamingUnavailable=!1;sessionManager;constructor(e,t,s){this.config=e,this.backend=t,this.sessionStore=new N(e.agent.workspaceRoot),this.artifactStore=new F(e.agent.workspaceRoot),this.dynamicMaxSteps=e.agent.maxSteps,this.portal=new H(e.agent.workspaceRoot),this.currentModelId=e.bedrock.modelId,this.llm=new L({endpointBase:e.bedrock.endpointBase,modelId:this.currentModelId,fallbackModelIds:e.bedrock.fallbackModelIds,bearerToken:e.bedrock.bearerToken,googleApiKey:e.bedrock.googleApiKey,temperature:e.bedrock.temperature,maxTokens:e.bedrock.maxTokens}),this.sessionManager=s??U(e.agent.workspaceRoot);const i=e.agent.themeColor||"cyan",n=y[i];"function"==typeof n&&(this.themeColor=n),this.voiceManager=this.buildVoiceManager(),this.syncVoiceLanguage(),this.startDashboardActionPump()}rebuildLlmClient(){this.llm=new L({endpointBase:this.config.bedrock.endpointBase,modelId:this.currentModelId,fallbackModelIds:this.config.bedrock.fallbackModelIds,bearerToken:this.config.bedrock.bearerToken,googleApiKey:this.config.bedrock.googleApiKey,temperature:this.config.bedrock.temperature,maxTokens:this.config.bedrock.maxTokens})}buildVoiceManager(){return new q({voiceLanguage:this.config.agent.voice.language,voiceSpeed:this.config.agent.voice.speed,voiceName:this.config.agent.voice.voice,voiceInput:this.config.agent.voice.microphone,googleApiKey:this.config.bedrock?.ownGoogleApiKey||this.config.bedrock?.googleApiKey})}applyVoiceSettings(e){this.config.agent.voice={...e},this.voiceManager.updateConfig({voiceLanguage:e.language,voiceSpeed:e.speed,voiceName:e.voice,voiceInput:e.microphone}),this.syncVoiceLanguage(e.language)}normalizeLanguageCode(e){return String(e||"auto").trim().toLowerCase().replace(/_/g,"-")}getConfiguredVoiceLanguage(){return this.normalizeLanguageCode(this.config.agent.voice.language)}syncVoiceLanguage(e){const t=this.getConfiguredVoiceLanguage();this.voiceLanguage="auto"===t?this.normalizeLanguageCode(e||this.voiceLanguage||"en"):t}getVoiceReplyLanguage(){const e=this.getConfiguredVoiceLanguage();return"auto"===e?this.normalizeLanguageCode(this.voiceLanguage||"en"):e}buildVoiceLanguageInstruction(){const e=this.getVoiceReplyLanguage(),t=K[e.split("-")[0]]||e;return"auto"===this.getConfiguredVoiceLanguage()?`Reply in the same language as the user's last spoken message. Current detected language: ${t}.`:`Always reply in ${t} unless the user explicitly asks to switch languages.`}sanitizeVoiceAssistantText(e){return e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*>\s+/gm,"").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/\p{Extended_Pictographic}/gu,"").replace(/[•▪◦●○◆◇★☆]/g," ").replace(/\s+/g," ").trim()||e.replace(/\s+/g," ").trim()}normalizeVoiceCommand(e){return e.trim().toLowerCase().normalize("NFKD").replace(/\p{Diacritic}/gu,"").replace(/[^\p{L}\p{N}\/\s]+/gu," ").replace(/\s+/g," ").trim()}isVoiceExitCommand(e){const t=this.normalizeVoiceCommand(e);return!!t&&W.some(e=>e.test(t))}getVoiceExitHint(){const e=this.getVoiceReplyLanguage().split("-")[0];return"de"===e?'Sage "Voice aus" oder "beende Sprachmodus", um Voice zu verlassen.':"en"===e?'Say "voice off" or "stop voice mode" to leave voice mode.':'Say "voice off" or "Voice aus" to leave voice mode.'}async refreshGitStatus(){try{const e=await this.backend.callTool("workspace.git_status",{});e.ok&&(this.gitStatusContext=`${e.branch}\nFiles:\n${e.status||"Clean (no uncommitted changes)"}`)}catch{this.gitStatusContext=""}}normalizeInspectUrl(e){const t=e.trim()||"http://localhost:3000";return/^https?:\/\//i.test(t)?t:`http://${t}`}async isUrlReachable(e,t=700){return await new Promise(s=>{let i;try{i=new URL(e)}catch{return void s(!1)}const n=b.request({hostname:i.hostname,port:i.port||("https:"===i.protocol?443:80),path:i.pathname||"/",method:"HEAD",timeout:t},e=>{e.resume(),s(Boolean(e.statusCode&&e.statusCode<500))});n.on("error",()=>s(!1)),n.on("timeout",()=>{n.destroy(),s(!1)}),n.end()})}async findReachableDevUrl(t){if(await this.isUrlReachable(t))return t;const s=new URL(t),i="0.0.0.0"===s.hostname?"127.0.0.1":s.hostname,n=e([s.port||("https:"===s.protocol?"443":"80"),"5173","5174","3000","3001","4173","8080"],8);for(const e of n){const t=`${s.protocol}//${i}:${e}`;if(await this.isUrlReachable(t,450))return t}return null}async handleInspect(e){let t=this.normalizeInspectUrl(e),s=await this.findReachableDevUrl(t);if(!s){f.write(y.yellow(`\n[Mesh Portal] No dev server detected near ${t}. Starting the workspace dev script...\n`));try{const e=p.join(this.config.agent.workspaceRoot,"package.json");let i={};try{i=JSON.parse(await u.readFile(e,"utf8"))}catch{}if(!(i.scripts?.dev||i.scripts?.start))throw new Error("No 'dev' or 'start' script found in package.json");{const{spawn:e}=await import("node:child_process");e("npm",["run",i.scripts?.dev?"dev":"start"],{cwd:this.config.agent.workspaceRoot,stdio:"ignore",detached:!0}).unref(),f.write(y.green("[Mesh Portal] Dev server launched in background. Probing common local ports...\n"));for(let e=0;e<25&&(await new Promise(e=>setTimeout(e,1e3)),s=await this.findReachableDevUrl(t),!s);e++);}}catch(e){f.write(y.red(`[Mesh Portal] Could not start server: ${e.message}\n`))}}s&&(t=s);const i=$({text:`Connecting visual inspector to ${t}...`,color:"cyan"}).start();try{await this.portal.start(t,async e=>{"meshEmit"===e.name&&await this.handlePortalMutation(e.payload)});const e=p.join(p.dirname(new URL(import.meta.url).pathname),"mesh-canvas-overlay.js"),s=await u.readFile(e,"utf8");await this.portal.evaluate(s),i.succeed(y.green(`Visual inspector active on ${t}. Alt+Click an element to describe a UI change.`))}catch(e){i.fail(y.red(`Visual inspector failed: ${e.message}`)),f.write(y.dim(`Tip: run your app manually, then use /inspect http://localhost:<port> or /preview ${t}.\n`))}}async handlePortalMutation(e){let t;try{t=JSON.parse(e)}catch{return}const{type:s,file:i,line:n,prompt:a,context:o,xray:r}=t,c=r?.source?.fileName||i,l=r?.source?.lineNumber||n;if(!c||"unknown"===c)return;const d=p.relative(this.config.agent.workspaceRoot,c),h=r?.component||this.extractComponentName(o?.tag,o?.classes)||"Anonymous",m=Array.isArray(r?.requests)?r.requests.slice(0,5):[],g=await Promise.all(m.map(async e=>{const t=`${String(e.method||"GET").toUpperCase()} ${e.route||e.url||""}`.trim();if(!t)return null;const s=await this.backend.callTool("workspace.ask_codebase",{query:t,mode:"runtime-path",limit:2}).catch(()=>null);return{request:e,matches:Array.isArray(s?.results)?s.results.slice(0,2).map(e=>({file:e.file,purpose:e.purpose,citations:Array.isArray(e.citations)?e.citations.slice(0,2).map(e=>({file:e.file,symbol:e.symbol,lines:e.lines,whyMatched:e.whyMatched})):[]})):[]}})),w=h&&"Anonymous"!==h?await this.backend.callTool("workspace.trace_symbol",{path:d,symbol:h}).catch(()=>null):null,$=g.filter(Boolean);if("PROMPT"===s){process.stdout.write(y.cyan(`\n[Visual AI] Designing for ${y.bold(d)}:${l||n||0}...\n`)),process.stdout.write(y.dim(` " ${a} "\n`));const e=await u.access(p.join(this.config.agent.workspaceRoot,"tailwind.config.js")).then(()=>!0).catch(()=>u.access(p.join(this.config.agent.workspaceRoot,"tailwind.config.ts")).then(()=>!0).catch(()=>!1)),t=`The user clicked an element in the browser and provided a visual instruction.\nEvidence:\n${[`Source: ${d}:${l||0}`,`Component: ${h}`,m.length>0?`Requests:\n${m.map(e=>`- ${String(e.method||"GET").toUpperCase()} ${e.route||e.url} -> ${e.status}${e.durationMs?` (${e.durationMs}ms)`:""}`).join("\n")}`:"Requests: none captured",$.length>0?`Route matches:\n${$.map(e=>{const t=e.matches.length>0?e.matches.map(e=>`- ${e.file}: ${e.purpose}`).join("\n"):"- no strong matches";return`${e.request.method} ${e.request.route||e.request.url}\n${t}`}).join("\n")}`:"Route matches: none",w&&w.ok?`Symbol trace:\n${JSON.stringify(w,null,2)}`:"Symbol trace: unavailable",`DOM:\n${o.html}`,`Parent DOM:\n${o.parentHtml}`].join("\n\n")}\n\nUser Instruction: "${a}"\nStyling Paradigm: ${e?"TAILWIND CSS (Use utility classes, avoid inline styles)":"STANDARD CSS/INLINE"}\n\nYour mission is a two-step process:\n1. IMMEDIATELY output a JSON block labeled 'PREVIEW_STYLE' with CSS properties for instant preview.\n2. Then, proceed to apply the PERMANENT code patch to the file using your tools.\n\nEnsure the final code is clean, idiomatic, and adheres to the styling paradigm. Finalize once done.`;let s=!1;const i={onDelta:async e=>{if(!s&&e.includes("PREVIEW_STYLE"))try{const t=e.match(/PREVIEW_STYLE\s*(\{.*?\})/);if(t){try{const e=JSON.parse(t[1]);await this.portal.applyGhostStyles(e)}catch{f.write(y.red("[Mesh] Error: Ghost styles parse failed — skipping live preview update.\n"))}s=!0,process.stdout.write(y.green("\n[Ghost Sync] Live preview applied. Capturing for Vision check...\n")),await new Promise(e=>setTimeout(e,300));const e=await this.portal.captureElementScreenshot();e&&(this.transcript.push({role:"user",content:[{text:"Here is a live screenshot of the element after your PREVIEW_STYLE was applied. Visual check: Does this match the user intent? If yes, finalize the code patch. If not, output a corrected PREVIEW_STYLE or adjust your patch."},{image:{format:"png",source:{bytes:e}}}]}),process.stdout.write(y.cyan("[Vision] Screenshot sent to Agent for verification.\n")))}}catch(e){}process.stdout.write(e)}};try{await this.runSingleTurn(t,i)}catch(e){process.stdout.write(y.red(`\n[Visual AI] Error: ${e.message}\n`))}}}extractComponentName(e,t){if(!e)return"Anonymous";const s=String(t||"").trim(),i=s?s.split(/\s+/)[0]:"";return i?`${e}.${i}`:e}async runCli(e){this.llm.logEndpoint(),await this.checkInit(),this.sessionCapsule=await this.sessionStore.load();try{const e=await u.readFile(this.historyPath,"utf-8");this.persistentHistory=e.split("\n").filter(Boolean).reverse(),this.persistentHistory=e.split("\n").filter(Boolean)}catch{this.persistentHistory=[]}try{const{execFile:e}=await import("node:child_process"),{promisify:t}=await import("node:util"),s=t(e),i=this.config.agent.workspaceRoot,[n,a]=await Promise.allSettled([s("git",["branch","--show-current"],{cwd:i}),s("git",["status","--short"],{cwd:i})]),o="fulfilled"===n.status?n.value.stdout.trim():"",r="fulfilled"===a.status?a.value.stdout.trim():"";o&&(this.currentBranch=o,this.workspaceContext=`Workspace context:\n- Git branch: ${o}\n- Git status:\n${r||"clean"}`)}catch{}try{const e=p.join(this.config.agent.workspaceRoot,".mesh","instructions.md");this.localInstructions=await u.readFile(e,"utf-8")}catch{}if(e?.trim()){const t=await this.tryLocalIntentAnswer(e);if(t)return void await this.renderLocalQuickAnswer(t);const s=await this.runSingleTurn(e);return void f.write(`${s}\n`)}if(this.printBanner(),await this.printStatus(),this.sessionManager.hasInterruptedSession()){const e=this.sessionManager.getInterruptedSession();if(e&&e.length>0){f.write(y.yellow("\n[Session] Found interrupted session from previous run.\n"));const t=new _({name:"resume",message:"Resume previous session?",initial:!0,stdin:g,stdout:f});if(await t.run()){for(const t of e)if("user"===t.role)this.transcript.push({role:"user",content:[{text:t.content}]});else{const e=[{text:t.content}];if(t.toolCalls?.length)for(const s of t.toolCalls)e.push({toolUse:{toolUseId:s.id,name:s.name,input:s.input}});this.transcript.push({role:"assistant",content:e})}f.write(y.green(`[Session] Resumed ${e.length} turns.\n`))}this.sessionManager.clearInterruptedSession()}}let t=0;for(;;){const e=m.createInterface({input:g,output:f,terminal:!0,completer:e=>this.completeInput(e),history:[...this.persistentHistory]});this.setupGhostText(e,g,f),e.on("SIGINT",()=>{if(this.abortController)this.abortController.abort(),this.abortController=null,f.write("\n\n"+y.dim("Request aborted. Returning to prompt.")+"\n");else{const s=Date.now();s-t<2e3?(e.close(),process.exit(0)):(t=s,f.write("\n"+this.themeColor(y.bold("Press Ctrl+C again within 2s to exit"))+"\n"),e.line="",e.write("\n"))}});const i=this.buildPrompt();let n="";try{if(this.voiceMode){f.write(this.themeColor(y.bold("\n[LISTENING]"))+y.dim(" (stops after silence...)\n"));try{const e=await this.voiceManager.record();f.write(y.dim("Transcribing...\n"));const t=await this.voiceManager.transcribe(e);n=t.text,this.syncVoiceLanguage(t.language),f.write(y.bold(`❯ ${n}\n`))}catch(t){f.write(y.red(`Voice error: ${t.message}\n`)),this.voiceMode=!1,e.close();continue}}else n=(await e.question(i)).trim();n&&!n.startsWith("/")&&n!==this.persistentHistory[this.persistentHistory.length-1]&&(this.persistentHistory.push(n),this.persistentHistory.length>1e3&&this.persistentHistory.shift(),await u.writeFile(this.historyPath,this.persistentHistory.join("\n"),"utf-8"))}catch(t){e.close();break}if(!n){e.close();continue}if(this.voiceMode&&this.isVoiceExitCommand(n)){this.voiceMode=!1,this.renderSystemMessage(y.green("Voice mode disabled. Back to text input.")),e.close();continue}if("exit"===n.toLowerCase()||"quit"===n.toLowerCase()){e.close();break}if(n.startsWith("/")){const t=await this.handleSlashCommand(n,e);if(e.close(),t.shouldExit)break;if(t.wasHandled)continue}const a=await this.tryLocalIntentAnswer(n);if(a)e.close(),await this.renderLocalQuickAnswer(a);else{await this.refreshGitStatus();try{const e=this.useAnsi?$({text:"Thinking...",color:"cyan",stream:f}).start():void 0;let t;this.sessionTokens;this.resetToolSummary();try{const i={onToolStart:(t,i,n,a)=>{if(e){const o=`[${n+1}/${a}]`;e.text=`${y.dim(o)} ${y.cyan(t)} ${y.dim(s(i))}`}this.renderToolEvent("start",t,s(i))},onToolEnd:(t,s,i)=>{e&&(e.text=s?`done ${y.cyan(t)}`:`failed ${y.cyan(t)}`),this.renderToolEvent(s?"success":"error",t,i)},onCommandChunk:t=>{e&&(e.stop(),e.clear()),f.write(t)},askPermission:async t=>{e&&e.stop();const s=this.useAnsi?y.yellow(`\n[Action Required]\n${t}\n[y/N/A]: `):`\n[Action Required]\n${t}\n[y/N/A]: `,i=m.createInterface({input:g,output:f}),n=(await i.question(s)).trim().toLowerCase();if(i.close(),"a"===n)return this.autoApproveTools=!0,e&&e.start(),!0;const a="y"===n||"yes"===n;return e&&e.start(),a}};if(this.voiceMode){t=await this.runSingleTurn(n,i);const s=this.sanitizeVoiceAssistantText(t);e&&(e.stop(),e.clear()),this.renderAssistantTurn(s),await this.voiceManager.speak(s,this.getVoiceReplyLanguage()).catch(e=>{this.renderSystemMessage(y.red(`Voice output failed: ${e.message}`))})}else{let s=!1;t=await this.runSingleTurn(n,{...i,onDelta:t=>{e&&(e.stop(),e.clear()),s||(s=!0,f.write("\n"+this.themeColor(y.bold("assistant"))+y.dim(" › ")+"\n")),f.write(t)}}),s?f.write("\n"):t&&this.renderAssistantTurn(t)}}finally{e&&(e.stop(),e.clear())}this.printToolSummary();const i=await this.autoCompactIfNeeded();i&&this.renderSystemMessage(i)}catch(e){this.renderSystemMessage(y.red(`Error: ${e.message}`))}finally{e.close()}}}}async runInit(e=[],t){if(this.llm.logEndpoint(),await this.checkInit(),this.sessionCapsule=await this.sessionStore.load(),f.write(this.themeColor(`\n${y.bold("Mesh Agent - Private Alpha")}\n`)),f.write(y.dim("Thank you for participating in the early access program.\n\n")),void 0===this.config.telemetry.contribute){const e=new _({name:"telemetry",message:"Can we collect anonymous telemetry to help improve Mesh?",initial:!0}),t=Boolean(await e.run().catch(()=>!1)),s=await R();await j({...s,telemetry:t}),this.config.telemetry.contribute=t,f.write(y.dim(t?"Telemetry enabled. Thank you!\n":"Telemetry disabled.\n"))}f.write(this.themeColor(`${y.bold("\nFirst-Run System Check")}\n`)),await this.runDoctor(["fix"]),t&&!await t.restoreAuthenticated()&&(f.write(y.yellow("\n[Mesh] Initial setup complete. Login is required for model access.\n")),await t.ensureAuthenticated(),this.config.bedrock.bearerToken||=t.getAccessToken()),f.write(y.green(y.bold('\n✓ All set! Start by asking: "What can you do here?"\n\n')))}async runDoctorCli(e=[]){this.llm.logEndpoint(),await this.runDoctor(e)}async runHeadlessTurn(e,t){await this.initializeHeadlessSession();const s=e.trim();if(!s)throw new Error("Headless turn requires non-empty input");const i=await this.tryLocalIntentAnswer(s);if(i)return{text:i,modelId:this.currentModelId,usageDelta:{inputTokens:0,outputTokens:0,totalTokens:0},totalUsage:{...this.sessionTokens}};await this.refreshGitStatus(),this.resetToolSummary();const n={...this.sessionTokens};return{text:await this.runSingleTurn(s,{...t,silent:!1,askPermission:t?.askPermission??(async()=>!1)}),modelId:this.currentModelId,usageDelta:{inputTokens:this.sessionTokens.inputTokens-n.inputTokens,outputTokens:this.sessionTokens.outputTokens-n.outputTokens,totalTokens:this.sessionTokens.inputTokens-n.inputTokens+this.sessionTokens.outputTokens-n.outputTokens},totalUsage:{...this.sessionTokens}}}async initializeHeadlessSession(){if(!this.headlessInitialized){await this.checkInit(),this.sessionCapsule=await this.sessionStore.load();try{const e=p.join(this.config.agent.workspaceRoot,".mesh","instructions.md");this.localInstructions=await u.readFile(e,"utf-8")}catch{this.localInstructions=""}this.headlessInitialized=!0}}async runSingleTurn(e,i){const n=i?.silent,a=await this.autoCompactIfNeeded();a&&!n&&this.renderSystemMessage(a),this.pendingPrefetchQueue.length>0&&this.prefetchQueue.push(...this.pendingPrefetchQueue.splice(0));const o=function(e){const s=new Set,i=[];for(const n of e){const e=t(n.name);let a=e,o=2;for(;s.has(a);)a=`${e}_${o}`,o+=1;s.add(a),i.push({wireName:a,tool:n})}return i}(await this.backend.listTools()),r=function(e,t){const s=t.toLowerCase(),i=new Set,n=(...e)=>{for(const t of e)i.add(t)};n("workspace.open_artifact","workspace.ask_codebase","workspace.get_diagnostics","workspace.git_status","workspace.list_files","workspace.list_directory","workspace.semantic_search","workspace.search_files","workspace.grep_ripgrep","workspace.read_file","workspace.get_file_graph","workspace.read_dir_overview","agent.plan"),/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|fehler|beheb|änder|aender|bau|mach)/i.test(s)&&n("workspace.write_file","workspace.patch_file","workspace.patch_surgical","workspace.run_command","workspace.read_file_raw","workspace.read_multiple_files","workspace.validate_patch","workspace.git_diff","workspace.impact_map","workspace.company_brain","workspace.explain_symbol","workspace.list_symbols","workspace.finalize_task"),/(dashboard|ui|frontend|browser|screenshot|inspect|visual|react|css|html)/i.test(s)&&n("web.inspect_ui","frontend.preview","workspace.trace_symbol","workspace.expand_execution_path"),/(runtime|crash|exception|stack|trace|debug|hologram|server|request|autopsy)/i.test(s)&&n("workspace.run_with_telemetry","runtime.start","runtime.capture_failure","runtime.capture_deep_autopsy","runtime.trace_request","runtime.explain_failure","runtime.fix_failure"),/(offene probleme|problem|bug|issue|ticket|pr|pull request|risk|risiko|audit|review|diagnos|causal|lab|repair|twin|ghost|fork|intent|memory|brain|cockpit)/i.test(s)&&n("workspace.digital_twin","workspace.predictive_repair","workspace.engineering_memory","workspace.company_brain","workspace.issue_autopilot","workspace.production_readiness","workspace.model_route","workspace.intent_compile","workspace.cockpit_snapshot","workspace.causal_intelligence","workspace.discovery_lab","workspace.reality_fork","workspace.ghost_engineer"),/(timeline|race|future|fork|parallel|promote|merge|swarm|agent)/i.test(s)&&n("workspace.timeline_create","workspace.timeline_apply_patch","workspace.timeline_run","workspace.timeline_compare","workspace.timeline_promote","workspace.timeline_list","agent.race_fixes","agent.spawn","agent.review","agent.merge_verified","agent.status");const a=e.filter(({tool:e})=>i.has(e.name));return a.length>0?a:e.slice(0,16)}(o,e);this.currentTurnPreferredTools=r.map(e=>e.tool.name);const c=function(e){return e.map(({wireName:e,tool:t})=>({name:e,description:t.description??"",inputSchema:t.inputSchema??{type:"object",properties:{}}}))}(o),l=new Map(o.map(e=>[e.wireName,e])),u=this.transcript.length;this.currentTurnRouteContext=await this.buildTurnRouteContext(e).catch(()=>null),this.transcript.push({role:"user",content:[{text:e}]}),this.sessionManager.addMessage("user",e);let h="";this.abortController=new AbortController;const p=this.maxStepsForInput(e),m=this.toolBudgetForInput(e),g=this.maxTokensForInput(e);let w=0;const k=new Set,v=new Map,b=!this.useAnsi||n||i?void 0:$({text:"Thinking...",color:"cyan",stream:f}).start();try{for(let e=0;e<p;e+=1){let t;if(i?.onDelta&&!this.streamingUnavailable){let e="";const s=[];try{const a=this.prepareModelInput(u,c),o=this.llm.converseStream(a.messages,a.tools,a.systemPromptArray,this.currentModelId,this.abortController.signal,g);for await(const t of o)"text"===t.kind&&t.text?(e+=t.text,n||i.onDelta(t.text)):"tool_use"===t.kind?s.push(t.toolUse):"stop"===t.kind&&t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0);t=s.length>0?{kind:"tool_use",toolUses:s.map(e=>({toolUseId:e.toolUseId,name:e.name,input:e.input??{}})),text:e||void 0,stopReason:"tool_use"}:{kind:"text",text:e,stopReason:"end_turn"}}catch(e){if(!d(e instanceof Error?e.message:String(e)))throw e;this.streamingUnavailable=!0;const s=this.prepareModelInput(u,c);t=await this.llm.converse(s.messages,s.tools,s.systemPromptArray,this.currentModelId,this.abortController.signal,g),t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0),t.text&&i.onDelta(t.text)}}else{const e=this.prepareModelInput(u,c);t=await this.llm.converse(e.messages,e.tools,e.systemPromptArray,this.currentModelId,this.abortController.signal,g),t.usage&&(this.sessionTokens.inputTokens+=t.usage.inputTokens??0,this.sessionTokens.outputTokens+=t.usage.outputTokens??0),i?.onDelta&&t.text&&i.onDelta(t.text)}if("text"===t.kind)return this.transcript.push({role:"assistant",content:[{text:t.text}]}),this.sessionManager.addMessage("assistant",t.text||""),t.text||h||"(no answer)";h=t.text??h;const a=[];t.text&&a.push({text:t.text});for(const e of t.toolUses)a.push({toolUse:{toolUseId:e.toolUseId,name:e.name,input:e.input}});this.transcript.push({role:"assistant",content:a}),this.sessionManager.addMessage("assistant",t.text||"",t.toolUses.map(e=>({id:e.toolUseId,name:e.name,input:e.input})));const o=new Map;for(const e of t.toolUses){const t=l.get(e.name);if(t)if(n)o.set(e.toolUseId,!0);else if(t.tool.requiresApproval&&!this.autoApproveTools){const s=this.buildApprovalPreview(t.tool.name,e.input),n=!i?.askPermission||!await i.askPermission(s);o.set(e.toolUseId,!n)}else o.set(e.toolUseId,!0);else o.set(e.toolUseId,!1)}const r=t.toolUses.map(e=>{const t=w<m;return w+=1,{tu:e,allowed:t}}),f=await Promise.all(r.map(async({tu:t,allowed:a})=>{const r=l.get(t.name),c=`${t.name}:${JSON.stringify(t.input)}`,d=this.toolFamilyFor(t.name);if(!a)return{toolUseId:t.toolUseId,status:"error",text:"Tool budget reached for this turn. Stop using tools and answer with the evidence already gathered."};if(k.has(c))return{toolUseId:t.toolUseId,status:"error",text:"Duplicate tool call blocked by Mesh Stop-Law. Use existing evidence or ask for a narrower artifact slice."};k.add(c);const u=v.get(d)??0;if(u>=("read"===d?4:"search"===d?3:2)&&"workspace_open_artifact"!==t.name)return{toolUseId:t.toolUseId,status:"error",text:`Repeated ${d} tools blocked by Mesh Stop-Law. Stop tool use and answer from gathered evidence.`};if(v.set(d,u+1),!r)return{toolUseId:t.toolUseId,status:"error",text:`Tool '${t.name}' is not available.`};if(!o.get(t.toolUseId))return{toolUseId:t.toolUseId,status:"error",text:"Tool requires interactive approval but no TTY is available."};if(this.emitPulse("tool_start",t.input.path,t.name),!n){if(b){const i=`[${e+1}/${p}]`;b.text=`${y.dim(i)} ${y.cyan(t.name)} ${y.dim(s(t.input))}`}i?.onToolStart?.(t.name,t.input,e,p)}try{if(("workspace.write_file"===r.tool.name||"workspace.patch_file"===r.tool.name||"workspace.alien_patch"===r.tool.name)&&this.transcript.length>=10){const e=`CRITICAL PRE-FLIGHT CHECK: You are about to modify a file (${t.input.path||"unknown"}). Based on the long context history, is there any contradictory fact or limitation that makes this edit unsafe or incorrect? Reply with ONLY 'SAFE' or 'UNSAFE: [reason]'.`;try{const s=await this.llm.converse([{role:"user",content:[{text:e}]}],[],"You are a Fact Verification Module."),i="text"===s.kind?s.text.trim().toUpperCase():"";if(i.startsWith("UNSAFE"))return!n&&b&&b.fail(y.red(`Fact Verification Blocked Edit: ${i}`)),{toolUseId:t.toolUseId,status:"error",text:`Fact Verification Pre-flight failed: ${i}`}}catch(e){}}const e=await this.backend.callTool(r.tool.name,t.input,{onProgress:n?void 0:i?.onCommandChunk});if("workspace.read_file"===r.tool.name||"workspace.expand_execution_path"===r.tool.name){const e=String(t.input.path??"");e&&(async()=>{const t=await this.backend.callTool("workspace.get_file_graph",{path:e}).catch(()=>null);t?.ok&&t.dependencies&&(await Promise.all(t.dependencies.slice(0,2).map(async e=>{const t=await this.backend.callTool("workspace.read_file",{path:e,tier:"low"}).catch(()=>null),s=t?.capsule??t?.content;s&&this.pendingPrefetchQueue.push(`File: ${e}\n${s}`)})),this.pendingPrefetchQueue.length>6&&(this.pendingPrefetchQueue=this.pendingPrefetchQueue.slice(-6)))})().catch(()=>{})}const s="workspace.open_artifact"===r.tool.name?this.clampToolResultText(r.tool.name,[`Tool called: ${r.tool.name}`,`Arguments: ${JSON.stringify(t.input)}`,`Result: ${JSON.stringify(e)}`].join("\n")):await this.buildToolEnvelopeText(r.tool.name,t.input,e);return n||i?.onToolEnd?.(t.name,!0,this.normalizeCapsuleLine(s,120)),this.consecutiveErrors.delete(c),{toolUseId:t.toolUseId,status:"success",text:s}}catch(e){const s=e.message,a=`${c} -> ${s}`,o=(this.consecutiveErrors.get(a)||0)+1;this.consecutiveErrors.set(a,o);const l=r.tool.name;let d="Try /doctor to diagnose.";s.includes("ENOENT")||s.includes("no such file")?d="Check that the file path exists, or run /index to rebuild workspace state.":s.includes("EACCES")||s.includes("permission denied")?d="Check file permissions with your OS.":(s.includes("timed out")||s.includes("AbortError"))&&(d="The operation timed out — try /compact to reduce context.");let u=`[Mesh] Error: ${l} failed — ${s.slice(0,200)}. ${d}`;return o>=2&&(u+="\n\n[MESH SYSTEM WARNING] This exact error has occurred multiple times. DO NOT retry the same action. Either try a different approach or stop and ask the user for clarification."),n||i?.onToolEnd?.(t.name,!1,this.normalizeCapsuleLine(u,120)),{toolUseId:t.toolUseId,status:"error",text:this.clampToolResultText(r.tool.name,u)}}}));this.transcript.push({role:"user",content:f.map(e=>({toolResult:{toolUseId:e.toolUseId,status:e.status,content:[{text:e.text}]}}))})}}catch(e){if(this.transcript=this.transcript.slice(0,u),"AbortError"===e.name||e.message?.includes("aborted"))return h||"Request aborted.";throw e}finally{b&&(b.stop(),b.clear()),this.abortController=null,this.currentTurnRouteContext=null,this.currentTurnPreferredTools=[]}return await this.forceFinalAnswer(h,u,c)}prepareModelInput(e,t){const s=V,i=[this.buildDynamicRuntimeContext(),this.currentTurnRouteContext].filter(Boolean).join("\n\n"),n=this.contextAssembler.assemble({transcript:this.transcript,currentTurnStart:e,tools:t,systemPrompt:s,sessionSummary:this.sessionCapsule?.summary??null,runtimeContext:i});if(this.lastContextReport=n.report,this.turnContextReports.push(n.report),n.report.totalTokens>n.report.maxInputTokens)throw new Error(`Context firewall blocked oversized request (${n.report.totalTokens}/${n.report.maxInputTokens} estimated tokens). Narrow the request or run /clear.`);return{messages:n.messages,tools:n.tools,systemPromptArray:n.systemPromptArray,report:n.report}}async forceFinalAnswer(e,t,s){const i=["Stop using tools now.","Answer the user with the evidence already gathered.","Be concise. If evidence is incomplete, say what is missing in one sentence."].join(" ");this.transcript.push({role:"user",content:[{text:i}]});const n=this.prepareModelInput(t,s),a=await this.llm.converse(n.messages,n.tools,n.systemPromptArray,this.currentModelId,this.abortController?.signal);a.usage&&(this.sessionTokens.inputTokens+=a.usage.inputTokens??0,this.sessionTokens.outputTokens+=a.usage.outputTokens??0);const o=a.text||e||"Kein belastbarer Befund.";return this.transcript.push({role:"assistant",content:[{text:o}]}),o}maxStepsForInput(e){const t=e.toLowerCase();return this.isSimpleLocalCandidate(e)?1:/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|beheb|änder|aender|bau|mach)/i.test(t)?Math.min(this.dynamicMaxSteps,4):/(runtime|crash|exception|stack|trace|debug|server|request|diagnos)/i.test(t)?Math.min(this.dynamicMaxSteps,3):(/(offene probleme|problem.*code|bug|bugs|issue|issues|diagnos|risiko|risk|audit|review|siehst du|findest du)/i.test(t),Math.min(this.dynamicMaxSteps,2))}toolBudgetForInput(e){const t=e.toLowerCase();return this.isSimpleLocalCandidate(e)?0:/(fix|edit|change|patch|implement|build|add|remove|refactor|commit|test|run|execute|beheb|änder|aender|bau|mach)/i.test(t)?10:/(runtime|crash|exception|stack|trace|debug|server|request|diagnos)/i.test(t)?6:/(offene probleme|problem.*code|bug|bugs|issue|issues|diagnos|risiko|risk|audit|review|siehst du|findest du)/i.test(t)?5:3}maxTokensForInput(e){const t=e.toLowerCase();return/(fix|edit|change|patch|implement|build|add|remove|refactor|write|commit|beheb|änder|aender|bau|mach)/i.test(t)?4096:/(list|read|grep|search|find|show|status|explain|summarize|zeige|lies|suche|liste)/i.test(t)?800:this.config.bedrock.maxTokens}toolFamilyFor(e){const t=e.replace(/_/g,".");return/read|open.artifact|expand/.test(t)?"read":/search|grep|ask.codebase|list/.test(t)?"search":/diagnostic|repair|causal|lab|twin|ghost|cockpit/.test(t)?"analysis":/write|patch|move|delete|run|timeline|agent/.test(t)?"action":"other"}clampToolResultText(e,t){const s=/read_file_raw|read_multiple_files|grep|ask_codebase|causal|discovery/i.test(e)?5e3:3500;return t.length<=s?t:`${t.slice(0,s)}\n\n[truncated ${t.length-s} chars; answer from available evidence or request a narrower read]`}async buildToolEnvelopeText(e,t,s){const i=await this.artifactStore.saveToolResult(e,t,s),n=this.artifactStore.buildEnvelopeText(i,s);return this.turnArtifactCharsStored+=i.originalChars,this.turnArtifactEnvelopeChars+=n.length,this.clampToolResultText(e,n)}buildApprovalPreview(e,t){if("workspace.write_file"===e){const e=String(t.path??"?"),s=String(t.content??"").split("\n").slice(0,10).join("\n");return`write_file → ${e}\n${y.dim("────────────────────")}\n${s}${String(t.content??"").split("\n").length>10?"\n…":""}`}if("workspace.patch_file"===e){const e=String(t.path??"?"),s=String(t.search??"").split("\n").slice(0,4).join("\n"),i=String(t.replace??"").split("\n").slice(0,4).join("\n");return`patch_file → ${e}\n${y.red("--- "+s)}\n${y.green("+++ "+i)}`}if("workspace.patch_surgical"===e){const e=String(t.path??"?"),s=String(t.searchBlock??"").split("\n").slice(0,6).join("\n"),i=String(t.replaceBlock??"").split("\n").slice(0,6).join("\n");return`patch_surgical → ${e}\n${y.red("SEARCH:\n"+s)}${String(t.searchBlock??"").split("\n").length>6?"\n…":""}\n${y.green("REPLACE:\n"+i)}${String(t.replaceBlock??"").split("\n").length>6?"\n…":""}`}return"workspace.run_command"===e?`run_command\n$ ${y.bold(String(t.command??"?"))}`:"workspace.delete_file"===e?`delete_file → ${y.red(String(t.path??"?"))}`:"workspace.move_file"===e?`move_file ${String(t.sourcePath??"?")} → ${String(t.destinationPath??"?")}`:`Allow ${e} to run?`}isSimpleLocalCandidate(e){const t=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");return/^(hi|hello|hey|hallo|servus|moin|guten morgen|guten tag|guten abend|wie gehts|wie geht es dir|alles gut|na wie gehts|how are you|how is it going|bist du da|da|online|ready|bereit|danke|thx|thanks|merci|dankeschoen|dankeschön|ok|okay|alles klar|passt|verstanden|got it|was kannst du|help|hilfe)$/.test(t)}async tryLocalIntentAnswer(e){const t=this.getLocalQuickAnswer(e);if(t)return t;const s=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");if(/^(status|repo status|git status|wie ist der status|was ist der status)$/.test(s)){const[e,t]=await Promise.allSettled([this.backend.callTool("workspace.git_status",{}),this.backend.callTool("workspace.get_index_status",{})]),s="fulfilled"===e.status?e.value:null,i="fulfilled"===t.status?t.value:null,n=s?.branch?`branch ${s.branch}`:"branch unbekannt",a=s?.status?String(s.status).split(/\r?\n/g).filter(Boolean).length:0;return`${n}. ${a?`${a} offene Dateiänderungen`:"Working tree sauber"}. ${null!=i?.cachedFiles&&null!=i?.totalFiles?`index ${i.cachedFiles}/${i.totalFiles}`:"index unbekannt"}.`}if(/^(welcher branch|branch|git branch)$/.test(s)){const e=await this.backend.callTool("workspace.git_status",{}).catch(()=>null);return e?.branch?`Branch: ${e.branch}.`:"Branch unbekannt."}if(/^(token status|tokens|kosten|cost|context status|context)$/.test(s)){const e=this.peakContextReport();return e?`Letzter Kontext: ca. ${o(e.totalTokens)}/${o(e.maxInputTokens)} Tokens, Tools ${e.toolsOut}/${e.toolsIn}, Messages ${e.messagesOut}/${e.messagesIn}.`:"Noch kein Modell-Call in diesem Turn."}return null}async buildTurnRouteContext(e){if(!this.shouldAttachRepoRouteContext(e))return null;const t=this.inferIndexMode(e),[s,i]=await Promise.allSettled([this.backend.callTool("workspace.ask_codebase",{query:e,mode:t,limit:5}),this.backend.callTool("workspace.git_status",{})]),n=["Purpose: pre-routed local index context. Prefer these refs before more search tools.",`Query mode: ${t}`],o=A(e);if(n.push(`Model route: ${o.taskType} confidence=${o.confidence} primary=${o.primaryChatModel}`,`Required gates: ${o.requiredGates.join(", ")}`),"fulfilled"===s.status){const e=s.value,t=Array.isArray(e?.topMatches)?e.topMatches:[];if(t.length>0){n.push("Likely relevant files:");for(const e of t.slice(0,5))n.push(`- ${e.path} :: ${a(String(e.snippet??""),160)}`)}e?.indexStatus&&n.push(`Index: ${e.indexStatus.cachedFiles}/${e.indexStatus.totalFiles} fresh (${e.indexStatus.percent}%)`)}if("fulfilled"===i.status){const e=i.value;e?.branch&&n.push(`Git branch: ${e.branch}`),e?.status&&n.push(`Dirty files: ${String(e.status).split(/\r?\n/g).filter(Boolean).slice(0,8).join("; ")}`)}return n.length>2?n.join("\n"):null}shouldAttachRepoRouteContext(e){return!this.isSimpleLocalCandidate(e)&&/(code|file|datei|src\/|test|bug|fix|edit|patch|implement|build|dashboard|graph|crash|fehler|problem|repo|commit|push|package|json|ts|js|css|html|api|tool|token|context|performance|diagnos|review|audit)/i.test(e)}inferIndexMode(e){return/(bug|fehler|crash|exception|diagnos|risk|risiko|problem)/i.test(e)?"bug":/(test|spec|coverage|verify|prüf|pruef)/i.test(e)?"test-impact":/(edit|patch|change|änder|aender|refactor|implement|mach|fix)/i.test(e)?"edit-impact":/(route|request|server|runtime|api)/i.test(e)?"runtime-path":/(commit|history|changed|dirty|recent)/i.test(e)?"recent-change":"architecture"}getLocalQuickAnswer(e){const t=e.trim().toLowerCase().replace(/[!?.\s]+$/g,"");return/^(hi|hello|hey|hallo|servus|moin|guten morgen|guten tag|guten abend)$/.test(t)?"Bin da.":/^(wie gehts|wie geht es dir|alles gut|na wie gehts|how are you|how is it going)$/.test(t)?"Läuft.":/^(bist du da|da|online|ready|bereit)$/.test(t)?"Ja.":/^(danke|thx|thanks|merci|dankeschoen|dankeschön)$/.test(t)?"Gerne.":/^(ok|okay|alles klar|passt|verstanden|got it)$/.test(t)?"Ok.":/^(was kannst du|help|hilfe)$/.test(t)?"Kurz: Code lesen, ändern, testen, Git/Dashboard/Diagnose lokal steuern. Frag direkt nach der Aufgabe.":null}async renderLocalQuickAnswer(e){const t=this.useAnsi?$({text:"Thinking...",color:"cyan",stream:f}).start():null;await new Promise(e=>setTimeout(e,260+Math.floor(180*Math.random()))),t&&(t.stop(),t.clear()),this.renderAssistantTurn(e)}printBanner(){const e=f.columns||80,t="═".repeat(e),s=[{mesh:"███╗ ███╗███████╗███████╗██╗ ██╗",left:" ▄██ ",right:" ██▄ "},{mesh:"████╗ ████║██╔════╝██╔════╝██║ ██║",left:" ▄██▀ ",right:" ▀██▄ "},{mesh:"██╔████╔██║█████╗ ███████╗███████║",left:"▄██▀ ",right:" ▀██▄"},{mesh:"██║╚██╔╝██║██╔══╝ ╚════██║██╔══██║",left:"▀██▄ ",right:" ▄██▀"},{mesh:"██║ ╚═╝ ██║███████╗███████║██║ ██║",left:" ▀██▄ ",right:" ▄██▀ "},{mesh:"╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝",left:" ▀██ ",right:" ██▀ "}],n=" ",a=" ",o=this.config.agent.accentColor||"magenta",r=y,c="function"==typeof r[o]?r[o]:y.magenta,l=[`mesh ${this.config.agent.mode} ${D(this.config.agent.workspaceRoot)}`,`branch: ${this.currentBranch} model: ${i(this.currentModelId)}`,"commands: /help for groups, /dashboard for local repo UI, /exit to quit","tip: Ask normal questions directly; slash commands are shortcuts"];if(!this.useAnsi)return f.write("\n"+t+"\n"),f.write(s.map(e=>e.mesh+n+e.left+a+e.right).join("\n")+"\n"),void f.write(l.join("\n")+"\n");f.write("\n"+this.themeColor(t)+"\n"),f.write(s.map(e=>this.themeColor(y.bold(e.mesh+n+e.left))+a+c(y.bold(e.right))).join("\n")+"\n"),f.write([`${this.themeColor(y.bold("mesh"))} ${y.dim(this.config.agent.mode)} ${y.dim(D(this.config.agent.workspaceRoot))}`,`${y.dim("branch:")} ${this.themeColor(this.currentBranch)} ${y.dim("model:")} ${this.themeColor(i(this.currentModelId))}`,`${y.dim("commands:")} ${y.magenta("/help")} ${y.dim("for groups")} ${y.magenta("/dashboard")} ${y.dim("for local repo UI")} ${y.magenta("/exit")}`,`${y.dim("tip:")} ${y.dim("Ask normal questions directly; slash commands are shortcuts")}`].join("\n")+"\n"),f.write(this.themeColor(t)+"\n")}buildPrompt(){if(!this.useAnsi)return`\n${y.cyan("◈")} ${y.bold("mesh")} // ${y.dim(this.currentBranch)} ${y.cyan("›")} `;const e=Math.max(48,Math.min(f.columns||80,140)),t=` mesh/${this.currentBranch} `,s=e-3-t.length,i=s>0?"─".repeat(s):"",n=`${this.themeColor("───")}${y.white(y.bold(t))}${this.themeColor(i)}`,a=`${this.themeColor("❯")} `;return`\n${n}\n${this.buildSessionStatsLine()}${a}`}buildSessionStatsLine(){const e=this.sessionTokens.inputTokens,t=this.sessionTokens.outputTokens;if(0===e&&0===t)return"";const s=J.find(e=>this.currentModelId.includes(e.value)||e.value.includes(this.currentModelId)),{inputPer1k:i,outputPer1k:n}=s?.pricing??{inputPer1k:.003,outputPer1k:.015},a=e*i/1e3+t*n/1e3,r=this.lastContextReport,c=r?` · ctx ${o(r.totalTokens)}/${o(r.maxInputTokens)}`:"",l=this.sessionRawSaved>0?` · saved ~${o(Math.ceil(this.sessionRawSaved/4))}`:"";return y.dim(`↑${o(e)} ↓${o(t)} · $${a.toFixed(4)}${c}${l}\n`)}async printSync(){const e=await this.backend.callTool("workspace.check_sync",{});e.l2Enabled?f.write(["",`${this.themeColor(y.bold("Cloud Sync Status"))}`,`${y.dim("L2 Capsules:")} ${y.green(e.l2Count)}`,`${y.dim("L2 Status:")} ${y.green("Connected")}`,""].join("\n")):f.write(y.yellow("\nCloud (L2) cache is disabled. Enable it in /setup.\n"))}async printStatusLine(){const e=this.config.bedrock.modelId.split(".").pop()?.split(":")[0]||"unknown",t=this.turnContextReports.length,s=this.sessionTokens.inputTokens+this.sessionTokens.outputTokens,i=s>1e3?`${(s/1e3).toFixed(1)}k`:`${s}`;let n="0k";const a=this.turnContextReports[this.turnContextReports.length-1];if(a){const e=a.totalTokens;n=e>1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}f.write(y.dim(`[Mesh] Model: ${y.cyan(e)} | Turns: ${y.cyan(t)} | Context: ${y.cyan(n)} | Usage: ${y.yellow(i)} tk`)+"\n")}async printStatus(){const e=await this.backend.callTool("workspace.get_index_status",{}),t=this.estimateTranscriptChars();f.write(["",`${y.dim("mode:")} ${this.config.agent.mode}`,`${y.dim("workspace:")} ${D(this.config.agent.workspaceRoot)}`,`${y.dim("model:")} ${this.currentModelId}`,`${y.dim("cloud:")} ${this.config.agent.enableCloudCache?y.green("on"):y.red("off")}`,`${y.dim("index:")} ${e.cachedFiles}/${e.totalFiles} files cached (${e.percent}%)`,`${y.dim("session:")} ${this.transcript.length} messages / ${t} chars`,`${y.dim("capsule:")} ${this.sessionCapsule?y.green(`active (${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages})`):y.dim("none")}`,""].join("\n"))}emitPulse(e,t,s){const i={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,path:t,msg:s,at:(new Date).toISOString()};this.dashboardEventWrite=this.dashboardEventWrite.then(()=>this.appendDashboardEvent(i)).catch(()=>{})}startDashboardActionPump(){if(this.dashboardActionTimer)return;const e=async()=>{await this.processDashboardActions(),this.dashboardActionTimer=setTimeout(()=>{e()},900),this.dashboardActionTimer.unref()};this.dashboardActionTimer=setTimeout(()=>{e()},0),this.dashboardActionTimer.unref()}getDashboardActionsPath(){return p.join(this.getDashboardDir(),"actions.json")}async processDashboardActions(){if(!this.dashboardActionRunning){this.dashboardActionRunning=!0;try{const e=await this.readDashboardActions(),t=e.map(e=>e.status).lastIndexOf("pending");if(t<0)return;const s={...e[t],status:"running",startedAt:(new Date).toISOString()};e[t]=s,await this.writeDashboardActions(e),await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`running ${s.action}`,at:(new Date).toISOString()});try{const i=await this.executeDashboardAction(String(s.action));e[t]={...s,status:"done",finishedAt:(new Date).toISOString(),result:i},await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`done ${s.action}`,at:(new Date).toISOString()})}catch(i){e[t]={...s,status:"error",finishedAt:(new Date).toISOString(),error:i.message},await this.appendDashboardEvent({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:"dashboard_action",msg:`failed ${s.action}`,at:(new Date).toISOString()})}await this.writeDashboardActions(e.slice(0,100))}finally{this.dashboardActionRunning=!1}}}async executeDashboardAction(e){switch(e){case"repair":return await this.backend.callTool("workspace.predictive_repair",{action:"analyze"});case"causal":return await this.backend.callTool("workspace.causal_intelligence",{action:"build"});case"lab":return await this.backend.callTool("workspace.discovery_lab",{action:"run"});case"twin":return await this.backend.callTool("workspace.digital_twin",{action:"build"});case"ghost_learn":return await this.backend.callTool("workspace.ghost_engineer",{action:"learn"});default:throw new Error(`Unsupported dashboard action: ${e}`)}}async readDashboardActions(){const e=await u.readFile(this.getDashboardActionsPath(),"utf8").catch(()=>"");if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}async writeDashboardActions(e){const t=this.getDashboardActionsPath();await u.mkdir(p.dirname(t),{recursive:!0}),await u.writeFile(t,JSON.stringify(e,null,2),"utf8")}async runSetup(e){f.write(this.themeColor("\n"+"═".repeat(40)+"\n")),f.write(this.themeColor(y.bold(" MESH SETUP WIZARD\n"))),f.write(this.themeColor("═".repeat(40)+"\n"));const t=await R();try{const s=J.map(e=>({name:e.value,message:`${y.bold(e.label)} ${y.dim(e.note)}`,hint:e.value===t.modelId?y.green("(current)"):y.dim(e.value)})),i=new E({name:"modelId",message:"Select Default Model",choices:s,initial:J.findIndex(e=>e.value===t.modelId),stdin:g,stdout:f}),n=await i.run();e.resume();const a=new _({name:"enableCloudCache",message:"Enable Cloud (L2) Sync?",initial:t.enableCloudCache,stdin:g,stdout:f}),o=await a.run();e.resume();const r=Array.from(Y).map(e=>({name:e,message:e,hint:e===t.themeColor?y.green("(current)"):""})),c=new E({name:"themeColor",message:"Select Theme Color",choices:r,initial:Array.from(Y).indexOf(t.themeColor),stdin:g,stdout:f}),l=await c.run();e.resume();const d=new M({name:"customApiKey",message:"Custom API Key (Enter to keep current, '-' to clear)",initial:"",stdin:g,stdout:f}),u=await d.run();e.resume();const h=""===u?t.customApiKey:"-"===u?void 0:u,p=[{name:"proxy",message:`${y.bold("Mesh shared proxy")} ${y.dim("(recommended — no API key needed)")}`},{name:"own",message:`${y.bold("My own Google API key")} ${y.dim("(direct to Google Gemini)")}`}],m=new E({name:"googleKeyMode",message:"How should Mesh call the AI?",choices:p,initial:"own"===t.googleKeyMode?1:0,stdin:g,stdout:f}),w=await m.run();e.resume();let $=t.ownGoogleApiKey;if("own"===w){const s=new M({name:"ownGoogleApiKey",message:"Google API Key (Enter to keep current, '-' to clear)",initial:"",stdin:g,stdout:f}),i=await s.run();e.resume(),$=""===i?t.ownGoogleApiKey:"-"===i?void 0:i}const k=await this.runVoiceSetupWizard(e,t.voice);if(!k)return void f.write(y.dim("\nSetup cancelled.\n"));const v={modelId:n,enableCloudCache:o,themeColor:l,customApiKey:h,customEndpoint:t.customEndpoint,googleKeyMode:w,ownGoogleApiKey:$,voice:k};await j(v),this.currentModelId=n;const b=y[l];"function"==typeof b&&(this.themeColor=b),this.config.agent.enableCloudCache=o,this.config.agent.themeColor=l,this.config.bedrock.ownGoogleApiKey=$,this.config.bedrock.googleApiKey="own"===w&&$||void 0,this.rebuildLlmClient(),this.applyVoiceSettings(k),f.write(y.green("\n✔ Settings saved and applied!\n")),f.write(this.useAnsi?"":"\n"),this.printBanner(),await this.printStatus()}catch{f.write(y.dim("\nSetup cancelled.\n"))}}async runVoiceSetupWizard(e,t){try{const s=new E({name:"voiceLanguage",message:"Voice language",choices:G.map(e=>({name:e.name,message:e.message,hint:e.name===t.language?y.green("(current)"):y.dim(e.hint)})),initial:Math.max(0,G.findIndex(e=>e.name===t.language)),stdin:g,stdout:f}),i=await s.run();e.resume();const n=this.voiceManager.listAudioInputDevices(),a=[{name:"default",message:"Default microphone",hint:"default"===t.microphone?y.green("(current)"):y.dim("Use system default input")},...n.map(e=>({name:e.id,message:`${e.name} ${y.dim(`#${e.id}`)}`,hint:e.id===t.microphone?y.green("(current)"):y.dim("Specific audio input")}))],o=new E({name:"voiceMicrophone",message:"Microphone",choices:a,initial:Math.max(0,a.findIndex(e=>e.name===t.microphone)),stdin:g,stdout:f}),r=await o.run();e.resume();const c=B.map(e=>({name:e.name,message:e.message,hint:e.name===t.voice?y.green("(current)"):y.dim(e.hint)})),l=new E({name:"voiceName",message:"Gemini voice",choices:c,initial:Math.max(0,c.findIndex(e=>e.name===t.voice)),stdin:g,stdout:f}),d=await l.run();return e.resume(),this.setupGhostText(e,g,f),{configured:!0,language:i,speed:t.speed,voice:d,microphone:r}}catch{return e.resume(),this.setupGhostText(e,g,f),null}}async checkInit(){const e=p.join(this.config.agent.workspaceRoot,".mesh"),t=p.join(e,"workspace.json"),s=await u.access(e).then(()=>!0).catch(()=>!1),i=await u.access(t).then(()=>!0).catch(()=>!1);if(!s){await u.mkdir(e,{recursive:!0}),await u.mkdir(p.join(e,"index"),{recursive:!0}),await u.mkdir(p.join(e,"history"),{recursive:!0});const t=["# Mesh Project Instructions 🛸","","This file defines the engineering soul of this project.","","## 🧠 System Architecture & Intelligence","* **Capsule Cache:** All transient file summaries (L1 Cache) are stored outside this repository.","* **Project Intelligence:** The `.mesh/` folder contains high-level artifacts.","","## 📏 Coding Standards","1. **DRY & KISS:** Favor simplicity over clever abstractions.","2. **Type Safety:** Strive for 100% type coverage.","3. **Mesh Optimization:** Use `patch_file` for small changes.",""].join("\n");await u.writeFile(p.join(e,"instructions.md"),t),await u.writeFile(p.join(e,"architecture.md"),"# Architecture\n\n*Generated during indexing...*"),await u.writeFile(p.join(e,"dependency_graph.md"),"# Dependency Graph\n\n*Generated during indexing...*")}const n=p.join(e,"config.json");let a={};try{const e=await u.readFile(n,"utf-8");a=JSON.parse(e)}catch{}const o={...a,modelId:this.config.bedrock.modelId,themeColor:this.config.agent.themeColor,enableCloudCache:this.config.agent.enableCloudCache,voice:this.config.agent.voice,updatedAt:(new Date).toISOString()};if(await u.writeFile(n,JSON.stringify(o,null,2)),!i){f.write(`${y.cyan("◈")} ${y.bold("New workspace detected. Initializing intelligence...")}\n`),await this.runIndexing();const e={firstIndexedAt:(new Date).toISOString(),lastIndexedAt:(new Date).toISOString(),status:"indexed"};await u.writeFile(t,JSON.stringify(e,null,2))}}async runIndexing(){if(!this.backend.indexEverything)return void f.write(y.red("\nIndexing is only available in local mode.\n"));const e=$({text:"Scanning workspace...",color:"cyan"}).start();try{for await(const t of this.backend.indexEverything())e.text=`Indexing [${t.current}/${t.total}] ${y.dim(t.path)}`;e.succeed(y.green("Workspace indexed successfully."))}catch(t){e.fail(y.red(`Indexing failed: ${t.message}`))}}async getWorkspaceIndexStatus(){try{return await this.backend.callTool("workspace.get_index_status",{})}catch{return null}}async runStart(e=[],t){const s=e.includes("fix")||e.includes("--fix"),i=e.includes("reindex")||e.includes("--reindex");f.write(this.themeColor(`\n${y.bold("Mesh Start")}\n`));const n=await R();if(!n.googleKeyMode&&t){f.write(y.dim("\nFirst-time setup: how should Mesh call the AI?\n\n"));try{const e=[{name:"proxy",message:`${y.bold("Mesh shared proxy")} ${y.dim("(recommended — no API key needed)")}`},{name:"own",message:`${y.bold("My own Google API key")} ${y.dim("(direct to Google Gemini)")}`}],s=new E({name:"googleKeyMode",message:"How should Mesh call the AI?",choices:e,initial:0,stdin:g,stdout:f}),i=await s.run();let a;if(t.resume(),"own"===i){const e=new M({name:"ownGoogleApiKey",message:"Google API Key",initial:"",stdin:g,stdout:f}),s=await e.run();t.resume(),a=s?.trim()||void 0}await j({...n,googleKeyMode:i,ownGoogleApiKey:a}),this.config.bedrock.ownGoogleApiKey=a,this.config.bedrock.googleApiKey="own"===i?a:void 0,this.rebuildLlmClient(),f.write(y.green(`\n✔ Using ${"own"===i?"your own Google API key":"Mesh shared proxy"}.\n`))}catch{f.write(y.dim("\nSkipped API key setup — using Mesh shared proxy.\n")),await j({...n,googleKeyMode:"proxy"})}}await this.runDoctor(s?["brief","fix"]:["brief"]);const a=await this.getWorkspaceIndexStatus(),o=Number.parseFloat(String(a?.percent??"0"));i||!Number.isFinite(o)||o<100?await this.runIndexing():f.write(y.green(`Workspace index already fresh enough (${a?.percent??"100"}%).\n`)),await this.printStatus(),await this.printFirstRunRepoSummary()}async printFirstRunRepoSummary(){const e=$({text:"Building first repo briefing...",color:"cyan"}).start();try{const t=await this.backend.callTool("workspace.ask_codebase",{query:"main runtime path architecture entrypoints tests verification",mode:"runtime-path",limit:5});e.succeed(y.cyan("First repo briefing ready."));const s=Array.isArray(t.results)?t.results.slice(0,5):[];0===s.length?f.write(y.yellow("\nNo strong codebase matches yet. Ask a normal repo question or run /index --rebuild after adding files.\n")):f.write(["",y.bold("Best starting points"),...s.map((e,t)=>{const s=e.file??e.path??"unknown",i=a(String(e.purpose??e.snippet??""),110);return`${t+1}. ${y.cyan(s)}${i?y.dim(` - ${i}`):""}`}),""].join("\n"));const i=await this.detectVerificationCommand();f.write([y.bold("Recommended next commands"),`${y.magenta("/change")} fix the smallest failing test or implement a tiny improvement`,`${y.magenta('mesh "explain the main runtime path with citations"')}`,i?`${y.magenta(i)} ${y.dim("(detected verification command)")}`:y.dim("No package verification command detected yet."),""].join("\n"))}catch(t){e.fail(y.red(`First repo briefing failed: ${t.message}`)),f.write(y.dim("You can still ask a normal repo question, for example: explain the main runtime path with citations\n"))}}async detectVerificationCommand(){const e=p.join(this.config.agent.workspaceRoot,"package.json");try{const t=await u.readFile(e,"utf8"),s=JSON.parse(t).scripts??{};return"string"==typeof s.test&&!/no test specified|exit 1/i.test(s.test)?"npm test":"string"==typeof s.typecheck?"npm run typecheck":"string"==typeof s.build?"npm run build":"string"==typeof s.lint?"npm run lint":null}catch{return null}}async distillProjectBrain(){const e=$({text:"Distilling Session into Project Brain...",color:"magenta"}).start();try{const t=this.transcript.map(e=>`${e.role}: ${JSON.stringify(e.content)}`).join("\n").slice(-24e3),s=await this.llm.converse([{role:"user",content:[{text:`Analyze this recent conversation and extract any clear architectural decisions, learned project rules, or strict user preferences (e.g. "use Vanilla CSS", "always use functional components", "use path aliases"). Ignore normal code edits or bug fixes. Output ONLY a valid JSON array of strings, each string being a concise, imperative rule. If absolutely nothing was decided, output [].\n\n<conversation>\n${t}\n</conversation>`}]}],[],"You are a specialized JSON-only extractor.",this.currentModelId);let i=[];try{const e=(s.text||"").match(/\[.*\]/s);i=e?JSON.parse(e[0]):[]}catch{throw new Error("Model did not return a valid JSON array.")}if(Array.isArray(i)&&i.length>0){for(const e of i)await this.backend.callTool("workspace.engineering_memory",{action:"record",outcome:"positive",rule:e,note:"Distilled automatically from session conversation."});e.succeed(y.magenta(`Distilled ${i.length} new rules into Engineering Memory.`))}else e.info(y.dim("No clear new project-wide rules found to distill in this session."))}catch(t){e.fail(y.red(`Distillation failed: ${t.message}`))}}async runSynthesize(){const e=p.join(this.config.agent.workspaceRoot,".mesh","latest_intent.json");try{const t=await u.readFile(e,"utf8");let s;try{s=JSON.parse(t)}catch{return void f.write(y.red("\n[Mesh] Error: Intent file is corrupted. Try /index first to rebuild workspace state.\n"))}f.write(y.cyan(`\n[Predictive Synthesis] Analyzing your recent change: ${s.message}\n`));const i=`You are a Predictive Synthesis orchestrator. I recently modified '${s.file}'.\nThe heuristic engine detected this intent: "${s.message}".\nHere is the git diff:\n${s.diff}\n\nYour task:\n1. Understand the broader architectural implications of this change (e.g., if a DB field was added, it likely needs UI, API, and test updates).\n2. DO NOT write code manually in your response.\n3. Instead, aggressively use 'agent.spawn_swarm' to delegate the updates across the stack in parallel, or use 'workspace.ghost_verify' to implement them safely.\n4. Finish by running 'workspace.finalize_task' to wrap these synthesized changes into a new branch.`;await u.unlink(e).catch(()=>{}),await this.runSingleTurn(i)}catch(e){f.write(y.yellow("\nNo recent structural intent detected by the watcher. Save a file with significant changes first.\n"))}}async runHologram(e){if("start"!==e[0]||!e[1])return void f.write(y.yellow("Usage: /hologram start <command>\nExample: /hologram start npm run dev\n"));const t=e.slice(1).join(" ");f.write(y.cyan(`\n[Live Memory Hologram] Injecting telemetry proxy into '${t}'...\n`)),await this.runSingleTurn(`Execute the command '${t}' using 'workspace.run_with_telemetry'. If the process crashes and you receive a memory dump of the V8 engine, analyze the exact variable states, find the root cause, and fix it using 'workspace.alien_patch' or 'workspace.patch_surgical'.`)}async runEntangle(e){const t=e[0];if(!t)return void f.write(y.yellow("Usage: /entangle <relative-path>\nExample: /entangle ../frontend-repo\n"));const s=p.resolve(this.config.agent.workspaceRoot,t);try{if(!(await u.stat(s)).isDirectory())throw new Error("Not a directory");this.backend.entangledWorkspaces&&this.backend.entangledWorkspaces.push(s),this.entangledWorkspaces.push(s),f.write(y.cyan(`\n[Quantum Entanglement] Workspace '${p.basename(s)}' is now entangled. AST mutations will sync automatically.\n`))}catch{f.write(y.red(`\nFailed to entangle: Directory '${s}' does not exist.\n`))}}async runInspect(e){f.write(y.cyan("\n[Neuro-Kinetic UI] Please open the /dashboard. Mouse movements on the canvas will now be translated to AST edits via the LLM.\n(Note: This requires an active dashboard session).\n"))}async runFrontendPreview(e){const t=e[0]?.trim();if(!t)return void f.write(y.yellow("Usage: /preview <url> [widthxheight] [protocol=auto|kitty|iterm2|sixel|none]\n"));const s=e.find(e=>/^\d+x\d+$/i.test(e)),[i,n]=s?s.toLowerCase().split("x"):["1280","800"],a=e.find(e=>e.startsWith("protocol=")),o=a?.split("=")[1]||"auto",r=this.useAnsi?$({text:"Capturing frontend preview via Chrome CDP...",color:"cyan",stream:f}).start():void 0;try{const e=await this.backend.callTool("frontend.preview",{url:t,width:Number(i),height:Number(n),protocol:o,render:!0},{onProgress:e=>{r&&(r.stop(),r.clear()),f.write(e)}});r&&r.succeed("Frontend preview captured."),f.write(["",`${y.dim("url:")} ${e.url}`,`${y.dim("viewport:")} ${e.width}x${e.height}`,`${y.dim("screenshot:")} ${e.screenshotPath}`,`${y.dim("protocol:")} ${e.protocol}${e.rendered?"":" (not rendered inline)"}`,""].join("\n"))}catch(e){r&&r.fail("Frontend preview failed."),f.write(y.red(`\nPreview failed: ${e.message}\n`))}}async runFix(){const e=this.backend;if(e.speculativeFixes&&e.speculativeFixes.size>0){const t=e.speculativeFixes.entries().next().value,s=t[0],i=t[1];f.write(y.cyan(`\n[🧠 Mesh Resolving] Applying pre-computed fix for '${s}'...\n`));const n=`I have a pre-computed speculative fix for the error in '${s}'.\nPlease review this patch and apply it using 'workspace.alien_patch' if it looks correct:\n${i}\n\nFinish by running 'workspace.finalize_task' with the commit message "Fix linter error in ${s} (Auto-Resolved)".`;e.speculativeFixes.delete(s),await this.runSingleTurn(n)}else f.write(y.yellow("\nNo background fixes currently available. Try introducing an error or running /doctor.\n"))}async runSlashCommandSafe(e,t){const s=$({text:`${e}...`,color:"cyan"}).start();try{await t(s)}catch(t){const i=t instanceof Error?t.message:String(t);let n,a;i.includes("429")||i.includes("rate_limit")||i.includes("ThrottlingException")?(n="LLM rate limit hit",a="Wait a moment, then try again. Run /doctor to check connectivity."):i.includes("LLM request failed")||i.includes("fetch failed")||i.includes("ECONNREFUSED")?(n="LLM backend unavailable",a="Run /doctor to diagnose. Check network connectivity."):i.includes("Context")&&i.includes("firewall")?(n="Context too large for this operation",a="Run /compact first to reduce context size."):i.includes("ENOENT")||i.includes("no such file")?(n="Required file not found",a="Run /index first to initialize workspace state."):i.includes("AbortError")||i.includes("aborted")||i.includes("timed out")?(n="Operation timed out after 60 seconds",a="Try /compact to reduce context, then retry."):(n=i.slice(0,200),a="Run /doctor to diagnose or try /reset if the session is corrupted.");const o=`${e} -> ${i.slice(0,80)}`,r=(this.consecutiveErrors.get(o)||0)+1;this.consecutiveErrors.set(o,r),s.fail(y.red(`[Mesh] Error: ${e} failed — ${n}. Try: ${a}`))}}async runDigitalTwin(e){const t=e[0]||"build",s=$({text:`Digital Twin ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.digital_twin",{action:t});s.succeed(y.cyan(`Digital Twin ${t} complete.`));const i=e.twin??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("files:")} ${i.files?.total??i.files??"n/a"}`,`${y.dim("symbols:")} ${i.symbols?.length??i.symbols??"n/a"}`,`${y.dim("routes:")} ${i.routes?.length??i.routes??"n/a"}`,`${y.dim("risk hotspots:")} ${i.riskHotspots?.length??i.riskHotspots??"n/a"}`,""].join("\n"))}catch(e){s.fail(y.red(`Digital Twin failed: ${e.message}`))}}async runPredictiveRepair(e){const t=e[0]||"analyze",s=$({text:`Predictive Repair ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.predictive_repair",{action:t});s.succeed(y.yellow(`Predictive Repair ${t} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("diagnostics:")} ${e.diagnosticsOk?y.green("clean"):y.red("attention")}`,`${y.dim("queue:")} ${Array.isArray(e.queue)?e.queue.length:0}`,...Array.isArray(e.queue)?e.queue.slice(0,5).map(e=>`${y.yellow("•")} ${e.summary} ${y.dim((e.files??[]).join(", "))}`):[],""].join("\n"))}catch(e){s.fail(y.red(`Predictive Repair failed: ${e.message}`))}}async runDaemon(e){const t=(e[0]||"status").toLowerCase(),s=$({text:`Daemon ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.daemon",{action:t});s.succeed(y.cyan(`Daemon ${t} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.message?[`${y.dim("message:")} ${e.message}`]:[],...e.digest?[`${y.dim("digest:")} ${e.digest}`]:[],...e.state?[`${y.dim("state:")} ${JSON.stringify(e.state,null,2)}`]:[],""].join("\n"))}catch(e){s.fail(y.red(`Daemon command failed: ${e.message}`))}}async runIssuePipeline(e){const t=(e[0]||"scan").toLowerCase(),s=e[1]?.toLowerCase();if(["plan","run","pr","create-pr"].includes(t))return void await this.runIssueAutopilot(e);const i=$({text:`Issue pipeline ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.issue_pipeline",{action:t,provider:s});i.succeed(y.yellow(`Issue pipeline ${t} complete.`)),f.write(["",`${y.dim("queued:")} ${e.queued??0}`,`${y.dim("processed:")} ${(e.processed??[]).length}`,...(e.processed??[]).slice(0,5).map(e=>`${y.yellow("•")} ${e.provider}:${e.issueId} -> ${e.prTitle}`),""].join("\n"))}catch(e){i.fail(y.red(`Issue pipeline failed: ${e.message}`))}}async runIssueAutopilot(e){const t=(e[0]||"status").toLowerCase().replace("-","_"),s=e.slice(1),i=s.join(" ").trim(),n={action:"create_pr"===t?"pr":t};/^https?:\/\//i.test(s[0]??"")?n.issueUrl=s[0]:i&&(n.title=i,n.body=i);const a=$({text:`Issue Autopilot ${n.action}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.issue_autopilot",n);a.succeed(y.yellow(`Issue Autopilot ${e.status??e.action} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.runId?[`${y.dim("run:")} ${e.runId}`]:[],...e.issue?[`${y.dim("issue:")} ${e.issue.provider}:${e.issue.id} ${e.issue.title}`]:[],...e.plan?.branchName?[`${y.dim("branch:")} ${e.plan.branchName}`]:[],...e.plan?.verificationCommand?[`${y.dim("verify:")} ${e.plan.verificationCommand}`]:[],...e.timeline?.id?[`${y.dim("timeline:")} ${e.timeline.id}`]:[],...e.proof?.verdict?[`${y.dim("proof:")} ${e.proof.verdict} ${e.proof.proofId??""}`]:[],...e.pr?.url?[`${y.dim("pr:")} ${e.pr.url}`]:[],...(e.plan?.likelyFiles??[]).slice(0,8).map(e=>`${y.yellow("•")} ${e}`),""].join("\n"))}catch(e){a.fail(y.red(`Issue Autopilot failed: ${e.message}`))}}async runChange(e,t){const i=e.join(" ").trim();if(!i)return f.write(y.yellow("\nUsage: /change <small goal>\n")),void f.write(y.dim("Example: /change fix the failing auth test\n"));const n=await this.detectVerificationCommand(),a=$({text:"Scoping narrow change...",color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.ask_codebase",{query:i,mode:"edit-impact",limit:6}),t=Array.isArray(e.results)?e.results.slice(0,6).map(e=>e.file??e.path).filter(Boolean):[];a.succeed(y.yellow("Change scope prepared.")),t.length>0&&f.write(["",y.bold("Likely files"),...t.map(e=>`${y.yellow("•")} ${e}`),""].join("\n"))}catch(e){a.warn(y.yellow(`Scope lookup skipped: ${e.message}`))}const o=["Execute Mesh /change for this narrow goal:",i,"","Hard constraints:","- Make the smallest safe code change that satisfies the goal.","- Prefer reading indexed/capsule context before raw files.","- Inspect impact before editing shared symbols.","- Do not publish, tag, push, create a PR, or run destructive commands.","- If the change is risky or multi-file, create a timeline first and verify there before touching the main workspace.","- After editing, run the detected verification command if it is available.",n?`- Detected verification command: ${n}`:"- No verification command was detected; explain what verification was skipped and why.","- Finish with exactly: changed files, verification result, residual risk, next action."].join("\n"),r=this.useAnsi?$({text:"Applying narrow change...",color:"cyan",stream:f}).start():void 0;let c=!1;try{this.resetToolSummary();const e=await this.runSingleTurn(o,{onToolStart:(e,t,i,n)=>{r&&(r.text=`${y.dim(`[${i+1}/${n}]`)} ${y.cyan(e)} ${y.dim(s(t))}`),this.renderToolEvent("start",e,s(t))},onToolEnd:(e,t,s)=>{r&&(r.text=t?`done ${y.cyan(e)}`:`failed ${y.cyan(e)}`),this.renderToolEvent(t?"success":"error",e,s)},onCommandChunk:e=>{r&&(r.stop(),r.clear()),f.write(e)},onDelta:e=>{r&&(r.stop(),r.clear()),c||(c=!0,f.write("\n"+this.themeColor(y.bold("change"))+y.dim(" › ")+"\n")),f.write(e)},askPermission:async e=>{r&&r.stop();const t=new _({name:"approve",message:e,initial:!1,stdin:g,stdout:f}),s=Boolean(await t.run().catch(()=>!1));return r&&r.start(),s}});!c&&e?this.renderAssistantTurn(e):c&&f.write("\n"),this.printToolSummary()}catch(e){r?r.fail(y.red(`Change failed: ${e.message}`)):f.write(y.red(`\nChange failed: ${e.message}\n`))}finally{r&&(r.stop(),r.clear())}}async runChatops(e){const t=(e[0]||"investigate").toLowerCase(),s=(e[1]||"slack").toLowerCase(),i=e.slice(2).join(" ").trim(),n=$({text:`ChatOps ${t}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.chatops",{action:t,platform:s,channel:"general",message:i});n.succeed(y.magenta(`ChatOps ${t} complete.`)),f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,...e.threadId?[`${y.dim("thread:")} ${e.threadId}`]:[],...e.status?[`${y.dim("status:")} ${e.status}`]:[],...(e.updates??[]).slice(0,4).map(e=>`${y.magenta("•")} ${e}`),...e.prDraft?[`${y.dim("pr draft:")}\n${e.prDraft}`]:[],""].join("\n"))}catch(e){n.fail(y.red(`ChatOps failed: ${e.message}`))}}async runProductionStatus(e){const t=(e[0]||"status").toLowerCase();if(["audit","gate","review","readiness"].includes(t)){const s=e.slice(1).join(" ").trim()||"production readiness",i=$({text:`Production readiness ${t}...`,color:"red"}).start();try{const e=await this.backend.callTool("workspace.production_readiness",{action:"readiness"===t?"audit":t,intent:s});i.succeed(y.red(`Production readiness ${e.status}.`)),f.write(["",`${y.dim("score:")} ${e.score}/100`,`${y.dim("ledger:")} ${e.ledgerPath}`,...(e.dimensions??[]).map(e=>`${"pass"===e.status?y.green("•"):"warn"===e.status?y.yellow("•"):y.red("•")} ${e.title}: ${e.score}/100`),...(e.blockers??[]).slice(0,5).map(e=>`${y.red("blocker:")} ${e}`),""].join("\n"))}catch(e){i.fail(y.red(`Production readiness failed: ${e.message}`))}return}const s=$({text:`Production ${t}...`,color:"red"}).start();try{const e=await this.backend.callTool("workspace.production_status",{action:t});s.succeed(y.red(`Production ${t} complete.`)),f.write(["",`${y.dim("updated:")} ${e.updatedAt??"never"}`,`${y.dim("signals:")} ${e.totalSignals??0}`,...(e.topErrors??[]).slice(0,8).map(e=>`${y.red("•")} ${e.file} req=${e.requestVolume} err=${e.errorRate} p99=${e.p99Ms}ms impact=$${e.revenueImpactDaily}/day`),""].join("\n"))}catch(e){s.fail(y.red(`Production telemetry failed: ${e.message}`))}}async runReplayTrace(e){const t=e[0],s=e[1];if(!t)return void f.write(y.yellow("Usage: /replay <traceId|sentryEventId> [commitRange]\n"));const i=$({text:"Replaying production trace...",color:"cyan"}).start();try{const e=await this.backend.callTool("runtime.replay_trace",{traceId:t,commitRange:s});i.succeed(y.cyan("Trace replay complete.")),f.write(["",`${y.dim("trace:")} ${e.traceId}`,`${y.dim("path:")} ${e.reconstructedRequest?.method} ${e.reconstructedRequest?.path}`,...e.divergence?[`${y.dim("divergence:")} ${e.divergence.span} ${e.divergence.file??""}:${e.divergence.line??""}`]:[],...e.commitAnalysis?[`${y.dim("likely introduced by:")} ${e.commitAnalysis.likelyIntroducedBy}`]:[],""].join("\n"))}catch(e){i.fail(y.red(`Trace replay failed: ${e.message}`))}}async runSymptomBisect(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /bisect <symptom> [verificationCommand]\n"));const s=$({text:"Running symptom bisect...",color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.symptom_bisect",{symptom:t});s.succeed(y.yellow("Symptom bisect complete.")),f.write(["",`${y.dim("symptom:")} ${e.symptom}`,`${y.dim("verification:")} ${e.verificationCommand??"n/a"}`,`${y.dim("culprit:")} ${e.culpritCommit??"undetermined"}`,...e.authorHint?[`${y.dim("author:")} ${e.authorHint}`]:[],...e.message?[e.message]:[],""].join("\n"))}catch(e){s.fail(y.red(`Symptom bisect failed: ${e.message}`))}}async runWhatIf(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /whatif <hypothesis>\n"));const s=$({text:"Running what-if analysis...",color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.what_if",{hypothesis:t});s.succeed(y.magenta("What-if report generated.")),f.write(["",`${y.dim("hypothesis:")} ${e.hypothesis}`,`${y.dim("verdict:")} ${e.verdict}`,`${y.dim("timeline:")} ${e.timelineId}`,`${y.dim("changed files:")} ${(e.changedFiles??[]).length}`,`${y.dim("changed lines:")} ${e.changedLineCount??0}`,`${y.dim("type errors:")} ${e.typeErrorsEstimate??0}`,`${y.dim("tests broken:")} ${e.testsBrokenEstimate??0}`,`${y.dim("bundle delta:")} ${e.bundleSizeDeltaKb??0} KB`,`${y.dim("note:")} ${e.note??""}`,""].join("\n"))}catch(e){s.fail(y.red(`What-if failed: ${e.message}`))}}async runAudit(e){const t=(e[0]||"verify").toLowerCase(),s=$({text:`Audit ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.audit",{action:t});if(s.succeed(y.yellow(`Audit ${t} complete.`)),"replay"===t)return void f.write(["",`${y.dim("entries:")} ${(e.entries??[]).length}`,...(e.entries??[]).slice(0,5).map(e=>`${y.yellow("•")} ${e.ts} ${e.tool}`),""].join("\n"));f.write(["",`${y.dim("ok:")} ${e.ok?y.green("yes"):y.red("no")}`,`${y.dim("total:")} ${e.total??0}`,`${y.dim("invalid:")} ${e.invalid??0}`,""].join("\n"))}catch(e){s.fail(y.red(`Audit command failed: ${e.message}`))}}async runMeshBrain(e){const t=(e[0]||"stats").replace("-","_"),s=$({text:`Mesh Brain ${t}...`,color:"blue"}).start();try{if("query"===t){const i=e.slice(1).join(" ").trim();if(!i)return s.stop(),void f.write(y.yellow("Usage: /brain query <error signature>\n"));const n=await this.backend.callTool("workspace.brain",{action:t,error:i,limit:5});return s.succeed(y.blue("Mesh Brain query complete.")),void f.write(["",`${y.dim("source:")} ${n.source??"unknown"}`,`${y.dim("patterns:")} ${(n.patterns??[]).length}`,...(n.patterns??[]).slice(0,5).map(e=>`${y.blue("•")} score=${Number(e.score??0).toFixed(2)} usage=${e.usageCount??0} ${e.fixSummary??"Pattern match"}`),""].join("\n"))}if("opt_out"===t)return await this.backend.callTool("workspace.brain",{action:t}),s.succeed(y.blue("Mesh Brain contributions disabled.")),void f.write(y.dim("You can still query global patterns; local contributions are now off.\n"));const i=await this.backend.callTool("workspace.brain",{action:"stats"});s.succeed(y.blue("Mesh Brain stats loaded.")),f.write(["",`${y.dim("contribute:")} ${i.telemetryContribute?y.green("enabled"):y.red("disabled")}`,`${y.dim("endpoint:")} ${i.endpoint??"local-only"}`,`${y.dim("contributions:")} ${i.contributions??0}`,`${y.dim("last contribution:")} ${i.lastContributionAt??"never"}`,""].join("\n"))}catch(e){s.fail(y.red(`Mesh Brain failed: ${e.message}`))}}async runCompanyBrain(e){const t=(e[0]||"status").toLowerCase().replace("-","_"),s=e.slice(1).join(" ").trim(),i={action:t};["query","ask","search"].includes(t)&&(i.query=s),["record","ingest"].includes(t)&&(i.kind="ingest"===t?"lesson":"decision",i.title=s.slice(0,160),i.body=s);const n=$({text:`Company Brain ${t}...`,color:"blue"}).start();try{const e=await this.backend.callTool("workspace.company_brain",i);if(n.succeed(y.blue(`Company Brain ${e.status??e.action} complete.`)),e.citations)return void f.write(["",`${y.dim("query:")} ${e.query}`,`${y.dim("answer:")} ${e.answer}`,...(e.citations??[]).slice(0,8).map(e=>`${y.blue("•")} ${e.file??e.title} ${e.lineStart?`L${e.lineStart}`:""} score=${e.score}`),""].join("\n"));f.write(["",`${y.dim("path:")} ${e.path??e.summaryPath??"n/a"}`,...e.summaryPath?[`${y.dim("summary:")} ${e.summaryPath}`]:[],...void 0!==e.files?[`${y.dim("files:")} ${e.files}`]:[],...void 0!==e.documents?[`${y.dim("documents:")} ${e.documents}`]:[],...void 0!==e.rules?[`${y.dim("rules:")} ${e.rules}`]:[],...void 0!==e.decisions?[`${y.dim("decisions:")} ${e.decisions}`]:[],...(e.domains??[]).slice(0,8).map(e=>`${y.blue("•")} ${e.name}: ${e.files} files, ${e.risks} risks`),""].join("\n"))}catch(e){n.fail(y.red(`Company Brain failed: ${e.message}`))}}async runEngineeringMemory(e){const t=e[0]||"read",s=$({text:`Engineering Memory ${t}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.engineering_memory",{action:t});s.succeed(y.magenta(`Engineering Memory ${t} complete.`));const i=e.memory??{};f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("rules:")} ${(i.rules??[]).length}`,`${y.dim("risk modules:")} ${(i.riskModules??[]).length}`,...(i.rules??[]).slice(0,6).map(e=>`${y.magenta("•")} ${e}`),""].join("\n"))}catch(e){s.fail(y.red(`Engineering Memory failed: ${e.message}`))}}async runIntentCompile(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /intent <product intent>\n"));const s=$({text:"Compiling intent...",color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.intent_compile",{intent:t});s.succeed(y.cyan("Intent compiled."));const i=e.contract;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("likely files:")} ${i.likelyFiles.join(", ")||"none"}`,`${y.dim("verification:")} ${i.rollout.verificationCommand}`,...i.phases.map((e,t)=>`${y.cyan(`${t+1}.`)} ${e}`),""].join("\n"))}catch(e){s.fail(y.red(`Intent compile failed: ${e.message}`))}}async runCausalIntelligence(e){const t=e[0]||"build",s="query"===t?e.slice(1).join(" ").trim():"";if("query"===t&&!s)return void f.write(y.yellow("Usage: /causal query <question>\n"));const i=$({text:`Causal Intelligence ${t}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.causal_intelligence",{action:t,query:s});if(i.succeed(y.cyan(`Causal Intelligence ${t} complete.`)),"query"===t)return void f.write(["",`${y.dim("answer:")} ${e.answer}`,...(e.topInsights??[]).slice(0,5).map(e=>`${y.cyan("•")} ${e.severity} ${e.title}`),""].join("\n"));const n=e.graph??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("nodes:")} ${n.nodes?.length??n.nodes??"n/a"}`,`${y.dim("edges:")} ${n.edges?.length??n.edges??"n/a"}`,`${y.dim("insights:")} ${n.insights?.length??n.insights??"n/a"}`,...(n.insights??[]).slice(0,5).map(e=>`${y.cyan("•")} ${e.severity} ${e.title}`),""].join("\n"))}catch(e){i.fail(y.red(`Causal Intelligence failed: ${e.message}`))}}async runDiscoveryLab(e){const t=e[0]||"run",s=$({text:`Discovery Lab ${t}...`,color:"yellow"}).start();try{const e=await this.backend.callTool("workspace.discovery_lab",{action:t});s.succeed(y.yellow(`Discovery Lab ${t} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("discoveries:")} ${Array.isArray(e.discoveries)?e.discoveries.length:0}`,...(e.discoveries??[]).slice(0,6).map(e=>`${y.yellow("•")} ${e.severity} ${e.hypothesis}`),""].join("\n"))}catch(e){s.fail(y.red(`Discovery Lab failed: ${e.message}`))}}async runRealityFork(e){const t=new Set(["plan","fork","status","clear"]),s=e[0]||"plan",i=t.has(s)?s:"plan",n=t.has(s)?e.slice(1).join(" ").trim():e.join(" ").trim();if(("plan"===i||"fork"===i)&&!n)return void f.write(y.yellow("Usage: /fork [plan|fork] <intent>\n"));const a=$({text:`Reality Fork ${i}...`,color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.reality_fork",{action:i,intent:n});a.succeed(y.magenta(`Reality Fork ${i} complete.`)),f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("intent:")} ${e.intent??"n/a"}`,`${y.dim("proposals:")} ${Array.isArray(e.proposals)?e.proposals.length:e.proposals??0}`,...(e.proposals??[]).slice(0,5).map(e=>{const t=e.timelineId?y.dim(` timeline=${e.timelineId}`):"";return`${y.magenta("•")} ${e.score} ${e.strategy}${t}`}),""].join("\n"))}catch(e){a.fail(y.red(`Reality Fork failed: ${e.message}`))}}async runGhostEngineer(e){const t=new Set(["learn","profile","status","predict","divergence","patch","clear"]),s=e[0]||"profile",i=t.has(s)?s:"predict",n=t.has(s)?e.slice(1).join(" ").trim():e.join(" ").trim();if(("predict"===i||"patch"===i)&&!n)return void f.write(y.yellow("Usage: /ghost predict <goal> or /ghost patch <goal>\n"));if("divergence"===i&&!n)return void f.write(y.yellow("Usage: /ghost divergence <plan>\n"));const a=$({text:`Ghost Engineer ${i}...`,color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.ghost_engineer",{action:i,goal:"predict"===i||"patch"===i?n:void 0,plan:"divergence"===i?n:void 0});if(a.succeed(y.cyan(`Ghost Engineer ${i} complete.`)),"predict"===i){const t=e.prediction;return void f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("prediction:")} ${t.prediction}`,`${y.dim("verification:")} ${t.predictedApproach.verificationCommand}`,`${y.dim("alignment:")} ${t.divergence.verdict} / ${t.divergence.alignmentScore}`,...t.predictedApproach.firstReads.slice(0,6).map(e=>`${y.cyan("•")} read ${e}`),""].join("\n"))}if("divergence"===i){const t=e.divergence;return void f.write(["",`${y.dim("alignment:")} ${t.verdict} / ${t.alignmentScore}`,...(t.warnings??[]).map(e=>`${y.yellow("•")} ${e.severity} ${e.message}`),""].join("\n"))}if("patch"===i)return void f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("timeline:")} ${e.timelineId}`,`${y.dim("verification:")} ${e.autopilot.predictedApproach.verificationCommand}`,...e.autopilot.autopilotPatch.suggestedPatchOrder.slice(0,5).map(e=>`${y.cyan("•")} ${e}`),""].join("\n"));const t=e.profile??e;f.write(["",`${y.dim("path:")} ${e.path}`,`${y.dim("learned:")} ${t.learnedAt??"n/a"}`,`${y.dim("confidence:")} ${t.confidence??"n/a"}`,`${y.dim("patch shape:")} ${t.habits?.patchShape??"n/a"}`,...(t.habits?.firstReadFiles??[]).slice(0,6).map(e=>`${y.cyan("•")} ${e}`),""].join("\n"))}catch(e){a.fail(y.red(`Ghost Engineer failed: ${e.message}`))}}async runTribunal(e){const t=e.join(" ").trim();if(!t)return void f.write(y.yellow("Usage: /tribunal <problem or engineering decision to adjudicate>\n"));const s=$({text:"Convening tribunal (3 panelists deliberating in parallel)...",color:"magenta"}).start();try{const e=await this.backend.callTool("workspace.tribunal",{action:"convene",problem:t});if(!e.ok)return void s.fail(y.red(`Tribunal failed: ${e.reason??"unknown error"}`));s.succeed(y.magenta(`Tribunal complete — verdict: ${e.synthesis?.verdict??"n/a"}`));const i=e.synthesis;f.write(["",`${y.dim("winner:")} ${i.winningPanelistId} (score ${i.scores?.[i.winningPanelistId]??"?"})`,`${y.dim("verdict:")} ${i.verdict}`,"",`${y.magenta("▶ Dominant Solution:")}`,i.dominantSolution,"",`${y.dim("rationale:")} ${i.rationale}`,...i.incorporated?.length>0?[`${y.dim("incorporated:")} ${i.incorporated.slice(0,3).join(" | ")}`]:[],...i.dissent?[`${y.dim("dissent:")} ${i.dissent}`]:[],`${y.dim("artifact:")} ${e.decisionArtifactPath}`,""].join("\n"))}catch(e){s.fail(y.red(`Tribunal failed: ${e.message}`))}}async runSessionResurrection(e){const t=e[0]?.toLowerCase()??"resurrect",s=e.slice(1);if("capture"===t)return f.write(y.cyan('\nTo capture your session state, ask the agent:\n "capture my session state" or use workspace.session_resurrection directly\n The agent will extract your intent, open questions, and next actions.\n\n')),void f.write(y.dim("Tip: The agent uses workspace.session_resurrection action=capture with your context.\n\n"));if("checkpoint"===t){const e=s.join(" ").trim();if(!e)return void f.write(y.yellow("Usage: /resurrect checkpoint <note>\n"));const t=$({text:"Saving checkpoint...",color:"cyan"}).start();try{const s=await this.backend.callTool("workspace.session_resurrection",{action:"checkpoint",note:e});t.succeed(y.cyan(`Checkpoint saved (${s.totalCheckpoints} total)`))}catch(e){t.fail(y.red(`Checkpoint failed: ${e.message}`))}return}if("status"===t){const e=$({text:"Reading session state...",color:"cyan"}).start();try{const t=await this.backend.callTool("workspace.session_resurrection",{action:"status"});e.succeed(y.cyan("Session resurrection status")),t.exists?f.write(["",`${y.dim("session:")} ${t.sessionId}`,`${y.dim("captured:")} ${t.capturedAt} (${t.age} ago)`,`${y.dim("intent:")} ${t.intent}`,`${y.dim("questions:")} ${t.openQuestionsCount} ${y.dim("next-actions:")} ${t.nextActionsCount} ${y.dim("checkpoints:")} ${t.checkpointsCount}`,""].join("\n")):f.write(y.dim("\nNo captured session.\n\n"))}catch(t){e.fail(y.red(`Status failed: ${t.message}`))}return}if("clear"===t){const e=$({text:"Clearing session state...",color:"cyan"}).start();try{await this.backend.callTool("workspace.session_resurrection",{action:"clear"}),e.succeed(y.cyan("Session resurrection state cleared."))}catch(t){e.fail(y.red(`Clear failed: ${t.message}`))}return}const i=$({text:"Reconstructing session state...",color:"cyan"}).start();try{const e=await this.backend.callTool("workspace.session_resurrection",{action:"resurrect"});i.succeed(y.cyan("Session resurrected.")),e.exists||e.snapshot?f.write("\n"+e.brief+"\n\n"):f.write(y.dim("\nNo previous session to resurrect. Work on something then run /resurrect capture.\n\n"))}catch(e){i.fail(y.red(`Resurrection failed: ${e.message}`))}}async runSemanticSheriff(e){const t=new Set(["scan","verify","lock","unlock","drift","status","clear"]),s=e[0]?.toLowerCase()??"verify",i=t.has(s)?s:"verify",n="lock"===i||"unlock"===i||"verify"===i?e[1]?.trim():void 0;if(("lock"===i||"unlock"===i)&&!n)return void f.write(y.yellow(`Usage: /sheriff ${i} <file>\n`));const a=$({text:"scan"===i?"Scanning and fingerprinting codebase...":"verify"===i?"Verifying semantic contracts...":"lock"===i?`Locking contract for ${n}...`:"drift"===i?"Loading drift report...":`Sheriff ${i}...`,color:"yellow"}).start();try{const e={action:i};n&&(e.file=n);const t=await this.backend.callTool("workspace.semantic_sheriff",e);if(a.succeed(y.yellow(`Sheriff ${i} complete.`)),"scan"===i)return void f.write(["",`${y.dim("scanned:")} ${t.scanned} ${y.dim("updated:")} ${t.updated} ${y.dim("total:")} ${t.totalContracts}`,`${y.dim("path:")} ${t.path}`,""].join("\n"));if("verify"===i||"drift"===i){const e=t.driftAlerts??[];return void f.write(["",`${y.dim("contracts:")} ${t.contracts} ${y.dim("locked:")} ${t.lockedContracts}`,`${y.dim("summary:")} ${t.summary}`,...e.slice(0,8).map(e=>{const t="critical"===e.severity?y.red:"high"===e.severity?y.yellow:y.dim,s=[...e.changes.removedExports.length>0?[`-exports: ${e.changes.removedExports.join(", ")}`]:[],...e.changes.addedExports.length>0?[`+exports: ${e.changes.addedExports.join(", ")}`]:[],...e.changes.purposeShift?["purpose shifted"]:[],...e.changes.behavioralShift?["behavioral patterns changed"]:[]].join("; ");return t(` ${e.severity.toUpperCase()} ${e.file} — ${s}`)}),""].join("\n"))}if("lock"===i)return void f.write(["",`${y.yellow("⬡")} ${t.file} locked`,`${y.dim("fingerprint:")} ${t.fingerprint}`,`${y.dim("message:")} ${t.message}`,""].join("\n"));f.write(`\n${y.dim(t.message??JSON.stringify(t))}\n\n`)}catch(e){a.fail(y.red(`Sheriff ${i} failed: ${e.message}`))}}async launchDashboard(){const e=$({text:"Starting dashboard...",color:"cyan"}).start();try{const t=this.getDashboardDir();await u.mkdir(t,{recursive:!0}),await this.appendDashboardEvent({id:`${Date.now()}-dashboard-open`,type:"dashboard",msg:"Dashboard opened",at:(new Date).toISOString()});const s=await this.readDashboardServerInfo();let i=s?.port;this.dashboardToken&&i&&"react-live-dashboard-v1"===s?.version&&await this.isDashboardReachable(i)||(this.dashboardToken=C.randomBytes(32).toString("hex"),i=await this.startDashboardServer(t,this.dashboardToken));const n=`http://127.0.0.1:${i}/#token=${this.dashboardToken}`;this.openDashboardUrl(n),e.succeed(y.green(`Dashboard live at http://127.0.0.1:${i}`))}catch(t){e.fail(y.red(`Interface initialization failed: ${t.message}`))}}getDashboardDir(){return p.join(this.config.agent.workspaceRoot,".mesh","dashboard")}getDashboardEventsPath(){return p.join(this.getDashboardDir(),"events.json")}getDashboardContextMetricsPath(){return p.join(this.getDashboardDir(),"context-metrics.json")}getDashboardServerInfoPath(){return p.join(this.getDashboardDir(),"server.json")}async writeContextMetrics(e,t){const s=this.getDashboardContextMetricsPath(),i={updatedAt:(new Date).toISOString(),report:e,rawCharsStored:this.turnArtifactCharsStored,envelopeCharsSent:this.turnArtifactEnvelopeChars,rawCharsSaved:t,rawTokensSavedEstimate:Math.ceil(Math.max(0,t)/4),toolCalls:this.turnToolCalls,toolErrors:this.turnToolErrors};await u.mkdir(p.dirname(s),{recursive:!0}),await u.writeFile(s,JSON.stringify(i,null,2),"utf8")}async appendDashboardEvent(e){const t=this.getDashboardEventsPath();await u.mkdir(p.dirname(t),{recursive:!0});const s=await u.readFile(t,"utf8").catch(()=>"[]");let i=[];try{i=JSON.parse(s)}catch{i=[]}i.unshift(e),await u.writeFile(t,JSON.stringify(i.slice(0,200),null,2),"utf8")}async readDashboardServerInfo(){const e=await u.readFile(this.getDashboardServerInfoPath(),"utf8").catch(()=>"");if(!e)return null;try{const t=JSON.parse(e);return Number.isFinite(t.port)?{port:Number(t.port),pid:t.pid,version:t.version}:null}catch{return null}}async isDashboardReachable(e){return await new Promise(t=>{const s=b.get({host:"127.0.0.1",port:e,path:"/health",timeout:700},e=>{e.resume(),t(200===e.statusCode)});s.on("error",()=>t(!1)),s.on("timeout",()=>{s.destroy(),t(!1)})})}async startDashboardServer(e,t){x(process.execPath,[p.join(p.dirname(w(import.meta.url)),"dashboard-server.js"),this.config.agent.workspaceRoot],{detached:!0,stdio:"ignore",env:{...process.env,MESH_DASHBOARD_TOKEN:t}}).unref();this.getDashboardServerInfoPath();for(let e=0;e<40;e++){await new Promise(e=>setTimeout(e,100));const e=await this.readDashboardServerInfo();if(e?.port&&await this.isDashboardReachable(e.port))return e.port}throw new Error(`Dashboard server did not start. Expected info at ${p.join(e,"server.json")}`)}openDashboardUrl(e){const t="darwin"===process.platform?{bin:"open",args:[e]}:"win32"===process.platform?{bin:"cmd",args:["/c","start","",e]}:{bin:"xdg-open",args:[e]};x(t.bin,t.args,{detached:!0,stdio:"ignore"}).unref()}printCost(){const e=this.sessionTokens.inputTokens,t=this.sessionTokens.outputTokens,s=J.find(e=>this.currentModelId.includes(e.value)||e.value.includes(this.currentModelId)),{inputPer1k:i,outputPer1k:n}=s?.pricing??{inputPer1k:.003,outputPer1k:.015},a=e*i/1e3+t*n/1e3;f.write(["",`${y.dim("session usage:")} ${this.themeColor(e.toLocaleString())} ${y.dim("input /")} ${this.themeColor(t.toLocaleString())} ${y.dim("output tokens")}`,`${y.dim("session cost:")} ${y.green("$"+a.toFixed(4))}`,""].join("\n"))}setupGhostText(e,t,s){if(!this.useAnsi)return;this.ghostTextListener&&t.removeListener("keypress",this.ghostTextListener);let i="",n=!1;this.ghostTextListener=(t,a)=>{if(this.useAnsi&&a){if(a.ctrl&&"o"===a.name)return this.toolEventsExpanded=!this.toolEventsExpanded,void s.write(y.dim(`\ntool output: ${this.toolEventsExpanded?"expanded":"collapsed"}\n`));if("return"!==a.name&&"enter"!==a.name){if(!n){if(("tab"===a.name||"right"===a.name&&i)&&i){const t=i;i="",n=!0;const s=e;return"function"==typeof s._refreshLine?(s.line=(s.line||"")+t,s.cursor=s.line.length,s._refreshLine()):e.write(t),void setTimeout(()=>{n=!1},20)}setTimeout(()=>{if(n)return;const t=e.line||"";if(t.startsWith("/")&&!t.includes(" ")){const e=this.getSlashCommands().flatMap(e=>[e.name,...e.aliases||[]]).find(e=>e.startsWith(t)&&e!==t);if(e){const n=e.slice(t.length);n!==i&&(i&&s.write(" ".repeat(i.length)+"["+i.length+"D"),s.write(y.dim(n)+"["+n.length+"D"),i=n)}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")},5)}}else i&&(s.write(" ".repeat(i.length)+"["+i.length+"D"),i="")}},t.on("keypress",this.ghostTextListener)}renderUserTurn(e){const t=this.useAnsi?y.bold(y.white("you")):"you";f.write(`\n${t}> ${e}\n`)}renderAssistantTurn(e){const t=this.sanitizeLlmOutput(e),s=S.parse(t);this.useAnsi?f.write("\n"+this.themeColor(y.bold("assistant"))+y.dim(" › ")+"\n"+s+"\n"):f.write(`\nassistant> ${t}\n`)}sanitizeLlmOutput(e){return sanitizeLlmOutput(e)}renderSystemMessage(e){const t=this.useAnsi?y.yellow("system>"):"system>";f.write(`\n${t} ${e}\n`)}renderToolEvent(e,t,s){if(this.lastToolEventAt=(new Date).toISOString(),"start"===e?(this.turnToolCalls+=1,this.turnToolNames.set(t,(this.turnToolNames.get(t)??0)+1)):"error"===e&&(this.turnToolErrors+=1),!this.toolEventsExpanded&&"error"!==e)return;const i="start"===e?y.dim("tool>"):"success"===e?y.green("tool<"):y.red("tool<");f.write(`\n${i} ${y.cyan(t)}${s?` ${y.dim(s)}`:""}\n`)}resetToolSummary(){this.turnToolCalls=0,this.turnToolErrors=0,this.turnToolNames.clear(),this.turnArtifactCharsStored=0,this.turnArtifactEnvelopeChars=0,this.turnContextReports=[],this.lastContextReport=null}printToolSummary(){if(this.turnToolCalls>0){const e=Array.from(this.turnToolNames.entries()).sort((e,t)=>t[1]-e[1]).slice(0,4).map(([e,t])=>`${e}${t>1?` x${t}`:""}`).join(", "),t=this.toolEventsExpanded?"expanded":"collapsed",s=this.turnToolErrors>0?` · ${this.turnToolErrors} errors`:"";f.write(y.dim(`\ntools: ${this.turnToolCalls} calls · ${e}${s} · ${t} (Ctrl+O)`))}const e=this.peakContextReport();if(e){const t=Math.max(0,this.turnArtifactCharsStored-this.turnArtifactEnvelopeChars);this.sessionRawSaved+=t,this.writeContextMetrics(e,t)}(this.turnToolCalls>0||e)&&f.write("\n")}peakContextReport(){return 0===this.turnContextReports.length?this.lastContextReport:[...this.turnContextReports].sort((e,t)=>t.totalTokens-e.totalTokens)[0]??null}printHelp(e=[]){const t=this.getSlashCommands(),s=e.includes("--all")||e.includes("advanced"),i=e[0]?.toLowerCase().replace(/^([^/])/,"/$1");if(i&&!["/all","advanced"].includes(i)){const e=t.find(e=>e.name===i||e.aliases?.includes(i));if(!e)return void f.write(y.yellow(`\nNo command named ${i}. Run /help for the command groups.\n`));const s=this.commandExamples(e.name);return void f.write(["",`${y.magenta(y.bold(e.name))}${e.aliases?.length?y.dim(` (${e.aliases.join(", ")})`):""}`,`${y.dim("what:")} ${e.description}`,`${y.dim("usage:")} ${e.usage}`,...s.length?[`${y.dim("examples:")}`,...s.map(e=>` ${e}`)]:[],""].join("\n"))}const n=new Map(t.map(e=>[e.name,e]));f.write(["",`${this.themeColor(y.bold("Mesh CLI - Private Alpha"))}`,`${y.dim("Run /help <command> for examples. Most things work as plain questions — slash commands are shortcuts.")}`,s?"":y.dim("Showing core commands. Run /help --all to see all groups."),"",...[{title:"Getting Started",names:["/start","/status","/index","/doctor"]},{title:"Making Changes",names:["/change","/intent","/autopilot","/issues","/fix","/ghost","/fork"]},{title:"Understand the Codebase",names:["/causal","/brain","/company","/learn","/lab","/twin","/distill","/synthesize","/repair"],advanced:!0},{title:"Quality & Safety",names:["/audit","/production","/sheriff","/tribunal","/bisect","/replay","/whatif"],advanced:!0},{title:"Session",names:["/model","/setup","/color","/compact","/capsule","/cost","/undo","/approvals","/steps","/clear","/exit"]},{title:"Tools & Integrations",names:["/dashboard","/inspect","/stop-inspect","/preview","/hologram","/entangle","/chatops","/daemon","/sync","/voice","/resurrect"],advanced:!0}].flatMap(e=>e.advanced&&!s?[]:[this.themeColor(y.bold(e.title)),...e.names.map(e=>n.get(e)).filter(e=>Boolean(e)).map(e=>`${y.magenta(e.name.padEnd(15," "))}${e.description}`),""])].join("\n")+"\n")}commandExamples(e){return{"/start":["/start","/start fix","/start reindex"],"/status":["/status"],"/index":["/index"],"/dashboard":["/dashboard"],"/twin":["/twin","/twin status"],"/repair":["/repair","/repair status","/repair clear"],"/company":["/company build","/company query auth flow","/company record API clients must validate env tokens"],"/autopilot":["/autopilot plan https://github.com/org/repo/issues/123","/autopilot run fix the failing auth test","/autopilot pr https://github.com/org/repo/issues/123"],"/change":["/change fix the failing auth test","/change add validation for empty project names"],"/causal":["/causal","/causal query why is auth risky?"],"/lab":["/lab","/lab status"],"/inspect":["/inspect","/inspect http://localhost:5173"],"/preview":["/preview http://localhost:5173 1280x800"],"/model":["/model list","/model sonnet4.6","/model save"],"/capsule":["/capsule show","/capsule stats","/capsule clear"],"/ghost":["/ghost learn","/ghost predict add billing settings"],"/fork":["/fork plan migrate dashboard to React"],"/sheriff":["/sheriff scan","/sheriff verify"],"/doctor":["/doctor","/doctor fix","/doctor full","/doctor voice"],"/color":["/color","/color cyan","/color magenta","/color green"]}[e]??[this.getSlashCommands().find(t=>t.name===e)?.usage??e]}getSlashCommands(){return[{name:"/help",aliases:["/commands"],usage:"/help [command]",description:"show command groups and examples"},{name:"/start",usage:"/start [fix|reindex]",description:"onboarding golden path: doctor + index + status + repo briefing"},{name:"/status",usage:"/status",description:"show runtime, session, and index state"},{name:"/index",usage:"/index",description:"re-index workspace and generate file capsules"},{name:"/doctor",usage:"/doctor [brief|full|fix|voice [fix]]",description:"run diagnostics and optional auto-fixes"},{name:"/change",usage:"/change <goal>",description:"make a focused code change, run verification, summarize the diff"},{name:"/intent",usage:"/intent <product intent>",description:"compile a product intent into a phased implementation contract"},{name:"/autopilot",usage:"/autopilot [status|plan|run|pr] <issueUrl|title>",description:"turn an issue into a verified patch with proof bundle and optional PR"},{name:"/issues",usage:"/issues [scan|status] [provider]",description:"scan and run GitHub/Linear/Jira issues through the PR pipeline"},{name:"/fix",usage:"/fix",description:"apply a background-resolved fix for a current linter/compiler error"},{name:"/ghost",usage:"/ghost [learn|profile|predict|divergence|patch] <input>",description:"learn your implementation style and predict how you would write new code"},{name:"/fork",usage:"/fork [plan|fork|status|clear] <intent>",description:"plan and run two competing implementations in isolated branches, compare results"},{name:"/causal",usage:"/causal [build|read|status|query <question>]",description:"build a causal dependency graph of the codebase and query it"},{name:"/brain",usage:"/brain [stats|query <error>|opt-out]",description:"query Mesh Brain for known fix patterns across all workspaces"},{name:"/company",aliases:["/company-brain"],usage:"/company [build|status|query <question>|record <decision>]",description:"build and query a durable memory of architectural decisions and ownership"},{name:"/learn",usage:"/learn [read|learn]",description:"read or refresh the Engineering Memory (coding rules, risk modules)"},{name:"/lab",usage:"/lab [run|status|clear]",description:"run autonomous hypothesis generation to surface hidden bugs and patterns"},{name:"/twin",usage:"/twin [build|read|status]",description:"build a structural model of the codebase for deep cross-file analysis"},{name:"/distill",usage:"/distill",description:"analyze recent changes and update the project brain context"},{name:"/synthesize",usage:"/synthesize",description:"detect structural intent in the last save and auto-propagate changes across the stack"},{name:"/repair",usage:"/repair [analyze|status|clear]",description:"inspect the predictive repair queue for fragile areas near recent changes"},{name:"/audit",usage:"/audit [verify|replay]",description:"verify or replay the audit trail for enterprise compliance"},{name:"/production",usage:"/production [refresh|status|audit|gate|review] [intent]",description:"show production telemetry or run the readiness gate before shipping"},{name:"/sheriff",usage:"/sheriff [scan|verify|lock <file>|drift|status|clear]",description:"fingerprint module semantics and alert when a refactor silently changes behavior"},{name:"/tribunal",usage:"/tribunal <problem>",description:"debate a hard engineering decision across 3 AI perspectives: correctness, performance, resilience"},{name:"/bisect",usage:"/bisect <symptom> [verificationCommand]",description:"autonomous git bisect to find the commit that introduced a symptom"},{name:"/replay",usage:"/replay <traceId|sentryEventId> [commitRange]",description:"replay a production trace locally and find where behavior diverges"},{name:"/whatif",usage:"/whatif <hypothesis>",description:"run a counterfactual analysis of a migration or refactor in an isolated timeline"},{name:"/model",usage:"/model [pick|list|id|save]",description:"switch or save the active model"},{name:"/setup",usage:"/setup [noninteractive key=value ...]",description:"interactive or scripted settings wizard"},{name:"/color",usage:"/color [cyan|magenta|yellow|green|blue|white]",description:"change theme color instantly"},{name:"/compact",usage:"/compact",description:"compress transcript into a session capsule to free context"},{name:"/capsule",aliases:["/memory"],usage:"/capsule [show|compact|clear|export [path]|stats|path]",description:"inspect or manage session capsule"},{name:"/cost",usage:"/cost",description:"show token usage and estimated cost for this session"},{name:"/undo",usage:"/undo",description:"revert the last file change made by the agent"},{name:"/approvals",usage:"/approvals [status|on|off]",description:"control tool auto-approval mode"},{name:"/steps",usage:"/steps [<n>|reset]",description:"set max tool steps for this session"},{name:"/clear",usage:"/clear",description:"clear the terminal"},{name:"/exit",aliases:["/quit"],usage:"/exit",description:"quit"},{name:"/dashboard",usage:"/dashboard",description:"open the local repo operations dashboard in the browser"},{name:"/inspect",usage:"/inspect [url]",description:"attach a visual inspector to a local dev server — Alt+Click elements to describe changes"},{name:"/stop-inspect",usage:"/stop-inspect",description:"detach the visual inspector"},{name:"/preview",usage:"/preview <url> [widthxheight] [protocol]",description:"render a frontend screenshot in the terminal via Chrome CDP"},{name:"/hologram",usage:"/hologram start <cmd>",description:"run a process with V8 memory telemetry — if it crashes, get the exact variable states"},{name:"/entangle",usage:"/entangle <path>",description:"link a second repository so the agent can read and cross-reference both workspaces"},{name:"/chatops",usage:"/chatops [investigate|approve|status] [platform] [message|threadId]",description:"run a Slack/Discord investigation or approval flow from the terminal"},{name:"/daemon",usage:"/daemon [start|status|digest|stop]",description:"control the Mesh background daemon"},{name:"/sync",usage:"/sync",description:"check cloud cache synchronization status"},{name:"/voice",usage:"/voice [on|off|setup]",description:"toggle or configure Speech-to-Speech mode"},{name:"/resurrect",usage:"/resurrect [capture|checkpoint <note>|status|clear]",description:"capture session intent and restore full context in a future session"}]}async handleSlashCommand(e,t){const s=e.trim();if(!s.startsWith("/"))return{wasHandled:!1,shouldExit:!1};const[i,...n]=s.split(/\s+/g),a=i.toLowerCase(),o=["/help","/start","/status","/index","/dashboard","/sync","/setup","/color","/clear","/model","/cost","/compact","/capsule","/memory","/approvals","/steps","/undo","/doctor","/exit","/quit","/reset","/debug","/commands","/voice","/distill","/synthesize","/company","/company-brain","/twin","/repair","/daemon","/issues","/autopilot","/change","/chatops","/production","/replay","/bisect","/whatif","/audit","/brain","/learn","/intent","/causal","/lab","/fork","/ghost","/hologram","/entangle","/inspect","/stop-inspect","/preview","/fix","/tribunal","/resurrect","/sheriff"];let r=a;if(o.includes(a))r=a;else{const e=o.filter(e=>e.startsWith(a));e.length>0&&(r=e[0])}try{switch(r){case"/undo":{const e=$({text:"Undoing last change...",color:"yellow"}).start();try{const t=await this.backend.callTool("workspace.undo",{});t.ok?e.succeed(y.green(t.message)):e.fail(y.red(t.error))}catch(t){e.fail(y.red(`Undo failed: ${t.message}`))}return{wasHandled:!0,shouldExit:!1}}case"/inspect":{const e=n[0]||"http://localhost:3000";return await this.handleInspect(e),{wasHandled:!0,shouldExit:!1}}case"/stop-inspect":return await this.portal.stop(),f.write(y.green("\n[Mesh Portal] Browser detached and overlay removed.\n")),{wasHandled:!0,shouldExit:!1};case"/help":case"/commands":return this.printHelp(n),{wasHandled:!0,shouldExit:!1};case"/start":return await this.runStart(n,t),{wasHandled:!0,shouldExit:!1};case"/status":return await this.printStatus(),{wasHandled:!0,shouldExit:!1};case"/index":return await this.runIndexing(),{wasHandled:!0,shouldExit:!1};case"/distill":return await this.distillProjectBrain(),{wasHandled:!0,shouldExit:!1};case"/synthesize":return await this.runSynthesize(),{wasHandled:!0,shouldExit:!1};case"/company":case"/company-brain":return await this.runCompanyBrain(n),{wasHandled:!0,shouldExit:!1};case"/twin":return await this.runDigitalTwin(n),{wasHandled:!0,shouldExit:!1};case"/repair":return await this.runPredictiveRepair(n),{wasHandled:!0,shouldExit:!1};case"/daemon":return await this.runDaemon(n),{wasHandled:!0,shouldExit:!1};case"/issues":return await this.runIssuePipeline(n),{wasHandled:!0,shouldExit:!1};case"/autopilot":return await this.runIssueAutopilot(n),{wasHandled:!0,shouldExit:!1};case"/change":return await this.runChange(n,t),{wasHandled:!0,shouldExit:!1};case"/chatops":return await this.runChatops(n),{wasHandled:!0,shouldExit:!1};case"/production":return await this.runProductionStatus(n),{wasHandled:!0,shouldExit:!1};case"/replay":return await this.runReplayTrace(n),{wasHandled:!0,shouldExit:!1};case"/bisect":return await this.runSymptomBisect(n),{wasHandled:!0,shouldExit:!1};case"/whatif":return await this.runWhatIf(n),{wasHandled:!0,shouldExit:!1};case"/audit":return await this.runAudit(n),{wasHandled:!0,shouldExit:!1};case"/brain":return await this.runMeshBrain(n),{wasHandled:!0,shouldExit:!1};case"/learn":return await this.runEngineeringMemory(n),{wasHandled:!0,shouldExit:!1};case"/intent":return await this.runIntentCompile(n),{wasHandled:!0,shouldExit:!1};case"/causal":return await this.runCausalIntelligence(n),{wasHandled:!0,shouldExit:!1};case"/lab":return await this.runDiscoveryLab(n),{wasHandled:!0,shouldExit:!1};case"/fork":return await this.runRealityFork(n),{wasHandled:!0,shouldExit:!1};case"/ghost":return await this.runGhostEngineer(n),{wasHandled:!0,shouldExit:!1};case"/fix":return await this.runFix(),{wasHandled:!0,shouldExit:!1};case"/tribunal":return await this.runTribunal(n),{wasHandled:!0,shouldExit:!1};case"/resurrect":return await this.runSessionResurrection(n),{wasHandled:!0,shouldExit:!1};case"/sheriff":return await this.runSemanticSheriff(n),{wasHandled:!0,shouldExit:!1};case"/hologram":return await this.runHologram(n),{wasHandled:!0,shouldExit:!1};case"/entangle":return await this.runEntangle(n),{wasHandled:!0,shouldExit:!1};case"/preview":return await this.runFrontendPreview(n),{wasHandled:!0,shouldExit:!1};case"/dashboard":return await this.launchDashboard(),{wasHandled:!0,shouldExit:!1};case"/sync":return await this.printSync(),{wasHandled:!0,shouldExit:!1};case"/color":return await this.handleColorCommand(n,t),{wasHandled:!0,shouldExit:!1};case"/setup":return{wasHandled:!0,shouldExit:(await this.handleSetupCommand(n,t)).shouldExit};case"/clear":return f.write(this.useAnsi?"":"\n"),this.printBanner(),{wasHandled:!0,shouldExit:!1};case"/model":return{wasHandled:!0,shouldExit:(await this.handleModelCommand(n,t)).shouldExit};case"/cost":return this.printCost(),{wasHandled:!0,shouldExit:!1};case"/compact":return f.write(this.themeColor(`\n${await this.compactTranscript()}\n`)),{wasHandled:!0,shouldExit:!1};case"/capsule":case"/memory":return await this.handleCapsuleCommand(n),{wasHandled:!0,shouldExit:!1};case"/approvals":return this.handleApprovalsCommand(n),{wasHandled:!0,shouldExit:!1};case"/steps":return this.handleStepsCommand(n),{wasHandled:!0,shouldExit:!1};case"/doctor":return await this.runDoctor(n),{wasHandled:!0,shouldExit:!1};case"/exit":case"exit":case"/quit":return{wasHandled:!0,shouldExit:!0};case"/reset":return this.transcript=[],f.write(y.green("\nTranscript reset.\n")),{wasHandled:!0,shouldExit:!1};case"/voice":const e=n[0]?.toLowerCase();if("setup"===e){const e=await R(),s=await this.runVoiceSetupWizard(t,e.voice);if(!s)return f.write(y.dim("\nVoice setup cancelled.\n")),{wasHandled:!0,shouldExit:!1};const i={...e,voice:s};return await j(i),this.applyVoiceSettings(s),f.write(["",y.green("Voice settings saved."),`${y.dim("language:")} ${s.language}`,`${y.dim("mic:")} ${s.microphone}`,`${y.dim("voice:")} ${s.voice}`,""].join("\n")),{wasHandled:!0,shouldExit:!1}}if(this.voiceMode="on"===e||"off"!==e&&!this.voiceMode,this.voiceMode){if(this.syncVoiceLanguage(),!this.config.agent.voice.configured){const e=await R(),s=await this.runVoiceSetupWizard(t,e.voice);if(!s)return this.voiceMode=!1,f.write(y.dim("\nVoice setup cancelled.\n")),{wasHandled:!0,shouldExit:!1};const i={...e,voice:s};await j(i),this.applyVoiceSettings(s)}const e=await this.voiceManager.checkDependencies(),s=e.filter(e=>!e.ok&&e.required);if(s.length>0){f.write(y.yellow("\nVoice dependencies missing.\n"));s.filter(e=>"ffmpeg"===e.name).length>0&&await this.ensureVoiceCoreDependencies(e);const t=(await this.voiceManager.checkDependencies()).filter(e=>!e.ok&&e.required);t.length>0&&(this.voiceMode=!1,f.write(y.red(`Voice mode remains OFF. Missing: ${t.map(e=>e.name).join(", ")}\n`)))}}return f.write(`\nVoice mode: ${this.voiceMode?y.green("ON"):y.red("OFF")}\n`),this.voiceMode&&f.write(`${y.dim(this.getVoiceExitHint())}\n`),{wasHandled:!0,shouldExit:!1};default:return f.write(`\nUnknown command: ${a} (resolved to ${r}). Use /help.\n`),{wasHandled:!0,shouldExit:!1}}}catch(e){const t=e instanceof Error?e.message:String(e);return f.write(y.red(`\n[Mesh] Error: Command "${r}" failed — ${t.slice(0,200)}. Try /doctor to diagnose.\n`)),{wasHandled:!0,shouldExit:!1}}}async handleModelCommand(e,t){const s=c(e),a=[...s.positionals,s.keyValues.model??""].join(" ").trim();if(!a||"pick"===a||"choose"===a)return await this.chooseModelInteractive(t),{shouldExit:!1};if("list"===a||"ls"===a)return f.write(["",`${this.themeColor(y.bold("Available Models"))}`,...J.map(e=>{const t=e.aliases.join(", "),s=e.value===this.currentModelId?y.green(" active"):"";return`${e.label} ${y.dim(e.value)}${s}\n${y.dim(`aliases: ${t} | ${e.note}`)}`}),""].join("\n")),{shouldExit:!1};if("current"===a)return f.write(`\ncurrent model: ${this.currentModelId}\n`),{shouldExit:!1};if("save"===a){const e=await R();return await j({...e,modelId:this.currentModelId}),f.write(`\ndefault model saved: ${this.themeColor(i(this.currentModelId))}\n`),{shouldExit:!1}}const o=l(a);return!o&&a.startsWith("/")?(f.write(`\nInvalid model argument: ${a}\n`),{shouldExit:!1}):(this.currentModelId=o?.value??n(a),f.write(`\nmodel switched: ${this.themeColor(i(this.currentModelId))}\n`),{shouldExit:!1})}async chooseModelInteractive(e){const t=J.map(e=>({name:e.value,message:`${y.bold(e.label)} ${y.dim(e.note)}`,hint:e.value===this.currentModelId?y.green("(active)"):y.dim(e.value)})),s=new E({name:"model",message:"Select an AI model",choices:t,stdin:g,stdout:f});try{const t=await s.run();e.resume(),this.setupGhostText(e,g,f);const i=J.find(e=>e.value===t);this.currentModelId=i.value,f.write(`\nmodel switched: ${this.themeColor(i.label)}\n`);const n=new _({name:"save",message:"Save as default model?",stdin:g,stdout:f}),a=await n.run();if(e.resume(),this.setupGhostText(e,g,f),a){const e=await R();await j({...e,modelId:i.value}),f.write(y.green("Default model saved.\n"))}}catch{e.resume(),this.setupGhostText(e,g,f),f.write(y.dim("\nSelection cancelled.\n"))}}completeInput(e){const t=this.getSlashCommands().flatMap(e=>[e.name,...e.aliases??[]]),s=e.trimStart();if(!s.startsWith("/"))return[[],e];const i=s.split(/\s+/g),n=i[0].toLowerCase(),a=i[i.length-1]?.toLowerCase()??"";if(i.length<=1&&!e.endsWith(" ")){const e=t.filter(e=>e.startsWith(n));return e.length>1?[[e[0]],n]:[e.length?e:t,n]}const o=["list","current","save","pick",...J.flatMap(e=>e.aliases)],r=["show","compact","clear","export","stats","path"],c=["status","on","off"],l=["brief","full","voice","fix"],d=["fix","reindex"],u=["fix","add","remove","refactor","validate"],h=["noninteractive","model=","cloud=","theme=","key=","endpoint=","voice_lang=","voice_speed=","voice_voice="],p=["on","off","setup"],m=["build","read","status"],g=["analyze","status","clear"],f=["read","learn"],w=["build","read","status","query"],y=["run","status","clear"],$=["plan","fork","status","clear"],k=["learn","profile","status","predict","divergence","patch","clear"];let v=[];switch(n){case"/model":v=o;break;case"/capsule":case"/memory":v=r;break;case"/approvals":v=c;break;case"/doctor":v=l;break;case"/start":v=d;break;case"/change":v=u;break;case"/setup":v=h;break;case"/voice":v=p;break;case"/twin":v=m;break;case"/repair":v=g;break;case"/learn":v=f;break;case"/causal":v=w;break;case"/lab":v=y;break;case"/fork":v=$;break;case"/ghost":v=k;break;default:v=[]}const b=e.endsWith(" ")?"":a,x=v.filter(e=>e.toLowerCase().startsWith(b));return[x.length?x:v,b]}async handleCapsuleCommand(e){const t=(e[0]||"show").toLowerCase();if("clear"===t)return this.sessionCapsule=null,await this.sessionStore.clear(),void f.write("\nSession capsule cleared.\n");if("compact"===t)return void f.write(this.themeColor(`\n${await this.compactTranscript()}\n`));if("export"===t)return void await this.exportSessionCapsule(e[1]);if("path"===t)return void f.write(`\n${this.getDefaultCapsuleExportPath()}\n`);if(!this.sessionCapsule)return void f.write("\nNo active session capsule.\n");const s=this.parseSessionCapsule(this.sessionCapsule.summary);"stats"!==t?f.write(["",`${this.themeColor(y.bold("Session Capsule"))}`,`${y.dim("generated:")} ${this.sessionCapsule.generatedAt}`,`${y.dim("scope:")} ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,"",this.formatStructuredCapsule(s),""].join("\n")):f.write(["",`${this.themeColor(y.bold("Capsule Stats"))}`,`${y.dim("generated:")} ${this.sessionCapsule.generatedAt}`,`${y.dim("scope:")} ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,`${y.dim("decisions:")} ${s.decisions.length}`,`${y.dim("open threads:")} ${s.openThreads.length}`,`${y.dim("next actions:")} ${s.nextActions.length}`,`${y.dim("files:")} ${s.filesTouched.length}`,`${y.dim("tools:")} ${s.toolActivity.length}`,""].join("\n"))}handleApprovalsCommand(e){const t=(e[0]||"status").toLowerCase();return"on"===t?(this.autoApproveTools=!0,void f.write("\nAuto-approval enabled for write/run tools.\n")):"off"===t?(this.autoApproveTools=!1,void f.write("\nAuto-approval disabled.\n")):void f.write(`\nAuto-approval: ${this.autoApproveTools?"on":"off"}\n`)}async handleColorCommand(e,t){const s=e[0]?.toLowerCase();if(s&&Y.has(s))return void await this.applyAndSaveTheme(s);if(s&&!Y.has(s))return void f.write(`\nInvalid color: ${s}. Allowed: ${Array.from(Y).join(", ")}\n`);const i=await R();try{const e=Array.from(Y).map(e=>({name:e,message:y[e](e),hint:e===i.themeColor?y.green("(current)"):""})),s=new E({name:"themeColor",message:"Select Theme Color",choices:e,initial:Array.from(Y).indexOf(i.themeColor),stdin:g,stdout:f}),n=await s.run();t.resume(),await this.applyAndSaveTheme(n)}catch{f.write(y.dim("\nColor change cancelled.\n"))}}async applyAndSaveTheme(e){const t=y[e];"function"==typeof t&&(this.themeColor=t),this.config.agent.themeColor=e;const s=await R();await j({...s,themeColor:e}),f.write(`\nTheme: ${this.themeColor(y.bold(e))}\n`)}handleStepsCommand(e){const t=(e[0]||"").toLowerCase();if(!t||"status"===t)return void f.write(`\nMax steps: ${this.dynamicMaxSteps} (default: ${this.config.agent.maxSteps})\n`);if("reset"===t)return this.dynamicMaxSteps=this.config.agent.maxSteps,void f.write(`\nMax steps reset to ${this.dynamicMaxSteps}.\n`);const s=parseInt(t,10);isNaN(s)||s<1||s>100?f.write("\nUsage: /steps <1-100> | reset\n"):(this.dynamicMaxSteps=s,f.write(`\nMax steps set to ${this.dynamicMaxSteps}.\n`))}async handleSetupCommand(e,t){const s=c(e);if("noninteractive"!==s.positionals[0]?.toLowerCase())return await this.runSetup(t),{shouldExit:!1};const a=await R(),o=s.keyValues;if(0===Object.keys(o).length)return f.write(["","Usage: /setup noninteractive model=sonnet4.6 cloud=on theme=cyan key=- endpoint=- google_key_mode=proxy google_key=<key> voice_lang=auto voice_mic=default voice_voice=auto","Keys: model, cloud, theme, key, endpoint, google_key_mode (proxy|own), google_key, voice_lang, voice_mic, voice_voice",""].join("\n")),{shouldExit:!1};const r=o.model?l(String(o.model)):null;if(o.model&&!r&&!String(o.model).includes("."))return f.write(`\nUnknown model alias: ${o.model}. Use /model list.\n`),{shouldExit:!1};if(o.theme&&!Y.has(String(o.theme)))return f.write(`\nInvalid theme: ${o.theme}. Allowed: ${Array.from(Y).join(", ")}\n`),{shouldExit:!1};if(o.google_key_mode&&!["proxy","own"].includes(String(o.google_key_mode)))return f.write(`\nInvalid google_key_mode: ${o.google_key_mode}. Use "proxy" or "own".\n`),{shouldExit:!1};if(o.voice_speed&&(!Number.isFinite(Number(o.voice_speed))||Number(o.voice_speed)<120||Number(o.voice_speed)>420))return f.write(`\nInvalid voice_speed: ${o.voice_speed}. Use a value between 120 and 420.\n`),{shouldExit:!1};const d=o.google_key_mode?String(o.google_key_mode):a.googleKeyMode,u="-"===o.google_key?void 0:void 0!==o.google_key?String(o.google_key):a.ownGoogleApiKey,h={modelId:o.model?r?.value??n(String(o.model)):a.modelId,enableCloudCache:o.cloud?["1","true","on","yes","y"].includes(String(o.cloud).toLowerCase()):a.enableCloudCache,themeColor:o.theme?String(o.theme):a.themeColor,customApiKey:"-"===o.key?void 0:void 0!==o.key?String(o.key):a.customApiKey,customEndpoint:"-"===o.endpoint?void 0:void 0!==o.endpoint?String(o.endpoint):a.customEndpoint,googleKeyMode:d,ownGoogleApiKey:u,voice:{configured:a.voice.configured||void 0!==o.voice_lang||void 0!==o.voice_mic||void 0!==o.voice_speed||void 0!==o.voice_voice,language:o.voice_lang?String(o.voice_lang):a.voice.language,microphone:o.voice_mic?String(o.voice_mic):a.voice.microphone,speed:o.voice_speed?Number(o.voice_speed):a.voice.speed,voice:o.voice_voice?String(o.voice_voice):a.voice.voice}};return await j(h),this.config.bedrock.ownGoogleApiKey=u,this.config.bedrock.googleApiKey="own"===d?u:void 0,this.rebuildLlmClient(),this.applyVoiceSettings(h.voice),f.write(["",`${y.green("Settings updated.")}`,`${y.dim("model:")} ${i(h.modelId)}`,`${y.dim("cloud:")} ${h.enableCloudCache?"on":"off"}`,`${y.dim("theme:")} ${h.themeColor}`,`${y.dim("google:")} ${d??"proxy"}`,`${y.dim("voice:")} ${h.voice.language} / ${h.voice.microphone} / ${h.voice.voice}`,""].join("\n")),{shouldExit:!1}}async runDoctor(e=[]){const t=e.includes("full"),s=e.includes("voice"),i=e.includes("fix");if(s){let e=await this.voiceManager.checkDependencies();f.write(this.themeColor(`\n${y.bold("Voice Diagnostics")}\n`));for(const t of e){const e=!1!==t.required,s=t.ok?y.green("✔"):e?y.red("✘"):y.yellow("•"),i=t.ok?y.green("Available"):e?y.red("Missing"):y.yellow("Optional");f.write(`${s} ${t.name.padEnd(15)} ${i}\n`),!t.ok&&t.hint&&f.write(` ${y.dim(`Hint: ${t.hint}`)}\n`)}return this.voiceManager.hasGeminiStt()?f.write(`${y.green("✔")} ${"stt/tts".padEnd(15)} ${y.green("Gemini Flash")} ${y.dim("(via GOOGLE_API_KEY)")}\n`):f.write(`${y.red("✘")} ${"stt/tts".padEnd(15)} ${y.red("GOOGLE_API_KEY not set")} ${y.dim("— run /setup to configure")}\n`),f.write(`${y.dim("•")} ${"voice config".padEnd(15)} ${y.dim(`lang:${this.config.agent.voice.language} voice:${this.config.agent.voice.voice} mic:${this.config.agent.voice.microphone}`)}\n`),void(i&&(e=await this.ensureVoiceCoreDependencies(e)))}const n=(e[0]||"brief").toLowerCase();f.write(this.themeColor(`\n${y.bold("Mesh System Diagnostics")}\n`));const a=$({text:"Running doctor checks...",color:"cyan"}).start();try{const e=new O(this.config);let s=await e.run(),o=[];if(i&&(a.text="Applying safe doctor fixes...",o=await e.autoFix(),s=await e.run()),a.stop(),o.length>0){f.write(y.bold("\nApplied safe fixes\n"));for(const e of o){const t=e.ok?y.green("✔"):y.red("✘");f.write(`${t} ${e.message}\n`);for(const t of e.details??[])f.write(` ${y.dim(t)}\n`)}f.write("\n")}for(const e of s.checks){const s="pass"===e.status?y.green("✔"):"warn"===e.status?y.yellow("⚠"):y.red("✘"),i="pass"===e.status?y.white:"warn"===e.status?y.yellow:y.red;if(f.write(`${s} ${y.bold(i(e.title.padEnd(25)))} ${e.message}\n`),(t||"brief"===n||"pass"!==e.status)&&e.details&&e.details.length>0)for(const t of e.details)f.write(` ${y.dim(t)}\n`);const a=(e.fixes??[]).filter(t=>!t.automatic||"pass"!==e.status);if(a.length>0&&"pass"!==e.status)for(const e of a){const t=e.automatic?"auto":"manual";f.write(` ${y.dim(`fix (${t}): ${e.title} - ${e.description}`)}\n`),e.command&&f.write(` ${y.dim(`command: ${e.command}`)}\n`)}f.write("\n")}s.ok?f.write(y.green(y.bold("All systems operational. Mesh is ready for duty.\n"))):f.write(y.red(y.bold("Some systems are failing. Check the warnings above to restore full functionality.\n")));const r=await this.backend.callTool("workspace.get_index_status",{});f.write(`\n${y.dim("Workspace index: ")} ${r?.percent??0}% (${r?.indexedFiles??0} files)\n\n`)}catch(e){a.fail(y.red(`Doctor failed unexpectedly: ${e.message}`))}}async ensureVoiceCoreDependencies(e){const t=e??await this.voiceManager.checkDependencies(),s=t.filter(e=>!e.ok&&"ffmpeg"===e.name).map(e=>e.name);if(0===s.length)return f.write(y.green("\nCore voice dependencies are already installed.\n")),t;if(!this.voiceManager.hasHomebrew())return f.write(y.red("\nHomebrew is not installed. Install it from https://brew.sh and rerun /doctor voice fix.\n")),t;const i=new _({name:"installVoiceDeps",message:`Install missing voice dependencies with Homebrew? (${s.join(", ")})`,initial:!0});if(!Boolean(await i.run().catch(()=>!1)))return f.write(y.dim("\nInstallation cancelled.\n")),t;const n=this.useAnsi?$({text:`Installing voice dependencies (${s.join(", ")})...`,color:"cyan",stream:f}).start():void 0;n||f.write(this.themeColor(`\nInstalling voice dependencies (${s.join(", ")})...\n`));try{await this.voiceManager.installCoreDependencies(s,{quiet:!0});const e=await this.voiceManager.checkDependencies();n?n.succeed(`Voice dependencies installed: ${s.join(", ")}`):f.write(y.green("\nVoice dependency installation complete.\n"));for(const t of e.filter(e=>!1!==e.required)){const e=t.ok?y.green("✔"):y.red("✘");f.write(`${e} ${t.name.padEnd(15)} ${t.ok?y.green("Available"):y.red("Missing")}\n`)}return e}catch(e){n&&n.fail("Voice dependency installation failed.");const s=e instanceof Error?e.message:String(e);return f.write(y.red(`\nVoice dependency installation failed: ${s}\n`)),t}}async exportSessionCapsule(e){if(!this.sessionCapsule)return void f.write("\nNo active session capsule to export.\n");const t=e?p.resolve(this.config.agent.workspaceRoot,e):this.getDefaultCapsuleExportPath(),s=this.parseSessionCapsule(this.sessionCapsule.summary),i=["# Session Capsule","",`- Generated: ${this.sessionCapsule.generatedAt}`,`- Workspace: ${this.config.agent.workspaceRoot}`,`- Scope: ${this.sessionCapsule.sourceMessages} -> ${this.sessionCapsule.retainedMessages} messages`,"",this.formatStructuredCapsule(s),""].join("\n");await u.mkdir(p.dirname(t),{recursive:!0}),await u.writeFile(t,i,"utf8"),f.write(`\nSession capsule exported to ${t}\n`)}buildDynamicRuntimeContext(){const e=[];this.currentTurnPreferredTools.length>0&&e.push(`[TOOL ROUTING]\nFor this turn, prefer these tools when useful: ${this.currentTurnPreferredTools.slice(0,24).join(", ")}`),this.gitStatusContext&&e.push(`\n[GIT REPOSITORY STATUS]\nCurrent branch: ${r(this.gitStatusContext,1200)}`),this.prefetchQueue.length>0&&(e.push("\n[PREDICTIVE CONTEXT PREFETCH]\nThe following file capsules were pre-loaded because they are highly likely to be relevant to your current task:"),e.push(...this.prefetchQueue.slice(0,2).map(e=>r(e,1200))),this.prefetchQueue=[]);try{const t=p.join(this.config.agent.workspaceRoot,".mesh","project-brain.md"),s=h(t,"utf8");s&&e.push(`\n[FRACTAL PROJECT CONTEXT (Project Brain)]\nAdhere to these distilled architectural rules and conventions specific to this project:\n${r(s,2400)}`)}catch{}try{const t=p.join(this.config.agent.workspaceRoot,".mesh","company-brain","summary.md"),s=h(t,"utf8");s&&e.push(`\n[COMPANY CODEBASE BRAIN]\nUse these durable repo facts, rules, risks, and decisions before proposing changes:\n${r(s,3200)}`)}catch{}try{const t=p.join(this.config.agent.workspaceRoot,".mesh","engineering-memory.json"),s=h(t,"utf8"),i=JSON.parse(s);if(i&&(i.rules?.length||i.decisions?.length)){const t=["Rules:",...(i.rules||[]).map(e=>`- ${e.rule||e}`),"Decisions:",...(i.decisions||i.acceptedPatterns||[]).map(e=>`- ${e.pattern||e}`)].join("\n");e.push(`\n[ENGINEERING MEMORY (Session Distiller)]\nApply these distilled project decisions and rules learned from previous sessions:\n${r(t,2400)}`)}}catch{}return this.voiceMode&&(e.push(`\nVoice Instructions:\n${z}`),e.push(`Voice Language:\n${this.buildVoiceLanguageInstruction()}`)),this.localInstructions&&e.push(`\nLocal Project Instructions:\n${r(this.localInstructions,2400)}`),this.workspaceContext&&e.push(r(this.workspaceContext,1200)),e.join("\n\n")}async autoCompactIfNeeded(){return this.transcript.length<30&&this.estimateTranscriptChars()<22e4?null:this.compactTranscript({reason:"auto"})}async compactTranscript(e){if(0===this.transcript.length)return"Transcript already empty. No compaction needed.";const t=this.transcript.length,s=Math.min(12,t),i=this.transcript.slice(-s),n=this.transcript.slice(0,Math.max(0,t-s)),a=await this.buildSessionCapsuleSummary(n,i);this.sessionCapsule={summary:a,generatedAt:(new Date).toISOString(),sourceMessages:t,retainedMessages:s},this.transcript=i,await this.sessionStore.save(this.sessionCapsule);return`${"auto"===e?.reason?"Auto-compacted session.":"Session compacted."} Retained ${s} recent messages, compressed ${Math.max(0,t-s)} older messages into capsule.`}async buildSessionCapsuleSummary(e,t){const s=this.buildHeuristicSessionCapsuleSummary(e,t),i=`You are a memory compression module for an autonomous AI agent.\nYour task is to refine the following raw heuristic session summary into a highly condensed, intent-preserving "Session Capsule".\nCRITICAL RULES:\n1. Preserve Tone, User Intent, Key Decisions, and Emotional Register.\n2. Maintain the structure: Summary, Decisions, Open Threads, Next Actions, Files Touched.\n3. Keep it terse and under 800 words.\n4. Output ONLY the refined capsule text. Do not add conversational filler.\n\nRaw Heuristic Summary:\n${s}`;try{const e=await this.llm.converse([{role:"user",content:[{text:i}]}],[],"You are a memory compression module.");if("text"===e.kind&&e.text.trim())return e.text}catch(e){}return s}buildHeuristicSessionCapsuleSummary(t,i){const n=[],a=[],o=[],r=[],c=[];for(const e of t)for(const t of e.content){if("text"in t&&t.text.trim()){const s=this.normalizeCapsuleLine(t.text);if(!s)continue;"user"===e.role?n.length<8&&n.push(s):a.length<8&&a.push(s)}if("toolUse"in t){const e=s(t.toolUse.input);o.push(`${t.toolUse.name} ${e}`);const i=t.toolUse.input;"string"==typeof i.path&&i.path.trim()&&c.push(i.path.trim())}if("toolResult"in t){const e=t.toolResult.content.find(e=>"text"in e&&"string"==typeof e.text);if(e&&"text"in e){const t=this.normalizeCapsuleLine(e.text);t&&r.push(t)}}}const l=this.sessionCapsule?this.parseSessionCapsule(this.sessionCapsule.summary):null,d={summary:this.normalizeCapsuleLine(a[a.length-1]||n[n.length-1]||`Conversation progressed through ${t.length} summarized messages.`,220),decisions:e([...l?.decisions??[],...a.slice(-4),...r.filter(e=>/saved|updated|created|switched|cleared|exported|connected|indexed/i.test(e))].map(e=>this.normalizeCapsuleLine(e,160)),20),openThreads:e([...l?.openThreads??[],...n.slice(-5),...r.filter(e=>/error|failed|denied|omitted|unknown/i.test(e))].map(e=>this.normalizeCapsuleLine(e,160)),20),nextActions:e([...l?.nextActions??[],...a.filter(e=>/next|should|can|recommend|suggest/i.test(e)),i.length?`Continue from ${i.length} preserved recent messages.`:""].map(e=>this.normalizeCapsuleLine(e,160)),15),filesTouched:e([...l?.filesTouched??[],...c].map(e=>this.normalizeCapsuleLine(e,120)),50),toolActivity:e([...l?.toolActivity??[],...o.slice(-8),...r.slice(-4)].map(e=>this.normalizeCapsuleLine(e,160)),20)};return this.serializeStructuredCapsule(d)}serializeStructuredCapsule(e){return[`summary: ${e.summary}`,...this.serializeCapsuleSection("decisions",e.decisions),...this.serializeCapsuleSection("open_threads",e.openThreads),...this.serializeCapsuleSection("next_actions",e.nextActions),...this.serializeCapsuleSection("files_touched",e.filesTouched),...this.serializeCapsuleSection("tool_activity",e.toolActivity)].join("\n")}serializeCapsuleSection(e,t){return[`${e}:`,...t.length?t.map(e=>`- ${e}`):["- none"]]}parseSessionCapsule(e){const t=String(e||"").split("\n"),s={summary:"",decisions:[],openThreads:[],nextActions:[],filesTouched:[],toolActivity:[]};let i=null;for(const e of t){const t=e.trim();if(t)if(t.startsWith("summary:"))s.summary=t.slice(8).trim(),i=null;else if("decisions:"!==t)if("open_threads:"!==t)if("next_actions:"!==t)if("files_touched:"!==t)if("tool_activity:"!==t){if(t.startsWith("- ")&&i){const e=t.slice(2).trim();e&&"none"!==e&&s[i].push(e)}}else i="toolActivity";else i="filesTouched";else i="nextActions";else i="openThreads";else i="decisions"}return s.summary||(s.summary=this.normalizeCapsuleLine(e,220)),s}formatStructuredCapsule(e){return[`Summary: ${e.summary}`,...this.formatCapsuleSection("Decisions",e.decisions),...this.formatCapsuleSection("Open Threads",e.openThreads),...this.formatCapsuleSection("Next Actions",e.nextActions),...this.formatCapsuleSection("Files Touched",e.filesTouched),...this.formatCapsuleSection("Tool Activity",e.toolActivity)].join("\n")}formatCapsuleSection(e,t){return["",e,...t.length?t.map(e=>`- ${e}`):["- none"]]}getDefaultCapsuleExportPath(){return p.join(this.config.agent.workspaceRoot,".mesh","session-capsule.md")}normalizeCapsuleLine(e,t=180){const s=e.replace(/\s+/g," ").trim();return s?s.length>t?`${s.slice(0,t-3)}...`:s:""}estimateTranscriptChars(){return this.transcript.reduce((e,t)=>e+t.content.reduce((e,t)=>"text"in t?e+t.text.length:"toolUse"in t?e+JSON.stringify(t.toolUse.input).length+t.toolUse.name.length:"toolResult"in t?e+JSON.stringify(t.toolResult).length:e,0),0)}}export function sanitizeLlmOutput(e){const t=function(e){const t=e.match(/[^\n]*\n|[^\n]+/g)??(e?[e]:[]),s=[];let i="",n=!1;const a=e=>{i&&(s.push({text:i,isCode:e}),i="")};for(const e of t)/^\s*```/.test(e)?n?(i+=e,a(!0),n=!1):(a(!1),i+=e,n=!0):i+=e;return a(n),s}(String(e??""));if(0===t.length)return"";const s=t.findIndex(e=>!e.isCode),i=t.findLastIndex(e=>!e.isCode),n=t.map((e,t)=>{if(e.isCode)return e.text;let n=function(e){return e.replace(/<thinking>[\s\S]*?<\/thinking>/g,"").replace(/<thought>[\s\S]*?<\/thought>/g,"").replace(/<reflection>[\s\S]*?<\/reflection>/g,"").replace(/<scratchpad>[\s\S]*?<\/scratchpad>/g,"").replace(/<\/?(artifact|result|answer)[^>]*>/g,"").replace(/<\/?(thinking|thought|reflection|scratchpad)[^>]*>/g,"").replace(/\\n/g,"\n").replace(/\n{4,}/g,"\n\n").replace(/^\s*\|\s*$/gm,"")}(e.text);return t===s&&(n=n.trimStart()),t===i&&(n=n.trimEnd()),n}).join("");return(n.match(/^```/gm)||[]).length%2==0?n:`${n}\n\`\`\``}
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- function e(e,o){const r=process.env[e];return r&&r.trim()?r.trim():o}function o(e,o){const r=process.env[e];if(!r)return o;const t=Number(r);if(Number.isNaN(t))throw new Error(`Invalid numeric env var ${e}: ${r}`);return t}function r(e,o){try{const o=JSON.parse(e);if(!Array.isArray(o)||o.some(e=>"string"!=typeof e))throw new Error("must be a JSON array of strings");return o}catch(e){throw new Error(`Invalid ${o}: ${e.message}`)}}function t(e){const o=e?.trim();return!o||p.has(o)?u:o}function n(){const e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;return e?.trim()||void 0}function s(e){const o=Number(e?.speed);return{configured:!0===e?.configured,language:e?.language?.trim()||E.language,speed:Number.isFinite(o)?o:E.speed,voice:e?.voice?.trim()||E.voice,microphone:e?.microphone?.trim()||E.microphone}}import c from"node:fs/promises";import i from"node:os";import a from"node:path";import{config as m}from"dotenv";import{DEFAULT_FALLBACK_MODEL_IDS as l,DEFAULT_MODEL_ID as u}from"./model-catalog.js";m();const p=new Set(["us.anthropic.claude-sonnet-4-5-20250929-v1:0","us.anthropic.claude-3-5-sonnet-20240620-v1:0","us.anthropic.claude-sonnet-4-6","us.anthropic.claude-opus-4-6-v1","us.anthropic.claude-haiku-4-5-20251001-v1:0"]);export function shortPathLabel(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)||e}const d=a.join(i.homedir(),".config","mesh","settings.json"),E={configured:!1,language:"auto",speed:260,voice:"auto",microphone:"default"};export async function loadUserSettings(){try{const e=await c.readFile(d,"utf-8"),o=JSON.parse(e);return{modelId:t(o.modelId),themeColor:o.themeColor||"cyan",enableCloudCache:"boolean"!=typeof o.enableCloudCache||o.enableCloudCache,telemetry:o.telemetry,customApiKey:o.customApiKey,customEndpoint:o.customEndpoint,voice:s(o.voice)}}catch{return{modelId:u,themeColor:"cyan",enableCloudCache:!0,voice:E}}}export async function saveUserSettings(e){const o=a.dirname(d);await c.mkdir(o,{recursive:!0,mode:448}),await c.writeFile(d,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}export async function loadConfig(){const i=await loadUserSettings(),m=a.resolve(process.env.WORKSPACE_ROOT||process.cwd());let u={};try{const e=await c.readFile(a.join(m,".mesh","config.json"),"utf-8");u=JSON.parse(e)}catch{}const p=(d=process.env.AGENT_MODE,"mcp"===String(d||"local").trim().toLowerCase()?"mcp":"local");var d;const E=process.env.MESH_MCP_ARGS??"[]",h=process.env.MESH_MCP_COMMAND?.trim(),v=t(process.env.MESH_MODEL_ID||process.env.BEDROCK_MODEL_ID||u.modelId||i.modelId),_=(f="MESH_FALLBACK_MODEL_IDS",(process.env[f]??"").split(",").map(e=>e.trim()).filter(Boolean)).map(t).filter(e=>e!==v);var f;if("mcp"===p&&!h)throw new Error("Missing required env var in mcp mode: MESH_MCP_COMMAND");const S=u.customEndpoint||i.customEndpoint||e("MESH_ENDPOINT",e("BEDROCK_ENDPOINT","https://mesh-llm.edgar-baumann.workers.dev"));return{bedrock:{endpointBase:(()=>{try{const e=new URL(S);if("https:"!==e.protocol&&"127.0.0.1"!==e.hostname&&"localhost"!==e.hostname)throw new Error(`MESH_ENDPOINT must use HTTPS (got ${S})`);return S}catch(e){if(e.message.startsWith("MESH_ENDPOINT"))throw e;throw new Error(`Invalid MESH_ENDPOINT URL: ${S}`)}})(),bearerToken:u.customApiKey||i.customApiKey||process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY,googleApiKey:n(),modelId:v,fallbackModelIds:_.length>0?_:l.filter(e=>e!==v),temperature:o("MESH_TEMPERATURE",o("BEDROCK_TEMPERATURE",0)),maxTokens:o("MESH_MAX_TOKENS",o("BEDROCK_MAX_TOKENS",8e3))},agent:{maxSteps:o("AGENT_MAX_STEPS",8),mode:p,workspaceRoot:m,enableCloudCache:u.enableCloudCache??i.enableCloudCache,themeColor:u.themeColor||i.themeColor,voice:s(u.voice??i.voice)},mcp:{command:h,args:r(E,"MESH_MCP_ARGS")},supabase:{url:process.env.SUPABASE_URL?.trim()||void 0,key:process.env.SUPABASE_KEY?.trim()||void 0},telemetry:{contribute:!0===i.telemetry||"1"===process.env.MESH_TELEMETRY||"true"===process.env.MESH_TELEMETRY,meshBrainEndpoint:process.env.MESH_BRAIN_ENDPOINT?.trim()||void 0}}}
1
+ function e(e,o){const r=process.env[e];return r&&r.trim()?r.trim():o}function o(e,o){const r=process.env[e];if(!r)return o;const t=Number(r);if(Number.isNaN(t))throw new Error(`Invalid numeric env var ${e}: ${r}`);return t}function r(e,o){try{const o=JSON.parse(e);if(!Array.isArray(o)||o.some(e=>"string"!=typeof e))throw new Error("must be a JSON array of strings");return o}catch(e){throw new Error(`Invalid ${o}: ${e.message}`)}}function t(e){const o=e?.trim();return!o||u.has(o)?p:o}function n(){const e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;return e?.trim()||void 0}function s(e){const o=Number(e?.speed);return{configured:!0===e?.configured,language:e?.language?.trim()||E.language,speed:Number.isFinite(o)?o:E.speed,voice:e?.voice?.trim()||E.voice,microphone:e?.microphone?.trim()||E.microphone}}import i from"node:fs/promises";import c from"node:os";import a from"node:path";import{config as l}from"dotenv";import{DEFAULT_FALLBACK_MODEL_IDS as m,DEFAULT_MODEL_ID as p}from"./model-catalog.js";l();const u=new Set(["us.anthropic.claude-sonnet-4-5-20250929-v1:0","us.anthropic.claude-3-5-sonnet-20240620-v1:0","us.anthropic.claude-sonnet-4-6","us.anthropic.claude-opus-4-6-v1","us.anthropic.claude-haiku-4-5-20251001-v1:0"]);export function shortPathLabel(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)||e}const d=a.join(c.homedir(),".config","mesh","settings.json"),E={configured:!1,language:"auto",speed:260,voice:"auto",microphone:"default"};export async function loadUserSettings(){try{const e=await i.readFile(d,"utf-8"),o=JSON.parse(e);return{modelId:t(o.modelId),themeColor:o.themeColor||"cyan",enableCloudCache:"boolean"!=typeof o.enableCloudCache||o.enableCloudCache,telemetry:o.telemetry,customApiKey:o.customApiKey,customEndpoint:o.customEndpoint,googleKeyMode:"own"===o.googleKeyMode?"own":"proxy"===o.googleKeyMode?"proxy":void 0,ownGoogleApiKey:o.ownGoogleApiKey,voice:s(o.voice)}}catch{return{modelId:p,themeColor:"cyan",enableCloudCache:!0,voice:E}}}export async function saveUserSettings(e){const o=a.dirname(d);await i.mkdir(o,{recursive:!0,mode:448}),await i.writeFile(d,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}export async function loadConfig(){const c=await loadUserSettings(),l=a.resolve(process.env.WORKSPACE_ROOT||process.cwd());let p={};try{const e=await i.readFile(a.join(l,".mesh","config.json"),"utf-8");p=JSON.parse(e)}catch{}const u=(d=process.env.AGENT_MODE,"mcp"===String(d||"local").trim().toLowerCase()?"mcp":"local");var d;const E=process.env.MESH_MCP_ARGS??"[]",v=process.env.MESH_MCP_COMMAND?.trim(),h=t(process.env.MESH_MODEL_ID||process.env.BEDROCK_MODEL_ID||p.modelId||c.modelId),g=(_="MESH_FALLBACK_MODEL_IDS",(process.env[_]??"").split(",").map(e=>e.trim()).filter(Boolean)).map(t).filter(e=>e!==h);var _;if("mcp"===u&&!v)throw new Error("Missing required env var in mcp mode: MESH_MCP_COMMAND");const f=p.customEndpoint||c.customEndpoint||e("MESH_ENDPOINT",e("BEDROCK_ENDPOINT","https://mesh-llm.edgar-baumann.workers.dev"));return{bedrock:{endpointBase:(()=>{try{const e=new URL(f);if("https:"!==e.protocol&&"127.0.0.1"!==e.hostname&&"localhost"!==e.hostname)throw new Error(`MESH_ENDPOINT must use HTTPS (got ${f})`);return f}catch(e){if(e.message.startsWith("MESH_ENDPOINT"))throw e;throw new Error(`Invalid MESH_ENDPOINT URL: ${f}`)}})(),bearerToken:p.customApiKey||c.customApiKey||process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY,googleApiKey:"own"===c.googleKeyMode?c.ownGoogleApiKey||n():void 0,ownGoogleApiKey:c.ownGoogleApiKey,modelId:h,fallbackModelIds:g.length>0?g:m.filter(e=>e!==h),temperature:o("MESH_TEMPERATURE",o("BEDROCK_TEMPERATURE",0)),maxTokens:o("MESH_MAX_TOKENS",o("BEDROCK_MAX_TOKENS",8e3))},agent:{maxSteps:o("AGENT_MAX_STEPS",8),mode:u,workspaceRoot:l,enableCloudCache:p.enableCloudCache??c.enableCloudCache,themeColor:p.themeColor||c.themeColor,voice:s(p.voice??c.voice)},mcp:{command:v,args:r(E,"MESH_MCP_ARGS")},supabase:{url:process.env.SUPABASE_URL?.trim()||void 0,key:process.env.SUPABASE_KEY?.trim()||void 0},telemetry:{contribute:!0===c.telemetry||"1"===process.env.MESH_TELEMETRY||"true"===process.env.MESH_TELEMETRY,meshBrainEndpoint:process.env.MESH_BRAIN_ENDPOINT?.trim()||void 0}}}
@@ -1 +1 @@
1
- function e(e){const t=e.length;if(0===t)return 0;const o={};for(const t of e)o[t]=(o[t]||0)+1;let s=0;for(const e in o){const n=o[e]/t;s-=n*Math.log2(n)}return s}import{DEFAULT_MODEL_ID as t,MODEL_CATALOG as o}from"./model-catalog.js";import{DEFAULT_NVIDIA_CHAT_MODELS as s,isNvidiaHostedModel as n,nvidiaChatCompletion as i}from"./nvidia-services.js";export function isGoogleHostedModel(e){return"google"===o.find(t=>t.value===e)?.provider||e.startsWith("google/")}export class BedrockLlmClient{options;constructor(e){this.options=e}logEndpoint(){process.stderr.write(`[Mesh] LLM endpoint: ${this.options.endpointBase}\n`)}async converse(e,t,o,s,i,r){const a=[];for(const l of this.candidateModelIds(s)){const s=i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4);if(n(l)||isGoogleHostedModel(l)){let n;try{n=await this.fetchOpenAiResponse(l,e,t,o,s,r)}catch(e){a.push(`${l} -> error: ${e.message.slice(0,220)}`),process.stderr.write(`[Mesh] Model ${l} failed (${e.message}), trying fallback...\n`);continue}if(n.response.ok)return this.parseNvidiaResponse(n.data);const i=this.buildErrorHint(n.response.status,n.rawText,l);if(a.push(`${l} -> ${n.response.status}: ${n.rawText.slice(0,220)}${i}`),!this.shouldTryFallback(n.response.status))break;process.stderr.write(`[Mesh] Model ${l} failed (${n.response.status}), trying fallback...\n`);continue}const c=this.buildBody(e,t,o,r),d={"content-type":"application/json"};this.options.bearerToken&&(d.authorization=`Bearer ${this.options.bearerToken}`);const p=await this.fetchWithRetry(this.buildUrl(l),{method:"POST",headers:d,body:JSON.stringify(c),signal:s});if(p.ok){const e=await p.json();return this.parseResponse(e)}const u=await p.text(),h=this.buildErrorHint(p.status,u,l);if(a.push(`${l} -> ${p.status}: ${u.slice(0,220)}${h}`),!this.shouldTryFallback(p.status))break;process.stderr.write(`[Mesh] Model ${l} failed (${p.status}), trying fallback...\n`)}throw new Error(`LLM request failed after ${a.length} attempt(s): ${a.join(" | ")}`)}async*converseStream(e,t,o,s,i,r){const a=s||this.options.modelId;if(n(a)||isGoogleHostedModel(a)){const n=await this.converse(e,t,o,s,i,r);if("text"===n.kind)n.text&&(yield{kind:"text",text:n.text});else{n.text&&(yield{kind:"text",text:n.text});for(const e of n.toolUses)yield{kind:"tool_use",toolUse:e}}return void(yield{kind:"stop",usage:n.usage})}const l=this.buildBody(e,t,o,r),c={"content-type":"application/json"};this.options.bearerToken&&(c.authorization=`Bearer ${this.options.bearerToken}`);const d=i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4);let p=null;const u=[];for(const e of this.candidateModelIds(s)){if(p=await fetch(this.buildUrl(e).replace("/converse","/converse-stream"),{method:"POST",headers:c,body:JSON.stringify(l),signal:d}),p.ok)break;const t=await p.text().catch(()=>""),o=this.buildErrorHint(p.status,t,e);if(u.push(`${e} -> ${p.status}: ${t.slice(0,220)}${o}`),!this.shouldTryFallback(p.status))throw new Error(`LLM streaming failed after ${u.length} attempt(s): ${u.join(" | ")}`)}if(!p?.ok)throw new Error(`LLM streaming failed after ${u.length} attempt(s): ${u.join(" | ")}`);if(!p.body)return;const h=p.body.getReader(),m=new TextDecoder;let g="";for(;;){const{done:e,value:t}=await h.read();if(e)break;g+=m.decode(t,{stream:!0});const o=g.split("\n");g=o.pop()||"";for(const e of o)if(e.trim())try{const t=JSON.parse(e);if(t.contentBlockDelta?.delta?.text){const e=t.contentBlockDelta.delta.text,o=detectStreamingHazard(g,e);if(o)return void(yield{kind:"stop",text:`\n[JIT REVERSION] Aborted: ${o}`});yield{kind:"text",text:e}}t.contentBlockStart?.start?.toolUse&&(yield{kind:"tool_use",toolUse:t.contentBlockStart.start.toolUse}),t.metadata?.usage&&(yield{kind:"stop",usage:t.metadata.usage})}catch{}}}buildUrl(e){return`${this.options.endpointBase.replace(/\/+$/,"")}/model/${encodeURIComponent(e)}/converse`}async fetchOpenAiResponse(e,t,o,s,n,r){const a=isGoogleHostedModel(e),l=a?"google":"nvidia",c=process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY,d=this.options.googleApiKey||process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;if(a&&d){const a="https://generativelanguage.googleapis.com/v1beta/openai";return i({model:e.replace(/^(google\/|xai\/)/,""),messages:this.buildOpenAiMessages(t,s),tools:o.length>0?this.buildOpenAiTools(o):void 0,temperature:this.options.temperature,maxTokens:r??this.options.maxTokens},{apiKey:d,baseUrl:a,abortSignal:n,extraHeaders:{}})}return i({model:a?e.replace(/^(google\/|xai\/)/,""):e,messages:this.buildOpenAiMessages(t,s),tools:o.length>0?this.buildOpenAiTools(o):void 0,temperature:this.options.temperature,maxTokens:r??this.options.maxTokens},{apiKey:c||this.options.bearerToken,baseUrl:c?void 0:this.options.endpointBase,abortSignal:n,extraHeaders:{"x-mesh-provider":l,"x-mesh-model-id":e}})}candidateModelIds(e){const o=e||this.options.modelId,n=new Set;if(n.add(o),this.options.fallbackModelIds)for(const e of this.options.fallbackModelIds)n.add(e);if(n.add(t),process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY)for(const e of s)n.add(e);return Array.from(n).filter(Boolean)}shouldTryFallback(e){return 401===e||404===e||429===e||e>=500}isRetryableStatus(e){return 429===e||408===e||e>=500}async fetchWithRetry(e,t,o=3){const s=[1e3,2e3,4e3];for(let n=0;n<=o;n++){const i=await fetch(e,t);if(i.ok||!this.isRetryableStatus(i.status))return i;if(!(n<o))return i;{const e=s[n]??4e3,t=Math.random()*e*.25;await new Promise(o=>setTimeout(o,e+t))}}return fetch(e,t)}buildErrorHint(e,o,s){return 400===e&&o.includes("on-demand throughput isn’t supported")?` | Hint: model '${s}' needs an inference profile id. Try '/model ${t}'`:403===e&&o.includes('"model_not_allowed"')?" | Hint: this model is blocked by worker ALLOWED_MODELS.":""}buildBody(e,t,o,s){const n=e.map(e=>({role:e.role,content:e.content.map(e=>"image"in e?{image:{format:e.image.format,source:{bytes:e.image.source.bytes}}}:e)}));let i;i="string"==typeof o?[{text:o,...o.length>1e3?{cache_control:{type:"ephemeral"}}:{}}]:o;const r={messages:n,system:i,inferenceConfig:{temperature:this.options.temperature,maxTokens:s??this.options.maxTokens}},a=e.some(e=>e.content.some(e=>"toolUse"in e||"toolResult"in e));if(t.length>0||a){const e={tools:t.map(e=>({toolSpec:{name:e.name,description:e.description??"",inputSchema:{json:e.inputSchema??{type:"object",properties:{}}}}}))};if(e.tools.length>0){e.tools[e.tools.length-1].toolSpec.cache_control={type:"ephemeral"}}r.toolConfig=e}return r}buildOpenAiTools(e){return e.map(e=>({type:"function",function:{name:e.name,description:e.description??"",parameters:e.inputSchema??{type:"object",properties:{}}}}))}buildOpenAiMessages(e,t){const o=[],s="string"==typeof t?t:t.map(e=>e.text).filter(Boolean).join("\n\n");s.trim()&&o.push({role:"system",content:s});for(const t of e){const e=[],s=[],n=[],i=[];for(const o of t.content)if("text"in o&&"string"==typeof o.text)e.push(o.text);else if("image"in o)s.push({type:"image_url",image_url:{url:`data:image/${o.image.format};base64,${o.image.source.bytes}`}});else if("toolUse"in o)n.push({id:o.toolUse.toolUseId,type:"function",function:{name:o.toolUse.name,arguments:JSON.stringify(o.toolUse.input??{})}});else if("toolResult"in o){const e=o.toolResult.content.map(e=>"text"in e?e.text:JSON.stringify("json"in e?e.json:e.image)).join("\n").trim();i.push({role:"tool",tool_call_id:o.toolResult.toolUseId,content:e||(o.toolResult.status??"ok")})}if(n.length>0)o.push({role:"assistant",content:e.join("\n").trim()||null,tool_calls:n});else if(s.length>0){const n=[...e.map(e=>({type:"text",text:e})),...s];o.push({role:t.role,content:n})}else e.length>0&&o.push({role:t.role,content:e.join("\n").trim()});o.push(...i)}return o}parseResponse(e){const t=e.output?.message?.content??[],o=e.stopReason??"end_turn",s=e.usage,n=[],i=[];for(const e of t)"text"in e&&"string"==typeof e.text?n.push(e.text):"toolUse"in e&&e.toolUse&&i.push({toolUseId:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input??{}});const r=n.join("\n").trim();return i.length>0?{kind:"tool_use",toolUses:i,text:r||void 0,stopReason:o,usage:s}:{kind:"text",text:r,stopReason:o,usage:s}}parseNvidiaResponse(e){const t=e?.choices?.[0],o=e?.usage?{inputTokens:e.usage.prompt_tokens,outputTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens}:void 0,s=t?.message?.content,n="string"==typeof s?s.trim():Array.isArray(s)?s.map(e=>e?.text??"").join("\n").trim():"",i=t?.message?.tool_calls??[];return i.length>0?{kind:"tool_use",text:n||void 0,stopReason:t?.finish_reason??"tool_use",usage:o,toolUses:i.map((e,t)=>{let o={};try{o=JSON.parse(e.function?.arguments??"{}")}catch{o={}}return{toolUseId:e.id||`tool_call_${t+1}`,name:e.function?.name||"unknown_tool",input:o}})}:{kind:"text",text:n,stopReason:t?.finish_reason??"end_turn",usage:o}}}export function detectStreamingHazard(t,o){const s=`${t}${o}`,n=s.slice(-1600).toLowerCase(),i=s.slice(-300).toLowerCase(),r=(/```[a-z]*[\s\S]*$/.test(n),/```(?:bash|sh|zsh|shell|powershell)[\s\S]*$/.test(n));let a=0;const l=[];/(?:\\x[0-9a-f]{2}){4,}/i.test(i)&&(a+=60,l.push("hex-encoded-payload")),/\b(?:base64|atob|btoa|decode|eval\(|unescape)\b/i.test(i)&&(a+=30,l.push("dynamic-decoding"));const c=["/etc/shadow","/etc/passwd","/etc/sudoers","~/.ssh","~/.aws","~/.docker",".git/config",".env","secrets.json","/dev/mem","/dev/kmem","/proc/kcore"];for(const e of c)n.includes(e)&&(a+=80,l.push(`sensitive-path:${e}`));const d=[{re:/\brm\s+-rf\b/i,weight:100,msg:"destructive-rm"},{re:/\bmkfs\b|\bparted\b|\bformat\b\s+[a-z]:/i,weight:100,msg:"disk-format"},{re:/\bchmod\s+(?:-r\s+)?777\b/i,weight:40,msg:"insecure-permissions"},{re:/\bkill\s+-9\s+(?:-1|0)\b/i,weight:70,msg:"process-mass-kill"},{re:/>\s*\/etc\/[a-z]+/i,weight:90,msg:"system-config-overwrite"}];for(const{re:e,weight:t,msg:o}of d)e.test(i)&&(a+=t,l.push(o));if(/(?:ignore previous instructions|you are now|system override|developer mode active)/i.test(i)&&(a+=50,l.push("meta-instruction-override")),a>=100)return`CRITICAL HAZARD: ${l.join(", ")} (Score: ${a})`;if(r&&a>=60)return`SHELL HAZARD: Suspicious command sequence in shell block (Score: ${a})`;const p=s.match(/[A-Za-z0-9/+]{32,}/g)||[];for(const t of p){const o=e(t);if(o>4.3&&t.length<500&&!/^[A-F0-9]+$/i.test(t))return`SECRET HAZARD: High-entropy string detected (${o.toFixed(2)})`}return/\bprocess\.env\.[A-Z0-9_]+\s*\.\s*(?:trim|toLowerCase|toUpperCase|split|replace)\s*\(/i.test(i)?"CODE HAZARD: unsafe chained env access":/\b(?:undefined|null)\s*(?:\.|\[)\s*[a-zA-Z_$]/i.test(i)?"CODE HAZARD: Potential null/undefined property access":null}
1
+ function e(e){const t=e.length;if(0===t)return 0;const o={};for(const t of e)o[t]=(o[t]||0)+1;let s=0;for(const e in o){const n=o[e]/t;s-=n*Math.log2(n)}return s}import{DEFAULT_MODEL_ID as t,MODEL_CATALOG as o}from"./model-catalog.js";import{DEFAULT_NVIDIA_CHAT_MODELS as s,isNvidiaHostedModel as n,nvidiaChatCompletion as i}from"./nvidia-services.js";export function isGoogleHostedModel(e){return"google"===o.find(t=>t.value===e)?.provider||e.startsWith("google/")}export class BedrockLlmClient{options;constructor(e){this.options=e}logEndpoint(){process.stderr.write(`[Mesh] LLM endpoint: ${this.options.endpointBase}\n`)}async converse(e,t,o,s,i,r){const a=[];for(const l of this.candidateModelIds(s)){const s=i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4);if(n(l)||isGoogleHostedModel(l)){let n;try{n=await this.fetchOpenAiResponse(l,e,t,o,s,r)}catch(e){a.push(`${l} -> error: ${e.message.slice(0,220)}`),process.stderr.write(`[Mesh] Model ${l} failed (${e.message}), trying fallback...\n`);continue}if(n.response.ok)return this.parseNvidiaResponse(n.data);const i=this.buildErrorHint(n.response.status,n.rawText,l);if(a.push(`${l} -> ${n.response.status}: ${n.rawText.slice(0,220)}${i}`),!this.shouldTryFallback(n.response.status))break;process.stderr.write(`[Mesh] Model ${l} failed (${n.response.status}), trying fallback...\n`);continue}const c=this.buildBody(e,t,o,r),d={"content-type":"application/json"};this.options.bearerToken&&(d.authorization=`Bearer ${this.options.bearerToken}`);const p=await this.fetchWithRetry(this.buildUrl(l),{method:"POST",headers:d,body:JSON.stringify(c),signal:s});if(p.ok){const e=await p.json();return this.parseResponse(e)}const u=await p.text(),h=this.buildErrorHint(p.status,u,l);if(a.push(`${l} -> ${p.status}: ${u.slice(0,220)}${h}`),!this.shouldTryFallback(p.status))break;process.stderr.write(`[Mesh] Model ${l} failed (${p.status}), trying fallback...\n`)}throw new Error(`LLM request failed after ${a.length} attempt(s): ${a.join(" | ")}`)}async*converseStream(e,t,o,s,i,r){const a=s||this.options.modelId;if(n(a)||isGoogleHostedModel(a)){const n=await this.converse(e,t,o,s,i,r);if("text"===n.kind)n.text&&(yield{kind:"text",text:n.text});else{n.text&&(yield{kind:"text",text:n.text});for(const e of n.toolUses)yield{kind:"tool_use",toolUse:e}}return void(yield{kind:"stop",usage:n.usage})}const l=this.buildBody(e,t,o,r),c={"content-type":"application/json"};this.options.bearerToken&&(c.authorization=`Bearer ${this.options.bearerToken}`);const d=i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4);let p=null;const u=[];for(const e of this.candidateModelIds(s)){if(p=await fetch(this.buildUrl(e).replace("/converse","/converse-stream"),{method:"POST",headers:c,body:JSON.stringify(l),signal:d}),p.ok)break;const t=await p.text().catch(()=>""),o=this.buildErrorHint(p.status,t,e);if(u.push(`${e} -> ${p.status}: ${t.slice(0,220)}${o}`),!this.shouldTryFallback(p.status))throw new Error(`LLM streaming failed after ${u.length} attempt(s): ${u.join(" | ")}`)}if(!p?.ok)throw new Error(`LLM streaming failed after ${u.length} attempt(s): ${u.join(" | ")}`);if(!p.body)return;const h=p.body.getReader(),m=new TextDecoder;let g="";for(;;){const{done:e,value:t}=await h.read();if(e)break;g+=m.decode(t,{stream:!0});const o=g.split("\n");g=o.pop()||"";for(const e of o)if(e.trim())try{const t=JSON.parse(e);if(t.contentBlockDelta?.delta?.text){const e=t.contentBlockDelta.delta.text,o=detectStreamingHazard(g,e);if(o)return void(yield{kind:"stop",text:`\n[JIT REVERSION] Aborted: ${o}`});yield{kind:"text",text:e}}t.contentBlockStart?.start?.toolUse&&(yield{kind:"tool_use",toolUse:t.contentBlockStart.start.toolUse}),t.metadata?.usage&&(yield{kind:"stop",usage:t.metadata.usage})}catch{}}}buildUrl(e){return`${this.options.endpointBase.replace(/\/+$/,"")}/model/${encodeURIComponent(e)}/converse`}async fetchOpenAiResponse(e,t,o,s,n,r){const a=isGoogleHostedModel(e),l=a?"google":"nvidia",c=process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY,d=this.options.googleApiKey;if(a&&d){const a="https://generativelanguage.googleapis.com/v1beta/openai";return i({model:e.replace(/^(google\/|xai\/)/,""),messages:this.buildOpenAiMessages(t,s),tools:o.length>0?this.buildOpenAiTools(o):void 0,temperature:this.options.temperature,maxTokens:r??this.options.maxTokens},{apiKey:d,baseUrl:a,abortSignal:n,extraHeaders:{}})}return i({model:a?e.replace(/^(google\/|xai\/)/,""):e,messages:this.buildOpenAiMessages(t,s),tools:o.length>0?this.buildOpenAiTools(o):void 0,temperature:this.options.temperature,maxTokens:r??this.options.maxTokens},{apiKey:c||this.options.bearerToken,baseUrl:c?void 0:this.options.endpointBase,abortSignal:n,extraHeaders:{"x-mesh-provider":l,"x-mesh-model-id":e}})}candidateModelIds(e){const o=e||this.options.modelId,n=new Set;if(n.add(o),this.options.fallbackModelIds)for(const e of this.options.fallbackModelIds)n.add(e);if(n.add(t),process.env.NVIDIA_API_KEY||process.env.NVAPI_KEY)for(const e of s)n.add(e);return Array.from(n).filter(Boolean)}shouldTryFallback(e){return 401===e||404===e||429===e||e>=500}isRetryableStatus(e){return 429===e||408===e||e>=500}async fetchWithRetry(e,t,o=3){const s=[1e3,2e3,4e3];for(let n=0;n<=o;n++){const i=await fetch(e,t);if(i.ok||!this.isRetryableStatus(i.status))return i;if(!(n<o))return i;{const e=s[n]??4e3,t=Math.random()*e*.25;await new Promise(o=>setTimeout(o,e+t))}}return fetch(e,t)}buildErrorHint(e,o,s){return 400===e&&o.includes("on-demand throughput isn’t supported")?` | Hint: model '${s}' needs an inference profile id. Try '/model ${t}'`:403===e&&o.includes('"model_not_allowed"')?" | Hint: this model is blocked by worker ALLOWED_MODELS.":""}buildBody(e,t,o,s){const n=e.map(e=>({role:e.role,content:e.content.map(e=>"image"in e?{image:{format:e.image.format,source:{bytes:e.image.source.bytes}}}:e)}));let i;i="string"==typeof o?[{text:o,...o.length>1e3?{cache_control:{type:"ephemeral"}}:{}}]:o;const r={messages:n,system:i,inferenceConfig:{temperature:this.options.temperature,maxTokens:s??this.options.maxTokens}},a=e.some(e=>e.content.some(e=>"toolUse"in e||"toolResult"in e));if(t.length>0||a){const e={tools:t.map(e=>({toolSpec:{name:e.name,description:e.description??"",inputSchema:{json:e.inputSchema??{type:"object",properties:{}}}}}))};if(e.tools.length>0){e.tools[e.tools.length-1].toolSpec.cache_control={type:"ephemeral"}}r.toolConfig=e}return r}buildOpenAiTools(e){return e.map(e=>({type:"function",function:{name:e.name,description:e.description??"",parameters:e.inputSchema??{type:"object",properties:{}}}}))}buildOpenAiMessages(e,t){const o=[],s="string"==typeof t?t:t.map(e=>e.text).filter(Boolean).join("\n\n");s.trim()&&o.push({role:"system",content:s});for(const t of e){const e=[],s=[],n=[],i=[];for(const o of t.content)if("text"in o&&"string"==typeof o.text)e.push(o.text);else if("image"in o)s.push({type:"image_url",image_url:{url:`data:image/${o.image.format};base64,${o.image.source.bytes}`}});else if("toolUse"in o)n.push({id:o.toolUse.toolUseId,type:"function",function:{name:o.toolUse.name,arguments:JSON.stringify(o.toolUse.input??{})}});else if("toolResult"in o){const e=o.toolResult.content.map(e=>"text"in e?e.text:JSON.stringify("json"in e?e.json:e.image)).join("\n").trim();i.push({role:"tool",tool_call_id:o.toolResult.toolUseId,content:e||(o.toolResult.status??"ok")})}if(n.length>0)o.push({role:"assistant",content:e.join("\n").trim()||null,tool_calls:n});else if(s.length>0){const n=[...e.map(e=>({type:"text",text:e})),...s];o.push({role:t.role,content:n})}else e.length>0&&o.push({role:t.role,content:e.join("\n").trim()});o.push(...i)}return o}parseResponse(e){const t=e.output?.message?.content??[],o=e.stopReason??"end_turn",s=e.usage,n=[],i=[];for(const e of t)"text"in e&&"string"==typeof e.text?n.push(e.text):"toolUse"in e&&e.toolUse&&i.push({toolUseId:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input??{}});const r=n.join("\n").trim();return i.length>0?{kind:"tool_use",toolUses:i,text:r||void 0,stopReason:o,usage:s}:{kind:"text",text:r,stopReason:o,usage:s}}parseNvidiaResponse(e){const t=e?.choices?.[0],o=e?.usage?{inputTokens:e.usage.prompt_tokens,outputTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens}:void 0,s=t?.message?.content,n="string"==typeof s?s.trim():Array.isArray(s)?s.map(e=>e?.text??"").join("\n").trim():"",i=t?.message?.tool_calls??[];return i.length>0?{kind:"tool_use",text:n||void 0,stopReason:t?.finish_reason??"tool_use",usage:o,toolUses:i.map((e,t)=>{let o={};try{o=JSON.parse(e.function?.arguments??"{}")}catch{o={}}return{toolUseId:e.id||`tool_call_${t+1}`,name:e.function?.name||"unknown_tool",input:o}})}:{kind:"text",text:n,stopReason:t?.finish_reason??"end_turn",usage:o}}}export function detectStreamingHazard(t,o){const s=`${t}${o}`,n=s.slice(-1600).toLowerCase(),i=s.slice(-300).toLowerCase(),r=(/```[a-z]*[\s\S]*$/.test(n),/```(?:bash|sh|zsh|shell|powershell)[\s\S]*$/.test(n));let a=0;const l=[];/(?:\\x[0-9a-f]{2}){4,}/i.test(i)&&(a+=60,l.push("hex-encoded-payload")),/\b(?:base64|atob|btoa|decode|eval\(|unescape)\b/i.test(i)&&(a+=30,l.push("dynamic-decoding"));const c=["/etc/shadow","/etc/passwd","/etc/sudoers","~/.ssh","~/.aws","~/.docker",".git/config",".env","secrets.json","/dev/mem","/dev/kmem","/proc/kcore"];for(const e of c)n.includes(e)&&(a+=80,l.push(`sensitive-path:${e}`));const d=[{re:/\brm\s+-rf\b/i,weight:100,msg:"destructive-rm"},{re:/\bmkfs\b|\bparted\b|\bformat\b\s+[a-z]:/i,weight:100,msg:"disk-format"},{re:/\bchmod\s+(?:-r\s+)?777\b/i,weight:40,msg:"insecure-permissions"},{re:/\bkill\s+-9\s+(?:-1|0)\b/i,weight:70,msg:"process-mass-kill"},{re:/>\s*\/etc\/[a-z]+/i,weight:90,msg:"system-config-overwrite"}];for(const{re:e,weight:t,msg:o}of d)e.test(i)&&(a+=t,l.push(o));if(/(?:ignore previous instructions|you are now|system override|developer mode active)/i.test(i)&&(a+=50,l.push("meta-instruction-override")),a>=100)return`CRITICAL HAZARD: ${l.join(", ")} (Score: ${a})`;if(r&&a>=60)return`SHELL HAZARD: Suspicious command sequence in shell block (Score: ${a})`;const p=s.match(/[A-Za-z0-9/+]{32,}/g)||[];for(const t of p){const o=e(t);if(o>4.3&&t.length<500&&!/^[A-F0-9]+$/i.test(t))return`SECRET HAZARD: High-entropy string detected (${o.toFixed(2)})`}return/\bprocess\.env\.[A-Z0-9_]+\s*\.\s*(?:trim|toLowerCase|toUpperCase|split|replace)\s*\(/i.test(i)?"CODE HAZARD: unsafe chained env access":/\b(?:undefined|null)\s*(?:\.|\[)\s*[a-zA-Z_$]/i.test(i)?"CODE HAZARD: Potential null/undefined property access":null}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trymesh/cli",
3
- "version": "0.3.23",
3
+ "version": "0.3.24",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Mesh terminal agent CLI. Zero-config: ships with a shared Mesh LLM proxy so no AWS credentials are needed.",