@alexwkleung/reika 0.12.0 → 0.14.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.
@@ -0,0 +1,2819 @@
1
+ import { createRequire as __reikaCreateRequire } from 'node:module';
2
+ const require = __reikaCreateRequire(import.meta.url);
3
+ import {
4
+ COMMANDS,
5
+ CONFIRM_ACCEPT,
6
+ IMPLEMENT_MODES,
7
+ NATIVE_IMAGE_NOTE,
8
+ ROOT_HISTORY_DIR,
9
+ TOGGLE_CANCEL,
10
+ TOGGLE_OFF,
11
+ TOGGLE_ON,
12
+ addFileToIndex,
13
+ autoApproveForced,
14
+ autoApproves,
15
+ bootstrap,
16
+ budgetWarning,
17
+ buildRoundZeroPrefix,
18
+ buildSubmitInput,
19
+ buildTranscriptMeta,
20
+ callModel,
21
+ clearIdentity,
22
+ countRealTurns,
23
+ createSession,
24
+ effectiveAutoApprove,
25
+ enableAnon,
26
+ estimateRequestTokens,
27
+ execStream,
28
+ expandPastes,
29
+ forAutosave,
30
+ formatBudget,
31
+ formatElapsed,
32
+ formatUnattendedDeclines,
33
+ hasBareImagePath,
34
+ hasImageMarker,
35
+ hasPasteMarker,
36
+ imageReader,
37
+ implementModeConfirmSpec,
38
+ invokeMcpTool,
39
+ isAnon,
40
+ isGrindPrompt,
41
+ isImplementCommand,
42
+ isMinimalPrompt,
43
+ isSaveCommand,
44
+ latchesFor,
45
+ listSessions,
46
+ modeSide,
47
+ modelHistoryFromScrollback,
48
+ newSessionPath,
49
+ parseCommand,
50
+ parseMcpArgs,
51
+ pasteIsNative,
52
+ pastedUrlConfirmSpec,
53
+ prefixStableActive,
54
+ projectHistoryDir,
55
+ resolveModeCommand,
56
+ resolveSkillCommand,
57
+ resolveTurnCommand,
58
+ saveHeader,
59
+ saveTranscript,
60
+ scrubPaths,
61
+ shouldCompact,
62
+ skillConfirmSpec,
63
+ skillToConfirm,
64
+ sniffImageMime,
65
+ systemOcr,
66
+ toggleConfirmSpec,
67
+ turnMode,
68
+ turnPromptMode,
69
+ turnRefines,
70
+ turnTools,
71
+ urlsToConfirm,
72
+ writeSession
73
+ } from "./chunk-LNUPGYM7.js";
74
+ import {
75
+ spillResult
76
+ } from "./chunk-S4S44BI2.js";
77
+ import {
78
+ persistableMode,
79
+ startProfiles
80
+ } from "./chunk-JTRHYW55.js";
81
+ import {
82
+ inheritProfile,
83
+ isOffline,
84
+ modeSwitchProfile,
85
+ resolveProfile
86
+ } from "./chunk-YCKCJJ3W.js";
87
+ import {
88
+ debugLog,
89
+ processSessionStem
90
+ } from "./chunk-OSLX5BGM.js";
91
+ import {
92
+ __commonJS,
93
+ __require
94
+ } from "./chunk-KI5CTLSX.js";
95
+
96
+ // node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
97
+ var require_has_flag = __commonJS({
98
+ "node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports, module) {
99
+ "use strict";
100
+ module.exports = (flag, argv = process.argv) => {
101
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
102
+ const position = argv.indexOf(prefix + flag);
103
+ const terminatorPosition = argv.indexOf("--");
104
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
105
+ };
106
+ }
107
+ });
108
+
109
+ // node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
110
+ var require_supports_color = __commonJS({
111
+ "node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js"(exports, module) {
112
+ "use strict";
113
+ var os2 = __require("os");
114
+ var tty2 = __require("tty");
115
+ var hasFlag2 = require_has_flag();
116
+ var { env: env2 } = process;
117
+ var forceColor;
118
+ if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
119
+ forceColor = 0;
120
+ } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
121
+ forceColor = 1;
122
+ }
123
+ if ("FORCE_COLOR" in env2) {
124
+ if (env2.FORCE_COLOR === "true") {
125
+ forceColor = 1;
126
+ } else if (env2.FORCE_COLOR === "false") {
127
+ forceColor = 0;
128
+ } else {
129
+ forceColor = env2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env2.FORCE_COLOR, 10), 3);
130
+ }
131
+ }
132
+ function translateLevel2(level) {
133
+ if (level === 0) {
134
+ return false;
135
+ }
136
+ return {
137
+ level,
138
+ hasBasic: true,
139
+ has256: level >= 2,
140
+ has16m: level >= 3
141
+ };
142
+ }
143
+ function supportsColor2(haveStream, streamIsTTY) {
144
+ if (forceColor === 0) {
145
+ return 0;
146
+ }
147
+ if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
148
+ return 3;
149
+ }
150
+ if (hasFlag2("color=256")) {
151
+ return 2;
152
+ }
153
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
154
+ return 0;
155
+ }
156
+ const min = forceColor || 0;
157
+ if (env2.TERM === "dumb") {
158
+ return min;
159
+ }
160
+ if (process.platform === "win32") {
161
+ const osRelease = os2.release().split(".");
162
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
163
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
164
+ }
165
+ return 1;
166
+ }
167
+ if ("CI" in env2) {
168
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env2) || env2.CI_NAME === "codeship") {
169
+ return 1;
170
+ }
171
+ return min;
172
+ }
173
+ if ("TEAMCITY_VERSION" in env2) {
174
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
175
+ }
176
+ if (env2.COLORTERM === "truecolor") {
177
+ return 3;
178
+ }
179
+ if ("TERM_PROGRAM" in env2) {
180
+ const version = parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
181
+ switch (env2.TERM_PROGRAM) {
182
+ case "iTerm.app":
183
+ return version >= 3 ? 3 : 2;
184
+ case "Apple_Terminal":
185
+ return 2;
186
+ }
187
+ }
188
+ if (/-256(color)?$/i.test(env2.TERM)) {
189
+ return 2;
190
+ }
191
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
192
+ return 1;
193
+ }
194
+ if ("COLORTERM" in env2) {
195
+ return 1;
196
+ }
197
+ return min;
198
+ }
199
+ function getSupportLevel(stream) {
200
+ const level = supportsColor2(stream, stream && stream.isTTY);
201
+ return translateLevel2(level);
202
+ }
203
+ module.exports = {
204
+ supportsColor: getSupportLevel,
205
+ stdout: translateLevel2(supportsColor2(true, tty2.isatty(1))),
206
+ stderr: translateLevel2(supportsColor2(true, tty2.isatty(2)))
207
+ };
208
+ }
209
+ });
210
+
211
+ // node_modules/.pnpm/supports-hyperlinks@3.2.0/node_modules/supports-hyperlinks/index.js
212
+ var require_supports_hyperlinks = __commonJS({
213
+ "node_modules/.pnpm/supports-hyperlinks@3.2.0/node_modules/supports-hyperlinks/index.js"(exports, module) {
214
+ "use strict";
215
+ var supportsColor2 = require_supports_color();
216
+ var hasFlag2 = require_has_flag();
217
+ function parseVersion(versionString) {
218
+ if (/^\d{3,4}$/.test(versionString)) {
219
+ const m = /(\d{1,2})(\d{2})/.exec(versionString) || [];
220
+ return {
221
+ major: 0,
222
+ minor: parseInt(m[1], 10),
223
+ patch: parseInt(m[2], 10)
224
+ };
225
+ }
226
+ const versions = (versionString || "").split(".").map((n) => parseInt(n, 10));
227
+ return {
228
+ major: versions[0],
229
+ minor: versions[1],
230
+ patch: versions[2]
231
+ };
232
+ }
233
+ function supportsHyperlink(stream) {
234
+ const {
235
+ CI,
236
+ FORCE_HYPERLINK,
237
+ NETLIFY,
238
+ TEAMCITY_VERSION,
239
+ TERM_PROGRAM,
240
+ TERM_PROGRAM_VERSION,
241
+ VTE_VERSION,
242
+ TERM
243
+ } = process.env;
244
+ if (FORCE_HYPERLINK) {
245
+ return !(FORCE_HYPERLINK.length > 0 && parseInt(FORCE_HYPERLINK, 10) === 0);
246
+ }
247
+ if (hasFlag2("no-hyperlink") || hasFlag2("no-hyperlinks") || hasFlag2("hyperlink=false") || hasFlag2("hyperlink=never")) {
248
+ return false;
249
+ }
250
+ if (hasFlag2("hyperlink=true") || hasFlag2("hyperlink=always")) {
251
+ return true;
252
+ }
253
+ if (NETLIFY) {
254
+ return true;
255
+ }
256
+ if (!supportsColor2.supportsColor(stream)) {
257
+ return false;
258
+ }
259
+ if (stream && !stream.isTTY) {
260
+ return false;
261
+ }
262
+ if ("WT_SESSION" in process.env) {
263
+ return true;
264
+ }
265
+ if (process.platform === "win32") {
266
+ return false;
267
+ }
268
+ if (CI) {
269
+ return false;
270
+ }
271
+ if (TEAMCITY_VERSION) {
272
+ return false;
273
+ }
274
+ if (TERM_PROGRAM) {
275
+ const version = parseVersion(TERM_PROGRAM_VERSION || "");
276
+ switch (TERM_PROGRAM) {
277
+ case "iTerm.app":
278
+ if (version.major === 3) {
279
+ return version.minor >= 1;
280
+ }
281
+ return version.major > 3;
282
+ case "WezTerm":
283
+ return version.major >= 20200620;
284
+ case "vscode":
285
+ return version.major > 1 || version.major === 1 && version.minor >= 72;
286
+ case "ghostty":
287
+ return true;
288
+ }
289
+ }
290
+ if (VTE_VERSION) {
291
+ if (VTE_VERSION === "0.50.0") {
292
+ return false;
293
+ }
294
+ const version = parseVersion(VTE_VERSION);
295
+ return version.major > 0 || version.minor >= 50;
296
+ }
297
+ switch (TERM) {
298
+ case "alacritty":
299
+ return true;
300
+ }
301
+ return false;
302
+ }
303
+ module.exports = {
304
+ supportsHyperlink,
305
+ stdout: supportsHyperlink(process.stdout),
306
+ stderr: supportsHyperlink(process.stderr)
307
+ };
308
+ }
309
+ });
310
+
311
+ // src/agent/busyqueue.ts
312
+ function queuedMessage(content, images, answers) {
313
+ if (!content) return null;
314
+ const live = images.filter((img) => content.includes(img.marker));
315
+ return { content, ...live.length > 0 ? { images: live } : {}, answers };
316
+ }
317
+ function canDrain(state) {
318
+ return state.idle && !state.dialogOpen && !state.resuming && !state.replaying && !state.preparing;
319
+ }
320
+ function takeNext(queue) {
321
+ if (queue.length === 0) return null;
322
+ const [next, ...rest] = queue;
323
+ return { next, rest };
324
+ }
325
+ function queuedPreview(msg) {
326
+ const [firstLine = "", ...rest] = msg.content.split("\n");
327
+ const more = rest.filter((line) => line.trim() !== "").length;
328
+ const fold = more > 0 ? ` (+${more} ${more === 1 ? "line" : "lines"})` : "";
329
+ const imageHint = msg.images?.length ? " [image]" : "";
330
+ return `${firstLine}${fold}${imageHint}`;
331
+ }
332
+ function queueReceipt(msg) {
333
+ const tag = msg.images?.length ? "[Queued] [image]" : "[Queued]";
334
+ const sep = msg.content.includes("\n") ? "\n" : " ";
335
+ return `${tag}${sep}${msg.content}`;
336
+ }
337
+
338
+ // src/agent/frozenstream.ts
339
+ var FROZEN_STREAM_CHARS = 16e3;
340
+ function frozenStreamMessage(stream) {
341
+ const reasoning = stream.reasoning.trim();
342
+ const content = stream.content.trim();
343
+ if (!reasoning && !content) return null;
344
+ return {
345
+ role: "assistant",
346
+ content: content.slice(-FROZEN_STREAM_CHARS),
347
+ ...reasoning ? { reasoning: reasoning.slice(-FROZEN_STREAM_CHARS) } : {},
348
+ discarded: stream.note ? "note" : "stream",
349
+ ...stream.nested ? { nested: true } : {}
350
+ };
351
+ }
352
+
353
+ // src/agent/launchnotices.ts
354
+ var OFFLINE_NOTICE = "No network \u2014 search and fetch_url tools are off for this session. Restart Reika once you are back online to get them back.";
355
+ function buildLaunchNotices(input) {
356
+ const { facts, config, mode, defaultMode, profile } = input;
357
+ const notices = [];
358
+ const say = (content, tone) => {
359
+ notices.push({ role: "system", content, ...tone ? { tone } : {}, skipAutosave: true });
360
+ };
361
+ const resumed = [
362
+ ...mode !== defaultMode ? [`${mode} mode`] : [],
363
+ ...profile !== "default" ? [`profile '${profile}' (${facts.model})`] : []
364
+ ];
365
+ if (resumed.length > 0) say(`Resumed ${resumed.join(" and ")} from the last session.`);
366
+ if (facts.limitsNotice) say(facts.limitsNotice);
367
+ if (facts.windowNotice) say(facts.windowNotice, "warn");
368
+ if (facts.budgetWarning) say(facts.budgetWarning, "warn");
369
+ if (facts.offline) say(OFFLINE_NOTICE, "warn");
370
+ if (facts.searchNotice) say(facts.searchNotice, "info");
371
+ for (const problem of config.modeModelErrors ?? []) say(problem, "warn");
372
+ if (config.projectEnvNotice) say(config.projectEnvNotice, "warn");
373
+ for (const notice of facts.mcpNotices) say(notice, notice.startsWith("MCP: ") ? "info" : "warn");
374
+ return notices;
375
+ }
376
+
377
+ // src/agent/warm.ts
378
+ var USER_MSG_ALLOWANCE_TOKENS = 512;
379
+ function warmEnabled() {
380
+ return process.env.REIKA_WARM === "1";
381
+ }
382
+ function warmKey(ctx) {
383
+ const last = ctx.history[ctx.history.length - 1];
384
+ const lastLen = !last ? 0 : last.role === "tool" ? last.summary.length : "content" in last ? last.content.length : 0;
385
+ const fingerprint = last ? `${last.role}:${lastLen}` : "empty";
386
+ return [
387
+ // Minimal, grind and norefine ride in the key beside promptMode, not folded into it: agent,
388
+ // minimal and grind all send promptMode 'agent', and plan and vibe's plan phase BOTH send
389
+ // 'plan', so without the tags they would share a key and a mode switch would serve a warm built
390
+ // from the other one's prefix — a guaranteed miss, and a silent one.
391
+ [
392
+ ctx.promptMode,
393
+ ctx.minimalPrompt ? "minimal" : ctx.grindPrompt ? "grind" : "",
394
+ ctx.allowRefine === false ? "norefine" : ""
395
+ ].filter(Boolean).join("+"),
396
+ ctx.config.model,
397
+ ctx.config.baseURL,
398
+ ctx.bundle.hash,
399
+ ctx.history.length,
400
+ fingerprint
401
+ ].join("\0");
402
+ }
403
+ function buildWarmPayload(ctx) {
404
+ const history = ctx.history.slice();
405
+ const system = buildRoundZeroPrefix({
406
+ history,
407
+ bundle: ctx.bundle,
408
+ promptMode: ctx.promptMode,
409
+ minimalPrompt: ctx.minimalPrompt,
410
+ grindPrompt: ctx.grindPrompt,
411
+ allowRefine: ctx.allowRefine,
412
+ sandbox: ctx.config.sandbox,
413
+ unattended: ctx.config.unattended,
414
+ tools: ctx.tools,
415
+ contextWindow: ctx.config.contextWindow,
416
+ calibration: ctx.calibration,
417
+ minGenTokens: ctx.config.minGenTokens
418
+ });
419
+ return { system, history };
420
+ }
421
+ function shouldSkipWarm(ctx, system, history) {
422
+ if (!ctx.config.contextWindow) return null;
423
+ const estimate = estimateRequestTokens(system, history, ctx.tools, {
424
+ contextWindow: ctx.config.contextWindow,
425
+ calibration: ctx.calibration,
426
+ reasoningRounds: ctx.config.reasoningRounds,
427
+ minGenTokens: ctx.config.minGenTokens,
428
+ prefixStable: prefixStableActive(ctx.config.contextWindow),
429
+ latches: latchesFor(ctx.config)
430
+ });
431
+ const projected = (estimate + USER_MSG_ALLOWANCE_TOKENS) * ctx.calibration;
432
+ if (shouldCompact(projected, ctx.config.contextWindow, ctx.config.minGenTokens)) {
433
+ return "near-compaction";
434
+ }
435
+ return null;
436
+ }
437
+ function createPrefixWarmer() {
438
+ let inflight = null;
439
+ let completedKey = null;
440
+ return {
441
+ onEdge(ctx) {
442
+ try {
443
+ if (!warmEnabled()) return;
444
+ const key = warmKey(ctx);
445
+ if (key === completedKey || key === inflight?.key) {
446
+ debugLog(`[reika:debug] warm skipped reason=dup mode=${ctx.promptMode}`);
447
+ return;
448
+ }
449
+ if (inflight) {
450
+ inflight.controller.abort();
451
+ inflight = null;
452
+ }
453
+ const { system, history } = buildWarmPayload(ctx);
454
+ const skip = shouldSkipWarm(ctx, system, history);
455
+ if (skip) {
456
+ debugLog(`[reika:debug] warm skipped reason=${skip} mode=${ctx.promptMode}`);
457
+ return;
458
+ }
459
+ const controller = new AbortController();
460
+ inflight = { key, controller };
461
+ const started = Date.now();
462
+ debugLog(
463
+ `[reika:debug] warm fired mode=${ctx.promptMode} model=${ctx.config.model} histLen=${history.length}`
464
+ );
465
+ void callModel({
466
+ system,
467
+ history,
468
+ tools: ctx.tools,
469
+ config: ctx.config,
470
+ calibration: ctx.calibration,
471
+ maxTokens: 1,
472
+ signal: controller.signal,
473
+ prefixStable: prefixStableActive(ctx.config.contextWindow),
474
+ stampRenders: false
475
+ }).then((res) => {
476
+ if (inflight?.controller === controller) inflight = null;
477
+ if (controller.signal.aborted) {
478
+ debugLog(`[reika:debug] warm aborted ms=${Date.now() - started}`);
479
+ return;
480
+ }
481
+ completedKey = key;
482
+ debugLog(
483
+ `[reika:debug] warm completed promptTokens=${res.usage?.promptTokens ?? "?"} cached=${res.usage?.cachedTokens ?? "?"} ms=${Date.now() - started}`
484
+ );
485
+ }).catch((e) => {
486
+ if (inflight?.controller === controller) inflight = null;
487
+ debugLog(`[reika:debug] warm failed err=${e instanceof Error ? e.message : e}`);
488
+ });
489
+ } catch (e) {
490
+ inflight = null;
491
+ debugLog(`[reika:debug] warm failed err=${e instanceof Error ? e.message : e}`);
492
+ }
493
+ },
494
+ cancel(reason) {
495
+ if (!inflight) return;
496
+ inflight.controller.abort();
497
+ inflight = null;
498
+ debugLog(`[reika:debug] warm cancel reason=${reason}`);
499
+ }
500
+ };
501
+ }
502
+
503
+ // src/agent/imageattach.ts
504
+ function imageReadLabel(config) {
505
+ if (config && pasteIsNative(config)) return null;
506
+ return config?.visionModel ? `Describing image with ${config.visionModel}` : "Extracting text";
507
+ }
508
+ async function readImageAttachment(bytes, config, origin) {
509
+ if (config && pasteIsNative(config)) {
510
+ return {
511
+ ok: true,
512
+ text: NATIVE_IMAGE_NOTE,
513
+ native: { bytes, mime: sniffImageMime(bytes) },
514
+ detail: `sent to ${config.model} as an image`
515
+ };
516
+ }
517
+ const result = await (config ? imageReader(config) : systemOcr())(bytes);
518
+ if (!result.ok) {
519
+ return {
520
+ ok: false,
521
+ notice: result.reason === "unavailable" ? "Image paste needs system OCR \u2014 macOS and Windows only." : result.reason === "no-text" ? "No text found in the pasted image." : `Couldn't read the pasted image: ${result.detail ?? "OCR failed"}`
522
+ };
523
+ }
524
+ const vision = config?.visionModel;
525
+ return {
526
+ ok: true,
527
+ text: result.text,
528
+ detail: vision ? `${result.text.length} chars described by ${vision}` : `${result.text.length} chars read from the ${origin}`
529
+ };
530
+ }
531
+
532
+ // src/ui/warmtrigger.ts
533
+ function isWarmableInput(value) {
534
+ if (value === "") return false;
535
+ if (value.startsWith("/") || value.startsWith("@")) return false;
536
+ return !hasPasteMarker(value) && !hasImageMarker(value) && !hasBareImagePath(value);
537
+ }
538
+ function isWarmEdge(previous, next) {
539
+ return !isWarmableInput(previous) && isWarmableInput(next);
540
+ }
541
+
542
+ // src/ui/summary.ts
543
+ function buildSummary(messages, usage, startedAt, approvals) {
544
+ const elapsed = Math.floor((Date.now() - startedAt) / 1e3);
545
+ const userTurns = messages.filter((m) => m.role === "user" && !m.nested && !m.meta).length;
546
+ const assistantTurns = messages.filter(
547
+ (m) => m.role === "assistant" && !m.nested && !m.compactionNote && !m.discarded
548
+ ).length;
549
+ const toolCounts = {};
550
+ const files = /* @__PURE__ */ new Set();
551
+ for (const m of messages) {
552
+ if (m.role === "tool" && m.changes) {
553
+ for (const f of m.changes.files) files.add(f.path);
554
+ continue;
555
+ }
556
+ if (m.role !== "assistant" || !m.toolCalls) continue;
557
+ for (const tc of m.toolCalls) {
558
+ toolCounts[tc.name] = (toolCounts[tc.name] ?? 0) + 1;
559
+ if (tc.name === "edit" || tc.name === "write") {
560
+ const p = tc.args.path;
561
+ if (typeof p === "string") files.add(p);
562
+ }
563
+ }
564
+ }
565
+ const totalTools = Object.values(toolCounts).reduce((a, b) => a + b, 0);
566
+ const subagentCount = toolCounts.subagent ?? 0;
567
+ const breakdownEntries = Object.entries(toolCounts).sort((a, b) => b[1] - a[1]).map(([n, c]) => `${c} ${n}`);
568
+ const breakdown = breakdownEntries.length > 0 ? ` (${breakdownEntries.join(", ")})` : "";
569
+ const filesText = files.size === 0 ? "(none)" : Array.from(files).sort().map((f) => scrubPaths(f)).join(", ");
570
+ const approx = usage.estimated ? "~" : "";
571
+ return [
572
+ "Session summary",
573
+ "\u2500".repeat(40),
574
+ `Duration: ${formatElapsed(elapsed)}`,
575
+ `Turns: ${userTurns} user \xB7 ${assistantTurns} assistant`,
576
+ `Tools: ${totalTools}${breakdown}`,
577
+ `Subagents: ${subagentCount}`,
578
+ `Tokens: ${approx}${usage.promptTokens.toLocaleString()} \u2191 ${approx}${usage.completionTokens.toLocaleString()} \u2193`,
579
+ ...usage.cachedTokens && usage.promptTokens > 0 ? [
580
+ `Cache hits: ${usage.cachedTokens.toLocaleString()} (${Math.round(
581
+ usage.cachedTokens / usage.promptTokens * 100
582
+ )}% of prompt)`
583
+ ] : [],
584
+ `Files modified: ${filesText}`,
585
+ `Approvals: ${approvals.approved} approved, ${approvals.declined} declined`
586
+ ].join("\n");
587
+ }
588
+ function hasActivity(messages) {
589
+ return messages.some((m) => m.role === "user" && !m.nested && !m.meta);
590
+ }
591
+
592
+ // src/agent/replycommands.ts
593
+ function resolveReplyCommand(name, ctx) {
594
+ switch (name) {
595
+ case "help":
596
+ return helpText(ctx.helpKeys);
597
+ case "cwd":
598
+ return ctx.cwd ?? "(unknown)";
599
+ case "tokens": {
600
+ const approx = ctx.usage.estimated ? "~" : "";
601
+ return `prompt: ${approx}${ctx.usage.promptTokens}
602
+ completion: ${approx}${ctx.usage.completionTokens}`;
603
+ }
604
+ case "stats":
605
+ return hasActivity(ctx.messages) ? buildSummary(ctx.messages, ctx.usage, ctx.startedAt, ctx.approvals) : "No activity yet.";
606
+ case "skills":
607
+ return skillsText(ctx.skills);
608
+ case "mcp":
609
+ return ctx.mcpList() ?? "MCP is not available in this session.";
610
+ default:
611
+ return null;
612
+ }
613
+ }
614
+ function unknownCommandText(name) {
615
+ return `Unknown command: /${name}. Try /help.`;
616
+ }
617
+ function skillsText(skills) {
618
+ if (skills.length === 0) {
619
+ return "No skills loaded. Drop *.md files or SKILL.md folders in ~/.config/reika/skills/, <cwd>/.reika/skills/, ~/.agents/skills/ or <cwd>/.agents/skills/.";
620
+ }
621
+ return [
622
+ "Available skills (invoke as /<name>):",
623
+ ...skills.map(
624
+ (s) => ` /${s.name.padEnd(16)} ${s.description} ${s.from ? `(${s.from})` : s.source === "project" ? "(project)" : ""}`
625
+ )
626
+ ].join("\n");
627
+ }
628
+ var TUI_HELP_KEYS = [
629
+ " ctrl-v paste an image; its text is read out and attached (macOS/Windows)",
630
+ " shift+tab cycle mode (agent \u2192 plan \u2192 minimal \u2192 vibe \u2192 grind \u2192 chat \u2192 shell)"
631
+ ];
632
+ function helpText(keys = TUI_HELP_KEYS) {
633
+ return [
634
+ "Commands:",
635
+ " /help show this list",
636
+ " /new, /clear reset conversation, tokens, mode",
637
+ " /cd <path> change cwd (re-indexes repo map)",
638
+ " /shell enter shell mode (raw bash, no model)",
639
+ " /chat enter chat mode (no filesystem/shell tools; isolated)",
640
+ " /plan enter plan mode (read-only exploration; ends with a written plan)",
641
+ " /vibe enter vibe mode (every prompt plans first, then implements)",
642
+ " /minimal enter minimal mode (shell only, no upfront project context)",
643
+ " /grind enter grind mode (verify-everything procedure; slower, checks its work)",
644
+ " /agent return to agent mode",
645
+ " /implement execute the plan above (from plan mode: pick the mode to run it in)",
646
+ " /compact compact older context now (compaction note, then a fold)",
647
+ " /model [name] pick a model/profile (interactive without a name; a name not in your config switches ad-hoc)",
648
+ " /anon show/toggle anonymized display (on|off; bare command opens the picker)",
649
+ " /approvals show/toggle session auto-approve (on|off; bare command opens the picker)",
650
+ " /unattended show/toggle unattended: decline instead of prompting (on|off; bare command opens the picker)",
651
+ " /cwd show working directory",
652
+ " /tokens show token usage this session",
653
+ " /stats show full session summary",
654
+ " /save save the full conversation to history, even mid-turn (--raw skips redaction)",
655
+ " /resume [all|root] resume a saved session of this project (chat mode: chats only; all: every session; root: the /save files)",
656
+ " /skills list available skills (loaded from your skill directories)",
657
+ " /mcp list MCP servers and their tools (REIKA_MCP_SERVERS)",
658
+ " /<server>:<tool> call an MCP tool directly (JSON args, or the bare string for a one-arg tool)",
659
+ " /search <query> search the web: the model runs one search and answers from the results",
660
+ " /exit, /quit exit reika (prints summary)",
661
+ " @<path> in agent mode, inline a file as context",
662
+ ...keys
663
+ ].join("\n");
664
+ }
665
+
666
+ // src/agent/shellruns.ts
667
+ var SHELL_RUN_MIN_CHARS = 1024;
668
+ var SHELL_RUN_MAX_CHARS = 4096;
669
+ var WINDOW_DIVISOR = 16;
670
+ var MAX_HELD_SHELL_RUNS = 12;
671
+ var MIN_TAIL_CHARS = 160;
672
+ var MAX_COMMAND_CHARS = 300;
673
+ function shellRunBudget(contextWindow) {
674
+ const perRun = contextWindow ? Math.min(
675
+ SHELL_RUN_MAX_CHARS,
676
+ Math.max(SHELL_RUN_MIN_CHARS, Math.round(contextWindow / WINDOW_DIVISOR))
677
+ ) : SHELL_RUN_MIN_CHARS;
678
+ return { perRun, total: perRun * 2 };
679
+ }
680
+ async function captureShellRun(command, exitCode, output) {
681
+ const spill = output.length > SHELL_RUN_MIN_CHARS ? await spillResult("shell", output) ?? void 0 : void 0;
682
+ return { command, exitCode, output, ...spill ? { spill } : {} };
683
+ }
684
+ function holdShellRun(held, run2) {
685
+ return [...held, run2].slice(-MAX_HELD_SHELL_RUNS);
686
+ }
687
+ function buildShellRunsBlock(runs, budget) {
688
+ if (runs.length === 0) return "";
689
+ let remaining = budget.total;
690
+ const shares = new Array(runs.length).fill(0);
691
+ for (let i = runs.length - 1; i >= 0; i--) {
692
+ const share = Math.min(budget.perRun, remaining, runs[i].output.trimEnd().length);
693
+ if (share < MIN_TAIL_CHARS && share < runs[i].output.trimEnd().length) continue;
694
+ shares[i] = share;
695
+ remaining -= share;
696
+ }
697
+ const parts = [
698
+ "<shell-runs>",
699
+ "The user ran these commands themselves in shell mode before this message. They are context, not a request."
700
+ ];
701
+ runs.forEach((run2, i) => parts.push(renderRun(run2, shares[i])));
702
+ parts.push("</shell-runs>");
703
+ return parts.join("\n");
704
+ }
705
+ function renderRun(run2, share) {
706
+ const command = run2.command.length > MAX_COMMAND_CHARS ? `${run2.command.slice(0, MAX_COMMAND_CHARS)}\u2026` : run2.command;
707
+ const status = run2.exitCode === null ? "killed" : `exit ${run2.exitCode}`;
708
+ const lines = [`$ ${command} (${status})`];
709
+ const output = run2.output.trimEnd();
710
+ if (!output) {
711
+ lines.push("(no output)");
712
+ return lines.join("\n");
713
+ }
714
+ if (share === 0) {
715
+ lines.push(`(${output.length} chars of output omitted${locator(run2)})`);
716
+ return lines.join("\n");
717
+ }
718
+ if (output.length <= share) {
719
+ lines.push(output);
720
+ return lines.join("\n");
721
+ }
722
+ const slice = output.slice(-share);
723
+ const nl = slice.indexOf("\n");
724
+ const tail = nl >= 0 && nl < slice.length - 1 ? slice.slice(nl + 1) : slice;
725
+ lines.push(`\u2026(earlier output omitted${locator(run2)})`, tail);
726
+ return lines.join("\n");
727
+ }
728
+ function locator(run2) {
729
+ return run2.spill ? `; full output saved to ${run2.spill.path}, read it with offset/limit` : "";
730
+ }
731
+
732
+ // src/agent/togglecommands.ts
733
+ function resolveToggleCommand(name, args, ctx) {
734
+ const arg = args.trim().toLowerCase();
735
+ const explicit = arg === "on" || arg === "off";
736
+ if (name === "approvals") {
737
+ if (explicit) {
738
+ if (ctx.autoApproveForced) {
739
+ return {
740
+ kind: "reply",
741
+ content: `auto-approve is forced to '${ctx.configAutoApprove}' by REIKA_AUTO_APPROVE; session toggle has no effect.`
742
+ };
743
+ }
744
+ return { kind: "set", toggle: "approvals", on: arg === "on" };
745
+ }
746
+ if (arg) return unknownArgument("approvals", arg);
747
+ if (!ctx.autoApproveForced) {
748
+ return {
749
+ kind: "ask",
750
+ toggle: "approvals",
751
+ title: "Approvals",
752
+ subtitle: `session auto-approve: ${ctx.autoApprove} \u2014 toggle on or off?`,
753
+ currentlyOn: ctx.autoApprove === "safe"
754
+ };
755
+ }
756
+ const mode = ctx.configAutoApprove ?? "safe";
757
+ return {
758
+ kind: "reply",
759
+ content: [
760
+ `auto-approve: ${mode}`,
761
+ mode === "bypass" ? " bypass \u2014 everything runs without confirmation, including dangerous commands" : " safe \u2014 ordinary actions auto-run; dangerous commands still prompt",
762
+ ` source: REIKA_AUTO_APPROVE=${ctx.configAutoApprove} (env)`,
763
+ ...ctx.unattended ? [" unattended: on \u2014 anything that would prompt is declined instead (/unattended off)"] : [],
764
+ "",
765
+ "env REIKA_AUTO_APPROVE forces this; session toggle is shadowed"
766
+ ].join("\n")
767
+ };
768
+ }
769
+ if (name === "unattended" || name === "anon") {
770
+ if (explicit) return { kind: "set", toggle: name, on: arg === "on" };
771
+ if (arg) return unknownArgument(name, arg);
772
+ const currentlyOn = name === "unattended" ? ctx.unattended : ctx.anon;
773
+ return {
774
+ kind: "ask",
775
+ toggle: name,
776
+ title: name === "unattended" ? "Unattended" : "Anonymize",
777
+ subtitle: `currently ${currentlyOn ? "on" : "off"} \u2014 toggle on or off?`,
778
+ currentlyOn
779
+ };
780
+ }
781
+ return null;
782
+ }
783
+ function unknownArgument(name, arg) {
784
+ return {
785
+ kind: "reply",
786
+ content: `Unknown argument: ${arg}. Use /${name} on or /${name} off.`
787
+ };
788
+ }
789
+ function toggleReceipt(toggle, on, identity) {
790
+ if (toggle === "approvals") return `Session auto-approve: ${on ? "on" : "off"}`;
791
+ if (toggle === "unattended") {
792
+ return on ? "unattended: on \u2014 anything that would prompt is declined and listed at turn end; questions go unanswered. /unattended off to approve again." : "unattended: off \u2014 approvals and questions prompt again.";
793
+ }
794
+ if (!on) return "anonymize: off \u2014 names, emails and account slugs render verbatim again";
795
+ const names = identity?.names ?? 0;
796
+ const emails = identity?.emails ?? 0;
797
+ return [
798
+ "anonymize: on",
799
+ names + emails === 0 ? " no identity found (no git config, no remote) \u2014 nothing to substitute" : ` substituting ${names} name(s) \u2192 <user>, ${emails} email(s) \u2192 <email>`,
800
+ // Rows already on screen are not redrawn, while a save re-serializes everything, so it is
801
+ // retroactive. Said here, or the untouched lines above read as a bug.
802
+ " applies to new output and to /save; run /clear to scrub what is above"
803
+ ].join("\n");
804
+ }
805
+
806
+ // src/controller.ts
807
+ import { homedir } from "node:os";
808
+ import { basename, dirname, isAbsolute, resolve } from "node:path";
809
+
810
+ // src/ui/models.ts
811
+ function buildModelTargets(config, activeProfile) {
812
+ const modelKeys = config.models.map((m) => m.toLowerCase());
813
+ const targets = config.models.map((m, i) => {
814
+ const key = m.toLowerCase();
815
+ const profile = config.profiles[key] ?? config.profiles.default;
816
+ return {
817
+ name: config.profiles[key] ? key : "default",
818
+ model: m,
819
+ baseURL: profile.baseURL,
820
+ kind: "model",
821
+ active: activeProfile === key || activeProfile === "default" && i === 0
822
+ };
823
+ });
824
+ for (const [name, p] of Object.entries(config.profiles)) {
825
+ if (name === "default" || modelKeys.includes(name)) continue;
826
+ targets.push({
827
+ name,
828
+ model: p.model,
829
+ baseURL: p.baseURL,
830
+ kind: "profile",
831
+ active: name === activeProfile,
832
+ ...p.adhoc ? { adhoc: true } : {},
833
+ ...p.group ? { group: p.group } : {}
834
+ });
835
+ }
836
+ return targets;
837
+ }
838
+
839
+ // src/ui/suggest.ts
840
+ var MAX_FILE_SUGGESTIONS = 8;
841
+ function computeSuggestions(value, fileIndex, skills = [], modelTargets = []) {
842
+ if (value.startsWith("/") && !value.includes(" ") && !value.includes("\n")) {
843
+ const partial = value.slice(1).toLowerCase();
844
+ const builtIns = COMMANDS.filter((c) => c.name.startsWith(partial)).map((c) => ({
845
+ value: `/${c.name}`,
846
+ display: `/${c.name} \u2014 ${c.desc}`
847
+ }));
848
+ const builtInNames = new Set(COMMANDS.map((c) => c.name));
849
+ const skillItems = skills.filter((s) => !builtInNames.has(s.name) && s.name.startsWith(partial)).map((s) => ({
850
+ value: `/${s.name}`,
851
+ display: `/${s.name} \u2014 ${s.description}`
852
+ }));
853
+ const items = [...builtIns, ...skillItems];
854
+ if (items.length === 0) return null;
855
+ return { kind: "command", items, partial: value };
856
+ }
857
+ const modelArg = /^\/model +(\S*)$/i.exec(value);
858
+ if (modelArg) {
859
+ const partial = modelArg[1].toLowerCase();
860
+ const items = modelTargets.filter(
861
+ (t) => t.name.startsWith(partial) || t.model.toLowerCase().startsWith(partial) || (t.group?.startsWith(partial) ?? false)
862
+ ).map((t) => ({
863
+ value: `/model ${t.name}`,
864
+ // Auto-registered model entries have name === lowercased model — the
865
+ // mapping suffix would just repeat the key, so it's only shown when
866
+ // the name doesn't already say which model you'd get. An extra says
867
+ // which profile it belongs to instead — the picker's `go → b`.
868
+ display: t.group ? `/model ${t.name} (${t.group})` : t.name === t.model.toLowerCase() ? `/model ${t.name}` : `/model ${t.name} \u2014 ${t.model}`
869
+ }));
870
+ if (items.length === 0) return null;
871
+ return { kind: "command", items, partial: value };
872
+ }
873
+ const mention = /@(\S*)$/.exec(value);
874
+ if (mention) {
875
+ const partial = mention[1];
876
+ const matched = matchFiles(fileIndex, partial);
877
+ if (matched.length === 0) return null;
878
+ return {
879
+ kind: "file",
880
+ items: matched.map((f) => ({ value: `@${f}`, display: f })),
881
+ partial: "@" + partial
882
+ };
883
+ }
884
+ return null;
885
+ }
886
+ function acceptSuggestion(value, selected, partial) {
887
+ return value.slice(0, value.length - partial.length) + selected.value;
888
+ }
889
+ function matchFiles(files, partial) {
890
+ if (!partial) return files.slice(0, MAX_FILE_SUGGESTIONS);
891
+ const lower = partial.toLowerCase();
892
+ const hits = [];
893
+ for (const file of files) {
894
+ const baseStart = file.lastIndexOf("/") + 1;
895
+ const basename2 = file.slice(baseStart).toLowerCase();
896
+ const fullLower = file.toLowerCase();
897
+ let score = 0;
898
+ if (basename2.startsWith(lower)) score = 3;
899
+ else if (basename2.includes(lower)) score = 2;
900
+ else if (fullLower.includes(lower)) score = 1;
901
+ if (score > 0) hits.push({ file, score });
902
+ if (hits.length >= 200) break;
903
+ }
904
+ hits.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
905
+ return hits.slice(0, MAX_FILE_SUGGESTIONS).map((h) => h.file);
906
+ }
907
+
908
+ // src/ui/pr.ts
909
+ import { execFile } from "node:child_process";
910
+ var GIT_TIMEOUT_MS = 2e3;
911
+ var GH_TIMEOUT_MS = 4e3;
912
+ var MISS_TTL_MS = 6e4;
913
+ var HIT_TTL_MS = 3e5;
914
+ var cache = /* @__PURE__ */ new Map();
915
+ async function resolvePr(cwd, now) {
916
+ const branch = await currentBranch(cwd);
917
+ if (!branch) return null;
918
+ const hit = cache.get(branch);
919
+ if (hit && isFresh(hit, now)) return hit.pr;
920
+ const pr = await lookupPr(cwd, branch);
921
+ cache.set(branch, { pr, at: now });
922
+ return pr;
923
+ }
924
+ function isFresh(entry, now) {
925
+ return now - entry.at < (entry.pr == null ? MISS_TTL_MS : HIT_TTL_MS);
926
+ }
927
+ async function currentBranch(cwd) {
928
+ const out = await run("git", ["branch", "--show-current"], cwd, GIT_TIMEOUT_MS);
929
+ return out?.trim() || null;
930
+ }
931
+ async function lookupPr(cwd, branch) {
932
+ const out = await run(
933
+ "gh",
934
+ ["pr", "view", branch, "--json", "number,state,isDraft,url"],
935
+ cwd,
936
+ GH_TIMEOUT_MS
937
+ );
938
+ return out ? parsePrView(out) : null;
939
+ }
940
+ function parsePrView(stdout) {
941
+ try {
942
+ const data = JSON.parse(stdout);
943
+ if (typeof data.number !== "number") return null;
944
+ const state = typeof data.state === "string" ? data.state.toUpperCase() : "OPEN";
945
+ if (state !== "OPEN" && state !== "MERGED") return null;
946
+ const url = typeof data.url === "string" && data.url ? data.url : void 0;
947
+ const pr = url ? { number: data.number, url } : { number: data.number };
948
+ if (state === "MERGED") pr.state = "merged";
949
+ else if (data.isDraft === true) pr.state = "draft";
950
+ return pr;
951
+ } catch {
952
+ return null;
953
+ }
954
+ }
955
+ function run(cmd, args, cwd, timeoutMs) {
956
+ return new Promise((resolve2) => {
957
+ execFile(cmd, args, { cwd, timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
958
+ resolve2(err ? null : stdout);
959
+ });
960
+ });
961
+ }
962
+
963
+ // src/controller.ts
964
+ var AUTOSAVE_INTERVAL_MS = 3e3;
965
+ var PR_POLL_MS = 15e3;
966
+ var MAX_HISTORY_ENTRIES = 500;
967
+ var MAX_HISTORY_CHARS = 2e6;
968
+ function expandHome(p) {
969
+ if (p === "~") return homedir();
970
+ if (p.startsWith("~/")) return resolve(homedir(), p.slice(2));
971
+ return p;
972
+ }
973
+ function emptyLive() {
974
+ return {
975
+ phase: null,
976
+ content: "",
977
+ reasoning: "",
978
+ tool: null,
979
+ pending: null,
980
+ plan: null,
981
+ usage: null,
982
+ subagent: false,
983
+ note: false,
984
+ typechecking: false,
985
+ recovering: false,
986
+ promptProgress: null,
987
+ looping: false
988
+ };
989
+ }
990
+ function createController(opts) {
991
+ const now = opts.now ?? (() => Date.now());
992
+ let snapshot = {
993
+ messages: [],
994
+ mode: opts.mode,
995
+ status: "loading",
996
+ queue: [],
997
+ replaying: false,
998
+ history: [],
999
+ preparing: false,
1000
+ approval: null,
1001
+ question: null,
1002
+ confirm: null,
1003
+ approvals: { approved: 0, declined: 0 },
1004
+ sessionAutoApprove: null,
1005
+ sessionUnattended: null,
1006
+ error: null,
1007
+ usage: { promptTokens: 0, completionTokens: 0 },
1008
+ lastUsage: null,
1009
+ estimatedContext: null,
1010
+ shrink: { sheds: 0, folds: 0 },
1011
+ decodeRate: void 0,
1012
+ pr: null
1013
+ };
1014
+ let shrinkEvents = [];
1015
+ let unattendedDeclines = [];
1016
+ let resolveApproval = null;
1017
+ let resolveQuestion = null;
1018
+ let resolveConfirm = null;
1019
+ const waitingConfirms = [];
1020
+ let stashed = {};
1021
+ let session = null;
1022
+ const warmer = createPrefixWarmer();
1023
+ let ownProfile = "default";
1024
+ let modelPinned = false;
1025
+ let startedAt = Date.now();
1026
+ let conversation = 0;
1027
+ let stopped = false;
1028
+ let sessionPath = null;
1029
+ let stemClaimed = false;
1030
+ let saveTimer = null;
1031
+ let saveQueued = false;
1032
+ let saveChain = Promise.resolve();
1033
+ let saveFailed = false;
1034
+ let saveHold = null;
1035
+ const historyRoot = opts.historyRoot ?? ROOT_HISTORY_DIR;
1036
+ const listeners = /* @__PURE__ */ new Set();
1037
+ let aborter = null;
1038
+ let heldShellRuns = [];
1039
+ const hintedSkills = /* @__PURE__ */ new Set();
1040
+ let submitting = false;
1041
+ let live = emptyLive();
1042
+ let callsStarted = 0;
1043
+ const liveListeners = /* @__PURE__ */ new Set();
1044
+ const notifyLive = (change) => {
1045
+ for (const listener of [...liveListeners]) {
1046
+ try {
1047
+ listener(change);
1048
+ } catch {
1049
+ liveListeners.delete(listener);
1050
+ }
1051
+ }
1052
+ };
1053
+ const setLive = (next) => {
1054
+ live = { ...live, ...next };
1055
+ notifyLive({ type: "live" });
1056
+ };
1057
+ const pendingHidden = () => snapshot.approval !== null || snapshot.question !== null;
1058
+ const liveToolProgress = (chunk, name) => {
1059
+ if (live.tool && live.tool.name === name) {
1060
+ live = { ...live, tool: { name, output: live.tool.output + chunk } };
1061
+ notifyLive({ type: "delta", channel: "tool", text: chunk });
1062
+ return;
1063
+ }
1064
+ setLive({ tool: { name, output: chunk } });
1065
+ };
1066
+ const set = (next) => {
1067
+ const hiddenBefore = pendingHidden();
1068
+ snapshot = { ...snapshot, ...next };
1069
+ for (const listener of listeners) listener();
1070
+ if (live.pending && hiddenBefore !== pendingHidden()) notifyLive({ type: "live" });
1071
+ if ("messages" in next || "status" in next) saveSoon();
1072
+ };
1073
+ const bothSides = () => {
1074
+ const onScreen = modeSide(snapshot.mode);
1075
+ const other = onScreen === "chat" ? "agent" : "chat";
1076
+ return { [onScreen]: snapshot.messages, [other]: stashed[other] ?? [] };
1077
+ };
1078
+ const projectDir = () => session ? projectHistoryDir(session.bundle.cwd, opts.historyRoot) : null;
1079
+ const logSessionFile = (path) => debugLog(`[reika:debug] session file=${basename(path)}`);
1080
+ const stopSaveTimer = () => {
1081
+ if (saveTimer !== null) clearTimeout(saveTimer);
1082
+ saveTimer = null;
1083
+ };
1084
+ const saveNow = () => {
1085
+ stopSaveTimer();
1086
+ const dir = projectDir();
1087
+ if (!session || !dir || !session.getSnapshot().config.autosave) return saveChain;
1088
+ const all = bothSides();
1089
+ const saved = { agent: forAutosave(all.agent), chat: forAutosave(all.chat) };
1090
+ const turns = countRealTurns(saved.agent) + countRealTurns(saved.chat);
1091
+ if (turns === 0 || turns <= (saveHold ?? 0)) return saveChain;
1092
+ saveHold = null;
1093
+ if (sessionPath === null) {
1094
+ const stem = stemClaimed ? void 0 : processSessionStem();
1095
+ stemClaimed = true;
1096
+ sessionPath = newSessionPath(dir, /* @__PURE__ */ new Date(), stem);
1097
+ logSessionFile(sessionPath);
1098
+ for (const listener of listeners) listener();
1099
+ }
1100
+ const path = sessionPath;
1101
+ const meta = transcriptMeta(session, saved.agent, snapshot.status === "busy");
1102
+ saveChain = saveChain.then(() => writeSession(path, saved, meta)).catch((e) => {
1103
+ if (saveFailed) return;
1104
+ saveFailed = true;
1105
+ append({
1106
+ role: "system",
1107
+ tone: "warn",
1108
+ content: `auto-save failed: ${e.message} \u2014 /resume won't have this session; /save still works.`
1109
+ });
1110
+ });
1111
+ return saveChain;
1112
+ };
1113
+ const saveSoon = () => {
1114
+ if (saveQueued) return;
1115
+ saveQueued = true;
1116
+ queueMicrotask(() => {
1117
+ saveQueued = false;
1118
+ if (!session?.getSnapshot().config.autosave) return;
1119
+ if (snapshot.status !== "busy" || sessionPath === null) {
1120
+ void saveNow();
1121
+ return;
1122
+ }
1123
+ saveTimer ??= setTimeout(() => {
1124
+ saveTimer = null;
1125
+ void saveNow();
1126
+ }, AUTOSAVE_INTERVAL_MS);
1127
+ });
1128
+ };
1129
+ const freshMeasurements = () => {
1130
+ shrinkEvents = [];
1131
+ return {
1132
+ usage: { promptTokens: 0, completionTokens: 0 },
1133
+ lastUsage: null,
1134
+ estimatedContext: null,
1135
+ shrink: { sheds: 0, folds: 0 }
1136
+ };
1137
+ };
1138
+ const transcriptMeta = (s, msgs, midTurn) => {
1139
+ const cfg = s.getSnapshot().config;
1140
+ const profile = cfg.profiles[s.profile] ?? cfg.profiles.default;
1141
+ return buildTranscriptMeta({
1142
+ msgs,
1143
+ model: profile.model,
1144
+ baseURL: profile.baseURL,
1145
+ cwd: s.bundle.cwd,
1146
+ mode: snapshot.mode,
1147
+ midTurn,
1148
+ status: {
1149
+ totals: snapshot.usage,
1150
+ lastUsage: snapshot.lastUsage,
1151
+ estimatedContext: snapshot.estimatedContext,
1152
+ shrink: s.shrink,
1153
+ shrinkEvents,
1154
+ contextWindow: profile.contextWindow ?? cfg.contextWindow,
1155
+ // The session's reserve is the learned one (#551), the number the next round compacts at.
1156
+ minGenTokens: s.config.minGenTokens ?? profile.minGenTokens
1157
+ }
1158
+ });
1159
+ };
1160
+ const counted = (approved) => ({
1161
+ approved: snapshot.approvals.approved + (approved ? 1 : 0),
1162
+ declined: snapshot.approvals.declined + (approved ? 0 : 1)
1163
+ });
1164
+ const config = () => session?.getSnapshot().config ?? null;
1165
+ const autoApprove = () => effectiveAutoApprove(config(), snapshot.sessionAutoApprove);
1166
+ const unattended = () => snapshot.sessionUnattended ?? config()?.unattended === true;
1167
+ const append = (...messages) => {
1168
+ if (messages.length > 0) set({ messages: [...snapshot.messages, ...messages] });
1169
+ };
1170
+ const switchModel = (target, echo, picked) => {
1171
+ const cfg = config();
1172
+ const next = cfg?.profiles[target];
1173
+ if (!session || !cfg || !next) return;
1174
+ const kind = cfg.models.map((m) => m.toLowerCase()).includes(target) ? "model" : "profile";
1175
+ if (snapshot.decodeRate !== void 0) set({ decodeRate: void 0 });
1176
+ void session.setProfile(target).then((notices) => append(...notices));
1177
+ if (picked) {
1178
+ modelPinned = true;
1179
+ opts.remember({ profile: target });
1180
+ }
1181
+ append(...echo ? [echo] : [], {
1182
+ role: "system",
1183
+ content: next.adhoc ? `Switched to model '${next.model}' \u2014 not in your config; using it anyway on ${next.baseURL}` : `Switched to ${kind} '${target}' (${next.model})`
1184
+ });
1185
+ };
1186
+ const applyModeModel = () => {
1187
+ const cfg = config();
1188
+ if (!session || !cfg || modelPinned) return;
1189
+ const target = modeSwitchProfile(cfg, snapshot.mode, ownProfile);
1190
+ if (!target || target === session.profile || !cfg.profiles[target]) return;
1191
+ switchModel(target, void 0, false);
1192
+ };
1193
+ const setMode = (mode) => {
1194
+ if (mode === snapshot.mode) return;
1195
+ set({ mode });
1196
+ modeChanged();
1197
+ };
1198
+ const modeChanged = () => {
1199
+ const persisted = persistableMode(snapshot.mode);
1200
+ if (persisted) opts.remember({ mode: persisted });
1201
+ applyModeModel();
1202
+ };
1203
+ const requestApproval = (request) => {
1204
+ if (autoApproves(autoApprove(), request)) {
1205
+ set({ approvals: counted(true) });
1206
+ return Promise.resolve(true);
1207
+ }
1208
+ if (unattended()) {
1209
+ unattendedDeclines.push(request);
1210
+ set({ approvals: counted(false) });
1211
+ return Promise.resolve(false);
1212
+ }
1213
+ return new Promise((resolve2) => {
1214
+ resolveApproval = resolve2;
1215
+ set({ approval: request });
1216
+ });
1217
+ };
1218
+ const openQuestion = (request) => new Promise((resolve2) => {
1219
+ resolveQuestion = resolve2;
1220
+ set({ question: request });
1221
+ });
1222
+ const openConfirm = (spec) => new Promise((resolve2) => {
1223
+ const show = () => {
1224
+ resolveConfirm = resolve2;
1225
+ set({ confirm: spec });
1226
+ };
1227
+ if (resolveConfirm) waitingConfirms.push(show);
1228
+ else show();
1229
+ });
1230
+ const setStatus = (status) => {
1231
+ if (status !== snapshot.status) set({ status });
1232
+ };
1233
+ let prTimer = null;
1234
+ const checkPr = async () => {
1235
+ const s = session;
1236
+ if (!s) return;
1237
+ const next = await resolvePr(s.bundle.cwd, Date.now());
1238
+ if (next !== snapshot.pr) set({ pr: next });
1239
+ };
1240
+ const startPrPoll = () => {
1241
+ if (!opts.pollPr || prTimer) return;
1242
+ void checkPr();
1243
+ prTimer = setInterval(() => void checkPr(), PR_POLL_MS);
1244
+ prTimer.unref?.();
1245
+ };
1246
+ const attachSession = (attached, own) => {
1247
+ session = attached;
1248
+ ownProfile = own;
1249
+ if (modeSide(snapshot.mode) === "chat") attached.switchSide("chat");
1250
+ startPrPoll();
1251
+ };
1252
+ const createSession2 = opts.createSession ?? createSession;
1253
+ const boot = async (input) => {
1254
+ try {
1255
+ const cfg = input.loadConfig();
1256
+ const started = startProfiles(cfg, snapshot.mode, input.lastState);
1257
+ input.onConfig?.(cfg);
1258
+ const s = await createSession2({
1259
+ cwd: input.cwd,
1260
+ config: cfg,
1261
+ profile: started.profile,
1262
+ canAsk: !cfg.unattended
1263
+ });
1264
+ attachSession(s, started.own);
1265
+ input.onSession?.(s, started);
1266
+ const runtime = s.config;
1267
+ debugLog(formatBudget(s.bundle, runtime));
1268
+ append(
1269
+ ...buildLaunchNotices({
1270
+ facts: {
1271
+ model: runtime.model,
1272
+ limitsNotice: s.limitsNotice,
1273
+ windowNotice: s.windowNotice,
1274
+ budgetWarning: budgetWarning(s.bundle, runtime),
1275
+ offline: s.offline,
1276
+ searchNotice: s.searchNotice,
1277
+ mcpNotices: s.mcpNotices
1278
+ },
1279
+ config: cfg,
1280
+ mode: snapshot.mode,
1281
+ defaultMode: input.defaultMode,
1282
+ profile: started.profile
1283
+ })
1284
+ );
1285
+ setStatus("idle");
1286
+ return s;
1287
+ } catch (e) {
1288
+ set({ status: "error", error: e.message });
1289
+ return null;
1290
+ }
1291
+ };
1292
+ const runTurn = async (text, turn, front) => {
1293
+ const s = session;
1294
+ const cfg = config();
1295
+ if (!s || !cfg || stopped) return [];
1296
+ let notices = turn.notices ?? [];
1297
+ const activeMode = turn.mode ?? snapshot.mode;
1298
+ return s.submit(text, {
1299
+ mode: activeMode,
1300
+ // What this turn is recorded as on its prompt, which is not always what it runs as.
1301
+ recordAs: turnMode(snapshot.mode, activeMode),
1302
+ display: turn.display,
1303
+ skill: turn.skill,
1304
+ nativeImages: turn.nativeImages,
1305
+ manualCompact: turn.manualCompact,
1306
+ requestApproval: cfg.autoApprove === "bypass" ? void 0 : front.requestApproval ?? requestApproval,
1307
+ requestQuestion: front.requestQuestion ?? openQuestion,
1308
+ isUnattended: unattended,
1309
+ onTurnStart: () => {
1310
+ setStatus("busy");
1311
+ setLive({ ...emptyLive(), phase: "thinking" });
1312
+ front.onTurnStart?.();
1313
+ aborter = new AbortController();
1314
+ return aborter.signal;
1315
+ },
1316
+ onTurnError: (e) => {
1317
+ append({ role: "error", content: e.message });
1318
+ },
1319
+ onTurnEnd: () => {
1320
+ const declined = formatUnattendedDeclines(unattendedDeclines.splice(0));
1321
+ if (declined) append({ role: "system", content: declined, tone: "warn" });
1322
+ setLive({ ...emptyLive(), plan: live.plan });
1323
+ front.onTurnEnd?.();
1324
+ setStatus("idle");
1325
+ aborter = null;
1326
+ },
1327
+ events: {
1328
+ ...front.events,
1329
+ onContentDelta: (delta) => {
1330
+ live = { ...live, content: live.content + delta };
1331
+ notifyLive({ type: "delta", channel: "content", text: delta });
1332
+ front.events?.onContentDelta?.(delta);
1333
+ },
1334
+ onReasoningDelta: (delta) => {
1335
+ live = { ...live, reasoning: live.reasoning + delta };
1336
+ notifyLive({ type: "delta", channel: "reasoning", text: delta });
1337
+ front.events?.onReasoningDelta?.(delta);
1338
+ },
1339
+ onToolProgress: (chunk, tool) => {
1340
+ liveToolProgress(chunk, tool);
1341
+ front.events?.onToolProgress?.(chunk, tool);
1342
+ },
1343
+ onToolStart: (name) => {
1344
+ callsStarted += 1;
1345
+ setLive({ pending: { name, since: now(), call: callsStarted } });
1346
+ front.events?.onToolStart?.(name);
1347
+ },
1348
+ onPhase: (phase) => {
1349
+ setLive({ phase, ...phase !== "thinking" ? { looping: false } : {} });
1350
+ front.events?.onPhase?.(phase);
1351
+ },
1352
+ onSubagent: (subagent) => {
1353
+ setLive({ subagent });
1354
+ front.events?.onSubagent?.(subagent);
1355
+ },
1356
+ onCompactionNote: (note) => {
1357
+ setLive({ note });
1358
+ front.events?.onCompactionNote?.(note);
1359
+ },
1360
+ onTypecheck: (typechecking) => {
1361
+ setLive({ typechecking });
1362
+ front.events?.onTypecheck?.(typechecking);
1363
+ },
1364
+ onRecovering: (recovering) => {
1365
+ setLive({ recovering });
1366
+ front.events?.onRecovering?.(recovering);
1367
+ },
1368
+ onPlanProgress: (steps) => {
1369
+ setLive({ plan: steps.map((step) => ({ ...step })) });
1370
+ front.events?.onPlanProgress?.(steps);
1371
+ },
1372
+ onPromptProgress: (progress) => {
1373
+ setLive({ promptProgress: progress ?? null });
1374
+ front.events?.onPromptProgress?.(progress);
1375
+ },
1376
+ onLiveUsage: (usage) => {
1377
+ setLive({ usage: usage ?? null });
1378
+ front.events?.onLiveUsage?.(usage);
1379
+ },
1380
+ onReasoningStatus: (looping) => {
1381
+ setLive({ looping });
1382
+ front.events?.onReasoningStatus?.(looping);
1383
+ },
1384
+ onReasoningReset: () => {
1385
+ const frozen = frozenStreamMessage({
1386
+ content: live.content,
1387
+ reasoning: live.reasoning,
1388
+ note: live.note,
1389
+ nested: live.subagent
1390
+ });
1391
+ setLive({ content: "", reasoning: "", looping: false });
1392
+ if (frozen) append(frozen);
1393
+ front.events?.onReasoningReset?.();
1394
+ },
1395
+ onUsage: (u) => {
1396
+ const t = snapshot.usage;
1397
+ set({
1398
+ // The gauge and cache chip read lastUsage, and an estimate has no real count for either.
1399
+ ...u.estimated ? {} : { lastUsage: u },
1400
+ usage: {
1401
+ promptTokens: t.promptTokens + u.promptTokens,
1402
+ completionTokens: t.completionTokens + u.completionTokens,
1403
+ ...u.cachedTokens != null ? { cachedTokens: (t.cachedTokens ?? 0) + u.cachedTokens } : t.cachedTokens != null ? { cachedTokens: t.cachedTokens } : {},
1404
+ ...u.estimated || t.estimated ? { estimated: true } : {}
1405
+ }
1406
+ });
1407
+ if (live.usage !== null) setLive({ usage: null });
1408
+ front.events?.onUsage?.(u);
1409
+ },
1410
+ onContextEstimate: (tokens) => {
1411
+ set({ estimatedContext: tokens });
1412
+ front.events?.onContextEstimate?.(tokens);
1413
+ },
1414
+ onShrink: (event, counts) => {
1415
+ set({ shrink: counts, lastUsage: null });
1416
+ const turnNumber = snapshot.messages.filter((m) => m.role === "assistant").length + 1;
1417
+ shrinkEvents = [...shrinkEvents, { turn: turnNumber, ...event }];
1418
+ front.events?.onShrink?.(event, counts);
1419
+ },
1420
+ onDecodeRate: (rate) => {
1421
+ set({ decodeRate: rate });
1422
+ front.events?.onDecodeRate?.(rate);
1423
+ },
1424
+ onMessage: (msg) => {
1425
+ if (msg.role === "assistant") setLive({ content: "", reasoning: "" });
1426
+ else if (msg.role === "tool") setLive({ tool: null, pending: null });
1427
+ front.onMessage?.(msg);
1428
+ if (msg.role === "tool") {
1429
+ const written = [
1430
+ ...msg.diff?.path ? [msg.diff.path] : [],
1431
+ ...(msg.changes?.files ?? []).filter((f) => f.kind !== "deleted" && !f.path.startsWith("..")).map((f) => f.path)
1432
+ ];
1433
+ if (written.length > 0) {
1434
+ s.updateBundle((prev) => {
1435
+ const next = written.reduce(
1436
+ (idx, p) => addFileToIndex(idx, p, prev.ignore),
1437
+ prev.fileIndex
1438
+ );
1439
+ return next === prev.fileIndex ? prev : { ...prev, fileIndex: next };
1440
+ });
1441
+ }
1442
+ }
1443
+ if (msg.role === "user" && notices.length > 0) {
1444
+ const flushed = notices;
1445
+ notices = [];
1446
+ append(msg, ...flushed);
1447
+ return;
1448
+ }
1449
+ append(msg);
1450
+ }
1451
+ }
1452
+ });
1453
+ };
1454
+ const runTurnCommand = async (cmd, raw, echo, front) => {
1455
+ if (cmd.kind === "refuse") {
1456
+ append(echo, { role: "system", content: cmd.content });
1457
+ return;
1458
+ }
1459
+ if (cmd.switchTo) setMode(cmd.switchTo);
1460
+ const before = cmd.before.map((n) => ({ role: "system", ...n }));
1461
+ if (cmd.echo || before.length > 0) {
1462
+ append(...cmd.echo ? [echo] : [], ...before);
1463
+ }
1464
+ await runTurn(
1465
+ cmd.modelText,
1466
+ {
1467
+ display: cmd.echo ? void 0 : raw,
1468
+ mode: cmd.mode,
1469
+ manualCompact: cmd.manualCompact,
1470
+ skill: cmd.skill,
1471
+ notices: cmd.after.map((n) => ({ role: "system", ...n }))
1472
+ },
1473
+ front
1474
+ );
1475
+ };
1476
+ const runCommand = async (raw, front) => {
1477
+ const { name, args } = parseCommand(raw);
1478
+ const echo = { role: "user", content: raw, meta: true };
1479
+ if (name === "clear" || name === "new") {
1480
+ controller.newConversation(echo);
1481
+ return;
1482
+ }
1483
+ if (name === "exit" || name === "quit") {
1484
+ front.exit();
1485
+ return;
1486
+ }
1487
+ const reply = resolveReplyCommand(name, {
1488
+ cwd: session?.bundle.cwd,
1489
+ skills: session?.bundle.skills ?? [],
1490
+ messages: snapshot.messages,
1491
+ usage: snapshot.usage,
1492
+ startedAt,
1493
+ approvals: snapshot.approvals,
1494
+ mcpList: () => session?.mcp.list(),
1495
+ ...front.helpKeys ? { helpKeys: front.helpKeys } : {}
1496
+ });
1497
+ if (reply !== null) {
1498
+ append(echo, { role: "system", content: reply });
1499
+ return;
1500
+ }
1501
+ const modeCommand = resolveModeCommand(name, {
1502
+ mode: snapshot.mode,
1503
+ busy: snapshot.status === "busy"
1504
+ });
1505
+ if (modeCommand) {
1506
+ if (modeCommand.kind === "refuse") {
1507
+ append(echo, { role: "system", content: modeCommand.content });
1508
+ } else {
1509
+ controller.transition(modeCommand.to, [
1510
+ echo,
1511
+ { role: "system", content: modeCommand.banner }
1512
+ ]);
1513
+ }
1514
+ return;
1515
+ }
1516
+ const turnCommand = resolveTurnCommand(name, args, {
1517
+ mode: snapshot.mode,
1518
+ implementMode: front.implementMode,
1519
+ searchAvailable: (target) => {
1520
+ const lists = session?.lists;
1521
+ return !!lists && turnTools(target, lists).some((t) => t.name === "search");
1522
+ },
1523
+ offline: isOffline
1524
+ });
1525
+ if (turnCommand) {
1526
+ await runTurnCommand(turnCommand, raw, echo, front.turn);
1527
+ return;
1528
+ }
1529
+ if (name === "cd") {
1530
+ await controller.changeDirectory(args, echo);
1531
+ return;
1532
+ }
1533
+ if (name === "resume") {
1534
+ const list = await controller.resumeList(args);
1535
+ if ("reply" in list) {
1536
+ append(echo, { role: "system", content: list.reply });
1537
+ return;
1538
+ }
1539
+ append(echo);
1540
+ front.pickSession(list);
1541
+ return;
1542
+ }
1543
+ if (name === "save") {
1544
+ await controller.saveTranscript(args.trim().toLowerCase() === "--raw", echo);
1545
+ return;
1546
+ }
1547
+ const toggle = controller.toggleCommand(name, args);
1548
+ if (toggle) {
1549
+ if (toggle.kind === "reply") {
1550
+ append(echo, { role: "system", content: toggle.content });
1551
+ return;
1552
+ }
1553
+ let on;
1554
+ if (toggle.kind === "ask") {
1555
+ const spec = toggleConfirmSpec({ title: toggle.title, subtitle: toggle.subtitle });
1556
+ const initial = toggle.currentlyOn ? TOGGLE_ON : TOGGLE_OFF;
1557
+ const choice = await (front.ask ? front.ask(spec, initial) : openConfirm(spec));
1558
+ if (choice === "abort" || choice === TOGGLE_CANCEL) {
1559
+ append(echo);
1560
+ return;
1561
+ }
1562
+ on = choice === TOGGLE_ON;
1563
+ } else {
1564
+ on = toggle.on;
1565
+ }
1566
+ await controller.setToggle(toggle.toggle, on, echo);
1567
+ return;
1568
+ }
1569
+ if (name === "model") {
1570
+ if (!config()) {
1571
+ append(echo, { role: "system", content: "config not loaded" });
1572
+ return;
1573
+ }
1574
+ if (args.trim()) {
1575
+ controller.pickModel(args, echo);
1576
+ return;
1577
+ }
1578
+ const targets = controller.modelTargets();
1579
+ append(echo);
1580
+ front.pickModel(targets);
1581
+ return;
1582
+ }
1583
+ const mcpCommand = session?.mcp.commands.find((c) => c.name === name);
1584
+ if (mcpCommand) {
1585
+ await controller.runMcpCommand(raw, mcpCommand, args);
1586
+ return;
1587
+ }
1588
+ const skillCommand = resolveSkillCommand(name, args, {
1589
+ skills: session?.bundle.skills ?? [],
1590
+ mode: snapshot.mode,
1591
+ pastes: front.pastes
1592
+ });
1593
+ if (skillCommand) {
1594
+ await runTurnCommand(skillCommand, raw, echo, front.turn);
1595
+ return;
1596
+ }
1597
+ append(echo, { role: "system", content: unknownCommandText(name) });
1598
+ };
1599
+ const ask = (front, spec) => front.ask ? front.ask(spec) : openConfirm(spec);
1600
+ const decideSkillRoute = async (prompt, front) => {
1601
+ const cfg = config();
1602
+ if (!session || !cfg) return void 0;
1603
+ const match = skillToConfirm(prompt, {
1604
+ skills: session.bundle.skills,
1605
+ skillAuto: cfg.skillAuto,
1606
+ mode: snapshot.mode,
1607
+ contextWindow: cfg.profiles[session.profile]?.contextWindow ?? cfg.contextWindow
1608
+ });
1609
+ if (!match) return void 0;
1610
+ const choice = await ask(front, skillConfirmSpec(match));
1611
+ return choice === "abort" ? "abort" : choice === CONFIRM_ACCEPT ? match.skill.name : null;
1612
+ };
1613
+ const decidePastedUrls = async (prompt, front) => {
1614
+ const cfg = config();
1615
+ if (!cfg) return void 0;
1616
+ const urls = urlsToConfirm(prompt, { pasteFetch: cfg.pasteFetch, mode: snapshot.mode });
1617
+ if (!urls) return void 0;
1618
+ const choice = await ask(front, pastedUrlConfirmSpec(urls));
1619
+ return choice === "abort" ? "abort" : choice === CONFIRM_ACCEPT;
1620
+ };
1621
+ const decideImplementMode = async (prompt, front) => {
1622
+ if (snapshot.mode !== "plan" || !isImplementCommand(prompt)) return void 0;
1623
+ front.beforeImplementQuestion?.();
1624
+ const choice = await ask(front, implementModeConfirmSpec());
1625
+ return choice === "abort" ? "abort" : IMPLEMENT_MODES[choice];
1626
+ };
1627
+ const askSubmitAnswers = async (prompt, front, carried = {}) => {
1628
+ const skill = carried.skill !== void 0 ? carried.skill : await decideSkillRoute(prompt, front);
1629
+ if (skill === "abort") return "abort";
1630
+ const fetchUrls = carried.fetchUrls !== void 0 ? carried.fetchUrls : await decidePastedUrls(prompt, front);
1631
+ if (fetchUrls === "abort") return "abort";
1632
+ const implementMode = carried.implementMode ?? await decideImplementMode(prompt, front);
1633
+ if (implementMode === "abort") return "abort";
1634
+ return {
1635
+ ...skill !== void 0 ? { skill } : {},
1636
+ ...fetchUrls !== void 0 ? { fetchUrls } : {},
1637
+ ...implementMode !== void 0 ? { implementMode } : {}
1638
+ };
1639
+ };
1640
+ const recordHistory = (line) => {
1641
+ const prev = snapshot.history;
1642
+ if (prev[prev.length - 1] === line) return;
1643
+ const next = [...prev, line];
1644
+ let chars = next.reduce((n, l) => n + l.length, 0);
1645
+ while (next.length > 1 && (next.length > MAX_HISTORY_ENTRIES || chars > MAX_HISTORY_CHARS)) {
1646
+ chars -= next.shift().length;
1647
+ }
1648
+ set({ history: next });
1649
+ };
1650
+ const submit = async (input, front, carried) => {
1651
+ if (stopped) return;
1652
+ const trimmed = input.trim();
1653
+ const held = snapshot.status !== "idle" || snapshot.preparing;
1654
+ if (session && held && isSaveCommand(input)) {
1655
+ front.onTaken(trimmed);
1656
+ recordHistory(trimmed);
1657
+ await runCommand(trimmed, front);
1658
+ return;
1659
+ }
1660
+ if (!session || held) {
1661
+ const answers = await askSubmitAnswers(trimmed, front, carried);
1662
+ if (answers === "abort") return;
1663
+ const msg = queuedMessage(trimmed, front.images, answers);
1664
+ if (!msg) return;
1665
+ front.onImagesTaken?.();
1666
+ controller.enqueue(msg);
1667
+ front.onTaken();
1668
+ return;
1669
+ }
1670
+ set({ preparing: true });
1671
+ try {
1672
+ await runLine(trimmed, front, carried);
1673
+ } finally {
1674
+ set({ preparing: false });
1675
+ }
1676
+ };
1677
+ const runLine = async (trimmed, front, carried) => {
1678
+ warmer.cancel("submit");
1679
+ const answers = await askSubmitAnswers(trimmed, front, carried);
1680
+ if (answers === "abort" || stopped) return;
1681
+ const { skill: route, fetchUrls, implementMode } = answers;
1682
+ front.onTaken(trimmed || void 0);
1683
+ if (trimmed) recordHistory(trimmed);
1684
+ if (!trimmed) return;
1685
+ if (trimmed.startsWith("/")) {
1686
+ await runCommand(trimmed, { ...front, implementMode });
1687
+ return;
1688
+ }
1689
+ if (snapshot.mode === "shell") {
1690
+ await controller.runShell(expandPastes(trimmed, front.pastes), front.shell);
1691
+ return;
1692
+ }
1693
+ await controller.submitPrompt(
1694
+ trimmed,
1695
+ {
1696
+ answers: { skill: route, fetchUrls },
1697
+ images: front.images,
1698
+ pastes: front.pastes,
1699
+ onStage: front.onStage,
1700
+ onBuilt: front.onImagesTaken
1701
+ },
1702
+ front.turn
1703
+ );
1704
+ };
1705
+ const controller = {
1706
+ getSnapshot: () => snapshot,
1707
+ subscribe: (listener) => {
1708
+ listeners.add(listener);
1709
+ return () => listeners.delete(listener);
1710
+ },
1711
+ get live() {
1712
+ return live.pending && pendingHidden() ? { ...live, pending: null } : live;
1713
+ },
1714
+ subscribeLive: (listener) => {
1715
+ liveListeners.add(listener);
1716
+ return () => {
1717
+ liveListeners.delete(listener);
1718
+ };
1719
+ },
1720
+ get runningCall() {
1721
+ return live.pending;
1722
+ },
1723
+ get messages() {
1724
+ return snapshot.messages;
1725
+ },
1726
+ get mode() {
1727
+ return snapshot.mode;
1728
+ },
1729
+ get status() {
1730
+ return snapshot.status;
1731
+ },
1732
+ setStatus,
1733
+ enqueue: (message) => set({
1734
+ queue: [...snapshot.queue, message],
1735
+ messages: [
1736
+ ...snapshot.messages,
1737
+ { role: "system", content: queueReceipt(message), tone: "info" }
1738
+ ]
1739
+ }),
1740
+ takeQueued: (blockers) => {
1741
+ const drainable = canDrain({
1742
+ idle: snapshot.status === "idle",
1743
+ replaying: snapshot.replaying,
1744
+ preparing: snapshot.preparing,
1745
+ dialogOpen: snapshot.approval !== null || snapshot.confirm !== null,
1746
+ ...blockers
1747
+ });
1748
+ const taken = drainable ? takeNext(snapshot.queue) : null;
1749
+ if (!taken) return null;
1750
+ set({ queue: taken.rest, replaying: true });
1751
+ return taken.next;
1752
+ },
1753
+ replayDone: () => {
1754
+ if (snapshot.replaying) set({ replaying: false });
1755
+ },
1756
+ get approval() {
1757
+ return snapshot.approval;
1758
+ },
1759
+ get question() {
1760
+ return snapshot.question;
1761
+ },
1762
+ get confirm() {
1763
+ return snapshot.confirm;
1764
+ },
1765
+ requestApproval,
1766
+ answerApproval: (answer, { always = false } = {}) => {
1767
+ const resolve2 = resolveApproval;
1768
+ if (!resolve2) return;
1769
+ resolveApproval = null;
1770
+ set({
1771
+ approval: null,
1772
+ approvals: counted(answer === true),
1773
+ ...always ? { sessionAutoApprove: true } : {}
1774
+ });
1775
+ resolve2(answer);
1776
+ },
1777
+ get autoApprove() {
1778
+ return autoApprove();
1779
+ },
1780
+ get unattended() {
1781
+ return unattended();
1782
+ },
1783
+ toggleCommand: (name, args) => {
1784
+ const cfg = config();
1785
+ return resolveToggleCommand(name, args, {
1786
+ autoApprove: autoApprove(),
1787
+ autoApproveForced: cfg ? autoApproveForced(cfg) : false,
1788
+ configAutoApprove: cfg?.autoApprove,
1789
+ unattended: unattended(),
1790
+ anon: isAnon()
1791
+ });
1792
+ },
1793
+ setToggle: async (toggle, on, echo) => {
1794
+ let identity;
1795
+ if (toggle === "approvals") {
1796
+ if (on !== snapshot.sessionAutoApprove) set({ sessionAutoApprove: on });
1797
+ } else if (toggle === "unattended") {
1798
+ if (on !== snapshot.sessionUnattended) set({ sessionUnattended: on });
1799
+ } else if (on) {
1800
+ const found = await enableAnon(session?.bundle.cwd ?? process.cwd());
1801
+ identity = { names: found.names.length, emails: found.emails.length };
1802
+ } else {
1803
+ clearIdentity();
1804
+ }
1805
+ append(...echo ? [echo] : [], {
1806
+ role: "system",
1807
+ content: toggleReceipt(toggle, on, identity)
1808
+ });
1809
+ },
1810
+ takeUnattendedDeclines: () => {
1811
+ const taken = unattendedDeclines;
1812
+ unattendedDeclines = [];
1813
+ return taken;
1814
+ },
1815
+ openQuestion,
1816
+ answerQuestion: (answer) => {
1817
+ const resolve2 = resolveQuestion;
1818
+ if (!resolve2) return;
1819
+ resolveQuestion = null;
1820
+ set({ question: null });
1821
+ resolve2(answer);
1822
+ },
1823
+ openConfirm,
1824
+ answerConfirm: (choice) => {
1825
+ const resolve2 = resolveConfirm;
1826
+ if (!resolve2) return;
1827
+ resolveConfirm = null;
1828
+ set({ confirm: null });
1829
+ resolve2(choice);
1830
+ waitingConfirms.shift()?.();
1831
+ },
1832
+ append,
1833
+ replace: (messages) => set({ messages }),
1834
+ setMode,
1835
+ transition: (mode, trailing = []) => {
1836
+ const changed = mode !== snapshot.mode;
1837
+ const from = modeSide(snapshot.mode);
1838
+ const to = modeSide(mode);
1839
+ if (from === to) {
1840
+ set({
1841
+ mode,
1842
+ ...trailing.length > 0 ? { messages: [...snapshot.messages, ...trailing] } : {}
1843
+ });
1844
+ } else {
1845
+ stashed[from] = snapshot.messages;
1846
+ session?.switchSide(to);
1847
+ set({ messages: [...stashed[to] ?? [], ...trailing], mode });
1848
+ }
1849
+ if (changed) modeChanged();
1850
+ },
1851
+ get session() {
1852
+ return session;
1853
+ },
1854
+ boot,
1855
+ attachSession,
1856
+ pickModel: (typed, echo) => {
1857
+ const cfg = config();
1858
+ if (!session || !cfg) return;
1859
+ const key = typed.trim().toLowerCase();
1860
+ if (cfg.profiles[key]) return switchModel(key, echo, true);
1861
+ if (cfg.models.some((m) => m.toLowerCase() === key)) return switchModel("default", echo, true);
1862
+ const inherit = cfg.profiles[session.profile] ?? cfg.profiles.default;
1863
+ session.addProfile(key, inheritProfile(inherit, typed.trim()));
1864
+ switchModel(key, echo, true);
1865
+ },
1866
+ modelTargets: () => {
1867
+ const cfg = config();
1868
+ return session && cfg ? buildModelTargets(cfg, session.profile) : [];
1869
+ },
1870
+ get modelPinned() {
1871
+ return modelPinned;
1872
+ },
1873
+ readImage: (bytes, origin) => readImageAttachment(bytes, session?.config ?? null, origin),
1874
+ imageReadLabel: () => imageReadLabel(session?.config ?? null),
1875
+ warm: (text) => {
1876
+ if (!session || snapshot.status !== "idle" || snapshot.preparing) return;
1877
+ if (snapshot.mode === "shell" || !isWarmableInput(text)) return;
1878
+ const m = snapshot.mode;
1879
+ warmer.onEdge({
1880
+ // The model history, so the warm reproduces the prefix round 0 will actually send —
1881
+ // including any span already folded by a previous turn's compaction.
1882
+ history: session.history,
1883
+ bundle: session.bundle,
1884
+ config: session.config,
1885
+ // runTurn's own mapping, so the warm cannot build a different prefix than the submit.
1886
+ // Vibe's first internal turn is a plan turn without the refinement line (turnRefines, #46).
1887
+ tools: turnTools(m, session.lists),
1888
+ promptMode: turnPromptMode(m),
1889
+ minimalPrompt: isMinimalPrompt(m),
1890
+ grindPrompt: isGrindPrompt(m),
1891
+ allowRefine: turnRefines(m),
1892
+ calibration: session.calibration ?? 1
1893
+ });
1894
+ },
1895
+ completions: (text) => {
1896
+ if (!session) return null;
1897
+ return computeSuggestions(
1898
+ text,
1899
+ session.bundle.fileIndex,
1900
+ // MCP commands complete like skills (#265): to the user both are a slash command that is
1901
+ // not a mode. Built-ins win a name clash; an MCP name carries a colon, so none clashes.
1902
+ [
1903
+ ...session.bundle.skills,
1904
+ ...session.mcp.commands.map((c) => ({
1905
+ name: c.name,
1906
+ description: `MCP ${c.server}${c.description ? ` \xB7 ${c.description}` : ""}`
1907
+ }))
1908
+ ],
1909
+ controller.modelTargets()
1910
+ );
1911
+ },
1912
+ get conversation() {
1913
+ return conversation;
1914
+ },
1915
+ get startedAt() {
1916
+ return startedAt;
1917
+ },
1918
+ newConversation: (echo) => {
1919
+ conversation++;
1920
+ stashed = {};
1921
+ heldShellRuns = [];
1922
+ startedAt = Date.now();
1923
+ stopSaveTimer();
1924
+ sessionPath = null;
1925
+ saveHold = null;
1926
+ set({
1927
+ messages: echo ? [
1928
+ echo,
1929
+ { role: "system", content: "New session \u2014 conversation, tokens, and mode reset." }
1930
+ ] : [],
1931
+ approvals: { approved: 0, declined: 0 },
1932
+ sessionAutoApprove: null,
1933
+ ...freshMeasurements(),
1934
+ // The tok/s chip goes with the token counts it sits next to (#204).
1935
+ decodeRate: void 0
1936
+ });
1937
+ session?.reset();
1938
+ session?.switchSide("agent");
1939
+ if (modelPinned && session) ownProfile = session.profile;
1940
+ modelPinned = false;
1941
+ setMode("agent");
1942
+ applyModeModel();
1943
+ setLive(emptyLive());
1944
+ },
1945
+ loadConversation: (sides, from) => {
1946
+ conversation++;
1947
+ setLive(emptyLive());
1948
+ stashed = {};
1949
+ session?.reset();
1950
+ stopSaveTimer();
1951
+ sessionPath = dirname(from.path) === projectDir() ? from.path : null;
1952
+ if (sessionPath) logSessionFile(sessionPath);
1953
+ saveHold = countRealTurns(sides.agent) + countRealTurns(sides.chat);
1954
+ set({ messages: [], ...freshMeasurements() });
1955
+ const agentTurns = countRealTurns(sides.agent);
1956
+ const chatTurns = countRealTurns(sides.chat);
1957
+ const switchedTo = snapshot.mode !== "chat" && agentTurns === 0 && chatTurns > 0 ? "chat" : snapshot.mode === "chat" && chatTurns === 0 && agentTurns > 0 ? "agent" : null;
1958
+ if (switchedTo) {
1959
+ session?.switchSide(modeSide(switchedTo));
1960
+ setMode(switchedTo);
1961
+ }
1962
+ const onScreen = modeSide(snapshot.mode);
1963
+ const offScreen = onScreen === "chat" ? "agent" : "chat";
1964
+ const active = sides[onScreen];
1965
+ const other = sides[offScreen];
1966
+ stashed = { [offScreen]: other };
1967
+ session?.loadHistory(modelHistoryFromScrollback(active), modelHistoryFromScrollback(other));
1968
+ const otherNote = other.length > 0 ? ` (+ ${other.length} on the ${offScreen} side)` : "";
1969
+ return [
1970
+ ...active,
1971
+ {
1972
+ role: "system",
1973
+ content: `Resumed "${from.title ?? "untitled"}" \u2014 ${active.length} ${onScreen} messages${otherNote}${switchedTo ? `, switched to ${switchedTo} mode,` : ""} from ${from.path}`
1974
+ },
1975
+ // What the mode change printed: the model it brought, which belongs under the receipt.
1976
+ ...snapshot.messages
1977
+ ];
1978
+ },
1979
+ sides: bothSides,
1980
+ offScreen: () => {
1981
+ const side = modeSide(snapshot.mode) === "chat" ? "agent" : "chat";
1982
+ return { side, turns: countRealTurns(stashed[side] ?? []) };
1983
+ },
1984
+ get sessionPath() {
1985
+ return sessionPath;
1986
+ },
1987
+ saveNow,
1988
+ changeDirectory: async (target, echo) => {
1989
+ const path = target.trim();
1990
+ if (!path) {
1991
+ append(echo, { role: "system", content: "Usage: /cd <path>" });
1992
+ return;
1993
+ }
1994
+ if (!session) return;
1995
+ const expanded = expandHome(path);
1996
+ const cwd = isAbsolute(expanded) ? expanded : resolve(session.bundle.cwd, expanded);
1997
+ set({
1998
+ status: "busy",
1999
+ messages: [...snapshot.messages, echo, { role: "system", content: `Re-indexing ${cwd}\u2026` }]
2000
+ });
2001
+ try {
2002
+ const bundle = await bootstrap(cwd, session.bundle.repoMapBudget);
2003
+ session.updateBundle(() => bundle);
2004
+ append({ role: "system", content: `cwd is now ${cwd}` });
2005
+ if (opts.pollPr) void checkPr();
2006
+ } catch (e) {
2007
+ append({ role: "system", content: `cd failed: ${e.message}` });
2008
+ } finally {
2009
+ set({ status: "idle" });
2010
+ }
2011
+ },
2012
+ saveTranscript: async (raw, echo) => {
2013
+ if (!session) return;
2014
+ const midTurn = snapshot.status === "busy";
2015
+ const msgs = snapshot.messages;
2016
+ if (msgs.length === 0) {
2017
+ append(echo, { role: "system", content: "Nothing to save yet." });
2018
+ return;
2019
+ }
2020
+ try {
2021
+ const { jsonlPath, txtPath } = await saveTranscript(
2022
+ historyRoot,
2023
+ msgs,
2024
+ saveHeader(transcriptMeta(session, msgs, midTurn), msgs),
2025
+ { redact: !raw }
2026
+ );
2027
+ append(echo, {
2028
+ role: "system",
2029
+ content: `saved ${msgs.length} messages${raw ? " (raw, unredacted)" : ""}${midTurn ? " \u2014 mid-turn, up to the last completed round; the turn continues" : ""} \u2192 ${jsonlPath}
2030
+ (+ ${txtPath})`
2031
+ });
2032
+ } catch (e) {
2033
+ append(echo, { role: "error", content: `save failed: ${e.message}` });
2034
+ }
2035
+ },
2036
+ resumeList: async (args) => {
2037
+ const dir = projectDir();
2038
+ if (!session || !dir) return { reply: "config not loaded" };
2039
+ if (snapshot.status === "busy") {
2040
+ return { reply: "Cannot resume while busy. Wait or ctrl-c to abort." };
2041
+ }
2042
+ const target = args.trim().toLowerCase();
2043
+ if (target !== "" && target !== "all" && target !== "root") {
2044
+ return {
2045
+ reply: "Usage: /resume (this project; chats only in chat mode), /resume all, or /resume root (manual /save files)."
2046
+ };
2047
+ }
2048
+ const chatsOnly = target === "" && snapshot.mode === "chat";
2049
+ let entries = [];
2050
+ let heading = "saved with /save";
2051
+ if (target !== "root") {
2052
+ entries = (await listSessions(dir)).filter((e) => e.path !== sessionPath);
2053
+ if (chatsOnly) entries = entries.filter((e) => e.chat);
2054
+ heading = chatsOnly ? "chats in this project" : "this project";
2055
+ }
2056
+ if (entries.length === 0) {
2057
+ entries = await listSessions(historyRoot, true);
2058
+ if (chatsOnly) entries = entries.filter((e) => e.chat);
2059
+ if (target === "" && entries.length > 0)
2060
+ heading = chatsOnly ? "no chats for this project \u2014 saved with /save" : "none for this project \u2014 saved with /save";
2061
+ }
2062
+ if (entries.length > 0) return { entries, heading };
2063
+ if (chatsOnly) {
2064
+ return { reply: "No saved chats for this project. /resume all lists every session." };
2065
+ }
2066
+ return {
2067
+ reply: target === "root" ? `No saved sessions in ${historyRoot}.` : session.getSnapshot().config.autosave ? "No saved sessions for this project yet." : "No saved sessions for this project (auto-save is off: REIKA_AUTOSAVE=0)."
2068
+ };
2069
+ },
2070
+ sessionList: async (scope) => {
2071
+ await saveChain;
2072
+ if (scope === "root") return session ? listSessions(historyRoot, true) : [];
2073
+ const dir = projectDir();
2074
+ return dir ? listSessions(dir) : [];
2075
+ },
2076
+ runTurn,
2077
+ submitPrompt: async (text, input, front) => {
2078
+ const s = session;
2079
+ const cfg = config();
2080
+ if (!s || !cfg || submitting) return;
2081
+ submitting = true;
2082
+ let modelText;
2083
+ let built;
2084
+ try {
2085
+ built = await buildSubmitInput(text, {
2086
+ cwd: s.bundle.cwd,
2087
+ skills: s.bundle.skills,
2088
+ config: resolveProfile(cfg, s.profile),
2089
+ skillRoute: input.answers.skill,
2090
+ skillHints: hintedSkills,
2091
+ fetchUrls: input.answers.fetchUrls,
2092
+ images: input.images,
2093
+ pastes: input.pastes,
2094
+ onStage: input.onStage
2095
+ });
2096
+ input.onBuilt?.();
2097
+ modelText = built.modelText;
2098
+ if (heldShellRuns.length > 0 && snapshot.mode !== "chat") {
2099
+ const budget = shellRunBudget(s.config.contextWindow);
2100
+ modelText = `${buildShellRunsBlock(heldShellRuns, budget)}
2101
+
2102
+ ${modelText}`;
2103
+ heldShellRuns = [];
2104
+ }
2105
+ } finally {
2106
+ input.onStage(null);
2107
+ submitting = false;
2108
+ }
2109
+ await runTurn(
2110
+ modelText,
2111
+ {
2112
+ // Vibe runs the plan→implement chain (#45) inside the session.
2113
+ ...snapshot.mode === "vibe" ? { mode: "vibe" } : {},
2114
+ display: built.display !== modelText ? built.display : void 0,
2115
+ nativeImages: built.nativeImages,
2116
+ skill: built.skill,
2117
+ notices: built.notices.map((n) => ({ role: "system", ...n }))
2118
+ },
2119
+ front
2120
+ );
2121
+ },
2122
+ runShell: async (command, front) => {
2123
+ const s = session;
2124
+ if (!s || stopped) return;
2125
+ append({ role: "user", content: command, meta: true });
2126
+ setStatus("busy");
2127
+ setLive({ tool: null });
2128
+ front.onStart?.();
2129
+ const running = new AbortController();
2130
+ aborter = running;
2131
+ try {
2132
+ const result = await execStream(command, {
2133
+ cwd: s.bundle.cwd,
2134
+ bashTimeoutMs: config()?.bashTimeoutMs,
2135
+ bashIdleMs: config()?.bashIdleMs,
2136
+ signal: running.signal,
2137
+ // Shell output streams through the tool block under the empty name.
2138
+ onProgress: (chunk) => {
2139
+ liveToolProgress(chunk, "");
2140
+ front.onProgress?.(chunk);
2141
+ }
2142
+ });
2143
+ setLive({ tool: null });
2144
+ append({ role: "shell", command, output: result.payload ?? "" });
2145
+ heldShellRuns = holdShellRun(
2146
+ heldShellRuns,
2147
+ await captureShellRun(command, result.exitCode ?? null, result.payload ?? "")
2148
+ );
2149
+ } catch (e) {
2150
+ append({ role: "error", content: e.message });
2151
+ } finally {
2152
+ if (live.tool) setLive({ tool: null });
2153
+ front.onEnd?.();
2154
+ aborter = null;
2155
+ setStatus("idle");
2156
+ }
2157
+ },
2158
+ // `/filesystem:read_file {"path":"src/index.ts"}`. No approval prompt: the user typed it, the
2159
+ // rule shell mode runs under. The result is a command and its output, and the user reading the
2160
+ // tool, not the model calling it.
2161
+ runMcpCommand: async (raw, command, args) => {
2162
+ const s = session;
2163
+ if (!s || stopped) return;
2164
+ const parsed = parseMcpArgs(command, args);
2165
+ if ("error" in parsed) {
2166
+ append({ role: "system", content: parsed.error, tone: "warn" });
2167
+ return;
2168
+ }
2169
+ setStatus("busy");
2170
+ const running = new AbortController();
2171
+ aborter = running;
2172
+ try {
2173
+ const result = await invokeMcpTool(
2174
+ s.mcp.call,
2175
+ `${command.server}:${command.tool}`,
2176
+ command.server,
2177
+ command.tool,
2178
+ parsed.args,
2179
+ { signal: running.signal }
2180
+ );
2181
+ const output = [result.summary, result.payload].filter(Boolean).join("\n");
2182
+ append({ role: "shell", command: raw, output });
2183
+ } finally {
2184
+ aborter = null;
2185
+ setStatus("idle");
2186
+ }
2187
+ },
2188
+ abort: () => {
2189
+ if (snapshot.status !== "busy" || !aborter) return false;
2190
+ aborter.abort();
2191
+ return true;
2192
+ },
2193
+ stop: () => {
2194
+ stopped = true;
2195
+ warmer.cancel("stop");
2196
+ controller.abort();
2197
+ },
2198
+ runCommand,
2199
+ submit
2200
+ };
2201
+ return controller;
2202
+ }
2203
+
2204
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
2205
+ var ANSI_BACKGROUND_OFFSET = 10;
2206
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
2207
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
2208
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
2209
+ var styles = {
2210
+ modifier: {
2211
+ reset: [0, 0],
2212
+ // 21 isn't widely supported and 22 does the same thing
2213
+ bold: [1, 22],
2214
+ dim: [2, 22],
2215
+ italic: [3, 23],
2216
+ underline: [4, 24],
2217
+ overline: [53, 55],
2218
+ inverse: [7, 27],
2219
+ hidden: [8, 28],
2220
+ strikethrough: [9, 29]
2221
+ },
2222
+ color: {
2223
+ black: [30, 39],
2224
+ red: [31, 39],
2225
+ green: [32, 39],
2226
+ yellow: [33, 39],
2227
+ blue: [34, 39],
2228
+ magenta: [35, 39],
2229
+ cyan: [36, 39],
2230
+ white: [37, 39],
2231
+ // Bright color
2232
+ blackBright: [90, 39],
2233
+ gray: [90, 39],
2234
+ // Alias of `blackBright`
2235
+ grey: [90, 39],
2236
+ // Alias of `blackBright`
2237
+ redBright: [91, 39],
2238
+ greenBright: [92, 39],
2239
+ yellowBright: [93, 39],
2240
+ blueBright: [94, 39],
2241
+ magentaBright: [95, 39],
2242
+ cyanBright: [96, 39],
2243
+ whiteBright: [97, 39]
2244
+ },
2245
+ bgColor: {
2246
+ bgBlack: [40, 49],
2247
+ bgRed: [41, 49],
2248
+ bgGreen: [42, 49],
2249
+ bgYellow: [43, 49],
2250
+ bgBlue: [44, 49],
2251
+ bgMagenta: [45, 49],
2252
+ bgCyan: [46, 49],
2253
+ bgWhite: [47, 49],
2254
+ // Bright color
2255
+ bgBlackBright: [100, 49],
2256
+ bgGray: [100, 49],
2257
+ // Alias of `bgBlackBright`
2258
+ bgGrey: [100, 49],
2259
+ // Alias of `bgBlackBright`
2260
+ bgRedBright: [101, 49],
2261
+ bgGreenBright: [102, 49],
2262
+ bgYellowBright: [103, 49],
2263
+ bgBlueBright: [104, 49],
2264
+ bgMagentaBright: [105, 49],
2265
+ bgCyanBright: [106, 49],
2266
+ bgWhiteBright: [107, 49]
2267
+ }
2268
+ };
2269
+ var modifierNames = Object.keys(styles.modifier);
2270
+ var foregroundColorNames = Object.keys(styles.color);
2271
+ var backgroundColorNames = Object.keys(styles.bgColor);
2272
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
2273
+ function assembleStyles() {
2274
+ const codes = /* @__PURE__ */ new Map();
2275
+ for (const [groupName, group] of Object.entries(styles)) {
2276
+ for (const [styleName, style] of Object.entries(group)) {
2277
+ styles[styleName] = {
2278
+ open: `\x1B[${style[0]}m`,
2279
+ close: `\x1B[${style[1]}m`
2280
+ };
2281
+ group[styleName] = styles[styleName];
2282
+ codes.set(style[0], style[1]);
2283
+ }
2284
+ Object.defineProperty(styles, groupName, {
2285
+ value: group,
2286
+ enumerable: false
2287
+ });
2288
+ }
2289
+ Object.defineProperty(styles, "codes", {
2290
+ value: codes,
2291
+ enumerable: false
2292
+ });
2293
+ styles.color.close = "\x1B[39m";
2294
+ styles.bgColor.close = "\x1B[49m";
2295
+ styles.color.ansi = wrapAnsi16();
2296
+ styles.color.ansi256 = wrapAnsi256();
2297
+ styles.color.ansi16m = wrapAnsi16m();
2298
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
2299
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
2300
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
2301
+ Object.defineProperties(styles, {
2302
+ rgbToAnsi256: {
2303
+ value(red, green, blue) {
2304
+ if (red === green && green === blue) {
2305
+ if (red < 8) {
2306
+ return 16;
2307
+ }
2308
+ if (red > 248) {
2309
+ return 231;
2310
+ }
2311
+ return Math.round((red - 8) / 247 * 24) + 232;
2312
+ }
2313
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
2314
+ },
2315
+ enumerable: false
2316
+ },
2317
+ hexToRgb: {
2318
+ value(hex) {
2319
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
2320
+ if (!matches) {
2321
+ return [0, 0, 0];
2322
+ }
2323
+ let [colorString] = matches;
2324
+ if (colorString.length === 3) {
2325
+ colorString = [...colorString].map((character) => character + character).join("");
2326
+ }
2327
+ const integer = Number.parseInt(colorString, 16);
2328
+ return [
2329
+ /* eslint-disable no-bitwise */
2330
+ integer >> 16 & 255,
2331
+ integer >> 8 & 255,
2332
+ integer & 255
2333
+ /* eslint-enable no-bitwise */
2334
+ ];
2335
+ },
2336
+ enumerable: false
2337
+ },
2338
+ hexToAnsi256: {
2339
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
2340
+ enumerable: false
2341
+ },
2342
+ ansi256ToAnsi: {
2343
+ value(code) {
2344
+ if (code < 8) {
2345
+ return 30 + code;
2346
+ }
2347
+ if (code < 16) {
2348
+ return 90 + (code - 8);
2349
+ }
2350
+ let red;
2351
+ let green;
2352
+ let blue;
2353
+ if (code >= 232) {
2354
+ red = ((code - 232) * 10 + 8) / 255;
2355
+ green = red;
2356
+ blue = red;
2357
+ } else {
2358
+ code -= 16;
2359
+ const remainder = code % 36;
2360
+ red = Math.floor(code / 36) / 5;
2361
+ green = Math.floor(remainder / 6) / 5;
2362
+ blue = remainder % 6 / 5;
2363
+ }
2364
+ const value = Math.max(red, green, blue) * 2;
2365
+ if (value === 0) {
2366
+ return 30;
2367
+ }
2368
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
2369
+ if (value === 2) {
2370
+ result += 60;
2371
+ }
2372
+ return result;
2373
+ },
2374
+ enumerable: false
2375
+ },
2376
+ rgbToAnsi: {
2377
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
2378
+ enumerable: false
2379
+ },
2380
+ hexToAnsi: {
2381
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
2382
+ enumerable: false
2383
+ }
2384
+ });
2385
+ return styles;
2386
+ }
2387
+ var ansiStyles = assembleStyles();
2388
+ var ansi_styles_default = ansiStyles;
2389
+
2390
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
2391
+ import process2 from "node:process";
2392
+ import os from "node:os";
2393
+ import tty from "node:tty";
2394
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2395
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2396
+ const position = argv.indexOf(prefix + flag);
2397
+ const terminatorPosition = argv.indexOf("--");
2398
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2399
+ }
2400
+ var { env } = process2;
2401
+ var flagForceColor;
2402
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2403
+ flagForceColor = 0;
2404
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2405
+ flagForceColor = 1;
2406
+ }
2407
+ function envForceColor() {
2408
+ if ("FORCE_COLOR" in env) {
2409
+ if (env.FORCE_COLOR === "true") {
2410
+ return 1;
2411
+ }
2412
+ if (env.FORCE_COLOR === "false") {
2413
+ return 0;
2414
+ }
2415
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2416
+ }
2417
+ }
2418
+ function translateLevel(level) {
2419
+ if (level === 0) {
2420
+ return false;
2421
+ }
2422
+ return {
2423
+ level,
2424
+ hasBasic: true,
2425
+ has256: level >= 2,
2426
+ has16m: level >= 3
2427
+ };
2428
+ }
2429
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2430
+ const noFlagForceColor = envForceColor();
2431
+ if (noFlagForceColor !== void 0) {
2432
+ flagForceColor = noFlagForceColor;
2433
+ }
2434
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2435
+ if (forceColor === 0) {
2436
+ return 0;
2437
+ }
2438
+ if (sniffFlags) {
2439
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2440
+ return 3;
2441
+ }
2442
+ if (hasFlag("color=256")) {
2443
+ return 2;
2444
+ }
2445
+ }
2446
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2447
+ return 1;
2448
+ }
2449
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
2450
+ return 0;
2451
+ }
2452
+ const min = forceColor || 0;
2453
+ if (env.TERM === "dumb") {
2454
+ return min;
2455
+ }
2456
+ if (process2.platform === "win32") {
2457
+ const osRelease = os.release().split(".");
2458
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2459
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2460
+ }
2461
+ return 1;
2462
+ }
2463
+ if ("CI" in env) {
2464
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
2465
+ return 3;
2466
+ }
2467
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
2468
+ return 1;
2469
+ }
2470
+ return min;
2471
+ }
2472
+ if ("TEAMCITY_VERSION" in env) {
2473
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2474
+ }
2475
+ if (env.COLORTERM === "truecolor") {
2476
+ return 3;
2477
+ }
2478
+ if (env.TERM === "xterm-kitty") {
2479
+ return 3;
2480
+ }
2481
+ if (env.TERM === "xterm-ghostty") {
2482
+ return 3;
2483
+ }
2484
+ if (env.TERM === "wezterm") {
2485
+ return 3;
2486
+ }
2487
+ if ("TERM_PROGRAM" in env) {
2488
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2489
+ switch (env.TERM_PROGRAM) {
2490
+ case "iTerm.app": {
2491
+ return version >= 3 ? 3 : 2;
2492
+ }
2493
+ case "Apple_Terminal": {
2494
+ return 2;
2495
+ }
2496
+ }
2497
+ }
2498
+ if (/-256(color)?$/i.test(env.TERM)) {
2499
+ return 2;
2500
+ }
2501
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2502
+ return 1;
2503
+ }
2504
+ if ("COLORTERM" in env) {
2505
+ return 1;
2506
+ }
2507
+ return min;
2508
+ }
2509
+ function createSupportsColor(stream, options = {}) {
2510
+ const level = _supportsColor(stream, {
2511
+ streamIsTTY: stream && stream.isTTY,
2512
+ ...options
2513
+ });
2514
+ return translateLevel(level);
2515
+ }
2516
+ var supportsColor = {
2517
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2518
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2519
+ };
2520
+ var supports_color_default = supportsColor;
2521
+
2522
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
2523
+ function stringReplaceAll(string, substring, replacer) {
2524
+ let index = string.indexOf(substring);
2525
+ if (index === -1) {
2526
+ return string;
2527
+ }
2528
+ const substringLength = substring.length;
2529
+ let endIndex = 0;
2530
+ let returnValue = "";
2531
+ do {
2532
+ returnValue += string.slice(endIndex, index) + substring + replacer;
2533
+ endIndex = index + substringLength;
2534
+ index = string.indexOf(substring, endIndex);
2535
+ } while (index !== -1);
2536
+ returnValue += string.slice(endIndex);
2537
+ return returnValue;
2538
+ }
2539
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2540
+ let endIndex = 0;
2541
+ let returnValue = "";
2542
+ do {
2543
+ const gotCR = string[index - 1] === "\r";
2544
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
2545
+ endIndex = index + 1;
2546
+ index = string.indexOf("\n", endIndex);
2547
+ } while (index !== -1);
2548
+ returnValue += string.slice(endIndex);
2549
+ return returnValue;
2550
+ }
2551
+
2552
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
2553
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
2554
+ var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
2555
+ var STYLER = /* @__PURE__ */ Symbol("STYLER");
2556
+ var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
2557
+ var levelMapping = [
2558
+ "ansi",
2559
+ "ansi",
2560
+ "ansi256",
2561
+ "ansi16m"
2562
+ ];
2563
+ var styles2 = /* @__PURE__ */ Object.create(null);
2564
+ var applyOptions = (object, options = {}) => {
2565
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2566
+ throw new Error("The `level` option should be an integer from 0 to 3");
2567
+ }
2568
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2569
+ object.level = options.level === void 0 ? colorLevel : options.level;
2570
+ };
2571
+ var chalkFactory = (options) => {
2572
+ const chalk2 = (...strings) => strings.join(" ");
2573
+ applyOptions(chalk2, options);
2574
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
2575
+ return chalk2;
2576
+ };
2577
+ function createChalk(options) {
2578
+ return chalkFactory(options);
2579
+ }
2580
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
2581
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
2582
+ styles2[styleName] = {
2583
+ get() {
2584
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
2585
+ Object.defineProperty(this, styleName, { value: builder });
2586
+ return builder;
2587
+ }
2588
+ };
2589
+ }
2590
+ styles2.visible = {
2591
+ get() {
2592
+ const builder = createBuilder(this, this[STYLER], true);
2593
+ Object.defineProperty(this, "visible", { value: builder });
2594
+ return builder;
2595
+ }
2596
+ };
2597
+ var getModelAnsi = (model, level, type, ...arguments_) => {
2598
+ if (model === "rgb") {
2599
+ if (level === "ansi16m") {
2600
+ return ansi_styles_default[type].ansi16m(...arguments_);
2601
+ }
2602
+ if (level === "ansi256") {
2603
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
2604
+ }
2605
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
2606
+ }
2607
+ if (model === "hex") {
2608
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
2609
+ }
2610
+ return ansi_styles_default[type][model](...arguments_);
2611
+ };
2612
+ var usedModels = ["rgb", "hex", "ansi256"];
2613
+ for (const model of usedModels) {
2614
+ styles2[model] = {
2615
+ get() {
2616
+ const { level } = this;
2617
+ return function(...arguments_) {
2618
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
2619
+ return createBuilder(this, styler, this[IS_EMPTY]);
2620
+ };
2621
+ }
2622
+ };
2623
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2624
+ styles2[bgModel] = {
2625
+ get() {
2626
+ const { level } = this;
2627
+ return function(...arguments_) {
2628
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
2629
+ return createBuilder(this, styler, this[IS_EMPTY]);
2630
+ };
2631
+ }
2632
+ };
2633
+ }
2634
+ var proto = Object.defineProperties(() => {
2635
+ }, {
2636
+ ...styles2,
2637
+ level: {
2638
+ enumerable: true,
2639
+ get() {
2640
+ return this[GENERATOR].level;
2641
+ },
2642
+ set(level) {
2643
+ this[GENERATOR].level = level;
2644
+ }
2645
+ }
2646
+ });
2647
+ var createStyler = (open, close, parent) => {
2648
+ let openAll;
2649
+ let closeAll;
2650
+ if (parent === void 0) {
2651
+ openAll = open;
2652
+ closeAll = close;
2653
+ } else {
2654
+ openAll = parent.openAll + open;
2655
+ closeAll = close + parent.closeAll;
2656
+ }
2657
+ return {
2658
+ open,
2659
+ close,
2660
+ openAll,
2661
+ closeAll,
2662
+ parent
2663
+ };
2664
+ };
2665
+ var createBuilder = (self, _styler, _isEmpty) => {
2666
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2667
+ Object.setPrototypeOf(builder, proto);
2668
+ builder[GENERATOR] = self;
2669
+ builder[STYLER] = _styler;
2670
+ builder[IS_EMPTY] = _isEmpty;
2671
+ return builder;
2672
+ };
2673
+ var applyStyle = (self, string) => {
2674
+ if (self.level <= 0 || !string) {
2675
+ return self[IS_EMPTY] ? "" : string;
2676
+ }
2677
+ let styler = self[STYLER];
2678
+ if (styler === void 0) {
2679
+ return string;
2680
+ }
2681
+ const { openAll, closeAll } = styler;
2682
+ if (string.includes("\x1B")) {
2683
+ while (styler !== void 0) {
2684
+ string = stringReplaceAll(string, styler.close, styler.open);
2685
+ styler = styler.parent;
2686
+ }
2687
+ }
2688
+ const lfIndex = string.indexOf("\n");
2689
+ if (lfIndex !== -1) {
2690
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2691
+ }
2692
+ return openAll + string + closeAll;
2693
+ };
2694
+ Object.defineProperties(createChalk.prototype, styles2);
2695
+ var chalk = createChalk();
2696
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2697
+ var source_default = chalk;
2698
+
2699
+ // src/display/palette.ts
2700
+ var palette = {
2701
+ accent: "#d68cd6",
2702
+ // soft orchid magenta — pastel but luminous enough to read as focus/selection
2703
+ // Soft lilac: the one purple slot the palette had free — redder and brighter than the vibe
2704
+ // periwinkle, far off the link blue, lighter and more saturated than the chat heather, and a
2705
+ // clear step back from the orchid accent so code in prose no longer reads as a pink highlight.
2706
+ // Unbolded on purpose: code recurs several times a line, and bold stacked on the hue (and
2707
+ // brightened by some terminals) made it outweigh the prose it sits in.
2708
+ inlineCode: "#d5afee",
2709
+ tool: "#c8c8c8",
2710
+ // Named terminal colours in the TUI (theme.ts), so the user's terminal theme picks them; the
2711
+ // page takes these, chosen to sit with the pastels.
2712
+ info: "#7fd3dc",
2713
+ secondary: "#a0a0a0",
2714
+ muted: "#808080",
2715
+ reasoning: "#6495ed",
2716
+ // cornflower blue: thinking-block bar, dimmer than the accent
2717
+ // The busy line during a prefill (#912). A warmer, softer cornflower: the family of the reasoning
2718
+ // blue it hands over to, tinted by Working to about 10° off it, so the two do not read as one.
2719
+ prefill: "#7a90ee",
2720
+ warning: "#e5d49a",
2721
+ // soft pastel yellow — luminous but easy on the eyes, matches the other accents
2722
+ queued: "#e8b87a",
2723
+ // soft pastel orange — `next ›` label on the queued list, complements the yellow warning
2724
+ // The `▎` bar on a nested (subagent) user bubble. `▎` is a legend, not decoration: the same
2725
+ // glyph marks the Thinking block (reasoning) and the user speaking (accent), so the color IS
2726
+ // the attribution. This is deliberately NOT `queued` — that orange marks the user's own words
2727
+ // waiting to be sent, and a queued message sits in the chrome while a subagent runs, so the two
2728
+ // would collide on the exact axis #172 exists to disambiguate. Apricot instead: it echoes the
2729
+ // syntax theme's number/literal tone (highlight.ts), which makes no claim about who is speaking.
2730
+ subagent: "#e0b48f",
2731
+ // The `auto approve` badge in the status line. A standing mode, not a warning event, so it
2732
+ // does not take `warning`: the context gauge in the same line turns yellow at 80% fill and
2733
+ // the two were indistinguishable side by side. Soft coral — one step below the `bypass
2734
+ // approvals` red on the same severity ladder, and off the `queued` orange that also lives
2735
+ // in the chrome.
2736
+ autoApprove: "#e8a090",
2737
+ error: "#ef7b7b",
2738
+ success: "#9fd49f",
2739
+ userBg: "#303030",
2740
+ // Status-line mode tags. Every mode gets its own soft hue so the tag reads at a glance
2741
+ // (none of them near the yellow warning); the heavily-used modes take the brighter pastels
2742
+ // and the secondary ones sit a step back in saturation.
2743
+ modeAgent: "#d7a8d7",
2744
+ // soft magenta, echoes the accent — the default workhorse
2745
+ modePlan: "#8fd0c8",
2746
+ // soft teal-cyan; also the plan-checklist header (PlanProgress) — teal = plan everywhere
2747
+ modeVibe: "#b4aee0",
2748
+ // soft periwinkle between plan teal and agent magenta — vibe runs both phases
2749
+ // Minimal: a desaturated slate, deliberately the quietest of the work-mode tags — the mode is
2750
+ // the harness doing LESS, and the chip should not read as louder than agent's.
2751
+ modeMinimal: "#9aa8b8",
2752
+ // Grind (#556): dusty rose — warm like the effort the mode asks for, pinker than the coral
2753
+ // auto-approve badge on the same line and well off the warning yellow.
2754
+ modeGrind: "#d89aa8",
2755
+ // Heather: a desaturated violet, greyer and darker than the vibe periwinkle and agent magenta
2756
+ // on either side of it in hue. Purple-tinted so it no longer reads as a disabled/grey chip
2757
+ // (#380), but the low saturation keeps it a secondary mode that recedes next to the two
2758
+ // pastel workhorses.
2759
+ modeChat: "#a892c4",
2760
+ modeShell: "#9fd49f",
2761
+ // soft green, tied to the $ prompt
2762
+ // URLs in the model's prose: bare ones and the `(href)` of a markdown link. They were
2763
+ // chalk.dim, which on a light-on-dark terminal is a fainter white — indistinguishable from
2764
+ // the surrounding sentence (#397). A creamy lavender-blue: bluer and paler than the vibe
2765
+ // periwinkle so a link never reads as a mode tag, and well off the reasoning cornflower
2766
+ // that marks the Thinking bar. Underlined only on terminals that take OSC 8 hyperlinks
2767
+ // (markdown.ts): an underline promises a click, and elsewhere there is none to deliver.
2768
+ link: "#aac0f0",
2769
+ // `merged` on the status line's PR chip. GitHub's merged purple, so it reads without a legend.
2770
+ // Not `warning`, which the context gauge on the same line turns at 80% fill, and more saturated
2771
+ // than the agent tag's soft magenta at the other end of that line.
2772
+ prMerged: "#b48cf0"
2773
+ };
2774
+
2775
+ // src/ui/theme.ts
2776
+ var truecolor = { ...palette, info: "cyan", error: "red", success: "green" };
2777
+ var ansi16 = {
2778
+ accent: "magentaBright",
2779
+ inlineCode: "magenta",
2780
+ tool: "white",
2781
+ secondary: "gray",
2782
+ muted: "gray",
2783
+ reasoning: "blueBright",
2784
+ prefill: "blueBright",
2785
+ warning: "yellowBright",
2786
+ queued: "yellow",
2787
+ subagent: "yellow",
2788
+ autoApprove: "redBright",
2789
+ modeAgent: "magentaBright",
2790
+ modePlan: "cyanBright",
2791
+ modeVibe: "blue",
2792
+ modeMinimal: "white",
2793
+ modeGrind: "magenta",
2794
+ modeChat: "cyan",
2795
+ modeShell: "greenBright",
2796
+ prMerged: "magenta",
2797
+ link: "blueBright"
2798
+ };
2799
+ function themeForLevel(level) {
2800
+ return level === 1 ? { ...truecolor, ...ansi16 } : truecolor;
2801
+ }
2802
+ var theme = themeForLevel(source_default.level);
2803
+ function themeChalk(color) {
2804
+ return color.startsWith("#") ? source_default.hex(color) : source_default[color];
2805
+ }
2806
+
2807
+ export {
2808
+ require_supports_hyperlinks,
2809
+ queuedPreview,
2810
+ isWarmEdge,
2811
+ buildSummary,
2812
+ hasActivity,
2813
+ acceptSuggestion,
2814
+ createController,
2815
+ source_default,
2816
+ palette,
2817
+ theme,
2818
+ themeChalk
2819
+ };