@yukino.js/yukino 0.0.5 → 0.0.7

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 (54) hide show
  1. package/README.md +35 -30
  2. package/dist/{acp-LOU6R4C7.js → acp-76S2XII3.js} +1 -1
  3. package/dist/anthropic-WK6EYMUE.js +4 -0
  4. package/dist/chunk-3OULXPVI.js +5 -0
  5. package/dist/chunk-7PPWFSIC.js +4 -0
  6. package/dist/chunk-7ZBAF7M4.js +4 -0
  7. package/dist/{chunk-BPA7URET.js → chunk-HWDSXNX4.js} +2 -2
  8. package/dist/{chunk-GYBJR2RB.js → chunk-IW5L5276.js} +2 -2
  9. package/dist/chunk-NG62ISUV.js +61 -0
  10. package/dist/chunk-P6DHMU7R.js +4 -0
  11. package/dist/{chunk-YVLW4WBA.js → chunk-QQZCYWYI.js} +20 -20
  12. package/dist/chunk-QRO6H32L.js +1031 -0
  13. package/dist/lib/{anthropic-UC7XIWCM.js → anthropic-CDPTNR5L.js} +2 -6
  14. package/dist/lib/{chunk-DXUJGZ5F.js → chunk-6NYUYSER.js} +3 -3
  15. package/dist/lib/{chunk-GAWWN3TY.js → chunk-EO23VPDZ.js} +416 -39
  16. package/dist/lib/chunk-HE4RUUZP.js +1342 -0
  17. package/dist/lib/{chunk-64Z3SMSG.js → chunk-PEV5NGQ2.js} +84 -44
  18. package/dist/lib/{chunk-WDO5MWH2.js → chunk-TKCJSTWI.js} +1 -1
  19. package/dist/lib/index.d.ts +113 -119
  20. package/dist/lib/index.js +6305 -1810
  21. package/dist/lib/{openai-OL5HXQUU.js → openai-TEFKPV7T.js} +2 -4
  22. package/dist/lib/{providers-N35WJDJM.js → providers-2X5JB2JX.js} +1 -1
  23. package/dist/lib/{seatbelt-G5Z5QEDD.js → seatbelt-VE3I3EGH.js} +1 -1
  24. package/dist/main.js +198 -198
  25. package/dist/{openai-NIBMRDVB.js → openai-RYXW7AKZ.js} +15 -15
  26. package/dist/{providers-TG3LGHNS.js → providers-YG2HYIG6.js} +1 -1
  27. package/dist/{seatbelt-IOLIYZZX.js → seatbelt-3YN3GMQO.js} +1 -1
  28. package/dist/server-66HLMSUR.js +4 -0
  29. package/package.json +8 -24
  30. package/dist/agent-5NW5ZV5P.js +0 -4
  31. package/dist/anthropic-UXFSBFXM.js +0 -4
  32. package/dist/chunk-2HUCPWD6.js +0 -29
  33. package/dist/chunk-3EQYWNP6.js +0 -4
  34. package/dist/chunk-3SPUH3TD.js +0 -164
  35. package/dist/chunk-5HF4GLFR.js +0 -865
  36. package/dist/chunk-HBXZ6MB4.js +0 -4
  37. package/dist/chunk-MQAQBW7F.js +0 -35
  38. package/dist/chunk-OFC2GD5K.js +0 -4
  39. package/dist/chunk-SDXAS44V.js +0 -4
  40. package/dist/chunk-TJVN4NL5.js +0 -5
  41. package/dist/chunk-VM26JJ6N.js +0 -4
  42. package/dist/chunk-WNHTKUKK.js +0 -4
  43. package/dist/chunk-ZPYQCXWT.js +0 -5
  44. package/dist/lib/agent-UGEA6EVB.js +0 -16
  45. package/dist/lib/chunk-65EUCQOF.js +0 -259
  46. package/dist/lib/chunk-F2YJG72O.js +0 -150
  47. package/dist/lib/chunk-NIJXTKNM.js +0 -3628
  48. package/dist/lib/chunk-OCTB6YMC.js +0 -625
  49. package/dist/lib/chunk-R3NJ2EET.js +0 -540
  50. package/dist/lib/chunk-UKINFW65.js +0 -652
  51. package/dist/lib/chunk-V2EYBIAU.js +0 -323
  52. package/dist/lib/permissions-EAKP6IZ3.js +0 -23
  53. package/dist/permissions-5EQWZS7O.js +0 -4
  54. package/dist/server-7ENYPCYC.js +0 -4
@@ -0,0 +1,1342 @@
1
+ import {
2
+ __export
3
+ } from "./chunk-MLKGABMK.js";
4
+
5
+ // src/logger/index.ts
6
+ var logger_exports = {};
7
+ __export(logger_exports, {
8
+ closeLogger: () => closeLogger,
9
+ createChildLogger: () => createChildLogger,
10
+ initLogger: () => initLogger,
11
+ logger: () => logger,
12
+ sanitizeNameSegment: () => sanitizeNameSegment
13
+ });
14
+ import { openSync, closeSync, mkdirSync, writeFileSync } from "fs";
15
+ import { readdir, stat, unlink } from "fs/promises";
16
+ import { homedir } from "os";
17
+ import { join, dirname, basename } from "path";
18
+ import pino from "pino";
19
+ var currentLogger = null;
20
+ var currentDest = null;
21
+ var currentFd = null;
22
+ function resolveLogPath(opts) {
23
+ const dir = opts.logDir ?? join(opts.workDir ?? process.cwd(), ".yukino", "logs");
24
+ return join(dir, `${opts.sessionId}.jsonl`);
25
+ }
26
+ function ensureYukinoGitignore(logPath) {
27
+ let dir = dirname(logPath);
28
+ while (basename(dir) !== ".yukino") {
29
+ const parent = dirname(dir);
30
+ if (parent === dir) {
31
+ return;
32
+ }
33
+ dir = parent;
34
+ }
35
+ try {
36
+ writeFileSync(join(dir, ".gitignore"), "*\n", { flag: "wx" });
37
+ } catch {
38
+ }
39
+ }
40
+ function sanitizeNameSegment(name) {
41
+ const cleaned = name.replace(/[^a-zA-Z0-9_-]/g, "_");
42
+ return cleaned || "unnamed";
43
+ }
44
+ function flushDestination(dest) {
45
+ if (typeof dest !== "object" || dest === null) {
46
+ return;
47
+ }
48
+ const fn = Reflect.get(dest, "flushSync");
49
+ if (typeof fn === "function") {
50
+ fn.call(dest);
51
+ }
52
+ }
53
+ var LOG_LEVEL = "warn";
54
+ function initLogger(opts) {
55
+ if (currentLogger) {
56
+ closeLogger();
57
+ }
58
+ const logPath = resolveLogPath(opts);
59
+ mkdirSync(dirname(logPath), { recursive: true });
60
+ ensureYukinoGitignore(logPath);
61
+ const fd = openSync(logPath, "a");
62
+ currentFd = fd;
63
+ currentDest = pino.destination(fd);
64
+ const pinoOpts = {
65
+ level: LOG_LEVEL,
66
+ base: { sessionId: opts.sessionId, mode: opts.mode },
67
+ serializers: { err: errSerializer }
68
+ };
69
+ if (opts.stdout) {
70
+ currentLogger = pino(
71
+ pinoOpts,
72
+ pino.multistream([
73
+ { stream: currentDest, level: LOG_LEVEL },
74
+ { stream: process.stdout, level: LOG_LEVEL }
75
+ ])
76
+ );
77
+ } else {
78
+ currentLogger = pino(pinoOpts, currentDest);
79
+ }
80
+ if (!opts.skipCleanup) {
81
+ const workDir = opts.workDir ?? process.cwd();
82
+ void cleanExpiredLogs(workDir).catch(() => {
83
+ });
84
+ }
85
+ return currentLogger;
86
+ }
87
+ function getLogger() {
88
+ return currentLogger;
89
+ }
90
+ function closeLogger() {
91
+ if (currentLogger) {
92
+ try {
93
+ currentLogger.flush();
94
+ } catch {
95
+ }
96
+ currentLogger = null;
97
+ }
98
+ if (currentDest) {
99
+ flushDestination(currentDest);
100
+ currentDest = null;
101
+ }
102
+ if (currentFd !== null) {
103
+ try {
104
+ closeSync(currentFd);
105
+ } catch {
106
+ }
107
+ currentFd = null;
108
+ }
109
+ }
110
+ var silentFallback = pino({ level: "silent" });
111
+ var logger = new Proxy(silentFallback, {
112
+ get(_target, prop, receiver) {
113
+ const current = getLogger();
114
+ const target = current ?? _target;
115
+ const value = Reflect.get(target, prop, receiver);
116
+ if (typeof value === "function") {
117
+ const bound = value.bind(target);
118
+ return bound;
119
+ }
120
+ return value;
121
+ },
122
+ set(_target, prop, value) {
123
+ return Reflect.set(getLogger() ?? _target, prop, value);
124
+ }
125
+ });
126
+ function createChildLogger(bindings) {
127
+ let cachedChild = null;
128
+ let cachedLogger = null;
129
+ const resolveChild = () => {
130
+ const current = getLogger();
131
+ if (!current) {
132
+ return null;
133
+ }
134
+ if (cachedChild === null || cachedLogger !== current) {
135
+ cachedChild = current.child(bindings);
136
+ cachedLogger = current;
137
+ }
138
+ return cachedChild;
139
+ };
140
+ return new Proxy(silentFallback, {
141
+ get(_target, prop, receiver) {
142
+ const target = resolveChild() ?? _target;
143
+ const value = Reflect.get(target, prop, receiver);
144
+ if (typeof value === "function") {
145
+ const bound = value.bind(target);
146
+ return bound;
147
+ }
148
+ return value;
149
+ },
150
+ set(_target, prop, value) {
151
+ return Reflect.set(resolveChild() ?? _target, prop, value);
152
+ }
153
+ });
154
+ }
155
+ async function cleanDir(dir) {
156
+ let files;
157
+ try {
158
+ files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl"));
159
+ } catch {
160
+ return 0;
161
+ }
162
+ const now = Date.now();
163
+ let removed = 0;
164
+ for (const file of files) {
165
+ const filePath = join(dir, file);
166
+ try {
167
+ const s = await stat(filePath);
168
+ if (now - s.mtimeMs > 30 * 24 * 60 * 60 * 1e3) {
169
+ await unlink(filePath);
170
+ removed++;
171
+ }
172
+ } catch {
173
+ }
174
+ }
175
+ return removed;
176
+ }
177
+ async function cleanExpiredLogs(workDir) {
178
+ let removed = 0;
179
+ removed += await cleanDir(join(workDir, ".yukino", "logs"));
180
+ const teamsDir = join(homedir(), ".yukino", "teams");
181
+ let teams;
182
+ try {
183
+ teams = await readdir(teamsDir);
184
+ } catch {
185
+ return removed;
186
+ }
187
+ for (const team of teams) {
188
+ removed += await cleanDir(join(teamsDir, team, "logs"));
189
+ }
190
+ return removed;
191
+ }
192
+ var CAUSE_MAX_DEPTH = 5;
193
+ var RESERVED_KEYS = /* @__PURE__ */ new Set(["name", "message", "stack", "cause"]);
194
+ function serializeErrorInstance(err, depth) {
195
+ const out = {
196
+ type: err.name,
197
+ message: err.message,
198
+ stack: err.stack
199
+ };
200
+ const causeDescriptor = Object.getOwnPropertyDescriptor(err, "cause");
201
+ if (causeDescriptor && depth < CAUSE_MAX_DEPTH) {
202
+ const cause = causeDescriptor.value;
203
+ if (cause instanceof Error) {
204
+ out.cause = serializeErrorInstance(cause, depth + 1);
205
+ } else if (cause !== void 0) {
206
+ out.cause = { message: safeStringify(cause) };
207
+ }
208
+ }
209
+ for (const key of Object.keys(err)) {
210
+ if (RESERVED_KEYS.has(key)) {
211
+ continue;
212
+ }
213
+ const descriptor = Object.getOwnPropertyDescriptor(err, key);
214
+ if (descriptor) {
215
+ const fieldValue = descriptor.value;
216
+ out[key] = fieldValue;
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+ function safeStringify(value) {
222
+ if (typeof value === "string") {
223
+ return value;
224
+ }
225
+ try {
226
+ const json = JSON.stringify(value);
227
+ if (json !== void 0) {
228
+ return json;
229
+ }
230
+ } catch {
231
+ }
232
+ try {
233
+ return String(value);
234
+ } catch {
235
+ return Object.prototype.toString.call(value);
236
+ }
237
+ }
238
+ function errSerializer(err) {
239
+ if (err instanceof Error) {
240
+ return serializeErrorInstance(err, 0);
241
+ }
242
+ return { message: safeStringify(err), value: err };
243
+ }
244
+
245
+ // src/utils/index.ts
246
+ var utils_exports = {};
247
+ __export(utils_exports, {
248
+ Paths: () => paths_exports,
249
+ Slug: () => slug_exports,
250
+ asError: () => asError,
251
+ asErrorString: () => asErrorString,
252
+ asRecord: () => asRecord,
253
+ asString: () => asString,
254
+ boolArg: () => boolArg,
255
+ contentToText: () => contentToText,
256
+ formatToolArgs: () => formatToolArgs,
257
+ intArg: () => intArg,
258
+ isObject: () => isObject,
259
+ isRecord: () => isRecord,
260
+ safeJSONParse: () => safeJSONParse,
261
+ strArg: () => strArg,
262
+ strList: () => strList,
263
+ toTry: () => toTry
264
+ });
265
+
266
+ // src/utils/paths.ts
267
+ var paths_exports = {};
268
+ __export(paths_exports, {
269
+ canonicalPath: () => canonicalPath,
270
+ compactPath: () => compactPath,
271
+ isPathWithin: () => isPathWithin
272
+ });
273
+ import { realpathSync } from "fs";
274
+ import { homedir as homedir2 } from "os";
275
+ import {
276
+ basename as basename2,
277
+ dirname as dirname2,
278
+ isAbsolute,
279
+ join as join2,
280
+ relative,
281
+ resolve,
282
+ sep
283
+ } from "path";
284
+ function canonicalPath(path) {
285
+ let current = resolve(path);
286
+ const missing = [];
287
+ for (; ; ) {
288
+ try {
289
+ return join2(realpathSync(current), ...missing);
290
+ } catch (error) {
291
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT" && error.code !== "ENOTDIR") {
292
+ throw error;
293
+ }
294
+ const parent = dirname2(current);
295
+ if (parent === current) {
296
+ return resolve(path);
297
+ }
298
+ missing.unshift(basename2(current));
299
+ current = parent;
300
+ }
301
+ }
302
+ }
303
+ function isPathWithin(root, path) {
304
+ const child = relative(root, path);
305
+ return child === "" || child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
306
+ }
307
+ function compactPath(path) {
308
+ const home = homedir2();
309
+ return path === home ? "~" : path.startsWith(`${home}/`) ? `~/${path.slice(home.length + 1)}` : path;
310
+ }
311
+
312
+ // src/utils/slug.ts
313
+ var slug_exports = {};
314
+ __export(slug_exports, {
315
+ generateSlug: () => generateSlug
316
+ });
317
+ import { randomBytes } from "crypto";
318
+ function generateSlug() {
319
+ const timestamp = Date.now().toString(36);
320
+ const entropy = randomBytes(6).toString("hex");
321
+ return `${timestamp}-${entropy}`;
322
+ }
323
+
324
+ // src/utils/index.ts
325
+ var log = createChildLogger({ module: "utils" });
326
+ function contentToText(content) {
327
+ if (typeof content === "string") {
328
+ return content;
329
+ }
330
+ const parts = [];
331
+ for (const block of content) {
332
+ if (block.type === "text" && typeof block.text === "string") {
333
+ parts.push(block.text);
334
+ } else if (block.type === "image" && isRecord(block.source)) {
335
+ const mediaType = block.source.type === "base64" && typeof block.source.media_type === "string" ? block.source.media_type : "image";
336
+ parts.push(`[Image: ${mediaType}]`);
337
+ } else if (block.type === "tool_reference" && typeof block.tool_name === "string") {
338
+ parts.push(`[Tool reference: ${block.tool_name}]`);
339
+ } else if (block.type === "search_result") {
340
+ const title = typeof block.title === "string" ? block.title : "search result";
341
+ const source = typeof block.source === "string" ? ` (${block.source})` : "";
342
+ const nested = Array.isArray(block.content) ? contentToText(block.content.filter(isRecord)) : "";
343
+ parts.push(`${title}${source}${nested ? `
344
+ ${nested}` : ""}`);
345
+ } else if (block.type === "document") {
346
+ const title = typeof block.title === "string" ? block.title : "document";
347
+ parts.push(`[Document: ${title}]`);
348
+ }
349
+ }
350
+ return parts.join("\n");
351
+ }
352
+ function isRecord(value) {
353
+ return typeof value === "object" && value !== null && !Array.isArray(value);
354
+ }
355
+ function asRecord(value) {
356
+ if (isRecord(value)) {
357
+ return value;
358
+ }
359
+ if (Array.isArray(value)) {
360
+ return Object.fromEntries(value.entries());
361
+ }
362
+ return {};
363
+ }
364
+ function asString(value) {
365
+ if (typeof value === "string") {
366
+ return value;
367
+ }
368
+ return String(value);
369
+ }
370
+ function asErrorString(value) {
371
+ if (value instanceof Error) {
372
+ return value.message;
373
+ }
374
+ return asString(value);
375
+ }
376
+ function isObject(value) {
377
+ return typeof value === "object" && value !== null;
378
+ }
379
+ function toTry(fn, ctx) {
380
+ if (typeof fn !== "function") {
381
+ return fn;
382
+ }
383
+ return function(...args) {
384
+ let ret;
385
+ try {
386
+ ret = ctx ? fn.call(ctx, ...args) : fn.call(this, ...args);
387
+ } catch (err) {
388
+ log.error({ err }, "utils operation failed");
389
+ return void 0;
390
+ }
391
+ return ret;
392
+ };
393
+ }
394
+ var safeJSONParse = toTry(JSON.parse, JSON);
395
+ function asError(err) {
396
+ if (err instanceof Error) {
397
+ return err;
398
+ }
399
+ return new Error(String(err));
400
+ }
401
+ function intArg(args, key, fallback) {
402
+ const v = args[key];
403
+ if (typeof v === "number") {
404
+ return Math.floor(v);
405
+ }
406
+ if (typeof v === "string") {
407
+ const n = Number.parseInt(v, 10);
408
+ return Number.isNaN(n) ? fallback : n;
409
+ }
410
+ return fallback;
411
+ }
412
+ function strList(raw) {
413
+ if (Array.isArray(raw)) {
414
+ return raw.filter((v) => typeof v === "string");
415
+ }
416
+ return [];
417
+ }
418
+ function strArg(args, key, fallback) {
419
+ const v = args[key];
420
+ if (typeof v === "string") {
421
+ return v;
422
+ }
423
+ return fallback ?? "";
424
+ }
425
+ function boolArg(args, key, fallback) {
426
+ const v = args[key];
427
+ if (typeof v === "boolean") {
428
+ return v;
429
+ }
430
+ return fallback ?? Boolean(v);
431
+ }
432
+ function formatToolArgs(args) {
433
+ if (args.command) {
434
+ return truncate(strArg(args, "command"), 80);
435
+ }
436
+ if (args.file_path) {
437
+ return truncate(strArg(args, "file_path"), 80);
438
+ }
439
+ if (args.pattern) {
440
+ return truncate(strArg(args, "pattern"), 80);
441
+ }
442
+ if (args.description) {
443
+ return truncate(strArg(args, "description"), 80);
444
+ }
445
+ return "";
446
+ }
447
+ function truncate(value, max) {
448
+ return value.length > max ? `${value.slice(0, max)}\u2026` : value;
449
+ }
450
+
451
+ // src/config/provider-config.ts
452
+ var provider_config_exports = {};
453
+ __export(provider_config_exports, {
454
+ DEFAULT_CONTEXT_WINDOW: () => DEFAULT_CONTEXT_WINDOW,
455
+ DEFAULT_MAX_OUTPUT_TOKENS: () => DEFAULT_MAX_OUTPUT_TOKENS,
456
+ DEFAULT_THINKING_LEVEL: () => DEFAULT_THINKING_LEVEL,
457
+ MIN_THINKING_ANSWER_TOKENS: () => MIN_THINKING_ANSWER_TOKENS,
458
+ MIN_THINKING_BUDGET_TOKENS: () => MIN_THINKING_BUDGET_TOKENS,
459
+ ProviderConfigSchema: () => ProviderConfigSchema,
460
+ THINKING_BUDGETS: () => THINKING_BUDGETS,
461
+ THINKING_LEVELS: () => THINKING_LEVELS,
462
+ clampThinkingLevel: () => clampThinkingLevel,
463
+ getContextWindow: () => getContextWindow,
464
+ getMaxOutputTokens: () => getMaxOutputTokens,
465
+ getSupportedThinkingLevels: () => getSupportedThinkingLevels,
466
+ getThinkingLevel: () => getThinkingLevel,
467
+ globalConfigPath: () => globalConfigPath,
468
+ isValidThinkingLevel: () => isValidThinkingLevel,
469
+ thinkingBudgetForLevel: () => thinkingBudgetForLevel,
470
+ toAnthropicThinkingEffort: () => toAnthropicThinkingEffort,
471
+ toReasoningEffort: () => toReasoningEffort,
472
+ withProviderDefaults: () => withProviderDefaults
473
+ });
474
+ import { homedir as homedir3 } from "os";
475
+ import { join as join3 } from "path";
476
+ import { z } from "zod";
477
+ function globalConfigPath() {
478
+ return join3(homedir3(), ".yukino", "config.yaml");
479
+ }
480
+ var THINKING_LEVELS = [
481
+ "off",
482
+ "minimal",
483
+ "low",
484
+ "medium",
485
+ "high",
486
+ "xhigh",
487
+ "max"
488
+ ];
489
+ var ReasoningEffortSchema = z.enum([
490
+ "none",
491
+ "minimal",
492
+ "low",
493
+ "medium",
494
+ "high",
495
+ "xhigh",
496
+ "max"
497
+ ]);
498
+ var AnthropicEffortSchema = z.enum(["low", "medium", "high", "xhigh", "max"]);
499
+ var ThinkingLevelMapSchema = z.strictObject({
500
+ off: z.literal("none").nullable().optional(),
501
+ minimal: ReasoningEffortSchema.nullable().optional(),
502
+ low: ReasoningEffortSchema.nullable().optional(),
503
+ medium: ReasoningEffortSchema.nullable().optional(),
504
+ high: ReasoningEffortSchema.nullable().optional(),
505
+ xhigh: ReasoningEffortSchema.nullable().optional(),
506
+ max: ReasoningEffortSchema.nullable().optional()
507
+ });
508
+ var ProviderConfigSchema = z.looseObject({
509
+ name: z.string(),
510
+ protocol: z.enum(["anthropic", "openai", "openai-compat"]),
511
+ base_url: z.string(),
512
+ model: z.string(),
513
+ api_key: z.string().optional(),
514
+ thinking: z.enum(THINKING_LEVELS).optional(),
515
+ /** Explicit capability metadata, never inferred from model names. */
516
+ reasoning: z.boolean().optional(),
517
+ thinking_level_map: ThinkingLevelMapSchema.optional(),
518
+ /** Only Anthropic uses this mode; existing configurations use budgets. */
519
+ thinking_mode: z.enum(["budget", "adaptive"]).optional(),
520
+ context_window: z.coerce.number().optional(),
521
+ /**
522
+ * The model's output ceiling (PI's `model.maxTokens`). Clamped to the
523
+ * context window; reasoning shares this ceiling instead of raising it.
524
+ */
525
+ max_output_tokens: z.coerce.number().optional()
526
+ });
527
+ var DEFAULT_THINKING_LEVEL = "high";
528
+ var DEFAULT_CONTEXT_WINDOW = 1e6;
529
+ var DEFAULT_MAX_OUTPUT_TOKENS = 128e3;
530
+ var THINKING_BUDGETS = {
531
+ minimal: 1024,
532
+ low: 2048,
533
+ medium: 8192,
534
+ high: 16384,
535
+ xhigh: 32768,
536
+ max: 65536
537
+ };
538
+ var MIN_THINKING_BUDGET_TOKENS = 1024;
539
+ var MIN_THINKING_ANSWER_TOKENS = 1024;
540
+ function isValidThinkingLevel(value) {
541
+ return THINKING_LEVELS.some((level) => level === value);
542
+ }
543
+ function getThinkingLevel(provider) {
544
+ return clampThinkingLevel(
545
+ provider,
546
+ provider.thinking ?? DEFAULT_THINKING_LEVEL
547
+ );
548
+ }
549
+ function thinkingBudgetForLevel(level) {
550
+ return level === "off" ? 0 : THINKING_BUDGETS[level];
551
+ }
552
+ function toReasoningEffort(level, provider) {
553
+ if (provider?.reasoning === false) {
554
+ return null;
555
+ }
556
+ if (level === "off") {
557
+ return "none";
558
+ }
559
+ const mapped = provider?.thinking_level_map?.[level];
560
+ if (mapped !== void 0) {
561
+ return mapped;
562
+ }
563
+ if (provider?.protocol === "anthropic" && provider.thinking_mode === "adaptive") {
564
+ if (level === "minimal") {
565
+ return "low";
566
+ }
567
+ if (level === "xhigh") {
568
+ return "high";
569
+ }
570
+ }
571
+ if ((provider?.protocol === "openai" || provider?.protocol === "openai-compat") && (level === "xhigh" || level === "max")) {
572
+ return "high";
573
+ }
574
+ return level;
575
+ }
576
+ function toAnthropicThinkingEffort(level, provider) {
577
+ const parsed = AnthropicEffortSchema.safeParse(
578
+ toReasoningEffort(level, provider)
579
+ );
580
+ return parsed.success ? parsed.data : null;
581
+ }
582
+ function getSupportedThinkingLevels(provider) {
583
+ if (provider.reasoning === false || provider.protocol === "anthropic" && provider.thinking_mode !== "adaptive" && getMaxOutputTokens(provider) < MIN_THINKING_BUDGET_TOKENS + MIN_THINKING_ANSWER_TOKENS) {
584
+ return ["off"];
585
+ }
586
+ return THINKING_LEVELS.filter((level) => {
587
+ if (level === "off") {
588
+ return true;
589
+ }
590
+ if (provider.protocol === "anthropic" && provider.thinking_mode === "adaptive") {
591
+ return toAnthropicThinkingEffort(level, provider) !== null;
592
+ }
593
+ const effort = toReasoningEffort(level, provider);
594
+ if (effort === null || effort === "none") {
595
+ return false;
596
+ }
597
+ if ((provider.protocol === "openai" || provider.protocol === "openai-compat") && (level === "xhigh" || level === "max") && provider.thinking_level_map?.[level] === void 0) {
598
+ return false;
599
+ }
600
+ return true;
601
+ });
602
+ }
603
+ function clampThinkingLevel(provider, level) {
604
+ const supported = getSupportedThinkingLevels(provider);
605
+ let effective = "off";
606
+ for (const candidate of THINKING_LEVELS) {
607
+ if (supported.includes(candidate)) {
608
+ effective = candidate;
609
+ }
610
+ if (candidate === level) {
611
+ break;
612
+ }
613
+ }
614
+ return effective;
615
+ }
616
+ function withProviderDefaults(provider) {
617
+ return {
618
+ ...provider,
619
+ thinking: getThinkingLevel(provider),
620
+ context_window: getContextWindow(provider),
621
+ max_output_tokens: getMaxOutputTokens(provider)
622
+ };
623
+ }
624
+ function getContextWindow(provider) {
625
+ return Number.isSafeInteger(provider.context_window) && (provider.context_window ?? 0) > 0 ? provider.context_window ?? DEFAULT_CONTEXT_WINDOW : DEFAULT_CONTEXT_WINDOW;
626
+ }
627
+ function getMaxOutputTokens(provider) {
628
+ const configured = provider.max_output_tokens;
629
+ const maxOutput = Number.isSafeInteger(configured) && (configured ?? 0) > 0 ? configured ?? DEFAULT_MAX_OUTPUT_TOKENS : DEFAULT_MAX_OUTPUT_TOKENS;
630
+ return Math.min(maxOutput, getContextWindow(provider));
631
+ }
632
+
633
+ // src/config/index.ts
634
+ var config_exports = {};
635
+ __export(config_exports, {
636
+ ConfigError: () => ConfigError,
637
+ HookConfigSchema: () => HookConfigSchema,
638
+ ProviderConfig: () => provider_config_exports,
639
+ ProviderLogin: () => provider_login_exports,
640
+ forkEnabled: () => forkEnabled,
641
+ loadConfig: () => loadConfig,
642
+ loadProjectMcpServers: () => loadProjectMcpServers,
643
+ memoryEnabled: () => memoryEnabled,
644
+ resolveAPIKey: () => resolveAPIKey,
645
+ withProjectMcpServers: () => withProjectMcpServers
646
+ });
647
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
648
+ import { join as join5 } from "path";
649
+ import {
650
+ getParseErrorMessage,
651
+ safeParse
652
+ } from "@modelcontextprotocol/sdk/server/zod-compat.js";
653
+ import yaml2 from "js-yaml";
654
+ import { z as z3 } from "zod";
655
+
656
+ // src/config/provider-login.ts
657
+ var provider_login_exports = {};
658
+ __export(provider_login_exports, {
659
+ ProviderLoginSchema: () => ProviderLoginSchema,
660
+ persistDefaultProvider: () => persistDefaultProvider,
661
+ persistModel: () => persistModel,
662
+ persistThinkingLevel: () => persistThinkingLevel,
663
+ saveProvider: () => saveProvider
664
+ });
665
+ import { randomUUID } from "crypto";
666
+ import {
667
+ existsSync,
668
+ mkdirSync as mkdirSync2,
669
+ readFileSync,
670
+ renameSync,
671
+ unlinkSync,
672
+ writeFileSync as writeFileSync2
673
+ } from "fs";
674
+ import { dirname as dirname3, join as join4 } from "path";
675
+ import yaml from "js-yaml";
676
+ import { z as z2 } from "zod";
677
+ var tokenLimit = (fallback, min, max) => z2.preprocess(
678
+ (value) => value === void 0 || typeof value === "string" && !value.trim() ? fallback : value,
679
+ z2.union([
680
+ z2.number(),
681
+ z2.string().trim().regex(/^\d+$/, "Enter a whole number").transform(Number)
682
+ ]).pipe(z2.number().int().min(min).max(max))
683
+ );
684
+ var ProviderLoginSchema = ProviderConfigSchema.extend({
685
+ name: z2.string().trim().min(1, "Name is required"),
686
+ base_url: z2.url("Enter a valid HTTP(S) URL").refine((url) => /^https?:\/\//i.test(url), "Use an HTTP(S) URL"),
687
+ api_key: z2.string().trim().min(1, "API key is required"),
688
+ model: z2.string().trim().min(1, "Model is required"),
689
+ thinking: z2.enum(THINKING_LEVELS).optional(),
690
+ context_window: tokenLimit(DEFAULT_CONTEXT_WINDOW, 1e3, 1e7),
691
+ max_output_tokens: tokenLimit(DEFAULT_MAX_OUTPUT_TOKENS, 1, 1e6)
692
+ }).refine((provider) => provider.max_output_tokens <= provider.context_window, {
693
+ path: ["max_output_tokens"],
694
+ message: "Max output tokens must not exceed the context window"
695
+ }).transform((provider) => ({
696
+ ...provider,
697
+ thinking: getThinkingLevel(provider)
698
+ }));
699
+ function readConfigRaw(path) {
700
+ if (!existsSync(path)) {
701
+ return {};
702
+ }
703
+ let raw;
704
+ try {
705
+ raw = yaml.load(readFileSync(path, "utf-8"));
706
+ } catch {
707
+ throw new Error(
708
+ `Unable to read existing ${path}; it has not been changed.`
709
+ );
710
+ }
711
+ return z2.record(z2.string(), z2.unknown()).parse(raw ?? {});
712
+ }
713
+ function writeConfigAtomic(path, raw) {
714
+ const directory = dirname3(path);
715
+ mkdirSync2(directory, { recursive: true });
716
+ const temporary = join4(directory, `.config-${randomUUID()}.tmp`);
717
+ try {
718
+ writeFileSync2(temporary, yaml.dump(raw, { lineWidth: -1, noRefs: true }), {
719
+ encoding: "utf-8",
720
+ mode: 384,
721
+ flag: "wx"
722
+ });
723
+ renameSync(temporary, path);
724
+ } finally {
725
+ if (existsSync(temporary)) {
726
+ unlinkSync(temporary);
727
+ }
728
+ }
729
+ }
730
+ function saveProvider(input, available) {
731
+ const provider = ProviderLoginSchema.parse(input);
732
+ const path = globalConfigPath();
733
+ const config = readConfigRaw(path);
734
+ const existing = z2.array(z2.record(z2.string(), z2.unknown())).parse(config.providers ?? []);
735
+ const current = [...existing];
736
+ for (const entry of available) {
737
+ if (!current.some((stored2) => stored2.base_url === entry.base_url)) {
738
+ current.push({ ...entry });
739
+ }
740
+ }
741
+ const stored = [];
742
+ let replaced = false;
743
+ for (const entry of current) {
744
+ if (entry.base_url !== provider.base_url) {
745
+ stored.push(entry);
746
+ continue;
747
+ }
748
+ if (replaced) {
749
+ continue;
750
+ }
751
+ replaced = true;
752
+ stored.push(provider);
753
+ }
754
+ if (!replaced) {
755
+ stored.push(provider);
756
+ }
757
+ const providers = stored.map((entry) => ProviderConfigSchema.parse(entry));
758
+ writeConfigAtomic(path, { ...config, providers: stored });
759
+ return { provider, providers, replaced, path };
760
+ }
761
+ function persistProviderField(baseUrl, field, value) {
762
+ const path = globalConfigPath();
763
+ const config = readConfigRaw(path);
764
+ const providers = z2.array(z2.record(z2.string(), z2.unknown())).parse(config.providers ?? []);
765
+ const targets = providers.filter((entry) => entry.base_url === baseUrl);
766
+ if (targets.length === 0) {
767
+ throw new Error(
768
+ `Provider with base URL "${baseUrl}" not found in ${path}.`
769
+ );
770
+ }
771
+ const changed = targets.filter((entry) => entry[field] !== value);
772
+ if (changed.length === 0) {
773
+ return;
774
+ }
775
+ for (const entry of changed) {
776
+ entry[field] = value;
777
+ }
778
+ writeConfigAtomic(path, { ...config, providers });
779
+ }
780
+ function persistThinkingLevel(baseUrl, level) {
781
+ persistProviderField(baseUrl, "thinking", level);
782
+ }
783
+ function persistModel(baseUrl, model) {
784
+ persistProviderField(baseUrl, "model", model);
785
+ }
786
+ function persistDefaultProvider(index) {
787
+ const path = globalConfigPath();
788
+ const config = readConfigRaw(path);
789
+ if (config.default_provider === index) {
790
+ return;
791
+ }
792
+ writeConfigAtomic(path, { ...config, default_provider: index });
793
+ }
794
+
795
+ // src/config/index.ts
796
+ var log2 = createChildLogger({ module: "config" });
797
+ var ENV_KEY_MAP = {
798
+ anthropic: "ANTHROPIC_API_KEY",
799
+ openai: "OPENAI_API_KEY",
800
+ "openai-compat": "OPENAI_API_KEY"
801
+ };
802
+ function isKeyofTypeofEnvKeyMap(k) {
803
+ return VALID_PROTOCOLS.has(k);
804
+ }
805
+ var VALID_PROTOCOLS = new Set(Object.keys(ENV_KEY_MAP));
806
+ var ConfigError = class extends Error {
807
+ constructor(message) {
808
+ super(message);
809
+ this.name = "ConfigError";
810
+ }
811
+ };
812
+ function resolveAPIKey(p) {
813
+ if (p.api_key) {
814
+ return p.api_key;
815
+ }
816
+ const envVar = isKeyofTypeofEnvKeyMap(p.protocol) ? ENV_KEY_MAP[p.protocol] : "";
817
+ if (!envVar) {
818
+ return "";
819
+ }
820
+ return process.env[envVar] ?? "";
821
+ }
822
+ var MCPServerConfigSchema = z3.object({
823
+ name: z3.string(),
824
+ command: z3.string().optional(),
825
+ args: z3.array(z3.string()).optional(),
826
+ url: z3.string().optional(),
827
+ transport: z3.string().optional(),
828
+ headers: z3.record(z3.string(), z3.string()).optional(),
829
+ env: z3.record(z3.string(), z3.string()).optional()
830
+ });
831
+ var HookConfigSchema = z3.object({
832
+ id: z3.string().optional(),
833
+ event: z3.string(),
834
+ condition: z3.string().optional(),
835
+ action: z3.object({
836
+ type: z3.string(),
837
+ command: z3.string().optional(),
838
+ url: z3.string().optional(),
839
+ method: z3.string().optional(),
840
+ prompt: z3.string().optional()
841
+ }),
842
+ reject: z3.boolean().optional(),
843
+ once: z3.boolean().optional(),
844
+ async: z3.boolean().optional(),
845
+ on_error: z3.string().optional()
846
+ });
847
+ var SandboxYamlConfigSchema = z3.object({
848
+ enabled: z3.boolean().optional(),
849
+ backend: z3.enum(["native", "sandbox-runtime"]).optional(),
850
+ auto_allow: z3.boolean().optional(),
851
+ network_enabled: z3.boolean().optional()
852
+ });
853
+ var AppConfigSchema = z3.looseObject({
854
+ default_provider: z3.number().default(0),
855
+ providers: z3.array(ProviderConfigSchema),
856
+ permission_mode: z3.string().optional(),
857
+ mcp_servers: z3.array(MCPServerConfigSchema).default([]),
858
+ hooks: z3.array(HookConfigSchema).default([]),
859
+ sandbox: SandboxYamlConfigSchema.optional(),
860
+ enable_coordinator_mode: z3.boolean().optional(),
861
+ /**
862
+ * Whether to fork when subagent_type is omitted. Enabled by default, so this
863
+ * field is left as undefined to represent "not specified in config"; only an
864
+ * explicit `false` disables forking (see forkEnabled).
865
+ */
866
+ enable_fork: z3.boolean().optional(),
867
+ /**
868
+ * Whether auto memory is enabled: gates index injection, recall, and
869
+ * background extraction in the hosts that run them (interactive UI, remote,
870
+ * ACP), and consolidation, which currently runs only in remote mode.
871
+ * Defaults to enabled; `memory: false` turns the whole automatic memory
872
+ * pipeline off. Left optional so "not set" and "explicitly false" stay
873
+ * distinguishable, mirroring enable_fork.
874
+ */
875
+ memory: z3.boolean().optional()
876
+ });
877
+ function forkEnabled(cfg) {
878
+ return cfg.enable_fork !== false;
879
+ }
880
+ function memoryEnabled(cfg) {
881
+ return cfg.memory !== false;
882
+ }
883
+ function isRecord2(value) {
884
+ return typeof value === "object" && value !== null;
885
+ }
886
+ function loadSingleFile(path) {
887
+ const data = readFileSync2(path, "utf-8");
888
+ const raw = yaml2.load(data);
889
+ if (!isRecord2(raw)) {
890
+ log2.error({ path }, "invalid yaml");
891
+ return { default_provider: 0, providers: [], mcp_servers: [], hooks: [] };
892
+ }
893
+ const parsed = safeParse(AppConfigSchema, raw);
894
+ if (parsed.success) {
895
+ const data2 = parsed.data;
896
+ return {
897
+ ...data2,
898
+ providers: data2.providers.map(withProviderDefaults)
899
+ };
900
+ }
901
+ log2.error({ error: parsed.error }, "config error");
902
+ let defaultProvider = 0;
903
+ let providers = [];
904
+ let permissionMode;
905
+ let mcpServers = [];
906
+ let hooks = [];
907
+ let sandbox = void 0;
908
+ let enableCoordinatorMode = false;
909
+ let enableFork = true;
910
+ let memory = true;
911
+ if ("default_provider" in raw) {
912
+ const parsed2 = safeParse(z3.number(), raw.default_provider);
913
+ if (parsed2.success) {
914
+ defaultProvider = parsed2.data;
915
+ }
916
+ }
917
+ if ("providers" in raw) {
918
+ const parsed2 = safeParse(z3.array(ProviderConfigSchema), raw.providers);
919
+ if (parsed2.success) {
920
+ providers = parsed2.data.map(withProviderDefaults);
921
+ } else {
922
+ throw new ConfigError(
923
+ `Invalid provider configuration in ${path}: ${getParseErrorMessage(parsed2.error)}`
924
+ );
925
+ }
926
+ }
927
+ if ("permission_mode" in raw && typeof raw.permission_mode === "string") {
928
+ permissionMode = raw.permission_mode;
929
+ }
930
+ if ("mcp_servers" in raw) {
931
+ const parsed2 = safeParse(z3.array(MCPServerConfigSchema), raw.mcp_servers);
932
+ if (parsed2.success) {
933
+ mcpServers = parsed2.data;
934
+ } else {
935
+ throw new ConfigError(
936
+ `Invalid MCP server configuration in ${path}: ${getParseErrorMessage(parsed2.error)}`
937
+ );
938
+ }
939
+ }
940
+ if ("hooks" in raw) {
941
+ const parsed2 = safeParse(z3.array(HookConfigSchema), raw.hooks);
942
+ if (parsed2.success) {
943
+ hooks = parsed2.data;
944
+ } else {
945
+ throw new ConfigError(
946
+ `Invalid hooks configuration in ${path}: ${getParseErrorMessage(parsed2.error)}`
947
+ );
948
+ }
949
+ }
950
+ if ("sandbox" in raw) {
951
+ const parsed2 = safeParse(SandboxYamlConfigSchema, raw.sandbox);
952
+ if (parsed2.success) {
953
+ sandbox = parsed2.data;
954
+ } else {
955
+ throw new ConfigError(
956
+ `Invalid sandbox configuration in ${path}: ${getParseErrorMessage(parsed2.error)}`
957
+ );
958
+ }
959
+ }
960
+ if ("enable_coordinator_mode" in raw) {
961
+ enableCoordinatorMode = Boolean(raw.enable_coordinator_mode);
962
+ }
963
+ if ("enable_fork" in raw) {
964
+ enableFork = Boolean(raw.enable_fork);
965
+ }
966
+ if ("memory" in raw) {
967
+ memory = Boolean(raw.memory);
968
+ }
969
+ return {
970
+ default_provider: defaultProvider,
971
+ providers,
972
+ permission_mode: permissionMode,
973
+ mcp_servers: mcpServers,
974
+ hooks,
975
+ sandbox,
976
+ enable_coordinator_mode: enableCoordinatorMode,
977
+ enable_fork: enableFork,
978
+ memory
979
+ };
980
+ }
981
+ function validateProviders(config) {
982
+ if (config.providers.length === 0) {
983
+ throw new ConfigError("At least one provider MUST be configured.");
984
+ }
985
+ const requiredFields = ["name", "protocol", "base_url", "model"];
986
+ const baseUrls = /* @__PURE__ */ new Map();
987
+ for (let i = 0; i < config.providers.length; i++) {
988
+ const p = config.providers[i];
989
+ const values = {
990
+ name: p.name,
991
+ protocol: p.protocol,
992
+ base_url: p.base_url,
993
+ model: p.model
994
+ };
995
+ const missing = requiredFields.filter((field) => !values[field].trim());
996
+ if (missing.length > 0) {
997
+ throw new ConfigError(
998
+ `Provider #${String(i + 1)}: missing fields: ${missing.join(", ")}`
999
+ );
1000
+ }
1001
+ if (!VALID_PROTOCOLS.has(p.protocol)) {
1002
+ throw new ConfigError(
1003
+ `Provider #${String(i + 1)}: invalid protocol '${p.protocol}', MUST be one of: ${Array.from(VALID_PROTOCOLS).join(", ")}`
1004
+ );
1005
+ }
1006
+ const previous = baseUrls.get(p.base_url);
1007
+ if (previous !== void 0) {
1008
+ throw new ConfigError(
1009
+ `Provider #${String(i + 1)}: duplicate base_url '${p.base_url}' (already used by provider #${String(previous + 1)}).`
1010
+ );
1011
+ }
1012
+ baseUrls.set(p.base_url, i);
1013
+ }
1014
+ }
1015
+ function validateMcpServers(config) {
1016
+ const names = /* @__PURE__ */ new Map();
1017
+ for (let i = 0; i < config.mcp_servers.length; i++) {
1018
+ const server = config.mcp_servers[i];
1019
+ const position = `MCP server #${String(i + 1)}`;
1020
+ if (!server.name.trim()) {
1021
+ throw new ConfigError(`${position}: name must not be empty.`);
1022
+ }
1023
+ const previous = names.get(server.name);
1024
+ if (previous !== void 0) {
1025
+ throw new ConfigError(
1026
+ `${position}: duplicate name '${server.name}' (already used by MCP server #${String(previous + 1)}).`
1027
+ );
1028
+ }
1029
+ names.set(server.name, i);
1030
+ const hasCommand = Boolean(server.command?.trim());
1031
+ const hasUrl = Boolean(server.url?.trim());
1032
+ if (hasCommand === hasUrl) {
1033
+ throw new ConfigError(
1034
+ `${position} '${server.name}': configure exactly one of command or url.`
1035
+ );
1036
+ }
1037
+ if (hasCommand && server.transport && server.transport !== "stdio") {
1038
+ throw new ConfigError(
1039
+ `${position} '${server.name}': command servers must use stdio.`
1040
+ );
1041
+ }
1042
+ if (hasUrl && server.transport && !["http", "sse"].includes(server.transport)) {
1043
+ throw new ConfigError(
1044
+ `${position} '${server.name}': URL transport must be http or sse.`
1045
+ );
1046
+ }
1047
+ }
1048
+ }
1049
+ var PROJECT_MCP_FILENAME = ".mcp.json";
1050
+ var McpJsonEntrySchema = z3.looseObject({
1051
+ command: z3.string().optional(),
1052
+ args: z3.array(z3.string()).optional(),
1053
+ env: z3.record(z3.string(), z3.string()).optional(),
1054
+ type: z3.enum(["stdio", "sse", "http"]).optional(),
1055
+ url: z3.string().optional(),
1056
+ headers: z3.record(z3.string(), z3.string()).optional()
1057
+ });
1058
+ var McpJsonFileSchema = z3.looseObject({
1059
+ // Parse entries independently below so one bad server does not disable every
1060
+ // valid server in the project file.
1061
+ mcpServers: z3.record(z3.string(), z3.unknown()).default({})
1062
+ });
1063
+ function mcpServerFromJsonEntry(name, entry) {
1064
+ const transport = entry.type ?? (entry.command !== void 0 ? "stdio" : "http");
1065
+ if (transport === "stdio") {
1066
+ if (!entry.command || entry.url !== void 0) {
1067
+ return null;
1068
+ }
1069
+ return { name, command: entry.command, args: entry.args, env: entry.env };
1070
+ }
1071
+ if (!entry.url || entry.command !== void 0) {
1072
+ return null;
1073
+ }
1074
+ return { name, url: entry.url, transport, headers: entry.headers };
1075
+ }
1076
+ function loadProjectMcpServers(workDir) {
1077
+ const path = join5(workDir, PROJECT_MCP_FILENAME);
1078
+ if (!existsSync2(path)) {
1079
+ return [];
1080
+ }
1081
+ let raw;
1082
+ try {
1083
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
1084
+ } catch (err) {
1085
+ log2.error({ err, path }, "invalid .mcp.json");
1086
+ return [];
1087
+ }
1088
+ const parsed = safeParse(McpJsonFileSchema, raw);
1089
+ if (!parsed.success) {
1090
+ log2.error({ error: parsed.error, path }, "invalid .mcp.json");
1091
+ return [];
1092
+ }
1093
+ const servers = [];
1094
+ for (const [name, rawEntry] of Object.entries(parsed.data.mcpServers)) {
1095
+ const parsedEntry = safeParse(McpJsonEntrySchema, rawEntry);
1096
+ if (!name.trim() || !parsedEntry.success) {
1097
+ log2.warn(
1098
+ {
1099
+ name,
1100
+ path,
1101
+ error: parsedEntry.success ? void 0 : parsedEntry.error
1102
+ },
1103
+ "skipping invalid .mcp.json server entry"
1104
+ );
1105
+ continue;
1106
+ }
1107
+ const server = mcpServerFromJsonEntry(name, parsedEntry.data);
1108
+ if (server) {
1109
+ servers.push(server);
1110
+ } else {
1111
+ log2.warn({ name, path }, "skipping invalid .mcp.json server entry");
1112
+ }
1113
+ }
1114
+ return servers;
1115
+ }
1116
+ function withProjectMcpServers(config, workDir) {
1117
+ const projectServers = loadProjectMcpServers(workDir);
1118
+ if (projectServers.length === 0) {
1119
+ return config;
1120
+ }
1121
+ const known = new Set(config.mcp_servers.map((s) => s.name));
1122
+ return {
1123
+ ...config,
1124
+ mcp_servers: [
1125
+ ...config.mcp_servers,
1126
+ ...projectServers.filter((s) => !known.has(s.name))
1127
+ ]
1128
+ };
1129
+ }
1130
+ function loadConfig(path, options = {}) {
1131
+ if (path) {
1132
+ const config2 = loadSingleFile(path);
1133
+ validateMcpServers(config2);
1134
+ if (!options.allowEmptyProviders || config2.providers.length > 0) {
1135
+ validateProviders(config2);
1136
+ }
1137
+ return config2;
1138
+ }
1139
+ const candidate = globalConfigPath();
1140
+ if (!existsSync2(candidate)) {
1141
+ if (options.allowEmptyProviders) {
1142
+ return { default_provider: 0, providers: [], mcp_servers: [], hooks: [] };
1143
+ }
1144
+ throw new ConfigError(`No config file found, expected ${candidate}.`);
1145
+ }
1146
+ const config = loadSingleFile(candidate);
1147
+ validateMcpServers(config);
1148
+ if (!options.allowEmptyProviders || config.providers.length > 0) {
1149
+ validateProviders(config);
1150
+ }
1151
+ return config;
1152
+ }
1153
+
1154
+ // src/conversation/pairing.ts
1155
+ var pairing_exports = {};
1156
+ __export(pairing_exports, {
1157
+ INTERRUPTED_TOOL_RESULT: () => INTERRUPTED_TOOL_RESULT,
1158
+ REJECTED_TOOL_RESULT: () => REJECTED_TOOL_RESULT,
1159
+ ensureToolPairing: () => ensureToolPairing
1160
+ });
1161
+ var INTERRUPTED_TOOL_RESULT = "Tool execution was interrupted. The tool may or may not have completed; verify before relying on its effects.";
1162
+ var REJECTED_TOOL_RESULT = "The user rejected this tool use. Nothing was changed (for file edits, the new content was NOT written).";
1163
+ function ensureToolPairing(messages) {
1164
+ const out = [];
1165
+ for (let i = 0; i < messages.length; i++) {
1166
+ const m = messages[i];
1167
+ if (m.role === "assistant" && m.toolUses?.length) {
1168
+ out.push(m);
1169
+ const pending = new Set(m.toolUses.map((tu) => tu.toolUseId));
1170
+ const results = [];
1171
+ const resultMessages = [];
1172
+ while (i + 1 < messages.length) {
1173
+ const next = messages[i + 1];
1174
+ if (next.role !== "user" || !next.toolResults?.length || next.toolUses?.length) {
1175
+ break;
1176
+ }
1177
+ i++;
1178
+ resultMessages.push(next);
1179
+ for (const tr of next.toolResults) {
1180
+ if (pending.delete(tr.toolUseId)) {
1181
+ results.push(tr);
1182
+ }
1183
+ }
1184
+ }
1185
+ for (const toolUseId of pending) {
1186
+ results.push({
1187
+ toolUseId,
1188
+ content: INTERRUPTED_TOOL_RESULT,
1189
+ isError: true
1190
+ });
1191
+ }
1192
+ out.push({
1193
+ ...resultMessages[0] ?? { role: "user", content: "" },
1194
+ toolResults: results
1195
+ });
1196
+ for (const remaining of resultMessages.slice(1)) {
1197
+ if (remaining.content.length > 0 || remaining.thinkingBlocks?.length) {
1198
+ out.push({ ...remaining, toolResults: [] });
1199
+ }
1200
+ }
1201
+ continue;
1202
+ }
1203
+ if ((m.toolResults?.length ?? 0) > 0) {
1204
+ if (m.content.length === 0 && !m.toolUses?.length && !m.thinkingBlocks?.length) {
1205
+ continue;
1206
+ }
1207
+ out.push({ ...m, toolResults: [] });
1208
+ } else {
1209
+ out.push(m);
1210
+ }
1211
+ }
1212
+ return out;
1213
+ }
1214
+
1215
+ // src/llm/errors.ts
1216
+ var errors_exports = {};
1217
+ __export(errors_exports, {
1218
+ AuthenticationError: () => AuthenticationError,
1219
+ ContextTooLongError: () => ContextTooLongError,
1220
+ LLMError: () => LLMError,
1221
+ NetworkError: () => NetworkError,
1222
+ RateLimitError: () => RateLimitError,
1223
+ containsContextLengthError: () => containsContextLengthError
1224
+ });
1225
+ var LLMError = class extends Error {
1226
+ constructor(message) {
1227
+ super(message);
1228
+ this.name = "LLMError";
1229
+ }
1230
+ };
1231
+ var AuthenticationError = class extends LLMError {
1232
+ constructor(message) {
1233
+ super(message);
1234
+ this.name = "AuthenticationError";
1235
+ }
1236
+ };
1237
+ var RateLimitError = class extends LLMError {
1238
+ retryAfter;
1239
+ constructor(message, retryAfter) {
1240
+ super(message);
1241
+ this.name = "RateLimitError";
1242
+ this.retryAfter = retryAfter;
1243
+ }
1244
+ };
1245
+ var NetworkError = class extends LLMError {
1246
+ constructor(message) {
1247
+ super(message);
1248
+ this.name = "NetworkError";
1249
+ }
1250
+ };
1251
+ var ContextTooLongError = class extends LLMError {
1252
+ constructor(message) {
1253
+ super(message);
1254
+ this.name = "ContextTooLongError";
1255
+ }
1256
+ };
1257
+ function containsContextLengthError(msg) {
1258
+ return /context_length_exceeded/i.test(msg) || /maximum\s+context\s+length/i.test(msg) || /prompts?\s+(?:is\s+)?too\s+long/i.test(msg);
1259
+ }
1260
+
1261
+ // src/llm/events.ts
1262
+ var events_exports = {};
1263
+ __export(events_exports, {
1264
+ parseToolArguments: () => parseToolArguments
1265
+ });
1266
+ function parseToolArguments(raw) {
1267
+ if (!raw.trim()) {
1268
+ return { arguments: {} };
1269
+ }
1270
+ try {
1271
+ const parsed = JSON.parse(raw);
1272
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1273
+ return {
1274
+ arguments: {},
1275
+ parseError: "Invalid tool arguments: expected a JSON object"
1276
+ };
1277
+ }
1278
+ return { arguments: Object.fromEntries(Object.entries(parsed)) };
1279
+ } catch (error) {
1280
+ return {
1281
+ arguments: {},
1282
+ parseError: `Invalid tool arguments JSON: ${error instanceof Error ? error.message : "parse failed"}`
1283
+ };
1284
+ }
1285
+ }
1286
+
1287
+ export {
1288
+ sanitizeNameSegment,
1289
+ initLogger,
1290
+ closeLogger,
1291
+ logger,
1292
+ createChildLogger,
1293
+ logger_exports,
1294
+ canonicalPath,
1295
+ isPathWithin,
1296
+ generateSlug,
1297
+ contentToText,
1298
+ isRecord,
1299
+ asRecord,
1300
+ asString,
1301
+ asErrorString,
1302
+ isObject,
1303
+ safeJSONParse,
1304
+ intArg,
1305
+ strList,
1306
+ strArg,
1307
+ boolArg,
1308
+ utils_exports,
1309
+ THINKING_LEVELS,
1310
+ DEFAULT_THINKING_LEVEL,
1311
+ DEFAULT_CONTEXT_WINDOW,
1312
+ DEFAULT_MAX_OUTPUT_TOKENS,
1313
+ MIN_THINKING_ANSWER_TOKENS,
1314
+ isValidThinkingLevel,
1315
+ getThinkingLevel,
1316
+ thinkingBudgetForLevel,
1317
+ toReasoningEffort,
1318
+ toAnthropicThinkingEffort,
1319
+ getSupportedThinkingLevels,
1320
+ clampThinkingLevel,
1321
+ getContextWindow,
1322
+ getMaxOutputTokens,
1323
+ persistThinkingLevel,
1324
+ resolveAPIKey,
1325
+ forkEnabled,
1326
+ memoryEnabled,
1327
+ withProjectMcpServers,
1328
+ loadConfig,
1329
+ config_exports,
1330
+ REJECTED_TOOL_RESULT,
1331
+ ensureToolPairing,
1332
+ pairing_exports,
1333
+ LLMError,
1334
+ AuthenticationError,
1335
+ RateLimitError,
1336
+ NetworkError,
1337
+ ContextTooLongError,
1338
+ containsContextLengthError,
1339
+ errors_exports,
1340
+ parseToolArguments,
1341
+ events_exports
1342
+ };