@alexwkleung/reika 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -81,7 +81,7 @@ cd your-project && reika
81
81
 
82
82
  Using a hosted API instead? Skip the server and set `REIKA_BASE_URL`, `REIKA_API_KEY` and `REIKA_MODEL` to the provider's endpoint, your key and its model id; [Install and first run](docs/getting-started.md#hosted) has the details.
83
83
 
84
- `REIKA_BASE_URL` defaults to `http://localhost:8080/v1`, llama-server's default. The context window is read from the server when it reports one, and for hosted endpoints from the models.dev catalog; set `REIKA_CONTEXT_WINDOW` when neither has it. Reika sends no sampling parameters of its own, so your server's flags are what apply.
84
+ `REIKA_BASE_URL` defaults to `http://localhost:9931/v1`, llama-server's default since llama.cpp v0.7.0 (older builds and its Docker images use 8080). The context window is read from the server when it reports one, and for hosted endpoints from the models.dev catalog; set `REIKA_CONTEXT_WINDOW` when neither has it. Reika sends no sampling parameters of its own, so your server's flags are what apply.
85
85
 
86
86
  To run from a checkout instead — `git clone https://github.com/alexwkleung/reika.git && cd reika`, then `pnpm install` (npm users: `npm i -g pnpm`) and `pnpm run install:global` to build and install the `reika` binary, or `cp .env.example .env` and `pnpm run dev` to run without installing. `pnpm run uninstall:global` removes the global binary.
87
87
 
@@ -92,7 +92,7 @@ Set these in your shell, a project `.env`, or `~/.config/reika/.env` (in that or
92
92
  | Key | Default | What |
93
93
  | ---------------------- | -------------------------- | ------------------------------------------------------------------------------------- |
94
94
  | `REIKA_MODEL` | _required_ | Model name, or a comma-separated list served by the same endpoint |
95
- | `REIKA_BASE_URL` | `http://localhost:8080/v1` | OpenAI-compatible endpoint |
95
+ | `REIKA_BASE_URL` | `http://localhost:9931/v1` | OpenAI-compatible endpoint |
96
96
  | `REIKA_API_KEY` | `no-key` | API key (any non-empty value for local servers) |
97
97
  | `REIKA_CONTEXT_WINDOW` | _probed from the server_ | Context window in tokens; drives compaction, the context gauge, and the repo map size |
98
98
  | `REIKA_MIN_GEN_TOKENS` | _learned_ (from `2048`) | Room reserved for the reply; learned from the model's rounds, set it to pin |
package/README.zh-CN.md CHANGED
@@ -81,7 +81,7 @@ cd your-project && reika
81
81
 
82
82
  改用托管 API?跳过启动服务器这一步,把 `REIKA_BASE_URL`、`REIKA_API_KEY` 和 `REIKA_MODEL` 设为服务商的端点、你的密钥和它的模型 ID;详见 [安装与首次运行](docs/getting-started.md#hosted)。
83
83
 
84
- `REIKA_BASE_URL` 默认是 `http://localhost:8080/v1`,即 llama-server 的默认地址。上下文窗口在服务器上报时从中读取,托管端点则从 models.dev 目录中读取;两者都没有时,请设置 `REIKA_CONTEXT_WINDOW`。Reika 不发送任何自己的采样参数,所以生效的就是你服务器的启动参数。
84
+ `REIKA_BASE_URL` 默认是 `http://localhost:9931/v1`,即 llama.cpp v0.7.0 起 llama-server 的默认地址(更早的版本及其 Docker 镜像使用 8080)。上下文窗口在服务器上报时从中读取,托管端点则从 models.dev 目录中读取;两者都没有时,请设置 `REIKA_CONTEXT_WINDOW`。Reika 不发送任何自己的采样参数,所以生效的就是你服务器的启动参数。
85
85
 
86
86
  想改从检出目录运行:`git clone https://github.com/alexwkleung/reika.git && cd reika`,然后 `pnpm install`(npm 用户先 `npm i -g pnpm`)并用 `pnpm run install:global` 构建安装 `reika` 可执行文件;或者 `cp .env.example .env`、编辑它,再 `pnpm run dev` 直接运行而不安装。`pnpm run uninstall:global` 会移除全局可执行文件。
87
87
 
@@ -92,7 +92,7 @@ cd your-project && reika
92
92
  | 键 | 默认值 | 说明 |
93
93
  | ---------------------- | --------------------------- | ------------------------------------------------------ |
94
94
  | `REIKA_MODEL` | _必填_ | 模型名称,或同一端点提供的逗号分隔列表 |
95
- | `REIKA_BASE_URL` | `http://localhost:8080/v1` | OpenAI 兼容端点 |
95
+ | `REIKA_BASE_URL` | `http://localhost:9931/v1` | OpenAI 兼容端点 |
96
96
  | `REIKA_API_KEY` | `no-key` | API 密钥(本地服务器填任意非空值) |
97
97
  | `REIKA_CONTEXT_WINDOW` | _从服务器探测_ | 上下文窗口 token 数;驱动压缩和上下文占用条 |
98
98
  | `REIKA_MIN_GEN_TOKENS` | _学习得到_(起始为 `2048`) | 为回复预留的空间;从模型的轮次中学习,设置它即固定该值 |
@@ -1269,6 +1269,7 @@ export async function runTurn(opts) {
1269
1269
  return await runTypecheck(opts.bundle.cwd, {
1270
1270
  signal: opts.signal,
1271
1271
  tsconfigPath: typecheckTsconfig,
1272
+ sandbox: opts.config.sandbox,
1272
1273
  });
1273
1274
  }
1274
1275
  finally {
@@ -2274,7 +2275,10 @@ export async function runTurn(opts) {
2274
2275
  `usage.promptTokens=${response.usage?.promptTokens ?? 'MISSING'} ` +
2275
2276
  `completion=${completion} finishReason=${response.finishReason ?? '?'} ` +
2276
2277
  `decode=${formatRate(sample?.rate)} smoothed=${formatRate(decodeThroughput.get())} ` +
2277
- `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source}\n`);
2278
+ `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source} ` +
2279
+ // Process uptime, not turn time: on a fanless machine the rates sag with sustained load
2280
+ // and recover across idle gaps, so separating that from context growth needs wall clock.
2281
+ `t=${process.uptime().toFixed(0)}s\n`);
2278
2282
  if (opts.signal?.aborted) {
2279
2283
  commitAborted(opts, response.content, response.reasoning, turnStart, fetchedUrls);
2280
2284
  return;
@@ -0,0 +1,81 @@
1
+ import { spillResult } from '../tools/_spill.js';
2
+ // Shell-mode runs the model should see. A command the user runs in shell mode used to land in the
3
+ // scrollback only, so "fix that" after a red `pnpm test` reached a model that never saw the run and
4
+ // re-ran it. The runs are held here and prepended to the next prompt, rather than sent as their own
5
+ // messages: a bare output blob with no request beside it reads to a small model as the task.
6
+ // Bounded by the window, the way the repo map is (#670): a 16k context gets ~1KB a run, a large one
7
+ // 4KB. With no window known the floor applies, erring small.
8
+ export const SHELL_RUN_MIN_CHARS = 1024;
9
+ export const SHELL_RUN_MAX_CHARS = 4096;
10
+ const WINDOW_DIVISOR = 16;
11
+ // Runs held at once; past it the oldest drops whole. Their command lines alone are cheap, but a
12
+ // session of fifty `ls` calls before one prompt is still fifty lines of noise.
13
+ export const MAX_HELD_SHELL_RUNS = 12;
14
+ // Below this a slice of output says nothing a command line and exit code don't.
15
+ const MIN_TAIL_CHARS = 160;
16
+ const MAX_COMMAND_CHARS = 300;
17
+ export function shellRunBudget(contextWindow) {
18
+ const perRun = contextWindow
19
+ ? Math.min(SHELL_RUN_MAX_CHARS, Math.max(SHELL_RUN_MIN_CHARS, Math.round(contextWindow / WINDOW_DIVISOR)))
20
+ : SHELL_RUN_MIN_CHARS;
21
+ return { perRun, total: perRun * 2 };
22
+ }
23
+ export async function captureShellRun(command, exitCode, output) {
24
+ const spill = output.length > SHELL_RUN_MIN_CHARS
25
+ ? ((await spillResult('shell', output)) ?? undefined)
26
+ : undefined;
27
+ return { command, exitCode, output, ...(spill ? { spill } : {}) };
28
+ }
29
+ export function holdShellRun(held, run) {
30
+ return [...held, run].slice(-MAX_HELD_SHELL_RUNS);
31
+ }
32
+ // Newest first gets the budget: the run the user just did is the one their prompt is about.
33
+ export function buildShellRunsBlock(runs, budget) {
34
+ if (runs.length === 0)
35
+ return '';
36
+ let remaining = budget.total;
37
+ const shares = new Array(runs.length).fill(0);
38
+ for (let i = runs.length - 1; i >= 0; i--) {
39
+ const share = Math.min(budget.perRun, remaining, runs[i].output.trimEnd().length);
40
+ if (share < MIN_TAIL_CHARS && share < runs[i].output.trimEnd().length)
41
+ continue;
42
+ shares[i] = share;
43
+ remaining -= share;
44
+ }
45
+ const parts = [
46
+ '<shell-runs>',
47
+ 'The user ran these commands themselves in shell mode before this message. They are context, not a request.',
48
+ ];
49
+ runs.forEach((run, i) => parts.push(renderRun(run, shares[i])));
50
+ parts.push('</shell-runs>');
51
+ return parts.join('\n');
52
+ }
53
+ function renderRun(run, share) {
54
+ const command = run.command.length > MAX_COMMAND_CHARS
55
+ ? `${run.command.slice(0, MAX_COMMAND_CHARS)}…`
56
+ : run.command;
57
+ const status = run.exitCode === null ? 'killed' : `exit ${run.exitCode}`;
58
+ const lines = [`$ ${command} (${status})`];
59
+ const output = run.output.trimEnd();
60
+ if (!output) {
61
+ lines.push('(no output)');
62
+ return lines.join('\n');
63
+ }
64
+ if (share === 0) {
65
+ lines.push(`(${output.length} chars of output omitted${locator(run)})`);
66
+ return lines.join('\n');
67
+ }
68
+ if (output.length <= share) {
69
+ lines.push(output);
70
+ return lines.join('\n');
71
+ }
72
+ // Cut at a line boundary: a run's verdict sits at its end, and a half line at the top is noise.
73
+ const slice = output.slice(-share);
74
+ const nl = slice.indexOf('\n');
75
+ const tail = nl >= 0 && nl < slice.length - 1 ? slice.slice(nl + 1) : slice;
76
+ lines.push(`…(earlier output omitted${locator(run)})`, tail);
77
+ return lines.join('\n');
78
+ }
79
+ function locator(run) {
80
+ return run.spill ? `; full output saved to ${run.spill.path}, read it with offset/limit` : '';
81
+ }
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { SANDBOX_EXEC_ERROR_PREFIX, sandboxArgv, sandboxPlan } from '../tools/_sandbox.js';
6
7
  const DEFAULT_TIMEOUT_MS = 30_000;
7
8
  // One tsc cascade can be hundreds of lines; a 16k-window model can't absorb that. Cap what the
8
9
  // model sees and tell it how many were elided rather than truncating silently.
@@ -156,7 +157,8 @@ export async function runTypecheck(cwd, opts = {}) {
156
157
  const buildInfo = opts.tsBuildInfoFile ?? defaultBuildInfoFile(cwd);
157
158
  // `--incremental` with an explicit `--tsBuildInfoFile` is what makes the re-check cheap and is
158
159
  // accepted alongside `--noEmit` across TS versions. `--pretty false` forces the stable
159
- // one-line-per-diagnostic format regardless of TTY, which DIAG_RE parses.
160
+ // one-line-per-diagnostic format regardless of TTY, which DIAG_RE parses. One list, used by both
161
+ // spawns below, so the confined and unconfined runs cannot drift apart.
160
162
  const args = [
161
163
  '--noEmit',
162
164
  '--incremental',
@@ -167,34 +169,124 @@ export async function runTypecheck(cwd, opts = {}) {
167
169
  '-p',
168
170
  tsconfig,
169
171
  ];
170
- return runTscProcess(tsc, args, cwd, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, opts.signal);
172
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
173
+ // Route the project-local `tsc` through the sandbox wrapper so it runs inside confinement — the
174
+ // same profile model-run bash gets (writes confined to cwd, temp and cache dirs, network denied;
175
+ // the temp allow is what lets `--tsBuildInfoFile` land in os.tmpdir()). The wrapper takes a shell
176
+ // command, so the binary has to be part of the line and both it and every argument must be
177
+ // quoted: a bare flag list would be run *as* the command (`/bin/sh -c "--noEmit …"` is an
178
+ // invalid option, exit 2), and tsc would never start — indistinguishable from a clean check, and
179
+ // so a silently dead gate. When the sandbox is unavailable, fall back to the direct spawn
180
+ // (fail-open), which is the gate's standing design.
181
+ //
182
+ // Once a plan exists there is no unconfined retry, even when the wrapper looks like it refused:
183
+ // that verdict is read off the output of the process we just ran, and a planted tsc can print the
184
+ // wrapper's line and exit 65 as easily as sandbox-exec can. A retry would hand it exactly the
185
+ // unconfined run this exists to prevent, so a refusal disables the gate for the turn instead.
186
+ if (opts.sandbox !== false) {
187
+ const plan = sandboxPlan(cwd, { network: false });
188
+ if ('args' in plan) {
189
+ const argv = sandboxArgv(plan, [tsc, ...args].map(shellQuote).join(' '));
190
+ if (argv)
191
+ return runTscProcess(argv.cmd, argv.args, cwd, timeoutMs, opts.signal, true);
192
+ }
193
+ }
194
+ return runTscProcess(tsc, args, cwd, timeoutMs, opts.signal);
195
+ }
196
+ // Whether the sandbox wrapper itself refused to run the command: nonzero exit, the wrapper's own
197
+ // line in the output, and nothing that parses as a diagnostic (so a tsc that really ran — even one
198
+ // whose errors the DIAG_RE cannot parse — is never mistaken for a refusal). A profile the OS
199
+ // rejects, or a param without its `-D` binding, exits 65 having run nothing; `sandboxPlan` probes
200
+ // the real argv for that before tsc runs (#738), so this is the backstop. Undetected, the empty
201
+ // output parses to zero diagnostics and masquerades as a green check. Any nonzero exit in this shape
202
+ // counts rather than bash.ts's exit-65 pin: an apply failure (71) leaves the same nothing-ran
203
+ // signature, and the prefix is required there too. Spoofable by the process inside, which is why a
204
+ // refusal only ever resolves "didn't run" and never buys a retry: the worst a fake one can do is
205
+ // switch the gate off for a turn.
206
+ export function sandboxRefused(code, out) {
207
+ return (code !== null &&
208
+ code !== 0 &&
209
+ out.includes(SANDBOX_EXEC_ERROR_PREFIX) &&
210
+ parseTscOutput(out).length === 0);
171
211
  }
172
- function runTscProcess(bin, args, cwd, timeoutMs, signal) {
212
+ // Single-quote one argument for the `/bin/sh -c` line `sandboxArgv` builds. Every path interpolated
213
+ // into that line is user-controlled — a cwd, tsconfig, or tsbuildinfo path may contain spaces or
214
+ // quotes — so concatenating bare would split one argument into several or let a quote re-parse the
215
+ // rest. `'\''` is the only way to carry a single quote inside a single-quoted string. Exported for
216
+ // tests: the quoting is the security boundary here, and a round-trip through a real /bin/sh is the
217
+ // only proof it holds.
218
+ export function shellQuote(arg) {
219
+ return `'${arg.replace(/'/g, "'\\''")}'`;
220
+ }
221
+ // What `/bin/sh` exits with when it could not run the command it was given: 126 found but not
222
+ // executable (a lost exec bit), 127 not found (a shebang interpreter missing from PATH). The direct
223
+ // spawn reports both as a spawn error; behind the wrapper they are ordinary exits with no tsc
224
+ // output, which would otherwise parse as zero diagnostics — a clean check from a tsc that never ran.
225
+ const SHELL_COULD_NOT_RUN = new Set([126, 127]);
226
+ // The wrapper is `sandbox-exec` → `/bin/sh` → tsc, so a kill aimed at the child pid can stop short
227
+ // of tsc (a shim that runs node without exec). Each spawn gets its own process group and every
228
+ // kill goes to the group, as bash.ts does (#408); the exit sweep covers a reika exit mid-check,
229
+ // since a group of its own is one the terminal's hangup no longer reaches.
230
+ const liveGroups = new Set();
231
+ process.once('exit', () => {
232
+ for (const pid of liveGroups) {
233
+ try {
234
+ process.kill(-pid, 'SIGKILL');
235
+ }
236
+ catch {
237
+ // Already gone.
238
+ }
239
+ }
240
+ });
241
+ // Exported for tests: the refusal branch is this gate's fail-open boundary — the case that used to
242
+ // resolve as a green check — and a real sandbox-exec refusing to load a profile is the only
243
+ // faithful way to drive it.
244
+ export function runTscProcess(bin, args, cwd, timeoutMs, signal, viaSandboxWrapper = false) {
173
245
  return new Promise(resolve => {
174
246
  let child;
175
247
  try {
176
- child = spawn(bin, args, { cwd });
248
+ child = spawn(bin, args, { cwd, detached: process.platform !== 'win32' });
177
249
  }
178
250
  catch (e) {
179
251
  resolve({ ran: false, reason: `spawn failed: ${e.message}` });
180
252
  return;
181
253
  }
254
+ const pid = child.pid;
255
+ if (pid != null && process.platform !== 'win32')
256
+ liveGroups.add(pid);
257
+ const killTree = () => {
258
+ try {
259
+ if (pid == null || process.platform === 'win32')
260
+ throw new Error('no group');
261
+ process.kill(-pid, 'SIGKILL');
262
+ }
263
+ catch {
264
+ try {
265
+ child.kill('SIGKILL');
266
+ }
267
+ catch {
268
+ // Already gone.
269
+ }
270
+ }
271
+ };
182
272
  let out = '';
183
273
  let settled = false;
184
274
  const finish = (r) => {
185
275
  if (settled)
186
276
  return;
187
277
  settled = true;
278
+ if (pid != null)
279
+ liveGroups.delete(pid);
188
280
  clearTimeout(timer);
189
281
  signal?.removeEventListener('abort', onAbort);
190
282
  resolve(r);
191
283
  };
192
284
  const timer = setTimeout(() => {
193
- child.kill('SIGKILL');
285
+ killTree();
194
286
  finish({ ran: false, reason: `timed out after ${timeoutMs}ms` });
195
287
  }, timeoutMs);
196
288
  const onAbort = () => {
197
- child.kill('SIGKILL');
289
+ killTree();
198
290
  finish({ ran: false, reason: 'aborted' });
199
291
  };
200
292
  signal?.addEventListener('abort', onAbort, { once: true });
@@ -203,6 +295,22 @@ function runTscProcess(bin, args, cwd, timeoutMs, signal) {
203
295
  child.stdout?.on('data', d => (out += d.toString()));
204
296
  child.stderr?.on('data', d => (out += d.toString()));
205
297
  child.on('error', e => finish({ ran: false, reason: `process error: ${e.message}` }));
206
- child.on('close', () => finish({ ran: true, diagnostics: parseTscOutput(out) }));
298
+ child.on('close', code => {
299
+ // Only the wrapper spawn gets refusal semantics: a nonzero exit there with the wrapper's own
300
+ // line and no tsc output means the command never ran — read as a clean check, that outcome is
301
+ // the silently-dead gate (see sandboxRefused above).
302
+ if (viaSandboxWrapper && sandboxRefused(code, out)) {
303
+ finish({ ran: false, reason: `sandbox wrapper refused to run tsc (exit ${code})` });
304
+ return;
305
+ }
306
+ if (viaSandboxWrapper &&
307
+ code !== null &&
308
+ SHELL_COULD_NOT_RUN.has(code) &&
309
+ parseTscOutput(out).length === 0) {
310
+ finish({ ran: false, reason: `shell could not run tsc (exit ${code})` });
311
+ return;
312
+ }
313
+ finish({ ran: true, diagnostics: parseTscOutput(out) });
314
+ });
207
315
  });
208
316
  }
package/dist/cli.js CHANGED
@@ -1,14 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { sweepDebugLogs } from './debug.js';
3
4
  import { sweepStaleSpills } from './tools/_spill.js';
4
5
  import { USAGE, parseHeadlessArgs } from './headlessargs.js';
5
6
  import { VERSION } from './version.js';
7
+ // Lowercase like the command: ps/top/Activity Monitor otherwise list every session as `node`, and
8
+ // pgrep/pkill match case-sensitively.
9
+ process.title = 'reika';
6
10
  // Spill directories are removed on a normal exit, but SIGHUP (closing the terminal window),
7
11
  // SIGTERM, SIGKILL and hard crashes never reach that handler (#224). The sweep is the cleanup
8
12
  // path for those, and it belongs here rather than in a React effect: it is a property of the
9
13
  // process starting, not of anything the UI mounts. Fire-and-forget — cleaning up after a session
10
14
  // that is already gone must never delay first paint, and it fails open on its own.
11
15
  void sweepStaleSpills();
16
+ // Debug-log retention (#761), the same shape: per-session logs past their age or size budget.
17
+ void sweepDebugLogs();
12
18
  // Both front-ends are imported lazily: the headless path (#52) never loads Ink, and the TUI
13
19
  // never loads the headless runner.
14
20
  let headless;
package/dist/config.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { DEFAULT_MIN_GEN_TOKENS } from './provider/budget.js';
6
+ import { DEFAULT_BASE_URL } from './provider/transport.js';
6
7
  import { parseMcpServers } from './mcp/config.js';
7
8
  // The cwd .env belongs to whatever repo reika was opened in, which may not be the user's. A cloned
8
9
  // repo's file must not turn the sandbox or approvals off, start a program (MCP), redirect where
@@ -76,7 +77,7 @@ export function loadConfig() {
76
77
  // llama-server's port, matching .env.example and the quick start. The fallback only applies
77
78
  // when REIKA_BASE_URL is unset, which for a required-REIKA_MODEL config means somebody
78
79
  // running on defaults end to end.
79
- const baseURL = process.env.REIKA_BASE_URL ?? 'http://localhost:8080/v1';
80
+ const baseURL = process.env.REIKA_BASE_URL ?? DEFAULT_BASE_URL;
80
81
  validateBaseURL(baseURL, 'REIKA_BASE_URL');
81
82
  const apiKey = process.env.REIKA_API_KEY ?? 'no-key';
82
83
  const maxTokens = parseIntOrUndef(process.env.REIKA_MAX_TOKENS);
package/dist/debug.js CHANGED
@@ -1,4 +1,6 @@
1
- import { appendFileSync, writeFileSync } from 'node:fs';
1
+ import { appendFileSync, mkdirSync, renameSync, symlinkSync, unlinkSync } from 'node:fs';
2
+ import { open, readdir, rm, stat } from 'node:fs/promises';
3
+ import { randomBytes } from 'node:crypto';
2
4
  import { homedir } from 'node:os';
3
5
  import { join } from 'node:path';
4
6
  import { VERSION } from './version.js';
@@ -9,36 +11,153 @@ import { VERSION } from './version.js';
9
11
  export function debugEnabled() {
10
12
  return !!process.env.REIKA_DEBUG;
11
13
  }
12
- // One stable path regardless of which project reika is pointed at. A cwd-relative default lands the
13
- // log inside the target repo (surprising, and easy to grep in the wrong place); the home dir is
14
- // always the same file, so runs across projects/models accumulate where you can find them.
15
- // REIKA_DEBUG_FILE overrides it (e.g. an absolute path for a specific experiment).
14
+ // The name a session's files share: its debug log here, its auto-save under history/ (#761), so a
15
+ // log found after the fact pairs with the transcript of the run that wrote it.
16
+ export function sessionStem(startedAt) {
17
+ const stamp = startedAt.toISOString().replace(/[:.]/g, '-');
18
+ return `${stamp}-${randomBytes(3).toString('hex')}`;
19
+ }
20
+ // One per process: reika is one process per session. The first auto-save of the process takes it
21
+ // too; a /new afterwards starts a transcript of its own, and the log records the switch.
22
+ let processStem;
23
+ export function processSessionStem() {
24
+ return (processStem ??= sessionStem(new Date()));
25
+ }
26
+ // Under ~/.config/reika beside history/, never cwd-relative: a log inside the target repo is
27
+ // surprising and easy to grep in the wrong place.
28
+ export function debugLogDir() {
29
+ return join(homedir(), '.config', 'reika', 'logs');
30
+ }
31
+ export const LATEST_LOG = 'latest.log';
32
+ // One file per session (#761). The old default was one file truncated at each launch (#114), so a
33
+ // spill or a slowdown nobody planned to debug was gone by the next start, and with small models a
34
+ // reproduction is a different run. REIKA_DEBUG_FILE is an explicit collection target instead —
35
+ // appended to across runs and never swept — which is what multi-run A/B analyses point at.
16
36
  export function debugLogPath() {
17
- return process.env.REIKA_DEBUG_FILE || join(homedir(), 'reika-debug.log');
37
+ return process.env.REIKA_DEBUG_FILE || join(debugLogDir(), `${processSessionStem()}.log`);
18
38
  }
19
- // The default log holds one session: the first write of a process truncates it (#114 — sessions run
20
- // thousands of lines, and append-forever bloats the file without bound). When you *want* runs to
21
- // accumulate (the multi-run distribution analyses), point REIKA_DEBUG_FILE at an experiment file —
22
- // an explicit collection target is never truncated.
23
39
  let sessionStarted = false;
40
+ // The first line of a per-session log names its owner, so the startup sweep can tell a running
41
+ // session's file from an abandoned one at any age; `latest.log` keeps the one stable path to the
42
+ // current session that the single-file default used to give.
43
+ function openSessionLog(path) {
44
+ const dir = debugLogDir();
45
+ mkdirSync(dir, { recursive: true });
46
+ appendFileSync(path, `[reika:debug] session pid=${process.pid} version=${VERSION}\n`);
47
+ const tmp = join(dir, `.latest-${process.pid}`);
48
+ try {
49
+ symlinkSync(`${processSessionStem()}.log`, tmp);
50
+ renameSync(tmp, join(dir, LATEST_LOG));
51
+ }
52
+ catch {
53
+ try {
54
+ unlinkSync(tmp);
55
+ }
56
+ catch {
57
+ // Nothing was created.
58
+ }
59
+ }
60
+ }
24
61
  export function debugLog(line) {
25
62
  if (!debugEnabled())
26
63
  return;
27
64
  const path = debugLogPath();
28
65
  const text = line.endsWith('\n') ? line : `${line}\n`;
29
66
  try {
30
- if (sessionStarted || process.env.REIKA_DEBUG_FILE) {
31
- appendFileSync(path, text);
32
- }
33
- else {
34
- writeFileSync(path, text);
35
- }
67
+ if (!sessionStarted && !process.env.REIKA_DEBUG_FILE)
68
+ openSessionLog(path);
36
69
  sessionStarted = true;
70
+ appendFileSync(path, text);
37
71
  }
38
72
  catch {
39
73
  // Best-effort: diagnostics must never break a turn.
40
74
  }
41
75
  }
76
+ // --- Retention (#761) -----------------------------------------------------------------------
77
+ //
78
+ // Swept at startup, fire-and-forget, the way spill directories are (#224): oldest first, until
79
+ // what is left is both younger than the age limit and under the size limit. Both numbers are a
80
+ // first guess — the largest log measured was 238KB (a 1,380-round grind run), typical 20–100KB.
81
+ // Runs whether or not REIKA_DEBUG is set, so turning debug off does not strand the logs it wrote.
82
+ // Only names this module writes are touched: latest.log, and any REIKA_DEBUG_FILE target, never.
83
+ export const LOG_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
84
+ export const LOG_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
85
+ const SESSION_LOG_RE = /^\d{4}-\d{2}-\d{2}T[\d-]+Z-[0-9a-f]{6}\.log$/;
86
+ const OWNER_RE = /^\[reika:debug\] session pid=(\d+)/;
87
+ // Signal 0 probes without delivering anything; EPERM means alive and somebody else's. Same check
88
+ // as the spill sweep's (`_spill.ts`), kept local rather than coupling the debug log to a tool.
89
+ function pidAlive(pid) {
90
+ try {
91
+ process.kill(pid, 0);
92
+ return true;
93
+ }
94
+ catch (e) {
95
+ return e.code === 'EPERM';
96
+ }
97
+ }
98
+ async function ownerPid(path) {
99
+ try {
100
+ const fh = await open(path, 'r');
101
+ try {
102
+ const buf = Buffer.alloc(128);
103
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
104
+ const m = OWNER_RE.exec(buf.subarray(0, bytesRead).toString('utf8'));
105
+ return m ? Number(m[1]) : null;
106
+ }
107
+ finally {
108
+ await fh.close();
109
+ }
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ // Returns the paths removed, for tests and diagnostics. `dir` and `now` are seams for tests.
116
+ export async function sweepDebugLogs(dir = debugLogDir(), now = Date.now()) {
117
+ const removed = [];
118
+ let names;
119
+ try {
120
+ names = (await readdir(dir)).filter(n => SESSION_LOG_RE.test(n));
121
+ }
122
+ catch {
123
+ return removed;
124
+ }
125
+ const own = process.env.REIKA_DEBUG_FILE || processStem === undefined
126
+ ? undefined
127
+ : join(dir, `${processStem}.log`);
128
+ const logs = [];
129
+ for (const name of names) {
130
+ const path = join(dir, name);
131
+ try {
132
+ const s = await stat(path);
133
+ if (s.isFile())
134
+ logs.push({ path, size: s.size, mtimeMs: s.mtimeMs });
135
+ }
136
+ catch {
137
+ // Gone already.
138
+ }
139
+ }
140
+ logs.sort((a, b) => a.mtimeMs - b.mtimeMs);
141
+ let total = logs.reduce((sum, l) => sum + l.size, 0);
142
+ for (const log of logs) {
143
+ if (now - log.mtimeMs <= LOG_MAX_AGE_MS && total <= LOG_MAX_TOTAL_BYTES)
144
+ break;
145
+ if (log.path === own)
146
+ continue;
147
+ const pid = await ownerPid(log.path);
148
+ if (pid !== null && pid > 0 && pidAlive(pid))
149
+ continue;
150
+ try {
151
+ await rm(log.path, { force: true });
152
+ removed.push(log.path);
153
+ total -= log.size;
154
+ }
155
+ catch {
156
+ // Not ours to remove after all; the next startup tries again.
157
+ }
158
+ }
159
+ return removed;
160
+ }
42
161
  // One self-describing line per session, so a log says which build and which experiment flags
43
162
  // produced it. Written after a lost A/B: an arm was run from a branch that did not contain the
44
163
  // feature at all, the flag it set was read by nothing, and the two arms — which looked like a
package/dist/headless.js CHANGED
@@ -54,6 +54,28 @@ export async function buildHeadlessInput(prompt, config, bundle, mode) {
54
54
  }
55
55
  return { modelText, notices };
56
56
  }
57
+ // `--profile` is the user naming the profile outright, so it outranks a launch REIKA_MODEL and the
58
+ // mode's own model alike (#710). Matched case-insensitively like /model; a name no profile defines
59
+ // keeps the run going on the profile it would have used anyway, and says so — passed through raw,
60
+ // it reached the session as a profile nothing defines and lost the default's probed window.
61
+ export function headlessProfile(config, mode, named) {
62
+ const fallback = startProfiles(config, mode, {}).profile;
63
+ if (named === undefined)
64
+ return { profile: fallback };
65
+ const key = named.toLowerCase();
66
+ if (config.profiles[key])
67
+ return { profile: key };
68
+ const known = Object.keys(config.profiles).join(', ');
69
+ return {
70
+ profile: fallback,
71
+ notice: `no profile named "${named}" (defined: ${known}); using "${fallback}"`,
72
+ };
73
+ }
74
+ // Names the route the turn was on, since with --profile it may not be the default one. Not worded
75
+ // as a fetch failure: an abort, a 400 or a tool throw lands here too.
76
+ export function formatTurnFailure(profile, baseURL, message) {
77
+ return `reika: turn failed (profile "${profile}" at ${baseURL}): ${message}`;
78
+ }
57
79
  export async function runHeadless(args, io) {
58
80
  const prompt = (args.prompt ?? (await io.readStdin())).trim();
59
81
  if (!prompt) {
@@ -67,7 +89,10 @@ export async function runHeadless(args, io) {
67
89
  // with its own model in REIKA_MODE_MODELS runs that one, `--mode` or not. Headless has no /model
68
90
  // and no saved state — its env is the whole answer — so an empty state is the whole of #365 here.
69
91
  const mode = args.mode ?? resolveDefaultMode();
70
- const profile = startProfiles(loaded, mode, {}).profile;
92
+ const chosen = headlessProfile(loaded, mode, args.profile);
93
+ if (chosen.notice)
94
+ io.stderr(`reika: ${chosen.notice}\n`);
95
+ const profile = chosen.profile;
71
96
  const stream = args.stream ? createStreamPrinter(io, args.json) : null;
72
97
  const session = await createSession({
73
98
  cwd: process.cwd(),
@@ -181,7 +206,7 @@ export async function runHeadless(args, io) {
181
206
  }
182
207
  if (failed) {
183
208
  debugLog(`headless: turn failed: ${failed.message}`);
184
- io.stderr(`reika: ${failed.message}\n`);
209
+ io.stderr(`${formatTurnFailure(profile, config.baseURL, failed.message)}\n`);
185
210
  return controller.signal.aborted ? 130 : 1;
186
211
  }
187
212
  if (args.json && !args.stream) {
@@ -2,6 +2,7 @@ export const USAGE = `usage: reika start the interactive TUI in
2
2
  reika -p [prompt] ... run one turn without the TUI and print the reply
3
3
 
4
4
  -p, --prompt [text] run one turn headless; reads stdin when no text is given
5
+ --profile <name> with -p: use this profile (outranks REIKA_MODEL and REIKA_MODE_MODELS)
5
6
  --mode <mode> agent | plan | vibe | minimal | grind | chat (default: REIKA_DEFAULT_MODE, else agent)
6
7
  --json print the turn's messages as a JSON array instead of the reply text
7
8
  --stream print as the turn runs: the reply as it is generated, tool calls on
@@ -11,7 +12,7 @@ export const USAGE = `usage: reika start the interactive TUI in
11
12
  -h, --help show this
12
13
 
13
14
  Configuration is read from the environment, then ./.env, then ~/.config/reika/.env; REIKA_MODEL
14
- is required and REIKA_BASE_URL defaults to http://localhost:8080/v1.
15
+ is required and REIKA_BASE_URL defaults to http://localhost:9931/v1.
15
16
 
16
17
  With -p: a prompt starting with /<skill> runs that skill. Approvals follow REIKA_AUTO_APPROVE
17
18
  (default 'safe'): with no prompt to fall back on, anything 'safe' would have asked about is
@@ -47,6 +48,13 @@ export function parseHeadlessArgs(argv) {
47
48
  }
48
49
  args.mode = value;
49
50
  }
51
+ else if (a === '--profile') {
52
+ // A flag-shaped value is a missing name: taking it would swallow the -p or --json after it.
53
+ const value = argv[++i];
54
+ if (!value || value.startsWith('-'))
55
+ throw new Error('--profile needs a profile name');
56
+ args.profile = value;
57
+ }
50
58
  else if (a === '--json') {
51
59
  args.json = true;
52
60
  }
@@ -82,5 +90,9 @@ export function parseHeadlessArgs(argv) {
82
90
  throw new Error(`unexpected argument ${a}\n${USAGE}`);
83
91
  }
84
92
  }
93
+ // The TUI does not read it, so starting one would drop the flag without a word.
94
+ if (!headless && args.profile !== undefined) {
95
+ throw new Error(`--profile applies to a headless run; add -p\n${USAGE}`);
96
+ }
85
97
  return headless ? args : null;
86
98
  }