ceulen 0.1.0 → 0.5.0

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 (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,244 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import {
4
+ commandCodeWindowToUsageWindow,
5
+ parseGenericUsage,
6
+ parseOmniUsageText,
7
+ routerUpstreamPrefix,
8
+ tokPerSecLabel,
9
+ formatMonthlyCredits,
10
+ jwtExpired,
11
+ } from "../index.ts";
12
+ import { parseEnvText } from "../../../lib/env.ts";
13
+
14
+ // ── parseOmniUsageText — OmniRoute /api/usage/om-usage free-text report ──────
15
+
16
+ test("om-usage: full report parses all four windows", () => {
17
+ const p = parseOmniUsageText(
18
+ [
19
+ "Personal quota",
20
+ "Daily",
21
+ "80% left",
22
+ "⏱ reset in 15h 0m",
23
+ "",
24
+ "Weekly",
25
+ "90% left",
26
+ "⏱ reset in 7d 0h 0m",
27
+ "",
28
+ "Provider quota",
29
+ "Session",
30
+ "47% left",
31
+ "⏱ reset in 9m",
32
+ "",
33
+ "Weekly",
34
+ "28% left",
35
+ "⏱ reset in 1d 0h 0m",
36
+ ].join("\n"),
37
+ );
38
+ assert.equal(p.personalDaily?.remaining, 80);
39
+ assert.equal(p.personalWeekly?.remaining, 90);
40
+ assert.equal(p.session?.remaining, 47);
41
+ assert.equal(p.providerWeekly?.remaining, 28);
42
+ // reset line → raw countdown label + compact remaining (15h → 15H, 9m → 9M).
43
+ assert.equal(p.personalDaily?.resetLabel, "⏱ 15h 0m");
44
+ assert.equal(p.personalDaily?.remainingLabel, "15H");
45
+ assert.equal(p.personalWeekly?.remainingLabel, "7D");
46
+ assert.equal(p.session?.remainingLabel, "9M");
47
+ });
48
+
49
+ test("om-usage: section switching — Weekly means personal or provider by section", () => {
50
+ const p = parseOmniUsageText(
51
+ ["Provider quota", "Weekly", "10% left", "Personal quota", "Weekly", "20% left"].join("\n"),
52
+ );
53
+ assert.equal(p.providerWeekly?.remaining, 10);
54
+ assert.equal(p.personalWeekly?.remaining, 20);
55
+ assert.equal(p.session, undefined);
56
+ assert.equal(p.personalDaily, undefined);
57
+ });
58
+
59
+ test("om-usage: out-of-range percentages are skipped", () => {
60
+ const p = parseOmniUsageText(["Personal quota", "Daily", "150% left", "Weekly", "-5% left"].join("\n"));
61
+ assert.deepEqual(p, {});
62
+ });
63
+
64
+ test("om-usage: non-report text parses empty (disabled key, no cached data)", () => {
65
+ assert.deepEqual(parseOmniUsageText("Usage command is disabled for this API key."), {});
66
+ assert.deepEqual(parseOmniUsageText("Provider quota\nNo cached usage data available."), {});
67
+ assert.deepEqual(parseOmniUsageText(""), {});
68
+ });
69
+
70
+ // ── commandCodeWindowToUsageWindow — /alpha/billing/credits JSON shape ───────
71
+
72
+ test("commandcode credits: USD window maps used/cap → remaining%, resetAt ms → labels", () => {
73
+ // Live response shape (resetAt is epoch milliseconds):
74
+ const w = commandCodeWindowToUsageWindow({ used: 2.5, cap: 10, exceeded: false, resetAt: Date.now() + 3_600_000 });
75
+ assert.ok(w);
76
+ assert.equal(w.percent, 25);
77
+ assert.equal(w.remaining, 75);
78
+ assert.match(w.remainingLabel ?? "", /^\d+[HM]$/, "future reset → compact remaining");
79
+ assert.ok(w.resetLabel, "reset clock label present");
80
+ });
81
+
82
+ test("commandcode credits: full response drives fiveHour + weekly windows", () => {
83
+ const w5 = commandCodeWindowToUsageWindow({ used: 0.25, cap: 5, resetAt: Date.now() + 7_200_000 });
84
+ const wk = commandCodeWindowToUsageWindow({ used: 3.75, cap: 50, resetAt: Date.now() + 86_400_000 });
85
+ assert.equal(w5?.remaining, 95);
86
+ // 3.75/50 = 7.5% used → Math.round → 8 → remaining 92.
87
+ assert.equal(wk?.remaining, 92);
88
+ });
89
+
90
+ test("commandcode credits: over-cap clamps to 0 remaining, bad windows → undefined", () => {
91
+ const over = commandCodeWindowToUsageWindow({ used: 12, cap: 10 });
92
+ assert.equal(over?.percent, 100);
93
+ assert.equal(over?.remaining, 0);
94
+ assert.equal(commandCodeWindowToUsageWindow(undefined), undefined);
95
+ assert.equal(commandCodeWindowToUsageWindow({ used: 1, cap: 0 }), undefined);
96
+ assert.equal(commandCodeWindowToUsageWindow({ used: 1, cap: undefined as unknown as number }), undefined);
97
+ // past resetAt (or missing) → no remaining label, window still valid
98
+ const past = commandCodeWindowToUsageWindow({ used: 1, cap: 10 });
99
+ assert.equal(past?.remaining, 90);
100
+ });
101
+
102
+ // ── parseEnvText — .env.local stdlib-style parser ────────────────────────────
103
+
104
+ test("env: export prefix, quotes, comments, plain values", () => {
105
+ const parsed = parseEnvText(
106
+ [
107
+ "# leading comment",
108
+ "",
109
+ "export ROUTER_API_KEY=rk_123",
110
+ 'QUOTED="hello world"',
111
+ "SINGLE='v'",
112
+ "PLAIN=1",
113
+ "A_1=b c",
114
+ ].join("\n"),
115
+ );
116
+ assert.deepEqual(parsed, {
117
+ ROUTER_API_KEY: "rk_123",
118
+ QUOTED: "hello world",
119
+ SINGLE: "v",
120
+ PLAIN: "1",
121
+ A_1: "b c",
122
+ });
123
+ });
124
+
125
+ test("env: CRLF files, non-assignment lines, `#` stays part of the value", () => {
126
+ const parsed = parseEnvText("export A=1\r\nB=2\r\nnot an assignment\r\nKEY=value # note");
127
+ assert.deepEqual(parsed, { A: "1", B: "2", KEY: "value # note" });
128
+ });
129
+
130
+ // ── routerUpstreamPrefix — router model id → upstream provider slug ─────────
131
+
132
+ test("router: alias normalization maps to canonical upstream slugs", () => {
133
+ assert.equal(routerUpstreamPrefix({ id: "command-code/deepseek/deepseek-v4-flash" }), "command-code");
134
+ assert.equal(routerUpstreamPrefix({ id: "cmd/deepseek/deepseek-v4-flash" }), "command-code");
135
+ assert.equal(routerUpstreamPrefix({ id: "oc/gpt-5" }), "opencode-go");
136
+ assert.equal(routerUpstreamPrefix({ id: "ds/v4" }), "deepseek");
137
+ // glm-cn is OmniRoute's connection slug (not the Pi provider id zai-coding-cn).
138
+ assert.equal(routerUpstreamPrefix({ id: "glm-cn/glm-5.2" }), "glm-cn");
139
+ assert.equal(routerUpstreamPrefix({ id: "glmcn/glm-5.2" }), "glm-cn");
140
+ assert.equal(routerUpstreamPrefix({ id: "zai-coding/glm-5.2" }), "zai-coding");
141
+ });
142
+
143
+ test("router: generic aliases carry no provider info → undefined", () => {
144
+ assert.equal(routerUpstreamPrefix({ id: "auto/best" }), undefined);
145
+ assert.equal(routerUpstreamPrefix({ id: "openrouter/gpt-5" }), undefined);
146
+ assert.equal(routerUpstreamPrefix({ id: "nvidia/gpt-5" }), undefined);
147
+ assert.equal(routerUpstreamPrefix({ id: "" }), undefined);
148
+ });
149
+
150
+ // ── tokPerSecLabel — usage.reasoning ⊂ usage.output, never summed ────────────
151
+
152
+ test("tok/s: think/answer split math (answer = output − reasoning)", () => {
153
+ assert.equal(tokPerSecLabel(3200, 2500, 70_000), "46 tok/s (36 think + 10 answer)");
154
+ assert.equal(tokPerSecLabel(200, 0, 10_000), "20 tok/s");
155
+ assert.equal(tokPerSecLabel(1000, 1000, 10_000), "100 tok/s (100 think + 0 answer)");
156
+ assert.equal(tokPerSecLabel(300, -1, 10_000), "30 tok/s");
157
+ });
158
+
159
+ // ── parseGenericUsage — yardmaster GET /v1/usage JSON ─────────────────────────
160
+
161
+ test("generic usage: windows + credits map to footer fields", () => {
162
+ const g = parseGenericUsage({
163
+ provider: "zai",
164
+ windows: {
165
+ session: { remaining_pct: 47, reset_at: Date.now() + 2 * 3600_000 },
166
+ weekly: { remaining_pct: 99.4, reset_at: Date.now() + 26 * 3600_000 },
167
+ },
168
+ credits: { currency: "USD", balance: 42.5 },
169
+ providers: ["zai"],
170
+ });
171
+ assert.equal(g.fiveHour?.remaining, 47);
172
+ assert.equal(g.weekly?.remaining, 99); // clamped + rounded
173
+ assert.ok(g.fiveHour?.remainingLabel === "2H", `session label ${g.fiveHour?.remainingLabel}`);
174
+ assert.ok(g.weekly?.remainingLabel === "2D", `weekly label ${g.weekly?.remainingLabel}`); // ceil(26h/24h)
175
+ assert.ok(g.fiveHour?.resetLabel?.includes("⏱ reset in"), g.fiveHour?.resetLabel);
176
+ assert.equal(g.monthlyCredits, 42.5);
177
+ assert.equal(g.creditsCurrency, "USD");
178
+ assert.ok(g.breakdown?.includes("Session 47% left"), g.breakdown);
179
+ assert.ok(g.breakdown?.includes("🪙 Balance (USD) $42.50"), g.breakdown);
180
+ });
181
+
182
+ test("generic usage: opencode monthly pct window maps through", () => {
183
+ const g = parseGenericUsage({
184
+ provider: "ocg",
185
+ windows: {
186
+ session: { remaining_pct: 99, reset_at: Date.now() + 5 * 3600_000 },
187
+ weekly: { remaining_pct: 100, reset_at: Date.now() + 6 * 24 * 3600_000 },
188
+ monthly: { remaining_pct: 20, reset_at: Date.now() + 4 * 24 * 3600_000 },
189
+ },
190
+ providers: ["ocg"],
191
+ });
192
+ assert.equal(g.monthly?.remaining, 20);
193
+ assert.ok(g.monthly?.remainingLabel === "4D", `monthly label ${g.monthly?.remainingLabel}`);
194
+ assert.ok(g.breakdown?.includes("Monthly 20% left"), g.breakdown);
195
+ // absent monthly stays absent
196
+ const none = parseGenericUsage({ windows: { session: { remaining_pct: 1 } } });
197
+ assert.equal(none.monthly, undefined);
198
+ });
199
+
200
+ test("generic usage: CNY balance keeps currency; monthly-only report accepted", () => {
201
+ const cny = parseGenericUsage({ credits: { currency: "CNY", balance: 88 } });
202
+ assert.equal(cny.creditsCurrency, "CNY");
203
+ assert.equal(formatMonthlyCredits(88, "CNY"), "¥88.00 CNY");
204
+ assert.equal(formatMonthlyCredits(69.99), "$69.99");
205
+ assert.equal(formatMonthlyCredits(42.5, "USD"), "$42.50");
206
+ // monthly-only report (router emits windows.monthly alone) parses
207
+ const mo = parseGenericUsage({ windows: { monthly: { remaining_pct: 20 } } });
208
+ assert.equal(mo.monthly?.remaining, 20);
209
+ assert.equal(mo.fiveHour, undefined);
210
+ });
211
+
212
+ test("generic usage: deepseek balance-only report (no windows), CNY currency", () => {
213
+ const g = parseGenericUsage({ credits: { currency: "CNY", balance: 88 } });
214
+ assert.equal(g.fiveHour, undefined);
215
+ assert.equal(g.weekly, undefined);
216
+ assert.equal(g.monthlyCredits, 88);
217
+ assert.equal(g.creditsCurrency, "CNY");
218
+ assert.ok(g.breakdown?.includes("¥88.00 CNY"), g.breakdown);
219
+ });
220
+
221
+ test("generic usage: garbage/empty input falls through empty", () => {
222
+ assert.deepEqual(parseGenericUsage(null), {});
223
+ assert.deepEqual(parseGenericUsage("nope"), {});
224
+ assert.deepEqual(parseGenericUsage({ providers: [] }), {});
225
+ // NaN / missing remaining_pct windows are skipped, not fabricated
226
+ const g = parseGenericUsage({ windows: { session: { remaining_pct: "x" } } });
227
+ assert.equal(g.fiveHour, undefined);
228
+ });
229
+
230
+ // ── jwtExpired — Codex OAuth access-token expiry check ───────────────────
231
+
232
+ test("jwtExpired: exp in the past → true", () => {
233
+ assert.equal(jwtExpired({ exp: Math.floor(Date.now() / 1000) - 60 }), true);
234
+ });
235
+
236
+ test("jwtExpired: exp in the future → false", () => {
237
+ assert.equal(jwtExpired({ exp: Math.floor(Date.now() / 1000) + 3600 }), false);
238
+ });
239
+
240
+ test("jwtExpired: missing exp or garbage payload → false (server arbitrates)", () => {
241
+ assert.equal(jwtExpired(undefined), false);
242
+ assert.equal(jwtExpired({}), false);
243
+ assert.equal(jwtExpired({ exp: "soon" }), false);
244
+ });
@@ -0,0 +1,294 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import extension, { REFRESH_DEBOUNCE_MS, REFRESH_INTERVAL_MS, scheduleRefresh, type State } from "../index.ts";
4
+
5
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
6
+
7
+ /** Fake ctx whose ui throws once `invalidate()` is called — mimics Pi's
8
+ * ExtensionRunner.invalidate() after session replacement. `message` lets
9
+ * tests pin the disarm matcher to wording, not to this fake's default. */
10
+ function makeCtx(message = "This extension ctx is stale after session replacement or reload.") {
11
+ const ctx = {
12
+ invalidated: false,
13
+ statusCalls: [] as string[],
14
+ signal: undefined,
15
+ staleMessage: message,
16
+ ui: {
17
+ theme: {
18
+ fg: (_color: string, text: string) => text,
19
+ },
20
+ setStatus(_key: string, _value?: string) {
21
+ if (ctx.invalidated) throw new Error(message);
22
+ ctx.statusCalls.push(_value ?? "");
23
+ },
24
+ notify() {
25
+ if (ctx.invalidated) throw new Error(message);
26
+ },
27
+ },
28
+ invalidate() {
29
+ ctx.invalidated = true;
30
+ },
31
+ };
32
+ return ctx;
33
+ }
34
+
35
+ function makeState(ctx?: ReturnType<typeof makeCtx>): State {
36
+ const fetchCalls: unknown[] = [];
37
+ return {
38
+ ctx,
39
+ lastRefreshAt: 0,
40
+ refreshGeneration: 0,
41
+ cumulativeOutput: 0,
42
+ cumulativeDurationMs: 0,
43
+ cumulativeCost: 0,
44
+ // ponytail: minimal adapter stub — the crash path must never reach fetchUsage
45
+ // when state.ctx is unset, and the positive control only needs the call count.
46
+ adapter: {
47
+ id: "test",
48
+ displayName: "Test",
49
+ fetchUsage(signal?: AbortSignal) {
50
+ fetchCalls.push(signal);
51
+ return Promise.resolve({} as never);
52
+ },
53
+ },
54
+ } as State & { adapter: { fetchCalls: unknown[] } };
55
+ }
56
+
57
+ test("debounce armed before session replacement no-ops after ctx is dropped (crash repro)", async () => {
58
+ const ctxA = makeCtx();
59
+ const state = makeState(ctxA);
60
+
61
+ scheduleRefresh(state);
62
+ // session_shutdown semantics: stopTimer can no longer help if the debounce was
63
+ // re-armed by a late event afterwards — dropping state.ctx must be enough.
64
+ state.ctx = undefined;
65
+ ctxA.invalidate();
66
+
67
+ await sleep(REFRESH_DEBOUNCE_MS + 100);
68
+ assert.equal(ctxA.statusCalls.length, 0, "stale ctx must not be rendered into");
69
+ });
70
+
71
+ test("late old-session scheduling cannot reinstall a ctx (advisor nit)", async () => {
72
+ const state = makeState(); // post-shutdown: state.ctx is undefined
73
+ const ctxA = makeCtx();
74
+ ctxA.invalidate();
75
+
76
+ // scheduleRefresh takes no ctx — a late after_provider_response has nothing
77
+ // stale to capture. The armed timer must still no-op.
78
+ scheduleRefresh(state);
79
+ await sleep(REFRESH_DEBOUNCE_MS + 100);
80
+ assert.equal(state.ctx, undefined);
81
+ assert.equal(ctxA.statusCalls.length, 0);
82
+ });
83
+
84
+ test("debounce fires with the ctx installed at fire time, not arm time", async () => {
85
+ const ctxA = makeCtx();
86
+ const state = makeState(ctxA);
87
+
88
+ scheduleRefresh(state);
89
+ // Session replaced: old ctx dead, new session started with ctxB.
90
+ state.ctx = makeCtx();
91
+ ctxA.invalidate();
92
+
93
+ await sleep(REFRESH_DEBOUNCE_MS + 100);
94
+ assert.notEqual(state.ctx, undefined);
95
+ assert.equal(ctxA.statusCalls.length, 0, "stale ctx must not be rendered into");
96
+ assert.equal((state.ctx as unknown as { statusCalls: string[] }).statusCalls.length > 0, true, "live ctx must be rendered into");
97
+ });
98
+
99
+ test("stale ctx still installed when the deferred refresh fires is caught and self-disarms, not an unhandled rejection", async () => {
100
+ const ctxA = makeCtx();
101
+ const state = makeState(ctxA);
102
+
103
+ scheduleRefresh(state);
104
+ // pi 0.85.1 hole: the ctx is invalidated WITHOUT session_shutdown being
105
+ // delivered, so state.ctx stays installed and stale. The 0.1.18/0.1.37
106
+ // guards (fire-time ctx resolution, identity-guarded shutdown) cannot help:
107
+ // refreshUsage hits ctx.ui, throws, and its void-discarded rejection used
108
+ // to exit pi. deferRefresh must catch it and self-disarm.
109
+ ctxA.invalidate();
110
+
111
+ let unhandled: unknown;
112
+ const onUnhandled = (reason: unknown) => {
113
+ unhandled = reason;
114
+ };
115
+ process.on("unhandledRejection", onUnhandled);
116
+ try {
117
+ await sleep(REFRESH_DEBOUNCE_MS + 100);
118
+ } finally {
119
+ process.off("unhandledRejection", onUnhandled);
120
+ }
121
+ assert.equal(unhandled, undefined, "stale-ctx throw must be caught, not left unhandled");
122
+ assert.equal(state.debounceTimer, undefined, "self-disarm must stop the debounce timer");
123
+ assert.equal(state.ctx, undefined, "self-disarm must drop the stale ctx");
124
+ assert.ok(state.refreshGeneration > 0, "self-disarm must invalidate in-flight state");
125
+ });
126
+
127
+ function makePi() {
128
+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<void> | void> = {};
129
+ const commands: Record<string, { handler: (args: string, ctx: unknown) => Promise<void> }> = {};
130
+ return {
131
+ handlers,
132
+ commands,
133
+ on(type: string, fn: (event: unknown, ctx: unknown) => Promise<void> | void) {
134
+ handlers[type] = fn;
135
+ },
136
+ registerCommand(name: string, opts: { handler: (args: string, ctx: unknown) => Promise<void> }) {
137
+ commands[name] = opts;
138
+ },
139
+ } as never;
140
+ }
141
+
142
+ function makePiHarness() {
143
+ const pi = makePi() as {
144
+ handlers: Record<string, (event: unknown, ctx: never) => Promise<void> | void>;
145
+ commands: Record<string, { handler: (args: string, ctx: never) => Promise<void> }>;
146
+ };
147
+ const state = extension(pi) as State;
148
+ return { pi, state };
149
+ }
150
+
151
+ function stubFetch() {
152
+ const realFetch = globalThis.fetch;
153
+ globalThis.fetch = (async () => new Response("{}", { headers: { "content-type": "application/json" } })) as typeof fetch;
154
+ return () => {
155
+ globalThis.fetch = realFetch;
156
+ };
157
+ }
158
+
159
+ function startLiveSession(harness: ReturnType<typeof makePiHarness>, reason: string) {
160
+ const ctxB = makeCtx();
161
+ (ctxB as unknown as { model: unknown }).model = { provider: "zai", id: "glm-5.3" };
162
+ return harness.pi.handlers.session_start({ reason }, ctxB as never).then(() => ctxB);
163
+ }
164
+
165
+ test("60s interval fires against an orphaned stale ctx and self-disarms (pi-exit repro)", async (t) => {
166
+ const restoreFetch = stubFetch();
167
+ try {
168
+ const { pi, state } = makePiHarness();
169
+ t.mock.timers.enable({ apis: ["setInterval"] });
170
+ const ctxB = await startLiveSession({ pi, state }, "new");
171
+ assert.ok(state.refreshTimer, "session_start must arm the refresh interval");
172
+ await sleep(20); // let session_start's immediate refresh settle (60s later it always has)
173
+ // Open the TTL gate so the tick renders + fetches instead of early-returning.
174
+ state.snapshot = undefined;
175
+ state.lastRefreshAt = 0;
176
+ ctxB.invalidate(); // orphaned invalidation, no session_shutdown delivered
177
+
178
+ let unhandled: unknown;
179
+ const onUnhandled = (reason: unknown) => {
180
+ unhandled = reason;
181
+ };
182
+ process.on("unhandledRejection", onUnhandled);
183
+ try {
184
+ t.mock.timers.tick(REFRESH_INTERVAL_MS);
185
+ await sleep(10); // flush rejection microtasks
186
+ } finally {
187
+ process.off("unhandledRejection", onUnhandled);
188
+ }
189
+ assert.equal(unhandled, undefined, "interval stale-ctx throw must be caught, not unhandled");
190
+ assert.equal(state.refreshTimer, undefined, "self-disarm must stop the interval");
191
+ assert.equal(state.ctx, undefined, "self-disarm must drop the stale ctx");
192
+ } finally {
193
+ restoreFetch();
194
+ }
195
+ });
196
+
197
+ test("/usage against an orphaned stale ctx disarms instead of throwing into the dispatcher", async () => {
198
+ const restoreFetch = stubFetch();
199
+ try {
200
+ const { pi, state } = makePiHarness();
201
+ const ctxB = await startLiveSession({ pi, state }, "new");
202
+ assert.ok(state.refreshTimer);
203
+ ctxB.invalidate(); // orphaned invalidation, no session_shutdown delivered
204
+
205
+ await pi.commands.usage.handler("", ctxB as never); // must not throw
206
+
207
+ assert.equal(state.ctx, undefined, "stale /usage must disarm");
208
+ assert.equal(state.refreshTimer, undefined, "stale /usage must stop the interval");
209
+ } finally {
210
+ restoreFetch();
211
+ }
212
+ });
213
+
214
+ test("disarm does not depend on pi's exact stale-error wording", async () => {
215
+ const ctxA = makeCtx("Extension context invalidated by the host.");
216
+ const state = makeState(ctxA);
217
+
218
+ scheduleRefresh(state);
219
+ ctxA.invalidate();
220
+
221
+ let unhandled: unknown;
222
+ const onUnhandled = (reason: unknown) => {
223
+ unhandled = reason;
224
+ };
225
+ process.on("unhandledRejection", onUnhandled);
226
+ try {
227
+ await sleep(REFRESH_DEBOUNCE_MS + 100);
228
+ } finally {
229
+ process.off("unhandledRejection", onUnhandled);
230
+ }
231
+ assert.equal(unhandled, undefined);
232
+ assert.equal(state.debounceTimer, undefined);
233
+ assert.equal(state.ctx, undefined);
234
+ });
235
+
236
+ const UNSUPPORTED_MODEL = { provider: "ollama", id: "qwen3" };
237
+
238
+ test("late old-session shutdown does not drop the new session's ctx", async () => {
239
+ const pi = makePi() as { handlers: Record<string, (event: unknown, ctx: never) => Promise<void> | void> };
240
+ extension(pi);
241
+
242
+ const ctxB = makeCtx();
243
+ (ctxB as unknown as { model: unknown }).model = UNSUPPORTED_MODEL;
244
+ await pi.handlers.session_start({ reason: "new" }, ctxB as never);
245
+ const renders = ctxB.statusCalls.length;
246
+ assert.ok(renders > 0, "session_start must render into the live ctx");
247
+
248
+ // Cross-boundary late delivery: the PREVIOUS session's shutdown arrives
249
+ // after the new session's session_start. It must only drop the ctx it was
250
+ // handed, not the live one.
251
+ const ctxA = makeCtx();
252
+ await pi.handlers.session_shutdown({ reason: "new" }, ctxA as never);
253
+
254
+ await pi.handlers.model_select({ model: UNSUPPORTED_MODEL }, ctxB as never);
255
+ assert.equal(
256
+ ctxB.statusCalls.length,
257
+ renders + 1,
258
+ "live session must still render after a late old-session shutdown",
259
+ );
260
+ });
261
+
262
+ test("late old-session shutdown leaves the live interval, generation, and invalidated ctx untouched", async () => {
263
+ const pi = makePi() as { handlers: Record<string, (event: unknown, ctx: never) => Promise<void> | void> };
264
+ const state = extension(pi) as State;
265
+
266
+ // Supported model → session_start arms the 60s refresh interval. Stub fetch
267
+ // so the fired refresh never leaves the test process.
268
+ const realFetch = globalThis.fetch;
269
+ globalThis.fetch = (async () => new Response("{}", { headers: { "content-type": "application/json" } })) as typeof fetch;
270
+ try {
271
+ const ctxB = makeCtx();
272
+ (ctxB as unknown as { model: unknown }).model = { provider: "zai", id: "glm-5.3" };
273
+ await pi.handlers.session_start({ reason: "new" }, ctxB as never);
274
+ assert.ok(state.refreshTimer, "session_start must arm the refresh interval");
275
+ const gen = state.refreshGeneration;
276
+
277
+ // Late shutdown of the PREVIOUS session, ctx already invalidated — the
278
+ // handler must not touch it (no throw) and must not tear down the live
279
+ // session's timer or bump its generation.
280
+ const ctxA = makeCtx();
281
+ ctxA.invalidate();
282
+ await pi.handlers.session_shutdown({ reason: "new" }, ctxA as never);
283
+ assert.ok(state.refreshTimer, "late shutdown must not kill the live interval");
284
+ assert.equal(state.refreshGeneration, gen, "late shutdown must not bump the live generation");
285
+ assert.equal(state.ctx, ctxB, "live ctx stays installed");
286
+
287
+ // Matching shutdown still tears down fully.
288
+ await pi.handlers.session_shutdown({ reason: "quit" }, ctxB as never);
289
+ assert.equal(state.refreshTimer, undefined, "matching shutdown stops the interval");
290
+ assert.equal(state.ctx, undefined, "matching shutdown drops the ctx");
291
+ } finally {
292
+ globalThis.fetch = realFetch;
293
+ }
294
+ });
@@ -0,0 +1,40 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { redactedError, supportedAdapter } from "../index.ts";
4
+
5
+ test("zai-anthropic model maps to the Z.ai (Anthropic) usage adapter", () => {
6
+ const a = supportedAdapter({ provider: "zai-anthropic", id: "glm-5.3-flash" });
7
+ assert.ok(a);
8
+ assert.equal(a.id, "zai-anthropic");
9
+ assert.equal(a.displayName, "Z.ai (Anthropic)");
10
+ assert.equal(typeof a.fetchUsage, "function");
11
+ });
12
+
13
+ test("sibling zai legs unchanged (regression guard)", () => {
14
+ assert.equal(supportedAdapter({ provider: "zai", id: "glm-5.3" })?.id, "zai");
15
+ assert.equal(supportedAdapter({ provider: "zai-coding-cn", id: "glm-5.3" })?.id, "zai-coding-cn");
16
+ assert.equal(supportedAdapter({ provider: "acme", id: "whatever" }), undefined);
17
+ });
18
+
19
+ // Live finding 2026-09-07: api.z.ai monitor returned HTTP 200 with
20
+ // {"code":500,"msg":"Internal service error"} — a server-side outage. The
21
+ // footer must show the server's message, not a generic "usage unavailable".
22
+ test("structured API errors surface the server message; auth ones stay redacted", () => {
23
+ assert.equal(
24
+ redactedError(new Error("Z.ai (Anthropic) API error: Internal service error"), "Z.ai (Anthropic)"),
25
+ "Z.ai (Anthropic) API error: Internal service error",
26
+ );
27
+ assert.equal(
28
+ redactedError(new Error("Z.ai (Anthropic) API error: token expired or incorrect"), "Z.ai (Anthropic)"),
29
+ "Z.ai (Anthropic) auth unavailable",
30
+ );
31
+ assert.equal(redactedError(new Error("something odd"), "Z.ai (Anthropic)"), "Z.ai (Anthropic) usage unavailable");
32
+ });
33
+
34
+ test("credential-shaped material in server messages is scrubbed", () => {
35
+ const shown = redactedError(new Error("Z.ai (Anthropic) API error: invalid api key sk-ant-abc123"), "Z.ai (Anthropic)");
36
+ assert.ok(!shown.includes("sk-ant-abc123"), "must not leak key material");
37
+ assert.ok(shown.includes("[REDACTED]"));
38
+ const bearer = redactedError(new Error("Z.ai (Anthropic) API error: rejected Bearer eyJhbGciOi.payload.sig"), "Z.ai (Anthropic)");
39
+ assert.ok(!bearer.includes("eyJhbGciOi"), "must not leak JWT material");
40
+ });
package/package.json CHANGED
@@ -1,9 +1,8 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.1.0",
3
+ "version": "0.5.0",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
- "main": "extensions/index.js",
7
6
  "license": "MIT",
8
7
  "keywords": [
9
8
  "pi",
@@ -14,7 +13,7 @@
14
13
  "cli"
15
14
  ],
16
15
  "engines": {
17
- "node": ">=20"
16
+ "node": ">=22.19.0"
18
17
  },
19
18
  "files": [
20
19
  "extensions",
@@ -29,9 +28,22 @@
29
28
  },
30
29
  "homepage": "https://github.com/ceulen-dev/ceulen#readme",
31
30
  "bugs": "https://github.com/ceulen-dev/ceulen/issues",
31
+ "scripts": {
32
+ "test": "node --import tsx --test extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts",
33
+ "typecheck": "tsc --noEmit"
34
+ },
32
35
  "pi": {
33
36
  "extensions": [
34
37
  "./extensions"
35
38
  ]
39
+ },
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-coding-agent": "^0.99.1",
42
+ "@earendil-works/pi-tui": "^0.99.1"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^20.19.43",
46
+ "tsx": "^4.23.1",
47
+ "typescript": "^5.9.3"
36
48
  }
37
49
  }