claude-autorouter 0.3.4 → 0.3.5

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/.env.example CHANGED
@@ -7,6 +7,10 @@ AUTOROUTER_EVALUATOR=jev
7
7
  AUTOROUTER_STATUSLINE=1
8
8
  # Optional metadata logs on stderr. Redirect stderr to a file when using the UI.
9
9
  # AUTOROUTER_DEBUG=1
10
+ # Optional: allow two tool-free Stop-hook continuations, then end the turn on
11
+ # the third block. Applies to /goal and all Stop/SubagentStop hooks.
12
+ # Unset keeps Claude's default (currently 8); 0 DISABLES the cap.
13
+ # CLAUDE_CODE_STOP_HOOK_BLOCK_CAP=2
10
14
  # Required for Jev only; subscription + Ollama needs no API keys.
11
15
  TYPESAFE_API_KEY=
12
16
  # For API billing instead, set AUTOROUTER_AUTH_MODE=api-key and fill this in.
package/README.md CHANGED
@@ -104,5 +104,6 @@ Historical measurements before 0.3.2, on a 16 GiB M4: Tev1 0.8B matched 18/24 he
104
104
  - The selected evaluator receives bounded excerpts that can contain source code and tool results: TypeSafe with Jev, or the local service with Ollama. Jev also receives system-text excerpts; the local path excludes Claude's executor system instructions. Anthropic receives the complete request. Images, document payloads, and private thinking are omitted from classifier input. [Data flow and authentication](docs/reference.md#data-flow-and-authentication).
105
105
  - Subscription access and usage limits still apply. Model switches can reduce cache reuse; cheaper token prices do not guarantee cheaper completed tasks. Run ordinary `claude` to bypass routing.
106
106
  - The launcher is quiet by default. Use `AUTOROUTER_DEBUG=1` for metadata diagnostics or `AUTOROUTER_STATUSLINE=0` to retain your existing status line. [Troubleshooting](docs/reference.md#troubleshooting).
107
+ - For blocked `/goal` loops, optionally launch with `env CLAUDE_CODE_STOP_HOOK_BLOCK_CAP=2 claude-autorouter claude`. Claude then ends the turn on the third consecutive blocking verdict without tool use, leaving the goal unmet. This also affects other Stop/SubagentStop hooks; defaults are unchanged. [Scope and saved configuration](docs/reference.md#shorter-stop-hook-loops-opt-in).
107
108
 
108
109
  [Reference](docs/reference.md) · [Development and validation](docs/development.md) · [CI and npm release setup](docs/releasing.md) · [Apache-2.0 license](LICENSE)
@@ -23,6 +23,7 @@ Usage:
23
23
  claude-autorouter setup [--auth-mode subscription|api-key] [--force]
24
24
  [--evaluator jev|ollama]
25
25
  [--ollama-model MODEL] [--ollama-timeout-ms N] [--pull]
26
+ [--stop-hook-block-cap N]
26
27
  claude-autorouter doctor
27
28
  claude-autorouter claude [Claude Code arguments]
28
29
  claude-autorouter serve
@@ -47,6 +48,9 @@ AUTOROUTER_AUTH_MODE=subscription uses your saved Claude Code login.
47
48
  Without setup, AUTOROUTER_AUTH_MODE defaults to api-key and also requires ANTHROPIC_API_KEY.
48
49
  AUTOROUTER_CLIENT_PROFILE=compatible (default) enables all three routing tiers.
49
50
  Use AUTOROUTER_CLIENT_PROFILE=native to retain Claude Code's own model/thinking settings.
51
+ Optional CLAUDE_CODE_STOP_HOOK_BLOCK_CAP=N limits consecutive tool-free Stop-hook continuations.
52
+ Use 2 to stop on the third block; applies to /goal and all Stop/SubagentStop hooks.
53
+ Unset preserves Claude's default; 0 disables the cap. Setup --stop-hook-block-cap N saves it.
50
54
  Standalone serve also requires AUTOROUTER_TOKEN (at least 16 characters).
51
55
  The claude launcher creates a temporary credential and an ephemeral port.
52
56
  It enables an AutoRouter status line for this session (AUTOROUTER_STATUSLINE=0 to opt out).
package/docs/reference.md CHANGED
@@ -6,6 +6,7 @@
6
6
  | --- | --- |
7
7
  | `claude-autorouter setup` | Save subscription-mode configuration and a Jev key |
8
8
  | `claude-autorouter setup --auth-mode api-key` | Configure Jev and Anthropic API-key billing |
9
+ | `claude-autorouter setup --stop-hook-block-cap 2` | Opt into a shorter native Stop-hook continuation cap during setup |
9
10
  | `claude-autorouter setup --evaluator ollama --pull` | Configure the native local evaluator and download its selected model if missing |
10
11
  | `claude-autorouter setup --evaluator ollama --ollama-timeout-ms 0 --force` | Save a disabled runtime evaluator deadline |
11
12
  | `claude-autorouter setup --force` | Replace an existing user config |
@@ -45,6 +46,7 @@ For an environment-only subscription launch, set `AUTOROUTER_AUTH_MODE=subscript
45
46
  | `AUTOROUTER_CLIENT_PROFILE` | `compatible` | `native` retains Claude's own model and thinking settings |
46
47
  | `AUTOROUTER_STATUSLINE` | enabled | `0` retains your existing status line |
47
48
  | `AUTOROUTER_DEBUG` | off | `1` enables launcher metadata logs on stderr |
49
+ | `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` | unset; Claude currently uses `8` | Optional cap on consecutive Stop/SubagentStop continuations without tool use; `0` disables the cap |
48
50
  | `ENABLE_TOOL_SEARCH` | `true` in launcher when unset | Load MCP tool definitions on demand; explicit values are preserved |
49
51
  | `AUTOROUTER_HAIKU_MODEL` | `claude-haiku-4-5-20251001` | Routine tier |
50
52
  | `AUTOROUTER_SONNET_MODEL` | `claude-sonnet-5` | Standard tier |
@@ -238,6 +240,26 @@ The launcher is quiet by default. Standalone `serve` logs to stderr by default.
238
240
 
239
241
  If the worker reports a blocker but the checker keeps returning “not yet met,” Claude can repeat its answer until its no-progress guard pauses the goal. Repeated tool calls can keep the loop running longer. Use `/goal clear` to end the loop, resolve the external blocker, and set the goal again. For tasks that may require human action, explicitly allow reporting a blocker as an alternative end condition, for example: `/goal Verify the discrepancy against upstream main and run the relevant tests, or report an external authorization blocker and stop.` This changes what counts as completion; AutoRouter does not declare blocked work successful or rewrite goal instructions. See [Claude Code goal evaluation](https://code.claude.com/docs/en/goal#how-evaluation-works).
240
242
 
243
+ ### Shorter Stop-hook loops (opt-in)
244
+
245
+ To return control sooner when a goal keeps reporting the same unmet condition, set Claude's native continuation cap for one launch:
246
+
247
+ ```sh
248
+ env CLAUDE_CODE_STOP_HOOK_BLOCK_CAP=2 claude-autorouter claude
249
+ ```
250
+
251
+ This permits two consecutive continuations without tool use; the third blocking verdict ends the turn. The goal remains set and unmet, and a new message can resume it. Tool activity resets the counter, so this is not a total turn or request limit and cannot bound repeated failed tool calls. It applies to **all Stop and SubagentStop hooks**, including `/goal`. A smaller cap can pause useful work sooner. Unset preserves Claude's default (currently `8`); **`0` disables the guard**. AutoRouter does not install a Stop hook or change completion verdicts. See [Claude's environment-variable reference](https://code.claude.com/docs/en/env-vars) and [Stop-hook loop behavior](https://code.claude.com/docs/en/hooks#stop).
252
+
253
+ The environment-only command also works on AutoRouter 0.3.4. Saved configuration and the setup flag require AutoRouter 0.3.5 or newer. To save the preference, add the following property to your existing AutoRouter config JSON, preserving its other values:
254
+
255
+ ```json
256
+ "CLAUDE_CODE_STOP_HOOK_BLOCK_CAP": "2"
257
+ ```
258
+
259
+ For a new configuration, use `claude-autorouter setup --stop-hook-block-cap 2`; the flag works with either evaluator and overrides the environment during setup. Runtime environment values override saved configuration. `setup --force` replaces the entire config, so keep your existing evaluator/authentication options if using it. `doctor` reports the cap when configured. AutoRouter accepts nonnegative safe integers and leaves the setting absent unless you opt in.
260
+
261
+ ### Other session issues
262
+
241
263
  **After restarting mid-conversation:** turn state is in memory and expires after 30 minutes. Unknown continuations preserve the incoming model. Start a fresh conversation when restarting around signed thinking; AutoRouter cannot reconstruct the prior actual model from lost turn state.
242
264
 
243
265
  Switching models can lose prompt-cache reuse. A cheaper price per token does not guarantee a cheaper or faster task. Only requests using Claude's configured base URL are visible to this proxy. Alternate provider modes such as Bedrock, Vertex, Foundry, Mantle, and `ANTHROPIC_AWS` are unsupported; unset their enable flags before launching. Use ordinary `claude` to bypass routing.
package/docs/releasing.md CHANGED
@@ -10,6 +10,8 @@ Version `0.3.3` fixes HTTP 400 errors when a compatible request with disabled th
10
10
 
11
11
  Version `0.3.4` preserves the selected model across Stop-hook feedback for the same prompt, including `/goal` commands that omit the gateway prompt-ID header. Recognized goal feedback remains conversation context rather than replacing the human task in evaluator excerpts. Goal-checker verdicts remain unchanged; external authorization blockers can still cause Claude's own goal loop to repeat. See [goal troubleshooting](reference.md#troubleshooting).
12
12
 
13
+ Version `0.3.5` adds opt-in saved configuration for Claude's native `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`, with `setup --stop-hook-block-cap N`, validation, and `doctor` reporting. A value of `2` permits two consecutive Stop-hook continuations without tool use and ends the turn on the third blocking verdict, leaving an unmet goal set. This affects all Stop/SubagentStop hooks, and tool activity resets the counter. Defaults and completion verdicts are unchanged; `0` disables the guard. See [shorter Stop-hook loops](reference.md#shorter-stop-hook-loops-opt-in).
14
+
13
15
  The GitHub repository is private. Publishing to npm makes the tarball's runtime source, README, configuration example, license, and shipped documentation public. Model weights, user configuration, credentials, transcripts, local artifacts, and test fixtures are excluded. Review the archive before the first publication and whenever the package allowlist changes.
14
16
 
15
17
  ## What runs automatically
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-autorouter",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "A Claude Code model router with Jev and local Ollama System One evaluators",
package/src/auth.mjs CHANGED
@@ -16,6 +16,11 @@ export function isSubscriptionRequest(headers) {
16
16
 
17
17
  export function buildClaudeEnv(config, baseUrl, parent = process.env) {
18
18
  const env = { ...parent, ANTHROPIC_BASE_URL: baseUrl, CLAUDE_CODE_GATEWAY_HINT_HEADERS: '1' };
19
+ // Opt into Claude's own loop guard without installing hooks or altering
20
+ // their verdicts. An unset cap leaves Claude's default in control.
21
+ if (env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP === undefined && config.stopHookBlockCap !== undefined) {
22
+ env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP = String(config.stopHookBlockCap);
23
+ }
19
24
  // Claude Code otherwise disables MCP tool search for a non-first-party
20
25
  // base URL and loads every schema into context. This proxy preserves both
21
26
  // tool_reference blocks and their beta headers. Respect explicit choices.
package/src/config.mjs CHANGED
@@ -2,6 +2,15 @@ import { DEFAULT_OLLAMA_MODEL, defaultOllamaTimeoutMs, validateOllamaEndpoint, v
2
2
 
3
3
  export const TIERS = ['haiku', 'sonnet', 'opus'];
4
4
 
5
+ export function parseStopHookBlockCap(value, name = 'CLAUDE_CODE_STOP_HOOK_BLOCK_CAP') {
6
+ if (!['string', 'number'].includes(typeof value)
7
+ || (typeof value === 'string' && !/^[0-9]+$/.test(value.trim()))
8
+ || !Number.isSafeInteger(Number(value)) || Number(value) < 0) {
9
+ throw new Error(`${name} requires a nonnegative safe integer (0 disables the Stop-hook continuation cap)`);
10
+ }
11
+ return Number(value);
12
+ }
13
+
5
14
  function number(env, key, fallback, min, max, integer = true) {
6
15
  const value = Number(env[key] ?? fallback);
7
16
  if (!Number.isFinite(value) || value < min || value > max || (integer && !Number.isInteger(value))) {
@@ -50,6 +59,8 @@ export function readConfig(env = process.env) {
50
59
  evaluator,
51
60
  authMode,
52
61
  clientProfile,
62
+ stopHookBlockCap: env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP === undefined
63
+ ? undefined : parseStopHookBlockCap(env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP),
53
64
  anthropicKey: authMode === 'api-key' ? env.ANTHROPIC_API_KEY : undefined,
54
65
  jevKey: env.TYPESAFE_API_KEY,
55
66
  localToken: env.AUTOROUTER_TOKEN,
@@ -3,7 +3,7 @@ import { existsSync } from 'node:fs';
3
3
  import { createInterface } from 'node:readline';
4
4
  import { Writable } from 'node:stream';
5
5
  import { promisify } from 'node:util';
6
- import { readConfig, requireKeys } from './config.mjs';
6
+ import { readConfig, requireKeys, parseStopHookBlockCap } from './config.mjs';
7
7
  import { buildClaudeEnv, conflictingProviders, LOCAL_AUTH_HEADER } from './auth.mjs';
8
8
  import { getConfigPath, loadUserConfig, saveUserConfig } from './user-config.mjs';
9
9
  import { DEFAULT_OLLAMA_MODEL, validateOllamaModel } from './ollama-models.mjs';
@@ -14,6 +14,10 @@ const execute = promisify(execFile);
14
14
  export const ollamaDeadlineText = timeoutMs => timeoutMs === 0
15
15
  ? 'routing deadline disabled' : `routing deadline ${timeoutMs} ms per request`;
16
16
 
17
+ const stopHookCapText = cap => cap === 0
18
+ ? 'Claude Stop/SubagentStop continuation cap disabled (0).'
19
+ : `Claude Stop/SubagentStop cap: ${cap} continuations without tool use.`;
20
+
17
21
  // Readline manages editing and restores terminal state; its output is discarded
18
22
  // so neither typing nor pasted credentials are echoed to the terminal.
19
23
  export async function askSecret(label, { input = process.stdin, output = process.stderr } = {}) {
@@ -40,6 +44,7 @@ export async function setup(args, {
40
44
  let evaluator = env.AUTOROUTER_EVALUATOR ?? 'jev';
41
45
  let model;
42
46
  let ollamaTimeoutMs;
47
+ let stopHookBlockCap = env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP;
43
48
  let pull = false;
44
49
  let overwrite = false;
45
50
  for (let i = 0; i < args.length; i++) {
@@ -53,19 +58,24 @@ export async function setup(args, {
53
58
  }
54
59
  ollamaTimeoutMs = String(Number(value));
55
60
  }
61
+ else if (args[i] === '--stop-hook-block-cap') {
62
+ stopHookBlockCap = parseStopHookBlockCap(args[++i], '--stop-hook-block-cap');
63
+ }
56
64
  else if (args[i] === '--pull') pull = true;
57
65
  else if (args[i] === '--force') overwrite = true;
58
- else throw new Error('Usage: claude-autorouter setup [--auth-mode subscription|api-key] [--evaluator jev|ollama] [--ollama-model TAG] [--ollama-timeout-ms N] [--pull] [--force]');
66
+ else throw new Error('Usage: claude-autorouter setup [--auth-mode subscription|api-key] [--evaluator jev|ollama] [--ollama-model TAG] [--ollama-timeout-ms N] [--stop-hook-block-cap N] [--pull] [--force]');
59
67
  }
60
68
  if (!['subscription', 'api-key'].includes(authMode)) throw new Error('--auth-mode must be subscription or api-key');
61
69
  if (!['jev', 'ollama'].includes(evaluator)) throw new Error('--evaluator must be jev or ollama');
62
70
  if (evaluator !== 'ollama' && (model !== undefined || ollamaTimeoutMs !== undefined || pull)) throw new Error('Ollama model, deadline and download options require --evaluator ollama');
71
+ if (stopHookBlockCap !== undefined) stopHookBlockCap = parseStopHookBlockCap(stopHookBlockCap);
63
72
  const path = getConfigPath(env);
64
73
  if (!overwrite && existsSync(path)) throw new Error('AutoRouter configuration already exists. Use setup --force to replace it.');
65
74
  write(evaluator === 'ollama'
66
75
  ? 'AutoRouter evaluates bounded prompt excerpts locally with Ollama. Complete requests still go to Anthropic.'
67
76
  : 'AutoRouter sends bounded prompt excerpts to TypeSafe Jev and complete requests to Anthropic.');
68
77
  const values = { AUTOROUTER_AUTH_MODE: authMode, AUTOROUTER_CLIENT_PROFILE: 'compatible', AUTOROUTER_EVALUATOR: evaluator };
78
+ if (stopHookBlockCap !== undefined) values.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP = String(stopHookBlockCap);
69
79
  if (evaluator === 'ollama') {
70
80
  values.AUTOROUTER_OLLAMA_MODEL = validateOllamaModel(model ?? env.AUTOROUTER_OLLAMA_MODEL ?? DEFAULT_OLLAMA_MODEL);
71
81
  for (const key of ['AUTOROUTER_OLLAMA_URL', 'AUTOROUTER_OLLAMA_TIMEOUT_MS', 'AUTOROUTER_OLLAMA_KEEP_ALIVE']) {
@@ -81,6 +91,7 @@ export async function setup(args, {
81
91
  }
82
92
  const config = readConfig(values);
83
93
  requireKeys(config);
94
+ if (config.stopHookBlockCap !== undefined) write(stopHookCapText(config.stopHookBlockCap));
84
95
  if (evaluator === 'ollama') {
85
96
  write(`Local evaluator: ${config.ollamaModel}; ${ollamaDeadlineText(config.ollamaTimeoutMs)}.`);
86
97
  const controller = new AbortController();
@@ -115,6 +126,7 @@ export async function doctor({ env = process.env, write = console.log, run = exe
115
126
  for (const key of conflictingProviders(effectiveEnv)) {
116
127
  report(false, `Unset ${key}; AutoRouter uses the Anthropic Messages API`);
117
128
  }
129
+ if (config?.stopHookBlockCap !== undefined) write(stopHookCapText(config.stopHookBlockCap));
118
130
  if (config?.evaluator === 'ollama') {
119
131
  write(`Local evaluator: ${config.ollamaModel}; ${ollamaDeadlineText(config.ollamaTimeoutMs)}.`);
120
132
  write('Model availability is checked below; classification speed and accuracy are not tested.');
@@ -13,7 +13,7 @@ const CONFIG_KEYS = new Set([
13
13
  'AUTOROUTER_HAIKU_MODEL', 'AUTOROUTER_SONNET_MODEL', 'AUTOROUTER_OPUS_MODEL',
14
14
  'AUTOROUTER_PORT', 'AUTOROUTER_JEV_TIMEOUT_MS', 'AUTOROUTER_TOKEN_COUNT_TIMEOUT_MS',
15
15
  'AUTOROUTER_MIN_CONFIDENCE', 'AUTOROUTER_STATUSLINE', 'AUTOROUTER_DEBUG',
16
- 'ENABLE_TOOL_SEARCH',
16
+ 'ENABLE_TOOL_SEARCH', 'CLAUDE_CODE_STOP_HOOK_BLOCK_CAP',
17
17
  'AUTOROUTER_EVALUATOR', 'AUTOROUTER_OLLAMA_URL', 'AUTOROUTER_OLLAMA_MODEL',
18
18
  'AUTOROUTER_OLLAMA_TIMEOUT_MS', 'AUTOROUTER_OLLAMA_KEEP_ALIVE',
19
19
  ]);