@alexwkleung/reika 0.4.0 → 0.6.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 |
@@ -141,7 +141,7 @@ The same pages are on the website, [reikacode.com](https://reikacode.com).
141
141
 
142
142
  ## Inspired by
143
143
 
144
- Claude Code, Codex, Crush, OpenCode, Pi, Aider, DeepSeek Harness, Qwen Code, Kimi Code CLI, Gemini CLI, Junie, and DS4.
144
+ Claude Code, Codex, Crush, OpenCode, Pi, Aider, DeepSeek Harness, Qwen Code, Kimi Code CLI, Gemini CLI, Junie, DS4, and Ante.
145
145
 
146
146
  ## License
147
147
 
package/README.zh-CN.md CHANGED
@@ -11,10 +11,10 @@
11
11
  </p>
12
12
 
13
13
  <p align="center">
14
- <a href="https://reikacode.com">网站</a> ·
14
+ <a href="https://reikacode.com/zh/">网站</a> ·
15
15
  <a href="#快速开始">快速开始</a> ·
16
16
  <a href="#文档">文档</a> ·
17
- <a href="docs/models.md">测试过的模型</a> ·
17
+ <a href="docs/zh/models.md">测试过的模型</a> ·
18
18
  <a href="README.md">English</a>
19
19
  </p>
20
20
 
@@ -51,7 +51,7 @@ Reika 还处于 1.0 之前,命令、设置和行为在不同版本之间仍可
51
51
 
52
52
  ## 要求
53
53
 
54
- - Node.js 22 或更新版本(macOS 11+,或 glibc 2.28+ 的 Linux —— 见[平台](docs/platforms.md))。
54
+ - Node.js 22 或更新版本(macOS 11+,或 glibc 2.28+ 的 Linux —— 见[平台](docs/zh/platforms.md))。
55
55
  - 一个 OpenAI 兼容的模型服务器:llama.cpp、MLX、vLLM 或云端 API。
56
56
  - macOS 是主要平台。Linux 可用,但没有 shell 沙箱和图片粘贴 OCR(可以设置 `REIKA_VISION_MODEL`,改用视觉模型读取粘贴的图片)。Windows 或许能在 WSL2 下运行。
57
57
  - 现代终端(iTerm2、Ghostty、Kitty 等)。想要正确的 TUI 渲染,建议使用它们。
@@ -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`) | 为回复预留的空间;从模型的轮次中学习,设置它即固定该值 |
@@ -123,24 +123,24 @@ cd your-project && reika
123
123
 
124
124
  ## 文档
125
125
 
126
- 这些页面也在网站 [reikacode.com](https://reikacode.com) 上(英文)。
127
-
128
- | 文档 | 内容 |
129
- | -------------------------------------- | ---------------------------------------------------------------- |
130
- | [配置](docs/configuration.md) | 每一个 `.env` 键、实验性开关、具名 profile、上次会话状态 |
131
- | [模式、无头与命令](docs/usage.md) | 各模式详解、`reika -p`、斜杠命令、`/save` 会话记录 |
132
- | [工具](docs/tools.md) | 模型可用的工具、审批提示、网络搜索设置、MCP 服务器、`.gitignore` |
133
- | [指令与技能](docs/skills.md) | `AGENTS.md`、作为斜杠命令的技能、自然语言路由、粘贴的链接 |
134
- | [测试过的模型](docs/models.md) | Reika 实际跑过的本地量化版本和 API |
135
- | [测量结果](docs/findings.md) | 实测记录:什么坏了、什么撑住了,以及每个数字是怎么得到的 |
136
- | [平台](docs/platforms.md) | 运行要求、在弱机器上运行、Linux 和 Windows 上的差异 |
137
- | [架构与注意事项](docs/architecture.md) | 框架如何工作,以及已知限制 |
138
- | [贡献](CONTRIBUTING.md) | 脚本、设计理念、`AGENTS.md` 指引,以及外部贡献者指南 |
139
- | [更新日志](CHANGELOG.md)(英文) | 每个版本的变更 |
126
+ 这些页面也在网站 [reikacode.com/zh](https://reikacode.com/zh/) 上。模型、平台和架构已翻译为中文,其余页面暂为英文。
127
+
128
+ | 文档 | 内容 |
129
+ | ----------------------------------------- | ---------------------------------------------------------------- |
130
+ | [配置](docs/configuration.md) | 每一个 `.env` 键、实验性开关、具名 profile、上次会话状态 |
131
+ | [模式、无头与命令](docs/usage.md) | 各模式详解、`reika -p`、斜杠命令、`/save` 会话记录 |
132
+ | [工具](docs/tools.md) | 模型可用的工具、审批提示、网络搜索设置、MCP 服务器、`.gitignore` |
133
+ | [指令与技能](docs/skills.md) | `AGENTS.md`、作为斜杠命令的技能、自然语言路由、粘贴的链接 |
134
+ | [测试过的模型](docs/zh/models.md) | Reika 实际跑过的本地量化版本和 API |
135
+ | [测量结果](docs/findings.md) | 实测记录:什么坏了、什么撑住了,以及每个数字是怎么得到的 |
136
+ | [平台](docs/zh/platforms.md) | 运行要求、在弱机器上运行、Linux 和 Windows 上的差异 |
137
+ | [架构与注意事项](docs/zh/architecture.md) | 框架如何工作,以及已知限制 |
138
+ | [贡献](CONTRIBUTING.md) | 脚本、设计理念、`AGENTS.md` 指引,以及外部贡献者指南 |
139
+ | [更新日志](CHANGELOG.md)(英文) | 每个版本的变更 |
140
140
 
141
141
  ## 灵感来自
142
142
 
143
- Claude Code、Codex、Crush、OpenCode、Pi、Aider、DeepSeek Harness、Qwen Code、Kimi Code CLI、Gemini CLI、Junie 和 DS4。
143
+ Claude Code、Codex、Crush、OpenCode、Pi、Aider、DeepSeek Harness、Qwen Code、Kimi Code CLI、Gemini CLI、Junie、DS4 和 Ante。
144
144
 
145
145
  ## 许可
146
146
 
@@ -15,6 +15,7 @@ import { ContinuationGate, continuationGate, continuationTail } from './continua
15
15
  import { biasableShingles, buildRuminationLogitBias } from './logitrecovery.js';
16
16
  import { EntropyTrace, formatEntropyReading } from './entropytrace.js';
17
17
  import { extractPlanReferences, verifyPlanReferences, buildGroundingNote, shouldSuppressGrounding, } from './groundcheck.js';
18
+ import { withDeclineFeedback } from '../approval.js';
18
19
  import { collectSourcedUrls } from '../tools/_exfil.js';
19
20
  import { groundUrlsForPlan } from '../tools/_urls.js';
20
21
  import { referencesSpill } from '../tools/_spill.js';
@@ -2275,7 +2276,10 @@ export async function runTurn(opts) {
2275
2276
  `usage.promptTokens=${response.usage?.promptTokens ?? 'MISSING'} ` +
2276
2277
  `completion=${completion} finishReason=${response.finishReason ?? '?'} ` +
2277
2278
  `decode=${formatRate(sample?.rate)} smoothed=${formatRate(decodeThroughput.get())} ` +
2278
- `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source}\n`);
2279
+ `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source} ` +
2280
+ // Process uptime, not turn time: on a fanless machine the rates sag with sustained load
2281
+ // and recover across idle gaps, so separating that from context growth needs wall clock.
2282
+ `t=${process.uptime().toFixed(0)}s\n`);
2279
2283
  if (opts.signal?.aborted) {
2280
2284
  commitAborted(opts, response.content, response.reasoning, turnStart, fetchedUrls);
2281
2285
  return;
@@ -2853,6 +2857,8 @@ export async function runTurn(opts) {
2853
2857
  subagentCalls.inRound = 0;
2854
2858
  }
2855
2859
  const subagentInRound = roundHasSubagent && subagentCalls.rounds <= MAX_SUBAGENTS_PER_TURN;
2860
+ // Reasons the user typed while declining this round's calls, sent after its results (below).
2861
+ const roundDeclineFeedback = [];
2856
2862
  for (const call of toolCalls) {
2857
2863
  if (opts.signal?.aborted)
2858
2864
  return;
@@ -2905,6 +2911,8 @@ export async function runTurn(opts) {
2905
2911
  let contentHash;
2906
2912
  let toolNotice;
2907
2913
  let editFailure;
2914
+ // The reason a user typed when declining this call, appended to its summary after the run.
2915
+ let declineFeedback;
2908
2916
  // Read-first (#72): path this call put file bytes in front of the model for, and whether the
2909
2917
  // model authored them (`write`) rather than being handed them. Applied once the tool message
2910
2918
  // exists, since handed-back grounding keys on its history index. See readfirst.ts.
@@ -2992,7 +3000,14 @@ export async function runTurn(opts) {
2992
3000
  groundedUrls,
2993
3001
  sourcedUrls: () => collectSourcedUrls(opts.history),
2994
3002
  askedQuestions,
2995
- requestApproval: opts.requestApproval,
3003
+ requestApproval: opts.requestApproval &&
3004
+ (async (req) => {
3005
+ const answer = await opts.requestApproval(req);
3006
+ if (typeof answer === 'boolean')
3007
+ return answer;
3008
+ declineFeedback = answer.feedback;
3009
+ return false;
3010
+ }),
2996
3011
  requestQuestion,
2997
3012
  onProgress: opts.onToolProgress && (chunk => opts.onToolProgress(chunk, tool.name)),
2998
3013
  spawnSubagent: makeSpawnSubagent(opts, subagentCalls, decodeThroughput, genReserve),
@@ -3002,8 +3017,12 @@ export async function runTurn(opts) {
3002
3017
  unattended: opts.isUnattended?.() ?? opts.config.unattended,
3003
3018
  signal: opts.signal,
3004
3019
  });
3005
- summary = result.summary;
3020
+ summary = declineFeedback
3021
+ ? withDeclineFeedback(result.summary, declineFeedback)
3022
+ : result.summary;
3006
3023
  payload = result.payload;
3024
+ if (declineFeedback)
3025
+ roundDeclineFeedback.push(declineFeedback);
3007
3026
  diff = result.diff;
3008
3027
  command = result.command;
3009
3028
  changes = result.changes;
@@ -3236,6 +3255,19 @@ export async function runTurn(opts) {
3236
3255
  opts.onMessage({ role: 'system', tone: 'info', content: planCheckoff });
3237
3256
  }
3238
3257
  }
3258
+ // The user's own words, as a user message rather than inside the declined call's result: in a
3259
+ // tool result even a framed quote read to lfm2.5-24b as the environment refusing ("maybe the
3260
+ // environment doesn't support it"), 0/3 on a reason asking for an answer instead of a command.
3261
+ // `harness`: not a turn boundary, so the task-spec pin stays put (#287). History only — the
3262
+ // declined call's row already shows the quote. The words go verbatim: opening with "I declined
3263
+ // `<command>`." gained nothing on a terse reason and buried an explicit one behind a long `cd`.
3264
+ if (roundDeclineFeedback.length > 0) {
3265
+ opts.history.push({
3266
+ role: 'user',
3267
+ content: roundDeclineFeedback.join('\n\n'),
3268
+ harness: true,
3269
+ });
3270
+ }
3239
3271
  // A round that added no new keys (all re-reads of already-seen sections / repeat searches) is a
3240
3272
  // stall; enough consecutive stalls trip the adaptive force-write on the next iteration.
3241
3273
  const roundLearned = seenReadOnly.size > seenBeforeRound || seenWebLookups.size > seenWebBeforeRound;
@@ -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
+ }
package/dist/approval.js CHANGED
@@ -35,6 +35,12 @@ export function declineSummary(action, target, ctx) {
35
35
  return `${action} declined by user${target}`;
36
36
  return `${action} not run${target} — unattended session, nobody to approve it. Carry on without it, or leave it for the user in your final reply.`;
37
37
  }
38
+ // A decline the user explained. A bare "declined by user" leaves a small model guessing what to do
39
+ // next, and the guess is often the same call again; the reason turns the dead end into the next
40
+ // instruction. The quote rides the summary, the part that survives aging and the user sees on the row.
41
+ export function withDeclineFeedback(summary, feedback) {
42
+ return `${summary}\nThe user wrote: "${feedback}"`;
43
+ }
38
44
  // The end-of-turn roll-up of what an unattended turn declined (#526). Built from the approval
39
45
  // requests themselves, so it is complete by construction — a model asked to recall its declines
40
46
  // could drop one or invent one. Null when nothing was declined.
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
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';
@@ -12,6 +13,8 @@ process.title = 'reika';
12
13
  // process starting, not of anything the UI mounts. Fire-and-forget — cleaning up after a session
13
14
  // that is already gone must never delay first paint, and it fails open on its own.
14
15
  void sweepStaleSpills();
16
+ // Debug-log retention (#761), the same shape: per-session logs past their age or size budget.
17
+ void sweepDebugLogs();
15
18
  // Both front-ends are imported lazily: the headless path (#52) never loads Ink, and the TUI
16
19
  // never loads the headless runner.
17
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
@@ -12,7 +12,7 @@ export const USAGE = `usage: reika start the interactive TUI in
12
12
  -h, --help show this
13
13
 
14
14
  Configuration is read from the environment, then ./.env, then ~/.config/reika/.env; REIKA_MODEL
15
- 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.
16
16
 
17
17
  With -p: a prompt starting with /<skill> runs that skill. Approvals follow REIKA_AUTO_APPROVE
18
18
  (default 'safe'): with no prompt to fall back on, anything 'safe' would have asked about is
@@ -1,6 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { isStreamTimeout, streamDispatcher, streamTimeoutMessage } from './dispatcher.js';
3
3
  import { API_USER_AGENT } from '../version.js';
4
+ import { errorCode } from '../tools/_net.js';
5
+ // llama-server's default since llama.cpp v0.7.0 (ggml-org/llama.cpp#30159); it was 8080 before.
6
+ export const DEFAULT_BASE_URL = 'http://localhost:9931/v1';
4
7
  // The OpenAI multimodal shape for one image, as a base64 data URL. Shared by the two paths that
5
8
  // put an image on the wire — the native send (provider/toolcall.ts) and the describe call
6
9
  // (ocr/vision.ts) — so the two spellings can't drift.
@@ -103,7 +106,7 @@ async function postWithRetry(url, body, apiKey, signal) {
103
106
  await sleep(backoffMs(attempt), signal);
104
107
  continue;
105
108
  }
106
- throw e;
109
+ throw refusedAtDefaultPort(url, e) ?? e;
107
110
  }
108
111
  }
109
112
  throw lastErr;
@@ -168,6 +171,15 @@ function parseSSELine(line) {
168
171
  return null;
169
172
  }
170
173
  }
174
+ // Nothing answering on the default port is most often a llama-server older than v0.7.0, which
175
+ // still listens on 8080 — say so, since a bare ECONNREFUSED reads as "the server is down".
176
+ function refusedAtDefaultPort(url, e) {
177
+ if (errorCode(e) !== 'ECONNREFUSED' || !url.startsWith(`${DEFAULT_BASE_URL}/`))
178
+ return undefined;
179
+ return new Error(`Nothing is listening at ${DEFAULT_BASE_URL}. llama-server uses 9931 since llama.cpp v0.7.0 ` +
180
+ 'and 8080 before it (and in its Docker images); set REIKA_BASE_URL to match your server, ' +
181
+ 'e.g. http://localhost:8080/v1.', { cause: e });
182
+ }
171
183
  // Stream a chat completion as an async iterable of typed chunks. The caller accumulates
172
184
  // deltas (content/reasoning/tool-calls) and reads usage/finish_reason off the chunks — same
173
185
  // shape the SDK's stream yielded, so client.ts's consume loop is unchanged in spirit.