@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,239 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { debugLog } from '../debug.js';
|
|
6
|
+
import { callModel } from './client.js';
|
|
7
|
+
import { latchesFor } from './latches.js';
|
|
8
|
+
import { chatTemplateKwargsFor, isLocalEngine } from './templatekwargs.js';
|
|
9
|
+
export const NOTE_SLOT_CACHE_PATH = join(homedir(), '.config', 'reika', 'note-slot.json');
|
|
10
|
+
// A template is part of the model file, so a verdict outlives sessions; a week bounds how long a
|
|
11
|
+
// swapped template or engine upgrade can go unnoticed.
|
|
12
|
+
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
13
|
+
// A probe the server never answered (still loading, down) is asked again at the next submit; a
|
|
14
|
+
// request it rejects outright would be rejected every time, so the attempts are bounded.
|
|
15
|
+
const MAX_ATTEMPTS = 3;
|
|
16
|
+
// Waiting on a model load is the one slow case, and the first real request would wait for it too.
|
|
17
|
+
const PROBE_TIMEOUT_MS = 120_000;
|
|
18
|
+
const SENTINEL_REASONING = [
|
|
19
|
+
'Checking the parser first: the tokenizer splits on whitespace, then the lexer groups runs of',
|
|
20
|
+
'digits into numbers and letters into identifiers. A quoted string keeps its spaces, so the',
|
|
21
|
+
'splitter must skip quotes. Escapes inside quotes need a lookahead. The tests cover nested',
|
|
22
|
+
'quotes but not an escape at the end of input, which is the likely crash.',
|
|
23
|
+
].join(' ');
|
|
24
|
+
const PROBE_TOOL = {
|
|
25
|
+
name: 'read',
|
|
26
|
+
description: 'Read a file.',
|
|
27
|
+
parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
|
|
28
|
+
run: async () => ({ summary: '' }),
|
|
29
|
+
};
|
|
30
|
+
// The verdict is a fact about the template AND whether `preserve_thinking` reaches it, so the key
|
|
31
|
+
// carries both: a run with the kwarg withheld (REIKA_PRESERVE_THINKING=0, or an engine that 400'd it
|
|
32
|
+
// and latched it off) correctly finds `hides`, and the same model with the kwarg on must not read
|
|
33
|
+
// that back and move its note for a week.
|
|
34
|
+
function endpointKey(config) {
|
|
35
|
+
const kwargs = chatTemplateKwargsFor(config.baseURL) !== undefined && !latchesFor(config).chatTemplateKwargs;
|
|
36
|
+
return `${config.baseURL.replace(/\/+$/, '')}\n${config.model}\n${kwargs ? 'kwargs' : 'no-kwargs'}`;
|
|
37
|
+
}
|
|
38
|
+
function readCache(path) {
|
|
39
|
+
try {
|
|
40
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
41
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function writeCache(path, key, verdict) {
|
|
48
|
+
try {
|
|
49
|
+
const all = readCache(path);
|
|
50
|
+
all[key] = { verdict, at: Date.now() };
|
|
51
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
52
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
53
|
+
writeFileSync(tmp, JSON.stringify(all));
|
|
54
|
+
renameSync(tmp, path);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Fail-open: an unwritable cache only means the next session probes again.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function cachedNoteSlotVerdict(config, path = NOTE_SLOT_CACHE_PATH, now = Date.now()) {
|
|
61
|
+
const entry = readCache(path)[endpointKey(config)];
|
|
62
|
+
if (!entry || now - entry.at > CACHE_TTL_MS)
|
|
63
|
+
return undefined;
|
|
64
|
+
return entry.verdict === 'hides' ||
|
|
65
|
+
entry.verdict === 'renders' ||
|
|
66
|
+
entry.verdict === 'never-renders'
|
|
67
|
+
? entry.verdict
|
|
68
|
+
: undefined;
|
|
69
|
+
}
|
|
70
|
+
// Applies a verdict to the endpoint's latch. One-way: a session that moved its note to the tool
|
|
71
|
+
// result never moves it back, since each move re-renders earlier reasoning and costs a re-prefill.
|
|
72
|
+
export function applyNoteSlotVerdict(config, verdict, path = NOTE_SLOT_CACHE_PATH) {
|
|
73
|
+
if (verdict === 'hides')
|
|
74
|
+
latchesFor(config).noteOnToolResult = true;
|
|
75
|
+
writeCache(path, endpointKey(config), verdict);
|
|
76
|
+
}
|
|
77
|
+
// Equal counts within the few tokens an empty <think></think> pair can add mean the reasoning was
|
|
78
|
+
// dropped; a difference of at least half the reasoning's size means it rendered. Anything between
|
|
79
|
+
// is not a verdict.
|
|
80
|
+
export function classifyProbe(counts, reasoningTokens) {
|
|
81
|
+
const rendered = (d) => d >= reasoningTokens * 0.5;
|
|
82
|
+
const dropped = (d) => Math.abs(d) <= Math.max(4, reasoningTokens * 0.15);
|
|
83
|
+
const beforeNote = counts.withReasoning - counts.bare;
|
|
84
|
+
const behindNote = counts.noteWithReasoning - counts.noteBare;
|
|
85
|
+
if (dropped(beforeNote))
|
|
86
|
+
return 'never-renders';
|
|
87
|
+
if (!rendered(beforeNote))
|
|
88
|
+
return undefined;
|
|
89
|
+
if (dropped(behindNote))
|
|
90
|
+
return 'hides';
|
|
91
|
+
if (rendered(behindNote))
|
|
92
|
+
return 'renders';
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
function probeHistory(reasoning) {
|
|
96
|
+
return [
|
|
97
|
+
{ role: 'user', content: 'Find the crash in the parser.' },
|
|
98
|
+
{
|
|
99
|
+
role: 'assistant',
|
|
100
|
+
content: '',
|
|
101
|
+
...(reasoning ? { reasoning: SENTINEL_REASONING } : {}),
|
|
102
|
+
toolCalls: [{ id: 'probe1', name: 'read', args: { path: 'src/parser.ts' } }],
|
|
103
|
+
},
|
|
104
|
+
{ role: 'tool', callId: 'probe1', summary: 'Read src/parser.ts', payload: 'export {};' },
|
|
105
|
+
];
|
|
106
|
+
}
|
|
107
|
+
// One request per variant, each with a fresh nonce at the head of the system prompt: an engine that
|
|
108
|
+
// reports only the tokens it evaluated (Ollama counts past its prefix cache) would otherwise read a
|
|
109
|
+
// shared prefix as a shorter prompt.
|
|
110
|
+
async function countPromptTokens(config, reasoning, note, signal) {
|
|
111
|
+
const res = await callModel({
|
|
112
|
+
system: `probe ${randomBytes(4).toString('hex')}`,
|
|
113
|
+
history: probeHistory(reasoning),
|
|
114
|
+
tools: [PROBE_TOOL],
|
|
115
|
+
config,
|
|
116
|
+
maxTokens: 1,
|
|
117
|
+
prefixStable: true,
|
|
118
|
+
trailingNote: note ? '(auto-generated status note — not user input)' : undefined,
|
|
119
|
+
stampRenders: false,
|
|
120
|
+
signal,
|
|
121
|
+
});
|
|
122
|
+
return res.usage?.promptTokens;
|
|
123
|
+
}
|
|
124
|
+
export async function probeNoteSlot(config, controller = new AbortController()) {
|
|
125
|
+
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
|
|
126
|
+
try {
|
|
127
|
+
// Sequential on purpose: a single-slot server serves them one at a time anyway.
|
|
128
|
+
const bare = await countPromptTokens(config, false, false, controller.signal);
|
|
129
|
+
const withReasoning = await countPromptTokens(config, true, false, controller.signal);
|
|
130
|
+
const noteBare = await countPromptTokens(config, false, true, controller.signal);
|
|
131
|
+
const noteWithReasoning = await countPromptTokens(config, true, true, controller.signal);
|
|
132
|
+
if (controller.signal.aborted)
|
|
133
|
+
return { reached: false };
|
|
134
|
+
if ([bare, withReasoning, noteBare, noteWithReasoning].some(n => n === undefined)) {
|
|
135
|
+
debugLog('[reika:debug] note-slot probe verdict=? reason=no-usage\n');
|
|
136
|
+
return { reached: true };
|
|
137
|
+
}
|
|
138
|
+
const counts = {
|
|
139
|
+
bare: bare,
|
|
140
|
+
withReasoning: withReasoning,
|
|
141
|
+
noteBare: noteBare,
|
|
142
|
+
noteWithReasoning: noteWithReasoning,
|
|
143
|
+
};
|
|
144
|
+
const verdict = classifyProbe(counts, Math.round(SENTINEL_REASONING.length / 4));
|
|
145
|
+
debugLog(`[reika:debug] note-slot probe verdict=${verdict ?? '?'} bare=${counts.bare} ` +
|
|
146
|
+
`reasoning=${counts.withReasoning} note=${counts.noteBare} noteReasoning=${counts.noteWithReasoning}\n`);
|
|
147
|
+
return { reached: true, verdict };
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
debugLog(`[reika:debug] note-slot probe unreached err=${e instanceof Error ? e.message : e}\n`);
|
|
151
|
+
return { reached: false };
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const probeStates = new Map();
|
|
158
|
+
// Settles which slot this endpoint's note takes before a turn starts. Idempotent and safe to call
|
|
159
|
+
// at every submit: a decided endpoint returns at once, a probe in flight is shared, and a server
|
|
160
|
+
// that was not up is asked again. Never between rounds — on a single-slot server a probe there
|
|
161
|
+
// would evict the conversation's cache. Only local engines: hosted APIs get no `preserve_thinking`
|
|
162
|
+
// to fail and no `prompt_tokens` worth comparing. REIKA_NOTE_SLOT forces the slot, so no probe.
|
|
163
|
+
// `signal` is the turn's: ctrl-c ends the wait at once and stops the probe rather than holding the
|
|
164
|
+
// turn until the probe's timeout on a hung server, and the probe is asked again at the next submit.
|
|
165
|
+
export function ensureNoteSlot(config, path = NOTE_SLOT_CACHE_PATH, signal) {
|
|
166
|
+
const settled = settleNoteSlot(config, path);
|
|
167
|
+
if (!signal || !probeStates.get(endpointKey(config))?.inflight)
|
|
168
|
+
return settled;
|
|
169
|
+
if (signal.aborted) {
|
|
170
|
+
stopProbe(config);
|
|
171
|
+
return Promise.resolve();
|
|
172
|
+
}
|
|
173
|
+
return new Promise(resolve => {
|
|
174
|
+
const onAbort = () => {
|
|
175
|
+
stopProbe(config);
|
|
176
|
+
resolve();
|
|
177
|
+
};
|
|
178
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
179
|
+
void settled.then(() => {
|
|
180
|
+
signal.removeEventListener('abort', onAbort);
|
|
181
|
+
resolve();
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
function stopProbe(config) {
|
|
186
|
+
const state = probeStates.get(endpointKey(config));
|
|
187
|
+
if (!state?.controller)
|
|
188
|
+
return;
|
|
189
|
+
state.userAborted = true;
|
|
190
|
+
state.controller.abort();
|
|
191
|
+
}
|
|
192
|
+
function settleNoteSlot(config, path) {
|
|
193
|
+
if (!config.noteSlotProbe || !isLocalEngine(config.baseURL))
|
|
194
|
+
return Promise.resolve();
|
|
195
|
+
if (process.env.REIKA_NOTE_SLOT || process.env.REIKA_PREFIX_STABLE === '0') {
|
|
196
|
+
return Promise.resolve();
|
|
197
|
+
}
|
|
198
|
+
const key = endpointKey(config);
|
|
199
|
+
const state = probeStates.get(key) ?? { attempts: 0, done: false };
|
|
200
|
+
probeStates.set(key, state);
|
|
201
|
+
if (state.done || latchesFor(config).noteOnToolResult)
|
|
202
|
+
return Promise.resolve();
|
|
203
|
+
if (state.inflight)
|
|
204
|
+
return state.inflight;
|
|
205
|
+
const cached = cachedNoteSlotVerdict(config, path);
|
|
206
|
+
if (cached) {
|
|
207
|
+
if (cached === 'hides')
|
|
208
|
+
latchesFor(config).noteOnToolResult = true;
|
|
209
|
+
state.done = true;
|
|
210
|
+
debugLog(`[reika:debug] note-slot cached verdict=${cached}\n`);
|
|
211
|
+
return Promise.resolve();
|
|
212
|
+
}
|
|
213
|
+
if (state.attempts >= MAX_ATTEMPTS)
|
|
214
|
+
return Promise.resolve();
|
|
215
|
+
state.attempts++;
|
|
216
|
+
state.controller = new AbortController();
|
|
217
|
+
state.userAborted = false;
|
|
218
|
+
state.inflight = probeNoteSlot(config, state.controller)
|
|
219
|
+
.then(outcome => {
|
|
220
|
+
if (!outcome.reached) {
|
|
221
|
+
// A probe the user cut short says nothing about the server, so it costs no attempt.
|
|
222
|
+
if (state.userAborted)
|
|
223
|
+
state.attempts--;
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
state.done = true;
|
|
227
|
+
if (outcome.verdict)
|
|
228
|
+
applyNoteSlotVerdict(config, outcome.verdict, path);
|
|
229
|
+
})
|
|
230
|
+
.finally(() => {
|
|
231
|
+
state.inflight = undefined;
|
|
232
|
+
state.controller = undefined;
|
|
233
|
+
});
|
|
234
|
+
return state.inflight;
|
|
235
|
+
}
|
|
236
|
+
// Tests only.
|
|
237
|
+
export function resetNoteSlotProbes() {
|
|
238
|
+
probeStates.clear();
|
|
239
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { classifyPrivateHost } from '../tools/_hosts.js';
|
|
2
|
+
// Thinking templates such as LFM2.5's and Qwen3.6's render an assistant message's `<think>` only
|
|
3
|
+
// after the newest user message unless `preserve_thinking` is set (#798). Under prefix-stable the
|
|
4
|
+
// per-round ledgers ride a trailing user message, so from the first shed on the model saw none of
|
|
5
|
+
// its own reasoning in the turn and re-derived it (T2, lfm2.5-24b-a2b: restating in 70–75% of
|
|
6
|
+
// rounds after the shed, against 3–17% with the switch on). Asking for it per request leaves
|
|
7
|
+
// reasoning visibility to reika's own aging, which is what the estimate already bills.
|
|
8
|
+
//
|
|
9
|
+
// Local and private hosts only: a hosted API runs its own templates and has no use for the field,
|
|
10
|
+
// and a strict one would 400 on it. A dotless name counts as local, since it cannot be public. A
|
|
11
|
+
// local engine that rejects it is latched off by client.ts on an error naming the field.
|
|
12
|
+
export function chatTemplateKwargsFor(baseURL) {
|
|
13
|
+
// `0` reproduces an engine that never applies the field: the #827 test bed.
|
|
14
|
+
if (process.env.REIKA_PRESERVE_THINKING === '0')
|
|
15
|
+
return undefined;
|
|
16
|
+
return isLocalEngine(baseURL) ? { preserve_thinking: true } : undefined;
|
|
17
|
+
}
|
|
18
|
+
// A loopback, private or dotless host: an inference engine on the user's own network rather than
|
|
19
|
+
// a hosted API. The note round's assistant prefill (#806) is gated on it too.
|
|
20
|
+
export function isLocalEngine(baseURL) {
|
|
21
|
+
let host;
|
|
22
|
+
try {
|
|
23
|
+
host = new URL(baseURL).hostname;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
if (!host)
|
|
29
|
+
return false;
|
|
30
|
+
return classifyPrivateHost(host) !== undefined || (!host.includes('.') && !host.includes(':'));
|
|
31
|
+
}
|
|
@@ -212,6 +212,17 @@ export function shapeRejection(reason) {
|
|
|
212
212
|
}
|
|
213
213
|
// The request shape is the OpenAI-compatible `/v1/chat/completions` protocol (`ChatMessageParam`,
|
|
214
214
|
// transport.ts) that every backend we talk to speaks — llama.cpp, vLLM, Ollama — not OpenAI itself.
|
|
215
|
+
// Where the per-round note goes on this endpoint (#827): the newest tool result once the probe or the
|
|
216
|
+
// live check has latched it (noteOnToolResult), else the trailing user slot. REIKA_NOTE_SLOT
|
|
217
|
+
// forces either side, for an A/B or for an engine the detection gets wrong.
|
|
218
|
+
export function noteRidesToolResult(latches) {
|
|
219
|
+
const forced = process.env.REIKA_NOTE_SLOT;
|
|
220
|
+
if (forced === 'tool')
|
|
221
|
+
return true;
|
|
222
|
+
if (forced === 'user')
|
|
223
|
+
return false;
|
|
224
|
+
return latches?.noteOnToolResult === true;
|
|
225
|
+
}
|
|
215
226
|
export function messagesToChatParams(system, history, opts) {
|
|
216
227
|
const prefixStable = !!opts?.prefixStable;
|
|
217
228
|
const freshFrom = prefixStable ? 0 : findFreshToolBlockStart(history);
|
|
@@ -399,7 +410,15 @@ export function messagesToChatParams(system, history, opts) {
|
|
|
399
410
|
// text stays first, so the next round still diverges only where the note sat.
|
|
400
411
|
if (opts?.trailingNote) {
|
|
401
412
|
const tail = out[out.length - 1];
|
|
402
|
-
|
|
413
|
+
// A user-role note makes a thinking template that ignores preserve_thinking drop every <think>
|
|
414
|
+
// before it (#827). On the tool result it is not a user turn, so the reasoning keeps rendering.
|
|
415
|
+
const onToolResult = noteRidesToolResult(opts.latches) &&
|
|
416
|
+
tail?.role === 'tool' &&
|
|
417
|
+
typeof tail.content === 'string';
|
|
418
|
+
if (onToolResult) {
|
|
419
|
+
out[out.length - 1] = { ...tail, content: `${tail.content}\n\n${opts.trailingNote}` };
|
|
420
|
+
}
|
|
421
|
+
else if (tail?.role === 'user' && typeof tail.content === 'string') {
|
|
403
422
|
out[out.length - 1] = { role: 'user', content: `${tail.content}\n\n${opts.trailingNote}` };
|
|
404
423
|
}
|
|
405
424
|
else {
|
|
@@ -431,6 +450,8 @@ export function messagesToChatParams(system, history, opts) {
|
|
|
431
450
|
if (!out.some(m => m.role === 'user')) {
|
|
432
451
|
out.splice(1, 0, { role: 'user', content: '(continue)' });
|
|
433
452
|
}
|
|
453
|
+
if (opts?.assistantPrefill)
|
|
454
|
+
out.push({ role: 'assistant', content: opts.assistantPrefill });
|
|
434
455
|
opts?.onCapStats?.(capStats);
|
|
435
456
|
opts?.onAgedStats?.(agedStats);
|
|
436
457
|
return out;
|
|
@@ -68,8 +68,9 @@ async function postWithRetry(url, body, apiKey, signal) {
|
|
|
68
68
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
69
69
|
if (signal?.aborted)
|
|
70
70
|
throw new DOMException('Aborted', 'AbortError');
|
|
71
|
+
let res;
|
|
71
72
|
try {
|
|
72
|
-
|
|
73
|
+
res = await fetch(url, {
|
|
73
74
|
method: 'POST',
|
|
74
75
|
headers: {
|
|
75
76
|
'Content-Type': 'application/json',
|
|
@@ -87,14 +88,6 @@ async function postWithRetry(url, body, apiKey, signal) {
|
|
|
87
88
|
signal,
|
|
88
89
|
...(dispatcher ? { dispatcher } : {}),
|
|
89
90
|
});
|
|
90
|
-
if (res.ok && res.body)
|
|
91
|
-
return res;
|
|
92
|
-
if (attempt < MAX_RETRIES && isRetryableStatus(res.status)) {
|
|
93
|
-
await sleep(backoffMs(attempt), signal);
|
|
94
|
-
continue;
|
|
95
|
-
}
|
|
96
|
-
const detail = await res.text().catch(() => '');
|
|
97
|
-
throw new Error(`chat/completions failed: ${res.status} ${res.statusText}${detail ? ` — ${detail}` : ''}`);
|
|
98
91
|
}
|
|
99
92
|
catch (e) {
|
|
100
93
|
if (isAbort(e) || signal?.aborted)
|
|
@@ -108,6 +101,16 @@ async function postWithRetry(url, body, apiKey, signal) {
|
|
|
108
101
|
}
|
|
109
102
|
throw refusedAtDefaultPort(url, e) ?? e;
|
|
110
103
|
}
|
|
104
|
+
if (res.ok && res.body)
|
|
105
|
+
return res;
|
|
106
|
+
if (attempt < MAX_RETRIES && isRetryableStatus(res.status)) {
|
|
107
|
+
await sleep(backoffMs(attempt), signal);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
// Outside the catch (#804): a 4xx is the server's answer, and caught there it was retried as a
|
|
111
|
+
// network error, so every degrade latch saw the same rejected request three times.
|
|
112
|
+
const detail = await res.text().catch(() => '');
|
|
113
|
+
throw new Error(`chat/completions failed: ${res.status} ${res.statusText}${detail ? ` — ${detail}` : ''}`);
|
|
111
114
|
}
|
|
112
115
|
throw lastErr;
|
|
113
116
|
}
|
package/dist/session.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { loadConfig, resolveProfile, withProbedLimits } from './config.js';
|
|
1
|
+
import { assertRawConfig, loadConfig, resolveProfile, withProbedLimits } from './config.js';
|
|
2
|
+
import { ensureNoteSlot } from './provider/noteslot.js';
|
|
3
|
+
import { debugLog, formatEndpointLine } from './debug.js';
|
|
2
4
|
import { repoMapBudgetFor } from './context/repomap.js';
|
|
3
5
|
import { needsLimitsProbe, probeModelLimits, } from './provider/modellimits.js';
|
|
4
6
|
import { bootstrap, refitRepoMap } from './context/bootstrap.js';
|
|
@@ -13,6 +15,8 @@ import { detectIdentity, setIdentity } from './ui/identity.js';
|
|
|
13
15
|
import { kFormat } from './ui/format.js';
|
|
14
16
|
import { buildImplementPrompt, isMinimalPrompt, isGrindPrompt, planWritten, turnPromptMode, turnRefines, turnTools, } from './ui/commands.js';
|
|
15
17
|
export async function createSession(opts) {
|
|
18
|
+
if (opts.config)
|
|
19
|
+
assertRawConfig(opts.config, 'createSession');
|
|
16
20
|
let cfg = opts.config ?? loadConfig();
|
|
17
21
|
let profile = opts.profile ?? 'default';
|
|
18
22
|
// Identity detection runs CONCURRENTLY with bootstrap, not before it. Four git subprocesses cost
|
|
@@ -49,6 +53,16 @@ export async function createSession(opts) {
|
|
|
49
53
|
const retryWindow = new Set();
|
|
50
54
|
if (probed && !probed.reached)
|
|
51
55
|
retryWindow.add(profile);
|
|
56
|
+
// #827: which slot the per-round note takes on this endpoint. Fired here so it overlaps startup,
|
|
57
|
+
// awaited at each submit once the user's message is on screen and before the turn's first request,
|
|
58
|
+
// so it never runs between rounds (a probe there would evict a single-slot server's cache), and
|
|
59
|
+
// asked again at a submit if the server was not up.
|
|
60
|
+
void ensureNoteSlot(resolveProfile(cfg, profile));
|
|
61
|
+
const logEndpoint = () => {
|
|
62
|
+
const p = resolveProfile(cfg, profile);
|
|
63
|
+
debugLog(formatEndpointLine(profile, p.model, p.baseURL));
|
|
64
|
+
};
|
|
65
|
+
logEndpoint();
|
|
52
66
|
// No route out → no web tools this session (#392). Checked once, here, because the tool list is
|
|
53
67
|
// part of the cached prefix; the per-turn latch in the tools covers a drop later.
|
|
54
68
|
const offline = isOffline();
|
|
@@ -146,6 +160,9 @@ export async function createSession(opts) {
|
|
|
146
160
|
// vibe) never refines, since its plan phase is a new task even when a plan sits right above.
|
|
147
161
|
allowRefine: turnRefines(recorded),
|
|
148
162
|
manualCompact: submit.manualCompact,
|
|
163
|
+
// After the user echo, so the prompt is on screen while a probe runs; still before the
|
|
164
|
+
// turn's first request, never between rounds.
|
|
165
|
+
beforeFirstRequest: () => ensureNoteSlot(resolveProfile(cfg, profile), undefined, signal ?? undefined),
|
|
149
166
|
// The prompt carries the turn's mode from here on (the loop has no notion of one), so a
|
|
150
167
|
// saved transcript can say what each turn was.
|
|
151
168
|
onMessage: raw => {
|
|
@@ -239,6 +256,8 @@ export async function createSession(opts) {
|
|
|
239
256
|
decodeRate = undefined;
|
|
240
257
|
genReserve = new GenReserve();
|
|
241
258
|
changed();
|
|
259
|
+
logEndpoint();
|
|
260
|
+
void ensureNoteSlot(resolveProfile(cfg, name));
|
|
242
261
|
if (!needsLimitsProbe(next))
|
|
243
262
|
return Promise.resolve([]);
|
|
244
263
|
return probeModelLimits(next).then(probe => {
|
|
@@ -269,6 +288,7 @@ export async function createSession(opts) {
|
|
|
269
288
|
if (profile !== 'default') {
|
|
270
289
|
profile = 'default';
|
|
271
290
|
changed();
|
|
291
|
+
logEndpoint();
|
|
272
292
|
}
|
|
273
293
|
};
|
|
274
294
|
return {
|
|
@@ -6,22 +6,30 @@ import { delimiter, dirname, extname, isAbsolute, join, resolve } from 'node:pat
|
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
const GLOBAL_DEFAULT = join(homedir(), '.config', 'reika', 'skills');
|
|
8
8
|
const PROJECT_RELATIVE = '.reika/skills';
|
|
9
|
-
// The skills that ship in the package (`issue`, `review`), beside `dist/` —
|
|
10
|
-
// module whether it runs as src/skills.ts or dist/skills.js.
|
|
11
|
-
export const BUNDLED_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'skills');
|
|
9
|
+
// The skills that ship in the package (`issue`, `review`), beside `dist/` — two levels up from this
|
|
10
|
+
// module whether it runs as src/skills/skills.ts or dist/skills/skills.js.
|
|
11
|
+
export const BUNDLED_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'skills');
|
|
12
|
+
// Other harnesses' skill dirs (#861), so a skill folder works where it already is. Global is the
|
|
13
|
+
// agent-agnostic `~/.agents/skills` only — never `~/.claude/skills`, another app's config dir; a
|
|
14
|
+
// Claude Code user links it there. Read after `homedir()` at call time, so a test's HOME applies.
|
|
15
|
+
const PROJECT_IMPORTED = ['.claude/skills', '.agents/skills'];
|
|
16
|
+
const GLOBAL_IMPORTED = '.agents/skills';
|
|
12
17
|
export async function loadSkills(cwd, bundledDir = BUNDLED_DIR) {
|
|
13
18
|
const globalDir = process.env.REIKA_SKILLS_DIR
|
|
14
19
|
? expandHome(process.env.REIKA_SKILLS_DIR)
|
|
15
20
|
: GLOBAL_DEFAULT;
|
|
16
21
|
const projectDir = join(cwd, PROJECT_RELATIVE);
|
|
17
|
-
|
|
22
|
+
// Lowest precedence first; a later dir replaces an earlier one on a name collision. Reika's own
|
|
23
|
+
// dirs always win, then project over global, and `.agents` over `.claude`.
|
|
24
|
+
const layers = await Promise.all([
|
|
18
25
|
loadFromDir(bundledDir, 'bundled'),
|
|
26
|
+
loadFromDir(join(homedir(), GLOBAL_IMPORTED), 'global', `~/${GLOBAL_IMPORTED}`),
|
|
27
|
+
...PROJECT_IMPORTED.map(rel => loadFromDir(join(cwd, rel), 'project', rel)),
|
|
19
28
|
loadFromDir(globalDir, 'global'),
|
|
20
29
|
loadFromDir(projectDir, 'project'),
|
|
21
30
|
]);
|
|
22
|
-
// The user's own copy wins: project over global over bundled, on name collision.
|
|
23
31
|
const byName = new Map();
|
|
24
|
-
for (const s of
|
|
32
|
+
for (const s of layers.flat())
|
|
25
33
|
byName.set(s.name, s);
|
|
26
34
|
const env = await skillEnvironment(cwd, [...byName.values()]);
|
|
27
35
|
return Array.from(byName.values())
|
|
@@ -97,7 +105,7 @@ async function findGitDir(start) {
|
|
|
97
105
|
return null;
|
|
98
106
|
}
|
|
99
107
|
}
|
|
100
|
-
async function loadFromDir(dir, source) {
|
|
108
|
+
async function loadFromDir(dir, source, from) {
|
|
101
109
|
let entries;
|
|
102
110
|
try {
|
|
103
111
|
const raw = await readdir(dir, { withFileTypes: true });
|
|
@@ -127,12 +135,19 @@ async function loadFromDir(dir, source) {
|
|
|
127
135
|
const name = entry.name.toLowerCase();
|
|
128
136
|
if (!isValidName(name))
|
|
129
137
|
continue;
|
|
130
|
-
const
|
|
138
|
+
const skillDir = resolve(dir, entry.name);
|
|
139
|
+
const skillFile = await findCanonicalSkillFile(skillDir);
|
|
131
140
|
if (!skillFile)
|
|
132
141
|
continue;
|
|
133
|
-
const loaded = await readSkill(skillFile, name, source);
|
|
134
|
-
if (loaded)
|
|
135
|
-
|
|
142
|
+
const loaded = await readSkill(skillFile, name, source, from);
|
|
143
|
+
if (!loaded)
|
|
144
|
+
continue;
|
|
145
|
+
const files = await listSupportingFiles(skillDir, skillFile);
|
|
146
|
+
if (files.length > 0) {
|
|
147
|
+
const body = rewriteSkillPaths(loaded.body, skillDir, files);
|
|
148
|
+
loaded.body = `${skillDirAnchor(skillDir, files)}\n\n${body}`;
|
|
149
|
+
}
|
|
150
|
+
byName.set(name, loaded);
|
|
136
151
|
}
|
|
137
152
|
else {
|
|
138
153
|
if (extname(entry.name).toLowerCase() !== '.md')
|
|
@@ -140,13 +155,77 @@ async function loadFromDir(dir, source) {
|
|
|
140
155
|
const name = entry.name.slice(0, -3).toLowerCase();
|
|
141
156
|
if (!isValidName(name))
|
|
142
157
|
continue;
|
|
143
|
-
const loaded = await readSkill(join(dir, entry.name), name, source);
|
|
158
|
+
const loaded = await readSkill(join(dir, entry.name), name, source, from);
|
|
144
159
|
if (loaded && !byName.has(name))
|
|
145
160
|
byName.set(name, loaded);
|
|
146
161
|
}
|
|
147
162
|
}
|
|
148
163
|
return Array.from(byName.values());
|
|
149
164
|
}
|
|
165
|
+
// --- supporting files (#861) -----------------------------------------------------------------
|
|
166
|
+
// A skill written for another harness names its files relative to its own directory ("run
|
|
167
|
+
// `scripts/extract.py`"), and the body reaches the model with nothing saying where that is, so
|
|
168
|
+
// the path resolved against the cwd. The anchor names the directory and what is in it — names
|
|
169
|
+
// only, never contents. Nothing here runs a script: the model runs it through `bash`, behind the
|
|
170
|
+
// same approval gate and sandbox as any other command.
|
|
171
|
+
const MAX_LISTED_FILES = 20;
|
|
172
|
+
const MAX_WALKED_FILES = 200;
|
|
173
|
+
const MAX_WALK_DEPTH = 3;
|
|
174
|
+
const SKIPPED_DIRS = new Set(['node_modules', '__pycache__']);
|
|
175
|
+
export async function listSupportingFiles(skillDir, skillFile) {
|
|
176
|
+
const files = [];
|
|
177
|
+
async function walk(dir, rel, depth) {
|
|
178
|
+
if (depth > MAX_WALK_DEPTH || files.length >= MAX_WALKED_FILES)
|
|
179
|
+
return;
|
|
180
|
+
let entries;
|
|
181
|
+
try {
|
|
182
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
188
|
+
for (const e of entries) {
|
|
189
|
+
if (files.length >= MAX_WALKED_FILES)
|
|
190
|
+
return;
|
|
191
|
+
if (e.name.startsWith('.'))
|
|
192
|
+
continue;
|
|
193
|
+
const path = join(dir, e.name);
|
|
194
|
+
const relPath = rel ? `${rel}/${e.name}` : e.name;
|
|
195
|
+
if (e.isDirectory()) {
|
|
196
|
+
if (!SKIPPED_DIRS.has(e.name))
|
|
197
|
+
await walk(path, relPath, depth + 1);
|
|
198
|
+
}
|
|
199
|
+
else if (path !== skillFile) {
|
|
200
|
+
files.push(relPath);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
await walk(skillDir, '', 1);
|
|
205
|
+
return files;
|
|
206
|
+
}
|
|
207
|
+
export function skillDirAnchor(skillDir, files) {
|
|
208
|
+
const shown = files.slice(0, MAX_LISTED_FILES);
|
|
209
|
+
const more = files.length - shown.length;
|
|
210
|
+
const tail = more <= 0 ? '' : files.length >= MAX_WALKED_FILES ? ', and more' : `, and ${more} more`;
|
|
211
|
+
return [`This skill's files are in ${skillDir}.`, `Files: ${shown.join(', ')}${tail}`].join('\n');
|
|
212
|
+
}
|
|
213
|
+
// The anchor alone was not enough (#861, lfm2.5-24b, 1/3): the model found the script through it,
|
|
214
|
+
// then ran the body's command as written — `sh scripts/tally.sh` from the project — and when that
|
|
215
|
+
// failed, copied the script into the project. So a reference to a file that exists in the skill
|
|
216
|
+
// directory is rewritten to its absolute path, and the command the model copies is already right.
|
|
217
|
+
// Only exact names of real files, at a word start (not after `/`), so prose and the user's own
|
|
218
|
+
// paths are left alone.
|
|
219
|
+
export function rewriteSkillPaths(body, skillDir, files) {
|
|
220
|
+
if (files.length === 0)
|
|
221
|
+
return body;
|
|
222
|
+
const names = [...files].sort((a, b) => b.length - a.length).map(escapeRegExp);
|
|
223
|
+
const ref = new RegExp(`(^|[\\s\`'"(=])(?:\\./)?(${names.join('|')})(?=$|[\\s\`'")\\],;:!?]|\\.(?:$|\\s))`, 'gm');
|
|
224
|
+
return body.replace(ref, (_, lead, file) => lead + join(skillDir, file));
|
|
225
|
+
}
|
|
226
|
+
function escapeRegExp(text) {
|
|
227
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
228
|
+
}
|
|
150
229
|
async function findCanonicalSkillFile(dir) {
|
|
151
230
|
try {
|
|
152
231
|
const entries = await readdir(dir);
|
|
@@ -158,7 +237,7 @@ async function findCanonicalSkillFile(dir) {
|
|
|
158
237
|
return null;
|
|
159
238
|
}
|
|
160
239
|
}
|
|
161
|
-
async function readSkill(path, name, source) {
|
|
240
|
+
async function readSkill(path, name, source, from) {
|
|
162
241
|
try {
|
|
163
242
|
const text = await readFile(path, 'utf8');
|
|
164
243
|
const { meta, body } = parseFrontmatter(text);
|
|
@@ -168,6 +247,7 @@ async function readSkill(path, name, source) {
|
|
|
168
247
|
description,
|
|
169
248
|
body: body.trim(),
|
|
170
249
|
source,
|
|
250
|
+
...(from ? { from } : {}),
|
|
171
251
|
path,
|
|
172
252
|
triggers: parseTriggers(meta.triggers),
|
|
173
253
|
requires: parseRequires(meta.requires),
|