@alexwkleung/reika 0.7.0 → 0.9.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 +15 -0
- package/README.zh-CN.md +15 -0
- package/dist/agent/compaction.js +82 -27
- package/dist/agent/loop.js +84 -20
- package/dist/agent/prefillcost.js +16 -0
- package/dist/agent/prompt.js +5 -2
- package/dist/cli.js +5 -11
- package/dist/context/bootstrap.js +1 -1
- package/dist/debug.js +15 -0
- package/dist/{headless.js → headless/headless.js} +185 -48
- package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
- package/dist/headless/headlessprompt.js +132 -0
- package/dist/mcp/client.js +97 -5
- package/dist/mcp/manager.js +15 -2
- package/dist/provider/client.js +13 -0
- package/dist/session.js +12 -1
- package/dist/{skills.js → skills/skills.js} +93 -13
- package/dist/store/sessions.js +40 -3
- package/dist/store/transcript.js +38 -1
- package/dist/tools/_carriers.js +119 -0
- package/dist/tools/_danger.js +305 -82
- package/dist/tools/_readonly.js +13 -12
- package/dist/tools/_sandbox.js +13 -5
- package/dist/ui/App.js +288 -83
- package/dist/ui/Approval.js +80 -33
- package/dist/ui/Confirm.js +1 -27
- package/dist/ui/DiffView.js +24 -14
- package/dist/ui/Question.js +152 -19
- package/dist/ui/ResumeSelect.js +13 -6
- package/dist/ui/Scrollback.js +44 -8
- package/dist/ui/Status.js +35 -10
- package/dist/ui/commands.js +1 -1
- package/dist/ui/dialogspecs.js +38 -0
- package/dist/ui/layout.js +149 -6
- package/dist/ui/markdown.js +6 -5
- package/dist/ui/pr.js +15 -9
- package/dist/ui/reactbuild.js +15 -0
- package/dist/ui/summary.js +3 -2
- package/dist/ui/termtext.js +5 -1
- package/dist/ui/theme.js +5 -0
- package/dist/ui/tui.js +9 -0
- package/package.json +1 -1
- /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
|
@@ -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 '
|
|
4
|
-
import { startProfiles } from '
|
|
5
|
-
import { saveTranscript,
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
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
|
-
|
|
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
|
|
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
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
//
|
|
87
|
-
const loaded = { ...loadConfig(), unattended:
|
|
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:
|
|
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(
|
|
106
|
-
return
|
|
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
|
|
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,87 @@ 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 => {
|
|
296
|
+
if (!u.estimated)
|
|
297
|
+
lastUsage = u;
|
|
298
|
+
},
|
|
299
|
+
onContextEstimate: t => (estimatedContext = t),
|
|
300
|
+
onShrink: event => {
|
|
301
|
+
lastUsage = null;
|
|
302
|
+
const turn = messages().filter(m => m.role === 'assistant').length + 1;
|
|
303
|
+
shrinkEvents.push({ turn, ...event });
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
status: session => ({
|
|
307
|
+
totals: session.totals,
|
|
308
|
+
lastUsage,
|
|
309
|
+
estimatedContext,
|
|
310
|
+
shrink: session.shrink,
|
|
311
|
+
shrinkEvents: [...shrinkEvents],
|
|
312
|
+
contextWindow: session.config.contextWindow,
|
|
313
|
+
minGenTokens: session.config.minGenTokens,
|
|
314
|
+
}),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
// Auto-save for a headless run (#871): the TUI's file, in the TUI's place, so /resume lists a
|
|
318
|
+
// `reika -p` run beside the interactive ones. Written on the first real prompt, at most once per
|
|
319
|
+
// interval while the turn runs (a long unattended turn is exactly the one a crash should not take
|
|
320
|
+
// whole), and once more at the end. Writes are chained so an older snapshot never lands last.
|
|
321
|
+
// A chat run is the chat side of the file, as the TUI writes it: chat history is isolated from
|
|
322
|
+
// the other modes, and a /resume of it must not land in agent history.
|
|
323
|
+
export function createHeadlessAutosave(path, messages, side, meta, onError, intervalMs = AUTOSAVE_INTERVAL_MS) {
|
|
324
|
+
let chain = Promise.resolve();
|
|
325
|
+
let timer = null;
|
|
326
|
+
let written = false;
|
|
327
|
+
let failed = false;
|
|
328
|
+
const save = (midTurn) => {
|
|
329
|
+
if (timer !== null) {
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
timer = null;
|
|
332
|
+
}
|
|
333
|
+
const msgs = messages();
|
|
334
|
+
// An MCP command or a turn that never reached its user echo is not a session worth listing.
|
|
335
|
+
if (countRealTurns(msgs) === 0)
|
|
336
|
+
return chain;
|
|
337
|
+
if (!written)
|
|
338
|
+
debugLog(`[reika:debug] session file=${basename(path)}`);
|
|
339
|
+
written = true;
|
|
340
|
+
const sides = { agent: [], chat: [], [side]: [...msgs] };
|
|
341
|
+
const header = meta(midTurn);
|
|
342
|
+
chain = chain
|
|
343
|
+
.then(() => writeSession(path, sides, header))
|
|
344
|
+
.catch((e) => {
|
|
345
|
+
// Said once: a full disk fails every save the same way.
|
|
346
|
+
if (failed)
|
|
347
|
+
return;
|
|
348
|
+
failed = true;
|
|
349
|
+
onError(e.message);
|
|
350
|
+
});
|
|
351
|
+
return chain;
|
|
352
|
+
};
|
|
353
|
+
return {
|
|
354
|
+
onMessage: () => {
|
|
355
|
+
if (!written) {
|
|
356
|
+
void save(true);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (timer !== null)
|
|
360
|
+
return;
|
|
361
|
+
timer = setTimeout(() => void save(true), intervalMs);
|
|
362
|
+
timer.unref?.();
|
|
363
|
+
},
|
|
364
|
+
finish: () => save(false),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
230
367
|
// --stream (#566). Text: the content channel goes to stdout as it arrives and each tool call's
|
|
231
368
|
// summary to stderr, so a pipe reads like the TUI minus the reasoning. What streams can't be taken
|
|
232
369
|
// 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.
|
|
20
|
-
|
|
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
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { openSync, createReadStream, createWriteStream } from 'node:fs';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { APPROVAL_FEEDBACK_INDEX, APPROVAL_OPTIONS } from '../ui/dialogspecs.js';
|
|
4
|
+
import { toolLabel } from '../ui/format.js';
|
|
5
|
+
// Headless dialogs (#872): `reika -p -i` asks what the TUI would have opened a dialog for, as a
|
|
6
|
+
// numbered menu on the controlling terminal. The terminal, not stdin/stderr: stdin may be the piped
|
|
7
|
+
// prompt and stderr a log file, and a question written into a log waits for an answer nobody sees.
|
|
8
|
+
// Rows of an approval preview printed before the menu. The TUI fits the preview to the pane; a
|
|
9
|
+
// line prompt has no pane, and a 400-line diff scrolls the menu off the screen.
|
|
10
|
+
export const PREVIEW_LINES = 40;
|
|
11
|
+
// The controlling terminal, or null when there is none (cron, CI, `setsid`) — the caller then
|
|
12
|
+
// refuses `--interactive` rather than hanging on a read that never completes.
|
|
13
|
+
export function openTerminalPrompter(signal) {
|
|
14
|
+
let fd;
|
|
15
|
+
try {
|
|
16
|
+
fd = openSync('/dev/tty', 'r+');
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
// The read stream owns the fd: destroying it closes the fd, so the write side must not.
|
|
22
|
+
const input = createReadStream('', { fd });
|
|
23
|
+
const output = createWriteStream('', { fd, autoClose: false });
|
|
24
|
+
const prompter = createPrompter(input, output, signal);
|
|
25
|
+
return {
|
|
26
|
+
...prompter,
|
|
27
|
+
close: () => {
|
|
28
|
+
prompter.close();
|
|
29
|
+
output.destroy();
|
|
30
|
+
input.destroy();
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function createPrompter(input, output, signal) {
|
|
35
|
+
const rl = createInterface({ input, output, terminal: false });
|
|
36
|
+
let closed = false;
|
|
37
|
+
rl.once('close', () => (closed = true));
|
|
38
|
+
// Answers are read one at a time: two approvals in one round must not share a typed line.
|
|
39
|
+
let chain = Promise.resolve();
|
|
40
|
+
const serial = (task) => {
|
|
41
|
+
const next = chain.then(task, task);
|
|
42
|
+
chain = next.catch(() => { });
|
|
43
|
+
return next;
|
|
44
|
+
};
|
|
45
|
+
const line = (prompt) => new Promise(resolve => {
|
|
46
|
+
if (closed || signal?.aborted)
|
|
47
|
+
return resolve(null);
|
|
48
|
+
const onClose = () => resolve(null);
|
|
49
|
+
rl.once('close', onClose);
|
|
50
|
+
rl.question(prompt, { signal }, answer => {
|
|
51
|
+
rl.off('close', onClose);
|
|
52
|
+
resolve(answer);
|
|
53
|
+
});
|
|
54
|
+
signal?.addEventListener('abort', () => resolve(null), { once: true });
|
|
55
|
+
});
|
|
56
|
+
const write = (text) => {
|
|
57
|
+
if (!closed)
|
|
58
|
+
output.write(text);
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
choose: (header, options, defaultIndex) => serial(async () => {
|
|
62
|
+
write(`\n${header.join('\n')}\n`);
|
|
63
|
+
options.forEach((o, i) => write(` ${i + 1}. ${o}${i === defaultIndex ? ' (default)' : ''}\n`));
|
|
64
|
+
for (;;) {
|
|
65
|
+
const answer = await line(`choose 1-${options.length}: `);
|
|
66
|
+
if (answer === null)
|
|
67
|
+
return null;
|
|
68
|
+
const picked = parseChoice(answer, options.length, defaultIndex);
|
|
69
|
+
if (picked !== null)
|
|
70
|
+
return picked;
|
|
71
|
+
write(` enter a number from 1 to ${options.length}\n`);
|
|
72
|
+
}
|
|
73
|
+
}),
|
|
74
|
+
ask: prompt => serial(() => line(prompt)),
|
|
75
|
+
close: () => rl.close(),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export function parseChoice(answer, count, defaultIndex) {
|
|
79
|
+
const t = answer.trim();
|
|
80
|
+
if (t === '')
|
|
81
|
+
return defaultIndex;
|
|
82
|
+
if (!/^\d+$/.test(t))
|
|
83
|
+
return null;
|
|
84
|
+
const n = Number(t);
|
|
85
|
+
return n >= 1 && n <= count ? n - 1 : null;
|
|
86
|
+
}
|
|
87
|
+
export function approvalHeader(req) {
|
|
88
|
+
const lines = req.preview.split('\n');
|
|
89
|
+
const shown = lines.slice(0, PREVIEW_LINES);
|
|
90
|
+
return [
|
|
91
|
+
`reika: approve ${toolLabel(req.tool)}? ${req.subject}`,
|
|
92
|
+
...(req.warnings ?? []).map(w => ` ▲ ${w}`),
|
|
93
|
+
...shown.map(l => ` │ ${l}`),
|
|
94
|
+
...(lines.length > shown.length ? [` │ … ${lines.length - shown.length} more lines`] : []),
|
|
95
|
+
];
|
|
96
|
+
}
|
|
97
|
+
// `always` is set when the user picks "Always (this session)": the caller switches its policy to
|
|
98
|
+
// 'safe', which — as in the TUI — still asks about anything the danger scan flagged.
|
|
99
|
+
export async function askApproval(prompter, req) {
|
|
100
|
+
const picked = await prompter.choose(approvalHeader(req), [...APPROVAL_OPTIONS], 0);
|
|
101
|
+
if (picked === null || picked === 1)
|
|
102
|
+
return { answer: false, always: false };
|
|
103
|
+
if (picked === 0)
|
|
104
|
+
return { answer: true, always: false };
|
|
105
|
+
if (picked === APPROVAL_FEEDBACK_INDEX) {
|
|
106
|
+
const reason = (await prompter.ask('what should it do instead? ')) ?? '';
|
|
107
|
+
return { answer: reason.trim() ? { feedback: reason.trim() } : false, always: false };
|
|
108
|
+
}
|
|
109
|
+
return { answer: true, always: true };
|
|
110
|
+
}
|
|
111
|
+
// The last row is the TUI's "type your own answer" field; a typed answer carries no index.
|
|
112
|
+
export async function askQuestion(prompter, req) {
|
|
113
|
+
const labels = req.options.map(o => [o.label, o.recommended ? '(recommended)' : '', o.description ? `— ${o.description}` : '']
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.join(' '));
|
|
116
|
+
const own = labels.length;
|
|
117
|
+
const recommended = req.options.findIndex(o => o.recommended);
|
|
118
|
+
const picked = await prompter.choose([`reika: the model asks: ${req.question}`], [...labels, 'Type my own answer'], recommended >= 0 ? recommended : 0);
|
|
119
|
+
if (picked === null)
|
|
120
|
+
return null;
|
|
121
|
+
if (picked === own) {
|
|
122
|
+
const text = (await prompter.ask('your answer: '))?.trim();
|
|
123
|
+
return text ? { text } : null;
|
|
124
|
+
}
|
|
125
|
+
return { text: req.options[picked].label, index: picked };
|
|
126
|
+
}
|
|
127
|
+
// The two-row confirms (skill route, pasted link). Row 0 is "send as typed" and the default, as in
|
|
128
|
+
// the TUI: nothing has happened yet, so the least action is the safe one. True accepts row 1.
|
|
129
|
+
export async function askConfirm(prompter, spec) {
|
|
130
|
+
const picked = await prompter.choose([`reika: ${spec.title} — ${spec.subtitle}`, ...spec.details.map(d => ` ${d}`)], spec.options, 0);
|
|
131
|
+
return picked === null ? null : picked === 1;
|
|
132
|
+
}
|