Skip to content
Back to search

eigenwise-toolshed

MarketplaceWorks with Claude CodeGitHub

Eigenwise's toolshed of Claude Code plugins.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Eigenwise/eigenwise-toolshed with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Eigenwise/eigenwise-toolshed'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/eigenwise--eigenwise-toolshed/badge.svg)](/listings/eigenwise--eigenwise-toolshed)

HTML

<a href="/listings/eigenwise--eigenwise-toolshed"><img src="/api/listings/eigenwise--eigenwise-toolshed/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Use the same marketplace with the scope you want:

/plugin marketplace add Eigenwise/eigenwise-toolshed
/plugin install <plugin-name>@eigenwise-toolshed --scope project

Replace `<plugin-name>` with `sidequest`, `model-gateway`, `observability`, `codebase-mapper`, `live-rules`, or `quartermaster`. Use `--scope user` for a plugin you want in every project, or `--scope local` when it should stay out of shared settings. Reload plugins or start a new session after an install. The [plugin guides](https://eigenwise.github.io/eigenwise-toolshed/getting-started/) cover the first workflow for each one.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 171 lines
  1. {
  2. "name": "eigenwise-toolshed",
  3. "owner": {
  4. "name": "Eigenwise",
  5. "email": "kenny@eigenwise.io"
  6. },
  7. "description": "Eigenwise's toolshed of Claude Code plugins.",
  8. "version": "3.625.0",
  9. "plugins": [
  10. {
  11. "name": "observability",
  12. "source": "./plugins/observability",
  13. "description": "Local usage board for Claude Code. A hooks module records one metadata row per turn (exact engine cost, tokens by model, tool calls, agent spawns, context fill, rate-limit windows) into a per-project JSONL ledger under your Claude config directory, and /observability:board opens a self-contained HTML board. Recording is off until /observability:track on in a project. No server, no network, nothing leaves the machine.",
  14. "version": "1.1.1",
  15. "author": {
  16. "name": "Eigenwise"
  17. },
  18. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/observability",
  19. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  20. "license": "MIT",
  21. "category": "productivity",
  22. "keywords": [
  23. "observability",
  24. "telemetry",
  25. "opentelemetry",
  26. "grafana",
  27. "statusline",
  28. "metrics",
  29. "tokens",
  30. "cost"
  31. ]
  32. },
  33. {
  34. "name": "model-gateway",
  35. "source": "./plugins/model-gateway",
  36. "description": "Your ChatGPT/Codex and Grok subscription models in Claude Code's /model picker. A local gateway routes claude-gpt-* models to OpenAI's Codex backend, claude-grok-* models to Grok, and everything else to api.anthropic.com, so you switch between Claude, GPT-5.x, and Grok mid-session like any other model. No API keys.",
  37. "version": "0.56.3",
  38. "author": {
  39. "name": "Eigenwise"
  40. },
  41. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/model-gateway",
  42. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  43. "license": "MIT",
  44. "category": "development",
  45. "keywords": [
  46. "codex",
  47. "openai",
  48. "gpt",
  49. "chatgpt",
  50. "model-picker",
  51. "gateway",
  52. "proxy",
  53. "subscription"
  54. ]
  55. },
  56. {
  57. "name": "sidequest",
  58. "source": "./plugins/sidequest",
  59. "description": "A local work board and orchestration loop for Claude Code. Every task saved as a ticket survives context compaction and new sessions, with instructions, status, and recorded discussion kept on the board. Categories route tickets to a model and effort; token-gated executors return verified work for review and integration. A self-hosted Kanban dashboard spans your projects.",
  60. "version": "6.10.2",
  61. "author": {
  62. "name": "Eigenwise"
  63. },
  64. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/sidequest",
  65. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  66. "license": "MIT",
  67. "category": "productivity",
  68. "keywords": [
  69. "tickets",
  70. "kanban",
  71. "trello",
  72. "board",
  73. "issues",
  74. "todo",
  75. "dashboard",
  76. "capture"
  77. ]
  78. },
  79. {
  80. "name": "codebase-mapper",
  81. "source": "./plugins/codebase-mapper",
  82. "description": "A self-maintaining codebase map: atomic docs Claude loads at the start of each session and keeps in sync as the code changes. Any stack; greenfield or existing.",
  83. "version": "2.15.10",
  84. "author": {
  85. "name": "Eigenwise"
  86. },
  87. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/codebase-mapper",
  88. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  89. "license": "MIT",
  90. "category": "documentation",
  91. "keywords": [
  92. "documentation",
  93. "codebase",
  94. "mapping",
  95. "context",
  96. "grounding",
  97. "onboarding",
  98. "architecture",
  99. "self-maintaining"
  100. ]
  101. },
  102. {
  103. "name": "quartermaster",
  104. "source": "./plugins/quartermaster",
  105. "description": "Set up a project from your existing Claude Code habits, keep Toolshed installs healthy, and find missing capabilities after real work accumulates. Local scripts reduce session history to a bounded summary before the active model sees it; setup, resupply, updates, and config changes happen only with your approval.",
  106. "version": "1.1.2",
  107. "author": {
  108. "name": "Eigenwise"
  109. },
  110. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/quartermaster",
  111. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  112. "license": "MIT",
  113. "category": "productivity",
  114. "keywords": [
  115. "resupply",
  116. "self-improvement",
  117. "capability",
  118. "measurement",
  119. "transcripts",
  120. "friction",
  121. "recommendations",
  122. "setup",
  123. "workspace",
  124. "permissions"
  125. ]
  126. },
  127. {
  128. "name": "quality-gate",
  129. "source": "./plugins/quality-gate",
  130. "description": "Local JavaScript and TypeScript function complexity and measured V8 coverage, with per-function CRAP scores strictly below 6. The scorer reads source with the TypeScript compiler installed in the scored project (or its own dependency), pairs each function with V8 coverage by name or source position, and prints a per-function report. Everything runs on your machine; no source, coverage or report leaves it.",
  131. "version": "1.5.1",
  132. "author": {
  133. "name": "Eigenwise"
  134. },
  135. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/quality-gate",
  136. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  137. "license": "MIT",
  138. "category": "productivity",
  139. "keywords": [
  140. "quality",
  141. "complexity",
  142. "coverage",
  143. "crap",
  144. "typescript"
  145. ]
  146. },
  147. {
  148. "name": "live-rules",
  149. "source": "./plugins/live-rules",
  150. "description": "Atomic project rules in .claude/live-rules/rules/ with a generated manifest. Claude injects applicable rules at SessionStart, then only new or changed unseen rules as prompts and edits match; legacy single-file storage is for migration or explicit overrides.",
  151. "version": "2.11.2",
  152. "author": {
  153. "name": "Eigenwise"
  154. },
  155. "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/live-rules",
  156. "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
  157. "license": "MIT",
  158. "category": "development",
  159. "keywords": [
  160. "rules",
  161. "context",
  162. "hooks",
  163. "guardrails",
  164. "conventions",
  165. "standards",
  166. "runtime",
  167. "developer-experience"
  168. ]
  169. }
  170. ]
  171. }
README.md · README · 95 lines
  1. # Eigenwise Toolshed
  2. [![Claude Code](https://img.shields.io/badge/Claude_Code-plugin_marketplace-D97757?logo=claude&logoColor=white)](https://claude.com/claude-code)
  3. [![Docs](https://img.shields.io/badge/docs-online-CB7D32)](https://eigenwise.github.io/eigenwise-toolshed/)
  4. [![License: MIT](https://img.shields.io/badge/license-MIT-yellow)](./LICENSE)
  5. [![GitHub Sponsors](https://img.shields.io/badge/Sponsor-EA4AAA?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/Eigenwise)
  6. [![Ko-fi](https://img.shields.io/badge/Ko--fi-support-FF5E5B?logo=kofi&logoColor=white)](https://ko-fi.com/eigenwise)
  7. Claude Code can use a project well and still make you re-teach it the repository, lose a side issue, or repeat the same setup work in every new session.
  8. The same thing happens around model choice and measurement. Expensive models get routine jobs, parallel changes need ownership and verification, and usage stays invisible until a bill or a slow week makes it obvious. Then a plugin install or update has its own friction: what scope did it change, which session needs a reload, and what is safe to turn on?
  9. Toolshed packages those jobs as six independent Claude Code plugins. Use one, a few, or all six. Quartermaster is the guided starting path when you want help choosing, installing, and checking the pieces that fit a project, and it draws on whatever plugins are available on the machine, not only these six.
  10. Sidequest makes it easy for every task recorded as a ticket to survive context compaction and new sessions. The task, instructions, status, and recorded discussion live on a local board, so Claude can pick the work up again after the chat context shrinks. Record decisions, progress, and next actions on the ticket to give the next session a useful starting point.
  11. ## The seven plugins
  12. | Problem | Plugin | What it does |
  13. | --- | --- | --- |
  14. | A fresh session keeps exploring the same repository | [Codebase Mapper](./plugins/codebase-mapper) | Builds a small project map, loads it at session start, and refreshes the parts touched by changes. |
  15. | Project rules get forgotten or fill every context | [Live Rules](./plugins/live-rules) | Re-injects matching rules when they apply, so conditional guidance stays out of unrelated work. |
  16. | Tasks get lost when context compacts or a new session starts | [Sidequest](./plugins/sidequest) | Keeps every recorded task on a local board across context compaction and sessions, assigns ownership, dispatches independent work, and gates results on verification before integration. |
  17. | You want the models and subscriptions you already have in Claude Code | [Model Gateway](./plugins/model-gateway) | Adds supported ChatGPT/Codex and Grok subscription models to Claude Code's `/model` picker through a local gateway. |
  18. | You want a number on the code Claude writes, not a vibe | [Quality Gate](./plugins/quality-gate) | Scores every new or complexity-raised function by cyclomatic complexity and measured coverage (CRAP) from LCOV any language can produce, and reports missing measurement as unverified instead of guessing. |
  19. | You cannot tell where time and tokens go | [Observability](./plugins/observability) | Records one metadata row per turn in a local JSONL ledger with per-project opt-in, and renders a self-contained local board. Nothing leaves the machine. |
  20. | Setup, updates, and missing capabilities keep pushing back | [Quartermaster](./plugins/quartermaster) | Recommends and installs plugins from any marketplace on the machine for setup, keeps active Toolshed installs current, checks health, and uses bounded session summaries to suggest one approved improvement at a time. |
  21. Each plugin has its own install path and guide. None requires the others. Sidequest can route across Claude models on its own; Model Gateway is only needed for its non-Claude routes. Observability is separate from the other plugins and remains opt-in per project.
  22. ## Start with Quartermaster
  23. Use Quartermaster when you want Claude to look at a project and recommend what fits from the plugins available on the machine, Toolshed and otherwise, installing only what you approve. Before it names a plugin, it can check current sources for whether that plugin is still maintained, whether its cached description is stale, and whether something better fits, including from a marketplace you have not added yet. Searches use generic capability terms, so your project names and file paths stay out of the search engine's logs. Install a plugin directly when you already know which job you want.
  24. From the project directory:
  25. 1. Add the marketplace.
  26. ```text
  27. /plugin marketplace add Eigenwise/eigenwise-toolshed
  28. ```
  29. 2. Install Quartermaster for this project. Project scope is the default example because the choice stays with the repository.
  30. ```text
  31. /plugin install quartermaster@eigenwise-toolshed --scope project
  32. ```
  33. 3. Activate the installed plugin by reloading plugins or starting a new Claude Code session.
  34. ```text
  35. /reload-plugins
  36. ```
  37. 4. Run setup and approve the plan item by item.
  38. ```text
  39. /quartermaster:setup
  40. ```
  41. 5. Setup installs the selected plugins and writes the approved workspace files. When it pauses at the reload boundary, reload plugins or restart Claude Code if the change affects the process environment, then tell Claude `continue`.
  42. 6. Let setup verify the installed plugins and workspace after that boundary. Try one real request in the project before adding more pieces.
  43. Quartermaster's setup uses project scope by default, but Claude Code also supports user and local scopes. Setup can recommend and install plugins from any marketplace. The updater is scoped to Toolshed only: it follows the recorded scope and project path for every active Toolshed install, so a request from one project can update Toolshed installs in other recorded projects too, and it never touches plugins from other marketplaces. Read the update and reload notes before running it.
  44. ## Install a plugin directly
  45. Use the same marketplace with the scope you want:
  46. ```text
  47. /plugin marketplace add Eigenwise/eigenwise-toolshed
  48. /plugin install <plugin-name>@eigenwise-toolshed --scope project
  49. ```
  50. Replace `<plugin-name>` with `sidequest`, `model-gateway`, `observability`, `codebase-mapper`, `live-rules`, or `quartermaster`. Use `--scope user` for a plugin you want in every project, or `--scope local` when it should stay out of shared settings. Reload plugins or start a new session after an install. The [plugin guides](https://eigenwise.github.io/eigenwise-toolshed/getting-started/) cover the first workflow for each one.
  51. ## Updates and reloads
  52. `/quartermaster:update-toolshed` is the requested updater. It refreshes the Eigenwise Toolshed marketplace and updates all active Toolshed registry installs at their recorded user, project, or local scope and project path. It leaves third-party marketplaces alone. Freshness hooks only report cached availability or loaded-version mismatches and point you to the updater; they do not install or restart anything.
  53. Marketplace auto-update is optional. Enable it for the Eigenwise Toolshed marketplace in Claude Code if you want marketplace checks after session start. An open session still needs `/reload-plugins` after plugin code changes. Changes to process-level gateway wiring or model discovery may need a new Claude Code process instead of a reload.
  54. ## Docs and source
  55. - [Getting started](https://eigenwise.github.io/eigenwise-toolshed/getting-started/)
  56. - [Quartermaster setup guide](https://eigenwise.github.io/eigenwise-toolshed/getting-started/quartermaster/)
  57. - [Plugin reference](https://eigenwise.github.io/eigenwise-toolshed/reference/)
  58. - [Contributing](https://eigenwise.github.io/eigenwise-toolshed/contributing/)
  59. - [Release process](https://eigenwise.github.io/eigenwise-toolshed/release-process/)
  60. - [Support](https://eigenwise.github.io/eigenwise-toolshed/support/)
  61. - [GitHub repository](https://github.com/Eigenwise/eigenwise-toolshed)
  62. ## Compatibility
  63. Toolshed plugins run inside Claude Code and use its plugin marketplace, plugin scopes, and reload commands. Quartermaster's local scripts use Node.js and the Node standard library. Model Gateway also needs the supported provider subscription and local process setup described in its guide. The plugin does not include that subscription. No plugin activation opts a project into telemetry, a gateway, or Sidequest routing by itself.
  64. ## Support
  65. Toolshed's plugin code is free and MIT-licensed. If it saves you time, optional donations through [Ko-fi](https://ko-fi.com/eigenwise) or [GitHub Sponsors](https://github.com/sponsors/Eigenwise) support its maintenance. Donations are never required to install or use a plugin.
  66. ## License
  67. [MIT](./LICENSE)
plugins/model-gateway/lib/commands.js · Bundled script · 2,870 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. 'use strict';
  3. /*
  4. * model-gateway: put your ChatGPT/Codex subscription models in Claude Code's
  5. * /model picker.
  6. *
  7. * Two local processes make that happen:
  8. * 1. claude-code-proxy (raine/claude-code-proxy) translates the Anthropic
  9. * Messages API to the Codex subscription backend. It owns the OAuth.
  10. * 2. This file's `serve-shim` mode, a router in front of it. Claude Code's
  11. * ANTHROPIC_BASE_URL points HERE. Requests for `claude-gpt-*` models
  12. * are un-prefixed and sent to the proxy; everything else passes through
  13. * to api.anthropic.com untouched (claude.ai login keeps working). The
  14. * shim's /v1/models advertises the proxy's Codex models under a bare
  15. * `claude-` prefix because Claude Code's gateway model discovery drops
  16. * ids that don't start with "claude" or "anthropic".
  17. *
  18. * Default mode above is zero-admin and always available, but Claude Code's
  19. * built-in /remote-control only lights up when ANTHROPIC_BASE_URL is exactly
  20. * the real Anthropic host. There's no supported way to get gateway routing
  21. * and that exact host at once without touching the OS resolver, so it's an
  22. * opt-in "RC-compatibility" mode: after the user confirms, the remote-control
  23. * command backs up and writes one hosts entry mapping api.anthropic.com to
  24. * loopback. The shim then additionally binds loopback:80 and Claude Code's env
  25. * is pointed at http://api.anthropic.com instead of 127.0.0.1:<shim port>. See
  26. * detectHostsCompat / syncCompatMode below. Hosts writes require confirmation;
  27. * the env switch and extra listener follow automatically.
  28. */
  29. const { anthropicCatalogReport, withCachedAnthropicRows } = require('./anthropic-catalog.js');
  30. const { withPreviousServerRows } = require('./previous-picker-rows.js');
  31. const { pickerGuardFailureLines, pickerGuardForCli, pickerGuardReport, runPickerGuard } = require('./picker-guard.js');
  32. const { fork, spawn, spawnSync } = require('node:child_process');
  33. const { StringDecoder } = require('node:string_decoder');
  34. const crypto = require('node:crypto');
  35. const fs = require('node:fs');
  36. const http = require('node:http');
  37. const https = require('node:https');
  38. const net = require('node:net');
  39. const os = require('node:os');
  40. const path = require('node:path');
  41. const zlib = require('node:zlib');
  42. const { writeFileAtomically } = require('./atomic-file.js');
  43. const { localRequestAllowed, authenticatedControlRequest, controlRequestHeaders, ensureControlToken } = require('./control-auth.js');
  44. const { downloadVerifiedArchive } = require('./release-verification.js');
  45. const { fetchLatestRelease } = require('./github-release.js');
  46. const { createGatewayUsageEmitter, recordRequestBodyHighWater } = require('./usage-observability.js');
  47. const grokBackend = require('./grok-backend.js');
  48. const {
  49. canReplaceInstalledCliPath, CLI_PATH, GATEWAY_MODELS_CACHE, MODEL_WINDOW_POLICY, resolveStableCommandPath,
  50. gatewayAdvertisedWindow, gatewayClientModelId, gatewayDiscoveryModels, readGatewayDiscoveryCache,
  51. resolveGatewayModelPolicy, sameGatewayDiscoveryModels, SOCKET_PATH, resolveNewestInstalledCliPath,
  52. syncGatewayDiscoveryCache, CONTEXT_WINDOW_PATH, contextWindowCap, contextWindowCompactAt, readContextWindowSettings,
  53. writeContextWindowSettings,
  54. } = require('./runtime.js');
  55. const {
  56. contextWindowReport, contextWindowUpdate, gatewayWindowNote, savedContextWindows, saveContextWindowUpdate, syncClaudeContextWindow,
  57. } = require('./context-window.js');
  58. const { latestHookWaitCutShort, latestObservedLifecycleExit, lifecycleLogPath, recordGatewayLifecycle } = require('./lifecycle-diagnostics.js');
  59. const {
  60. CODEX_UPSTREAM_BLOCK_PATH, clearUpstreamBlocked, clearUpstreamUnavailable, readUpstreamUnavailable,
  61. setUpstreamBlocked, setUpstreamUnavailable,
  62. } = require('./codex-upstream-state.js');
  63. const { effectivePluginEnabled, pluginDisabledNotice } = require('./recovery-policy.js');
  64. const { withLifecycleLock, intentionallyStopped, recordIntentionalStop, resumeIntentionalStop } = require('./lifecycle-lock.js');
  65. const WIN = process.platform === 'win32';
  66. const STATE = path.join(os.homedir(), '.claude', 'model-gateway');
  67. const LOGS = path.join(STATE, 'logs');
  68. const BIN_DIR = path.join(STATE, 'bin');
  69. const WIRING_CONFIG_PATH = path.join(STATE, 'wiring.json');
  70. const SHIM_FAILURE_PATH = path.join(STATE, 'shim-supervisor-failure.txt');
  71. const PLUGIN_VERSION = readPluginVersion();
  72. const PROXY_BIN = path.join(BIN_DIR, WIN ? 'claude-code-proxy.exe' : 'claude-code-proxy');
  73. const PROXY_SERVING_VERSION_PATH = path.join(STATE, 'proxy-serving-version.txt');
  74. const PUBLIC_SHIM_PORT = Number(process.env.CODEX_GATEWAY_PORT || 18764);
  75. const SHIM_PORT = Number(process.env.CODEX_GATEWAY_WORKER_PORT || PUBLIC_SHIM_PORT);
  76. const PROXY_PORT = Number(process.env.CODEX_GATEWAY_PROXY_PORT || 18765);
  77. const QUIET_STARTUP_WAIT_MS = 12000;
  78. // Advertised ids are `claude-` + the backend's own id (`claude-gpt-5.6-sol`,
  79. // `claude-grok-4.5`). The `claude-` part is not decoration: Claude Code's
  80. // gateway model discovery drops every id that doesn't start with claude/
  81. // anthropic, so an unprefixed id vanishes from /model.
  82. //
  83. // Real Anthropic ids share that prefix, so PREFIX alone can NEVER decide a
  84. // route — matching on it would send claude.ai traffic to the Codex proxy. The
  85. // backend family segment decides: `gpt-*` is Codex, `grok-*` is Grok, anything
  86. // else passes through untouched.
  87. const PREFIX = 'claude-';
  88. const GROK_PREFIX = 'claude-grok-';
  89. const CODEX_FAMILY_RE = /^gpt-/;
  90. // Pre-3.x advertised the backend name too (`claude-codex-gpt-5.6-sol`). Claude
  91. // Code persists the selected model per project, so those ids outlive the
  92. // upgrade in every already-wired project; keep resolving them.
  93. const LEGACY_CODEX_PREFIX = 'claude-codex-';
  94. // Sidequest's virtual dispatch pin, resolved from the conversation's route
  95. // marker rather than from the id itself. It keeps the backend name because
  96. // `codex` here IS the backend (it owns the proxy's OAuth), and because the id
  97. // is persisted in generated agent defs and board dispatch records.
  98. const DISPATCH_MODEL_ID = 'claude-codex-auto';
  99. const GROK_ENDPOINT = process.env.CODEX_GATEWAY_GROK_ENDPOINT || grokBackend.GROK_ENDPOINT;
  100. const REPO = 'raine/claude-code-proxy';
  101. // Earliest claude-code-proxy release that maps a context overflow to HTTP 413
  102. // request_too_large (commit 968cbe2, first tagged in v0.1.14; v0.1.13 has none).
  103. // Below this the proxy signals overflow with an older, differently-shaped error;
  104. // `ensure` nudges the user (once, fail-soft) to re-run setup, which fetches latest.
  105. // Compared numerically (see semverLt); a string compare would read '0.1.9' as
  106. // newer than '0.1.14'.
  107. const MIN_PROXY_VERSION = '0.1.14';
  108. const ANTHROPIC_UPSTREAM = process.env.CODEX_GATEWAY_ANTHROPIC_UPSTREAM || 'https://api.anthropic.com';
  109. // Enabled by default because route logs are metadata-only: never write prompts,
  110. // tool payloads, auth, or arbitrary headers. Set to `0` to opt out; a running shim
  111. // picks this up at its next natural restart. See requestRouteLog below.
  112. const REQUEST_ROUTE_LOG = process.env.CODEX_GATEWAY_REQUEST_LOG !== '0';
  113. const REQUEST_ROUTE_LOG_PATH = process.env.CODEX_GATEWAY_REQUEST_LOG_PATH || path.join(LOGS, 'request-routes.jsonl');
  114. const DISPATCH_ROUTE_CACHE_PATH = process.env.CODEX_GATEWAY_DISPATCH_CACHE_PATH || path.join(STATE, 'dispatch-routes.json');
  115. const LIST_DISPATCH_MODEL = process.env.CODEX_GATEWAY_LIST_DISPATCH_MODEL === '1';
  116. const ROUTE_TELEMETRY_ENABLED = process.env.CLAUDE_CODE_PROPAGATE_TRACEPARENT === '1';
  117. const ROUTE_TELEMETRY_TIMEOUT_MS = 500;
  118. const TRACE_HEADERS = ['traceparent', 'tracestate', 'baggage'];
  119. const AUTH_HEADERS = ['authorization', 'proxy-authorization', 'x-api-key', 'cookie'];
  120. const {
  121. COMPAT_BASE_URL, COMPAT_HOST, COMPAT_PORT, DEFAULT_BASE_URL, HOSTS_BLOCK_END, HOSTS_BLOCK_LINE,
  122. HOSTS_BLOCK_START, PIN_ALIASES, PIN_OVERRIDE_PATH, STATIC_ENV_BLOCK, CODEX_UNKNOWN_MODEL_WINDOW,
  123. codexContextWindow,
  124. } = require('./runtime.js');
  125. const {
  126. codexBaseFromId, detectedPinDefaults, effectivePins, envBlockFor, gatewayEnvBlock, isGatewayModelId,
  127. claudeVersion, isValidPin, ourBaseUrls, ownedPinValues, realClaudeRefusedUnderTest, pinProvenance, readPinOverrides, refreshDetectedPins, refreshCatalogPins, comparePinVersions, stalePinUpdates,
  128. writePinOverrides,
  129. } = require('./pins.js');
  130. // Versions through 0.4.1 wrote this unsafe global override. Remove it during
  131. // the next env write/remove, but leave a user-supplied different value alone.
  132. const LEGACY_ENV_BLOCK = {
  133. CLAUDE_CODE_AUTO_COMPACT_WINDOW: '950000',
  134. CLAUDE_CODE_MAX_CONTEXT_TOKENS: '920000',
  135. };
  136. const USAGE = `usage: model-gateway.js <command>
  137. setup download the claude-code-proxy binary (v-latest) into ${BIN_DIR}
  138. login [--device] run the ChatGPT OAuth flow (--device for headless device-code)
  139. start | stop start/stop the proxy + shim (detached, logs in ${LOGS})
  140. ensure [--quiet] maintain installed wiring and start unless intentionally stopped
  141. recover restore readiness without settings, pin or cache maintenance
  142. status show what's running
  143. models show the model list the shim advertises to Claude Code
  144. catalog [--json] [--refresh] print the sidequest-readable model catalog (${path.join(STATE, 'catalog.json')});
  145. --refresh exits non-zero and says why on stderr when it could not write a
  146. fresh one, and prints the retained catalog unchanged
  147. pin [--opus|--sonnet|--fable <model|default>]
  148. show pin sources and newest catalog ids, or persist an override (${PIN_OVERRIDE_PATH});
  149. default removes the override and follows detected/catalog defaults, never backwards
  150. context-window [--claude <tokens|full>] [--codex <tokens|full>] [--grok <tokens|full>]
  151. show or persist the context window per backend (${CONTEXT_WINDOW_PATH}); the
  152. orchestrator and every executor share it. Defaults: claude full, codex 272000,
  153. grok full. Without compact-at, a gateway cap compacts 85000 below the cap.
  154. --codex-compact-at <tokens|cap> and --grok-compact-at <tokens|cap> set a direct
  155. maximum before compaction (positive whole tokens); cap removes the override.
  156. The cap and backend window minus 40000 still limit the effective maximum.
  157. A saved compact-at ignores CODEX_GATEWAY_COMPACT_TRIGGER, reported unchanged.
  158. Example: --codex-compact-at 242000 leaves the 272000 cap unchanged. OpenAI bills
  159. input above 272k tokens at 2x; the crossing turn and compaction request can still
  160. exceed 272k. Existing installations keep their current policy until configured.
  161. --claude sets the native autoCompactWindow in project-wired settings; native
  162. engine headroom applies and the exact trigger is unverified. Claude compact-at
  163. is unsupported. No same-model main/subagent split is applied.
  164. CODEX_GATEWAY_CONTEXT_WINDOW is superseded and only applies when no codex value is saved.
  165. env [--write-project | --write-user | --remove] [--reconcile]
  166. print the Claude Code env block, or merge/remove wiring
  167. --remove clears owned routing, discovery, static env and alias pins; preserves and names user pins
  168. (--write-project writes .claude/settings.local.json; --write-user
  169. is an opt-in shared fallback in ~/.claude/settings.json)
  170. doctor full health check, Anthropic catalog age/fallback, pin sources and newest ids
  171. remote-control <enable|disable|doctor> [--confirm]
  172. manage the opt-in hosts-file compatibility mode; enable refuses an effective
  173. HTTPS api.anthropic.com process URL before hosts changes
  174. serve-shim (internal) run the router in the foreground
  175. Request route logging (on by default; set CODEX_GATEWAY_REQUEST_LOG=0 to opt out):
  176. CODEX_GATEWAY_REQUEST_LOG=0
  177. Writes JSONL route metadata to ${REQUEST_ROUTE_LOG_PATH}. Override the path with
  178. CODEX_GATEWAY_REQUEST_LOG_PATH. It records no request bodies, prompts, tools, or auth.`;
  179. const cmd = process.argv[2];
  180. const args = process.argv.slice(3);
  181. const flag = (f) => args.includes(f);
  182. // A `--json` invocation's stdout is a machine contract. `catalog --refresh --json` writes the catalog on the
  183. // way out, and that write logs when it preserves models from a subset response, so a diagnostic line landed
  184. // ahead of the JSON and Sidequest's catalog refresh threw on parse and silently gave up (SQ-2208). Human lines
  185. // still get emitted, on stderr, where they belong once stdout is data.
  186. // SessionStart hook stdout is model context and nothing else, so every actionable gateway state reached the
  187. // model and nobody else: on 2026-08-13 this hook found the session unwired, said so, and the user only learned
  188. // it hours later by asking which hooks had run (SQ-1901). systemMessage is the one channel Claude Code shows
  189. // the user, and it is only readable inside a JSON object, so the hook path buffers its lines, hands the model
  190. // the same text it always got, and puts the states someone has to go fix in front of the user.
  191. let bufferedHookLines = null;
  192. const userActionNotices = [];
  193. function log(m) {
  194. if (bufferedHookLines) { bufferedHookLines.push(String(m)); return; }
  195. if (flag('--json')) console.error(m); else console.log(m);
  196. }
  197. function noticeForUser(text, { toStderr = false } = {}) {
  198. userActionNotices.push(text);
  199. if (bufferedHookLines) bufferedHookLines.push(text);
  200. else if (toStderr) console.error(text);
  201. else log(text);
  202. }
  203. function flushHookOutput() {
  204. if (!bufferedHookLines) return;
  205. const lines = bufferedHookLines;
  206. bufferedHookLines = null;
  207. const output = {};
  208. if (lines.length) output.hookSpecificOutput = { hookEventName: 'SessionStart', additionalContext: lines.join('\n') };
  209. const [worst, ...rest] = userActionNotices;
  210. // One line, every session start, so noise discipline is part of the contract: the first actionable state names
  211. // its own fix, and the rest are counted with the one command that lists them all.
  212. if (worst) output.systemMessage = rest.length ? `${worst} (+${rest.length} more: run \`node "${resolveStableCommandPath()}" doctor\`)` : worst;
  213. if (Object.keys(output).length) process.stdout.write(JSON.stringify(output));
  214. }
  215. // Flushes first so a die() from anywhere inside the hook path still emits what was buffered; otherwise the
  216. // buffering below would turn a mid-run failure into total silence.
  217. function die(m, code) { flushHookOutput(); console.error('model-gateway: ' + m); process.exit(code == null ? 1 : code); }
  218. function readPluginVersion() {
  219. try {
  220. const { version } = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '.claude-plugin', 'plugin.json'), 'utf8'));
  221. return typeof version === 'string' ? version : null;
  222. } catch { return null; }
  223. }
  224. function mkdirs() { for (const d of [STATE, LOGS, BIN_DIR]) fs.mkdirSync(d, { recursive: true }); }
  225. const {
  226. createProbeChildRegistry, createProxyRecovery, fetchUrl, killPidAsync, listeningPidsFromNetstat, portListening, postJson, processOwningPortAsync, recordedGatewayPids, reapGatewayOrphans, resolvePortOwner, unknownPortOwnerReason,
  227. removePid, restartWorkerWithDrain, shimHealthy, spawnDetached, stopAll, stopProcessAsync, stopRunningSupervisor,
  228. stopShimWithDrain, waitForShimExit, writePidRecordAsync,
  229. } = require('./process-supervision.js');
  230. const { describeShimState, fetchShimHealth, parseSemver, probeShimState, semverLt, servingCurrentVersion, servingShimVersion, shimNeedsRestart } = require('./shim-state.js');
  231. const {
  232. removeGatewayOwnedSettings, projectWiringIssues, repairProjectWiring, cleanLegacyEnvSettings, cleanLegacyGatewayModelCache, effectiveBaseUrl, isWired, migrateLegacyProjectSettings,
  233. processEnvGatewayBypass, readSettingsForWrite, reconcileRegisteredProjectWirings, recordProjectWiring, registeredProjectPinDisagreements, registeredProjectWirings,
  234. selectedWiringScope, retireWiringModeConfig, settingsPath, syncRegisteredProjectPins, unsafeRemoteControlProcessEnv, wiredMode, writeSettings,
  235. } = require('./settings-wiring.js');
  236. // ------------------------------------------------- RC-compatibility hosts
  237. const {
  238. addManagedHostsBlock, configureRemoteControl, detectHostsCompat, findConflictingHostsMappings, hostsFilePath,
  239. managedHostsBlock, parseHostsCompatBlock, parseHostsCompatEntry, removeManagedHostsBlock, remoteControlCommand,
  240. } = require('./remote-control.js');
  241. function compatibilityPortOwnerIdentifiers(lookup = spawnSync) {
  242. const portLookup = WIN
  243. ? lookup('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8', windowsHide: true })
  244. : lookup('lsof', ['-nP', `-iTCP:${COMPAT_PORT}`, '-sTCP:LISTEN', '-t'], { encoding: 'utf8', windowsHide: true });
  245. if (portLookup.status !== 0) return [];
  246. const output = String(portLookup.stdout);
  247. return WIN ? listeningPidsFromNetstat(output, COMPAT_PORT) : [...new Set(output.split(/\s+/).map(Number).filter(Boolean))];
  248. }
  249. function processNameForIdentifier(processIdentifier) {
  250. const processLookup = WIN
  251. ? spawnSync('tasklist', ['/FI', `PID eq ${processIdentifier}`, '/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true })
  252. : spawnSync('ps', ['-p', String(processIdentifier), '-o', 'comm='], { encoding: 'utf8', windowsHide: true });
  253. if (processLookup.status !== 0) return null;
  254. const output = String(processLookup.stdout || '').trim();
  255. if (!output) return null;
  256. return WIN ? output.match(/^"([^"]+)"/)?.[1] || null : output;
  257. }
  258. function compatibilityPortConflict() {
  259. const owners = compatibilityPortOwnerIdentifiers().map((processIdentifier) => {
  260. const processName = processNameForIdentifier(processIdentifier);
  261. return { processIdentifier, processName };
  262. });
  263. if (!owners.length) return null;
  264. const holders = owners.map(({ processIdentifier, processName }) => {
  265. const holder = processName ? `${processName} (PID ${processIdentifier})` : `PID ${processIdentifier}`;
  266. return processName && /docker/i.test(processName) ? `Docker Desktop (${holder})` : holder;
  267. });
  268. const includesDockerDesktop = owners.some(({ processName }) => processName && /docker/i.test(processName));
  269. const releaser = owners.length === 1
  270. ? (includesDockerDesktop ? 'Docker Desktop' : 'that process')
  271. : (includesDockerDesktop ? 'Docker Desktop and the other listed processes' : 'the listed processes');
  272. return `port ${COMPAT_PORT}: held by ${holders.join(', ')}. RC-compatibility cannot start until ${releaser} release${owners.length === 1 ? 's' : ''} port ${COMPAT_PORT}.`;
  273. }
  274. const RC_CONTROL_PATH = '/internal/rc-compatibility';
  275. const RC_CONTROL_HEADER = 'x-model-gateway-control';
  276. const RC_CONTROL_VALUE = 'rc-compatibility';
  277. configureRemoteControl({ args, flag, log, die, doctor, fetchShimHealth, requestServingCompatibility, startAll, syncCompatMode, compatibilityPortConflict, unsafeRemoteControlProcessEnv });
  278. // Model Gateway runs where it is installed. Project-scoped installs and
  279. // project-local wiring are the standard configuration. We still report an
  280. // installed user copy for diagnosis, without treating either scope as broken.
  281. //
  282. // Returns 'user', 'project-only', or 'unknown' when installed_plugins.json is
  283. // absent (for example, a --plugin-dir development checkout).
  284. function installScope(home = os.homedir()) {
  285. try {
  286. const file = path.join(home, '.claude', 'plugins', 'installed_plugins.json');
  287. const data = JSON.parse(fs.readFileSync(file, 'utf8'));
  288. const entries = Object.entries(data.plugins || {})
  289. .filter(([pluginId]) => pluginId.startsWith('model-gateway@'))
  290. .flatMap(([, installs]) => installs);
  291. if (!entries.length) return 'unknown';
  292. return entries.some((entry) => entry.scope === 'user') ? 'user' : 'project-only';
  293. } catch { return 'unknown'; }
  294. }
  295. function isAuthed() {
  296. const r = spawnSync(PROXY_BIN, ['codex', 'auth', 'status'], { encoding: 'utf8', timeout: 15000, windowsHide: true });
  297. return r.status === 0 && /account/i.test((r.stdout || '') + (r.stderr || ''));
  298. }
  299. function noteCodexRequestSuccess() {
  300. clearUpstreamBlocked();
  301. clearUpstreamUnavailable();
  302. }
  303. function providerReadiness(readiness) {
  304. return {
  305. ready: Boolean(readiness?.ready),
  306. state: typeof readiness?.state === 'string' ? readiness.state : 'unavailable',
  307. message: typeof readiness?.message === 'string' ? readiness.message : 'Readiness is unavailable.',
  308. };
  309. }
  310. // ------------------------------------------------------------------- setup
  311. function proxyVersion(version) {
  312. return Array.isArray(version) ? version.join('.') : null;
  313. }
  314. function currentProxyVersion(binary = PROXY_BIN) {
  315. return proxyVersion(parseSemver((spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim()));
  316. }
  317. function oldProxyPath(currentPath, version, now = Date.now()) {
  318. return `${currentPath}.old-${version || 'unknown'}-${now}`;
  319. }
  320. function sweepOldProxyBinaries({ directory = BIN_DIR, basename = path.basename(PROXY_BIN), fsImpl = fs } = {}) {
  321. let entries;
  322. try { entries = fsImpl.readdirSync(directory); } catch { return; }
  323. for (const entry of entries) {
  324. if (!String(entry).startsWith(`${basename}.old-`)) continue;
  325. try { fsImpl.rmSync(path.join(directory, entry)); } catch {}
  326. }
  327. }
  328. function replaceProxyBinary({ currentPath = PROXY_BIN, stagedPath, currentVersion, fsImpl = fs, now = Date.now() } = {}) {
  329. const hadExistingProxy = fsImpl.existsSync(currentPath);
  330. const previousPath = hadExistingProxy ? oldProxyPath(currentPath, proxyVersion(currentVersion), now) : null;
  331. if (hadExistingProxy) fsImpl.renameSync(currentPath, previousPath);
  332. try {
  333. fsImpl.renameSync(stagedPath, currentPath);
  334. } catch (error) {
  335. if (previousPath) fsImpl.renameSync(previousPath, currentPath);
  336. throw new Error(`proxy upgrade failed (${error.code || error.message}); original proxy restored.`, { cause: error });
  337. }
  338. return { hadExistingProxy, previousPath };
  339. }
  340. function readProxyServingVersion(file = PROXY_SERVING_VERSION_PATH) {
  341. try { return fs.readFileSync(file, 'utf8').trim() || null; } catch { return null; }
  342. }
  343. function writeProxyServingVersion(version, file = PROXY_SERVING_VERSION_PATH) {
  344. if (!version) return;
  345. fs.writeFileSync(file, `${version}\n`);
  346. }
  347. async function waitForProxyExit({ listening = portListening, attempts = 7, delay = 100 } = {}) {
  348. for (let attempt = 0; attempt < attempts; attempt += 1) {
  349. if (!(await listening(PROXY_PORT))) return true;
  350. await new Promise((resolve) => setTimeout(resolve, delay));
  351. }
  352. return false;
  353. }
  354. async function restartProxyForVersionChange({
  355. previousVersion,
  356. listening = portListening,
  357. stop = stopProcessAsync,
  358. supervisorRunning = async () => (await resolvePortOwner(PUBLIC_SHIM_PORT)).state === 'same-install',
  359. } = {}) {
  360. if (previousVersion) writeProxyServingVersion(previousVersion);
  361. if (await listening(PROXY_PORT)) await stop('proxy');
  362. if (!(await waitForProxyExit({ listening }))) return false;
  363. return supervisorRunning();
  364. }
  365. async function restartProxyIfOutdated({
  366. quiet = false,
  367. currentVersion = currentProxyVersion,
  368. readServingVersion = readProxyServingVersion,
  369. restart = restartProxyForVersionChange,
  370. report = log,
  371. } = {}) {
  372. const onDisk = currentVersion();
  373. const serving = readServingVersion() || onDisk;
  374. if (!onDisk || !serving || onDisk === serving) return { restarted: false, onDisk, serving };
  375. const restarted = await restart({ previousVersion: serving });
  376. if (!restarted && !quiet) report(`proxy on disk: ${onDisk} serving: ${serving} restarts on next \`ensure\``);
  377. return { restarted, onDisk, serving };
  378. }
  379. async function restartSetupProxy({ previousVersion }) {
  380. if (intentionallyStopped()) return false;
  381. return restartProxyForVersionChange({ previousVersion });
  382. }
  383. async function restartAfterSetup(proxyRecoveryHandoff) {
  384. if (proxyRecoveryHandoff || intentionallyStopped()) return null;
  385. const supervisorRestart = await restartShimIfOutdated({ operation: 'setup' });
  386. if (supervisorRestart) return supervisorRestart;
  387. const restarting = await restartWorkerWithDrain();
  388. if (!restarting.ok) die(`could not restart shim worker: ${restarting.reason}`);
  389. return null;
  390. }
  391. async function setup({ preserveWiring = false } = {}) {
  392. mkdirs();
  393. refreshCatalogPinsAndWiring();
  394. migrateReadinessGates();
  395. sweepOldProxyBinaries();
  396. const arch = process.arch === 'arm64' ? 'arm64' : 'amd64';
  397. const plat = WIN ? 'windows' : process.platform === 'darwin' ? 'darwin' : 'linux';
  398. const ext = WIN ? 'zip' : 'tar.gz';
  399. const assetName = `claude-code-proxy-${plat}-${arch}.${ext}`;
  400. let release;
  401. try { release = await fetchLatestRelease(REPO, { fetchUrl, log }); }
  402. catch (error) { die(error.message); }
  403. let archive;
  404. try { archive = await downloadVerifiedArchive(release, assetName, { fetchUrl, log }); }
  405. catch (error) { die(error.message); }
  406. const stage = fs.mkdtempSync(path.join(BIN_DIR, 'stage-'));
  407. const archiveFile = path.join(stage, assetName);
  408. fs.writeFileSync(archiveFile, archive);
  409. const tarBin = WIN
  410. ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
  411. : 'tar';
  412. const tar = spawnSync(tarBin, ['-xf', archiveFile], { encoding: 'utf8', cwd: stage, windowsHide: true });
  413. if (tar.status !== 0) die(`extract failed: ${tar.stderr || tar.status}`);
  414. const staged = fs.readdirSync(stage, { recursive: true })
  415. .map(String).find((file) => path.basename(file) === path.basename(PROXY_BIN));
  416. if (!staged) die(`extracted, but ${path.basename(PROXY_BIN)} not found in ${BIN_DIR}`);
  417. const stagedProxy = path.join(stage, staged);
  418. if (!WIN) fs.chmodSync(stagedProxy, 0o755);
  419. const currentVersion = parseSemver((spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim());
  420. const stagedVersion = parseSemver((spawnSync(stagedProxy, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim());
  421. const proxyChanged = !currentVersion || !stagedVersion || currentVersion.join('.') !== stagedVersion.join('.');
  422. const maintenanceStopped = preserveWiring && intentionallyStopped();
  423. let proxyRecoveryHandoff = false;
  424. if (proxyChanged) {
  425. const previousVersion = proxyVersion(currentVersion);
  426. const installedVersion = proxyVersion(stagedVersion);
  427. replaceProxyBinary({ stagedPath: stagedProxy, currentVersion });
  428. proxyRecoveryHandoff = await restartSetupProxy({ previousVersion });
  429. if (!proxyRecoveryHandoff) log(`proxy on disk: ${installedVersion || 'unknown'} serving: ${previousVersion || 'unknown'} restarts on next \`ensure\``);
  430. } else {
  431. log('model-gateway: proxy unchanged; keeping its authenticated process running.');
  432. }
  433. fs.rmSync(stage, { recursive: true, force: true });
  434. if (maintenanceStopped) return log('Model Gateway updated; intentional stop preserved. Run start to resume.');
  435. const supervisorRestart = await restartAfterSetup(proxyRecoveryHandoff);
  436. if (supervisorRestart && !supervisorRestart.ok && !supervisorRestart.stillStarting) die(`could not restart shim supervisor: ${supervisorRestart.reason}`);
  437. const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', windowsHide: true });
  438. log(`installed: ${(v.stdout || v.stderr || '').trim() || PROXY_BIN}`);
  439. if (supervisorRestart?.stillStarting) return warnShimStillStarting(supervisorRestart);
  440. // one-shot: start everything, and finish the wiring when auth already works
  441. const r = await startAll({ lifecycleOperation: 'setup', resumeIntent: !preserveWiring, preserveRunningSupervisor: proxyRecoveryHandoff });
  442. if (r.stillStarting) return warnShimStillStarting(r);
  443. if (!r.ok) die(r.reason);
  444. clearUpstreamBlocked();
  445. clearUpstreamUnavailable();
  446. if (!isAuthed()) {
  447. log(`next: node "${resolveStableCommandPath()}" login (ChatGPT browser sign-in), then setup again to wire Claude Code`);
  448. return;
  449. }
  450. log('ChatGPT auth: valid');
  451. await refreshDetectedPinsAndWiring({ force: true });
  452. if (preserveWiring) return finishUpdateWithoutWiring();
  453. const { mode } = await resolveIntendedMode();
  454. if (isWired()) {
  455. const current = wiredMode();
  456. if (!current || !current.scope) {
  457. // Refusing to copy an environment value into settings is deliberate (it may point at someone's dev
  458. // instance), but saying only that left no route forward, so setup skipped the write on every run and the
  459. // machine stayed permanently wired by one terminal (SQ-1901). Name the command that does converge it.
  460. log(`already wired through ${current ? current.source : 'ANTHROPIC_BASE_URL'}, which has no settings file this command can write, so nothing here is permanent: any session started outside that environment is unwired. Run \`node "${resolveStableCommandPath()}" env --write-project\` to write this project's .claude/settings.local.json. Claude alias pins were left alone; they belong wherever that base URL is defined.`);
  461. } else if (current.mode !== mode) {
  462. writeEnv(current.scope, false, { mode, quiet: true });
  463. log(`model-gateway: hosts compatibility state changed since last wired; switched ${current.scope} settings to ${mode} mode. Restart Claude Code.`);
  464. } else {
  465. writeEnv(current.scope, false, { mode, quiet: true });
  466. log('already wired; refreshed Claude alias pins. Restart Claude Code and open /model');
  467. }
  468. await statusReport();
  469. return;
  470. }
  471. writeEnv(selectedWiringScope(), false, { mode });
  472. await writeCatalog().catch(() => { /* advisory only; Claude Code can retry on the next ensure */ });
  473. await statusReport();
  474. }
  475. // ------------------------------------------------------- process management
  476. function servingVersionIsCurrentOrNewer(servingVersion, installedVersion) {
  477. if (servingVersion === installedVersion) return true;
  478. const serving = parseSemver(servingVersion);
  479. const installed = parseSemver(installedVersion);
  480. return Boolean(serving && installed && !semverLt(serving, installed));
  481. }
  482. function servingVersionIsNewer(servingVersion, installedVersion) {
  483. const serving = parseSemver(servingVersion);
  484. const installed = parseSemver(installedVersion);
  485. return Boolean(serving && installed && semverLt(installed, serving));
  486. }
  487. function staleSessionReloadNotice(installedVersion, health) {
  488. const servingVersion = servingShimVersion(health);
  489. if (!servingVersionIsNewer(servingVersion, installedVersion)) return null;
  490. return `model-gateway: this session loaded ${installedVersion}, but the serving shim is newer (${servingVersion}). Reload plugins with /reload-plugins or restart Claude Code; the newer shim was left running.`;
  491. }
  492. // Fail-soft: read the running proxy's --version and, if it's below
  493. // MIN_PROXY_VERSION, print exactly one stderr nudge. Never throws and never
  494. // blocks the session; a version we can't read/parse is treated as "don't nag".
  495. // Does NOT auto-download; that belongs in `setup`, not the 30s keepalive hook.
  496. function warnIfProxyOutdated() {
  497. try {
  498. const floor = parseSemver(MIN_PROXY_VERSION);
  499. const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', timeout: 10000, windowsHide: true });
  500. const got = parseSemver((v.stdout || '') + (v.stderr || ''));
  501. if (got && floor && semverLt(got, floor)) {
  502. console.error(`model-gateway: claude-code-proxy ${got.join('.')} is older than ${MIN_PROXY_VERSION}; Codex context-overflow recovery needs the newer proxy. Run the model-gateway skill setup to update (it downloads the latest).`);
  503. }
  504. } catch { /* fail-soft: a version check must never break the session */ }
  505. }
  506. function startupWaitMsFor(quiet) {
  507. return quiet
  508. ? QUIET_STARTUP_WAIT_MS
  509. : Math.max(12000, (Number(process.env.CODEX_GATEWAY_DRAIN_TIMEOUT_MS) || 30000) + 12000);
  510. }
  511. async function ensureWiredGateway(wired, quiet) {
  512. if (!wired || recoveryExplicitlyDisabled()) return { ok: true, started: [] };
  513. const proxyRestart = await restartProxyIfOutdated({ quiet });
  514. return startAll({ quiet, lifecycleOperation: 'ensure', preserveRunningSupervisor: proxyRestart.restarted });
  515. }
  516. async function automaticLifecycle(operation) {
  517. if (recoveryExplicitlyDisabled()) return;
  518. return withLifecycleLock(() => {
  519. if (intentionallyStopped()) {
  520. noticeForUser('model-gateway is intentionally stopped; run start to resume.', { toStderr: true });
  521. return;
  522. }
  523. return operation();
  524. });
  525. }
  526. function reportReadinessGate() {
  527. const effective = effectiveBaseUrl();
  528. const file = effective.file || effective.shadowed.find((definition) => definition.file)?.file;
  529. const settings = file ? readSettingsForWrite(file) : {};
  530. const present = require('./readiness-hooks.js').readinessHookPresent(settings);
  531. log(`readiness gate installed: ${present}; hooks disabled: ${settings.disableAllHooks === true}; settings: ${file || 'none'}`);
  532. log(`intentional stop: ${intentionallyStopped()}; state: ${require('./lifecycle-lock.js').STOP_PATH}`);
  533. log(`explicit plugin disable: ${effectivePluginEnabled() === false}`);
  534. log(`recovery diagnostics: ${LOGS}; startup failures: ${SHIM_FAILURE_PATH}`);
  535. }
  536. function migrateReadinessGates() {
  537. require('../hooks/registry-writer.js').writeCommandLauncher();
  538. const files = registeredProjectWirings().map((wiring) => wiring.file);
  539. files.push(settingsPath('user'));
  540. for (const file of files) migrateReadinessGate(file);
  541. }
  542. function migrateReadinessGate(file) {
  543. const settings = readSettingsForWrite(file);
  544. if (!ourBaseUrls().includes(settings.env?.ANTHROPIC_BASE_URL)) return;
  545. const original = JSON.stringify(settings);
  546. require('./readiness-hooks.js').syncReadinessHooks(settings, true);
  547. if (JSON.stringify(settings) !== original) writeSettings(file, settings);
  548. }
  549. function startupFailureFor(supervisorPid, startupGeneration) {
  550. try {
  551. const failure = JSON.parse(fs.readFileSync(SHIM_FAILURE_PATH, 'utf8'));
  552. if (failure.supervisorPid !== supervisorPid) return null;
  553. if (startupGeneration && failure.generation !== startupGeneration) return null;
  554. return failure.message;
  555. } catch { return null; }
  556. }
  557. function writeStartupFailure(message) {
  558. writeFileAtomically(SHIM_FAILURE_PATH, JSON.stringify({ supervisorPid: process.pid, generation: process.env.MODEL_GATEWAY_STARTUP_GENERATION, message }));
  559. }
  560. function recoveryExplicitlyDisabled() {
  561. if (effectivePluginEnabled() !== false) return false;
  562. noticeForUser(pluginDisabledNotice(), { toStderr: true });
  563. return true;
  564. }
  565. async function recoverGateway() {
  566. if (recoveryExplicitlyDisabled()) return { ok: true, started: [] };
  567. const result = await startAll({ quiet: true, lifecycleOperation: 'recover', refreshCatalog: async () => {} });
  568. if (!result.ok) throw new Error(result.reason);
  569. return result;
  570. }
  571. function readObservedStartupFailure(exists, read) {
  572. if (!exists()) return null;
  573. return read();
  574. }
  575. async function waitForStartupReadiness({
  576. timeout,
  577. shimReady = shimHealthy,
  578. shimFailureExists = () => fs.existsSync(SHIM_FAILURE_PATH),
  579. readShimFailure = () => startupFailureFor(supervisorPid, startupGeneration),
  580. supervisorPid = null,
  581. startupGeneration = null,
  582. now = Date.now,
  583. pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
  584. } = {}) {
  585. const deadline = now() + timeout;
  586. while (now() < deadline) {
  587. if (await shimReady()) return { ok: true };
  588. const failure = readObservedStartupFailure(shimFailureExists, readShimFailure);
  589. if (failure) return { ok: false, reason: failure, timedOut: false };
  590. await pause(300);
  591. }
  592. return { ok: false, timedOut: true };
  593. }
  594. function reportSiblingSupervisorReplacement(stopped, quiet) {
  595. if (!quiet && stopped.siblingInstallRoot) log(`model-gateway: replaced older sibling shim version at ${stopped.siblingInstallRoot}.`);
  596. }
  597. function recoveryOutcome(result) {
  598. if (result.ok) return 'ready';
  599. return result.stillStarting ? 'starting' : 'failed';
  600. }
  601. function lifecycleRecovery(lifecycleOperation, recordLifecycle) {
  602. let attempted = false;
  603. return {
  604. begin() {
  605. if (attempted || !lifecycleOperation) return;
  606. attempted = true;
  607. recordLifecycle(`${lifecycleOperation}-recovery-started`, {
  608. component: lifecycleOperation,
  609. pid: process.pid,
  610. startedAt: new Date().toISOString(),
  611. });
  612. },
  613. finish(result) {
  614. if (attempted && lifecycleOperation) {
  615. recordLifecycle(`${lifecycleOperation}-recovery-finished`, {
  616. component: lifecycleOperation,
  617. pid: process.pid,
  618. outcome: recoveryOutcome(result),
  619. ...(result.supervisorPid ? { supervisorPid: result.supervisorPid } : {}),
  620. });
  621. }
  622. return { ...result, recoveryAttempted: attempted };
  623. },
  624. };
  625. }
  626. // A supervisor that is still starting gets the startup window to answer before anything binds against it (#230,
  627. // #251). Its old failure file is not evidence about this start, so the wait ignores it.
  628. async function readSettledShimState(probe, { quiet, report, awaitReadiness, timeout }) {
  629. const shim = await probe();
  630. if (!quiet) report(describeShimState(shim));
  631. if (shim.state !== 'starting') return shim;
  632. await awaitReadiness({ timeout, shimFailureExists: () => false });
  633. return probe();
  634. }
  635. function shimStartPlan(shim, preserveRunningSupervisor) {
  636. if (shim.state === 'running-foreign') return refuseForeignShim;
  637. if (servingCurrentVersion(shim)) return keepRunningShim;
  638. return preserveRunningSupervisor && shim.state === 'starting' ? waitForRunningShim : replaceShim;
  639. }
  640. function refuseForeignShim(shim, { lifecycleOperation, recordLifecycle }) {
  641. if (shim.owner.state === 'foreign-install') {
  642. return { ok: false, reason: `PID ${shim.pid} owns :${PUBLIC_SHIM_PORT} from a different install root (${shim.image})` };
  643. }
  644. const operation = lifecycleOperation || 'start';
  645. recordLifecycle(`${operation}-owner-unknown`, { component: operation, pid: process.pid, outcome: 'owner-unknown' });
  646. return { ok: false, reason: unknownPortOwnerReason(shim.owner, PUBLIC_SHIM_PORT) };
  647. }
  648. async function keepRunningShim(shim, context) {
  649. // The lifecycle lock serializes cleanup; only birth-identified stale workers
  650. // with a conclusively lost parent can be reaped beside this healthy supervisor.
  651. if (shim.owner.state === 'same-install') context.reapOrphans(shim.pid);
  652. noticeStaleSession(shim.health);
  653. // setup handed a replaced proxy to this supervisor, so it waits for that proxy to answer.
  654. if (context.preserveRunningSupervisor) return finishStartingShim([], context, shim.pid);
  655. return reportShimReady([], context);
  656. }
  657. function waitForRunningShim(shim, context) {
  658. return finishStartingShim([], context, shim.pid);
  659. }
  660. async function replaceShim(shim, context) {
  661. const refused = await clearShimForStart(shim, context);
  662. if (refused) return context.recovery.finish(refused);
  663. return finishStartingShim(['shim'], context, launchSupervisor(context));
  664. }
  665. async function clearShimForStart(shim, { quiet, lifecycleOperation, reapOrphans, stopSupervisor, recovery }) {
  666. if (shim.state === 'stopped') {
  667. reapOrphans(null);
  668. return null;
  669. }
  670. recovery.begin();
  671. const stopped = await stopSupervisor({ quiet, operation: lifecycleOperation || 'restart' });
  672. if (!stopped.ok) return stopped;
  673. reportSiblingSupervisorReplacement(stopped, quiet);
  674. return null;
  675. }
  676. function launchSupervisor(context) {
  677. const { recovery, spawnSupervisor } = context;
  678. context.startupGeneration = crypto.randomUUID();
  679. recovery.begin();
  680. try { fs.rmSync(SHIM_FAILURE_PATH); } catch {}
  681. const supervisorArguments = [resolveNewestInstalledCliPath(), 'serve-shim'];
  682. const supervisorPid = spawnSupervisor('guardian', process.execPath, supervisorArguments, { MODEL_GATEWAY_STARTUP_GENERATION: context.startupGeneration });
  683. if (context.resumeIntent) resumeIntentionalStop();
  684. return supervisorPid;
  685. }
  686. async function finishStartingShim(started, context, supervisorPid) {
  687. const readiness = await context.awaitReadiness({ timeout: context.timeout, supervisorPid, startupGeneration: context.startupGeneration });
  688. if (readiness.ok) return reportShimReady(started, context);
  689. if (!readiness.timedOut) return context.recovery.finish({ ok: false, reason: readiness.reason });
  690. const waited = `${Math.ceil(context.timeout / 1000)}s`;
  691. // The wait returns early on a failure file, so a timeout with the supervisor alive means it is still starting.
  692. const stillStarting = context.supervisorAlive(supervisorPid);
  693. return context.recovery.finish({
  694. ok: false,
  695. reason: stillStarting
  696. ? `still starting after ${waited}; supervisor pid ${supervisorPid} is running`
  697. : `not healthy after ${waited} (check logs in ${LOGS})`,
  698. started,
  699. waitCutShort: context.quiet,
  700. ...(stillStarting ? { stillStarting, supervisorPid } : {}),
  701. });
  702. }
  703. function processAlive(pid) {
  704. if (!Number.isInteger(pid) || pid <= 0) return false;
  705. try {
  706. process.kill(pid, 0);
  707. return true;
  708. } catch (error) {
  709. return error.code === 'EPERM';
  710. }
  711. }
  712. async function reportShimReady(started, { quiet, report, refreshCatalog, recovery }) {
  713. if (!quiet && started.length) report(`started: ${started.join(', ')}`);
  714. await refreshCatalog().catch(() => { /* advisory only; sidequest just won't see fresh models */ });
  715. return recovery.finish({ ok: true, started });
  716. }
  717. function noticeStaleSession(health) {
  718. const staleSessionNotice = staleSessionReloadNotice(PLUGIN_VERSION, health);
  719. if (staleSessionNotice) noticeForUser(staleSessionNotice, { toStderr: true });
  720. }
  721. async function startAll(options = {}) {
  722. return withLifecycleLock(() => startAllLocked(options));
  723. }
  724. async function startAllLocked({
  725. quiet = false,
  726. lifecycleOperation = null,
  727. proxyExists = () => fs.existsSync(PROXY_BIN),
  728. ensureState = mkdirs,
  729. recordLifecycle = recordGatewayLifecycle,
  730. resolveOwner = resolvePortOwner,
  731. fetchHealth = fetchShimHealth,
  732. probeShim = probeShimState,
  733. reapOrphans = reapGatewayOrphans,
  734. stopSupervisor = stopRunningSupervisor,
  735. spawnSupervisor = spawnDetached,
  736. supervisorAlive = processAlive,
  737. awaitReadiness = waitForStartupReadiness,
  738. refreshCatalog = writeCatalog,
  739. report = log,
  740. preserveRunningSupervisor = false,
  741. resumeIntent = false,
  742. } = {}) {
  743. if (intentionallyStopped() && !resumeIntent) return { ok: false, reason: 'gateway intentionally stopped; run start to resume' };
  744. if (!proxyExists()) return { ok: false, reason: 'proxy binary missing (run setup)' };
  745. ensureState();
  746. const context = {
  747. quiet, lifecycleOperation, recordLifecycle, reapOrphans, stopSupervisor, spawnSupervisor, supervisorAlive, awaitReadiness, refreshCatalog, report,
  748. preserveRunningSupervisor, resumeIntent, timeout: startupWaitMsFor(quiet), recovery: lifecycleRecovery(lifecycleOperation, recordLifecycle),
  749. };
  750. const shim = await readSettledShimState(() => probeShim({ resolveOwner, fetchHealth }), context);
  751. return shimStartPlan(shim, preserveRunningSupervisor)(shim, context);
  752. }
  753. function unknownServingCompatibility(reason) {
  754. return { status: 'unknown', reason };
  755. }
  756. function hasServingCompatibilityHealth(health, supervisorPid) {
  757. return health?.ok === true
  758. && health.supervisorPid === supervisorPid
  759. && typeof health.compat?.hostsDetected === 'boolean'
  760. && typeof health.compat?.port80Bound === 'boolean';
  761. }
  762. async function requestServingCompatibility({ action = 'probe', expectedSupervisorPid = null } = {}) {
  763. const owner = await resolvePortOwner(PUBLIC_SHIM_PORT).catch(() => ({ state: 'unknown', pid: null }));
  764. if (owner.state !== 'same-install' || !Number.isInteger(owner.pid)) {
  765. return unknownServingCompatibility('could not confirm a same-install shim supervisor');
  766. }
  767. if (expectedSupervisorPid != null && owner.pid !== expectedSupervisorPid) {
  768. return unknownServingCompatibility('shim supervisor identity changed');
  769. }
  770. const health = await fetchShimHealth();
  771. if (!hasServingCompatibilityHealth(health, owner.pid)) {
  772. return unknownServingCompatibility('shim health did not confirm the serving supervisor');
  773. }
  774. if (action === 'probe' && health.compat.port80Bound) {
  775. return { status: 'bound', supervisorPid: owner.pid };
  776. }
  777. try {
  778. const response = await postJson(
  779. `http://127.0.0.1:${PUBLIC_SHIM_PORT}${RC_CONTROL_PATH}`,
  780. { action, expectedSupervisorPid: owner.pid },
  781. 3000,
  782. { [RC_CONTROL_HEADER]: RC_CONTROL_VALUE },
  783. );
  784. if (response.status !== 200) return unknownServingCompatibility(`serving control returned ${response.status}`);
  785. const result = JSON.parse(response.body.toString());
  786. if (result?.supervisorPid !== owner.pid || !['bound', 'bindable', 'unavailable', 'unknown'].includes(result.status)) {
  787. return unknownServingCompatibility('serving control returned an unrecognized response');
  788. }
  789. if (result.status === 'unavailable' && typeof result.code !== 'string') {
  790. return unknownServingCompatibility('serving control omitted its bind failure code');
  791. }
  792. return result;
  793. } catch (error) {
  794. return unknownServingCompatibility(error?.message || 'serving control did not respond');
  795. }
  796. }
  797. async function restartSupervisorForVersionMismatch({ quiet = false, operation = 'restart', health = null, fetchHealth = fetchShimHealth, start = startAll } = {}) {
  798. const currentHealth = health || await fetchHealth().catch(() => null);
  799. if (currentHealth && !shimNeedsRestart(PLUGIN_VERSION, currentHealth)) return null;
  800. const stopped = await stopRunningSupervisor({ quiet, operation });
  801. if (!stopped.ok) return stopped;
  802. reportSiblingSupervisorReplacement(stopped, quiet);
  803. return start({ quiet, lifecycleOperation: operation });
  804. }
  805. async function restartShimIfOutdated({
  806. quiet = false,
  807. operation = 'restart',
  808. fetchHealth = fetchShimHealth,
  809. restartWorker = restartWorkerWithDrain,
  810. restartSupervisor = restartSupervisorForVersionMismatch,
  811. start = startAll,
  812. } = {}) {
  813. let health;
  814. try { health = await fetchHealth(); } catch { return null; }
  815. if (!shimNeedsRestart(PLUGIN_VERSION, health)) return null;
  816. return restartSupervisor({ quiet, operation, health, restartWorker, start });
  817. }
  818. // What mode the running shim actually achieved this session: compat only if
  819. // the user's hosts entry is present AND the shim actually managed to bind
  820. // loopback:COMPAT_PORT (never trust the hosts file alone — a bind failure,
  821. // e.g. no permission or something else already on :80, must fall back).
  822. async function resolveIntendedMode() {
  823. const health = await fetchShimHealth();
  824. const compat = (health && health.compat) || { hostsDetected: false, port80Bound: false };
  825. return { mode: compat.hostsDetected && compat.port80Bound ? 'compat' : 'default', compat };
  826. }
  827. // The shim serves these while its proxy is unreachable but never persists them as the discovery cache.
  828. const STAND_IN_CATALOG_NOTES = {
  829. fallback: 'fallback catalog (proxy unreachable)',
  830. 'models.json': 'models.json catalog (proxy unreachable)',
  831. };
  832. function reportAdvertisedModels(health) {
  833. const standIn = STAND_IN_CATALOG_NOTES[health?.catalog];
  834. const catalogNote = standIn ? '; ' + standIn : '';
  835. log(`models advertised to Claude Code: ${health?.models ?? 'unavailable'}${catalogNote}`);
  836. log(health?.proxyRecovery
  837. ? 'proxy recovery: shim supervisor probes /v1/models and restarts an unavailable proxy with bounded backoff'
  838. : 'proxy recovery: unavailable until the shim supervisor is refreshed');
  839. }
  840. function reportShimState(shim) {
  841. const { owner } = shim;
  842. log(describeShimState(shim));
  843. if (owner.state === 'foreign-install') log(`shim supervisor conflict: PID ${owner.pid} owns :${PUBLIC_SHIM_PORT} from a different install root (${owner.installRoot || 'unknown'}).`);
  844. if (owner.identity === 'pid-record') log(`shim supervisor ownership: PID ${owner.pid} matches its recorded start time, but its command line is unavailable. It may be elevated; stop or setup must run from a session with the same privileges.`);
  845. if (owner.reason === 'unreadable-command') log(`shim supervisor ownership: ${unknownPortOwnerReason(owner, PUBLIC_SHIM_PORT)}.`);
  846. }
  847. function reportCompatibilityListener(compat) {
  848. if (!compat) return;
  849. if (!compat.hostsDetected) {
  850. log('RC-compatibility hosts entry: not present (default gateway mode)');
  851. return;
  852. }
  853. log(`RC-compatibility hosts entry: detected (${compat.hostsLine})`);
  854. log(` 127.0.0.1:${COMPAT_PORT} bound: ${compat.port80Bound ? 'yes' : `no${compat.reason ? ` (${compat.reason})` : ''}`}`);
  855. log(' Remote Control transport: this reports local HTTP listener status only, not end-to-end Remote Control.');
  856. }
  857. async function statusReport({ readiness = null, probeShim = probeShimState } = {}) {
  858. const codex = readiness || await getCodexReadiness();
  859. const { checks, health } = codex;
  860. log(`proxy (claude-code-proxy) on :${PROXY_PORT}: ${checks.proxyModels ? 'answering /v1/models' : 'DOWN'}`);
  861. if (checks.shimRunning) reportAdvertisedModels(health);
  862. reportShimState(await probeShim({ fetchHealth: async () => health }));
  863. reportCompatibilityListener(health?.compat);
  864. log(`Codex readiness: ${codex.state}`);
  865. if (!codex.ready) log(codex.message);
  866. reportContextWindows();
  867. log(anthropicCatalogReport());
  868. reportEffectivePins();
  869. return { ok: codex.ready, health, readiness: codex };
  870. }
  871. function reportContextWindows() {
  872. for (const line of contextWindowReport(readContextWindowSettings(), configuredAutoCompactWindow())) {
  873. log(`context window ${line}`);
  874. }
  875. }
  876. // autoCompactWindow is Claude Code's only per-project window knob, so a Claude cap needs project-scoped wiring;
  877. // written at user scope it would cap every project and every model.
  878. function applyClaudeWindowChange(previous, next) {
  879. if (previous === next) return;
  880. const wirings = registeredProjectWirings();
  881. if (next !== 'full' && wirings.length === 0) {
  882. die('a Claude context window cap is written as autoCompactWindow into each project-wired .claude/settings.local.json, and no project is wired to the gateway at project scope. Run /model-gateway:model-gateway, then use its env --write-project command inside the project first; nothing was saved.', 2);
  883. }
  884. reportClaudeWindowSync(syncClaudeContextWindow(wirings.map((wiring) => wiring.file), { owned: previous, next }));
  885. }
  886. function reportClaudeWindowSync(result) {
  887. for (const changed of result.changed) log(`updated autoCompactWindow in ${changed.file}`);
  888. for (const skipped of result.skipped) log(`skipped ${skipped.file}: ${skipped.reason}`);
  889. }
  890. // A project wired after the Claude cap was saved gets it at the next refresh, the same way pins reach it.
  891. // Skips are not reported here: this runs at every session start, and the context-window command already named them.
  892. function refreshRegisteredClaudeWindow() {
  893. const claude = readContextWindowSettings().claude.value;
  894. if (claude === 'full') return;
  895. const files = registeredProjectWirings().map((wiring) => wiring.file);
  896. for (const changed of syncClaudeContextWindow(files, { owned: claude, next: claude }).changed) log(`updated autoCompactWindow in ${changed.file}`);
  897. }
  898. function contextWindowCommand() {
  899. if (!args.length) {
  900. reportContextWindows();
  901. return;
  902. }
  903. const current = readContextWindowSettings();
  904. const saved = savedContextWindows(current);
  905. for (let index = 0; index < args.length; index += 2) {
  906. const update = contextWindowUpdate(args[index], args[index + 1]);
  907. if (update.error) die(update.error, 2);
  908. saveContextWindowUpdate(saved, update);
  909. }
  910. applyClaudeWindowChange(current.claude.value, saved.claude || 'full');
  911. writeContextWindowSettings(saved);
  912. log(`saved context windows to ${CONTEXT_WINDOW_PATH}`);
  913. reportContextWindows();
  914. log('The running gateway serves new Codex and Grok windows after it restarts (stop, then ensure). Restart open Claude Code sessions to pick up a Claude change.');
  915. }
  916. // -------------------------------------------------------------- env wiring
  917. function reportRegisteredPinSync(result) {
  918. for (const wiring of result.changed) log(`updated gateway pins in ${wiring.file}`);
  919. for (const wiring of result.skipped) {
  920. const detail = wiring.key ? `${wiring.key}=${wiring.value}` : wiring.reason;
  921. log(`skipped ${wiring.file}: ${detail} (${wiring.reason})`);
  922. }
  923. for (const pruned of result.pruned) log(`pruned registered project ${pruned.project}: ${pruned.reason}`);
  924. }
  925. function refreshRegisteredProjectPins(ownedPins) {
  926. return reportRegisteredPinSync(syncRegisteredProjectPins({ ownedPins }));
  927. }
  928. // Syncs on every refresh, not only when this refresh moved a pin: a release that bumps the
  929. // shipped default moves the effective pin between plugin versions, and no single refresh sees it.
  930. // The sync writes nothing when every registered project already agrees.
  931. async function refreshDetectedPinsAndWiring(options = {}) {
  932. const ownedPins = ownedPinValues();
  933. const previous = effectivePins();
  934. await refreshDetectedPins(options);
  935. refreshCatalogPins();
  936. reportPinChanges(previous);
  937. refreshRegisteredProjectPins(ownedPins);
  938. refreshRegisteredClaudeWindow();
  939. }
  940. function refreshCatalogPinsAndWiring() {
  941. const ownedPins = ownedPinValues();
  942. const previous = effectivePins();
  943. refreshCatalogPins();
  944. reportPinChanges(previous);
  945. refreshRegisteredProjectPins(ownedPins);
  946. }
  947. function reportPinChanges(previous) {
  948. for (const [alias, pin] of Object.entries(effectivePins())) {
  949. if (pin.value !== previous[alias].value) log(`model-gateway: ${alias} pin moved ${previous[alias].value} -> ${pin.value}`);
  950. reportOutdatedOverride(alias, pin);
  951. }
  952. }
  953. function reportOutdatedOverride(alias, pin) {
  954. if (pin.source !== 'override' || comparePinVersions(pin.newest || '', pin.value) !== 1) return;
  955. log(`${alias} pinned by override to ${pin.value}; catalog has ${pin.newest}; pin --${alias} default follows the catalog`);
  956. }
  957. function reportEffectivePins(label = '', suffix = '') {
  958. for (const [alias, pin] of Object.entries(effectivePins())) {
  959. log(`${label}${alias}${suffix}: ${pin.value} (${pinProvenance(pin)}); newest catalog: ${pin.newest || 'unavailable'}`);
  960. reportOutdatedOverride(alias, pin);
  961. }
  962. }
  963. function updatePinOverride(overrides, option, value) {
  964. const alias = option && option.startsWith('--') ? option.slice(2) : null;
  965. if (!Object.hasOwn(PIN_ALIASES, alias) || value == null) {
  966. die('pin expects --opus, --sonnet, or --fable followed by a model id or default', 2);
  967. }
  968. if (value === 'default') {
  969. delete overrides[alias];
  970. return;
  971. }
  972. if (!isValidPin(value)) die(`invalid ${alias} pin: use a non-empty model id without whitespace or shell characters`, 2);
  973. overrides[alias] = value;
  974. }
  975. function pinCommand() {
  976. if (args.length === 0) {
  977. reportEffectivePins();
  978. return;
  979. }
  980. const ownedPins = ownedPinValues();
  981. const overrides = readPinOverrides();
  982. for (let index = 0; index < args.length; index += 2) {
  983. updatePinOverride(overrides, args[index], args[index + 1]);
  984. }
  985. writePinOverrides(overrides);
  986. refreshRegisteredProjectPins(ownedPins);
  987. log(`saved Claude alias pins to ${PIN_OVERRIDE_PATH}`);
  988. log('Applied the pin change to registered wired projects. Restart open Claude Code sessions to pick it up.');
  989. }
  990. function wiredGatewayEnv() {
  991. return envBlockFor(wiredMode()?.mode || 'default');
  992. }
  993. // Runs the /model comparison at most once per Claude Code version, inside the SessionStart budget,
  994. // and repeats a recorded failure each session until a release or a fix clears it.
  995. async function reportStalePickerRowsOncePerCli() {
  996. if (realClaudeRefusedUnderTest()) return;
  997. const run = () => runPickerGuard({ gatewayEnv: wiredGatewayEnv(), timeoutMs: PICKER_HOOK_PROBE_TIMEOUT_MS });
  998. const result = await pickerGuardForCli(await claudeVersion(), { run });
  999. const lines = result && !result.unverified ? pickerGuardFailureLines(result) : [];
  1000. if (lines.length) noticeForUser(`${lines.join('; ')}. Run \`node "${resolveStableCommandPath()}" doctor\` for both row lists.`);
  1001. }
  1002. async function syncGatewayWiring() {
  1003. await refreshDetectedPinsAndWiring();
  1004. const current = wiredMode();
  1005. if (!current?.scope) return;
  1006. const env = readSettingsForWrite(settingsPath(current.scope)).env || {};
  1007. const expected = envBlockFor(current.mode);
  1008. if (Object.entries(expected).some(([key, value]) => env[key] !== value)) {
  1009. writeEnv(current.scope, false, { mode: current.mode, quiet: true });
  1010. }
  1011. }
  1012. async function syncUnwiredPins() {
  1013. repairProjectWiring(log);
  1014. }
  1015. async function envCommand() {
  1016. for (const retired of ['--mode', '--show-mode']) {
  1017. if (flag(retired)) {
  1018. die(`env ${retired} was removed. Use env --write-project for this project, env --write-user for a shared fallback, or env --remove to unwire this project.`, 2);
  1019. }
  1020. }
  1021. const reconcile = flag('--reconcile');
  1022. const remove = flag('--remove');
  1023. const writeProject = flag('--write-project');
  1024. const writeUser = flag('--write-user');
  1025. if (writeProject && writeUser) die('env accepts either --write-project or --write-user, not both', 2);
  1026. if (reconcile && !writeUser) die('env --reconcile only applies to --write-user', 2);
  1027. if (!writeProject && !writeUser && !remove) {
  1028. log('add this to the "env" block of this project\'s .claude/settings.local.json:');
  1029. log(JSON.stringify({ env: envBlockFor('default') }, null, 2));
  1030. log('\nor use /model-gateway:model-gateway to run its env --write-project command');
  1031. log('\nProject wiring is the default: this local block keeps this project and its executor worktrees routed after restart.');
  1032. log('Use env --write-user only when you deliberately want the same fallback URL in every project.');
  1033. log('RC-compatibility mode is opt-in: run remote-control enable, then re-run with --confirm to let it back up and write the hosts entry for you. It configures compatibility transport, not verified end-to-end Remote Control.');
  1034. return;
  1035. }
  1036. const scope = writeUser ? 'user' : 'project';
  1037. recordProjectWiring();
  1038. if (!remove) await refreshDetectedPinsAndWiring({ force: true });
  1039. writeEnv(scope, remove, { mode: remove ? 'default' : (await resolveIntendedMode()).mode });
  1040. retireWiringModeConfig();
  1041. if (remove || !writeUser) return;
  1042. const targetBaseUrl = readSettingsForWrite(settingsPath('user')).env?.ANTHROPIC_BASE_URL;
  1043. const result = reconcileRegisteredProjectWirings(targetBaseUrl, { confirm: reconcile });
  1044. if (!result.conflicting.length) return;
  1045. log(`${result.conflicting.length} recorded project-local wiring ${result.conflicting.length === 1 ? 'entry overrides' : 'entries override'} the user-scoped URL:`);
  1046. for (const wiring of result.conflicting) log(` ${wiring.file}`);
  1047. if (reconcile) log(`removed model-gateway-owned wiring from ${result.reconciled.length} project${result.reconciled.length === 1 ? '' : 's'}`);
  1048. else log('project files were not changed. To confirm cleanup, invoke env --write-user --reconcile for the model-gateway-owned entries shown above.');
  1049. }
  1050. // mode only matters when writing (not removing); quiet suppresses this
  1051. // function's own logging so a caller doing an automatic mode switch can print
  1052. // its own single, more specific line instead.
  1053. function writeEnv(scope, remove, { mode = 'default', quiet = false } = {}) {
  1054. // Runs for the user scope too: a committed project settings.json carrying
  1055. // gateway keys outranks ~/.claude/settings.json and would shadow this write.
  1056. const migration = remove ? null : migrateLegacyProjectSettings();
  1057. const effectiveMode = migration?.mode || mode;
  1058. const file = settingsPath(scope);
  1059. if (remove && !fs.existsSync(file)) {
  1060. if (scope === 'project') recordProjectWiring();
  1061. return { changed: false, file };
  1062. }
  1063. require('../hooks/registry-writer.js').writeCommandLauncher();
  1064. const settings = readSettingsForWrite(file);
  1065. const original = JSON.stringify(settings);
  1066. require('./readiness-hooks.js').syncReadinessHooks(settings, !remove);
  1067. settings.env = settings.env || {};
  1068. delete settings.env.ANTHROPIC_UNIX_SOCKET;
  1069. if (remove) {
  1070. const preserved = removeGatewayOwnedSettings(settings);
  1071. if (preserved.length) log(`model-gateway: preserved user pins in ${file}: ${preserved.join(', ')}`);
  1072. } else {
  1073. Object.assign(settings.env, envBlockFor(effectiveMode));
  1074. for (const [k, v] of Object.entries(LEGACY_ENV_BLOCK)) {
  1075. if (String(settings.env[k]) === String(v)) delete settings.env[k];
  1076. }
  1077. cleanLegacyGatewayModelCache();
  1078. }
  1079. if (remove && JSON.stringify(settings) === original) {
  1080. if (scope === 'project') recordProjectWiring();
  1081. return { changed: false, file };
  1082. }
  1083. writeSettings(file, settings);
  1084. const verified = readSettingsForWrite(file);
  1085. const expected = remove ? settings.env?.ANTHROPIC_BASE_URL : envBlockFor(effectiveMode).ANTHROPIC_BASE_URL;
  1086. if (verified.env?.ANTHROPIC_BASE_URL !== expected) throw new Error(`Could not verify gateway settings in ${file}`);
  1087. const verifiedMode = verified.env?.ANTHROPIC_BASE_URL === COMPAT_BASE_URL ? 'compat' : 'default';
  1088. if (scope === 'project') recordProjectWiring();
  1089. if (quiet) return { changed: true, file, mode: verifiedMode };
  1090. log(`${remove ? 'removed from' : 'written to'} ${file}`);
  1091. if (!remove) {
  1092. log('new Claude Code sessions now use this wiring. Restart Claude Code, then open /model to see the Codex rows.');
  1093. }
  1094. return { changed: true, file, mode: verifiedMode };
  1095. }
  1096. // Called once per session (from `ensure`, after the shim is confirmed
  1097. // running) to keep the wired env in sync with the hosts file: promotes to
  1098. // compat mode when the entry appears and the shim actually bound :80, reverts
  1099. // to default the moment either condition stops holding (entry removed, or
  1100. // the port became unavailable). Exactly one log line when something changes;
  1101. // silent otherwise. Never touches settings this plugin didn't wire itself.
  1102. async function syncCompatMode({ requiredMode = null } = {}) {
  1103. const { mode: desiredMode, compat } = await resolveIntendedMode();
  1104. if (requiredMode && desiredMode !== requiredMode) return { mode: desiredMode, compat, changed: false };
  1105. migrateLegacyProjectSettings();
  1106. const current = wiredMode();
  1107. const scope = current?.scope || (current ? null : selectedWiringScope());
  1108. const observedMode = current?.mode || 'default';
  1109. if (!scope || desiredMode === observedMode) return { mode: observedMode, compat, changed: false };
  1110. const written = writeEnv(scope, false, { mode: desiredMode, quiet: true });
  1111. const mode = written.mode;
  1112. if (mode === 'compat') {
  1113. log(`model-gateway: hosts entry mapping ${COMPAT_HOST} to loopback detected (${compat.hostsLine}); switched to RC-compatibility transport (http://${COMPAT_HOST} via 127.0.0.1:${COMPAT_PORT}). Restart Claude Code to use the updated transport.`);
  1114. } else {
  1115. const why = compat.hostsDetected
  1116. ? `127.0.0.1:${COMPAT_PORT} is unavailable${compat.reason ? ` (${compat.reason})` : ''}`
  1117. : `the hosts entry mapping ${COMPAT_HOST} to loopback was removed`;
  1118. log(`model-gateway: reverted to default gateway mode (${why}). Restart Claude Code.`);
  1119. }
  1120. return { mode, compat, changed: true };
  1121. }
  1122. // ------------------------------------------------------------------ doctor
  1123. function configuredAutoCompactWindow() {
  1124. const candidates = [{ source: 'CLAUDE_CODE_AUTO_COMPACT_WINDOW', value: process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW }];
  1125. for (const source of ['project-local', 'project-shared', 'user']) {
  1126. const scope = source === 'project-local' ? 'project' : source;
  1127. try {
  1128. const value = JSON.parse(fs.readFileSync(settingsPath(scope), 'utf8')).autoCompactWindow;
  1129. candidates.push({ source: `settings ${source}`, value });
  1130. } catch {}
  1131. }
  1132. for (const candidate of candidates) {
  1133. const window = Number(candidate.value);
  1134. if (Number.isInteger(window) && window > 0) return { source: candidate.source, window };
  1135. }
  1136. return null;
  1137. }
  1138. function windowValue(value) {
  1139. return Number.isFinite(value) ? String(value) : 'upstream-managed';
  1140. }
  1141. function evidenceDate(measurement) {
  1142. const date = String(measurement || '').match(/\b\d{4}-\d{2}-\d{2}\b/);
  1143. if (date) return date[0];
  1144. return String(measurement || '').startsWith('unmeasured') ? 'unmeasured' : 'upstream-managed';
  1145. }
  1146. function nativeModelPolicyIds() {
  1147. return [...new Set([
  1148. ...Object.values(effectivePins()).map((pin) => pin.value),
  1149. 'claude-haiku-4-5',
  1150. ])];
  1151. }
  1152. function modelWindowPolicyRow(id, pickerId = gatewayClientModelId(id)) {
  1153. const policy = resolveGatewayModelPolicy(id);
  1154. if (!policy) return null;
  1155. const clientWindow = pickerId.endsWith('[1m]') ? 1000000 : CODEX_UNKNOWN_MODEL_WINDOW;
  1156. const autoCompact = configuredAutoCompactWindow();
  1157. const sentryPolicy = effectiveSentryPolicy(policy);
  1158. return {
  1159. backend: policy.backend,
  1160. backendId: policy.backend === 'anthropic' ? id.replace(/\[1m\]$/, '') : policy.backendId,
  1161. pickerId,
  1162. backendWindow: policy.backendWindow,
  1163. advertisedWindow: gatewayAdvertisedWindow(id),
  1164. clientWindow,
  1165. clientCompactPoint: 'unverified (native engine headroom)',
  1166. sentry: policy.sentry,
  1167. sentryTrigger: sentryPolicy ? `${sentryPolicy.compactTrigger} (${sentryPolicy.source})` : 'none',
  1168. evidenceDate: evidenceDate(policy.measurement),
  1169. };
  1170. }
  1171. function policyGatewayModelIds(liveIds = []) {
  1172. if (liveIds.length) {
  1173. return [...new Set(liveIds.filter((id) => {
  1174. const policy = resolveGatewayModelPolicy(id);
  1175. return policy?.backend === 'codex' || policy?.backend === 'grok';
  1176. }))];
  1177. }
  1178. return Object.values(MODEL_WINDOW_POLICY)
  1179. .filter((policy) => policy.backendId !== 'default' && policy.backend !== 'anthropic')
  1180. .map((policy) => policy.backendId);
  1181. }
  1182. function modelWindowPolicyRows(liveIds = []) {
  1183. const gatewayRows = policyGatewayModelIds(liveIds).map((id) => modelWindowPolicyRow(id));
  1184. const nativeRows = nativeModelPolicyIds().map((id) => modelWindowPolicyRow(id, id));
  1185. return [...gatewayRows, ...nativeRows].filter(Boolean);
  1186. }
  1187. function expectedShimModelIds(liveIds = []) {
  1188. return modelWindowPolicyRows(liveIds)
  1189. .filter((row) => row.backend !== 'anthropic')
  1190. .map((row) => row.pickerId);
  1191. }
  1192. function modelIdDifference(liveIds) {
  1193. const live = new Set(liveIds);
  1194. const expected = new Set(expectedShimModelIds(liveIds));
  1195. return {
  1196. missing: [...expected].filter((id) => !live.has(id)),
  1197. extra: [...live].filter((id) => !expected.has(id)),
  1198. };
  1199. }
  1200. function reportModelWindowPolicy(liveIds = []) {
  1201. const autoCompact = configuredAutoCompactWindow();
  1202. log(`model window policy: ${autoCompact
  1203. ? `auto-compact cap ${autoCompact.window} (${autoCompact.source})`
  1204. : 'no auto-compact cap configured'}`);
  1205. log('backend id | picker/client id | backend window | advertised window | client window | client compact point | sentry | effective trigger | evidence date');
  1206. for (const row of modelWindowPolicyRows(liveIds)) {
  1207. log([
  1208. row.backendId,
  1209. row.pickerId,
  1210. windowValue(row.backendWindow),
  1211. windowValue(row.advertisedWindow),
  1212. row.clientWindow,
  1213. row.clientCompactPoint,
  1214. row.sentry,
  1215. row.sentryTrigger,
  1216. row.evidenceDate,
  1217. ].join(' | '));
  1218. }
  1219. }
  1220. async function reportLiveShimModelPolicy() {
  1221. let liveIds;
  1222. try {
  1223. liveIds = (await fetchShimModels()).map((model) => model.id);
  1224. } catch (error) {
  1225. log(`live shim model ids: unavailable (${error.message})`);
  1226. reportModelWindowPolicy();
  1227. return false;
  1228. }
  1229. reportModelWindowPolicy(liveIds);
  1230. const { missing, extra } = modelIdDifference(liveIds);
  1231. if (!missing.length && !extra.length) {
  1232. log('live shim model ids: PASS (match the installed policy)');
  1233. return true;
  1234. }
  1235. console.error(`model-gateway: FAIL: live shim model ids differ from policy; missing: ${missing.join(', ') || 'none'}; extra: ${extra.join(', ') || 'none'}. Restart the shim through the normal ensure/setup path, then restart Claude Code sessions so the picker re-discovers.`);
  1236. process.exitCode = 1;
  1237. return false;
  1238. }
  1239. function reportRegisteredProjectPinDisagreements() {
  1240. const result = registeredProjectPinDisagreements();
  1241. for (const pruned of result.pruned) log(`pruned registered project ${pruned.project}: ${pruned.reason}`);
  1242. for (const disagreement of result.disagreements) {
  1243. const staleValue = disagreement.staleValue === undefined ? 'missing' : disagreement.staleValue;
  1244. console.error(`model-gateway: ERROR: registered project pin disagrees in ${disagreement.file}: ${disagreement.key}=${staleValue} (expected ${disagreement.expectedValue}).`);
  1245. }
  1246. return result.disagreements.length > 0;
  1247. }
  1248. function reportProjectWiringIssues() {
  1249. for (const issue of projectWiringIssues()) log(`model-gateway: ${issue.message} in ${issue.file}; run ensure to repair.`);
  1250. }
  1251. const PICKER_HOOK_PROBE_TIMEOUT_MS = 8000;
  1252. async function doctor({ readiness: suppliedReadiness = null } = {}) {
  1253. reportReadinessGate();
  1254. reportProjectWiringIssues();
  1255. recordedGatewayPids();
  1256. const readiness = suppliedReadiness || await getCodexReadiness();
  1257. log(`binary: ${readiness.checks.proxyBinary ? PROXY_BIN : 'MISSING (run setup)'}`);
  1258. if (readiness.checks.proxyBinary) {
  1259. const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', timeout: 10000, windowsHide: true });
  1260. log(`version: ${(v.stdout || v.stderr || '').trim()}`);
  1261. log(`codex auth: ${readiness.checks.codexAuth ? 'authenticated' : 'MISSING'}`);
  1262. }
  1263. try {
  1264. grokBackend.readGrokAuth();
  1265. log(`grok auth: present (${grokBackend.readGrokVersion()})`);
  1266. } catch (error) {
  1267. log(`grok auth: ${error.message}`);
  1268. }
  1269. const status = await statusReport({ readiness });
  1270. const servingVersion = readiness.checks.servingVersion;
  1271. log(`serving shim version: ${servingVersion || 'unavailable'}`);
  1272. for (const line of pickerGuardReport(await runPickerGuard({ gatewayEnv: wiredGatewayEnv() }))) log(line);
  1273. log(`lifecycle evidence: ${lifecycleLogPath()}`);
  1274. const observedExit = latestObservedLifecycleExit();
  1275. if (observedExit) {
  1276. const identity = observedExit.child || { component: observedExit.component, pid: observedExit.pid };
  1277. const exitCode = Object.hasOwn(observedExit, 'exitCode') ? observedExit.exitCode : 'unavailable';
  1278. log(`lifecycle exit evidence: observed ${identity.component} PID ${identity.pid}; exit code ${exitCode}; signal ${observedExit.signal || 'none'}`);
  1279. } else {
  1280. log('lifecycle exit evidence: no observed exit record. A force-killed supervisor or OS termination may leave no final record.');
  1281. }
  1282. const hookWaitCutShort = latestHookWaitCutShort();
  1283. if (hookWaitCutShort) {
  1284. log(`lifecycle startup evidence: SessionStart started the supervisor and stopped waiting after ${QUIET_STARTUP_WAIT_MS / 1000}s; it kept starting in the background (${hookWaitCutShort.at}).`);
  1285. }
  1286. log('model fallback diagnostic: if dispatch and served models appear different, reproduce in a throwaway session with CLAUDE_CODE_NO_MODEL_FALLBACK=true; unset it afterwards. It turns silent fallback into a thrown error identifying the call site, while normal operation should keep graceful fallback for transient 5xx errors.');
  1287. if (readiness.checks.shimRunning && !readiness.checks.servingVersionMatches) {
  1288. log(`model-gateway: VERSION MISMATCH: CLI ${PLUGIN_VERSION}, serving shim ${servingVersion}. Run node "${resolveStableCommandPath()}" ensure to replace the stale supervisor.`);
  1289. }
  1290. const catalog = readCatalog();
  1291. log(catalog && Array.isArray(catalog.models)
  1292. ? `catalog: ${catalog.models.length} models at ${CATALOG_PATH} (writtenBy: ${catalog.writtenBy || 'unknown'})`
  1293. : 'catalog: not written yet');
  1294. await reportGatewayDiscoveryCache();
  1295. reportEffectivePins('Claude ', ' pin');
  1296. if (reportRegisteredProjectPinDisagreements()) process.exitCode = 1;
  1297. await reportLiveShimModelPolicy();
  1298. const activeScope = selectedWiringScope();
  1299. const effective = effectiveBaseUrl();
  1300. const modeFor = (base) => (base === COMPAT_BASE_URL ? 'compat' : base === DEFAULT_BASE_URL ? 'default' : null);
  1301. const labelFor = {
  1302. env: 'process env',
  1303. 'project-local': 'project settings.local.json',
  1304. 'project-shared': 'project settings.json',
  1305. user: 'user settings.json',
  1306. };
  1307. const scopeFor = { 'project-local': 'project', 'project-shared': 'project', user: 'user' };
  1308. const effectiveWired = ourBaseUrls().includes(effective.value);
  1309. const effectiveLocation = effective.source
  1310. ? `${labelFor[effective.source]}${effective.file ? ` (${effective.file})` : ''}`
  1311. : 'none';
  1312. log(`wiring: effective ${effectiveLocation}${effectiveWired ? ' [model-gateway]' : ''}`);
  1313. log('default wiring target: this project\'s .claude/settings.local.json');
  1314. for (const source of ['env', 'project-local', 'project-shared', 'user']) {
  1315. const scope = scopeFor[source];
  1316. const file = source === 'env' ? null : settingsPath(source === 'project-local' ? 'project' : source);
  1317. let base = source === 'env' ? process.env.ANTHROPIC_BASE_URL : null;
  1318. if (file) {
  1319. try { base = JSON.parse(fs.readFileSync(file, 'utf8')).env?.ANTHROPIC_BASE_URL; } catch {}
  1320. }
  1321. const wired = ourBaseUrls().includes(base);
  1322. const mode = modeFor(base);
  1323. const tags = [source === effective.source ? ' [effective]' : '', scope === activeScope ? ' [default write target]' : ''].join('');
  1324. const modeLabel = mode === 'compat' ? ' [RC-compatibility mode]' : mode === 'default' ? ' [default mode]' : '';
  1325. log(`${labelFor[source]}: ${wired ? 'wired' + modeLabel : 'not wired'}${file ? ` (${file})` : ''}${tags}`);
  1326. }
  1327. if (effective.source === 'project-local' && effective.shadowed.some(({ source }) => source === 'user')) {
  1328. log('wiring precedence: project settings.local.json wins over user settings.json.');
  1329. }
  1330. const processEnvBypass = processEnvGatewayBypass(effective);
  1331. if (processEnvBypass) {
  1332. console.error(`model-gateway: ERROR: process env ANTHROPIC_BASE_URL (${effective.value}) bypasses model-gateway and shadows wired ${processEnvBypass.shadowedWiring.file}. A user-controlled Claude Code CLI launch can correct or unset ANTHROPIC_BASE_URL, then restart. If a host replaces it, use the supported Claude Code CLI on this wired project; Desktop routing is unsupported under forced overrides on Windows and macOS. Settings, parent, and User-scope edits cannot be promised to win.`);
  1333. process.exitCode = 1;
  1334. }
  1335. if (!effectiveWired) {
  1336. if (!processEnvBypass) console.error('model-gateway: ERROR: wiring is not configured. Run /model-gateway:model-gateway, then use its env --write-project command and restart Claude Code.');
  1337. process.exitCode = 1;
  1338. }
  1339. const effectiveMode = modeFor(effective.value);
  1340. const shadowedMode = effective.shadowed.find((definition) => {
  1341. const mode = modeFor(definition.value);
  1342. return mode && mode !== effectiveMode;
  1343. });
  1344. if (effectiveMode && shadowedMode) {
  1345. const shadowedLocation = shadowedMode.file || 'process env ANTHROPIC_BASE_URL';
  1346. const effectiveLocation = effective.file || 'process env ANTHROPIC_BASE_URL';
  1347. const resolution = effective.source === 'project-local'
  1348. ? `Project settings.local.json wins. Make the modes agree with env --write-project or remove ANTHROPIC_BASE_URL from ${shadowedLocation}.`
  1349. : effective.source === 'env'
  1350. ? `Process env wins. Update or remove its ANTHROPIC_BASE_URL before changing settings.`
  1351. : `The highest-precedence setting wins. Make the modes agree with env --write-project or remove ANTHROPIC_BASE_URL from ${shadowedLocation}.`;
  1352. console.error(`model-gateway: ERROR: effective ${effectiveLocation} uses ${effectiveMode} mode, but shadowed ${shadowedLocation} uses ${modeFor(shadowedMode.value)} mode. ${resolution} Restart Claude Code.`);
  1353. process.exitCode = 1;
  1354. }
  1355. const scope = installScope();
  1356. if (scope === 'project-only') {
  1357. log('install scope: project (expected for project-local wiring)');
  1358. } else if (scope === 'user') {
  1359. log('install scope: user (shared installation)');
  1360. }
  1361. if (!status.ok) process.exitCode = 1;
  1362. }
  1363. // ---------------------------------------------------------------- the shim
  1364. // display_name feeds the /model PICKER only (with gateway model discovery on,
  1365. // for ids starting with claude-/anthropic-), where it shows correctly as e.g.
  1366. // "GPT-5.6 Terra (Codex)". It does NOT reach the running-subagent CARD: that
  1367. // surface resolves the model label internally and maps an unrecognized claude-*
  1368. // id (like claude-gpt-5.6-terra) to a Claude family name — it renders
  1369. // "Fable 5" for a Terra run. Nothing we return here overrides that (verified:
  1370. // the response model field is "gpt-5.6-terra" and the model self-reports GPT-5,
  1371. // so the RUN is correct — only the card label lies). Native subagent model
  1372. // display isn't a supported feature (anthropics/claude-code#24094, not planned).
  1373. // The sidequest agent NAME (sidequest-exec-codex-gpt-5-6-terra-*) carries the
  1374. // true runtime, so don't chase the badge by editing display_name — it's a dead
  1375. // end. See SQ-202.
  1376. function displayName(id, backend = 'codex') {
  1377. if (backend === 'grok') return id.replace(/^grok-/, 'Grok ').replace(/-/g, ' ');
  1378. return id.replace(/^gpt-/, 'GPT-').replace(/\[1m\]$/, '') + ' (Codex)';
  1379. }
  1380. // claude-code-proxy v0.1.10 has no /v1/models route, so the shim owns the
  1381. // catalog: ~/.claude/model-gateway/models.json if present, else the Codex ids
  1382. // its README documents. A future proxy /v1/models takes precedence over both.
  1383. const PLAN_TOOLS = ['EnterPlanMode', 'ExitPlanMode'];
  1384. const DEFAULT_MODELS = [
  1385. 'gpt-6.1-sol', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-6-astra',
  1386. ];
  1387. const DEFAULT_GROK_MODELS = grokBackend.GROK_MODELS;
  1388. // Claude Code 2.1.261 ignores settings-file CLAUDE_CODE_MAX_CONTEXT_TOKENS for
  1389. // its unrecognized-model resolver. Codex rows therefore use Claude Code's [1m]
  1390. // spelling, chosen from the same context table used for max_input_tokens. The
  1391. // worker sentry retains backend headroom because that spelling is a 1M client
  1392. // window rather than the backend's exact 920k limit.
  1393. function gatewayModel(id, backend = 'codex') {
  1394. const policy = id === 'auto' ? null : resolveGatewayModelPolicy(id);
  1395. if (id !== 'auto' && policy?.backend !== backend) return null;
  1396. return {
  1397. id: id === 'auto' ? DISPATCH_MODEL_ID : gatewayClientModelId(id),
  1398. display_name: id === 'auto' ? 'Sidequest Dispatch (Codex)' : displayName(id, backend),
  1399. type: 'model',
  1400. max_input_tokens: gatewayAdvertisedWindow(id) || codexContextWindow(id),
  1401. };
  1402. }
  1403. // ------------------------------------------------------------ model catalog
  1404. //
  1405. // sidequest (same marketplace) auto-discovers Codex models by reading this
  1406. // file: ~/.claude/model-gateway/catalog.json. Shape is a frozen contract
  1407. // (see plugins/sidequest/lib/discovery.js) — don't change it casually.
  1408. const CATALOG_PATH = path.join(STATE, 'catalog.json');
  1409. const CATALOG_STALE_MS = 5 * 60 * 1000;
  1410. const CATALOG_SCHEMA_VERSION = 4;
  1411. // Slugs keep the `codex-` backend name and so survive the id rename byte for
  1412. // byte: the board's route table pins slugs, and re-slugging would break every
  1413. // persisted route at once.
  1414. //
  1415. // Provider + base, dots→dashes, kept inside ^[a-z0-9][a-z0-9-]{1,31}$; on
  1416. // collision (or an over-length base) fall back to a short deterministic hash
  1417. // so the slug stays unique without depending on iteration order.
  1418. function slugFor(provider, base, used) {
  1419. const providerPrefix = `${provider}-`;
  1420. const providerBase = base.startsWith(providerPrefix) ? base.slice(providerPrefix.length) : base;
  1421. let s = (providerPrefix + providerBase).toLowerCase()
  1422. .replace(/\[1m\]$/, '')
  1423. .replace(/\./g, '-')
  1424. .replace(/[^a-z0-9-]+/g, '-')
  1425. .replace(/-+/g, '-')
  1426. .replace(/^-+|-+$/g, '');
  1427. if (!/^[a-z0-9]/.test(s)) s = 'x' + s;
  1428. if (s.length > 32) {
  1429. const hash = crypto.createHash('sha1').update(s).digest('hex').slice(0, 6);
  1430. s = s.slice(0, 32 - 1 - hash.length) + '-' + hash;
  1431. }
  1432. let unique = s;
  1433. let n = 2;
  1434. while (used.has(unique)) {
  1435. const suffix = '-' + n;
  1436. unique = s.slice(0, Math.max(1, 32 - suffix.length)) + suffix;
  1437. n++;
  1438. }
  1439. used.add(unique);
  1440. return unique;
  1441. }
  1442. // "gpt-5.6-sol" -> "GPT-5.6 Sol", "gpt-5.3-codex-spark" -> "GPT-5.3 Codex Spark"
  1443. function labelFor(base) {
  1444. const rest = base.replace(/^gpt-/, '');
  1445. const m = rest.match(/^(\d+(?:\.\d+)?)(?:-(.+))?$/);
  1446. if (!m) return 'GPT-' + rest.replace(/-/g, ' ');
  1447. const [, ver, suffix] = m;
  1448. const suffixLabel = suffix
  1449. ? ' ' + suffix.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join(' ')
  1450. : '';
  1451. return `GPT-${ver}${suffixLabel}`;
  1452. }
  1453. function modelCatalogDetails(id) {
  1454. const codexBase = codexBaseFromId(id);
  1455. if (codexBase && codexBase !== 'auto') {
  1456. return { provider: 'codex', base: codexBase, label: labelFor(codexBase) };
  1457. }
  1458. if (typeof id === 'string' && id.startsWith(GROK_PREFIX)) {
  1459. const base = id.slice(PREFIX.length).replace(/\[1m\]$/, '');
  1460. return { provider: 'grok', base, label: displayName(base, 'grok') };
  1461. }
  1462. return null;
  1463. }
  1464. function unavailableProviderReadiness(provider) {
  1465. return {
  1466. ready: false,
  1467. state: 'unavailable',
  1468. message: `${provider} readiness is unavailable.`,
  1469. };
  1470. }
  1471. function getGrokReadiness({ readAuth = grokBackend.readGrokAuth } = {}) {
  1472. try {
  1473. readAuth();
  1474. return {
  1475. ready: true,
  1476. state: 'ready',
  1477. message: 'Grok CLI auth is present.',
  1478. };
  1479. } catch (error) {
  1480. const message = error instanceof Error ? error.message : 'Grok CLI auth is unavailable. Run `grok` and log in again.';
  1481. return {
  1482. ready: false,
  1483. state: /invalid/i.test(message) ? 'auth-invalid' : 'auth-missing',
  1484. message,
  1485. };
  1486. }
  1487. }
  1488. function providerCatalogReadiness(provider, readiness) {
  1489. const source = readiness?.[provider] ?? (provider === 'codex' ? readiness : null);
  1490. if (source) return providerReadiness(source);
  1491. if (provider === 'grok') return getGrokReadiness();
  1492. return unavailableProviderReadiness(provider);
  1493. }
  1494. function catalogContextWindow(id, provider) {
  1495. const contextWindow = gatewayAdvertisedWindow(id);
  1496. if (!contextWindow) return {};
  1497. const contextWindowNote = gatewayWindowNote(provider, contextWindowCap(provider), contextWindowCompactAt(provider), resolveGatewayModelPolicy(id));
  1498. return contextWindowNote ? { contextWindow, contextWindowNote } : { contextWindow };
  1499. }
  1500. function buildCatalog(ids, readiness = null) {
  1501. const used = new Set();
  1502. const models = ids
  1503. .map((id) => ({ id, details: modelCatalogDetails(id) }))
  1504. .filter(({ details }) => details)
  1505. .map(({ id, details }) => ({
  1506. slug: slugFor(details.provider, details.base, used),
  1507. id: gatewayClientModelId(id),
  1508. label: details.label,
  1509. provider: details.provider,
  1510. ...catalogContextWindow(id, details.provider),
  1511. }));
  1512. const providers = Object.fromEntries(
  1513. [...new Set(models.map((model) => model.provider))].map((provider) => [provider, providerCatalogReadiness(provider, readiness)]),
  1514. );
  1515. return {
  1516. schemaVersion: CATALOG_SCHEMA_VERSION,
  1517. source: 'model-gateway',
  1518. updatedAt: new Date().toISOString(),
  1519. writtenBy: PLUGIN_VERSION,
  1520. providers,
  1521. codexReadiness: providers.codex ?? null,
  1522. models,
  1523. };
  1524. }
  1525. function readJsonFile(file) {
  1526. try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
  1527. }
  1528. function catalogSchemaVersion(catalog) {
  1529. if (!catalog || typeof catalog !== 'object') return null;
  1530. const version = catalog.schemaVersion ?? catalog.schema;
  1531. return Number.isInteger(version) && version > 0 ? version : null;
  1532. }
  1533. function catalogModelIds(catalog) {
  1534. return new Set(
  1535. Array.isArray(catalog?.models)
  1536. ? catalog.models.filter((model) => typeof model?.id === 'string').map((model) => model.id)
  1537. : [],
  1538. );
  1539. }
  1540. function mergeSubsetCatalog(existing, catalog) {
  1541. if (catalogSchemaVersion(existing) !== CATALOG_SCHEMA_VERSION || !Array.isArray(existing.models)) return catalog;
  1542. const existingIds = catalogModelIds(existing);
  1543. const fetchedIds = catalogModelIds(catalog);
  1544. const isStrictSubset = fetchedIds.size < existingIds.size && [...fetchedIds].every((id) => existingIds.has(id));
  1545. if (!isStrictSubset) return catalog;
  1546. // A removal-only response is indistinguishable from a stale writer. Adding a model makes the response authoritative, so intentional replacement can still remove entries.
  1547. const preserved = existing.models.filter((model) => typeof model?.id === 'string' && !fetchedIds.has(model.id));
  1548. const models = [...catalog.models, ...preserved];
  1549. const providers = { ...catalog.providers };
  1550. for (const model of preserved) {
  1551. if (typeof model.provider === 'string' && !providers[model.provider] && existing.providers?.[model.provider]) {
  1552. providers[model.provider] = existing.providers[model.provider];
  1553. }
  1554. }
  1555. log(`catalog: preserved ${preserved.map((model) => model.id).join(', ')} from a subset write`);
  1556. return { ...catalog, models, providers, codexReadiness: providers.codex ?? null };
  1557. }
  1558. function writeCatalogFile(catalogPath, catalog) {
  1559. const existing = readJsonFile(catalogPath);
  1560. const storedVersion = catalogSchemaVersion(existing);
  1561. if (storedVersion != null && storedVersion > CATALOG_SCHEMA_VERSION) {
  1562. throw new Error(`refusing to overwrite catalog schema ${storedVersion} at ${catalogPath}; this gateway supports schema ${CATALOG_SCHEMA_VERSION}, upgrade required`);
  1563. }
  1564. const nextCatalog = mergeSubsetCatalog(existing, catalog);
  1565. try {
  1566. writeFileAtomically(catalogPath, JSON.stringify(nextCatalog, null, 2) + '\n');
  1567. } catch (error) {
  1568. log(`catalog: could not replace ${catalogPath} (${error.code || error.message}); the models list stays at its previous contents`);
  1569. throw error;
  1570. }
  1571. return nextCatalog;
  1572. }
  1573. async function fetchShimModels() {
  1574. // the shim's own refreshModels() can still be mid-flight right after
  1575. // /healthz starts answering; retry once, short, before giving up
  1576. for (let attempt = 0; attempt < 2; attempt++) {
  1577. const response = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/v1/models`, { timeout: 3000 });
  1578. if (response.status !== 200) throw new Error(`shim /v1/models returned ${response.status}`);
  1579. const models = (JSON.parse(response.body.toString()).data || []).filter((model) => model && typeof model.id === 'string');
  1580. if (models.length || attempt === 1) return models;
  1581. await new Promise((resolve) => setTimeout(resolve, 300));
  1582. }
  1583. return [];
  1584. }
  1585. function discoveryCacheBaseUrl() {
  1586. const baseUrl = effectiveBaseUrl().value;
  1587. if (baseUrl === COMPAT_BASE_URL) return COMPAT_BASE_URL;
  1588. return baseUrl === DEFAULT_BASE_URL ? DEFAULT_BASE_URL : null;
  1589. }
  1590. // An older shim reports no catalog source; its list is written as before.
  1591. function writeGatewayDiscoveryCache(models, catalogSource) {
  1592. const standIn = STAND_IN_CATALOG_NOTES[catalogSource];
  1593. if (standIn) {
  1594. log(`discovery cache: kept; the shim is serving its ${standIn}`);
  1595. return { state: 'skipped', reason: 'stand-in-catalog', modelCount: 0 };
  1596. }
  1597. const result = syncGatewayDiscoveryCache({ models: withPreviousServerRows(withCachedAnthropicRows(models)), baseUrl: discoveryCacheBaseUrl() });
  1598. if (result.state === 'wrote') log(`discovery cache: wrote ${result.modelCount} models`);
  1599. else if (result.state === 'unchanged') log('discovery cache: unchanged');
  1600. return result;
  1601. }
  1602. function cacheAgeLabel(fetchedAt) {
  1603. if (!Number.isFinite(fetchedAt)) return 'unknown age';
  1604. return `${Math.max(0, Math.floor((Date.now() - fetchedAt) / 1000))}s old`;
  1605. }
  1606. async function reportGatewayDiscoveryCache() {
  1607. const cache = readGatewayDiscoveryCache();
  1608. const cachedModels = gatewayDiscoveryModels(cache?.models);
  1609. let liveModels = null;
  1610. try { liveModels = gatewayDiscoveryModels(await fetchShimModels()); } catch {}
  1611. const expectedBaseUrl = discoveryCacheBaseUrl();
  1612. const matchesLiveList = liveModels && cache?.baseUrl === expectedBaseUrl
  1613. && sameGatewayDiscoveryModels(cache.models, liveModels);
  1614. const state = liveModels ? (matchesLiveList ? 'matches live list' : 'stale') : 'live list unavailable';
  1615. log(`discovery cache: ${GATEWAY_MODELS_CACHE}; ${cache ? `${cacheAgeLabel(cache.fetchedAt)}, ${cachedModels.length} models` : 'not written, 0 models'}; ${state}`);
  1616. if (state === 'stale' && expectedBaseUrl !== COMPAT_BASE_URL) {
  1617. log('discovery cache: Claude Code cannot refresh this cache under OAuth login; run ensure or restart after the gateway updates it.');
  1618. }
  1619. }
  1620. async function writeCatalog() {
  1621. const shimModels = await fetchShimModels();
  1622. writeGatewayDiscoveryCache(shimModels, (await fetchShimHealth())?.catalog);
  1623. const ids = shimModels.map((model) => model.id).filter((id) => modelCatalogDetails(id) != null);
  1624. // A zero-model catalog would merge straight back to the stored models with a fresh timestamp, so
  1625. // publishing it would make a shim that advertises nothing routable look like a successful refresh.
  1626. // Refusing is right; returning null was not, because every caller read that as "nothing to do".
  1627. if (!ids.length) throw new Error(`shim advertised ${shimModels.length} model(s), none of them a gateway id`);
  1628. const readiness = await getCodexReadiness();
  1629. const catalog = buildCatalog(ids, readiness);
  1630. mkdirs();
  1631. return writeCatalogFile(CATALOG_PATH, catalog);
  1632. }
  1633. // setup --preserve-wiring ends here. The stable updater runs from whatever directory
  1634. // /update-toolshed was started in, and that directory is not consent to route it
  1635. // through the gateway (GH-292). Recorded projects already had their pins synced by
  1636. // refreshDetectedPinsAndWiring, and each wired session reconciles itself at SessionStart.
  1637. // A loaded machine can outlast the startup wait while the new supervisor is alive and finishes on its own schedule
  1638. // (GH-360); failing the update or starting a second supervisor would both be wrong.
  1639. function warnShimStillStarting(result) {
  1640. log(`model-gateway: warning: shim supervisor ${result.reason}; check \`node "${resolveStableCommandPath()}" status\` in a minute.`);
  1641. }
  1642. async function finishUpdateWithoutWiring() {
  1643. log(`model-gateway: update leaves wiring as recorded and never wires the directory it runs from. To wire a project, run node "${resolveStableCommandPath()}" env --write-project inside it.`);
  1644. await writeCatalog().catch(() => { /* advisory only; the next ensure retries */ });
  1645. await statusReport();
  1646. }
  1647. function readCatalog() {
  1648. return readJsonFile(CATALOG_PATH);
  1649. }
  1650. // "Not answering" was the only reason a refresh ever gave, even when /healthz answered with an error or
  1651. // answered too slowly, which sent people hunting for a dead port that was alive (issue #227).
  1652. async function requireShimHealth() {
  1653. const where = `/healthz on 127.0.0.1:${SHIM_PORT}`;
  1654. const response = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/healthz`, { timeout: 3000 }).catch((error) => {
  1655. throw new Error(`shim is not answering ${where} (${error.message})`);
  1656. });
  1657. if (response.status !== 200) throw new Error(`shim ${where} returned ${response.status}`);
  1658. }
  1659. async function catalogCommand() {
  1660. const jsonOut = flag('--json');
  1661. const refresh = flag('--refresh');
  1662. let catalog = readCatalog();
  1663. const stale = !catalog || (Date.now() - Date.parse(catalog.updatedAt || 0) > CATALOG_STALE_MS);
  1664. let refusal = null;
  1665. if (refresh || stale) {
  1666. try {
  1667. await requireShimHealth();
  1668. catalog = await writeCatalog();
  1669. } catch (error) {
  1670. refusal = error.message;
  1671. }
  1672. }
  1673. if (!catalog) die(`no catalog available yet (${refusal || 'run setup or start first'})`);
  1674. // A refresh that fell back to the stored catalog used to be indistinguishable from one that
  1675. // wrote: exit 0, no diagnostic, an unchanged file the caller then discards as stale (issue #227).
  1676. // stdout stays a machine contract, so the reason goes to stderr, and an explicitly requested
  1677. // refresh also fails the exit code, which is what sidequest's refresh checks.
  1678. if (refusal) console.error(`model-gateway: catalog refresh did not write (${refusal}); kept the stored catalog from ${catalog.updatedAt || 'an unknown time'}`);
  1679. if (refusal && refresh) process.exitCode = 1;
  1680. if (jsonOut) process.stdout.write(JSON.stringify(catalog) + '\n');
  1681. else log(JSON.stringify(catalog, null, 2));
  1682. }
  1683. function loopbackTelemetryEndpoint() {
  1684. if (!ROUTE_TELEMETRY_ENABLED) return null;
  1685. const explicit = process.env.CODEX_GATEWAY_TELEMETRY_ENDPOINT;
  1686. if (explicit === '0') return null;
  1687. let raw = explicit || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
  1688. let appendTracesPath = false;
  1689. if (!raw && process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
  1690. raw = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
  1691. appendTracesPath = true;
  1692. }
  1693. if (!raw) raw = 'http://127.0.0.1:4318/v1/traces';
  1694. try {
  1695. const endpoint = new URL(raw);
  1696. const hostname = endpoint.hostname.replace(/^\[|\]$/g, '').toLowerCase();
  1697. const loopback = hostname === 'localhost' || hostname === '::1' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
  1698. if (!loopback || !['http:', 'https:'].includes(endpoint.protocol)) return null;
  1699. if (hostname === 'localhost') endpoint.hostname = '127.0.0.1';
  1700. if (appendTracesPath) endpoint.pathname = `${endpoint.pathname.replace(/\/$/, '')}/v1/traces`;
  1701. endpoint.search = '';
  1702. endpoint.hash = '';
  1703. return endpoint;
  1704. } catch {
  1705. return null;
  1706. }
  1707. }
  1708. function parseIncomingTraceparent(headers) {
  1709. if (!ROUTE_TELEMETRY_ENABLED) return null;
  1710. const value = headers.traceparent;
  1711. if (typeof value !== 'string') return null;
  1712. const match = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-[0-9a-f-]+)?$/.exec(value.trim());
  1713. if (!match || match[1] === 'ff' || (match[1] === '00' && match[5])) return null;
  1714. if (/^0{32}$/.test(match[2]) || /^0{16}$/.test(match[3])) return null;
  1715. return { traceId: match[2], parentSpanId: match[3], flags: parseInt(match[4], 16) };
  1716. }
  1717. function safeMetadataId(value, maxLength = 128) {
  1718. if (typeof value !== 'string' || value.length < 1 || value.length > maxLength) return null;
  1719. return /^[a-zA-Z0-9][a-zA-Z0-9._:/\[\]-]*$/.test(value) ? value : null;
  1720. }
  1721. function otlpAttribute(key, value) {
  1722. if (value == null) return null;
  1723. if (typeof value === 'boolean') return { key, value: { boolValue: value } };
  1724. if (typeof value === 'number') {
  1725. if (Number.isInteger(value)) return { key, value: { intValue: String(value) } };
  1726. return { key, value: { doubleValue: value } };
  1727. }
  1728. return { key, value: { stringValue: String(value) } };
  1729. }
  1730. function postRouteSpan(endpoint, span) {
  1731. if (!endpoint) return;
  1732. try {
  1733. const body = JSON.stringify({
  1734. resourceSpans: [{
  1735. resource: { attributes: [otlpAttribute('service.name', 'model-gateway')] },
  1736. scopeSpans: [{
  1737. scope: { name: 'eigenwise.codex-gateway' },
  1738. spans: [span],
  1739. }],
  1740. }],
  1741. });
  1742. const client = endpoint.protocol === 'https:' ? https : http;
  1743. const telemetryReq = client.request(endpoint, {
  1744. method: 'POST',
  1745. agent: false,
  1746. headers: {
  1747. 'content-type': 'application/json',
  1748. 'content-length': Buffer.byteLength(body),
  1749. },
  1750. }, (telemetryRes) => telemetryRes.resume());
  1751. telemetryReq.on('socket', (socket) => socket.unref());
  1752. telemetryReq.on('error', () => {});
  1753. telemetryReq.setTimeout(ROUTE_TELEMETRY_TIMEOUT_MS, () => telemetryReq.destroy());
  1754. telemetryReq.end(body);
  1755. } catch {}
  1756. }
  1757. function routeStatus(statusCode, override) {
  1758. if (override) return override;
  1759. if (!Number.isInteger(statusCode)) return 'upstream_error';
  1760. if (statusCode >= 500) return 'server_error';
  1761. if (statusCode >= 400) return 'client_error';
  1762. return 'ok';
  1763. }
  1764. function buildRouteTelemetry(req) {
  1765. const endpoint = loopbackTelemetryEndpoint();
  1766. if (!endpoint) return { setRoute() {}, finish() {} };
  1767. const incoming = parseIncomingTraceparent(req.headers);
  1768. const traceId = incoming?.traceId || crypto.randomBytes(16).toString('hex');
  1769. const spanId = crypto.randomBytes(8).toString('hex');
  1770. const parentSpanId = incoming?.parentSpanId || null;
  1771. const routeId = crypto.randomUUID();
  1772. const sessionId = safeMetadataId(requestHeader(req, 'x-claude-code-session-id'));
  1773. const startedAt = BigInt(Date.now()) * 1000000n;
  1774. const started = process.hrtime.bigint();
  1775. let route = {};
  1776. let finished = false;
  1777. return {
  1778. setRoute(nextRoute) {
  1779. route = { ...nextRoute };
  1780. },
  1781. finish(statusCode, statusOverride = null) {
  1782. if (finished) return;
  1783. finished = true;
  1784. try {
  1785. const elapsed = process.hrtime.bigint() - started;
  1786. const durationMs = Number(elapsed) / 1000000;
  1787. const status = routeStatus(statusCode, statusOverride);
  1788. const attributes = [
  1789. otlpAttribute('source', 'codex-gateway'),
  1790. otlpAttribute('source_event_id', routeId),
  1791. otlpAttribute('source_schema', '1'),
  1792. otlpAttribute('event_name', 'codex_gateway.route'),
  1793. otlpAttribute('route_id', routeId),
  1794. otlpAttribute('trace_id', traceId),
  1795. otlpAttribute('span_id', spanId),
  1796. otlpAttribute('parent_span_id', parentSpanId),
  1797. otlpAttribute('trace_linked', !!incoming),
  1798. otlpAttribute('session_id', sessionId),
  1799. otlpAttribute('selected_model', safeMetadataId(route.selectedModel)),
  1800. otlpAttribute('effective_model', safeMetadataId(route.effectiveModel)),
  1801. otlpAttribute('backend', ['codex', 'anthropic'].includes(route.backend) ? route.backend : null),
  1802. otlpAttribute('effort', ['low', 'medium', 'high', 'xhigh', 'max'].includes(route.effort) ? route.effort : null),
  1803. otlpAttribute('fallback', route.fallback === true),
  1804. otlpAttribute('via', ['direct', 'dispatch', 'dispatch-cached'].includes(route.via) ? route.via : null),
  1805. otlpAttribute('status', status),
  1806. otlpAttribute('status_code', Number.isInteger(statusCode) ? statusCode : null),
  1807. otlpAttribute('duration_ms', durationMs),
  1808. ].filter(Boolean);
  1809. const endedAt = startedAt + elapsed;
  1810. postRouteSpan(endpoint, {
  1811. traceId,
  1812. spanId,
  1813. ...(parentSpanId ? { parentSpanId } : {}),
  1814. ...(incoming ? { flags: incoming.flags } : {}),
  1815. name: 'codex_gateway.route',
  1816. kind: 2,
  1817. startTimeUnixNano: startedAt.toString(),
  1818. endTimeUnixNano: endedAt.toString(),
  1819. attributes,
  1820. events: [{ timeUnixNano: endedAt.toString(), name: 'codex_gateway.route', attributes }],
  1821. status: { code: status === 'ok' ? 1 : 2 },
  1822. });
  1823. } catch {}
  1824. },
  1825. };
  1826. }
  1827. function createRouteTelemetry(req) {
  1828. try {
  1829. return buildRouteTelemetry(req);
  1830. } catch {
  1831. return { setRoute() {}, finish() {} };
  1832. }
  1833. }
  1834. function requestHeader(req, name) {
  1835. const value = req.headers[name];
  1836. return typeof value === 'string' ? value : null;
  1837. }
  1838. // A completed IncomingMessage can be destroyed while its response is still
  1839. // writable. Only upload aborts and the response's state establish disconnects.
  1840. function uploadResponseUnavailable(req, res) {
  1841. return req.aborted || res.destroyed || res.writableEnded || res.socket?.destroyed;
  1842. }
  1843. function sendUploadError(req, res, statusCode) {
  1844. if (uploadResponseUnavailable(req, res)) return;
  1845. res.writeHead(statusCode, {
  1846. 'connection': 'close', 'x-should-retry': 'false',
  1847. ...(statusCode === 400 ? { 'content-type': 'application/json' } : {}),
  1848. });
  1849. res.end(statusCode === 400 ? JSON.stringify({
  1850. type: 'error',
  1851. error: { type: 'invalid_request_error', message: 'model-gateway could not read the request body' },
  1852. }) : undefined);
  1853. }
  1854. function rejectOversizedUpload(req, res) {
  1855. if (uploadResponseUnavailable(req, res)) return;
  1856. res.writeHead(413, { 'connection': 'close', 'content-length': '0', 'x-should-retry': 'false' });
  1857. // Closing with unread upload bytes can reset even a locally flushed response.
  1858. const drainTimeout = setTimeout(() => res.destroy(), 250);
  1859. drainTimeout.unref();
  1860. res.once('close', () => clearTimeout(drainTimeout));
  1861. req.once('end', () => res.end());
  1862. res.flushHeaders();
  1863. req.resume();
  1864. }
  1865. async function collectShimRequestBody(req, res) {
  1866. const chunks = [];
  1867. let size = 0;
  1868. for await (const chunk of req.iterator({ destroyOnReturn: false })) {
  1869. size += chunk.length;
  1870. if (size > 64 * 1024 * 1024) {
  1871. rejectOversizedUpload(req, res);
  1872. return null;
  1873. }
  1874. chunks.push(chunk);
  1875. }
  1876. return Buffer.concat(chunks);
  1877. }
  1878. async function readShimRequestBody(req, res) {
  1879. try {
  1880. const body = await collectShimRequestBody(req, res);
  1881. return uploadResponseUnavailable(req, res) ? null : body;
  1882. } catch (error) {
  1883. // This boundary covers incoming reads only. Worker failures still follow
  1884. // the relay's existing delivery/retry accounting, not this client error.
  1885. if (!['ECONNRESET', 'ERR_STREAM_PREMATURE_CLOSE', 'ABORT_ERR'].includes(error?.code)) {
  1886. sendUploadError(req, res, 400);
  1887. }
  1888. return null;
  1889. }
  1890. }
  1891. function parseCompatibilityControl(body) {
  1892. try { return JSON.parse(body.toString()) ?? {}; } catch { return {}; }
  1893. }
  1894. const {
  1895. catalogReadiness, effectiveSentryPolicy, getCodexReadiness, hasOpenAiRejectionEvidence, noteCodexUpstreamRejection, runWorker,
  1896. } = require('./request-worker.js');
  1897. function createShimRelay({
  1898. httpClient = http,
  1899. getWorker = () => null,
  1900. getWorkerPort = () => 0,
  1901. isStopped = () => false,
  1902. agent,
  1903. getHealthMetadata = () => ({}),
  1904. onWorkerRequestLost = () => {},
  1905. } = {}) {
  1906. // A worker that already took the body may have spent it upstream, so only
  1907. // the loss of that worker justifies sending the request again: a resend to a
  1908. // live worker is a second inference, billed to the user's subscription, that
  1909. // the caller never sees.
  1910. function requestWorker(req, body) {
  1911. return new Promise((resolve, reject) => {
  1912. let settled = false;
  1913. const settle = (finish, value) => {
  1914. if (settled) return;
  1915. settled = true;
  1916. finish(value);
  1917. };
  1918. const lostWorkerRequest = (error, workerThatTookBody) => {
  1919. onWorkerRequestLost(error, workerThatTookBody);
  1920. return Object.assign(error, { bodyTakenByWorker: true });
  1921. };
  1922. const attempt = (attemptsLeft, acceptingWorker) => {
  1923. if (settled) return;
  1924. const canWait = () => attemptsLeft > 0 && !isStopped();
  1925. const waitForAnotherAttempt = (nextAcceptingWorker) => setTimeout(
  1926. () => attempt(attemptsLeft - 1, nextAcceptingWorker), 50,
  1927. );
  1928. if (acceptingWorker && getWorker() === acceptingWorker) {
  1929. if (!canWait()) return settle(reject, lostWorkerRequest(new Error('shim worker never answered the request it had accepted'), acceptingWorker));
  1930. return waitForAnotherAttempt(acceptingWorker);
  1931. }
  1932. const workerPort = getWorkerPort();
  1933. if (!workerPort) {
  1934. if (!canWait()) return settle(reject, new Error('shim worker did not report a listener port'));
  1935. return waitForAnotherAttempt(null);
  1936. }
  1937. let deliveredToWorker = null;
  1938. const upstream = httpClient.request({
  1939. host: '127.0.0.1', port: workerPort, method: req.method, path: req.url,
  1940. headers: { ...req.headers, host: `127.0.0.1:${workerPort}` }, agent,
  1941. }, (response) => settle(resolve, response));
  1942. upstream.once('socket', (socket) => {
  1943. const noteDelivered = () => { deliveredToWorker = getWorker(); };
  1944. if (socket.connecting) socket.once('connect', noteDelivered);
  1945. else noteDelivered();
  1946. });
  1947. upstream.once('error', (error) => {
  1948. if (settled) return;
  1949. if (!canWait()) return settle(reject, deliveredToWorker ? lostWorkerRequest(error, deliveredToWorker) : error);
  1950. waitForAnotherAttempt(deliveredToWorker);
  1951. });
  1952. upstream.end(body);
  1953. };
  1954. attempt(80, null);
  1955. });
  1956. }
  1957. function relayWorkerResponse(req, res, upstream) {
  1958. // Once the worker's headers are out this can no longer become an HTTP
  1959. // error, and `pipe` forwards neither an error nor an abort, so a worker
  1960. // that dies mid-answer would leave the client holding an open response
  1961. // that never completes. Break the connection instead, the way the worker
  1962. // already does when its own upstream dies, so the client sees ECONNRESET
  1963. // and decides for itself whether to ask again.
  1964. upstream.on('error', () => res.destroy());
  1965. upstream.on('aborted', () => res.destroy());
  1966. if (req.url.split('?')[0] === '/healthz') {
  1967. const response = [];
  1968. upstream.on('data', (chunk) => response.push(chunk));
  1969. upstream.once('end', () => {
  1970. const health = JSON.parse(Buffer.concat(response).toString());
  1971. health.supervisorVersion = PLUGIN_VERSION;
  1972. health.supervisorPid = process.pid;
  1973. health.proxyRecovery = true;
  1974. health.compat = getHealthMetadata();
  1975. res.writeHead(upstream.statusCode || 502, upstream.headers);
  1976. res.end(JSON.stringify(health));
  1977. });
  1978. return;
  1979. }
  1980. res.writeHead(upstream.statusCode || 502, upstream.headers);
  1981. upstream.pipe(res);
  1982. }
  1983. function sendWorkerFailure(res, error) {
  1984. // Claude Code resends any retryable status without telling the user:
  1985. // measured at five identical resends of one 503, and `x-should-retry:
  1986. // false` cuts that to none (verification/SQ-2861). So the answer depends
  1987. // on whether a worker took the body: if it did, that inference is
  1988. // already being paid for upstream and a resend silently buys a second
  1989. // one, and if it did not, the resend is free and wanted.
  1990. const bodyTakenByWorker = error?.bodyTakenByWorker === true;
  1991. res.writeHead(503, {
  1992. 'content-type': 'application/json',
  1993. ...(bodyTakenByWorker ? { 'x-should-retry': 'false' } : {}),
  1994. });
  1995. res.end(JSON.stringify({
  1996. type: 'error',
  1997. error: {
  1998. type: 'api_error',
  1999. message: bodyTakenByWorker
  2000. ? 'model-gateway lost the shim worker connection after this request reached the model; that answer cannot be recovered, and retrying automatically would pay for a second inference, so send it again yourself if you still want one'
  2001. : 'model-gateway could not deliver this request to the shim worker; retry it shortly',
  2002. },
  2003. }));
  2004. }
  2005. async function relay(req, res) {
  2006. const body = await readShimRequestBody(req, res);
  2007. if (body === null) return;
  2008. try {
  2009. relayWorkerResponse(req, res, await requestWorker(req, body));
  2010. } catch (error) {
  2011. sendWorkerFailure(res, error);
  2012. }
  2013. }
  2014. return { relay, requestWorker };
  2015. }
  2016. function runShim() {
  2017. mkdirs();
  2018. const controlToken = ensureControlToken();
  2019. const supervisorStartedAt = new Date().toISOString();
  2020. const probeChildren = createProbeChildRegistry();
  2021. let proxyRecovery = null;
  2022. recordGatewayLifecycle('supervisor-started', {
  2023. component: 'supervisor',
  2024. pid: process.pid,
  2025. startedAt: supervisorStartedAt,
  2026. });
  2027. process.once('exit', (exitCode) => {
  2028. proxyRecovery?.stopSync();
  2029. recordGatewayLifecycle('supervisor-exit', {
  2030. component: 'supervisor',
  2031. pid: process.pid,
  2032. startedAt: supervisorStartedAt,
  2033. exitCode,
  2034. });
  2035. });
  2036. process.once('uncaughtExceptionMonitor', (error, origin) => {
  2037. const errorType = typeof error?.name === 'string' ? error.name : 'Error';
  2038. recordGatewayLifecycle('supervisor-uncaught-failure', {
  2039. component: 'supervisor',
  2040. pid: process.pid,
  2041. startedAt: supervisorStartedAt,
  2042. outcome: origin,
  2043. errorType,
  2044. });
  2045. try { writeStartupFailure(`model-gateway: shim supervisor stopped after an uncaught ${errorType}`); } catch {}
  2046. });
  2047. const configuredWorkerPort = Number(process.env.CODEX_GATEWAY_WORKER_PORT || 0);
  2048. const workerPortReportTimeoutMs = 5000;
  2049. let workerPort = configuredWorkerPort;
  2050. const timeout = Number(process.env.CODEX_GATEWAY_DRAIN_TIMEOUT_MS) || 30000;
  2051. const hostsEntry = detectHostsCompat();
  2052. const compatState = { hostsDetected: !!hostsEntry, hostsLine: hostsEntry?.line ?? null, port80Bound: false, reason: null };
  2053. let worker = null;
  2054. // One connection per request. A pooled keep-alive socket the worker closed at
  2055. // the same moment fails after the body is written even though the worker never
  2056. // read it, which is indistinguishable from a worker that took the body and
  2057. // went quiet: measured 4 requests over 1 socket on the default agent, so three
  2058. // of four would have been misread that way (verification/SQ-2861).
  2059. const workerAgent = new http.Agent({ keepAlive: false });
  2060. let workerScript = CLI_PATH;
  2061. let workerPortReportTimeout = null;
  2062. let restarting = false;
  2063. let stopped = false;
  2064. const recoveryIntervalMs = Math.max(1000, Number(process.env.CODEX_GATEWAY_PROXY_RECOVERY_INTERVAL_MS) || 5000);
  2065. proxyRecovery = createProxyRecovery({
  2066. probeChildren,
  2067. onStarted: (pid) => {
  2068. writeProxyServingVersion(currentProxyVersion());
  2069. if (pid) trackSupervisorWrite(writePidRecordAsync('proxy', pid, { probeChildren, stillActive: () => !stopped }));
  2070. },
  2071. recordLifecycle: recordGatewayLifecycle,
  2072. });
  2073. let proxyRecoveryTimer = null;
  2074. let main = null;
  2075. let compatServer = null;
  2076. let compatibilityActions = Promise.resolve();
  2077. let activeCompatibilityProbe = null;
  2078. let shutdownPromise = null;
  2079. const pendingSupervisorWrites = new Set();
  2080. function trackSupervisorWrite(write) {
  2081. const completedWrite = write.catch(() => {});
  2082. pendingSupervisorWrites.add(completedWrite);
  2083. void completedWrite.finally(() => pendingSupervisorWrites.delete(completedWrite));
  2084. }
  2085. function closeServer(server) {
  2086. return new Promise((resolve) => {
  2087. if (!server) return resolve();
  2088. try { server.close(() => resolve()); } catch { resolve(); }
  2089. });
  2090. }
  2091. function serializeCompatibility(action) {
  2092. const result = compatibilityActions.then(action, action);
  2093. compatibilityActions = result.catch(() => {});
  2094. return result;
  2095. }
  2096. function stopCompatibilityProbe() {
  2097. activeCompatibilityProbe?.finish({ status: 'unknown', code: 'ESHUTDOWN' });
  2098. }
  2099. function waitForWorkerExit(child, timeout = 3000) {
  2100. return new Promise((resolve) => {
  2101. if (!child || child.exitCode != null) return resolve(true);
  2102. const timer = setTimeout(() => finish(false), timeout);
  2103. const finish = (exited) => {
  2104. clearTimeout(timer);
  2105. child.off('exit', onExit);
  2106. child.off('error', onExit);
  2107. resolve(exited);
  2108. };
  2109. const onExit = () => finish(true);
  2110. child.once('exit', onExit);
  2111. child.once('error', onExit);
  2112. });
  2113. }
  2114. function stopSupervisor(exitCode, signal = null) {
  2115. if (shutdownPromise) return shutdownPromise;
  2116. stopped = true;
  2117. shutdownPromise = (async () => {
  2118. if (signal) {
  2119. recordGatewayLifecycle('supervisor-stop-requested', {
  2120. component: 'supervisor',
  2121. pid: process.pid,
  2122. startedAt: supervisorStartedAt,
  2123. signal,
  2124. });
  2125. if (worker?.pid) {
  2126. recordGatewayLifecycle('worker-stop-requested', {
  2127. component: 'supervisor',
  2128. pid: process.pid,
  2129. child: { component: 'worker', pid: worker.pid },
  2130. signal: WIN ? 'TASKKILL' : signal,
  2131. });
  2132. }
  2133. }
  2134. clearWorkerPortReportTimeout();
  2135. clearInterval(proxyRecoveryTimer);
  2136. stopCompatibilityProbe();
  2137. const stoppingWorker = worker;
  2138. await proxyRecovery.stop();
  2139. await Promise.all([...pendingSupervisorWrites]);
  2140. await compatibilityActions;
  2141. if (stoppingWorker?.connected) {
  2142. try { stoppingWorker.disconnect(); } catch {}
  2143. }
  2144. if (!(await waitForWorkerExit(stoppingWorker))) {
  2145. await killPidAsync(stoppingWorker?.pid, { trusted: true });
  2146. await waitForWorkerExit(stoppingWorker);
  2147. }
  2148. await Promise.all([closeServer(compatServer), closeServer(main)]);
  2149. process.exit(exitCode);
  2150. })();
  2151. return shutdownPromise;
  2152. }
  2153. function clearWorkerPortReportTimeout() {
  2154. if (!workerPortReportTimeout) return;
  2155. clearTimeout(workerPortReportTimeout);
  2156. workerPortReportTimeout = null;
  2157. }
  2158. function stopForMissingWorkerPort() {
  2159. if (stopped || configuredWorkerPort || workerPort) return;
  2160. console.error(`model-gateway: shim worker did not report its listener port within ${workerPortReportTimeoutMs}ms`);
  2161. void stopSupervisor(1);
  2162. }
  2163. function startWorker() {
  2164. if (stopped || (worker && worker.exitCode == null)) return;
  2165. if (!configuredWorkerPort) {
  2166. workerPort = 0;
  2167. workerPortReportTimeout ||= setTimeout(stopForMissingWorkerPort, workerPortReportTimeoutMs);
  2168. }
  2169. const out = fs.openSync(path.join(LOGS, 'shim.log'), 'a');
  2170. const child = fork(workerScript, ['serve-worker'], {
  2171. stdio: ['ignore', out, out, 'ipc'],
  2172. windowsHide: true,
  2173. env: { ...process.env, CODEX_GATEWAY_WORKER_PORT: String(configuredWorkerPort) },
  2174. });
  2175. fs.closeSync(out);
  2176. worker = child;
  2177. recordGatewayLifecycle('worker-started', {
  2178. component: 'supervisor',
  2179. pid: process.pid,
  2180. startedAt: supervisorStartedAt,
  2181. child: { component: 'worker', pid: child.pid },
  2182. });
  2183. if (!configuredWorkerPort) {
  2184. child.once('message', (message) => {
  2185. const reportedPort = message?.type === 'listening' ? message.port : null;
  2186. if (worker !== child || !Number.isInteger(reportedPort) || reportedPort < 1 || reportedPort > 65535) return;
  2187. workerPort = reportedPort;
  2188. clearWorkerPortReportTimeout();
  2189. });
  2190. }
  2191. trackSupervisorWrite(writePidRecordAsync('shim', child.pid, { probeChildren, stillActive: () => !stopped }));
  2192. child.unref();
  2193. child.once('exit', (exitCode, signal) => {
  2194. recordGatewayLifecycle('worker-exit', {
  2195. component: 'supervisor',
  2196. pid: process.pid,
  2197. startedAt: supervisorStartedAt,
  2198. child: { component: 'worker', pid: child.pid },
  2199. exitCode,
  2200. signal,
  2201. });
  2202. if (worker === child) worker = null;
  2203. removePid('shim', child.pid);
  2204. if (!stopped) setTimeout(startWorker, 50);
  2205. });
  2206. }
  2207. function workerReady() {
  2208. return portListening(workerPort, 100);
  2209. }
  2210. const shimRelay = createShimRelay({
  2211. httpClient: http,
  2212. getWorker: () => worker,
  2213. getWorkerPort: () => workerPort,
  2214. isStopped: () => stopped,
  2215. agent: workerAgent,
  2216. getHealthMetadata: () => ({ ...compatState }),
  2217. onWorkerRequestLost: (error, workerThatTookBody) => {
  2218. recordGatewayLifecycle('worker-request-lost', {
  2219. component: 'supervisor',
  2220. pid: process.pid,
  2221. startedAt: supervisorStartedAt,
  2222. ...(workerThatTookBody?.pid ? { child: { component: 'worker', pid: workerThatTookBody.pid } } : {}),
  2223. outcome: 'response-lost',
  2224. errorType: error.code || error.name,
  2225. });
  2226. },
  2227. });
  2228. async function restartWorker(script) {
  2229. if (script && path.isAbsolute(script) && canReplaceInstalledCliPath(workerScript, script)) workerScript = script;
  2230. const current = worker;
  2231. recordGatewayLifecycle('restart-worker-requested', {
  2232. component: 'supervisor',
  2233. pid: process.pid,
  2234. ...(current?.pid ? { child: { component: 'worker', pid: current.pid } } : {}),
  2235. outcome: current ? 'drain' : 'start',
  2236. });
  2237. restarting = true;
  2238. if (!current) {
  2239. restarting = false;
  2240. startWorker();
  2241. return;
  2242. }
  2243. try { await postJson(`http://127.0.0.1:${workerPort}/drain`, { timeout }, timeout + 1000, controlRequestHeaders()); } catch {}
  2244. setTimeout(() => {
  2245. if (worker === current && current.exitCode == null) {
  2246. console.error(`model-gateway: shim drain timed out after ${Math.ceil(timeout / 1000)}s; force-stopping it.`);
  2247. recordGatewayLifecycle('restart-worker-stop-requested', {
  2248. component: 'supervisor',
  2249. pid: process.pid,
  2250. child: { component: 'worker', pid: current.pid },
  2251. signal: WIN ? 'TASKKILL' : 'SIGTERM',
  2252. outcome: 'drain-timeout',
  2253. });
  2254. void killPidAsync(current.pid, { probeChildren });
  2255. }
  2256. }, timeout);
  2257. current.once('exit', () => {
  2258. restarting = false;
  2259. startWorker();
  2260. });
  2261. }
  2262. function controlRequestAllowed(req, compatibilityListener) {
  2263. return !compatibilityListener
  2264. && req.method === 'POST'
  2265. && localRequestAllowed(req, [`127.0.0.1:${PUBLIC_SHIM_PORT}`])
  2266. && req.headers['content-type'] === 'application/json'
  2267. && requestHeader(req, RC_CONTROL_HEADER) === RC_CONTROL_VALUE;
  2268. }
  2269. function sendControlResponse(res, response) {
  2270. res.writeHead(200, { 'content-type': 'application/json' });
  2271. res.end(JSON.stringify({ ...response, supervisorPid: process.pid }));
  2272. }
  2273. function probeCompatibilityListener() {
  2274. return new Promise((resolve) => {
  2275. const server = net.createServer((socket) => socket.destroy());
  2276. let finished = false;
  2277. const timer = setTimeout(() => finish({ status: 'unknown', code: 'ETIMEDOUT' }), 2000);
  2278. const finish = (result) => {
  2279. if (finished) return;
  2280. finished = true;
  2281. clearTimeout(timer);
  2282. const complete = () => {
  2283. if (activeCompatibilityProbe?.server === server) activeCompatibilityProbe = null;
  2284. resolve(result);
  2285. };
  2286. if (!server.listening) return complete();
  2287. server.once('close', complete);
  2288. try { server.close(); } catch { complete(); }
  2289. };
  2290. activeCompatibilityProbe = { server, finish };
  2291. server.once('error', (error) => finish({ status: 'unavailable', code: error.code || 'EUNKNOWN' }));
  2292. server.once('listening', () => {
  2293. if (finished) return server.close();
  2294. finish({ status: 'bindable' });
  2295. });
  2296. const address = detectHostsCompat()?.ip || '127.0.0.1';
  2297. server.listen(COMPAT_PORT, address);
  2298. });
  2299. }
  2300. function reconcileCompatibilityListener() {
  2301. return serializeCompatibility(async () => {
  2302. const entry = detectHostsCompat();
  2303. await closeServer(compatServer);
  2304. compatServer = null;
  2305. compatState.hostsDetected = !!entry;
  2306. compatState.hostsLine = entry?.line ?? null;
  2307. compatState.port80Bound = false;
  2308. compatState.reason = null;
  2309. if (!entry) return { status: 'bound' };
  2310. return new Promise((resolve) => {
  2311. const server = listen(COMPAT_PORT, entry.ip, () => {
  2312. compatServer = server;
  2313. compatState.port80Bound = true;
  2314. console.log(`model-gateway RC-compatibility supervisor on ${entry.ip}:${COMPAT_PORT}`);
  2315. resolve({ status: 'bound' });
  2316. }, true);
  2317. server.once('error', (error) => {
  2318. if (compatServer === server) compatServer = null;
  2319. compatState.reason = error.code || error.message;
  2320. console.error(`model-gateway: RC-compatibility supervisor unavailable: ${compatState.reason}`);
  2321. resolve({ status: 'unavailable', code: compatState.reason });
  2322. });
  2323. });
  2324. });
  2325. }
  2326. async function handleCompatibilityControl(req, res) {
  2327. async function compatibilityControlResponse(control) {
  2328. if (control.expectedSupervisorPid !== process.pid) return { status: 'unknown' };
  2329. if (control.action === 'probe') {
  2330. return serializeCompatibility(async () => {
  2331. if (compatServer?.listening && compatState.port80Bound) return { status: 'bound' };
  2332. return probeCompatibilityListener();
  2333. });
  2334. }
  2335. if (control.action === 'reconcile') return reconcileCompatibilityListener();
  2336. return { status: 'unknown' };
  2337. }
  2338. const body = await readShimRequestBody(req, res);
  2339. if (body === null) return;
  2340. sendControlResponse(res, await compatibilityControlResponse(parseCompatibilityControl(body)));
  2341. }
  2342. function supervisorRequestAllowed(req, compatibilityListener) {
  2343. const port = req.socket.localPort;
  2344. const hosts = [`127.0.0.1:${port}`, `localhost:${port}`];
  2345. if (compatibilityListener) hosts.push(COMPAT_HOST, `${COMPAT_HOST}:${port}`);
  2346. return localRequestAllowed(req, hosts);
  2347. }
  2348. function handle(req, res, compatibilityListener = false) {
  2349. if (!supervisorRequestAllowed(req, compatibilityListener)) {
  2350. res.writeHead(403);
  2351. res.end();
  2352. return;
  2353. }
  2354. const pathOnly = req.url.split('?')[0];
  2355. if (pathOnly === '/restart' || pathOnly === '/drain') {
  2356. if (!authenticatedControlRequest(req, controlToken, [req.socket.localPort], compatibilityListener)) {
  2357. res.writeHead(403);
  2358. res.end();
  2359. return;
  2360. }
  2361. }
  2362. if (pathOnly === RC_CONTROL_PATH) {
  2363. if (!controlRequestAllowed(req, compatibilityListener)) {
  2364. res.writeHead(404);
  2365. res.end();
  2366. return;
  2367. }
  2368. void handleCompatibilityControl(req, res);
  2369. return;
  2370. }
  2371. if (pathOnly === '/restart') {
  2372. const chunks = [];
  2373. let size = 0;
  2374. req.on('data', (chunk) => {
  2375. size += chunk.length;
  2376. if (size <= 4096) chunks.push(chunk);
  2377. else if (!res.writableEnded) { res.writeHead(413); res.end(); }
  2378. });
  2379. req.on('end', () => {
  2380. if (res.writableEnded) return;
  2381. let script;
  2382. try {
  2383. const body = JSON.parse(Buffer.concat(chunks).toString());
  2384. if (!body || Array.isArray(body) || typeof body !== 'object') throw new Error('invalid restart body');
  2385. script = body.script;
  2386. if (script !== undefined && !canReplaceInstalledCliPath(workerScript, script)) throw new Error('untrusted worker path');
  2387. } catch {
  2388. res.writeHead(400, { 'content-type': 'application/json' });
  2389. res.end(JSON.stringify({ ok: false, reason: 'restart requires this CLI or a non-older sibling in the same plugin cache' }));
  2390. return;
  2391. }
  2392. restartWorker(script);
  2393. res.writeHead(202, { 'content-type': 'application/json' });
  2394. res.end(JSON.stringify({ ok: true, restarting: true }));
  2395. });
  2396. return;
  2397. }
  2398. return shimRelay.relay(req, res);
  2399. }
  2400. function monitorProxy() {
  2401. void proxyRecovery.recover().catch((error) => {
  2402. console.error(`${new Date().toISOString()} model-gateway: proxy recovery failed: ${error.message}`);
  2403. });
  2404. }
  2405. function listen(port, host, callback, compatibilityListener = false) {
  2406. const server = http.createServer((req, res) => handle(req, res, compatibilityListener));
  2407. server.requestTimeout = 0;
  2408. server.headersTimeout = 120000;
  2409. server.keepAliveTimeout = 75000;
  2410. server.listen(port, host, callback);
  2411. return server;
  2412. }
  2413. main = listen(PUBLIC_SHIM_PORT, '127.0.0.1', async () => {
  2414. const publicShimPort = main.address().port;
  2415. try { fs.rmSync(SHIM_FAILURE_PATH); } catch {}
  2416. console.log(`model-gateway shim supervisor listening on 127.0.0.1:${publicShimPort}`);
  2417. await reconcileCompatibilityListener();
  2418. startWorker();
  2419. monitorProxy();
  2420. proxyRecoveryTimer = setInterval(monitorProxy, recoveryIntervalMs);
  2421. proxyRecoveryTimer.unref();
  2422. });
  2423. main.once('error', (error) => {
  2424. void (async () => {
  2425. const owner = error.code === 'EADDRINUSE' ? await processOwningPortAsync(PUBLIC_SHIM_PORT, { probeChildren }) : null;
  2426. const remedy = owner
  2427. ? `PID ${owner} owns 127.0.0.1:${PUBLIC_SHIM_PORT}; run node "${resolveStableCommandPath()}" stop, then node "${resolveStableCommandPath()}" ensure.`
  2428. : `run node "${resolveStableCommandPath()}" stop, then node "${resolveStableCommandPath()}" ensure.`;
  2429. const message = `model-gateway: shim supervisor cannot bind 127.0.0.1:${PUBLIC_SHIM_PORT}: ${error.code || error.message}; ${remedy}`;
  2430. try { writeStartupFailure(message); } catch {}
  2431. console.error(message);
  2432. await stopSupervisor(1);
  2433. })();
  2434. });
  2435. process.once('SIGTERM', () => { void stopSupervisor(0, 'SIGTERM'); });
  2436. process.once('SIGINT', () => { void stopSupervisor(0, 'SIGINT'); });
  2437. if (process.connected) {
  2438. process.once('message', (message) => {
  2439. if (message?.type === 'fixture-shutdown') void stopSupervisor(0, 'fixture-shutdown');
  2440. });
  2441. }
  2442. }
  2443. function sessionStartWiringNotice({ readiness, effectiveWiring, projectWirings }) {
  2444. const processEnvBypass = processEnvGatewayBypass(effectiveWiring);
  2445. if (processEnvBypass) {
  2446. return `Model Gateway is bypassed: process env ANTHROPIC_BASE_URL (${effectiveWiring.value}) shadows wired ${processEnvBypass.shadowedWiring.file}. A user-controlled Claude Code CLI launch can correct or unset ANTHROPIC_BASE_URL, then restart. If a host replaces it, use the supported Claude Code CLI on this wired project; Desktop routing is unsupported under forced overrides on Windows and macOS. Settings, parent, and User-scope edits cannot be promised to win.`;
  2447. }
  2448. if (!readiness.checks.codexAuth) {
  2449. return 'model-gateway is running but not signed in to ChatGPT. Offer to run its login (browser sign-in), then setup to finish wiring. See the model-gateway skill.';
  2450. }
  2451. const locallyWired = effectiveWiring.source === 'project-local' && ourBaseUrls().includes(effectiveWiring.value);
  2452. if (locallyWired) {
  2453. return `Claude Code is wired to model-gateway through project settings.local.json (${effectiveWiring.file}).`;
  2454. }
  2455. const currentProjectFile = path.resolve(settingsPath('project'));
  2456. const siblingWiring = projectWirings.find(({ file }) => path.resolve(file) !== currentProjectFile);
  2457. if (siblingWiring) {
  2458. return `Claude Code is not wired to model-gateway, so your ChatGPT/Codex models are missing from /model. A recorded project-local wiring exists at ${siblingWiring.file}; run \`node "${resolveStableCommandPath()}" env --write-project\` to wire this project's .claude/settings.local.json, then restart Claude Code.`;
  2459. }
  2460. return `Claude Code is not wired to model-gateway, so your ChatGPT/Codex models are missing from /model. Run \`node "${resolveStableCommandPath()}" env --write-project\` to wire this project's .claude/settings.local.json, then restart Claude Code.`;
  2461. }
  2462. function loginSuccessMessage({ wired = isWired(), health = null } = {}) {
  2463. if (wired && health && !shimNeedsRestart(PLUGIN_VERSION, health)) {
  2464. return 'signed in; the proxy picks up the new credential on the next request';
  2465. }
  2466. return 'signed in; run setup once more to finish wiring Claude Code';
  2467. }
  2468. const commands = {
  2469. setup: () => withLifecycleLock(() => setup({ preserveWiring: flag('--preserve-wiring') })),
  2470. login: async () => {
  2471. if (!fs.existsSync(PROXY_BIN)) die('proxy binary missing, run setup first');
  2472. const mode = flag('--device') ? 'device' : 'login';
  2473. const result = spawnSync(PROXY_BIN, ['codex', 'auth', mode], { stdio: 'inherit', windowsHide: true });
  2474. if (result.status === 0) log(loginSuccessMessage({ health: await fetchShimHealth() }));
  2475. process.exitCode = result.status == null ? 1 : result.status;
  2476. },
  2477. start: () => withLifecycleLock(async () => {
  2478. const result = await startAll({ lifecycleOperation: 'start', resumeIntent: true });
  2479. if (!result.ok) die(result.reason);
  2480. await statusReport();
  2481. }),
  2482. recover: () => recoverGateway(),
  2483. 'readiness-gate': () => require('./readiness-gate.js').readinessGate(),
  2484. stop: () => withLifecycleLock(async () => {
  2485. recordIntentionalStop();
  2486. const result = await stopAll();
  2487. if (!result.ok) {
  2488. console.error(`model-gateway: ${result.reason}.`);
  2489. process.exitCode = 1;
  2490. return;
  2491. }
  2492. log('stopped');
  2493. }),
  2494. ensure: async () => {
  2495. const quiet = flag('--quiet');
  2496. if (quiet) bufferedHookLines = [];
  2497. // The hook path exits 0 even on a refusal state, because Claude Code reads a hook's stdout JSON only on a
  2498. // zero exit: exiting nonzero there trades the one user-visible line for a bare "hook failed" badge, which is
  2499. // this ticket's whole complaint (SQ-1901). A direct `ensure` still fails loudly for the updater and for a
  2500. // person running it by hand.
  2501. const finish = (code) => { flushHookOutput(); process.exit(quiet ? 0 : code); };
  2502. migrateReadinessGates();
  2503. cleanLegacyEnvSettings();
  2504. cleanLegacyGatewayModelCache();
  2505. sweepOldProxyBinaries();
  2506. repairProjectWiring(noticeForUser);
  2507. const wired = isWired();
  2508. refreshCatalogPinsAndWiring();
  2509. const initialReadiness = await getCodexReadiness();
  2510. if (!initialReadiness.checks.proxyBinary) {
  2511. if (wired) {
  2512. noticeForUser(initialReadiness.message, { toStderr: true });
  2513. finish(1);
  2514. }
  2515. noticeForUser('model-gateway is installed but not set up. Offer to run its setup (one command; needs a ChatGPT browser sign-in) to put the user\'s ChatGPT/Codex models in the /model picker. See the model-gateway skill.');
  2516. finish(0);
  2517. }
  2518. const result = await ensureWiredGateway(wired, quiet);
  2519. if (!result.ok) {
  2520. if (quiet && result.waitCutShort) {
  2521. if (result.started?.includes('shim')) {
  2522. recordGatewayLifecycle('ensure-hook-wait-cut-short', {
  2523. component: 'SessionStart',
  2524. pid: process.pid,
  2525. outcome: 'supervisor-started',
  2526. });
  2527. }
  2528. noticeForUser('model-gateway is still starting; retry the Codex model in a few seconds', { toStderr: true });
  2529. finish(0);
  2530. }
  2531. noticeForUser(`model-gateway could not start: ${result.reason}. Run \`node "${resolveStableCommandPath()}" doctor\` to see which part is down.`, { toStderr: true });
  2532. finish(1);
  2533. }
  2534. const readiness = await getCodexReadiness();
  2535. if (quiet && !readiness.ready) noticeForUser(readiness.message, { toStderr: true });
  2536. warnIfProxyOutdated();
  2537. const effectiveWiring = effectiveBaseUrl();
  2538. if (!wired) {
  2539. noticeForUser(sessionStartWiringNotice({
  2540. readiness,
  2541. effectiveWiring,
  2542. projectWirings: registeredProjectWirings(),
  2543. }));
  2544. await syncUnwiredPins();
  2545. } else {
  2546. // isWired() accepts a base URL exported by the shell, which is how a machine ends up routed only in the
  2547. // terminal that exported it: background sessions and executor worktrees start unwired, and the only place
  2548. // that said so was a per-request stderr line in the worker.
  2549. const wiring = effectiveWiring;
  2550. if (wiring.source === 'env' && !wiring.shadowed.some((definition) => definition.file)) {
  2551. noticeForUser(`model-gateway wiring is shell-only: ANTHROPIC_BASE_URL comes from this terminal's environment and no settings file sets it, so sessions started anywhere else are not routed through the gateway. Run \`node "${resolveStableCommandPath()}" env --write-project\` to persist it in this project's .claude/settings.local.json.`);
  2552. }
  2553. await syncCompatMode();
  2554. await syncGatewayWiring();
  2555. await reportStalePickerRowsOncePerCli();
  2556. }
  2557. if (!quiet) await statusReport({ readiness });
  2558. flushHookOutput();
  2559. },
  2560. status: async () => { process.exitCode = (await statusReport()).ok ? 0 : 1; },
  2561. models: async () => {
  2562. const result = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/v1/models`, { timeout: 3000 })
  2563. .catch(() => die('shim not running (start it first)'));
  2564. log(JSON.stringify(JSON.parse(result.body.toString()), null, 2));
  2565. },
  2566. catalog: () => catalogCommand(),
  2567. pin: () => pinCommand(),
  2568. 'context-window': () => contextWindowCommand(),
  2569. env: () => envCommand(),
  2570. doctor: (options) => doctor(options),
  2571. 'remote-control': () => remoteControlCommand(),
  2572. 'serve-shim': () => runShim(),
  2573. 'serve-worker': () => runWorker(),
  2574. };
  2575. const ensureCommand = commands.ensure;
  2576. commands.ensure = () => automaticLifecycle(ensureCommand);
  2577. module.exports = {
  2578. commands,
  2579. recoverGateway,
  2580. migrateReadinessGates,
  2581. startupFailureFor,
  2582. writeStartupFailure,
  2583. usage: USAGE,
  2584. parseHostsCompatEntry,
  2585. parseHostsCompatBlock,
  2586. addManagedHostsBlock,
  2587. removeManagedHostsBlock,
  2588. findConflictingHostsMappings,
  2589. managedHostsBlock,
  2590. detectHostsCompat,
  2591. hostsFilePath,
  2592. envBlockFor,
  2593. ourBaseUrls,
  2594. isWired,
  2595. wiredMode,
  2596. writeEnv,
  2597. syncUnwiredPins,
  2598. finishUpdateWithoutWiring,
  2599. migrateLegacyProjectSettings,
  2600. effectiveBaseUrl,
  2601. sessionStartWiringNotice,
  2602. loginSuccessMessage,
  2603. startupWaitMsFor,
  2604. startAll,
  2605. statusReport,
  2606. compatibilityPortOwnerIdentifiers,
  2607. requestServingCompatibility,
  2608. syncCompatMode,
  2609. waitForStartupReadiness,
  2610. settingsPath,
  2611. installScope,
  2612. COMPAT_HOST,
  2613. COMPAT_PORT,
  2614. DEFAULT_BASE_URL,
  2615. COMPAT_BASE_URL,
  2616. SOCKET_PATH,
  2617. WIRING_CONFIG_PATH,
  2618. parseSemver,
  2619. processAlive,
  2620. semverLt,
  2621. resolveNewestInstalledCliPath,
  2622. staleSessionReloadNotice,
  2623. oldProxyPath,
  2624. replaceProxyBinary,
  2625. restartProxyForVersionChange,
  2626. restartProxyIfOutdated,
  2627. sweepOldProxyBinaries,
  2628. shimNeedsRestart,
  2629. servingShimVersion,
  2630. restartShimIfOutdated,
  2631. restartSupervisorForVersionMismatch,
  2632. stopShimWithDrain,
  2633. PLUGIN_VERSION,
  2634. MIN_PROXY_VERSION,
  2635. getCodexReadiness,
  2636. catalogReadiness,
  2637. getGrokReadiness,
  2638. setUpstreamBlocked,
  2639. clearUpstreamBlocked,
  2640. readUpstreamUnavailable,
  2641. setUpstreamUnavailable,
  2642. clearUpstreamUnavailable,
  2643. noteCodexRequestSuccess,
  2644. hasOpenAiRejectionEvidence,
  2645. noteCodexUpstreamRejection,
  2646. CODEX_UPSTREAM_BLOCK_PATH,
  2647. CATALOG_SCHEMA_VERSION,
  2648. codexBaseFromId,
  2649. isGatewayModelId,
  2650. buildCatalog,
  2651. writeCatalogFile,
  2652. modelWindowPolicyRows,
  2653. expectedShimModelIds,
  2654. modelIdDifference,
  2655. createShimRelay,
  2656. };
plugins/sidequest/hooks/guards/guards.test.ts · Bundled script · 107 lines · 1 finding marked
  1. import { expect, mock, test } from 'claude-code/testing'
  2. import type { On } from 'claude-code'
  3. const WINDOWS = { OS: 'Windows_NT', USERPROFILE: 'C:\\Users\\kenny' }
  4. // SQ-3743 probe: classic.PreToolUse gives a module only the envelope, so the guards hook tool.call.
  5. // This pins that shape: a test hook beneath the module sees no agent_type, session_id or cwd.
  6. test('classic.PreToolUse carries only the tool envelope, and a guard deny comes back as the deny', async ($, on) => {
  7. mock.env(on, WINDOWS)
  8. const seen: string[][] = []
  9. on('classic.PreToolUse', ($$, e, next) => {
  10. seen.push(Object.keys(e).sort())
  11. return next(e)
  12. })
  13. passThrough(on)
  14. await $.tool.call({ tool: 'Bash', command: 'echo ok' })
  15. expect(seen).toEqual([['command', 'tool', 'tool_use_id']])
  16. const denied = await $.tool.call({ tool: 'Bash', command: 'rm -rf ~' })
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 20 on GitHub
  17. expect(denied).toMatchObject({ deny: 'sidequest: blocked a recursive delete aimed at the user profile or .claude root. Use a specific project or scratchpad path instead.' })
  18. expect(seen.length).toBe(1)
  19. })
  20. function passThrough(on: On) {
  21. on('session.id', () => ({ value: 'guards-session' }))
  22. on('session.cwd', () => ({ value: 'C:/guards-project' }))
  23. on('fs.read', () => ({ deny: 'ENOENT' }))
  24. on('tool.call', () => ({ result: 'ran', text: 'ran' }) as never)
  25. }
  26. test('an unquoted Windows path in Bash is denied on Windows and allowed elsewhere', async ($, on) => {
  27. mock.env(on, WINDOWS)
  28. passThrough(on)
  29. const denied = await $.tool.call({ tool: 'Bash', command: 'ls C:\\Users\\kenny\\x' })
  30. expect(denied).toMatchObject({ deny: expect.stringContaining('sidequest: unquoted Windows path in a POSIX shell (C:\\Users\\kenny\\x)') })
  31. })
  32. test('a POSIX container path and a Start-Process npm shim get context, not a deny', async ($, on) => {
  33. mock.env(on, WINDOWS)
  34. passThrough(on)
  35. const docker = await $.tool.call({ tool: 'Bash', command: 'docker exec -w /app box ls' })
  36. expect(docker).toMatchObject({ text: 'ran', context: [expect.stringContaining('sidequest: Git Bash rewrites this POSIX container path')] })
  37. const shim = await $.tool.call({ tool: 'PowerShell', command: 'Start-Process -FilePath npm -ArgumentList run' })
  38. expect(shim).toMatchObject({ text: 'ran', context: [expect.stringContaining('sidequest: npm is a .cmd shim on Windows')] })
  39. })
  40. test('the Windows-only guards stay silent off Windows', async ($, on) => {
  41. mock.env(on, { HOME: '/home/kenny' })
  42. passThrough(on)
  43. const ran = await $.tool.call({ tool: 'Bash', command: 'ls C:\\Users\\kenny\\x' })
  44. expect(ran).toMatchObject({ text: 'ran' })
  45. expect(ran.context).toBeUndefined()
  46. })
  47. test('SendMessage retries admission timeouts and preserves the second failure cause', async ($, on) => {
  48. mock.env(on, WINDOWS)
  49. passThrough(on)
  50. let attempts = 0
  51. const logs: string[] = []
  52. const notices: string[] = []
  53. on('process.run', () => {
  54. attempts += 1
  55. if (attempts === 1) return { deny: 'sidequest: $.process.run(node) aborted: still running after 10000ms' }
  56. return { value: { exitCode: 3, stdout: '', stderr: 'dispatch store unavailable' } }
  57. })
  58. on('ui.log', ($$, event) => { logs.push(event.text); return { value: undefined } })
  59. on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
  60. const denied = await $.tool.call({ tool: 'SendMessage', to: 'executor', message: 'continue' } as never)
  61. expect(denied).toMatchObject({ deny: expect.stringContaining('admission decision exited 3: dispatch store unavailable') })
  62. expect(attempts).toBe(2)
  63. expect(logs).toEqual(['guard-executor-admission failed for SendMessage: admission decision exited 3: dispatch store unavailable'])
  64. expect(notices).toEqual(logs)
  65. })
  66. test('an advisory guard error logs and toasts once without a duplicate plugin prefix or sticky status', async ($, on) => {
  67. mock.env(on, WINDOWS)
  68. passThrough(on)
  69. const notices: string[] = []
  70. const logs: object[] = []
  71. const statuses: unknown[] = []
  72. on('state.get', ($$, event, next) => {
  73. if (event.key === 'inlineWork') return { deny: 'state unavailable' }
  74. return next(event)
  75. })
  76. on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
  77. on('ui.log', ($$, event) => { logs.push(event); return { value: undefined } })
  78. on('ui.status', ($$, event) => { statuses.push(event.text); return { value: undefined } })
  79. expect(await $.tool.call({ tool: 'Read', file_path: 'file.txt' })).toMatchObject({ text: 'ran' })
  80. expect(notices).toEqual(['inline-work-nudge failed for Read: sidequest: $.state.get: state unavailable'])
  81. expect(logs).toEqual([{ text: notices[0], to: 'debug' }])
  82. expect(statuses).toEqual([])
  83. })
  84. test('a refusing guard error logs and toasts once and blocks the tool with its error', async ($, on) => {
  85. mock.env(on, WINDOWS)
  86. on('tool.call', () => ({ result: 'ran', text: 'ran' }) as never)
  87. const notices: string[] = []
  88. const logs: object[] = []
  89. on('session.cwd', () => ({ deny: 'session cwd unavailable' }))
  90. on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
  91. on('ui.log', ($$, event) => { logs.push(event); return { value: undefined } })
  92. const denied = await $.tool.call({ tool: 'Read', file_path: 'file.txt', agentId: 'executor' } as never)
  93. expect(denied).toMatchObject({ deny: 'sidequest: guard-denied-tools failed for Read: sidequest: $.session.cwd: session cwd unavailable; tool call refused' })
  94. expect(notices).toEqual(['guard-denied-tools failed for Read: sidequest: $.session.cwd: session cwd unavailable'])
  95. expect(logs).toEqual([{ text: notices[0], to: 'debug' }])
  96. })

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.