@unerr-ai/unerr 0.0.0-beta.5 → 0.0.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -116,9 +116,21 @@ After install, your AI agent automatically connects to unerr via MCP. No config
116
116
 
117
117
  ## Supported Agents
118
118
 
119
+ ### Confirmed
120
+
121
+ Fully tested and production-ready.
122
+
119
123
  ```bash
120
124
  unerr install claude-code # .mcp.json + CLAUDE.md + .claude/skills/ + hooks
121
- unerr install cursor # .cursor/mcp.json + .cursor/rules/
125
+ unerr install cursor # .cursor/mcp.json + .cursor/rules/ + hooks
126
+ unerr install antigravity # .antigravity/mcp_config.json + .agents/rules/ + .agents/skills/
127
+ ```
128
+
129
+ ### In Development
130
+
131
+ MCP config and basic integration work. Instruction injection, skills, and hooks support varies — contributions welcome.
132
+
133
+ ```bash
122
134
  unerr install vscode # .vscode/mcp.json + .github/copilot-instructions.md
123
135
  unerr install windsurf # .windsurf/mcp.json
124
136
  unerr install zed # .zed/mcp.json
@@ -134,7 +146,7 @@ unerr install github-copilot-cli # .github/mcp.json + .github/copilot-instructio
134
146
  unerr install continue # .continue/config.json
135
147
  ```
136
148
 
137
- Works with any MCP-compatible agent. 15 supported out of the box.
149
+ 16 agents supported. Works with any MCP-compatible client.
138
150
 
139
151
  <details>
140
152
  <summary>Manual MCP config (any agent)</summary>
package/dist/cli.js CHANGED
@@ -4576,7 +4576,9 @@ function normalizeAgentName(input) {
4576
4576
  "copilot-cli": "github-copilot-cli",
4577
4577
  gemini: "gemini-cli",
4578
4578
  code: "vscode",
4579
- vs: "vscode"
4579
+ vs: "vscode",
4580
+ google: "antigravity",
4581
+ "google-antigravity": "antigravity"
4580
4582
  };
4581
4583
  return aliases[input.toLowerCase()] ?? input.toLowerCase();
4582
4584
  }
@@ -4764,6 +4766,18 @@ var init_agent_registry = __esm({
4764
4766
  description: "Open-source AI code assistant (VS Code/JetBrains)",
4765
4767
  instructionFilePath: null,
4766
4768
  instructionFormat: null
4769
+ },
4770
+ {
4771
+ id: "antigravity",
4772
+ name: "Google Antigravity",
4773
+ projectConfigPath: ".antigravity/mcp_config.json",
4774
+ configFormat: "mcp-json",
4775
+ dirMarkers: [".antigravity", ".agents"],
4776
+ envVars: ["ANTIGRAVITY_PROJECT_DIR", "ANTIGRAVITY_VERSION"],
4777
+ hookSupport: false,
4778
+ description: "Google's AI coding IDE (Gemini 3)",
4779
+ instructionFilePath: ".agents/rules/unerr-instructions.md",
4780
+ instructionFormat: "antigravity-rule"
4767
4781
  }
4768
4782
  ];
4769
4783
  }
@@ -5049,6 +5063,9 @@ async function detectIde(cwd) {
5049
5063
  if (existsSync6(join8(cwd, ".vscode"))) return "vscode";
5050
5064
  if (process.env.ZED_TERM === "true" || existsSync6(join8(cwd, ".zed")))
5051
5065
  return "zed";
5066
+ if (process.env.ANTIGRAVITY_PROJECT_DIR || process.env.ANTIGRAVITY_VERSION)
5067
+ return "antigravity";
5068
+ if (existsSync6(join8(cwd, ".antigravity"))) return "antigravity";
5052
5069
  return "unknown";
5053
5070
  }
5054
5071
  function ideDisplayName(ide) {
@@ -5083,6 +5100,8 @@ function ideDisplayName(ide) {
5083
5100
  return "GitHub Copilot CLI";
5084
5101
  case "continue":
5085
5102
  return "Continue";
5103
+ case "antigravity":
5104
+ return "Google Antigravity";
5086
5105
  case "other":
5087
5106
  return "Other";
5088
5107
  case "unknown":
@@ -5111,6 +5130,7 @@ var init_detect = __esm({
5111
5130
  { title: "Augment", value: "augment" },
5112
5131
  { title: "GitHub Copilot CLI", value: "github-copilot-cli" },
5113
5132
  { title: "Continue", value: "continue" },
5133
+ { title: "Google Antigravity", value: "antigravity" },
5114
5134
  { title: "Other (manual MCP setup)", value: "other" }
5115
5135
  ];
5116
5136
  }
@@ -9569,9 +9589,9 @@ function buildScipArgs(language, binaryPath, projectRoot, outputPath) {
9569
9589
  case "go":
9570
9590
  return [binaryPath, "-o", outputPath, "./..."];
9571
9591
  case "java":
9572
- return [binaryPath, "--output", outputPath];
9592
+ return [binaryPath, "index", "--output", outputPath];
9573
9593
  case "rust":
9574
- return [binaryPath, "scip", outputPath];
9594
+ return [binaryPath, "scip", projectRoot, "--output", outputPath];
9575
9595
  default:
9576
9596
  return [binaryPath, "--output", outputPath];
9577
9597
  }
@@ -11751,6 +11771,12 @@ function getSkillDir(ide, cwd) {
11751
11771
  ext: ".md",
11752
11772
  dirPerSkill: false
11753
11773
  };
11774
+ case "antigravity":
11775
+ return {
11776
+ dir: join29(cwd, ".agents", "skills"),
11777
+ ext: ".md",
11778
+ dirPerSkill: true
11779
+ };
11754
11780
  default:
11755
11781
  return {
11756
11782
  dir: join29(cwd, ".unerr", "skills"),
@@ -11765,7 +11791,12 @@ function writeSkillFile(skill, ide, skillDir, ext, dirPerSkill) {
11765
11791
  const skillName = `unerr-${baseName}`;
11766
11792
  let filePath;
11767
11793
  let content;
11768
- if (dirPerSkill) {
11794
+ if (dirPerSkill && ide === "antigravity") {
11795
+ const skillSubDir = join29(skillDir, skillName);
11796
+ mkdirSync16(skillSubDir, { recursive: true });
11797
+ filePath = join29(skillSubDir, "SKILL.md");
11798
+ content = formatAntigravitySkill(skill);
11799
+ } else if (dirPerSkill) {
11769
11800
  const skillSubDir = join29(skillDir, skillName);
11770
11801
  mkdirSync16(skillSubDir, { recursive: true });
11771
11802
  filePath = join29(skillSubDir, "SKILL.md");
@@ -11905,6 +11936,32 @@ version: "${skill.version ?? "1.0.0"}"
11905
11936
 
11906
11937
  # ${skill.name}
11907
11938
 
11939
+ ${skill.content}
11940
+ `;
11941
+ }
11942
+ function formatAntigravitySkill(skill) {
11943
+ const trigger = skill.trigger;
11944
+ const triggerType = trigger?.type ?? "always";
11945
+ let globs = [];
11946
+ if (trigger?.globs) {
11947
+ globs = trigger.globs;
11948
+ }
11949
+ let frontmatter = `---
11950
+ name: ${skill.name}
11951
+ description: ${skill.description}`;
11952
+ if (globs.length > 0) {
11953
+ frontmatter += `
11954
+ globs:
11955
+ ${globs.map((g) => ` - ${g}`).join("\n")}`;
11956
+ }
11957
+ if (triggerType === "manual") {
11958
+ frontmatter += `
11959
+ user_invocable: true`;
11960
+ }
11961
+ frontmatter += `
11962
+ ---`;
11963
+ return `${frontmatter}
11964
+
11908
11965
  ${skill.content}
11909
11966
  `;
11910
11967
  }
@@ -36986,6 +37043,10 @@ var COMMAND_HINTS = {
36986
37043
  // JS/TS
36987
37044
  tsc: "error_diagnostic",
36988
37045
  "npx tsc": "error_diagnostic",
37046
+ "pnpm run typecheck": "error_diagnostic",
37047
+ "npm run typecheck": "error_diagnostic",
37048
+ "yarn typecheck": "error_diagnostic",
37049
+ "pnpm typecheck": "error_diagnostic",
36989
37050
  eslint: "error_diagnostic",
36990
37051
  "npx eslint": "error_diagnostic",
36991
37052
  "biome check": "error_diagnostic",
@@ -36996,6 +37057,16 @@ var COMMAND_HINTS = {
36996
37057
  jshint: "error_diagnostic",
36997
37058
  "deno lint": "error_diagnostic",
36998
37059
  "bun lint": "error_diagnostic",
37060
+ "pnpm run lint": "error_diagnostic",
37061
+ "npm run lint": "error_diagnostic",
37062
+ "yarn lint": "error_diagnostic",
37063
+ "pnpm lint": "error_diagnostic",
37064
+ "pnpm run lint:fix": "error_diagnostic",
37065
+ "npm run lint:fix": "error_diagnostic",
37066
+ "yarn lint:fix": "error_diagnostic",
37067
+ "pnpm run check": "error_diagnostic",
37068
+ "npm run check": "error_diagnostic",
37069
+ "yarn check": "error_diagnostic",
36999
37070
  // Python
37000
37071
  mypy: "error_diagnostic",
37001
37072
  pyright: "error_diagnostic",
@@ -40257,6 +40328,25 @@ async function runExecMain(argv) {
40257
40328
  if (combined.length > 0 && !combined.endsWith("\n")) process.stdout.write("\n");
40258
40329
  return exitCode;
40259
40330
  }
40331
+ const TEE_RAW_LINE_LIMIT = 150;
40332
+ if (/\.unerr\/tee\/[^\s]*\.txt/.test(cmd)) {
40333
+ const lines = combined.split("\n");
40334
+ if (lines.length > TEE_RAW_LINE_LIMIT) {
40335
+ const truncated = lines.slice(0, TEE_RAW_LINE_LIMIT).join("\n");
40336
+ process.stdout.write(truncated);
40337
+ process.stdout.write(
40338
+ `
40339
+
40340
+ [unerr] Raw output truncated to ${TEE_RAW_LINE_LIMIT}/${lines.length} lines to prevent context overload. Use filtering (grep/head/tail) for specific sections.
40341
+ `
40342
+ );
40343
+ } else {
40344
+ process.stdout.write(combined);
40345
+ if (combined.length > 0 && !combined.endsWith("\n")) process.stdout.write("\n");
40346
+ }
40347
+ appendExecNudge();
40348
+ return exitCode;
40349
+ }
40260
40350
  try {
40261
40351
  const out = await compressShellOutput(cmd, combined, {
40262
40352
  cwd: process.cwd(),
@@ -40274,8 +40364,7 @@ async function runExecMain(argv) {
40274
40364
  }
40275
40365
  appendExecNudge();
40276
40366
  if (exitCode !== 0) {
40277
- process.stderr.write(`[unerr:exec] command exited with code ${exitCode}: ${cmd.slice(0, 120)}
40278
- `);
40367
+ startupLog.warn(`command exited with code ${exitCode}: ${cmd.slice(0, 120)}`);
40279
40368
  }
40280
40369
  return exitCode;
40281
40370
  }
@@ -41310,6 +41399,27 @@ function writeInstructionFile(cwd, ide) {
41310
41399
  if (agentDef.instructionFormat === "mdc") {
41311
41400
  return writeMdcInstructionFile(filePath);
41312
41401
  }
41402
+ if (agentDef.instructionFormat === "antigravity-rule") {
41403
+ mkdirSync15(dirname5(filePath), { recursive: true });
41404
+ const content = getInstructionContent();
41405
+ const antigravityContent = `---
41406
+ name: unerr-instructions
41407
+ description: Tool routing instructions for unerr MCP integration
41408
+ type: manual
41409
+ ---
41410
+
41411
+ ${content}
41412
+ `;
41413
+ const existed = existsSync21(filePath);
41414
+ if (existed) {
41415
+ const existing = readFileSync20(filePath, "utf-8");
41416
+ if (existing === antigravityContent) {
41417
+ return { path: filePath, action: "skipped" };
41418
+ }
41419
+ }
41420
+ writeFileSync11(filePath, antigravityContent, "utf-8");
41421
+ return { path: filePath, action: existed ? "updated" : "created" };
41422
+ }
41313
41423
  return mergeMarkdownSection(filePath, getInstructionContent());
41314
41424
  }
41315
41425
  function mergeMarkdownSection(filePath, content) {
@@ -41367,6 +41477,13 @@ function removeInstructionSection(cwd, ide) {
41367
41477
  unlinkSync3(filePath);
41368
41478
  return true;
41369
41479
  }
41480
+ if (agentDef.instructionFormat === "antigravity-rule") {
41481
+ if (existsSync21(filePath)) {
41482
+ unlinkSync3(filePath);
41483
+ return true;
41484
+ }
41485
+ return false;
41486
+ }
41370
41487
  const content = readFileSync20(filePath, "utf-8");
41371
41488
  const startIdx = content.indexOf(SENTINEL_START);
41372
41489
  const endIdx = content.indexOf(SENTINEL_END);
@@ -1,5 +1,5 @@
1
1
  import{n as e,t}from"./rolldown-runtime-jpDsebLB.js";import{n,t as r}from"./vis-network-NIJHUFI3.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var i=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),a=t(((e,t)=>{t.exports=i()}))(),o=[{id:`overview`,label:`Command Center`,href:`#/`},{id:`visual`,label:`Codebase Map`,href:`#/visual`},{id:`graph`,label:`Entity Explorer`,href:`#/graph`},{id:`ledger`,label:`Activity Log`,href:`#/ledger`},{id:`facts`,label:`Fact Store`,href:`#/facts`},{id:`session`,label:`Live Session`,href:`#/session`},{id:`token-flow`,label:`Token Trace`,href:`#/token-flow`},{id:`settings`,label:`Settings`,href:`#/settings`}];function s({title:e,subtitle:t,statusDot:n,activeRoute:r,children:i}){return(0,a.jsxs)(`div`,{className:`flex min-h-screen flex-col md:flex-row`,children:[(0,a.jsxs)(`aside`,{className:`flex w-full shrink-0 flex-col border-b border-border-subtle bg-sidebar px-5 py-6 md:w-56 md:border-r md:border-b-0 md:sticky md:top-0 md:h-screen md:overflow-y-auto`,children:[(0,a.jsxs)(`div`,{className:`mb-8 flex items-center gap-3`,children:[(0,a.jsx)(`img`,{src:`/icon-wordmark.png`,alt:`unerr`,className:`h-7`,draggable:!1}),(0,a.jsx)(`span`,{className:`ml-auto inline-flex h-2 w-2 rounded-full ${n===`live`?`bg-success shadow-[0_0_6px_rgba(52,211,153,0.6)]`:`bg-warning animate-pulse`}`,title:n===`live`?`SSE connected`:`Reconnecting...`})]}),(0,a.jsx)(`nav`,{className:`flex flex-col gap-0.5`,"aria-label":`Primary`,children:o.map(e=>(0,a.jsx)(`a`,{href:e.href,className:`block rounded-md px-3 py-2 text-sm transition-colors ${r===e.id?`el-raised font-medium text-foreground-emphasis`:`text-muted-foreground hover:text-foreground hover:el-raised`}`,children:e.label},e.id))}),t?(0,a.jsxs)(`div`,{className:`mt-auto pt-8`,children:[(0,a.jsx)(`div`,{className:`divider-shimmer mb-4`}),(0,a.jsx)(`p`,{className:`t-tertiary text-xs leading-relaxed`,children:t})]}):null]}),(0,a.jsxs)(`main`,{className:`flex min-h-0 flex-1 flex-col overflow-auto bg-background`,children:[(0,a.jsx)(`header`,{className:`border-b border-border-subtle bg-background/90 px-6 py-4 backdrop-blur-sm`,children:(0,a.jsx)(`h1`,{children:e})}),(0,a.jsx)(`div`,{className:`flex-1 p-6`,children:i})]})]})}var c=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},l=new class extends c{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},d=new class{#e=u;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function f(e){setTimeout(e,0)}var p=typeof window>`u`||`Deno`in globalThis;function m(){}function h(e,t){return typeof e==`function`?e(t):e}function g(e){return typeof e==`number`&&e>=0&&e!==1/0}function _(e,t){return Math.max(e+(t||0)-Date.now(),0)}function v(e,t){return typeof e==`function`?e(t):e}function y(e,t){return typeof e==`function`?e(t):e}function b(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==S(o,t.options))return!1}else if(!w(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function x(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(C(t.options.mutationKey)!==C(a))return!1}else if(!w(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function S(e,t){return(t?.queryKeyHashFn||C)(e)}function C(e){return JSON.stringify(e,(e,t)=>E(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function w(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>w(e[n],t[n])):!1}var ee=Object.prototype.hasOwnProperty;function te(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=T(e)&&T(t);if(!r&&!(E(e)&&E(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:ee.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=te(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function ne(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function T(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function E(e){if(!re(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!re(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function re(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{d.setTimeout(t,e)})}function ae(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:te(e,t)}function D(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function O(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var oe=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===oe?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var k=(()=>{let e=()=>p;return{isServer(){return e()},setIsServer(t){e=t}}})();function A(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var ue=f;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var j=de(),fe=new class extends c{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function pe(e){return Math.min(1e3*2**e,3e4)}function me(e){return(e??`online`)===`online`?fe.isOnline():!0}var he=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function ge(e){let t=!1,n=0,r,i=A(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new he(t);p(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},u=()=>l.isFocused()&&(e.networkMode===`always`||fe.isOnline())&&e.canRun(),d=()=>me(e.networkMode)&&e.canRun(),f=e=>{a()||(r?.(),i.resolve(e))},p=e=>{a()||(r?.(),i.reject(e))},m=()=>new Promise(t=>{r=e=>{(a()||u())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),h=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(f).catch(r=>{if(a())return;let i=e.retry??(k.isServer()?0:3),o=e.retryDelay??pe,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){p(r);return}n++,e.onFail?.(n,r),ie(s).then(()=>u()?void 0:m()).then(()=>{t?p(r):h()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:d,start:()=>(d()?h():m().then(h),i)}}var _e=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g(this.gcTime)&&(this.#e=d.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(k.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(d.clearTimeout(this.#e),this.#e=void 0)}};function ve(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?O:D;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?be:ye,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ye(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function ye(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function be(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var xe=class extends _e{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=we(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=we(this.options);e.data!==void 0&&(this.setState(Ce(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ae(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(m).catch(m):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===oe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>v(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!_(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ve(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=ge({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof he&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof he){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Se(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Ce(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),j.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Se(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:me(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Ce(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function we(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Te=class extends c{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=A(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),De(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Oe(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Oe(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof y(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!ne(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ke(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||v(this.options.staleTime,this.#t)!==v(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||y(this.options.enabled,this.#t)!==y(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return je(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(m)),t}#g(){this.#b();let e=v(this.options.staleTime,this.#t);if(k.isServer()||this.#r.isStale||!g(e))return;let t=_(this.#r.dataUpdatedAt,e)+1;this.#d=d.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(k.isServer()||y(this.options.enabled,this.#t)===!1||!g(this.#p)||this.#p===0)&&(this.#f=d.setInterval(()=>{(this.options.refetchIntervalInBackground||l.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(d.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(d.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&De(e,t),o=i&&ke(e,n,t,r);(a||o)&&(l={...l,...Se(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=ae(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=ae(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,b=_&&g,x=d!==void 0,S={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:b,isLoading:b,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&x,isStale:Ae(e,t),refetch:this.refetch,promise:this.#o,isEnabled:y(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=S.data!==void 0,r=S.status===`error`&&!t,i=e=>{r?e.reject(S.error):t&&e.resolve(S.data)},a=()=>{i(this.#o=S.promise=A())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||S.data!==o.value)&&a();break;case`rejected`:(!r||S.error!==o.reason)&&a();break}}return S}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!ne(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){j.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Ee(e,t){return y(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&y(t.retryOnMount,e)===!1)}function De(e,t){return Ee(e,t)||e.state.data!==void 0&&Oe(e,t,t.refetchOnMount)}function Oe(e,t,n){if(y(t.enabled,e)!==!1&&v(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Ae(e,t)}return!1}function ke(e,t,n,r){return(e!==t||y(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ae(e,n)}function Ae(e,t){return y(t.enabled,e)!==!1&&e.isStaleByTime(v(t.staleTime,e))}function je(e,t){return!ne(e.getCurrentResult(),t)}var Me=class extends _e{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Ne(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=ge({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),j.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Ne(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Pe=class extends c{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Me({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Fe(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Fe(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Fe(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=Fe(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>x(t,e))}findAll(e={}){return this.getAll().filter(t=>x(e,t))}notify(e){j.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return j.batch(()=>Promise.all(e.map(e=>e.continue().catch(m))))}};function Fe(e){return e.options.scope?.id}var Ie=class extends c{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),ne(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&C(t.mutationKey)!==C(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Ne();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){j.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Le=class extends c{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??S(r,t),a=this.get(i);return a||(a=new xe({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){j.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>b(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>b(e,t)):t}notify(e){j.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){j.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Re=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Le,this.#t=e.mutationCache||new Pe,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=l.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(v(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=h(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;j.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return j.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(m).catch(m)}invalidateQueries(e,t={}){return j.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=j.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(m)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(m)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(v(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(m).catch(m)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(m).catch(m)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(C(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{w(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(C(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{w(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=S(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===oe&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},ze=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},ee=Object.prototype.hasOwnProperty;function te(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function ne(e,t){return te(e.type,t,e.props)}function T(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function E(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var re=/\/+/g;function ie(e,t){return typeof e==`object`&&e&&e.key!=null?E(``+e.key):t.toString(36)}function ae(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function D(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,D(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ie(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(re,`$&/`)+`/`),D(o,r,i,``,function(e){return e})):o!=null&&(T(o)&&(o=ne(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(re,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u<e.length;u++)a=e[u],s=l+ie(a,u),c+=D(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+ie(a,u++),c+=D(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return D(ae(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function O(e,t,n){if(e==null)return e;var r=[],i=0;return D(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function oe(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var se=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},ce={map:O,forEach:function(e,t,n){O(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return O(e,function(){t++}),t},toArray:function(e){return O(e,function(e){return e})||[]},only:function(e){if(!T(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=ce,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return w.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!ee.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return te(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)ee.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return te(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=T,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:oe}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=w.T,n={};w.T=n;try{var r=e(),i=w.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(C,se)}catch(e){se(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),w.T=t}},e.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()},e.use=function(e){return w.H.use(e)},e.useActionState=function(e,t,n){return w.H.useActionState(e,t,n)},e.useCallback=function(e,t){return w.H.useCallback(e,t)},e.useContext=function(e){return w.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return w.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return w.H.useEffect(e,t)},e.useEffectEvent=function(e){return w.H.useEffectEvent(e)},e.useId=function(){return w.H.useId()},e.useImperativeHandle=function(e,t,n){return w.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return w.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return w.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return w.H.useMemo(e,t)},e.useOptimistic=function(e,t){return w.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return w.H.useReducer(e,t,n)},e.useRef=function(e){return w.H.useRef(e)},e.useState=function(e){return w.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return w.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return w.H.useTransition()},e.version=`19.2.5`})),Be=t(((e,t)=>{t.exports=ze()})),M=e(Be(),1),Ve=M.createContext(void 0),He=e=>{let t=M.useContext(Ve);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Ue=({client:e,children:t})=>(M.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,a.jsx)(Ve.Provider,{value:e,children:t})),We=M.createContext(!1),Ge=()=>M.useContext(We);We.Provider;function Ke(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var qe=M.createContext(Ke()),Je=()=>M.useContext(qe),Ye=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Xe=e=>{M.useEffect(()=>{e.clearReset()},[e])},Ze=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ce(n,[e.error,r])),Qe=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},$e=(e,t)=>e.isLoading&&e.isFetching&&!t,et=(e,t)=>e?.suspense&&t.isPending,tt=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function nt(e,t,n){let r=Ge(),i=Je(),a=He(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,Qe(o),Ye(o,i,s),Xe(i);let c=!a.getQueryCache().get(o.queryHash),[l]=M.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(M.useSyncExternalStore(M.useCallback(e=>{let t=d?l.subscribe(j.batchCalls(e)):m;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),M.useEffect(()=>{l.setOptions(o)},[o,l]),et(o,u))throw tt(o,l,i);if(Ze({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!k.isServer()&&$e(u,r)&&(c?tt(o,l,i):s?.promise)?.catch(m).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function N(e,t){return nt(e,Te,t)}function rt(e,t){let n=He(t),[r]=M.useState(()=>new Ie(n,e));M.useEffect(()=>{r.setOptions(e)},[r,e]);let i=M.useSyncExternalStore(M.useCallback(e=>r.subscribe(j.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=M.useCallback((e,t)=>{r.mutate(e,t).catch(m)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var it=new Re({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1,staleTime:5e3}}}),at={overview:`Command Center`,visual:`Codebase Map`,graph:`Entity Explorer`,ledger:`Activity Log`,facts:`Fact Store`,session:`Live Session`,"token-flow":`Token Trace`,settings:`Settings`};function ot(e){return at[e]}function st(){switch((window.location.hash.replace(/^#/,``).trim()||`/`).split(`/`).filter(Boolean)[0]?.toLowerCase()){case`visual`:return`visual`;case`graph`:return`graph`;case`ledger`:return`ledger`;case`facts`:return`facts`;case`session`:return`session`;case`token-flow`:return`token-flow`;case`settings`:return`settings`;default:return`overview`}}function ct(){let[e,t]=(0,M.useState)(()=>typeof window>`u`?`overview`:st());return(0,M.useEffect)(()=>{t(st());let e=()=>t(st());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),e}var lt=[`live-feed`],ut=[`session-snapshot`];function dt(e){try{return JSON.parse(e)}catch{return e}}function ft(e,t){let n=!1,r=null,i=1e3,a=null,o=(t,n)=>{let r={t:Date.now(),type:t,data:n};e.setQueryData(lt,(e=[])=>[...e,r].slice(-100))},s=()=>{e.invalidateQueries({queryKey:[`intelligence`]})},c=()=>{e.invalidateQueries({queryKey:[`session`]})},l=e=>t=>{o(e,dt(t.data)),e===`drift`&&s(),e===`intent`&&c(),(e===`violation`||e===`circuit_breaker`)&&c()},u=t=>{let n=dt(t.data);e.setQueryData(ut,n),e.invalidateQueries({queryKey:[`session`]})},d=()=>{},f=()=>{a!==null&&(clearTimeout(a),a=null)},p=()=>{f(),!n&&(a=setTimeout(()=>{i=Math.min(i*2,3e4),m()},i))};function m(){if(!n){r?.close();try{r=new EventSource(`/api/stream`)}catch{t(!1),p();return}r.onopen=()=>{i=1e3,t(!0)},r.onerror=()=>{t(!1),r?.close(),r=null,p()};for(let e of[`tool_call`,`drift`,`violation`,`circuit_breaker`,`intent`])r.addEventListener(e,l(e));r.addEventListener(`session_stats`,u),r.addEventListener(`ping`,d)}}return m(),()=>{n=!0,f(),r?.close(),r=null,t(!1)}}function P({className:e=``}){return(0,a.jsx)(`div`,{className:`animate-pulse rounded-md bg-surface-overlay ${e}`,"aria-hidden":`true`})}var pt=[`c0`,`c1`,`c2`,`c3`];function mt({n:e=4}){return(0,a.jsx)(`div`,{className:`grid gap-4 sm:grid-cols-2 lg:grid-cols-4`,children:pt.slice(0,Math.min(e,pt.length)).map(e=>(0,a.jsxs)(`div`,{className:`glass-card rounded-xl p-4`,children:[(0,a.jsx)(P,{className:`h-3 w-20`}),(0,a.jsx)(P,{className:`mt-3 h-8 w-14`})]},e))})}var ht=[`r0`,`r1`,`r2`,`r3`,`r4`,`r5`,`r6`,`r7`,`r8`,`r9`,`r10`,`r11`];function gt({rows:e=4}){return(0,a.jsx)(`div`,{className:`space-y-3 px-4 py-4`,children:ht.slice(0,Math.min(e,ht.length)).map(e=>(0,a.jsx)(P,{className:`h-4 w-full max-w-md`},e))})}var _t=[`h0`,`h1`,`h2`,`h3`,`h4`,`h5`],vt=[`t0`,`t1`,`t2`,`t3`,`t4`,`t5`,`t6`,`t7`];function yt({cols:e=5,rows:t=6}){let n=_t.slice(0,Math.min(e,_t.length)),r=vt.slice(0,Math.min(t,vt.length));return(0,a.jsxs)(`div`,{className:`px-5 py-4`,children:[(0,a.jsx)(`div`,{className:`mb-3 flex gap-2 border-b border-border-subtle pb-2`,children:n.map(e=>(0,a.jsx)(P,{className:`h-3 flex-1`},e))}),r.map(e=>(0,a.jsx)(`div`,{className:`mb-2 flex gap-2`,children:n.map(t=>(0,a.jsx)(P,{className:`h-4 flex-1`},`${e}-${t}`))},e))]})}var bt=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};async function F(e,t){let n=await fetch(e,{...t,headers:{Accept:`application/json`,...t?.headers}}),r=await n.text(),i;try{i=r?JSON.parse(r):null}catch{i=r}if(!n.ok)throw new bt(typeof i==`object`&&i&&`error`in i?String(i.error):n.statusText,n.status);return i}function xt({label:e,value:t,hint:n,color:r=`text-live`}){return(0,a.jsxs)(`div`,{className:`glass-card card-hover rounded-xl p-4`,children:[(0,a.jsx)(`div`,{className:`section-label`,children:e}),(0,a.jsx)(`div`,{className:`mt-2 font-mono font-semibold text-2xl tabular-nums ${r}`,children:t}),n?(0,a.jsx)(`div`,{className:`mt-1 t-tertiary text-xs leading-snug`,children:n}):null]})}function St(e){try{let t=JSON.stringify(e);return t.length>320?`${t.slice(0,317)}…`:t}catch{return String(e)}}function Ct({sseConnected:e,liveFeed:t,sessionSnapshot:n}){let r=N({queryKey:[`intelligence`,`graph-stats`],queryFn:()=>F(`/api/intelligence/graph-stats`)}),i=N({queryKey:[`session`,`stats`],queryFn:()=>F(`/api/session/stats`)}),o=N({queryKey:[`system`,`status`],queryFn:()=>F(`/api/system/status`)}),s=r.data?.data,c=r.error||r.data?._meta.graph===`unavailable`||s===null,l=i.data?.data,u=n,d=u?.tool_calls??l?.tool_calls??o.data?.data.session.tool_calls,f=u?.tokens_saved??l?.estimated_tokens_saved??o.data?.data.session.tokens_saved,p=u?.violations_caught??l?.violations_caught??0,m=u?.caught_total??l?.caught_events?.total,h=r.isLoading&&r.data===void 0,g=i.isLoading&&u===void 0&&l===void 0;return(0,a.jsxs)(`div`,{className:`mx-auto flex max-w-6xl flex-col gap-8`,children:[h?(0,a.jsx)(mt,{n:4}):(0,a.jsxs)(`section`,{className:`grid gap-4 sm:grid-cols-2 lg:grid-cols-4`,children:[(0,a.jsx)(xt,{label:`Entities`,value:c?`—`:s?.entityCount??o.data?.data.graph.entities??`—`,hint:c?`Graph unavailable (PARSE mode or no snapshot).`:void 0}),(0,a.jsx)(xt,{label:`Edges`,value:c?`—`:s?.edgeCount??o.data?.data.graph.edges??`—`}),(0,a.jsx)(xt,{label:`Rules`,value:c?`—`:s?.ruleCount??o.data?.data.graph.rules??`—`}),(0,a.jsx)(xt,{label:`Drift overlay`,value:c?`—`:s?.driftCount??`—`,color:`text-warning`})]}),(0,a.jsxs)(`section`,{className:`grid gap-4 lg:grid-cols-2`,children:[(0,a.jsxs)(`div`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Session value`}),(0,a.jsxs)(`dl`,{className:`mt-4 grid grid-cols-2 gap-4 text-sm`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Local tool calls`}),(0,a.jsx)(`dd`,{className:`mt-1 font-mono text-live text-xl tabular-nums`,children:g?(0,a.jsx)(P,{className:`inline-block h-7 w-16`}):d??`—`})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Tokens saved (est.)`}),(0,a.jsx)(`dd`,{className:`mt-1 font-mono text-live text-xl tabular-nums`,children:g?(0,a.jsx)(P,{className:`inline-block h-7 w-20`}):f??`—`})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Violations caught`}),(0,a.jsx)(`dd`,{className:`mt-1 font-mono text-warning text-xl tabular-nums`,children:g?(0,a.jsx)(P,{className:`inline-block h-7 w-12`}):p??`—`})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Caught events`}),(0,a.jsx)(`dd`,{className:`mt-1 font-mono text-success text-xl tabular-nums`,children:g?(0,a.jsx)(P,{className:`inline-block h-7 w-12`}):m??`—`})]})]}),(0,a.jsxs)(`div`,{className:`mt-4 flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`inline-flex h-1.5 w-1.5 rounded-full ${e?`bg-success`:`bg-warning animate-pulse`}`}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[`SSE `,e?`connected`:`reconnecting`]})]})]}),(0,a.jsxs)(`div`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Proxy`}),o.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,a.jsx)(P,{className:`h-4 w-full max-w-xs`}),(0,a.jsx)(P,{className:`h-4 w-full max-w-sm`}),(0,a.jsx)(P,{className:`h-4 w-3/4 max-w-md`})]}):o.error?(0,a.jsx)(`p`,{className:`mt-3 text-error text-sm`,children:`Could not load /api/system/status`}):(0,a.jsxs)(`dl`,{className:`mt-4 space-y-3 text-sm`,children:[(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Dashboard port`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:o.data?.data.dashboard_port})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`IDE`}),(0,a.jsx)(`dd`,{className:`truncate font-mono text-xs text-foreground`,children:o.data?.data.ide})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Working directory`}),(0,a.jsx)(`dd`,{className:`max-w-[14rem] truncate font-mono text-xs text-foreground`,title:o.data?.data.cwd,children:o.data?.data.cwd})]})]})]})]}),(0,a.jsxs)(`section`,{className:`glass-panel overflow-hidden rounded-xl`,children:[(0,a.jsxs)(`div`,{className:`border-b border-border-subtle px-5 py-3`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Live feed`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:`Stream: tool_call · drift · violation · circuit_breaker · intent · session_stats`})]}),(0,a.jsx)(`div`,{className:`custom-scrollbar max-h-[28rem] overflow-auto font-mono text-xs leading-relaxed`,children:(t?.length??0)===0?(0,a.jsx)(`div`,{className:`px-5 py-8 t-tertiary`,children:`Waiting for events… Use the MCP proxy or edit files to populate the graph and drift layers.`}):(0,a.jsx)(`ul`,{className:`divide-y divide-border-subtle`,children:t?.map((e,t)=>(0,a.jsxs)(`li`,{className:`px-5 py-2.5`,children:[(0,a.jsx)(`span`,{className:`t-tertiary`,children:new Date(e.t).toLocaleTimeString()}),` `,(0,a.jsx)(`span`,{className:`text-violet-500 font-medium`,children:e.type}),(0,a.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap break-words t-secondary`,children:St(e.data)})]},`${e.t}-${t}`))})})]}),(r.error||i.error)&&(0,a.jsx)(`p`,{className:`text-error text-sm`,children:"Some REST requests failed. Run the MCP proxy (`unerr`) and align UNERR_DASHBOARD_PORT with the listening dashboard port."})]})}function wt(){let[e,t]=(0,M.useState)(``),[n,r]=(0,M.useState)(``),[i,o]=(0,M.useState)(null);(0,M.useEffect)(()=>{let t=setTimeout(()=>r(e.trim()),300);return()=>clearTimeout(t)},[e]);let s=N({queryKey:[`intelligence`,`search`,n],queryFn:()=>F(`/api/intelligence/search?q=${encodeURIComponent(n)}&limit=30`),enabled:n.length>=2}),c=N({queryKey:[`intelligence`,`top-entities`,25],queryFn:()=>F(`/api/intelligence/top-entities?limit=25`)}),l=N({queryKey:[`intelligence`,`entity`,i],queryFn:()=>F(`/api/intelligence/entity/${encodeURIComponent(i??``)}`),enabled:!!i}),u=N({queryKey:[`intelligence`,`test-coverage`,i],queryFn:()=>F(`/api/intelligence/test-coverage/${encodeURIComponent(i??``)}`),enabled:!!i}),d=s.data?.data??[],f=c.data?.data??[],p=l.data?.data,m=u.data?.data??[];return(0,a.jsxs)(`div`,{className:`flex flex-col gap-6 lg:flex-row`,children:[(0,a.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`label`,{htmlFor:`entity-search`,className:`mb-2 block section-label`,children:`Entity search`}),(0,a.jsx)(`input`,{id:`entity-search`,type:`search`,value:e,onChange:e=>t(e.target.value),placeholder:`Type at least 2 characters…`,className:`w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm text-foreground outline-none ring-violet-500 transition-shadow placeholder:t-tertiary focus:ring-2 focus:border-violet-500`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:`Local BM25-style search over indexed symbols.`})]}),(0,a.jsxs)(`section`,{className:`glass-panel overflow-hidden rounded-xl`,children:[(0,a.jsx)(`div`,{className:`border-b border-border-subtle px-4 py-2.5`,children:(0,a.jsx)(`span`,{className:`section-label text-violet-500`,children:`Results`})}),(0,a.jsx)(`div`,{className:`custom-scrollbar max-h-64 overflow-auto`,children:n.length<2?(0,a.jsx)(`p`,{className:`px-4 py-6 t-secondary text-sm`,children:`Enter a query to search.`}):s.isLoading?(0,a.jsx)(gt,{rows:5}):s.isError?(0,a.jsx)(`p`,{className:`px-4 py-6 text-error text-sm`,children:`Search unavailable (graph not loaded or proxy down).`}):d.length===0?(0,a.jsx)(`p`,{className:`px-4 py-6 t-secondary text-sm`,children:`No matches.`}):(0,a.jsx)(`ul`,{className:`divide-y divide-border-subtle`,children:d.map(e=>(0,a.jsx)(`li`,{children:(0,a.jsxs)(`button`,{type:`button`,onClick:()=>o(e.key),className:`w-full px-4 py-2.5 text-left text-sm transition-colors hover:el-raised ${i===e.key?`el-raised`:``}`,children:[(0,a.jsx)(`div`,{className:`font-mono text-live text-xs`,children:e.name}),(0,a.jsxs)(`div`,{className:`t-tertiary text-xs`,children:[e.kind,` · `,e.file_path,` · score `,e.score.toFixed(2)]})]})},e.key))})})]}),(0,a.jsxs)(`section`,{className:`glass-panel overflow-hidden rounded-xl`,children:[(0,a.jsx)(`div`,{className:`border-b border-border-subtle px-4 py-2.5`,children:(0,a.jsx)(`span`,{className:`section-label text-violet-500`,children:`God nodes (highest degree)`})}),(0,a.jsx)(`div`,{className:`custom-scrollbar max-h-72 overflow-auto`,children:c.isLoading?(0,a.jsx)(yt,{cols:4,rows:8}):c.isError?(0,a.jsx)(`p`,{className:`px-4 py-6 text-error text-sm`,children:`Unavailable.`}):f.length===0?(0,a.jsx)(`p`,{className:`px-4 py-6 t-secondary text-sm`,children:`No entities indexed yet.`}):(0,a.jsx)(`ul`,{className:`divide-y divide-border-subtle`,children:f.map(e=>(0,a.jsx)(`li`,{children:(0,a.jsxs)(`button`,{type:`button`,onClick:()=>o(e.key),className:`w-full px-4 py-2.5 text-left text-sm transition-colors hover:el-raised ${i===e.key?`el-raised`:``}`,children:[(0,a.jsx)(`div`,{className:`font-mono text-live text-xs`,children:e.name}),(0,a.jsxs)(`div`,{className:`t-tertiary text-xs`,children:[`deg `,e.degree,` · in `,e.fan_in,` / out `,e.fan_out,` ·`,` `,e.risk_level]}),(0,a.jsx)(`div`,{className:`truncate t-tertiary text-xs`,children:e.file_path})]})},e.key))})})]})]}),(0,a.jsx)(`aside`,{className:`w-full shrink-0 lg:max-w-xl lg:basis-[42%]`,children:(0,a.jsxs)(`div`,{className:`sticky top-0 glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Entity detail`}),i?l.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(gt,{rows:8})}):l.isError||!p?(0,a.jsx)(`p`,{className:`mt-3 text-error text-sm`,children:`Could not load entity.`}):(0,a.jsxs)(`div`,{className:`mt-4 space-y-4 text-sm`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`font-mono text-live text-xs font-medium`,children:p.entity.name}),(0,a.jsxs)(`div`,{className:`t-tertiary text-xs`,children:[p.entity.kind,` · `,p.entity.file_path,`:`,p.entity.start_line]}),(0,a.jsxs)(`div`,{className:`mt-1.5 text-xs text-foreground`,children:[`fan_in`,` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:p.entity.fan_in}),` · `,`fan_out`,` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:p.entity.fan_out}),` · `,(0,a.jsx)(`span`,{className:`text-warning`,children:p.entity.risk_level})]})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`section-label mb-1.5`,children:[`Production callers`,(0,a.jsxs)(`span`,{className:`ml-1.5 text-xs font-normal t-tertiary`,children:[`(`,p.production_callers.length,`)`]})]}),(0,a.jsx)(`ul`,{className:`custom-scrollbar max-h-28 space-y-1 overflow-auto font-mono text-xs`,children:p.production_callers.length===0?(0,a.jsx)(`li`,{className:`t-tertiary`,children:`—`}):p.production_callers.map(e=>(0,a.jsxs)(`li`,{children:[(0,a.jsx)(`button`,{type:`button`,className:`text-left text-live hover:underline`,onClick:()=>o(e.key),children:e.name}),(0,a.jsxs)(`span`,{className:`t-tertiary`,children:[` · `,e.file_path]})]},e.key))})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`section-label mb-1.5`,children:[`Test callers`,(0,a.jsxs)(`span`,{className:`ml-1.5 text-xs font-normal t-tertiary`,children:[`(`,p.test_callers.length,`)`]})]}),(0,a.jsx)(`ul`,{className:`custom-scrollbar max-h-28 space-y-1 overflow-auto font-mono text-xs`,children:p.test_callers.length===0?(0,a.jsx)(`li`,{className:`t-tertiary`,children:`—`}):p.test_callers.map(e=>(0,a.jsxs)(`li`,{children:[(0,a.jsx)(`button`,{type:`button`,className:`text-left text-emerald-400 hover:underline`,onClick:()=>o(e.key),children:e.name}),(0,a.jsxs)(`span`,{className:`t-tertiary`,children:[` · `,e.file_path]})]},e.key))})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`section-label mb-1.5`,children:[`Test coverage`,(0,a.jsxs)(`span`,{className:`ml-1.5 text-xs font-normal t-tertiary`,children:[`(`,m.length,` test`,m.length===1?``:`s`,`)`]})]}),u.isLoading?(0,a.jsx)(gt,{rows:3}):m.length===0?(0,a.jsx)(`p`,{className:`t-tertiary text-xs font-mono`,children:`— no tests cover this entity`}):(0,a.jsx)(`ul`,{className:`custom-scrollbar max-h-28 space-y-1 overflow-auto font-mono text-xs`,children:m.map(e=>(0,a.jsxs)(`li`,{children:[(0,a.jsx)(`button`,{type:`button`,className:`text-left text-emerald-400 hover:underline`,onClick:()=>o(e.test_key),children:e.test_name}),(0,a.jsxs)(`span`,{className:`t-tertiary`,children:[` · `,e.relation===`transitive`?`depth ${e.depth}`:`direct`,` · `,e.test_file]})]},e.test_key))})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`section-label mb-1.5`,children:`Callees`}),(0,a.jsx)(`ul`,{className:`custom-scrollbar max-h-28 space-y-1 overflow-auto font-mono text-xs`,children:p.callees.length===0?(0,a.jsx)(`li`,{className:`t-tertiary`,children:`—`}):p.callees.map(e=>(0,a.jsxs)(`li`,{children:[(0,a.jsx)(`button`,{type:`button`,className:`text-left text-live hover:underline`,onClick:()=>o(e.key),children:e.name}),(0,a.jsxs)(`span`,{className:`t-tertiary`,children:[` · `,e.file_path]})]},e.key))})]}),(0,a.jsx)(`pre`,{className:`custom-scrollbar max-h-64 overflow-auto whitespace-pre-wrap rounded-lg el-substrate border border-border-subtle p-3 font-mono text-xs leading-relaxed t-secondary`,children:p.entity.body_truncated?`${p.entity.body}\n\n(body truncated)`:p.entity.body})]}):(0,a.jsx)(`p`,{className:`mt-3 t-secondary text-sm`,children:`Select a search hit or critical node to load callers, callees, and body.`})]})})]})}var Tt=[271,195,140,25,320,50,170,240,0,90,210,300,60,150,30,280];function Et(e){return`hsl(${Tt[e%Tt.length]}, ${e%3==0?70:e%3==1?85:60}%, 62%)`}function Dt(e){return`hsl(${Tt[e%Tt.length]}, ${e%3==0?70:e%3==1?85:60}%, 42%)`}function Ot(e){return`hsl(${Tt[e%Tt.length]}, 60%, 20%)`}var kt=`hsl(160, 40%, 45%)`,At=`hsl(160, 40%, 30%)`,jt={fetching:`Fetching graph data…`,building:`Building graph layout…`,done:``},Mt=`cluster:filecommunity:`,Nt=`cluster:file:`;function Pt(e){return`${Mt}${e}`}function Ft(e){return`${Nt}${e}`}function It(e){return Number.parseInt(e.replace(Mt,``),10)}function Lt(e){return e.replace(Nt,``)}function Rt(e){return e.split(`/`).pop()??e}var zt=`unerr:graph-positions`;function Bt(){try{let e=localStorage.getItem(zt);return e?JSON.parse(e):null}catch{return null}}function Vt(e){try{localStorage.setItem(zt,JSON.stringify(e))}catch{}}var Ht=100;function Ut(e,t){let n=e.filter(e=>t.has(e.from)&&t.has(e.to));if(n.length<=Ht)return n;let r={calls:3,tests:2,imports:1};return[...n].sort((e,t)=>(r[t.type]??0)-(r[e.type]??0)).slice(0,Ht)}function Wt(){let e=(0,M.useRef)(null),t=(0,M.useRef)(null),i=(0,M.useRef)(null),o=(0,M.useRef)(null),s=(0,M.useRef)(null),[c,l]=(0,M.useState)(null),[u,d]=(0,M.useState)(null),[f,p]=(0,M.useState)([]),[m,h]=(0,M.useState)(``),[g,_]=(0,M.useState)(`L0`),[v,y]=(0,M.useState)(null),[b,x]=(0,M.useState)(null),[S,C]=(0,M.useState)([{label:`All Clusters`,level:`L0`}]),[w,ee]=(0,M.useState)(`fetching`),[te,ne]=(0,M.useState)(0),{data:T,isLoading:E,isError:re}=N({queryKey:[`intelligence`,`graph-visual`],queryFn:()=>F(`/api/intelligence/graph-visual`)});(0,M.useEffect)(()=>{T&&w===`fetching`?ee(`building`):E&&ee(`fetching`)},[T,E,w]),(0,M.useEffect)(()=>{if(!T?.data||!e.current)return;i.current&&=(i.current.destroy(),null);let{nodes:t,edges:a,fileNodes:c,fileEdges:u,fileCommunities:f,positions:m}=T.data,h=T._meta.view_mode;if(t.length===0){ee(`done`);return}let g=m&&Object.keys(m.files).length>0?m:Bt()??{communities:{},files:{},entities:{}};m&&Object.keys(m.files).length>0&&Vt(m);let v=Math.max(...t.map(e=>e.fanIn+e.fanOut),1),b=t.map(e=>{let t=e.fanIn+e.fanOut,n=e.members??0,r=8+t/v*28+(n>0?Math.min(n*2,12):0),i=e.isTest===!0,a=c.find(t=>t.filePath===e.file)?.fileCommunity??0,o=i?kt:Et(a),s=i?At:Dt(a),l=t>v*.1||n>3,u=n>0?` (${n})`:``,d=e.externalOut>0?` ↗${e.externalOut}`:``,f=g.entities[e.id];return{id:e.id,label:l?`${e.label}${u}${d}`:``,title:`${e.label}\n${e.kind}${n>0?` · ${n} members`:``}\n${e.file}\nfan_in: ${e.fanIn} fan_out: ${e.fanOut}\nrisk: ${e.risk}${e.externalOut>0?`\n↗ ${e.externalOut} cross-cluster`:``}`,size:r,shape:i?`diamond`:`dot`,color:{background:o,border:s,highlight:{background:o,border:`#fafafa`},hover:{background:o,border:`#fafafa`}},font:{color:`rgba(250, 250, 250, 0.85)`,size:Math.max(10,r*.7),face:`JetBrains Mono, monospace`},borderWidth:n>0?3:2,borderWidthSelected:3,x:f?.x,y:f?.y,filePath:e.file,fileCommunity:a,_raw:e}}),S=new Map(t.map(e=>[e.id,e])),w=Ut(a,new Set(t.map(e=>e.id))).map((e,t)=>{let n=S.get(e.from),r=c.find(e=>e.filePath===n?.file),i=r?Et(r.fileCommunity):`#8B5CF6`;return{id:`e-${t}`,from:e.from,to:e.to,title:e.type,color:{color:i,opacity:.25,highlight:i,hover:i},width:e.type===`calls`?1.5:1,smooth:{type:`continuous`,roundness:.3},arrows:{to:{enabled:!0,scaleFactor:.4}},font:{color:`rgba(250, 250, 250, 0.3)`,size:8,face:`JetBrains Mono, monospace`,strokeWidth:0}}}),te=new r(b),ne=new r(w);o.current=te,s.current=ne;let E=new n(e.current,{nodes:te,edges:ne},{physics:{enabled:!1},interaction:{hover:!0,tooltipDelay:150,zoomView:!0,dragView:!0,multiselect:!1},nodes:{shape:`dot`},edges:{selectionWidth:2}});i.current=E;function re(){for(let e of c){if(t.filter(t=>t.file===e.filePath).length===0)continue;let n=g.files[e.filePath];E.cluster({joinCondition:t=>t.filePath===e.filePath,clusterNodeProperties:{id:Ft(e.filePath),label:`${e.label}\n(${e.entityCount})`,title:`${e.filePath}\n${e.entityCount} entities\nfan_in: ${e.totalFanIn} fan_out: ${e.totalFanOut}\nrisk: ${e.maxRisk}`,shape:`box`,size:15+Math.min(e.entityCount*3,30),x:n?.x,y:n?.y,color:{background:Ot(e.fileCommunity),border:Et(e.fileCommunity),highlight:{background:Ot(e.fileCommunity),border:`#fafafa`},hover:{background:Ot(e.fileCommunity),border:`#fafafa`}},font:{color:`rgba(250, 250, 250, 0.9)`,size:11,face:`JetBrains Mono, monospace`,multi:!0},borderWidth:2,borderWidthSelected:3,fileCommunity:e.fileCommunity,_fileNode:e},clusterEdgeProperties:{color:{inherit:`both`,opacity:.35}}})}for(let e of f){let t=g.communities[e.id];E.cluster({joinCondition:t=>t.fileCommunity===e.id,clusterNodeProperties:{id:Pt(e.id),label:`${e.label}\n(${e.fileCount} files)`,title:`${e.label}\n${e.fileCount} files · ${e.entityCount} entities\nCohesion: ${Math.round(e.cohesion*100)}%`,shape:`dot`,size:25+Math.min(e.fileCount*4,45),x:t?.x,y:t?.y,color:{background:Ot(e.id),border:Et(e.id),highlight:{background:Ot(e.id),border:`#fafafa`},hover:{background:Ot(e.id),border:`#fafafa`}},font:{color:Et(e.id),size:14,face:`Space Grotesk, sans-serif`,bold:{color:`#fafafa`},multi:!0},borderWidth:e.cohesion>.5?3:2,borderWidthSelected:4,shapeProperties:{borderDashes:e.cohesion<.3?[5,5]:!1}},clusterEdgeProperties:{color:{inherit:`both`,opacity:.4},smooth:{type:`continuous`,roundness:.5}}})}}function ae(e){let n=e===void 0?c:c.filter(t=>t.fileCommunity===e);for(let r of n){if(t.filter(e=>e.file===r.filePath).length<2)continue;let n=g.files[r.filePath];E.cluster({joinCondition:t=>e!==void 0&&t.fileCommunity!==e?!1:t.filePath===r.filePath,clusterNodeProperties:{id:Ft(r.filePath),label:`${r.label}\n(${r.entityCount})`,title:`${r.filePath}\n${r.entityCount} entities`,shape:`box`,size:15+Math.min(r.entityCount*3,25),x:n?.x,y:n?.y,color:{background:Ot(r.fileCommunity),border:Et(r.fileCommunity),highlight:{background:Ot(r.fileCommunity),border:`#fafafa`},hover:{background:Ot(r.fileCommunity),border:`#fafafa`}},font:{color:`rgba(250, 250, 250, 0.9)`,size:11,face:`JetBrains Mono, monospace`,multi:!0},borderWidth:2,borderWidthSelected:3,fileCommunity:r.fileCommunity,_fileNode:r},clusterEdgeProperties:{color:{inherit:`both`,opacity:.35}}})}}h===`hierarchical`?(re(),_(`L0`),C([{label:`All Clusters`,level:`L0`}])):h===`file-clusters`?(ae(),_(`L1`),C([{label:`All Files`,level:`L1`}])):(_(`L2`),C([{label:`Flat View`,level:`L2`}])),E.setOptions({physics:{enabled:!0,solver:`forceAtlas2Based`,forceAtlas2Based:{gravitationalConstant:-60,centralGravity:.008,springLength:120,springConstant:.06,damping:.8,avoidOverlap:.3},stabilization:!1}}),E.stabilize(80),E.on(`doubleClick`,e=>{let t=e.nodes?.[0];if(t&&E.isCluster(t)){let e=String(t).startsWith(Mt),n=String(t).startsWith(Nt);if(E.openCluster(t,{releaseFunction:(e,t)=>{let n=Object.keys(t),r=n.length,i=Math.max(80,r*12),a={};return n.forEach((t,n)=>{let o=g.files[t]??g.entities[t];if(o)a[t]={x:e.x+o.x*.5,y:e.y+o.y*.5};else{let o=2*Math.PI*n/r;a[t]={x:e.x+i*Math.cos(o),y:e.y+i*Math.sin(o)}}}),a}}),E.setOptions({physics:{enabled:!0,solver:`forceAtlas2Based`,forceAtlas2Based:{damping:.85,gravitationalConstant:-40},stabilization:{enabled:!1}}}),setTimeout(()=>{E.setOptions({physics:{enabled:!1}})},1500),e){let e=It(t);_(`L1`),y(e),x(null),C([{label:`All Clusters`,level:`L0`},{label:f.find(t=>t.id===e)?.label||`Cluster ${e}`,level:`L1`,communityId:e}])}else if(n){let e=Lt(t);_(`L2`),x(e),C(t=>[...t.slice(0,t.length>1?2:1),{label:Rt(e),level:`L2`,file:e}])}setTimeout(()=>{E.fit({animation:{duration:600,easingFunction:`easeInOutQuad`}})},200)}}),E.on(`selectNode`,e=>{let n=e.nodes[0];if(E.isCluster(n)){if(String(n).startsWith(Nt)){let e=Lt(n),t=c.find(t=>t.filePath===e);t&&(d(t),l(null))}return}let r=t.find(e=>e.id===n);if(r){l(r),d(null);let e=a.filter(e=>e.from===n||e.to===n),i=new Set(e.map(e=>e.from===n?e.to:e.from));p(t.filter(e=>i.has(e.id)).slice(0,20))}}),E.on(`deselectNode`,()=>{l(null),d(null),p([])});let D=!1,O=()=>{D||(D=!0,E.setOptions({physics:{enabled:!1}}),ee(`done`),ie())};E.on(`stabilizationIterationsDone`,O);let oe=setTimeout(O,3e3);return E.on(`zoom`,()=>ie()),E.on(`dragEnd`,()=>ie()),ee(`building`),()=>{clearTimeout(oe),E.destroy(),i.current=null,o.current=null,s.current=null}},[T,te]);let ie=(0,M.useCallback)(()=>{let n=t.current,r=i.current;if(!n||!r)return;let a=n.getContext(`2d`);if(!a)return;let o=n.width,s=n.height;a.clearRect(0,0,o,s);let c=r.getPositions(),l=Object.values(c);if(l.length===0)return;let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let e of l)e.x<u&&(u=e.x),e.x>d&&(d=e.x),e.y<f&&(f=e.y),e.y>p&&(p=e.y);let m=d-u||1,h=p-f||1;a.fillStyle=`rgba(139, 92, 246, 0.5)`;for(let e of l){let t=10+(e.x-u)/m*(o-20),n=10+(e.y-f)/h*(s-20);a.beginPath(),a.arc(t,n,1.5,0,Math.PI*2),a.fill()}try{let t=r.getViewPosition(),n=r.getScale(),i=e.current;if(i&&t){let e=i.clientWidth/n,r=i.clientHeight/n,c=10+(t.x-e/2-u)/m*(o-20),l=10+(t.y-r/2-f)/h*(s-20),d=e/m*(o-20),p=r/h*(s-20);a.strokeStyle=`rgba(250, 250, 250, 0.6)`,a.lineWidth=1,a.strokeRect(c,l,d,p)}}catch{}},[]),ae=(0,M.useCallback)(e=>{if(!i.current||!T?.data)return;let{fileCommunities:t,fileNodes:n,nodes:r}=T.data;e.level===`L0`?(_(`L0`),y(null),x(null),C([{label:`All Clusters`,level:`L0`}])):e.level===`L1`&&e.communityId!=null&&(_(`L1`),y(e.communityId),x(null),C([{label:`All Clusters`,level:`L0`},{label:e.label,level:`L1`,communityId:e.communityId}])),ee(`building`),ne(e=>e+1)},[T]);(0,M.useEffect)(()=>{function e(e){if(e.key===`Escape`&&S.length>1){let e=S[S.length-2];ae(e)}}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[S,ae]);let D=(0,M.useCallback)(e=>{if(h(e),!i.current||!T?.data||e.length<2)return;let t=e.toLowerCase(),n=T.data.nodes.find(e=>e.label.toLowerCase().includes(t)),r=T.data.fileNodes.find(e=>e.label.toLowerCase().includes(t)||e.filePath.toLowerCase().includes(t)),a=n?.id??(r?Ft(r.filePath):null);if(a&&i.current){let e=i.current.findNode(a);if(e&&e.length>1)for(let t=0;t<e.length-1;t++){let n=e[t];i.current.isCluster(n)&&i.current.openCluster(n)}i.current.selectNodes([a]),i.current.focus(a,{scale:1.5,animation:{duration:600,easingFunction:`easeInOutQuad`}}),n?(l(n),d(null)):r&&(d(r),l(null))}},[T]),O=(0,M.useCallback)(()=>{if(!e.current)return;let t=e.current.querySelector(`canvas`);if(!t)return;let n=document.createElement(`canvas`);n.width=t.width,n.height=t.height;let r=n.getContext(`2d`);if(!r)return;r.drawImage(t,0,0);let i=document.createElement(`a`);i.download=`unerr-codebase-map.png`,i.href=n.toDataURL(`image/png`),i.click()},[]),oe=T?.data?.nodes.length??0;T?.data?.edges.length;let se=T?._meta,ce=se?.file_count??0,le=se?.file_edge_count??0,k=se?.collapsed_count??0,A=se?.total_entities??0,ue=T?.data?.fileCommunities??[],de=se?.view_mode??`flat`,j=w!==`done`&&!re;return(0,a.jsxs)(`div`,{className:`flex h-[calc(100vh-73px)] flex-col gap-0 overflow-hidden lg:flex-row`,children:[(0,a.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,a.jsxs)(`div`,{className:`flex items-center gap-3 border-b border-border-subtle bg-surface/80 px-4 py-2 backdrop-blur`,children:[(0,a.jsx)(`nav`,{className:`flex items-center gap-1 text-xs`,children:S.map((e,t)=>(0,a.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,a.jsx)(`span`,{className:`t-ghost`,children:`›`}),t<S.length-1?(0,a.jsx)(`button`,{type:`button`,onClick:()=>ae(e),className:`rounded px-1.5 py-0.5 text-violet-400 transition hover:bg-violet-500/10 hover:text-violet-300`,children:e.label}):(0,a.jsx)(`span`,{className:`px-1.5 py-0.5 text-foreground font-medium`,children:e.label})]},`${e.level}-${e.communityId??e.file??`root`}`))}),(0,a.jsx)(`div`,{className:`mx-2 h-4 w-px bg-border-subtle`}),(0,a.jsx)(`input`,{type:`search`,value:m,onChange:e=>D(e.target.value),placeholder:`Search files & entities...`,className:`w-48 rounded-lg border border-border bg-background px-3 py-1.5 font-mono text-sm text-foreground outline-none ring-violet-500 placeholder:t-tertiary focus:ring-2 focus:border-violet-500`}),(0,a.jsx)(`div`,{className:`flex-1`}),(0,a.jsxs)(`span`,{className:`font-mono text-xs t-tertiary`,children:[ce,` files · `,oe,` entities`,de!==`flat`&&(0,a.jsx)(`span`,{className:`ml-2 rounded bg-violet-500/10 px-1.5 py-0.5 text-violet-400`,children:g===`L0`?`Clusters`:g===`L1`?`Files`:`Entities`})]}),S.length>1&&(0,a.jsx)(`button`,{type:`button`,onClick:()=>ae(S[S.length-2]),className:`rounded-lg border border-border-subtle el-raised px-3 py-1.5 text-xs font-medium text-foreground transition hover:el-overlay hover:border-violet-500`,title:`Zoom out (Esc)`,children:`↑ Up`}),(0,a.jsx)(`button`,{type:`button`,onClick:O,className:`rounded-lg border border-border-subtle el-raised px-3 py-1.5 text-xs font-medium text-foreground transition hover:el-overlay hover:border-violet-500`,children:`Export PNG`}),(0,a.jsx)(`button`,{type:`button`,onClick:()=>i.current?.fit({animation:!0}),className:`rounded-lg border border-border-subtle el-raised px-3 py-1.5 text-xs font-medium text-foreground transition hover:el-overlay hover:border-violet-500`,children:`Fit`})]}),(0,a.jsxs)(`div`,{className:`relative flex-1 bg-background`,children:[j&&(0,a.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center pointer-events-none`,children:(0,a.jsxs)(`div`,{className:`flex flex-col items-center gap-4 rounded-xl border border-border-subtle bg-surface-default/95 px-10 py-8 shadow-2xl backdrop-blur-sm`,children:[(0,a.jsxs)(`svg`,{className:`h-12 w-12 animate-spin`,viewBox:`0 0 48 48`,fill:`none`,children:[(0,a.jsx)(`circle`,{cx:`24`,cy:`24`,r:`20`,stroke:`rgba(255,255,255,0.06)`,strokeWidth:`5`}),(0,a.jsx)(`path`,{d:`M24 4 A20 20 0 0 1 41.32 34`,stroke:`#8B5CF6`,strokeWidth:`5`,strokeLinecap:`round`}),(0,a.jsx)(`path`,{d:`M41.32 34 A20 20 0 0 1 14 40.64`,stroke:`#22D3EE`,strokeWidth:`5`,strokeLinecap:`round`}),(0,a.jsx)(`path`,{d:`M14 40.64 A20 20 0 0 1 6.06 17.1`,stroke:`#34D399`,strokeWidth:`5`,strokeLinecap:`round`})]}),(0,a.jsx)(`p`,{className:`font-mono text-sm text-foreground font-medium`,children:jt[w]}),oe>0&&(0,a.jsxs)(`p`,{className:`font-mono text-[11px] t-tertiary`,children:[ce,` files · `,oe,` entities`]})]})}),re&&(0,a.jsx)(`div`,{className:`absolute inset-0 z-20 flex items-center justify-center`,children:(0,a.jsxs)(`div`,{className:`glass-panel rounded-xl p-8 text-center`,children:[(0,a.jsx)(`p`,{className:`text-error text-sm font-medium`,children:`Graph unavailable`}),(0,a.jsxs)(`p`,{className:`mt-2 t-secondary text-xs`,children:[`Intelligence graph not loaded. Run`,` `,(0,a.jsx)(`code`,{className:`rounded el-substrate px-1.5 py-0.5 font-mono`,children:`unerr`}),` `,`in your project to index.`]})]})}),!E&&!re&&oe===0&&(0,a.jsx)(`div`,{className:`absolute inset-0 z-20 flex items-center justify-center`,children:(0,a.jsxs)(`div`,{className:`glass-panel rounded-xl p-8 text-center`,children:[(0,a.jsx)(`p`,{className:`text-foreground text-sm font-medium`,children:`No entities found`}),(0,a.jsx)(`p`,{className:`mt-2 t-secondary text-xs`,children:`The graph will appear once the project is indexed.`})]})}),(0,a.jsx)(`div`,{ref:e,className:`absolute inset-0`,style:{opacity:w===`done`?1:w===`building`?.4:.2,transition:`opacity 0.8s ease`}}),w===`done`&&(0,a.jsx)(`div`,{className:`absolute bottom-4 left-4 rounded-lg border border-border-subtle bg-surface-default/90 p-1 backdrop-blur-sm`,children:(0,a.jsx)(`canvas`,{ref:t,width:160,height:100,className:`rounded`,style:{background:`rgba(0,0,0,0.3)`}})}),w===`done`&&g===`L0`&&de===`hierarchical`&&(0,a.jsx)(`div`,{className:`pointer-events-none absolute bottom-4 right-4 rounded-lg border border-border-subtle bg-surface-default/90 px-3 py-2 backdrop-blur-sm`,children:(0,a.jsx)(`p`,{className:`font-mono text-[10px] t-secondary`,children:`Double-click a cluster to explore its files`})})]})]}),(0,a.jsx)(`aside`,{className:`w-full shrink-0 overflow-y-auto border-t border-border-subtle glass-panel lg:w-80 lg:border-t-0 lg:border-l`,children:(0,a.jsxs)(`div`,{className:`p-4`,children:[c?(0,a.jsxs)(`div`,{className:`space-y-4`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label text-violet-500`,children:`Selected entity`}),(0,a.jsxs)(`div`,{className:`mt-2 rounded-lg el-raised p-3`,children:[(0,a.jsx)(`div`,{className:`font-mono text-live text-sm font-medium`,children:c.label}),(0,a.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 flex-wrap`,children:[(0,a.jsx)(`span`,{className:`t-tertiary text-xs`,children:c.kind}),(c.members??0)>0&&(0,a.jsxs)(`span`,{className:`rounded bg-violet-500/15 px-1.5 py-0.5 font-mono text-[10px] font-medium text-violet-400`,children:[c.members,` members`]}),c.isTest&&(0,a.jsx)(`span`,{className:`rounded bg-emerald-500/15 px-1.5 py-0.5 font-mono text-[10px] font-medium text-emerald-400`,children:`test`})]}),(0,a.jsx)(`div`,{className:`mt-1 truncate t-tertiary text-xs`,children:c.file}),(0,a.jsxs)(`div`,{className:`mt-2 flex gap-3 text-xs`,children:[(0,a.jsxs)(`span`,{children:[(0,a.jsx)(`span`,{className:`t-secondary`,children:`in`}),` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:c.fanIn})]}),(0,a.jsxs)(`span`,{children:[(0,a.jsx)(`span`,{className:`t-secondary`,children:`out`}),` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:c.fanOut})]}),(0,a.jsx)(`span`,{className:`rounded px-1.5 py-0.5 font-mono text-[10px] font-medium ${c.risk===`critical`?`bg-error/15 text-error`:c.risk===`high`?`bg-warning/15 text-warning`:c.risk===`medium`?`bg-violet-500/15 text-violet-500`:`bg-success/15 text-success`}`,children:c.risk})]})]})]}),(c.externalOut>0||c.externalIn>0)&&(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label t-secondary`,children:`Cross-cluster`}),(0,a.jsxs)(`div`,{className:`mt-2 flex gap-4 text-xs`,children:[c.externalOut>0&&(0,a.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,a.jsx)(`span`,{className:`text-warning`,children:`↗`}),(0,a.jsx)(`span`,{className:`font-mono text-live`,children:c.externalOut}),(0,a.jsx)(`span`,{className:`t-tertiary`,children:`outbound`})]}),c.externalIn>0&&(0,a.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,a.jsx)(`span`,{className:`text-info`,children:`↙`}),(0,a.jsx)(`span`,{className:`font-mono text-live`,children:c.externalIn}),(0,a.jsx)(`span`,{className:`t-tertiary`,children:`inbound`})]})]})]}),v!=null&&(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label t-secondary`,children:`Location`}),(0,a.jsxs)(`div`,{className:`mt-2 text-xs`,children:[(0,a.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`inline-block h-2 w-2 rounded-full`,style:{backgroundColor:Et(v)}}),(0,a.jsx)(`span`,{className:`text-foreground`,children:ue.find(e=>e.id===v)?.label||`Cluster ${v}`})]}),ue.find(e=>e.id===v)?.cohesion!=null&&(0,a.jsxs)(`div`,{className:`mt-1 t-tertiary`,children:[`Cohesion:`,` `,Math.round((ue.find(e=>e.id===v)?.cohesion??0)*100),`%`]})]})]}),f.length>0&&(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`h3`,{className:`section-label t-secondary`,children:[`Connected (`,f.length,`)`]}),(0,a.jsx)(`ul`,{className:`mt-2 max-h-48 space-y-1 overflow-auto custom-scrollbar`,children:f.map(e=>(0,a.jsx)(`li`,{children:(0,a.jsxs)(`button`,{type:`button`,onClick:()=>{i.current&&(i.current.selectNodes([e.id]),i.current.focus(e.id,{scale:1.5,animation:{duration:400,easingFunction:`easeInOutQuad`}})),l(e)},className:`w-full rounded px-2 py-1 text-left text-xs transition hover:el-raised`,children:[(0,a.jsx)(`span`,{className:`font-mono text-live`,children:e.label}),(0,a.jsxs)(`span`,{className:`t-tertiary`,children:[` `,`· `,Rt(e.file)]})]})},e.id))})]})]}):u?(0,a.jsxs)(`div`,{className:`space-y-4`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label text-violet-500`,children:`Selected file`}),(0,a.jsxs)(`div`,{className:`mt-2 rounded-lg el-raised p-3`,children:[(0,a.jsx)(`div`,{className:`font-mono text-live text-sm font-medium`,children:u.label}),(0,a.jsx)(`div`,{className:`mt-1 truncate t-tertiary text-xs`,children:u.filePath}),(0,a.jsxs)(`div`,{className:`mt-2 flex gap-3 text-xs flex-wrap`,children:[(0,a.jsxs)(`span`,{children:[(0,a.jsx)(`span`,{className:`t-secondary`,children:`entities`}),` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:u.entityCount})]}),(0,a.jsxs)(`span`,{children:[(0,a.jsx)(`span`,{className:`t-secondary`,children:`fan_in`}),` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:u.totalFanIn})]}),(0,a.jsxs)(`span`,{children:[(0,a.jsx)(`span`,{className:`t-secondary`,children:`fan_out`}),` `,(0,a.jsx)(`span`,{className:`font-mono text-live`,children:u.totalFanOut})]}),(0,a.jsx)(`span`,{className:`rounded px-1.5 py-0.5 font-mono text-[10px] font-medium ${u.maxRisk===`high`?`bg-warning/15 text-warning`:u.maxRisk===`medium`?`bg-violet-500/15 text-violet-500`:`bg-success/15 text-success`}`,children:u.maxRisk})]}),(0,a.jsx)(`div`,{className:`mt-2 flex gap-2 flex-wrap`,children:Object.entries(u.kinds).map(([e,t])=>(0,a.jsxs)(`span`,{className:`rounded bg-surface-overlay px-1.5 py-0.5 font-mono text-[10px] t-secondary`,children:[e,`: `,t]},e))})]})]}),(u.externalOut>0||u.externalIn>0)&&(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label t-secondary`,children:`Cross-cluster edges`}),(0,a.jsxs)(`div`,{className:`mt-2 flex gap-4 text-xs`,children:[u.externalOut>0&&(0,a.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,a.jsx)(`span`,{className:`text-warning`,children:`↗`}),(0,a.jsx)(`span`,{className:`font-mono text-live`,children:u.externalOut}),(0,a.jsx)(`span`,{className:`t-tertiary`,children:`outbound`})]}),u.externalIn>0&&(0,a.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,a.jsx)(`span`,{className:`text-info`,children:`↙`}),(0,a.jsx)(`span`,{className:`font-mono text-live`,children:u.externalIn}),(0,a.jsx)(`span`,{className:`t-tertiary`,children:`inbound`})]})]})]})]}):(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label text-violet-500`,children:`Inspector`}),(0,a.jsx)(`p`,{className:`mt-3 t-secondary text-xs leading-relaxed`,children:g===`L0`?`Double-click a file cluster to explore its files. Click a node for details.`:g===`L1`?`Double-click a file to see its entities. Click a node for details.`:`Click a node to inspect its connections, risk level, and dependencies.`})]}),(0,a.jsxs)(`div`,{className:`mt-6`,children:[(0,a.jsx)(`h3`,{className:`section-label t-secondary`,children:`File Clusters`}),(0,a.jsxs)(`ul`,{className:`mt-2 max-h-40 space-y-1 overflow-auto custom-scrollbar`,children:[ue.slice(0,16).map(e=>(0,a.jsxs)(`li`,{className:`flex items-center gap-2 text-xs`,children:[(0,a.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full`,style:{backgroundColor:Et(e.id)}}),(0,a.jsx)(`span`,{className:`truncate text-foreground`,children:e.label}),(0,a.jsxs)(`span`,{className:`ml-auto tabular-nums t-tertiary`,children:[e.fileCount,`f`]}),e.cohesion<.3&&(0,a.jsx)(`span`,{className:`text-warning text-[10px]`,title:`Low cohesion`,children:`!`})]},e.id)),(0,a.jsxs)(`li`,{className:`flex items-center gap-2 text-xs`,children:[(0,a.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rotate-45 rounded-sm`,style:{backgroundColor:kt}}),(0,a.jsx)(`span`,{className:`text-foreground`,children:`Test files`}),(0,a.jsx)(`span`,{className:`ml-auto t-tertiary`,children:`◇`})]})]})]}),(0,a.jsxs)(`div`,{className:`mt-6 rounded-lg border border-border-subtle el-raised p-3`,children:[(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 text-xs`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`t-secondary`,children:`Files`}),(0,a.jsx)(`div`,{className:`font-mono text-live text-lg tabular-nums`,children:ce})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`t-secondary`,children:`File edges`}),(0,a.jsx)(`div`,{className:`font-mono text-live text-lg tabular-nums`,children:le})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`t-secondary`,children:`Clusters`}),(0,a.jsx)(`div`,{className:`font-mono text-live text-lg tabular-nums`,children:ue.length})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`t-secondary`,children:`Entities`}),(0,a.jsx)(`div`,{className:`font-mono text-live text-lg tabular-nums`,children:A})]})]}),k>0&&(0,a.jsxs)(`div`,{className:`mt-2 pt-2 border-t border-border-subtle t-tertiary text-[10px]`,children:[k,` child entities (methods, types, constructors) merged into parent nodes`]}),de!==`flat`&&(0,a.jsxs)(`div`,{className:`mt-2 pt-2 border-t border-border-subtle t-tertiary text-[10px]`,children:[`View:`,` `,de===`hierarchical`?`Hierarchical (L0→L1→L2)`:`File clusters`,` `,`· Level: `,g]})]})]})})]})}var Gt=[`all`,`procedural`,`semantic`,`negative`,`convention`,`episodic`];function Kt(e){return e>=.7?`text-success`:e>=.4?`text-warning`:`text-error`}function qt(e){let t=Date.now()-e,n=Math.floor(t/6e4);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function Jt(){let e=He(),[t,n]=(0,M.useState)(`all`),r=N({queryKey:[`facts`,`health`],queryFn:()=>F(`/api/facts/health`),refetchInterval:3e4}),i=N({queryKey:[`facts`,`list`,t],queryFn:()=>{let e=new URLSearchParams({scope:`*`,min_confidence:`0`,limit:`100`});return t!==`all`&&e.set(`type`,t),F(`/api/facts?${e}`)},refetchInterval:15e3}),o=N({queryKey:[`facts`,`sessions`],queryFn:()=>F(`/api/sessions?limit=10`)}),s=rt({mutationFn:e=>F(`/api/facts/${e}/reinforce`,{method:`POST`}),onSuccess:()=>{e.invalidateQueries({queryKey:[`facts`]})}}),c=rt({mutationFn:e=>F(`/api/facts/${e}`,{method:`DELETE`}),onSuccess:()=>{e.invalidateQueries({queryKey:[`facts`]})}}),l=r.data,u=i.data?.facts??[],d=o.data?.sessions??[];return(0,a.jsxs)(`div`,{className:`flex flex-col gap-8`,children:[(0,a.jsxs)(`section`,{children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Fact store health`}),r.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(mt,{n:4})}):r.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load health.`}):l?(0,a.jsxs)(`div`,{className:`mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-4`,children:[(0,a.jsx)(Yt,{label:`Total facts`,value:l.total}),(0,a.jsx)(Yt,{label:`Active`,value:l.active,accent:`text-success`}),(0,a.jsx)(Yt,{label:`Decaying`,value:l.decayed,accent:`text-warning`}),(0,a.jsx)(Yt,{label:`Avg confidence`,value:`${(l.avg_confidence*100).toFixed(0)}%`,accent:Kt(l.avg_confidence)})]}):null]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Facts`}),(0,a.jsx)(`select`,{className:`rounded-md border border-border-subtle bg-surface-overlay px-3 py-1.5 text-xs text-foreground`,value:t,onChange:e=>n(e.target.value),children:Gt.map(e=>(0,a.jsx)(`option`,{value:e,children:e===`all`?`All types`:e},e))})]}),i.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(yt,{cols:6,rows:8})}):i.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load facts.`}):u.length===0?(0,a.jsxs)(`p`,{className:`mt-6 t-tertiary text-sm text-center py-8`,children:[`No facts recorded yet. Use `,(0,a.jsx)(`code`,{className:`font-mono text-xs`,children:`record_fact`}),` via MCP to persist project knowledge.`]}):(0,a.jsx)(`div`,{className:`mt-4 overflow-x-auto custom-scrollbar`,children:(0,a.jsxs)(`table`,{className:`w-full min-w-[800px] text-left text-sm`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Type`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Subject`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Content`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Confidence`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Source`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Age`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`Actions`})]})}),(0,a.jsx)(`tbody`,{children:u.map(e=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle`,children:[(0,a.jsx)(`td`,{className:`py-2.5 pr-3`,children:(0,a.jsx)(Zt,{type:e.fact_type})}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 font-mono text-xs max-w-[140px] truncate`,title:e.subject,children:e.subject}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 text-xs max-w-[280px] truncate`,title:e.content,children:e.content}),(0,a.jsxs)(`td`,{className:`py-2.5 pr-3 font-mono tabular-nums text-xs ${Kt(e.effective_confidence)}`,children:[(e.effective_confidence*100).toFixed(0),`%`]}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 t-secondary text-xs`,children:e.source.replace(/_/g,` `)}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 t-secondary text-xs tabular-nums`,children:qt(e.created_at)}),(0,a.jsx)(`td`,{className:`py-2.5`,children:(0,a.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,a.jsx)(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs el-substrate border border-border-subtle text-success hover:bg-success/10 transition-colors disabled:opacity-50`,onClick:()=>s.mutate(e.fact_id),disabled:s.isPending,title:`Reinforce — mark as still true`,children:`Reinforce`}),(0,a.jsx)(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs el-substrate border border-border-subtle text-error hover:bg-error/10 transition-colors disabled:opacity-50`,onClick:()=>c.mutate(e.fact_id),disabled:c.isPending,title:`Dismiss — reduce confidence`,children:`Dismiss`})]})})]},e.fact_id))})]})})]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Recent sessions`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:`MCP sessions with fact activity`}),o.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(yt,{cols:5,rows:4})}):o.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load sessions.`}):d.length===0?(0,a.jsx)(`p`,{className:`mt-4 t-tertiary text-sm text-center py-4`,children:`No sessions yet.`}):(0,a.jsx)(`div`,{className:`mt-4 overflow-x-auto custom-scrollbar`,children:(0,a.jsxs)(`table`,{className:`w-full min-w-[640px] text-left text-sm`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Session`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Branch`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Tools`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Files`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Facts`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`When`})]})}),(0,a.jsx)(`tbody`,{children:d.map(e=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle`,children:[(0,a.jsx)(`td`,{className:`py-2.5 pr-3 font-mono text-xs t-secondary`,children:e.session_id.slice(0,8)}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 text-xs`,children:e.branch}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 tabular-nums text-xs t-secondary`,children:e.tool_calls}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 tabular-nums text-xs t-secondary`,children:e.files_modified}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 tabular-nums text-xs t-secondary`,children:e.facts_recorded}),(0,a.jsx)(`td`,{className:`py-2.5 text-xs t-secondary`,children:Qt(e.ended_at)})]},e.session_id))})]})})]})]})}function Yt({label:e,value:t,accent:n}){return(0,a.jsxs)(`div`,{className:`glass-card rounded-xl p-4`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-xs font-medium uppercase`,children:e}),(0,a.jsx)(`p`,{className:`mt-2 text-2xl font-semibold tabular-nums ${n??`text-foreground`}`,children:t})]})}var Xt={procedural:`bg-cyan-500/15 text-cyan-400`,semantic:`bg-violet-500/15 text-violet-400`,negative:`bg-red-500/15 text-red-400`,convention:`bg-emerald-500/15 text-emerald-400`,episodic:`bg-amber-500/15 text-amber-400`};function Zt({type:e}){return(0,a.jsx)(`span`,{className:`inline-block rounded-full px-2 py-0.5 text-[10px] font-medium uppercase ${Xt[e]??`bg-surface-overlay text-muted-foreground`}`,children:e})}function Qt(e){let t=new Date(e),n=Date.now()-t.getTime(),r=Math.floor(n/6e4);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function $t(){let e=N({queryKey:[`intelligence`,`durability`],queryFn:()=>F(`/api/intelligence/durability?ledger_limit=800`)}),t=N({queryKey:[`intelligence`,`conventions`],queryFn:()=>F(`/api/intelligence/conventions`)}),n=N({queryKey:[`session`,`ledger`],queryFn:()=>F(`/api/session/ledger?limit=80`)}),r=e.data?.data.profiles??[],i=e.data?.data.most_fragile??[],o=t.data?.data??[],s=n.data?.data??[];return(0,a.jsxs)(`div`,{className:`flex flex-col gap-8`,children:[(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Prompt durability`}),(0,a.jsxs)(`p`,{className:`mt-1 t-tertiary text-xs`,children:[`Profiles from shadow ledger · overall`,` `,(0,a.jsx)(`span`,{className:`font-mono text-foreground`,children:e.data?.data.overall?.toFixed(3)??`—`})]}),e.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(yt,{cols:5,rows:6})}):e.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load durability.`}):(0,a.jsx)(`div`,{className:`mt-4 overflow-x-auto custom-scrollbar`,children:(0,a.jsxs)(`table`,{className:`w-full min-w-[640px] text-left text-sm`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Action`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Risk`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Scope`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`Durability`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-3 font-medium`,children:`n`})]})}),(0,a.jsx)(`tbody`,{children:r.map(e=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle`,children:[(0,a.jsx)(`td`,{className:`py-2.5 pr-3 font-mono text-xs`,children:e.actionType}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 t-secondary`,children:e.targetRisk}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 t-secondary`,children:e.scope}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 font-mono tabular-nums text-live`,children:e.durability.toFixed(2)}),(0,a.jsx)(`td`,{className:`py-2.5 pr-3 tabular-nums t-secondary`,children:e.sampleCount})]},`${e.actionType}-${e.targetRisk}-${e.scope}`))})]})}),i.length>0?(0,a.jsxs)(`div`,{className:`mt-6`,children:[(0,a.jsx)(`h3`,{className:`section-label`,children:`Most fragile`}),(0,a.jsx)(`ul`,{className:`mt-3 space-y-2`,children:i.map((e,t)=>(0,a.jsxs)(`li`,{className:`rounded-lg el-substrate border border-border-subtle p-3`,children:[(0,a.jsxs)(`div`,{className:`font-mono text-warning text-xs`,children:[e.actionType,` · `,e.targetRisk,` · `,e.scope]}),e.recommendation?(0,a.jsx)(`p`,{className:`mt-1 t-secondary text-xs leading-relaxed`,children:e.recommendation}):null]},`${e.actionType}-fragile-${e.scope}-${t}`))})]}):null]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Learned conventions`}),t.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(gt,{rows:6})}):t.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load conventions.`}):o.length===0?(0,a.jsx)(`p`,{className:`mt-4 t-secondary text-sm`,children:`No conventions detected yet.`}):(0,a.jsx)(`ul`,{className:`mt-4 space-y-3`,children:o.map(e=>(0,a.jsxs)(`li`,{className:`glass-card rounded-lg p-4`,children:[(0,a.jsx)(`div`,{className:`font-medium text-foreground text-sm`,children:e.name}),(0,a.jsx)(`div`,{className:`mt-1 font-mono t-secondary text-xs`,children:e.pattern}),(0,a.jsxs)(`div`,{className:`mt-2 t-tertiary text-xs`,children:[`confidence`,` `,(0,a.jsxs)(`span`,{className:`text-live font-mono`,children:[(e.confidence*100).toFixed(0),`%`]}),` · `,`n=`,e.observationCount]})]},e.id))})]}),(0,a.jsxs)(`section`,{className:`glass-panel overflow-hidden rounded-xl`,children:[(0,a.jsxs)(`div`,{className:`border-b border-border-subtle px-5 py-3`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Shadow ledger timeline`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:`Recent MCP tool calls (newest last in batch — scroll for latest).`})]}),(0,a.jsx)(`div`,{className:`custom-scrollbar max-h-[28rem] overflow-auto font-mono text-xs`,children:n.isLoading?(0,a.jsx)(gt,{rows:10}):n.isError?(0,a.jsx)(`p`,{className:`px-5 py-6 text-error`,children:`Could not load ledger.`}):(0,a.jsx)(`ul`,{className:`divide-y divide-border-subtle`,children:s.slice().reverse().map(e=>(0,a.jsxs)(`li`,{className:`px-5 py-2.5`,children:[(0,a.jsx)(`span`,{className:`t-tertiary`,children:e.ts}),` `,(0,a.jsx)(`span`,{className:`text-violet-500 font-medium`,children:e.tool}),` `,(0,a.jsx)(`span`,{className:`t-secondary`,children:e.branch}),(0,a.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap break-words t-secondary`,children:JSON.stringify(e.result_summary)})]},e.id))})})]})]})}var en={graph_query:{bg:`bg-violet-500/20`,text:`text-violet-400`,bar:`bg-violet-500`},shell_compression:{bg:`bg-cyan-500/20`,text:`text-cyan-400`,bar:`bg-cyan-500`},format_encoding:{bg:`bg-amber-500/20`,text:`text-amber-400`,bar:`bg-amber-500`},session_dedup:{bg:`bg-emerald-500/20`,text:`text-emerald-400`,bar:`bg-emerald-500`},smart_truncation:{bg:`bg-blue-500/20`,text:`text-blue-400`,bar:`bg-blue-500`},file_read:{bg:`bg-indigo-500/20`,text:`text-indigo-400`,bar:`bg-indigo-500`},behavior_automation:{bg:`bg-rose-500/20`,text:`text-rose-400`,bar:`bg-rose-500`}};function tn(e){return en[e]??{bg:`bg-zinc-500/20`,text:`text-zinc-400`,bar:`bg-zinc-500`}}function nn(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function rn({label:e,v:t,accent:n}){return(0,a.jsxs)(`div`,{className:`glass-card rounded-xl p-4`,children:[(0,a.jsx)(`div`,{className:`section-label`,children:e}),(0,a.jsx)(`div`,{className:`mt-1.5 font-mono text-2xl tabular-nums ${n??`text-live`}`,children:t??`—`})]})}function an({data:e}){if(e.length===0)return null;let t=e[e.length-1]?.cumulative_tokens_saved??1,n=e.map((t,n)=>{let r=n>0?e[n-1].cumulative_tokens_saved:0,i=r>0?(t.cumulative_tokens_saved-r)/r*100:0;return{...t,growthRate:i}});return(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`flex items-baseline justify-between mb-2`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Cumulative Token Savings`}),(0,a.jsxs)(`span`,{className:`text-success font-mono text-sm font-medium`,children:[nn(t),` total`]})]}),(0,a.jsx)(`p`,{className:`t-tertiary text-xs mb-3`,children:`Each bar shows cumulative savings through that turn. As context shrinks, each subsequent optimization compounds on the reduced context.`}),(0,a.jsx)(`div`,{className:`flex items-end gap-px`,style:{height:`80px`},children:n.map(e=>{let n=t>0?e.cumulative_tokens_saved/t*100:0,r=tn(Object.entries(e.mechanisms_this_turn).sort(([,e],[,t])=>t-e)[0]?.[0]??`graph_query`);return(0,a.jsxs)(`div`,{className:`group relative flex-1 min-w-[3px] max-w-[20px]`,title:`Turn #${e.turn}: +${nn(e.tokens_saved_this_turn)} this turn, ${nn(e.cumulative_tokens_saved)} cumulative`,children:[(0,a.jsx)(`div`,{className:`${r.bar} opacity-70 hover:opacity-100 rounded-t transition-all cursor-pointer`,style:{height:`${Math.max(2,n)}%`}}),(0,a.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 hidden group-hover:block z-10`,children:(0,a.jsxs)(`div`,{className:`bg-zinc-900 border border-zinc-700 rounded px-2 py-1 text-xs whitespace-nowrap shadow-lg`,children:[(0,a.jsxs)(`div`,{className:`font-medium`,children:[`Turn #`,e.turn]}),(0,a.jsx)(`div`,{className:`t-tertiary`,children:e.tools.join(`, `)||`exec`}),(0,a.jsxs)(`div`,{className:`text-success`,children:[`+`,nn(e.tokens_saved_this_turn)]}),(0,a.jsxs)(`div`,{className:`t-secondary`,children:[`Cumulative: `,nn(e.cumulative_tokens_saved)]}),e.growthRate>0&&(0,a.jsxs)(`div`,{className:`text-amber-400`,children:[e.growthRate.toFixed(1),`% compound growth`]})]})})]},e.turn)})}),(0,a.jsxs)(`div`,{className:`flex justify-between mt-1`,children:[(0,a.jsx)(`span`,{className:`t-tertiary text-[10px]`,children:`Turn 1`}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px]`,children:[`Turn `,e.length]})]})]})}function on({mechanisms:e}){let t=Object.entries(e).sort(([,e],[,t])=>t.tokens_saved-e.tokens_saved);if(t.length===0)return(0,a.jsx)(`p`,{className:`t-secondary text-sm mt-3`,children:`No mechanism data yet.`});let n=t[0]?.[1].tokens_saved??1;return(0,a.jsx)(`div`,{className:`space-y-2 mt-3`,children:t.map(([e,t])=>{let r=tn(e),i=n>0?t.tokens_saved/n*100:0;return(0,a.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,a.jsx)(`span`,{className:`${r.text} text-xs font-medium w-32 shrink-0`,children:e.replace(/_/g,` `)}),(0,a.jsx)(`div`,{className:`flex-1 h-5 rounded bg-surface-secondary overflow-hidden`,children:(0,a.jsx)(`div`,{className:`h-full ${r.bar} opacity-80 rounded transition-all`,style:{width:`${Math.max(2,i)}%`}})}),(0,a.jsx)(`span`,{className:`text-success font-mono text-xs w-16 text-right shrink-0`,children:nn(t.tokens_saved)}),(0,a.jsxs)(`span`,{className:`t-tertiary font-mono text-xs w-12 text-right shrink-0`,children:[t.pct_of_total,`%`]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs w-10 text-right shrink-0`,children:[t.event_count,`×`]})]},e)})})}function sn({sessionSnapshot:e}){let t=N({queryKey:[`session`,`stats`],queryFn:()=>F(`/api/session/stats`)}),n=N({queryKey:[`session`,`efficiency`],queryFn:()=>F(`/api/session/efficiency`)}),r=N({queryKey:[`session`,`intents`],queryFn:()=>F(`/api/session/intents`)}),i=N({queryKey:[`token-flow`,`session`],queryFn:()=>F(`/api/token-flow/session`),refetchInterval:5e3}),o=N({queryKey:[`token-flow`,`cumulative`],queryFn:()=>F(`/api/token-flow/cumulative`),refetchInterval:5e3}),s=t.data?.data,c=e,l=n.data?.data,u=r.data?.data??[],d=i.data?.data,f=o.data?.data??[],p=c?.tool_calls??s?.tool_calls,m=c?.violations_caught??s?.violations_caught;c?.caught_total??s?.caught_events?.total;let h=d?.total_tokens_saved??c?.tokens_saved??s?.estimated_tokens_saved,g=d?.efficiency_pct,_=s?.caught_events,v={};if(_)for(let[e,t]of Object.entries(_))e!==`total`&&typeof t==`number`&&(v[e]=t);let y=c?.session_events?{...c.session_events}:v;return(0,a.jsxs)(`div`,{className:`flex flex-col gap-8`,children:[t.isLoading&&c===void 0&&s===void 0?(0,a.jsx)(mt,{n:5}):(0,a.jsxs)(`section`,{className:`grid gap-4 sm:grid-cols-2 lg:grid-cols-5`,children:[(0,a.jsx)(rn,{label:`Tool calls`,v:p}),(0,a.jsx)(rn,{label:`Tokens saved`,v:h==null?void 0:nn(h),accent:`text-success`}),(0,a.jsx)(rn,{label:`Efficiency`,v:g==null?void 0:`${g}%`,accent:`text-violet-400`}),(0,a.jsx)(rn,{label:`Violations caught`,v:m,accent:`text-amber-400`}),(0,a.jsx)(rn,{label:`Turns tracked`,v:d?.total_turns})]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Token Optimization`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:`Session-level token reduction. As prompting continues, context-level optimization compounds — each turn builds on prior savings.`}),i.isLoading?(0,a.jsx)(`div`,{className:`mt-4`,children:(0,a.jsx)(P,{className:`h-32 w-full`})}):!d||d.total_tokens_saved===0?(0,a.jsx)(`p`,{className:`mt-4 t-secondary text-sm`,children:`No token flow data yet. Use unerr MCP tools or exec commands to generate savings.`}):(0,a.jsxs)(`div`,{className:`mt-4 grid gap-6 lg:grid-cols-2`,children:[(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-4`,children:(0,a.jsx)(an,{data:f})}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-4`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Savings by Mechanism`}),(0,a.jsx)(`p`,{className:`t-tertiary text-xs mt-0.5 mb-1`,children:`Which optimization strategies contributed most to token reduction.`}),(0,a.jsx)(on,{mechanisms:d.by_mechanism})]})]}),f.length>=3&&d&&d.total_tokens_saved>0&&(0,a.jsxs)(`div`,{className:`mt-4 el-raised rounded-lg p-4 border border-violet-500/20`,children:[(0,a.jsx)(`div`,{className:`flex items-center gap-2 mb-2`,children:(0,a.jsx)(`span`,{className:`text-violet-400 text-sm font-medium`,children:`Compound Effect`})}),(0,a.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3 text-sm`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-tertiary text-xs`,children:`Tokens without unerr`}),(0,a.jsx)(`dd`,{className:`font-mono text-foreground text-lg tabular-nums`,children:nn(d.total_tokens_without)})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-tertiary text-xs`,children:`Tokens delivered`}),(0,a.jsx)(`dd`,{className:`font-mono text-foreground text-lg tabular-nums`,children:nn(d.total_tokens_with)})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-tertiary text-xs`,children:`Net reduction`}),(0,a.jsxs)(`dd`,{className:`font-mono text-success text-lg tabular-nums`,children:[nn(d.total_tokens_saved),` `,(0,a.jsxs)(`span`,{className:`text-xs t-secondary`,children:[`(`,d.efficiency_pct,`%)`]})]})]})]}),(0,a.jsxs)(`p`,{className:`mt-2 t-tertiary text-xs`,children:[`Across `,d.total_turns,` turns with `,d.event_count,` optimization events. Average `,nn(Math.round(d.total_tokens_saved/Math.max(1,d.total_turns))),` saved per turn.`]})]})]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Session events`}),(0,a.jsx)(`p`,{className:`mt-1 t-tertiary text-xs`,children:"Values merge REST + SSE `session_stats` when connected."}),Object.keys(y).length===0?(0,a.jsx)(`p`,{className:`mt-4 t-secondary text-sm`,children:`No event breakdown yet.`}):(0,a.jsx)(`dl`,{className:`mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4 text-sm`,children:Object.entries(y).map(([e,t])=>(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:e}),(0,a.jsx)(`dd`,{className:`font-mono text-success`,children:t??`—`})]},e))})]}),(0,a.jsxs)(`section`,{className:`glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Compression efficiency`}),n.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 grid gap-4 sm:grid-cols-3`,children:[(0,a.jsx)(P,{className:`h-10 w-full`}),(0,a.jsx)(P,{className:`h-10 w-full`}),(0,a.jsx)(P,{className:`h-10 w-full`})]}):l?(0,a.jsxs)(`dl`,{className:`mt-4 grid gap-4 sm:grid-cols-3 text-sm`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Calls`}),(0,a.jsx)(`dd`,{className:`font-mono text-foreground text-xl tabular-nums`,children:l.totalCalls})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Saved tokens`}),(0,a.jsx)(`dd`,{className:`font-mono text-live text-xl tabular-nums`,children:l.savedTokens})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`dt`,{className:`t-secondary text-xs`,children:`Efficiency %`}),(0,a.jsx)(`dd`,{className:`font-mono text-foreground text-xl tabular-nums`,children:l.efficiency})]})]}):(0,a.jsx)(`p`,{className:`mt-3 t-secondary text-sm`,children:`No efficiency data yet.`})]}),(0,a.jsxs)(`section`,{className:`glass-panel overflow-hidden rounded-xl`,children:[(0,a.jsx)(`div`,{className:`border-b border-border-subtle px-5 py-3`,children:(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Intent groups`})}),(0,a.jsx)(`div`,{className:`overflow-x-auto custom-scrollbar`,children:r.isLoading?(0,a.jsx)(yt,{cols:6,rows:6}):u.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No intent groups recorded.`}):(0,a.jsxs)(`table`,{className:`w-full min-w-[720px] text-left text-sm`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-2.5 font-medium`,children:`Intent`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`Calls`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`Consumed`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`Saved`}),(0,a.jsx)(`th`,{className:`py-2.5 font-medium`,children:`Outcome`}),(0,a.jsx)(`th`,{className:`py-2.5 pr-5 font-medium`,children:`Duration`})]})}),(0,a.jsx)(`tbody`,{children:u.map(e=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle`,children:[(0,a.jsxs)(`td`,{className:`px-5 py-2.5 font-mono text-xs`,children:[e.intentId.slice(0,12),`…`]}),(0,a.jsx)(`td`,{className:`py-2.5 tabular-nums`,children:e.toolCalls}),(0,a.jsx)(`td`,{className:`py-2.5 tabular-nums`,children:e.tokensConsumed}),(0,a.jsx)(`td`,{className:`py-2.5 tabular-nums text-live`,children:e.tokensSaved}),(0,a.jsx)(`td`,{className:`py-2.5 t-secondary`,children:e.outcome}),(0,a.jsxs)(`td`,{className:`py-2.5 pr-5 tabular-nums t-secondary`,children:[e.durationMs,` ms`]})]},e.intentId))})]})})]})]})}var cn={graph_query:{bg:`bg-violet-500/20`,text:`text-violet-400`,bar:`bg-violet-500`,ring:`ring-violet-500/40`},shell_compression:{bg:`bg-cyan-500/20`,text:`text-cyan-400`,bar:`bg-cyan-500`,ring:`ring-cyan-500/40`},format_encoding:{bg:`bg-amber-500/20`,text:`text-amber-400`,bar:`bg-amber-500`,ring:`ring-amber-500/40`},session_dedup:{bg:`bg-emerald-500/20`,text:`text-emerald-400`,bar:`bg-emerald-500`,ring:`ring-emerald-500/40`},smart_truncation:{bg:`bg-blue-500/20`,text:`text-blue-400`,bar:`bg-blue-500`,ring:`ring-blue-500/40`},file_read:{bg:`bg-indigo-500/20`,text:`text-indigo-400`,bar:`bg-indigo-500`,ring:`ring-indigo-500/40`},behavior_automation:{bg:`bg-rose-500/20`,text:`text-rose-400`,bar:`bg-rose-500`,ring:`ring-rose-500/40`}},ln=[`graph_query`,`shell_compression`,`format_encoding`,`session_dedup`,`smart_truncation`,`file_read`,`behavior_automation`];function I(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function un(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function dn(e){return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function fn(e){return cn[e]??{bg:`bg-zinc-500/20`,text:`text-zinc-400`,bar:`bg-zinc-500`,ring:`ring-zinc-500/40`}}function pn(e){let t=e.detail;if(!t)return e.tool??`optimization`;if(t.command){let e=String(t.command);return e.length>80?e.slice(0,77)+`…`:e}return t.optimization?String(t.optimization):t.counterfactual&&t.counterfactual!==`generic file exploration`?String(t.counterfactual):t.format?`${e.tool??`query`} → ${t.format} format`:e.tool??`optimization`}function mn(e){if(e.length===0)return{label:`Empty turn`,subtitle:``};let t=[...new Set(e.map(e=>e.tool).filter(Boolean))],n=[...new Set(e.map(e=>e.mechanism))],r=e.find(e=>e.detail?.command);if(r){let t=String(r.detail.command);return{label:t.length>60?t.slice(0,57)+`…`:t,subtitle:`shell → ${e.length} optimization${e.length>1?`s`:``}`}}let i=e.find(e=>e.detail?.optimization);if(i){let n=String(i.detail.optimization),r=e.length>1?` +${e.length-1} more`:``;return{label:n,subtitle:t.join(`, `)+r}}if(t.length>0){let r=t.join(` → `),i=e.length,a=n[0]?.replace(/_/g,` `)??``;return{label:r,subtitle:`${i} event${i>1?`s`:``} · ${a}`}}return{label:n.map(e=>e.replace(/_/g,` `)).join(`, `),subtitle:`${e.length} event${e.length>1?`s`:``}`}}function hn({label:e,value:t,accent:n,hint:r}){return(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-4`,title:r,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-xs uppercase tracking-wider`,children:e}),(0,a.jsx)(`p`,{className:`mt-1 text-2xl font-bold font-mono tabular-nums ${n??`text-foreground`}`,children:t})]})}function gn({mechanisms:e,totalSaved:t}){let n=Object.entries(e).sort(([,e],[,t])=>t.tokens_saved-e.tokens_saved);if(n.length===0)return(0,a.jsx)(`p`,{className:`t-secondary text-sm py-3`,children:`No mechanism data.`});let r=n[0][1].tokens_saved||1;return(0,a.jsx)(`div`,{className:`space-y-1.5`,children:n.map(([e,t])=>{let n=fn(e),i=Math.max(3,t.tokens_saved/r*100);return(0,a.jsxs)(`div`,{className:`flex items-center gap-3 py-0.5`,children:[(0,a.jsx)(`span`,{className:`${n.text} text-xs font-medium w-36 shrink-0 truncate`,children:e.replace(/_/g,` `)}),(0,a.jsx)(`div`,{className:`flex-1 h-5 rounded bg-surface-secondary overflow-hidden`,children:(0,a.jsx)(`div`,{className:`h-full ${n.bar} opacity-80 rounded`,style:{width:`${i}%`}})}),(0,a.jsx)(`span`,{className:`text-success font-mono text-xs w-14 text-right shrink-0`,children:I(t.tokens_saved)}),(0,a.jsxs)(`span`,{className:`t-tertiary font-mono text-xs w-10 text-right shrink-0`,children:[t.pct_of_total,`%`]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs w-8 text-right shrink-0`,children:[t.event_count,`×`]})]},e)})})}function _n({mechanism:e}){let t=fn(e);return(0,a.jsx)(`span`,{className:`inline-flex items-center rounded-full px-2 py-0.5 ${t.bg} ${t.text} text-[10px] font-medium`,children:e.replace(/_/g,` `)})}function vn({items:e}){return(0,a.jsx)(`nav`,{className:`flex items-center gap-1.5 text-sm mb-5`,children:e.map((t,n)=>{let r=n===e.length-1;return(0,a.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[n>0&&(0,a.jsx)(`span`,{className:`t-tertiary`,children:`›`}),r?(0,a.jsx)(`span`,{className:`text-foreground font-medium`,children:t.label}):(0,a.jsx)(`button`,{type:`button`,className:`text-violet-400 hover:text-violet-300 transition-colors cursor-pointer`,onClick:t.onClick,children:t.label})]},n)})})}var yn={"claude-code":{bg:`bg-amber-500/20`,text:`text-amber-400`,label:`Claude Code`},"claude-desktop":{bg:`bg-amber-500/20`,text:`text-amber-400`,label:`Claude Desktop`},cursor:{bg:`bg-blue-500/20`,text:`text-blue-400`,label:`Cursor`},cline:{bg:`bg-emerald-500/20`,text:`text-emerald-400`,label:`Cline`},windsurf:{bg:`bg-cyan-500/20`,text:`text-cyan-400`,label:`Windsurf`},copilot:{bg:`bg-zinc-500/20`,text:`text-zinc-400`,label:`Copilot`}};function bn({name:e}){if(!e)return(0,a.jsx)(`span`,{className:`t-tertiary text-[10px]`,children:`unknown`});let t=yn[e.toLowerCase().replace(/\s+/g,`-`)]??{bg:`bg-zinc-500/20`,text:`text-zinc-400`,label:e};return(0,a.jsx)(`span`,{className:`inline-flex items-center rounded-full px-2 py-0.5 ${t.bg} ${t.text} text-[10px] font-medium`,children:t.label})}var xn=[`Su`,`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`];function Sn(e,t){return new Date(e,t+1,0).getDate()}function Cn(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function wn(e,t,n){if(!t||!n)return!1;let r=e.getTime();return r>t.getTime()&&r<n.getTime()}function Tn(e){return`${e.toLocaleString(`en-US`,{month:`short`})} ${e.getDate()}, ${e.getFullYear()}`}function En({selected:e,rangeStart:t,rangeEnd:n,onSelect:r,month:i,year:o,onMonthChange:s}){let c=Sn(o,i),l=new Date(o,i,1).getDay(),u=new Date;return(0,a.jsxs)(`div`,{className:`w-[252px]`,children:[(0,a.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,a.jsx)(`button`,{type:`button`,onClick:()=>{let e=i===0?11:i-1;s(i===0?o-1:o,e)},className:`t-tertiary hover:text-foreground p-1 rounded transition-colors text-xs`,children:`<`}),(0,a.jsx)(`span`,{className:`text-foreground text-xs font-medium`,children:new Date(o,i).toLocaleString(`en-US`,{month:`long`,year:`numeric`})}),(0,a.jsx)(`button`,{type:`button`,onClick:()=>{let e=i===11?0:i+1;s(i===11?o+1:o,e)},className:`t-tertiary hover:text-foreground p-1 rounded transition-colors text-xs`,children:`>`})]}),(0,a.jsx)(`div`,{className:`grid grid-cols-7 gap-0 mb-1`,children:xn.map(e=>(0,a.jsx)(`div`,{className:`text-center t-tertiary text-[10px] font-medium py-0.5`,children:e},e))}),(0,a.jsxs)(`div`,{className:`grid grid-cols-7 gap-0`,children:[Array.from({length:l}).map((e,t)=>(0,a.jsx)(`div`,{},`pad-${t}`)),Array.from({length:c}).map((s,c)=>{let l=new Date(o,i,c+1),d=Cn(l,u),f=e&&Cn(l,e),p=t&&Cn(l,t),m=n&&Cn(l,n),h=wn(l,t,n),g=l>u;return(0,a.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>r(l),className:[`h-8 w-9 text-xs rounded transition-all text-center`,g?`t-tertiary opacity-30 cursor-not-allowed`:`cursor-pointer`,f||p||m?`bg-violet-500 text-white font-medium`:h?`bg-violet-500/20 text-violet-300`:d?`border border-violet-500/50 text-foreground`:`text-foreground hover:bg-surface-secondary`].join(` `),children:c+1},c+1)})]})]})}var Dn=[{label:`Today`,days:0},{label:`Last 7 days`,days:7},{label:`Last 30 days`,days:30},{label:`Last 90 days`,days:90}];function On({fromTs:e,toTs:t,onChange:n}){let[r,i]=(0,M.useState)(!1),[o,s]=(0,M.useState)(`from`),c=(0,M.useRef)(null),l=new Date,[u,d]=(0,M.useState)(l.getFullYear()),[f,p]=(0,M.useState)(l.getMonth()),m=e?new Date(e):null,h=t?new Date(t):null;(0,M.useEffect)(()=>{if(!r)return;let e=e=>{c.current&&!c.current.contains(e.target)&&i(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[r]);let g=r=>{o===`from`?(n(new Date(r.getFullYear(),r.getMonth(),r.getDate(),0,0,0).toISOString(),t),s(`to`)):(n(e,new Date(r.getFullYear(),r.getMonth(),r.getDate(),23,59,59).toISOString()),i(!1),s(`from`))},_=e=>{let t=new Date;n((e===0?new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0):new Date(Date.now()-e*24*60*60*1e3)).toISOString(),t.toISOString()),i(!1)},v=m||h?`${m?Tn(m):`...`} — ${h?Tn(h):`...`}`:`All time`;return(0,a.jsxs)(`div`,{ref:c,className:`relative`,children:[(0,a.jsxs)(`button`,{type:`button`,onClick:()=>i(!r),className:`flex items-center gap-2 bg-surface-secondary border border-border-subtle rounded-lg px-3 py-1.5 text-xs text-foreground hover:border-violet-500/50 transition-colors`,children:[(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5 t-tertiary shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z`})}),(0,a.jsx)(`span`,{className:`font-mono`,children:v}),(e||t)&&(0,a.jsx)(`span`,{className:`text-violet-400 hover:text-violet-300 ml-1`,onClick:e=>{e.stopPropagation(),n(``,``)},children:`x`})]}),r&&(0,a.jsxs)(`div`,{className:`absolute top-full mt-1 right-0 z-50 border border-border-subtle rounded-lg shadow-2xl p-4 flex gap-4`,style:{backgroundColor:`#18181b`},children:[(0,a.jsxs)(`div`,{className:`flex flex-col gap-1 border-r border-border-subtle pr-4`,children:[(0,a.jsx)(`span`,{className:`t-tertiary text-[10px] uppercase tracking-wider mb-1`,children:`Quick select`}),Dn.map(e=>(0,a.jsx)(`button`,{type:`button`,onClick:()=>_(e.days),className:`text-left text-xs px-2 py-1.5 rounded hover:bg-surface-secondary text-foreground transition-colors whitespace-nowrap`,children:e.label},e.label))]}),(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`flex items-center gap-2 mb-3`,children:[(0,a.jsxs)(`button`,{type:`button`,onClick:()=>s(`from`),className:`text-xs px-2 py-1 rounded transition-colors ${o===`from`?`bg-violet-500/20 text-violet-300 font-medium`:`t-tertiary hover:text-foreground`}`,children:[`From`,m?`: ${Tn(m)}`:``]}),(0,a.jsx)(`span`,{className:`t-tertiary text-xs`,children:`—`}),(0,a.jsxs)(`button`,{type:`button`,onClick:()=>s(`to`),className:`text-xs px-2 py-1 rounded transition-colors ${o===`to`?`bg-violet-500/20 text-violet-300 font-medium`:`t-tertiary hover:text-foreground`}`,children:[`To`,h?`: ${Tn(h)}`:``]})]}),(0,a.jsx)(En,{selected:o===`from`?m:h,rangeStart:m,rangeEnd:h,onSelect:g,month:f,year:u,onMonthChange:(e,t)=>{d(e),p(t)}})]})]})]})}function kn({total:e,limit:t,offset:n,onPageChange:r}){let i=Math.ceil(e/t),o=Math.floor(n/t)+1;return i<=1?null:(0,a.jsxs)(`div`,{className:`flex items-center justify-between px-1 py-2`,children:[(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[n+1,`–`,Math.min(n+t,e),` of `,e]}),(0,a.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,a.jsx)(`button`,{type:`button`,disabled:o<=1,className:`px-2.5 py-1 rounded text-xs font-medium bg-surface-secondary hover:bg-surface-tertiary disabled:opacity-30 disabled:cursor-not-allowed text-foreground transition-colors`,onClick:()=>r(Math.max(0,n-t)),children:`‹ Prev`}),(0,a.jsxs)(`span`,{className:`t-secondary text-xs px-2 font-mono`,children:[o,`/`,i]}),(0,a.jsx)(`button`,{type:`button`,disabled:o>=i,className:`px-2.5 py-1 rounded text-xs font-medium bg-surface-secondary hover:bg-surface-tertiary disabled:opacity-30 disabled:cursor-not-allowed text-foreground transition-colors`,onClick:()=>r(n+t),children:`Next ›`})]})]})}function An({onSelectSession:e}){let[t,n]=(0,M.useState)(``),[r,i]=(0,M.useState)(``),[o,s]=(0,M.useState)(0),c=t||r?`${t?`&from_ts=${t}`:``}${r?`&to_ts=${r}`:``}`:``,l=N({queryKey:[`token-flow-global`,t,r],queryFn:()=>F(`/api/token-flow/global?_=1${c}`),refetchInterval:5e3}),u=N({queryKey:[`token-flow-sessions`,t,r,o],queryFn:()=>F(`/api/token-flow/sessions?limit=20&offset=${o}${c}`),refetchInterval:5e3});if(l.isLoading)return(0,a.jsx)(mt,{n:4});let d=l.data?.data,f=u.data?.data??[],p=u.data?.total??0;return!d||d.event_count===0?(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-10 text-center`,children:[(0,a.jsx)(`p`,{className:`t-secondary text-lg`,children:`No token flow data yet`}),(0,a.jsx)(`p`,{className:`t-tertiary mt-2 text-sm`,children:`Token savings appear here as the agent makes tool calls through unerr.`}),(0,a.jsx)(`p`,{className:`t-tertiary mt-1 text-xs`,children:`Sources: graph queries, shell compression, format encoding, session dedup, smart truncation, file reads, behavior automation.`})]}):(0,a.jsxs)(`div`,{className:`space-y-6`,children:[(0,a.jsxs)(`div`,{className:`flex items-center justify-end gap-3 flex-wrap -mt-2`,children:[(0,a.jsx)(On,{fromTs:t,toTs:r,onChange:(e,t)=>{n(e),i(t),s(0)}}),(0,a.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded-md border border-border-subtle px-3 py-1.5 text-xs font-medium t-secondary hover:text-foreground hover:bg-surface-secondary transition-colors`,title:`Export all token flow data as CSV`,onClick:()=>{let e=t||r?`${t?`&from_ts=${t}`:``}${r?`&to_ts=${r}`:``}`:``;fetch(`/api/token-flow/events?limit=500${e}`).then(e=>e.json()).then(e=>{let t=e.data??[];if(t.length===0)return;let n=[`timestamp`,`session_id`,`turn`,`mechanism`,`tool`,`tokens_without`,`tokens_with`,`tokens_saved`,`detail`],r=t.map(e=>[e.ts,e.session_id,e.turn,e.mechanism,e.tool??``,e.tokens_without,e.tokens_with,e.tokens_saved,(e.detail??``).toString().replace(/"/g,`""`)].map(e=>`"${e}"`).join(`,`)),i=[n.join(`,`),...r].join(`
2
- `),a=new Blob([i],{type:`text/csv`}),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o,s.download=`token-economics-${new Date().toISOString().slice(0,10)}.csv`,s.click(),URL.revokeObjectURL(o)})},children:[(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z`})}),`Export CSV`]})]}),(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Total Tokens Saved`,value:I(d.total_tokens_saved),accent:`text-success`,hint:`Total tokens removed from responses across all sessions — direct savings before context compounding`}),(0,a.jsx)(hn,{label:`Context Avoided`,value:I(d.total_context_avoided),accent:`text-cyan-400`,hint:`Total token-turns of context pressure prevented — savings compound because each turn's reduction carries forward to all future turns`}),(0,a.jsx)(hn,{label:`Total Delivered`,value:I(d.total_tokens_with),hint:`Total tokens actually sent to the agent after optimization`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${d.efficiency_pct}%`,accent:`text-violet-400`,hint:`Percentage of original tokens that were optimized away (saved ÷ original)`}),(0,a.jsx)(hn,{label:`Sessions`,value:d.total_sessions,hint:`Number of distinct agent sessions tracked`})]}),d.avg_context_reduction>0&&(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-5 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-start justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Pressure Prevented`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1 max-w-xl`,children:[`Across `,d.total_sessions,` session`,d.total_sessions===1?``:`s`,` and `,d.total_turns,` turns,`,` `,(0,a.jsx)(`span`,{className:`text-cyan-400 font-medium`,children:I(d.total_context_avoided)}),` total token-turns of context avoided — each turn ran with `,I(d.avg_context_reduction),` fewer tokens on average, peaking at `,I(d.peak_context_reduction),`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-6 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Total Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium text-lg`,children:I(d.total_context_avoided)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Avg / Turn`}),(0,a.jsx)(`p`,{className:`text-foreground font-mono font-medium text-lg`,children:I(d.avg_context_reduction)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Direct Savings`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium text-lg`,children:I(d.total_tokens_saved)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Peak Reduction`}),(0,a.jsx)(`p`,{className:`text-violet-400 font-mono font-medium text-lg`,children:I(d.peak_context_reduction)})]})]})]})}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsxs)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:[`Savings by Mechanism`,t||r?` (Filtered)`:` (All Time)`]}),(0,a.jsx)(gn,{mechanisms:d.by_mechanism,totalSaved:d.total_tokens_saved})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Sessions`}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[p,` session`,p===1?``:`s`]})]}),f.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No sessions recorded.`}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[700px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-2.5 font-medium`,title:`Unique session identifier`,children:`Session`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`AI agent that ran this session`,children:`Agent`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`When the last event was recorded`,children:`Last Active`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Number of optimization events in this session`,children:`Events`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Types of optimization applied (e.g. graph query, shell compression)`,children:`Mechanisms`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Total tokens removed from responses (direct savings)`,children:`Tokens Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Average tokens of context pressure avoided per turn — savings compound because each turn's reduction carries to all future turns`,children:`Avg Context Reduced`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 pr-5 font-medium w-16`})]})}),(0,a.jsx)(`tbody`,{children:f.map((t,n)=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors cursor-pointer group`,onClick:()=>e(t.session_id),children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,children:(0,a.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`font-mono text-xs text-foreground group-hover:text-violet-400 transition-colors`,children:t.session_id.slice(0,12)}),n===0&&o===0&&(0,a.jsx)(`span`,{className:`rounded-full bg-emerald-500/20 text-emerald-400 px-2 py-0.5 text-[10px] font-medium`,children:`latest`})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(bn,{name:t.agent_name})}),(0,a.jsx)(`td`,{className:`px-3 py-3 t-secondary text-xs`,children:un(t.last_ts)}),(0,a.jsx)(`td`,{className:`px-3 py-3 font-mono text-xs tabular-nums`,children:t.event_count}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[t.mechanisms.slice(0,4).map(e=>(0,a.jsx)(_n,{mechanism:e},e)),t.mechanisms.length>4&&(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px]`,children:[`+`,t.mechanisms.length-4]})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-sm`,children:I(t.total_saved)})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:t.avg_context_reduction>0?(0,a.jsx)(`span`,{className:`text-cyan-400 font-mono font-medium text-sm`,title:`Each turn ran with ~${I(t.avg_context_reduction)} fewer tokens in context on average (across ${t.total_turns} turns)`,children:I(t.avg_context_reduction)}):(0,a.jsx)(`span`,{className:`t-tertiary font-mono text-sm`,children:`—`})}),(0,a.jsx)(`td`,{className:`pl-4 py-3 pr-5 text-right w-16`,children:(0,a.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity font-medium whitespace-nowrap`,children:[`View `,(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M9 5l7 7-7 7`})})]})})]},t.session_id))})]})}),(0,a.jsx)(`div`,{className:`px-5 py-2 border-t border-border-subtle`,children:(0,a.jsx)(kn,{total:p,limit:20,offset:o,onPageChange:s})})]})]})]})}function jn({sessionId:e,onSelectTurn:t}){let[n,r]=(0,M.useState)(0),i=N({queryKey:[`token-flow-session`,e],queryFn:()=>F(`/api/token-flow/session${e?`?session_id=${e}`:``}`),refetchInterval:5e3}),o=N({queryKey:[`token-flow-cumulative`,e],queryFn:()=>F(`/api/token-flow/cumulative?session_id=${e}`),refetchInterval:5e3}),s=N({queryKey:[`token-flow-events`,e],queryFn:()=>F(`/api/token-flow/events?session_id=${e}`),refetchInterval:5e3});if(i.isLoading)return(0,a.jsx)(mt,{n:4});let c=i.data?.data,l=o.data?.data??[],u=s.data?.data??[];if(!c)return(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-8 text-center`,children:(0,a.jsxs)(`p`,{className:`t-secondary`,children:[`No data for session `,e.slice(0,12)]})});let d=new Map;for(let e of u){let t=d.get(e.turn)??[];t.push(e),d.set(e.turn,t)}let f=[...d.entries()].sort(([e],[t])=>t-e),p=f.slice(n*20,(n+1)*20),m=p.reduce((e,[,t])=>{let n=t.reduce((e,t)=>e+t.tokens_saved,0);return Math.max(e,n)},1),h=new Map;for(let e of l)h.set(e.turn,e);return(0,a.jsxs)(`div`,{className:`space-y-6`,children:[(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Tokens Saved`,value:I(c.total_tokens_saved),accent:`text-success`,hint:`Tokens removed from responses in this session`}),(0,a.jsx)(hn,{label:`Delivered`,value:I(c.total_tokens_with),hint:`Tokens actually sent to the agent after optimization`}),(0,a.jsx)(hn,{label:`Without unerr`,value:I(c.total_tokens_without),hint:`Tokens that would have been sent without unerr`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${c.efficiency_pct}%`,accent:`text-violet-400`,hint:`Percentage of original tokens optimized away`}),(0,a.jsx)(hn,{label:`Turns`,value:c.total_turns,hint:`Number of conversation turns in this session`})]}),(o.data?.avg_context_reduction??0)>0&&(()=>{let e=o.data;return(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-5 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-start justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Pressure Prevented`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1 max-w-xl`,children:[`Across `,c.total_turns,` turns, `,(0,a.jsx)(`span`,{className:`text-cyan-400 font-medium`,children:I(e.total_context_avoided)}),` total token-turns of context avoided — each turn ran with `,I(e.avg_context_reduction),` fewer tokens on average, peaking at `,I(e.peak_context_reduction),`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-6 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Total Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium text-lg`,children:I(e.total_context_avoided)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Avg / Turn`}),(0,a.jsx)(`p`,{className:`text-foreground font-mono font-medium text-lg`,children:I(e.avg_context_reduction)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Direct Savings`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium text-lg`,children:I(c.total_tokens_saved)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Peak Reduction`}),(0,a.jsx)(`p`,{className:`text-violet-400 font-mono font-medium text-lg`,children:I(e.peak_context_reduction)})]})]})]})})})(),(0,a.jsxs)(`div`,{className:`grid gap-6 lg:grid-cols-2`,children:[(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-1`,children:`Cumulative Savings`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mb-3`,children:[`Each bar = cumulative tokens saved through that turn. Showing latest `,Math.min(60,l.length),` of `,l.length,` turns. Hover for details.`]}),l.length===0?(0,a.jsx)(`div`,{className:`h-[140px] flex items-center justify-center`,children:(0,a.jsx)(`p`,{className:`t-tertiary text-xs`,children:`Loading chart data...`})}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`flex gap-[3px]`,style:{height:`140px`},children:l.slice(-60).map(e=>{let n=l[l.length-1]?.cumulative_tokens_saved||1,r=e.cumulative_tokens_saved/n*100;return(0,a.jsxs)(`div`,{className:`group relative flex-1 min-w-[6px] max-w-[28px] h-full flex items-end`,children:[(0,a.jsx)(`div`,{className:`w-full ${fn(Object.entries(e.mechanisms_this_turn).sort(([,e],[,t])=>t-e)[0]?.[0]??`graph_query`).bar} opacity-70 hover:opacity-100 rounded-t transition-all cursor-pointer`,style:{height:`${Math.max(4,r)}%`},onClick:()=>t(e.turn)}),(0,a.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 hidden group-hover:block z-20 pointer-events-none`,children:(0,a.jsxs)(`div`,{className:`bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-xs whitespace-nowrap shadow-xl`,children:[(0,a.jsxs)(`div`,{className:`font-medium text-foreground`,children:[`Turn #`,e.turn]}),(0,a.jsx)(`div`,{className:`t-tertiary mt-0.5`,children:e.tools.join(`, `)||`exec`}),(0,a.jsxs)(`div`,{className:`text-success mt-1`,children:[`+`,I(e.tokens_saved_this_turn),` this turn`]}),(0,a.jsxs)(`div`,{className:`t-secondary`,children:[`Cumulative: `,I(e.cumulative_tokens_saved)]}),(0,a.jsxs)(`div`,{className:`text-cyan-400 mt-0.5`,children:[`Context avoided: `,I(e.context_avoided)]}),(0,a.jsx)(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:Object.keys(e.mechanisms_this_turn).map(e=>(0,a.jsx)(_n,{mechanism:e},e))})]})})]},e.turn)})}),(0,a.jsxs)(`div`,{className:`flex justify-between mt-1.5`,children:[(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] font-mono`,children:[`T`,l.length>60?l.length-59:1]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] font-mono`,children:[`T`,l.length]})]}),(0,a.jsx)(`div`,{className:`flex flex-wrap gap-3 mt-3 pt-3 border-t border-border-subtle/50`,children:ln.filter(e=>l.some(t=>e in t.mechanisms_this_turn)).map(e=>(0,a.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,a.jsx)(`div`,{className:`h-2.5 w-2.5 rounded-sm ${fn(e).bar}`}),(0,a.jsx)(`span`,{className:`t-tertiary text-[10px]`,children:e.replace(/_/g,` `)})]},e))})]})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:`Savings by Mechanism`}),(0,a.jsx)(gn,{mechanisms:c.by_mechanism,totalSaved:c.total_tokens_saved})]})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Turns`}),(0,a.jsx)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:`Click a turn to see all events and mechanisms within it.`})]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[f.length,` turn`,f.length===1?``:`s`]})]}),p.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No turns recorded.`}):(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[800px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-2.5 font-medium w-14`,title:`Turn number in the conversation`,children:`Turn`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Summary of what happened in this turn`,children:`Description`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium w-36`,title:`Relative savings compared to the largest turn — wider bar means more tokens saved`,children:`Savings Bar`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Types of optimization applied in this turn`,children:`Mechanisms`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Tokens removed from responses in this turn (direct savings)`,children:`Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Cumulative tokens of context avoided at this point — prior savings carry forward, keeping context smaller for this and future turns`,children:`Context Avoided`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Number of optimization events in this turn`,children:`Events`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 pr-5 font-medium w-16`})]})}),(0,a.jsx)(`tbody`,{children:p.map(([e,n])=>{let r=n.reduce((e,t)=>e+t.tokens_saved,0),i=[...new Set(n.map(e=>e.mechanism))],{label:o,subtitle:s}=mn(n),c=h.get(e);return(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors cursor-pointer group`,onClick:()=>t(e),children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,children:(0,a.jsxs)(`span`,{className:`t-tertiary font-mono text-xs group-hover:text-violet-400 transition-colors`,children:[`#`,e]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsxs)(`div`,{className:`min-w-0 max-w-[260px]`,children:[(0,a.jsx)(`p`,{className:`text-foreground font-mono text-xs truncate group-hover:text-violet-300 transition-colors`,children:o}),s&&(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] mt-0.5 truncate`,children:s})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(`div`,{className:`w-32 h-4 relative rounded-sm bg-surface-secondary overflow-hidden`,children:(()=>{let e=new Map;for(let t of n)e.set(t.mechanism,(e.get(t.mechanism)??0)+t.tokens_saved);let t=0;return[...e.entries()].sort(([,e],[,t])=>t-e).map(([e,n])=>{let r=m>0?n/m*100:0,i=t;return t+=r,(0,a.jsx)(`div`,{className:`absolute inset-y-0 ${fn(e).bar} opacity-80`,style:{left:`${i}%`,width:`${Math.max(1,r)}%`}},e)})})()})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:i.map(e=>(0,a.jsx)(_n,{mechanism:e},e))})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(r)})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:c?(0,a.jsx)(`span`,{className:`text-cyan-400 font-mono font-medium text-xs`,title:`${I(c.context_avoided)} tokens of cumulative context avoided at turn #${e}`,children:I(c.context_avoided)}):(0,a.jsx)(`span`,{className:`t-tertiary font-mono text-xs`,children:`—`})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`t-tertiary text-xs`,children:n.length})}),(0,a.jsx)(`td`,{className:`pl-4 py-3 pr-5 text-right w-16`,children:(0,a.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity font-medium whitespace-nowrap`,children:[`View `,(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M9 5l7 7-7 7`})})]})})]},e)})})]})}),(0,a.jsx)(kn,{total:f.length,limit:20,offset:n*20,onPageChange:e=>r(Math.floor(e/20))})]})]})}function Mn({sessionId:e,turn:t}){let n=N({queryKey:[`token-flow-events`,e,t],queryFn:()=>F(`/api/token-flow/events?session_id=${e}&turn=${t}`)}),r=N({queryKey:[`token-flow-cumulative`,e],queryFn:()=>F(`/api/token-flow/cumulative?session_id=${e}`)}),i=r.data?.data?.find(e=>e.turn===t),o=r.data?.total_turns??0,s=o>0?o-(r.data?.data?.findIndex(e=>e.turn===t)??0)-1:0,c=n.data?.data??[],[l,u]=(0,M.useState)(0),d=c.slice(l,l+20),f=c.reduce((e,t)=>e+t.tokens_saved,0),p=c.reduce((e,t)=>e+t.tokens_without,0),m=c.reduce((e,t)=>e+t.tokens_with,0),h=[...new Set(c.map(e=>e.tool).filter(Boolean))],g=p>0?Math.round(f/p*100):0,_={};for(let e of c){let t=_[e.mechanism]??{tokens_saved:0,tokens_delivered:0,event_count:0,pct_of_total:0};t.tokens_saved+=e.tokens_saved,t.tokens_delivered+=e.tokens_with,t.event_count++,_[e.mechanism]=t}for(let e of Object.values(_))e.pct_of_total=f>0?Math.round(e.tokens_saved/f*100):0;return n.isLoading?(0,a.jsx)(mt,{n:4}):(0,a.jsxs)(`div`,{className:`space-y-6`,children:[(()=>{let{label:e,subtitle:t}=mn(c);return(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-4 border-l-4 border-violet-500/60`,children:[(0,a.jsx)(`p`,{className:`text-foreground font-mono text-sm font-medium`,children:e}),t&&(0,a.jsx)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:t})]})})(),(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Tokens Saved`,value:I(f),accent:`text-success`,hint:`Tokens removed in this turn`}),(0,a.jsx)(hn,{label:`Without unerr`,value:I(p),hint:`Tokens that would have been sent without optimization`}),(0,a.jsx)(hn,{label:`Delivered`,value:I(m),hint:`Tokens actually sent to the agent`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${g}%`,accent:`text-violet-400`,hint:`Percentage of tokens optimized away this turn`}),(0,a.jsx)(hn,{label:`Tools`,value:h.join(`, `)||`exec`,hint:`MCP tools that triggered optimizations in this turn`})]}),i&&(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-4 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-center justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Impact`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1`,children:[`At this point, `,I(i.context_avoided),` tokens of cumulative context avoided`,s>0?` — this turn's ${I(i.tokens_saved_this_turn)} savings carry forward to ${s} more turn${s===1?``:`s`}`:``,`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-5 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`This Turn`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium`,children:I(i.tokens_saved_this_turn)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium`,children:I(i.context_avoided)})]})]})]})}),Object.keys(_).length>0&&(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:`Mechanisms in this Turn`}),(0,a.jsx)(gn,{mechanisms:_,totalSaved:f})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Events`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:[`Every optimization event in turn #`,t,`: tool calls, exec commands, and the mechanism that reduced tokens.`]})]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[c.length,` event`,c.length===1?``:`s`]})]}),c.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No events for this turn.`}):(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[900px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-3 font-medium`,title:`When this optimization event occurred`,children:`Time`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium`,title:`Type of optimization applied (e.g. graph query, shell compression)`,children:`Mechanism`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium`,title:`MCP tool that triggered this optimization`,children:`Tool`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens that would have been sent without unerr`,children:`Without`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens actually delivered to the agent after optimization`,children:`Delivered`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens removed by this optimization (Without − Delivered)`,children:`Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-3 pr-5 font-medium`,title:`Description of what was optimized`,children:`Detail`})]})}),(0,a.jsx)(`tbody`,{children:d.map(e=>{fn(e.mechanism);let t=e.tokens_without>0?Math.round(e.tokens_saved/e.tokens_without*100):0;return(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors`,children:[(0,a.jsx)(`td`,{className:`t-tertiary px-5 py-3 font-mono text-xs whitespace-nowrap`,children:dn(e.ts)}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(_n,{mechanism:e.mechanism})}),(0,a.jsx)(`td`,{className:`t-secondary px-3 py-3 font-mono text-xs whitespace-nowrap`,children:e.tool??`—`}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums whitespace-nowrap`,children:I(e.tokens_without)}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums whitespace-nowrap`,children:I(e.tokens_with)}),(0,a.jsxs)(`td`,{className:`px-3 py-3 text-right whitespace-nowrap`,children:[(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(e.tokens_saved)}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] ml-1`,children:[`(`,t,`%)`]})]}),(0,a.jsx)(`td`,{className:`px-3 py-3 pr-5 font-mono text-xs max-w-[400px]`,children:(0,a.jsx)(`span`,{className:`t-secondary break-words leading-relaxed`,children:pn(e)})})]},e.id)})}),(0,a.jsx)(`tfoot`,{children:(0,a.jsxs)(`tr`,{className:`border-t border-border-subtle font-medium bg-surface-secondary/30`,children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,colSpan:3,children:(0,a.jsx)(`span`,{className:`t-secondary text-xs uppercase tracking-wider`,children:`Turn Total`})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums`,children:I(p)}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums`,children:I(m)}),(0,a.jsxs)(`td`,{className:`px-3 py-3 text-right`,children:[(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(f)}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] ml-1`,children:[`(`,g,`%)`]})]}),(0,a.jsx)(`td`,{})]})})]})}),(0,a.jsx)(`div`,{className:`px-5 py-2 border-t border-border-subtle`,children:(0,a.jsx)(kn,{total:c.length,limit:20,offset:l,onPageChange:u})})]})]})}function Nn(){let[e,t]=(0,M.useState)({level:`global`}),n=()=>t({level:`global`}),r=e=>t({level:`session`,sessionId:e}),i=(e,n)=>t({level:`turn`,sessionId:e,turn:n}),o=[];return(e.level===`session`||e.level===`turn`)&&o.push({label:`All Sessions`,onClick:n},{label:`Session ${e.sessionId.slice(0,12)}`,onClick:e.level===`turn`?()=>r(e.sessionId):void 0}),e.level===`turn`&&o.push({label:`Turn #${e.turn}`}),(0,a.jsxs)(`div`,{children:[o.length>0&&(0,a.jsx)(vn,{items:o}),e.level===`global`&&(0,a.jsx)(An,{onSelectSession:r}),e.level===`session`&&(0,a.jsx)(jn,{sessionId:e.sessionId,onSelectTurn:t=>i(e.sessionId,t)}),e.level===`turn`&&(0,a.jsx)(Mn,{sessionId:e.sessionId,turn:e.turn})]})}function Pn(){let e=N({queryKey:[`system`,`status`],queryFn:()=>F(`/api/system/status`)}),t=N({queryKey:[`system`,`config`],queryFn:()=>F(`/api/system/config`)}),n=e.data?.data,r=t.data?.data;return(0,a.jsxs)(`div`,{className:`flex flex-col gap-8 lg:flex-row`,children:[(0,a.jsxs)(`section`,{className:`flex-1 glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Proxy status`}),e.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,a.jsx)(P,{className:`h-4 w-full max-w-xs`}),(0,a.jsx)(P,{className:`h-4 w-full max-w-sm`}),(0,a.jsx)(P,{className:`h-4 w-full max-w-md`})]}):e.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not reach /api/system/status.`}):(0,a.jsxs)(`dl`,{className:`mt-4 space-y-3 text-sm`,children:[(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`State`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.status})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`PID`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.pid})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Uptime`}),(0,a.jsxs)(`dd`,{className:`font-mono text-xs text-foreground`,children:[n?.uptime_s,`s`]})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Dashboard port`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.dashboard_port})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`IDE`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.ide})]}),(0,a.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Working directory`}),(0,a.jsx)(`dd`,{className:`break-all font-mono text-xs t-secondary`,children:n?.cwd})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Graph entities`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-live`,children:n?.graph.entities})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Session tool calls`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-live`,children:n?.session.tool_calls})]})]})]}),(0,a.jsxs)(`section`,{className:`flex-1 glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Configuration`}),t.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,a.jsx)(P,{className:`h-4 w-56`}),(0,a.jsx)(P,{className:`h-24 w-full`})]}):t.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load config.`}):(0,a.jsxs)(`div`,{className:`mt-4 space-y-5`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label`,children:`Installed skills`}),r?.skills_installed?.length?(0,a.jsx)(`ul`,{className:`mt-2 space-y-1 font-mono text-xs`,children:r.skills_installed.map(e=>(0,a.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`inline-block h-1 w-1 rounded-full bg-violet-500`}),(0,a.jsx)(`span`,{className:`text-foreground`,children:e})]},e))}):(0,a.jsx)(`p`,{className:`mt-2 t-secondary text-sm`,children:`None reported.`})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label`,children:`Repo config (.unerr/config.json)`}),(0,a.jsx)(`pre`,{className:`mt-2 custom-scrollbar max-h-80 overflow-auto whitespace-pre-wrap rounded-lg el-substrate border border-border-subtle p-3 font-mono text-xs leading-relaxed t-secondary`,children:JSON.stringify(r?.repo_config??{},null,2)})]})]})]})]})}function Fn(){let e=ct(),[t,n]=(0,M.useState)(!1);(0,M.useEffect)(()=>ft(it,n),[]);let{data:r=[]}=N({queryKey:[`live-feed`],initialData:[]}),{data:i}=N({queryKey:[`session-snapshot`]}),o=ot(e),c;switch(e){case`overview`:c=(0,a.jsx)(Ct,{sseConnected:t,liveFeed:r,sessionSnapshot:i});break;case`visual`:c=(0,a.jsx)(Wt,{});break;case`graph`:c=(0,a.jsx)(wt,{});break;case`ledger`:c=(0,a.jsx)($t,{});break;case`facts`:c=(0,a.jsx)(Jt,{});break;case`session`:c=(0,a.jsx)(sn,{sessionSnapshot:i});break;case`token-flow`:c=(0,a.jsx)(Nn,{});break;case`settings`:c=(0,a.jsx)(Pn,{});break}return(0,a.jsx)(s,{title:o,activeRoute:e,statusDot:t?`live`:`reconnecting`,children:c})}var In=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,T());else{var t=n(l);t!==null&&ie(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-ee<w)}function ne(){if(g=!1,S){var t=e.unstable_now();ee=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ie(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?T():S=!1}}}var T;if(typeof y==`function`)T=function(){y(ne)};else if(typeof MessageChannel<`u`){var E=new MessageChannel,re=E.port2;E.port1.onmessage=ne,T=function(){re.postMessage(null)}}else T=function(){_(ne,0)};function ie(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,ie(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,T()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Ln=t(((e,t)=>{t.exports=In()})),Rn=t((e=>{var t=Be();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`);function o(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var s=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function c(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return o(e,t,null,r)},e.flushSync=function(e){var t=s.T,n=i.p;try{if(s.T=null,i.p=2,e)return e()}finally{s.T=t,i.p=n,i.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`)if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=c(t.as,t.crossOrigin);i.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??i.d.M(e)},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin);i.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`)if(t){var n=c(t.as,t.crossOrigin);i.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else i.d.m(e)},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return s.H.useFormState(e,t,n)},e.useFormStatus=function(){return s.H.useHostTransitionStatus()},e.version=`19.2.5`})),zn=t(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Rn()})),Bn=t((e=>{var t=Ln(),n=Be(),r=zn();function i(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function s(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function c(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(o(e)!==e)throw Error(i(188))}function u(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return l(a),e;if(s===r)return l(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,u=a.child;u;){if(u===n){c=!0,n=a,r=s;break}if(u===r){c=!0,r=a,n=s;break}u=u.sibling}if(!c){for(u=s.child;u;){if(u===n){c=!0,n=s,r=a;break}if(u===r){c=!0,r=s,n=a;break}u=u.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function d(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=d(e),t!==null)return t;e=e.sibling}return null}var f=Object.assign,p=Symbol.for(`react.element`),m=Symbol.for(`react.transitional.element`),h=Symbol.for(`react.portal`),g=Symbol.for(`react.fragment`),_=Symbol.for(`react.strict_mode`),v=Symbol.for(`react.profiler`),y=Symbol.for(`react.consumer`),b=Symbol.for(`react.context`),x=Symbol.for(`react.forward_ref`),S=Symbol.for(`react.suspense`),C=Symbol.for(`react.suspense_list`),w=Symbol.for(`react.memo`),ee=Symbol.for(`react.lazy`),te=Symbol.for(`react.activity`),ne=Symbol.for(`react.memo_cache_sentinel`),T=Symbol.iterator;function E(e){return typeof e!=`object`||!e?null:(e=T&&e[T]||e[`@@iterator`],typeof e==`function`?e:null)}var re=Symbol.for(`react.client.reference`);function ie(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===re?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case g:return`Fragment`;case v:return`Profiler`;case _:return`StrictMode`;case S:return`Suspense`;case C:return`SuspenseList`;case te:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case h:return`Portal`;case b:return e.displayName||`Context`;case y:return(e._context.displayName||`Context`)+`.Consumer`;case x:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case w:return t=e.displayName||null,t===null?ie(e.type)||`Memo`:t;case ee:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}var ae=Array.isArray,D=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,oe={pending:!1,data:null,method:null,action:null},se=[],ce=-1;function le(e){return{current:e}}function k(e){0>ce||(e.current=se[ce],se[ce]=null,ce--)}function A(e,t){ce++,se[ce]=e.current,e.current=t}var ue=le(null),de=le(null),j=le(null),fe=le(null);function pe(e,t){switch(A(j,t),A(de,e),A(ue,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Vd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Vd(t),e=Hd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}k(ue),A(ue,e)}function me(){k(ue),k(de),k(j)}function he(e){e.memoizedState!==null&&A(fe,e);var t=ue.current,n=Hd(t,e.type);t!==n&&(A(de,e),A(ue,n))}function ge(e){de.current===e&&(k(ue),k(de)),fe.current===e&&(k(fe),Qf._currentValue=oe)}var _e,ve;function ye(e){if(_e===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);_e=t&&t[1]||``,ve=-1<e.stack.indexOf(`
2
+ `),a=new Blob([i],{type:`text/csv`}),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o,s.download=`token-economics-${new Date().toISOString().slice(0,10)}.csv`,s.click(),URL.revokeObjectURL(o)})},children:[(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z`})}),`Export CSV`]})]}),(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Total Tokens Saved`,value:I(d.total_tokens_saved),accent:`text-success`,hint:`Total tokens removed from responses across all sessions — direct savings before context compounding`}),(0,a.jsx)(hn,{label:`Context Avoided`,value:I(d.total_context_avoided),accent:`text-cyan-400`,hint:`Total token-turns of context pressure prevented — savings compound because each turn's reduction carries forward to all future turns`}),(0,a.jsx)(hn,{label:`Total Delivered`,value:I(d.total_tokens_with),hint:`Total tokens actually sent to the agent after optimization`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${d.efficiency_pct}%`,accent:`text-violet-400`,hint:`Percentage of original tokens that were optimized away (saved ÷ original)`}),(0,a.jsx)(hn,{label:`Sessions`,value:d.total_sessions,hint:`Number of distinct agent sessions tracked`})]}),d.avg_context_reduction>0&&(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-5 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-start justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Pressure Prevented`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1 max-w-xl`,children:[`Across `,d.total_sessions,` session`,d.total_sessions===1?``:`s`,` and `,d.total_turns,` turns,`,` `,(0,a.jsx)(`span`,{className:`text-cyan-400 font-medium`,children:I(d.total_context_avoided)}),` total token-turns of context avoided — each turn ran with `,I(d.avg_context_reduction),` fewer tokens on average, peaking at `,I(d.peak_context_reduction),`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-6 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Total Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium text-lg`,children:I(d.total_context_avoided)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Avg / Turn`}),(0,a.jsx)(`p`,{className:`text-foreground font-mono font-medium text-lg`,children:I(d.avg_context_reduction)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Direct Savings`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium text-lg`,children:I(d.total_tokens_saved)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Compound Multiplier`}),(0,a.jsx)(`p`,{className:`text-violet-400 font-mono font-medium text-lg`,children:d.total_tokens_saved>0?`${(d.total_context_avoided/d.total_tokens_saved).toFixed(1)}×`:`—`})]})]})]})}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsxs)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:[`Savings by Mechanism`,t||r?` (Filtered)`:` (All Time)`]}),(0,a.jsx)(gn,{mechanisms:d.by_mechanism,totalSaved:d.total_tokens_saved})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Sessions`}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[p,` session`,p===1?``:`s`]})]}),f.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No sessions recorded.`}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[700px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-2.5 font-medium`,title:`Unique session identifier`,children:`Session`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`AI agent that ran this session`,children:`Agent`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`When the last event was recorded`,children:`Last Active`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Number of optimization events in this session`,children:`Events`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Types of optimization applied (e.g. graph query, shell compression)`,children:`Mechanisms`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Total tokens removed from responses (direct savings)`,children:`Tokens Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Average tokens of context pressure avoided per turn — savings compound because each turn's reduction carries to all future turns`,children:`Avg Context Reduced`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 pr-5 font-medium w-16`})]})}),(0,a.jsx)(`tbody`,{children:f.map((t,n)=>(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors cursor-pointer group`,onClick:()=>e(t.session_id),children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,children:(0,a.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`font-mono text-xs text-foreground group-hover:text-violet-400 transition-colors`,children:t.session_id.slice(0,12)}),n===0&&o===0&&(0,a.jsx)(`span`,{className:`rounded-full bg-emerald-500/20 text-emerald-400 px-2 py-0.5 text-[10px] font-medium`,children:`latest`})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(bn,{name:t.agent_name})}),(0,a.jsx)(`td`,{className:`px-3 py-3 t-secondary text-xs`,children:un(t.last_ts)}),(0,a.jsx)(`td`,{className:`px-3 py-3 font-mono text-xs tabular-nums`,children:t.event_count}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[t.mechanisms.slice(0,4).map(e=>(0,a.jsx)(_n,{mechanism:e},e)),t.mechanisms.length>4&&(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px]`,children:[`+`,t.mechanisms.length-4]})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-sm`,children:I(t.total_saved)})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:t.avg_context_reduction>0?(0,a.jsx)(`span`,{className:`text-cyan-400 font-mono font-medium text-sm`,title:`Each turn ran with ~${I(t.avg_context_reduction)} fewer tokens in context on average (across ${t.total_turns} turns)`,children:I(t.avg_context_reduction)}):(0,a.jsx)(`span`,{className:`t-tertiary font-mono text-sm`,children:`—`})}),(0,a.jsx)(`td`,{className:`pl-4 py-3 pr-5 text-right w-16`,children:(0,a.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity font-medium whitespace-nowrap`,children:[`View `,(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M9 5l7 7-7 7`})})]})})]},t.session_id))})]})}),(0,a.jsx)(`div`,{className:`px-5 py-2 border-t border-border-subtle`,children:(0,a.jsx)(kn,{total:p,limit:20,offset:o,onPageChange:s})})]})]})]})}function jn({sessionId:e,onSelectTurn:t}){let[n,r]=(0,M.useState)(0),i=N({queryKey:[`token-flow-session`,e],queryFn:()=>F(`/api/token-flow/session${e?`?session_id=${e}`:``}`),refetchInterval:5e3}),o=N({queryKey:[`token-flow-cumulative`,e],queryFn:()=>F(`/api/token-flow/cumulative?session_id=${e}`),refetchInterval:5e3}),s=N({queryKey:[`token-flow-events`,e],queryFn:()=>F(`/api/token-flow/events?session_id=${e}`),refetchInterval:5e3});if(i.isLoading)return(0,a.jsx)(mt,{n:4});let c=i.data?.data,l=o.data?.data??[],u=s.data?.data??[];if(!c)return(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-8 text-center`,children:(0,a.jsxs)(`p`,{className:`t-secondary`,children:[`No data for session `,e.slice(0,12)]})});let d=new Map;for(let e of u){let t=d.get(e.turn)??[];t.push(e),d.set(e.turn,t)}let f=[...d.entries()].sort(([e],[t])=>t-e),p=f.slice(n*20,(n+1)*20),m=p.reduce((e,[,t])=>{let n=t.reduce((e,t)=>e+t.tokens_saved,0);return Math.max(e,n)},1),h=new Map;for(let e of l)h.set(e.turn,e);return(0,a.jsxs)(`div`,{className:`space-y-6`,children:[(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Tokens Saved`,value:I(c.total_tokens_saved),accent:`text-success`,hint:`Tokens removed from responses in this session`}),(0,a.jsx)(hn,{label:`Delivered`,value:I(c.total_tokens_with),hint:`Tokens actually sent to the agent after optimization`}),(0,a.jsx)(hn,{label:`Without unerr`,value:I(c.total_tokens_without),hint:`Tokens that would have been sent without unerr`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${c.efficiency_pct}%`,accent:`text-violet-400`,hint:`Percentage of original tokens optimized away`}),(0,a.jsx)(hn,{label:`Turns`,value:c.total_turns,hint:`Number of conversation turns in this session`})]}),(o.data?.avg_context_reduction??0)>0&&(()=>{let e=o.data;return(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-5 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-start justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Pressure Prevented`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1 max-w-xl`,children:[`Across `,c.total_turns,` turns, `,(0,a.jsx)(`span`,{className:`text-cyan-400 font-medium`,children:I(e.total_context_avoided)}),` total token-turns of context avoided — each turn ran with `,I(e.avg_context_reduction),` fewer tokens on average, peaking at `,I(e.peak_context_reduction),`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-6 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Total Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium text-lg`,children:I(e.total_context_avoided)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Avg / Turn`}),(0,a.jsx)(`p`,{className:`text-foreground font-mono font-medium text-lg`,children:I(e.avg_context_reduction)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Direct Savings`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium text-lg`,children:I(c.total_tokens_saved)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Compound Multiplier`}),(0,a.jsx)(`p`,{className:`text-violet-400 font-mono font-medium text-lg`,children:c.total_tokens_saved>0?`${(e.total_context_avoided/c.total_tokens_saved).toFixed(1)}×`:`—`})]})]})]})})})(),(0,a.jsxs)(`div`,{className:`grid gap-6 lg:grid-cols-2`,children:[(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-1`,children:`Cumulative Savings`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mb-3`,children:[`Each bar = cumulative tokens saved through that turn. Showing latest `,Math.min(60,l.length),` of `,l.length,` turns. Hover for details.`]}),l.length===0?(0,a.jsx)(`div`,{className:`h-[140px] flex items-center justify-center`,children:(0,a.jsx)(`p`,{className:`t-tertiary text-xs`,children:`Loading chart data...`})}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`flex gap-[3px]`,style:{height:`140px`},children:l.slice(-60).map(e=>{let n=l[l.length-1]?.cumulative_tokens_saved||1,r=e.cumulative_tokens_saved/n*100;return(0,a.jsxs)(`div`,{className:`group relative flex-1 min-w-[6px] max-w-[28px] h-full flex items-end`,children:[(0,a.jsx)(`div`,{className:`w-full ${fn(Object.entries(e.mechanisms_this_turn).sort(([,e],[,t])=>t-e)[0]?.[0]??`graph_query`).bar} opacity-70 hover:opacity-100 rounded-t transition-all cursor-pointer`,style:{height:`${Math.max(4,r)}%`},onClick:()=>t(e.turn)}),(0,a.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 hidden group-hover:block z-20 pointer-events-none`,children:(0,a.jsxs)(`div`,{className:`bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-xs whitespace-nowrap shadow-xl`,children:[(0,a.jsxs)(`div`,{className:`font-medium text-foreground`,children:[`Turn #`,e.turn]}),(0,a.jsx)(`div`,{className:`t-tertiary mt-0.5`,children:e.tools.join(`, `)||`exec`}),(0,a.jsxs)(`div`,{className:`text-success mt-1`,children:[`+`,I(e.tokens_saved_this_turn),` this turn`]}),(0,a.jsxs)(`div`,{className:`t-secondary`,children:[`Cumulative: `,I(e.cumulative_tokens_saved)]}),(0,a.jsxs)(`div`,{className:`text-cyan-400 mt-0.5`,children:[`Context avoided: `,I(e.context_avoided)]}),(0,a.jsx)(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:Object.keys(e.mechanisms_this_turn).map(e=>(0,a.jsx)(_n,{mechanism:e},e))})]})})]},e.turn)})}),(0,a.jsxs)(`div`,{className:`flex justify-between mt-1.5`,children:[(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] font-mono`,children:[`T`,l.length>60?l.length-59:1]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] font-mono`,children:[`T`,l.length]})]}),(0,a.jsx)(`div`,{className:`flex flex-wrap gap-3 mt-3 pt-3 border-t border-border-subtle/50`,children:ln.filter(e=>l.some(t=>e in t.mechanisms_this_turn)).map(e=>(0,a.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,a.jsx)(`div`,{className:`h-2.5 w-2.5 rounded-sm ${fn(e).bar}`}),(0,a.jsx)(`span`,{className:`t-tertiary text-[10px]`,children:e.replace(/_/g,` `)})]},e))})]})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:`Savings by Mechanism`}),(0,a.jsx)(gn,{mechanisms:c.by_mechanism,totalSaved:c.total_tokens_saved})]})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Turns`}),(0,a.jsx)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:`Click a turn to see all events and mechanisms within it.`})]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[f.length,` turn`,f.length===1?``:`s`]})]}),p.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No turns recorded.`}):(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[800px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-2.5 font-medium w-14`,title:`Turn number in the conversation`,children:`Turn`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Summary of what happened in this turn`,children:`Description`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium w-36`,title:`Relative savings compared to the largest turn — wider bar means more tokens saved`,children:`Savings Bar`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium`,title:`Types of optimization applied in this turn`,children:`Mechanisms`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Tokens removed from responses in this turn (direct savings)`,children:`Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Cumulative tokens of context avoided at this point — prior savings carry forward, keeping context smaller for this and future turns`,children:`Context Avoided`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 font-medium text-right`,title:`Number of optimization events in this turn`,children:`Events`}),(0,a.jsx)(`th`,{className:`px-3 py-2.5 pr-5 font-medium w-16`})]})}),(0,a.jsx)(`tbody`,{children:p.map(([e,n])=>{let r=n.reduce((e,t)=>e+t.tokens_saved,0),i=[...new Set(n.map(e=>e.mechanism))],{label:o,subtitle:s}=mn(n),c=h.get(e);return(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors cursor-pointer group`,onClick:()=>t(e),children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,children:(0,a.jsxs)(`span`,{className:`t-tertiary font-mono text-xs group-hover:text-violet-400 transition-colors`,children:[`#`,e]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsxs)(`div`,{className:`min-w-0 max-w-[260px]`,children:[(0,a.jsx)(`p`,{className:`text-foreground font-mono text-xs truncate group-hover:text-violet-300 transition-colors`,children:o}),s&&(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] mt-0.5 truncate`,children:s})]})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(`div`,{className:`w-32 h-4 relative rounded-sm bg-surface-secondary overflow-hidden`,children:(()=>{let e=new Map;for(let t of n)e.set(t.mechanism,(e.get(t.mechanism)??0)+t.tokens_saved);let t=0;return[...e.entries()].sort(([,e],[,t])=>t-e).map(([e,n])=>{let r=m>0?n/m*100:0,i=t;return t+=r,(0,a.jsx)(`div`,{className:`absolute inset-y-0 ${fn(e).bar} opacity-80`,style:{left:`${i}%`,width:`${Math.max(1,r)}%`}},e)})})()})}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:i.map(e=>(0,a.jsx)(_n,{mechanism:e},e))})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(r)})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:c?(0,a.jsx)(`span`,{className:`text-cyan-400 font-mono font-medium text-xs`,title:`${I(c.context_avoided)} tokens of cumulative context avoided at turn #${e}`,children:I(c.context_avoided)}):(0,a.jsx)(`span`,{className:`t-tertiary font-mono text-xs`,children:`—`})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right`,children:(0,a.jsx)(`span`,{className:`t-tertiary text-xs`,children:n.length})}),(0,a.jsx)(`td`,{className:`pl-4 py-3 pr-5 text-right w-16`,children:(0,a.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-violet-400 opacity-0 group-hover:opacity-100 transition-opacity font-medium whitespace-nowrap`,children:[`View `,(0,a.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M9 5l7 7-7 7`})})]})})]},e)})})]})}),(0,a.jsx)(kn,{total:f.length,limit:20,offset:n*20,onPageChange:e=>r(Math.floor(e/20))})]})]})}function Mn({sessionId:e,turn:t}){let n=N({queryKey:[`token-flow-events`,e,t],queryFn:()=>F(`/api/token-flow/events?session_id=${e}&turn=${t}`)}),r=N({queryKey:[`token-flow-cumulative`,e],queryFn:()=>F(`/api/token-flow/cumulative?session_id=${e}`)}),i=r.data?.data?.find(e=>e.turn===t),o=r.data?.total_turns??0,s=o>0?o-(r.data?.data?.findIndex(e=>e.turn===t)??0)-1:0,c=n.data?.data??[],[l,u]=(0,M.useState)(0),d=c.slice(l,l+20),f=c.reduce((e,t)=>e+t.tokens_saved,0),p=c.reduce((e,t)=>e+t.tokens_without,0),m=c.reduce((e,t)=>e+t.tokens_with,0),h=[...new Set(c.map(e=>e.tool).filter(Boolean))],g=p>0?Math.round(f/p*100):0,_={};for(let e of c){let t=_[e.mechanism]??{tokens_saved:0,tokens_delivered:0,event_count:0,pct_of_total:0};t.tokens_saved+=e.tokens_saved,t.tokens_delivered+=e.tokens_with,t.event_count++,_[e.mechanism]=t}for(let e of Object.values(_))e.pct_of_total=f>0?Math.round(e.tokens_saved/f*100):0;return n.isLoading?(0,a.jsx)(mt,{n:4}):(0,a.jsxs)(`div`,{className:`space-y-6`,children:[(()=>{let{label:e,subtitle:t}=mn(c);return(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-4 border-l-4 border-violet-500/60`,children:[(0,a.jsx)(`p`,{className:`text-foreground font-mono text-sm font-medium`,children:e}),t&&(0,a.jsx)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:t})]})})(),(0,a.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 lg:grid-cols-5`,children:[(0,a.jsx)(hn,{label:`Tokens Saved`,value:I(f),accent:`text-success`,hint:`Tokens removed in this turn`}),(0,a.jsx)(hn,{label:`Without unerr`,value:I(p),hint:`Tokens that would have been sent without optimization`}),(0,a.jsx)(hn,{label:`Delivered`,value:I(m),hint:`Tokens actually sent to the agent`}),(0,a.jsx)(hn,{label:`Efficiency`,value:`${g}%`,accent:`text-violet-400`,hint:`Percentage of tokens optimized away this turn`}),(0,a.jsx)(hn,{label:`Tools`,value:h.join(`, `)||`exec`,hint:`MCP tools that triggered optimizations in this turn`})]}),i&&(0,a.jsx)(`div`,{className:`el-raised rounded-lg p-4 border-l-4 border-cyan-500/60`,children:(0,a.jsxs)(`div`,{className:`flex items-center justify-between gap-4 flex-wrap`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`text-foreground text-sm font-medium`,children:`Context Impact`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-1`,children:[`At this point, `,I(i.context_avoided),` tokens of cumulative context avoided`,s>0?` — this turn's ${I(i.tokens_saved_this_turn)} savings carry forward to ${s} more turn${s===1?``:`s`}`:``,`.`]})]}),(0,a.jsxs)(`div`,{className:`flex gap-5 shrink-0`,children:[(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`This Turn`}),(0,a.jsx)(`p`,{className:`text-success font-mono font-medium`,children:I(i.tokens_saved_this_turn)})]}),(0,a.jsxs)(`div`,{className:`text-right`,children:[(0,a.jsx)(`p`,{className:`t-tertiary text-[10px] uppercase tracking-wider`,children:`Context Avoided`}),(0,a.jsx)(`p`,{className:`text-cyan-400 font-mono font-medium`,children:I(i.context_avoided)})]})]})]})}),Object.keys(_).length>0&&(0,a.jsxs)(`div`,{className:`el-raised rounded-lg p-5`,children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium mb-3`,children:`Mechanisms in this Turn`}),(0,a.jsx)(gn,{mechanisms:_,totalSaved:f})]}),(0,a.jsxs)(`div`,{className:`el-raised rounded-lg overflow-hidden`,children:[(0,a.jsxs)(`div`,{className:`px-5 py-3 border-b border-border-subtle flex items-center justify-between`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`t-secondary text-sm font-medium`,children:`Events`}),(0,a.jsxs)(`p`,{className:`t-tertiary text-xs mt-0.5`,children:[`Every optimization event in turn #`,t,`: tool calls, exec commands, and the mechanism that reduced tokens.`]})]}),(0,a.jsxs)(`span`,{className:`t-tertiary text-xs`,children:[c.length,` event`,c.length===1?``:`s`]})]}),c.length===0?(0,a.jsx)(`p`,{className:`px-5 py-6 t-secondary text-sm`,children:`No events for this turn.`}):(0,a.jsx)(`div`,{className:`overflow-x-auto`,children:(0,a.jsxs)(`table`,{className:`w-full text-left text-sm min-w-[900px]`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle t-tertiary text-xs uppercase`,children:[(0,a.jsx)(`th`,{className:`px-5 py-3 font-medium`,title:`When this optimization event occurred`,children:`Time`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium`,title:`Type of optimization applied (e.g. graph query, shell compression)`,children:`Mechanism`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium`,title:`MCP tool that triggered this optimization`,children:`Tool`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens that would have been sent without unerr`,children:`Without`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens actually delivered to the agent after optimization`,children:`Delivered`}),(0,a.jsx)(`th`,{className:`px-3 py-3 font-medium text-right`,title:`Tokens removed by this optimization (Without − Delivered)`,children:`Saved`}),(0,a.jsx)(`th`,{className:`px-3 py-3 pr-5 font-medium`,title:`Description of what was optimized`,children:`Detail`})]})}),(0,a.jsx)(`tbody`,{children:d.map(e=>{fn(e.mechanism);let t=e.tokens_without>0?Math.round(e.tokens_saved/e.tokens_without*100):0;return(0,a.jsxs)(`tr`,{className:`border-b border-border-subtle hover:bg-surface-secondary transition-colors`,children:[(0,a.jsx)(`td`,{className:`t-tertiary px-5 py-3 font-mono text-xs whitespace-nowrap`,children:dn(e.ts)}),(0,a.jsx)(`td`,{className:`px-3 py-3`,children:(0,a.jsx)(_n,{mechanism:e.mechanism})}),(0,a.jsx)(`td`,{className:`t-secondary px-3 py-3 font-mono text-xs whitespace-nowrap`,children:e.tool??`—`}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums whitespace-nowrap`,children:I(e.tokens_without)}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums whitespace-nowrap`,children:I(e.tokens_with)}),(0,a.jsxs)(`td`,{className:`px-3 py-3 text-right whitespace-nowrap`,children:[(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(e.tokens_saved)}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] ml-1`,children:[`(`,t,`%)`]})]}),(0,a.jsx)(`td`,{className:`px-3 py-3 pr-5 font-mono text-xs max-w-[400px]`,children:(0,a.jsx)(`span`,{className:`t-secondary break-words leading-relaxed`,children:pn(e)})})]},e.id)})}),(0,a.jsx)(`tfoot`,{children:(0,a.jsxs)(`tr`,{className:`border-t border-border-subtle font-medium bg-surface-secondary/30`,children:[(0,a.jsx)(`td`,{className:`px-5 py-3`,colSpan:3,children:(0,a.jsx)(`span`,{className:`t-secondary text-xs uppercase tracking-wider`,children:`Turn Total`})}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums`,children:I(p)}),(0,a.jsx)(`td`,{className:`px-3 py-3 text-right font-mono text-xs tabular-nums`,children:I(m)}),(0,a.jsxs)(`td`,{className:`px-3 py-3 text-right`,children:[(0,a.jsx)(`span`,{className:`text-success font-mono font-medium text-xs`,children:I(f)}),(0,a.jsxs)(`span`,{className:`t-tertiary text-[10px] ml-1`,children:[`(`,g,`%)`]})]}),(0,a.jsx)(`td`,{})]})})]})}),(0,a.jsx)(`div`,{className:`px-5 py-2 border-t border-border-subtle`,children:(0,a.jsx)(kn,{total:c.length,limit:20,offset:l,onPageChange:u})})]})]})}function Nn(){let[e,t]=(0,M.useState)({level:`global`}),n=()=>t({level:`global`}),r=e=>t({level:`session`,sessionId:e}),i=(e,n)=>t({level:`turn`,sessionId:e,turn:n}),o=[];return(e.level===`session`||e.level===`turn`)&&o.push({label:`All Sessions`,onClick:n},{label:`Session ${e.sessionId.slice(0,12)}`,onClick:e.level===`turn`?()=>r(e.sessionId):void 0}),e.level===`turn`&&o.push({label:`Turn #${e.turn}`}),(0,a.jsxs)(`div`,{children:[o.length>0&&(0,a.jsx)(vn,{items:o}),e.level===`global`&&(0,a.jsx)(An,{onSelectSession:r}),e.level===`session`&&(0,a.jsx)(jn,{sessionId:e.sessionId,onSelectTurn:t=>i(e.sessionId,t)}),e.level===`turn`&&(0,a.jsx)(Mn,{sessionId:e.sessionId,turn:e.turn})]})}function Pn(){let e=N({queryKey:[`system`,`status`],queryFn:()=>F(`/api/system/status`)}),t=N({queryKey:[`system`,`config`],queryFn:()=>F(`/api/system/config`)}),n=e.data?.data,r=t.data?.data;return(0,a.jsxs)(`div`,{className:`flex flex-col gap-8 lg:flex-row`,children:[(0,a.jsxs)(`section`,{className:`flex-1 glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Proxy status`}),e.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,a.jsx)(P,{className:`h-4 w-full max-w-xs`}),(0,a.jsx)(P,{className:`h-4 w-full max-w-sm`}),(0,a.jsx)(P,{className:`h-4 w-full max-w-md`})]}):e.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not reach /api/system/status.`}):(0,a.jsxs)(`dl`,{className:`mt-4 space-y-3 text-sm`,children:[(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`State`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.status})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`PID`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.pid})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Uptime`}),(0,a.jsxs)(`dd`,{className:`font-mono text-xs text-foreground`,children:[n?.uptime_s,`s`]})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Dashboard port`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.dashboard_port})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`IDE`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-foreground`,children:n?.ide})]}),(0,a.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Working directory`}),(0,a.jsx)(`dd`,{className:`break-all font-mono text-xs t-secondary`,children:n?.cwd})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Graph entities`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-live`,children:n?.graph.entities})]}),(0,a.jsxs)(`div`,{className:`flex justify-between gap-4`,children:[(0,a.jsx)(`dt`,{className:`t-secondary`,children:`Session tool calls`}),(0,a.jsx)(`dd`,{className:`font-mono text-xs text-live`,children:n?.session.tool_calls})]})]})]}),(0,a.jsxs)(`section`,{className:`flex-1 glass-panel rounded-xl p-5`,children:[(0,a.jsx)(`h2`,{className:`section-label text-violet-500`,children:`Configuration`}),t.isLoading?(0,a.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[(0,a.jsx)(P,{className:`h-4 w-56`}),(0,a.jsx)(P,{className:`h-24 w-full`})]}):t.isError?(0,a.jsx)(`p`,{className:`mt-4 text-error text-sm`,children:`Could not load config.`}):(0,a.jsxs)(`div`,{className:`mt-4 space-y-5`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label`,children:`Installed skills`}),r?.skills_installed?.length?(0,a.jsx)(`ul`,{className:`mt-2 space-y-1 font-mono text-xs`,children:r.skills_installed.map(e=>(0,a.jsxs)(`li`,{className:`flex items-center gap-2`,children:[(0,a.jsx)(`span`,{className:`inline-block h-1 w-1 rounded-full bg-violet-500`}),(0,a.jsx)(`span`,{className:`text-foreground`,children:e})]},e))}):(0,a.jsx)(`p`,{className:`mt-2 t-secondary text-sm`,children:`None reported.`})]}),(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`h3`,{className:`section-label`,children:`Repo config (.unerr/config.json)`}),(0,a.jsx)(`pre`,{className:`mt-2 custom-scrollbar max-h-80 overflow-auto whitespace-pre-wrap rounded-lg el-substrate border border-border-subtle p-3 font-mono text-xs leading-relaxed t-secondary`,children:JSON.stringify(r?.repo_config??{},null,2)})]})]})]})]})}function Fn(){let e=ct(),[t,n]=(0,M.useState)(!1);(0,M.useEffect)(()=>ft(it,n),[]);let{data:r=[]}=N({queryKey:[`live-feed`],initialData:[]}),{data:i}=N({queryKey:[`session-snapshot`]}),o=ot(e),c;switch(e){case`overview`:c=(0,a.jsx)(Ct,{sseConnected:t,liveFeed:r,sessionSnapshot:i});break;case`visual`:c=(0,a.jsx)(Wt,{});break;case`graph`:c=(0,a.jsx)(wt,{});break;case`ledger`:c=(0,a.jsx)($t,{});break;case`facts`:c=(0,a.jsx)(Jt,{});break;case`session`:c=(0,a.jsx)(sn,{sessionSnapshot:i});break;case`token-flow`:c=(0,a.jsx)(Nn,{});break;case`settings`:c=(0,a.jsx)(Pn,{});break}return(0,a.jsx)(s,{title:o,activeRoute:e,statusDot:t?`live`:`reconnecting`,children:c})}var In=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,T());else{var t=n(l);t!==null&&ie(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-ee<w)}function ne(){if(g=!1,S){var t=e.unstable_now();ee=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ie(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?T():S=!1}}}var T;if(typeof y==`function`)T=function(){y(ne)};else if(typeof MessageChannel<`u`){var E=new MessageChannel,re=E.port2;E.port1.onmessage=ne,T=function(){re.postMessage(null)}}else T=function(){_(ne,0)};function ie(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,ie(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,T()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Ln=t(((e,t)=>{t.exports=In()})),Rn=t((e=>{var t=Be();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`);function o(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var s=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function c(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return o(e,t,null,r)},e.flushSync=function(e){var t=s.T,n=i.p;try{if(s.T=null,i.p=2,e)return e()}finally{s.T=t,i.p=n,i.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`)if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=c(t.as,t.crossOrigin);i.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??i.d.M(e)},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin);i.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`)if(t){var n=c(t.as,t.crossOrigin);i.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else i.d.m(e)},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return s.H.useFormState(e,t,n)},e.useFormStatus=function(){return s.H.useHostTransitionStatus()},e.version=`19.2.5`})),zn=t(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Rn()})),Bn=t((e=>{var t=Ln(),n=Be(),r=zn();function i(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function s(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function c(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(o(e)!==e)throw Error(i(188))}function u(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return l(a),e;if(s===r)return l(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,u=a.child;u;){if(u===n){c=!0,n=a,r=s;break}if(u===r){c=!0,r=a,n=s;break}u=u.sibling}if(!c){for(u=s.child;u;){if(u===n){c=!0,n=s,r=a;break}if(u===r){c=!0,r=s,n=a;break}u=u.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function d(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=d(e),t!==null)return t;e=e.sibling}return null}var f=Object.assign,p=Symbol.for(`react.element`),m=Symbol.for(`react.transitional.element`),h=Symbol.for(`react.portal`),g=Symbol.for(`react.fragment`),_=Symbol.for(`react.strict_mode`),v=Symbol.for(`react.profiler`),y=Symbol.for(`react.consumer`),b=Symbol.for(`react.context`),x=Symbol.for(`react.forward_ref`),S=Symbol.for(`react.suspense`),C=Symbol.for(`react.suspense_list`),w=Symbol.for(`react.memo`),ee=Symbol.for(`react.lazy`),te=Symbol.for(`react.activity`),ne=Symbol.for(`react.memo_cache_sentinel`),T=Symbol.iterator;function E(e){return typeof e!=`object`||!e?null:(e=T&&e[T]||e[`@@iterator`],typeof e==`function`?e:null)}var re=Symbol.for(`react.client.reference`);function ie(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===re?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case g:return`Fragment`;case v:return`Profiler`;case _:return`StrictMode`;case S:return`Suspense`;case C:return`SuspenseList`;case te:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case h:return`Portal`;case b:return e.displayName||`Context`;case y:return(e._context.displayName||`Context`)+`.Consumer`;case x:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case w:return t=e.displayName||null,t===null?ie(e.type)||`Memo`:t;case ee:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}var ae=Array.isArray,D=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,oe={pending:!1,data:null,method:null,action:null},se=[],ce=-1;function le(e){return{current:e}}function k(e){0>ce||(e.current=se[ce],se[ce]=null,ce--)}function A(e,t){ce++,se[ce]=e.current,e.current=t}var ue=le(null),de=le(null),j=le(null),fe=le(null);function pe(e,t){switch(A(j,t),A(de,e),A(ue,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Vd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Vd(t),e=Hd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}k(ue),A(ue,e)}function me(){k(ue),k(de),k(j)}function he(e){e.memoizedState!==null&&A(fe,e);var t=ue.current,n=Hd(t,e.type);t!==n&&(A(de,e),A(ue,n))}function ge(e){de.current===e&&(k(ue),k(de)),fe.current===e&&(k(fe),Qf._currentValue=oe)}var _e,ve;function ye(e){if(_e===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);_e=t&&t[1]||``,ve=-1<e.stack.indexOf(`
3
3
  at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
4
4
  `+_e+e+ve}var be=!1;function xe(e,t){if(!e||be)return``;be=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,`props`,{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,`name`,{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
5
5
  `),l=s.split(`
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>unerr — intelligence</title>
7
- <script type="module" crossorigin src="/assets/index-C0jcrEHE.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-Bi-binEM.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-jpDsebLB.js">
9
9
  <link rel="modulepreload" crossorigin href="/assets/vis-network-NIJHUFI3.js">
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-DvCs_BqT.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unerr-ai/unerr",
3
- "version": "0.0.0-beta.5",
3
+ "version": "0.0.0-beta.6",
4
4
  "description": "Local-first code intelligence CLI for unerr",
5
5
  "type": "module",
6
6
  "bin": {