pi-mega-compact 0.20.64 → 0.20.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +1 -1
  2. package/dist/config/vector-cortex-enc2b.js +36 -0
  3. package/dist/config/vector-cortex.js +2 -0
  4. package/dist/config.js +1 -1
  5. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +1 -0
  6. package/dist/extensions/dashboard-server/routes-setup-enc2b.js +77 -0
  7. package/dist/extensions/dashboard-server/routes-setup.js +39 -3
  8. package/dist/src/config/vector-cortex-enc2b.js +36 -0
  9. package/dist/src/config/vector-cortex.js +2 -0
  10. package/dist/src/config.js +1 -1
  11. package/dist/src/vector-cortex/encoder/native-qualify-retest.js +225 -0
  12. package/dist/vector-cortex/encoder/native-qualify-retest.js +225 -0
  13. package/extensions/dashboard-client/dist/assets/{AdminTab-sjV8P5A4.js → AdminTab-B31efZ_R.js} +2 -2
  14. package/extensions/dashboard-client/dist/assets/{AdminTab-sjV8P5A4.js.map → AdminTab-B31efZ_R.js.map} +1 -1
  15. package/extensions/dashboard-client/dist/assets/{AreaChart-C03yuld4.js → AreaChart-BpjHNUZm.js} +2 -2
  16. package/extensions/dashboard-client/dist/assets/{AreaChart-C03yuld4.js.map → AreaChart-BpjHNUZm.js.map} +1 -1
  17. package/extensions/dashboard-client/dist/assets/{BarChart-B9jtJ7ud.js → BarChart-CY2FndXC.js} +2 -2
  18. package/extensions/dashboard-client/dist/assets/{BarChart-B9jtJ7ud.js.map → BarChart-CY2FndXC.js.map} +1 -1
  19. package/extensions/dashboard-client/dist/assets/{CacheTab-B7Eh3qfp.js → CacheTab-kMSrMD3e.js} +2 -2
  20. package/extensions/dashboard-client/dist/assets/{CacheTab-B7Eh3qfp.js.map → CacheTab-kMSrMD3e.js.map} +1 -1
  21. package/extensions/dashboard-client/dist/assets/{ConfigTab-DDTqosv2.js → ConfigTab-BrKpv2YG.js} +2 -2
  22. package/extensions/dashboard-client/dist/assets/{ConfigTab-DDTqosv2.js.map → ConfigTab-BrKpv2YG.js.map} +1 -1
  23. package/extensions/dashboard-client/dist/assets/{EventsTab-BmyQGmUa.js → EventsTab-DaClreCm.js} +2 -2
  24. package/extensions/dashboard-client/dist/assets/{EventsTab-BmyQGmUa.js.map → EventsTab-DaClreCm.js.map} +1 -1
  25. package/extensions/dashboard-client/dist/assets/{HealthTab-DzPqNqpm.js → HealthTab-CxKQDqF3.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{HealthTab-DzPqNqpm.js.map → HealthTab-CxKQDqF3.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-6g3d-M1p.js → MaintenanceTab-BKSlSjv0.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-6g3d-M1p.js.map → MaintenanceTab-BKSlSjv0.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-Nk2yYPMS.js → MemoryMapTab-C2goWDt8.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-Nk2yYPMS.js.map → MemoryMapTab-C2goWDt8.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{MetricsCards-BlIiuZp5.js → MetricsCards-DCPuCnrw.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{MetricsCards-BlIiuZp5.js.map → MetricsCards-DCPuCnrw.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/MetricsTab-Bz0Mdyb_.js +2 -0
  34. package/extensions/dashboard-client/dist/assets/{MetricsTab-DfRDIAEU.js.map → MetricsTab-Bz0Mdyb_.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{OverviewTab-xkuFE5GV.js → OverviewTab-B-eZ-eDR.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{OverviewTab-xkuFE5GV.js.map → OverviewTab-B-eZ-eDR.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{ReposTab-C6qZmmgQ.js → ReposTab-W_NKRWpk.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{ReposTab-C6qZmmgQ.js.map → ReposTab-W_NKRWpk.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{SessionsTab-Bkd_In3n.js → SessionsTab-GYrtNt4_.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{SessionsTab-Bkd_In3n.js.map → SessionsTab-GYrtNt4_.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/SetupTab-_1xa6eTJ.js +3 -0
  42. package/extensions/dashboard-client/dist/assets/SetupTab-_1xa6eTJ.js.map +1 -0
  43. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dr0KNUed.js → TimeSavedCard-Ciu8anVG.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dr0KNUed.js.map → TimeSavedCard-Ciu8anVG.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{TurnMemoryView-CjmSiRQ_.js → TurnMemoryView-BhXLIjWr.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{TurnMemoryView-CjmSiRQ_.js.map → TurnMemoryView-BhXLIjWr.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/TurnsTab-C-f3DggL.js +2 -0
  48. package/extensions/dashboard-client/dist/assets/{TurnsTab-JsDstDDA.js.map → TurnsTab-C-f3DggL.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-C96wfemg.js → VcStatusBadge-D97V04WE.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-C96wfemg.js.map → VcStatusBadge-D97V04WE.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-DGV3kA7X.js → VectorCortexTab-cyDJPAPB.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-DGV3kA7X.js.map → VectorCortexTab-cyDJPAPB.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{WikiTab-EFfy5v-D.js → WikiTab-dQ96DyjP.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{WikiTab-EFfy5v-D.js.map → WikiTab-dQ96DyjP.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{button-CvaPx9Bu.js → button-B1beLEiV.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{button-CvaPx9Bu.js.map → button-B1beLEiV.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{card-Crs5SwRQ.js → card-CK9KH_ob.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{card-Crs5SwRQ.js.map → card-CK9KH_ob.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{client-extra-Bd27WKSo.js → client-extra-gN7xjggX.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{client-extra-Bd27WKSo.js.map → client-extra-gN7xjggX.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-qnHql9Es.js → generateCategoricalChart-MB2_0u55.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-qnHql9Es.js.map → generateCategoricalChart-MB2_0u55.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{index-B4twCFnn.js → index-CKVd_Ym_.js} +3 -3
  64. package/extensions/dashboard-client/dist/assets/{index-B4twCFnn.js.map → index-CKVd_Ym_.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/{switch-BXutQI5d.js → switch-CswmYrO_.js} +2 -2
  66. package/extensions/dashboard-client/dist/assets/{switch-BXutQI5d.js.map → switch-CswmYrO_.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{toggle-uE-OSaba.js → toggle-CMepFsf0.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{toggle-uE-OSaba.js.map → toggle-CMepFsf0.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{useSSE-BRgPAqeS.js → useSSE-Bl55LQFZ.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{useSSE-BRgPAqeS.js.map → useSSE-Bl55LQFZ.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/index.html +1 -1
  72. package/extensions/dashboard-client/src/tabs/SetupTab/CortexRetestCard.tsx +104 -0
  73. package/extensions/dashboard-client/src/tabs/SetupTab/CortexSetup.tsx +2 -0
  74. package/extensions/dashboard-server/api-contracts/setup.ts +30 -0
  75. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +6 -0
  76. package/extensions/dashboard-server/routes-setup-enc2b.ts +82 -0
  77. package/extensions/dashboard-server/routes-setup.ts +39 -3
  78. package/package.json +1 -1
  79. package/src/config/vector-cortex-enc2b.ts +38 -0
  80. package/src/config/vector-cortex.ts +2 -0
  81. package/src/config.ts +1 -0
  82. package/src/vector-cortex/encoder/native-qualify-retest.ts +264 -0
  83. package/extensions/dashboard-client/dist/assets/MetricsTab-DfRDIAEU.js +0 -2
  84. package/extensions/dashboard-client/dist/assets/SetupTab-CEXL71VP.js +0 -3
  85. package/extensions/dashboard-client/dist/assets/SetupTab-CEXL71VP.js.map +0 -1
  86. package/extensions/dashboard-client/dist/assets/TurnsTab-JsDstDDA.js +0 -2
@@ -0,0 +1,82 @@
1
+ /**
2
+ * dashboard-server/routes-setup-enc2b.ts — ENC-2b native onnxruntime
3
+ * qualification retest (reader-only probe) + POST retest action.
4
+ *
5
+ * Extracted out of routes-setup.ts (which hovers at the 300-line source soft
6
+ * cap, mirroring the ENC-1b/ENC-2a sibling extracts) so the ENC-2b additive
7
+ * GET field — the native qualification retest result + effective backend —
8
+ * lives in a sibling impl file and routes-setup.ts stays a thin host.
9
+ *
10
+ * The retest's job is RE-QUALIFICATION: when the operator installed
11
+ * onnxruntime-node via the ENC-2a guide, the encoder read path does not
12
+ * automatically re-evaluate the qualification verdict. This sibling surface
13
+ * runs `runNativeRetest` (a bounded, reader-only, local probe) and:
14
+ *
15
+ * - surfaces `nativeOrtRetestResult` + `nativeOrtBackendEffective` on the GET
16
+ * when the flag is on AND a binding is installed — absent otherwise
17
+ * (byte-identical to the ENC-2a-era shape on flag-off/none);
18
+ * - handles the POST `nativeOrtRetest` key (`false` → 400
19
+ * `retest_rejected_false_nothing_to_do`; `true` → run + echo the fresh
20
+ * result; flag-off → the key is unrecognized, byte-identical predecessor).
21
+ *
22
+ * `nativeOrtBackendEffective` is `"native"` only when the retest verdict is
23
+ * `qualified`; any `degraded`/`failed` verdict keeps the backend `"wasm"` — the
24
+ * runtime never silently switches to a backend whose retest failed.
25
+ *
26
+ * Guardrails: PREVENT-PI-004 (local filesystem + in-process binding load only,
27
+ * zero network — the retest NEVER fetches), PREVENT-011 (no `any`).
28
+ */
29
+
30
+ import { ENC_2B_ENABLED } from "../../src/config/vector-cortex.js";
31
+ import {
32
+ runNativeRetest,
33
+ type RetestResult,
34
+ } from "../../src/vector-cortex/encoder/native-qualify-retest.js";
35
+ import type { SetupConfigureRequest } from "./api-contracts/setup.js";
36
+
37
+ /**
38
+ * Resolve the ENC-2b additive GET fields. Returns BOTH fields when the flag is
39
+ * on AND a native binding is installed (the retest ran); returns `{}` on
40
+ * flag-off AND when no binding is installed — both fields are OMITTED (absent,
41
+ * not null), so the GET stays byte-identical to the ENC-2a-era shape and the
42
+ * client hides the retest card. Flag-off omits, never nulls: the ENC-2a-era
43
+ * host spreads `...{}` so no new key appears. Mirror of the ENC-2a/ENC-1b
44
+ * sibling idiom; async because the retest loads the binding in-process.
45
+ */
46
+ export async function readEnc2bRetest(stateDir: string): Promise<{
47
+ nativeOrtRetestResult?: RetestResult;
48
+ nativeOrtBackendEffective?: "native" | "wasm";
49
+ }> {
50
+ if (!ENC_2B_ENABLED()) return {};
51
+ const result = await runNativeRetest(stateDir);
52
+ if (result === null) return {};
53
+ return {
54
+ nativeOrtRetestResult: result,
55
+ nativeOrtBackendEffective: result.verdict === "qualified" ? "native" : "wasm",
56
+ };
57
+ }
58
+
59
+ /**
60
+ * ENC-2b POST retest-action key handling (flag-gated, additive).
61
+ *
62
+ * `true` → { action: "run" } (the host runs the retest and returns the result)
63
+ * `false` → { action: "reject" } (400 `retest_rejected_false_nothing_to_do`)
64
+ * other → null (key absent or flag off — falls through unrecognized,
65
+ * byte-identical ENC-2a-era predecessor).
66
+ */
67
+ export function enc2bRetestRequest(body: SetupConfigureRequest): "run" | "reject" | null {
68
+ if (!ENC_2B_ENABLED()) return null;
69
+ if (body.nativeOrtRetest === true) return "run";
70
+ if (body.nativeOrtRetest === false) return "reject";
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * Run the ENC-2b retest now (bounded, synchronous on the request) and return
76
+ * the fresh result. Flag-off or no binding → null. Used by the POST "run"
77
+ * branch; the result is returned on the response body, never persisted.
78
+ */
79
+ export async function runEnc2bRetest(stateDir: string): Promise<RetestResult | null> {
80
+ if (!ENC_2B_ENABLED()) return null;
81
+ return runNativeRetest(stateDir);
82
+ }
@@ -22,6 +22,7 @@ import {
22
22
  enc2BudgetValidateCombined,
23
23
  } from "./routes-setup-enc2budget.js";
24
24
  import { readEnc2aGuide, enc2aGuideRequest } from "./routes-setup-enc2a.js";
25
+ import { readEnc2bRetest, enc2bRetestRequest, runEnc2bRetest } from "./routes-setup-enc2b.js";
25
26
  import { writeEmbedderEnv } from "./routes-setup-env-upsert.js";
26
27
  import {
27
28
  detectOllama,
@@ -94,7 +95,7 @@ export function handleSetupStatus(
94
95
  // ENC-1a (flag-gated, additive): echo the persisted endpoint URL and an
95
96
  // embeddingApiKeySet boolean ONLY — the raw API key is never returned. When
96
97
  // the flag is off (or neither is set) both fields are simply omitted.
97
- const body: SetupStatusResponse = {
98
+ const base: SetupStatusResponse = {
98
99
  currentEmbedder: active,
99
100
  configuredEmbedder: configured.embedder,
100
101
  configuredUrl: configured.url,
@@ -109,9 +110,20 @@ export function handleSetupStatus(
109
110
  ...(enc2a.guide !== null ? { nativeOrtInstallGuide: enc2a.guide } : {}),
110
111
  ...(enc2a.installedVersion !== null ? { nativeOrtInstalledVersion: enc2a.installedVersion } : {}),
111
112
  };
113
+ // ENC-2b (flag-gated, additive): the native qualification retest fields. The
114
+ // retest loads the on-disk binding in-process (bounded, never a fetch), so
115
+ // readEnc2bRetest is async; the handler returns true synchronously for the
116
+ // dispatch and writes the response after the await. Flag-off/none mutates
117
+ // the body additively and stays byte-identical to the ENC-2a-era shape.
112
118
  // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
113
- res.writeHead(200, { "Content-Type": "application/json" });
114
- res.end(JSON.stringify(body));
119
+ readEnc2bRetest(ctx.stateDir).then((enc2b) => {
120
+ const body: SetupStatusResponse = { ...base, ...enc2b };
121
+ res.writeHead(200, { "Content-Type": "application/json" });
122
+ res.end(JSON.stringify(body));
123
+ }).catch(() => {
124
+ res.writeHead(200, { "Content-Type": "application/json" });
125
+ res.end(JSON.stringify(base));
126
+ });
115
127
  return true;
116
128
  }
117
129
 
@@ -248,6 +260,30 @@ export function handleSetupConfigure(
248
260
  res.end(JSON.stringify({ nativeOrtInstallGuide: readEnc2aGuide(ctx.stateDir).guide }));
249
261
  return;
250
262
  }
263
+ // ENC-2b retest-action key (flag-gated, additive): `false` → 400 (an
264
+ // operator-driven no-op — nothing to retest), `true` → run the bounded
265
+ // retest synchronously and return the fresh result. Flag-off: the key
266
+ // falls through unrecognized (byte-identical ENC-2a-era predecessor).
267
+ // The retest never fetches — the binding is on disk from the ENC-2a
268
+ // install (PREVENT-PI-004 clean).
269
+ const retestReq = enc2bRetestRequest(body);
270
+ // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
271
+ if (retestReq === "reject") {
272
+ res.writeHead(400, { "Content-Type": "application/json" });
273
+ res.end(JSON.stringify({ error: "retest_rejected_false_nothing_to_do" }));
274
+ return;
275
+ }
276
+ if (retestReq === "run") {
277
+ // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
278
+ runEnc2bRetest(ctx.stateDir).then((fresh) => {
279
+ res.writeHead(200, { "Content-Type": "application/json" });
280
+ res.end(JSON.stringify({ nativeOrtRetestResult: fresh }));
281
+ }).catch(() => {
282
+ res.writeHead(500, { "Content-Type": "application/json" });
283
+ res.end(JSON.stringify({ error: "retest_failed" }));
284
+ });
285
+ return;
286
+ }
251
287
  if (tryEnc1aConfigure(body, res, ctx)) return;
252
288
  if (tryEnc1bConfigure(body, res, ctx)) return; // pure ENC-1b configure (dim/headers/allow-remote/native)
253
289
  // ENC-1b combined-payload validation: when a payload carries a valid
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.20.64",
3
+ "version": "0.20.65",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -0,0 +1,38 @@
1
+ /**
2
+ * config/vector-cortex-enc2b.ts — ENC-2b native onnxruntime qualification
3
+ * retest flag.
4
+ *
5
+ * Sibling of vector-cortex-enc2a.ts / vector-cortex-enc2budget.ts so
6
+ * vector-cortex.ts stays under the 300-line soft limit (soft-as-hard gate).
7
+ * vector-cortex.ts re-exports the flag below and root src/config.ts re-exports
8
+ * it, so no consumer import path changes.
9
+ *
10
+ * ENC-2b re-probes and re-qualifies the installed native onnxruntime binding
11
+ * (`onnxruntime-node` in `~/.pi/mega-compact/native-ort/`, operator-installed
12
+ * via the ENC-2a guide). When the operator installs the binding the read path
13
+ * does not automatically re-evaluate the qualification verdict; this sprint
14
+ * delivers a reader-only retest that loads the LOCAL on-disk binding, runs a
15
+ * bounded warmup + p95 probe against it, measures RSS, computes a fresh
16
+ * qualification verdict against the ENC-0f p95 budget + the operator
17
+ * install-budget, and surfaces it on the Setup Cortex sub-tab and the GET
18
+ * `/api/setup-status` response.
19
+ *
20
+ * `MEGACOMPACT_ENC_2B=0` disables: the GET omits both new retest fields, the
21
+ * POST ignores the retest-request key, the Cortex sub-tab renders no retest
22
+ * card — byte-identical to the ENC-2a predecessor. The flag MUST also be a
23
+ * dashboard SETTINGS toggle (visible in config UI, never in EXCLUDED_SETTINGS
24
+ * — see `feedback_dashboard-flags-toggleable` memory).
25
+ *
26
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 / PREVENT-011).
27
+ */
28
+
29
+ import { sprintFlag } from "./vector-cortex-flag.js";
30
+
31
+ /**
32
+ * ENC-2b — native onnxruntime qualification retest (detect installed binding,
33
+ * re-probe p95/RSS, re-qualify). Default ON. `MEGACOMPACT_ENC_2B=0` disables and
34
+ * is byte-identical to the ENC-2a predecessor: no retest GET fields, no retest
35
+ * POST branch, no retest card. This flag MUST also be a dashboard SETTINGS
36
+ * toggle (visible in config UI, never in EXCLUDED_SETTINGS).
37
+ */
38
+ export const ENC_2B_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_ENC_2B");
@@ -94,6 +94,8 @@ export {
94
94
  } from "./vector-cortex-enc2budget.js";
95
95
  // ENC-2a native onnxruntime install-guide flag extracted to vector-cortex-enc2a.ts.
96
96
  export { ENC_2A_ENABLED } from "./vector-cortex-enc2a.js";
97
+ // ENC-2b native onnxruntime qualification-retest flag extracted to vector-cortex-enc2b.ts.
98
+ export { ENC_2B_ENABLED } from "./vector-cortex-enc2b.js";
97
99
  // Breaker constants (TRIAD_RESILIENCE.md §breaker) extracted to vector-cortex-breakers.ts.
98
100
  export {
99
101
  BREAKER_WINDOW_MS,
package/src/config.ts CHANGED
@@ -203,6 +203,7 @@ export {
203
203
  ENC_2BUDGET_MAX_MIB,
204
204
  ENC_2BUDGET_DEFAULT_MIB,
205
205
  ENC_2A_ENABLED,
206
+ ENC_2B_ENABLED,
206
207
  COSINE_FP_BENCH_ENABLED,
207
208
  COSINE_FP_REAL_ENABLED,
208
209
  REPO_CORPUS_ENABLED,
@@ -0,0 +1,264 @@
1
+ /**
2
+ * vector-cortex/encoder/native-qualify-retest.ts — ENC-2b native onnxruntime
3
+ * qualification retest (reader-only probe).
4
+ *
5
+ * When an operator installs onnxruntime-node via the ENC-2a guide, the encoder
6
+ * read path does not automatically re-evaluate the qualification verdict — the
7
+ * encoder still reports encoderBackend "wasm" until a retest runs. This module
8
+ * is that retest: a pure, bounded, reader-only probe that
9
+ *
10
+ * (a) resolves the installed binding `<native-ort>/node_modules/onnxruntime-node/`;
11
+ * (b) reads its `package.json` version;
12
+ * (c) dynamic-imports the binding;
13
+ * (d) finds a LOCAL onnx model to probe against (under `~/.pi/mega-compact/`);
14
+ * (e) runs a bounded warmup (3 passes) + 10 timed inference passes on a fixed
15
+ * 512-token synthetic input (the bench-onnx.mjs harness shape, in-process);
16
+ * (f) measures p95 (sorted index) and RSS (`process.memoryUsage().rss`);
17
+ * (g) computes a fresh qualification verdict against the ENC-0f p95 budget
18
+ * (`ENCODER_LATENCY_P95_MS`) and the operator install-budget
19
+ * (`installBudgetMib()` as the RSS ceiling — the ENC-2budget derivative).
20
+ *
21
+ * Results: `{platform, version, verdict: "qualified"|"degraded"|"failed",
22
+ * p95Ms, rssMiB, testedAt}` or `null` when no binding is installed. It NEVER
23
+ * throws into the route layer: every binding-load/session/model failure is
24
+ * caught and reported as a `failed` verdict with the error message surfaced in
25
+ * the engine, never raised. NO network (PREVENT-PI-004 — the binding + model
26
+ * are on disk from the operator's ENC-2a install), NO training (HG-1 unchanged).
27
+ *
28
+ * Pi-agnostic, dependency-free. No `any` (PREVENT-011).
29
+ */
30
+
31
+ import { readFileSync, existsSync } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { ENCODER_LATENCY_P95_MS, ENCODER_MAX_TOKENS } from "./types.js";
34
+ import { installBudgetMib } from "./decision.js";
35
+ import { detectPlatform } from "./asset.js";
36
+ import { NATIVE_ORT_PACKAGE, type EncoderPlatform } from "./native-install-artifacts.js";
37
+
38
+ /** Candidate ONNX runtime native-ort prefixes. The ENC-2a guide installs to
39
+ * the global `~/.pi/mega-compact/native-ort/`; `stateDir` (per-repo) is a
40
+ * secondary probe root so the retest resolves either install location. */
41
+ function nativeOrtRootCandidates(stateDir: string): string[] {
42
+ return [
43
+ join(process.env.HOME ?? "", ".pi", "mega-compact", "native-ort"),
44
+ join(stateDir, "native-ort"),
45
+ ];
46
+ }
47
+
48
+ /** A single bounded inference pass on the fixed 512-token synthetic input;
49
+ * returns latency ms, or null when the session cannot run (caller reports
50
+ * failed). The input mirrors bench-onnx.mjs: batch 1, 512 int64 ids. */
51
+ async function timedPass(
52
+ ort: unknown,
53
+ session: unknown,
54
+ ids: BigInt64Array,
55
+ mask: BigInt64Array,
56
+ types: BigInt64Array,
57
+ ): Promise<number | null> {
58
+ try {
59
+ const dims = [1, ENCODER_MAX_TOKENS];
60
+ const o = ort as {
61
+ Tensor: new (type: string, data: BigInt64Array, dims: number[]) => unknown;
62
+ };
63
+ const s = session as {
64
+ inputNames: readonly string[];
65
+ run: (feeds: Record<string, unknown>) => Promise<unknown>;
66
+ };
67
+ const feeds: Record<string, unknown> = {};
68
+ if (s.inputNames.includes("input_ids")) {
69
+ feeds.input_ids = new o.Tensor("int64", ids, dims);
70
+ }
71
+ if (s.inputNames.includes("attention_mask")) {
72
+ feeds.attention_mask = new o.Tensor("int64", mask, dims);
73
+ }
74
+ if (s.inputNames.includes("token_type_ids")) {
75
+ feeds.token_type_ids = new o.Tensor("int64", types, dims);
76
+ }
77
+ const t = process.hrtime.bigint();
78
+ await s.run(feeds);
79
+ return Number(process.hrtime.bigint() - t) / 1e6;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /** The retest verdict covering the ENC-0f p95 budget + the RSS ceiling. */
86
+ export type RetestVerdict = "qualified" | "degraded" | "failed";
87
+
88
+ /** The ENC-2b retest result surfaced on the GET read path + retest card. */
89
+ export interface RetestResult {
90
+ readonly platform: string;
91
+ readonly version: string;
92
+ readonly verdict: RetestVerdict;
93
+ readonly p95Ms: number;
94
+ readonly rssMiB: number;
95
+ readonly testedAt: string;
96
+ }
97
+
98
+ /** Resolve the first existing installed-binding package root, or the first
99
+ * candidate's path (for a missing-binding probe) when none exists. */
100
+ function bindingRootDir(stateDir: string): string {
101
+ for (const root of nativeOrtRootCandidates(stateDir)) {
102
+ const pkg = join(root, "node_modules", NATIVE_ORT_PACKAGE);
103
+ if (existsSync(pkg)) return pkg;
104
+ }
105
+ return join(nativeOrtRootCandidates(stateDir)[0], "node_modules", NATIVE_ORT_PACKAGE);
106
+ }
107
+
108
+ /** Read the installed binding version from its package.json; null when absent. */
109
+ function readInstalledVersion(pkgJsonPath: string): string | null {
110
+ try {
111
+ const raw = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as unknown;
112
+ if (
113
+ typeof raw === "object" &&
114
+ raw !== null &&
115
+ typeof (raw as { version?: unknown }).version === "string"
116
+ ) {
117
+ return (raw as { version: string }).version;
118
+ }
119
+ return null;
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ /** Locate a LOCAL onnx model to probe against, under the native-ort roots.
126
+ * Null when none exists (the retest cannot qualify without a probe target). */
127
+ function findLocalModel(stateDir: string): string | null {
128
+ const candidates = [
129
+ join(nativeOrtRootCandidates(stateDir)[0], "model.onnx"),
130
+ join(stateDir, "model.onnx"),
131
+ ];
132
+ for (const c of candidates) {
133
+ if (existsSync(c)) return c;
134
+ }
135
+ return null;
136
+ }
137
+
138
+ /** p95 of sorted latencies (sorted-index percentile, bench-onnx idiom). */
139
+ function p95Of(sorted: number[]): number {
140
+ if (sorted.length === 0) return 0;
141
+ const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95));
142
+ return +sorted[idx].toFixed(2);
143
+ }
144
+
145
+ /**
146
+ * Run the native onnxruntime qualification retest. Returns `RetestResult` on a
147
+ * completed (pass/fail/degrade) probe, or `null` when no binding is installed.
148
+ * Never throws: binding-load / session / model failures produce a `failed`
149
+ * verdict with the message on the result, and the `testedAt`/RSS are filled.
150
+ */
151
+ export async function runNativeRetest(stateDir: string): Promise<RetestResult | null> {
152
+ const rootDir = bindingRootDir(stateDir);
153
+ const pkgJsonPath = join(rootDir, "package.json");
154
+ if (!existsSync(pkgJsonPath)) return null;
155
+
156
+ const version = readInstalledVersion(pkgJsonPath);
157
+ const platform: EncoderPlatform | null = detectPlatform();
158
+ const platformStr = platform ?? `${process.platform}-${process.arch}`;
159
+ const testedAt = new Date().toISOString();
160
+ const rssMiB = +((process.memoryUsage().rss / 1048576).toFixed(1));
161
+
162
+ // Binding present but version unreadable — report failed (never throw).
163
+ if (version === null) {
164
+ return {
165
+ platform: platformStr,
166
+ version: "unknown",
167
+ verdict: "failed",
168
+ p95Ms: 0,
169
+ rssMiB,
170
+ testedAt,
171
+ };
172
+ }
173
+
174
+ // Load the LOCAL binding via dynamic import. Load failure -> failed verdict.
175
+ let ort: unknown;
176
+ try {
177
+ ort = await import(join(rootDir, "lib", "index.js"));
178
+ } catch {
179
+ try {
180
+ ort = await import(join(rootDir, "dist", "ort.node.mjs"));
181
+ } catch {
182
+ return {
183
+ platform: platformStr,
184
+ version,
185
+ verdict: "failed",
186
+ p95Ms: 0,
187
+ rssMiB,
188
+ testedAt,
189
+ };
190
+ }
191
+ }
192
+
193
+ // Find a local probe model; without one the binding cannot be qualified.
194
+ const modelPath = findLocalModel(stateDir);
195
+ if (modelPath === null) {
196
+ return {
197
+ platform: platformStr,
198
+ version,
199
+ verdict: "failed",
200
+ p95Ms: 0,
201
+ rssMiB,
202
+ testedAt,
203
+ };
204
+ }
205
+
206
+ // Create the session (bounded); failure -> failed.
207
+ try {
208
+ const factory = ort as {
209
+ InferenceSession: {
210
+ create: (
211
+ path: string,
212
+ opts: { executionProviders: string[]; intraOpNumThreads: number; graphOptimizationLevel: string },
213
+ ) => Promise<unknown>;
214
+ };
215
+ };
216
+ const session = await factory.InferenceSession.create(modelPath, {
217
+ executionProviders: ["cpu"],
218
+ intraOpNumThreads: 4,
219
+ graphOptimizationLevel: "all",
220
+ });
221
+ const n = ENCODER_MAX_TOKENS;
222
+ const ids = BigInt64Array.from({ length: n }, (_, i) =>
223
+ BigInt(i === 0 ? 101 : i === n - 1 ? 102 : 2000 + (i % 500)),
224
+ );
225
+ const mask = BigInt64Array.from({ length: n }, () => 1n);
226
+ const types = new BigInt64Array(n);
227
+
228
+ // Bounded warmup (3 passes) + 10 timed passes.
229
+ for (let i = 0; i < 3; i++) await timedPass(ort, session, ids, mask, types);
230
+ const lat: number[] = [];
231
+ for (let i = 0; i < 10; i++) {
232
+ const ms = await timedPass(ort, session, ids, mask, types);
233
+ if (ms === null) break;
234
+ lat.push(ms);
235
+ }
236
+ if (lat.length === 0) {
237
+ return {
238
+ platform: platformStr,
239
+ version,
240
+ verdict: "failed",
241
+ p95Ms: 0,
242
+ rssMiB,
243
+ testedAt,
244
+ };
245
+ }
246
+ lat.sort((a, b) => a - b);
247
+ const p95Ms = p95Of(lat);
248
+ const rssBudgetMib = installBudgetMib();
249
+ const verdict: RetestVerdict =
250
+ p95Ms <= ENCODER_LATENCY_P95_MS && rssMiB <= rssBudgetMib
251
+ ? "qualified"
252
+ : "degraded";
253
+ return { platform: platformStr, version, verdict, p95Ms, rssMiB, testedAt };
254
+ } catch {
255
+ return {
256
+ platform: platformStr,
257
+ version,
258
+ verdict: "failed",
259
+ p95Ms: 0,
260
+ rssMiB,
261
+ testedAt,
262
+ };
263
+ }
264
+ }
@@ -1,2 +0,0 @@
1
- import{j as r}from"./index-B4twCFnn.js";import{M as t}from"./MetricsCards-BlIiuZp5.js";import"./card-Crs5SwRQ.js";import"./generateCategoricalChart-qnHql9Es.js";import"./BarChart-B9jtJ7ud.js";import"./AreaChart-C03yuld4.js";function e(){return r.jsx(t,{})}export{e as default};
2
- //# sourceMappingURL=MetricsTab-DfRDIAEU.js.map
@@ -1,3 +0,0 @@
1
- import{r as s,j as e,o as L,p as Z,q as ae,s as oe,C as le,t as ie,e as ee,v as de,w as X,x as V,y as ce,u as K,z as te,A as se}from"./index-B4twCFnn.js";import{C as me}from"./ConfigTab-DDTqosv2.js";import{S as ue}from"./switch-BXutQI5d.js";import{b as he,p as pe,d as fe}from"./client-extra-Bd27WKSo.js";import{V as ge}from"./VcStatusBadge-C96wfemg.js";import{T as xe}from"./toggle-uE-OSaba.js";function be(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function re({achievements:t}){const n=s.useRef(0),[r,o]=s.useState(null),a=t.reduce((i,d)=>Math.max(i,d.unlocked_at??0),0),l=n.current;s.useEffect(()=>{a>n.current&&(n.current=a)},[a]),s.useEffect(()=>{if(l>0&&a>l){const i=t.filter(d=>d.unlocked_at!=null&&(d.unlocked_at??0)>l);if(i.length>0){const d=i.map(m=>`${m.icon??""} ${m.title}`.trim()).join(", ")+" unlocked!";o(d);const g=setTimeout(()=>o(null),4e3);return()=>clearTimeout(g)}}},[t,a,l]);const c=t.filter(i=>!(i.hidden===1&&i.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[r!=null&&e.jsx("div",{className:"ach-toast show",children:r}),e.jsxs("div",{className:"ach-tiles",children:[c.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),c.map(i=>{if(i.unlocked_at!=null){const d=l>0&&(i.unlocked_at??0)>l;return e.jsxs("div",{className:`ach-tile unlocked${d?" just-unlocked":""}`,children:[i.icon??""," ",i.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",be(i.unlocked_at)]})]},i.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",i.title]},i.id)})]})]})}function D(t){return(Math.round(t*10)/10).toString()+"%"}function F(t){return t!=null?new Date(t).toLocaleString():"—"}function H(t){return t&&typeof t=="object"?t:{}}function ye(t){return t.split("/").pop()||t}function _({title:t,rows:n,badge:r,renderValue:o}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,r]}),n.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:n.map((a,l)=>e.jsxs("tr",{children:[e.jsx("td",{title:a.repo_root,children:ye(a.repo_root)}),e.jsx("td",{className:"num",children:o(a)})]},`${a.repo_root}-${l}`))})})]})}function je(){const[t,n]=s.useState({}),[r,o]=s.useState(0),[a,l]=s.useState([]),[c,i]=s.useState(!1),[d,g]=s.useState(!0),[m,b]=s.useState(null),x=s.useRef(0),y=s.useCallback(async()=>{try{const[j,f,R,M,W,U]=await Promise.all([L({metric:"cache",limit:25}),L({metric:"dedupe",limit:25}),L({metric:"turns",limit:25}),L({metric:"mega_cache",limit:25}),L({metric:"repos",limit:1}),Z()]),P=M.find(I=>I.ts>x.current&&I.value>100);x.current>0&&P&&(b(`oopsie! cache went to ${Math.round(P.value)}% — MEGA CACHE 🥧`),setTimeout(()=>b(null),4e3)),M.length>0&&(x.current=Math.max(...M.map(I=>I.ts))),n({cache:j,dedupe:f,turns:R,mega_cache:M}),o(W[0]?.value??0),l(U)}catch{}finally{g(!1)}},[]);s.useEffect(()=>{let j=!0;const f=async()=>{j&&await y()};f();const R=setInterval(()=>void f(),15e3);return()=>{j=!1,clearInterval(R)}},[y]),s.useEffect(()=>{let j=!0;const f=async()=>{try{const M=await ae();j&&(i(!!M.game_mode_on),M.theme&&(document.documentElement.dataset.theme=M.theme))}catch{}};f();const R=setInterval(()=>void f(),15e3);return()=>{j=!1,clearInterval(R)}},[]);const v=t.mega_cache??[];let S=null,w=null;for(const j of v){(S==null||j.value>S)&&(S=j.value);const f=H(j.meta),R=f.firstSeenTs??f.firstSeen??j.ts;(w==null||R<w)&&(w=R)}const E=S!=null&&S>100,p=t.turns??[],N=p.reduce((j,f)=>Math.max(j,f.value),0),T=Math.floor(Math.log2(N+1))+1,z=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||p.length>0||v.length>0||r>0;return e.jsxs("div",{className:`game-tab${c?" game-mode-on":""}`,children:[m!=null&&e.jsx("div",{className:"mega-cache-toast show",children:m}),E&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",D(S)," — first reached ",F(w)]}),E&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",D(S)," · first ",F(w)]})]}),e.jsx("h2",{children:"High Scores"}),!z&&!d&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),z&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx(_,{title:"Cache %",rows:t.cache??[],renderValue:j=>D(j.value)}),e.jsx(_,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:j=>j.value.toLocaleString()}),e.jsx(_,{title:"Turns",rows:p,badge:p.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",T]}):void 0,renderValue:j=>j.value.toLocaleString()}),e.jsx(_,{title:"MEGA CACHE trophies",rows:v,renderValue:j=>e.jsxs(e.Fragment,{children:[D(j.value),e.jsx("span",{className:"lb-meta",children:F(H(j.meta).firstSeenTs??H(j.meta).firstSeen??j.ts)})]})})]}),r>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[r," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(re,{achievements:a})]})}function ve(){const[t,n]=s.useState([]),[r,o]=s.useState(!0),[a,l]=s.useState(null),c=s.useCallback(async()=>{try{const i=await Z();n(i),l(null)}catch(i){l(i instanceof Error?i:new Error(String(i)))}finally{o(!1)}},[]);return s.useEffect(()=>{let i=!0;const d=async()=>{i&&await c()};d();const g=setInterval(()=>void d(),15e3);return()=>{i=!1,clearInterval(g)}},[c]),r&&t.length===0?e.jsx("div",{className:"tab-stub",children:"Loading achievements…"}):a&&t.length===0?e.jsxs("div",{className:"tab-stub",children:["Error: ",a.message]}):e.jsxs("div",{className:"achievements-tab",children:[e.jsx("h2",{children:"Achievements"}),e.jsx(re,{achievements:t})]})}const A={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"}};function Se(){const[t,n]=s.useState(null),[r,o]=s.useState(null),a=s.useCallback(()=>{oe().then(n).catch(g=>o(g instanceof Error?g.message:String(g)))},[]);s.useEffect(()=>{a()},[a]),s.useEffect(()=>{const g=setInterval(a,3e4);return()=>clearInterval(g)},[a]);const l=t?.status==="ok",c=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",i=l?"#4caf50":"#f44336",d=l?"✓":"✗";return e.jsxs("div",{style:A.section,children:[e.jsx("h3",{style:A.sectionTitle,children:"Embedder Health"}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:A.row,children:[e.jsxs("span",{style:{...A.label,color:`${i}`},children:[d," ",c,":"]}),e.jsxs("span",{style:A.value,children:[t.dim," dims"]}),t.latencyMs!==void 0&&e.jsxs("span",{style:{color:"#a0a0c0",marginLeft:"0.5rem"},children:["(",t.latencyMs.toFixed(1)," ms)"]})]}),e.jsxs("div",{style:A.row,children:[e.jsx("span",{style:A.label,children:"Endpoint:"}),e.jsx("span",{style:A.value,children:t.url??e.jsx("span",{style:{color:"#888"},children:"built-in (no URL)"})})]}),t.error&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:t.error})]})]})}function we({title:t,children:n}){const[r,o]=s.useState(!0),a=`settings-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;return e.jsxs("section",{className:"overflow-hidden rounded-xl border border-border bg-bg-elevated/40",children:[e.jsxs("button",{type:"button",onClick:()=>o(l=>!l),className:"flex w-full items-center justify-between rounded-t-xl bg-bg-elevated/60 px-4 py-3 text-left text-sm font-semibold text-foreground transition-colors hover:bg-bg-elevated","aria-expanded":r,"aria-controls":a,children:[e.jsx("span",{children:t}),e.jsx(le,{className:ie("h-4 w-4 text-muted-foreground transition-transform",r&&"rotate-180"),"aria-hidden":"true"})]}),r&&e.jsx("div",{id:a,className:"divide-y divide-border px-4 py-1",children:n})]})}const Ce="rounded-md border border-border bg-bg-elevated/50 px-2 py-1 text-sm outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50";function ke(){return e.jsx("span",{className:"ml-2 inline-flex items-center rounded-md border border-warning/40 bg-warning/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-warning",title:"Requires an LLM embedder (Ollama/HTTP) to be effective",children:"LLM"})}function Ee({setting:t,id:n,llmActive:r,saving:o,onUpdate:a}){const[l,c]=s.useState(null),i=t.requiresLlm&&!r,d=s.useRef(null);s.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=s.useCallback(x=>{a(t.key,x).then(y=>c(y)).catch(y=>c(y instanceof Error?y.message:String(y)))},[a,t.key]),m=s.useCallback(x=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>g(x),500)},[g]),b=o||i;return e.jsxs("div",{className:"py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center text-sm font-semibold text-foreground",children:[e.jsx("label",{htmlFor:`${n}-input`,className:"cursor-pointer",children:t.label}),t.requiresLlm&&!r&&e.jsx(ke,{})]}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:t.description})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:t.type==="boolean"?e.jsx(ue,{id:`${n}-input`,checked:!!t.value,disabled:b||i,onCheckedChange:x=>g(String(x)),"aria-label":t.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:`${n}-input`,type:t.type==="number"?"number":"text",defaultValue:String(t.value??""),min:t.min,max:t.max,disabled:b,onChange:x=>m(x.target.value),className:`${Ce} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),l&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",l]})]})}function Te(){const[t,n]=s.useState(null),[r,o]=s.useState(null),[a,l]=s.useState(!1),[c,i]=s.useState(null),d=s.useCallback(()=>{ee().then(n).catch(m=>o(m instanceof Error?m.message:String(m)))},[]);s.useEffect(()=>{d()},[d]);const g=s.useCallback(async(m,b)=>{l(!0);try{const x=await de({key:m,value:b});return i(x.restartRequired?"Saved — restart pi to apply changes.":"Saved."),d(),null}catch(x){return x instanceof Error?x.message:String(x)}finally{l(!1)}},[d]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[r&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",r]}),!t&&!r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(m=>e.jsx(we,{title:m.name,children:m.settings.map(b=>e.jsx(Ee,{setting:b,id:`${m.name.replace(/[^a-z0-9]+/gi,"-")}-${b.key}`,llmActive:t.llmActive,saving:a,onUpdate:g},b.key))},m.name)),c&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:c})]})}const u={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},detectRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600}},Ne="Saved; takes effect on next session start";function Re({customUrl:t,setCustomUrl:n,applyEmbedder:r,configuring:o,inputEnabled:a,apiKeySet:l,embeddingDim:c,embeddingHeadersSet:i,allowRemoteEmbedder:d,configureResult:g,configureError:m}){const[b,x]=s.useState(""),[y,v]=s.useState(""),[S,w]=s.useState(!1),[E,p]=s.useState(""),[N,T]=s.useState(!1),[z,j]=s.useState(!1);return a&&!S&&typeof c=="string"&&(v(c),w(!0)),a&&!z&&typeof d=="boolean"&&(T(d),j(!0)),e.jsxs("div",{style:u.section,children:[e.jsx("h3",{style:u.sectionTitle,children:"Custom Endpoint (remote / third-party)"}),e.jsxs("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:["Point at any OpenAI-compatible embeddings API or hosted endpoint. This opts in to a non-loopback connection (sets"," ",e.jsx("code",{children:"MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1"}),") — your prompts' embedding requests will be sent to the URL you enter. Default is loopback-only."]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[e.jsx("input",{type:"url",placeholder:"https://api.example.com/v1/embeddings",value:t,onChange:f=>n(f.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&e.jsx("input",{type:"password",autoComplete:"new-password","aria-label":"API key (optional Bearer)",placeholder:"API key (optional Bearer)",value:b,onChange:f=>x(f.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),a&&l&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"API key saved"}),a&&i&&e.jsx("span",{style:{fontSize:"0.75rem",color:"#81c784",border:"1px solid #2a4e2a",borderRadius:"4px",padding:"0.15rem 0.45rem"},children:"Headers saved"}),e.jsx("button",{style:{...u.button,opacity:t?1:.4},onClick:()=>r("custom",t,b,y,E,N),disabled:!t||o!==null,children:o==="custom"?"Writing...":"Use Custom URL"})]}),a&&e.jsxs("div",{style:{marginTop:"0.75rem"},children:[e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...u.label,display:"block",marginBottom:"0.25rem"},children:"Embedding dim (optional)"}),e.jsx("input",{type:"number",min:1,placeholder:"e.g. 384",value:y,onChange:f=>v(f.target.value),style:{width:"200px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}})]}),e.jsxs("div",{style:{marginBottom:"0.5rem"},children:[e.jsx("label",{style:{...u.label,display:"block",marginBottom:"0.25rem"},children:"Embedding headers (JSON, write-only — never re-displayed)"}),e.jsx("textarea",{placeholder:'{"Authorization": "Bearer ..."}',value:E,onChange:f=>p(f.target.value),"aria-label":"Embedding headers JSON (write-only — never re-displayed)",rows:2,style:{width:"100%",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace",resize:"vertical"}})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:N,onChange:f=>T(f.target.checked),"aria-label":"Allow remote embedder (skips loopback-only check)"}),"Allow remote embedder (skips loopback-only check)"]})]}),m!==null&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",m]}),g!==null&&g.embedder==="custom"&&e.jsx("div",{style:u.warning,children:Ne}),e.jsxs("div",{style:u.warning,children:[e.jsx("strong",{children:"Heads up:"})," a remote endpoint receives the text you embed (it does NOT receive your full conversation — only the strings passed to",e.jsx("code",{children:" embed()"})," for recall/dedup). Verify the endpoint's privacy policy before use."]})]})}function J(t){switch(t){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}}function Be(t){return t?.currentEmbedder!=="trigram"?null:e.jsxs("div",{style:u.warning,children:[e.jsx("strong",{children:"Note:"})," TrigramEmbedder is a heuristic-strength default embedder. It works without any setup but recall quality may be lower than a dedicated embedding backend. If you notice poor recall results, consider installing Ollama and running the"," ",e.jsx("code",{children:"/megasetup"})," command, or set"," ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL"})," to point at your own localhost embedding server."]})}function G(t){const n=t?"#1a5a1a":"#3a1a1a",r=t?"#4caf50":"#f44336";return e.jsx("span",{style:{...u.badge,background:n,color:r},children:t?"Detected":"Not found"})}function ze({status:t,statusError:n}){return e.jsxs("div",{style:u.section,children:[e.jsx("h3",{style:u.sectionTitle,children:"Current Embedder Configuration"}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.row,children:[e.jsx("span",{style:u.label,children:"Active Embedder:"}),e.jsx("span",{style:u.value,children:J(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:u.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",J(t.configuredEmbedder)," is configured in .mega-compact.env but not yet loaded."," ",e.jsx("strong",{children:"Restart pi"})," to activate it.",t.configuredUrl&&e.jsxs(e.Fragment,{children:[" (",t.configuredUrl,")"]})]}),"restartRequired"in t&&t.restartRequired&&e.jsxs("div",{style:{...u.row,color:"#ff9800"},children:[e.jsx("span",{style:u.label,children:"Status:"}),e.jsx("span",{style:u.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:u.row,children:[e.jsx("span",{style:u.label,children:"Embedding URL:"}),e.jsx("span",{style:u.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:u.row,children:[e.jsx("span",{style:u.label,children:"Embed Cache:"}),e.jsx("span",{style:u.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:u.row,children:[e.jsx("span",{style:u.label,children:"MiniLM:"}),e.jsx("span",{style:u.value,children:t.minilm?"enabled":"disabled"})]}),Be(t)]}),!t&&!n&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]})}function Me(){const[t,n]=s.useState(null),[r,o]=s.useState(null),[a,l]=s.useState(null),[c,i]=s.useState(null),[d,g]=s.useState(!1),[m,b]=s.useState(null),[x,y]=s.useState(null),[v,S]=s.useState(null),[w,E]=s.useState(""),[p,N]=s.useState(!1),T=s.useCallback(()=>{X().then(n).catch(f=>l(f instanceof Error?f.message:String(f)))},[]),z=s.useCallback((f,R,M,W,U,P)=>{b(f),S(null),y(null);const I="embeddingHeadersSet"in(t??{});V({embedder:f,url:R,embeddingEndpointUrl:R,embeddingApiKey:M,...I?{embeddingDim:W,embeddingHeaders:U,allowRemoteEmbedder:P}:{}}).then(O=>{y(O),b(null),T()}).catch(O=>{S(O instanceof Error?O.message:String(O)),b(null)})},[T,t]),j=s.useCallback(()=>{g(!0),i(null),ce().then(f=>{o(f),g(!1)}).catch(f=>{i(f instanceof Error?f.message:String(f)),g(!1)})},[]);return s.useEffect(()=>{T()},[T]),s.useEffect(()=>{p||t&&typeof t.embeddingEndpointUrl=="string"&&t.embeddingEndpointUrl.length>0&&(E(t.embeddingEndpointUrl),N(!0))},[t,p]),s.useEffect(()=>{const f=setInterval(T,5e3);return()=>clearInterval(f)},[T]),s.useEffect(()=>{j();const f=setInterval(j,5e3);return()=>clearInterval(f)},[j]),e.jsxs("div",{style:u.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(Se,{}),e.jsx(ze,{status:t,statusError:a}),e.jsxs("div",{style:u.section,children:[e.jsx("h3",{style:u.sectionTitle,children:"Local Embedder Detection"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Detect which local embedding backends are available on this machine. No software is installed — detection only."}),r&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),r.ollama!==null?e.jsxs("span",{children:[G(r.ollama.installed),r.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:r.ollama.running?`server running, ${r.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:u.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),r.llamaCpp!==null?e.jsxs("span",{children:[G(r.llamaCpp.installed),r.llamaCpp.installed&&r.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:r.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:u.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),r.onnx!==null?e.jsxs("span",{children:[G(r.onnx.installed),r.onnx.installed&&r.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:r.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),r.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",r.error]})]}),c&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",c]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:u.button,onClick:j,disabled:d,children:d?"Detecting...":"Run Detection"}),e.jsxs("span",{style:{fontSize:"0.8rem",color:"#888",marginLeft:"0.75rem"},children:["Or run ",e.jsx("code",{children:"/megasetup"})," in the chat for an interactive wizard."]})]}),r&&e.jsxs("div",{style:{marginTop:"1rem",paddingTop:"0.75rem",borderTop:"1px solid #2a2a4e"},children:[e.jsx("div",{style:{fontSize:"0.9rem",fontWeight:600,marginBottom:"0.5rem"},children:"Configure"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[e.jsx("button",{style:{...u.button,opacity:r.ollama?.installed?1:.4},onClick:()=>z("ollama"),disabled:!r.ollama?.installed||m!==null,children:m==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...u.button,opacity:r.llamaCpp?.installed?1:.4},onClick:()=>z("llama"),disabled:!r.llamaCpp?.installed||m!==null,children:m==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...u.button,opacity:r.onnx?.installed?1:.4},onClick:()=>z("onnx"),disabled:!r.onnx?.installed||m!==null,children:m==="onnx"?"Writing...":"Use ONNX"}),e.jsx("button",{style:{...u.button,background:"#444"},onClick:()=>z("trigram"),disabled:m!==null,children:m==="trigram"?"Writing...":"Use Trigram (default)"})]}),x&&x.embedder!=="custom"&&e.jsx("div",{style:u.warning,children:x.alreadyActive?"Already active — no restart needed.":`Configured ${x.embedder}. Restart pi to activate (config written to ${x.envPath}).`}),v&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",v]})]})]}),e.jsx(Re,{customUrl:w,setCustomUrl:E,applyEmbedder:z,configuring:m,inputEnabled:t!==null&&"embeddingApiKeySet"in t,apiKeySet:t?.embeddingApiKeySet===!0,embeddingDim:t?.embeddingDim,embeddingHeadersSet:t?.embeddingHeadersSet===!0,allowRemoteEmbedder:t?.allowRemoteEmbedder,configureResult:x,configureError:v}),e.jsxs("div",{style:u.section,children:[e.jsx("h3",{style:u.sectionTitle,children:"How to Upgrade"}),e.jsxs("ul",{style:{fontSize:"0.85rem",lineHeight:1.6,paddingLeft:"1.25rem"},children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Ollama:"})," Install from"," ",e.jsx("a",{href:"https://ollama.com",style:{color:"#6a9fff"},target:"_blank",rel:"noopener noreferrer",children:"ollama.com"}),", then ",e.jsx("code",{children:"ollama pull nomic-embed-text"})," and restart pi. Set ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL=http://localhost:11434/api/embeddings"}),"."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"llama.cpp:"})," Build or install llama.cpp, run"," ",e.jsx("code",{children:"llama-server"})," with an embedding model, and set the URL accordingly."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"ONNX Runtime:"})," Run a local text-embeddings server (e.g. TEI) and click ",e.jsx("strong",{children:"Use ONNX"})," above. Default URL: ",e.jsx("code",{children:"http://localhost:8081/v1/embeddings"}),"."]})]})]}),e.jsxs("div",{style:u.section,children:[e.jsx("h3",{style:u.sectionTitle,children:"Settings"}),e.jsx(Te,{})]})]})}function $(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Ae(t,n,r){if(t<=0)return"—";const a=(n>0?n:Math.ceil(t*.1))+Math.ceil(t*(r/100)),l=t-a;return l<=0?"0 (at risk)":`${$(l)} tokens`}function Q({label:t,value:n,min:r,max:o,step:a=1,onChange:l,warning:c}){return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-fg-muted",children:t}),e.jsxs("span",{className:`font-mono ${c?"text-warning":"text-fg"}`,title:c,children:[n,"%"]})]}),e.jsx("input",{type:"range",min:r,max:o,step:a,value:n,onChange:i=>l(Number(i.target.value)),className:"threshold-slider w-full"}),c&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",c]})]})}function Ie({model:t,defaults:n,safetyRange:r,fireRange:o,onSave:a,onReset:l,saving:c}){const[i,d]=s.useState(t.threshold.safetyMarginPct),[g,m]=s.useState(t.threshold.firePointPct),[b,x]=s.useState(!1),[y,v]=s.useState(null);s.useEffect(()=>{d(t.threshold.safetyMarginPct),m(t.threshold.firePointPct),x(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const S=i<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,w=g>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,E=s.useCallback(async()=>{v(null);try{await a(t.modelId,i,g),x(!1)}catch(p){v(p instanceof Error?p.message:String(p))}},[t.modelId,i,g,a]);return e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.modelName??t.modelId}),t.threshold.isOverride&&e.jsx("span",{className:"rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-primary",title:"This model has a custom override (not the default)",children:"Override"})]}),e.jsxs("div",{className:"text-[11px] text-fg-muted",children:[t.provider," · ",$(t.contextWindow)," window ·"," ",$(t.maxTokens)," output"]})]}),e.jsxs("div",{className:"text-right text-[11px] text-fg-muted",children:[e.jsxs("div",{children:["Usable tail:"," ",e.jsx("span",{className:"font-mono text-fg",children:Ae(t.contextWindow,t.maxTokens,i)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:$(Math.ceil(t.contextWindow*(g/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(Q,{label:"Safety margin",value:i,min:r[0],max:r[1],onChange:p=>{d(p),x(!0)},warning:S}),e.jsx(Q,{label:"Fire point",value:g,min:o[0],max:o[1],onChange:p=>{m(p),x(!0)},warning:w})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:E,disabled:!b||c,className:"rounded-md bg-primary px-2.5 py-1 text-xs font-semibold text-primary-fg disabled:cursor-not-allowed disabled:opacity-50",children:b?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>l(t.modelId),disabled:c,className:"rounded-md border border-border px-2.5 py-1 text-xs text-fg-muted disabled:cursor-not-allowed disabled:opacity-50",children:["Reset to default (",n.safetyMarginPct,"% /"," ",n.firePointPct,"%)"]}),y&&e.jsx("span",{className:"text-[11px] text-error",children:y})]})]})}function Oe(){const[t,n]=s.useState(null),[r,o]=s.useState(!0),[a,l]=s.useState(null),[c,i]=s.useState(!1),d=s.useCallback(async()=>{try{l(null),n(await he())}catch(b){l(b instanceof Error?b.message:String(b))}finally{o(!1)}},[]);s.useEffect(()=>{d()},[d]);const g=s.useCallback(async(b,x,y)=>{i(!0);try{await pe({modelId:b,safetyMarginPct:x,firePointPct:y}),await d()}finally{i(!1)}},[d]),m=s.useCallback(async b=>{i(!0);try{await fe(b),await d()}finally{i(!1)}},[d]);return r?e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"Loading thresholds…"}):a?e.jsxs("div",{className:"p-4 text-sm text-error",children:["Error: ",a]}):t?e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/20 p-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Per-Model Compaction Thresholds"}),e.jsxs("p",{className:"mt-1 text-[11px] text-fg-muted",children:["Tune when compaction fires + how much safety margin to reserve,",e.jsx("strong",{children:" per model"}),". Different providers' models range from 8K to 1M+ context — one global % is wrong. Defaults:"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.safetyMarginPct,"% safety"]})," ","/"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.firePointPct,"% fire"]}),". Values outside the safe band show warnings."]})]}),t.models.length===0?e.jsx("div",{className:"rounded-md border border-border p-4 text-sm text-fg-muted",children:"No models captured yet. Start a pi session in any repo to populate model snapshots, then return here to tune per-model thresholds."}):e.jsx("div",{className:"flex flex-col gap-3",children:t.models.map(b=>e.jsx(Ie,{model:b,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:g,onReset:m,saving:c},b.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}async function Le(){const t=await fetch("/api/setup-cortex-status");if(!t.ok)throw new Error(`setup-cortex status: ${t.status}`);return t.json()}async function Pe(t){const n=await fetch("/api/setup-cortex-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return{ok:!0,result:await n.json()};let r;try{r=await n.json()}catch{r={error:"disabled"}}return{ok:!1,status:n.status,error:r}}async function De(t){const n=await fetch(`/api/setup-cortex-action-log?name=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`setup-cortex action-log: ${n.status}`);return n.json()}function _e(t){return t===null?!0:t.enabled&&t.status!=="off"}function ne(){const[t,n]=s.useState({loading:!0,error:null,data:null}),r=s.useCallback(()=>{n(o=>({...o,loading:!0})),Le().then(o=>n(a=>({...a,data:o,loading:!1,error:null}))).catch(o=>n(a=>({...a,loading:!1,error:o instanceof Error?o.message:String(o)})))},[]);return s.useEffect(()=>{r();const o=setInterval(r,5e3);return()=>clearInterval(o)},[r]),[t,r]}const h={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},blocked:{background:"#3a1a1a",border:"1px solid #662222",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ff6666",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},buttonDanger:{background:"#6a2a2a",color:"#ffb3b3",border:"1px solid #662222",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},blockerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.6rem",borderRadius:"6px",marginBottom:"0.35rem",fontSize:"0.85rem"},blockerRowHighlighted:{background:"#3a1a1a",border:"1px solid #662222"},mono:{fontFamily:"ui-monospace, monospace",fontSize:"0.8rem"}};function $e(t){switch(t){case"A":return"A — qualified learned encoder asset";case"B":return"B — demoted (heuristic/trigram)";case"C":return"C — absent (asset not verified)";default:return"—"}}function We(t){const n=t==="qualified"?"#1a5a1a":t==="demoted"?"#3a3a1a":"#3a1a1a",r=t==="qualified"?"#4caf50":t==="demoted"?"#ffcc00":"#f44336";return e.jsx("span",{style:{...h.badge,background:n,color:r},children:t??"unknown"})}function Ue({data:t,error:n}){return e.jsxs("div",{style:h.section,children:[e.jsxs("h3",{style:h.sectionTitle,children:[e.jsx("span",{style:{marginRight:"0.5rem"},children:"Cortex Encoder"}),e.jsx(ge,{status:t?.status})]}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]}),!t&&!n&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading cortex status..."}),!t?.enabled&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:"Cortex status disabled (VC9A off)."}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Mode:"}),e.jsx("span",{style:h.value,children:$e(t?.encoderHealth.mode)})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Asset digest prefix:"}),e.jsx("span",{style:{...h.value,...h.mono},children:t?.assetDigestPrefix??e.jsx("span",{style:{color:"#888"},children:"not available"})})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Qualification:"}),We(t?.qualification.verdict)]}),(t?.qualification.thresholdFailures.length??0)>0&&e.jsxs("div",{style:h.warning,children:[e.jsx("strong",{children:"Threshold failure(s):"})," ",t?.qualification.thresholdFailures.join(", ")]}),t?.status==="awaiting_data"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Awaiting encoder data. Qualification will appear once an asset is present."}),t?.status==="deferred"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Encoder status deferred."})]})}function Fe(t){switch(t){case"blocker":return"#f44336";case"high":return"#ff9800";default:return"#a0a0c0"}}function He({blockers:t,highlight:n,darwinX64:r}){const o=n??[];return e.jsxs("div",{style:h.section,children:[e.jsxs("h3",{style:h.sectionTitle,children:["Open Hard-Gate Blockers",e.jsx("span",{style:{...h.badge,background:"#3a1a1a",color:"#f44336"},children:t.length})]}),t.length===0&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.85rem"},children:"No open hard-gate blockers."}),r?.demoted===!0&&e.jsxs("div",{style:h.blockerRow,"data-darwin-x64-demoted":"true",children:[e.jsx("span",{style:{...h.mono,fontWeight:700},children:"HG-4"}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:r.reason||"darwin-x64: demoted to WASM (reason unavailable)"}),e.jsx("span",{style:{color:"#ff9800"},children:"high"}),e.jsx("span",{style:{color:"#4caf50",fontStyle:"italic"},children:"diagnosed"})]}),t.map(a=>{const l=o.includes(a.id);return e.jsxs("div",{style:{...h.blockerRow,...l?h.blockerRowHighlighted:{}},children:[e.jsx("span",{style:{...h.mono,fontWeight:700},children:a.id}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:a.title}),e.jsx("span",{style:{color:Fe(a.severity)},children:a.severity}),e.jsx("span",{style:{color:"#a0a0c0",fontStyle:"italic"},children:l?"gates this action":a.status})]},a.id)}),o.length>0&&e.jsxs("div",{style:h.blocked,children:[e.jsx("strong",{children:"Blocked:"})," the requested action is gated by the highlighted open hard-gate item(s). It was not run."]})]})}const Ge=[{key:"fetch-model",label:"Fetch Model",desc:"Fetch the qualified encoder model asset",dangerous:!0,confirm:"Fetch the encoder model asset onto this host? (Gated by any open hard gate.)"},{key:"bench",label:"Bench Encoder",desc:"Benchmark the encoder runtime on this host",dangerous:!0,confirm:"Run an encoder benchmark on this host? (Gated by any open hard gate.)"},{key:"verify-asset",label:"Verify Asset",desc:"Re-verify the committed encoder asset",dangerous:!1,confirm:"Re-verify the committed encoder asset?"}];function qe({data:t,onBlocked:n,onAction:r}){const[o,a]=s.useState(null),[l,c]=s.useState(null),[i,d]=s.useState(null),[g,m]=s.useState(!1),b=s.useCallback(async y=>{a(y.key),d(null),c(null),m(!1),n([]);try{const v=await Pe({action:y.key,confirm:!0});if(v.ok){const S=v.result;let w=null,E=null;try{const p=await De(S.logName);w=p.tail,E=p.complete}catch{}c({action:S.action,logName:S.logName,tail:w,complete:E,message:S.ok?`${S.action} completed (spawned: ${S.spawned})`:`${S.action} did not complete cleanly`}),r()}else v.error.error==="action_blocked_by_open_item"?(n(v.error.blockers),d("The action is blocked by an open hard-gate item and was not run.")):v.error.error==="confirmation_required"?d("The server rejected the action: explicit confirmation is required."):(m(!0),d(v.status===404?"Setup Cortex actions are disabled (off).":`Action failed (${v.status}).`))}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(null)}},[n,r]),x=y=>{window.confirm(y.confirm)&&b(y)};return e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Cortex Actions"}),Ge.map(y=>{const v=o===y.key;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600},children:y.label}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:y.desc})]}),e.jsx("button",{style:y.dangerous?h.buttonDanger:h.button,disabled:o!==null,onClick:()=>x(y),children:v?"Running…":"Run"})]},y.key)}),g&&e.jsx("div",{style:h.blocked,children:"Setup Cortex actions are disabled. Enable MEGACOMPACT_VC9B to run them."}),i&&!g&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:i}),l&&e.jsxs("div",{style:h.warning,"data-testid":"cortex-action-result",children:[e.jsxs("strong",{children:["Result (",l.action,"):"]})," ",l.message,l.logName&&e.jsxs("span",{style:{...h.mono,marginLeft:"0.5rem"},children:["log: ",l.logName]}),l.tail!==null&&e.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"0.75rem",maxHeight:"12rem",overflow:"auto",marginTop:"0.5rem"},children:[l.tail,l.complete===!1&&`
2
- … (truncated)`]})]}),!t?.enabled&&!g&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.8rem",marginTop:"0.5rem"},children:"Cortex status unavailable — actions may not be schedulable."})]})}const B={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},toggleRow:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem",fontSize:"0.9rem"}},q=8192;function Ve(){const[t,n]=s.useState(null),[r,o]=s.useState(null),[a,l]=s.useState(!1),[c,i]=s.useState(""),[d,g]=s.useState(!1),m=s.useCallback(()=>{X().then(n).catch(p=>o(p instanceof Error?p.message:String(p)))},[]);s.useEffect(()=>{m()},[m]),s.useEffect(()=>{const p=setInterval(m,5e3);return()=>clearInterval(p)},[m]);const b=t!==null&&"encoderNativeOptIn"in t,x=t?.nativeOrtBudgetEffectiveMib;s.useEffect(()=>{if(!d&&t&&"nativeOrtBudgetEffectiveMib"in t){const p=t.nativeOrtBudgetMib??t.nativeOrtBudgetEffectiveMib??"";typeof p=="string"&&i(p),g(!0)}},[d,t]);const y=s.useCallback(p=>{l(!0),o(null),V({embedder:"custom",url:t?.embeddingEndpointUrl??void 0,encoderNativeOptIn:p}).then(()=>{l(!1),m()}).catch(N=>{o(N instanceof Error?N.message:String(N)),l(!1)})},[t,m]),v=s.useCallback(()=>{const p=c.trim();if(!/^\d+$/.test(p)){o("Install budget must be a positive integer (MiB)");return}const N=Number(p);if(!Number.isSafeInteger(N)||N<1||N>q){o(`Install budget must be between 1 and ${q} MiB`);return}l(!0),o(null),V({embedder:"custom",url:t?.embeddingEndpointUrl??void 0,nativeOrtBudgetMib:p}).then(()=>{l(!1),m()}).catch(T=>{o(T instanceof Error?T.message:String(T)),l(!1)})},[c,t,m]);if(!b)return e.jsx(e.Fragment,{});const S=t?.encoderBackend??"wasm",w=t?.encoderDemotionReason??null,E=t!==null&&"nativeOrtBudgetEffectiveMib"in t;return e.jsxs("div",{style:B.section,children:[e.jsx("h3",{style:B.sectionTitle,children:"Encoder Runtime"}),e.jsx("p",{style:B.subtitle,children:"ONNX backend selection"}),e.jsxs("div",{style:B.toggleRow,children:[e.jsx("input",{type:"checkbox",checked:t?.encoderNativeOptIn===!0,onChange:p=>y(p.target.checked),disabled:a,"aria-label":"Native ONNX runtime (onnxruntime-node)"}),e.jsx("label",{children:"Native ONNX runtime (onnxruntime-node)"}),a&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:"saving..."})]}),e.jsxs("div",{style:B.row,children:[e.jsx("span",{style:B.label,children:"Effective backend:"}),e.jsx("span",{style:B.value,children:S})]}),E&&e.jsxs("div",{style:B.row,children:[e.jsx("label",{htmlFor:"enc2-budget-input",style:{...B.label,marginRight:"0.5rem"},children:"Native install budget (MiB):"}),e.jsx("input",{id:"enc2-budget-input",type:"number",min:1,max:q,step:1,value:c,onChange:p=>i(p.target.value),disabled:a,style:{width:"6rem"},"aria-label":"Native onnxruntime install budget in MiB"}),e.jsx("button",{type:"button",onClick:v,disabled:a||c.trim().length===0,style:{marginLeft:"0.5rem"},children:"Save"}),x!==void 0&&e.jsxs("span",{style:{...B.value,marginLeft:"0.5rem"},children:["(effective: ",x," MiB)"]})]}),w!==null&&e.jsxs("div",{style:B.warning,children:[e.jsx("strong",{children:"Demoted:"})," ",w]}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]})]})}function Xe(){const[t,n]=s.useState(!1),r=s.useCallback(async o=>{try{await navigator.clipboard.writeText(o),n(!0),window.setTimeout(()=>n(!1),1500)}catch{n(!1)}},[]);return[t,r]}function Ke(){const[t,n]=s.useState(null),[r,o]=Xe(),a=s.useCallback(()=>{X().then(n).catch(()=>{})},[]);s.useEffect(()=>{a();const i=setInterval(a,5e3);return()=>clearInterval(i)},[a]);const l=t?.nativeOrtInstallGuide??null,c=t?.nativeOrtInstalledVersion??null;return l?e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Encoder Runtime Install"}),e.jsxs("p",{style:{...h.label,fontSize:"0.85rem",marginBottom:"0.75rem"},children:["Platform: ",l.platform]}),c!==null&&e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Detected:"}),e.jsx("span",{style:h.value,children:c})]}),l.commands.map((i,d)=>e.jsxs("div",{style:h.row,children:[e.jsxs("span",{style:h.label,children:["Step ",d+1,":"]}),e.jsx("code",{style:{...h.mono,display:"inline-block",marginTop:"0.15rem"},children:i}),e.jsx("button",{type:"button",onClick:()=>{o(i)},style:{marginLeft:"0.5rem",fontSize:"0.8rem"},children:"Copy"})]},`${d}-${i}`)),e.jsxs("p",{style:{...h.row,fontSize:"0.85rem"},children:[e.jsx("span",{style:h.label,children:"Script:"})," ",e.jsx("code",{style:h.mono,children:l.scriptPath})]}),r&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.8rem",margin:"0.25rem 0 0"},children:"Copied to clipboard"})]}):e.jsx(e.Fragment,{})}const C={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},disabled:{background:"#1a1a2e",border:"1px solid #2a2a4e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",color:"#a0a0c0",fontSize:"0.85rem"}},Je=()=>{const{data:t,error:n,loading:r}=K(s.useMemo(()=>()=>te("/api/cosine-fp-report").catch(o=>{if(o instanceof se&&o.status===404)return null;throw o}),[]),{pollInterval:5e3});return t===null&&!n&&!r?e.jsx("div",{style:C.disabled,children:"Cosine FP synthetic bench: disabled (MEGACOMPACT_COSINE_FP_BENCH=0)."}):e.jsxs("div",{style:C.section,children:[e.jsx("h3",{style:C.sectionTitle,children:"Cosine FP threshold"}),e.jsx("p",{style:C.subtitle,children:"Last synthetic bench threshold recommendation"}),n!==null?e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error loading report: ",n.message]}):t===null?e.jsx("div",{style:C.value,children:"Loading…"}):e.jsxs("div",{children:[e.jsxs("div",{style:C.row,children:[e.jsx("span",{style:C.label,children:"Recommended default:"}),e.jsxs("span",{style:C.value,children:[t.recommendedDefault??"—"," (shipped"," ",t.shippedDefault,")"]})]}),e.jsxs("div",{style:C.row,children:[e.jsx("span",{style:C.label,children:"Overrides:"}),e.jsxs("span",{style:C.value,children:["CODE ",t.overrides?.code??"—"," · PROSE"," ",t.overrides?.prose??"—"," · MIXED"," ",t.overrides?.mixed??"—"]})]}),e.jsxs("div",{style:C.row,children:[e.jsx("span",{style:C.label,children:"Grid:"}),e.jsx("span",{style:C.value,children:t.grid?`${t.grid.lo} → ${t.grid.hi} (${t.grid.points} points)`:"—"})]}),e.jsxs("div",{style:C.row,children:[e.jsx("span",{style:C.label,children:"Report digest:"}),e.jsx("span",{style:C.value,title:t.digest??void 0,children:t.digest?t.digest.slice(0,16)+"…":"—"})]})]})]})},k={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.25rem",color:"#e0e0e0"},subtitle:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0,marginBottom:"0.75rem"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},disabled:{background:"#1a1a2e",border:"1px solid #2a2a4e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",color:"#a0a0c0",fontSize:"0.85rem"}},Qe=()=>{const{data:t,error:n,loading:r}=K(s.useMemo(()=>()=>te("/api/repo-corpus").catch(o=>{if(o instanceof se&&o.status===404)return null;throw o}),[]),{pollInterval:5e3});return t===null&&!n&&!r?e.jsx("div",{style:k.disabled,children:"Cross-repo corpus: disabled (MEGACOMPACT_REPO_CORPUS=0)."}):e.jsxs("div",{style:k.section,children:[e.jsx("h3",{style:k.sectionTitle,children:"Cross-Repo Corpus"}),e.jsx("p",{style:k.subtitle,children:"Pseudonymous consent status across donated repos"}),n!==null?e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error loading corpus: ",n.message]}):t===null?e.jsx("div",{style:k.value,children:"Loading…"}):e.jsxs("div",{children:[e.jsxs("div",{style:k.row,children:[e.jsx("span",{style:k.label,children:"Status:"}),e.jsx("span",{style:k.value,children:t.status})]}),e.jsxs("div",{style:k.row,children:[e.jsx("span",{style:k.label,children:"Total events:"}),e.jsx("span",{style:k.value,children:t.totalEvents})]}),e.jsxs("div",{style:k.row,children:[e.jsx("span",{style:k.label,children:"Overlap pairs:"}),e.jsx("span",{style:k.value,children:t.corpus?t.corpus.overlaps.length:0})]}),e.jsx("div",{style:{marginTop:"0.5rem"},children:(t.perRepo??[]).map(o=>e.jsxs("div",{style:k.row,children:[e.jsxs("span",{style:k.label,children:[o.repoPseudonym.slice(0,8),":"]}),e.jsxs("span",{style:k.value,children:[o.sessions," sessions ·"," ",o.consentedCrossRepo?o.revokedAt?`revoked ${o.revokedAt}`:"consented":"not consented"]})]},o.repoPseudonym))})]})]})};function Ye(){const[t,n]=ne(),[r,o]=s.useState([]),a=s.useCallback(c=>{o(c)},[]),l=s.useCallback(()=>{n()},[n]);return e.jsxs("div",{style:h.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Setup Cortex"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Vector-cortex encoder gate: mode, qualification, open hard-gate blockers, and the confirmation-gated fetch/bench/verify actions."}),e.jsx(Ue,{data:t.data,error:t.error}),e.jsx(Ve,{}),e.jsx(Ke,{}),e.jsx(Je,{}),e.jsx(Qe,{}),e.jsx(He,{blockers:t.data?.blockers??[],highlight:r,darwinX64:t.data?.darwinX64}),e.jsx(qe,{data:t.data,onBlocked:a,onAction:l})]})}const Ze="MEGACOMPACT_DASH_0C";function et(t){if(!t)return!1;for(const n of t.categories)for(const r of n.settings)if(r.key===Ze&&r.type==="boolean")return r.value===!0;return!1}const Y=[{id:"embedder",label:"Embedder"},{id:"thresholds",label:"Thresholds"},{id:"config",label:"Config"},{id:"game",label:"Game Mode"},{id:"achievements",label:"Achievements"}],tt={id:"cortex",label:"Cortex"};function it(){const[t,n]=s.useState("embedder"),[r]=ne(),{data:o}=K(s.useCallback(()=>ee(),[]),{pollInterval:0,maxRetries:0}),a=et(o),l=s.useMemo(()=>{const c=a?Y.filter(i=>i.id!=="config"):[...Y];return _e(r.data)&&c.push(tt),c},[r.data,a]);return e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-4 p-4",children:[e.jsx("nav",{className:"flex gap-2 border-b border-border pb-2","aria-label":"Setup sections",children:l.map(c=>e.jsx(xe,{pressed:t===c.id,onClick:()=>n(c.id),children:c.label},c.id))}),t==="embedder"&&e.jsx(Me,{}),t==="thresholds"&&e.jsx(Oe,{}),t==="config"&&!a&&e.jsx(me,{}),t==="game"&&e.jsx(je,{}),t==="achievements"&&e.jsx(ve,{}),t==="cortex"&&e.jsx(Ye,{})]})}export{it as default};
3
- //# sourceMappingURL=SetupTab-CEXL71VP.js.map