@alexwkleung/reika 0.4.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`) | 为回复预留的空间;从模型的轮次中学习,设置它即固定该值 |
@@ -2275,7 +2275,10 @@ export async function runTurn(opts) {
2275
2275
  `usage.promptTokens=${response.usage?.promptTokens ?? 'MISSING'} ` +
2276
2276
  `completion=${completion} finishReason=${response.finishReason ?? '?'} ` +
2277
2277
  `decode=${formatRate(sample?.rate)} smoothed=${formatRate(decodeThroughput.get())} ` +
2278
- `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`);
2279
2282
  if (opts.signal?.aborted) {
2280
2283
  commitAborted(opts, response.content, response.reasoning, turnStart, fetchedUrls);
2281
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
+ }
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.
@@ -2,6 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { open, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, join } from 'node:path';
5
+ import { sessionStem } from '../debug.js';
5
6
  import { deriveTitle, serializeJsonl } from './transcript.js';
6
7
  // Session persistence and /resume (#1). An auto-save is the same canonical .jsonl /save writes
7
8
  // (meta line, one message per line), written unredacted — it is a local resume source, and a
@@ -19,10 +20,10 @@ export function projectHistoryDir(cwd, root = ROOT_HISTORY_DIR) {
19
20
  return join(root, 'projects', `${slug}-${hash}`);
20
21
  }
21
22
  // Fixed for the life of the session: every auto-save rewrites this one file, so a session is one
22
- // entry in the /resume list rather than one per save.
23
- export function newSessionPath(dir, startedAt) {
24
- const stamp = startedAt.toISOString().replace(/[:.]/g, '-');
25
- return join(dir, `${stamp}-${randomBytes(3).toString('hex')}.jsonl`);
23
+ // entry in the /resume list rather than one per save. `stem` names it after the process's debug
24
+ // log (#761), so the two pair.
25
+ export function newSessionPath(dir, startedAt, stem = sessionStem(startedAt)) {
26
+ return join(dir, `${stem}.jsonl`);
26
27
  }
27
28
  // Chat mode keeps its own history (see the mode table in AGENTS.md), so a file carries both sides:
28
29
  // the agent side's messages, then this marker, then the chat side's. Absent when chat was never