@alexwkleung/reika 0.6.0 → 0.7.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/config.js CHANGED
@@ -158,6 +158,8 @@ export function loadConfig() {
158
158
  // Per-project session auto-save for /resume (#1). Default on; `0` stops reika writing
159
159
  // conversations to disk at all, which is the one reason to want it off.
160
160
  autosave: process.env.REIKA_AUTOSAVE !== '0',
161
+ // #827: REIKA_NOTE_SLOT=tool|user forces the slot instead, checked where the probe would run.
162
+ noteSlotProbe: true,
161
163
  // Rotating garden words on the busy indicator (#500). Default on; `0` keeps the plain
162
164
  // "Working…" for anyone who finds it noise.
163
165
  workingWords: process.env.REIKA_WORKING_WORDS !== '0',
@@ -474,23 +476,34 @@ export function inheritProfile(from, model) {
474
476
  adhoc: true,
475
477
  };
476
478
  }
479
+ // The type brand is erased by any `Config` annotation or helper on the way, so the tag is what
480
+ // actually catches a resolved config reaching createSession (#832). Enumerable so a spread keeps it.
481
+ const RESOLVED = Symbol('ResolvedConfig');
482
+ export function assertRawConfig(config, where) {
483
+ if (RESOLVED in config) {
484
+ throw new Error(`${where} was given resolveProfile()'s result; pass the raw config instead`);
485
+ }
486
+ }
477
487
  export function resolveProfile(config, profileName) {
488
+ assertRawConfig(config, 'resolveProfile');
478
489
  const profile = config.profiles[profileName];
479
- if (!profile)
480
- return config;
481
- return {
482
- ...config,
483
- model: profile.model,
484
- baseURL: profile.baseURL,
485
- apiKey: profile.apiKey,
486
- maxTokens: profile.maxTokens,
487
- contextWindow: profile.contextWindow,
488
- maxOutputTokens: profile.maxOutputTokens,
489
- minGenTokens: profile.minGenTokens ?? config.minGenTokens,
490
- minGenAdaptive: profile.minGenTokens != null ? profile.minGenAdaptive : config.minGenAdaptive,
491
- // Same `?? config.x` fallback shape as minGenTokens. Without this line the profile's route is
492
- // dead weight: `...config` above would carry the *default* profile's value straight over it, so
493
- // a `/model <vl>` switch would keep describing while claiming to be native.
494
- vision: profile.vision ?? config.vision,
495
- };
490
+ // An unknown name falls back to the top level, i.e. the default profile.
491
+ const overlaid = profile
492
+ ? {
493
+ ...config,
494
+ model: profile.model,
495
+ baseURL: profile.baseURL,
496
+ apiKey: profile.apiKey,
497
+ maxTokens: profile.maxTokens,
498
+ contextWindow: profile.contextWindow,
499
+ maxOutputTokens: profile.maxOutputTokens,
500
+ minGenTokens: profile.minGenTokens ?? config.minGenTokens,
501
+ minGenAdaptive: profile.minGenTokens != null ? profile.minGenAdaptive : config.minGenAdaptive,
502
+ // Same `?? config.x` fallback shape as minGenTokens. Without this line the profile's route
503
+ // is dead weight: `...config` above would carry the *default* profile's value straight over
504
+ // it, so a `/model <vl>` switch would keep describing while claiming to be native.
505
+ vision: profile.vision ?? config.vision,
506
+ }
507
+ : config;
508
+ return { ...overlaid, [RESOLVED]: true };
496
509
  }
@@ -68,7 +68,9 @@ async function summarizeProject(cwd) {
68
68
  // crowding out the conversation on small windows (12KB ≈ 3k tokens), so we fall
69
69
  // back to an outline + read pointer instead of the full text.
70
70
  const INSTRUCTIONS_BUDGET = 12 * 1024;
71
- const INSTRUCTIONS_NAMES = ['AGENTS.md', 'CLAUDE.md'];
71
+ // First match wins. AGENT.md is an older spelling of the same tool-neutral convention; CLAUDE.md
72
+ // goes last because it is often written for Claude Code's own commands and tools.
73
+ const INSTRUCTIONS_NAMES = ['AGENTS.md', 'AGENT.md', 'CLAUDE.md'];
72
74
  const GLOBAL_INSTRUCTIONS_DIR = join(homedir(), '.config', 'reika');
73
75
  // Global (~/.config/reika/AGENTS.md) carries the user's personal preferences; the project
74
76
  // file carries the repo's. Both go in when both exist, global first so the project's more
@@ -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,
@@ -60,6 +62,9 @@ export async function callModel(opts) {
60
62
  const cacheControl = latches.cacheControl
61
63
  ? undefined
62
64
  : cacheControlFor(opts.config.baseURL, opts.config.model);
65
+ const templateKwargs = latches.chatTemplateKwargs
66
+ ? undefined
67
+ : chatTemplateKwargsFor(opts.config.baseURL);
63
68
  const body = {
64
69
  model: opts.config.model,
65
70
  messages,
@@ -74,6 +79,7 @@ export async function callModel(opts) {
74
79
  ...(wantLogprobs ? { logprobs: true, top_logprobs: opts.logprobs } : {}),
75
80
  ...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
76
81
  ...(cacheControl ? { cache_control: cacheControl } : {}),
82
+ ...(templateKwargs ? { chat_template_kwargs: templateKwargs } : {}),
77
83
  };
78
84
  // True once a single chunk has been consumed. Gates the logprobs degrade below: retrying after
79
85
  // any content streamed would duplicate it (same rule transport.ts applies to its own retries).
@@ -230,6 +236,15 @@ export async function callModel(opts) {
230
236
  req = plain;
231
237
  continue;
232
238
  }
239
+ // Name-keyed like the cache hints: logprobs below latches on any pre-chunk failure, and a
240
+ // server still loading at startup would otherwise cost the session its reasoning.
241
+ if (req.chat_template_kwargs !== undefined && reason.includes('chat_template_kwargs')) {
242
+ latches.chatTemplateKwargs = true;
243
+ debugLog(`[reika:debug] chat_template_kwargs unsupported by backend — retrying without (${reason})\n`);
244
+ const { chat_template_kwargs: _templateKwargs, ...plain } = req;
245
+ req = plain;
246
+ continue;
247
+ }
233
248
  if (req.logprobs !== undefined) {
234
249
  latches.logprobs = true;
235
250
  debugLog(`[reika:debug] logprobs unsupported by backend — retrying without (${reason})\n`);
@@ -17,6 +17,9 @@ export function latchesFor(endpoint) {
17
17
  toolMessageName: false,
18
18
  promptCacheKey: false,
19
19
  cacheControl: false,
20
+ chatTemplateKwargs: false,
21
+ assistantPrefill: false,
22
+ noteOnToolResult: false,
20
23
  };
21
24
  latchesByEndpoint.set(key, latches);
22
25
  }
@@ -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
- if (tail?.role === 'user' && typeof tail.content === 'string') {
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
- const res = await fetch(url, {
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,5 @@
1
- import { loadConfig, resolveProfile, withProbedLimits } from './config.js';
1
+ import { assertRawConfig, loadConfig, resolveProfile, withProbedLimits } from './config.js';
2
+ import { ensureNoteSlot } from './provider/noteslot.js';
2
3
  import { repoMapBudgetFor } from './context/repomap.js';
3
4
  import { needsLimitsProbe, probeModelLimits, } from './provider/modellimits.js';
4
5
  import { bootstrap, refitRepoMap } from './context/bootstrap.js';
@@ -13,6 +14,8 @@ import { detectIdentity, setIdentity } from './ui/identity.js';
13
14
  import { kFormat } from './ui/format.js';
14
15
  import { buildImplementPrompt, isMinimalPrompt, isGrindPrompt, planWritten, turnPromptMode, turnRefines, turnTools, } from './ui/commands.js';
15
16
  export async function createSession(opts) {
17
+ if (opts.config)
18
+ assertRawConfig(opts.config, 'createSession');
16
19
  let cfg = opts.config ?? loadConfig();
17
20
  let profile = opts.profile ?? 'default';
18
21
  // Identity detection runs CONCURRENTLY with bootstrap, not before it. Four git subprocesses cost
@@ -49,6 +52,11 @@ export async function createSession(opts) {
49
52
  const retryWindow = new Set();
50
53
  if (probed && !probed.reached)
51
54
  retryWindow.add(profile);
55
+ // #827: which slot the per-round note takes on this endpoint. Fired here so it overlaps startup,
56
+ // awaited at each submit once the user's message is on screen and before the turn's first request,
57
+ // so it never runs between rounds (a probe there would evict a single-slot server's cache), and
58
+ // asked again at a submit if the server was not up.
59
+ void ensureNoteSlot(resolveProfile(cfg, profile));
52
60
  // No route out → no web tools this session (#392). Checked once, here, because the tool list is
53
61
  // part of the cached prefix; the per-turn latch in the tools covers a drop later.
54
62
  const offline = isOffline();
@@ -146,6 +154,9 @@ export async function createSession(opts) {
146
154
  // vibe) never refines, since its plan phase is a new task even when a plan sits right above.
147
155
  allowRefine: turnRefines(recorded),
148
156
  manualCompact: submit.manualCompact,
157
+ // After the user echo, so the prompt is on screen while a probe runs; still before the
158
+ // turn's first request, never between rounds.
159
+ beforeFirstRequest: () => ensureNoteSlot(resolveProfile(cfg, profile), undefined, signal ?? undefined),
149
160
  // The prompt carries the turn's mode from here on (the loop has no notion of one), so a
150
161
  // saved transcript can say what each turn was.
151
162
  onMessage: raw => {
@@ -239,6 +250,7 @@ export async function createSession(opts) {
239
250
  decodeRate = undefined;
240
251
  genReserve = new GenReserve();
241
252
  changed();
253
+ void ensureNoteSlot(resolveProfile(cfg, name));
242
254
  if (!needsLimitsProbe(next))
243
255
  return Promise.resolve([]);
244
256
  return probeModelLimits(next).then(probe => {