@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.
- package/README.md +15 -0
- package/README.zh-CN.md +15 -0
- package/dist/agent/bashread.js +177 -0
- package/dist/agent/compaction.js +5 -0
- package/dist/agent/compactionreport.js +184 -0
- package/dist/agent/loop.js +172 -45
- package/dist/agent/noteslotmonitor.js +82 -0
- package/dist/agent/prefillcost.js +16 -0
- package/dist/agent/prompt.js +5 -2
- package/dist/agent/readtrace.js +18 -8
- package/dist/check/typecheck.js +29 -0
- package/dist/cli.js +2 -2
- package/dist/config.js +30 -17
- package/dist/context/bootstrap.js +4 -2
- package/dist/debug.js +15 -0
- package/dist/{headless.js → headless/headless.js} +182 -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 +28 -0
- package/dist/provider/latches.js +3 -0
- package/dist/provider/noteslot.js +239 -0
- package/dist/provider/templatekwargs.js +31 -0
- package/dist/provider/toolcall.js +22 -1
- package/dist/provider/transport.js +12 -9
- package/dist/session.js +21 -1
- package/dist/{skills.js → skills/skills.js} +93 -13
- package/dist/store/sessions.js +39 -2
- package/dist/store/transcript.js +35 -0
- package/dist/tools/_carriers.js +119 -0
- package/dist/tools/_danger.js +539 -90
- package/dist/tools/_readonly.js +13 -12
- package/dist/ui/App.js +183 -70
- package/dist/ui/Approval.js +80 -33
- package/dist/ui/Confirm.js +1 -27
- package/dist/ui/DiffView.js +23 -12
- package/dist/ui/Question.js +152 -19
- package/dist/ui/ResumeSelect.js +3 -2
- package/dist/ui/Status.js +19 -7
- package/dist/ui/commands.js +47 -1
- package/dist/ui/dialogspecs.js +38 -0
- package/dist/ui/layout.js +118 -0
- package/package.json +1 -1
- /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
|
@@ -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
|
+
}
|
package/dist/mcp/client.js
CHANGED
|
@@ -68,6 +68,14 @@ const MAX_STDOUT_LINE_CHARS = 8 * 1024 * 1024;
|
|
|
68
68
|
// immediate SIGTERM. The process-exit hook below stays an immediate kill: there is no time to wait.
|
|
69
69
|
const CLOSE_GRACE_MS = 2000;
|
|
70
70
|
const TERM_GRACE_MS = 1000;
|
|
71
|
+
// The stdio binding's SHOULD for a server that exits unexpectedly: restart it (#592). Lazily, on
|
|
72
|
+
// the next call — a server nobody calls again costs nothing — and bounded, so one that crashes on
|
|
73
|
+
// start or on every call is given up on rather than respawned forever. Per session, never reset:
|
|
74
|
+
// a server that keeps dying after a quiet spell is still one that keeps dying.
|
|
75
|
+
const MAX_RESTARTS = 3;
|
|
76
|
+
// Waited before each respawn, by its index. The first is immediate (one crash is the common case
|
|
77
|
+
// and the call is waiting); the rest give a server that dies on start time to stop flapping.
|
|
78
|
+
const RESTART_BACKOFF_MS = [0, 1000, 3000];
|
|
71
79
|
// Every spawned server, killed when reika exits whatever route it leaves by. A stdio server's
|
|
72
80
|
// parent dying closes its pipes — which most servers treat as EOF and exit on — but one mid-call
|
|
73
81
|
// would linger as an orphan, and one hook covers every session (and every test) at once.
|
|
@@ -103,9 +111,19 @@ export class McpClient {
|
|
|
103
111
|
discardingLine = false;
|
|
104
112
|
stderrTail = '';
|
|
105
113
|
exitError;
|
|
114
|
+
connectedOnce = false;
|
|
115
|
+
closed = false;
|
|
116
|
+
restartBackoffMs;
|
|
117
|
+
// How many times the server was respawned after exiting, for `/mcp`.
|
|
118
|
+
restarts = 0;
|
|
119
|
+
// Set once the restart budget is spent: the reason every later call fails with.
|
|
120
|
+
gaveUpError;
|
|
121
|
+
// One respawn shared by every call that finds the server gone, so two parallel calls start one.
|
|
122
|
+
restarting;
|
|
106
123
|
constructor(config, opts = {}) {
|
|
107
124
|
this.config = config;
|
|
108
125
|
this.probeWaitMs = opts.probeWaitMs ?? PROBE_WAIT_MS;
|
|
126
|
+
this.restartBackoffMs = opts.restartBackoffMs ?? RESTART_BACKOFF_MS;
|
|
109
127
|
}
|
|
110
128
|
get name() {
|
|
111
129
|
return this.config.name;
|
|
@@ -123,6 +141,10 @@ export class McpClient {
|
|
|
123
141
|
get dead() {
|
|
124
142
|
return this.exitError !== undefined;
|
|
125
143
|
}
|
|
144
|
+
// Dead for the rest of the session: the restart budget is spent.
|
|
145
|
+
get gaveUp() {
|
|
146
|
+
return this.gaveUpError !== undefined;
|
|
147
|
+
}
|
|
126
148
|
// The handshake's own bound: a server that is slow to start costs a session's first paint, which
|
|
127
149
|
// a per-call timeout has no reason to govern (see McpServerConfig.connectTimeoutMs).
|
|
128
150
|
get connectTimeoutMs() {
|
|
@@ -131,16 +153,56 @@ export class McpClient {
|
|
|
131
153
|
// Spawn + handshake + tool discovery. Resolves only on a server that answered the handshake AND
|
|
132
154
|
// `tools/list`: a server that started but says nothing is a failure the user has to see.
|
|
133
155
|
async connect() {
|
|
156
|
+
this.tools = await this.spawnAndHandshake();
|
|
157
|
+
this.connectedOnce = true;
|
|
158
|
+
}
|
|
159
|
+
async spawnAndHandshake() {
|
|
134
160
|
await this.start();
|
|
135
161
|
try {
|
|
136
162
|
await this.handshake();
|
|
137
|
-
|
|
163
|
+
return await this.listTools();
|
|
138
164
|
}
|
|
139
165
|
catch (e) {
|
|
140
|
-
|
|
141
|
-
|
|
166
|
+
const err = new Error(this.explain(e));
|
|
167
|
+
// Kept as the reason the server is down, ahead of the exit the kill below causes.
|
|
168
|
+
this.exitError ??= err;
|
|
169
|
+
this.stopChild();
|
|
170
|
+
throw err;
|
|
142
171
|
}
|
|
143
172
|
}
|
|
173
|
+
// A server that exited after a successful connect is respawned here, before the call that needs
|
|
174
|
+
// it. The call that was in flight when it died is NOT retried: it may have acted before the crash.
|
|
175
|
+
async ensureRunning(signal) {
|
|
176
|
+
if (this.gaveUpError)
|
|
177
|
+
throw this.gaveUpError;
|
|
178
|
+
this.restarting ??= this.restart().finally(() => {
|
|
179
|
+
this.restarting = undefined;
|
|
180
|
+
});
|
|
181
|
+
await raceAbort(this.restarting, signal);
|
|
182
|
+
}
|
|
183
|
+
async restart() {
|
|
184
|
+
const last = this.exitError?.message ?? 'server exited';
|
|
185
|
+
if (this.restarts >= MAX_RESTARTS) {
|
|
186
|
+
this.gaveUpError = new Error(`${last}; not restarted again after ${MAX_RESTARTS} restarts this session`);
|
|
187
|
+
throw this.gaveUpError;
|
|
188
|
+
}
|
|
189
|
+
const wait = this.restartBackoffMs[this.restarts] ?? this.restartBackoffMs.at(-1) ?? 0;
|
|
190
|
+
this.restarts++;
|
|
191
|
+
debugLog(`[reika:debug] mcp ${this.name}: restart ${this.restarts} after: ${last}\n`);
|
|
192
|
+
if (wait > 0)
|
|
193
|
+
await delay(wait);
|
|
194
|
+
// Per-process state; the era is probed again since the binary may have changed under us.
|
|
195
|
+
this.era = undefined;
|
|
196
|
+
this.stdoutBuffer = '';
|
|
197
|
+
this.discardingLine = false;
|
|
198
|
+
this.stderrTail = '';
|
|
199
|
+
this.exitError = undefined;
|
|
200
|
+
const tools = await this.spawnAndHandshake();
|
|
201
|
+
// The tool list is fixed at session start (round-0 prefix), so a different one is surfaced the
|
|
202
|
+
// way list_changed is rather than adopted.
|
|
203
|
+
if (JSON.stringify(tools) !== JSON.stringify(this.tools))
|
|
204
|
+
this.toolsChanged = true;
|
|
205
|
+
}
|
|
144
206
|
// The spec's stdio probe: `server/discover` first; a result or a spec-range error is a modern
|
|
145
207
|
// server, anything else (or silence) a legacy one. The spec's version of "silence" is a timeout,
|
|
146
208
|
// which a modern server behind a cold `npx` install would trip — so after a short wait
|
|
@@ -244,6 +306,10 @@ export class McpClient {
|
|
|
244
306
|
}
|
|
245
307
|
async callTool(name, args, opts = {}) {
|
|
246
308
|
const timeoutMs = opts.timeoutMs ?? this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
309
|
+
// Only awaited when a restart is due: a tick's yield here would let an abort land before the
|
|
310
|
+
// request is even sent, and the server would never hear it was cancelled.
|
|
311
|
+
if (this.exitError && this.connectedOnce && !this.closed)
|
|
312
|
+
await this.ensureRunning(opts.signal);
|
|
247
313
|
let state;
|
|
248
314
|
for (let attempt = 0;; attempt++) {
|
|
249
315
|
const res = await this.request('tools/call', { name, arguments: args, ...(state !== undefined ? { requestState: state } : {}) }, timeoutMs, { signal: opts.signal });
|
|
@@ -267,6 +333,10 @@ export class McpClient {
|
|
|
267
333
|
// Resolves once the child is gone. Callers that are leaving anyway need not await it: the
|
|
268
334
|
// pending exit keeps the event loop alive until the server has had its chance to exit on EOF.
|
|
269
335
|
close() {
|
|
336
|
+
this.closed = true;
|
|
337
|
+
return this.stopChild();
|
|
338
|
+
}
|
|
339
|
+
stopChild() {
|
|
270
340
|
this.rejectInFlight(new Error('closed'));
|
|
271
341
|
const child = this.child;
|
|
272
342
|
this.child = undefined;
|
|
@@ -315,13 +385,16 @@ export class McpClient {
|
|
|
315
385
|
// A child that dies takes every in-flight request with it. The error surfaces here rather
|
|
316
386
|
// than as a hang: a server that exits mid-call is exactly the bug the user must be told.
|
|
317
387
|
child.on('error', (e) => {
|
|
318
|
-
this.exitError
|
|
388
|
+
this.exitError ??= new Error(`could not start ${command}: ${e.message}`);
|
|
319
389
|
this.rejectInFlight(this.exitError);
|
|
320
390
|
reject(this.exitError);
|
|
321
391
|
});
|
|
322
392
|
child.on('exit', (code, signal) => {
|
|
323
393
|
liveChildren.delete(child);
|
|
324
|
-
|
|
394
|
+
// A process already replaced by a restart says nothing about the one running now.
|
|
395
|
+
if (this.child !== undefined && this.child !== child)
|
|
396
|
+
return;
|
|
397
|
+
this.exitError ??= new Error(`server exited (${signal ? `signal ${signal}` : `code ${code}`})${this.stderrSuffix()}`);
|
|
325
398
|
this.rejectInFlight(this.exitError);
|
|
326
399
|
});
|
|
327
400
|
liveChildren.add(child);
|
|
@@ -410,6 +483,8 @@ export class McpClient {
|
|
|
410
483
|
}
|
|
411
484
|
request(method, params, timeoutMs, opts = {}) {
|
|
412
485
|
const { signal } = opts;
|
|
486
|
+
if (this.closed)
|
|
487
|
+
return Promise.reject(new Error('closed'));
|
|
413
488
|
if (this.exitError)
|
|
414
489
|
return Promise.reject(this.exitError);
|
|
415
490
|
if (signal?.aborted)
|
|
@@ -521,6 +596,23 @@ function modernVersionError(e) {
|
|
|
521
596
|
function unsupportedVersionsText(versions) {
|
|
522
597
|
return `server speaks protocol ${versions.join(', ') || '(none listed)'}; reika speaks ${MODERN_PROTOCOL_VERSION} and ${[...LEGACY_VERSIONS].join(', ')}`;
|
|
523
598
|
}
|
|
599
|
+
function raceAbort(promise, signal) {
|
|
600
|
+
if (!signal)
|
|
601
|
+
return promise;
|
|
602
|
+
if (signal.aborted)
|
|
603
|
+
return Promise.reject(new Error('aborted'));
|
|
604
|
+
return new Promise((resolve, reject) => {
|
|
605
|
+
const onAbort = () => reject(new Error('aborted'));
|
|
606
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
607
|
+
promise.then(v => {
|
|
608
|
+
signal.removeEventListener('abort', onAbort);
|
|
609
|
+
resolve(v);
|
|
610
|
+
}, (e) => {
|
|
611
|
+
signal.removeEventListener('abort', onAbort);
|
|
612
|
+
reject(e);
|
|
613
|
+
});
|
|
614
|
+
});
|
|
615
|
+
}
|
|
524
616
|
function delay(ms) {
|
|
525
617
|
return new Promise(resolve => setTimeout(() => resolve(undefined), ms).unref());
|
|
526
618
|
}
|
package/dist/mcp/manager.js
CHANGED
|
@@ -72,6 +72,12 @@ export async function connectMcpServers(servers) {
|
|
|
72
72
|
get dead() {
|
|
73
73
|
return entry.dead;
|
|
74
74
|
},
|
|
75
|
+
get restarts() {
|
|
76
|
+
return entry.restarts;
|
|
77
|
+
},
|
|
78
|
+
get gaveUp() {
|
|
79
|
+
return entry.gaveUp;
|
|
80
|
+
},
|
|
75
81
|
});
|
|
76
82
|
}
|
|
77
83
|
return {
|
|
@@ -136,10 +142,17 @@ export function formatMcpList(statuses) {
|
|
|
136
142
|
lines.push(` ${s.name} — ${s.tools} tool${s.tools === 1 ? '' : 's'} (${who})${s.alwaysAsk ? ' — asks before every call' : ''}`);
|
|
137
143
|
for (const c of s.commands)
|
|
138
144
|
lines.push(` /${c.name.padEnd(28)} ${c.description}`);
|
|
139
|
-
if (s.
|
|
140
|
-
lines.push(` (this server
|
|
145
|
+
if (s.gaveUp)
|
|
146
|
+
lines.push(` (this server kept exiting and is not restarted again after ${plural(s.restarts ?? 0, 'restart')} — its tools are still in the tool list, so calls fail until reika restarts)`);
|
|
147
|
+
else if (s.dead)
|
|
148
|
+
lines.push(` (this server has exited — it is restarted on its next call)`);
|
|
149
|
+
else if (s.restarts)
|
|
150
|
+
lines.push(` (restarted ${s.restarts === 1 ? 'once' : `${s.restarts} times`} after exiting)`);
|
|
141
151
|
if (s.changed)
|
|
142
152
|
lines.push(` (this server announced a changed tool list — restart reika to pick it up; the tool list is part of the cached request prefix)`);
|
|
143
153
|
}
|
|
144
154
|
return lines.join('\n');
|
|
145
155
|
}
|
|
156
|
+
function plural(n, word) {
|
|
157
|
+
return `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
158
|
+
}
|
package/dist/provider/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { jsonrepair } from 'jsonrepair';
|
|
2
2
|
import { debugLog } from '../debug.js';
|
|
3
3
|
import { cacheControlFor, promptCacheKeyFor } from './cachehints.js';
|
|
4
|
+
import { chatTemplateKwargsFor } from './templatekwargs.js';
|
|
4
5
|
import { latchesFor, resetEndpointLatches } from './latches.js';
|
|
5
6
|
import { messagesToChatParams, shapeRejection, toolsToChatTools } from './toolcall.js';
|
|
6
7
|
import { streamChatCompletion } from './transport.js';
|
|
@@ -29,6 +30,7 @@ export async function callModel(opts) {
|
|
|
29
30
|
rerender,
|
|
30
31
|
latches,
|
|
31
32
|
trailingNote: opts.trailingNote,
|
|
33
|
+
assistantPrefill: opts.assistantPrefill,
|
|
32
34
|
nativeImages: opts.nativeImages,
|
|
33
35
|
onCapStats: opts.onCapStats,
|
|
34
36
|
onAgedStats: opts.onAgedStats,
|
|
@@ -46,6 +48,7 @@ export async function callModel(opts) {
|
|
|
46
48
|
// consume attempt: a retry only happens before any chunk arrived (the `received` gate below), so
|
|
47
49
|
// there is never a stale one to clear.
|
|
48
50
|
let engineTimings;
|
|
51
|
+
let enginePrompt;
|
|
49
52
|
// Reset per consume attempt: the logprobs degrade below re-sends from scratch, so a retry's
|
|
50
53
|
// prefill must not be timed from the rejected request's start.
|
|
51
54
|
let startedAt = Date.now();
|
|
@@ -60,6 +63,9 @@ export async function callModel(opts) {
|
|
|
60
63
|
const cacheControl = latches.cacheControl
|
|
61
64
|
? undefined
|
|
62
65
|
: cacheControlFor(opts.config.baseURL, opts.config.model);
|
|
66
|
+
const templateKwargs = latches.chatTemplateKwargs
|
|
67
|
+
? undefined
|
|
68
|
+
: chatTemplateKwargsFor(opts.config.baseURL);
|
|
63
69
|
const body = {
|
|
64
70
|
model: opts.config.model,
|
|
65
71
|
messages,
|
|
@@ -74,6 +80,7 @@ export async function callModel(opts) {
|
|
|
74
80
|
...(wantLogprobs ? { logprobs: true, top_logprobs: opts.logprobs } : {}),
|
|
75
81
|
...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
|
|
76
82
|
...(cacheControl ? { cache_control: cacheControl } : {}),
|
|
83
|
+
...(templateKwargs ? { chat_template_kwargs: templateKwargs } : {}),
|
|
77
84
|
};
|
|
78
85
|
// True once a single chunk has been consumed. Gates the logprobs degrade below: retrying after
|
|
79
86
|
// any content streamed would duplicate it (same rule transport.ts applies to its own retries).
|
|
@@ -119,6 +126,16 @@ export async function callModel(opts) {
|
|
|
119
126
|
perSecond: et.predicted_per_second,
|
|
120
127
|
};
|
|
121
128
|
}
|
|
129
|
+
// Prefill stats ride the same object, cumulative the same way; each field is taken on its own.
|
|
130
|
+
if (et) {
|
|
131
|
+
const prompt = {
|
|
132
|
+
...(typeof et.prompt_n === 'number' ? { promptN: et.prompt_n } : {}),
|
|
133
|
+
...(typeof et.prompt_ms === 'number' ? { promptMs: et.prompt_ms } : {}),
|
|
134
|
+
...(typeof et.cache_n === 'number' ? { cacheN: et.cache_n } : {}),
|
|
135
|
+
};
|
|
136
|
+
if (Object.keys(prompt).length > 0)
|
|
137
|
+
enginePrompt = prompt;
|
|
138
|
+
}
|
|
122
139
|
// Logprobs ride the choice, not the delta, and a chunk can carry them with no delta at all
|
|
123
140
|
// — so collect before the delta guard. Normalized to SampledToken here (the wire's null
|
|
124
141
|
// top_logprobs becomes an absent `top`) so nothing downstream handles wire shapes.
|
|
@@ -230,6 +247,15 @@ export async function callModel(opts) {
|
|
|
230
247
|
req = plain;
|
|
231
248
|
continue;
|
|
232
249
|
}
|
|
250
|
+
// Name-keyed like the cache hints: logprobs below latches on any pre-chunk failure, and a
|
|
251
|
+
// server still loading at startup would otherwise cost the session its reasoning.
|
|
252
|
+
if (req.chat_template_kwargs !== undefined && reason.includes('chat_template_kwargs')) {
|
|
253
|
+
latches.chatTemplateKwargs = true;
|
|
254
|
+
debugLog(`[reika:debug] chat_template_kwargs unsupported by backend — retrying without (${reason})\n`);
|
|
255
|
+
const { chat_template_kwargs: _templateKwargs, ...plain } = req;
|
|
256
|
+
req = plain;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
233
259
|
if (req.logprobs !== undefined) {
|
|
234
260
|
latches.logprobs = true;
|
|
235
261
|
debugLog(`[reika:debug] logprobs unsupported by backend — retrying without (${reason})\n`);
|
|
@@ -262,6 +288,7 @@ export async function callModel(opts) {
|
|
|
262
288
|
finishReason,
|
|
263
289
|
timing: timing(),
|
|
264
290
|
...(engineTimings ? { engineTimings } : {}),
|
|
291
|
+
...(enginePrompt ? { enginePrompt } : {}),
|
|
265
292
|
...(sampled.length > 0 ? { sampled } : {}),
|
|
266
293
|
};
|
|
267
294
|
}
|
|
@@ -285,6 +312,7 @@ export async function callModel(opts) {
|
|
|
285
312
|
finishReason,
|
|
286
313
|
timing: timing(),
|
|
287
314
|
...(engineTimings ? { engineTimings } : {}),
|
|
315
|
+
...(enginePrompt ? { enginePrompt } : {}),
|
|
288
316
|
...(sampled.length > 0 ? { sampled } : {}),
|
|
289
317
|
};
|
|
290
318
|
}
|
package/dist/provider/latches.js
CHANGED