@trymesh/cli 0.3.22

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.
Files changed (95) hide show
  1. package/assets/mesh-banner.svg +23 -0
  2. package/bin/mesh-daemon.cjs +25 -0
  3. package/bin/mesh.cjs +25 -0
  4. package/dist/agent-loop.js +1 -0
  5. package/dist/agent-os.js +1 -0
  6. package/dist/agents/critic.js +1 -0
  7. package/dist/agents/persona-loader.js +1 -0
  8. package/dist/agents/redteam.js +1 -0
  9. package/dist/audit/logger.js +1 -0
  10. package/dist/auth.js +1 -0
  11. package/dist/cache-manager.js +1 -0
  12. package/dist/command-filter.js +1 -0
  13. package/dist/command-safety.js +1 -0
  14. package/dist/company-brain.js +1 -0
  15. package/dist/composite-backend.js +1 -0
  16. package/dist/config.js +1 -0
  17. package/dist/context-artifacts.js +1 -0
  18. package/dist/context-assembler.js +1 -0
  19. package/dist/daemon-protocol.js +1 -0
  20. package/dist/daemon.js +2 -0
  21. package/dist/dashboard/assets/index-Co1IW0HE.css +1 -0
  22. package/dist/dashboard/assets/index-DIj6iOWd.js +1 -0
  23. package/dist/dashboard/index.html +13 -0
  24. package/dist/dashboard-server.js +1 -0
  25. package/dist/doctor.js +1 -0
  26. package/dist/index.js +2 -0
  27. package/dist/integrations/chatops/manager.js +1 -0
  28. package/dist/integrations/issues/github.js +1 -0
  29. package/dist/integrations/issues/jira.js +1 -0
  30. package/dist/integrations/issues/linear.js +1 -0
  31. package/dist/integrations/issues/manager.js +1 -0
  32. package/dist/integrations/issues/types.js +1 -0
  33. package/dist/integrations/telemetry/datadog.js +1 -0
  34. package/dist/integrations/telemetry/manager.js +1 -0
  35. package/dist/integrations/telemetry/otel.js +1 -0
  36. package/dist/integrations/telemetry/posthog.js +1 -0
  37. package/dist/integrations/telemetry/sentry.js +1 -0
  38. package/dist/issue-autopilot.js +1 -0
  39. package/dist/llm-client.js +1 -0
  40. package/dist/local-tools.js +1 -0
  41. package/dist/mcp-client.js +1 -0
  42. package/dist/mesh-brain.js +1 -0
  43. package/dist/mesh-core-adapter.js +1 -0
  44. package/dist/mesh-gateway.js +1 -0
  45. package/dist/mesh-portal.js +1 -0
  46. package/dist/model-catalog.js +1 -0
  47. package/dist/model-router.js +1 -0
  48. package/dist/moonshots/causal-autopsy.js +1 -0
  49. package/dist/moonshots/common.js +1 -0
  50. package/dist/moonshots/conversational-codebase.js +1 -0
  51. package/dist/moonshots/ephemeral-execution.js +1 -0
  52. package/dist/moonshots/fluid-mesh.js +1 -0
  53. package/dist/moonshots/hive-mind.js +1 -0
  54. package/dist/moonshots/live-wire.js +1 -0
  55. package/dist/moonshots/living-software.js +1 -0
  56. package/dist/moonshots/natural-language-source.js +1 -0
  57. package/dist/moonshots/precrime.js +1 -0
  58. package/dist/moonshots/probabilistic-codebase.js +1 -0
  59. package/dist/moonshots/proof-carrying-change.js +1 -0
  60. package/dist/moonshots/schrodingers-ast.js +1 -0
  61. package/dist/moonshots/semantic-git.js +1 -0
  62. package/dist/moonshots/semantic-sheriff.js +1 -0
  63. package/dist/moonshots/session-resurrection.js +1 -0
  64. package/dist/moonshots/shadow-deploy.js +1 -0
  65. package/dist/moonshots/spec-code.js +1 -0
  66. package/dist/moonshots/todo-resolver.js +1 -0
  67. package/dist/moonshots/tribunal.js +1 -0
  68. package/dist/nvidia-services.js +1 -0
  69. package/dist/production-readiness.js +1 -0
  70. package/dist/quality/property-tests.js +1 -0
  71. package/dist/quality/smt.js +1 -0
  72. package/dist/refactor/ts-compiler.js +1 -0
  73. package/dist/runtime/replay.js +1 -0
  74. package/dist/runtime-api.js +1 -0
  75. package/dist/runtime-observer.js +1 -0
  76. package/dist/security/self-defending.js +1 -0
  77. package/dist/session-capsule-store.js +1 -0
  78. package/dist/session-manager.js +1 -0
  79. package/dist/structured-logger.js +1 -0
  80. package/dist/support.js +1 -0
  81. package/dist/terminal-preview.js +1 -0
  82. package/dist/timeline/symptom-bisect.js +1 -0
  83. package/dist/timeline-manager.js +1 -0
  84. package/dist/tool-backend.js +1 -0
  85. package/dist/tool-schema.js +1 -0
  86. package/dist/voice-manager.js +1 -0
  87. package/dist/workspace-index.js +1 -0
  88. package/package.json +94 -0
  89. package/scripts/minify.js +114 -0
  90. package/scripts/postinstall.cjs +81 -0
  91. package/scripts/published-install-smoke.cjs +103 -0
  92. package/scripts/release-smoke.cjs +116 -0
  93. package/scripts/run-eval.ts +84 -0
  94. package/scripts/run-tests.cjs +54 -0
  95. package/scripts/update-brew.sh +57 -0
@@ -0,0 +1,23 @@
1
+ <svg width="1280" height="360" viewBox="0 0 1280 360" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title desc">
2
+ <title id="title">Mesh terminal agent CLI banner</title>
3
+ <desc id="desc">A professional dark banner for Mesh, a terminal-first AI engineering agent.</desc>
4
+ <rect width="1280" height="360" rx="28" fill="#0B0F14"/>
5
+ <rect x="1" y="1" width="1278" height="358" rx="27" stroke="#1F2937" stroke-width="2"/>
6
+ <path d="M0 282C138 244 230 253 353 282C513 320 628 330 791 287C948 245 1090 244 1280 298V360H0V282Z" fill="#111827"/>
7
+ <path d="M90 83H1190" stroke="#1F2937" stroke-width="1"/>
8
+ <path d="M90 277H1190" stroke="#1F2937" stroke-width="1"/>
9
+ <path d="M126 104L188 166L126 228" stroke="#14B8A6" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"/>
10
+ <path d="M224 226H360" stroke="#F8FAFC" stroke-width="16" stroke-linecap="round"/>
11
+ <circle cx="850" cy="125" r="7" fill="#14B8A6"/>
12
+ <circle cx="932" cy="91" r="7" fill="#F59E0B"/>
13
+ <circle cx="1018" cy="141" r="7" fill="#38BDF8"/>
14
+ <circle cx="1102" cy="101" r="7" fill="#F8FAFC"/>
15
+ <circle cx="945" cy="219" r="7" fill="#14B8A6"/>
16
+ <circle cx="1054" cy="238" r="7" fill="#F59E0B"/>
17
+ <path d="M850 125L932 91L1018 141L1102 101" stroke="#334155" stroke-width="3"/>
18
+ <path d="M850 125L945 219L1054 238L1102 101" stroke="#334155" stroke-width="3"/>
19
+ <path d="M932 91L945 219L1018 141L1054 238" stroke="#334155" stroke-width="3"/>
20
+ <text x="415" y="158" fill="#F8FAFC" font-family="Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="74" font-weight="800" letter-spacing="0">Mesh</text>
21
+ <text x="421" y="206" fill="#CBD5E1" font-family="Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif" font-size="25" font-weight="500" letter-spacing="0">Terminal-first AI engineering agent</text>
22
+ <text x="423" y="250" fill="#14B8A6" font-family="SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace" font-size="21" font-weight="600" letter-spacing="0">npm install -g @edgarelmo/mesh-agent-cli</text>
23
+ </svg>
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { existsSync } = require("node:fs");
5
+ const { join } = require("node:path");
6
+ const { spawnSync } = require("node:child_process");
7
+
8
+ const root = join(__dirname, "..");
9
+ const args = process.argv.slice(2);
10
+ const distEntry = join(root, "dist", "daemon.js");
11
+
12
+ let command = process.execPath;
13
+ let commandArgs = [distEntry, ...args];
14
+
15
+ if (!existsSync(distEntry)) {
16
+ console.error("Mesh daemon is not built. Run `pnpm --filter @mesh/cli build` first.");
17
+ process.exit(1);
18
+ }
19
+
20
+ const result = spawnSync(command, commandArgs, { stdio: "inherit" });
21
+ if (result.error) {
22
+ console.error(result.error.message);
23
+ process.exit(1);
24
+ }
25
+ process.exit(result.status ?? 1);
package/bin/mesh.cjs ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { existsSync } = require("node:fs");
5
+ const { join } = require("node:path");
6
+ const { spawnSync } = require("node:child_process");
7
+
8
+ const root = join(__dirname, "..");
9
+ const args = process.argv.slice(2);
10
+ const distEntry = join(root, "dist", "index.js");
11
+
12
+ let command = process.execPath;
13
+ let commandArgs = [distEntry, ...args];
14
+
15
+ if (!existsSync(distEntry)) {
16
+ console.error("Mesh CLI is not built. Run `pnpm --filter @mesh/cli build` first.");
17
+ process.exit(1);
18
+ }
19
+
20
+ const result = spawnSync(command, commandArgs, { stdio: "inherit" });
21
+ if (result.error) {
22
+ console.error(result.error.message);
23
+ process.exit(1);
24
+ }
25
+ process.exit(result.status ?? 1);
@@ -0,0 +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\`\`\``}
@@ -0,0 +1 @@
1
+ function e(e){if(Array.isArray(e))return e.map(e=>String(e).trim()).filter(Boolean)}import{promises as t}from"node:fs";import i from"node:path";import r from"node:os";import s from"node:crypto";export class AgentOs{workspaceRoot;timelines;workspaceHash;basePath;constructor(e,t){this.workspaceRoot=e,this.timelines=t,this.workspaceHash=s.createHash("sha256").update(i.resolve(e)).digest("hex").slice(0,24),this.basePath=i.join(r.homedir(),".config","mesh","agents",this.workspaceHash)}async spawn(t){const i=String(t.role??"").trim(),r=String(t.task??"").trim();if(!i||!r)throw new Error("agent.spawn requires role and task");const n=await this.readDefinition(i),o=await this.timelines.create({name:`${i}-${Date.now().toString(36)}`}),a={id:`agent-${Date.now().toString(36)}-${s.randomBytes(3).toString("hex")}`,role:i,task:r,workspaceScope:e(t.workspaceScope),writeScope:e(t.writeScope),timelineId:o.timeline.id,status:"ready",definitionPath:n.path,outputContract:n.outputContract,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()};return await this.writeRecord(a),{ok:!0,agent:a,timelineRoot:o.timeline.root}}async status(e={}){const r="string"==typeof e.id?e.id.trim():"";await t.mkdir(this.basePath,{recursive:!0});const s=await t.readdir(this.basePath,{withFileTypes:!0}).catch(()=>[]),n=[];for(const e of s){if(!e.isFile()||!e.name.endsWith(".json"))continue;const s=await t.readFile(i.join(this.basePath,e.name),"utf8").catch(()=>"");if(!s)continue;const o=JSON.parse(s);r&&o.id!==r||n.push(o)}return n.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)),{ok:!0,agents:n}}async review(e){const t=String(e.timelineId??"").trim();if(!t)throw new Error("agent.review requires timelineId");const i=(await this.timelines.compare({timelineIds:[t]})).comparisons[0]??{},r=String(i.diffPreview??""),s=String(i.diffStat??""),n=[];return/exec\(|spawn\(|rm\s+-rf|AWS_|SECRET|TOKEN/i.test(r)&&n.push({severity:"high",message:"Diff touches shell execution, destructive operations, or secret-bearing code."}),/package-lock\.json|package\.json|tsconfig\.json/.test(s)&&n.push({severity:"medium",message:"Diff changes project-level configuration or dependency metadata."}),/test|spec|verify|npm test|npm run build/i.test(JSON.stringify(i.lastCommand??{}))||n.push({severity:"low",message:"No targeted verification command is recorded on this timeline."}),{ok:!0,timelineId:t,verdict:n.some(e=>"high"===e.severity)?"flag":"pass",findings:n,diffStat:s}}async mergeVerified(e){const t=String(e.timelineId??"").trim();if(!t)throw new Error("agent.merge_verified requires timelineId");return this.timelines.promote({timelineId:t})}async ensureDefaultDefinitions(){const e=i.join(this.workspaceRoot,".mesh","agents");await t.mkdir(e,{recursive:!0});const r={"code-reviewer.md":["# code-reviewer","","Role: inspect timeline diffs for correctness, regressions, security issues, and missing tests.","Model: default","Tools: workspace.timeline_compare, workspace.impact_map, workspace.ask_codebase","Budget: medium","Permissions: read-only","Output contract: findings ordered by severity with file/line citations and residual risk."].join("\n"),"debugger.md":["# debugger","","Role: connect runtime failures and test failures back to source symbols.","Model: default","Tools: runtime.capture_failure, runtime.explain_failure, workspace.impact_map, workspace.timeline_run","Budget: high","Permissions: timeline writes only","Output contract: root cause, candidate patch plan, verification command, residual risk."].join("\n"),"test-runner.md":["# test-runner","","Role: run targeted verification in an isolated timeline and report the exact command output.","Model: default","Tools: workspace.timeline_run, workspace.timeline_compare","Budget: low","Permissions: command execution inside timeline only","Output contract: command, exit code, pass/fail verdict, relevant stdout/stderr excerpts."].join("\n")};for(const[s,n]of Object.entries(r)){const r=i.join(e,s);await t.access(r).then(()=>!0).catch(()=>!1)||await t.writeFile(r,`${n}\n`,"utf8")}}async readDefinition(e){const r=e.replace(/[^a-zA-Z0-9._-]+/g,"-"),s=i.join(this.workspaceRoot,".mesh","agents",`${r}.md`),n=await t.readFile(s,"utf8").catch(()=>"");if(!n)return{};const o=n.split(/\r?\n/g).find(e=>e.toLowerCase().startsWith("output contract:"))?.replace(/^output contract:\s*/i,"").trim();return{path:s,outputContract:o}}async writeRecord(e){await t.mkdir(this.basePath,{recursive:!0}),await t.writeFile(i.join(this.basePath,`${e.id}.json`),JSON.stringify(e,null,2),"utf8")}}
@@ -0,0 +1 @@
1
+ export function runCritic(e){const i=[];return e.verificationOk||i.push({severity:"high",reason:"Verification failed but promotion attempted.",evidence:"timeline verification verdict != pass"}),/any\b/.test(e.diffPreview)&&i.push({severity:"medium",reason:"Diff introduces implicit any-like typing risk.",evidence:"Detected token 'any' in diff preview"}),/TODO|FIXME/.test(e.diffPreview)&&i.push({severity:"low",reason:"Diff includes TODO/FIXME markers.",evidence:"Detected TODO/FIXME in diff preview"}),{ok:i.every(e=>"high"!==e.severity),findings:i}}
@@ -0,0 +1 @@
1
+ function e(e,t){const s=e.match(new RegExp(`${t}\\s*:\\s*\\[(.*?)\\]`,"is"));return s?s[1].split(",").map(e=>e.replace(/['"`]/g,"").trim()).filter(Boolean):[]}function t(e,t){const s=e.match(new RegExp(`${t}\\s*:\\s*([\\w-]+)`,"i"));return s?s[1].trim():null}import{promises as s}from"node:fs";import r from"node:path";export class PersonaLoader{workspaceRoot;constructor(e){this.workspaceRoot=e}async list(){const e=r.join(this.workspaceRoot,".mesh","personas");try{const t=await s.readdir(e);return(await Promise.all(t.filter(e=>e.endsWith(".md")).map(t=>this.readPersona(r.join(e,t))))).filter(e=>Boolean(e))}catch{return[]}}async assembleTeam(e){const t=await this.list(),s=function(e){const t=new Set;return/security|xss|auth|token|cve/i.test(e)&&t.add("security"),/perf|latency|p99|slow|optimi[sz]e/i.test(e)&&t.add("performance"),/a11y|accessibility|aria|screen reader/i.test(e)&&t.add("a11y"),/db|query|migration|sql|prisma/i.test(e)&&t.add("db"),/infra|deploy|ci|docker|kubernetes|helm/i.test(e)&&t.add("devops"),/frontend|ui|react|css|component/i.test(e)&&t.add("frontend"),/test|coverage|spec|jest|vitest|playwright/i.test(e)&&t.add("testing"),Array.from(t)}(e),r=t.filter(e=>s.includes(e.name));return{ok:!0,task:e,labels:s,personas:r.length>0?r:t.slice(0,2)}}async readPersona(a){try{const i=await s.readFile(a,"utf8"),o=r.basename(a,".md");return{name:o,systemPrompt:i.trim(),toolWhitelist:e(i,"tool_whitelist"),verificationRules:e(i,"verification_rules"),escalationThreshold:t(i,"escalation_threshold")||"medium"}}catch{return null}}}
@@ -0,0 +1 @@
1
+ export function runRedTeam(e){const n=[],t=[];return/parseInt|Number\(/.test(e.diffPreview)&&(n.push("property: numeric parsing should reject NaN and Infinity."),t.push({input:"Infinity",reason:"Potential unchecked numeric coercion."})),/JSON\.parse/.test(e.diffPreview)&&(n.push("property: malformed JSON input should never crash request path."),t.push({input:"{ invalid json }",reason:"Potential unguarded JSON.parse path."})),{ok:0===t.length,generatedTests:n,failingInputs:t}}
@@ -0,0 +1 @@
1
+ function t(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(t).join(",")+"]";return"{"+Object.keys(e).sort().map(s=>JSON.stringify(s)+":"+t(e[s])).join(",")+"}"}function e(t){return i.createHash("sha256").update(t).digest("hex")}function s(t,e){return i.createHmac("sha256",t).update(e).digest("hex")}import{promises as r}from"node:fs";import o from"node:path";import i from"node:crypto";export class AuditLogger{workspaceRoot;previousHash="genesis";key;constructor(t,e){this.workspaceRoot=t;const s=`${e||process.env.USER||"mesh-user"}:${this.workspaceRoot}`;this.key=i.createHash("sha256").update(s).digest()}async append(i,n,a){const c=(new Date).toISOString(),h=process.env.USER||"mesh-user",u=process.env.BEDROCK_MODEL_ID||"unknown-model",p=e(t(n)),l=e(t(a)),d=this.previousHash,f=e([c,h,u,i,p,l,d].join("|")),y={ts:c,user:h,model:u,tool:i,inputHash:p,outputHash:l,parentHash:d,hash:f,signature:s(this.key,f)};this.previousHash=f;const m=this.dayFile();return await r.mkdir(o.dirname(m),{recursive:!0}),await r.appendFile(m,JSON.stringify(y)+"\n","utf8"),y}async replay(t=200){return(await this.readAllEntries()).slice(-t)}async verify(){const t=await this.readAllEntries();let r="genesis",o=0;for(const i of t){const t=e([i.ts,i.user,i.model,i.tool,i.inputHash,i.outputHash,r].join("|")),n=s(this.key,t);t===i.hash&&n===i.signature||(o+=1),r=i.hash}return{ok:0===o,total:t.length,invalid:o}}dayFile(){const t=(new Date).toISOString().slice(0,10);return o.join(this.workspaceRoot,".mesh","audit",`${t}.jsonl`)}async readAllEntries(){const t=o.join(this.workspaceRoot,".mesh","audit"),e=await r.readdir(t).catch(()=>[]),s=[];for(const i of e.filter(t=>t.endsWith(".jsonl")).sort()){const e=await r.readFile(o.join(t,i),"utf8").catch(()=>"");for(const t of e.split(/\r?\n/g).filter(Boolean))try{s.push(JSON.parse(t))}catch{}}return s}}
package/dist/auth.js ADDED
@@ -0,0 +1 @@
1
+ function e(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"string"==typeof e.access_token&&function(e){const s=e.split(".");if(3!==s.length)return!1;try{const e=JSON.parse(Buffer.from(s[1],"base64url").toString("utf8"));return!("number"==typeof e.exp&&1e3*e.exp<Date.now())}catch{return!1}}(e.access_token)}function s(e){return e.trim().replace(/\s+at\s+|[\(\[]\s*at\s*[\)\]]|_at_|\*at\*/i,"@").replace(/\s+/g,"").toLowerCase()}async function t(){try{const e=await import("keytar");return e.default??e}catch{return null}}import n from"node:fs/promises";import i from"node:path";import r from"node:os";import a from"enquirer";const{prompt:o}=a;import{createClient as c}from"@supabase/supabase-js";import u from"picocolors";import"dotenv/config";const l=process.env.SUPABASE_URL||"https://msmonxiacxhendxehezw.supabase.co",h=process.env.SUPABASE_ANON_KEY||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1zbW9ueGlhY3hoZW5keGVoZXp3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY5NDU3NTMsImV4cCI6MjA5MjUyMTc1M30.K-FQFpcOwtJAIAfn5lTzmrox_6cv_8qqXGxi9IgosB8",m=i.join(r.homedir(),".config","mesh"),d=i.join(m,"session.json"),p="mesh-agent-cli",f="refresh-token",w=process.env.MESH_USERNAME_EMAIL_DOMAIN?.trim();export class AuthManager{supabase;session=null;keytarUnavailable=!1;constructor(){this.supabase=c(l,h)}async restoreAuthenticated(){try{const s=await n.readFile(d,"utf-8"),t=JSON.parse(s);if(!e(t))throw new Error("Invalid session shape");const i=await this.getKeychainRefreshToken(),r=t.refresh_token??void 0,a=i||r;if(t.access_token){const{data:e,error:s}=await this.supabase.auth.setSession({access_token:t.access_token,refresh_token:a||""});if(!s&&e.session&&e.user&&e.user.email)return this.session=e.session,await this.saveSession(e.session),{email:e.user.email,id:e.user.id}}}catch{}return null}async ensureAuthenticated(){const e=await this.restoreAuthenticated();return e||this.promptLogin()}async promptLogin(){process.stdout.write(["",`${u.cyan(u.bold("mesh"))} ${u.dim("Please sign in to continue.")}`,""].join("\n")+"\n");let e=null;for(;!e;){const{identifier:t,password:n}=await o([{type:"input",name:"identifier",message:u.dim("email or username: ")},{type:"password",name:"password",message:u.dim("password: ")}]),i=s(t||""),r=n?.trim()||"";if(!i||!r){process.stdout.write(u.red("\n ✗ Email/username and password are required.\n\n"));continue}const a=await this.resolveLoginEmail(i);if(!a){process.stdout.write(u.red("\n ✗ Username not found or ambiguous. Try your full email address.\n\n"));continue}const{data:c,error:l}=await this.supabase.auth.signInWithPassword({email:a,password:r});!l&&c.session&&c.user&&c.user.email?(this.session=c.session,await this.saveSession(c.session),e={email:c.user.email,id:c.user.id}):process.stdout.write(u.red(`\n ✗ ${l?.message??"Login failed. Please try again."}\n\n`))}return process.stdout.write(u.green(`\n ✓ Signed in as ${e.email}\n\n`)),e}async signOut(){await this.supabase.auth.signOut();try{await n.unlink(d),await this.deleteKeychainRefreshToken()}catch{}process.stdout.write(u.dim("\nSigned out.\n"))}async saveSession(e){await n.mkdir(m,{recursive:!0,mode:448});let s=!1;e.refresh_token&&(s=await this.setKeychainRefreshToken(e.refresh_token));const{refresh_token:t,...i}=e,r=s||!e.refresh_token?i:{...i,refresh_token:e.refresh_token};await n.writeFile(d,JSON.stringify(r),{mode:384})}getAccessToken(){return this.session?.access_token}async resolveLoginEmail(e){if(e.includes("@"))return e;try{const{data:s,error:t}=await this.supabase.rpc("mesh_resolve_login_identifier",{identifier:e});if(!t&&"string"==typeof s&&s.includes("@"))return s.trim().toLowerCase()}catch{}return w?`${e}@${w}`.toLowerCase():null}async getKeychainRefreshToken(){const e=await t();if(!e)return this.keytarUnavailable=!0,null;try{return await e.getPassword(p,f)}catch{return this.keytarUnavailable=!0,null}}async setKeychainRefreshToken(e){const s=await t();if(!s)return this.noteKeytarFallback(),!1;try{return await s.setPassword(p,f,e),!0}catch{return this.noteKeytarFallback(),!1}}async deleteKeychainRefreshToken(){const e=await t();e&&await e.deletePassword(p,f).catch(()=>!1)}noteKeytarFallback(){this.keytarUnavailable||(this.keytarUnavailable=!0,process.stderr.write(u.dim("[Mesh] OS keychain unavailable; storing session fallback in ~/.config/mesh/session.json with 0600 permissions.\n")))}}
@@ -0,0 +1 @@
1
+ import t from"node:fs/promises";import e from"node:path";import s from"node:os";import a from"node:crypto";import{createClient as i}from"@supabase/supabase-js";export class CacheManager{l1BasePath;supabase=null;workspaceHash;pendingL2Writes=new Map;flushTimer=null;constructor(t){this.workspaceHash=a.createHash("md5").update(t.agent.workspaceRoot).digest("hex"),this.l1BasePath=e.join(s.tmpdir(),"mesh-agent-cache",this.workspaceHash),t.agent.enableCloudCache&&t.supabase?.url&&t.supabase?.key&&(this.supabase=i(t.supabase.url,t.supabase.key))}getL1Path(t,s){return e.join(this.l1BasePath,t,`${s}.json`)}async getCapsule(e,s,a,i){const n=this.getL1Path(e,s);try{const e=await t.readFile(n,"utf-8"),s=JSON.parse(e);if(i&&s.contentHash===i)return s;if(!i&&s.mtimeMs===a)return s}catch{}if(this.supabase)try{const{data:t,error:n}=await this.supabase.from("capsules").select("content, mtime, content_hash").eq("workspace_hash",this.workspaceHash).eq("file_path",e).eq("tier",s).maybeSingle();if(t&&!n){const n=i&&t.content_hash===i,r=!i&&Number(t.mtime)===a;if(n||r){const n={content:t.content,capsuleTier:s,mtimeMs:a,contentHash:t.content_hash||i||""};return await this.writeL1(e,s,n),n}}if(i){const{data:t,error:n}=await this.supabase.from("capsules").select("content, mtime, content_hash").eq("content_hash",i).eq("tier",s).limit(1).maybeSingle();if(t&&!n){const n={content:t.content,capsuleTier:s,mtimeMs:a,contentHash:i};return await this.writeL1(e,s,n),n}}}catch{}return null}async setCapsule(t,e,s,a,i){const n={content:s,capsuleTier:e,mtimeMs:a,contentHash:i||""};await this.writeL1(t,e,n),this.supabase&&this.queueL2Write({workspace_hash:this.workspaceHash,file_path:t,tier:e,content:s,mtime:a,content_hash:i||""})}async getCapsuleBatch(e){const s=new Map,a=[];for(const i of e){const e=this.batchKey(i.filePath,i.tier),n=this.getL1Path(i.filePath,i.tier);try{const a=await t.readFile(n,"utf-8"),r=JSON.parse(a),h=i.contentHash&&r.contentHash===i.contentHash,c=!i.contentHash&&r.mtimeMs===i.mtimeMs;if(h||c){s.set(e,r);continue}}catch{}a.push(i)}if(!this.supabase||0===a.length)return s;for(let t=0;t<a.length;t+=100){const e=a.slice(t,t+100),i=Array.from(new Set(e.map(t=>t.filePath))),n=Array.from(new Set(e.map(t=>t.tier)));try{const{data:t,error:a}=await this.supabase.from("capsules").select("file_path, tier, content, mtime, content_hash").eq("workspace_hash",this.workspaceHash).in("file_path",i).in("tier",n);if(a||!Array.isArray(t))continue;const r=new Map(e.map(t=>[this.batchKey(t.filePath,t.tier),t]));for(const e of t){const t=this.batchKey(e.file_path,e.tier),a=r.get(t);if(!a)continue;const i=a.contentHash&&e.content_hash===a.contentHash,n=!a.contentHash&&Number(e.mtime)===a.mtimeMs;if(!i&&!n)continue;const h={content:e.content,capsuleTier:e.tier,mtimeMs:a.mtimeMs,contentHash:e.content_hash||a.contentHash||""};s.set(t,h),await this.writeL1(a.filePath,a.tier,h)}}catch{}}return s}async flushCache(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.supabase||0===this.pendingL2Writes.size)return;const t=Array.from(this.pendingL2Writes.values());this.pendingL2Writes.clear();try{await this.supabase.from("capsules").upsert(t,{onConflict:"workspace_hash,file_path,tier"})}catch{}}async deleteCapsule(e,s){const a=this.getL1Path(e,s);try{await t.unlink(a)}catch{}if(this.supabase)try{await this.supabase.from("capsules").delete().eq("workspace_hash",this.workspaceHash).eq("file_path",e).eq("tier",s)}catch{}}async getSyncStatus(){if(!this.supabase)return{l2Count:0,l2Enabled:!1};try{const{count:t,error:e}=await this.supabase.from("capsules").select("*",{count:"exact",head:!0}).eq("workspace_hash",this.workspaceHash);return{l2Count:t||0,l2Enabled:!0}}catch{return{l2Count:0,l2Enabled:!0}}}async writeL1(s,a,i){try{const n=this.getL1Path(s,a);await t.mkdir(e.dirname(n),{recursive:!0}),await t.writeFile(n,JSON.stringify(i),"utf-8")}catch{}}queueL2Write(t){this.pendingL2Writes.set(this.batchKey(t.file_path,t.tier),t),this.pendingL2Writes.size>=50?this.flushCache():this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushCache()},500),this.flushTimer.unref?.())}batchKey(t,e){return`${t}\0${e}`}async getSimilarRagQuery(s,a=.95){const i=e.join(this.l1BasePath,"rag_queries.json");try{const e=await t.readFile(i,"utf-8"),n=JSON.parse(e);for(const t of n)if(this.cosine(s,t.queryVector)>=a)return t.results}catch{}return null}async setRagQuery(s,a){const i=e.join(this.l1BasePath,"rag_queries.json");let n=[];try{const e=await t.readFile(i,"utf-8");n=JSON.parse(e)}catch{}n.push({queryVector:s,results:a}),n.length>50&&n.shift(),await t.mkdir(e.dirname(i),{recursive:!0}),await t.writeFile(i,JSON.stringify(n),"utf-8")}cosine(t,e){if(!t||!e||0===t.length||0===e.length||t.length!==e.length)return 0;let s=0;for(let a=0;a<t.length;a++)s+=t[a]*e[a];return s}}
@@ -0,0 +1 @@
1
+ async function t(t,n,i){if(i.trim())try{const r=e.join(t,".mesh","tee");await s.mkdir(r,{recursive:!0});const o=n.trim().slice(0,40).replace(/[^a-zA-Z0-9_\-]/g,"_").replace(/_+/g,"_"),a=`${Date.now()}_${o}.log`,c=e.join(r,a);await s.writeFile(c,i,"utf8");const l=(await s.readdir(r)).filter(t=>t.endsWith(".log")).sort(),u=l.slice(0,Math.max(0,l.length-30));return await Promise.all(u.map(t=>s.unlink(e.join(r,t)).catch(()=>{}))),e.relative(t,c)}catch{return}}import{promises as s}from"node:fs";import e from"node:path";const n=/\x1B(?:[@-Z\\-_]|\[[0-9;]*[ -/]*[@-~]|\][^\x07]*\x07|\][^\x1B]*\x1B\\)|\r(?!\n)/g;export function stripAnsi(t){return t.replace(n,"")}const i=/^(?:[#=\-*>]{3,}.*\d{1,3}%|.*\d{1,3}%\s*[#=\-*>]{3,}|==> Downloading\b|==> Fetching\b|==> Pouring\b|Downloading\s+https?:\/\/|Fetching\s+https?:\/\/|remote:\s+Counting objects|remote:\s+Compressing objects|remote:\s+Total\s|remote:\s+Resolving deltas|Receiving objects:\s+\d|Resolving deltas:\s+\d|Unpacking objects:\s+\d|Counting objects:\s+\d|Delta compression|Compressing objects:\s+\d|Writing objects:\s+\d)/;export function stripProgress(t){return t.split("\n").filter(t=>!i.test(stripAnsi(t).trimStart())).join("\n")}export function deduplicateLines(t,s=3){const e=t.split("\n"),n=[];let i=0;for(;i<e.length;){const t=e[i];if(!t.trim()){n.push(t),i++;continue}let r=1;for(;i+r<e.length&&e[i+r]===t;)r++;if(r>=s)n.push(`${t} (×${r})`);else for(let s=0;s<r;s++)n.push(t);i+=r}return n.join("\n")}const r=[{pattern:/nothing to commit[,\s]+working tree clean/i,message:"ok: nothing to commit, working tree clean"},{pattern:/Your branch is up to date with/i,message:"ok: branch up to date",unless:/(?:CONFLICT|error|fatal|diverged)/i},{pattern:/Already up to date\./i,message:"ok: already up to date"},{pattern:/already installed and up.to.date/i,message:"ok: already installed and up-to-date"},{pattern:/Everything up-to-date/i,message:"ok: push — everything up-to-date"},{pattern:/No changes\. Your infrastructure matches/i,message:"ok: terraform — no changes, infrastructure matches configuration"},{pattern:/No issues found\./i,message:"ok: no issues found",unless:/error/i},{pattern:/All (\d+) tests? passed/i,message:t=>`ok: all ${t[1]} tests passed`,unless:/(?:fail|error)/i},{pattern:/(\d+) tests? passed,\s*0 failed/i,message:t=>`ok: ${t[1]} tests passed, 0 failed`,unless:/error/i},{pattern:/^(\d+) passed in [\d.]+s$/m,message:t=>`ok: ${t[1]} tests passed`,unless:/(?:fail|error)/i},{pattern:/test result: ok\.\s+(\d+) passed/i,message:t=>`ok: cargo test — ${t[1]} passed`},{pattern:/^ok\s+\S+\s+[\d.]+s$/m,message:"ok: go test passed",unless:/FAIL/},{pattern:/Passed! - (\d+) passed/i,message:t=>`ok: ${t[1]} tests passed`,unless:/failed/i}];export function checkShortCircuit(t){for(const s of r){const e=t.match(s.pattern);if(e&&!s.unless?.test(t))return"function"==typeof s.message?s.message(e):s.message}return null}export function detectCommandType(t){const s=t.trim().toLowerCase().replace(/^([a-z_][a-z0-9_]*=[^\s]* )+/,"");return/\bvitest\b/.test(s)||/\bjest\b/.test(s)||/\bmocha\b/.test(s)||/\b(?:pnpm|npm|yarn)\s+(?:run\s+)?test\b/.test(s)||/\bnpx\s+(?:--[^\s]+\s+)*(?:jest|vitest|mocha)\b/.test(s)?"js-test":/\bcargo\s+(?:test|nextest)\b/.test(s)?"cargo-test":/\bpytest\b/.test(s)?"pytest":/\bgo\s+test\b/.test(s)?"go-test":/\brspec\b/.test(s)?"rspec":/\bdotnet\s+test\b/.test(s)?"dotnet-test":/\bgit\s+status\b/.test(s)?"git-status":/\bgit\s+(?:diff|show)\b/.test(s)?"git-diff":/\bgit\s+log\b/.test(s)?"git-log":/\bgit\s+(?:add|commit|push|pull|fetch|merge|rebase|stash)\b/.test(s)?"git-mutation":/\bbiome\b/.test(s)||/\beslint\b/.test(s)||/\bruff\s+check\b/.test(s)||/\bgolangci-lint\b/.test(s)||/\brubocopb/.test(s)?"eslint":/\btsc\b/.test(s)&&!/\bts-node\b/.test(s)?"tsc":/\bcargo\s+(?:build|clippy|check)\b/.test(s)?"cargo-build":/\bgo\s+(?:build|vet)\b/.test(s)?"go-build":/\b(?:pnpm|npm|yarn)\s+(?:install|i|add|ci)\b/.test(s)||/\bbrew\s+(?:install|upgrade)\b/.test(s)||/\bpip\s+install\b/.test(s)||/\bpoetry\s+install\b/.test(s)||/\buv\s+(?:sync|install|add)\b/.test(s)||/\bbundle\s+install\b/.test(s)?"pkg-install":"passthrough"}export async function filterCommandOutput(s,e,n,i,r){const o=e.length+n.length,a=detectCommandType(s),c=stripProgress(stripAnsi(e)),l=stripProgress(stripAnsi(n));if(0===i){const t=checkShortCircuit((c+"\n"+l).trim());if(t)return{stdout:t,stderr:"",strategy:a,originalBytes:o,filteredBytes:t.length}}let u,p;switch(a){case"js-test":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1,o=0;for(const t of n){const s=t.trim();/^(Tests?|Test Suites?|Test Files?|Snapshots?|Duration|Time|Ran all):\s/.test(s)||/^Test Files\s+/.test(s)||/^Tests\s+/.test(s)||/^\s*(FAIL|×|✗)\s+\S/.test(t)?(i.push(t),r=!1):/^\s*(PASS|✓|✔)\s+\S/.test(t)||(/^\s*[●•✕✗]\s/.test(t)||/^\s*\d+\)\s/.test(t)?(r=!0,o=0,i.push(t)):r?""===s?(o++,o<=1&&i.push(t)):(o=0,i.push(t)):/^(Error|TypeError|ReferenceError|SyntaxError|AssertionError|FAIL)[\s:]/i.test(s)&&i.push(t))}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"cargo-test":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1;for(const t of n){const s=t.trim();/^test .+ \.\.\. ok$/.test(s)||/^running \d+ tests?$/.test(s)||(/^failures:$/.test(s)||/^-{4} .+ stdout -{4}$/.test(s)?(r=!0,i.push(t)):(r||/^test result:/.test(s)||/^error(\[|\s)/.test(s)||/\bFAILED\b/.test(s))&&i.push(t))}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"pytest":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1;for(const t of n){const s=t.trim();if(/^={3,}/.test(s)){if(/fail|error/i.test(s)){r=!0,i.push(t);continue}if(/passed/i.test(s)&&!/fail/i.test(s)){i.push(t),r=!1;continue}i.push(t)}else/^_{3,}/.test(s)?(r=!0,i.push(t)):r?i.push(t):/^[.]+$/.test(s)||/^PASSED\b/.test(s)||/^collected \d+ items?/.test(s)||(/^FAILED\b/.test(s)||/^ERROR\b/.test(s)||/^\s+E\s/.test(t)||/^\s*(short test summary|=)/.test(s))&&i.push(t)}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"go-test":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1;for(const t of n){const s=t.trim();/^--- FAIL/.test(s)||/^FAIL\s/.test(s)||/^ok\s+\S+/.test(s)?(i.push(t),r=!1):/panic:/.test(s)||/^goroutine \d+ \[/.test(s)?(r=!0,i.push(t)):r?(i.push(t),""===s&&(r=!1)):(/Error:/.test(s)||/\bFAIL\b/.test(s))&&i.push(t)}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"rspec":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1;for(const t of n){const s=t.trim();/^Failures:$/i.test(s)?(r=!0,i.push(t)):(/^Pending:/i.test(s)&&(r=!1),/^Finished in/.test(s)||/examples?,\s*\d+ failures?/.test(s)?(i.push(t),r=!1):r?i.push(t):/^[.F*]+$/.test(s)||/^Randomized with seed/.test(s)||(/\bfailed\b/i.test(s)||/\bFAILED\b/.test(s))&&i.push(t))}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"dotnet-test":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];let r=!1;for(const t of n){const s=t.trim();/^Determining projects to restore/i.test(s)||/^All projects are up.to.date/i.test(s)||/^Build succeeded/i.test(s)||(/^\s*✗\s/.test(t)||/^\s*Failed\s*$/.test(s)||/^\s*X\s+/.test(t)?(r=!0,i.push(t)):r?""===s?(r=!1,i.push(t)):i.push(t):/^(Failed!|Passed!)/.test(s)||/total \d+ in/.test(s)?i.push(t):(/Error Message:/i.test(s)||/Assert\.\w+\(\) Failure/.test(s))&&(r=!0,i.push(t)))}return i.join("\n").replace(/\n{3,}/g,"\n\n").trim()||e.trim()}(c,l);break;case"git-status":u=function(t){const s=stripAnsi(t).split("\n");let e="",n="";const i=[],r=[],o=[];let a=null;for(const t of s){const s=t.trimEnd(),c=s.trim(),l=s.match(/^.{0,20}[Bb]ranch\s+(\S+)\s*$/i)||s.match(/^HEAD detached at (\S+)/i)||s.match(/^HEAD abgekoppelt bei (\S+)/i);if(l){e=l[1].trim();continue}const u=c.match(/\b(\d+) commit/i);if(u)/ahead|voraus|avance|adelantado|avant/i.test(c)?n=` (↑${u[1]})`:/behind|zurück|retard|detrás|trás/i.test(c)&&(n=` (↓${u[1]})`);else if(/diverged|auseinander|divergé|divergido/i.test(c))n=" (diverged)";else{if(/nothing to commit|nichts.*zu committen|rien à valider|nada.*confirmar/i.test(c))return(e?`branch: ${e}${n}\n`:"")+"nothing to commit, working tree clean";if(!/^\s*\(/.test(s)){if(!s.startsWith("\t")&&c.endsWith(":")&&c.length>2){const t=c.toLowerCase();if(/commit.*:\s*$/.test(t)&&!/not staged|nicht.*nicht|non préparées|sin preparar/i.test(t)){a="staged";continue}if(/not staged|nicht.*commit|non.*valid|sin preparar|não preparad/i.test(t)){a="unstaged";continue}if(/untrack|unversion|non suivi|sin seguimiento|não rastreados/i.test(t)){a="untracked";continue}a=null;continue}if(s.startsWith("\t")){const t=c.indexOf(":");if(t>0&&"untracked"!==a){const s=c.slice(0,t).trim(),e=c.slice(t+1).trim();if(e){const t=`${s}: ${e}`;"staged"===a?i.push(t):"unstaged"===a&&r.push(t)}}else"untracked"===a&&c&&!c.startsWith("(")&&o.push(c);continue}}}}const c=[];if(e&&c.push(`branch: ${e}${n}`),i.length){const t=i.slice(0,8).join(", "),s=i.length>8?` (+${i.length-8} more)`:"";c.push(`staged (${i.length}): ${t}${s}`)}if(r.length){const t=r.slice(0,8).join(", "),s=r.length>8?` (+${r.length-8} more)`:"";c.push(`unstaged (${r.length}): ${t}${s}`)}if(o.length){const t=o.slice(0,6).join(", "),s=o.length>6?` (+${o.length-6} more)`:"";c.push(`untracked (${o.length}): ${t}${s}`)}return(0===c.length||1===c.length&&c[0].startsWith("branch:"))&&c.push("nothing to commit, working tree clean"),c.join("\n")}(c);break;case"git-diff":u=function(t){const s=stripAnsi(t).split("\n"),e=[],n=[];let i=!1;const r=t=>{0!==n.length&&(n.length<=4?e.push(...n):i?t?(e.push(...n.slice(0,2)),n.length>2&&e.push(` ... [${n.length-2} lines] ...`)):(e.push(...n.slice(0,2)),e.push(` ... [${n.length-2} lines] ...`)):(e.push(` ... [${n.length-2} lines] ...`),e.push(...n.slice(-2))),n.length=0)};for(const t of s)/^(diff --git|index |---|\+\+\+|@@|Binary files )/.test(t)?(r(!0),e.push(t),i=!1):t.startsWith("+")||t.startsWith("-")?(r(!1),e.push(t),i=!0):t.startsWith(" ")||""===t?n.push(t):(r(!1),e.push(t),i=!1);return r(!0),e.join("\n")}(c);break;case"git-log":u=function(t){const s=stripAnsi(t);if(!/^commit [0-9a-f]{40}/m.test(s))return s.trim();const e=s.split("\n"),n=[];let i="",r="",o="",a="";const c=()=>{if(!i)return;const t=[i];o&&t.push(`(${o})`),a&&t.push(a),r&&t.push(`— ${r}`),n.push(t.join(" ")),i="",r="",o="",a=""};for(const t of e){const s=t.trim();/^commit [0-9a-f]{40}/.test(s)?(c(),i=s.slice(7,14)):/^Author:/.test(s)?r=s.replace(/^Author:\s*/,"").replace(/<[^>]*>/,"").trim():/^Date:/.test(s)?o=s.replace(/^Date:\s*/,"").trim():!/^ /.test(t)||a||(a=s)}return c(),n.filter(Boolean).join("\n").trim()}(c);break;case"git-mutation":u=function(t,s){const e=stripAnsi(t+"\n"+s).split("\n"),n=[];for(const t of e){const s=t.trim();s&&(/^remote:\s+(Counting|Compressing|Total|Resolving)/.test(s)||/^(Enumerating|Counting|Delta compression|Compressing|Writing) objects:/.test(s)||/^Unpacking objects:/.test(s)||/^Receiving objects:/.test(s)||n.push(t))}return n.join("\n").trim()}(c,l);break;case"eslint":u=function(t,s){const e=stripAnsi(t+"\n"+s).split("\n"),n=[];let i="",r=0;for(const t of e){const s=t.trim();s&&(/^(?:\/|\.\/|\.\.\/|[A-Z]:\\)[^\n]*\.(ts|tsx|js|jsx|mjs|cjs|py|go|rb|rs)$/.test(s)||/^[a-zA-Z0-9_\-][a-zA-Z0-9_\-./]*\.(ts|tsx|js|jsx|mjs|cjs|py|go|rb|rs)$/.test(s)?(i=s,r=0,n.push(t)):/^\s*\d+[:\|]\d+\s+(error|warning|note|info)/i.test(t)||/^\s*\d+\s+(error|warning|note)/i.test(t)?(r<100?(n.push(t),r++):100===r&&(n.push(` ... (more violations in ${i})`),r++),/error/i.test(s)):(/^[^\s]+\.py:\d+:\d+:\s+[A-Z]\d+/.test(s)||/^(✖|✗|×|Found|Linted|\d+ (?:error|warning|problem|issue)|✓ Lint)/i.test(s)||/\d+ error[s,]/.test(s)||/\d+ warning/.test(s))&&n.push(t))}return 0===n.length?"ok: no lint violations found":n.join("\n").trim()}(c,l);break;case"tsc":u=function(t,s){const e=stripAnsi(t+"\n"+s).split("\n"),n=[],i=new Set;for(const t of e){const s=t.trim();(/error TS\d+:/.test(s)||/warning TS\d+:/.test(s))&&(i.has(s)||(i.add(s),n.push(s)))}if(0===n.length)return"ok: TypeScript compiled without errors";const r=n.slice(0,80),o=n.length>80?`\n...and ${n.length-80} more errors`:"";return`${r.join("\n")}${o}\n\n${n.length} TypeScript error${1!==n.length?"s":""}`}(c,l);break;case"cargo-build":u=function(t,s){const e=stripAnsi(s+"\n"+t).split("\n"),n=[];let i=!1;for(const t of e){const s=t.trim();if(/^(error|warning)(\[E\d+\])?:/.test(s)||/^error: could not compile/.test(s))i=!0,n.push(t);else{if(i){if(/^\s*(-->|\||\d+ \||\s*=\s*(note|help|see))/.test(t)||""===s){""===s?(i=!1,n.push(t)):n.push(t);continue}i=!1}(/^error: aborting due to/.test(s)||/^error\[/.test(s)||/^For more information about this error/.test(s))&&n.push(t)}}return 0===n.length?"ok: cargo build/clippy — no errors or warnings":n.join("\n").trim()}(c,l);break;case"go-build":u=function(t,s){const e=stripAnsi(s+"\n"+t).split("\n").filter(t=>{const s=t.trim();return s&&(/^[^:]+\.go:\d+:\d*:/.test(s)||/^#\s/.test(s)||/\berror\b/i.test(s))});return 0===e.length?"ok: go build/vet — no errors":e.join("\n").trim()}(c,l);break;case"pkg-install":u=function(t,s){const e=stripAnsi(t+"\n"+s),n=e.split("\n"),i=[];for(const t of n){const s=t.trim();s&&(/^(WARN|ERR!|error|npm warn|warning)/i.test(s)||/^(Packages?:|added|removed|changed|audited|Found|fixed)/i.test(s)||/Done in [\d.]+s/.test(s)||/packages? are looking/.test(s)||/vulnerabilit/i.test(s)||/^Successfully installed/.test(s)||/^==> Summary/.test(s)||/\d+ packages? installed/.test(s)||/already installed/.test(s))&&i.push(s)}if(0===i.length)return e.split("\n").map(t=>t.trim()).filter(Boolean).slice(-5).join("\n");return i.join("\n")}(c,l);break;default:u=deduplicateLines((c+(l?"\n"+l:"")).trim())}u.trim()||!c.trim()&&!l.trim()||(u=deduplicateLines((c+"\n"+l).trim())),u=deduplicateLines(u);const d=e+(n?"\n--- stderr ---\n"+n:"");if(u.length>12e3){p=await t(r,s,d);const e=u.slice(0,4e3),n=u.slice(-6e3);u=`${e}${p?`\n\n[output truncated — full output saved at: ${p}]\n`:"\n\n[output truncated]\n"}${n}`}else 0!==i&&o>5e3&&(p=await t(r,s,d),p&&(u=`${u}\n\n[full unfiltered output: ${p}]`));return{stdout:u.trim(),stderr:"",strategy:a,originalBytes:o,filteredBytes:u.length,teePath:p}}
@@ -0,0 +1 @@
1
+ const e=new Set(["npm","node","git"]),s=[{pattern:/\brm\s+(?:-[^\s]*r[^\s]*f|-[^\s]*f[^\s]*r|--recursive\b[\s\S]*--force\b|--force\b[\s\S]*--recursive\b)/i,reason:"recursive forced deletion"},{pattern:/\b(?:sudo\s+)?(?:mkfs|diskutil\s+erase|fdisk|parted|sfdisk)\b/i,reason:"disk or filesystem mutation"},{pattern:/\bdd\b[\s\S]*\bof\s*=\s*(?:\/dev\/|\/)/i,reason:"raw disk or root filesystem write"},{pattern:/:\s*\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/,reason:"fork bomb"},{pattern:/\bgit\s+push\b[\s\S]*(?:--force|-f\b)/i,reason:"forced git push"},{pattern:/\bgit\s+reset\s+--hard\b/i,reason:"hard git reset"},{pattern:/\bgit\s+clean\b[\s\S]*-[^\s]*f/i,reason:"forced git clean"},{pattern:/\b(?:rm|shred|truncate)\b[\s\S]*(?:\.env(?:\b|[./_-])|_history\b|\.bash_history\b|\.zsh_history\b)/i,reason:"credential or shell history deletion"},{pattern:/\b(?:curl|wget|nc|netcat)\b[\s\S]*(?:\bprintenv\b|\benv\b|\bcat\s+\.env\b|\bcat\s+[^;&|]*\/\.env\b)/i,reason:"credential exfiltration pattern"},{pattern:/\b(?:cat|less|more|head|tail|sed|awk|grep|rg)\b[\s\S]*(?:^|\s)(?:\.env(?:\b|[./_-])|[^;&|]*\/\.env(?:\b|[./_-])|[^;&|]*(?:secret|credential|token|private)[^;&|]*\.(?:json|key|pem)\b)/i,reason:"credential file read"},{pattern:/(?:^|[;&|]\s*)(?:env|printenv|set)\b/i,reason:"environment dump"},{pattern:/\bchmod\s+-R\s+777\s+(?:\/|\.)/i,reason:"unsafe recursive permission change"},{pattern:/\bchown\s+-R\b[\s\S]+\s(?:\/|\.)/i,reason:"unsafe recursive ownership change"}];export function analyzeCommandSafety(t){const n=t.trim();if(!n)return{ok:!1,reason:"empty command"};const r=n.replace(/['"\\]/g,"");for(const e of s)if(e.pattern.test(n)||e.pattern.test(r))return{ok:!1,reason:e.reason,pattern:String(e.pattern)};if(/(?:^|\|\s*|\&\&\s*|;\s*)(?:eval|exec)\s+/i.test(n))return{ok:!1,reason:"dynamic evaluation (eval/exec) blocked"};if(/(?:`[^`]*`|\$\([^)]*\))/.test(n))return{ok:!1,reason:"command substitution blocked"};if(/\|\s*base64\s+(?:-d|--decode)\s*\|\s*(?:sh|bash|zsh)/i.test(n))return{ok:!1,reason:"base64 payload execution blocked"};if(/\b(?:sh|bash|zsh)\s+-c\b/i.test(n))return{ok:!1,reason:"nested shell execution blocked"};if(/(?:^|[;&|]\s*)(?:curl|wget|nc|netcat)\b/i.test(n)&&/\b(?:\.env|SECRET|TOKEN|API_KEY|PASSWORD|PRIVATE_KEY|printenv|env)\b/i.test(n))return{ok:!1,reason:"network credential exfiltration blocked"};const o=function(s){const t=[];let n="",r=null;for(let e=0;e<s.length;e+=1){const o=s[e];if(r)o===r?r=null:"\\"===o&&e+1<s.length?(e+=1,n+=s[e]):n+=o;else if("'"!==o&&'"'!==o)if(/\s/.test(o))n&&(t.push(n),n="");else{if(/[;&|<>]/.test(o))return{reason:"shell control operators are not allowed"};if("\\"===o||"`"===o)return{reason:"shell escaping and command substitution are not allowed"};n+=o}else r=o}if(r)return{reason:"unterminated quoted argument"};if(n&&t.push(n),0===t.length)return{reason:"empty command"};const o=t[0];return e.has(o)?{command:o,args:t.slice(1)}:{reason:"command must start with an allowed executable: npm, node, or git"}}(n);return"reason"in o?{ok:!1,reason:o.reason}:{ok:!0,parsed:o}}export function assertCommandAllowed(e){const s=analyzeCommandSafety(e);if(!s.ok)throw new Error(`workspace.run_command blocked: ${s.reason}`)}export function parseAllowedCommand(e){const s=analyzeCommandSafety(e);if(!s.ok||!s.parsed)throw new Error(`workspace.run_command blocked: ${s.reason}`);return s.parsed}