@alexwkleung/reika 0.6.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.
Files changed (45) hide show
  1. package/README.md +15 -0
  2. package/README.zh-CN.md +15 -0
  3. package/dist/agent/bashread.js +177 -0
  4. package/dist/agent/compaction.js +5 -0
  5. package/dist/agent/compactionreport.js +184 -0
  6. package/dist/agent/loop.js +172 -45
  7. package/dist/agent/noteslotmonitor.js +82 -0
  8. package/dist/agent/prefillcost.js +16 -0
  9. package/dist/agent/prompt.js +5 -2
  10. package/dist/agent/readtrace.js +18 -8
  11. package/dist/check/typecheck.js +29 -0
  12. package/dist/cli.js +2 -2
  13. package/dist/config.js +30 -17
  14. package/dist/context/bootstrap.js +4 -2
  15. package/dist/debug.js +15 -0
  16. package/dist/{headless.js → headless/headless.js} +182 -48
  17. package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
  18. package/dist/headless/headlessprompt.js +132 -0
  19. package/dist/mcp/client.js +97 -5
  20. package/dist/mcp/manager.js +15 -2
  21. package/dist/provider/client.js +28 -0
  22. package/dist/provider/latches.js +3 -0
  23. package/dist/provider/noteslot.js +239 -0
  24. package/dist/provider/templatekwargs.js +31 -0
  25. package/dist/provider/toolcall.js +22 -1
  26. package/dist/provider/transport.js +12 -9
  27. package/dist/session.js +21 -1
  28. package/dist/{skills.js → skills/skills.js} +93 -13
  29. package/dist/store/sessions.js +39 -2
  30. package/dist/store/transcript.js +35 -0
  31. package/dist/tools/_carriers.js +119 -0
  32. package/dist/tools/_danger.js +539 -90
  33. package/dist/tools/_readonly.js +13 -12
  34. package/dist/ui/App.js +183 -70
  35. package/dist/ui/Approval.js +80 -33
  36. package/dist/ui/Confirm.js +1 -27
  37. package/dist/ui/DiffView.js +23 -12
  38. package/dist/ui/Question.js +152 -19
  39. package/dist/ui/ResumeSelect.js +3 -2
  40. package/dist/ui/Status.js +19 -7
  41. package/dist/ui/commands.js +47 -1
  42. package/dist/ui/dialogspecs.js +38 -0
  43. package/dist/ui/layout.js +118 -0
  44. package/package.json +1 -1
  45. /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
@@ -32,6 +32,7 @@ export class ReadTrace {
32
32
  unique: 0,
33
33
  changed: 0,
34
34
  narrowed: 0,
35
+ regrounded: 0,
35
36
  'dup-live': 0,
36
37
  'dup-aged': 0,
37
38
  };
@@ -39,16 +40,23 @@ export class ReadTrace {
39
40
  // is correct: the fresh block only spans the active turn's history, so liveness is a within-turn
40
41
  // notion. `hash` is the whole-file hash from the read result. Returns the class plus the running
41
42
  // repeat count for this region (1 = first/just-changed), so the caller can log and detect loops.
42
- record(path, offset, hash, round, limit) {
43
+ record(path, offset, hash, round, limit, via = 'read') {
43
44
  const key = `${path}\0${offset}`;
44
45
  const prior = this.seen.get(key);
46
+ const file = this.files.get(path);
45
47
  // An absent (or nonsensical) limit reads as unbounded, so it is never *narrower* than anything
46
48
  // and callers that don't track windows keep the pre-carve-out behaviour exactly.
47
49
  const window = typeof limit === 'number' && Number.isFinite(limit) && limit > 0 ? limit : Infinity;
48
50
  let cls;
49
51
  let repeats;
50
52
  let narrowings;
51
- if (!prior) {
53
+ if (via === 'read' && file?.hash === hash && file.lastVia === 'bash') {
54
+ // The read-first gate asked for these bytes again; the run stays where the shell read left it.
55
+ cls = 'regrounded';
56
+ repeats = prior?.hash === hash ? prior.repeats : 1;
57
+ narrowings = prior?.hash === hash ? prior.narrowings : 0;
58
+ }
59
+ else if (!prior) {
52
60
  cls = 'unique';
53
61
  repeats = 1;
54
62
  narrowings = 0;
@@ -89,7 +97,7 @@ export class ReadTrace {
89
97
  lastLive: cls === 'dup-live',
90
98
  });
91
99
  this.counts[cls]++;
92
- this.recordFile(path, offset, window, hash, round, cls);
100
+ this.recordFile(path, offset, window, hash, round, cls, via);
93
101
  return { cls, repeats };
94
102
  }
95
103
  // The per-file coverage depth (#341). A changed hash resets the file: the model edited it, so
@@ -99,15 +107,16 @@ export class ReadTrace {
99
107
  // `narrowed` read is recorded (later reads see its range) but never deepens: it is the sanctioned
100
108
  // descent into a capped page, already bounded per region by MAX_NARROWINGS, and the #184
101
109
  // transcript (300 → 70 → 35 → 18 at one offset) would otherwise be depth 4 by construction.
102
- recordFile(path, offset, window, hash, round, cls) {
110
+ recordFile(path, offset, window, hash, round, cls, via) {
103
111
  const lo = Math.max(1, offset);
104
112
  const hi = window === Infinity ? Infinity : lo + window - 1;
105
113
  let f = this.files.get(path);
106
114
  if (!f || f.hash !== hash) {
107
- f = { hash, ranges: [], depth: 0, lastRound: round };
115
+ f = { hash, ranges: [], depth: 0, lastRound: round, lastVia: via };
108
116
  this.files.set(path, f);
109
117
  }
110
- if (cls !== 'narrowed') {
118
+ f.lastVia = via;
119
+ if (cls !== 'narrowed' && cls !== 'regrounded') {
111
120
  const points = [lo, ...f.ranges.map(([a]) => a).filter(a => a >= lo && a <= hi)];
112
121
  let depth = 1;
113
122
  for (const p of points) {
@@ -159,7 +168,7 @@ export class ReadTrace {
159
168
  }
160
169
  total() {
161
170
  const c = this.counts;
162
- return c.unique + c.changed + c.narrowed + c['dup-live'] + c['dup-aged'];
171
+ return c.unique + c.changed + c.narrowed + c.regrounded + c['dup-live'] + c['dup-aged'];
163
172
  }
164
173
  summary() {
165
174
  const c = this.counts;
@@ -176,6 +185,7 @@ export class ReadTrace {
176
185
  if (f.depth >= FILE_OVERLAP_DEPTH)
177
186
  overlapped++;
178
187
  return (`unique=${c.unique} changed=${c.changed} dup-live=${c['dup-live']} dup-aged=${c['dup-aged']} ` +
179
- `narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped}`);
188
+ `narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped} ` +
189
+ `regrounded=${c.regrounded}`);
180
190
  }
181
191
  }
@@ -92,6 +92,35 @@ export function decideTypecheckGate(args) {
92
92
  userNotice: `Typecheck: ${n} type ${word} from this turn still unresolved after ${maxRounds} attempts — finishing anyway.`,
93
93
  };
94
94
  }
95
+ // How many introduced errors a stop message quotes. The full list is the next turn's gate's job;
96
+ // the stop only has to say the tree is broken and where to start.
97
+ const STOP_REPORT_SHOWN = 2;
98
+ // The gate's final check, reported rather than enforced, for a turn the harness ended itself (a
99
+ // loop stop, the round cap — #830). No send-back: a stop fires because the model stopped acting on
100
+ // directives, so a typecheck retry would land on the same loop. Empty when the check didn't run.
101
+ export function stopTypecheckReport(baseline, final) {
102
+ if (!final.ran)
103
+ return {};
104
+ const introduced = introducedDiagnostics(baseline, final.diagnostics);
105
+ const n = introduced.length;
106
+ if (n === 0) {
107
+ return { tone: 'info', userNotice: 'Typecheck passed — no new type errors from your edits.' };
108
+ }
109
+ const word = n === 1 ? 'error' : 'errors';
110
+ const shown = introduced
111
+ .slice(0, STOP_REPORT_SHOWN)
112
+ // tsc's own period dropped: the sentence closes the list, so it would print `….`.
113
+ .map(d => {
114
+ const msg = d.message.slice(0, MAX_MESSAGE_CHARS).replace(/\.$/, '');
115
+ return `\`${d.file}:${d.line} ${d.code}: ${msg}\``;
116
+ });
117
+ const more = n > shown.length ? `, +${n - shown.length} more` : '';
118
+ return {
119
+ addendum: ` The edits also introduced ${n} new type ${word}: ${shown.join(', ')}${more}.`,
120
+ tone: 'warn',
121
+ userNotice: `Typecheck: the edits introduced ${n} new type ${word}, left unfixed by the stop.`,
122
+ };
123
+ }
95
124
  // ── impure shell ──────────────────────────────────────────────────────────────────────────────
96
125
  // Resolve the tsconfig that governs an edit. Three layers, every one fail-open — any uncertainty
97
126
  // resolves to null, which disables the gate (the same no-op as a project with no tsconfig at all)
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),
package/dist/config.js CHANGED
@@ -158,6 +158,8 @@ export function loadConfig() {
158
158
  // Per-project session auto-save for /resume (#1). Default on; `0` stops reika writing
159
159
  // conversations to disk at all, which is the one reason to want it off.
160
160
  autosave: process.env.REIKA_AUTOSAVE !== '0',
161
+ // #827: REIKA_NOTE_SLOT=tool|user forces the slot instead, checked where the probe would run.
162
+ noteSlotProbe: true,
161
163
  // Rotating garden words on the busy indicator (#500). Default on; `0` keeps the plain
162
164
  // "Working…" for anyone who finds it noise.
163
165
  workingWords: process.env.REIKA_WORKING_WORDS !== '0',
@@ -474,23 +476,34 @@ export function inheritProfile(from, model) {
474
476
  adhoc: true,
475
477
  };
476
478
  }
479
+ // The type brand is erased by any `Config` annotation or helper on the way, so the tag is what
480
+ // actually catches a resolved config reaching createSession (#832). Enumerable so a spread keeps it.
481
+ const RESOLVED = Symbol('ResolvedConfig');
482
+ export function assertRawConfig(config, where) {
483
+ if (RESOLVED in config) {
484
+ throw new Error(`${where} was given resolveProfile()'s result; pass the raw config instead`);
485
+ }
486
+ }
477
487
  export function resolveProfile(config, profileName) {
488
+ assertRawConfig(config, 'resolveProfile');
478
489
  const profile = config.profiles[profileName];
479
- if (!profile)
480
- return config;
481
- return {
482
- ...config,
483
- model: profile.model,
484
- baseURL: profile.baseURL,
485
- apiKey: profile.apiKey,
486
- maxTokens: profile.maxTokens,
487
- contextWindow: profile.contextWindow,
488
- maxOutputTokens: profile.maxOutputTokens,
489
- minGenTokens: profile.minGenTokens ?? config.minGenTokens,
490
- minGenAdaptive: profile.minGenTokens != null ? profile.minGenAdaptive : config.minGenAdaptive,
491
- // Same `?? config.x` fallback shape as minGenTokens. Without this line the profile's route is
492
- // dead weight: `...config` above would carry the *default* profile's value straight over it, so
493
- // a `/model <vl>` switch would keep describing while claiming to be native.
494
- vision: profile.vision ?? config.vision,
495
- };
490
+ // An unknown name falls back to the top level, i.e. the default profile.
491
+ const overlaid = profile
492
+ ? {
493
+ ...config,
494
+ model: profile.model,
495
+ baseURL: profile.baseURL,
496
+ apiKey: profile.apiKey,
497
+ maxTokens: profile.maxTokens,
498
+ contextWindow: profile.contextWindow,
499
+ maxOutputTokens: profile.maxOutputTokens,
500
+ minGenTokens: profile.minGenTokens ?? config.minGenTokens,
501
+ minGenAdaptive: profile.minGenTokens != null ? profile.minGenAdaptive : config.minGenAdaptive,
502
+ // Same `?? config.x` fallback shape as minGenTokens. Without this line the profile's route
503
+ // is dead weight: `...config` above would carry the *default* profile's value straight over
504
+ // it, so a `/model <vl>` switch would keep describing while claiming to be native.
505
+ vision: profile.vision ?? config.vision,
506
+ }
507
+ : config;
508
+ return { ...overlaid, [RESOLVED]: true };
496
509
  }
@@ -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([
@@ -68,7 +68,9 @@ async function summarizeProject(cwd) {
68
68
  // crowding out the conversation on small windows (12KB ≈ 3k tokens), so we fall
69
69
  // back to an outline + read pointer instead of the full text.
70
70
  const INSTRUCTIONS_BUDGET = 12 * 1024;
71
- const INSTRUCTIONS_NAMES = ['AGENTS.md', 'CLAUDE.md'];
71
+ // First match wins. AGENT.md is an older spelling of the same tool-neutral convention; CLAUDE.md
72
+ // goes last because it is often written for Claude Code's own commands and tools.
73
+ const INSTRUCTIONS_NAMES = ['AGENTS.md', 'AGENT.md', 'CLAUDE.md'];
72
74
  const GLOBAL_INSTRUCTIONS_DIR = join(homedir(), '.config', 'reika');
73
75
  // Global (~/.config/reika/AGENTS.md) carries the user's personal preferences; the project
74
76
  // file carries the repo's. Both go in when both exist, global first so the project's more
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
  }