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,142 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ // ── Types ────────────────────────────────────────────────────────────────────
6
+
7
+ export interface RouterSettings {
8
+ /** Base URL of the router's OpenAI-compatible API (e.g. http://host:20128/v1). */
9
+ baseUrl: string;
10
+ /** Enable Pi thinking-level controls on router models. Default true. */
11
+ enableReasoning: boolean;
12
+ }
13
+
14
+ // ── Constants ────────────────────────────────────────────────────────────────
15
+
16
+ /** Repo-scope settings (`.pi/settings.json` in the working directory). */
17
+ const REPO_SETTINGS_PATH = join(process.cwd(), ".pi", "settings.json");
18
+
19
+ function agentDir(): string {
20
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
21
+ }
22
+
23
+ /** User-global settings (lazy — honors PI_CODING_AGENT_DIR set by tests). */
24
+ function globalSettingsPath(): string {
25
+ return join(agentDir(), "settings.json");
26
+ }
27
+
28
+ function authPath(): string {
29
+ return join(agentDir(), "auth.json");
30
+ }
31
+
32
+ /** Env names (ROUTER_* with NINE_ROUTER_* legacy aliases), read lazily. */
33
+ const envBaseUrl = () => process.env.ROUTER_BASE_URL ?? process.env.NINE_ROUTER_BASE_URL;
34
+ const envReasoning = () => process.env.ROUTER_ENABLE_REASONING ?? process.env.NINE_ROUTER_ENABLE_REASONING;
35
+
36
+ // ── Public API ───────────────────────────────────────────────────────────────
37
+
38
+ /** Read `router` settings. Precedence (with trustProject: true): env var >
39
+ * repo `.pi/settings.json` > global `~/.pi/agent/settings.json` > defaults.
40
+ * Default (trustProject falsy): repo settings are ignored entirely — an
41
+ * untrusted checkout must not redirect `router.baseUrl` to an attacker
42
+ * endpoint while the auth.json credential is sent there as Bearer.
43
+ * Repo-scope `router.apiKey` is ignored (secrets must not come from a checked-in file). */
44
+ export function getSettings(opts: { trustProject?: boolean } = {}): RouterSettings {
45
+ const saved = readRouterSection(readFileJson(globalSettingsPath())) ?? {};
46
+ const repo = opts.trustProject
47
+ ? readRouterSection(readFileJson(REPO_SETTINGS_PATH)) ?? {}
48
+ : {};
49
+ return {
50
+ baseUrl: normalizeUrl(envBaseUrl() || repo.baseUrl || saved.baseUrl || ""),
51
+ enableReasoning:
52
+ parseBooleanFlag(envReasoning()) ?? repo.enableReasoning ?? saved.enableReasoning ?? true,
53
+ };
54
+ }
55
+
56
+ // ── Helpers ──────────────────────────────────────────────────────────────────
57
+
58
+ function readFileJson(path: string): Record<string, unknown> | null {
59
+ try {
60
+ if (!existsSync(path)) return null;
61
+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ /** Non-secret fields only; drop any `apiKey` a repo file tries to inject. */
68
+ function readRouterSection(json: Record<string, unknown> | null): Partial<RouterSettings> | null {
69
+ if (!json || typeof json.router !== "object" || json.router === null) return null;
70
+ const r = json.router as Record<string, unknown>;
71
+ const out: Partial<RouterSettings> = {};
72
+ if (typeof r.baseUrl === "string" && r.baseUrl.trim()) out.baseUrl = r.baseUrl.trim();
73
+ if (typeof r.enableReasoning === "boolean") out.enableReasoning = r.enableReasoning;
74
+ return out;
75
+ }
76
+
77
+ export function normalizeUrl(url: string): string {
78
+ return url.replace(/\/+$/, "");
79
+ }
80
+
81
+ /** Read the stored API key from `~/.pi/agent/auth.json` (status display only —
82
+ * request auth resolution is Pi's job via the provider's apiKey config). */
83
+ export function readStoredApiKey(): string | undefined {
84
+ const json = readFileJson(authPath());
85
+ const cred = json?.router as { key?: unknown } | undefined;
86
+ return typeof cred?.key === "string" && cred.key ? cred.key : undefined;
87
+ }
88
+
89
+ export function maskApiKey(key: string | undefined): string {
90
+ if (!key) return "(not set)";
91
+ if (key.length <= 8) return `(${key.length} chars)`;
92
+ return key.slice(0, 4) + "●".repeat(key.length - 8) + key.slice(-4);
93
+ }
94
+
95
+ // ── Writes ───────────────────────────────────────────────────────────────────
96
+
97
+ /** Read-modify-write non-secret `router` fields into the GLOBAL settings.json
98
+ * (merge, never clobber). `baseUrl` is normalized (trailing slashes stripped).
99
+ * Atomicity (tmp+rename) is part of the contract — exported for tests. */
100
+ export function writeRouterSection(patch: { baseUrl?: string; enableReasoning?: boolean }): void {
101
+ let settings: Record<string, unknown> | null = {};
102
+ try {
103
+ if (existsSync(globalSettingsPath())) {
104
+ settings = JSON.parse(readFileSync(globalSettingsPath(), "utf8")) as Record<string, unknown>;
105
+ }
106
+ } catch {
107
+ // Corrupt ≠ missing: a {} fallback would make the rename below overwrite
108
+ // the file with ONLY the router section, destroying every other key.
109
+ settings = null;
110
+ }
111
+ if (settings === null) {
112
+ throw new Error(`${globalSettingsPath()} is not valid JSON — fix or remove it before saving.`);
113
+ }
114
+ const router = (settings.router ?? {}) as Record<string, unknown>;
115
+ if (patch.baseUrl !== undefined) router.baseUrl = normalizeUrl(patch.baseUrl);
116
+ if (patch.enableReasoning !== undefined) router.enableReasoning = patch.enableReasoning;
117
+ settings.router = router;
118
+ mkdirSync(dirname(globalSettingsPath()), { recursive: true });
119
+ const tmp = globalSettingsPath() + ".tmp";
120
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
121
+ renameSync(tmp, globalSettingsPath());
122
+ }
123
+
124
+ export function configSummary(settings: RouterSettings): string {
125
+ const key = process.env.ROUTER_API_KEY
126
+ ? maskApiKey(process.env.ROUTER_API_KEY) + " (env)"
127
+ : maskApiKey(readStoredApiKey());
128
+ const reasoning = settings.enableReasoning
129
+ ? "ON"
130
+ : "OFF (enable via /config → Router)";
131
+ return `Endpoint: ${settings.baseUrl || "(not configured)"}
132
+ API key: ${key}
133
+ Reasoning: ${reasoning}`;
134
+ }
135
+
136
+ function parseBooleanFlag(value: string | undefined): boolean | undefined {
137
+ if (!value) return undefined;
138
+ const v = value.trim().toLowerCase();
139
+ if (["1", "true", "yes", "on", "enabled"].includes(v)) return true;
140
+ if (["0", "false", "no", "off", "disabled"].includes(v)) return false;
141
+ return undefined;
142
+ }
@@ -0,0 +1,92 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname } from "node:path";
4
+ import { join } from "node:path";
5
+
6
+ /** One-shot migration: pi-9router's `9router-config.json` →
7
+ * settings.json (`router.baseUrl`, `router.enableReasoning`) + auth.json
8
+ * (`router.api_key` credential, for `/login router` semantics).
9
+ * Runs only when the legacy file exists; never overwrites existing router
10
+ * entries; renames the legacy file to `.migrated` when done. */
11
+
12
+ function agentDir(): string {
13
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
14
+ }
15
+ const legacyConfigPath = () => join(agentDir(), "9router-config.json");
16
+ const settingsPath = () => join(agentDir(), "settings.json");
17
+ const authPath = () => join(agentDir(), "auth.json");
18
+
19
+ interface LegacyConfig {
20
+ baseUrl?: string;
21
+ apiKey?: string;
22
+ enableReasoning?: boolean;
23
+ }
24
+
25
+ /** Returns true when a migration happened (or the legacy file was consumed). */
26
+ export function migrateLegacyConfig(): boolean {
27
+ const LEGACY_CONFIG_PATH = legacyConfigPath();
28
+ if (!existsSync(LEGACY_CONFIG_PATH)) return false;
29
+
30
+ let legacy: LegacyConfig = {};
31
+ try {
32
+ legacy = JSON.parse(readFileSync(LEGACY_CONFIG_PATH, "utf8")) as LegacyConfig;
33
+ } catch {
34
+ // Unreadable legacy config — rename out of the way so we never retry.
35
+ safeRename(LEGACY_CONFIG_PATH);
36
+ return false;
37
+ }
38
+
39
+ // settings.json: merge `router` section without clobbering existing keys.
40
+ const settings = readFileJson(settingsPath());
41
+ if (settings === null) return false; // unparseable settings.json — don't wipe it; retry next load
42
+ const router = (settings.router ?? {}) as Record<string, unknown>;
43
+ if (legacy.baseUrl && router.baseUrl === undefined) router.baseUrl = legacy.baseUrl;
44
+ if (legacy.enableReasoning !== undefined && router.enableReasoning === undefined) {
45
+ router.enableReasoning = legacy.enableReasoning;
46
+ }
47
+ if (Object.keys(router).length > 0) {
48
+ settings.router = router;
49
+ atomicWriteJson(settingsPath(), settings);
50
+ }
51
+
52
+ // auth.json: add `router` credential if absent and legacy key exists.
53
+ if (legacy.apiKey) {
54
+ const auth = readFileJson(authPath());
55
+ if (auth !== null && !auth.router) { // unparseable auth.json — never overwrite
56
+ auth.router = { type: "api_key", key: legacy.apiKey };
57
+ atomicWriteJson(authPath(), auth);
58
+ }
59
+ }
60
+
61
+ safeRename(LEGACY_CONFIG_PATH);
62
+ return true;
63
+ }
64
+
65
+ /** Write settings/auth atomically: tmp file in the same dir, then rename —
66
+ * a crash mid-write can never leave a truncated settings.json/auth.json
67
+ * (same pattern as writeRouterSection in lib/config.ts). */
68
+ function atomicWriteJson(path: string, value: unknown): void {
69
+ mkdirSync(dirname(path), { recursive: true });
70
+ const tmp = path + ".tmp";
71
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
72
+ renameSync(tmp, path);
73
+ }
74
+
75
+ /** Rename the legacy file out of the way; tolerate losing a race with
76
+ * another Pi session that migrated first (ENOENT/EPERM) and read-only dirs. */
77
+ function safeRename(from: string): void {
78
+ try {
79
+ renameSync(from, from + ".migrated");
80
+ } catch { /* already migrated elsewhere or unwritable — non-fatal */ }
81
+ }
82
+
83
+ function readFileJson(path: string): Record<string, unknown> | null {
84
+ try {
85
+ if (!existsSync(path)) return {};
86
+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
87
+ } catch {
88
+ // Exists but unparseable — signal "don't touch" so the caller never
89
+ // overwrite-wipes the user's settings/auth with a fresh {}.
90
+ return null;
91
+ }
92
+ }
@@ -0,0 +1,138 @@
1
+ import type { ExtensionAPI, ProviderConfig, ProviderModelConfig } from "@earendil-works/pi-coding-agent";
2
+ import type { RouterSettings } from "./config.js";
3
+ import { fetchModels, mapModel, applyReasoning, resolveVision, type PiModel } from "./client.js";
4
+
5
+ export const PROVIDER_ID = "router";
6
+
7
+ /** Freshness window for the persisted catalog: within it, maybeRefreshCatalog
8
+ * treats the stored models as fresh and skips the network fetch. */
9
+ export const ROUTER_MODELS_TTL_MS = 15 * 60_000;
10
+
11
+ /** Unix ms of the last completed network fetch (persisted as `checkedAt`,
12
+ * mirroring Pi's own remote-catalog convention). Undefined = never fetched
13
+ * or legacy store without the field → treated as stale so the next
14
+ * maybeRefreshCatalog backfills it. */
15
+ let lastFetchedAt: number | undefined;
16
+
17
+ /** Shared in-flight refresh — concurrent callers await the same operation
18
+ * instead of stacking generations that supersede each other (pi-ai drops
19
+ * publications from superseded generations). */
20
+ let inflight: Promise<void> | undefined;
21
+
22
+ /** Test hook: reset freshness + in-flight state between tests. */
23
+ export function resetCatalogState(): void {
24
+ lastFetchedAt = undefined;
25
+ inflight = undefined;
26
+ }
27
+
28
+ /** Age of the persisted catalog, or undefined when unknown (legacy/absent). */
29
+ export function catalogAgeMs(): number | undefined {
30
+ return lastFetchedAt === undefined ? undefined : Date.now() - lastFetchedAt;
31
+ }
32
+
33
+ /** TTL-gated, in-flight-guarded provider-scoped refresh. The only call site
34
+ * that reaches the network for router models in RPC/print/headless modes
35
+ * (Pi itself only network-refreshes from the TUI /model picker). Skips when
36
+ * PI_OFFLINE is set or the catalog is fresh (unless force).
37
+ *
38
+ * Force semantics: force with a refresh in flight does NOT join it — a join
39
+ * would silently return the OLD endpoint's fetch right after a baseUrl flip
40
+ * and leave the new catalog unpulled for a full TTL. Instead the in-flight
41
+ * job is superseded and the forced fetch proceeds. Non-force joins. */
42
+ export function maybeRefreshCatalog(
43
+ ctx: { modelRegistry: { refresh(options?: { providers?: string[]; force?: boolean }): Promise<unknown> } },
44
+ opts?: { force?: boolean },
45
+ ): Promise<void> {
46
+ if (opts?.force === true) {
47
+ // Supersede the in-flight job (if any): its finally sees
48
+ // inflight !== job.p and skips the clear; the registry's per-provider
49
+ // generation guard aborts the stale fetch (refreshControllers).
50
+ inflight = undefined;
51
+ } else if (inflight) {
52
+ return inflight;
53
+ }
54
+ if (process.env.PI_OFFLINE) return Promise.resolve();
55
+ if (!opts?.force && lastFetchedAt !== undefined && Date.now() - lastFetchedAt < ROUTER_MODELS_TTL_MS) {
56
+ return Promise.resolve();
57
+ }
58
+ // Holder object: the finally clause must reference the promise while TS's
59
+ // definite-assignment analysis can't see the IIFE-to-let assignment order.
60
+ const job = { p: undefined as unknown as Promise<void> };
61
+ job.p = (async () => {
62
+ try {
63
+ await ctx.modelRegistry.refresh({ providers: [PROVIDER_ID], force: opts?.force === true ? true : undefined });
64
+ } finally {
65
+ if (inflight === job.p) inflight = undefined;
66
+ }
67
+ })();
68
+ inflight = job.p;
69
+ return job.p;
70
+ }
71
+
72
+ /** Context Pi hands to refreshModels (RefreshModelsContext is not exported
73
+ * by the SDK's public surface — derive it from ProviderConfig's signature). */
74
+ export type RefreshCtx = NonNullable<Parameters<NonNullable<ProviderConfig["refreshModels"]>>[0]>;
75
+
76
+ /** Register the router provider with dynamic model discovery via Pi's
77
+ * `refreshModels` contract:
78
+ * - Offline phase (startup, `allowNetwork: false`): return the persisted
79
+ * catalog from `~/.pi/agent/models-store.json` (`context.stored`), re-mapped
80
+ * with the current reasoning flag. The composer applies the return value
81
+ * in-memory — instant session restore, no network, and a reasoning toggle
82
+ * takes effect even when the endpoint is down.
83
+ * - Network phase: fetch `GET /v1/models`, map, return. We also persist via
84
+ * `context.publish({ persist })` so the next session restores from cache.
85
+ *
86
+ * Auth: `apiKey: "$ROUTER_API_KEY"` — auth.json credential (from `/login router`)
87
+ * wins over the env var; provider is unconfigured only when both are absent.
88
+ *
89
+ * Return-value contract (provider-composer.js): truthy return replaces the
90
+ * in-memory list; `undefined` keeps the current list untouched. */
91
+ export function registerProvider(pi: ExtensionAPI, settings: RouterSettings): void {
92
+ pi.registerProvider(PROVIDER_ID, {
93
+ name: "Router (OpenAI-compatible)",
94
+ baseUrl: settings.baseUrl,
95
+ apiKey: "$ROUTER_API_KEY",
96
+ api: "openai-completions",
97
+ models: [],
98
+ // SDK type says Promise<ProviderModelConfig[]>, but the composer treats a
99
+ // falsy return as "no change" (provider-composer.js `if (refreshed)`) —
100
+ // returning undefined keeps the restored list. Runtime-verified.
101
+ refreshModels: (async (context: RefreshCtx): Promise<ProviderModelConfig[] | undefined> => {
102
+ const stored = context.stored?.models as PiModel[] | undefined;
103
+ // Freshness for maybeRefreshCatalog; backfilled on restore for legacy
104
+ // stores that predate the checkedAt field.
105
+ const checkedAt = (context.stored as { checkedAt?: number } | undefined)?.checkedAt;
106
+
107
+ if (!context.allowNetwork || context.signal.aborted) {
108
+ if (checkedAt !== undefined) lastFetchedAt = checkedAt;
109
+ // Offline: restore persisted catalog, re-mapped with current reasoning
110
+ // flag. Vision is re-resolved so stale persisted flags self-heal —
111
+ // /v1/models vision metadata lies in both directions (see client.ts
112
+ // VISION_OVERRIDES/VISION_DOWNGRADES) and old caches froze it verbatim.
113
+ return stored?.length
114
+ ? (stored
115
+ // Array.isArray guards legacy/malformed store entries (treated as text-only).
116
+ .map((m) => ({ ...m, input: resolveVision(m.id, Array.isArray(m.input) && m.input.includes("image")) ? ["text", "image"] : ["text"] }) as PiModel)
117
+ .map((m) => applyReasoning(m, settings.enableReasoning)) as unknown as ProviderModelConfig[])
118
+ : undefined;
119
+ }
120
+
121
+ const cred = context.credential as { type?: string; key?: string } | undefined;
122
+ const raw = await fetchModels(settings, context.signal, cred?.key);
123
+ if (context.signal.aborted) return undefined;
124
+ const models = raw.map((m) => mapModel(m, settings.enableReasoning)) as unknown as ProviderModelConfig[];
125
+ if (!models.length) return undefined; // keep restored models on empty fetch
126
+ lastFetchedAt = Date.now();
127
+ // persist entry is Model<Api>[] at runtime; our mapped shape is compatible
128
+ // (composer clones and stores it verbatim — verified in models-store.json).
129
+ // checkedAt survives restarts so freshness is known across sessions.
130
+ await context.publish({ persist: { models: models as never, checkedAt: lastFetchedAt } });
131
+ // Late-loading signal for other extensions (pi-plan per-mode model retry).
132
+ // Runs after all extensions registered their listeners, so this is safe.
133
+ pi.events.emit("router:models-loaded", { provider: PROVIDER_ID, count: models.length });
134
+ return models;
135
+ }) as ProviderConfig["refreshModels"],
136
+ });
137
+ }
138
+
@@ -0,0 +1,19 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { PROVIDER_ID } from "./provider.js";
3
+
4
+ /** Re-select the active router model so Pi picks up refreshed capability
5
+ * flags (e.g. reasoning after a toggle). id+provider are unchanged, so Pi's
6
+ * modelsAreEqual guard suppresses the model_select event — but Pi core still
7
+ * re-applies the global thinking default inside setModel (its guard covers
8
+ * only the event), which would silently reset a session-only /thinking pick.
9
+ * Snapshot the level and restore it if setModel clobbered it. */
10
+ export async function refreshActiveModel(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
11
+ const active = ctx.model;
12
+ if (active?.provider !== PROVIDER_ID || !active.id) return;
13
+ const refreshed = ctx.modelRegistry.find(PROVIDER_ID, active.id);
14
+ if (refreshed) {
15
+ const level = pi.getThinkingLevel();
16
+ try { await pi.setModel(refreshed); } catch { return; /* missing auth — ignore */ }
17
+ if (pi.getThinkingLevel() !== level) pi.setThinkingLevel(level);
18
+ }
19
+ }
@@ -0,0 +1,77 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { guarded } from "../../../index.ts";
4
+
5
+ // Minimal ExtensionAPI stub — only the register* surface the guard wraps.
6
+ function makePi() {
7
+ const calls: { kind: string; name: string }[] = [];
8
+ const rec = (kind: string) => (first: { name?: string } | string) => {
9
+ calls.push({ kind, name: typeof first === "string" ? first : first.name! });
10
+ };
11
+ return {
12
+ calls,
13
+ pi: {
14
+ registerCommand: rec("command"),
15
+ registerTool: rec("tool"),
16
+ registerFlag: rec("flag"),
17
+ registerShortcut: rec("shortcut"),
18
+ registerMessageRenderer: rec("renderer"),
19
+ registerEntryRenderer: rec("entry-renderer"),
20
+ registerProvider: rec("provider"),
21
+ } as never,
22
+ };
23
+ }
24
+
25
+ test("cross-module claim of the same name throws naming both modules", () => {
26
+ const { pi } = makePi();
27
+ const owner = new Map<string, string>();
28
+ guarded(pi, "router", owner).registerCommand("usage-detail", {} as never);
29
+ assert.throws(
30
+ () => guarded(pi, "usage", owner).registerCommand("usage-detail", {} as never),
31
+ /module "usage" re-registered command:usage-detail \(already owned by "router"\)/,
32
+ );
33
+ });
34
+
35
+ test("same-module re-claim passes — router's runtime provider refresh pattern", () => {
36
+ const { pi } = makePi();
37
+ const owner = new Map<string, string>();
38
+ const g = guarded(pi, "router", owner);
39
+ g.registerProvider("router" as never);
40
+ g.registerProvider("router" as never); // settings reload re-registers the provider
41
+ g.registerCommand("router-status", {} as never);
42
+ g.registerCommand("router-status", {} as never); // harmless re-claim
43
+ assert.deepEqual(owner.get("provider:router"), "router");
44
+ });
45
+
46
+ test("different names from different modules coexist; ownership never transfers", () => {
47
+ const { pi } = makePi();
48
+ const owner = new Map<string, string>();
49
+ guarded(pi, "router", owner).registerCommand("router-status", {} as never);
50
+ guarded(pi, "usage", owner).registerCommand("usage", {} as never);
51
+ guarded(pi, "usage", owner).registerMessageRenderer("ceulen-usage-context", (() => {}) as never);
52
+ assert.equal(owner.get("command:router-status"), "router");
53
+ assert.equal(owner.get("command:usage"), "usage");
54
+ assert.equal(owner.get("renderer:ceulen-usage-context"), "usage");
55
+ });
56
+
57
+ test("the config module owns command:config; another module claiming it throws", () => {
58
+ const { pi } = makePi();
59
+ const owner = new Map<string, string>();
60
+ guarded(pi, "config", owner).registerCommand("config", {} as never);
61
+ assert.equal(owner.get("command:config"), "config");
62
+ assert.throws(
63
+ () => guarded(pi, "router", owner).registerCommand("config", {} as never),
64
+ /module "router" re-registered command:config \(already owned by "config"\)/,
65
+ );
66
+ });
67
+
68
+ test("claims pass through to the underlying pi API", () => {
69
+ const { pi, calls } = makePi();
70
+ const owner = new Map<string, string>();
71
+ guarded(pi, "usage", owner).registerCommand("usage", {} as never);
72
+ guarded(pi, "usage", owner).registerProvider({ name: "router" } as never);
73
+ assert.deepEqual(calls, [
74
+ { kind: "command", name: "usage" },
75
+ { kind: "provider", name: "router" },
76
+ ]);
77
+ });