eigenwise-toolshed
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.
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
Markdown
[](/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
- {
- "name": "eigenwise-toolshed",
- "owner": {
- "name": "Eigenwise",
- "email": "kenny@eigenwise.io"
- },
- "description": "Eigenwise's toolshed of Claude Code plugins.",
- "version": "3.625.0",
- "plugins": [
- {
- "name": "observability",
- "source": "./plugins/observability",
- "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.",
- "version": "1.1.1",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/observability",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "productivity",
- "keywords": [
- "observability",
- "telemetry",
- "opentelemetry",
- "grafana",
- "statusline",
- "metrics",
- "tokens",
- "cost"
- ]
- },
- {
- "name": "model-gateway",
- "source": "./plugins/model-gateway",
- "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.",
- "version": "0.56.3",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/model-gateway",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "development",
- "keywords": [
- "codex",
- "openai",
- "gpt",
- "chatgpt",
- "model-picker",
- "gateway",
- "proxy",
- "subscription"
- ]
- },
- {
- "name": "sidequest",
- "source": "./plugins/sidequest",
- "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.",
- "version": "6.10.2",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/sidequest",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "productivity",
- "keywords": [
- "tickets",
- "kanban",
- "trello",
- "board",
- "issues",
- "todo",
- "dashboard",
- "capture"
- ]
- },
- {
- "name": "codebase-mapper",
- "source": "./plugins/codebase-mapper",
- "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.",
- "version": "2.15.10",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/codebase-mapper",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "documentation",
- "keywords": [
- "documentation",
- "codebase",
- "mapping",
- "context",
- "grounding",
- "onboarding",
- "architecture",
- "self-maintaining"
- ]
- },
- {
- "name": "quartermaster",
- "source": "./plugins/quartermaster",
- "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.",
- "version": "1.1.2",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/quartermaster",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "productivity",
- "keywords": [
- "resupply",
- "self-improvement",
- "capability",
- "measurement",
- "transcripts",
- "friction",
- "recommendations",
- "setup",
- "workspace",
- "permissions"
- ]
- },
- {
- "name": "quality-gate",
- "source": "./plugins/quality-gate",
- "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.",
- "version": "1.5.1",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/quality-gate",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "productivity",
- "keywords": [
- "quality",
- "complexity",
- "coverage",
- "crap",
- "typescript"
- ]
- },
- {
- "name": "live-rules",
- "source": "./plugins/live-rules",
- "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.",
- "version": "2.11.2",
- "author": {
- "name": "Eigenwise"
- },
- "homepage": "https://github.com/Eigenwise/eigenwise-toolshed/tree/main/plugins/live-rules",
- "repository": "https://github.com/Eigenwise/eigenwise-toolshed",
- "license": "MIT",
- "category": "development",
- "keywords": [
- "rules",
- "context",
- "hooks",
- "guardrails",
- "conventions",
- "standards",
- "runtime",
- "developer-experience"
- ]
- }
- ]
- }
README.md · README · 95 lines
- # Eigenwise Toolshed
- [](https://claude.com/claude-code)
- [](https://eigenwise.github.io/eigenwise-toolshed/)
- [](./LICENSE)
- [](https://github.com/sponsors/Eigenwise)
- [](https://ko-fi.com/eigenwise)
- 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.
- 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?
- 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.
- 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.
- ## The seven plugins
- | Problem | Plugin | What it does |
- | --- | --- | --- |
- | 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. |
- | 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. |
- | 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. |
- | 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. |
- | 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. |
- | 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. |
- | 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. |
- 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.
- ## Start with Quartermaster
- 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.
- From the project directory:
- 1. Add the marketplace.
- ```text
- /plugin marketplace add Eigenwise/eigenwise-toolshed
- ```
- 2. Install Quartermaster for this project. Project scope is the default example because the choice stays with the repository.
- ```text
- /plugin install quartermaster@eigenwise-toolshed --scope project
- ```
- 3. Activate the installed plugin by reloading plugins or starting a new Claude Code session.
- ```text
- /reload-plugins
- ```
- 4. Run setup and approve the plan item by item.
- ```text
- /quartermaster:setup
- ```
- 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`.
- 6. Let setup verify the installed plugins and workspace after that boundary. Try one real request in the project before adding more pieces.
- 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.
- ## Install a plugin directly
- Use the same marketplace with the scope you want:
- ```text
- /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.
- ## Updates and reloads
- `/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.
- 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.
- ## Docs and source
- - [Getting started](https://eigenwise.github.io/eigenwise-toolshed/getting-started/)
- - [Quartermaster setup guide](https://eigenwise.github.io/eigenwise-toolshed/getting-started/quartermaster/)
- - [Plugin reference](https://eigenwise.github.io/eigenwise-toolshed/reference/)
- - [Contributing](https://eigenwise.github.io/eigenwise-toolshed/contributing/)
- - [Release process](https://eigenwise.github.io/eigenwise-toolshed/release-process/)
- - [Support](https://eigenwise.github.io/eigenwise-toolshed/support/)
- - [GitHub repository](https://github.com/Eigenwise/eigenwise-toolshed)
- ## Compatibility
- 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.
- ## Support
- 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.
- ## License
- [MIT](./LICENSE)
plugins/model-gateway/lib/commands.js · Bundled script · 2,870 lines · 1 finding marked
- #!/usr/bin/env node
- 'use strict';
- /*
- * model-gateway: put your ChatGPT/Codex subscription models in Claude Code's
- * /model picker.
- *
- * Two local processes make that happen:
- * 1. claude-code-proxy (raine/claude-code-proxy) translates the Anthropic
- * Messages API to the Codex subscription backend. It owns the OAuth.
- * 2. This file's `serve-shim` mode, a router in front of it. Claude Code's
- * ANTHROPIC_BASE_URL points HERE. Requests for `claude-gpt-*` models
- * are un-prefixed and sent to the proxy; everything else passes through
- * to api.anthropic.com untouched (claude.ai login keeps working). The
- * shim's /v1/models advertises the proxy's Codex models under a bare
- * `claude-` prefix because Claude Code's gateway model discovery drops
- * ids that don't start with "claude" or "anthropic".
- *
- * Default mode above is zero-admin and always available, but Claude Code's
- * built-in /remote-control only lights up when ANTHROPIC_BASE_URL is exactly
- * the real Anthropic host. There's no supported way to get gateway routing
- * and that exact host at once without touching the OS resolver, so it's an
- * opt-in "RC-compatibility" mode: after the user confirms, the remote-control
- * command backs up and writes one hosts entry mapping api.anthropic.com to
- * loopback. The shim then additionally binds loopback:80 and Claude Code's env
- * is pointed at http://api.anthropic.com instead of 127.0.0.1:<shim port>. See
- * detectHostsCompat / syncCompatMode below. Hosts writes require confirmation;
- * the env switch and extra listener follow automatically.
- */
- const { anthropicCatalogReport, withCachedAnthropicRows } = require('./anthropic-catalog.js');
- const { withPreviousServerRows } = require('./previous-picker-rows.js');
- const { pickerGuardFailureLines, pickerGuardForCli, pickerGuardReport, runPickerGuard } = require('./picker-guard.js');
- const { fork, spawn, spawnSync } = require('node:child_process');
- const { StringDecoder } = require('node:string_decoder');
- const crypto = require('node:crypto');
- const fs = require('node:fs');
- const http = require('node:http');
- const https = require('node:https');
- const net = require('node:net');
- const os = require('node:os');
- const path = require('node:path');
- const zlib = require('node:zlib');
- const { writeFileAtomically } = require('./atomic-file.js');
- const { localRequestAllowed, authenticatedControlRequest, controlRequestHeaders, ensureControlToken } = require('./control-auth.js');
- const { downloadVerifiedArchive } = require('./release-verification.js');
- const { fetchLatestRelease } = require('./github-release.js');
- const { createGatewayUsageEmitter, recordRequestBodyHighWater } = require('./usage-observability.js');
- const grokBackend = require('./grok-backend.js');
- const {
- canReplaceInstalledCliPath, CLI_PATH, GATEWAY_MODELS_CACHE, MODEL_WINDOW_POLICY, resolveStableCommandPath,
- gatewayAdvertisedWindow, gatewayClientModelId, gatewayDiscoveryModels, readGatewayDiscoveryCache,
- resolveGatewayModelPolicy, sameGatewayDiscoveryModels, SOCKET_PATH, resolveNewestInstalledCliPath,
- syncGatewayDiscoveryCache, CONTEXT_WINDOW_PATH, contextWindowCap, contextWindowCompactAt, readContextWindowSettings,
- writeContextWindowSettings,
- } = require('./runtime.js');
- const {
- contextWindowReport, contextWindowUpdate, gatewayWindowNote, savedContextWindows, saveContextWindowUpdate, syncClaudeContextWindow,
- } = require('./context-window.js');
- const { latestHookWaitCutShort, latestObservedLifecycleExit, lifecycleLogPath, recordGatewayLifecycle } = require('./lifecycle-diagnostics.js');
- const {
- CODEX_UPSTREAM_BLOCK_PATH, clearUpstreamBlocked, clearUpstreamUnavailable, readUpstreamUnavailable,
- setUpstreamBlocked, setUpstreamUnavailable,
- } = require('./codex-upstream-state.js');
- const { effectivePluginEnabled, pluginDisabledNotice } = require('./recovery-policy.js');
- const { withLifecycleLock, intentionallyStopped, recordIntentionalStop, resumeIntentionalStop } = require('./lifecycle-lock.js');
- const WIN = process.platform === 'win32';
- const STATE = path.join(os.homedir(), '.claude', 'model-gateway');
- const LOGS = path.join(STATE, 'logs');
- const BIN_DIR = path.join(STATE, 'bin');
- const WIRING_CONFIG_PATH = path.join(STATE, 'wiring.json');
- const SHIM_FAILURE_PATH = path.join(STATE, 'shim-supervisor-failure.txt');
- const PLUGIN_VERSION = readPluginVersion();
- const PROXY_BIN = path.join(BIN_DIR, WIN ? 'claude-code-proxy.exe' : 'claude-code-proxy');
- const PROXY_SERVING_VERSION_PATH = path.join(STATE, 'proxy-serving-version.txt');
- const PUBLIC_SHIM_PORT = Number(process.env.CODEX_GATEWAY_PORT || 18764);
- const SHIM_PORT = Number(process.env.CODEX_GATEWAY_WORKER_PORT || PUBLIC_SHIM_PORT);
- const PROXY_PORT = Number(process.env.CODEX_GATEWAY_PROXY_PORT || 18765);
- const QUIET_STARTUP_WAIT_MS = 12000;
- // Advertised ids are `claude-` + the backend's own id (`claude-gpt-5.6-sol`,
- // `claude-grok-4.5`). The `claude-` part is not decoration: Claude Code's
- // gateway model discovery drops every id that doesn't start with claude/
- // anthropic, so an unprefixed id vanishes from /model.
- //
- // Real Anthropic ids share that prefix, so PREFIX alone can NEVER decide a
- // route — matching on it would send claude.ai traffic to the Codex proxy. The
- // backend family segment decides: `gpt-*` is Codex, `grok-*` is Grok, anything
- // else passes through untouched.
- const PREFIX = 'claude-';
- const GROK_PREFIX = 'claude-grok-';
- const CODEX_FAMILY_RE = /^gpt-/;
- // Pre-3.x advertised the backend name too (`claude-codex-gpt-5.6-sol`). Claude
- // Code persists the selected model per project, so those ids outlive the
- // upgrade in every already-wired project; keep resolving them.
- const LEGACY_CODEX_PREFIX = 'claude-codex-';
- // Sidequest's virtual dispatch pin, resolved from the conversation's route
- // marker rather than from the id itself. It keeps the backend name because
- // `codex` here IS the backend (it owns the proxy's OAuth), and because the id
- // is persisted in generated agent defs and board dispatch records.
- const DISPATCH_MODEL_ID = 'claude-codex-auto';
- const GROK_ENDPOINT = process.env.CODEX_GATEWAY_GROK_ENDPOINT || grokBackend.GROK_ENDPOINT;
- const REPO = 'raine/claude-code-proxy';
- // Earliest claude-code-proxy release that maps a context overflow to HTTP 413
- // request_too_large (commit 968cbe2, first tagged in v0.1.14; v0.1.13 has none).
- // Below this the proxy signals overflow with an older, differently-shaped error;
- // `ensure` nudges the user (once, fail-soft) to re-run setup, which fetches latest.
- // Compared numerically (see semverLt); a string compare would read '0.1.9' as
- // newer than '0.1.14'.
- const MIN_PROXY_VERSION = '0.1.14';
- const ANTHROPIC_UPSTREAM = process.env.CODEX_GATEWAY_ANTHROPIC_UPSTREAM || 'https://api.anthropic.com';
- // Enabled by default because route logs are metadata-only: never write prompts,
- // tool payloads, auth, or arbitrary headers. Set to `0` to opt out; a running shim
- // picks this up at its next natural restart. See requestRouteLog below.
- const REQUEST_ROUTE_LOG = process.env.CODEX_GATEWAY_REQUEST_LOG !== '0';
- const REQUEST_ROUTE_LOG_PATH = process.env.CODEX_GATEWAY_REQUEST_LOG_PATH || path.join(LOGS, 'request-routes.jsonl');
- const DISPATCH_ROUTE_CACHE_PATH = process.env.CODEX_GATEWAY_DISPATCH_CACHE_PATH || path.join(STATE, 'dispatch-routes.json');
- const LIST_DISPATCH_MODEL = process.env.CODEX_GATEWAY_LIST_DISPATCH_MODEL === '1';
- const ROUTE_TELEMETRY_ENABLED = process.env.CLAUDE_CODE_PROPAGATE_TRACEPARENT === '1';
- const ROUTE_TELEMETRY_TIMEOUT_MS = 500;
- const TRACE_HEADERS = ['traceparent', 'tracestate', 'baggage'];
- const AUTH_HEADERS = ['authorization', 'proxy-authorization', 'x-api-key', 'cookie'];
- const {
- COMPAT_BASE_URL, COMPAT_HOST, COMPAT_PORT, DEFAULT_BASE_URL, HOSTS_BLOCK_END, HOSTS_BLOCK_LINE,
- HOSTS_BLOCK_START, PIN_ALIASES, PIN_OVERRIDE_PATH, STATIC_ENV_BLOCK, CODEX_UNKNOWN_MODEL_WINDOW,
- codexContextWindow,
- } = require('./runtime.js');
- const {
- codexBaseFromId, detectedPinDefaults, effectivePins, envBlockFor, gatewayEnvBlock, isGatewayModelId,
- claudeVersion, isValidPin, ourBaseUrls, ownedPinValues, realClaudeRefusedUnderTest, pinProvenance, readPinOverrides, refreshDetectedPins, refreshCatalogPins, comparePinVersions, stalePinUpdates,
- writePinOverrides,
- } = require('./pins.js');
- // Versions through 0.4.1 wrote this unsafe global override. Remove it during
- // the next env write/remove, but leave a user-supplied different value alone.
- const LEGACY_ENV_BLOCK = {
- CLAUDE_CODE_AUTO_COMPACT_WINDOW: '950000',
- CLAUDE_CODE_MAX_CONTEXT_TOKENS: '920000',
- };
- const USAGE = `usage: model-gateway.js <command>
- setup download the claude-code-proxy binary (v-latest) into ${BIN_DIR}
- login [--device] run the ChatGPT OAuth flow (--device for headless device-code)
- start | stop start/stop the proxy + shim (detached, logs in ${LOGS})
- ensure [--quiet] maintain installed wiring and start unless intentionally stopped
- recover restore readiness without settings, pin or cache maintenance
- status show what's running
- models show the model list the shim advertises to Claude Code
- catalog [--json] [--refresh] print the sidequest-readable model catalog (${path.join(STATE, 'catalog.json')});
- --refresh exits non-zero and says why on stderr when it could not write a
- fresh one, and prints the retained catalog unchanged
- pin [--opus|--sonnet|--fable <model|default>]
- show pin sources and newest catalog ids, or persist an override (${PIN_OVERRIDE_PATH});
- default removes the override and follows detected/catalog defaults, never backwards
- context-window [--claude <tokens|full>] [--codex <tokens|full>] [--grok <tokens|full>]
- show or persist the context window per backend (${CONTEXT_WINDOW_PATH}); the
- orchestrator and every executor share it. Defaults: claude full, codex 272000,
- grok full. Without compact-at, a gateway cap compacts 85000 below the cap.
- --codex-compact-at <tokens|cap> and --grok-compact-at <tokens|cap> set a direct
- maximum before compaction (positive whole tokens); cap removes the override.
- The cap and backend window minus 40000 still limit the effective maximum.
- A saved compact-at ignores CODEX_GATEWAY_COMPACT_TRIGGER, reported unchanged.
- Example: --codex-compact-at 242000 leaves the 272000 cap unchanged. OpenAI bills
- input above 272k tokens at 2x; the crossing turn and compaction request can still
- exceed 272k. Existing installations keep their current policy until configured.
- --claude sets the native autoCompactWindow in project-wired settings; native
- engine headroom applies and the exact trigger is unverified. Claude compact-at
- is unsupported. No same-model main/subagent split is applied.
- CODEX_GATEWAY_CONTEXT_WINDOW is superseded and only applies when no codex value is saved.
- env [--write-project | --write-user | --remove] [--reconcile]
- print the Claude Code env block, or merge/remove wiring
- --remove clears owned routing, discovery, static env and alias pins; preserves and names user pins
- (--write-project writes .claude/settings.local.json; --write-user
- is an opt-in shared fallback in ~/.claude/settings.json)
- doctor full health check, Anthropic catalog age/fallback, pin sources and newest ids
- remote-control <enable|disable|doctor> [--confirm]
- manage the opt-in hosts-file compatibility mode; enable refuses an effective
- HTTPS api.anthropic.com process URL before hosts changes
- serve-shim (internal) run the router in the foreground
- Request route logging (on by default; set CODEX_GATEWAY_REQUEST_LOG=0 to opt out):
- CODEX_GATEWAY_REQUEST_LOG=0
- Writes JSONL route metadata to ${REQUEST_ROUTE_LOG_PATH}. Override the path with
- CODEX_GATEWAY_REQUEST_LOG_PATH. It records no request bodies, prompts, tools, or auth.`;
- const cmd = process.argv[2];
- const args = process.argv.slice(3);
- const flag = (f) => args.includes(f);
- // A `--json` invocation's stdout is a machine contract. `catalog --refresh --json` writes the catalog on the
- // way out, and that write logs when it preserves models from a subset response, so a diagnostic line landed
- // ahead of the JSON and Sidequest's catalog refresh threw on parse and silently gave up (SQ-2208). Human lines
- // still get emitted, on stderr, where they belong once stdout is data.
- // SessionStart hook stdout is model context and nothing else, so every actionable gateway state reached the
- // model and nobody else: on 2026-08-13 this hook found the session unwired, said so, and the user only learned
- // it hours later by asking which hooks had run (SQ-1901). systemMessage is the one channel Claude Code shows
- // the user, and it is only readable inside a JSON object, so the hook path buffers its lines, hands the model
- // the same text it always got, and puts the states someone has to go fix in front of the user.
- let bufferedHookLines = null;
- const userActionNotices = [];
- function log(m) {
- if (bufferedHookLines) { bufferedHookLines.push(String(m)); return; }
- if (flag('--json')) console.error(m); else console.log(m);
- }
- function noticeForUser(text, { toStderr = false } = {}) {
- userActionNotices.push(text);
- if (bufferedHookLines) bufferedHookLines.push(text);
- else if (toStderr) console.error(text);
- else log(text);
- }
- function flushHookOutput() {
- if (!bufferedHookLines) return;
- const lines = bufferedHookLines;
- bufferedHookLines = null;
- const output = {};
- if (lines.length) output.hookSpecificOutput = { hookEventName: 'SessionStart', additionalContext: lines.join('\n') };
- const [worst, ...rest] = userActionNotices;
- // One line, every session start, so noise discipline is part of the contract: the first actionable state names
- // its own fix, and the rest are counted with the one command that lists them all.
- if (worst) output.systemMessage = rest.length ? `${worst} (+${rest.length} more: run \`node "${resolveStableCommandPath()}" doctor\`)` : worst;
- if (Object.keys(output).length) process.stdout.write(JSON.stringify(output));
- }
- // Flushes first so a die() from anywhere inside the hook path still emits what was buffered; otherwise the
- // buffering below would turn a mid-run failure into total silence.
- function die(m, code) { flushHookOutput(); console.error('model-gateway: ' + m); process.exit(code == null ? 1 : code); }
- function readPluginVersion() {
- try {
- const { version } = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '.claude-plugin', 'plugin.json'), 'utf8'));
- return typeof version === 'string' ? version : null;
- } catch { return null; }
- }
- function mkdirs() { for (const d of [STATE, LOGS, BIN_DIR]) fs.mkdirSync(d, { recursive: true }); }
- const {
- createProbeChildRegistry, createProxyRecovery, fetchUrl, killPidAsync, listeningPidsFromNetstat, portListening, postJson, processOwningPortAsync, recordedGatewayPids, reapGatewayOrphans, resolvePortOwner, unknownPortOwnerReason,
- removePid, restartWorkerWithDrain, shimHealthy, spawnDetached, stopAll, stopProcessAsync, stopRunningSupervisor,
- stopShimWithDrain, waitForShimExit, writePidRecordAsync,
- } = require('./process-supervision.js');
- const { describeShimState, fetchShimHealth, parseSemver, probeShimState, semverLt, servingCurrentVersion, servingShimVersion, shimNeedsRestart } = require('./shim-state.js');
- const {
- removeGatewayOwnedSettings, projectWiringIssues, repairProjectWiring, cleanLegacyEnvSettings, cleanLegacyGatewayModelCache, effectiveBaseUrl, isWired, migrateLegacyProjectSettings,
- processEnvGatewayBypass, readSettingsForWrite, reconcileRegisteredProjectWirings, recordProjectWiring, registeredProjectPinDisagreements, registeredProjectWirings,
- selectedWiringScope, retireWiringModeConfig, settingsPath, syncRegisteredProjectPins, unsafeRemoteControlProcessEnv, wiredMode, writeSettings,
- } = require('./settings-wiring.js');
- // ------------------------------------------------- RC-compatibility hosts
- const {
- addManagedHostsBlock, configureRemoteControl, detectHostsCompat, findConflictingHostsMappings, hostsFilePath,
- managedHostsBlock, parseHostsCompatBlock, parseHostsCompatEntry, removeManagedHostsBlock, remoteControlCommand,
- } = require('./remote-control.js');
- function compatibilityPortOwnerIdentifiers(lookup = spawnSync) {
- const portLookup = WIN
- ? lookup('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8', windowsHide: true })
- : lookup('lsof', ['-nP', `-iTCP:${COMPAT_PORT}`, '-sTCP:LISTEN', '-t'], { encoding: 'utf8', windowsHide: true });
- if (portLookup.status !== 0) return [];
- const output = String(portLookup.stdout);
- return WIN ? listeningPidsFromNetstat(output, COMPAT_PORT) : [...new Set(output.split(/\s+/).map(Number).filter(Boolean))];
- }
- function processNameForIdentifier(processIdentifier) {
- const processLookup = WIN
- ? spawnSync('tasklist', ['/FI', `PID eq ${processIdentifier}`, '/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true })
- : spawnSync('ps', ['-p', String(processIdentifier), '-o', 'comm='], { encoding: 'utf8', windowsHide: true });
- if (processLookup.status !== 0) return null;
- const output = String(processLookup.stdout || '').trim();
- if (!output) return null;
- return WIN ? output.match(/^"([^"]+)"/)?.[1] || null : output;
- }
- function compatibilityPortConflict() {
- const owners = compatibilityPortOwnerIdentifiers().map((processIdentifier) => {
- const processName = processNameForIdentifier(processIdentifier);
- return { processIdentifier, processName };
- });
- if (!owners.length) return null;
- const holders = owners.map(({ processIdentifier, processName }) => {
- const holder = processName ? `${processName} (PID ${processIdentifier})` : `PID ${processIdentifier}`;
- return processName && /docker/i.test(processName) ? `Docker Desktop (${holder})` : holder;
- });
- const includesDockerDesktop = owners.some(({ processName }) => processName && /docker/i.test(processName));
- const releaser = owners.length === 1
- ? (includesDockerDesktop ? 'Docker Desktop' : 'that process')
- : (includesDockerDesktop ? 'Docker Desktop and the other listed processes' : 'the listed processes');
- return `port ${COMPAT_PORT}: held by ${holders.join(', ')}. RC-compatibility cannot start until ${releaser} release${owners.length === 1 ? 's' : ''} port ${COMPAT_PORT}.`;
- }
- const RC_CONTROL_PATH = '/internal/rc-compatibility';
- const RC_CONTROL_HEADER = 'x-model-gateway-control';
- const RC_CONTROL_VALUE = 'rc-compatibility';
- configureRemoteControl({ args, flag, log, die, doctor, fetchShimHealth, requestServingCompatibility, startAll, syncCompatMode, compatibilityPortConflict, unsafeRemoteControlProcessEnv });
- // Model Gateway runs where it is installed. Project-scoped installs and
- // project-local wiring are the standard configuration. We still report an
- // installed user copy for diagnosis, without treating either scope as broken.
- //
- // Returns 'user', 'project-only', or 'unknown' when installed_plugins.json is
- // absent (for example, a --plugin-dir development checkout).
- function installScope(home = os.homedir()) {
- try {
- const file = path.join(home, '.claude', 'plugins', 'installed_plugins.json');
- const data = JSON.parse(fs.readFileSync(file, 'utf8'));
- const entries = Object.entries(data.plugins || {})
- .filter(([pluginId]) => pluginId.startsWith('model-gateway@'))
- .flatMap(([, installs]) => installs);
- if (!entries.length) return 'unknown';
- return entries.some((entry) => entry.scope === 'user') ? 'user' : 'project-only';
- } catch { return 'unknown'; }
- }
- function isAuthed() {
- const r = spawnSync(PROXY_BIN, ['codex', 'auth', 'status'], { encoding: 'utf8', timeout: 15000, windowsHide: true });
- return r.status === 0 && /account/i.test((r.stdout || '') + (r.stderr || ''));
- }
- function noteCodexRequestSuccess() {
- clearUpstreamBlocked();
- clearUpstreamUnavailable();
- }
- function providerReadiness(readiness) {
- return {
- ready: Boolean(readiness?.ready),
- state: typeof readiness?.state === 'string' ? readiness.state : 'unavailable',
- message: typeof readiness?.message === 'string' ? readiness.message : 'Readiness is unavailable.',
- };
- }
- // ------------------------------------------------------------------- setup
- function proxyVersion(version) {
- return Array.isArray(version) ? version.join('.') : null;
- }
- function currentProxyVersion(binary = PROXY_BIN) {
- return proxyVersion(parseSemver((spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim()));
- }
- function oldProxyPath(currentPath, version, now = Date.now()) {
- return `${currentPath}.old-${version || 'unknown'}-${now}`;
- }
- function sweepOldProxyBinaries({ directory = BIN_DIR, basename = path.basename(PROXY_BIN), fsImpl = fs } = {}) {
- let entries;
- try { entries = fsImpl.readdirSync(directory); } catch { return; }
- for (const entry of entries) {
- if (!String(entry).startsWith(`${basename}.old-`)) continue;
- try { fsImpl.rmSync(path.join(directory, entry)); } catch {}
- }
- }
- function replaceProxyBinary({ currentPath = PROXY_BIN, stagedPath, currentVersion, fsImpl = fs, now = Date.now() } = {}) {
- const hadExistingProxy = fsImpl.existsSync(currentPath);
- const previousPath = hadExistingProxy ? oldProxyPath(currentPath, proxyVersion(currentVersion), now) : null;
- if (hadExistingProxy) fsImpl.renameSync(currentPath, previousPath);
- try {
- fsImpl.renameSync(stagedPath, currentPath);
- } catch (error) {
- if (previousPath) fsImpl.renameSync(previousPath, currentPath);
- throw new Error(`proxy upgrade failed (${error.code || error.message}); original proxy restored.`, { cause: error });
- }
- return { hadExistingProxy, previousPath };
- }
- function readProxyServingVersion(file = PROXY_SERVING_VERSION_PATH) {
- try { return fs.readFileSync(file, 'utf8').trim() || null; } catch { return null; }
- }
- function writeProxyServingVersion(version, file = PROXY_SERVING_VERSION_PATH) {
- if (!version) return;
- fs.writeFileSync(file, `${version}\n`);
- }
- async function waitForProxyExit({ listening = portListening, attempts = 7, delay = 100 } = {}) {
- for (let attempt = 0; attempt < attempts; attempt += 1) {
- if (!(await listening(PROXY_PORT))) return true;
- await new Promise((resolve) => setTimeout(resolve, delay));
- }
- return false;
- }
- async function restartProxyForVersionChange({
- previousVersion,
- listening = portListening,
- stop = stopProcessAsync,
- supervisorRunning = async () => (await resolvePortOwner(PUBLIC_SHIM_PORT)).state === 'same-install',
- } = {}) {
- if (previousVersion) writeProxyServingVersion(previousVersion);
- if (await listening(PROXY_PORT)) await stop('proxy');
- if (!(await waitForProxyExit({ listening }))) return false;
- return supervisorRunning();
- }
- async function restartProxyIfOutdated({
- quiet = false,
- currentVersion = currentProxyVersion,
- readServingVersion = readProxyServingVersion,
- restart = restartProxyForVersionChange,
- report = log,
- } = {}) {
- const onDisk = currentVersion();
- const serving = readServingVersion() || onDisk;
- if (!onDisk || !serving || onDisk === serving) return { restarted: false, onDisk, serving };
- const restarted = await restart({ previousVersion: serving });
- if (!restarted && !quiet) report(`proxy on disk: ${onDisk} serving: ${serving} restarts on next \`ensure\``);
- return { restarted, onDisk, serving };
- }
- async function restartSetupProxy({ previousVersion }) {
- if (intentionallyStopped()) return false;
- return restartProxyForVersionChange({ previousVersion });
- }
- async function restartAfterSetup(proxyRecoveryHandoff) {
- if (proxyRecoveryHandoff || intentionallyStopped()) return null;
- const supervisorRestart = await restartShimIfOutdated({ operation: 'setup' });
- if (supervisorRestart) return supervisorRestart;
- const restarting = await restartWorkerWithDrain();
- if (!restarting.ok) die(`could not restart shim worker: ${restarting.reason}`);
- return null;
- }
- async function setup({ preserveWiring = false } = {}) {
- mkdirs();
- refreshCatalogPinsAndWiring();
- migrateReadinessGates();
- sweepOldProxyBinaries();
- const arch = process.arch === 'arm64' ? 'arm64' : 'amd64';
- const plat = WIN ? 'windows' : process.platform === 'darwin' ? 'darwin' : 'linux';
- const ext = WIN ? 'zip' : 'tar.gz';
- const assetName = `claude-code-proxy-${plat}-${arch}.${ext}`;
- let release;
- try { release = await fetchLatestRelease(REPO, { fetchUrl, log }); }
- catch (error) { die(error.message); }
- let archive;
- try { archive = await downloadVerifiedArchive(release, assetName, { fetchUrl, log }); }
- catch (error) { die(error.message); }
- const stage = fs.mkdtempSync(path.join(BIN_DIR, 'stage-'));
- const archiveFile = path.join(stage, assetName);
- fs.writeFileSync(archiveFile, archive);
- const tarBin = WIN
- ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
- : 'tar';
- const tar = spawnSync(tarBin, ['-xf', archiveFile], { encoding: 'utf8', cwd: stage, windowsHide: true });
- if (tar.status !== 0) die(`extract failed: ${tar.stderr || tar.status}`);
- const staged = fs.readdirSync(stage, { recursive: true })
- .map(String).find((file) => path.basename(file) === path.basename(PROXY_BIN));
- if (!staged) die(`extracted, but ${path.basename(PROXY_BIN)} not found in ${BIN_DIR}`);
- const stagedProxy = path.join(stage, staged);
- if (!WIN) fs.chmodSync(stagedProxy, 0o755);
- const currentVersion = parseSemver((spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim());
- const stagedVersion = parseSemver((spawnSync(stagedProxy, ['--version'], { encoding: 'utf8', windowsHide: true }).stdout || '').trim());
- const proxyChanged = !currentVersion || !stagedVersion || currentVersion.join('.') !== stagedVersion.join('.');
- const maintenanceStopped = preserveWiring && intentionallyStopped();
- let proxyRecoveryHandoff = false;
- if (proxyChanged) {
- const previousVersion = proxyVersion(currentVersion);
- const installedVersion = proxyVersion(stagedVersion);
- replaceProxyBinary({ stagedPath: stagedProxy, currentVersion });
- proxyRecoveryHandoff = await restartSetupProxy({ previousVersion });
- if (!proxyRecoveryHandoff) log(`proxy on disk: ${installedVersion || 'unknown'} serving: ${previousVersion || 'unknown'} restarts on next \`ensure\``);
- } else {
- log('model-gateway: proxy unchanged; keeping its authenticated process running.');
- }
- fs.rmSync(stage, { recursive: true, force: true });
- if (maintenanceStopped) return log('Model Gateway updated; intentional stop preserved. Run start to resume.');
- const supervisorRestart = await restartAfterSetup(proxyRecoveryHandoff);
- if (supervisorRestart && !supervisorRestart.ok && !supervisorRestart.stillStarting) die(`could not restart shim supervisor: ${supervisorRestart.reason}`);
- const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', windowsHide: true });
- log(`installed: ${(v.stdout || v.stderr || '').trim() || PROXY_BIN}`);
- if (supervisorRestart?.stillStarting) return warnShimStillStarting(supervisorRestart);
- // one-shot: start everything, and finish the wiring when auth already works
- const r = await startAll({ lifecycleOperation: 'setup', resumeIntent: !preserveWiring, preserveRunningSupervisor: proxyRecoveryHandoff });
- if (r.stillStarting) return warnShimStillStarting(r);
- if (!r.ok) die(r.reason);
- clearUpstreamBlocked();
- clearUpstreamUnavailable();
- if (!isAuthed()) {
- log(`next: node "${resolveStableCommandPath()}" login (ChatGPT browser sign-in), then setup again to wire Claude Code`);
- return;
- }
- log('ChatGPT auth: valid');
- await refreshDetectedPinsAndWiring({ force: true });
- if (preserveWiring) return finishUpdateWithoutWiring();
- const { mode } = await resolveIntendedMode();
- if (isWired()) {
- const current = wiredMode();
- if (!current || !current.scope) {
- // Refusing to copy an environment value into settings is deliberate (it may point at someone's dev
- // instance), but saying only that left no route forward, so setup skipped the write on every run and the
- // machine stayed permanently wired by one terminal (SQ-1901). Name the command that does converge it.
- 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.`);
- } else if (current.mode !== mode) {
- writeEnv(current.scope, false, { mode, quiet: true });
- log(`model-gateway: hosts compatibility state changed since last wired; switched ${current.scope} settings to ${mode} mode. Restart Claude Code.`);
- } else {
- writeEnv(current.scope, false, { mode, quiet: true });
- log('already wired; refreshed Claude alias pins. Restart Claude Code and open /model');
- }
- await statusReport();
- return;
- }
- writeEnv(selectedWiringScope(), false, { mode });
- await writeCatalog().catch(() => { /* advisory only; Claude Code can retry on the next ensure */ });
- await statusReport();
- }
- // ------------------------------------------------------- process management
- function servingVersionIsCurrentOrNewer(servingVersion, installedVersion) {
- if (servingVersion === installedVersion) return true;
- const serving = parseSemver(servingVersion);
- const installed = parseSemver(installedVersion);
- return Boolean(serving && installed && !semverLt(serving, installed));
- }
- function servingVersionIsNewer(servingVersion, installedVersion) {
- const serving = parseSemver(servingVersion);
- const installed = parseSemver(installedVersion);
- return Boolean(serving && installed && semverLt(installed, serving));
- }
- function staleSessionReloadNotice(installedVersion, health) {
- const servingVersion = servingShimVersion(health);
- if (!servingVersionIsNewer(servingVersion, installedVersion)) return null;
- 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.`;
- }
- // Fail-soft: read the running proxy's --version and, if it's below
- // MIN_PROXY_VERSION, print exactly one stderr nudge. Never throws and never
- // blocks the session; a version we can't read/parse is treated as "don't nag".
- // Does NOT auto-download; that belongs in `setup`, not the 30s keepalive hook.
- function warnIfProxyOutdated() {
- try {
- const floor = parseSemver(MIN_PROXY_VERSION);
- const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', timeout: 10000, windowsHide: true });
- const got = parseSemver((v.stdout || '') + (v.stderr || ''));
- if (got && floor && semverLt(got, floor)) {
- 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).`);
- }
- } catch { /* fail-soft: a version check must never break the session */ }
- }
- function startupWaitMsFor(quiet) {
- return quiet
- ? QUIET_STARTUP_WAIT_MS
- : Math.max(12000, (Number(process.env.CODEX_GATEWAY_DRAIN_TIMEOUT_MS) || 30000) + 12000);
- }
- async function ensureWiredGateway(wired, quiet) {
- if (!wired || recoveryExplicitlyDisabled()) return { ok: true, started: [] };
- const proxyRestart = await restartProxyIfOutdated({ quiet });
- return startAll({ quiet, lifecycleOperation: 'ensure', preserveRunningSupervisor: proxyRestart.restarted });
- }
- async function automaticLifecycle(operation) {
- if (recoveryExplicitlyDisabled()) return;
- return withLifecycleLock(() => {
- if (intentionallyStopped()) {
- noticeForUser('model-gateway is intentionally stopped; run start to resume.', { toStderr: true });
- return;
- }
- return operation();
- });
- }
- function reportReadinessGate() {
- const effective = effectiveBaseUrl();
- const file = effective.file || effective.shadowed.find((definition) => definition.file)?.file;
- const settings = file ? readSettingsForWrite(file) : {};
- const present = require('./readiness-hooks.js').readinessHookPresent(settings);
- log(`readiness gate installed: ${present}; hooks disabled: ${settings.disableAllHooks === true}; settings: ${file || 'none'}`);
- log(`intentional stop: ${intentionallyStopped()}; state: ${require('./lifecycle-lock.js').STOP_PATH}`);
- log(`explicit plugin disable: ${effectivePluginEnabled() === false}`);
- log(`recovery diagnostics: ${LOGS}; startup failures: ${SHIM_FAILURE_PATH}`);
- }
- function migrateReadinessGates() {
- require('../hooks/registry-writer.js').writeCommandLauncher();
- const files = registeredProjectWirings().map((wiring) => wiring.file);
- files.push(settingsPath('user'));
- for (const file of files) migrateReadinessGate(file);
- }
- function migrateReadinessGate(file) {
- const settings = readSettingsForWrite(file);
- if (!ourBaseUrls().includes(settings.env?.ANTHROPIC_BASE_URL)) return;
- const original = JSON.stringify(settings);
- require('./readiness-hooks.js').syncReadinessHooks(settings, true);
- if (JSON.stringify(settings) !== original) writeSettings(file, settings);
- }
- function startupFailureFor(supervisorPid, startupGeneration) {
- try {
- const failure = JSON.parse(fs.readFileSync(SHIM_FAILURE_PATH, 'utf8'));
- if (failure.supervisorPid !== supervisorPid) return null;
- if (startupGeneration && failure.generation !== startupGeneration) return null;
- return failure.message;
- } catch { return null; }
- }
- function writeStartupFailure(message) {
- writeFileAtomically(SHIM_FAILURE_PATH, JSON.stringify({ supervisorPid: process.pid, generation: process.env.MODEL_GATEWAY_STARTUP_GENERATION, message }));
- }
- function recoveryExplicitlyDisabled() {
- if (effectivePluginEnabled() !== false) return false;
- noticeForUser(pluginDisabledNotice(), { toStderr: true });
- return true;
- }
- async function recoverGateway() {
- if (recoveryExplicitlyDisabled()) return { ok: true, started: [] };
- const result = await startAll({ quiet: true, lifecycleOperation: 'recover', refreshCatalog: async () => {} });
- if (!result.ok) throw new Error(result.reason);
- return result;
- }
- function readObservedStartupFailure(exists, read) {
- if (!exists()) return null;
- return read();
- }
- async function waitForStartupReadiness({
- timeout,
- shimReady = shimHealthy,
- shimFailureExists = () => fs.existsSync(SHIM_FAILURE_PATH),
- readShimFailure = () => startupFailureFor(supervisorPid, startupGeneration),
- supervisorPid = null,
- startupGeneration = null,
- now = Date.now,
- pause = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
- } = {}) {
- const deadline = now() + timeout;
- while (now() < deadline) {
- if (await shimReady()) return { ok: true };
- const failure = readObservedStartupFailure(shimFailureExists, readShimFailure);
- if (failure) return { ok: false, reason: failure, timedOut: false };
- await pause(300);
- }
- return { ok: false, timedOut: true };
- }
- function reportSiblingSupervisorReplacement(stopped, quiet) {
- if (!quiet && stopped.siblingInstallRoot) log(`model-gateway: replaced older sibling shim version at ${stopped.siblingInstallRoot}.`);
- }
- function recoveryOutcome(result) {
- if (result.ok) return 'ready';
- return result.stillStarting ? 'starting' : 'failed';
- }
- function lifecycleRecovery(lifecycleOperation, recordLifecycle) {
- let attempted = false;
- return {
- begin() {
- if (attempted || !lifecycleOperation) return;
- attempted = true;
- recordLifecycle(`${lifecycleOperation}-recovery-started`, {
- component: lifecycleOperation,
- pid: process.pid,
- startedAt: new Date().toISOString(),
- });
- },
- finish(result) {
- if (attempted && lifecycleOperation) {
- recordLifecycle(`${lifecycleOperation}-recovery-finished`, {
- component: lifecycleOperation,
- pid: process.pid,
- outcome: recoveryOutcome(result),
- ...(result.supervisorPid ? { supervisorPid: result.supervisorPid } : {}),
- });
- }
- return { ...result, recoveryAttempted: attempted };
- },
- };
- }
- // A supervisor that is still starting gets the startup window to answer before anything binds against it (#230,
- // #251). Its old failure file is not evidence about this start, so the wait ignores it.
- async function readSettledShimState(probe, { quiet, report, awaitReadiness, timeout }) {
- const shim = await probe();
- if (!quiet) report(describeShimState(shim));
- if (shim.state !== 'starting') return shim;
- await awaitReadiness({ timeout, shimFailureExists: () => false });
- return probe();
- }
- function shimStartPlan(shim, preserveRunningSupervisor) {
- if (shim.state === 'running-foreign') return refuseForeignShim;
- if (servingCurrentVersion(shim)) return keepRunningShim;
- return preserveRunningSupervisor && shim.state === 'starting' ? waitForRunningShim : replaceShim;
- }
- function refuseForeignShim(shim, { lifecycleOperation, recordLifecycle }) {
- if (shim.owner.state === 'foreign-install') {
- return { ok: false, reason: `PID ${shim.pid} owns :${PUBLIC_SHIM_PORT} from a different install root (${shim.image})` };
- }
- const operation = lifecycleOperation || 'start';
- recordLifecycle(`${operation}-owner-unknown`, { component: operation, pid: process.pid, outcome: 'owner-unknown' });
- return { ok: false, reason: unknownPortOwnerReason(shim.owner, PUBLIC_SHIM_PORT) };
- }
- async function keepRunningShim(shim, context) {
- // The lifecycle lock serializes cleanup; only birth-identified stale workers
- // with a conclusively lost parent can be reaped beside this healthy supervisor.
- if (shim.owner.state === 'same-install') context.reapOrphans(shim.pid);
- noticeStaleSession(shim.health);
- // setup handed a replaced proxy to this supervisor, so it waits for that proxy to answer.
- if (context.preserveRunningSupervisor) return finishStartingShim([], context, shim.pid);
- return reportShimReady([], context);
- }
- function waitForRunningShim(shim, context) {
- return finishStartingShim([], context, shim.pid);
- }
- async function replaceShim(shim, context) {
- const refused = await clearShimForStart(shim, context);
- if (refused) return context.recovery.finish(refused);
- return finishStartingShim(['shim'], context, launchSupervisor(context));
- }
- async function clearShimForStart(shim, { quiet, lifecycleOperation, reapOrphans, stopSupervisor, recovery }) {
- if (shim.state === 'stopped') {
- reapOrphans(null);
- return null;
- }
- recovery.begin();
- const stopped = await stopSupervisor({ quiet, operation: lifecycleOperation || 'restart' });
- if (!stopped.ok) return stopped;
- reportSiblingSupervisorReplacement(stopped, quiet);
- return null;
- }
- function launchSupervisor(context) {
- const { recovery, spawnSupervisor } = context;
- context.startupGeneration = crypto.randomUUID();
- recovery.begin();
- try { fs.rmSync(SHIM_FAILURE_PATH); } catch {}
- const supervisorArguments = [resolveNewestInstalledCliPath(), 'serve-shim'];
- const supervisorPid = spawnSupervisor('guardian', process.execPath, supervisorArguments, { MODEL_GATEWAY_STARTUP_GENERATION: context.startupGeneration });
- if (context.resumeIntent) resumeIntentionalStop();
- return supervisorPid;
- }
- async function finishStartingShim(started, context, supervisorPid) {
- const readiness = await context.awaitReadiness({ timeout: context.timeout, supervisorPid, startupGeneration: context.startupGeneration });
- if (readiness.ok) return reportShimReady(started, context);
- if (!readiness.timedOut) return context.recovery.finish({ ok: false, reason: readiness.reason });
- const waited = `${Math.ceil(context.timeout / 1000)}s`;
- // The wait returns early on a failure file, so a timeout with the supervisor alive means it is still starting.
- const stillStarting = context.supervisorAlive(supervisorPid);
- return context.recovery.finish({
- ok: false,
- reason: stillStarting
- ? `still starting after ${waited}; supervisor pid ${supervisorPid} is running`
- : `not healthy after ${waited} (check logs in ${LOGS})`,
- started,
- waitCutShort: context.quiet,
- ...(stillStarting ? { stillStarting, supervisorPid } : {}),
- });
- }
- function processAlive(pid) {
- if (!Number.isInteger(pid) || pid <= 0) return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch (error) {
- return error.code === 'EPERM';
- }
- }
- async function reportShimReady(started, { quiet, report, refreshCatalog, recovery }) {
- if (!quiet && started.length) report(`started: ${started.join(', ')}`);
- await refreshCatalog().catch(() => { /* advisory only; sidequest just won't see fresh models */ });
- return recovery.finish({ ok: true, started });
- }
- function noticeStaleSession(health) {
- const staleSessionNotice = staleSessionReloadNotice(PLUGIN_VERSION, health);
- if (staleSessionNotice) noticeForUser(staleSessionNotice, { toStderr: true });
- }
- async function startAll(options = {}) {
- return withLifecycleLock(() => startAllLocked(options));
- }
- async function startAllLocked({
- quiet = false,
- lifecycleOperation = null,
- proxyExists = () => fs.existsSync(PROXY_BIN),
- ensureState = mkdirs,
- recordLifecycle = recordGatewayLifecycle,
- resolveOwner = resolvePortOwner,
- fetchHealth = fetchShimHealth,
- probeShim = probeShimState,
- reapOrphans = reapGatewayOrphans,
- stopSupervisor = stopRunningSupervisor,
- spawnSupervisor = spawnDetached,
- supervisorAlive = processAlive,
- awaitReadiness = waitForStartupReadiness,
- refreshCatalog = writeCatalog,
- report = log,
- preserveRunningSupervisor = false,
- resumeIntent = false,
- } = {}) {
- if (intentionallyStopped() && !resumeIntent) return { ok: false, reason: 'gateway intentionally stopped; run start to resume' };
- if (!proxyExists()) return { ok: false, reason: 'proxy binary missing (run setup)' };
- ensureState();
- const context = {
- quiet, lifecycleOperation, recordLifecycle, reapOrphans, stopSupervisor, spawnSupervisor, supervisorAlive, awaitReadiness, refreshCatalog, report,
- preserveRunningSupervisor, resumeIntent, timeout: startupWaitMsFor(quiet), recovery: lifecycleRecovery(lifecycleOperation, recordLifecycle),
- };
- const shim = await readSettledShimState(() => probeShim({ resolveOwner, fetchHealth }), context);
- return shimStartPlan(shim, preserveRunningSupervisor)(shim, context);
- }
- function unknownServingCompatibility(reason) {
- return { status: 'unknown', reason };
- }
- function hasServingCompatibilityHealth(health, supervisorPid) {
- return health?.ok === true
- && health.supervisorPid === supervisorPid
- && typeof health.compat?.hostsDetected === 'boolean'
- && typeof health.compat?.port80Bound === 'boolean';
- }
- async function requestServingCompatibility({ action = 'probe', expectedSupervisorPid = null } = {}) {
- const owner = await resolvePortOwner(PUBLIC_SHIM_PORT).catch(() => ({ state: 'unknown', pid: null }));
- if (owner.state !== 'same-install' || !Number.isInteger(owner.pid)) {
- return unknownServingCompatibility('could not confirm a same-install shim supervisor');
- }
- if (expectedSupervisorPid != null && owner.pid !== expectedSupervisorPid) {
- return unknownServingCompatibility('shim supervisor identity changed');
- }
- const health = await fetchShimHealth();
- if (!hasServingCompatibilityHealth(health, owner.pid)) {
- return unknownServingCompatibility('shim health did not confirm the serving supervisor');
- }
- if (action === 'probe' && health.compat.port80Bound) {
- return { status: 'bound', supervisorPid: owner.pid };
- }
- try {
- const response = await postJson(
- `http://127.0.0.1:${PUBLIC_SHIM_PORT}${RC_CONTROL_PATH}`,
- { action, expectedSupervisorPid: owner.pid },
- 3000,
- { [RC_CONTROL_HEADER]: RC_CONTROL_VALUE },
- );
- if (response.status !== 200) return unknownServingCompatibility(`serving control returned ${response.status}`);
- const result = JSON.parse(response.body.toString());
- if (result?.supervisorPid !== owner.pid || !['bound', 'bindable', 'unavailable', 'unknown'].includes(result.status)) {
- return unknownServingCompatibility('serving control returned an unrecognized response');
- }
- if (result.status === 'unavailable' && typeof result.code !== 'string') {
- return unknownServingCompatibility('serving control omitted its bind failure code');
- }
- return result;
- } catch (error) {
- return unknownServingCompatibility(error?.message || 'serving control did not respond');
- }
- }
- async function restartSupervisorForVersionMismatch({ quiet = false, operation = 'restart', health = null, fetchHealth = fetchShimHealth, start = startAll } = {}) {
- const currentHealth = health || await fetchHealth().catch(() => null);
- if (currentHealth && !shimNeedsRestart(PLUGIN_VERSION, currentHealth)) return null;
- const stopped = await stopRunningSupervisor({ quiet, operation });
- if (!stopped.ok) return stopped;
- reportSiblingSupervisorReplacement(stopped, quiet);
- return start({ quiet, lifecycleOperation: operation });
- }
- async function restartShimIfOutdated({
- quiet = false,
- operation = 'restart',
- fetchHealth = fetchShimHealth,
- restartWorker = restartWorkerWithDrain,
- restartSupervisor = restartSupervisorForVersionMismatch,
- start = startAll,
- } = {}) {
- let health;
- try { health = await fetchHealth(); } catch { return null; }
- if (!shimNeedsRestart(PLUGIN_VERSION, health)) return null;
- return restartSupervisor({ quiet, operation, health, restartWorker, start });
- }
- // What mode the running shim actually achieved this session: compat only if
- // the user's hosts entry is present AND the shim actually managed to bind
- // loopback:COMPAT_PORT (never trust the hosts file alone — a bind failure,
- // e.g. no permission or something else already on :80, must fall back).
- async function resolveIntendedMode() {
- const health = await fetchShimHealth();
- const compat = (health && health.compat) || { hostsDetected: false, port80Bound: false };
- return { mode: compat.hostsDetected && compat.port80Bound ? 'compat' : 'default', compat };
- }
- // The shim serves these while its proxy is unreachable but never persists them as the discovery cache.
- const STAND_IN_CATALOG_NOTES = {
- fallback: 'fallback catalog (proxy unreachable)',
- 'models.json': 'models.json catalog (proxy unreachable)',
- };
- function reportAdvertisedModels(health) {
- const standIn = STAND_IN_CATALOG_NOTES[health?.catalog];
- const catalogNote = standIn ? '; ' + standIn : '';
- log(`models advertised to Claude Code: ${health?.models ?? 'unavailable'}${catalogNote}`);
- log(health?.proxyRecovery
- ? 'proxy recovery: shim supervisor probes /v1/models and restarts an unavailable proxy with bounded backoff'
- : 'proxy recovery: unavailable until the shim supervisor is refreshed');
- }
- function reportShimState(shim) {
- const { owner } = shim;
- log(describeShimState(shim));
- if (owner.state === 'foreign-install') log(`shim supervisor conflict: PID ${owner.pid} owns :${PUBLIC_SHIM_PORT} from a different install root (${owner.installRoot || 'unknown'}).`);
- 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.`);
- if (owner.reason === 'unreadable-command') log(`shim supervisor ownership: ${unknownPortOwnerReason(owner, PUBLIC_SHIM_PORT)}.`);
- }
- function reportCompatibilityListener(compat) {
- if (!compat) return;
- if (!compat.hostsDetected) {
- log('RC-compatibility hosts entry: not present (default gateway mode)');
- return;
- }
- log(`RC-compatibility hosts entry: detected (${compat.hostsLine})`);
- log(` 127.0.0.1:${COMPAT_PORT} bound: ${compat.port80Bound ? 'yes' : `no${compat.reason ? ` (${compat.reason})` : ''}`}`);
- log(' Remote Control transport: this reports local HTTP listener status only, not end-to-end Remote Control.');
- }
- async function statusReport({ readiness = null, probeShim = probeShimState } = {}) {
- const codex = readiness || await getCodexReadiness();
- const { checks, health } = codex;
- log(`proxy (claude-code-proxy) on :${PROXY_PORT}: ${checks.proxyModels ? 'answering /v1/models' : 'DOWN'}`);
- if (checks.shimRunning) reportAdvertisedModels(health);
- reportShimState(await probeShim({ fetchHealth: async () => health }));
- reportCompatibilityListener(health?.compat);
- log(`Codex readiness: ${codex.state}`);
- if (!codex.ready) log(codex.message);
- reportContextWindows();
- log(anthropicCatalogReport());
- reportEffectivePins();
- return { ok: codex.ready, health, readiness: codex };
- }
- function reportContextWindows() {
- for (const line of contextWindowReport(readContextWindowSettings(), configuredAutoCompactWindow())) {
- log(`context window ${line}`);
- }
- }
- // autoCompactWindow is Claude Code's only per-project window knob, so a Claude cap needs project-scoped wiring;
- // written at user scope it would cap every project and every model.
- function applyClaudeWindowChange(previous, next) {
- if (previous === next) return;
- const wirings = registeredProjectWirings();
- if (next !== 'full' && wirings.length === 0) {
- 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);
- }
- reportClaudeWindowSync(syncClaudeContextWindow(wirings.map((wiring) => wiring.file), { owned: previous, next }));
- }
- function reportClaudeWindowSync(result) {
- for (const changed of result.changed) log(`updated autoCompactWindow in ${changed.file}`);
- for (const skipped of result.skipped) log(`skipped ${skipped.file}: ${skipped.reason}`);
- }
- // A project wired after the Claude cap was saved gets it at the next refresh, the same way pins reach it.
- // Skips are not reported here: this runs at every session start, and the context-window command already named them.
- function refreshRegisteredClaudeWindow() {
- const claude = readContextWindowSettings().claude.value;
- if (claude === 'full') return;
- const files = registeredProjectWirings().map((wiring) => wiring.file);
- for (const changed of syncClaudeContextWindow(files, { owned: claude, next: claude }).changed) log(`updated autoCompactWindow in ${changed.file}`);
- }
- function contextWindowCommand() {
- if (!args.length) {
- reportContextWindows();
- return;
- }
- const current = readContextWindowSettings();
- const saved = savedContextWindows(current);
- for (let index = 0; index < args.length; index += 2) {
- const update = contextWindowUpdate(args[index], args[index + 1]);
- if (update.error) die(update.error, 2);
- saveContextWindowUpdate(saved, update);
- }
- applyClaudeWindowChange(current.claude.value, saved.claude || 'full');
- writeContextWindowSettings(saved);
- log(`saved context windows to ${CONTEXT_WINDOW_PATH}`);
- reportContextWindows();
- 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.');
- }
- // -------------------------------------------------------------- env wiring
- function reportRegisteredPinSync(result) {
- for (const wiring of result.changed) log(`updated gateway pins in ${wiring.file}`);
- for (const wiring of result.skipped) {
- const detail = wiring.key ? `${wiring.key}=${wiring.value}` : wiring.reason;
- log(`skipped ${wiring.file}: ${detail} (${wiring.reason})`);
- }
- for (const pruned of result.pruned) log(`pruned registered project ${pruned.project}: ${pruned.reason}`);
- }
- function refreshRegisteredProjectPins(ownedPins) {
- return reportRegisteredPinSync(syncRegisteredProjectPins({ ownedPins }));
- }
- // Syncs on every refresh, not only when this refresh moved a pin: a release that bumps the
- // shipped default moves the effective pin between plugin versions, and no single refresh sees it.
- // The sync writes nothing when every registered project already agrees.
- async function refreshDetectedPinsAndWiring(options = {}) {
- const ownedPins = ownedPinValues();
- const previous = effectivePins();
- await refreshDetectedPins(options);
- refreshCatalogPins();
- reportPinChanges(previous);
- refreshRegisteredProjectPins(ownedPins);
- refreshRegisteredClaudeWindow();
- }
- function refreshCatalogPinsAndWiring() {
- const ownedPins = ownedPinValues();
- const previous = effectivePins();
- refreshCatalogPins();
- reportPinChanges(previous);
- refreshRegisteredProjectPins(ownedPins);
- }
- function reportPinChanges(previous) {
- for (const [alias, pin] of Object.entries(effectivePins())) {
- if (pin.value !== previous[alias].value) log(`model-gateway: ${alias} pin moved ${previous[alias].value} -> ${pin.value}`);
- reportOutdatedOverride(alias, pin);
- }
- }
- function reportOutdatedOverride(alias, pin) {
- if (pin.source !== 'override' || comparePinVersions(pin.newest || '', pin.value) !== 1) return;
- log(`${alias} pinned by override to ${pin.value}; catalog has ${pin.newest}; pin --${alias} default follows the catalog`);
- }
- function reportEffectivePins(label = '', suffix = '') {
- for (const [alias, pin] of Object.entries(effectivePins())) {
- log(`${label}${alias}${suffix}: ${pin.value} (${pinProvenance(pin)}); newest catalog: ${pin.newest || 'unavailable'}`);
- reportOutdatedOverride(alias, pin);
- }
- }
- function updatePinOverride(overrides, option, value) {
- const alias = option && option.startsWith('--') ? option.slice(2) : null;
- if (!Object.hasOwn(PIN_ALIASES, alias) || value == null) {
- die('pin expects --opus, --sonnet, or --fable followed by a model id or default', 2);
- }
- if (value === 'default') {
- delete overrides[alias];
- return;
- }
- if (!isValidPin(value)) die(`invalid ${alias} pin: use a non-empty model id without whitespace or shell characters`, 2);
- overrides[alias] = value;
- }
- function pinCommand() {
- if (args.length === 0) {
- reportEffectivePins();
- return;
- }
- const ownedPins = ownedPinValues();
- const overrides = readPinOverrides();
- for (let index = 0; index < args.length; index += 2) {
- updatePinOverride(overrides, args[index], args[index + 1]);
- }
- writePinOverrides(overrides);
- refreshRegisteredProjectPins(ownedPins);
- log(`saved Claude alias pins to ${PIN_OVERRIDE_PATH}`);
- log('Applied the pin change to registered wired projects. Restart open Claude Code sessions to pick it up.');
- }
- function wiredGatewayEnv() {
- return envBlockFor(wiredMode()?.mode || 'default');
- }
- // Runs the /model comparison at most once per Claude Code version, inside the SessionStart budget,
- // and repeats a recorded failure each session until a release or a fix clears it.
- async function reportStalePickerRowsOncePerCli() {
- if (realClaudeRefusedUnderTest()) return;
- const run = () => runPickerGuard({ gatewayEnv: wiredGatewayEnv(), timeoutMs: PICKER_HOOK_PROBE_TIMEOUT_MS });
- const result = await pickerGuardForCli(await claudeVersion(), { run });
- const lines = result && !result.unverified ? pickerGuardFailureLines(result) : [];
- if (lines.length) noticeForUser(`${lines.join('; ')}. Run \`node "${resolveStableCommandPath()}" doctor\` for both row lists.`);
- }
- async function syncGatewayWiring() {
- await refreshDetectedPinsAndWiring();
- const current = wiredMode();
- if (!current?.scope) return;
- const env = readSettingsForWrite(settingsPath(current.scope)).env || {};
- const expected = envBlockFor(current.mode);
- if (Object.entries(expected).some(([key, value]) => env[key] !== value)) {
- writeEnv(current.scope, false, { mode: current.mode, quiet: true });
- }
- }
- async function syncUnwiredPins() {
- repairProjectWiring(log);
- }
- async function envCommand() {
- for (const retired of ['--mode', '--show-mode']) {
- if (flag(retired)) {
- 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);
- }
- }
- const reconcile = flag('--reconcile');
- const remove = flag('--remove');
- const writeProject = flag('--write-project');
- const writeUser = flag('--write-user');
- if (writeProject && writeUser) die('env accepts either --write-project or --write-user, not both', 2);
- if (reconcile && !writeUser) die('env --reconcile only applies to --write-user', 2);
- if (!writeProject && !writeUser && !remove) {
- log('add this to the "env" block of this project\'s .claude/settings.local.json:');
- log(JSON.stringify({ env: envBlockFor('default') }, null, 2));
- log('\nor use /model-gateway:model-gateway to run its env --write-project command');
- log('\nProject wiring is the default: this local block keeps this project and its executor worktrees routed after restart.');
- log('Use env --write-user only when you deliberately want the same fallback URL in every project.');
- 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.');
- return;
- }
- const scope = writeUser ? 'user' : 'project';
- recordProjectWiring();
- if (!remove) await refreshDetectedPinsAndWiring({ force: true });
- writeEnv(scope, remove, { mode: remove ? 'default' : (await resolveIntendedMode()).mode });
- retireWiringModeConfig();
- if (remove || !writeUser) return;
- const targetBaseUrl = readSettingsForWrite(settingsPath('user')).env?.ANTHROPIC_BASE_URL;
- const result = reconcileRegisteredProjectWirings(targetBaseUrl, { confirm: reconcile });
- if (!result.conflicting.length) return;
- log(`${result.conflicting.length} recorded project-local wiring ${result.conflicting.length === 1 ? 'entry overrides' : 'entries override'} the user-scoped URL:`);
- for (const wiring of result.conflicting) log(` ${wiring.file}`);
- if (reconcile) log(`removed model-gateway-owned wiring from ${result.reconciled.length} project${result.reconciled.length === 1 ? '' : 's'}`);
- else log('project files were not changed. To confirm cleanup, invoke env --write-user --reconcile for the model-gateway-owned entries shown above.');
- }
- // mode only matters when writing (not removing); quiet suppresses this
- // function's own logging so a caller doing an automatic mode switch can print
- // its own single, more specific line instead.
- function writeEnv(scope, remove, { mode = 'default', quiet = false } = {}) {
- // Runs for the user scope too: a committed project settings.json carrying
- // gateway keys outranks ~/.claude/settings.json and would shadow this write.
- const migration = remove ? null : migrateLegacyProjectSettings();
- const effectiveMode = migration?.mode || mode;
- const file = settingsPath(scope);
- if (remove && !fs.existsSync(file)) {
- if (scope === 'project') recordProjectWiring();
- return { changed: false, file };
- }
- require('../hooks/registry-writer.js').writeCommandLauncher();
- const settings = readSettingsForWrite(file);
- const original = JSON.stringify(settings);
- require('./readiness-hooks.js').syncReadinessHooks(settings, !remove);
- settings.env = settings.env || {};
- delete settings.env.ANTHROPIC_UNIX_SOCKET;
- if (remove) {
- const preserved = removeGatewayOwnedSettings(settings);
- if (preserved.length) log(`model-gateway: preserved user pins in ${file}: ${preserved.join(', ')}`);
- } else {
- Object.assign(settings.env, envBlockFor(effectiveMode));
- for (const [k, v] of Object.entries(LEGACY_ENV_BLOCK)) {
- if (String(settings.env[k]) === String(v)) delete settings.env[k];
- }
- cleanLegacyGatewayModelCache();
- }
- if (remove && JSON.stringify(settings) === original) {
- if (scope === 'project') recordProjectWiring();
- return { changed: false, file };
- }
- writeSettings(file, settings);
- const verified = readSettingsForWrite(file);
- const expected = remove ? settings.env?.ANTHROPIC_BASE_URL : envBlockFor(effectiveMode).ANTHROPIC_BASE_URL;
- if (verified.env?.ANTHROPIC_BASE_URL !== expected) throw new Error(`Could not verify gateway settings in ${file}`);
- const verifiedMode = verified.env?.ANTHROPIC_BASE_URL === COMPAT_BASE_URL ? 'compat' : 'default';
- if (scope === 'project') recordProjectWiring();
- if (quiet) return { changed: true, file, mode: verifiedMode };
- log(`${remove ? 'removed from' : 'written to'} ${file}`);
- if (!remove) {
- log('new Claude Code sessions now use this wiring. Restart Claude Code, then open /model to see the Codex rows.');
- }
- return { changed: true, file, mode: verifiedMode };
- }
- // Called once per session (from `ensure`, after the shim is confirmed
- // running) to keep the wired env in sync with the hosts file: promotes to
- // compat mode when the entry appears and the shim actually bound :80, reverts
- // to default the moment either condition stops holding (entry removed, or
- // the port became unavailable). Exactly one log line when something changes;
- // silent otherwise. Never touches settings this plugin didn't wire itself.
- async function syncCompatMode({ requiredMode = null } = {}) {
- const { mode: desiredMode, compat } = await resolveIntendedMode();
- if (requiredMode && desiredMode !== requiredMode) return { mode: desiredMode, compat, changed: false };
- migrateLegacyProjectSettings();
- const current = wiredMode();
- const scope = current?.scope || (current ? null : selectedWiringScope());
- const observedMode = current?.mode || 'default';
- if (!scope || desiredMode === observedMode) return { mode: observedMode, compat, changed: false };
- const written = writeEnv(scope, false, { mode: desiredMode, quiet: true });
- const mode = written.mode;
- if (mode === 'compat') {
- 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.`);
- } else {
- const why = compat.hostsDetected
- ? `127.0.0.1:${COMPAT_PORT} is unavailable${compat.reason ? ` (${compat.reason})` : ''}`
- : `the hosts entry mapping ${COMPAT_HOST} to loopback was removed`;
- log(`model-gateway: reverted to default gateway mode (${why}). Restart Claude Code.`);
- }
- return { mode, compat, changed: true };
- }
- // ------------------------------------------------------------------ doctor
- function configuredAutoCompactWindow() {
- const candidates = [{ source: 'CLAUDE_CODE_AUTO_COMPACT_WINDOW', value: process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW }];
- for (const source of ['project-local', 'project-shared', 'user']) {
- const scope = source === 'project-local' ? 'project' : source;
- try {
- const value = JSON.parse(fs.readFileSync(settingsPath(scope), 'utf8')).autoCompactWindow;
- candidates.push({ source: `settings ${source}`, value });
- } catch {}
- }
- for (const candidate of candidates) {
- const window = Number(candidate.value);
- if (Number.isInteger(window) && window > 0) return { source: candidate.source, window };
- }
- return null;
- }
- function windowValue(value) {
- return Number.isFinite(value) ? String(value) : 'upstream-managed';
- }
- function evidenceDate(measurement) {
- const date = String(measurement || '').match(/\b\d{4}-\d{2}-\d{2}\b/);
- if (date) return date[0];
- return String(measurement || '').startsWith('unmeasured') ? 'unmeasured' : 'upstream-managed';
- }
- function nativeModelPolicyIds() {
- return [...new Set([
- ...Object.values(effectivePins()).map((pin) => pin.value),
- 'claude-haiku-4-5',
- ])];
- }
- function modelWindowPolicyRow(id, pickerId = gatewayClientModelId(id)) {
- const policy = resolveGatewayModelPolicy(id);
- if (!policy) return null;
- const clientWindow = pickerId.endsWith('[1m]') ? 1000000 : CODEX_UNKNOWN_MODEL_WINDOW;
- const autoCompact = configuredAutoCompactWindow();
- const sentryPolicy = effectiveSentryPolicy(policy);
- return {
- backend: policy.backend,
- backendId: policy.backend === 'anthropic' ? id.replace(/\[1m\]$/, '') : policy.backendId,
- pickerId,
- backendWindow: policy.backendWindow,
- advertisedWindow: gatewayAdvertisedWindow(id),
- clientWindow,
- clientCompactPoint: 'unverified (native engine headroom)',
- sentry: policy.sentry,
- sentryTrigger: sentryPolicy ? `${sentryPolicy.compactTrigger} (${sentryPolicy.source})` : 'none',
- evidenceDate: evidenceDate(policy.measurement),
- };
- }
- function policyGatewayModelIds(liveIds = []) {
- if (liveIds.length) {
- return [...new Set(liveIds.filter((id) => {
- const policy = resolveGatewayModelPolicy(id);
- return policy?.backend === 'codex' || policy?.backend === 'grok';
- }))];
- }
- return Object.values(MODEL_WINDOW_POLICY)
- .filter((policy) => policy.backendId !== 'default' && policy.backend !== 'anthropic')
- .map((policy) => policy.backendId);
- }
- function modelWindowPolicyRows(liveIds = []) {
- const gatewayRows = policyGatewayModelIds(liveIds).map((id) => modelWindowPolicyRow(id));
- const nativeRows = nativeModelPolicyIds().map((id) => modelWindowPolicyRow(id, id));
- return [...gatewayRows, ...nativeRows].filter(Boolean);
- }
- function expectedShimModelIds(liveIds = []) {
- return modelWindowPolicyRows(liveIds)
- .filter((row) => row.backend !== 'anthropic')
- .map((row) => row.pickerId);
- }
- function modelIdDifference(liveIds) {
- const live = new Set(liveIds);
- const expected = new Set(expectedShimModelIds(liveIds));
- return {
- missing: [...expected].filter((id) => !live.has(id)),
- extra: [...live].filter((id) => !expected.has(id)),
- };
- }
- function reportModelWindowPolicy(liveIds = []) {
- const autoCompact = configuredAutoCompactWindow();
- log(`model window policy: ${autoCompact
- ? `auto-compact cap ${autoCompact.window} (${autoCompact.source})`
- : 'no auto-compact cap configured'}`);
- log('backend id | picker/client id | backend window | advertised window | client window | client compact point | sentry | effective trigger | evidence date');
- for (const row of modelWindowPolicyRows(liveIds)) {
- log([
- row.backendId,
- row.pickerId,
- windowValue(row.backendWindow),
- windowValue(row.advertisedWindow),
- row.clientWindow,
- row.clientCompactPoint,
- row.sentry,
- row.sentryTrigger,
- row.evidenceDate,
- ].join(' | '));
- }
- }
- async function reportLiveShimModelPolicy() {
- let liveIds;
- try {
- liveIds = (await fetchShimModels()).map((model) => model.id);
- } catch (error) {
- log(`live shim model ids: unavailable (${error.message})`);
- reportModelWindowPolicy();
- return false;
- }
- reportModelWindowPolicy(liveIds);
- const { missing, extra } = modelIdDifference(liveIds);
- if (!missing.length && !extra.length) {
- log('live shim model ids: PASS (match the installed policy)');
- return true;
- }
- 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.`);
- process.exitCode = 1;
- return false;
- }
- function reportRegisteredProjectPinDisagreements() {
- const result = registeredProjectPinDisagreements();
- for (const pruned of result.pruned) log(`pruned registered project ${pruned.project}: ${pruned.reason}`);
- for (const disagreement of result.disagreements) {
- const staleValue = disagreement.staleValue === undefined ? 'missing' : disagreement.staleValue;
- console.error(`model-gateway: ERROR: registered project pin disagrees in ${disagreement.file}: ${disagreement.key}=${staleValue} (expected ${disagreement.expectedValue}).`);
- }
- return result.disagreements.length > 0;
- }
- function reportProjectWiringIssues() {
- for (const issue of projectWiringIssues()) log(`model-gateway: ${issue.message} in ${issue.file}; run ensure to repair.`);
- }
- const PICKER_HOOK_PROBE_TIMEOUT_MS = 8000;
- async function doctor({ readiness: suppliedReadiness = null } = {}) {
- reportReadinessGate();
- reportProjectWiringIssues();
- recordedGatewayPids();
- const readiness = suppliedReadiness || await getCodexReadiness();
- log(`binary: ${readiness.checks.proxyBinary ? PROXY_BIN : 'MISSING (run setup)'}`);
- if (readiness.checks.proxyBinary) {
- const v = spawnSync(PROXY_BIN, ['--version'], { encoding: 'utf8', timeout: 10000, windowsHide: true });
- log(`version: ${(v.stdout || v.stderr || '').trim()}`);
- log(`codex auth: ${readiness.checks.codexAuth ? 'authenticated' : 'MISSING'}`);
- }
- try {
- grokBackend.readGrokAuth();
- log(`grok auth: present (${grokBackend.readGrokVersion()})`);
- } catch (error) {
- log(`grok auth: ${error.message}`);
- }
- const status = await statusReport({ readiness });
- const servingVersion = readiness.checks.servingVersion;
- log(`serving shim version: ${servingVersion || 'unavailable'}`);
- for (const line of pickerGuardReport(await runPickerGuard({ gatewayEnv: wiredGatewayEnv() }))) log(line);
- log(`lifecycle evidence: ${lifecycleLogPath()}`);
- const observedExit = latestObservedLifecycleExit();
- if (observedExit) {
- const identity = observedExit.child || { component: observedExit.component, pid: observedExit.pid };
- const exitCode = Object.hasOwn(observedExit, 'exitCode') ? observedExit.exitCode : 'unavailable';
- log(`lifecycle exit evidence: observed ${identity.component} PID ${identity.pid}; exit code ${exitCode}; signal ${observedExit.signal || 'none'}`);
- } else {
- log('lifecycle exit evidence: no observed exit record. A force-killed supervisor or OS termination may leave no final record.');
- }
- const hookWaitCutShort = latestHookWaitCutShort();
- if (hookWaitCutShort) {
- 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}).`);
- }
- 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.');
- if (readiness.checks.shimRunning && !readiness.checks.servingVersionMatches) {
- log(`model-gateway: VERSION MISMATCH: CLI ${PLUGIN_VERSION}, serving shim ${servingVersion}. Run node "${resolveStableCommandPath()}" ensure to replace the stale supervisor.`);
- }
- const catalog = readCatalog();
- log(catalog && Array.isArray(catalog.models)
- ? `catalog: ${catalog.models.length} models at ${CATALOG_PATH} (writtenBy: ${catalog.writtenBy || 'unknown'})`
- : 'catalog: not written yet');
- await reportGatewayDiscoveryCache();
- reportEffectivePins('Claude ', ' pin');
- if (reportRegisteredProjectPinDisagreements()) process.exitCode = 1;
- await reportLiveShimModelPolicy();
- const activeScope = selectedWiringScope();
- const effective = effectiveBaseUrl();
- const modeFor = (base) => (base === COMPAT_BASE_URL ? 'compat' : base === DEFAULT_BASE_URL ? 'default' : null);
- const labelFor = {
- env: 'process env',
- 'project-local': 'project settings.local.json',
- 'project-shared': 'project settings.json',
- user: 'user settings.json',
- };
- const scopeFor = { 'project-local': 'project', 'project-shared': 'project', user: 'user' };
- const effectiveWired = ourBaseUrls().includes(effective.value);
- const effectiveLocation = effective.source
- ? `${labelFor[effective.source]}${effective.file ? ` (${effective.file})` : ''}`
- : 'none';
- log(`wiring: effective ${effectiveLocation}${effectiveWired ? ' [model-gateway]' : ''}`);
- log('default wiring target: this project\'s .claude/settings.local.json');
- for (const source of ['env', 'project-local', 'project-shared', 'user']) {
- const scope = scopeFor[source];
- const file = source === 'env' ? null : settingsPath(source === 'project-local' ? 'project' : source);
- let base = source === 'env' ? process.env.ANTHROPIC_BASE_URL : null;
- if (file) {
- try { base = JSON.parse(fs.readFileSync(file, 'utf8')).env?.ANTHROPIC_BASE_URL; } catch {}
- }
- const wired = ourBaseUrls().includes(base);
- const mode = modeFor(base);
- const tags = [source === effective.source ? ' [effective]' : '', scope === activeScope ? ' [default write target]' : ''].join('');
- const modeLabel = mode === 'compat' ? ' [RC-compatibility mode]' : mode === 'default' ? ' [default mode]' : '';
- log(`${labelFor[source]}: ${wired ? 'wired' + modeLabel : 'not wired'}${file ? ` (${file})` : ''}${tags}`);
- }
- if (effective.source === 'project-local' && effective.shadowed.some(({ source }) => source === 'user')) {
- log('wiring precedence: project settings.local.json wins over user settings.json.');
- }
- const processEnvBypass = processEnvGatewayBypass(effective);
- if (processEnvBypass) {
- 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.`);
- process.exitCode = 1;
- }
- if (!effectiveWired) {
- 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.');
- process.exitCode = 1;
- }
- const effectiveMode = modeFor(effective.value);
- const shadowedMode = effective.shadowed.find((definition) => {
- const mode = modeFor(definition.value);
- return mode && mode !== effectiveMode;
- });
- if (effectiveMode && shadowedMode) {
- const shadowedLocation = shadowedMode.file || 'process env ANTHROPIC_BASE_URL';
- const effectiveLocation = effective.file || 'process env ANTHROPIC_BASE_URL';
- const resolution = effective.source === 'project-local'
- ? `Project settings.local.json wins. Make the modes agree with env --write-project or remove ANTHROPIC_BASE_URL from ${shadowedLocation}.`
- : effective.source === 'env'
- ? `Process env wins. Update or remove its ANTHROPIC_BASE_URL before changing settings.`
- : `The highest-precedence setting wins. Make the modes agree with env --write-project or remove ANTHROPIC_BASE_URL from ${shadowedLocation}.`;
- console.error(`model-gateway: ERROR: effective ${effectiveLocation} uses ${effectiveMode} mode, but shadowed ${shadowedLocation} uses ${modeFor(shadowedMode.value)} mode. ${resolution} Restart Claude Code.`);
- process.exitCode = 1;
- }
- const scope = installScope();
- if (scope === 'project-only') {
- log('install scope: project (expected for project-local wiring)');
- } else if (scope === 'user') {
- log('install scope: user (shared installation)');
- }
- if (!status.ok) process.exitCode = 1;
- }
- // ---------------------------------------------------------------- the shim
- // display_name feeds the /model PICKER only (with gateway model discovery on,
- // for ids starting with claude-/anthropic-), where it shows correctly as e.g.
- // "GPT-5.6 Terra (Codex)". It does NOT reach the running-subagent CARD: that
- // surface resolves the model label internally and maps an unrecognized claude-*
- // id (like claude-gpt-5.6-terra) to a Claude family name — it renders
- // "Fable 5" for a Terra run. Nothing we return here overrides that (verified:
- // the response model field is "gpt-5.6-terra" and the model self-reports GPT-5,
- // so the RUN is correct — only the card label lies). Native subagent model
- // display isn't a supported feature (anthropics/claude-code#24094, not planned).
- // The sidequest agent NAME (sidequest-exec-codex-gpt-5-6-terra-*) carries the
- // true runtime, so don't chase the badge by editing display_name — it's a dead
- // end. See SQ-202.
- function displayName(id, backend = 'codex') {
- if (backend === 'grok') return id.replace(/^grok-/, 'Grok ').replace(/-/g, ' ');
- return id.replace(/^gpt-/, 'GPT-').replace(/\[1m\]$/, '') + ' (Codex)';
- }
- // claude-code-proxy v0.1.10 has no /v1/models route, so the shim owns the
- // catalog: ~/.claude/model-gateway/models.json if present, else the Codex ids
- // its README documents. A future proxy /v1/models takes precedence over both.
- const PLAN_TOOLS = ['EnterPlanMode', 'ExitPlanMode'];
- const DEFAULT_MODELS = [
- 'gpt-6.1-sol', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-6-astra',
- ];
- const DEFAULT_GROK_MODELS = grokBackend.GROK_MODELS;
- // Claude Code 2.1.261 ignores settings-file CLAUDE_CODE_MAX_CONTEXT_TOKENS for
- // its unrecognized-model resolver. Codex rows therefore use Claude Code's [1m]
- // spelling, chosen from the same context table used for max_input_tokens. The
- // worker sentry retains backend headroom because that spelling is a 1M client
- // window rather than the backend's exact 920k limit.
- function gatewayModel(id, backend = 'codex') {
- const policy = id === 'auto' ? null : resolveGatewayModelPolicy(id);
- if (id !== 'auto' && policy?.backend !== backend) return null;
- return {
- id: id === 'auto' ? DISPATCH_MODEL_ID : gatewayClientModelId(id),
- display_name: id === 'auto' ? 'Sidequest Dispatch (Codex)' : displayName(id, backend),
- type: 'model',
- max_input_tokens: gatewayAdvertisedWindow(id) || codexContextWindow(id),
- };
- }
- // ------------------------------------------------------------ model catalog
- //
- // sidequest (same marketplace) auto-discovers Codex models by reading this
- // file: ~/.claude/model-gateway/catalog.json. Shape is a frozen contract
- // (see plugins/sidequest/lib/discovery.js) — don't change it casually.
- const CATALOG_PATH = path.join(STATE, 'catalog.json');
- const CATALOG_STALE_MS = 5 * 60 * 1000;
- const CATALOG_SCHEMA_VERSION = 4;
- // Slugs keep the `codex-` backend name and so survive the id rename byte for
- // byte: the board's route table pins slugs, and re-slugging would break every
- // persisted route at once.
- //
- // Provider + base, dots→dashes, kept inside ^[a-z0-9][a-z0-9-]{1,31}$; on
- // collision (or an over-length base) fall back to a short deterministic hash
- // so the slug stays unique without depending on iteration order.
- function slugFor(provider, base, used) {
- const providerPrefix = `${provider}-`;
- const providerBase = base.startsWith(providerPrefix) ? base.slice(providerPrefix.length) : base;
- let s = (providerPrefix + providerBase).toLowerCase()
- .replace(/\[1m\]$/, '')
- .replace(/\./g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-+|-+$/g, '');
- if (!/^[a-z0-9]/.test(s)) s = 'x' + s;
- if (s.length > 32) {
- const hash = crypto.createHash('sha1').update(s).digest('hex').slice(0, 6);
- s = s.slice(0, 32 - 1 - hash.length) + '-' + hash;
- }
- let unique = s;
- let n = 2;
- while (used.has(unique)) {
- const suffix = '-' + n;
- unique = s.slice(0, Math.max(1, 32 - suffix.length)) + suffix;
- n++;
- }
- used.add(unique);
- return unique;
- }
- // "gpt-5.6-sol" -> "GPT-5.6 Sol", "gpt-5.3-codex-spark" -> "GPT-5.3 Codex Spark"
- function labelFor(base) {
- const rest = base.replace(/^gpt-/, '');
- const m = rest.match(/^(\d+(?:\.\d+)?)(?:-(.+))?$/);
- if (!m) return 'GPT-' + rest.replace(/-/g, ' ');
- const [, ver, suffix] = m;
- const suffixLabel = suffix
- ? ' ' + suffix.split('-').map((w) => w[0].toUpperCase() + w.slice(1)).join(' ')
- : '';
- return `GPT-${ver}${suffixLabel}`;
- }
- function modelCatalogDetails(id) {
- const codexBase = codexBaseFromId(id);
- if (codexBase && codexBase !== 'auto') {
- return { provider: 'codex', base: codexBase, label: labelFor(codexBase) };
- }
- if (typeof id === 'string' && id.startsWith(GROK_PREFIX)) {
- const base = id.slice(PREFIX.length).replace(/\[1m\]$/, '');
- return { provider: 'grok', base, label: displayName(base, 'grok') };
- }
- return null;
- }
- function unavailableProviderReadiness(provider) {
- return {
- ready: false,
- state: 'unavailable',
- message: `${provider} readiness is unavailable.`,
- };
- }
- function getGrokReadiness({ readAuth = grokBackend.readGrokAuth } = {}) {
- try {
- readAuth();
- return {
- ready: true,
- state: 'ready',
- message: 'Grok CLI auth is present.',
- };
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Grok CLI auth is unavailable. Run `grok` and log in again.';
- return {
- ready: false,
- state: /invalid/i.test(message) ? 'auth-invalid' : 'auth-missing',
- message,
- };
- }
- }
- function providerCatalogReadiness(provider, readiness) {
- const source = readiness?.[provider] ?? (provider === 'codex' ? readiness : null);
- if (source) return providerReadiness(source);
- if (provider === 'grok') return getGrokReadiness();
- return unavailableProviderReadiness(provider);
- }
- function catalogContextWindow(id, provider) {
- const contextWindow = gatewayAdvertisedWindow(id);
- if (!contextWindow) return {};
- const contextWindowNote = gatewayWindowNote(provider, contextWindowCap(provider), contextWindowCompactAt(provider), resolveGatewayModelPolicy(id));
- return contextWindowNote ? { contextWindow, contextWindowNote } : { contextWindow };
- }
- function buildCatalog(ids, readiness = null) {
- const used = new Set();
- const models = ids
- .map((id) => ({ id, details: modelCatalogDetails(id) }))
- .filter(({ details }) => details)
- .map(({ id, details }) => ({
- slug: slugFor(details.provider, details.base, used),
- id: gatewayClientModelId(id),
- label: details.label,
- provider: details.provider,
- ...catalogContextWindow(id, details.provider),
- }));
- const providers = Object.fromEntries(
- [...new Set(models.map((model) => model.provider))].map((provider) => [provider, providerCatalogReadiness(provider, readiness)]),
- );
- return {
- schemaVersion: CATALOG_SCHEMA_VERSION,
- source: 'model-gateway',
- updatedAt: new Date().toISOString(),
- writtenBy: PLUGIN_VERSION,
- providers,
- codexReadiness: providers.codex ?? null,
- models,
- };
- }
- function readJsonFile(file) {
- try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
- }
- function catalogSchemaVersion(catalog) {
- if (!catalog || typeof catalog !== 'object') return null;
- const version = catalog.schemaVersion ?? catalog.schema;
- return Number.isInteger(version) && version > 0 ? version : null;
- }
- function catalogModelIds(catalog) {
- return new Set(
- Array.isArray(catalog?.models)
- ? catalog.models.filter((model) => typeof model?.id === 'string').map((model) => model.id)
- : [],
- );
- }
- function mergeSubsetCatalog(existing, catalog) {
- if (catalogSchemaVersion(existing) !== CATALOG_SCHEMA_VERSION || !Array.isArray(existing.models)) return catalog;
- const existingIds = catalogModelIds(existing);
- const fetchedIds = catalogModelIds(catalog);
- const isStrictSubset = fetchedIds.size < existingIds.size && [...fetchedIds].every((id) => existingIds.has(id));
- if (!isStrictSubset) return catalog;
- // A removal-only response is indistinguishable from a stale writer. Adding a model makes the response authoritative, so intentional replacement can still remove entries.
- const preserved = existing.models.filter((model) => typeof model?.id === 'string' && !fetchedIds.has(model.id));
- const models = [...catalog.models, ...preserved];
- const providers = { ...catalog.providers };
- for (const model of preserved) {
- if (typeof model.provider === 'string' && !providers[model.provider] && existing.providers?.[model.provider]) {
- providers[model.provider] = existing.providers[model.provider];
- }
- }
- log(`catalog: preserved ${preserved.map((model) => model.id).join(', ')} from a subset write`);
- return { ...catalog, models, providers, codexReadiness: providers.codex ?? null };
- }
- function writeCatalogFile(catalogPath, catalog) {
- const existing = readJsonFile(catalogPath);
- const storedVersion = catalogSchemaVersion(existing);
- if (storedVersion != null && storedVersion > CATALOG_SCHEMA_VERSION) {
- throw new Error(`refusing to overwrite catalog schema ${storedVersion} at ${catalogPath}; this gateway supports schema ${CATALOG_SCHEMA_VERSION}, upgrade required`);
- }
- const nextCatalog = mergeSubsetCatalog(existing, catalog);
- try {
- writeFileAtomically(catalogPath, JSON.stringify(nextCatalog, null, 2) + '\n');
- } catch (error) {
- log(`catalog: could not replace ${catalogPath} (${error.code || error.message}); the models list stays at its previous contents`);
- throw error;
- }
- return nextCatalog;
- }
- async function fetchShimModels() {
- // the shim's own refreshModels() can still be mid-flight right after
- // /healthz starts answering; retry once, short, before giving up
- for (let attempt = 0; attempt < 2; attempt++) {
- const response = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/v1/models`, { timeout: 3000 });
- if (response.status !== 200) throw new Error(`shim /v1/models returned ${response.status}`);
- const models = (JSON.parse(response.body.toString()).data || []).filter((model) => model && typeof model.id === 'string');
- if (models.length || attempt === 1) return models;
- await new Promise((resolve) => setTimeout(resolve, 300));
- }
- return [];
- }
- function discoveryCacheBaseUrl() {
- const baseUrl = effectiveBaseUrl().value;
- if (baseUrl === COMPAT_BASE_URL) return COMPAT_BASE_URL;
- return baseUrl === DEFAULT_BASE_URL ? DEFAULT_BASE_URL : null;
- }
- // An older shim reports no catalog source; its list is written as before.
- function writeGatewayDiscoveryCache(models, catalogSource) {
- const standIn = STAND_IN_CATALOG_NOTES[catalogSource];
- if (standIn) {
- log(`discovery cache: kept; the shim is serving its ${standIn}`);
- return { state: 'skipped', reason: 'stand-in-catalog', modelCount: 0 };
- }
- const result = syncGatewayDiscoveryCache({ models: withPreviousServerRows(withCachedAnthropicRows(models)), baseUrl: discoveryCacheBaseUrl() });
- if (result.state === 'wrote') log(`discovery cache: wrote ${result.modelCount} models`);
- else if (result.state === 'unchanged') log('discovery cache: unchanged');
- return result;
- }
- function cacheAgeLabel(fetchedAt) {
- if (!Number.isFinite(fetchedAt)) return 'unknown age';
- return `${Math.max(0, Math.floor((Date.now() - fetchedAt) / 1000))}s old`;
- }
- async function reportGatewayDiscoveryCache() {
- const cache = readGatewayDiscoveryCache();
- const cachedModels = gatewayDiscoveryModels(cache?.models);
- let liveModels = null;
- try { liveModels = gatewayDiscoveryModels(await fetchShimModels()); } catch {}
- const expectedBaseUrl = discoveryCacheBaseUrl();
- const matchesLiveList = liveModels && cache?.baseUrl === expectedBaseUrl
- && sameGatewayDiscoveryModels(cache.models, liveModels);
- const state = liveModels ? (matchesLiveList ? 'matches live list' : 'stale') : 'live list unavailable';
- log(`discovery cache: ${GATEWAY_MODELS_CACHE}; ${cache ? `${cacheAgeLabel(cache.fetchedAt)}, ${cachedModels.length} models` : 'not written, 0 models'}; ${state}`);
- if (state === 'stale' && expectedBaseUrl !== COMPAT_BASE_URL) {
- log('discovery cache: Claude Code cannot refresh this cache under OAuth login; run ensure or restart after the gateway updates it.');
- }
- }
- async function writeCatalog() {
- const shimModels = await fetchShimModels();
- writeGatewayDiscoveryCache(shimModels, (await fetchShimHealth())?.catalog);
- const ids = shimModels.map((model) => model.id).filter((id) => modelCatalogDetails(id) != null);
- // A zero-model catalog would merge straight back to the stored models with a fresh timestamp, so
- // publishing it would make a shim that advertises nothing routable look like a successful refresh.
- // Refusing is right; returning null was not, because every caller read that as "nothing to do".
- if (!ids.length) throw new Error(`shim advertised ${shimModels.length} model(s), none of them a gateway id`);
- const readiness = await getCodexReadiness();
- const catalog = buildCatalog(ids, readiness);
- mkdirs();
- return writeCatalogFile(CATALOG_PATH, catalog);
- }
- // setup --preserve-wiring ends here. The stable updater runs from whatever directory
- // /update-toolshed was started in, and that directory is not consent to route it
- // through the gateway (GH-292). Recorded projects already had their pins synced by
- // refreshDetectedPinsAndWiring, and each wired session reconciles itself at SessionStart.
- // A loaded machine can outlast the startup wait while the new supervisor is alive and finishes on its own schedule
- // (GH-360); failing the update or starting a second supervisor would both be wrong.
- function warnShimStillStarting(result) {
- log(`model-gateway: warning: shim supervisor ${result.reason}; check \`node "${resolveStableCommandPath()}" status\` in a minute.`);
- }
- async function finishUpdateWithoutWiring() {
- 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.`);
- await writeCatalog().catch(() => { /* advisory only; the next ensure retries */ });
- await statusReport();
- }
- function readCatalog() {
- return readJsonFile(CATALOG_PATH);
- }
- // "Not answering" was the only reason a refresh ever gave, even when /healthz answered with an error or
- // answered too slowly, which sent people hunting for a dead port that was alive (issue #227).
- async function requireShimHealth() {
- const where = `/healthz on 127.0.0.1:${SHIM_PORT}`;
- const response = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/healthz`, { timeout: 3000 }).catch((error) => {
- throw new Error(`shim is not answering ${where} (${error.message})`);
- });
- if (response.status !== 200) throw new Error(`shim ${where} returned ${response.status}`);
- }
- async function catalogCommand() {
- const jsonOut = flag('--json');
- const refresh = flag('--refresh');
- let catalog = readCatalog();
- const stale = !catalog || (Date.now() - Date.parse(catalog.updatedAt || 0) > CATALOG_STALE_MS);
- let refusal = null;
- if (refresh || stale) {
- try {
- await requireShimHealth();
- catalog = await writeCatalog();
- } catch (error) {
- refusal = error.message;
- }
- }
- if (!catalog) die(`no catalog available yet (${refusal || 'run setup or start first'})`);
- // A refresh that fell back to the stored catalog used to be indistinguishable from one that
- // wrote: exit 0, no diagnostic, an unchanged file the caller then discards as stale (issue #227).
- // stdout stays a machine contract, so the reason goes to stderr, and an explicitly requested
- // refresh also fails the exit code, which is what sidequest's refresh checks.
- if (refusal) console.error(`model-gateway: catalog refresh did not write (${refusal}); kept the stored catalog from ${catalog.updatedAt || 'an unknown time'}`);
- if (refusal && refresh) process.exitCode = 1;
- if (jsonOut) process.stdout.write(JSON.stringify(catalog) + '\n');
- else log(JSON.stringify(catalog, null, 2));
- }
- function loopbackTelemetryEndpoint() {
- if (!ROUTE_TELEMETRY_ENABLED) return null;
- const explicit = process.env.CODEX_GATEWAY_TELEMETRY_ENDPOINT;
- if (explicit === '0') return null;
- let raw = explicit || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
- let appendTracesPath = false;
- if (!raw && process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
- raw = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
- appendTracesPath = true;
- }
- if (!raw) raw = 'http://127.0.0.1:4318/v1/traces';
- try {
- const endpoint = new URL(raw);
- const hostname = endpoint.hostname.replace(/^\[|\]$/g, '').toLowerCase();
- const loopback = hostname === 'localhost' || hostname === '::1' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
- if (!loopback || !['http:', 'https:'].includes(endpoint.protocol)) return null;
- if (hostname === 'localhost') endpoint.hostname = '127.0.0.1';
- if (appendTracesPath) endpoint.pathname = `${endpoint.pathname.replace(/\/$/, '')}/v1/traces`;
- endpoint.search = '';
- endpoint.hash = '';
- return endpoint;
- } catch {
- return null;
- }
- }
- function parseIncomingTraceparent(headers) {
- if (!ROUTE_TELEMETRY_ENABLED) return null;
- const value = headers.traceparent;
- if (typeof value !== 'string') return null;
- const match = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-[0-9a-f-]+)?$/.exec(value.trim());
- if (!match || match[1] === 'ff' || (match[1] === '00' && match[5])) return null;
- if (/^0{32}$/.test(match[2]) || /^0{16}$/.test(match[3])) return null;
- return { traceId: match[2], parentSpanId: match[3], flags: parseInt(match[4], 16) };
- }
- function safeMetadataId(value, maxLength = 128) {
- if (typeof value !== 'string' || value.length < 1 || value.length > maxLength) return null;
- return /^[a-zA-Z0-9][a-zA-Z0-9._:/\[\]-]*$/.test(value) ? value : null;
- }
- function otlpAttribute(key, value) {
- if (value == null) return null;
- if (typeof value === 'boolean') return { key, value: { boolValue: value } };
- if (typeof value === 'number') {
- if (Number.isInteger(value)) return { key, value: { intValue: String(value) } };
- return { key, value: { doubleValue: value } };
- }
- return { key, value: { stringValue: String(value) } };
- }
- function postRouteSpan(endpoint, span) {
- if (!endpoint) return;
- try {
- const body = JSON.stringify({
- resourceSpans: [{
- resource: { attributes: [otlpAttribute('service.name', 'model-gateway')] },
- scopeSpans: [{
- scope: { name: 'eigenwise.codex-gateway' },
- spans: [span],
- }],
- }],
- });
- const client = endpoint.protocol === 'https:' ? https : http;
- const telemetryReq = client.request(endpoint, {
- method: 'POST',
- agent: false,
- headers: {
- 'content-type': 'application/json',
- 'content-length': Buffer.byteLength(body),
- },
- }, (telemetryRes) => telemetryRes.resume());
- telemetryReq.on('socket', (socket) => socket.unref());
- telemetryReq.on('error', () => {});
- telemetryReq.setTimeout(ROUTE_TELEMETRY_TIMEOUT_MS, () => telemetryReq.destroy());
- telemetryReq.end(body);
- } catch {}
- }
- function routeStatus(statusCode, override) {
- if (override) return override;
- if (!Number.isInteger(statusCode)) return 'upstream_error';
- if (statusCode >= 500) return 'server_error';
- if (statusCode >= 400) return 'client_error';
- return 'ok';
- }
- function buildRouteTelemetry(req) {
- const endpoint = loopbackTelemetryEndpoint();
- if (!endpoint) return { setRoute() {}, finish() {} };
- const incoming = parseIncomingTraceparent(req.headers);
- const traceId = incoming?.traceId || crypto.randomBytes(16).toString('hex');
- const spanId = crypto.randomBytes(8).toString('hex');
- const parentSpanId = incoming?.parentSpanId || null;
- const routeId = crypto.randomUUID();
- const sessionId = safeMetadataId(requestHeader(req, 'x-claude-code-session-id'));
- const startedAt = BigInt(Date.now()) * 1000000n;
- const started = process.hrtime.bigint();
- let route = {};
- let finished = false;
- return {
- setRoute(nextRoute) {
- route = { ...nextRoute };
- },
- finish(statusCode, statusOverride = null) {
- if (finished) return;
- finished = true;
- try {
- const elapsed = process.hrtime.bigint() - started;
- const durationMs = Number(elapsed) / 1000000;
- const status = routeStatus(statusCode, statusOverride);
- const attributes = [
- otlpAttribute('source', 'codex-gateway'),
- otlpAttribute('source_event_id', routeId),
- otlpAttribute('source_schema', '1'),
- otlpAttribute('event_name', 'codex_gateway.route'),
- otlpAttribute('route_id', routeId),
- otlpAttribute('trace_id', traceId),
- otlpAttribute('span_id', spanId),
- otlpAttribute('parent_span_id', parentSpanId),
- otlpAttribute('trace_linked', !!incoming),
- otlpAttribute('session_id', sessionId),
- otlpAttribute('selected_model', safeMetadataId(route.selectedModel)),
- otlpAttribute('effective_model', safeMetadataId(route.effectiveModel)),
- otlpAttribute('backend', ['codex', 'anthropic'].includes(route.backend) ? route.backend : null),
- otlpAttribute('effort', ['low', 'medium', 'high', 'xhigh', 'max'].includes(route.effort) ? route.effort : null),
- otlpAttribute('fallback', route.fallback === true),
- otlpAttribute('via', ['direct', 'dispatch', 'dispatch-cached'].includes(route.via) ? route.via : null),
- otlpAttribute('status', status),
- otlpAttribute('status_code', Number.isInteger(statusCode) ? statusCode : null),
- otlpAttribute('duration_ms', durationMs),
- ].filter(Boolean);
- const endedAt = startedAt + elapsed;
- postRouteSpan(endpoint, {
- traceId,
- spanId,
- ...(parentSpanId ? { parentSpanId } : {}),
- ...(incoming ? { flags: incoming.flags } : {}),
- name: 'codex_gateway.route',
- kind: 2,
- startTimeUnixNano: startedAt.toString(),
- endTimeUnixNano: endedAt.toString(),
- attributes,
- events: [{ timeUnixNano: endedAt.toString(), name: 'codex_gateway.route', attributes }],
- status: { code: status === 'ok' ? 1 : 2 },
- });
- } catch {}
- },
- };
- }
- function createRouteTelemetry(req) {
- try {
- return buildRouteTelemetry(req);
- } catch {
- return { setRoute() {}, finish() {} };
- }
- }
- function requestHeader(req, name) {
- const value = req.headers[name];
- return typeof value === 'string' ? value : null;
- }
- // A completed IncomingMessage can be destroyed while its response is still
- // writable. Only upload aborts and the response's state establish disconnects.
- function uploadResponseUnavailable(req, res) {
- return req.aborted || res.destroyed || res.writableEnded || res.socket?.destroyed;
- }
- function sendUploadError(req, res, statusCode) {
- if (uploadResponseUnavailable(req, res)) return;
- res.writeHead(statusCode, {
- 'connection': 'close', 'x-should-retry': 'false',
- ...(statusCode === 400 ? { 'content-type': 'application/json' } : {}),
- });
- res.end(statusCode === 400 ? JSON.stringify({
- type: 'error',
- error: { type: 'invalid_request_error', message: 'model-gateway could not read the request body' },
- }) : undefined);
- }
- function rejectOversizedUpload(req, res) {
- if (uploadResponseUnavailable(req, res)) return;
- res.writeHead(413, { 'connection': 'close', 'content-length': '0', 'x-should-retry': 'false' });
- // Closing with unread upload bytes can reset even a locally flushed response.
- const drainTimeout = setTimeout(() => res.destroy(), 250);
- drainTimeout.unref();
- res.once('close', () => clearTimeout(drainTimeout));
- req.once('end', () => res.end());
- res.flushHeaders();
- req.resume();
- }
- async function collectShimRequestBody(req, res) {
- const chunks = [];
- let size = 0;
- for await (const chunk of req.iterator({ destroyOnReturn: false })) {
- size += chunk.length;
- if (size > 64 * 1024 * 1024) {
- rejectOversizedUpload(req, res);
- return null;
- }
- chunks.push(chunk);
- }
- return Buffer.concat(chunks);
- }
- async function readShimRequestBody(req, res) {
- try {
- const body = await collectShimRequestBody(req, res);
- return uploadResponseUnavailable(req, res) ? null : body;
- } catch (error) {
- // This boundary covers incoming reads only. Worker failures still follow
- // the relay's existing delivery/retry accounting, not this client error.
- if (!['ECONNRESET', 'ERR_STREAM_PREMATURE_CLOSE', 'ABORT_ERR'].includes(error?.code)) {
- sendUploadError(req, res, 400);
- }
- return null;
- }
- }
- function parseCompatibilityControl(body) {
- try { return JSON.parse(body.toString()) ?? {}; } catch { return {}; }
- }
- const {
- catalogReadiness, effectiveSentryPolicy, getCodexReadiness, hasOpenAiRejectionEvidence, noteCodexUpstreamRejection, runWorker,
- } = require('./request-worker.js');
- function createShimRelay({
- httpClient = http,
- getWorker = () => null,
- getWorkerPort = () => 0,
- isStopped = () => false,
- agent,
- getHealthMetadata = () => ({}),
- onWorkerRequestLost = () => {},
- } = {}) {
- // A worker that already took the body may have spent it upstream, so only
- // the loss of that worker justifies sending the request again: a resend to a
- // live worker is a second inference, billed to the user's subscription, that
- // the caller never sees.
- function requestWorker(req, body) {
- return new Promise((resolve, reject) => {
- let settled = false;
- const settle = (finish, value) => {
- if (settled) return;
- settled = true;
- finish(value);
- };
- const lostWorkerRequest = (error, workerThatTookBody) => {
- onWorkerRequestLost(error, workerThatTookBody);
- return Object.assign(error, { bodyTakenByWorker: true });
- };
- const attempt = (attemptsLeft, acceptingWorker) => {
- if (settled) return;
- const canWait = () => attemptsLeft > 0 && !isStopped();
- const waitForAnotherAttempt = (nextAcceptingWorker) => setTimeout(
- () => attempt(attemptsLeft - 1, nextAcceptingWorker), 50,
- );
- if (acceptingWorker && getWorker() === acceptingWorker) {
- if (!canWait()) return settle(reject, lostWorkerRequest(new Error('shim worker never answered the request it had accepted'), acceptingWorker));
- return waitForAnotherAttempt(acceptingWorker);
- }
- const workerPort = getWorkerPort();
- if (!workerPort) {
- if (!canWait()) return settle(reject, new Error('shim worker did not report a listener port'));
- return waitForAnotherAttempt(null);
- }
- let deliveredToWorker = null;
- const upstream = httpClient.request({
- host: '127.0.0.1', port: workerPort, method: req.method, path: req.url,
- headers: { ...req.headers, host: `127.0.0.1:${workerPort}` }, agent,
- }, (response) => settle(resolve, response));
- upstream.once('socket', (socket) => {
- const noteDelivered = () => { deliveredToWorker = getWorker(); };
- if (socket.connecting) socket.once('connect', noteDelivered);
- else noteDelivered();
- });
- upstream.once('error', (error) => {
- if (settled) return;
- if (!canWait()) return settle(reject, deliveredToWorker ? lostWorkerRequest(error, deliveredToWorker) : error);
- waitForAnotherAttempt(deliveredToWorker);
- });
- upstream.end(body);
- };
- attempt(80, null);
- });
- }
- function relayWorkerResponse(req, res, upstream) {
- // Once the worker's headers are out this can no longer become an HTTP
- // error, and `pipe` forwards neither an error nor an abort, so a worker
- // that dies mid-answer would leave the client holding an open response
- // that never completes. Break the connection instead, the way the worker
- // already does when its own upstream dies, so the client sees ECONNRESET
- // and decides for itself whether to ask again.
- upstream.on('error', () => res.destroy());
- upstream.on('aborted', () => res.destroy());
- if (req.url.split('?')[0] === '/healthz') {
- const response = [];
- upstream.on('data', (chunk) => response.push(chunk));
- upstream.once('end', () => {
- const health = JSON.parse(Buffer.concat(response).toString());
- health.supervisorVersion = PLUGIN_VERSION;
- health.supervisorPid = process.pid;
- health.proxyRecovery = true;
- health.compat = getHealthMetadata();
- res.writeHead(upstream.statusCode || 502, upstream.headers);
- res.end(JSON.stringify(health));
- });
- return;
- }
- res.writeHead(upstream.statusCode || 502, upstream.headers);
- upstream.pipe(res);
- }
- function sendWorkerFailure(res, error) {
- // Claude Code resends any retryable status without telling the user:
- Note: Quoted as data in code: Tells the agent to keep something from the user
- Line 2,166 on GitHub
- // measured at five identical resends of one 503, and `x-should-retry:
- // false` cuts that to none (verification/SQ-2861). So the answer depends
- // on whether a worker took the body: if it did, that inference is
- // already being paid for upstream and a resend silently buys a second
- // one, and if it did not, the resend is free and wanted.
- const bodyTakenByWorker = error?.bodyTakenByWorker === true;
- res.writeHead(503, {
- 'content-type': 'application/json',
- ...(bodyTakenByWorker ? { 'x-should-retry': 'false' } : {}),
- });
- res.end(JSON.stringify({
- type: 'error',
- error: {
- type: 'api_error',
- message: bodyTakenByWorker
- ? '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'
- : 'model-gateway could not deliver this request to the shim worker; retry it shortly',
- },
- }));
- }
- async function relay(req, res) {
- const body = await readShimRequestBody(req, res);
- if (body === null) return;
- try {
- relayWorkerResponse(req, res, await requestWorker(req, body));
- } catch (error) {
- sendWorkerFailure(res, error);
- }
- }
- return { relay, requestWorker };
- }
- function runShim() {
- mkdirs();
- const controlToken = ensureControlToken();
- const supervisorStartedAt = new Date().toISOString();
- const probeChildren = createProbeChildRegistry();
- let proxyRecovery = null;
- recordGatewayLifecycle('supervisor-started', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- });
- process.once('exit', (exitCode) => {
- proxyRecovery?.stopSync();
- recordGatewayLifecycle('supervisor-exit', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- exitCode,
- });
- });
- process.once('uncaughtExceptionMonitor', (error, origin) => {
- const errorType = typeof error?.name === 'string' ? error.name : 'Error';
- recordGatewayLifecycle('supervisor-uncaught-failure', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- outcome: origin,
- errorType,
- });
- try { writeStartupFailure(`model-gateway: shim supervisor stopped after an uncaught ${errorType}`); } catch {}
- });
- const configuredWorkerPort = Number(process.env.CODEX_GATEWAY_WORKER_PORT || 0);
- const workerPortReportTimeoutMs = 5000;
- let workerPort = configuredWorkerPort;
- const timeout = Number(process.env.CODEX_GATEWAY_DRAIN_TIMEOUT_MS) || 30000;
- const hostsEntry = detectHostsCompat();
- const compatState = { hostsDetected: !!hostsEntry, hostsLine: hostsEntry?.line ?? null, port80Bound: false, reason: null };
- let worker = null;
- // One connection per request. A pooled keep-alive socket the worker closed at
- // the same moment fails after the body is written even though the worker never
- // read it, which is indistinguishable from a worker that took the body and
- // went quiet: measured 4 requests over 1 socket on the default agent, so three
- // of four would have been misread that way (verification/SQ-2861).
- const workerAgent = new http.Agent({ keepAlive: false });
- let workerScript = CLI_PATH;
- let workerPortReportTimeout = null;
- let restarting = false;
- let stopped = false;
- const recoveryIntervalMs = Math.max(1000, Number(process.env.CODEX_GATEWAY_PROXY_RECOVERY_INTERVAL_MS) || 5000);
- proxyRecovery = createProxyRecovery({
- probeChildren,
- onStarted: (pid) => {
- writeProxyServingVersion(currentProxyVersion());
- if (pid) trackSupervisorWrite(writePidRecordAsync('proxy', pid, { probeChildren, stillActive: () => !stopped }));
- },
- recordLifecycle: recordGatewayLifecycle,
- });
- let proxyRecoveryTimer = null;
- let main = null;
- let compatServer = null;
- let compatibilityActions = Promise.resolve();
- let activeCompatibilityProbe = null;
- let shutdownPromise = null;
- const pendingSupervisorWrites = new Set();
- function trackSupervisorWrite(write) {
- const completedWrite = write.catch(() => {});
- pendingSupervisorWrites.add(completedWrite);
- void completedWrite.finally(() => pendingSupervisorWrites.delete(completedWrite));
- }
- function closeServer(server) {
- return new Promise((resolve) => {
- if (!server) return resolve();
- try { server.close(() => resolve()); } catch { resolve(); }
- });
- }
- function serializeCompatibility(action) {
- const result = compatibilityActions.then(action, action);
- compatibilityActions = result.catch(() => {});
- return result;
- }
- function stopCompatibilityProbe() {
- activeCompatibilityProbe?.finish({ status: 'unknown', code: 'ESHUTDOWN' });
- }
- function waitForWorkerExit(child, timeout = 3000) {
- return new Promise((resolve) => {
- if (!child || child.exitCode != null) return resolve(true);
- const timer = setTimeout(() => finish(false), timeout);
- const finish = (exited) => {
- clearTimeout(timer);
- child.off('exit', onExit);
- child.off('error', onExit);
- resolve(exited);
- };
- const onExit = () => finish(true);
- child.once('exit', onExit);
- child.once('error', onExit);
- });
- }
- function stopSupervisor(exitCode, signal = null) {
- if (shutdownPromise) return shutdownPromise;
- stopped = true;
- shutdownPromise = (async () => {
- if (signal) {
- recordGatewayLifecycle('supervisor-stop-requested', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- signal,
- });
- if (worker?.pid) {
- recordGatewayLifecycle('worker-stop-requested', {
- component: 'supervisor',
- pid: process.pid,
- child: { component: 'worker', pid: worker.pid },
- signal: WIN ? 'TASKKILL' : signal,
- });
- }
- }
- clearWorkerPortReportTimeout();
- clearInterval(proxyRecoveryTimer);
- stopCompatibilityProbe();
- const stoppingWorker = worker;
- await proxyRecovery.stop();
- await Promise.all([...pendingSupervisorWrites]);
- await compatibilityActions;
- if (stoppingWorker?.connected) {
- try { stoppingWorker.disconnect(); } catch {}
- }
- if (!(await waitForWorkerExit(stoppingWorker))) {
- await killPidAsync(stoppingWorker?.pid, { trusted: true });
- await waitForWorkerExit(stoppingWorker);
- }
- await Promise.all([closeServer(compatServer), closeServer(main)]);
- process.exit(exitCode);
- })();
- return shutdownPromise;
- }
- function clearWorkerPortReportTimeout() {
- if (!workerPortReportTimeout) return;
- clearTimeout(workerPortReportTimeout);
- workerPortReportTimeout = null;
- }
- function stopForMissingWorkerPort() {
- if (stopped || configuredWorkerPort || workerPort) return;
- console.error(`model-gateway: shim worker did not report its listener port within ${workerPortReportTimeoutMs}ms`);
- void stopSupervisor(1);
- }
- function startWorker() {
- if (stopped || (worker && worker.exitCode == null)) return;
- if (!configuredWorkerPort) {
- workerPort = 0;
- workerPortReportTimeout ||= setTimeout(stopForMissingWorkerPort, workerPortReportTimeoutMs);
- }
- const out = fs.openSync(path.join(LOGS, 'shim.log'), 'a');
- const child = fork(workerScript, ['serve-worker'], {
- stdio: ['ignore', out, out, 'ipc'],
- windowsHide: true,
- env: { ...process.env, CODEX_GATEWAY_WORKER_PORT: String(configuredWorkerPort) },
- });
- fs.closeSync(out);
- worker = child;
- recordGatewayLifecycle('worker-started', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- child: { component: 'worker', pid: child.pid },
- });
- if (!configuredWorkerPort) {
- child.once('message', (message) => {
- const reportedPort = message?.type === 'listening' ? message.port : null;
- if (worker !== child || !Number.isInteger(reportedPort) || reportedPort < 1 || reportedPort > 65535) return;
- workerPort = reportedPort;
- clearWorkerPortReportTimeout();
- });
- }
- trackSupervisorWrite(writePidRecordAsync('shim', child.pid, { probeChildren, stillActive: () => !stopped }));
- child.unref();
- child.once('exit', (exitCode, signal) => {
- recordGatewayLifecycle('worker-exit', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- child: { component: 'worker', pid: child.pid },
- exitCode,
- signal,
- });
- if (worker === child) worker = null;
- removePid('shim', child.pid);
- if (!stopped) setTimeout(startWorker, 50);
- });
- }
- function workerReady() {
- return portListening(workerPort, 100);
- }
- const shimRelay = createShimRelay({
- httpClient: http,
- getWorker: () => worker,
- getWorkerPort: () => workerPort,
- isStopped: () => stopped,
- agent: workerAgent,
- getHealthMetadata: () => ({ ...compatState }),
- onWorkerRequestLost: (error, workerThatTookBody) => {
- recordGatewayLifecycle('worker-request-lost', {
- component: 'supervisor',
- pid: process.pid,
- startedAt: supervisorStartedAt,
- ...(workerThatTookBody?.pid ? { child: { component: 'worker', pid: workerThatTookBody.pid } } : {}),
- outcome: 'response-lost',
- errorType: error.code || error.name,
- });
- },
- });
- async function restartWorker(script) {
- if (script && path.isAbsolute(script) && canReplaceInstalledCliPath(workerScript, script)) workerScript = script;
- const current = worker;
- recordGatewayLifecycle('restart-worker-requested', {
- component: 'supervisor',
- pid: process.pid,
- ...(current?.pid ? { child: { component: 'worker', pid: current.pid } } : {}),
- outcome: current ? 'drain' : 'start',
- });
- restarting = true;
- if (!current) {
- restarting = false;
- startWorker();
- return;
- }
- try { await postJson(`http://127.0.0.1:${workerPort}/drain`, { timeout }, timeout + 1000, controlRequestHeaders()); } catch {}
- setTimeout(() => {
- if (worker === current && current.exitCode == null) {
- console.error(`model-gateway: shim drain timed out after ${Math.ceil(timeout / 1000)}s; force-stopping it.`);
- recordGatewayLifecycle('restart-worker-stop-requested', {
- component: 'supervisor',
- pid: process.pid,
- child: { component: 'worker', pid: current.pid },
- signal: WIN ? 'TASKKILL' : 'SIGTERM',
- outcome: 'drain-timeout',
- });
- void killPidAsync(current.pid, { probeChildren });
- }
- }, timeout);
- current.once('exit', () => {
- restarting = false;
- startWorker();
- });
- }
- function controlRequestAllowed(req, compatibilityListener) {
- return !compatibilityListener
- && req.method === 'POST'
- && localRequestAllowed(req, [`127.0.0.1:${PUBLIC_SHIM_PORT}`])
- && req.headers['content-type'] === 'application/json'
- && requestHeader(req, RC_CONTROL_HEADER) === RC_CONTROL_VALUE;
- }
- function sendControlResponse(res, response) {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ ...response, supervisorPid: process.pid }));
- }
- function probeCompatibilityListener() {
- return new Promise((resolve) => {
- const server = net.createServer((socket) => socket.destroy());
- let finished = false;
- const timer = setTimeout(() => finish({ status: 'unknown', code: 'ETIMEDOUT' }), 2000);
- const finish = (result) => {
- if (finished) return;
- finished = true;
- clearTimeout(timer);
- const complete = () => {
- if (activeCompatibilityProbe?.server === server) activeCompatibilityProbe = null;
- resolve(result);
- };
- if (!server.listening) return complete();
- server.once('close', complete);
- try { server.close(); } catch { complete(); }
- };
- activeCompatibilityProbe = { server, finish };
- server.once('error', (error) => finish({ status: 'unavailable', code: error.code || 'EUNKNOWN' }));
- server.once('listening', () => {
- if (finished) return server.close();
- finish({ status: 'bindable' });
- });
- const address = detectHostsCompat()?.ip || '127.0.0.1';
- server.listen(COMPAT_PORT, address);
- });
- }
- function reconcileCompatibilityListener() {
- return serializeCompatibility(async () => {
- const entry = detectHostsCompat();
- await closeServer(compatServer);
- compatServer = null;
- compatState.hostsDetected = !!entry;
- compatState.hostsLine = entry?.line ?? null;
- compatState.port80Bound = false;
- compatState.reason = null;
- if (!entry) return { status: 'bound' };
- return new Promise((resolve) => {
- const server = listen(COMPAT_PORT, entry.ip, () => {
- compatServer = server;
- compatState.port80Bound = true;
- console.log(`model-gateway RC-compatibility supervisor on ${entry.ip}:${COMPAT_PORT}`);
- resolve({ status: 'bound' });
- }, true);
- server.once('error', (error) => {
- if (compatServer === server) compatServer = null;
- compatState.reason = error.code || error.message;
- console.error(`model-gateway: RC-compatibility supervisor unavailable: ${compatState.reason}`);
- resolve({ status: 'unavailable', code: compatState.reason });
- });
- });
- });
- }
- async function handleCompatibilityControl(req, res) {
- async function compatibilityControlResponse(control) {
- if (control.expectedSupervisorPid !== process.pid) return { status: 'unknown' };
- if (control.action === 'probe') {
- return serializeCompatibility(async () => {
- if (compatServer?.listening && compatState.port80Bound) return { status: 'bound' };
- return probeCompatibilityListener();
- });
- }
- if (control.action === 'reconcile') return reconcileCompatibilityListener();
- return { status: 'unknown' };
- }
- const body = await readShimRequestBody(req, res);
- if (body === null) return;
- sendControlResponse(res, await compatibilityControlResponse(parseCompatibilityControl(body)));
- }
- function supervisorRequestAllowed(req, compatibilityListener) {
- const port = req.socket.localPort;
- const hosts = [`127.0.0.1:${port}`, `localhost:${port}`];
- if (compatibilityListener) hosts.push(COMPAT_HOST, `${COMPAT_HOST}:${port}`);
- return localRequestAllowed(req, hosts);
- }
- function handle(req, res, compatibilityListener = false) {
- if (!supervisorRequestAllowed(req, compatibilityListener)) {
- res.writeHead(403);
- res.end();
- return;
- }
- const pathOnly = req.url.split('?')[0];
- if (pathOnly === '/restart' || pathOnly === '/drain') {
- if (!authenticatedControlRequest(req, controlToken, [req.socket.localPort], compatibilityListener)) {
- res.writeHead(403);
- res.end();
- return;
- }
- }
- if (pathOnly === RC_CONTROL_PATH) {
- if (!controlRequestAllowed(req, compatibilityListener)) {
- res.writeHead(404);
- res.end();
- return;
- }
- void handleCompatibilityControl(req, res);
- return;
- }
- if (pathOnly === '/restart') {
- const chunks = [];
- let size = 0;
- req.on('data', (chunk) => {
- size += chunk.length;
- if (size <= 4096) chunks.push(chunk);
- else if (!res.writableEnded) { res.writeHead(413); res.end(); }
- });
- req.on('end', () => {
- if (res.writableEnded) return;
- let script;
- try {
- const body = JSON.parse(Buffer.concat(chunks).toString());
- if (!body || Array.isArray(body) || typeof body !== 'object') throw new Error('invalid restart body');
- script = body.script;
- if (script !== undefined && !canReplaceInstalledCliPath(workerScript, script)) throw new Error('untrusted worker path');
- } catch {
- res.writeHead(400, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ ok: false, reason: 'restart requires this CLI or a non-older sibling in the same plugin cache' }));
- return;
- }
- restartWorker(script);
- res.writeHead(202, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ ok: true, restarting: true }));
- });
- return;
- }
- return shimRelay.relay(req, res);
- }
- function monitorProxy() {
- void proxyRecovery.recover().catch((error) => {
- console.error(`${new Date().toISOString()} model-gateway: proxy recovery failed: ${error.message}`);
- });
- }
- function listen(port, host, callback, compatibilityListener = false) {
- const server = http.createServer((req, res) => handle(req, res, compatibilityListener));
- server.requestTimeout = 0;
- server.headersTimeout = 120000;
- server.keepAliveTimeout = 75000;
- server.listen(port, host, callback);
- return server;
- }
- main = listen(PUBLIC_SHIM_PORT, '127.0.0.1', async () => {
- const publicShimPort = main.address().port;
- try { fs.rmSync(SHIM_FAILURE_PATH); } catch {}
- console.log(`model-gateway shim supervisor listening on 127.0.0.1:${publicShimPort}`);
- await reconcileCompatibilityListener();
- startWorker();
- monitorProxy();
- proxyRecoveryTimer = setInterval(monitorProxy, recoveryIntervalMs);
- proxyRecoveryTimer.unref();
- });
- main.once('error', (error) => {
- void (async () => {
- const owner = error.code === 'EADDRINUSE' ? await processOwningPortAsync(PUBLIC_SHIM_PORT, { probeChildren }) : null;
- const remedy = owner
- ? `PID ${owner} owns 127.0.0.1:${PUBLIC_SHIM_PORT}; run node "${resolveStableCommandPath()}" stop, then node "${resolveStableCommandPath()}" ensure.`
- : `run node "${resolveStableCommandPath()}" stop, then node "${resolveStableCommandPath()}" ensure.`;
- const message = `model-gateway: shim supervisor cannot bind 127.0.0.1:${PUBLIC_SHIM_PORT}: ${error.code || error.message}; ${remedy}`;
- try { writeStartupFailure(message); } catch {}
- console.error(message);
- await stopSupervisor(1);
- })();
- });
- process.once('SIGTERM', () => { void stopSupervisor(0, 'SIGTERM'); });
- process.once('SIGINT', () => { void stopSupervisor(0, 'SIGINT'); });
- if (process.connected) {
- process.once('message', (message) => {
- if (message?.type === 'fixture-shutdown') void stopSupervisor(0, 'fixture-shutdown');
- });
- }
- }
- function sessionStartWiringNotice({ readiness, effectiveWiring, projectWirings }) {
- const processEnvBypass = processEnvGatewayBypass(effectiveWiring);
- if (processEnvBypass) {
- 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.`;
- }
- if (!readiness.checks.codexAuth) {
- 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.';
- }
- const locallyWired = effectiveWiring.source === 'project-local' && ourBaseUrls().includes(effectiveWiring.value);
- if (locallyWired) {
- return `Claude Code is wired to model-gateway through project settings.local.json (${effectiveWiring.file}).`;
- }
- const currentProjectFile = path.resolve(settingsPath('project'));
- const siblingWiring = projectWirings.find(({ file }) => path.resolve(file) !== currentProjectFile);
- if (siblingWiring) {
- 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.`;
- }
- 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.`;
- }
- function loginSuccessMessage({ wired = isWired(), health = null } = {}) {
- if (wired && health && !shimNeedsRestart(PLUGIN_VERSION, health)) {
- return 'signed in; the proxy picks up the new credential on the next request';
- }
- return 'signed in; run setup once more to finish wiring Claude Code';
- }
- const commands = {
- setup: () => withLifecycleLock(() => setup({ preserveWiring: flag('--preserve-wiring') })),
- login: async () => {
- if (!fs.existsSync(PROXY_BIN)) die('proxy binary missing, run setup first');
- const mode = flag('--device') ? 'device' : 'login';
- const result = spawnSync(PROXY_BIN, ['codex', 'auth', mode], { stdio: 'inherit', windowsHide: true });
- if (result.status === 0) log(loginSuccessMessage({ health: await fetchShimHealth() }));
- process.exitCode = result.status == null ? 1 : result.status;
- },
- start: () => withLifecycleLock(async () => {
- const result = await startAll({ lifecycleOperation: 'start', resumeIntent: true });
- if (!result.ok) die(result.reason);
- await statusReport();
- }),
- recover: () => recoverGateway(),
- 'readiness-gate': () => require('./readiness-gate.js').readinessGate(),
- stop: () => withLifecycleLock(async () => {
- recordIntentionalStop();
- const result = await stopAll();
- if (!result.ok) {
- console.error(`model-gateway: ${result.reason}.`);
- process.exitCode = 1;
- return;
- }
- log('stopped');
- }),
- ensure: async () => {
- const quiet = flag('--quiet');
- if (quiet) bufferedHookLines = [];
- // The hook path exits 0 even on a refusal state, because Claude Code reads a hook's stdout JSON only on a
- // zero exit: exiting nonzero there trades the one user-visible line for a bare "hook failed" badge, which is
- // this ticket's whole complaint (SQ-1901). A direct `ensure` still fails loudly for the updater and for a
- // person running it by hand.
- const finish = (code) => { flushHookOutput(); process.exit(quiet ? 0 : code); };
- migrateReadinessGates();
- cleanLegacyEnvSettings();
- cleanLegacyGatewayModelCache();
- sweepOldProxyBinaries();
- repairProjectWiring(noticeForUser);
- const wired = isWired();
- refreshCatalogPinsAndWiring();
- const initialReadiness = await getCodexReadiness();
- if (!initialReadiness.checks.proxyBinary) {
- if (wired) {
- noticeForUser(initialReadiness.message, { toStderr: true });
- finish(1);
- }
- 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.');
- finish(0);
- }
- const result = await ensureWiredGateway(wired, quiet);
- if (!result.ok) {
- if (quiet && result.waitCutShort) {
- if (result.started?.includes('shim')) {
- recordGatewayLifecycle('ensure-hook-wait-cut-short', {
- component: 'SessionStart',
- pid: process.pid,
- outcome: 'supervisor-started',
- });
- }
- noticeForUser('model-gateway is still starting; retry the Codex model in a few seconds', { toStderr: true });
- finish(0);
- }
- noticeForUser(`model-gateway could not start: ${result.reason}. Run \`node "${resolveStableCommandPath()}" doctor\` to see which part is down.`, { toStderr: true });
- finish(1);
- }
- const readiness = await getCodexReadiness();
- if (quiet && !readiness.ready) noticeForUser(readiness.message, { toStderr: true });
- warnIfProxyOutdated();
- const effectiveWiring = effectiveBaseUrl();
- if (!wired) {
- noticeForUser(sessionStartWiringNotice({
- readiness,
- effectiveWiring,
- projectWirings: registeredProjectWirings(),
- }));
- await syncUnwiredPins();
- } else {
- // isWired() accepts a base URL exported by the shell, which is how a machine ends up routed only in the
- // terminal that exported it: background sessions and executor worktrees start unwired, and the only place
- // that said so was a per-request stderr line in the worker.
- const wiring = effectiveWiring;
- if (wiring.source === 'env' && !wiring.shadowed.some((definition) => definition.file)) {
- 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.`);
- }
- await syncCompatMode();
- await syncGatewayWiring();
- await reportStalePickerRowsOncePerCli();
- }
- if (!quiet) await statusReport({ readiness });
- flushHookOutput();
- },
- status: async () => { process.exitCode = (await statusReport()).ok ? 0 : 1; },
- models: async () => {
- const result = await fetchUrl(`http://127.0.0.1:${SHIM_PORT}/v1/models`, { timeout: 3000 })
- .catch(() => die('shim not running (start it first)'));
- log(JSON.stringify(JSON.parse(result.body.toString()), null, 2));
- },
- catalog: () => catalogCommand(),
- pin: () => pinCommand(),
- 'context-window': () => contextWindowCommand(),
- env: () => envCommand(),
- doctor: (options) => doctor(options),
- 'remote-control': () => remoteControlCommand(),
- 'serve-shim': () => runShim(),
- 'serve-worker': () => runWorker(),
- };
- const ensureCommand = commands.ensure;
- commands.ensure = () => automaticLifecycle(ensureCommand);
- module.exports = {
- commands,
- recoverGateway,
- migrateReadinessGates,
- startupFailureFor,
- writeStartupFailure,
- usage: USAGE,
- parseHostsCompatEntry,
- parseHostsCompatBlock,
- addManagedHostsBlock,
- removeManagedHostsBlock,
- findConflictingHostsMappings,
- managedHostsBlock,
- detectHostsCompat,
- hostsFilePath,
- envBlockFor,
- ourBaseUrls,
- isWired,
- wiredMode,
- writeEnv,
- syncUnwiredPins,
- finishUpdateWithoutWiring,
- migrateLegacyProjectSettings,
- effectiveBaseUrl,
- sessionStartWiringNotice,
- loginSuccessMessage,
- startupWaitMsFor,
- startAll,
- statusReport,
- compatibilityPortOwnerIdentifiers,
- requestServingCompatibility,
- syncCompatMode,
- waitForStartupReadiness,
- settingsPath,
- installScope,
- COMPAT_HOST,
- COMPAT_PORT,
- DEFAULT_BASE_URL,
- COMPAT_BASE_URL,
- SOCKET_PATH,
- WIRING_CONFIG_PATH,
- parseSemver,
- processAlive,
- semverLt,
- resolveNewestInstalledCliPath,
- staleSessionReloadNotice,
- oldProxyPath,
- replaceProxyBinary,
- restartProxyForVersionChange,
- restartProxyIfOutdated,
- sweepOldProxyBinaries,
- shimNeedsRestart,
- servingShimVersion,
- restartShimIfOutdated,
- restartSupervisorForVersionMismatch,
- stopShimWithDrain,
- PLUGIN_VERSION,
- MIN_PROXY_VERSION,
- getCodexReadiness,
- catalogReadiness,
- getGrokReadiness,
- setUpstreamBlocked,
- clearUpstreamBlocked,
- readUpstreamUnavailable,
- setUpstreamUnavailable,
- clearUpstreamUnavailable,
- noteCodexRequestSuccess,
- hasOpenAiRejectionEvidence,
- noteCodexUpstreamRejection,
- CODEX_UPSTREAM_BLOCK_PATH,
- CATALOG_SCHEMA_VERSION,
- codexBaseFromId,
- isGatewayModelId,
- buildCatalog,
- writeCatalogFile,
- modelWindowPolicyRows,
- expectedShimModelIds,
- modelIdDifference,
- createShimRelay,
- };
plugins/sidequest/hooks/guards/guards.test.ts · Bundled script · 107 lines · 1 finding marked
- import { expect, mock, test } from 'claude-code/testing'
- import type { On } from 'claude-code'
- const WINDOWS = { OS: 'Windows_NT', USERPROFILE: 'C:\\Users\\kenny' }
- // SQ-3743 probe: classic.PreToolUse gives a module only the envelope, so the guards hook tool.call.
- // This pins that shape: a test hook beneath the module sees no agent_type, session_id or cwd.
- test('classic.PreToolUse carries only the tool envelope, and a guard deny comes back as the deny', async ($, on) => {
- mock.env(on, WINDOWS)
- const seen: string[][] = []
- on('classic.PreToolUse', ($$, e, next) => {
- seen.push(Object.keys(e).sort())
- return next(e)
- })
- passThrough(on)
- await $.tool.call({ tool: 'Bash', command: 'echo ok' })
- expect(seen).toEqual([['command', 'tool', 'tool_use_id']])
- 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
- 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.' })
- expect(seen.length).toBe(1)
- })
- function passThrough(on: On) {
- on('session.id', () => ({ value: 'guards-session' }))
- on('session.cwd', () => ({ value: 'C:/guards-project' }))
- on('fs.read', () => ({ deny: 'ENOENT' }))
- on('tool.call', () => ({ result: 'ran', text: 'ran' }) as never)
- }
- test('an unquoted Windows path in Bash is denied on Windows and allowed elsewhere', async ($, on) => {
- mock.env(on, WINDOWS)
- passThrough(on)
- const denied = await $.tool.call({ tool: 'Bash', command: 'ls C:\\Users\\kenny\\x' })
- expect(denied).toMatchObject({ deny: expect.stringContaining('sidequest: unquoted Windows path in a POSIX shell (C:\\Users\\kenny\\x)') })
- })
- test('a POSIX container path and a Start-Process npm shim get context, not a deny', async ($, on) => {
- mock.env(on, WINDOWS)
- passThrough(on)
- const docker = await $.tool.call({ tool: 'Bash', command: 'docker exec -w /app box ls' })
- expect(docker).toMatchObject({ text: 'ran', context: [expect.stringContaining('sidequest: Git Bash rewrites this POSIX container path')] })
- const shim = await $.tool.call({ tool: 'PowerShell', command: 'Start-Process -FilePath npm -ArgumentList run' })
- expect(shim).toMatchObject({ text: 'ran', context: [expect.stringContaining('sidequest: npm is a .cmd shim on Windows')] })
- })
- test('the Windows-only guards stay silent off Windows', async ($, on) => {
- mock.env(on, { HOME: '/home/kenny' })
- passThrough(on)
- const ran = await $.tool.call({ tool: 'Bash', command: 'ls C:\\Users\\kenny\\x' })
- expect(ran).toMatchObject({ text: 'ran' })
- expect(ran.context).toBeUndefined()
- })
- test('SendMessage retries admission timeouts and preserves the second failure cause', async ($, on) => {
- mock.env(on, WINDOWS)
- passThrough(on)
- let attempts = 0
- const logs: string[] = []
- const notices: string[] = []
- on('process.run', () => {
- attempts += 1
- if (attempts === 1) return { deny: 'sidequest: $.process.run(node) aborted: still running after 10000ms' }
- return { value: { exitCode: 3, stdout: '', stderr: 'dispatch store unavailable' } }
- })
- on('ui.log', ($$, event) => { logs.push(event.text); return { value: undefined } })
- on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
- const denied = await $.tool.call({ tool: 'SendMessage', to: 'executor', message: 'continue' } as never)
- expect(denied).toMatchObject({ deny: expect.stringContaining('admission decision exited 3: dispatch store unavailable') })
- expect(attempts).toBe(2)
- expect(logs).toEqual(['guard-executor-admission failed for SendMessage: admission decision exited 3: dispatch store unavailable'])
- expect(notices).toEqual(logs)
- })
- test('an advisory guard error logs and toasts once without a duplicate plugin prefix or sticky status', async ($, on) => {
- mock.env(on, WINDOWS)
- passThrough(on)
- const notices: string[] = []
- const logs: object[] = []
- const statuses: unknown[] = []
- on('state.get', ($$, event, next) => {
- if (event.key === 'inlineWork') return { deny: 'state unavailable' }
- return next(event)
- })
- on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
- on('ui.log', ($$, event) => { logs.push(event); return { value: undefined } })
- on('ui.status', ($$, event) => { statuses.push(event.text); return { value: undefined } })
- expect(await $.tool.call({ tool: 'Read', file_path: 'file.txt' })).toMatchObject({ text: 'ran' })
- expect(notices).toEqual(['inline-work-nudge failed for Read: sidequest: $.state.get: state unavailable'])
- expect(logs).toEqual([{ text: notices[0], to: 'debug' }])
- expect(statuses).toEqual([])
- })
- test('a refusing guard error logs and toasts once and blocks the tool with its error', async ($, on) => {
- mock.env(on, WINDOWS)
- on('tool.call', () => ({ result: 'ran', text: 'ran' }) as never)
- const notices: string[] = []
- const logs: object[] = []
- on('session.cwd', () => ({ deny: 'session cwd unavailable' }))
- on('ui.toast', ($$, event) => { notices.push(event.text); return { value: undefined } })
- on('ui.log', ($$, event) => { logs.push(event); return { value: undefined } })
- const denied = await $.tool.call({ tool: 'Read', file_path: 'file.txt', agentId: 'executor' } as never)
- expect(denied).toMatchObject({ deny: 'sidequest: guard-denied-tools failed for Read: sidequest: $.session.cwd: session cwd unavailable; tool call refused' })
- expect(notices).toEqual(['guard-denied-tools failed for Read: sidequest: $.session.cwd: session cwd unavailable'])
- expect(logs).toEqual([{ text: notices[0], to: 'debug' }])
- })
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.