@alexwkleung/reika 0.9.0 → 0.11.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/dist/THIRD_PARTY_LICENSES.txt +1271 -0
- package/dist/chunk-AX767B3T.js +22724 -0
- package/dist/chunk-JVOYWUGK.js +279 -0
- package/dist/chunk-KI5CTLSX.js +59 -0
- package/dist/chunk-SBBXMTSX.js +4050 -0
- package/dist/cli.js +153 -53
- package/dist/devtools-FYXXYYMR.js +2 -0
- package/dist/esm-SND35LIM.js +8494 -0
- package/dist/headless-Y2V6WPLB.js +592 -0
- package/dist/node-7FRVMBZF.js +69479 -0
- package/dist/tui-KWAD5BDE.js +34366 -0
- package/package.json +16 -17
- package/dist/agent/attachments.js +0 -63
- package/dist/agent/bashread.js +0 -177
- package/dist/agent/compaction.js +0 -922
- package/dist/agent/compactionreport.js +0 -248
- package/dist/agent/continuation.js +0 -153
- package/dist/agent/decoderate.js +0 -132
- package/dist/agent/entropytrace.js +0 -169
- package/dist/agent/genreserve.js +0 -75
- package/dist/agent/groundcheck.js +0 -195
- package/dist/agent/logitrecovery.js +0 -171
- package/dist/agent/loop.js +0 -3676
- package/dist/agent/mentions.js +0 -118
- package/dist/agent/noteslotmonitor.js +0 -82
- package/dist/agent/pastedurls.js +0 -203
- package/dist/agent/planpressure.js +0 -87
- package/dist/agent/plantrack.js +0 -503
- package/dist/agent/prefillcost.js +0 -95
- package/dist/agent/prefixtrace.js +0 -90
- package/dist/agent/prompt.js +0 -349
- package/dist/agent/readfirst.js +0 -190
- package/dist/agent/readtrace.js +0 -191
- package/dist/agent/reasoningtrace.js +0 -242
- package/dist/agent/shellruns.js +0 -81
- package/dist/agent/subagentpressure.js +0 -70
- package/dist/agent/subagentreport.js +0 -117
- package/dist/agent/warm.js +0 -163
- package/dist/approval.js +0 -59
- package/dist/check/typecheck.js +0 -345
- package/dist/config.js +0 -509
- package/dist/context/bootstrap.js +0 -122
- package/dist/context/bundlesize.js +0 -74
- package/dist/context/files.js +0 -67
- package/dist/context/gitignore.js +0 -102
- package/dist/context/repomap.js +0 -304
- package/dist/debug.js +0 -197
- package/dist/headless/headless.js +0 -440
- package/dist/headless/headlessargs.js +0 -108
- package/dist/headless/headlessprompt.js +0 -132
- package/dist/laststate.js +0 -71
- package/dist/limit.js +0 -27
- package/dist/mcp/client.js +0 -630
- package/dist/mcp/config.js +0 -187
- package/dist/mcp/manager.js +0 -158
- package/dist/mcp/tools.js +0 -323
- package/dist/ocr/select.js +0 -29
- package/dist/ocr/system.js +0 -162
- package/dist/ocr/types.js +0 -1
- package/dist/ocr/vision.js +0 -139
- package/dist/provider/budget.js +0 -56
- package/dist/provider/cachehints.js +0 -30
- package/dist/provider/client.js +0 -573
- package/dist/provider/contextwindow.js +0 -78
- package/dist/provider/dispatcher.js +0 -126
- package/dist/provider/latches.js +0 -31
- package/dist/provider/modellimits.js +0 -186
- package/dist/provider/noteslot.js +0 -239
- package/dist/provider/templatekwargs.js +0 -31
- package/dist/provider/tokens.js +0 -32
- package/dist/provider/toolcall.js +0 -1088
- package/dist/provider/transport.js +0 -264
- package/dist/search/_chrome.js +0 -422
- package/dist/search/cdp.js +0 -223
- package/dist/search/searxng.js +0 -86
- package/dist/search/types.js +0 -17
- package/dist/session.js +0 -411
- package/dist/skills/skillmatch.js +0 -143
- package/dist/skills/skills.js +0 -349
- package/dist/store/payloads.js +0 -21
- package/dist/store/sessions.js +0 -180
- package/dist/store/transcript.js +0 -390
- package/dist/tools/_carriers.js +0 -119
- package/dist/tools/_danger.js +0 -1848
- package/dist/tools/_deps.js +0 -203
- package/dist/tools/_diff.js +0 -64
- package/dist/tools/_exfil.js +0 -168
- package/dist/tools/_heredoc.js +0 -419
- package/dist/tools/_hosts.js +0 -224
- package/dist/tools/_markdown.js +0 -288
- package/dist/tools/_net.js +0 -65
- package/dist/tools/_paths.js +0 -171
- package/dist/tools/_readonly.js +0 -545
- package/dist/tools/_sandbox.js +0 -953
- package/dist/tools/_spill.js +0 -216
- package/dist/tools/_spillstats.js +0 -45
- package/dist/tools/_treediff.js +0 -350
- package/dist/tools/_urls.js +0 -335
- package/dist/tools/_walk.js +0 -24
- package/dist/tools/_writetargets.js +0 -96
- package/dist/tools/ask.js +0 -194
- package/dist/tools/bash.js +0 -638
- package/dist/tools/edit.js +0 -439
- package/dist/tools/fetch.js +0 -415
- package/dist/tools/glob.js +0 -142
- package/dist/tools/grep.js +0 -263
- package/dist/tools/index.js +0 -171
- package/dist/tools/list.js +0 -96
- package/dist/tools/read.js +0 -74
- package/dist/tools/search.js +0 -134
- package/dist/tools/subagent.js +0 -23
- package/dist/tools/write.js +0 -107
- package/dist/types.js +0 -1
- package/dist/ui/App.js +0 -2874
- package/dist/ui/Approval.js +0 -148
- package/dist/ui/Confirm.js +0 -51
- package/dist/ui/DiffView.js +0 -401
- package/dist/ui/Input.js +0 -461
- package/dist/ui/ModelSelect.js +0 -32
- package/dist/ui/PlanProgress.js +0 -50
- package/dist/ui/Question.js +0 -238
- package/dist/ui/QueuedList.js +0 -17
- package/dist/ui/ResumeSelect.js +0 -61
- package/dist/ui/Scrollback.js +0 -715
- package/dist/ui/Splash.js +0 -42
- package/dist/ui/Status.js +0 -207
- package/dist/ui/Suggestions.js +0 -50
- package/dist/ui/Working.js +0 -242
- package/dist/ui/clipboard.js +0 -77
- package/dist/ui/commands.js +0 -205
- package/dist/ui/dialogspecs.js +0 -38
- package/dist/ui/focus.js +0 -56
- package/dist/ui/format.js +0 -180
- package/dist/ui/framedrops.js +0 -34
- package/dist/ui/glyphs.js +0 -48
- package/dist/ui/harnessecho.js +0 -24
- package/dist/ui/highlight.js +0 -191
- package/dist/ui/identity.js +0 -211
- package/dist/ui/layout.js +0 -224
- package/dist/ui/markdown.js +0 -357
- package/dist/ui/models.js +0 -32
- package/dist/ui/pastes.js +0 -59
- package/dist/ui/paths.js +0 -19
- package/dist/ui/pr.js +0 -78
- package/dist/ui/queue.js +0 -25
- package/dist/ui/reactbuild.js +0 -15
- package/dist/ui/reasoningfold.js +0 -63
- package/dist/ui/redact.js +0 -51
- package/dist/ui/scrub.js +0 -49
- package/dist/ui/suggest.js +0 -92
- package/dist/ui/summary.js +0 -60
- package/dist/ui/syncframe.js +0 -97
- package/dist/ui/termtext.js +0 -117
- package/dist/ui/theme.js +0 -100
- package/dist/ui/tui.js +0 -9
- package/dist/ui/warmtrigger.js +0 -37
- package/dist/version.js +0 -27
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
import { createRequire as __reikaCreateRequire } from 'node:module';
|
|
2
|
+
const require = __reikaCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
APPROVAL_FEEDBACK_INDEX,
|
|
5
|
+
APPROVAL_OPTIONS,
|
|
6
|
+
autoApproves,
|
|
7
|
+
budgetWarning,
|
|
8
|
+
buildTranscriptMeta,
|
|
9
|
+
callMcpTool,
|
|
10
|
+
countRealTurns,
|
|
11
|
+
createSession,
|
|
12
|
+
expandMentions,
|
|
13
|
+
expandPastedUrls,
|
|
14
|
+
findMcpCommand,
|
|
15
|
+
formatElapsed,
|
|
16
|
+
imageReader,
|
|
17
|
+
loadConfig,
|
|
18
|
+
matchSkill,
|
|
19
|
+
newSessionPath,
|
|
20
|
+
parseMcpArgs,
|
|
21
|
+
pastedUrlConfirmSpec,
|
|
22
|
+
planPastedUrls,
|
|
23
|
+
projectHistoryDir,
|
|
24
|
+
resolveDefaultMode,
|
|
25
|
+
saveHeader,
|
|
26
|
+
saveTranscript,
|
|
27
|
+
shouldAutoInject,
|
|
28
|
+
shouldConfirmInject,
|
|
29
|
+
skillConfirmSpec,
|
|
30
|
+
startProfiles,
|
|
31
|
+
stripTerminalControls,
|
|
32
|
+
toolLabel,
|
|
33
|
+
writeSession
|
|
34
|
+
} from "./chunk-AX767B3T.js";
|
|
35
|
+
import {
|
|
36
|
+
debugLog,
|
|
37
|
+
processSessionStem
|
|
38
|
+
} from "./chunk-JVOYWUGK.js";
|
|
39
|
+
import "./chunk-KI5CTLSX.js";
|
|
40
|
+
|
|
41
|
+
// src/headless/headless.ts
|
|
42
|
+
import { basename, join } from "node:path";
|
|
43
|
+
import { homedir } from "node:os";
|
|
44
|
+
|
|
45
|
+
// src/headless/headlessprompt.ts
|
|
46
|
+
import { openSync, createReadStream, createWriteStream } from "node:fs";
|
|
47
|
+
import { createInterface } from "node:readline";
|
|
48
|
+
var PREVIEW_LINES = 40;
|
|
49
|
+
function openTerminalPrompter(signal) {
|
|
50
|
+
let fd;
|
|
51
|
+
try {
|
|
52
|
+
fd = openSync("/dev/tty", "r+");
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
const input = createReadStream("", { fd });
|
|
57
|
+
const output = createWriteStream("", { fd, autoClose: false });
|
|
58
|
+
const prompter = createPrompter(input, output, signal);
|
|
59
|
+
return {
|
|
60
|
+
...prompter,
|
|
61
|
+
close: () => {
|
|
62
|
+
prompter.close();
|
|
63
|
+
output.destroy();
|
|
64
|
+
input.destroy();
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function createPrompter(input, output, signal) {
|
|
69
|
+
const rl = createInterface({ input, output, terminal: false });
|
|
70
|
+
let closed = false;
|
|
71
|
+
rl.once("close", () => closed = true);
|
|
72
|
+
let chain = Promise.resolve();
|
|
73
|
+
const serial = (task) => {
|
|
74
|
+
const next = chain.then(task, task);
|
|
75
|
+
chain = next.catch(() => {
|
|
76
|
+
});
|
|
77
|
+
return next;
|
|
78
|
+
};
|
|
79
|
+
const line = (prompt) => new Promise((resolve) => {
|
|
80
|
+
if (closed || signal?.aborted) return resolve(null);
|
|
81
|
+
const onClose = () => resolve(null);
|
|
82
|
+
rl.once("close", onClose);
|
|
83
|
+
rl.question(prompt, { signal }, (answer) => {
|
|
84
|
+
rl.off("close", onClose);
|
|
85
|
+
resolve(answer);
|
|
86
|
+
});
|
|
87
|
+
signal?.addEventListener("abort", () => resolve(null), { once: true });
|
|
88
|
+
});
|
|
89
|
+
const write = (text) => {
|
|
90
|
+
if (!closed) output.write(stripTerminalControls(text));
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
choose: (header, options, defaultIndex) => serial(async () => {
|
|
94
|
+
write(`
|
|
95
|
+
${header.join("\n")}
|
|
96
|
+
`);
|
|
97
|
+
options.forEach(
|
|
98
|
+
(o, i) => write(` ${i + 1}. ${o}${i === defaultIndex ? " (default)" : ""}
|
|
99
|
+
`)
|
|
100
|
+
);
|
|
101
|
+
for (; ; ) {
|
|
102
|
+
const answer = await line(`choose 1-${options.length}: `);
|
|
103
|
+
if (answer === null) return null;
|
|
104
|
+
const picked = parseChoice(answer, options.length, defaultIndex);
|
|
105
|
+
if (picked !== null) return picked;
|
|
106
|
+
write(` enter a number from 1 to ${options.length}
|
|
107
|
+
`);
|
|
108
|
+
}
|
|
109
|
+
}),
|
|
110
|
+
ask: (prompt) => serial(() => line(prompt)),
|
|
111
|
+
close: () => rl.close()
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function parseChoice(answer, count, defaultIndex) {
|
|
115
|
+
const t = answer.trim();
|
|
116
|
+
if (t === "") return defaultIndex;
|
|
117
|
+
if (!/^\d+$/.test(t)) return null;
|
|
118
|
+
const n = Number(t);
|
|
119
|
+
return n >= 1 && n <= count ? n - 1 : null;
|
|
120
|
+
}
|
|
121
|
+
function approvalHeader(req) {
|
|
122
|
+
const lines = req.preview.split("\n");
|
|
123
|
+
const shown = lines.slice(0, PREVIEW_LINES);
|
|
124
|
+
return [
|
|
125
|
+
`reika: approve ${toolLabel(req.tool)}? ${req.subject}`,
|
|
126
|
+
...(req.warnings ?? []).map((w) => ` \u25B2 ${w}`),
|
|
127
|
+
...shown.map((l) => ` \u2502 ${l}`),
|
|
128
|
+
...lines.length > shown.length ? [` \u2502 \u2026 ${lines.length - shown.length} more lines`] : []
|
|
129
|
+
];
|
|
130
|
+
}
|
|
131
|
+
async function askApproval(prompter, req) {
|
|
132
|
+
const picked = await prompter.choose(approvalHeader(req), [...APPROVAL_OPTIONS], 0);
|
|
133
|
+
if (picked === null || picked === 1) return { answer: false, always: false };
|
|
134
|
+
if (picked === 0) return { answer: true, always: false };
|
|
135
|
+
if (picked === APPROVAL_FEEDBACK_INDEX) {
|
|
136
|
+
const reason = await prompter.ask("what should it do instead? ") ?? "";
|
|
137
|
+
return { answer: reason.trim() ? { feedback: reason.trim() } : false, always: false };
|
|
138
|
+
}
|
|
139
|
+
return { answer: true, always: true };
|
|
140
|
+
}
|
|
141
|
+
async function askQuestion(prompter, req) {
|
|
142
|
+
const labels = req.options.map(
|
|
143
|
+
(o) => [o.label, o.recommended ? "(recommended)" : "", o.description ? `\u2014 ${o.description}` : ""].filter(Boolean).join(" ")
|
|
144
|
+
);
|
|
145
|
+
const own = labels.length;
|
|
146
|
+
const recommended = req.options.findIndex((o) => o.recommended);
|
|
147
|
+
const picked = await prompter.choose(
|
|
148
|
+
[`reika: the model asks: ${req.question}`],
|
|
149
|
+
[...labels, "Type my own answer"],
|
|
150
|
+
recommended >= 0 ? recommended : 0
|
|
151
|
+
);
|
|
152
|
+
if (picked === null) return null;
|
|
153
|
+
if (picked === own) {
|
|
154
|
+
const text = (await prompter.ask("your answer: "))?.trim();
|
|
155
|
+
return text ? { text } : null;
|
|
156
|
+
}
|
|
157
|
+
return { text: req.options[picked].label, index: picked };
|
|
158
|
+
}
|
|
159
|
+
async function askConfirm(prompter, spec) {
|
|
160
|
+
const picked = await prompter.choose(
|
|
161
|
+
[`reika: ${spec.title} \u2014 ${spec.subtitle}`, ...spec.details.map((d) => ` ${d}`)],
|
|
162
|
+
spec.options,
|
|
163
|
+
0
|
|
164
|
+
);
|
|
165
|
+
return picked === null ? null : picked === 1;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/headless/headless.ts
|
|
169
|
+
var EXIT_HARNESS_STOP = 2;
|
|
170
|
+
var AUTOSAVE_INTERVAL_MS = 3e3;
|
|
171
|
+
async function buildHeadlessInput(prompt, config, bundle, mode, confirm) {
|
|
172
|
+
const notices = [];
|
|
173
|
+
if (prompt.startsWith("/")) {
|
|
174
|
+
const [name, ...rest] = prompt.slice(1).split(/\s+/);
|
|
175
|
+
const skill = bundle.skills.find((s) => s.name === name);
|
|
176
|
+
if (!skill) throw new Error(`unknown skill /${name}`);
|
|
177
|
+
const extra = rest.join(" ").trim();
|
|
178
|
+
notices.push(
|
|
179
|
+
`Skill /${skill.name} applied \u2014 its body was sent as this prompt${extra ? ", with your text after it" : ""}.`
|
|
180
|
+
);
|
|
181
|
+
return {
|
|
182
|
+
modelText: extra ? `${skill.body}
|
|
183
|
+
|
|
184
|
+
${extra}` : skill.body,
|
|
185
|
+
skill: skill.name,
|
|
186
|
+
notices
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const match = matchSkill(prompt, bundle.skills);
|
|
190
|
+
const applySkill = confirm && match && config.skillAuto !== "off" && mode !== "chat" ? shouldConfirmInject(match, config.contextWindow) && await confirm(skillConfirmSpec(match)) === true : void 0;
|
|
191
|
+
const urlPlan = planPastedUrls(prompt);
|
|
192
|
+
const incidental = confirm && config.pasteFetch !== "off" && urlPlan.urls.length > 0 && !urlPlan.request ? await confirm(pastedUrlConfirmSpec(urlPlan.urls)) === true : void 0;
|
|
193
|
+
const expansion = await expandMentions(prompt, bundle.cwd, { ocr: imageReader(config) });
|
|
194
|
+
notices.push(...expansion.notices);
|
|
195
|
+
const urls = await expandPastedUrls(prompt, { mode: config.pasteFetch, incidental });
|
|
196
|
+
notices.push(...urls.notices.map((n) => n.text));
|
|
197
|
+
let modelText = expansion.augmented;
|
|
198
|
+
if (urls.blocks.length > 0) modelText = `${urls.blocks.join("\n\n")}
|
|
199
|
+
|
|
200
|
+
${modelText}`;
|
|
201
|
+
const auto = applySkill ?? (match && config.skillAuto === "apply" && (mode === "agent" || mode === "vibe") && shouldAutoInject(match, config.contextWindow));
|
|
202
|
+
if (match && auto) {
|
|
203
|
+
notices.push(
|
|
204
|
+
`Skill /${match.skill.name} applied \u2014 its body was prepended to this prompt (matched: ${match.matched.join(", ")}).`
|
|
205
|
+
);
|
|
206
|
+
return { modelText: `${match.skill.body}
|
|
207
|
+
|
|
208
|
+
${modelText}`, skill: match.skill.name, notices };
|
|
209
|
+
}
|
|
210
|
+
return { modelText, notices };
|
|
211
|
+
}
|
|
212
|
+
function headlessProfile(config, mode, named) {
|
|
213
|
+
const fallback = startProfiles(config, mode, {}).profile;
|
|
214
|
+
if (named === void 0) return { profile: fallback };
|
|
215
|
+
const key = named.toLowerCase();
|
|
216
|
+
if (config.profiles[key]) return { profile: key };
|
|
217
|
+
const known = Object.keys(config.profiles).join(", ");
|
|
218
|
+
return {
|
|
219
|
+
profile: fallback,
|
|
220
|
+
notice: `no profile named "${named}" (defined: ${known}); using "${fallback}"`
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function formatTurnFailure(profile, baseURL, message) {
|
|
224
|
+
return `reika: turn failed (profile "${profile}" at ${baseURL}): ${message}`;
|
|
225
|
+
}
|
|
226
|
+
function formatRunSummary(run) {
|
|
227
|
+
const { model, totals, elapsedMs, sessionPath } = run;
|
|
228
|
+
const n = (t) => t.toLocaleString("en-US");
|
|
229
|
+
const approx = totals.estimated ? "~" : "";
|
|
230
|
+
const cached = totals.cachedTokens ? ` (${n(totals.cachedTokens)} cached)` : "";
|
|
231
|
+
const counted = totals.promptTokens > 0 || totals.completionTokens > 0;
|
|
232
|
+
const parts = [
|
|
233
|
+
model,
|
|
234
|
+
...counted ? [
|
|
235
|
+
`${approx}${n(totals.promptTokens)} tokens in${cached}, ${approx}${n(totals.completionTokens)} out`
|
|
236
|
+
] : [],
|
|
237
|
+
formatElapsed(Math.floor(elapsedMs / 1e3)),
|
|
238
|
+
...sessionPath ? [`session ${sessionPath}`] : []
|
|
239
|
+
];
|
|
240
|
+
return parts.join(" \xB7 ");
|
|
241
|
+
}
|
|
242
|
+
function terminalSafeWriter(stream) {
|
|
243
|
+
return (text) => void stream.write(stream.isTTY ? stripTerminalControls(text) : text);
|
|
244
|
+
}
|
|
245
|
+
async function runHeadless(args, io) {
|
|
246
|
+
const prompt = (args.prompt ?? await io.readStdin()).trim();
|
|
247
|
+
if (!prompt) {
|
|
248
|
+
io.stderr("reika: no prompt given\n");
|
|
249
|
+
return 1;
|
|
250
|
+
}
|
|
251
|
+
const controller = new AbortController();
|
|
252
|
+
let prompter = null;
|
|
253
|
+
if (args.interactive) {
|
|
254
|
+
prompter = openTerminalPrompter(controller.signal);
|
|
255
|
+
if (!prompter) {
|
|
256
|
+
io.stderr("reika: --interactive needs a terminal to ask on, and this run has none\n");
|
|
257
|
+
return 1;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
return await runHeadlessTurn(args, io, prompt, controller, prompter);
|
|
262
|
+
} finally {
|
|
263
|
+
prompter?.close();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
async function runHeadlessTurn(args, io, prompt, controller, prompter) {
|
|
267
|
+
const loaded = { ...loadConfig(), unattended: !prompter };
|
|
268
|
+
let policy = loaded.autoApprove;
|
|
269
|
+
const mode = args.mode ?? resolveDefaultMode();
|
|
270
|
+
const chosen = headlessProfile(loaded, mode, args.profile);
|
|
271
|
+
if (chosen.notice) io.stderr(`reika: ${chosen.notice}
|
|
272
|
+
`);
|
|
273
|
+
const profile = chosen.profile;
|
|
274
|
+
const stream = args.stream ? createStreamPrinter(io, args.json) : null;
|
|
275
|
+
let transcript = () => [];
|
|
276
|
+
const tracked = createHeadlessStatus(() => transcript());
|
|
277
|
+
let autosave = null;
|
|
278
|
+
const session = await createSession({
|
|
279
|
+
cwd: process.cwd(),
|
|
280
|
+
config: loaded,
|
|
281
|
+
profile,
|
|
282
|
+
canAsk: !!prompter,
|
|
283
|
+
requestQuestion: prompter ? (req) => askQuestion(prompter, req) : void 0,
|
|
284
|
+
requestApproval: loaded.autoApprove === "bypass" ? void 0 : async (req) => {
|
|
285
|
+
if (autoApproves(policy, req)) return true;
|
|
286
|
+
if (prompter) {
|
|
287
|
+
const { answer, always } = await askApproval(prompter, req);
|
|
288
|
+
if (always && policy === "off") policy = "safe";
|
|
289
|
+
return answer;
|
|
290
|
+
}
|
|
291
|
+
io.stderr(
|
|
292
|
+
`reika: declined ${toolLabel(req.tool)} (no prompt to ask at): ${firstLine(req.preview)}
|
|
293
|
+
`
|
|
294
|
+
);
|
|
295
|
+
return false;
|
|
296
|
+
},
|
|
297
|
+
events: {
|
|
298
|
+
...stream?.events,
|
|
299
|
+
...tracked.events,
|
|
300
|
+
// The persistent receipts App puts in the scrollback — a fold, a declined URL, the
|
|
301
|
+
// typecheck gate bouncing the model — are the ones a human watching a pipe should see.
|
|
302
|
+
onMessage: (msg) => {
|
|
303
|
+
if (msg.role === "system") io.stderr(`reika: ${msg.content}
|
|
304
|
+
`);
|
|
305
|
+
stream?.onMessage(msg);
|
|
306
|
+
autosave?.onMessage();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
transcript = () => session.transcript;
|
|
311
|
+
try {
|
|
312
|
+
const { config, bundle } = session;
|
|
313
|
+
const meta = (midTurn) => buildTranscriptMeta({
|
|
314
|
+
msgs: session.transcript,
|
|
315
|
+
model: config.model,
|
|
316
|
+
baseURL: config.baseURL,
|
|
317
|
+
cwd: bundle.cwd,
|
|
318
|
+
mode,
|
|
319
|
+
status: tracked.status(session),
|
|
320
|
+
midTurn
|
|
321
|
+
});
|
|
322
|
+
if (config.autosave) {
|
|
323
|
+
autosave = createHeadlessAutosave(
|
|
324
|
+
newSessionPath(projectHistoryDir(bundle.cwd), /* @__PURE__ */ new Date(), processSessionStem()),
|
|
325
|
+
() => session.transcript,
|
|
326
|
+
mode === "chat" ? "chat" : "agent",
|
|
327
|
+
meta,
|
|
328
|
+
(message) => io.stderr(`reika: auto-save failed: ${message}
|
|
329
|
+
`)
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
if (session.limitsNotice) io.stderr(`reika: ${session.limitsNotice}
|
|
333
|
+
`);
|
|
334
|
+
if (session.windowNotice) io.stderr(`reika: ${session.windowNotice}
|
|
335
|
+
`);
|
|
336
|
+
const budgetProblem = budgetWarning(bundle, config);
|
|
337
|
+
if (budgetProblem) io.stderr(`reika: ${budgetProblem}
|
|
338
|
+
`);
|
|
339
|
+
if (session.offline)
|
|
340
|
+
io.stderr("reika: no network \u2014 search and fetch_url are off for this run\n");
|
|
341
|
+
if (session.searchNotice) io.stderr(`reika: ${session.searchNotice}
|
|
342
|
+
`);
|
|
343
|
+
for (const notice of session.mcpNotices) io.stderr(`reika: ${notice}
|
|
344
|
+
`);
|
|
345
|
+
for (const problem of config.modeModelErrors ?? []) io.stderr(`reika: ${problem}
|
|
346
|
+
`);
|
|
347
|
+
if (config.projectEnvNotice) io.stderr(`reika: ${config.projectEnvNotice}
|
|
348
|
+
`);
|
|
349
|
+
const mcpCall = prompt.includes("\n") ? void 0 : findMcpCommand(prompt, session.mcp.commands);
|
|
350
|
+
if (mcpCall) {
|
|
351
|
+
const parsed = parseMcpArgs(mcpCall.command, mcpCall.rest);
|
|
352
|
+
if ("error" in parsed) {
|
|
353
|
+
io.stderr(`reika: ${parsed.error}
|
|
354
|
+
`);
|
|
355
|
+
return 1;
|
|
356
|
+
}
|
|
357
|
+
const { server, tool } = mcpCall.command;
|
|
358
|
+
const { result, failed: failed2 } = await callMcpTool(
|
|
359
|
+
session.mcp.call,
|
|
360
|
+
`${server}:${tool}`,
|
|
361
|
+
server,
|
|
362
|
+
tool,
|
|
363
|
+
parsed.args
|
|
364
|
+
);
|
|
365
|
+
io.stdout(`${result.payload ? `${result.payload}
|
|
366
|
+
` : ""}`);
|
|
367
|
+
io.stderr(`reika: ${result.summary}
|
|
368
|
+
`);
|
|
369
|
+
return failed2 ? 1 : 0;
|
|
370
|
+
}
|
|
371
|
+
const input = await buildHeadlessInput(
|
|
372
|
+
prompt,
|
|
373
|
+
config,
|
|
374
|
+
bundle,
|
|
375
|
+
mode,
|
|
376
|
+
prompter ? (spec) => askConfirm(prompter, spec) : void 0
|
|
377
|
+
);
|
|
378
|
+
for (const n of input.notices) io.stderr(`reika: ${n}
|
|
379
|
+
`);
|
|
380
|
+
const onSigint = () => controller.abort();
|
|
381
|
+
process.once("SIGINT", onSigint);
|
|
382
|
+
let failed = null;
|
|
383
|
+
const turnStartedAt = Date.now();
|
|
384
|
+
try {
|
|
385
|
+
await session.submit(input.modelText, {
|
|
386
|
+
mode,
|
|
387
|
+
display: prompt,
|
|
388
|
+
skill: input.skill,
|
|
389
|
+
signal: controller.signal
|
|
390
|
+
});
|
|
391
|
+
} catch (e) {
|
|
392
|
+
failed = e;
|
|
393
|
+
} finally {
|
|
394
|
+
process.off("SIGINT", onSigint);
|
|
395
|
+
stream?.finish();
|
|
396
|
+
}
|
|
397
|
+
const appended = session.transcript;
|
|
398
|
+
await autosave?.finish();
|
|
399
|
+
if (args.save) {
|
|
400
|
+
try {
|
|
401
|
+
const { jsonlPath } = await saveTranscript(
|
|
402
|
+
join(homedir(), ".config", "reika", "history"),
|
|
403
|
+
appended,
|
|
404
|
+
saveHeader(meta(false), appended)
|
|
405
|
+
);
|
|
406
|
+
io.stderr(`reika: saved ${appended.length} messages \u2192 ${jsonlPath}
|
|
407
|
+
`);
|
|
408
|
+
} catch (e) {
|
|
409
|
+
io.stderr(`reika: save failed: ${e.message}
|
|
410
|
+
`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
const summary = formatRunSummary({
|
|
414
|
+
model: config.model,
|
|
415
|
+
totals: session.totals,
|
|
416
|
+
elapsedMs: Date.now() - turnStartedAt,
|
|
417
|
+
sessionPath: autosave?.savedPath()
|
|
418
|
+
});
|
|
419
|
+
io.stderr(`reika: ${summary}
|
|
420
|
+
`);
|
|
421
|
+
if (failed) {
|
|
422
|
+
debugLog(`headless: turn failed: ${failed.message}`);
|
|
423
|
+
io.stderr(`${formatTurnFailure(profile, config.baseURL, failed.message)}
|
|
424
|
+
`);
|
|
425
|
+
return controller.signal.aborted ? 130 : 1;
|
|
426
|
+
}
|
|
427
|
+
if (args.json && !args.stream) {
|
|
428
|
+
io.stdout(`${JSON.stringify(appended)}
|
|
429
|
+
`);
|
|
430
|
+
}
|
|
431
|
+
if (controller.signal.aborted) {
|
|
432
|
+
io.stderr("reika: interrupted\n");
|
|
433
|
+
return 130;
|
|
434
|
+
}
|
|
435
|
+
const closing = closingAssistantMessage(appended);
|
|
436
|
+
if (closing?.role === "assistant" && closing.harnessStop) {
|
|
437
|
+
io.stderr(`reika: stopped (${closing.harnessStop}): ${closing.content}
|
|
438
|
+
`);
|
|
439
|
+
return EXIT_HARNESS_STOP;
|
|
440
|
+
}
|
|
441
|
+
const reply = finalReply(appended);
|
|
442
|
+
if (!reply) io.stderr("reika: the turn ended without a reply\n");
|
|
443
|
+
if (!args.json && !args.stream && reply) io.stdout(`${reply}
|
|
444
|
+
`);
|
|
445
|
+
return reply ? 0 : 1;
|
|
446
|
+
} finally {
|
|
447
|
+
await session.mcp.close();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function createHeadlessStatus(messages) {
|
|
451
|
+
let lastUsage = null;
|
|
452
|
+
let estimatedContext = null;
|
|
453
|
+
const shrinkEvents = [];
|
|
454
|
+
return {
|
|
455
|
+
events: {
|
|
456
|
+
onUsage: (u) => {
|
|
457
|
+
if (!u.estimated) lastUsage = u;
|
|
458
|
+
},
|
|
459
|
+
onContextEstimate: (t) => estimatedContext = t,
|
|
460
|
+
onShrink: (event) => {
|
|
461
|
+
lastUsage = null;
|
|
462
|
+
const turn = messages().filter((m) => m.role === "assistant").length + 1;
|
|
463
|
+
shrinkEvents.push({ turn, ...event });
|
|
464
|
+
}
|
|
465
|
+
},
|
|
466
|
+
status: (session) => ({
|
|
467
|
+
totals: session.totals,
|
|
468
|
+
lastUsage,
|
|
469
|
+
estimatedContext,
|
|
470
|
+
shrink: session.shrink,
|
|
471
|
+
shrinkEvents: [...shrinkEvents],
|
|
472
|
+
contextWindow: session.config.contextWindow,
|
|
473
|
+
minGenTokens: session.config.minGenTokens
|
|
474
|
+
})
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function createHeadlessAutosave(path, messages, side, meta, onError, intervalMs = AUTOSAVE_INTERVAL_MS) {
|
|
478
|
+
let chain = Promise.resolve();
|
|
479
|
+
let timer = null;
|
|
480
|
+
let written = false;
|
|
481
|
+
let failed = false;
|
|
482
|
+
const save = (midTurn) => {
|
|
483
|
+
if (timer !== null) {
|
|
484
|
+
clearTimeout(timer);
|
|
485
|
+
timer = null;
|
|
486
|
+
}
|
|
487
|
+
const msgs = messages();
|
|
488
|
+
if (countRealTurns(msgs) === 0) return chain;
|
|
489
|
+
if (!written) debugLog(`[reika:debug] session file=${basename(path)}`);
|
|
490
|
+
written = true;
|
|
491
|
+
const sides = { agent: [], chat: [], [side]: [...msgs] };
|
|
492
|
+
const header = meta(midTurn);
|
|
493
|
+
chain = chain.then(() => writeSession(path, sides, header)).catch((e) => {
|
|
494
|
+
if (failed) return;
|
|
495
|
+
failed = true;
|
|
496
|
+
onError(e.message);
|
|
497
|
+
});
|
|
498
|
+
return chain;
|
|
499
|
+
};
|
|
500
|
+
return {
|
|
501
|
+
onMessage: () => {
|
|
502
|
+
if (!written) {
|
|
503
|
+
void save(true);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (timer !== null) return;
|
|
507
|
+
timer = setTimeout(() => void save(true), intervalMs);
|
|
508
|
+
timer.unref?.();
|
|
509
|
+
},
|
|
510
|
+
finish: () => save(false),
|
|
511
|
+
savedPath: () => written && !failed ? path : null
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function createStreamPrinter(io, json) {
|
|
515
|
+
if (json) {
|
|
516
|
+
return {
|
|
517
|
+
events: {},
|
|
518
|
+
onMessage: (msg) => io.stdout(`${JSON.stringify(msg)}
|
|
519
|
+
`),
|
|
520
|
+
finish: () => {
|
|
521
|
+
}
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
let wrote = false;
|
|
525
|
+
let lineOpen = false;
|
|
526
|
+
let roundStarted = false;
|
|
527
|
+
let subagent = false;
|
|
528
|
+
let note = false;
|
|
529
|
+
const endLine = () => {
|
|
530
|
+
if (lineOpen) io.stdout("\n");
|
|
531
|
+
lineOpen = false;
|
|
532
|
+
};
|
|
533
|
+
const endRound = () => {
|
|
534
|
+
endLine();
|
|
535
|
+
roundStarted = false;
|
|
536
|
+
};
|
|
537
|
+
return {
|
|
538
|
+
events: {
|
|
539
|
+
onPhase: endRound,
|
|
540
|
+
onSubagent: (live) => subagent = live,
|
|
541
|
+
onCompactionNote: (live) => note = live,
|
|
542
|
+
onContentDelta: (delta) => {
|
|
543
|
+
if (subagent || note) return;
|
|
544
|
+
if (!roundStarted) {
|
|
545
|
+
delta = delta.trimStart();
|
|
546
|
+
if (!delta) return;
|
|
547
|
+
roundStarted = true;
|
|
548
|
+
if (wrote) io.stdout("\n");
|
|
549
|
+
}
|
|
550
|
+
io.stdout(delta);
|
|
551
|
+
wrote = true;
|
|
552
|
+
lineOpen = !delta.endsWith("\n");
|
|
553
|
+
}
|
|
554
|
+
},
|
|
555
|
+
onMessage: (msg) => {
|
|
556
|
+
if (msg.role === "assistant") endRound();
|
|
557
|
+
if (msg.role === "tool" && !subagent) {
|
|
558
|
+
io.stderr(`reika: \u21B3 ${firstLine(msg.summary)}
|
|
559
|
+
`);
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
finish: endLine
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function closingAssistantMessage(messages) {
|
|
566
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
567
|
+
const m = messages[i];
|
|
568
|
+
if (m.role === "assistant" && !m.nested && !m.compactionNote) return m;
|
|
569
|
+
}
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
function finalReply(messages) {
|
|
573
|
+
const closing = closingAssistantMessage(messages);
|
|
574
|
+
if (closing?.role !== "assistant" || closing.toolCalls?.length) return null;
|
|
575
|
+
return closing.content?.trim() || null;
|
|
576
|
+
}
|
|
577
|
+
function firstLine(text) {
|
|
578
|
+
const line = text.split("\n", 1)[0] ?? "";
|
|
579
|
+
return line.length > 80 ? `${line.slice(0, 77)}\u2026` : line;
|
|
580
|
+
}
|
|
581
|
+
export {
|
|
582
|
+
buildHeadlessInput,
|
|
583
|
+
createHeadlessAutosave,
|
|
584
|
+
createHeadlessStatus,
|
|
585
|
+
createStreamPrinter,
|
|
586
|
+
finalReply,
|
|
587
|
+
formatRunSummary,
|
|
588
|
+
formatTurnFailure,
|
|
589
|
+
headlessProfile,
|
|
590
|
+
runHeadless,
|
|
591
|
+
terminalSafeWriter
|
|
592
|
+
};
|