@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.
package/README.md CHANGED
@@ -143,6 +143,21 @@ The same pages are on the website, [reikacode.com](https://reikacode.com).
143
143
 
144
144
  Claude Code, Codex, Crush, OpenCode, Pi, Aider, DeepSeek Harness, Qwen Code, Kimi Code CLI, Gemini CLI, Junie, DS4, and Ante.
145
145
 
146
+ ## Citation
147
+
148
+ If you use Reika in your work, you can cite it as:
149
+
150
+ ```bibtex
151
+ @software{reika2026,
152
+ author = {Leung, Alex},
153
+ title = {Reika},
154
+ year = {2026},
155
+ url = {https://github.com/alexwkleung/reika}
156
+ }
157
+ ```
158
+
159
+ GitHub's "Cite this repository" button gives the same entry in other formats, from [CITATION.cff](CITATION.cff).
160
+
146
161
  ## License
147
162
 
148
163
  Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
package/README.zh-CN.md CHANGED
@@ -142,6 +142,21 @@ cd your-project && reika
142
142
 
143
143
  Claude Code、Codex、Crush、OpenCode、Pi、Aider、DeepSeek Harness、Qwen Code、Kimi Code CLI、Gemini CLI、Junie、DS4 和 Ante。
144
144
 
145
+ ## 引用
146
+
147
+ 如果你在工作中使用了 Reika,可以这样引用:
148
+
149
+ ```bibtex
150
+ @software{reika2026,
151
+ author = {Leung, Alex},
152
+ title = {Reika},
153
+ year = {2026},
154
+ url = {https://github.com/alexwkleung/reika}
155
+ }
156
+ ```
157
+
158
+ GitHub 的 "Cite this repository" 按钮会根据 [CITATION.cff](CITATION.cff) 给出其他格式的同一条目。
159
+
145
160
  ## 许可
146
161
 
147
162
  Apache License 2.0。见 [LICENSE](LICENSE) 和 [NOTICE](NOTICE)。
@@ -10,7 +10,7 @@ import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastU
10
10
  import { ReadTrace } from './readtrace.js';
11
11
  import { traceBashRead, traceReadPath } from './bashread.js';
12
12
  import { PrefixTrace } from './prefixtrace.js';
13
- import { PrefillRate, formatPrefillCost, reprocessedTokens, sampleTokens } from './prefillcost.js';
13
+ import { PrefillRate, formatMeasuredPrefill, formatPrefillCost, reprocessedTokens, sampleTokens, } from './prefillcost.js';
14
14
  import { DecodeRate, decodeSample, formatRate } from './decoderate.js';
15
15
  import { GenReserve, resolveGenReserve, withGenReserve } from './genreserve.js';
16
16
  import { selfRepeatRatio, repeatedSelfShingles, ReasoningTrace, liveSpinSignal, verbatimAbortThreshold, } from './reasoningtrace.js';
@@ -378,6 +378,13 @@ const DROPPED_LEDGER = process.env.REIKA_DROPPED_LEDGER !== '0';
378
378
  // runs as-is), suspended while inspection tools are withdrawn (the directed read would be refused).
379
379
  // The `would-land=` field on the bounce debug line is the measurement. See agent/readfirst.ts.
380
380
  const READ_FIRST = process.env.REIKA_READ_FIRST !== '0';
381
+ // EXPERIMENT (#867): keep the offered tool list unchanged while inspection is withdrawn, enforcing
382
+ // the pause at dispatch and through the ledger only. The template renders the tools ahead of the
383
+ // system prompt, so dropping them makes the withdrawal round and the lift round each a full
384
+ // re-prefill (`cause=tools-changed`). On by default since 2026-10-29 (`=0` is the baseline arm): on
385
+ // T2 with lfm2.5 it cut engine prefill per round by a third and refused calls per pause went down,
386
+ // not up — a model that still sees read/grep did not keep reaching for them.
387
+ const WITHDRAW_KEEP_TOOLS = process.env.REIKA_WITHDRAW_KEEP_TOOLS !== '0';
381
388
  // EXPERIMENT (plan mode): the force-write turn is a *transformation*, not another exploration
382
389
  // round. Asking the exploring model to "stop and write prose" fights its action prior and lets
383
390
  // the plan it already has decay across turns; but the plan is reliably in its reasoning. So at
@@ -1740,14 +1747,14 @@ export async function runTurn(opts) {
1740
1747
  }
1741
1748
  }
1742
1749
  // Empty tool lists are already a supported path (chat mode with no search provider). On a loop
1743
- // break, drop the inspection tools so the offered set steers a tool-list-respecting model
1744
- // straight to edit/write; the dispatch layer enforces it for one that emits reads in-band.
1750
+ // break the dispatch layer refuses inspection calls; with REIKA_WITHDRAW_KEEP_TOOLS=0 the
1751
+ // inspection tools are also dropped from the offered set (the pre-#867 behaviour).
1745
1752
  // The subagent's report round keeps the list and forbids calls with `tool_choice` instead
1746
1753
  // (#426): the template renders the tool list into the system turn, so withholding it would
1747
1754
  // re-prefill the subagent's whole context on its last round.
1748
1755
  const callTools = planForceWrite
1749
1756
  ? []
1750
- : withdrawInspection
1757
+ : withdrawInspection && !WITHDRAW_KEEP_TOOLS
1751
1758
  ? opts.tools.filter(t => !INSPECTION_TOOLS.has(t.name))
1752
1759
  : opts.tools;
1753
1760
  const planTransformBudget = window ? planTransformBudgetChars(window) : Number.MAX_SAFE_INTEGER;
@@ -2381,6 +2388,7 @@ export async function runTurn(opts) {
2381
2388
  `completion=${completion} finishReason=${response.finishReason ?? '?'} ` +
2382
2389
  `decode=${formatRate(sample?.rate)} smoothed=${formatRate(decodeThroughput.get())} ` +
2383
2390
  `src=${sample?.source ?? '?'} reserve=${reserve.tokens} reserveSrc=${reserve.source} ` +
2391
+ `${formatMeasuredPrefill(response.usage, response.enginePrompt, roundReprocessTokens)} ` +
2384
2392
  // Process uptime, not turn time: on a fanless machine the rates sag with sustained load
2385
2393
  // and recover across idle gaps, so separating that from context growth needs wall clock.
2386
2394
  `t=${process.uptime().toFixed(0)}s\n`);
@@ -77,3 +77,19 @@ export function formatPrefillCost(tokens, rate, bounded = false) {
77
77
  function formatSeconds(s) {
78
78
  return s >= 10 ? `${Math.round(s)}s` : `${s.toFixed(1)}s`;
79
79
  }
80
+ // The `round=` line's measured half (#868): what the provider and the engine reported about this
81
+ // request's prefill, beside the estimate the `prefix-cache` line printed before the call. `cached=?`
82
+ // rather than `0` when the provider reports no cache accounting — zero would claim a cold cache. The
83
+ // engine fields appear only when llama.cpp sent them, and `prompt_n` carries the estimate it should
84
+ // be read against (`reprocessEst=`), since that line was written before the count existed.
85
+ export function formatMeasuredPrefill(usage, engine, reprocessEstimate) {
86
+ const parts = [`cached=${usage?.cachedTokens ?? '?'}`];
87
+ if (engine?.promptN != null) {
88
+ parts.push(`prompt_n=${engine.promptN}`, `reprocessEst=${reprocessEstimate}`);
89
+ }
90
+ if (engine?.promptMs != null)
91
+ parts.push(`prompt_ms=${Math.round(engine.promptMs)}`);
92
+ if (engine?.cacheN != null)
93
+ parts.push(`cache_n=${engine.cacheN}`);
94
+ return parts.join(' ');
95
+ }
@@ -325,7 +325,9 @@ function buildAgentPrompt(opts) {
325
325
  // "only if asked" because on a small model a named path is an attractor for unrelated exploration.
326
326
  // Deliberately omitted: `~/.config/reika/.env` (API keys — naming it invites a `cat` that lands
327
327
  // them in context and the saved transcript), the chrome profile, and the binary (`reika -p` from
328
- // bash is a nested agent outside the subagent cap).
328
+ // bash is a nested agent outside the subagent cap). Both history paths are spelled out in full: named
329
+ // as `history/` alone, a model listed the root's /save files and never found projects/, where most
330
+ // sessions are.
329
331
  // `REIKA_SELF_AWARE=0` is the baseline arm: the prompt without the line, byte-for-byte.
330
332
  function selfLineParts() {
331
333
  return process.env.REIKA_SELF_AWARE === '0' ? [] : [reikaSelfLine()];
@@ -334,7 +336,8 @@ export function reikaSelfLine(docsDir = DOCS_DIR) {
334
336
  const where = [
335
337
  ...(docsDir ? [`its reference docs are in ${docsDir}`] : []),
336
338
  'user skills in ~/.config/reika/skills/ (project skills in .reika/skills/)',
337
- 'saved sessions in ~/.config/reika/history/',
339
+ 'auto-saved sessions in ~/.config/reika/history/projects/ (one subdirectory per project)',
340
+ '/save transcripts in ~/.config/reika/history/',
338
341
  ];
339
342
  return `You are running inside reika ${VERSION}. Only if the user asks about reika itself: ${where.join(', ')}.`;
340
343
  }
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { sweepDebugLogs } from './debug.js';
4
4
  import { sweepStaleSpills } from './tools/_spill.js';
5
- import { USAGE, parseHeadlessArgs } from './headlessargs.js';
5
+ import { USAGE, parseHeadlessArgs } from './headless/headlessargs.js';
6
6
  import { VERSION } from './version.js';
7
7
  // Lowercase like the command: ps/top/Activity Monitor otherwise list every session as `node`, and
8
8
  // pgrep/pkill match case-sensitively.
@@ -36,7 +36,7 @@ if (headless?.help) {
36
36
  process.exit(0);
37
37
  }
38
38
  if (headless) {
39
- const { runHeadless } = await import('./headless.js');
39
+ const { runHeadless } = await import('./headless/headless.js');
40
40
  const code = await runHeadless(headless, {
41
41
  stdout: text => process.stdout.write(text),
42
42
  stderr: text => process.stderr.write(text),
@@ -7,7 +7,7 @@ import { formatBundleSize } from './bundlesize.js';
7
7
  import { DEFAULT_BUDGET, packRepoMap, rankRepoMap } from './repomap.js';
8
8
  import { buildFileIndex } from './files.js';
9
9
  import { loadGitignore } from './gitignore.js';
10
- import { loadSkills } from '../skills.js';
10
+ import { loadSkills } from '../skills/skills.js';
11
11
  export async function bootstrap(cwd, repoMapBudget = DEFAULT_BUDGET) {
12
12
  const ig = await loadGitignore(cwd);
13
13
  const [projectSummary, instructions, repoMapRanked, fileIndex, skills] = await Promise.all([
package/dist/debug.js CHANGED
@@ -180,3 +180,18 @@ export function formatExperimentFlags() {
180
180
  });
181
181
  return `[reika:debug] flags version=${VERSION} ${flags.join(' ') || '(none set)'}`;
182
182
  }
183
+ // Which model and server a log's rounds ran against (#868): once per session and on every switch,
184
+ // so saved logs can be split by model. The host only — a base URL's path, query and userinfo stay
185
+ // out, as the flags line keeps values out. A model id that is a filesystem path (llama.cpp names a
186
+ // model by the file it loaded) is cut to its basename, so a home path cannot land in the log.
187
+ export function formatEndpointLine(profile, model, baseURL) {
188
+ let host = '?';
189
+ try {
190
+ host = new URL(baseURL).hostname || '?';
191
+ }
192
+ catch {
193
+ // An unparseable base URL is logged as unknown rather than verbatim.
194
+ }
195
+ const id = /^([/~\\]|[A-Za-z]:[/\\])/.test(model) ? (model.split(/[/\\]/).pop() ?? '?') : model;
196
+ return `[reika:debug] endpoint profile=${profile} model=${id || '?'} host=${host}`;
197
+ }
@@ -1,22 +1,35 @@
1
- import { join } from 'node:path';
1
+ import { basename, join } from 'node:path';
2
2
  import { homedir } from 'node:os';
3
- import { loadConfig, resolveDefaultMode } from './config.js';
4
- import { startProfiles } from './laststate.js';
5
- import { saveTranscript, TRANSCRIPT_VERSION } from './store/transcript.js';
6
- import { createSession } from './session.js';
7
- import { expandMentions } from './agent/mentions.js';
8
- import { expandPastedUrls } from './agent/pastedurls.js';
9
- import { matchSkill, shouldAutoInject } from './skillmatch.js';
10
- import { imageReader } from './ocr/select.js';
11
- import { autoApproves } from './approval.js';
12
- import { toolLabel } from './ui/format.js';
13
- import { debugLog } from './debug.js';
14
- import { callMcpTool, findMcpCommand, parseMcpArgs } from './mcp/tools.js';
3
+ import { loadConfig, resolveDefaultMode } from '../config.js';
4
+ import { startProfiles } from '../laststate.js';
5
+ import { buildTranscriptMeta, saveTranscript, } from '../store/transcript.js';
6
+ import { countRealTurns, newSessionPath, projectHistoryDir, saveHeader, writeSession, } from '../store/sessions.js';
7
+ import { createSession } from '../session.js';
8
+ import { expandMentions } from '../agent/mentions.js';
9
+ import { expandPastedUrls, planPastedUrls } from '../agent/pastedurls.js';
10
+ import { matchSkill, shouldAutoInject, shouldConfirmInject } from '../skills/skillmatch.js';
11
+ import { imageReader } from '../ocr/select.js';
12
+ import { autoApproves } from '../approval.js';
13
+ import { toolLabel } from '../ui/format.js';
14
+ import { debugLog, processSessionStem } from '../debug.js';
15
+ import { callMcpTool, findMcpCommand, parseMcpArgs } from '../mcp/tools.js';
16
+ import { askApproval, askConfirm, askQuestion, openTerminalPrompter, } from './headlessprompt.js';
17
+ import { pastedUrlConfirmSpec, skillConfirmSpec } from '../ui/dialogspecs.js';
18
+ // Headless mode (#52): `reika -p "<prompt>"` runs one turn with no TUI and prints the reply.
19
+ // The session (boot, threaded state, the vibe chain) is session.ts, shared with the eval runner;
20
+ // what lives here is the part of App's submit path that shapes what the model sees (mention/URL
21
+ // expansion, skill routing) and the approval policy. Those are deliberately the same modules App
22
+ // calls, in the same order: a headless run must be the run the TUI would have made, or it is
23
+ // useless as the debugging instrument the issue asks for.
24
+ // The TUI's mid-turn auto-save cadence.
25
+ const AUTOSAVE_INTERVAL_MS = 3000;
15
26
  // The model-facing text for a prompt, built the way App's submit path builds it: a leading
16
27
  // /<skill> is that skill's body (with the rest as extra guidance), otherwise @mentions and pasted
17
28
  // URLs expand and a `triggers:` match may auto-inject. Returns the notices those steps produced
18
- // so the caller can surface them; they never enter the model's context here either.
19
- export async function buildHeadlessInput(prompt, config, bundle, mode) {
29
+ // so the caller can surface them; they never enter the model's context here either. With `confirm`
30
+ // (--interactive, #872) the skill and pasted-link questions are asked as the TUI asks them, before
31
+ // any expansion, so no fetch precedes the question; null (EOF, ctrl-c) is "send as typed".
32
+ export async function buildHeadlessInput(prompt, config, bundle, mode, confirm) {
20
33
  const notices = [];
21
34
  if (prompt.startsWith('/')) {
22
35
  const [name, ...rest] = prompt.slice(1).split(/\s+/);
@@ -31,11 +44,21 @@ export async function buildHeadlessInput(prompt, config, bundle, mode) {
31
44
  notices,
32
45
  };
33
46
  }
47
+ const match = matchSkill(prompt, bundle.skills);
48
+ // App.decideSkillRoute's gate: every mode but chat, and no word cap — a human is answering.
49
+ const applySkill = confirm && match && config.skillAuto !== 'off' && mode !== 'chat'
50
+ ? shouldConfirmInject(match, config.contextWindow) &&
51
+ (await confirm(skillConfirmSpec(match))) === true
52
+ : undefined;
53
+ const urlPlan = planPastedUrls(prompt);
54
+ const incidental = confirm && config.pasteFetch !== 'off' && urlPlan.urls.length > 0 && !urlPlan.request
55
+ ? (await confirm(pastedUrlConfirmSpec(urlPlan.urls))) === true
56
+ : undefined;
34
57
  const expansion = await expandMentions(prompt, bundle.cwd, { ocr: imageReader(config) });
35
58
  notices.push(...expansion.notices);
36
- // No `incidental`: there is nobody to ask, so a link the prompt is not about is left alone
37
- // under 'ask' and fetched under 'apply' — the REIKA_SKILL_AUTO split.
38
- const urls = await expandPastedUrls(prompt, { mode: config.pasteFetch });
59
+ // No `incidental` without --interactive: there is nobody to ask, so a link the prompt is not
60
+ // about is left alone under 'ask' and fetched under 'apply' — the REIKA_SKILL_AUTO split.
61
+ const urls = await expandPastedUrls(prompt, { mode: config.pasteFetch, incidental });
39
62
  notices.push(...urls.notices.map(n => n.text));
40
63
  let modelText = expansion.augmented;
41
64
  if (urls.blocks.length > 0)
@@ -43,11 +66,11 @@ export async function buildHeadlessInput(prompt, config, bundle, mode) {
43
66
  // Same exclusion as App.routeSkill: a skill body landing in plan mode competes with the plan
44
67
  // prompt. Headless has no one to suggest it to, so a non-injecting match is silent — and no one
45
68
  // to ask, so only 'apply' injects; the interactive default 'ask' sends the prompt as typed.
46
- const match = matchSkill(prompt, bundle.skills);
47
- const auto = match &&
48
- config.skillAuto === 'apply' &&
49
- (mode === 'agent' || mode === 'vibe') &&
50
- shouldAutoInject(match, config.contextWindow);
69
+ const auto = applySkill ??
70
+ (match &&
71
+ config.skillAuto === 'apply' &&
72
+ (mode === 'agent' || mode === 'vibe') &&
73
+ shouldAutoInject(match, config.contextWindow));
51
74
  if (match && auto) {
52
75
  notices.push(`Skill /${match.skill.name} applied — its body was prepended to this prompt (matched: ${match.matched.join(', ')}).`);
53
76
  return { modelText: `${match.skill.body}\n\n${modelText}`, skill: match.skill.name, notices };
@@ -82,9 +105,30 @@ export async function runHeadless(args, io) {
82
105
  io.stderr('reika: no prompt given\n');
83
106
  return 1;
84
107
  }
108
+ // Opened before the session, since it decides the tool list: ask_user is offered only when
109
+ // someone can answer it. Its reads end on the turn's abort, so ctrl-c at a menu stops the run.
110
+ const controller = new AbortController();
111
+ let prompter = null;
112
+ if (args.interactive) {
113
+ prompter = openTerminalPrompter(controller.signal);
114
+ if (!prompter) {
115
+ io.stderr('reika: --interactive needs a terminal to ask on, and this run has none\n');
116
+ return 1;
117
+ }
118
+ }
119
+ try {
120
+ return await runHeadlessTurn(args, io, prompt, controller, prompter);
121
+ }
122
+ finally {
123
+ prompter?.close();
124
+ }
125
+ }
126
+ async function runHeadlessTurn(args, io, prompt, controller, prompter) {
85
127
  // autoApprove is session-wide, not per-profile, so the loaded config decides the policy.
86
- // Always unattended: nobody can answer a prompt here, so a decline must not read as the user's.
87
- const loaded = { ...loadConfig(), unattended: true };
128
+ // Unattended unless --interactive: with nobody to answer, a decline must not read as the user's.
129
+ const loaded = { ...loadConfig(), unattended: !prompter };
130
+ // "Always (this session)" lifts the policy to 'safe', as the TUI's toggle does.
131
+ let policy = loaded.autoApprove;
88
132
  // The mode is settled before the session is created, because it decides the model (#616): a mode
89
133
  // with its own model in REIKA_MODE_MODELS runs that one, `--mode` or not. Headless has no /model
90
134
  // and no saved state — its env is the whole answer — so an empty state is the whole of #365 here.
@@ -94,34 +138,61 @@ export async function runHeadless(args, io) {
94
138
  io.stderr(`reika: ${chosen.notice}\n`);
95
139
  const profile = chosen.profile;
96
140
  const stream = args.stream ? createStreamPrinter(io, args.json) : null;
141
+ // Read lazily: the transcript belongs to the session created below.
142
+ let transcript = () => [];
143
+ const tracked = createHeadlessStatus(() => transcript());
144
+ // Assigned once the session exists: the file lives under the bundle's cwd.
145
+ let autosave = null;
97
146
  const session = await createSession({
98
147
  cwd: process.cwd(),
99
148
  config: loaded,
100
149
  profile,
101
- canAsk: false,
150
+ canAsk: !!prompter,
151
+ requestQuestion: prompter ? req => askQuestion(prompter, req) : undefined,
102
152
  requestApproval: loaded.autoApprove === 'bypass'
103
153
  ? undefined
104
- : (req) => {
105
- if (autoApproves(loaded.autoApprove, req))
106
- return Promise.resolve(true);
154
+ : async (req) => {
155
+ if (autoApproves(policy, req))
156
+ return true;
157
+ if (prompter) {
158
+ const { answer, always } = await askApproval(prompter, req);
159
+ if (always && policy === 'off')
160
+ policy = 'safe';
161
+ return answer;
162
+ }
107
163
  io.stderr(`reika: declined ${toolLabel(req.tool)} (no prompt to ask at): ${firstLine(req.preview)}\n`);
108
- return Promise.resolve(false);
164
+ return false;
109
165
  },
110
166
  events: {
111
167
  ...stream?.events,
168
+ ...tracked.events,
112
169
  // The persistent receipts App puts in the scrollback — a fold, a declined URL, the
113
170
  // typecheck gate bouncing the model — are the ones a human watching a pipe should see.
114
171
  onMessage: msg => {
115
172
  if (msg.role === 'system')
116
173
  io.stderr(`reika: ${msg.content}\n`);
117
174
  stream?.onMessage(msg);
175
+ autosave?.onMessage();
118
176
  },
119
177
  },
120
178
  });
179
+ transcript = () => session.transcript;
121
180
  // MCP servers are this run's children: closed on every way out, so each gets its stdin EOF and a
122
181
  // moment to exit before `process.exit` would kill it outright (#594).
123
182
  try {
124
183
  const { config, bundle } = session;
184
+ const meta = (midTurn) => buildTranscriptMeta({
185
+ msgs: session.transcript,
186
+ model: config.model,
187
+ baseURL: config.baseURL,
188
+ cwd: bundle.cwd,
189
+ mode,
190
+ status: tracked.status(session),
191
+ midTurn,
192
+ });
193
+ if (config.autosave) {
194
+ autosave = createHeadlessAutosave(newSessionPath(projectHistoryDir(bundle.cwd), new Date(), processSessionStem()), () => session.transcript, mode === 'chat' ? 'chat' : 'agent', meta, message => io.stderr(`reika: auto-save failed: ${message}\n`));
195
+ }
125
196
  if (session.limitsNotice)
126
197
  io.stderr(`reika: ${session.limitsNotice}\n`);
127
198
  if (session.windowNotice)
@@ -157,10 +228,9 @@ export async function runHeadless(args, io) {
157
228
  // summary on stderr is not something it can parse.
158
229
  return failed ? 1 : 0;
159
230
  }
160
- const input = await buildHeadlessInput(prompt, config, bundle, mode);
231
+ const input = await buildHeadlessInput(prompt, config, bundle, mode, prompter ? spec => askConfirm(prompter, spec) : undefined);
161
232
  for (const n of input.notices)
162
233
  io.stderr(`reika: ${n}\n`);
163
- const controller = new AbortController();
164
234
  const onSigint = () => controller.abort();
165
235
  process.once('SIGINT', onSigint);
166
236
  let failed = null;
@@ -180,24 +250,10 @@ export async function runHeadless(args, io) {
180
250
  stream?.finish();
181
251
  }
182
252
  const appended = session.transcript;
253
+ await autosave?.finish();
183
254
  if (args.save) {
184
255
  try {
185
- const { jsonlPath } = await saveTranscript(join(homedir(), '.config', 'reika', 'history'), appended, {
186
- version: TRANSCRIPT_VERSION,
187
- savedAt: new Date().toISOString(),
188
- model: config.model,
189
- baseURL: config.baseURL,
190
- cwd: bundle.cwd,
191
- messageCount: appended.length,
192
- mode,
193
- usage: {
194
- turns: appended.filter(m => m.role === 'assistant').length,
195
- ...session.totals,
196
- contextTokens: session.lastUsage?.promptTokens ?? null,
197
- ...(config.contextWindow ? { contextWindow: config.contextWindow } : {}),
198
- ...(session.shrink.sheds > 0 || session.shrink.folds > 0 ? session.shrink : {}),
199
- },
200
- });
256
+ const { jsonlPath } = await saveTranscript(join(homedir(), '.config', 'reika', 'history'), appended, saveHeader(meta(false), appended));
201
257
  io.stderr(`reika: saved ${appended.length} messages → ${jsonlPath}\n`);
202
258
  }
203
259
  catch (e) {
@@ -227,6 +283,84 @@ export async function runHeadless(args, io) {
227
283
  await session.mcp.close();
228
284
  }
229
285
  }
286
+ // The status-line operands the session does not keep itself, tracked the way App tracks them so the
287
+ // saved header is the TUI's (#871): the pre-send estimate, each shed or fold stamped with its turn,
288
+ // and the last call's usage dropped once a shrink has made it stale.
289
+ export function createHeadlessStatus(messages) {
290
+ let lastUsage = null;
291
+ let estimatedContext = null;
292
+ const shrinkEvents = [];
293
+ return {
294
+ events: {
295
+ onUsage: u => (lastUsage = u),
296
+ onContextEstimate: t => (estimatedContext = t),
297
+ onShrink: event => {
298
+ lastUsage = null;
299
+ const turn = messages().filter(m => m.role === 'assistant').length + 1;
300
+ shrinkEvents.push({ turn, ...event });
301
+ },
302
+ },
303
+ status: session => ({
304
+ totals: session.totals,
305
+ lastUsage,
306
+ estimatedContext,
307
+ shrink: session.shrink,
308
+ shrinkEvents: [...shrinkEvents],
309
+ contextWindow: session.config.contextWindow,
310
+ minGenTokens: session.config.minGenTokens,
311
+ }),
312
+ };
313
+ }
314
+ // Auto-save for a headless run (#871): the TUI's file, in the TUI's place, so /resume lists a
315
+ // `reika -p` run beside the interactive ones. Written on the first real prompt, at most once per
316
+ // interval while the turn runs (a long unattended turn is exactly the one a crash should not take
317
+ // whole), and once more at the end. Writes are chained so an older snapshot never lands last.
318
+ // A chat run is the chat side of the file, as the TUI writes it: chat history is isolated from
319
+ // the other modes, and a /resume of it must not land in agent history.
320
+ export function createHeadlessAutosave(path, messages, side, meta, onError, intervalMs = AUTOSAVE_INTERVAL_MS) {
321
+ let chain = Promise.resolve();
322
+ let timer = null;
323
+ let written = false;
324
+ let failed = false;
325
+ const save = (midTurn) => {
326
+ if (timer !== null) {
327
+ clearTimeout(timer);
328
+ timer = null;
329
+ }
330
+ const msgs = messages();
331
+ // An MCP command or a turn that never reached its user echo is not a session worth listing.
332
+ if (countRealTurns(msgs) === 0)
333
+ return chain;
334
+ if (!written)
335
+ debugLog(`[reika:debug] session file=${basename(path)}`);
336
+ written = true;
337
+ const sides = { agent: [], chat: [], [side]: [...msgs] };
338
+ const header = meta(midTurn);
339
+ chain = chain
340
+ .then(() => writeSession(path, sides, header))
341
+ .catch((e) => {
342
+ // Said once: a full disk fails every save the same way.
343
+ if (failed)
344
+ return;
345
+ failed = true;
346
+ onError(e.message);
347
+ });
348
+ return chain;
349
+ };
350
+ return {
351
+ onMessage: () => {
352
+ if (!written) {
353
+ void save(true);
354
+ return;
355
+ }
356
+ if (timer !== null)
357
+ return;
358
+ timer = setTimeout(() => void save(true), intervalMs);
359
+ timer.unref?.();
360
+ },
361
+ finish: () => save(false),
362
+ };
363
+ }
230
364
  // --stream (#566). Text: the content channel goes to stdout as it arrives and each tool call's
231
365
  // summary to stderr, so a pipe reads like the TUI minus the reasoning. What streams can't be taken
232
366
  // back, so the two things the TUI streams and then replaces stay off stdout: a subagent's rounds
@@ -8,6 +8,8 @@ export const USAGE = `usage: reika start the interactive TUI in
8
8
  --stream print as the turn runs: the reply as it is generated, tool calls on
9
9
  stderr; with --json, one message per line (NDJSON) as each is committed
10
10
  --save save the transcript to ~/.config/reika/history like /save
11
+ -i, --interactive with -p: ask approvals, ask_user and confirms on the terminal
12
+ instead of declining them (needs a terminal; stdin may still be piped)
11
13
  -v, --version print the version
12
14
  -h, --help show this
13
15
 
@@ -16,8 +18,9 @@ is required and REIKA_BASE_URL defaults to http://localhost:9931/v1.
16
18
 
17
19
  With -p: a prompt starting with /<skill> runs that skill. Approvals follow REIKA_AUTO_APPROVE
18
20
  (default 'safe'): with no prompt to fall back on, anything 'safe' would have asked about is
19
- declined, and 'off' declines every edit and command. ask_user is never offered. Exit status: 0 on
20
- a reply, 1 on an error, 130 when interrupted.`;
21
+ declined, and 'off' declines every edit and command. ask_user is never offered. With -i each of
22
+ those is asked instead, as a numbered menu on the terminal. Exit status: 0 on a reply, 1 on an
23
+ error, 130 when interrupted.`;
21
24
  const MODES = new Set(['agent', 'plan', 'vibe', 'minimal', 'grind', 'chat']);
22
25
  // Returns null when the argv holds no headless request, so the caller starts the TUI. --help and
23
26
  // --version count as requests: both answer without starting either front-end. Throws on
@@ -27,6 +30,7 @@ export function parseHeadlessArgs(argv) {
27
30
  json: false,
28
31
  stream: false,
29
32
  save: false,
33
+ interactive: false,
30
34
  help: false,
31
35
  version: false,
32
36
  };
@@ -64,6 +68,9 @@ export function parseHeadlessArgs(argv) {
64
68
  else if (a === '--save') {
65
69
  args.save = true;
66
70
  }
71
+ else if (a === '-i' || a === '--interactive') {
72
+ args.interactive = true;
73
+ }
67
74
  else if (a === '-h' || a === '--help') {
68
75
  args.help = true;
69
76
  headless = true;
@@ -94,5 +101,8 @@ export function parseHeadlessArgs(argv) {
94
101
  if (!headless && args.profile !== undefined) {
95
102
  throw new Error(`--profile applies to a headless run; add -p\n${USAGE}`);
96
103
  }
104
+ if (!headless && args.interactive) {
105
+ throw new Error(`--interactive applies to a headless run; add -p\n${USAGE}`);
106
+ }
97
107
  return headless ? args : null;
98
108
  }