durable-chat 0.0.0-stage → 1.0.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.
package/dist/config.js ADDED
@@ -0,0 +1,567 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { parse as parseYaml, parseDocument } from "yaml";
5
+ const KINDS = ["faux", "openai", "local", "openai-codex"];
6
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
7
+ /** A slash command override for this run; the config file still decides the next run. */
8
+ export function parseThinkingLevel(raw) {
9
+ return readThinking("session", "thinking", raw.trim());
10
+ }
11
+ const KNOWN_KEYS = new Set([
12
+ "store", "provider", "model", "baseUrl", "apiKeyEnv", "contextWindow", "maxTokens",
13
+ "streamTimeoutMs", "retries", "thinkingLevel", "maxTurns", "jobMaxTurns", "autoContinue", "codemode", "providers", "mcp",
14
+ ]);
15
+ const KNOWN_MCP_KEYS = new Set(["enabled", "servers", "tools", "config"]);
16
+ const KNOWN_PROVIDER_KEYS = new Set([
17
+ "kind", "model", "baseUrl", "apiKeyEnv", "contextWindow", "maxTokens", "streamTimeoutMs", "thinkingLevel",
18
+ ]);
19
+ const PROVIDER_MAX = { contextWindow: 2_000_000, maxTokens: 200_000, streamTimeoutMs: 900_000 };
20
+ const BUILTIN = {
21
+ store: ".durable-chat/store.sqlite",
22
+ provider: "faux",
23
+ contextWindow: 128_000,
24
+ maxTokens: 8192,
25
+ streamTimeoutMs: 180_000,
26
+ streamTimeoutLocalMs: 600_000,
27
+ streamTimeoutCodexMs: 300_000,
28
+ retries: 1,
29
+ thinkingLevel: "off",
30
+ maxTurns: 60,
31
+ jobMaxTurns: 120,
32
+ autoContinue: true,
33
+ codemode: true,
34
+ };
35
+ function expandHome(value) {
36
+ if (value === "~")
37
+ return homedir();
38
+ if (value.startsWith("~/"))
39
+ return join(homedir(), value.slice(2));
40
+ return value;
41
+ }
42
+ function pathFrom(value, base = process.cwd()) {
43
+ const expanded = expandHome(value);
44
+ return isAbsolute(expanded) ? expanded : resolve(base, expanded);
45
+ }
46
+ export function defaultConfigPath(env = process.env) {
47
+ const explicit = env.DURABLE_CHAT_CONFIG;
48
+ if (explicit !== undefined && explicit.trim() !== "")
49
+ return pathFrom(explicit);
50
+ const base = env.XDG_CONFIG_HOME !== undefined && env.XDG_CONFIG_HOME.trim() !== ""
51
+ ? env.XDG_CONFIG_HOME
52
+ : join(homedir(), ".config");
53
+ // Prefer .yaml, but accept file discovery of .yml in loadConfigFile.
54
+ return join(pathFrom(base), "durable-chat", "config.yaml");
55
+ }
56
+ function configCandidates(env) {
57
+ const explicit = env.DURABLE_CHAT_CONFIG;
58
+ if (explicit !== undefined && explicit.trim() !== "") {
59
+ return { candidates: [pathFrom(explicit)], explicit: true };
60
+ }
61
+ const preferred = defaultConfigPath(env);
62
+ return { candidates: [preferred, preferred.replace(/\.yaml$/, ".yml")], explicit: false };
63
+ }
64
+ /** Only the launch folder is inspected; parent folders do not contribute config. */
65
+ export function localConfigPath() {
66
+ const preferred = resolve(".durable-chat/config.yaml");
67
+ const alternate = preferred.replace(/\.yaml$/, ".yml");
68
+ return existsSync(preferred) ? preferred : existsSync(alternate) ? alternate : preferred;
69
+ }
70
+ /** Select an edit target without parsing, so invalid configs can still be repaired. */
71
+ export function configEditPath(explicitPath, env = process.env) {
72
+ if (explicitPath !== undefined)
73
+ return pathFrom(explicitPath);
74
+ const { candidates, explicit } = configCandidates(env);
75
+ const local = localConfigPath();
76
+ if (!explicit && existsSync(local))
77
+ return local;
78
+ return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
79
+ }
80
+ class ConfigError extends Error {
81
+ constructor(path, key, problem) {
82
+ super(`${path}: ${key} ${problem}`);
83
+ }
84
+ }
85
+ function readString(path, key, value) {
86
+ if (typeof value !== "string" || value.trim() === "")
87
+ throw new ConfigError(path, key, "must be a non-empty string");
88
+ return value.trim();
89
+ }
90
+ function readNumber(path, key, value, max) {
91
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
92
+ throw new ConfigError(path, key, "must be a positive number");
93
+ }
94
+ return Math.min(Math.trunc(value), max);
95
+ }
96
+ function readBoolean(path, key, value) {
97
+ if (typeof value !== "boolean")
98
+ throw new ConfigError(path, key, "must be true or false");
99
+ return value;
100
+ }
101
+ function readStringArray(path, key, value) {
102
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
103
+ throw new ConfigError(path, key, "must be a list of strings");
104
+ }
105
+ return value.map((item) => item.trim()).filter(Boolean);
106
+ }
107
+ function envBoolean(name, value) {
108
+ if (value === undefined || value.trim() === "")
109
+ return undefined;
110
+ const normalized = value.trim().toLowerCase();
111
+ if (["1", "true", "yes", "on"].includes(normalized))
112
+ return true;
113
+ if (["0", "false", "no", "off"].includes(normalized))
114
+ return false;
115
+ throw new Error(`environment: ${name} must be true or false`);
116
+ }
117
+ function readProvider(path, key, value, knownNames = []) {
118
+ const name = typeof value === "string" ? value.trim() : "";
119
+ // A configured entry name is as good a provider value as a provider kind.
120
+ if (knownNames.includes(name))
121
+ return name;
122
+ if (!KINDS.includes(name))
123
+ throw new ConfigError(path, key, `must be ${KINDS.map((kind) => `"${kind}"`).join(", ")}${knownNames.length === 0 ? "" : ` or a configured provider name (${knownNames.join(", ")})`}`);
124
+ return name;
125
+ }
126
+ function readThinking(path, key, value) {
127
+ if (typeof value === "string" && THINKING_LEVELS.includes(value)) {
128
+ return value;
129
+ }
130
+ throw new ConfigError(path, key, `must be one of ${THINKING_LEVELS.join(", ")}`);
131
+ }
132
+ function validate(path, raw, warnings) {
133
+ if (raw === null || raw === undefined)
134
+ return {};
135
+ if (typeof raw !== "object" || Array.isArray(raw))
136
+ throw new ConfigError(path, "root", "must be a mapping");
137
+ const record = raw;
138
+ for (const key of Object.keys(record)) {
139
+ if (!KNOWN_KEYS.has(key))
140
+ warnings.push(`${path}: unknown key "${key}" ignored`);
141
+ }
142
+ const config = {};
143
+ if (record.store !== undefined)
144
+ config.store = readString(path, "store", record.store);
145
+ if (record.provider !== undefined)
146
+ config.provider = readProvider(path, "provider", record.provider, Object.keys(record.providers !== undefined && typeof record.providers === "object" && !Array.isArray(record.providers) ? record.providers : {}));
147
+ if (record.model !== undefined)
148
+ config.model = readString(path, "model", record.model);
149
+ if (record.baseUrl !== undefined)
150
+ config.baseUrl = readString(path, "baseUrl", record.baseUrl);
151
+ if (record.apiKeyEnv !== undefined)
152
+ config.apiKeyEnv = readString(path, "apiKeyEnv", record.apiKeyEnv);
153
+ if (record.contextWindow !== undefined)
154
+ config.contextWindow = readNumber(path, "contextWindow", record.contextWindow, 2_000_000);
155
+ if (record.maxTokens !== undefined)
156
+ config.maxTokens = readNumber(path, "maxTokens", record.maxTokens, 200_000);
157
+ if (record.streamTimeoutMs !== undefined)
158
+ config.streamTimeoutMs = readNumber(path, "streamTimeoutMs", record.streamTimeoutMs, 900_000);
159
+ if (record.retries !== undefined)
160
+ config.retries = readNumber(path, "retries", record.retries, 5);
161
+ if (record.thinkingLevel !== undefined)
162
+ config.thinkingLevel = readThinking(path, "thinkingLevel", record.thinkingLevel);
163
+ if (record.maxTurns !== undefined)
164
+ config.maxTurns = readNumber(path, "maxTurns", record.maxTurns, 1000);
165
+ if (record.jobMaxTurns !== undefined)
166
+ config.jobMaxTurns = readNumber(path, "jobMaxTurns", record.jobMaxTurns, 1000);
167
+ if (record.autoContinue !== undefined)
168
+ config.autoContinue = readBoolean(path, "autoContinue", record.autoContinue);
169
+ if (record.codemode !== undefined)
170
+ config.codemode = readBoolean(path, "codemode", record.codemode);
171
+ if (record.providers !== undefined) {
172
+ if (typeof record.providers !== "object" || record.providers === null || Array.isArray(record.providers)) {
173
+ throw new ConfigError(path, "providers", "must be a mapping of provider names to settings");
174
+ }
175
+ const providers = {};
176
+ for (const [name, value] of Object.entries(record.providers)) {
177
+ if (!/^[A-Za-z0-9._-]+$/.test(name))
178
+ throw new ConfigError(path, "providers", `name "${name}" must be a simple id`);
179
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
180
+ throw new ConfigError(path, `providers.${name}`, "must be a mapping");
181
+ }
182
+ const entry = {};
183
+ for (const key of Object.keys(value)) {
184
+ const at = `providers.${name}.${key}`;
185
+ if (!KNOWN_PROVIDER_KEYS.has(key))
186
+ warnings.push(`${path}: unknown key "${at}" ignored`);
187
+ else if (key === "kind")
188
+ entry[key] = readProvider(path, at, value[key]);
189
+ else if (key === "thinkingLevel")
190
+ entry.thinkingLevel = readThinking(path, at, value[key]);
191
+ else if (key === "contextWindow" || key === "maxTokens" || key === "streamTimeoutMs")
192
+ entry[key] = readNumber(path, at, value[key], PROVIDER_MAX[key]);
193
+ else
194
+ entry[key] = readString(path, at, value[key]);
195
+ }
196
+ providers[name] = entry;
197
+ }
198
+ config.providers = providers;
199
+ }
200
+ if (record.mcp !== undefined) {
201
+ if (typeof record.mcp !== "object" || record.mcp === null || Array.isArray(record.mcp)) {
202
+ throw new ConfigError(path, "mcp", "must be a mapping");
203
+ }
204
+ const mcp = record.mcp;
205
+ for (const key of Object.keys(mcp)) {
206
+ if (!KNOWN_MCP_KEYS.has(key))
207
+ warnings.push(`${path}: unknown key "mcp.${key}" ignored`);
208
+ }
209
+ config.mcp = {};
210
+ if (mcp.enabled !== undefined)
211
+ config.mcp.enabled = readBoolean(path, "mcp.enabled", mcp.enabled);
212
+ if (mcp.servers !== undefined)
213
+ config.mcp.servers = readStringArray(path, "mcp.servers", mcp.servers);
214
+ if (mcp.tools !== undefined)
215
+ config.mcp.tools = readStringArray(path, "mcp.tools", mcp.tools);
216
+ if (mcp.config !== undefined)
217
+ config.mcp.config = readString(path, "mcp.config", mcp.config);
218
+ }
219
+ return config;
220
+ }
221
+ function loadConfigFile(env, warnings, explicitPath) {
222
+ const { candidates, explicit } = explicitPath === undefined
223
+ ? configCandidates(env)
224
+ : { candidates: [pathFrom(explicitPath)], explicit: true };
225
+ const found = candidates.find((candidate) => existsSync(candidate));
226
+ if (found === undefined) {
227
+ if (explicit)
228
+ throw new Error(`Config file not found: ${candidates[0]}`);
229
+ return { path: candidates[0], found: false, config: {} };
230
+ }
231
+ let parsed;
232
+ try {
233
+ parsed = parseYaml(readFileSync(found, "utf8"));
234
+ }
235
+ catch (error) {
236
+ throw new Error(`${found}: ${error instanceof Error ? error.message : String(error)}`);
237
+ }
238
+ return { path: found, found: true, config: validate(found, parsed, warnings) };
239
+ }
240
+ /** CLI > environment > folder-local config > global config > built-ins. Explicit files stand alone. */
241
+ export function resolveConfig(overrides = {}, env = process.env) {
242
+ const warnings = [];
243
+ const file = loadConfigFile(env, warnings, overrides.configPath);
244
+ const explicit = overrides.configPath !== undefined || configCandidates(env).explicit;
245
+ const localPath = localConfigPath();
246
+ const local = !explicit && existsSync(localPath) ? loadConfigFile(env, warnings, localPath) : undefined;
247
+ const activeFile = local ?? file;
248
+ const raw = {
249
+ ...file.config,
250
+ ...local?.config,
251
+ ...(file.config.mcp === undefined && local?.config.mcp === undefined
252
+ ? {}
253
+ : { mcp: { ...file.config.mcp, ...local?.config.mcp } }),
254
+ };
255
+ const envBaseUrl = env.DURABLE_BASE_URL !== undefined && env.DURABLE_BASE_URL.trim() !== "" ? env.DURABLE_BASE_URL.trim() : undefined;
256
+ const envText = (name) => env[name] !== undefined && env[name].trim() !== "" ? env[name].trim() : undefined;
257
+ const envNumber = (name, max) => {
258
+ const value = env[name];
259
+ return value !== undefined && value.trim() !== "" ? readNumber("environment", name, Number(value), max) : undefined;
260
+ };
261
+ const envThinking = envText("DURABLE_THINKING_LEVEL") === undefined ? undefined : readThinking("environment", "DURABLE_THINKING_LEVEL", envText("DURABLE_THINKING_LEVEL"));
262
+ // A `provider` value names a configured entry when it matches one, and is a kind otherwise.
263
+ const configured = raw.providers ?? {};
264
+ let flatKind;
265
+ let activeName;
266
+ const sources = [["--provider", overrides.provider], ["environment", env.DURABLE_PROVIDER], ["config file", raw.provider]];
267
+ for (const [source, value] of sources) {
268
+ if (typeof value !== "string" || value.trim() === "")
269
+ continue;
270
+ const trimmed = value.trim();
271
+ if (Object.hasOwn(configured, trimmed))
272
+ activeName ??= trimmed;
273
+ else
274
+ flatKind ??= readProvider(source, "provider", trimmed, Object.keys(configured));
275
+ }
276
+ flatKind ??= raw.baseUrl !== undefined || envBaseUrl !== undefined ? "local" : BUILTIN.provider;
277
+ const entryFor = (name, rawEntry) => {
278
+ // An entry keeps its own kind; its name or its endpoint can imply one; otherwise the flat kind applies.
279
+ const kind = rawEntry.kind
280
+ ?? (KINDS.includes(name) ? name : rawEntry.baseUrl !== undefined ? "local" : flatKind);
281
+ const isActive = name === (activeName ?? flatKind);
282
+ const model = (isActive ? overrides.model ?? envText("DURABLE_MODEL_ID") ?? envText("PI_MODEL_ID") : undefined)
283
+ ?? rawEntry.model ?? raw.model ?? (kind === "openai-codex" ? "gpt-6.1-sol" : undefined);
284
+ const baseUrl = envBaseUrl ?? rawEntry.baseUrl ?? raw.baseUrl;
285
+ const apiKeyEnv = env.DURABLE_API_KEY_ENV ?? rawEntry.apiKeyEnv ?? raw.apiKeyEnv;
286
+ const apiKey = (isActive ? env.DURABLE_API_KEY : undefined) ?? (apiKeyEnv === undefined ? undefined : env[apiKeyEnv]);
287
+ const contextWindow = envNumber("DURABLE_CONTEXT_WINDOW", 2_000_000) ?? rawEntry.contextWindow ?? raw.contextWindow ?? BUILTIN.contextWindow;
288
+ const maxTokens = envNumber("DURABLE_MAX_TOKENS", 200_000) ?? rawEntry.maxTokens ?? raw.maxTokens ?? BUILTIN.maxTokens;
289
+ const streamTimeoutMs = envNumber("DURABLE_STREAM_TIMEOUT_MS", 900_000) ?? rawEntry.streamTimeoutMs ?? raw.streamTimeoutMs
290
+ ?? (kind === "local" ? BUILTIN.streamTimeoutLocalMs : kind === "openai-codex" ? BUILTIN.streamTimeoutCodexMs : BUILTIN.streamTimeoutMs);
291
+ const thinkingLevel = envThinking ?? rawEntry.thinkingLevel ?? raw.thinkingLevel ?? (kind === "openai-codex" ? "medium" : BUILTIN.thinkingLevel);
292
+ if (kind === "local" && (baseUrl === undefined || model === undefined || model === "")) {
293
+ throw new Error(`provider "${name}": the local provider needs baseUrl and model (${activeFile.path}).`);
294
+ }
295
+ if ((kind === "openai" || kind === "openai-codex") && (model === undefined || model === "")) {
296
+ throw new Error(`provider "${name}": the ${kind} provider needs a model (${activeFile.path}).`);
297
+ }
298
+ return {
299
+ name, kind,
300
+ ...(model === undefined ? {} : { model }),
301
+ ...(baseUrl === undefined ? {} : { baseUrl }),
302
+ ...(apiKey === undefined ? {} : { apiKey }),
303
+ ...(apiKeyEnv === undefined ? {} : { apiKeyEnv }),
304
+ contextWindow, maxTokens, streamTimeoutMs, thinkingLevel,
305
+ };
306
+ };
307
+ // Only configured entries are listed; a provider value with no entry stays a plain kind.
308
+ const entries = Object.entries(configured).map(([name, entry]) => entryFor(name, entry));
309
+ const active = entries.find((entry) => entry.name === (activeName ?? flatKind)) ?? entryFor(activeName ?? flatKind, {});
310
+ if (!entries.includes(active))
311
+ entries.unshift(active);
312
+ const retries = envNumber("DURABLE_RETRIES", 5) ?? raw.retries ?? BUILTIN.retries;
313
+ const maxTurns = envNumber("DURABLE_MAX_TURNS", 1000) ?? raw.maxTurns ?? BUILTIN.maxTurns;
314
+ const jobMaxTurns = envNumber("DURABLE_JOB_MAX_TURNS", 1000) ?? raw.jobMaxTurns ?? BUILTIN.jobMaxTurns;
315
+ const autoContinue = envBoolean("DURABLE_AUTO_CONTINUE", env.DURABLE_AUTO_CONTINUE) ?? raw.autoContinue ?? BUILTIN.autoContinue;
316
+ const codemode = envBoolean("DURABLE_CODEMODE", env.DURABLE_CODEMODE) ?? raw.codemode ?? BUILTIN.codemode;
317
+ const storeRaw = overrides.store
318
+ ?? (env.DURABLE_STORE !== undefined && env.DURABLE_STORE.trim() !== "" ? env.DURABLE_STORE.trim() : undefined)
319
+ ?? raw.store
320
+ ?? BUILTIN.store;
321
+ const envMcpEnabled = envBoolean("DURABLE_MCP_ENABLED", env.DURABLE_MCP_ENABLED);
322
+ const mcpEnabled = overrides.noMcp === true ? false : envMcpEnabled ?? raw.mcp?.enabled ?? true;
323
+ const envServers = env.DURABLE_MCP_SERVERS !== undefined && env.DURABLE_MCP_SERVERS.trim() !== ""
324
+ ? env.DURABLE_MCP_SERVERS.split(",").map((name) => name.trim()).filter(Boolean)
325
+ : undefined;
326
+ const envTools = env.DURABLE_MCP_TOOLS !== undefined && env.DURABLE_MCP_TOOLS.trim() !== ""
327
+ ? env.DURABLE_MCP_TOOLS.split(",").map((name) => name.trim()).filter(Boolean)
328
+ : undefined;
329
+ const mcpConfigRaw = (env.DURABLE_MCP_CONFIG !== undefined && env.DURABLE_MCP_CONFIG.trim() !== "" ? env.DURABLE_MCP_CONFIG.trim() : undefined)
330
+ ?? raw.mcp?.config;
331
+ return {
332
+ configPath: activeFile.path,
333
+ configFound: activeFile.found,
334
+ configPaths: [file, ...(local === undefined ? [] : [local])].filter((source) => source.found).map((source) => source.path),
335
+ ...(explicit ? { explicitConfigPath: file.path } : {}),
336
+ warnings,
337
+ storePath: pathFrom(storeRaw),
338
+ provider: active.name,
339
+ providers: entries,
340
+ active,
341
+ ...(active.model === undefined ? {} : { model: active.model }),
342
+ ...(active.baseUrl === undefined ? {} : { baseUrl: active.baseUrl }),
343
+ ...(active.apiKey === undefined ? {} : { apiKey: active.apiKey }),
344
+ ...(active.apiKeyEnv === undefined ? {} : { apiKeyEnv: active.apiKeyEnv }),
345
+ contextWindow: active.contextWindow,
346
+ maxTokens: active.maxTokens,
347
+ streamTimeoutMs: active.streamTimeoutMs,
348
+ retries,
349
+ thinkingLevel: active.thinkingLevel,
350
+ maxTurns,
351
+ jobMaxTurns,
352
+ autoContinue,
353
+ codemode,
354
+ mcp: {
355
+ enabled: mcpEnabled,
356
+ servers: envServers ?? raw.mcp?.servers ?? ["substrate"],
357
+ tools: envTools ?? raw.mcp?.tools ?? [],
358
+ ...(mcpConfigRaw === undefined ? {} : { configPath: pathFrom(mcpConfigRaw) }),
359
+ },
360
+ };
361
+ }
362
+ /** The config written by `durable-chat config init`; local inference is the default. */
363
+ export function configTemplate() {
364
+ return `# durable-chat defaults. CLI flags override environment variables, which override this file.
365
+ provider: local
366
+ model: nemotron-bolt
367
+ baseUrl: http://dev.local:1234/v1
368
+ contextWindow: 262144
369
+ maxTokens: 32768
370
+ # A cold local model start can take minutes.
371
+ streamTimeoutMs: 600000
372
+ retries: 1
373
+ thinkingLevel: "off"
374
+ maxTurns: 60
375
+ jobMaxTurns: 120
376
+ autoContinue: true
377
+ # QuickJS scripts that call the conversation's tools; only the script's output comes back.
378
+ codemode: true
379
+ # More than one provider can be configured. The provider key selects the active entry by name, and
380
+ # each entry inherits the values above for keys it does not set. Entry names are provider ids.
381
+ # providers:
382
+ # codex: { kind: openai-codex, model: gpt-6.1-sol }
383
+ # ollama: { model: llama3, baseUrl: http://127.0.0.1:11434/v1, contextWindow: 131072 }
384
+ store: ~/.local/share/durable-chat/store.sqlite
385
+ mcp:
386
+ enabled: true
387
+ servers:
388
+ - substrate
389
+ tools: []
390
+ config: ~/.pi/agent/mcp.json
391
+ `;
392
+ }
393
+ export function initConfigFile(path, options = {}) {
394
+ mkdirSync(dirname(path), { recursive: true });
395
+ try {
396
+ const template = options.local === true
397
+ ? "# Folder-local overrides; unspecified keys inherit global defaults.\n# For a folder-local database, set: store: .durable-chat/store.sqlite\n{}\n"
398
+ : configTemplate();
399
+ writeFileSync(path, template, { flag: options.force === true ? "w" : "wx" });
400
+ }
401
+ catch (error) {
402
+ if (error.code === "EEXIST") {
403
+ throw new Error(`${path} already exists; pass --force to overwrite it.`);
404
+ }
405
+ throw error;
406
+ }
407
+ return path;
408
+ }
409
+ /** Printable summary. Never includes secret values. */
410
+ export function describeConfig(config) {
411
+ const lines = [
412
+ `Config: ${config.configPath}${config.configFound ? "" : " (not found; using built-ins)"}`,
413
+ ...(config.configPaths.length > 1 ? [`Config layers (low → high): ${config.configPaths.join(" → ")}`] : []),
414
+ `provider: ${config.provider}`,
415
+ ...(config.providers.length > 1
416
+ ? [`providers: ${config.providers.map((entry) => `${entry.name}${entry.name === config.provider ? " (active)" : ""}`).join(", ")}`]
417
+ : []),
418
+ `model: ${config.model ?? "(provider default)"}`,
419
+ `baseUrl: ${config.baseUrl ?? "(provider default)"}`,
420
+ `store: ${config.storePath}`,
421
+ `contextWindow: ${config.contextWindow}`,
422
+ `maxTokens: ${config.maxTokens}`,
423
+ `streamTimeoutMs: ${config.streamTimeoutMs}`,
424
+ `retries: ${config.retries}`,
425
+ `thinkingLevel: ${config.thinkingLevel}`,
426
+ `maxTurns: ${config.maxTurns}`,
427
+ `jobMaxTurns: ${config.jobMaxTurns}`,
428
+ `autoContinue: ${config.autoContinue}`,
429
+ `codemode: ${config.codemode ? "enabled" : "disabled"}`,
430
+ `apiKey: ${config.apiKey === undefined ? "(none)" : config.apiKeyEnv === undefined ? "(set)" : `from ${config.apiKeyEnv}`}`,
431
+ `mcp: ${config.mcp.enabled ? "enabled" : "disabled"}, servers: ${config.mcp.servers.join(", ") || "(none)"}`,
432
+ ...(config.mcp.tools.length === 0 ? [] : [`mcp extra tools: ${config.mcp.tools.join(", ")}`]),
433
+ `mcp config: ${config.mcp.configPath ?? "(default)"}`,
434
+ ...config.warnings.map((warning) => `warning: ${warning}`),
435
+ ];
436
+ return lines;
437
+ }
438
+ const KEY_PATHS = {
439
+ store: ["store"],
440
+ provider: ["provider"],
441
+ model: ["model"],
442
+ baseUrl: ["baseUrl"],
443
+ apiKeyEnv: ["apiKeyEnv"],
444
+ contextWindow: ["contextWindow"],
445
+ maxTokens: ["maxTokens"],
446
+ streamTimeoutMs: ["streamTimeoutMs"],
447
+ retries: ["retries"],
448
+ thinkingLevel: ["thinkingLevel"],
449
+ maxTurns: ["maxTurns"],
450
+ jobMaxTurns: ["jobMaxTurns"],
451
+ autoContinue: ["autoContinue"],
452
+ codemode: ["codemode"],
453
+ providers: ["providers"],
454
+ "mcp.enabled": ["mcp", "enabled"],
455
+ "mcp.servers": ["mcp", "servers"],
456
+ "mcp.tools": ["mcp", "tools"],
457
+ "mcp.config": ["mcp", "config"],
458
+ };
459
+ export function configKeys() {
460
+ return Object.keys(KEY_PATHS);
461
+ }
462
+ export function configKeyPath(key) {
463
+ const path = KEY_PATHS[key];
464
+ if (path !== undefined)
465
+ return path;
466
+ // Accept a nested `mcp` key write only through its subkeys.
467
+ if (key === "mcp")
468
+ return undefined;
469
+ // One provider entry is written through its subkeys, as in `providers.codex.model`.
470
+ const parts = key.split(".");
471
+ if (parts.length === 3 && parts[0] === "providers" && KNOWN_PROVIDER_KEYS.has(parts[2]))
472
+ return parts;
473
+ return undefined;
474
+ }
475
+ function loadDocument(path) {
476
+ if (!existsSync(path))
477
+ return parseDocument("");
478
+ const doc = parseDocument(readFileSync(path, "utf8"));
479
+ if (doc.errors.length > 0) {
480
+ throw new Error(`${path}: ${doc.errors[0]?.message ?? "invalid YAML"}`);
481
+ }
482
+ return doc;
483
+ }
484
+ function setAt(target, keyPath, value) {
485
+ let cursor = target;
486
+ for (const part of keyPath.slice(0, -1)) {
487
+ const next = cursor[part];
488
+ if (typeof next !== "object" || next === null || Array.isArray(next))
489
+ cursor[part] = {};
490
+ cursor = cursor[part];
491
+ }
492
+ cursor[keyPath[keyPath.length - 1]] = value;
493
+ }
494
+ function parseCliValue(raw) {
495
+ const text = raw.trim();
496
+ if (text === "")
497
+ throw new Error("A value is required.");
498
+ try {
499
+ const parsed = parseYaml(text);
500
+ // A bare word stays a string; YAML null only when the user typed null/tilde.
501
+ if (parsed === null || parsed === undefined)
502
+ return text;
503
+ return parsed;
504
+ }
505
+ catch {
506
+ return text;
507
+ }
508
+ }
509
+ export function setConfigValue(path, key, rawValue) {
510
+ const keyPath = configKeyPath(key);
511
+ if (keyPath === undefined) {
512
+ throw new Error(`Unknown config key "${key}". Known keys: ${configKeys().join(", ")}`);
513
+ }
514
+ const doc = loadDocument(path);
515
+ const value = parseCliValue(rawValue);
516
+ const candidate = (doc.toJS() ?? {});
517
+ setAt(candidate, keyPath, value);
518
+ // Type-check the whole file before writing, so a typo never lands.
519
+ validate(path, candidate, []);
520
+ doc.setIn(keyPath, value);
521
+ mkdirSync(dirname(path), { recursive: true });
522
+ writeFileSync(path, doc.toString(), "utf8");
523
+ return { key, value };
524
+ }
525
+ export function unsetConfigValue(path, key) {
526
+ const keyPath = configKeyPath(key);
527
+ if (keyPath === undefined) {
528
+ throw new Error(`Unknown config key "${key}". Known keys: ${configKeys().join(", ")}`);
529
+ }
530
+ if (!existsSync(path))
531
+ return false;
532
+ const doc = loadDocument(path);
533
+ const before = JSON.stringify(doc.toJS() ?? {});
534
+ doc.deleteIn(keyPath);
535
+ const after = JSON.stringify(doc.toJS() ?? {});
536
+ if (before === after)
537
+ return false;
538
+ writeFileSync(path, doc.toString(), "utf8");
539
+ return true;
540
+ }
541
+ /** Effective value for `config get`; secrets are reported as present, never printed. */
542
+ export function effectiveValue(config, key) {
543
+ switch (key) {
544
+ case "store": return config.storePath;
545
+ case "provider": return config.provider;
546
+ case "providers": return config.providers.map((entry) => `${entry.name}${entry.name === config.provider ? " (active)" : ""}`).join(", ");
547
+ case "model": return config.model ?? "(provider default)";
548
+ case "baseUrl": return config.baseUrl ?? "(provider default)";
549
+ case "apiKey": return config.apiKey === undefined ? "(none)" : config.apiKeyEnv === undefined ? "(set)" : `(set from ${config.apiKeyEnv})`;
550
+ case "apiKeyEnv": return config.apiKeyEnv ?? "(none)";
551
+ case "contextWindow": return String(config.contextWindow);
552
+ case "maxTokens": return String(config.maxTokens);
553
+ case "streamTimeoutMs": return String(config.streamTimeoutMs);
554
+ case "retries": return String(config.retries);
555
+ case "thinkingLevel": return config.thinkingLevel;
556
+ case "maxTurns": return String(config.maxTurns);
557
+ case "jobMaxTurns": return String(config.jobMaxTurns);
558
+ case "autoContinue": return String(config.autoContinue);
559
+ case "codemode": return String(config.codemode);
560
+ case "mcp.enabled": return String(config.mcp.enabled);
561
+ case "mcp.servers": return config.mcp.servers.join(", ") || "(none)";
562
+ case "mcp.tools": return config.mcp.tools.join(", ") || "(none)";
563
+ case "mcp.config": return config.mcp.configPath ?? "(default)";
564
+ default:
565
+ throw new Error(`Unknown config key "${key}". Known keys: ${configKeys().join(", ")}`);
566
+ }
567
+ }
@@ -0,0 +1,48 @@
1
+ import { DEFAULT_COMPACTION_POLICY } from "@earendil-works/pi-durable";
2
+ import { calculateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
3
+ /**
4
+ * The same active-request estimate Pi Durable uses for automatic compaction:
5
+ * the newest assistant's recorded context usage after the head marker, plus
6
+ * estimates for the messages that followed it.
7
+ */
8
+ export function estimateContextTokens(view) {
9
+ let measured;
10
+ let measuredMessage;
11
+ const after = Number(view.head?.id ?? Number.NEGATIVE_INFINITY);
12
+ for (let index = view.entries.length - 1; index >= 0 && measured === undefined; index--) {
13
+ const entry = view.entries[index];
14
+ if (Number(entry.id) <= after)
15
+ continue;
16
+ const assistant = view.contributions[index]?.flatMap((message) => {
17
+ if (message.role !== "assistant")
18
+ return [];
19
+ const tokens = calculateContextTokens(message.usage);
20
+ return tokens > 0 ? [{ message, tokens }] : [];
21
+ }).at(-1);
22
+ if (assistant !== undefined) {
23
+ measured = assistant.tokens;
24
+ measuredMessage = assistant.message;
25
+ }
26
+ }
27
+ const from = measuredMessage === undefined ? 0 : view.messages.indexOf(measuredMessage) + 1;
28
+ let tokens = measured ?? 0;
29
+ for (const message of view.messages.slice(from))
30
+ tokens += estimateMessageTokens(message);
31
+ return tokens;
32
+ }
33
+ /** Default automatic-compaction blocking threshold for a model window. */
34
+ export function compactionLimit(contextWindow) {
35
+ return Math.max(0, contextWindow - DEFAULT_COMPACTION_POLICY.reserveTokens);
36
+ }
37
+ export function contextPercent(tokens, contextWindow) {
38
+ return contextWindow <= 0 ? 0 : Math.min(100, Math.max(0, (tokens / contextWindow) * 100));
39
+ }
40
+ export function formatTokenCount(tokens) {
41
+ if (!Number.isFinite(tokens) || tokens <= 0)
42
+ return "0";
43
+ if (tokens < 1000)
44
+ return String(Math.round(tokens));
45
+ if (tokens < 100_000)
46
+ return `${(tokens / 1000).toFixed(1)}k`;
47
+ return `${Math.round(tokens / 1000)}k`;
48
+ }
@@ -0,0 +1,52 @@
1
+ import childProcess from "node:child_process";
2
+ const FOCUS_GHOSTTY = `function run(argv) {
3
+ const ownerPID = Number(argv[0]);
4
+ const ownerTTY = argv[1];
5
+ const app = Application("com.mitchellh.ghostty");
6
+ if (!app.running()) return "not-found";
7
+ const terminals = app.terminals();
8
+ for (const candidate of terminals) {
9
+ let matchesOwner = false;
10
+ try { matchesOwner = candidate.pid() === ownerPID; } catch (_) {}
11
+ if (!matchesOwner && ownerTTY) {
12
+ try { matchesOwner = candidate.tty() === ownerTTY; } catch (_) {}
13
+ }
14
+ if (matchesOwner) {
15
+ candidate.focus();
16
+ return "focused";
17
+ }
18
+ }
19
+ return "not-found";
20
+ }`;
21
+ function capture(command, args, timeout) {
22
+ return new Promise((resolve, reject) => {
23
+ childProcess.execFile(command, args, { encoding: "utf8", timeout, maxBuffer: 64 * 1024 }, (error, stdout) => {
24
+ if (error)
25
+ reject(error);
26
+ else
27
+ resolve(stdout);
28
+ });
29
+ });
30
+ }
31
+ /** Best-effort handoff of an interactive local launch to the Ghostty terminal owning its store. */
32
+ export async function focusExistingSession(pid, options = {}) {
33
+ const env = options.env ?? process.env;
34
+ const platform = options.platform ?? process.platform;
35
+ const isTTY = options.isTTY ?? (process.stdin.isTTY === true && process.stdout.isTTY === true);
36
+ if (!isTTY || platform !== "darwin" || !Number.isSafeInteger(pid) || pid <= 0
37
+ || (options.command !== undefined && options.command !== "tui" && options.command !== "chat")
38
+ || env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY)
39
+ return false;
40
+ if (env.TERM_PROGRAM?.toLowerCase() !== "ghostty" && !env.TERM?.toLowerCase().includes("ghostty") && !env.GHOSTTY_RESOURCES_DIR)
41
+ return false;
42
+ try {
43
+ const tty = (await capture("/bin/ps", ["-p", String(pid), "-o", "tty="], 1000)).trim();
44
+ const device = tty === "" || tty === "?" || tty === "??" ? "" : tty.startsWith("/dev/") ? tty : `/dev/${tty}`;
45
+ // Pass metadata as arguments: neither PID nor terminal identity becomes script source.
46
+ return (await capture("/usr/bin/osascript", ["-l", "JavaScript", "-e", FOCUS_GHOSTTY, String(pid), device], 3000)).trim() === "focused";
47
+ }
48
+ catch {
49
+ // Missing APIs, denied Automation permission and timeouts preserve the original lock error.
50
+ return false;
51
+ }
52
+ }