@polderlabs/bizar 5.0.0 → 5.0.2

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 (97) hide show
  1. package/bizar-dash/dist/assets/{icons-CFqu2M-c.js → icons-Bo0iH9EC.js} +166 -121
  2. package/bizar-dash/dist/assets/icons-Bo0iH9EC.js.map +1 -0
  3. package/bizar-dash/dist/assets/main-C1cpttnv.js +19 -0
  4. package/bizar-dash/dist/assets/main-C1cpttnv.js.map +1 -0
  5. package/bizar-dash/dist/assets/main-DTkNlLrw.css +1 -0
  6. package/bizar-dash/dist/assets/mobile-BtxQJftK.js +2 -0
  7. package/bizar-dash/dist/assets/mobile-BtxQJftK.js.map +1 -0
  8. package/bizar-dash/dist/assets/{mobile-DHXXbn1A.js → mobile-DD-FZrTC.js} +1 -1
  9. package/bizar-dash/dist/assets/{mobile-DHXXbn1A.js.map → mobile-DD-FZrTC.js.map} +1 -1
  10. package/bizar-dash/dist/index.html +4 -4
  11. package/bizar-dash/dist/mobile.html +3 -3
  12. package/bizar-dash/node_modules/.package-lock.json +6 -0
  13. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  14. package/bizar-dash/package-lock.json +6 -0
  15. package/bizar-dash/src/server/api.mjs +7 -0
  16. package/bizar-dash/src/server/diagnostics-store.mjs +452 -2
  17. package/bizar-dash/src/server/memory-store.mjs +46 -0
  18. package/bizar-dash/src/server/providers-store.mjs +11 -4
  19. package/bizar-dash/src/server/routes/_shared.mjs +2 -2
  20. package/bizar-dash/src/server/routes/doctor.mjs +71 -0
  21. package/bizar-dash/src/server/routes/env-vars.mjs +67 -1
  22. package/bizar-dash/src/server/routes/memory.mjs +3 -0
  23. package/bizar-dash/src/server/routes/opencode-session-detail.mjs +61 -42
  24. package/bizar-dash/src/server/routes/schedules.mjs +55 -0
  25. package/bizar-dash/src/server/serve-info.mjs +172 -0
  26. package/bizar-dash/src/web/App.tsx +48 -11
  27. package/bizar-dash/src/web/components/AutosaveField.tsx +50 -0
  28. package/bizar-dash/src/web/components/DoctorPanel.tsx +160 -0
  29. package/bizar-dash/src/web/components/EnvVarManager.tsx +245 -62
  30. package/bizar-dash/src/web/components/ScheduleTemplateCard.tsx +71 -0
  31. package/bizar-dash/src/web/components/SettingsNav.tsx +101 -0
  32. package/bizar-dash/src/web/components/Sidebar.tsx +25 -1
  33. package/bizar-dash/src/web/components/StatusBadge.tsx +33 -2
  34. package/bizar-dash/src/web/components/Topbar.tsx +11 -0
  35. package/bizar-dash/src/web/components/chat/ChatInfoPanel.tsx +64 -0
  36. package/bizar-dash/src/web/components/chat/Composer.tsx +1 -1
  37. package/bizar-dash/src/web/components/chat/useChat.ts +118 -1
  38. package/bizar-dash/src/web/hooks/useAutosave.ts +107 -0
  39. package/bizar-dash/src/web/lib/types.ts +134 -0
  40. package/bizar-dash/src/web/styles/chat.css +8 -5
  41. package/bizar-dash/src/web/styles/main.css +77 -2
  42. package/bizar-dash/src/web/styles/settings.css +265 -0
  43. package/bizar-dash/src/web/views/Chat.tsx +15 -1
  44. package/bizar-dash/src/web/views/Doctor.tsx +317 -0
  45. package/bizar-dash/src/web/views/MiniMaxUsage.tsx +1 -0
  46. package/bizar-dash/src/web/views/Schedules.tsx +94 -12
  47. package/bizar-dash/src/web/views/Settings.tsx +76 -46
  48. package/bizar-dash/src/web/views/memory/ConfigPanel.tsx +114 -133
  49. package/bizar-dash/src/web/views/settings/AgentSection.tsx +23 -12
  50. package/bizar-dash/src/web/views/settings/EnvVarsSection.tsx +5 -6
  51. package/bizar-dash/src/web/views/settings/GeneralSection.tsx +38 -15
  52. package/bizar-dash/src/web/views/settings/MemorySection.tsx +92 -8
  53. package/bizar-dash/tests/autosave.test.tsx +276 -0
  54. package/bizar-dash/tests/chat-composer.test.tsx +140 -0
  55. package/bizar-dash/tests/components/doctor-panel.test.tsx +105 -0
  56. package/bizar-dash/tests/diagnostics-store.test.mjs +206 -0
  57. package/bizar-dash/tests/env-vars-extended.test.mjs +190 -0
  58. package/bizar-dash/tests/layout-spacing.test.mjs +101 -0
  59. package/bizar-dash/tests/memory-default-vault.test.mjs +98 -0
  60. package/bizar-dash/tests/minimax-bar.test.tsx +113 -0
  61. package/bizar-dash/tests/minimax-models.test.mjs +123 -0
  62. package/bizar-dash/tests/opencode-sessions-detail.test.mjs +158 -0
  63. package/bizar-dash/tests/routes-doctor.test.mjs +159 -0
  64. package/bizar-dash/tests/schedules-templates.test.mjs +144 -0
  65. package/bizar-dash/tests/settings-layout.test.tsx +129 -0
  66. package/bizar-dash/tests/settings-mode-wiring.test.tsx +151 -0
  67. package/bizar-dash/tests/settings-nav.test.tsx +126 -0
  68. package/cli/commands/dash.mjs +5 -1
  69. package/cli/commands/minimax.mjs +5 -2
  70. package/cli/tests/minimax-cli.test.mjs +79 -0
  71. package/config/agents/frigg.md +1 -1
  72. package/config/agents/heimdall.md +1 -1
  73. package/config/agents/mimir.md +1 -1
  74. package/config/agents/quick.md +1 -1
  75. package/config/agents/semble-search.md +1 -1
  76. package/config/agents/vor.md +1 -1
  77. package/config/opencode.json +28 -21
  78. package/config/opencode.json.template +8 -1
  79. package/package.json +1 -1
  80. package/plugins/bizar/index.ts +77 -0
  81. package/plugins/bizar/src/compaction.d.mts +48 -0
  82. package/plugins/bizar/src/compaction.mjs +192 -0
  83. package/plugins/bizar/tests/compaction.test.ts +264 -0
  84. package/templates/schedules/daily-backup.json +12 -0
  85. package/templates/schedules/daily-cleanup.json +12 -0
  86. package/templates/schedules/hourly-health-check.json +12 -0
  87. package/templates/schedules/webhook-on-push.json +13 -0
  88. package/templates/schedules/weekly-digest.json +13 -0
  89. package/bizar-dash/dist/assets/icons-CFqu2M-c.js.map +0 -1
  90. package/bizar-dash/dist/assets/main-Dl8yY5_H.js +0 -16
  91. package/bizar-dash/dist/assets/main-Dl8yY5_H.js.map +0 -1
  92. package/bizar-dash/dist/assets/main-ZAfGKENE.css +0 -1
  93. package/bizar-dash/dist/assets/mobile-C2gysFOZ.js +0 -2
  94. package/bizar-dash/dist/assets/mobile-C2gysFOZ.js.map +0 -1
  95. package/bizar-dash/src/web/views/settings/BackupSection.tsx +0 -16
  96. package/bizar-dash/src/web/views/settings/ProvidersSection.tsx +0 -16
  97. package/bizar-dash/src/web/views/settings/SkillsSection.tsx +0 -16
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Mimir — Deep codebase research and exploration. Uses Semble as primary search tool. Architecture analysis, pattern discovery, documentation research, and project initialization.
3
3
  mode: subagent
4
- model: opencode/deepseek-v4-flash-free
4
+ model: minimax/MiniMax-M2.7
5
5
  color: "#06b6d4"
6
6
  permission:
7
7
  read: allow
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Quick (quick) — fast single-shot tasks. No delegation, no parallel streams. Use for small edits, mechanical changes, one-shot questions. Routes to no one.
3
3
  mode: primary
4
- model: minimax/MiniMax-M2.7
4
+ model: minimax/MiniMax-M2.7-Flash
5
5
  color: "#22d3ee"
6
6
  permission:
7
7
  read: allow
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Code search agent for exploring any codebase. Use for finding code by intent, locating implementations, understanding how something works, or discovering related code. Prefer over Bash/Read for any semantic or exploratory question.
3
3
  mode: subagent
4
- model: opencode/deepseek-v4-flash-free
4
+ model: minimax/MiniMax-M2.7
5
5
  color: "#64748b"
6
6
  permission:
7
7
  read: allow
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Vör — Asks clarifying questions for ambiguous or incomplete requests. Reads project context first, then asks one targeted, project-specific question.
3
3
  mode: subagent
4
- model: opencode/deepseek-v4-flash-free
4
+ model: minimax/MiniMax-M2.7
5
5
  color: "#a78bfa"
6
6
  permission:
7
7
  read: allow
@@ -37,7 +37,14 @@
37
37
  "loopThresholdWarn": 5,
38
38
  "loopThresholdEscalate": 8,
39
39
  "loopThresholdBlock": 12,
40
- "loopWindowSize": 10
40
+ "loopWindowSize": 10,
41
+ "compaction": {
42
+ "auto": true,
43
+ "threshold": 0.5,
44
+ "preserve_recent": 10,
45
+ "strategy": "summarize",
46
+ "model": "minimax/MiniMax-M3-Reasoning"
47
+ }
41
48
  }]
42
49
  ],
43
50
  "tools": {
@@ -66,9 +73,9 @@
66
73
  }
67
74
  },
68
75
  "vor": {
69
- "description": "Vör — Tier 2 clarifier. Reads project context first and asks targeted, project-specific questions when requests are ambiguous. Backed by DeepSeek V4 Flash. Operates inside BizarHarness alongside 13 sibling agents.",
76
+ "description": "Vör — Tier 2 clarifier. Reads project context first and asks targeted, project-specific questions when requests are ambiguous. Backed by MiniMax M2.7. Operates inside BizarHarness alongside 13 sibling agents.",
70
77
  "mode": "subagent",
71
- "model": "opencode/deepseek-v4-flash-free",
78
+ "model": "minimax/MiniMax-M2.7",
72
79
  "color": "#8b5cf6",
73
80
  "permission": {
74
81
  "read": "allow",
@@ -77,9 +84,9 @@
77
84
  }
78
85
  },
79
86
  "frigg": {
80
- "description": "Frigg — Tier 1 primary. Read-only Q&A agent that answers codebase questions with file:line citations, never edits. Backed by DeepSeek V4 Flash. Operates inside BizarHarness alongside 13 sibling agents.",
87
+ "description": "Frigg — Tier 1 primary. Read-only Q&A agent that answers codebase questions with file:line citations, never edits. Backed by MiniMax M2.7. Operates inside BizarHarness alongside 13 sibling agents.",
81
88
  "mode": "primary",
82
- "model": "opencode/deepseek-v4-flash-free",
89
+ "model": "minimax/MiniMax-M2.7",
83
90
  "color": "#06b6d4",
84
91
  "permission": {
85
92
  "read": "allow",
@@ -93,9 +100,9 @@
93
100
  }
94
101
  },
95
102
  "quick": {
96
- "description": "Quick — Tier 1 primary. Fast single-shot escape hatch for small edits, mechanical changes, and one-shot questions. No delegation, no parallel streams. Backed by MiniMax M2.7. Operates inside BizarHarness alongside 13 sibling agents.",
103
+ "description": "Quick — Tier 1 primary. Fast single-shot escape hatch for small edits, mechanical changes, and one-shot questions. No delegation, no parallel streams. Backed by MiniMax M2.7 Flash. Operates inside BizarHarness alongside 13 sibling agents.",
97
104
  "mode": "primary",
98
- "model": "minimax/MiniMax-M2.7",
105
+ "model": "minimax/MiniMax-M2.7-Flash",
99
106
  "color": "#22d3ee",
100
107
  "permission": {
101
108
  "read": "allow",
@@ -112,9 +119,9 @@
112
119
  }
113
120
  },
114
121
  "mimir": {
115
- "description": "Mimir — Tier 2 research. Dedicated codebase exploration agent who uses Semble as primary search tool for deep analysis, pattern discovery, and documentation research. Backed by DeepSeek V4 Flash. Operates inside BizarHarness alongside 13 sibling agents.",
122
+ "description": "Mimir — Tier 2 research. Dedicated codebase exploration agent who uses Semble as primary search tool for deep analysis, pattern discovery, and documentation research. Backed by MiniMax M2.7. Operates inside BizarHarness alongside 13 sibling agents.",
116
123
  "mode": "subagent",
117
- "model": "opencode/deepseek-v4-flash-free",
124
+ "model": "minimax/MiniMax-M2.7",
118
125
  "color": "#0ea5e9",
119
126
  "permission": {
120
127
  "read": "allow",
@@ -130,9 +137,9 @@
130
137
  }
131
138
  },
132
139
  "heimdall": {
133
- "description": "Heimdall — Tier 2 mechanical. Handles simple, routine, deterministic engineering tasks with speed and precision using DeepSeek V4 Flash. The ever-watchful guardian. Operates inside BizarHarness alongside 13 sibling agents.",
140
+ "description": "Heimdall — Tier 2 mechanical. Handles simple, routine, deterministic engineering tasks with speed and precision using MiniMax M2.7. The ever-watchful guardian. Operates inside BizarHarness alongside 13 sibling agents.",
134
141
  "mode": "subagent",
135
- "model": "opencode/deepseek-v4-flash-free",
142
+ "model": "minimax/MiniMax-M2.7",
136
143
  "color": "#10b981",
137
144
  "permission": {
138
145
  "read": "allow",
@@ -249,9 +256,9 @@
249
256
  }
250
257
  },
251
258
  "semble-search": {
252
- "description": "semble-search — Tier 2 research. Code search agent for exploring any codebase using Semble's semantic search. For finding code by intent, locating implementations, and understanding how things work. Backed by DeepSeek V4 Flash. Operates inside BizarHarness alongside 13 sibling agents.",
259
+ "description": "semble-search — Tier 2 research. Code search agent for exploring any codebase using Semble's semantic search. For finding code by intent, locating implementations, and understanding how things work. Backed by MiniMax M2.7. Operates inside BizarHarness alongside 13 sibling agents.",
253
260
  "mode": "subagent",
254
- "model": "opencode/deepseek-v4-flash-free",
261
+ "model": "minimax/MiniMax-M2.7",
255
262
  "color": "#0ea5e9",
256
263
  "permission": {
257
264
  "bash": "allow",
@@ -312,15 +319,15 @@
312
319
  },
313
320
  "provider": {
314
321
  "minimax": {
322
+ "options": {
323
+ "baseURL": "https://api.minimax.io/v1",
324
+ "apiKey": "{env:MiniMax_API_KEY}"
325
+ },
315
326
  "models": {
316
- "MiniMax-M3": {
317
- "interleaved": { "field": "reasoning_details" },
318
- "reasoning": true
319
- },
320
- "MiniMax-M2.7": {
321
- "interleaved": { "field": "reasoning_details" },
322
- "reasoning": true
323
- }
327
+ "MiniMax-M2.7-Flash": { "name": "MiniMax M2.7 Flash", "interleaved": { "field": "reasoning_details" }, "reasoning": true },
328
+ "MiniMax-M2.7": { "name": "MiniMax M2.7", "interleaved": { "field": "reasoning_details" }, "reasoning": true },
329
+ "MiniMax-M3": { "name": "MiniMax M3", "interleaved": { "field": "reasoning_details" }, "reasoning": true },
330
+ "MiniMax-M3-Reasoning": { "name": "MiniMax M3 Reasoning", "interleaved": { "field": "reasoning_details" }, "reasoning": true }
324
331
  }
325
332
  }
326
333
  }
@@ -28,7 +28,14 @@
28
28
  "loopThresholdWarn": 5,
29
29
  "loopThresholdEscalate": 8,
30
30
  "loopThresholdBlock": 12,
31
- "loopWindowSize": 10
31
+ "loopWindowSize": 10,
32
+ "compaction": {
33
+ "auto": true,
34
+ "threshold": 0.5,
35
+ "preserve_recent": 10,
36
+ "strategy": "summarize",
37
+ "model": "minimax/MiniMax-M3-Reasoning"
38
+ }
32
39
  }]
33
40
  ],
34
41
  "tools": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polderlabs/bizar",
3
- "version": "5.0.0",
3
+ "version": "5.0.2",
4
4
  "description": "Norse-pantheon multi-agent system for opencode — 13 agents across 4 cost tiers with cost-aware routing, plans, and a configurable agent harness. v4 ships as a single npm package bundling the dashboard server, opencode plugin, and typed SDK.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -143,6 +143,18 @@ import { executeSideEffect, type ExecuteOptions } from "./src/commands-impl.js";
143
143
  import { join as pathJoin } from "node:path";
144
144
  import { homedir } from "node:os";
145
145
 
146
+ // v0.6.3 — Compaction gate. Configures the compaction threshold from
147
+ // `rawOptions.compaction.threshold` (default 0.5) and wires two opencode
148
+ // hooks: `experimental.session.compacting` (push a Bizar-policy note onto
149
+ // the compaction prompt) and `experimental.compaction.autocontinue`
150
+ // (skip the synthetic "continue" turn when our policy decides to compact).
151
+ // The pure decision logic lives in `src/compaction.mjs`.
152
+ import {
153
+ getCompactionThreshold,
154
+ setCompactionThreshold,
155
+ resetCompactionDefaults,
156
+ } from "./src/compaction.mjs";
157
+
146
158
  // --- Env-var constants (per spec §8) -------------------------------------
147
159
 
148
160
  /** `BIZAR_SERVE_PORT` — default 0 (random). */
@@ -402,6 +414,29 @@ async function init(
402
414
  const logger = createLogger(input.client as unknown as Parameters<typeof createLogger>[0]);
403
415
  loggerHandle = logger;
404
416
 
417
+ // v0.6.3 — Compaction gate. Read the user-configured threshold from
418
+ // `rawOptions.compaction.threshold` (default 0.5). Invalid values are
419
+ // caught by `setCompactionThreshold` and logged; we fall back to the
420
+ // module default rather than crashing init (per spec §8.1: any init
421
+ // error must not break the plugin).
422
+ resetCompactionDefaults();
423
+ const compactionCfg = (rawOptions as Record<string, unknown> | undefined)
424
+ ?.compaction as { threshold?: unknown } | undefined;
425
+ if (compactionCfg && typeof compactionCfg.threshold === "number") {
426
+ try {
427
+ setCompactionThreshold(compactionCfg.threshold);
428
+ logger.info(
429
+ `bizar: compaction threshold set to ${compactionCfg.threshold} (from plugin options)`,
430
+ );
431
+ } catch (err) {
432
+ logger.warn(
433
+ `bizar: invalid compaction threshold ${String(compactionCfg.threshold)}; using default ${getCompactionThreshold()}: ${
434
+ err instanceof Error ? err.message : String(err)
435
+ }`,
436
+ );
437
+ }
438
+ }
439
+
405
440
  // §6.4 — refuse to start if logDir or stateDir is inside a secret dir.
406
441
  const offending = findOffendingPath(options);
407
442
  if (offending !== null) {
@@ -1412,6 +1447,48 @@ function buildHooks(ctx: RuntimeContext, bg: BgDeps): Hooks {
1412
1447
  // v0.4.2 — register the 4 background tools.
1413
1448
  tool: tools,
1414
1449
 
1450
+ // v0.6.3 — Compaction gate. Called by opencode BEFORE it starts a
1451
+ // session compaction. We append a one-line Bizar policy note so the
1452
+ // model summarises with our threshold in mind (the default opencode
1453
+ // compaction prompt doesn't know about our 50% trigger). The threshold
1454
+ // itself was set during `init()` from `rawOptions.compaction.threshold`.
1455
+ "experimental.session.compacting": async (_input, output) => {
1456
+ try {
1457
+ const threshold = getCompactionThreshold();
1458
+ output.context.push(
1459
+ `Bizar compaction policy: this compaction was triggered at the configured ${threshold} ratio of context usage. Preserve technical decisions, file paths, error messages, and unresolved questions verbatim in the summary; compress conversational filler.`,
1460
+ );
1461
+ } catch (err) {
1462
+ ctx.logger.warn(
1463
+ `bizar: experimental.session.compacting failed (passing through): ${
1464
+ err instanceof Error ? err.message : String(err)
1465
+ }`,
1466
+ );
1467
+ }
1468
+ },
1469
+
1470
+ // v0.6.3 — Compaction auto-continue gate. Called by opencode AFTER
1471
+ // compaction succeeds and BEFORE it injects a synthetic user "continue"
1472
+ // message. We disable auto-continue when compaction was actually
1473
+ // triggered (so the user sees the compacted state and can drive the
1474
+ // next step), and let auto-continue proceed otherwise. We can't read
1475
+ // the live usage ratio here, so we use the configured threshold as a
1476
+ // proxy: if it's been lowered below 1.0, the policy is "compact
1477
+ // early", and we want the user in the loop.
1478
+ "experimental.compaction.autocontinue": async (_input, output) => {
1479
+ try {
1480
+ if (getCompactionThreshold() < 1.0) {
1481
+ output.enabled = false;
1482
+ }
1483
+ } catch (err) {
1484
+ ctx.logger.warn(
1485
+ `bizar: experimental.compaction.autocontinue failed (passing through): ${
1486
+ err instanceof Error ? err.message : String(err)
1487
+ }`,
1488
+ );
1489
+ }
1490
+ },
1491
+
1415
1492
  // v0.4.2 — dispose hook. Opencode calls this when the plugin is
1416
1493
  // being torn down. We do a best-effort cleanup similar to the
1417
1494
  // signal trap, but we do NOT call `process.exit` — that's the
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Type declarations for `./compaction.mjs`.
3
+ *
4
+ * The runtime module is shipped as plain ESM JavaScript (`.mjs`) per the
5
+ * brief, but its consumers in `index.ts` and `tests/compaction.test.ts`
6
+ * are TypeScript. Without this companion declaration file, TypeScript
7
+ * would type the exports as `any`, which causes cascading `implicitly
8
+ * has 'any' type` errors at call sites (e.g. the `texts` parameter in
9
+ * the test's `summarizer` stubs).
10
+ *
11
+ * The declarations here mirror the contract documented in
12
+ * `./compaction.mjs`. They are NOT loaded at runtime — they exist only
13
+ * for the type-checker.
14
+ */
15
+
16
+ export interface CompactionResult {
17
+ compacted: boolean;
18
+ reason?: "below_threshold";
19
+ sessionId?: string;
20
+ threshold?: number;
21
+ preservedRecent?: number;
22
+ atMessages?: number;
23
+ ratio?: number | null;
24
+ }
25
+
26
+ export interface MaybeCompactSessionOpts {
27
+ sessionId: string;
28
+ messageCount: number;
29
+ currentUsage: { total?: number } | null | undefined;
30
+ maxContext: number | null | undefined;
31
+ summarizer: (texts: string[]) => Promise<string>;
32
+ preserveRecent?: number;
33
+ }
34
+
35
+ export function shouldCompact(
36
+ usage: { total?: number } | null | undefined,
37
+ maxContext: number | null | undefined,
38
+ ): boolean;
39
+
40
+ export function maybeCompactSession(opts: MaybeCompactSessionOpts): Promise<CompactionResult>;
41
+
42
+ export function getCompactionThreshold(): number;
43
+
44
+ export function setCompactionThreshold(value: number): void;
45
+
46
+ export function resetCompactionDefaults(): void;
47
+
48
+ export function getDefaultPreserveRecent(): number;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * compaction.mjs
3
+ *
4
+ * Context-window compaction gate.
5
+ *
6
+ * Monitors a chat session's context-usage ratio and reports whether the
7
+ * session has reached the compaction threshold (default 50% of the model's
8
+ * max-context window). When the ratio crosses the threshold, callers can
9
+ * trigger summarization of the older message history while preserving a
10
+ * configurable recent tail so the model retains short-term continuity.
11
+ *
12
+ * Spec contract:
13
+ * - The threshold is the *ratio* `usage.total / maxContext`, NOT an
14
+ * absolute token count. This makes the gate model-agnostic — it works
15
+ * whether the model has a 32k, 128k, or 1M context window.
16
+ * - `shouldCompact` is a pure function: same inputs → same output, no I/O.
17
+ * - `maybeCompactSession` is async to match the real summarizer signature
18
+ * but performs no I/O itself when below threshold — it short-circuits.
19
+ * - Threshold is mutable via `setCompactionThreshold` and is validated
20
+ * against the range [0.1, 1.0]. A throw is the right signal here —
21
+ * misconfiguration should fail loudly at startup, not silently use a
22
+ * bad value at runtime.
23
+ * - Threshold uses `let` (not `const`) so the setter can mutate it.
24
+ * The reference spec used `const` and would throw a TypeError on
25
+ * assignment; this implementation keeps the API but fixes the bug.
26
+ */
27
+
28
+ const PRESERVE_RECENT_MESSAGES_DEFAULT = 10;
29
+ const MIN_THRESHOLD = 0.1;
30
+ const MAX_THRESHOLD = 1.0;
31
+
32
+ // Module-level threshold. Exposed via get/set for tunability.
33
+ // Exported as a number via getCompactionThreshold(); the underlying binding
34
+ // is private (not exported) so callers cannot bypass validation by writing
35
+ // to it directly.
36
+ let compactionThreshold = 0.5;
37
+
38
+ /**
39
+ * Returns `true` when `usage.total / maxContext` meets or exceeds the
40
+ * compaction threshold. `false` when below, or when either input is
41
+ * missing/invalid (defensive default).
42
+ *
43
+ * @param {{ total?: number } | null | undefined} usage
44
+ * Object with a `total` token count, or null/undefined.
45
+ * @param {number | null | undefined} maxContext
46
+ * Maximum context window size in tokens.
47
+ * @returns {boolean}
48
+ */
49
+ export function shouldCompact(usage, maxContext) {
50
+ if (!usage || typeof usage.total !== "number") return false;
51
+ if (typeof maxContext !== "number" || maxContext <= 0) return false;
52
+ const ratio = usage.total / maxContext;
53
+ return ratio >= compactionThreshold;
54
+ }
55
+
56
+ /**
57
+ * Decision-shaped result returned by `maybeCompactSession`.
58
+ *
59
+ * - When below threshold: `{ compacted: false, reason: "below_threshold", ratio }`.
60
+ * - When at/over threshold: `{ compacted: true, sessionId, threshold,
61
+ * preservedRecent, atMessages, ratio }`.
62
+ *
63
+ * @typedef {Object} CompactionResult
64
+ * @property {boolean} compacted
65
+ * @property {"below_threshold"} [reason] when compacted=false
66
+ * @property {string} [sessionId]
67
+ * @property {number} [threshold] the threshold at decision time
68
+ * @property {number} [preservedRecent] how many recent messages to keep verbatim
69
+ * @property {number} [atMessages] message count at decision time
70
+ * @property {number} [ratio] usage.total / maxContext
71
+ */
72
+
73
+ /**
74
+ * Decide whether to compact and, if so, record the decision. The summarizer
75
+ * is NOT invoked here — that is the caller's responsibility. This function
76
+ * is the decision gate, not the executor. (The summarizer receives an
77
+ * `Array<string>` of older messages and returns a single summary string.)
78
+ *
79
+ * @param {Object} opts
80
+ * @param {string} opts.sessionId
81
+ * @param {number} opts.messageCount total messages in the session
82
+ * @param {{ total?: number } | null | undefined} opts.currentUsage
83
+ * @param {number | null | undefined} opts.maxContext
84
+ * @param {(texts: string[]) => Promise<string>} opts.summarizer
85
+ * Async summarizer used by the caller when `compacted === true`. Not invoked
86
+ * here. Accepting it as a parameter documents the contract for downstream
87
+ * callers without forcing this function to do I/O.
88
+ * @param {number} [opts.preserveRecent=10] how many recent messages to keep verbatim
89
+ * @returns {Promise<CompactionResult>}
90
+ */
91
+ export async function maybeCompactSession({
92
+ sessionId,
93
+ messageCount,
94
+ currentUsage,
95
+ maxContext,
96
+ // summarizer is accepted for API symmetry with downstream callers; we do
97
+ // not invoke it here because compaction execution lives in the plugin
98
+ // hook layer, not in this pure decision gate.
99
+ summarizer, // eslint-disable-line no-unused-vars
100
+ preserveRecent = PRESERVE_RECENT_MESSAGES_DEFAULT,
101
+ }) {
102
+ if (typeof sessionId !== "string" || sessionId === "") {
103
+ // Misuse — caller forgot a sessionId. Refuse rather than silently
104
+ // returning below_threshold, which would mask a real bug upstream.
105
+ throw new Error("maybeCompactSession: sessionId is required");
106
+ }
107
+
108
+ if (!shouldCompact(currentUsage, maxContext)) {
109
+ const ratio = computeRatio(currentUsage, maxContext);
110
+ return { compacted: false, reason: "below_threshold", ratio };
111
+ }
112
+
113
+ const ratio = computeRatio(currentUsage, maxContext);
114
+ return {
115
+ compacted: true,
116
+ sessionId,
117
+ threshold: compactionThreshold,
118
+ preservedRecent: preserveRecent,
119
+ atMessages: messageCount,
120
+ ratio,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Return the current compaction threshold (0.0–1.0).
126
+ *
127
+ * @returns {number}
128
+ */
129
+ export function getCompactionThreshold() {
130
+ return compactionThreshold;
131
+ }
132
+
133
+ /**
134
+ * Set the compaction threshold. Validates the new value is in the range
135
+ * `[0.1, 1.0]` and is a finite number. Throws on invalid input.
136
+ *
137
+ * The minimum of 0.1 prevents pathological "compact at 10%" configurations
138
+ * that would shred the conversation on the first reply. The maximum of 1.0
139
+ * means "compact only when the context is full" — anything above 1.0 would
140
+ * mean "never compact", which `shouldCompact` already handles correctly, so
141
+ * we reject it for clarity.
142
+ *
143
+ * @param {number} value
144
+ * @returns {void}
145
+ */
146
+ export function setCompactionThreshold(value) {
147
+ if (typeof value !== "number" || !Number.isFinite(value)) {
148
+ throw new Error(`Invalid compaction threshold: ${value} (must be a finite number)`);
149
+ }
150
+ if (value < MIN_THRESHOLD || value > MAX_THRESHOLD) {
151
+ throw new Error(
152
+ `Invalid compaction threshold: ${value} (must be in [${MIN_THRESHOLD}, ${MAX_THRESHOLD}])`,
153
+ );
154
+ }
155
+ compactionThreshold = value;
156
+ }
157
+
158
+ /**
159
+ * Reset the threshold and preserve-count to their defaults. Exposed for
160
+ * tests and for plugin re-init (so a hot-reload doesn't carry stale state).
161
+ *
162
+ * @returns {void}
163
+ */
164
+ export function resetCompactionDefaults() {
165
+ compactionThreshold = 0.5;
166
+ }
167
+
168
+ /**
169
+ * Return the number of recent messages that the default policy preserves
170
+ * verbatim when compacting.
171
+ *
172
+ * @returns {number}
173
+ */
174
+ export function getDefaultPreserveRecent() {
175
+ return PRESERVE_RECENT_MESSAGES_DEFAULT;
176
+ }
177
+
178
+ // --- Internal helpers -----------------------------------------------------
179
+
180
+ /**
181
+ * Compute `usage.total / maxContext`, or `null` when either input is
182
+ * missing/invalid. Returns a number in `[0, +Infinity)` for valid inputs.
183
+ *
184
+ * @param {{ total?: number } | null | undefined} usage
185
+ * @param {number | null | undefined} maxContext
186
+ * @returns {number | null}
187
+ */
188
+ function computeRatio(usage, maxContext) {
189
+ if (!usage || typeof usage.total !== "number") return null;
190
+ if (typeof maxContext !== "number" || maxContext <= 0) return null;
191
+ return usage.total / maxContext;
192
+ }