@krtclcdy/tersio 2.25.5 → 2.25.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +17 -36
  2. package/dashboard/dist/index.html +15 -15
  3. package/dist/cli/backups.js +7 -14
  4. package/dist/cli/banner.js +4 -3
  5. package/dist/cli/common.js +28 -12
  6. package/dist/cli/currency.js +1 -1
  7. package/dist/cli/dashboard.js +66 -35
  8. package/dist/cli/doctor-fix.js +204 -19
  9. package/dist/cli/doctor.js +226 -39
  10. package/dist/cli/hosts.js +25 -5
  11. package/dist/cli/install.js +144 -48
  12. package/dist/cli/interactive.js +3 -3
  13. package/dist/cli/manifest.js +87 -7
  14. package/dist/cli/profile.js +13 -8
  15. package/dist/cli/rtk-wiring.js +1 -1
  16. package/dist/cli/settings.js +20 -5
  17. package/dist/cli/uninstall.js +3 -3
  18. package/dist/cli/update.js +6 -7
  19. package/dist/cli/usage.js +6 -9
  20. package/dist/extensions/caveman/index.js +4 -2
  21. package/dist/extensions/caveman/rule-megacave.md +5 -3
  22. package/dist/extensions/caveman/rule-ultra.md +4 -4
  23. package/dist/extensions/caveman/rule.md +55 -45
  24. package/dist/extensions/combo/index.js +62 -21
  25. package/dist/extensions/commands/index.js +1 -1
  26. package/dist/extensions/pstack/index.js +119 -0
  27. package/dist/extensions/pstack/rule.md +65 -0
  28. package/dist/extensions/rtk/filter.js +0 -1
  29. package/dist/extensions/rtk/session.js +4 -4
  30. package/dist/extensions/server.js +90 -6
  31. package/dist/extensions/shared/agent-stats.js +214 -278
  32. package/dist/extensions/shared/brand-marks.js +33 -34
  33. package/dist/extensions/shared/carbon.js +1 -1
  34. package/dist/extensions/shared/plugin-settings.js +11 -6
  35. package/dist/extensions/shared/pricing.js +8 -16
  36. package/dist/extensions/shared/rtk-gain.js +4 -9
  37. package/dist/extensions/shared/session-state.js +15 -10
  38. package/dist/extensions/shared/sqlite.js +168 -0
  39. package/dist/extensions/shared/status.js +8 -8
  40. package/dist/extensions/shared/types.js +1 -1
  41. package/dist/extensions/shared/usage-ledger.js +53 -41
  42. package/dist/extensions/shared/usage-store.js +111 -52
  43. package/dist/extensions/shared/utils.js +5 -5
  44. package/dist/extensions/timing/index.js +31 -0
  45. package/dist/extensions/updater/index.js +3 -6
  46. package/dist/tersio.js +8 -3
  47. package/extensions/caveman/index.ts +4 -2
  48. package/extensions/caveman/rule-megacave.md +5 -3
  49. package/extensions/caveman/rule-ultra.md +4 -4
  50. package/extensions/caveman/rule.md +55 -45
  51. package/extensions/combo/index.ts +62 -19
  52. package/extensions/commands/index.ts +1 -1
  53. package/extensions/pstack/index.ts +128 -0
  54. package/extensions/pstack/rule.md +65 -0
  55. package/extensions/rtk/filter.ts +0 -1
  56. package/extensions/rtk/session.ts +4 -4
  57. package/extensions/server.ts +72 -7
  58. package/extensions/shared/agent-stats.ts +226 -278
  59. package/extensions/shared/brand-marks.ts +34 -34
  60. package/extensions/shared/carbon.ts +1 -1
  61. package/extensions/shared/plugin-settings.ts +12 -6
  62. package/extensions/shared/pricing.ts +10 -26
  63. package/extensions/shared/rtk-gain.ts +4 -9
  64. package/extensions/shared/session-state.ts +18 -13
  65. package/extensions/shared/sqlite.ts +168 -0
  66. package/extensions/shared/status.ts +9 -8
  67. package/extensions/shared/types.ts +2 -1
  68. package/extensions/shared/usage-ledger.ts +60 -47
  69. package/extensions/shared/usage-store.ts +120 -52
  70. package/extensions/shared/utils.ts +5 -5
  71. package/extensions/timing/index.ts +45 -0
  72. package/extensions/updater/index.ts +3 -8
  73. package/package.json +17 -8
@@ -1,10 +1,4 @@
1
- // Brand mark catalog: names, not bytes. One list serves both consumers — the dashboard draws from
2
- // it at runtime, and the CLI export inlines the same URLs so a single-file dashboard keeps its
3
- // logos with the network off. Simple Icons files are CC0-1.0; the marks stay their owners'
4
- // property and the dashboard uses them nominatively, to name the service that served a request.
5
- // A vendor with no Simple Icons entry keeps its owner-hosted mark, one with no hosted mark is
6
- // drawn inline (`dashboard/app/src/lib/marks/inline.ts`), and bumping `SIMPLE_ICONS` once moves
7
- // every Simple Icons entry with it.
1
+ // Brand mark catalog: names not bytes; Simple Icons files are CC0-1.0, marks remain their owners'.
8
2
  const SIMPLE_ICONS = "https://cdn.jsdelivr.net/npm/simple-icons@16/icons";
9
3
 
10
4
  /** Slug to mark URL. Only slugs named here resolve to a mark; the rest get a monogram. */
@@ -34,6 +28,8 @@ export const REMOTE_MARKS: Readonly<Record<string, string>> = {
34
28
  // Owner-hosted, nominative use.
35
29
  groq: "https://groq.com/favicon.svg",
36
30
  poolside: "https://poolside.ai/favicon/favicon.svg",
31
+ // AWS owns Kiro; Wikimedia hosts its vector, as AWS serves only a 16x16 ICO that cannot grow into a tile.
32
+ amazonaws: "https://upload.wikimedia.org/wikipedia/commons/5/5c/AWS_Simple_Icons_AWS_Cloud.svg",
37
33
  cerebras:
38
34
  "https://cdn.sanity.io/images/e4qjo92p/production/e7a55ae5ab7e2c4fdfd4e66a51f628d1f2f44207-967x967.png?w=256&h=256&fit=max",
39
35
  inclusionai: "https://cdn-avatars.huggingface.co/v1/production/uploads/662e1f9da266499277937d33/fyKuazRifqiaIO34xrhhm.jpeg",
@@ -48,14 +44,18 @@ export const REMOTE_MARKS: Readonly<Record<string, string>> = {
48
44
  magpie: "https://usemagpie.ai/favicon.png",
49
45
  gmicloud: "https://gmicloud.ai/favicon.ico",
50
46
  charmhyper: "https://github.com/charmbracelet.png?size=80",
47
+ // WorkBuddy's own favicon, a hashed asset on the Tencent CDN its page serves.
48
+ workbuddy:
49
+ "https://download.codebuddy.ai/web/workbuddy/913b2390aae396c66b937bd9143ae5259306d7d7/assets/logo.svg",
50
+ // Trae's own favicon: a dark tile carrying its green mark, so the tile matches the artwork.
51
+ trae: "https://lf16-web-neutral.traecdn.ai/obj/trae-ai-static/trae_website/favicon.png",
52
+ // Kiro's own icon, a purple tile with the mark drawn inside it.
53
+ kiro: "https://kiro.dev/icon.svg",
54
+ // Meituan's own icon: its yellow tile with the logotype.
55
+ meituan: "https://s3plus.meituan.net/v1/mss_e2821d7f0cfe4ac1bf9202ecf9590e67/cdn-prod/file:1040877d/favicon-mt.ico",
51
56
  };
52
57
 
53
- /**
54
- * Tile fill, not text. A mark whose tile carries its brand color reads as the brand, and a mark
55
- * whose logo already fills its own box never shows the fill. Values come from the brand (the
56
- * service's own page or its own asset), never from a guess; a slug absent here keeps the plain
57
- * panel and the theme ink.
58
- */
58
+ /** Tile fill per slug from the brand's own page, never a guess; an absent slug keeps the plain panel. */
59
59
  export const MARK_BG: Readonly<Record<string, string>> = {
60
60
  // Simple Icons marks: the vendor's brand color, taken from its own brand page.
61
61
  anthropic: "#d97757",
@@ -80,8 +80,7 @@ export const MARK_BG: Readonly<Record<string, string>> = {
80
80
  instagram: "#e4405f",
81
81
  reddit: "#ff4500",
82
82
  linkedin: "#0a66c2",
83
- // Owner-hosted marks: the tile matches the asset's own square, and a slug whose artwork already
84
- // carries its own color takes a white tile so the art reads.
83
+ // Owner-hosted marks match the asset's own square; art that already carries color takes a white tile.
85
84
  groq: "#f43e01",
86
85
  poolside: "#4137ff",
87
86
  cerebras: "#ffffff",
@@ -90,18 +89,22 @@ export const MARK_BG: Readonly<Record<string, string>> = {
90
89
  stepfun: "#ffffff",
91
90
  kilo: "#f7f576",
92
91
  opencode: "#131010",
92
+ // The AWS cloud mark draws its own orange and its own white, so the tile stays plain white.
93
+ amazonaws: "#ffffff",
93
94
  // The mark's own artwork is white, so the tile is white and the glyph is black.
94
95
  openai: "#ffffff",
95
96
  commandcode: "#ffffff",
96
97
  gmicloud: "#ffffff",
97
98
  magpie: "#0b0b0c",
99
+ // WorkBuddy's mark is a full-bleed teal tile carrying its own white art.
100
+ workbuddy: "#01c886",
101
+ // The mark is a full-bleed tile, so the tile fill repeats the artwork's own background.
102
+ trae: "#000000",
103
+ kiro: "#9046ff",
104
+ meituan: "#ffd100",
98
105
  };
99
106
 
100
- /**
101
- * Glyph scale per slug, applied to the glyph box the tile clips. Simple Icons art fills its 24 box
102
- * by very different amounts, so the measured ink box decides the scale: a logo that runs to its
103
- * box edge shrinks and one with an invisible margin grows. One is the default.
104
- */
107
+ /** Glyph scale per slug over the tile clip; the measured ink box decides, and one is the default. */
105
108
  export const MARK_SCALE: Readonly<Record<string, number>> = {
106
109
  kimi: 0.72,
107
110
  zdotai: 0.72,
@@ -119,21 +122,12 @@ export function luminance(hex: string): number {
119
122
  return 0.2126 * ch[0] + 0.7152 * ch[1] + 0.0722 * ch[2];
120
123
  }
121
124
 
122
- /**
123
- * The glyph color that stays legible on a tile fill. The cut sits at 0.35, which keeps white ink
124
- * on a brand color: Meta blue, DeepSeek blue, Xiaomi orange, Mistral orange, and Kimi blue all
125
- * carry a white logo, which is how their own brand sheets print them. Only a light neutral takes
126
- * black: Kilo yellow, StepFun teal, and Lightbend orange.
127
- */
125
+ /** The ink legible on a tile fill: luminance above 0.35 takes black, else white. */
128
126
  export function contrastInk(hex: string): string {
129
127
  return luminance(hex) > 0.35 ? "#000000" : "#ffffff";
130
128
  }
131
129
 
132
- /**
133
- * Marks that carry their own color or their own background. Everything else is opaque black, so
134
- * it draws as an alpha mask filled with the chosen ink instead of an image. A slug whose asset is
135
- * a filled tile must draw as an image, or the mask paints one flat block and the logo vanishes.
136
- */
130
+ /** Marks carrying their own color or background; a filled-tile asset must draw as an image, not a mask. */
137
131
  export const COLORED_MARKS: ReadonlySet<string> = new Set([
138
132
  "cerebras",
139
133
  "inclusionai",
@@ -144,12 +138,18 @@ export const COLORED_MARKS: ReadonlySet<string> = new Set([
144
138
  "magpie",
145
139
  "charmhyper",
146
140
  "stepfun",
147
- // The ICO and the two inline PNGs are dark tiles with light art drawn inside them. The Groq
148
- // favicon is one flat orange, so it draws as a mask instead: a masked glyph on a Groq-orange
149
- // tile is a logo, and the same art as an image on the same orange tile is a blank tile.
141
+ // The ICO and inline PNGs are dark tiles with light art; flat-orange Groq draws as a mask instead.
150
142
  "gmicloud",
151
143
  "stealth",
152
144
  "cognition",
145
+ // A full-bleed teal tile with its own white art, so a mask would flatten both into one ink.
146
+ "workbuddy",
147
+ // Each is a full-bleed brand tile with its own ink, so a mask would flatten both into one color.
148
+ "trae",
149
+ "kiro",
150
+ "meituan",
151
+ // Carries its own orange and its own white, so a mask would flatten both into one ink.
152
+ "amazonaws",
153
153
  ]);
154
154
 
155
155
  /** The URL a mark comes from, or null when the name has no hosted mark. */
@@ -44,7 +44,7 @@ interface RegistryEntry {
44
44
  source: 'registry' | 'borrowed';
45
45
  }
46
46
 
47
- // Registry values verbatim from EcoLogits' model_repository; borrows cite the public param disclosure they stand in for (MoE active/total).
47
+ // Verbatim from EcoLogits' model_repository; borrows cite the param disclosure they replace (MoE active/total).
48
48
  const TABLE: RegistryEntry[] = [
49
49
  { match: 'opus', active: 625.0, total: 2000, provider: 'anthropic', source: 'registry' },
50
50
  { match: 'sonnet', active: 137.5, total: 440, provider: 'anthropic', source: 'registry' },
@@ -11,7 +11,7 @@ export function tersioSettingsFile(): string {
11
11
  return path.join(tersioHome(), 'settings.json');
12
12
  }
13
13
 
14
- // Older installs kept these as OMP plugin settings; still read so switching the store does not reset a user's defaults.
14
+ // Older installs kept these as OMP plugin settings; still read so switching stores does not reset a user's defaults.
15
15
  function legacyOmpSettings(): Record<string, unknown> | null {
16
16
  const configHome = process.env.XDG_CONFIG_HOME || path.join(homeDir(), '.config');
17
17
  for (const p of [
@@ -39,7 +39,7 @@ function readSettingsFile(): Record<string, unknown> | null {
39
39
  }
40
40
  }
41
41
 
42
- // The stored settings; empty when the file is missing, corrupt, or empty.
42
+ // The stored settings; {} when the file is missing or corrupt.
43
43
  export function readPluginSettings(): Record<string, unknown> {
44
44
  return readSettingsFile() ?? legacyOmpSettings() ?? {};
45
45
  }
@@ -47,6 +47,8 @@ export function readPluginSettings(): Record<string, unknown> {
47
47
  const COMBO_LEVELS = new Set(['off', 'medium', 'balanced', 'max']);
48
48
  const CAVEMAN_MODES = new Set(['off', 'lite', 'full', 'ultra', 'megacave', 'megacave-lite', 'megacave-full', 'megacave-ultra', 'wenyan', 'wenyan-lite', 'wenyan-full', 'wenyan-ultra']);
49
49
  const PONYTAIL_MODES = new Set(['off', 'lite', 'full', 'ultra']);
50
+ // Opt-in only: no combo preset writes this, so it never reaches a user who did not ask for it.
51
+ const PSTACK_MODES = new Set(['off', 'on']);
50
52
 
51
53
  function readStringDefault(key: string, valid: Set<string>): string {
52
54
  const raw = readPluginSettings()[key];
@@ -70,15 +72,19 @@ export function readPonytailDefault(): string {
70
72
  return readStringDefault('ponytailDefault', PONYTAIL_MODES);
71
73
  }
72
74
 
75
+ export function readPstackDefault(): string {
76
+ return readStringDefault('pstackDefault', PSTACK_MODES);
77
+ }
78
+
73
79
  export function isComboSetupComplete(): boolean {
74
80
  return readPluginSettings().comboSetupComplete === true;
75
81
  }
76
82
 
77
83
  const COMBO_MODE_DEFAULTS = {
78
- off: { cavemanDefault: 'off', rtkDefault: false, ponytailDefault: 'off' },
79
- medium: { cavemanDefault: 'lite', rtkDefault: true, ponytailDefault: 'lite' },
80
- balanced: { cavemanDefault: 'full', rtkDefault: true, ponytailDefault: 'full' },
81
- max: { cavemanDefault: 'ultra', rtkDefault: true, ponytailDefault: 'ultra' },
84
+ off: { cavemanDefault: 'off', rtkDefault: false, ponytailDefault: 'off', pstackDefault: 'off' },
85
+ medium: { cavemanDefault: 'lite', rtkDefault: true, ponytailDefault: 'lite', pstackDefault: 'on' },
86
+ balanced: { cavemanDefault: 'full', rtkDefault: true, ponytailDefault: 'full', pstackDefault: 'on' },
87
+ max: { cavemanDefault: 'ultra', rtkDefault: true, ponytailDefault: 'ultra', pstackDefault: 'on' },
82
88
  } as const;
83
89
 
84
90
  export function saveComboSetup(level: string): boolean {
@@ -1,4 +1,4 @@
1
- // extensions/shared/pricing.ts — dynamic model pricing from LiteLLM. Exact id → provider-prefix strip → default, reported with known:false when unpriced.
1
+ // pricing.ts — model pricing from LiteLLM. Exact id → prefix strip → default, known:false if unpriced.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { tersioDataPath } from './utils.ts';
@@ -13,18 +13,10 @@ export interface ModelPrice {
13
13
  // Sonnet-class default for unpriced models; always paired with known:false.
14
14
  export const DEFAULT_PRICE: ModelPrice = { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 };
15
15
 
16
- /**
17
- * How a price was found, strongest first. `tail` and `default` are estimates.
18
- *
19
- * - `measured`: the host reported it. The only tier that can be zero without being a guess.
20
- * - `override`: the operator's `prices.local.json`, exact for the gateway it names.
21
- * - `exact`: the feed holds the id verbatim, or case-folded. `alias`: via `MODEL_ALIASES`.
22
- * - `tail`: the feed holds the bare name under some provider, which need not be the one billed.
23
- * - `default`: no match. `DEFAULT_PRICE`, an estimate by definition.
24
- */
16
+ /** How a price was found, strongest first; `tail` and `default` are estimates. */
25
17
  export type PriceTier = 'measured' | 'override' | 'exact' | 'alias' | 'tail' | 'default';
26
18
 
27
- /** Tiers firm enough to call a price. `tail` and `default` are estimates, so they are not. */
19
+ /** Tiers firm enough to call a price; `tail` and `default` are estimates. */
28
20
  export const PRICE_TIERS_FIRM: readonly PriceTier[] = ['measured', 'override', 'exact', 'alias'];
29
21
 
30
22
  export interface PriceHit {
@@ -35,7 +27,7 @@ export interface PriceHit {
35
27
  }
36
28
 
37
29
  const LITELLM_URL = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
38
- // Readers use the file even when stale, and only one refresh runs per process; `tersio update` still forces a fresh fetch.
30
+ // Readers use the file even when stale; one refresh per process. `tersio update` still forces a fresh fetch.
39
31
  const CACHE_TTL_MS = 7 * 24 * 3600 * 1000;
40
32
  let refreshInflight: Promise<boolean> | null = null;
41
33
 
@@ -45,11 +37,7 @@ export function pricesCachePath(): string {
45
37
  return tersioDataPath('prices.json', 'tersio-prices.json');
46
38
  }
47
39
 
48
- /**
49
- * The operator's own prices, merged over the feed and keyed exactly as the transcript spells a
50
- * model. A `*` prefix matches any gateway suffix. This is where a model the feed keys under a
51
- * different provider gets a real price.
52
- */
40
+ /** Operator prices keyed as the transcript spells a model; a `*` prefix matches any gateway suffix. */
53
41
  export function pricesOverridePath(): string {
54
42
  const override = process.env.TERSIO_PRICES_OVERRIDE_FILE;
55
43
  if (override) return override;
@@ -79,7 +67,6 @@ function loadOverrides(stamp = overrideStamp()): { exact: Map<string, ModelPrice
79
67
  for (const [id, row] of Object.entries(parsed ?? {})) {
80
68
  const price = asPrice(row);
81
69
  if (!price) continue;
82
- // A `*` prefix matches any gateway prefix, so one entry covers every spelling of a model.
83
70
  if (id.startsWith('*')) tails.push([id.slice(1).toLowerCase(), price]);
84
71
  else exact.set(id, price);
85
72
  }
@@ -94,7 +81,7 @@ export function pricesUrl(): string {
94
81
 
95
82
  export interface LivePrices {
96
83
  fetchedAt: number;
97
- // Compact tuples [input, output, cacheRead, cacheWrite] per LiteLLM id — the full feed caches to ~1MB instead of multi-MB objects.
84
+ // Tuples [input, output, cacheRead, cacheWrite] per LiteLLM id — the full feed caches to ~1MB, not multi-MB objects.
98
85
  exact: Record<string, [number, number, number, number]>;
99
86
  deprecated?: string[];
100
87
  }
@@ -192,7 +179,7 @@ export function priceFor(model: string, live?: LivePrices | null): PriceHit {
192
179
  return resolvePrice(model, table, overrideStamp());
193
180
  }
194
181
 
195
- // Recent rows repeat a handful of models; the memo turns thousands of lookups into one per model. Cleared whenever the table identity changes.
182
+ // Recent rows repeat a few models; the memo turns thousands of lookups into one per model. Cleared on table change.
196
183
  let memoTable: LivePrices | null | undefined;
197
184
  let memoStamp = 0;
198
185
  let memo = new Map<string, PriceHit>();
@@ -227,21 +214,18 @@ function resolvePrice(model: string, table: LivePrices | null, stamp = overrideS
227
214
  }
228
215
  }
229
216
 
230
- // An alias goes through the same chain as any other id, so it still resolves when the feed keys
231
- // it under a provider prefix.
217
+ // An alias runs the same chain, so it still resolves when the feed keys it under a provider prefix.
232
218
  const alias = MODEL_ALIASES.find((a) => a.id === model.toLowerCase());
233
219
  const id = alias?.feed ?? model;
234
220
  if (table) {
235
221
  const entries = priceEntries(table);
236
- // 1. The id verbatim, then case-folded. Nothing is being guessed here.
222
+ // The id verbatim, then case-folded; nothing guessed.
237
223
  const hit = entries.find(([k]) => k === id) ?? entries.find(([k]) => k === id.toLowerCase());
238
224
  if (hit) return { price: hit[1], known: true, live: true, tier: alias ? 'alias' : 'exact' };
239
225
 
240
226
  const lower = id.toLowerCase();
241
227
  const tail = lower.split('/').pop() ?? lower;
242
- // The bare model name under any provider, which need not be the provider that billed the row.
243
- // Reported as tier `tail`, so a caller keeps it out of a firm total; `prices.local.json` fixes
244
- // a specific case.
228
+ // Bare name under any provider (need not be the billing one); tier `tail` keeps it out of a firm total.
245
229
  const bare = entries.find(([k]) => {
246
230
  const lk = k.toLowerCase();
247
231
  return lk === tail || lk.endsWith(`/${tail}`);
@@ -1,8 +1,8 @@
1
1
  // Savings read from rtk history, never estimated; modes bench in docs/BENCHMARK.md.
2
- import { execFileSync } from 'node:child_process';
3
2
  import fs from 'node:fs';
4
3
  import os from 'node:os';
5
4
  import path from 'node:path';
5
+ import { sqliteRead } from './sqlite.ts';
6
6
 
7
7
  export interface RtkCommandRow {
8
8
  command: string;
@@ -23,7 +23,7 @@ export interface RtkGain {
23
23
 
24
24
  const EMPTY: RtkGain = { commands: 0, saved: 0, input: 0, avgPct: 0, totalMs: 0, byCommand: [] };
25
25
 
26
- // The table shows one clipped cell, so bound the command before it crosses the sqlite3 CLI and lands in every /data.json poll.
26
+ // The table shows one clipped cell, so bound the command before it reaches /data.json.
27
27
  const MAX_CMD_CHARS = 200;
28
28
 
29
29
  // A multi-line stored command would derail every row after it; flatten on read.
@@ -40,12 +40,7 @@ export function rtkDbPath(): string {
40
40
  }
41
41
 
42
42
  function query(db: string, sql: string): string[][] {
43
- const out = execFileSync('sqlite3', ['-separator', '\t', db, sql], {
44
- encoding: 'utf8',
45
- timeout: 5000,
46
- stdio: ['ignore', 'pipe', 'ignore'],
47
- });
48
- return out
43
+ return sqliteRead(db, sql)
49
44
  .split('\n')
50
45
  .filter((line) => line.trim())
51
46
  .map((line) => line.split('\t'));
@@ -54,7 +49,7 @@ function query(db: string, sql: string): string[][] {
54
49
  export function readRtkGain(limit = 10, cutoffMs?: number): RtkGain {
55
50
  try {
56
51
  if (!fs.existsSync(rtkDbPath())) return EMPTY;
57
- // View-level cutoff only: rtk's own rows stay untouched. Timestamps that do not parse land on 0 and drop out of a filtered view.
52
+ // View-level cutoff only: rtk's rows stay untouched. Unparseable timestamps land on 0 and drop from filtered views.
58
53
  const where = cutoffMs && cutoffMs > 0
59
54
  ? `WHERE CAST(strftime('%s', timestamp) AS INTEGER) >= ${Math.floor(cutoffMs / 1000)}`
60
55
  : '';
@@ -3,32 +3,35 @@ import type { ComboLevel, ComboState, ExtensionCtx, SessionEntry } from './types
3
3
 
4
4
  const BRIDGE_KEY = Symbol.for('tersio/combo-session-state');
5
5
 
6
- // A verbatim sentence from omp's subagent prompt, so it can drift; read from the installed omp binary on 2026-10-01. pi has no built-in subagent prompt.
6
+ // A verbatim sentence from omp's subagent prompt, so it can drift; read from the installed omp binary on 2026-10-01.
7
7
  export const OMP_SUBAGENT_MARKER = 'Worker agent: delegated tasks.';
8
8
 
9
+ // Every level above off turns pstack on with the other three; off is the one level without it.
9
10
  export const COMBO_LEVELS: Record<string, Readonly<ComboState>> = Object.freeze({
10
- off: Object.freeze({ level: 'off', caveman: 'off', rtk: 'off', ponytail: 'off' }),
11
- medium: Object.freeze({ level: 'medium', caveman: 'lite', rtk: 'on', ponytail: 'lite' }),
12
- balanced: Object.freeze({ level: 'balanced', caveman: 'full', rtk: 'on', ponytail: 'full' }),
13
- max: Object.freeze({ level: 'max', caveman: 'ultra', rtk: 'on', ponytail: 'ultra' }),
11
+ off: Object.freeze({ level: 'off', caveman: 'off', rtk: 'off', ponytail: 'off', pstack: 'off' }),
12
+ medium: Object.freeze({ level: 'medium', caveman: 'lite', rtk: 'on', ponytail: 'lite', pstack: 'on' }),
13
+ balanced: Object.freeze({ level: 'balanced', caveman: 'full', rtk: 'on', ponytail: 'full', pstack: 'on' }),
14
+ max: Object.freeze({ level: 'max', caveman: 'ultra', rtk: 'on', ponytail: 'ultra', pstack: 'on' }),
14
15
  });
15
16
 
16
17
  const MODE_VALUES: Record<string, Set<string>> = {
17
18
  caveman: new Set(['off', 'lite', 'full', 'ultra', 'megacave', 'megacave-lite', 'megacave-full', 'megacave-ultra', 'wenyan', 'wenyan-lite', 'wenyan-full', 'wenyan-ultra']),
18
19
  rtk: new Set(['off', 'on']),
19
20
  ponytail: new Set(['off', 'lite', 'full', 'ultra']),
21
+ pstack: new Set(['off', 'on']),
20
22
  };
21
23
 
22
24
  // Upstream renamed wenyan to megacave and kept the old spelling as an alias.
23
25
  const CAVEMAN_LEGACY_PREFIX = /^wenyan/;
24
26
 
25
- type ModeName = 'caveman' | 'rtk' | 'ponytail';
27
+ type ModeName = 'caveman' | 'rtk' | 'ponytail' | 'pstack';
26
28
  type Modes = Record<ModeName, string>;
27
29
 
28
30
  const MODE_ENTRY_TYPES: Record<string, ModeName> = {
29
31
  'caveman-mode': 'caveman',
30
32
  'rtk-mode': 'rtk',
31
33
  'ponytail-mode': 'ponytail',
34
+ 'pstack-mode': 'pstack',
32
35
  };
33
36
 
34
37
  /** True when the branch carries Tersio's own mode state; a subagent starts without it. */
@@ -54,7 +57,7 @@ export function normalizeMode(name: ModeName, value: unknown): string | null {
54
57
  export function deriveLevel(modes: Modes | null | undefined): ComboLevel {
55
58
  for (const level of Object.keys(COMBO_LEVELS) as ComboLevel[]) {
56
59
  const preset = COMBO_LEVELS[level];
57
- if (preset.caveman === modes?.caveman && preset.rtk === modes?.rtk && preset.ponytail === modes?.ponytail) return level;
60
+ if (preset.caveman === modes?.caveman && preset.rtk === modes?.rtk && preset.ponytail === modes?.ponytail && preset.pstack === modes?.pstack) return level;
58
61
  }
59
62
  return 'custom';
60
63
  }
@@ -72,6 +75,7 @@ function normalizedState(modes: Partial<Modes> | null | undefined, level: ComboL
72
75
  caveman: normalizeMode('caveman', modes?.caveman) || 'off',
73
76
  rtk: normalizeMode('rtk', modes?.rtk) || 'off',
74
77
  ponytail: normalizeMode('ponytail', modes?.ponytail) || 'off',
78
+ pstack: normalizeMode('pstack', modes?.pstack) || 'off',
75
79
  };
76
80
  return Object.freeze({ level: isKnownLevel(level) ? level : deriveLevel(state), ...state });
77
81
  }
@@ -122,7 +126,7 @@ export function normalizeComboLevel(value: unknown): ComboLevel | null {
122
126
  }
123
127
 
124
128
 
125
- // Last-wins scan for a custom session entry; skips entries whose value fails to parse so a corrupt write never shadows an older valid one.
129
+ // Last-wins scan for a custom session entry; skips unparseable values so a corrupt write never shadows a valid one.
126
130
  export function lastCustomValue<T>(entries: SessionEntry[] | null | undefined, customType: string, pick: (data: SessionEntry['data']) => T | null | undefined): T | null {
127
131
  if (!Array.isArray(entries)) return null;
128
132
  for (let i = entries.length - 1; i >= 0; i -= 1) {
@@ -156,15 +160,16 @@ export function setSharedComboMode(name: ModeName, value: unknown): Readonly<Com
156
160
  const mode = normalizeMode(name, value);
157
161
  if (!mode) return getSharedComboState();
158
162
  const modes = { ...getSharedComboState(), [name]: mode } as Modes;
159
- // Derive the level from the final triplet so a redundant same-value write cannot strand a matching preset at 'custom' and drop the combo bar.
163
+ // Derive the level from the final quartet, so a redundant same-value write cannot strand a preset at 'custom'.
160
164
  return publish(normalizedState(modes));
161
165
  }
162
166
 
163
- export function setSharedComboModes(modes: { caveman?: unknown; rtk?: unknown; ponytail?: unknown }): Readonly<ComboState> {
167
+ export function setSharedComboModes(modes: { caveman?: unknown; rtk?: unknown; ponytail?: unknown; pstack?: unknown }): Readonly<ComboState> {
164
168
  return publish(normalizedState({
165
169
  caveman: normalizeMode('caveman', modes.caveman) || 'off',
166
170
  rtk: normalizeMode('rtk', modes.rtk) || 'off',
167
171
  ponytail: normalizeMode('ponytail', modes.ponytail) || 'off',
172
+ pstack: normalizeMode('pstack', modes.pstack) || 'off',
168
173
  }));
169
174
  }
170
175
 
@@ -185,13 +190,13 @@ export function reconcileSharedComboEntries(entries: SessionEntry[] | null | und
185
190
  if (mode) modes[name] = mode;
186
191
  }
187
192
  }
188
- // The level reflects the final triplet, never the write order, so a preset entry followed by the same values reconciles back to the preset.
193
+ // The level reflects the final quartet, not write order, so a preset followed by the same values reconciles back.
189
194
  return publish(normalizedState(modes));
190
195
  }
191
196
 
192
197
  // One-line session-wide mode summary for change confirmations.
193
- export function activeModesSummary(state: { caveman: string; rtk: string; ponytail: string }): string {
194
- return `caveman=${state.caveman.toUpperCase()}, rtk=${state.rtk.toUpperCase()}, ponytail=${state.ponytail.toUpperCase()}`;
198
+ export function activeModesSummary(state: { caveman: string; rtk: string; ponytail: string; pstack: string }): string {
199
+ return `caveman=${state.caveman.toUpperCase()}, rtk=${state.rtk.toUpperCase()}, ponytail=${state.ponytail.toUpperCase()}, pstack=${state.pstack.toUpperCase()}`;
195
200
  }
196
201
 
197
202
  // Keyed registration drops stale closures; hosts offer no teardown hook.
@@ -0,0 +1,168 @@
1
+ // One place that runs SQL against a database file.
2
+ //
3
+ // Bun and Node 22.5+ carry SQLite in process, so the `sqlite3` binary is a fallback rather than a
4
+ // requirement: hosts without it kept silently reading nothing. Reads come back exactly as the sqlite3
5
+ // CLI printed them -- rows on their own lines, cells joined by tabs, NULL an empty cell, one trailing
6
+ // newline -- because every caller already parses that shape. The engine rungs take one statement per
7
+ // read, so a caller with several queries calls once per query.
8
+ //
9
+ // The write path leaves the journal mode alone. The store's own schema sets WAL so a reader (the
10
+ // dashboard) never blocks a writer, and changing the mode needs exclusive access: with a reader holding
11
+ // the file the pragma fails, which is a failure reported after the caller's rows have already committed.
12
+ import { execFileSync } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import { createRequire } from 'node:module';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+
18
+ /** A read this large used to vanish behind a 1MB cap, which cleared on one busy session_message table. */
19
+ const SQLITE_READ_BUFFER = 50 * 1024 * 1024;
20
+
21
+ const TIMEOUT = 30_000;
22
+ const requireOptional = createRequire(import.meta.url);
23
+
24
+ interface Engine {
25
+ kind: 'bun' | 'node';
26
+ read(db: string, sql: string): unknown[][];
27
+ exec(db: string, sql: string): void;
28
+ }
29
+
30
+ interface BunDatabase {
31
+ query(sql: string): { values(): unknown[][] };
32
+ exec(sql: string): void;
33
+ close(): void;
34
+ }
35
+
36
+ interface NodeStatement {
37
+ all(): unknown[][];
38
+ setReturnArrays?(on: boolean): unknown;
39
+ }
40
+
41
+ interface NodeDatabase {
42
+ prepare(sql: string): NodeStatement;
43
+ exec(sql: string): void;
44
+ close(): void;
45
+ }
46
+
47
+ let cached: Engine | null | undefined;
48
+ let cachedFor: string | undefined;
49
+
50
+ /** Bun's SQLite, or Node's when this build carries one. Null when neither runtime has an engine. */
51
+ function engine(): Engine | null {
52
+ const asked = process.env.TERSIO_SQLITE ?? '';
53
+ if (cached !== undefined && cachedFor === asked) return cached;
54
+ cachedFor = asked;
55
+ cached = null;
56
+ if (asked === 'cli') return cached;
57
+ try {
58
+ const { Database } = requireOptional('bun:sqlite') as { Database: new (db: string, opts?: { readonly?: boolean }) => BunDatabase };
59
+ cached = {
60
+ kind: 'bun',
61
+ read: (db, sql) => { const d = new Database(db, { readonly: true }); try { return d.query(sql).values(); } finally { d.close(); } },
62
+ exec: (db, sql) => { const d = new Database(db); try { d.exec(sql); } finally { d.close(); } },
63
+ };
64
+ return cached;
65
+ } catch { /* not Bun, or no SQLite in this build */ }
66
+ try {
67
+ const { DatabaseSync } = requireOptional('node:sqlite') as { DatabaseSync: new (db: string, opts?: { readOnly?: boolean }) => NodeDatabase };
68
+ // Rows arrive keyed by column name unless the statement returns arrays. A duplicate name collapses
69
+ // its key and shifts every later cell, so a Node that cannot return arrays is no engine at all.
70
+ const probe = new DatabaseSync(':memory:');
71
+ try {
72
+ if (typeof probe.prepare('SELECT 1').setReturnArrays !== 'function') throw new Error('no positional rows');
73
+ } finally {
74
+ probe.close();
75
+ }
76
+ cached = {
77
+ kind: 'node',
78
+ read: (db, sql) => {
79
+ const d = new DatabaseSync(db, { readOnly: true });
80
+ try {
81
+ const st = d.prepare(sql);
82
+ st.setReturnArrays?.(true);
83
+ return st.all();
84
+ } finally { d.close(); }
85
+ },
86
+ exec: (db, sql) => { const d = new DatabaseSync(db); try { d.exec(sql); } finally { d.close(); } },
87
+ };
88
+ return cached;
89
+ } catch { /* Node older than 22.5, or one built without SQLite or positional rows */ }
90
+ return cached;
91
+ }
92
+
93
+ /** The `sqlite3` binary, resolved once from PATH so a missing one costs one scan, not one spawn per call. */
94
+ let binary: string | null | undefined;
95
+ function findBinary(): string | null {
96
+ if (binary !== undefined) return binary;
97
+ binary = null;
98
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
99
+ if (!dir) continue;
100
+ for (const name of process.platform === 'win32' ? ['sqlite3.exe', 'sqlite3'] : ['sqlite3']) {
101
+ const at = path.join(dir, name);
102
+ try {
103
+ fs.accessSync(at, fs.constants.X_OK);
104
+ binary = at;
105
+ return binary;
106
+ } catch { /* not here */ }
107
+ }
108
+ }
109
+ return binary;
110
+ }
111
+
112
+ /** `bun`, `node`, `cli`, or null when this host has no way to read SQLite at all. */
113
+ export function sqliteEngine(): 'bun' | 'node' | 'cli' | null {
114
+ return engine()?.kind ?? (findBinary() === null ? null : 'cli');
115
+ }
116
+
117
+ /** Whether any path can run SQL: what the tests guard their skips on. */
118
+ export function sqliteAvailable(): boolean {
119
+ return sqliteEngine() !== null;
120
+ }
121
+
122
+ /** Rows as the CLI prints them, so a caller cannot tell which engine answered. */
123
+ function toTsv(rows: unknown[][]): string {
124
+ if (rows.length === 0) return '';
125
+ return `${rows.map((row) => row.map((cell) => (cell === null || cell === undefined ? '' : String(cell))).join('\t')).join('\n')}\n`;
126
+ }
127
+
128
+ function cliRead(db: string, sql: string): string {
129
+ const opts = { encoding: 'utf8' as const, timeout: TIMEOUT, stdio: ['pipe', 'pipe', 'ignore'] as ['pipe', 'pipe', 'ignore'], maxBuffer: SQLITE_READ_BUFFER, input: sql };
130
+ try {
131
+ return execFileSync('sqlite3', ['-separator', '\t', '-readonly', db], opts);
132
+ } catch { /* the side files may be gone; try the next rung */ }
133
+ if (!fs.existsSync(`${db}-wal`)) {
134
+ try {
135
+ return execFileSync('sqlite3', ['-separator', '\t', `file:${db}?immutable=1`], opts);
136
+ } catch { /* fall through to the copy */ }
137
+ }
138
+ // A live database cannot be read without its write-ahead log, so copy the set and read the copy.
139
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tersio-sqlite-'));
140
+ const target = path.join(dir, path.basename(db));
141
+ try {
142
+ fs.copyFileSync(db, target);
143
+ for (const suffix of ['-wal', '-shm']) {
144
+ if (fs.existsSync(`${db}${suffix}`)) fs.copyFileSync(`${db}${suffix}`, `${target}${suffix}`);
145
+ }
146
+ return execFileSync('sqlite3', ['-separator', '\t', '-readonly', target], opts);
147
+ } finally {
148
+ fs.rmSync(dir, { recursive: true, force: true });
149
+ }
150
+ }
151
+
152
+ /** Run a read and return the tab-separated rows. Throws when the file is missing, as the callers expect. */
153
+ export function sqliteRead(db: string, sql: string): string {
154
+ if (!fs.existsSync(db)) throw new Error(`missing database: ${db}`);
155
+ const e = engine();
156
+ if (e !== null) return toTsv(e.read(db, sql));
157
+ return cliRead(db, sql);
158
+ }
159
+
160
+ /** Run a script, creating the file if needed. Stops at the first error, so a failed INSERT leaves no DELETEs. */
161
+ export function sqliteExec(db: string, sql: string): void {
162
+ const e = engine();
163
+ if (e !== null) {
164
+ e.exec(db, sql);
165
+ return;
166
+ }
167
+ execFileSync('sqlite3', ['-bail', db, sql], { stdio: ['ignore', 'ignore', 'ignore'], timeout: TIMEOUT });
168
+ }
@@ -1,4 +1,4 @@
1
- // One status string every surface renders: host footer bar, CLI menu title, dashboard banner. Nothing else formats mode state.
1
+ // One status string every surface renders: host footer, CLI title, dashboard banner. Nothing else formats mode state.
2
2
  import { getSharedComboState } from './session-state.ts';
3
3
  import type { ExtensionCtx, UiApi } from './types.ts';
4
4
 
@@ -7,19 +7,20 @@ export interface StatusState {
7
7
  caveman: string;
8
8
  rtk: string;
9
9
  ponytail: string;
10
+ pstack: string;
10
11
  }
11
12
 
12
- /** OFF collapses the three modes into one word; a preset or a mix names itself. */
13
+ /** OFF collapses every mode into one word; a preset or a mix names itself. */
13
14
  export function formatStatus(state: StatusState): string {
14
- const { level, caveman, rtk, ponytail } = state;
15
- if (level === 'off' && caveman === 'off' && rtk === 'off' && ponytail === 'off') return '🧩 combo OFF';
15
+ const { level, caveman, rtk, ponytail, pstack } = state;
16
+ if (level === 'off' && caveman === 'off' && rtk === 'off' && ponytail === 'off' && pstack === 'off') return '🧩 combo OFF';
16
17
  const label = level === 'custom' ? 'CUSTOM' : level.toUpperCase();
17
- return `🧩 combo ${label}: 🪨caveman=${caveman.toUpperCase()} ⚡rtk=${rtk.toUpperCase()} 🦥ponytail=${ponytail.toUpperCase()}`;
18
+ return `🧩 combo ${label}: 🪨caveman=${caveman.toUpperCase()} ⚡rtk=${rtk.toUpperCase()} 🦥ponytail=${ponytail.toUpperCase()} 🥔pstack=${pstack.toUpperCase()}`;
18
19
  }
19
20
 
20
- // The string upstream's skill tells the model to relay for `/caveman status`.
21
+ // The string upstream's skill tells the model to relay for `/caveman status`; `off` is a mode, so it reads as one.
21
22
  export function formatCavemanStatus(mode: string): string {
22
- return `Caveman mode: ${mode && mode !== 'off' ? mode : 'unknown'}`;
23
+ return `Caveman mode: ${mode || 'unknown'}`;
23
24
  }
24
25
 
25
26
  // Stale ctx access throws, so never let it abort a mode restore.
@@ -38,6 +39,7 @@ let lastText: string | undefined;
38
39
  let lastUi: UiApi | undefined;
39
40
 
40
41
  // Paint the host footer bar; same text on the same UI is skipped, a new ctx repaints it.
42
+ // One key only: the combo line already names the caveman mode, and a second key renders as a second footer line.
41
43
  export function announceStatus(ctx: ExtensionCtx | undefined): void {
42
44
  const state = getSharedComboState();
43
45
  const text = formatStatus(state);
@@ -48,5 +50,4 @@ export function announceStatus(ctx: ExtensionCtx | undefined): void {
48
50
  lastText = text;
49
51
  lastUi = ui;
50
52
  ui.setStatus?.('tersio', text);
51
- ui.setStatus?.('caveman', formatCavemanStatus(state.caveman));
52
53
  }