@alexwkleung/reika 0.7.0 → 0.8.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,132 @@
1
+ import { openSync, createReadStream, createWriteStream } from 'node:fs';
2
+ import { createInterface } from 'node:readline';
3
+ import { APPROVAL_FEEDBACK_INDEX, APPROVAL_OPTIONS } from '../ui/dialogspecs.js';
4
+ import { toolLabel } from '../ui/format.js';
5
+ // Headless dialogs (#872): `reika -p -i` asks what the TUI would have opened a dialog for, as a
6
+ // numbered menu on the controlling terminal. The terminal, not stdin/stderr: stdin may be the piped
7
+ // prompt and stderr a log file, and a question written into a log waits for an answer nobody sees.
8
+ // Rows of an approval preview printed before the menu. The TUI fits the preview to the pane; a
9
+ // line prompt has no pane, and a 400-line diff scrolls the menu off the screen.
10
+ export const PREVIEW_LINES = 40;
11
+ // The controlling terminal, or null when there is none (cron, CI, `setsid`) — the caller then
12
+ // refuses `--interactive` rather than hanging on a read that never completes.
13
+ export function openTerminalPrompter(signal) {
14
+ let fd;
15
+ try {
16
+ fd = openSync('/dev/tty', 'r+');
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ // The read stream owns the fd: destroying it closes the fd, so the write side must not.
22
+ const input = createReadStream('', { fd });
23
+ const output = createWriteStream('', { fd, autoClose: false });
24
+ const prompter = createPrompter(input, output, signal);
25
+ return {
26
+ ...prompter,
27
+ close: () => {
28
+ prompter.close();
29
+ output.destroy();
30
+ input.destroy();
31
+ },
32
+ };
33
+ }
34
+ export function createPrompter(input, output, signal) {
35
+ const rl = createInterface({ input, output, terminal: false });
36
+ let closed = false;
37
+ rl.once('close', () => (closed = true));
38
+ // Answers are read one at a time: two approvals in one round must not share a typed line.
39
+ let chain = Promise.resolve();
40
+ const serial = (task) => {
41
+ const next = chain.then(task, task);
42
+ chain = next.catch(() => { });
43
+ return next;
44
+ };
45
+ const line = (prompt) => new Promise(resolve => {
46
+ if (closed || signal?.aborted)
47
+ return resolve(null);
48
+ const onClose = () => resolve(null);
49
+ rl.once('close', onClose);
50
+ rl.question(prompt, { signal }, answer => {
51
+ rl.off('close', onClose);
52
+ resolve(answer);
53
+ });
54
+ signal?.addEventListener('abort', () => resolve(null), { once: true });
55
+ });
56
+ const write = (text) => {
57
+ if (!closed)
58
+ output.write(text);
59
+ };
60
+ return {
61
+ choose: (header, options, defaultIndex) => serial(async () => {
62
+ write(`\n${header.join('\n')}\n`);
63
+ options.forEach((o, i) => write(` ${i + 1}. ${o}${i === defaultIndex ? ' (default)' : ''}\n`));
64
+ for (;;) {
65
+ const answer = await line(`choose 1-${options.length}: `);
66
+ if (answer === null)
67
+ return null;
68
+ const picked = parseChoice(answer, options.length, defaultIndex);
69
+ if (picked !== null)
70
+ return picked;
71
+ write(` enter a number from 1 to ${options.length}\n`);
72
+ }
73
+ }),
74
+ ask: prompt => serial(() => line(prompt)),
75
+ close: () => rl.close(),
76
+ };
77
+ }
78
+ export function parseChoice(answer, count, defaultIndex) {
79
+ const t = answer.trim();
80
+ if (t === '')
81
+ return defaultIndex;
82
+ if (!/^\d+$/.test(t))
83
+ return null;
84
+ const n = Number(t);
85
+ return n >= 1 && n <= count ? n - 1 : null;
86
+ }
87
+ export function approvalHeader(req) {
88
+ const lines = req.preview.split('\n');
89
+ const shown = lines.slice(0, PREVIEW_LINES);
90
+ return [
91
+ `reika: approve ${toolLabel(req.tool)}? ${req.subject}`,
92
+ ...(req.warnings ?? []).map(w => ` ▲ ${w}`),
93
+ ...shown.map(l => ` │ ${l}`),
94
+ ...(lines.length > shown.length ? [` │ … ${lines.length - shown.length} more lines`] : []),
95
+ ];
96
+ }
97
+ // `always` is set when the user picks "Always (this session)": the caller switches its policy to
98
+ // 'safe', which — as in the TUI — still asks about anything the danger scan flagged.
99
+ export async function askApproval(prompter, req) {
100
+ const picked = await prompter.choose(approvalHeader(req), [...APPROVAL_OPTIONS], 0);
101
+ if (picked === null || picked === 1)
102
+ return { answer: false, always: false };
103
+ if (picked === 0)
104
+ return { answer: true, always: false };
105
+ if (picked === APPROVAL_FEEDBACK_INDEX) {
106
+ const reason = (await prompter.ask('what should it do instead? ')) ?? '';
107
+ return { answer: reason.trim() ? { feedback: reason.trim() } : false, always: false };
108
+ }
109
+ return { answer: true, always: true };
110
+ }
111
+ // The last row is the TUI's "type your own answer" field; a typed answer carries no index.
112
+ export async function askQuestion(prompter, req) {
113
+ const labels = req.options.map(o => [o.label, o.recommended ? '(recommended)' : '', o.description ? `— ${o.description}` : '']
114
+ .filter(Boolean)
115
+ .join(' '));
116
+ const own = labels.length;
117
+ const recommended = req.options.findIndex(o => o.recommended);
118
+ const picked = await prompter.choose([`reika: the model asks: ${req.question}`], [...labels, 'Type my own answer'], recommended >= 0 ? recommended : 0);
119
+ if (picked === null)
120
+ return null;
121
+ if (picked === own) {
122
+ const text = (await prompter.ask('your answer: '))?.trim();
123
+ return text ? { text } : null;
124
+ }
125
+ return { text: req.options[picked].label, index: picked };
126
+ }
127
+ // The two-row confirms (skill route, pasted link). Row 0 is "send as typed" and the default, as in
128
+ // the TUI: nothing has happened yet, so the least action is the safe one. True accepts row 1.
129
+ export async function askConfirm(prompter, spec) {
130
+ const picked = await prompter.choose([`reika: ${spec.title} — ${spec.subtitle}`, ...spec.details.map(d => ` ${d}`)], spec.options, 0);
131
+ return picked === null ? null : picked === 1;
132
+ }
@@ -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();
@@ -250,6 +256,7 @@ export async function createSession(opts) {
250
256
  decodeRate = undefined;
251
257
  genReserve = new GenReserve();
252
258
  changed();
259
+ logEndpoint();
253
260
  void ensureNoteSlot(resolveProfile(cfg, name));
254
261
  if (!needsLimitsProbe(next))
255
262
  return Promise.resolve([]);
@@ -281,6 +288,7 @@ export async function createSession(opts) {
281
288
  if (profile !== 'default') {
282
289
  profile = 'default';
283
290
  changed();
291
+ logEndpoint();
284
292
  }
285
293
  };
286
294
  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),