@jadelclemens/pi-model-map 0.0.0-stage → 0.1.1

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.
package/src/config.ts ADDED
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { CONFIG_DIR_NAME } from "./constants.js";
6
+ import type { ModelMapConfig } from "./mapping.js";
7
+ import { ModelMapper } from "./mapping.js";
8
+ import { validateProviderConfig } from "./warnings.js";
9
+
10
+ const GLOBAL_CONFIG_DIR = path.join(os.homedir(), ".pi", "agent", CONFIG_DIR_NAME);
11
+
12
+ const parseConfigFile = (file: string): ModelMapConfig => {
13
+ const raw = fs.readFileSync(file, "utf8");
14
+ const parsed = JSON.parse(raw) as ModelMapConfig;
15
+ if (!parsed.mappings || typeof parsed.mappings !== "object") {
16
+ throw new Error(`${file}: missing required "mappings" object`);
17
+ }
18
+ return parsed;
19
+ };
20
+
21
+ const providerDefaultFromFilename = (file: string): string | undefined => {
22
+ const base = path.basename(file, path.extname(file));
23
+ return base.length > 0 ? base : undefined;
24
+ };
25
+
26
+ const loadConfigDir = (dir: string): ModelMapper[] => {
27
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
28
+ return [];
29
+ }
30
+
31
+ const files = fs
32
+ .readdirSync(dir)
33
+ .filter((name) => name.endsWith(".json"))
34
+ .sort()
35
+ .map((name) => path.join(dir, name));
36
+
37
+ if (files.length === 0) {
38
+ return [];
39
+ }
40
+
41
+ const mappers = files.map((file) => {
42
+ const config = parseConfigFile(file);
43
+ const mapper = new ModelMapper(config, file, providerDefaultFromFilename(file));
44
+ validateProviderConfig(mapper);
45
+ return mapper;
46
+ });
47
+
48
+ const seen = new Set<string>();
49
+ for (const mapper of mappers) {
50
+ if (seen.has(mapper.provider)) {
51
+ throw new Error(
52
+ `${mapper.source}: duplicate provider "${mapper.provider}" — each config file must use a unique provider id`,
53
+ );
54
+ }
55
+ seen.add(mapper.provider);
56
+ }
57
+
58
+ return mappers;
59
+ };
60
+
61
+ const configDirCandidates = (cwd: string): string[] => [
62
+ path.join(cwd, ".pi", "agent", CONFIG_DIR_NAME),
63
+ path.join(cwd, ".pi", CONFIG_DIR_NAME),
64
+ path.join(cwd, CONFIG_DIR_NAME),
65
+ GLOBAL_CONFIG_DIR,
66
+ ];
67
+
68
+ export const loadModelMappers = (cwd = process.cwd()): ModelMapper[] => {
69
+ for (const dir of configDirCandidates(cwd)) {
70
+ const mappers = loadConfigDir(dir);
71
+ if (mappers.length > 0) {
72
+ return mappers;
73
+ }
74
+ }
75
+
76
+ throw new Error(
77
+ `No model-map config found. Create ${GLOBAL_CONFIG_DIR}/cursor.json (one file per provider mapping) ` +
78
+ `or copy from examples/.`,
79
+ );
80
+ };
81
+
82
+ export const createModelMappers = (cwd = process.cwd()): ModelMapper[] => {
83
+ return loadModelMappers(cwd);
84
+ };
@@ -0,0 +1,10 @@
1
+ export const CONFIG_DIR_NAME = "model-map";
2
+
3
+ /** Command name prefix for the /pi-model-map-* command family. */
4
+ export const COMMAND_PREFIX = "pi-model-map";
5
+
6
+ /** Plugin log file name, under `~/.pi/agent/model-map/`. */
7
+ export const LOG_FILE_NAME = "pi-model-map.log";
8
+
9
+ /** Log file size cap before truncate-rotation. */
10
+ export const LOG_MAX_BYTES = 2 * 1024 * 1024;
package/src/index.ts ADDED
@@ -0,0 +1,392 @@
1
+ import type { ModelThinkingLevel, ThinkingLevel } from "@earendil-works/pi-ai";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+
8
+ import { buildVirtualModelMeta } from "./catalog.js";
9
+ import { createModelMappers } from "./config.js";
10
+ import { COMMAND_PREFIX } from "./constants.js";
11
+ import { logFilePath, pluginWarn } from "./log.js";
12
+ import type { ModelMapper } from "./mapping.js";
13
+ import { checkAgainstSource } from "./source-check.js";
14
+ import { warnOnSessionStart } from "./warnings.js";
15
+
16
+ /** ModelThinkingLevel's "off" isn't a real ThinkingLevel -- normalize it to undefined for the mapper APIs that expect `ThinkingLevel | undefined`. */
17
+ const asReasoningLevel = (level: ModelThinkingLevel | undefined): ThinkingLevel | undefined =>
18
+ level && level !== "off" ? level : undefined;
19
+
20
+ type ToggleArg = "on" | "off" | "toggle";
21
+
22
+ /**
23
+ * Opt-in routing trace. Off by default (silent, matches every other Pi provider). Enable with
24
+ * PI_MODEL_MAP_DEBUG=1 to print, on every request, exactly which backend provider/model a
25
+ * canonical model + effort level + toggle combination resolved to. Useful for confirming
26
+ * routing without needing to inspect the actual outbound HTTP payload.
27
+ */
28
+ const DEBUG =
29
+ process.env.PI_MODEL_MAP_DEBUG === "1" || process.env.PI_MODEL_MAP_DEBUG === "true";
30
+
31
+ const parseToggleArg = (args: string): ToggleArg => {
32
+ const trimmed = args.trim().toLowerCase();
33
+ if (trimmed === "on" || trimmed === "off") return trimmed;
34
+ if (trimmed === "") return "toggle";
35
+ throw new Error(`Expected "on", "off", or no argument to toggle. Got "${args}".`);
36
+ };
37
+
38
+ export default (pi: ExtensionAPI) => {
39
+ const mappers = createModelMappers();
40
+ let lastCtx: ExtensionContext | null = null;
41
+ let warnedOnSession = false;
42
+
43
+ // Session-wide mapping toggles. These do not add or emulate any real API parameter —
44
+ // they only pick which pre-baked backend model ID a "provider/modelId" map entry
45
+ // resolves to for providers (like Cursor) that bake a "thinking" mode and/or a
46
+ // "fast" routing tier into the model ID string instead of exposing them as
47
+ // request options.
48
+ let thinkingEnabled = false;
49
+ let fastEnabled = false;
50
+
51
+ /**
52
+ * Warn if `canonicalId` at effort level `reasoning` has no non-thinking backend at all, so
53
+ * `/pi-model-map-thinking off` is silently overridden. Shared by route() (checked on every
54
+ * request) and the model_select / thinking_level_select handlers (checked the moment the
55
+ * selection changes, before any request is ever sent).
56
+ *
57
+ * Tracks only the *most recently checked* (provider, canonicalId, level) combination, not
58
+ * "every combination ever warned about this session" -- so cycling /thinking xhigh -> max ->
59
+ * xhigh warns all three times (each is a real change from the immediately preceding state),
60
+ * while sending multiple turns in a row without changing the model or effort level does not
61
+ * repeat the warning, since nothing changed between those checks.
62
+ */
63
+ let lastCheckedThinkingOnlyKey: string | undefined;
64
+ const checkThinkingOnlyLevel = (
65
+ mapper: ModelMapper,
66
+ canonicalId: string,
67
+ reasoning: ThinkingLevel | undefined,
68
+ ): void => {
69
+ if (thinkingEnabled) return;
70
+ const level = mapper.resolvedLevel(canonicalId, reasoning);
71
+ const key = `${mapper.provider}/${canonicalId}:${level}`;
72
+ if (key === lastCheckedThinkingOnlyKey) return;
73
+ lastCheckedThinkingOnlyKey = key;
74
+ if (!mapper.isThinkingOnlyLevel(canonicalId, level)) return;
75
+ const effortLabel = reasoning ?? "off";
76
+ lastCtx?.ui.notify(
77
+ `${effortLabel} effort for ${canonicalId} is only supported in "thinking" mode. Thinking will be ` +
78
+ `silently enabled regardless of your current pi-model-map "thinking" setting.`,
79
+ "warning",
80
+ );
81
+ };
82
+
83
+ /**
84
+ * Warn if `canonicalId` was asked for an effort level that has no entry at all in its map, so
85
+ * `toBackendRef` silently falls back to the "default" level instead. Shared by route()
86
+ * (checked on every request -- the only place this is guaranteed to see the level that will
87
+ * actually be sent, since a wrapper like pi-provider-manager's roundrobin can pick a different
88
+ * candidate per request without this extension ever seeing a model_select/thinking_level_select
89
+ * for it) and the model_select / thinking_level_select handlers (checked the moment the
90
+ * selection changes, for models selected directly rather than through such a wrapper).
91
+ *
92
+ * Tracked separately from `lastCheckedThinkingOnlyKey` (own dedup key) since the two warn about
93
+ * unrelated conditions and either can be true independently of the other's dedup state.
94
+ */
95
+ let lastCheckedUnmappedLevelKey: string | undefined;
96
+ const checkUnmappedLevel = (
97
+ mapper: ModelMapper,
98
+ canonicalId: string,
99
+ reasoning: ThinkingLevel | undefined,
100
+ ): void => {
101
+ // "off" (reasoning === undefined here) resolves to "default" by design, not by fallback --
102
+ // that's gated separately by offSupported / thinkingLevelMap.off in catalog.ts. Nothing to
103
+ // warn about here unless a real effort level was requested.
104
+ if (!reasoning) return;
105
+ const key = `${mapper.provider}/${canonicalId}:${reasoning}`;
106
+ if (key === lastCheckedUnmappedLevelKey) return;
107
+ lastCheckedUnmappedLevelKey = key;
108
+ if (!mapper.isUnmappedLevel(canonicalId, reasoning)) return;
109
+ lastCtx?.ui.notify(
110
+ `"${reasoning}" effort has no mapping for ${canonicalId} in ${mapper.source}. Falling back to ` +
111
+ `the default effort level for this model.`,
112
+ "warning",
113
+ );
114
+ };
115
+
116
+ /** Provider ids may be shared with physical models, so match on the family id too. */
117
+ const mapperFor = (provider: string | undefined, id: string): ModelMapper | undefined =>
118
+ mappers.find((m) => m.provider === provider && m.getCanonicalFamilies().includes(id));
119
+
120
+ const registerFamily = (mapper: ModelMapper, id: string): void => {
121
+ pi.registerVirtualModel({
122
+ ...buildVirtualModelMeta(mapper, id),
123
+ route: (request, ctx) => {
124
+ lastCtx = ctx;
125
+ const reasoning = asReasoningLevel(request.thinkingLevel);
126
+ const ref = mapper.toBackendRef(id, reasoning, thinkingEnabled, fastEnabled);
127
+ if (!ref) {
128
+ throw new Error(`[pi-model-map] No mapping found for "${id}" in ${mapper.source}.`);
129
+ }
130
+ checkThinkingOnlyLevel(mapper, id, reasoning);
131
+ checkUnmappedLevel(mapper, id, reasoning);
132
+ if (DEBUG) {
133
+ // Leading "\n": Pi's TUI doesn't insert a newline before extension stderr output.
134
+ console.error(
135
+ `\n[pi-model-map:debug] ${mapper.provider}/${id} ` +
136
+ `(reasoning=${reasoning ?? "default"}, thinking=${thinkingEnabled}, fast=${fastEnabled}) ` +
137
+ `-> ${ref.provider}/${ref.id}`,
138
+ );
139
+ }
140
+ const model = ctx.modelRegistry.find(ref.provider, ref.id);
141
+ if (!model) {
142
+ throw new Error(
143
+ `[pi-model-map] Backend ${ref.provider}/${ref.id} for ${mapper.provider}/${id} is not registered ` +
144
+ `(${mapper.source}). Install and authenticate the delegate provider first.`,
145
+ );
146
+ }
147
+ return { model, thinkingLevel: request.thinkingLevel };
148
+ },
149
+ });
150
+ };
151
+
152
+ for (const mapper of mappers) {
153
+ for (const id of mapper.getCanonicalFamilies()) registerFamily(mapper, id);
154
+ }
155
+
156
+ const missingBackends = (mapper: ModelMapper, canonicalId: string, ctx: ExtensionContext): string[] => {
157
+ return mapper.getFamilyBackendRefs(canonicalId)
158
+ .filter((ref) => !ctx.modelRegistry.find(ref.provider, ref.id))
159
+ .map((ref) => `${ref.provider}/${ref.id}`);
160
+ };
161
+
162
+ /** Registry availability is a session-start diagnostic, not a per-request check. */
163
+ const scanRegistryAvailability = (ctx: ExtensionContext): number => {
164
+ let issues = 0;
165
+ for (const mapper of mappers) {
166
+ warnOnSessionStart(ctx, mapper);
167
+ const availableFamilies = mapper.getCanonicalFamilies().filter((id) =>
168
+ mapper.getFamilyBackendRefs(id).some((ref) => ctx.modelRegistry.find(ref.provider, ref.id)),
169
+ );
170
+ for (const id of mapper.getCanonicalFamilies()) {
171
+ const refs = mapper.getFamilyBackendRefs(id);
172
+ const missing = missingBackends(mapper, id, ctx);
173
+ if (!availableFamilies.includes(id)) {
174
+ pluginWarn(
175
+ `Omitting ${mapper.provider}/${id}: none of its mapped backend models are registered.`,
176
+ );
177
+ issues++;
178
+ } else if (missing.length > 0 && missing.length < refs.length) {
179
+ pluginWarn(
180
+ `${mapper.provider}/${id} has unavailable mapped backend(s): ${missing.join(", ")}. ` +
181
+ `Other mapped backend variants are available; selecting an unavailable variant may fail.`,
182
+ );
183
+ issues++;
184
+ }
185
+ }
186
+ for (const id of mapper.getCanonicalFamilies()) {
187
+ if (availableFamilies.includes(id)) registerFamily(mapper, id);
188
+ else pi.unregisterVirtualModel(mapper.provider, id);
189
+ }
190
+ }
191
+ return issues;
192
+ };
193
+
194
+ const updateStatus = (ctx: ExtensionContext): void => {
195
+ const parts: string[] = [];
196
+ if (thinkingEnabled) parts.push("thinking");
197
+ if (fastEnabled) parts.push("fast");
198
+ ctx.ui.setStatus("pi-model-map", parts.length > 0 ? parts.join("+") : undefined);
199
+ };
200
+
201
+ const applyThinking = (ctx: ExtensionCommandContext, arg: ToggleArg): void => {
202
+ const next = arg === "toggle" ? !thinkingEnabled : arg === "on";
203
+ const mapper = ctx.model && mapperFor(ctx.model.provider, ctx.model.id);
204
+ if (next && mapper && ctx.model && !mapper.supportsThinkingToggle(ctx.model.id)) {
205
+ ctx.ui.notify(
206
+ `No "thinking" variant configured for ${ctx.model.id} in ${mapper.source}. Falling back to the default mapping.`,
207
+ "warning",
208
+ );
209
+ }
210
+ thinkingEnabled = next;
211
+ if (thinkingEnabled) {
212
+ // The thinking-only-level warning only applies while the toggle is off (see
213
+ // checkThinkingOnlyLevel); clear its "last checked" state so that if the toggle is turned
214
+ // back off later while still on the same model/level, that's treated as a fresh change and
215
+ // warns again, rather than being silently deduped against a check from before this toggle.
216
+ lastCheckedThinkingOnlyKey = undefined;
217
+ }
218
+ updateStatus(ctx);
219
+ ctx.ui.notify(`Model-map thinking variant: ${thinkingEnabled ? "on" : "off"}`, "info");
220
+ };
221
+
222
+ const applyFast = (ctx: ExtensionCommandContext, arg: ToggleArg): void => {
223
+ const next = arg === "toggle" ? !fastEnabled : arg === "on";
224
+ const mapper = ctx.model && mapperFor(ctx.model.provider, ctx.model.id);
225
+ if (next && mapper && ctx.model && !mapper.supportsFastToggle(ctx.model.id)) {
226
+ ctx.ui.notify(
227
+ `No "fast" variant configured for ${ctx.model.id} in ${mapper.source}. Falling back to the default mapping.`,
228
+ "warning",
229
+ );
230
+ }
231
+ fastEnabled = next;
232
+ updateStatus(ctx);
233
+ ctx.ui.notify(`Model-map fast variant: ${fastEnabled ? "on" : "off"}`, "info");
234
+ };
235
+
236
+ const toggleCompletions = (prefix: string) => {
237
+ const options = ["on", "off"];
238
+ const trimmed = prefix.trim();
239
+ const filtered = trimmed.length > 0 ? options.filter((o) => o.startsWith(trimmed)) : options;
240
+ return filtered.length > 0 ? filtered.map((value) => ({ value, label: value })) : null;
241
+ };
242
+
243
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking`, {
244
+ description:
245
+ 'Toggle use of the mapped "thinking" backend variant (falls back to default if unconfigured)',
246
+ getArgumentCompletions: toggleCompletions,
247
+ handler: async (args, ctx) => {
248
+ try {
249
+ applyThinking(ctx, parseToggleArg(args));
250
+ } catch (error) {
251
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
252
+ }
253
+ },
254
+ });
255
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking-on`, {
256
+ description: 'Enable the mapped "thinking" backend variant',
257
+ handler: async (_args, ctx) => applyThinking(ctx, "on"),
258
+ });
259
+ pi.registerCommand(`${COMMAND_PREFIX}-thinking-off`, {
260
+ description: 'Disable the mapped "thinking" backend variant',
261
+ handler: async (_args, ctx) => applyThinking(ctx, "off"),
262
+ });
263
+
264
+ pi.registerCommand(`${COMMAND_PREFIX}-fast`, {
265
+ description:
266
+ 'Toggle use of the mapped "fast" backend variant (falls back to default if unconfigured)',
267
+ getArgumentCompletions: toggleCompletions,
268
+ handler: async (args, ctx) => {
269
+ try {
270
+ applyFast(ctx, parseToggleArg(args));
271
+ } catch (error) {
272
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
273
+ }
274
+ },
275
+ });
276
+ pi.registerCommand(`${COMMAND_PREFIX}-fast-on`, {
277
+ description: 'Enable the mapped "fast" backend variant',
278
+ handler: async (_args, ctx) => applyFast(ctx, "on"),
279
+ });
280
+ pi.registerCommand(`${COMMAND_PREFIX}-fast-off`, {
281
+ description: 'Disable the mapped "fast" backend variant',
282
+ handler: async (_args, ctx) => applyFast(ctx, "off"),
283
+ });
284
+
285
+ pi.registerCommand(`${COMMAND_PREFIX}-check-source`, {
286
+ description:
287
+ 'Re-check every config file\'s "source" catalog now (without restarting Pi) and report any backend ids that have disappeared',
288
+ handler: async (_args, ctx) => {
289
+ let checked = 0;
290
+ let stale = 0;
291
+ let skipped = 0;
292
+ for (const mapper of mappers) {
293
+ const result = checkAgainstSource(mapper);
294
+ if (!result) {
295
+ skipped++;
296
+ continue;
297
+ }
298
+ checked++;
299
+ if (result.error) {
300
+ ctx.ui.notify(
301
+ `${mapper.provider}: could not check "${result.resolvedPath}": ${result.error}`,
302
+ "warning",
303
+ );
304
+ continue;
305
+ }
306
+ if (result.missingIds.length > 0) {
307
+ stale += result.missingIds.length;
308
+ for (const id of result.missingIds) {
309
+ const locations = mapper.getBackendIdLocations(id).join(", ");
310
+ ctx.ui.notify(
311
+ `${mapper.provider}: backend id "${id}" (${locations}) not found in ${result.resolvedPath}`,
312
+ "warning",
313
+ );
314
+ }
315
+ }
316
+ }
317
+ if (checked === 0) {
318
+ ctx.ui.notify(
319
+ `No config file has "source" set -- nothing to check. Add "source" (and optionally ` +
320
+ `"sourceListPath"/"sourceIdField") to a config file to enable this.`,
321
+ "info",
322
+ );
323
+ } else if (stale === 0) {
324
+ ctx.ui.notify(
325
+ `Checked ${checked} config file(s) against their "source" catalogs: every backend id still exists.${skipped > 0 ? ` (${skipped} file(s) skipped -- no "source" set.)` : ""}`,
326
+ "info",
327
+ );
328
+ } else {
329
+ ctx.ui.notify(`Found ${stale} stale backend id(s) across ${checked} checked config file(s). See warnings above.`, "warning");
330
+ }
331
+ },
332
+ });
333
+
334
+ const rememberContext = (_: unknown, ctx: ExtensionContext) => {
335
+ lastCtx = ctx;
336
+ updateStatus(ctx);
337
+ };
338
+
339
+ pi.on("session_start", (_event, ctx) => {
340
+ lastCtx = ctx;
341
+ const issues = scanRegistryAvailability(ctx);
342
+ if (issues > 0) {
343
+ ctx.ui.notify(
344
+ `${issues} mapped family(ies) have backends Pi has not registered. Details: ${logFilePath()}`,
345
+ "warning",
346
+ );
347
+ }
348
+ if (!warnedOnSession) {
349
+ // Also check whatever model/thinking-level is already active as of this session bind --
350
+ // covers a session that already had an affected model+level selected before this check
351
+ // existed, or before an extension reload, rather than only catching it on the next change
352
+ // or the next request.
353
+ if (ctx.model) {
354
+ const mapper = mapperFor(ctx.model.provider, ctx.model.id);
355
+ if (mapper) {
356
+ const level = asReasoningLevel(ctx.thinkingLevel);
357
+ checkThinkingOnlyLevel(mapper, ctx.model.id, level);
358
+ checkUnmappedLevel(mapper, ctx.model.id, level);
359
+ }
360
+ }
361
+ warnedOnSession = true;
362
+ }
363
+ updateStatus(ctx);
364
+ });
365
+
366
+ // Keep lastCtx current for nested streaming; do not re-scan the registry on every turn.
367
+ pi.on("before_agent_start", rememberContext);
368
+
369
+ // Proactively catch the same "this effort level is thinking-only" situation the moment the
370
+ // model or thinking level changes, rather than only at request time (route() already
371
+ // covers request time; these two cover selection time).
372
+ pi.on("model_select", (event, ctx) => {
373
+ lastCtx = ctx;
374
+ const mapper = mapperFor(event.model.provider, event.model.id);
375
+ if (mapper) {
376
+ const level = asReasoningLevel(ctx.thinkingLevel);
377
+ checkThinkingOnlyLevel(mapper, event.model.id, level);
378
+ checkUnmappedLevel(mapper, event.model.id, level);
379
+ }
380
+ });
381
+
382
+ pi.on("thinking_level_select", (event, ctx) => {
383
+ lastCtx = ctx;
384
+ if (!ctx.model) return;
385
+ const mapper = mapperFor(ctx.model.provider, ctx.model.id);
386
+ if (mapper) {
387
+ const level = asReasoningLevel(event.level);
388
+ checkThinkingOnlyLevel(mapper, ctx.model.id, level);
389
+ checkUnmappedLevel(mapper, ctx.model.id, level);
390
+ }
391
+ });
392
+ };
package/src/log.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { appendFileSync, mkdirSync, statSync, truncateSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { CONFIG_DIR_NAME, LOG_FILE_NAME, LOG_MAX_BYTES } from "./constants.js";
6
+
7
+ const WARN_PREFIX = "[pi-model-map]";
8
+
9
+ /** Always `~/.pi/agent/model-map/pi-model-map.log`, even when config was loaded from a project-local directory. */
10
+ export const logFilePath = (): string =>
11
+ path.join(os.homedir(), ".pi", "agent", CONFIG_DIR_NAME, LOG_FILE_NAME);
12
+
13
+ const appendLog = (message: string): void => {
14
+ const file = logFilePath();
15
+ const line = `${new Date().toISOString()} ${message}\n`;
16
+ try {
17
+ mkdirSync(path.dirname(file), { recursive: true });
18
+ let size = 0;
19
+ try {
20
+ size = statSync(file).size;
21
+ } catch {
22
+ size = 0;
23
+ }
24
+ if (size > LOG_MAX_BYTES) truncateSync(file, 0);
25
+ appendFileSync(file, line);
26
+ } catch {
27
+ /* best-effort — logging must never break startup or a turn */
28
+ }
29
+ };
30
+
31
+ /** Persist a warning to the plugin log and echo it to stderr (TUI startup output is ephemeral). */
32
+ export const pluginWarn = (message: string): void => {
33
+ const line = message.startsWith(WARN_PREFIX) ? message : `${WARN_PREFIX} ${message}`;
34
+ console.warn(line);
35
+ appendLog(line);
36
+ };