@alexwkleung/reika 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +15 -0
  2. package/README.zh-CN.md +15 -0
  3. package/dist/agent/compaction.js +82 -27
  4. package/dist/agent/loop.js +84 -20
  5. package/dist/agent/prefillcost.js +16 -0
  6. package/dist/agent/prompt.js +5 -2
  7. package/dist/cli.js +5 -11
  8. package/dist/context/bootstrap.js +1 -1
  9. package/dist/debug.js +15 -0
  10. package/dist/{headless.js → headless/headless.js} +185 -48
  11. package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
  12. package/dist/headless/headlessprompt.js +132 -0
  13. package/dist/mcp/client.js +97 -5
  14. package/dist/mcp/manager.js +15 -2
  15. package/dist/provider/client.js +13 -0
  16. package/dist/session.js +12 -1
  17. package/dist/{skills.js → skills/skills.js} +93 -13
  18. package/dist/store/sessions.js +40 -3
  19. package/dist/store/transcript.js +38 -1
  20. package/dist/tools/_carriers.js +119 -0
  21. package/dist/tools/_danger.js +305 -82
  22. package/dist/tools/_readonly.js +13 -12
  23. package/dist/tools/_sandbox.js +13 -5
  24. package/dist/ui/App.js +288 -83
  25. package/dist/ui/Approval.js +80 -33
  26. package/dist/ui/Confirm.js +1 -27
  27. package/dist/ui/DiffView.js +24 -14
  28. package/dist/ui/Question.js +152 -19
  29. package/dist/ui/ResumeSelect.js +13 -6
  30. package/dist/ui/Scrollback.js +44 -8
  31. package/dist/ui/Status.js +35 -10
  32. package/dist/ui/commands.js +1 -1
  33. package/dist/ui/dialogspecs.js +38 -0
  34. package/dist/ui/layout.js +149 -6
  35. package/dist/ui/markdown.js +6 -5
  36. package/dist/ui/pr.js +15 -9
  37. package/dist/ui/reactbuild.js +15 -0
  38. package/dist/ui/summary.js +3 -2
  39. package/dist/ui/termtext.js +5 -1
  40. package/dist/ui/theme.js +5 -0
  41. package/dist/ui/tui.js +9 -0
  42. package/package.json +1 -1
  43. /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
@@ -68,6 +68,14 @@ const MAX_STDOUT_LINE_CHARS = 8 * 1024 * 1024;
68
68
  // immediate SIGTERM. The process-exit hook below stays an immediate kill: there is no time to wait.
69
69
  const CLOSE_GRACE_MS = 2000;
70
70
  const TERM_GRACE_MS = 1000;
71
+ // The stdio binding's SHOULD for a server that exits unexpectedly: restart it (#592). Lazily, on
72
+ // the next call — a server nobody calls again costs nothing — and bounded, so one that crashes on
73
+ // start or on every call is given up on rather than respawned forever. Per session, never reset:
74
+ // a server that keeps dying after a quiet spell is still one that keeps dying.
75
+ const MAX_RESTARTS = 3;
76
+ // Waited before each respawn, by its index. The first is immediate (one crash is the common case
77
+ // and the call is waiting); the rest give a server that dies on start time to stop flapping.
78
+ const RESTART_BACKOFF_MS = [0, 1000, 3000];
71
79
  // Every spawned server, killed when reika exits whatever route it leaves by. A stdio server's
72
80
  // parent dying closes its pipes — which most servers treat as EOF and exit on — but one mid-call
73
81
  // would linger as an orphan, and one hook covers every session (and every test) at once.
@@ -103,9 +111,19 @@ export class McpClient {
103
111
  discardingLine = false;
104
112
  stderrTail = '';
105
113
  exitError;
114
+ connectedOnce = false;
115
+ closed = false;
116
+ restartBackoffMs;
117
+ // How many times the server was respawned after exiting, for `/mcp`.
118
+ restarts = 0;
119
+ // Set once the restart budget is spent: the reason every later call fails with.
120
+ gaveUpError;
121
+ // One respawn shared by every call that finds the server gone, so two parallel calls start one.
122
+ restarting;
106
123
  constructor(config, opts = {}) {
107
124
  this.config = config;
108
125
  this.probeWaitMs = opts.probeWaitMs ?? PROBE_WAIT_MS;
126
+ this.restartBackoffMs = opts.restartBackoffMs ?? RESTART_BACKOFF_MS;
109
127
  }
110
128
  get name() {
111
129
  return this.config.name;
@@ -123,6 +141,10 @@ export class McpClient {
123
141
  get dead() {
124
142
  return this.exitError !== undefined;
125
143
  }
144
+ // Dead for the rest of the session: the restart budget is spent.
145
+ get gaveUp() {
146
+ return this.gaveUpError !== undefined;
147
+ }
126
148
  // The handshake's own bound: a server that is slow to start costs a session's first paint, which
127
149
  // a per-call timeout has no reason to govern (see McpServerConfig.connectTimeoutMs).
128
150
  get connectTimeoutMs() {
@@ -131,16 +153,56 @@ export class McpClient {
131
153
  // Spawn + handshake + tool discovery. Resolves only on a server that answered the handshake AND
132
154
  // `tools/list`: a server that started but says nothing is a failure the user has to see.
133
155
  async connect() {
156
+ this.tools = await this.spawnAndHandshake();
157
+ this.connectedOnce = true;
158
+ }
159
+ async spawnAndHandshake() {
134
160
  await this.start();
135
161
  try {
136
162
  await this.handshake();
137
- this.tools = await this.listTools();
163
+ return await this.listTools();
138
164
  }
139
165
  catch (e) {
140
- void this.close();
141
- throw new Error(this.explain(e));
166
+ const err = new Error(this.explain(e));
167
+ // Kept as the reason the server is down, ahead of the exit the kill below causes.
168
+ this.exitError ??= err;
169
+ this.stopChild();
170
+ throw err;
142
171
  }
143
172
  }
173
+ // A server that exited after a successful connect is respawned here, before the call that needs
174
+ // it. The call that was in flight when it died is NOT retried: it may have acted before the crash.
175
+ async ensureRunning(signal) {
176
+ if (this.gaveUpError)
177
+ throw this.gaveUpError;
178
+ this.restarting ??= this.restart().finally(() => {
179
+ this.restarting = undefined;
180
+ });
181
+ await raceAbort(this.restarting, signal);
182
+ }
183
+ async restart() {
184
+ const last = this.exitError?.message ?? 'server exited';
185
+ if (this.restarts >= MAX_RESTARTS) {
186
+ this.gaveUpError = new Error(`${last}; not restarted again after ${MAX_RESTARTS} restarts this session`);
187
+ throw this.gaveUpError;
188
+ }
189
+ const wait = this.restartBackoffMs[this.restarts] ?? this.restartBackoffMs.at(-1) ?? 0;
190
+ this.restarts++;
191
+ debugLog(`[reika:debug] mcp ${this.name}: restart ${this.restarts} after: ${last}\n`);
192
+ if (wait > 0)
193
+ await delay(wait);
194
+ // Per-process state; the era is probed again since the binary may have changed under us.
195
+ this.era = undefined;
196
+ this.stdoutBuffer = '';
197
+ this.discardingLine = false;
198
+ this.stderrTail = '';
199
+ this.exitError = undefined;
200
+ const tools = await this.spawnAndHandshake();
201
+ // The tool list is fixed at session start (round-0 prefix), so a different one is surfaced the
202
+ // way list_changed is rather than adopted.
203
+ if (JSON.stringify(tools) !== JSON.stringify(this.tools))
204
+ this.toolsChanged = true;
205
+ }
144
206
  // The spec's stdio probe: `server/discover` first; a result or a spec-range error is a modern
145
207
  // server, anything else (or silence) a legacy one. The spec's version of "silence" is a timeout,
146
208
  // which a modern server behind a cold `npx` install would trip — so after a short wait
@@ -244,6 +306,10 @@ export class McpClient {
244
306
  }
245
307
  async callTool(name, args, opts = {}) {
246
308
  const timeoutMs = opts.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
309
+ // Only awaited when a restart is due: a tick's yield here would let an abort land before the
310
+ // request is even sent, and the server would never hear it was cancelled.
311
+ if (this.exitError && this.connectedOnce && !this.closed)
312
+ await this.ensureRunning(opts.signal);
247
313
  let state;
248
314
  for (let attempt = 0;; attempt++) {
249
315
  const res = await this.request('tools/call', { name, arguments: args, ...(state !== undefined ? { requestState: state } : {}) }, timeoutMs, { signal: opts.signal });
@@ -267,6 +333,10 @@ export class McpClient {
267
333
  // Resolves once the child is gone. Callers that are leaving anyway need not await it: the
268
334
  // pending exit keeps the event loop alive until the server has had its chance to exit on EOF.
269
335
  close() {
336
+ this.closed = true;
337
+ return this.stopChild();
338
+ }
339
+ stopChild() {
270
340
  this.rejectInFlight(new Error('closed'));
271
341
  const child = this.child;
272
342
  this.child = undefined;
@@ -315,13 +385,16 @@ export class McpClient {
315
385
  // A child that dies takes every in-flight request with it. The error surfaces here rather
316
386
  // than as a hang: a server that exits mid-call is exactly the bug the user must be told.
317
387
  child.on('error', (e) => {
318
- this.exitError = new Error(`could not start ${command}: ${e.message}`);
388
+ this.exitError ??= new Error(`could not start ${command}: ${e.message}`);
319
389
  this.rejectInFlight(this.exitError);
320
390
  reject(this.exitError);
321
391
  });
322
392
  child.on('exit', (code, signal) => {
323
393
  liveChildren.delete(child);
324
- this.exitError = new Error(`server exited (${signal ? `signal ${signal}` : `code ${code}`})${this.stderrSuffix()}`);
394
+ // A process already replaced by a restart says nothing about the one running now.
395
+ if (this.child !== undefined && this.child !== child)
396
+ return;
397
+ this.exitError ??= new Error(`server exited (${signal ? `signal ${signal}` : `code ${code}`})${this.stderrSuffix()}`);
325
398
  this.rejectInFlight(this.exitError);
326
399
  });
327
400
  liveChildren.add(child);
@@ -410,6 +483,8 @@ export class McpClient {
410
483
  }
411
484
  request(method, params, timeoutMs, opts = {}) {
412
485
  const { signal } = opts;
486
+ if (this.closed)
487
+ return Promise.reject(new Error('closed'));
413
488
  if (this.exitError)
414
489
  return Promise.reject(this.exitError);
415
490
  if (signal?.aborted)
@@ -521,6 +596,23 @@ function modernVersionError(e) {
521
596
  function unsupportedVersionsText(versions) {
522
597
  return `server speaks protocol ${versions.join(', ') || '(none listed)'}; reika speaks ${MODERN_PROTOCOL_VERSION} and ${[...LEGACY_VERSIONS].join(', ')}`;
523
598
  }
599
+ function raceAbort(promise, signal) {
600
+ if (!signal)
601
+ return promise;
602
+ if (signal.aborted)
603
+ return Promise.reject(new Error('aborted'));
604
+ return new Promise((resolve, reject) => {
605
+ const onAbort = () => reject(new Error('aborted'));
606
+ signal.addEventListener('abort', onAbort, { once: true });
607
+ promise.then(v => {
608
+ signal.removeEventListener('abort', onAbort);
609
+ resolve(v);
610
+ }, (e) => {
611
+ signal.removeEventListener('abort', onAbort);
612
+ reject(e);
613
+ });
614
+ });
615
+ }
524
616
  function delay(ms) {
525
617
  return new Promise(resolve => setTimeout(() => resolve(undefined), ms).unref());
526
618
  }
@@ -72,6 +72,12 @@ export async function connectMcpServers(servers) {
72
72
  get dead() {
73
73
  return entry.dead;
74
74
  },
75
+ get restarts() {
76
+ return entry.restarts;
77
+ },
78
+ get gaveUp() {
79
+ return entry.gaveUp;
80
+ },
75
81
  });
76
82
  }
77
83
  return {
@@ -136,10 +142,17 @@ export function formatMcpList(statuses) {
136
142
  lines.push(` ${s.name} — ${s.tools} tool${s.tools === 1 ? '' : 's'} (${who})${s.alwaysAsk ? ' — asks before every call' : ''}`);
137
143
  for (const c of s.commands)
138
144
  lines.push(` /${c.name.padEnd(28)} ${c.description}`);
139
- if (s.dead)
140
- lines.push(` (this server has exited — its tools are still in the tool list, so calls fail until reika restarts)`);
145
+ if (s.gaveUp)
146
+ lines.push(` (this server kept exiting and is not restarted again after ${plural(s.restarts ?? 0, 'restart')} — its tools are still in the tool list, so calls fail until reika restarts)`);
147
+ else if (s.dead)
148
+ lines.push(` (this server has exited — it is restarted on its next call)`);
149
+ else if (s.restarts)
150
+ lines.push(` (restarted ${s.restarts === 1 ? 'once' : `${s.restarts} times`} after exiting)`);
141
151
  if (s.changed)
142
152
  lines.push(` (this server announced a changed tool list — restart reika to pick it up; the tool list is part of the cached request prefix)`);
143
153
  }
144
154
  return lines.join('\n');
145
155
  }
156
+ function plural(n, word) {
157
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
158
+ }
@@ -48,6 +48,7 @@ export async function callModel(opts) {
48
48
  // consume attempt: a retry only happens before any chunk arrived (the `received` gate below), so
49
49
  // there is never a stale one to clear.
50
50
  let engineTimings;
51
+ let enginePrompt;
51
52
  // Reset per consume attempt: the logprobs degrade below re-sends from scratch, so a retry's
52
53
  // prefill must not be timed from the rejected request's start.
53
54
  let startedAt = Date.now();
@@ -125,6 +126,16 @@ export async function callModel(opts) {
125
126
  perSecond: et.predicted_per_second,
126
127
  };
127
128
  }
129
+ // Prefill stats ride the same object, cumulative the same way; each field is taken on its own.
130
+ if (et) {
131
+ const prompt = {
132
+ ...(typeof et.prompt_n === 'number' ? { promptN: et.prompt_n } : {}),
133
+ ...(typeof et.prompt_ms === 'number' ? { promptMs: et.prompt_ms } : {}),
134
+ ...(typeof et.cache_n === 'number' ? { cacheN: et.cache_n } : {}),
135
+ };
136
+ if (Object.keys(prompt).length > 0)
137
+ enginePrompt = prompt;
138
+ }
128
139
  // Logprobs ride the choice, not the delta, and a chunk can carry them with no delta at all
129
140
  // — so collect before the delta guard. Normalized to SampledToken here (the wire's null
130
141
  // top_logprobs becomes an absent `top`) so nothing downstream handles wire shapes.
@@ -277,6 +288,7 @@ export async function callModel(opts) {
277
288
  finishReason,
278
289
  timing: timing(),
279
290
  ...(engineTimings ? { engineTimings } : {}),
291
+ ...(enginePrompt ? { enginePrompt } : {}),
280
292
  ...(sampled.length > 0 ? { sampled } : {}),
281
293
  };
282
294
  }
@@ -300,6 +312,7 @@ export async function callModel(opts) {
300
312
  finishReason,
301
313
  timing: timing(),
302
314
  ...(engineTimings ? { engineTimings } : {}),
315
+ ...(enginePrompt ? { enginePrompt } : {}),
303
316
  ...(sampled.length > 0 ? { sampled } : {}),
304
317
  };
305
318
  }
package/dist/session.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { assertRawConfig, loadConfig, resolveProfile, withProbedLimits } from './config.js';
2
2
  import { ensureNoteSlot } from './provider/noteslot.js';
3
+ import { debugLog, formatEndpointLine } from './debug.js';
3
4
  import { repoMapBudgetFor } from './context/repomap.js';
4
5
  import { needsLimitsProbe, probeModelLimits, } from './provider/modellimits.js';
5
6
  import { bootstrap, refitRepoMap } from './context/bootstrap.js';
@@ -57,6 +58,11 @@ export async function createSession(opts) {
57
58
  // so it never runs between rounds (a probe there would evict a single-slot server's cache), and
58
59
  // asked again at a submit if the server was not up.
59
60
  void ensureNoteSlot(resolveProfile(cfg, profile));
61
+ const logEndpoint = () => {
62
+ const p = resolveProfile(cfg, profile);
63
+ debugLog(formatEndpointLine(profile, p.model, p.baseURL));
64
+ };
65
+ logEndpoint();
60
66
  // No route out → no web tools this session (#392). Checked once, here, because the tool list is
61
67
  // part of the cached prefix; the per-turn latch in the tools covers a drop later.
62
68
  const offline = isOffline();
@@ -166,13 +172,16 @@ export async function createSession(opts) {
166
172
  emit(n);
167
173
  },
168
174
  onUsage: u => {
169
- lastUsage = u;
175
+ // An estimate says nothing about the last real request, which is what lastUsage is for.
176
+ if (!u.estimated)
177
+ lastUsage = u;
170
178
  totals = {
171
179
  promptTokens: totals.promptTokens + u.promptTokens,
172
180
  completionTokens: totals.completionTokens + u.completionTokens,
173
181
  ...(u.cachedTokens != null || totals.cachedTokens != null
174
182
  ? { cachedTokens: (totals.cachedTokens ?? 0) + (u.cachedTokens ?? 0) }
175
183
  : {}),
184
+ ...(u.estimated || totals.estimated ? { estimated: true } : {}),
176
185
  };
177
186
  events.onUsage?.(u);
178
187
  },
@@ -250,6 +259,7 @@ export async function createSession(opts) {
250
259
  decodeRate = undefined;
251
260
  genReserve = new GenReserve();
252
261
  changed();
262
+ logEndpoint();
253
263
  void ensureNoteSlot(resolveProfile(cfg, name));
254
264
  if (!needsLimitsProbe(next))
255
265
  return Promise.resolve([]);
@@ -281,6 +291,7 @@ export async function createSession(opts) {
281
291
  if (profile !== 'default') {
282
292
  profile = 'default';
283
293
  changed();
294
+ logEndpoint();
284
295
  }
285
296
  };
286
297
  return {
@@ -6,22 +6,30 @@ import { delimiter, dirname, extname, isAbsolute, join, resolve } from 'node:pat
6
6
  import { fileURLToPath } from 'node:url';
7
7
  const GLOBAL_DEFAULT = join(homedir(), '.config', 'reika', 'skills');
8
8
  const PROJECT_RELATIVE = '.reika/skills';
9
- // The skills that ship in the package (`issue`, `review`), beside `dist/` — one level up from this
10
- // module whether it runs as src/skills.ts or dist/skills.js.
11
- export const BUNDLED_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'skills');
9
+ // The skills that ship in the package (`issue`, `review`), beside `dist/` — two levels up from this
10
+ // module whether it runs as src/skills/skills.ts or dist/skills/skills.js.
11
+ export const BUNDLED_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills');
12
+ // Other harnesses' skill dirs (#861), so a skill folder works where it already is. Global is the
13
+ // agent-agnostic `~/.agents/skills` only — never `~/.claude/skills`, another app's config dir; a
14
+ // Claude Code user links it there. Read after `homedir()` at call time, so a test's HOME applies.
15
+ const PROJECT_IMPORTED = ['.claude/skills', '.agents/skills'];
16
+ const GLOBAL_IMPORTED = '.agents/skills';
12
17
  export async function loadSkills(cwd, bundledDir = BUNDLED_DIR) {
13
18
  const globalDir = process.env.REIKA_SKILLS_DIR
14
19
  ? expandHome(process.env.REIKA_SKILLS_DIR)
15
20
  : GLOBAL_DEFAULT;
16
21
  const projectDir = join(cwd, PROJECT_RELATIVE);
17
- const [bundledSkills, globalSkills, projectSkills] = await Promise.all([
22
+ // Lowest precedence first; a later dir replaces an earlier one on a name collision. Reika's own
23
+ // dirs always win, then project over global, and `.agents` over `.claude`.
24
+ const layers = await Promise.all([
18
25
  loadFromDir(bundledDir, 'bundled'),
26
+ loadFromDir(join(homedir(), GLOBAL_IMPORTED), 'global', `~/${GLOBAL_IMPORTED}`),
27
+ ...PROJECT_IMPORTED.map(rel => loadFromDir(join(cwd, rel), 'project', rel)),
19
28
  loadFromDir(globalDir, 'global'),
20
29
  loadFromDir(projectDir, 'project'),
21
30
  ]);
22
- // The user's own copy wins: project over global over bundled, on name collision.
23
31
  const byName = new Map();
24
- for (const s of [...bundledSkills, ...globalSkills, ...projectSkills])
32
+ for (const s of layers.flat())
25
33
  byName.set(s.name, s);
26
34
  const env = await skillEnvironment(cwd, [...byName.values()]);
27
35
  return Array.from(byName.values())
@@ -97,7 +105,7 @@ async function findGitDir(start) {
97
105
  return null;
98
106
  }
99
107
  }
100
- async function loadFromDir(dir, source) {
108
+ async function loadFromDir(dir, source, from) {
101
109
  let entries;
102
110
  try {
103
111
  const raw = await readdir(dir, { withFileTypes: true });
@@ -127,12 +135,19 @@ async function loadFromDir(dir, source) {
127
135
  const name = entry.name.toLowerCase();
128
136
  if (!isValidName(name))
129
137
  continue;
130
- const skillFile = await findCanonicalSkillFile(join(dir, entry.name));
138
+ const skillDir = resolve(dir, entry.name);
139
+ const skillFile = await findCanonicalSkillFile(skillDir);
131
140
  if (!skillFile)
132
141
  continue;
133
- const loaded = await readSkill(skillFile, name, source);
134
- if (loaded)
135
- byName.set(name, loaded);
142
+ const loaded = await readSkill(skillFile, name, source, from);
143
+ if (!loaded)
144
+ continue;
145
+ const files = await listSupportingFiles(skillDir, skillFile);
146
+ if (files.length > 0) {
147
+ const body = rewriteSkillPaths(loaded.body, skillDir, files);
148
+ loaded.body = `${skillDirAnchor(skillDir, files)}\n\n${body}`;
149
+ }
150
+ byName.set(name, loaded);
136
151
  }
137
152
  else {
138
153
  if (extname(entry.name).toLowerCase() !== '.md')
@@ -140,13 +155,77 @@ async function loadFromDir(dir, source) {
140
155
  const name = entry.name.slice(0, -3).toLowerCase();
141
156
  if (!isValidName(name))
142
157
  continue;
143
- const loaded = await readSkill(join(dir, entry.name), name, source);
158
+ const loaded = await readSkill(join(dir, entry.name), name, source, from);
144
159
  if (loaded && !byName.has(name))
145
160
  byName.set(name, loaded);
146
161
  }
147
162
  }
148
163
  return Array.from(byName.values());
149
164
  }
165
+ // --- supporting files (#861) -----------------------------------------------------------------
166
+ // A skill written for another harness names its files relative to its own directory ("run
167
+ // `scripts/extract.py`"), and the body reaches the model with nothing saying where that is, so
168
+ // the path resolved against the cwd. The anchor names the directory and what is in it — names
169
+ // only, never contents. Nothing here runs a script: the model runs it through `bash`, behind the
170
+ // same approval gate and sandbox as any other command.
171
+ const MAX_LISTED_FILES = 20;
172
+ const MAX_WALKED_FILES = 200;
173
+ const MAX_WALK_DEPTH = 3;
174
+ const SKIPPED_DIRS = new Set(['node_modules', '__pycache__']);
175
+ export async function listSupportingFiles(skillDir, skillFile) {
176
+ const files = [];
177
+ async function walk(dir, rel, depth) {
178
+ if (depth > MAX_WALK_DEPTH || files.length >= MAX_WALKED_FILES)
179
+ return;
180
+ let entries;
181
+ try {
182
+ entries = await readdir(dir, { withFileTypes: true });
183
+ }
184
+ catch {
185
+ return;
186
+ }
187
+ entries.sort((a, b) => a.name.localeCompare(b.name));
188
+ for (const e of entries) {
189
+ if (files.length >= MAX_WALKED_FILES)
190
+ return;
191
+ if (e.name.startsWith('.'))
192
+ continue;
193
+ const path = join(dir, e.name);
194
+ const relPath = rel ? `${rel}/${e.name}` : e.name;
195
+ if (e.isDirectory()) {
196
+ if (!SKIPPED_DIRS.has(e.name))
197
+ await walk(path, relPath, depth + 1);
198
+ }
199
+ else if (path !== skillFile) {
200
+ files.push(relPath);
201
+ }
202
+ }
203
+ }
204
+ await walk(skillDir, '', 1);
205
+ return files;
206
+ }
207
+ export function skillDirAnchor(skillDir, files) {
208
+ const shown = files.slice(0, MAX_LISTED_FILES);
209
+ const more = files.length - shown.length;
210
+ const tail = more <= 0 ? '' : files.length >= MAX_WALKED_FILES ? ', and more' : `, and ${more} more`;
211
+ return [`This skill's files are in ${skillDir}.`, `Files: ${shown.join(', ')}${tail}`].join('\n');
212
+ }
213
+ // The anchor alone was not enough (#861, lfm2.5-24b, 1/3): the model found the script through it,
214
+ // then ran the body's command as written — `sh scripts/tally.sh` from the project — and when that
215
+ // failed, copied the script into the project. So a reference to a file that exists in the skill
216
+ // directory is rewritten to its absolute path, and the command the model copies is already right.
217
+ // Only exact names of real files, at a word start (not after `/`), so prose and the user's own
218
+ // paths are left alone.
219
+ export function rewriteSkillPaths(body, skillDir, files) {
220
+ if (files.length === 0)
221
+ return body;
222
+ const names = [...files].sort((a, b) => b.length - a.length).map(escapeRegExp);
223
+ const ref = new RegExp(`(^|[\\s\`'"(=])(?:\\./)?(${names.join('|')})(?=$|[\\s\`'")\\],;:!?]|\\.(?:$|\\s))`, 'gm');
224
+ return body.replace(ref, (_, lead, file) => lead + join(skillDir, file));
225
+ }
226
+ function escapeRegExp(text) {
227
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
228
+ }
150
229
  async function findCanonicalSkillFile(dir) {
151
230
  try {
152
231
  const entries = await readdir(dir);
@@ -158,7 +237,7 @@ async function findCanonicalSkillFile(dir) {
158
237
  return null;
159
238
  }
160
239
  }
161
- async function readSkill(path, name, source) {
240
+ async function readSkill(path, name, source, from) {
162
241
  try {
163
242
  const text = await readFile(path, 'utf8');
164
243
  const { meta, body } = parseFrontmatter(text);
@@ -168,6 +247,7 @@ async function readSkill(path, name, source) {
168
247
  description,
169
248
  body: body.trim(),
170
249
  source,
250
+ ...(from ? { from } : {}),
171
251
  path,
172
252
  triggers: parseTriggers(meta.triggers),
173
253
  requires: parseRequires(meta.requires),
@@ -35,10 +35,17 @@ export function serializeSession(sides, meta) {
35
35
  if (sides.chat.length === 0)
36
36
  return body;
37
37
  // The header's title is derived from the agent side; a session spent in chat takes the chat's.
38
+ // `modes` covers the agent side only, so the chat side is counted here (#875): without it a
39
+ // chat-only file read as an empty timeline, and a listing could not tell it held a chat.
38
40
  const nl = body.indexOf('\n');
39
41
  const header = JSON.parse(body.slice(0, nl));
40
42
  const chatTitle = header.title === undefined ? deriveTitle(sides.chat) : undefined;
41
- const head = chatTitle === undefined ? body.slice(0, nl) : JSON.stringify({ ...header, title: chatTitle });
43
+ const chatTurns = countRealTurns(sides.chat);
44
+ const head = JSON.stringify({
45
+ ...header,
46
+ ...(chatTitle !== undefined ? { title: chatTitle } : {}),
47
+ ...(chatTurns > 0 ? { chatTurns } : {}),
48
+ });
42
49
  const chat = sides.chat.map(m => JSON.stringify(m)).join('\n');
43
50
  return `${head}${body.slice(nl)}${JSON.stringify(CHAT_SEGMENT)}\n${chat}\n`;
44
51
  }
@@ -55,7 +62,10 @@ export async function writeSession(path, sides, meta) {
55
62
  // Newest first. Only the header line is read — a session with its tool payloads can run to
56
63
  // megabytes, and the list needs a title and a date. Unreadable or foreign files are skipped: a
57
64
  // listing is never an error.
58
- export async function listSessions(dir) {
65
+ // `root` reads a header's `mode: "chat"` as a chat (#882): every file there is a /save, and a
66
+ // chat-mode /save writes the chat scrollback. Never in a project dir, where an auto-save taken
67
+ // right after Shift+Tab into chat says `chat` while holding only the agent side (#880).
68
+ export async function listSessions(dir, root = false) {
59
69
  let names;
60
70
  try {
61
71
  names = (await readdir(dir)).filter(n => n.endsWith('.jsonl'));
@@ -69,12 +79,15 @@ export async function listSessions(dir) {
69
79
  const meta = await readHeader(path);
70
80
  if (!meta || typeof meta.savedAt !== 'string')
71
81
  continue;
82
+ const chatTurns = typeof meta.chatTurns === 'number' && meta.chatTurns > 0 ? meta.chatTurns : undefined;
72
83
  entries.push({
73
84
  path,
74
85
  ...(typeof meta.title === 'string' ? { title: meta.title } : {}),
75
86
  savedAt: meta.savedAt,
76
87
  messageCount: typeof meta.messageCount === 'number' ? meta.messageCount : 0,
77
88
  ...(typeof meta.model === 'string' ? { model: meta.model } : {}),
89
+ ...(chatTurns !== undefined ? { chatTurns } : {}),
90
+ ...(chatTurns !== undefined || (root && meta.mode === 'chat') ? { chat: true } : {}),
78
91
  });
79
92
  }
80
93
  return entries.sort((a, b) => b.savedAt.localeCompare(a.savedAt));
@@ -103,17 +116,32 @@ export async function loadSession(path) {
103
116
  const lines = (await readFile(path, 'utf8')).split('\n').filter(l => l.trim().length > 0);
104
117
  const sides = { agent: [], chat: [] };
105
118
  let side = sides.agent;
119
+ let marked = false;
106
120
  // Line 0 is the meta header.
107
121
  for (const line of lines.slice(1)) {
108
122
  const rec = JSON.parse(line);
109
123
  if ('segment' in rec) {
124
+ marked = true;
110
125
  side = sides.chat;
111
126
  continue;
112
127
  }
113
128
  side.push(rec);
114
129
  }
130
+ // A /save made in chat mode writes the chat scrollback through the plain transcript serializer,
131
+ // so it carries no segment marker (#880). Its prompts are what say so, not the header's `mode`:
132
+ // an auto-save taken right after Shift+Tab into chat is agent-only, unmarked, with `mode: "chat"`
133
+ // in its header too. Reading the prompts also fixes the chat saves made before this rule.
134
+ if (!marked && isChatOnly(sides.agent)) {
135
+ sides.chat = sides.agent;
136
+ sides.agent = [];
137
+ }
115
138
  return sides;
116
139
  }
140
+ // Every prompt was sent in chat mode — the session stamps each user message with its mode.
141
+ function isChatOnly(messages) {
142
+ const prompts = messages.filter(m => m.role === 'user' && !m.meta);
143
+ return prompts.length > 0 && prompts.every(m => m.role === 'user' && m.mode === 'chat');
144
+ }
117
145
  // The model-facing history a resumed session continues from, rebuilt from its scrollback: what
118
146
  // the loop pushes to history, minus what only the UI sees (command echoes, notices, subagent
119
147
  // rows, compaction notes, shell-mode output). Folds are not restored — the scrollback keeps every
@@ -125,7 +153,7 @@ export function modelHistoryFromScrollback(messages) {
125
153
  case 'user':
126
154
  return !m.meta;
127
155
  case 'assistant':
128
- return !m.nested && !m.compactionNote;
156
+ return !m.nested && !m.compactionNote && !m.discarded;
129
157
  case 'tool':
130
158
  return !m.nested;
131
159
  default:
@@ -133,6 +161,15 @@ export function modelHistoryFromScrollback(messages) {
133
161
  }
134
162
  });
135
163
  }
164
+ // The header for a /save. In chat mode the saved scrollback is the chat side, so it carries the
165
+ // chat count the listing filters on (#882) — counted here rather than in buildTranscriptMeta,
166
+ // whose auto-save callers pass the agent side under whatever mode is current.
167
+ export function saveHeader(meta, msgs) {
168
+ if (meta.mode !== 'chat')
169
+ return meta;
170
+ const chatTurns = countRealTurns(msgs);
171
+ return chatTurns > 0 ? { ...meta, chatTurns } : meta;
172
+ }
136
173
  // Real prompts and shell commands — what makes a scrollback worth a file, as opposed to the
137
174
  // splash notices or a /resume that was opened and left.
138
175
  export function countRealTurns(messages) {
@@ -1,6 +1,7 @@
1
1
  import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import { randomBytes } from 'node:crypto';
3
3
  import { join } from 'node:path';
4
+ import { compactThreshold } from '../agent/compaction.js';
4
5
  import { scrubDisplay } from '../ui/scrub.js';
5
6
  import { changeLabel, contextFill, formatDurationMs, formatShrink, kFormat } from '../ui/format.js';
6
7
  import { foldedAssistantFields } from '../ui/reasoningfold.js';
@@ -8,6 +9,41 @@ import { foldedAssistantFields } from '../ui/reasoningfold.js';
8
9
  // persistent-sessions loader (which will append message records the same way) can migrate old
9
10
  // files instead of choking on them. Start at 1; never reuse a number.
10
11
  export const TRANSCRIPT_VERSION = 1;
12
+ export function buildTranscriptMeta(opts) {
13
+ const { msgs, status } = opts;
14
+ const { totals, lastUsage: last, shrink, contextWindow: window } = status;
15
+ const usable = window ? Math.round(compactThreshold(window, status.minGenTokens)) : undefined;
16
+ // Computed exactly as the status bar computes it — same turn count, same last-call-else-estimate
17
+ // context — so the header and a screenshot of the footer can never disagree (#199).
18
+ const usage = {
19
+ turns: msgs.filter(m => m.role === 'assistant').length,
20
+ promptTokens: totals.promptTokens,
21
+ completionTokens: totals.completionTokens,
22
+ ...(totals.cachedTokens != null ? { cachedTokens: totals.cachedTokens } : {}),
23
+ ...(totals.estimated ? { tokensEstimated: true } : {}),
24
+ contextTokens: last?.promptTokens ?? status.estimatedContext,
25
+ // No call has landed yet, so the context size above is the pre-send estimate.
26
+ ...(last?.promptTokens == null ? { contextEstimated: true } : {}),
27
+ ...(window ? { contextWindow: window } : {}),
28
+ ...(usable ? { contextUsable: usable } : {}),
29
+ ...(last?.cachedTokens != null ? { lastCachedTokens: last.cachedTokens } : {}),
30
+ ...(shrink.sheds > 0 || shrink.folds > 0
31
+ ? { ...shrink, shrinkEvents: status.shrinkEvents }
32
+ : {}),
33
+ };
34
+ return {
35
+ version: TRANSCRIPT_VERSION,
36
+ // Stamped here: the serializers below are pure and take no clock.
37
+ savedAt: new Date().toISOString(),
38
+ model: opts.model,
39
+ baseURL: opts.baseURL,
40
+ cwd: opts.cwd,
41
+ messageCount: msgs.length,
42
+ mode: opts.mode,
43
+ usage,
44
+ ...(opts.midTurn ? { midTurn: true } : {}),
45
+ };
46
+ }
11
47
  export const TITLE_MAX_CHARS = 80;
12
48
  // The first thing the human typed, as one short line: what a session list or a resume prompt
13
49
  // would show for this file (issue #309). Derived at save time rather than stamped by the UI so a
@@ -70,7 +106,8 @@ export function summarizeModes(messages) {
70
106
  export function formatUsageHeader(usage) {
71
107
  const lines = [`# turns: ${usage.turns}`];
72
108
  const cachedTotal = usage.cachedTokens != null ? `, ${kFormat(usage.cachedTokens)} from cache` : '';
73
- lines.push(`# tokens: ${kFormat(usage.promptTokens)}↑ ${kFormat(usage.completionTokens)}↓ (session total${cachedTotal})`);
109
+ const approx = usage.tokensEstimated ? '~' : '';
110
+ lines.push(`# tokens: ${approx}${kFormat(usage.promptTokens)}↑ ${approx}${kFormat(usage.completionTokens)}↓ (session total${cachedTotal})`);
74
111
  const ctx = usage.contextTokens;
75
112
  if (ctx != null && ctx > 0) {
76
113
  const fill = contextFill(ctx, usage.contextUsable ?? usage.contextWindow);