@tobi-or-not/quorum 0.4.0 → 0.5.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.
Files changed (71) hide show
  1. package/README.md +1 -1
  2. package/dist/bench/fingerprint.d.ts +7 -5
  3. package/dist/bench/fingerprint.js +22 -9
  4. package/dist/bench/records.d.ts +70 -0
  5. package/dist/bench/records.js +30 -0
  6. package/dist/bench/runner.d.ts +18 -0
  7. package/dist/bench/runner.js +29 -3
  8. package/dist/cli/bench.d.ts +11 -4
  9. package/dist/cli/bench.js +34 -17
  10. package/dist/cli/bin.js +2 -2
  11. package/dist/cli/main.d.ts +34 -14
  12. package/dist/cli/main.js +99 -20
  13. package/dist/cli/print-config.d.ts +8 -6
  14. package/dist/cli/print-config.js +21 -8
  15. package/dist/cli/render.d.ts +2 -2
  16. package/dist/cli/render.js +21 -2
  17. package/dist/config/env.d.ts +32 -19
  18. package/dist/config/env.js +95 -32
  19. package/dist/config/from-config.js +15 -3
  20. package/dist/config/resolve.d.ts +9 -1
  21. package/dist/config/resolve.js +17 -1
  22. package/dist/config/schema.d.ts +141 -5
  23. package/dist/config/schema.js +125 -12
  24. package/dist/core/clock.d.ts +17 -0
  25. package/dist/core/clock.js +14 -0
  26. package/dist/core/coverage.d.ts +49 -0
  27. package/dist/core/coverage.js +144 -0
  28. package/dist/core/diff.d.ts +24 -0
  29. package/dist/core/diff.js +63 -18
  30. package/dist/core/errors.d.ts +12 -3
  31. package/dist/core/errors.js +21 -2
  32. package/dist/core/exclude.d.ts +42 -0
  33. package/dist/core/exclude.js +189 -0
  34. package/dist/core/limits.d.ts +82 -0
  35. package/dist/core/limits.js +163 -0
  36. package/dist/core/output.d.ts +3 -2
  37. package/dist/core/output.js +3 -2
  38. package/dist/core/ports.d.ts +57 -2
  39. package/dist/core/ports.js +36 -1
  40. package/dist/core/quorum.d.ts +24 -8
  41. package/dist/core/quorum.js +187 -56
  42. package/dist/core/retry.d.ts +36 -0
  43. package/dist/core/retry.js +46 -0
  44. package/dist/core/stages/context.d.ts +118 -23
  45. package/dist/core/stages/context.js +304 -46
  46. package/dist/core/stages/panel.d.ts +5 -4
  47. package/dist/core/stages/panel.js +30 -11
  48. package/dist/core/stages/research.d.ts +15 -6
  49. package/dist/core/stages/research.js +75 -18
  50. package/dist/core/tokens.d.ts +31 -0
  51. package/dist/core/tokens.js +81 -0
  52. package/dist/core/types.d.ts +77 -10
  53. package/dist/index.d.ts +1 -1
  54. package/dist/providers/anthropic.d.ts +2 -1
  55. package/dist/providers/anthropic.js +8 -3
  56. package/dist/providers/claude-code.d.ts +51 -11
  57. package/dist/providers/claude-code.js +60 -25
  58. package/dist/providers/gemini.d.ts +4 -1
  59. package/dist/providers/gemini.js +63 -11
  60. package/dist/providers/http.d.ts +49 -4
  61. package/dist/providers/http.js +155 -14
  62. package/dist/providers/ollama.d.ts +3 -1
  63. package/dist/providers/ollama.js +11 -5
  64. package/dist/providers/openai-compatible.d.ts +3 -1
  65. package/dist/providers/openai-compatible.js +11 -5
  66. package/dist/providers/options.d.ts +12 -3
  67. package/dist/providers/options.js +30 -10
  68. package/dist/providers/size.d.ts +10 -14
  69. package/dist/providers/size.js +15 -69
  70. package/package.json +1 -1
  71. package/schema/quorum.schema.json +34 -1
@@ -38,10 +38,16 @@ export interface ClaudeCodeOptions {
38
38
  model: string;
39
39
  /**
40
40
  * The model's context window in tokens, prompt and reply together. Required: every request is checked
41
- * against it and refused, before it is run, when it may not fit. It must be more than 20096, the reply
42
- * budget and the reserve for what Claude Code adds.
41
+ * against it and refused, before it is run, when it may not fit. It must be more than `maxTokens` and the
42
+ * 4096 tokens reserved for what Claude Code adds: 20096 by default.
43
43
  */
44
44
  contextTokens: number;
45
+ /**
46
+ * The most tokens each reply may hold, thinking included, which Claude Code reads from
47
+ * `CLAUDE_CODE_MAX_OUTPUT_TOKENS` and caps at the model's own limit: a whole number of at least 1. Default 16000.
48
+ * It replaces a `CLAUDE_CODE_MAX_OUTPUT_TOKENS` of the environment.
49
+ */
50
+ maxTokens?: number;
45
51
  /** Whose credentials `claude` uses. Default `inherit`. */
46
52
  auth?: ClaudeCodeAuth;
47
53
  /**
@@ -62,6 +68,19 @@ export interface ClaudeCodeOptions {
62
68
  command?: string;
63
69
  /** The environment `claude` inherits, less what its auth mode removes. Read once, when the provider is made. Default `process.env`. */
64
70
  env?: Readonly<Record<string, string | undefined>>;
71
+ /**
72
+ * How long Claude Code waits for the response headers of each attempt at its API call (`API_TIMEOUT_MS`), in
73
+ * milliseconds, from 1000 to 86400000. Default 600000. It bounds that wait only. The provider states
74
+ * `timeoutMs` times `retries` plus one to the core as the deadline of the whole run, so raise it for a long run.
75
+ * It replaces an `API_TIMEOUT_MS` of the environment.
76
+ */
77
+ timeoutMs?: number;
78
+ /**
79
+ * Claude Code's own retries of an API call that failed in passing, from 0 to 5. Default 2, where Claude Code
80
+ * alone makes 10. The provider states no retry to the core, which would retry what Claude Code retried. It
81
+ * replaces a `CLAUDE_CODE_MAX_RETRIES` of the environment.
82
+ */
83
+ retries?: number;
65
84
  }
66
85
  /** The command-line settings of a run. */
67
86
  export interface ClaudeArgsSettings {
@@ -111,13 +130,19 @@ export declare function claudeArgs(settings: ClaudeArgsSettings, systemPromptFil
111
130
  * every credential, header and endpoint variable, so a login or a key never reaches another host or travels
112
131
  * with another credential. Names are matched in any letter case, since Windows reads them so. Under
113
132
  * `api-key`, `ANTHROPIC_API_KEY` is then `apiKey` when it is a non-empty string, else the environment's
114
- * own, trimmed, when that is not blank. Last come ten variables the run sets over whatever the environment
133
+ * own, trimmed, when that is not blank. Last come thirteen variables the run sets over whatever the environment
115
134
  * held, in any case: no auto memory, no compaction of a long prompt, a temporary directory of its own, no
116
- * IDE connection or claude.ai MCP connector, which are on by default, and no attachment, file mention,
117
- * `CLAUDE.md` file, bundled skill or managed skill. A line naming a path (`@/path`) in the message makes
118
- * Claude Code attach that file for the model to read, with every tool off, unless the first two are set.
135
+ * IDE connection or claude.ai MCP connector, which are on by default, no attachment, file mention,
136
+ * `CLAUDE.md` file, bundled skill or managed skill, Claude Code's wait for each attempt's response headers
137
+ * and its own retries, and, the last, its limit on each reply, which follow the provider's settings
138
+ * (`settings`). A line naming a path (`@/path`) in the message makes Claude Code attach that file for the
139
+ * model to read, with every tool off, unless the first two are set.
119
140
  */
120
- export declare function childEnv(env: Readonly<Record<string, string | undefined>>, auth: ClaudeCodeAuth, apiKey: string | undefined, tmpDir: string): Record<string, string>;
141
+ export declare function childEnv(env: Readonly<Record<string, string | undefined>>, auth: ClaudeCodeAuth, apiKey: string | undefined, tmpDir: string, settings: {
142
+ readonly timeoutMs: number;
143
+ readonly retries: number;
144
+ readonly maxTokens: number;
145
+ }): Record<string, string>;
121
146
  /**
122
147
  * The values a quoted text must be redacted of: those of the credential variables of the environment a run
123
148
  * gets (`childEnv`'s result), each as written and trimmed, with names matched in any letter case. A value
@@ -137,7 +162,7 @@ export declare function versionProblem(output: string): string | undefined;
137
162
  * JSON result: a signal, a non-zero exit with a quote of stderr, or nothing at all, each a failure. Every
138
163
  * quoted text goes through `snippet`, redacted of the key.
139
164
  *
140
- * @throws ProviderError of the kind the failure is: `too-large`, `refusal`, `http`, `process` or `invalid-response`
165
+ * @throws ProviderError of the kind the failure is: `too-large`, `refusal`, `truncated`, `http`, `process` or `invalid-response`
141
166
  */
142
167
  export declare function readResult(run: ClaudeRun, context: ResultContext): CompletionResponse;
143
168
  /** The directory of one run and what it holds. */
@@ -180,7 +205,8 @@ export declare function trackRun(run: LiveRun): () => void;
180
205
  * 1. exactly one message, a user message, else `unsupported`;
181
206
  * 2. a message that starts with `/` after white space, which `-p` would run as a command: `unsupported`;
182
207
  * 3. a message over `MAX_STDIN_BYTES` bytes: `too-large`;
183
- * 4. the size guard, with `CLAUDE_CODE_TEMPLATE_TOKENS` kept for the context Claude Code adds: `too-large`;
208
+ * 4. the size guard, with the reply budget, `maxTokens`, and `CLAUDE_CODE_TEMPLATE_TOKENS` kept for the
209
+ * context Claude Code adds: `too-large`;
184
210
  * 5. an aborted signal: `aborted`;
185
211
  * 6. a directory of its own, under the temporary directory, holding an empty working directory, `claude`'s
186
212
  * scratch directory and the system text's file: a failure to make it is `process`;
@@ -199,8 +225,22 @@ export declare function trackRun(run: LiveRun): () => void;
199
225
  * 13. an aborted signal: `aborted`; else `readResult`'s reply or failure, with every credential of the
200
226
  * child's environment redacted from the text it quotes (`credentialValues`).
201
227
  *
202
- * No timeout is set: Claude Code retries a failed API call by itself, for minutes, and a deadline is the
203
- * caller's own (a signal).
228
+ * Claude Code retries a failed API call by itself, ten times by default, so the provider sets `API_TIMEOUT_MS`
229
+ * and `CLAUDE_CODE_MAX_RETRIES` in the child's environment from `timeoutMs` and `retries` (600000 ms and 2 by
230
+ * default) over any the environment held, and states no retry to the core, which would retry what Claude Code
231
+ * retried. It sets `CLAUDE_CODE_MAX_OUTPUT_TOKENS` the same way from `maxTokens` (16000 by default, where
232
+ * Claude Code asks for up to 128000 by itself), so the model's API bounds every reply. It states one deadline
233
+ * for the whole run, `timeoutMs` times `retries` plus one: Claude Code's own attempts and the waits between
234
+ * them, its start and the version check, and each reply's time after its headers all count against it, where
235
+ * `API_TIMEOUT_MS` limits only an attempt's wait for its headers. At it the core aborts the signal, which
236
+ * stops the child's group as step 11 says.
237
+ *
238
+ * It states its worst case from the count its size guard keeps, over the model turns of a run: in `schema`
239
+ * mode two, since the model answers by calling the schema tool and `claude` then makes a second turn after
240
+ * the tool's result, which carries the first reply as input, so `2 * (text + 4096) + 3 * maxTokens`; in
241
+ * `prompt` mode one, `text + 4096 + maxTokens`. It leaves out what Claude Code spends beyond that, a reply
242
+ * it continues after its limit, up to three times a turn, and its own retries: those count once the run
243
+ * reports its usage.
204
244
  *
205
245
  * @throws ConfigError with every problem of the options, before any request
206
246
  */
@@ -4,10 +4,11 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { isAbsolute, join, resolve } from 'node:path';
6
6
  import { ConfigError } from "../core/errors.js";
7
+ import { DEFAULT_RETRIES, DEFAULT_TIMEOUT_MS } from "../core/ports.js";
7
8
  import { snippet } from "./http.js";
8
- import { contextTokensIssues, isRecord, NOT_VISIBLE_ASCII, wordList } from "./options.js";
9
+ import { attemptIssues, contextTokensIssues, isRecord, maxTokensIssues, NOT_VISIBLE_ASCII, wordList } from "./options.js";
9
10
  import { replyFailure, tokenUsage } from "./reply.js";
10
- import { checkFits, contextBudget, utf8Length } from "./size.js";
11
+ import { checkFits, contextBudget, DEFAULT_REPLY_TOKENS, utf8Length, worstCaseTokens } from "./size.js";
11
12
  /**
12
13
  * The `claude-code` adapter runs the user's installed `claude` CLI once per request, headless and isolated,
13
14
  * as a pure completion: no tool but the schema tool, no settings file, MCP server, slash command or
@@ -39,7 +40,6 @@ const HTTP_FIELDS = [
39
40
  'query',
40
41
  'extraBody',
41
42
  'temperature',
42
- 'maxTokens',
43
43
  'systemPrompt',
44
44
  ];
45
45
  const WINDOWS_SCRIPT = /\.(?:cmd|bat)$/i;
@@ -274,7 +274,7 @@ function apiKeyIssues(path, auth, apiKey) {
274
274
  * message repeats a value: a key, a model id or an argument can be a secret.
275
275
  */
276
276
  export function claudeCodeIssues(options) {
277
- const { id, model, contextTokens, auth, apiKey, structuredOutput, args, command } = options;
277
+ const { id, model, contextTokens, maxTokens, auth, apiKey, structuredOutput, args, command, timeoutMs, retries } = options;
278
278
  const at = (field, message) => ({ path: `${id}.${field}`, message });
279
279
  const given = options;
280
280
  const issues = HTTP_FIELDS
@@ -282,7 +282,8 @@ export function claudeCodeIssues(options) {
282
282
  .map(field => at(field, 'is not an option of the claude-code protocol'));
283
283
  if (typeof model !== 'string' || !plainValue(model))
284
284
  issues.push(at('model', 'must be a model id of visible ASCII characters, with no space, that does not start with -'));
285
- issues.push(...contextTokensIssues(id, contextTokens, undefined, CLAUDE_CODE_TEMPLATE_TOKENS));
285
+ issues.push(...maxTokensIssues(id, maxTokens));
286
+ issues.push(...contextTokensIssues(id, contextTokens, maxTokens, CLAUDE_CODE_TEMPLATE_TOKENS));
286
287
  if (auth !== undefined && !AUTH_MODES.includes(auth))
287
288
  issues.push(at('auth', `must be ${wordList(AUTH_MODES)}`));
288
289
  issues.push(...apiKeyIssues(`${id}.apiKey`, auth, apiKey));
@@ -299,6 +300,7 @@ export function claudeCodeIssues(options) {
299
300
  if (problem !== undefined)
300
301
  issues.push(at('command', problem));
301
302
  }
303
+ issues.push(...attemptIssues(id, timeoutMs, retries));
302
304
  return issues;
303
305
  }
304
306
  /**
@@ -337,14 +339,16 @@ function removedVariable(name, auth, runVariables) {
337
339
  * every credential, header and endpoint variable, so a login or a key never reaches another host or travels
338
340
  * with another credential. Names are matched in any letter case, since Windows reads them so. Under
339
341
  * `api-key`, `ANTHROPIC_API_KEY` is then `apiKey` when it is a non-empty string, else the environment's
340
- * own, trimmed, when that is not blank. Last come ten variables the run sets over whatever the environment
342
+ * own, trimmed, when that is not blank. Last come thirteen variables the run sets over whatever the environment
341
343
  * held, in any case: no auto memory, no compaction of a long prompt, a temporary directory of its own, no
342
- * IDE connection or claude.ai MCP connector, which are on by default, and no attachment, file mention,
343
- * `CLAUDE.md` file, bundled skill or managed skill. A line naming a path (`@/path`) in the message makes
344
- * Claude Code attach that file for the model to read, with every tool off, unless the first two are set.
344
+ * IDE connection or claude.ai MCP connector, which are on by default, no attachment, file mention,
345
+ * `CLAUDE.md` file, bundled skill or managed skill, Claude Code's wait for each attempt's response headers
346
+ * and its own retries, and, the last, its limit on each reply, which follow the provider's settings
347
+ * (`settings`). A line naming a path (`@/path`) in the message makes Claude Code attach that file for the
348
+ * model to read, with every tool off, unless the first two are set.
345
349
  */
346
- export function childEnv(env, auth, apiKey, tmpDir) {
347
- const isolation = {
350
+ export function childEnv(env, auth, apiKey, tmpDir, settings) {
351
+ const runVariables = {
348
352
  CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',
349
353
  DISABLE_COMPACT: '1',
350
354
  CLAUDE_CODE_TMPDIR: tmpDir,
@@ -355,6 +359,9 @@ export function childEnv(env, auth, apiKey, tmpDir) {
355
359
  CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1',
356
360
  CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: '1',
357
361
  CLAUDE_CODE_DISABLE_POLICY_SKILLS: '1',
362
+ API_TIMEOUT_MS: String(settings.timeoutMs),
363
+ CLAUDE_CODE_MAX_RETRIES: String(settings.retries),
364
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(settings.maxTokens),
358
365
  };
359
366
  const own = Object.entries(env).filter((entry) => typeof entry[1] === 'string');
360
367
  const inheritedKey = (own.find(([name]) => name === KEY_VARIABLE) ?? own.find(([name]) => name.toUpperCase() === KEY_VARIABLE))?.[1].trim();
@@ -362,11 +369,11 @@ export function childEnv(env, auth, apiKey, tmpDir) {
362
369
  ? apiKey
363
370
  : inheritedKey;
364
371
  return {
365
- ...Object.fromEntries(own.filter(([name]) => !removedVariable(name, auth, isolation))),
372
+ ...Object.fromEntries(own.filter(([name]) => !removedVariable(name, auth, runVariables))),
366
373
  ...(auth === 'api-key' && key !== undefined && key !== ''
367
374
  ? { [KEY_VARIABLE]: key }
368
375
  : {}),
369
- ...isolation,
376
+ ...runVariables,
370
377
  };
371
378
  }
372
379
  /**
@@ -515,11 +522,13 @@ function signalName(signal) {
515
522
  }
516
523
  /**
517
524
  * The reply of a result, or the `ProviderError` it amounts to, in this order: a prompt too long, a
518
- * refusal, an error (anything but an `is_error` of `false` is one), a child a signal ended or a non-zero
519
- * exit after a success, a tool the server ran, a reply the token limit cut off, then the text. Claude Code
520
- * reports an API error as exit 1 with `subtype: "success"` and `is_error: true`, so the JSON on stdout is
521
- * read before the exit code. Every failure carries the usage the result reports, summed as `sumUsage`
522
- * does, since the model generated and billed those tokens whatever came after.
525
+ * refusal, a reply Claude Code reports cut off at its output limit (an error result whose `api_error` is
526
+ * `max_output_tokens`, which it gives after continuing the reply three times), an error (anything but an
527
+ * `is_error` of `false` is one), a child a signal ended or a non-zero exit after a success, a tool the server
528
+ * ran, a reply the token limit cut off, then the text. Claude Code reports an API error as exit 1 with
529
+ * `subtype: "success"` and `is_error: true`, so the JSON on stdout is read before the exit code. Every
530
+ * failure carries the usage the result reports, summed as `sumUsage` does, since the model generated and
531
+ * billed those tokens whatever came after.
523
532
  */
524
533
  function readFinished(result, run, context) {
525
534
  const modelUsage = isRecord(result.modelUsage)
@@ -531,6 +540,8 @@ function readFinished(result, run, context) {
531
540
  throw fail('too-large', 'Claude Code refused the prompt as too long for the model\'s context');
532
541
  if (result.stop_reason === 'refusal')
533
542
  throw fail('refusal', 'model refused');
543
+ if (result.api_error === 'max_output_tokens')
544
+ throw fail('truncated', 'reply was cut off by the token limit');
534
545
  if (result.is_error !== false || result.subtype !== 'success')
535
546
  throw errorFailure(result, run, context, usage);
536
547
  if (run.signal !== null)
@@ -557,7 +568,7 @@ function readFinished(result, run, context) {
557
568
  * JSON result: a signal, a non-zero exit with a quote of stderr, or nothing at all, each a failure. Every
558
569
  * quoted text goes through `snippet`, redacted of the key.
559
570
  *
560
- * @throws ProviderError of the kind the failure is: `too-large`, `refusal`, `http`, `process` or `invalid-response`
571
+ * @throws ProviderError of the kind the failure is: `too-large`, `refusal`, `truncated`, `http`, `process` or `invalid-response`
561
572
  */
562
573
  export function readResult(run, context) {
563
574
  const result = parseResult(run.stdout);
@@ -887,7 +898,8 @@ async function requireVersion(launch, signal, fail) {
887
898
  * 1. exactly one message, a user message, else `unsupported`;
888
899
  * 2. a message that starts with `/` after white space, which `-p` would run as a command: `unsupported`;
889
900
  * 3. a message over `MAX_STDIN_BYTES` bytes: `too-large`;
890
- * 4. the size guard, with `CLAUDE_CODE_TEMPLATE_TOKENS` kept for the context Claude Code adds: `too-large`;
901
+ * 4. the size guard, with the reply budget, `maxTokens`, and `CLAUDE_CODE_TEMPLATE_TOKENS` kept for the
902
+ * context Claude Code adds: `too-large`;
891
903
  * 5. an aborted signal: `aborted`;
892
904
  * 6. a directory of its own, under the temporary directory, holding an empty working directory, `claude`'s
893
905
  * scratch directory and the system text's file: a failure to make it is `process`;
@@ -906,8 +918,22 @@ async function requireVersion(launch, signal, fail) {
906
918
  * 13. an aborted signal: `aborted`; else `readResult`'s reply or failure, with every credential of the
907
919
  * child's environment redacted from the text it quotes (`credentialValues`).
908
920
  *
909
- * No timeout is set: Claude Code retries a failed API call by itself, for minutes, and a deadline is the
910
- * caller's own (a signal).
921
+ * Claude Code retries a failed API call by itself, ten times by default, so the provider sets `API_TIMEOUT_MS`
922
+ * and `CLAUDE_CODE_MAX_RETRIES` in the child's environment from `timeoutMs` and `retries` (600000 ms and 2 by
923
+ * default) over any the environment held, and states no retry to the core, which would retry what Claude Code
924
+ * retried. It sets `CLAUDE_CODE_MAX_OUTPUT_TOKENS` the same way from `maxTokens` (16000 by default, where
925
+ * Claude Code asks for up to 128000 by itself), so the model's API bounds every reply. It states one deadline
926
+ * for the whole run, `timeoutMs` times `retries` plus one: Claude Code's own attempts and the waits between
927
+ * them, its start and the version check, and each reply's time after its headers all count against it, where
928
+ * `API_TIMEOUT_MS` limits only an attempt's wait for its headers. At it the core aborts the signal, which
929
+ * stops the child's group as step 11 says.
930
+ *
931
+ * It states its worst case from the count its size guard keeps, over the model turns of a run: in `schema`
932
+ * mode two, since the model answers by calling the schema tool and `claude` then makes a second turn after
933
+ * the tool's result, which carries the first reply as input, so `2 * (text + 4096) + 3 * maxTokens`; in
934
+ * `prompt` mode one, `text + 4096 + maxTokens`. It leaves out what Claude Code spends beyond that, a reply
935
+ * it continues after its limit, up to three times a turn, and its own retries: those count once the run
936
+ * reports its usage.
911
937
  *
912
938
  * @throws ConfigError with every problem of the options, before any request
913
939
  */
@@ -915,15 +941,24 @@ export function claudeCode(options) {
915
941
  const issues = claudeCodeIssues(options);
916
942
  if (issues.length > 0)
917
943
  throw new ConfigError(issues);
918
- const { id, model, contextTokens, auth = 'inherit', apiKey, structuredOutput = 'schema', command = 'claude' } = options;
944
+ const { id, model, contextTokens, maxTokens = DEFAULT_REPLY_TOKENS, auth = 'inherit', apiKey, structuredOutput = 'schema', command = 'claude', timeoutMs = DEFAULT_TIMEOUT_MS, retries = DEFAULT_RETRIES } = options;
945
+ const settings = { timeoutMs, retries, maxTokens };
919
946
  const args = [
920
947
  ...options.args ?? [],
921
948
  ];
922
949
  const env = Object.fromEntries(Object.entries(options.env ?? process.env));
923
- const budget = contextBudget(contextTokens, undefined, CLAUDE_CODE_TEMPLATE_TOKENS);
950
+ const budget = contextBudget(contextTokens, maxTokens, CLAUDE_CODE_TEMPLATE_TOKENS);
924
951
  return {
925
952
  id,
926
953
  model,
954
+ timeoutMs: timeoutMs * (retries + 1),
955
+ retries: 0,
956
+ worstCase: request => worstCaseTokens({
957
+ system: request.system,
958
+ messages: [...request.messages],
959
+ }, request.output, budget, structuredOutput === 'schema'
960
+ ? 2
961
+ : 1),
927
962
  async complete(request) {
928
963
  const fail = replyFailure(id);
929
964
  const message = messageOf(request, fail);
@@ -938,7 +973,7 @@ export function claudeCode(options) {
938
973
  const untrack = trackRun(live);
939
974
  try {
940
975
  throwIfAborted(signal, fail);
941
- const environment = childEnv(env, auth, apiKey, run.tmp);
976
+ const environment = childEnv(env, auth, apiKey, run.tmp, settings);
942
977
  await requireVersion({
943
978
  command,
944
979
  args: [],
@@ -5,7 +5,10 @@ export type GeminiOptions = HttpProviderOptions;
5
5
  /**
6
6
  * A provider for the Gemini API's `generateContent`. The key, when there is one, travels only in the
7
7
  * header `auth` names, `x-goog-api-key` by default (invariant I1), never in the `key` query parameter. It
8
- * refuses, before any request, a request that may not fit `contextTokens`.
8
+ * refuses, before any request, a request that may not fit `contextTokens`. It sends the reply's limit,
9
+ * `maxTokens` else the budget of the size guard, as `generationConfig.maxOutputTokens`, so the server bounds
10
+ * a reply's length. It states its worst case from the count its size guard keeps: the text it sends, the
11
+ * template reserve and that budget.
9
12
  *
10
13
  * @throws ConfigError with every problem of the options, before any request
11
14
  */
@@ -1,9 +1,10 @@
1
1
  import { issuePath } from "../core/errors.js";
2
+ import { DEFAULT_RETRIES, DEFAULT_TIMEOUT_MS } from "../core/ports.js";
2
3
  import { postJson, snippet } from "./http.js";
3
4
  import { shapeMessages } from "./messages.js";
4
- import { bodyKeyForm, isRecord, mergeBody, prepareHttp, spellingIssues, unlessEmpty } from "./options.js";
5
+ import { bodyKeyForm, isRecord, mergeBody, prepareHttp, spellingIssues } from "./options.js";
5
6
  import { endedEarly, joinedText, replyFailure, tokenUsage } from "./reply.js";
6
- import { checkFits, contextBudget } from "./size.js";
7
+ import { checkFits, contextBudget, worstCaseTokens } from "./size.js";
7
8
  /** A Gemini model id, such as `gemini-3.8-flash`. It goes in the URL's path, so it holds no `/`, `?`, `#`, `%` or `:`. */
8
9
  const MODEL_ID = /^[a-z0-9][a-z0-9.-]*$/i;
9
10
  /** The longest block reason quoted, in characters: the pattern's bound and the quote's cut. */
@@ -33,6 +34,50 @@ const FILTERED = new Set([
33
34
  'SPII',
34
35
  'IMAGE_SAFETY',
35
36
  ]);
37
+ const RETRY_INFO = 'type.googleapis.com/google.rpc.RetryInfo';
38
+ const QUOTA_FAILURE = 'type.googleapis.com/google.rpc.QuotaFailure';
39
+ /** A `retryDelay` as Google's protobuf JSON writes a duration: whole or fractional seconds, nine digits at most. */
40
+ const RETRY_DELAY = /^(\d+(?:\.\d{1,9})?)s$/;
41
+ /** The part of a quota's id that names a per-day limit, which no wait of seconds lifts. */
42
+ const PER_DAY = 'PerDay';
43
+ /** The entries of `list` that are objects of the given `@type`, when it is a list. */
44
+ function detailsOfType(list, type) {
45
+ return Array.isArray(list)
46
+ ? list.filter((entry) => isRecord(entry) && entry['@type'] === type)
47
+ : [];
48
+ }
49
+ /** A `retryDelay` as milliseconds, when it is a positive duration in seconds. */
50
+ function delayMs(retryDelay) {
51
+ const match = typeof retryDelay === 'string'
52
+ ? RETRY_DELAY.exec(retryDelay)
53
+ : null;
54
+ const ms = Number(match?.[1]) * 1000;
55
+ return Number.isFinite(ms) && ms > 0
56
+ ? ms
57
+ : undefined;
58
+ }
59
+ /**
60
+ * What an error body of Google's `{ error: { details } }` says of a retry, read defensively: the first
61
+ * `RetryInfo` with a valid `retryDelay` is the wait, and a `QuotaFailure` violation whose `quotaId` names
62
+ * a per-day limit turns the retry off, whatever the delay says, since the quota is back only the next day.
63
+ * Only numbers and a verdict leave this function: no text of the body does.
64
+ */
65
+ function errorHints(body) {
66
+ const details = isRecord(body) && isRecord(body.error)
67
+ ? body.error.details
68
+ : undefined;
69
+ const retryAfterMs = detailsOfType(details, RETRY_INFO).map(info => delayMs(info.retryDelay)).find(ms => ms !== undefined);
70
+ const perDay = detailsOfType(details, QUOTA_FAILURE).some(failure => Array.isArray(failure.violations)
71
+ && failure.violations.some(violation => isRecord(violation) && typeof violation.quotaId === 'string' && violation.quotaId.includes(PER_DAY)));
72
+ return {
73
+ ...(retryAfterMs === undefined
74
+ ? {}
75
+ : { retryAfterMs }),
76
+ ...(perDay
77
+ ? { retryable: false }
78
+ : {}),
79
+ };
80
+ }
36
81
  /** A `key` query parameter, in any letter case, would put the key in the URL: it travels only in the header `auth` names. */
37
82
  function keyParameterIssues(id, query) {
38
83
  return Object.keys(query)
@@ -58,18 +103,18 @@ function generationConfigIssues(id, extraBody) {
58
103
  ];
59
104
  });
60
105
  }
61
- /** The generation config of a request, or undefined when it would be empty. */
62
- function generationConfig({ temperature, maxTokens, structuredOutput }, output) {
63
- return unlessEmpty({
106
+ /** The generation config of a request: it always holds the reply's limit. */
107
+ function generationConfig({ temperature, replyTokens, structuredOutput }, output) {
108
+ return {
64
109
  temperature: temperature ?? undefined,
65
- maxOutputTokens: maxTokens,
110
+ maxOutputTokens: replyTokens,
66
111
  responseMimeType: structuredOutput === 'prompt'
67
112
  ? undefined
68
113
  : 'application/json',
69
114
  responseJsonSchema: structuredOutput === 'schema'
70
115
  ? output.schema
71
116
  : undefined,
72
- });
117
+ };
73
118
  }
74
119
  /**
75
120
  * Turn a `generateContent` reply into text, or a `ProviderError`. Every property is read defensively: the
@@ -124,12 +169,15 @@ function readReply(reply, { id, model }, redact) {
124
169
  /**
125
170
  * A provider for the Gemini API's `generateContent`. The key, when there is one, travels only in the
126
171
  * header `auth` names, `x-goog-api-key` by default (invariant I1), never in the `key` query parameter. It
127
- * refuses, before any request, a request that may not fit `contextTokens`.
172
+ * refuses, before any request, a request that may not fit `contextTokens`. It sends the reply's limit,
173
+ * `maxTokens` else the budget of the size guard, as `generationConfig.maxOutputTokens`, so the server bounds
174
+ * a reply's length. It states its worst case from the count its size guard keeps: the text it sends, the
175
+ * template reserve and that budget.
128
176
  *
129
177
  * @throws ConfigError with every problem of the options, before any request
130
178
  */
131
179
  export function gemini(options) {
132
- const { id, model, auth = { header: 'x-goog-api-key' }, query, temperature, maxTokens, contextTokens, systemPrompt = 'native', structuredOutput = 'json' } = options;
180
+ const { id, model, auth = { header: 'x-goog-api-key' }, query, temperature, maxTokens, contextTokens, systemPrompt = 'native', structuredOutput = 'json', timeoutMs = DEFAULT_TIMEOUT_MS, retries = DEFAULT_RETRIES } = options;
133
181
  const modelId = typeof model === 'string'
134
182
  ? model.replace(/^models\//, '')
135
183
  : '';
@@ -147,10 +195,13 @@ export function gemini(options) {
147
195
  return {
148
196
  id,
149
197
  model,
198
+ timeoutMs,
199
+ retries,
200
+ worstCase: request => worstCaseTokens(shapeMessages(request, systemPrompt), request.output, budget),
150
201
  async complete(request) {
151
202
  const { system, messages } = shapeMessages(request, systemPrompt);
152
203
  checkFits(id, { system, messages }, request.output, budget);
153
- // JSON.stringify drops the undefined fields: no systemInstruction inline, no generationConfig when it is empty.
204
+ // JSON.stringify drops the undefined fields: no systemInstruction inline, no temperature unless set.
154
205
  const reply = await postJson({
155
206
  providerId: id,
156
207
  url,
@@ -171,10 +222,11 @@ export function gemini(options) {
171
222
  { text: system },
172
223
  ],
173
224
  },
174
- generationConfig: generationConfig({ temperature, maxTokens, structuredOutput }, request.output),
225
+ generationConfig: generationConfig({ temperature, replyTokens: budget.replyTokens, structuredOutput }, request.output),
175
226
  }, extraBody),
176
227
  signal: request.signal,
177
228
  redact,
229
+ errorHints,
178
230
  });
179
231
  return readReply(reply, { id, model }, redact);
180
232
  },
@@ -1,3 +1,11 @@
1
+ /**
2
+ * What an adapter reads of a failed reply's body that `postJson` cannot: a wait the server asks for, in
3
+ * milliseconds, and a reason never to retry. A hook can add a hint and turn a retry off, never on.
4
+ */
5
+ export interface ErrorHints {
6
+ readonly retryAfterMs?: number;
7
+ readonly retryable?: false;
8
+ }
1
9
  export interface PostJsonOptions {
2
10
  providerId: string;
3
11
  url: string;
@@ -6,6 +14,8 @@ export interface PostJsonOptions {
6
14
  signal?: AbortSignal;
7
15
  /** Values redacted from any server text that echoes them: the key, the base URL's path and the header values. */
8
16
  redact?: readonly string[];
17
+ /** What the adapter reads of a failed reply's body, handed the body parsed as JSON, or `undefined` when it is none. */
18
+ errorHints?: (body: unknown) => ErrorHints;
9
19
  }
10
20
  /**
11
21
  * Server or model text made safe to put in an error message. The text is first cut to 64 KiB, as much as
@@ -40,11 +50,46 @@ export declare function originOf(url: string): string;
40
50
  * Anything that is not a string URL with the `http:` or `https:` scheme has none.
41
51
  */
42
52
  export declare function httpOrigin(url: unknown): string | undefined;
53
+ /**
54
+ * Node's global dispatcher handed each request with both of undici's timers off, the 300-second
55
+ * limits on the headers and on the body, or undefined when the runtime has none: Bun's `fetch`
56
+ * never reads a dispatcher, and its own timer goes off with `timeout: false`. The global is read at
57
+ * each request, never kept, so a proxy agent an operator set still carries it. The delegate calls
58
+ * the global's `dispatch` as its method, with the request's options and both timeouts at 0 (none),
59
+ * and the same handler.
60
+ */
61
+ export declare function timersOff(): {
62
+ dispatch: (options: object, handler: unknown) => unknown;
63
+ } | undefined;
64
+ /**
65
+ * The wait a failed reply asks for, in milliseconds: `retry-after-ms`, then `retry-after` in seconds, then
66
+ * `retry-after` as an HTTP date less `now`, the wall clock in milliseconds. The first that is a positive
67
+ * finite number is the hint. A value is read as decimal digits with an optional fraction, or as an
68
+ * IMF-fixdate matched by its shape before `Date.parse` reads it, since the runtimes read a bare `1` or
69
+ * `120` as a year and the other date forms as local time. Anything else is no hint, and the header is
70
+ * never copied anywhere.
71
+ */
72
+ export declare function retryAfterHint(headers: Headers, now: number): number | undefined;
73
+ /**
74
+ * What the body of a failed reply says of a retry that the vendors' own codes settle: `false` for a used-up
75
+ * credit, spend limit or quota (OpenAI's `error.code`, or its `error.type` for `insufficient_quota`, and
76
+ * Anthropic's `error.details.error_code`), `true` for OpenRouter's 402 of its in-flight budget when the
77
+ * reply is `hinted` with a wait, else `undefined`, and the status decides. A code is only compared, never
78
+ * copied. This checks objects with a local test, since `options.ts` imports this module.
79
+ */
80
+ export declare function vendorRetryable(body: unknown, status: number, hinted: boolean): boolean | undefined;
43
81
  /**
44
82
  * POST a JSON body and return the parsed JSON reply. A redirect is not followed: it is an `http` error,
45
- * so a key sent in any header never reaches another endpoint. A reply body over 16 MiB is refused
46
- * unread. Every failure is a `ProviderError` without a `cause`: the runtime's own error text can hold
47
- * the URL with its credentials or a header value, so it is never copied, and no header value appears in
48
- * a message.
83
+ * so a key sent in any header never reaches another endpoint. The runtimes' own timers are off, so
84
+ * the core's deadline is the only one: a long reply of a thinking model is not cut at 300 seconds.
85
+ * A reply body over 16 MiB is refused unread. Every failure is a `ProviderError` without a `cause`:
86
+ * the runtime's own error text can hold the URL with its credentials or a header value, so it is
87
+ * never copied, and no header value appears in a message.
88
+ *
89
+ * A failed reply's error quotes the body in its message, as it always did, and carries what the reply
90
+ * says of a retry as a number and a boolean, never as text: `retryAfterMs` from `retry-after-ms` or
91
+ * `retry-after`, else from `errorHints`, and `retryable` when the reply settles it, which a "never" wins:
92
+ * `x-should-retry: false`, a used-up credit, spend limit or quota, or a hook's, else `x-should-retry: true`
93
+ * or OpenRouter's in-flight 402 with a hint, else the status decides.
49
94
  */
50
95
  export declare function postJson<T>(options: PostJsonOptions): Promise<T>;