Skip to content
Back to search

claude-night-market

MarketplaceWorks with Claude CodeGitHub

23 production-ready Claude Code plugins: git workflows, code review, spec-driven development, architecture patterns, codebase visualization, resource optimization, memory systems, multi-LLM delegation, ML inference, knowledge challenges, and multi-source research

Safety scan

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

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

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

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/athola/claude-night-market 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/athola/claude-night-market'

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

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/athola--claude-night-market/badge.svg)](/listings/athola--claude-night-market)

HTML

<a href="/listings/athola--claude-night-market"><img src="/api/listings/athola--claude-night-market/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.

Requires **Claude Code 2.1.16+** (2.1.32+ for agent teams, 2.1.38+ for security features, 2.1.287+ for the context and loop bands that conserve and egregore draw above the prompt) and **Python 3.9+** for hooks, which is what macOS ships.

# Add the marketplace, then install the plugins you want
/plugin marketplace add athola/claude-night-market
/plugin install sanctum@claude-night-market    # Git workflows
/plugin install pensive@claude-night-market    # Code review
/plugin install spec-kit@claude-night-market   # Spec-driven dev

Run `claude --init-only` once after installing. It runs the plugins' Setup hooks, then exits. Updates are not automatic for third-party marketplaces. The [Installation Guide][install] shows how to enable auto-update, and covers the one-command, `opkg`, and skill-files-only install paths.

> If the `Skill` tool is unavailable, read skill files directly > at `plugins/{plugin}/skills/{skill-name}/SKILL.md`.

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 · 177 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "claude-night-market",
  4. "version": "1.10.3",
  5. "description": "23 production-ready Claude Code plugins: git workflows, code review, spec-driven development, architecture patterns, codebase visualization, resource optimization, memory systems, multi-LLM delegation, ML inference, knowledge challenges, and multi-source research",
  6. "owner": {
  7. "name": "athola",
  8. "email": "athola@users.noreply.github.com"
  9. },
  10. "renames": {
  11. "conservation": "conserve",
  12. "pensieve": "pensive"
  13. },
  14. "plugins": [
  15. {
  16. "name": "abstract",
  17. "source": "./plugins/abstract",
  18. "description": "Skill authoring, hook development, evaluation frameworks, and escalation governance for the Claude Code plugin ecosystem",
  19. "version": "1.10.3",
  20. "keywords": ["meta", "skill-authoring", "hooks", "evaluation"]
  21. },
  22. {
  23. "name": "attune",
  24. "source": "./plugins/attune",
  25. "description": "Full-cycle project development: brainstorm, specify, plan, initialize, execute, and polish with war-room deliberation for strategic decisions",
  26. "version": "1.10.3",
  27. "keywords": ["project-lifecycle", "brainstorming", "planning", "scaffolding"]
  28. },
  29. {
  30. "name": "archetypes",
  31. "source": "./plugins/archetypes",
  32. "description": "Architecture paradigm selection and implementation planning: 14 paradigms from functional-core to hexagonal to microservices",
  33. "version": "1.10.3",
  34. "keywords": ["architecture", "design-patterns", "hexagonal", "cqrs", "microservices"]
  35. },
  36. {
  37. "name": "cartograph",
  38. "source": "./plugins/cartograph",
  39. "description": "Codebase visualization: architecture, data flow, dependency, call chains, community detection, and class diagrams via Mermaid Chart MCP",
  40. "version": "1.10.3",
  41. "keywords": ["visualization", "diagram", "mermaid", "architecture", "data-flow", "call-chain", "community-detection"]
  42. },
  43. {
  44. "name": "conjure",
  45. "source": "./plugins/conjure",
  46. "description": "Delegate tasks to external LLMs (Gemini, Qwen) with cheapest-capable model selection while retaining strategic oversight",
  47. "version": "1.10.3",
  48. "keywords": ["llm-delegation", "multi-model", "gemini", "qwen"]
  49. },
  50. {
  51. "name": "conserve",
  52. "source": "./plugins/conserve",
  53. "description": "Context optimization, bloat detection, CPU/GPU monitoring, and token conservation for efficient Claude Code sessions",
  54. "version": "1.10.3",
  55. "keywords": ["optimization", "performance", "bloat-detection", "token-conservation"]
  56. },
  57. {
  58. "name": "hookify",
  59. "source": "./plugins/hookify",
  60. "description": "Behavioral rules engine: create safety hooks through markdown configuration with pattern matching and zero-code rule authoring",
  61. "version": "1.10.3",
  62. "keywords": ["hooks", "safety", "behavioral-rules", "configuration"]
  63. },
  64. {
  65. "name": "imbue",
  66. "source": "./plugins/imbue",
  67. "description": "TDD enforcement, proof-of-work validation, scope guarding, rigorous reasoning, and research-enriched feature review with RICE/WSJF/Kano scoring",
  68. "version": "1.10.3",
  69. "keywords": ["tdd", "quality-gates", "proof-of-work", "scope-guard"]
  70. },
  71. {
  72. "name": "leyline",
  73. "source": "./plugins/leyline",
  74. "description": "Foundation infrastructure: auth flows, quota management, error patterns, markdown formatting, trust verification, and injection detection",
  75. "version": "1.10.3",
  76. "keywords": ["infrastructure", "auth", "security", "injection-detection", "quota"]
  77. },
  78. {
  79. "name": "memory-palace",
  80. "source": "./plugins/memory-palace",
  81. "description": "Spatial knowledge organization with memory palace techniques: build, navigate, and maintain virtual memory structures with PR review capture",
  82. "version": "1.10.3",
  83. "keywords": ["memory", "knowledge-management", "spatial-organization", "recall"]
  84. },
  85. {
  86. "name": "minister",
  87. "source": "./plugins/minister",
  88. "description": "GitHub issue management, label taxonomy, and initiative tracking: turns repositories, issues, and projects into status dashboards",
  89. "version": "1.10.3",
  90. "keywords": ["project-management", "github-issues", "tracking", "dashboards"]
  91. },
  92. {
  93. "name": "parseltongue",
  94. "source": "./plugins/parseltongue",
  95. "description": "Python development suite: testing, performance optimization, async patterns, and packaging guidance",
  96. "version": "1.10.3",
  97. "keywords": ["python", "testing", "async", "packaging", "performance"]
  98. },
  99. {
  100. "name": "pensive",
  101. "source": "./plugins/pensive",
  102. "description": "Multi-discipline code review: architecture, bugs, APIs, blast radius analysis, security, tests, Makefiles, and NASA Power of 10 analysis",
  103. "version": "1.10.3",
  104. "keywords": ["code-review", "architecture-review", "bug-hunting", "blast-radius", "security-review"]
  105. },
  106. {
  107. "name": "phantom",
  108. "source": "./plugins/phantom",
  109. "description": "Computer use toolkit for driving desktop environments through Claude's vision and action API with screenshot capture, mouse/keyboard control, and an autonomous agent loop",
  110. "version": "1.10.3",
  111. "keywords": ["computer-use", "desktop", "automation", "screenshot", "mouse", "keyboard", "gui"]
  112. },
  113. {
  114. "name": "sanctum",
  115. "source": "./plugins/sanctum",
  116. "description": "Git workflows: commit messages, PR preparation, documentation updates, version management, sessions, and deferred-item capture",
  117. "version": "1.10.3",
  118. "keywords": ["git", "commits", "pull-requests", "version-management"]
  119. },
  120. {
  121. "name": "scribe",
  122. "source": "./plugins/scribe",
  123. "description": "Documentation review, cleanup, and generation with AI slop detection, style learning, and human-quality writing enforcement",
  124. "version": "1.10.3",
  125. "keywords": ["documentation", "slop-detection", "writing", "style"]
  126. },
  127. {
  128. "name": "scry",
  129. "source": "./plugins/scry",
  130. "description": "Media generation: terminal recordings (VHS), browser recordings (Playwright), GIF processing, and media composition",
  131. "version": "1.10.3",
  132. "keywords": ["media", "recordings", "vhs", "playwright", "gif"]
  133. },
  134. {
  135. "name": "spec-kit",
  136. "source": "./plugins/spec-kit",
  137. "description": "Specification-driven development: structured specs, implementation planning, and task orchestration for systematic feature delivery",
  138. "version": "1.10.3",
  139. "keywords": ["specifications", "planning", "task-orchestration", "feature-delivery"]
  140. },
  141. {
  142. "name": "egregore",
  143. "source": "./plugins/egregore",
  144. "description": "Autonomous agent orchestrator: parallel worktree execution, agent specialization, cross-item learning, and crash recovery",
  145. "version": "1.10.3",
  146. "keywords": ["autonomous-agents", "orchestration", "parallel-execution", "worktrees"]
  147. },
  148. {
  149. "name": "gauntlet",
  150. "source": "./plugins/gauntlet",
  151. "description": "Codebase learning through knowledge extraction, code knowledge graph, adaptive challenges, and spaced repetition for developer onboarding and fluency",
  152. "version": "1.10.3",
  153. "keywords": ["learning", "onboarding", "knowledge", "challenges", "spaced-repetition", "code-graph"]
  154. },
  155. {
  156. "name": "herald",
  157. "source": "./plugins/herald",
  158. "description": "Standalone notification system: GitHub issue alerts and webhook support for Slack, Discord, and generic endpoints.",
  159. "version": "1.10.3",
  160. "keywords": ["notifications", "alerts", "webhooks", "github-issues", "slack", "discord"]
  161. },
  162. {
  163. "name": "oracle",
  164. "source": "./plugins/oracle",
  165. "description": "ONNX Runtime inference daemon for ML-enhanced plugin capabilities with local model inference over HTTP and opt-in activation",
  166. "version": "1.10.3",
  167. "keywords": ["ml", "inference", "onnx", "scoring", "daemon"]
  168. },
  169. {
  170. "name": "tome",
  171. "source": "./plugins/tome",
  172. "description": "Multi-source research: code archaeology, community discourse (HN, Reddit), academic literature (arXiv, Semantic Scholar), and TRIZ cross-domain analysis",
  173. "version": "1.10.3",
  174. "keywords": ["research", "code-archaeology", "academic", "triz", "literature-review"]
  175. }
  176. ]
  177. }
README.md · README · 239 lines
  1. # Claude Night Market
  2. [![Version](https://img.shields.io/badge/version-1.10.3-blue)](CHANGELOG.md)
  3. [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
  4. [![Plugins](https://img.shields.io/badge/plugins-23-orange)](book/src/plugins/)
  5. [![Skills](https://img.shields.io/badge/skills-199-teal)](book/src/reference/capabilities-reference.md)
  6. [![Claude Code](https://img.shields.io/badge/Claude_Code-2.1.16%2B-purple)](https://code.claude.com/docs/en/overview)
  7. **A plugin marketplace for Claude Code.** Install only the
  8. plugins you need to run git workflows, code review,
  9. spec-driven development, and autonomous agents from inside
  10. your Claude Code session.
  11. *Written for a practitioner: someone who already uses Claude Code and
  12. wants to know what these plugins do and whether to install them. If you
  13. are new to Claude Code, start with the
  14. [official docs](https://code.claude.com/docs/en/overview). For the
  15. design rationale behind a plugin, see
  16. [the book](book/src/plugins/).*
  17. <p align="center">
  18. <img src="assets/gifs/skills-showcase.gif" alt="Night Market skills in action" width="720">
  19. </p>
  20. ## Install
  21. Requires **Claude Code 2.1.16+** (2.1.32+ for agent teams, 2.1.38+
  22. for security features, 2.1.287+ for the context and loop bands that
  23. conserve and egregore draw above the prompt) and **Python 3.9+** for
  24. hooks, which is what macOS ships.
  25. ```bash
  26. # Add the marketplace, then install the plugins you want
  27. /plugin marketplace add athola/claude-night-market
  28. /plugin install sanctum@claude-night-market # Git workflows
  29. /plugin install pensive@claude-night-market # Code review
  30. /plugin install spec-kit@claude-night-market # Spec-driven dev
  31. ```
  32. Run `claude --init-only` once after installing. It runs the plugins'
  33. Setup hooks, then exits. Updates are not automatic for third-party
  34. marketplaces. The [Installation Guide][install] shows how to enable
  35. auto-update, and covers the one-command, `opkg`, and skill-files-only
  36. install paths.
  37. > If the `Skill` tool is unavailable, read skill files directly
  38. > at `plugins/{plugin}/skills/{skill-name}/SKILL.md`.
  39. ## Everyday Use
  40. Night Market is built around the loop you already work in.
  41. A typical feature runs end to end on a handful of commands:
  42. 1. **Start a feature.** `/attune:mission` routes you through
  43. brainstorm, specify, plan, and execute phases.
  44. 2. **Write the code.** `imbue` enforces a failing test before
  45. the implementation is written.
  46. 3. **Review before you push.** `/full-review` runs a
  47. multi-discipline pass; `/refine-code` cleans up duplication
  48. and dead code.
  49. 4. **Ship it.** `/prepare-pr` runs quality gates and drafts a
  50. description that says who the change is for, where it lands
  51. inside and outside the codebase, and when it is fully
  52. integrated.
  53. 5. **Pick up where you left off.** `/catchup` rebuilds context
  54. from recent git history after a break.
  55. The commands you reach for most:
  56. | Task | Command |
  57. |------|---------|
  58. | Run the project lifecycle | `/attune:mission` |
  59. | Initialize a new project | `/attune:arch-init` |
  60. | Review a PR | `/full-review` |
  61. | Address review feedback | `/fix-pr` |
  62. | Implement an issue | `/do-issue` |
  63. | Prepare a pull request | `/prepare-pr` |
  64. | Write a spec | `/speckit-specify` |
  65. | Catch up on changes | `/catchup` |
  66. | Package project knowledge as skills | `/attune:skill-library` |
  67. | Clean up the codebase | `/unbloat` |
  68. | Pressure-test a decision | `/attune:war-room` |
  69. Full task-by-task walkthroughs are in the
  70. [Common Workflows Guide][workflows].
  71. ## What's Inside
  72. 23 plugins in four layers. Each installs independently, and
  73. dependencies pull their shared runtime automatically.
  74. **Foundation** is the base every other layer builds on:
  75. `leyline` (auth, quotas, error patterns, trust verification),
  76. `sanctum` (git, commits, PR prep, sessions), and `imbue`
  77. (TDD enforcement, proof-of-work, scope guarding).
  78. **Utility** handles cross-cutting concerns: `conserve` (context
  79. and token optimization), `conjure` (delegation to seven external
  80. model CLIs plus a local runner), `hookify` (a behavioral rules
  81. engine with a security catalog), `egregore` (autonomous agent
  82. orchestration), `herald` (notifications), and `oracle` (local ML
  83. inference).
  84. **Domain** is where the day-to-day work happens: `pensive` (code
  85. and architecture review), `attune` (project lifecycle), `spec-kit`
  86. (spec-driven development), `parseltongue` (Python), `minister`
  87. (GitHub issues and DORA metrics), `memory-palace` (knowledge
  88. organization), `archetypes` (architecture paradigms), `gauntlet`
  89. (codebase learning), `phantom` (computer use), `scribe`
  90. (documentation and slop detection), `scry` (recordings), `tome`
  91. (research), and `cartograph` (codebase visualization).
  92. **Meta** improves the system itself: `abstract` (skill authoring,
  93. hook development, evaluation, and skill-stability tracking).
  94. <picture>
  95. <source media="(prefers-color-scheme: dark)" srcset="assets/architecture-dark.svg">
  96. <img alt="Plugin architecture across Foundation, Utility, Domain, and Meta layers" src="assets/architecture-light.svg">
  97. </picture>
  98. The full skill, command, and agent inventory is in the
  99. [Capabilities Reference](book/src/reference/capabilities-reference.md).
  100. ## Safety
  101. > ⚠️ Plugins run inside your Claude Code session and can read or
  102. > edit your repo, run shell commands, and call external services.
  103. > **Review any plugin before installing it.**
  104. Five guards reduce the blast radius, but none replace your own
  105. review:
  106. - **TDD gates** (`imbue`) block implementation writes that lack a
  107. failing test.
  108. - **Destructive-command blockers** (`conserve`, `hookify`)
  109. auto-approve safe commands and halt or warn on `rm -rf`,
  110. `git push --force`, and production-shaped targets.
  111. - **Credential-read denial** (`conserve`) refuses `cat`, `head`,
  112. `grep`, `rg` and `git show` on `.env`, `.netrc`, credential files
  113. and SSH keys.
  114. - **External-content sanitizing** (`leyline`) strips invisible
  115. characters from web fetches and other external-tool output, and
  116. blocks prompt-injection phrases before the model reads them.
  117. - **Additive-bias audits** (`leyline`) flag unjustified additions
  118. before commit.
  119. [CONSTITUTION.md](CONSTITUTION.md) holds the rules that override any
  120. conflicting skill or hook, each paired with what checks it.
  121. [STEWARDSHIP.md](STEWARDSHIP.md) is the maintenance contract.
  122. ## Network and data
  123. Three parts of the marketplace reach off your machine, and each can be
  124. turned off. Two hooks use your existing GitHub credentials, and both do
  125. nothing when `gh` is unauthenticated or the network is unavailable.
  126. - **Star prompt** (`leyline`, `hooks/auto-star-repo.sh`). On session
  127. start it checks whether you have starred this repository, through
  128. `gh` or a `GITHUB_TOKEN` / `GH_TOKEN` variable. It reads star status,
  129. asks once per session, and never stars without your consent.
  130. `CLAUDE_NIGHT_MARKET_NO_STAR_PROMPT=1` disables it.
  131. - **Learnings posting** (`abstract`, `hooks/post_learnings_stop.py`).
  132. On session stop, when `~/.claude/skills/LEARNINGS.md` has content, it
  133. posts a skill-usage discussion through `gh` and may promote
  134. high-severity items to issues. The target is `target_repo` in
  135. `~/.claude/skills/discussions/config.json`, else the current repo.
  136. It is on by default. `auto_post_learnings: false` in that file
  137. disables it.
  138. - **Delegation** (`conjure`, also reached by `attune` missions and
  139. `egregore` steps) sends the prompt and the file contents it carries to
  140. the first external model CLI that answers, in the order Gemini, Qwen,
  141. MiniMax, GLM, Muse, Codex, OpenCode, under the credentials you
  142. configured for it. It runs by default. `CONJURE_DELEGATION=off`
  143. declines it for one run, and `"enabled": false` in
  144. `~/.claude/hooks/delegation/config.json` declines it on one machine.
  145. When no provider answers, the work stays on your machine.
  146. ## Plugin Development
  147. ```bash
  148. make validate-all
  149. make lint && make test # checks only; rewrites nothing
  150. make fix # ruff format + ruff check --fix
  151. ```
  152. A plugin directory holds `.claude-plugin/plugin.json` (metadata)
  153. plus any of `commands/`, `skills/`, `hooks/`, `agents/`,
  154. `workflows/`, and `tests/`, with a `Makefile` and
  155. `pyproject.toml`. A `workflows/` script orchestrates several
  156. subagents at once and runs only when you ask for one. Copy the
  157. layout from an existing plugin such as `plugins/abstract`, then
  158. see the [Plugin Development Guide][dev-guide] for structure and
  159. naming conventions. Working on this repo needs **Python 3.12+**
  160. and **GNU make 3.82+**. The guide covers both, including why
  161. Xcode's make 3.81 reports a green build it did not run.
  162. ## Documentation
  163. - [Installation Guide](book/src/getting-started/installation.md)
  164. - [Quick Start](book/src/getting-started/quick-start.md)
  165. - [Common Workflows][workflows]
  166. - [Plugin Development Guide][dev-guide]
  167. - [Capabilities Reference](book/src/reference/capabilities-reference.md)
  168. - [Tutorials](book/src/tutorials/README.md)
  169. - [Architecture Decision Records](docs/adr/)
  170. - [CHANGELOG](CHANGELOG.md)
  171. Per-plugin pages are in `book/src/plugins/`.
  172. ## Stewardship and Contributing
  173. Every plugin is entrusted to the community: steward rather than
  174. own, and think several iterations ahead. Each plugin maintains
  175. its own tests and docs; run `make test` at the repo root to
  176. execute every suite, and `/stewardship-health` to view per-plugin
  177. health. Contribution guidelines are in the
  178. [Plugin Development Guide][dev-guide].
  179. ## Acknowledgements
  180. Night Market builds on [Anthropic Claude Code][claude-code] and
  181. integrates with [github/spec-kit][spec-kit-upstream] (v1.4.0) and
  182. [obra/superpowers][superpowers-upstream] (v7.0.2, see the
  183. [integration guide][superpowers-doc]). Its AI involvement is declared
  184. under the [Quillx][quillx] disclosure standard as 3/5 (Adapted):
  185. human-directed, AI-generated, and meaningfully edited.
  186. ## License
  187. [MIT](LICENSE)
  188. [claude-code]: https://docs.anthropic.com/en/docs/build-with-claude/claude-code
  189. [dev-guide]: docs/plugin-development-guide.md
  190. [workflows]: book/src/getting-started/common-workflows.md
  191. [spec-kit-upstream]: https://github.com/github/spec-kit
  192. [superpowers-upstream]: https://github.com/obra/superpowers
  193. [superpowers-doc]: book/src/reference/superpowers-integration.md
  194. [quillx]: https://github.com/QAInsights/Quillx
  195. [install]: book/src/getting-started/installation.md
plugins/conjure/scripts/delegation_services.py · Bundled script · 709 lines · 2 findings marked
  1. """Service registry, config contract and credential checks for delegation.
  2. Split out of ``delegation_executor`` so the data a provider is described
  3. by, and the checks that read that data without spawning anything, can be
  4. changed without touching the process that spawns. Imports flow one way:
  5. this module never imports ``Delegator``.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. import re
  11. import time
  12. from dataclasses import MISSING, dataclass, field, fields, replace
  13. from datetime import datetime
  14. from pathlib import Path
  15. from typing import Any
  16. from scripts.quota_tracker import (
  17. DEFAULT_CODEX_LIMITS,
  18. DEFAULT_GEMINI_LIMITS,
  19. DEFAULT_GLM_LIMITS,
  20. DEFAULT_MINIMAX_LIMITS,
  21. DEFAULT_MUSE_LIMITS,
  22. DEFAULT_OPENCODE_LIMITS,
  23. DEFAULT_QWEN_LIMITS,
  24. )
  25. # Spawning a binary by name trusts whatever PATH resolves it to, so every name
  26. # this module spawns is recorded here with the package that publishes it and a
  27. # source a reviewer can check. A service whose command is absent from this map
  28. # fails its test rather than reaching a user's shell.
  29. VERIFIED_BINARIES: dict[str, dict[str, str]] = {
  30. "gemini": {
  31. "package": "@google/gemini-cli",
  32. "publisher": "Google",
  33. "install": "npm install -g @google/gemini-cli",
  34. "source": "https://github.com/google-gemini/gemini-cli",
  35. },
  36. "qwen": {
  37. "package": "@qwen-code/qwen-code",
  38. "publisher": "Alibaba / QwenLM",
  39. "install": "npm install -g @qwen-code/qwen-code",
  40. "source": "https://github.com/QwenLM/qwen-code",
  41. },
  42. "mmx": {
  43. "package": "mmx-cli",
  44. "publisher": "MiniMax-AI",
  45. "install": "npm install -g mmx-cli",
  46. "source": "https://github.com/MiniMax-AI/cli",
  47. },
  48. # Spawned by the endpoint-swap services, which run the stock binary
  49. # against a different base URL rather than shipping a CLI of their own.
  50. "claude": {
  51. "package": "@anthropic-ai/claude-code",
  52. "publisher": "Anthropic",
  53. "install": "npm install -g @anthropic-ai/claude-code",
  54. "source": "https://github.com/anthropics/claude-code",
  55. },
  56. # Meta publishes no npm or PyPI artifact for Muse Code: the documented
  57. # install is a script served from Meta's own domain.
  58. "muse": {
  59. "package": "muse-code (standalone installer)",
  60. "publisher": "Meta",
  61. "install": "curl -fsSL https://dev.meta.ai/install.sh | sh",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 66 on GitHub
  62. "source": "https://dev.meta.ai/docs/muse-code",
  63. },
  64. "codex": {
  65. "package": "@openai/codex",
  66. "publisher": "OpenAI",
  67. "install": "npm install -g @openai/codex",
  68. "source": "https://github.com/openai/codex",
  69. },
  70. "opencode": {
  71. "package": "opencode-ai",
  72. "publisher": "SST",
  73. "install": "npm install -g opencode-ai@latest",
  74. "source": "https://github.com/sst/opencode",
  75. },
  76. "ollama": {
  77. "package": "ollama",
  78. "publisher": "Ollama",
  79. "install": "curl -fsSL https://ollama.com/install.sh | sh",
  80. "source": "https://github.com/ollama/ollama",
  81. },
  82. }
  83. # Above this, an epoch timestamp is milliseconds rather than seconds. The
  84. # boundary is in the year 5138 read as seconds, so no real deadline is
  85. # ambiguous.
  86. _EPOCH_MILLISECOND_FLOOR = 100_000_000_000
  87. #: The values ``delegation_executor`` and the verifier actually branch on.
  88. #: Kept as a frozenset beside the type rather than an Enum, because these
  89. #: configs are built from YAML and an Enum would push the same string
  90. #: validation up to every construction site.
  91. AUTH_METHODS = frozenset({"api_key", "cli", "none"})
  92. @dataclass(frozen=True)
  93. class ServiceConfig:
  94. """Configuration for a delegation service.
  95. Frozen because the registry is shared. ``Delegator.__init__`` copies
  96. the ``SERVICES`` mapping and not its values, so every Delegator in a
  97. process holds these same objects; while this was mutable, one field
  98. assignment rewrote the contract process wide. ``_apply_overrides``
  99. already builds a new object with ``replace``, so nothing needed to
  100. assign.
  101. The trailing fields describe the CLI contract. They exist because the
  102. supported CLIs genuinely diverge: ``mmx`` puts text generation behind a
  103. ``text chat`` subcommand, names its prompt flag ``--message``, spells
  104. output format ``--output``, and has no ``@path`` context syntax.
  105. Defaults reproduce the Gemini contract, so existing services and custom
  106. entries in ``config.json`` are unaffected.
  107. A default is a claim about a CLI, not a neutral placeholder: a provider
  108. that leaves ``output_format_flag`` alone is asserting that its binary
  109. spells the flag ``--output-format``. Four did not, and the mismatch
  110. only surfaced when a caller passed the matching option. Probe the
  111. binary before trusting a default here.
  112. """
  113. name: str
  114. command: str
  115. #: One of :data:`AUTH_METHODS`. Validated in ``__post_init__`` because
  116. #: ``_apply_overrides`` checks field *names* and not their values, so
  117. #: "apikey" constructed cleanly and then silently skipped both the auth
  118. #: probe and the API-key check: a service that looked configured and
  119. #: authenticated against nothing.
  120. auth_method: str
  121. auth_env_var: str | None = None
  122. quota_limits: dict[str, int] | None = None
  123. # Tuple rather than list: a default_factory field would read as required
  124. # to _missing_required_fields and silently skip valid custom configs.
  125. subcommand: tuple[str, ...] = ()
  126. # None means the prompt is positional. ``muse exec <prompt>``,
  127. # ``codex exec <prompt>`` and ``opencode run <prompt>`` all take it that
  128. # way, so a flag name is not universal enough to be mandatory.
  129. prompt_flag: str | None = "-p"
  130. # Long form of the prompt flag, used to attach a dash-leading prompt as
  131. # ``--prompt=-x``. A separator does not protect a flag's value: probed on
  132. # 2026-08-22, ``gemini -p -- --help`` still printed the help page while
  133. # ``gemini --prompt=--help`` reached authentication. Positional providers
  134. # need no entry here and take ``--`` instead. The default pairs with
  135. # the default ``-p``: both are the Gemini spelling.
  136. prompt_long_flag: str | None = "--prompt"
  137. # None where the CLI takes no format value. muse and codex offer only a
  138. # boolean ``--json``, which a flag-and-value pair cannot express.
  139. # How this CLI is told which model to use. `--model` was hardcoded at
  140. # the call site while the comment above it claimed every flag spelling
  141. # comes from the config, and it is not universal: `ollama run --help`
  142. # (0.13.1) lists no --model at all, because `ollama run MODEL [PROMPT]`
  143. # takes the model positionally. None means the model is not passed as a
  144. # flag. Recorded from each CLI's own --help: gemini 0.26.0, qwen, codex,
  145. # opencode and muse document `-m, --model`; `claude --model` and
  146. # `mmx text chat --model` likewise.
  147. model_flag: str | None = "--model"
  148. output_format_flag: str | None = "--output-format"
  149. # True when the flag above takes no value. `muse exec --json` and
  150. # `codex exec --json` are booleans: "Emit machine-readable JSONL
  151. # events on stdout", read off each binary's own --help. The
  152. # key-and-value shape cannot express that, since `--json json` lands
  153. # "json" as a positional and both providers take the prompt
  154. # positionally, so the request used to be dropped in silence.
  155. output_format_is_boolean: bool = False
  156. temperature_flag: str | None = "--temperature"
  157. inline_files: bool = False
  158. # Prompt on stdin rather than argv. execve caps a single argument at
  159. # 128 KiB, which a large inlined context exceeds.
  160. stdin_prompt: bool = False
  161. # Environment applied to the child only. An endpoint-swap harness runs a
  162. # stock binary against a different base URL, which is environment, not
  163. # argv. Values may reference the caller's variables as ``${VAR}`` so a
  164. # credential is named here rather than stored here.
  165. env: dict[str, str] = field(default_factory=dict)
  166. # Probes, because not every CLI answers --version or `auth status`.
  167. version_probe: tuple[str, ...] = ("--version",)
  168. auth_probe: tuple[str, ...] = ("auth", "status")
  169. # Files the CLI writes its credentials to, ``~`` accepted. The check is
  170. # one-directional: all of them absent means the CLI cannot be
  171. # authenticated, and any of them present means only that the question
  172. # stays open. Presence is never evidence of a working credential.
  173. # `opencode auth list` exits 0 naming a credentials path that does not
  174. # exist, and `codex login status` prints "Logged in using ChatGPT" over
  175. # a refresh token that has already been spent.
  176. auth_files: tuple[str, ...] = ()
  177. # Text in the auth probe's own output that means the credential was
  178. # refused, whatever the exit code. qwen 0.4.0 prints
  179. # "[API Error: 401 Incorrect API key provided...]" and exits 0, and
  180. # its delegation envelope reports "is_error": false over the same
  181. # text, so the exit code is not a signal for this CLI and the output
  182. # is the only honest one. Matched case-insensitively.
  183. auth_failure_markers: tuple[str, ...] = ()
  184. # A check beyond "the binary exists". `ollama --version` answers
  185. # whenever ollama is installed, and says nothing about whether the
  186. # model named in `subcommand` was ever pulled, so `--verify` reported
  187. # OK for a provider that fails at spawn. The probe runs
  188. # `command + readiness_probe` and requires `readiness_expect` in its
  189. # output.
  190. readiness_probe: tuple[str, ...] = ()
  191. readiness_expect: str = ""
  192. readiness_hint: str = ""
  193. # Shown when the binary is missing, so a failure names its own remedy.
  194. install_hint: str = ""
  195. # How an operator logs this CLI in, when the CLI owns its own
  196. # credentials. Recorded only where the command was read off the
  197. # installed binary's own help output, never inferred from the
  198. # binary name: an invented login command is the same class of
  199. # error as an invented install command.
  200. login_hint: str = ""
  201. # Selection metadata. smart_delegate derives both its candidate order and
  202. # its model choice from these, so registering a provider is the only step
  203. # needed to make it selectable. The previous design kept the order and the
  204. # model ids in module-level dicts that had to be edited in step with
  205. # SERVICES, and forgetting either one failed silently or raised KeyError.
  206. priority: int = 50
  207. default_model: str | None = None
  208. large_context_model: str | None = None
  209. fast_response_model: str | None = None
  210. # Requirement keys this service is preferred for, e.g. ("code_execution",).
  211. # This is how "qwen is the one for code execution" survives the move off
  212. # the hardcoded if/elif chain without becoming a branch per provider.
  213. strengths: tuple[str, ...] = ()
  214. def __post_init__(self) -> None:
  215. """Reject a config the argv builder or the verifier cannot honor.
  216. ``_apply_overrides`` validates field names, not their values, so
  217. each of these constructed cleanly and failed later. A misspelled
  218. ``auth_method`` matched neither the ``api_key`` branch nor the
  219. ``cli`` one, and the service reported itself configured while
  220. authenticating against nothing. The pairings below fail the same
  221. way, one at argv time and the rest by checking nothing.
  222. """
  223. if self.auth_method not in AUTH_METHODS:
  224. self._refuse(
  225. f"auth_method {self.auth_method!r} is not one of {sorted(AUTH_METHODS)}"
  226. )
  227. # _prompt_argv needs the long form to attach a dash-leading prompt,
  228. # and raises at call time without it.
  229. if (
  230. self.prompt_flag is not None
  231. and not self.stdin_prompt
  232. and not self.prompt_long_flag
  233. ):
  234. self._refuse(
  235. f"prompt_long_flag is required with prompt_flag "
  236. f"{self.prompt_flag!r}, or a dash-leading prompt cannot be sent"
  237. )
  238. # build_command appends the flag alone. With no flag the request
  239. # for machine-readable output is dropped without a word.
  240. if self.output_format_is_boolean and self.output_format_flag is None:
  241. self._refuse("output_format_is_boolean needs an output_format_flag")
  242. # credential_issues and the doctor both skip an api_key provider
  243. # that names no variable, so it reads as configured.
  244. if self.auth_method == "api_key" and not self.auth_env_var:
  245. self._refuse("auth_env_var is required when auth_method is 'api_key'")
  246. # verify_service reads these only after running readiness_probe.
  247. for name in ("readiness_expect", "readiness_hint"):
  248. if getattr(self, name) and not self.readiness_probe:
  249. self._refuse(f"{name} is never checked without a readiness_probe")
  250. def _refuse(self, reason: str) -> None:
  251. raise ValueError(f"{self.name!r}: {reason}")
  252. def _apply_overrides(
  253. current: ServiceConfig, service_name: str, overrides: Any
  254. ) -> ServiceConfig:
  255. """Return ``current`` with the fields named in ``overrides`` replaced.
  256. Every field the config file does not mention keeps the value it
  257. already had, so a partial override cannot reset the CLI contract.
  258. An unrecognized field name raises rather than being ignored, matching
  259. the new-service branch (CJR-003: config load must not swallow
  260. unexpected errors).
  261. """
  262. if not isinstance(overrides, dict):
  263. msg = f"service config for {service_name!r} must be an object"
  264. raise TypeError(msg)
  265. known = {f.name for f in fields(ServiceConfig)}
  266. unknown = set(overrides) - known
  267. if unknown:
  268. msg = (
  269. f"unknown ServiceConfig field(s) for {service_name!r}: "
  270. f"{', '.join(sorted(unknown))}"
  271. )
  272. raise TypeError(msg)
  273. return replace(current, **{k: v for k, v in overrides.items() if k != "name"})
  274. def _missing_required_fields(service_config: Any) -> set[str]:
  275. """Return required ServiceConfig fields absent from a known-only config.
  276. Only returns missing names when ``service_config`` is a dict whose keys
  277. are all recognised ServiceConfig fields: such an entry is incomplete and
  278. should be skipped. A dict with unknown keys (or a non-dict) returns an
  279. empty set so the caller lets construction raise instead of silently
  280. skipping malformed config (CJR-003).
  281. """
  282. if not isinstance(service_config, dict):
  283. return set()
  284. known = {f.name for f in fields(ServiceConfig)}
  285. keys = set(service_config)
  286. if not keys <= known:
  287. return set()
  288. required = {
  289. f.name
  290. for f in fields(ServiceConfig)
  291. if f.default is MISSING and f.default_factory is MISSING
  292. }
  293. return required - keys
  294. _ENV_REFERENCE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
  295. def _env_ref(variable: str) -> str:
  296. """Name the caller variable holding a credential, for an env overlay.
  297. An overlay stores the name of the variable, never the value, so nothing
  298. secret is written into this file or into config.json. Building the
  299. reference here rather than writing the literal keeps that intent
  300. explicit, and stops a secret scanner from reading a template as a
  301. hardcoded credential.
  302. """
  303. return f"${{{variable}}}"
  304. def resolve_env_overlay(service: ServiceConfig) -> tuple[dict[str, str], list[str]]:
  305. """Expand ``${VAR}`` references in a service's environment overlay.
  306. Returns the resolved overlay and the names of any referenced variables
  307. that are unset. A credential is named in the config rather than stored
  308. there, so an unset reference is a configuration error worth reporting
  309. rather than a value to guess: substituting an empty string would send an
  310. unauthenticated request and surface as a confusing downstream 401.
  311. """
  312. resolved: dict[str, str] = {}
  313. missing: list[str] = []
  314. for key, template in service.env.items():
  315. def _substitute(match: re.Match[str]) -> str:
  316. variable = match.group(1)
  317. value = os.getenv(variable)
  318. if value is None:
  319. missing.append(variable)
  320. return ""
  321. return value
  322. resolved[key] = _ENV_REFERENCE.sub(_substitute, template)
  323. return resolved, missing
  324. SERVICES: dict[str, ServiceConfig] = {
  325. "gemini": ServiceConfig(
  326. name="gemini",
  327. command="gemini",
  328. auth_method="api_key",
  329. auth_env_var="GEMINI_API_KEY",
  330. quota_limits=DEFAULT_GEMINI_LIMITS,
  331. prompt_long_flag="--prompt",
  332. # gemini 0.26.0 documents -p, -m and -o/--output-format and no
  333. # temperature flag. Passing one exits 1 on "Unknown argument".
  334. temperature_flag=None,
  335. install_hint="npm install -g @google/gemini-cli",
  336. priority=10,
  337. # gemini-3.8-flash is the newest stable model. The only 1M Pro is a
  338. # preview; ai.google.dev/gemini-api/docs/deprecations dates its end.
  339. default_model="gemini-3.8-flash",
  340. large_context_model="gemini-3.1-pro-preview",
  341. fast_response_model="gemini-3.8-flash",
  342. strengths=("large_context", "fast_response"),
  343. ),
  344. "qwen": ServiceConfig(
  345. name="qwen",
  346. command="qwen",
  347. auth_method="cli",
  348. auth_env_var=None,
  349. quota_limits=DEFAULT_QWEN_LIMITS,
  350. prompt_long_flag="--prompt",
  351. # `qwen --help` lists no auth subcommand, so the inherited
  352. # ("auth", "status") probe was delivered to the model as the
  353. # prompt "auth status" and billed as a completion. It answered
  354. # `[API Error: 401 ...]` and exited 0, so it reported success
  355. # while paying for a rejected call, on every chain walk.
  356. # Credentials are in oauth_creds.json, which a `qwen` run
  357. # writes. settings.json exists without them and is not the
  358. # file to test.
  359. auth_probe=(),
  360. auth_files=("~/.qwen/oauth_creds.json",),
  361. # qwen 0.4.0 spells it -o/--output-format like gemini, so the
  362. # default stands. The earlier "--format" exited 1 as an unknown
  363. # argument. No temperature flag exists either.
  364. temperature_flag=None,
  365. install_hint="npm install -g @qwen-code/qwen-code",
  366. auth_failure_markers=("API Error: 401", "Incorrect API key"),
  367. priority=20,
  368. # The auth file above is Qwen OAuth, which accepts only coder-model
  369. # and silently replaces any other --model with it. One id serves
  370. # every requirement, and naming it keeps the usage log truthful.
  371. default_model="coder-model",
  372. strengths=("code_execution",),
  373. ),
  374. # The official MiniMax CLI is npm ``mmx-cli``, which installs a
  375. # binary named ``mmx``. The name ``minimax`` belongs to an unrelated
  376. # third-party npm package, so it must not be spawned here.
  377. # ``mmx auth login`` writes credentials to ~/.mmx/config.json. There
  378. # is no MINIMAX_API_KEY env var to check, and ``mmx auth status`` is
  379. # the documented way to verify them.
  380. "minimax": ServiceConfig(
  381. name="minimax",
  382. command="mmx",
  383. auth_method="cli",
  384. auth_env_var=None,
  385. quota_limits=DEFAULT_MINIMAX_LIMITS,
  386. subcommand=("text", "chat"),
  387. auth_files=("~/.mmx/config.json",),
  388. prompt_flag="--message",
  389. prompt_long_flag="--message",
  390. output_format_flag="--output",
  391. # `mmx text chat --help` documents "--temperature <n> Sampling
  392. # temperature (0.0, 1.0]". Declaring None dropped it silently.
  393. temperature_flag="--temperature",
  394. inline_files=True,
  395. install_hint="npm install -g mmx-cli",
  396. login_hint="mmx auth login",
  397. priority=30,
  398. default_model="MiniMax-M3.1-Flash",
  399. large_context_model="MiniMax-M3",
  400. fast_response_model="MiniMax-M3.1-Flash",
  401. strengths=("code_execution",),
  402. ),
  403. # GLM has no CLI of its own. Z.ai serves an Anthropic-compatible
  404. # endpoint, so the stock claude binary reaches it by environment
  405. # alone. ANTHROPIC_AUTH_TOKEN is the documented variable. Putting the
  406. # key in ANTHROPIC_API_KEY is the most common way to get a 401 here.
  407. # Model ids from https://docs.z.ai/devpack/latest-model. Z.ai's own
  408. # Claude Code mapping (docs.z.ai/devpack/tool/claude) puts the Haiku
  409. # slot on glm-5.3-flash, which is the fast-response id here.
  410. "glm": ServiceConfig(
  411. name="glm",
  412. command="claude",
  413. auth_method="api_key",
  414. auth_env_var="ZAI_API_KEY",
  415. quota_limits=DEFAULT_GLM_LIMITS,
  416. # `claude --help` documents "claude [options] [prompt]" and
  417. # "-p, --print", so -p selects non-interactive mode and the
  418. # prompt is positional. Declaring it as prompt_flag worked by
  419. # coincidence and put glm in the wrong escaping group. As a
  420. # subcommand it takes `--` like the other positional providers.
  421. subcommand=("-p",),
  422. prompt_flag=None,
  423. temperature_flag=None,
  424. env={
  425. "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
  426. "ANTHROPIC_AUTH_TOKEN": _env_ref("ZAI_API_KEY"),
  427. },
  428. auth_probe=(),
  429. install_hint="npm install -g @anthropic-ai/claude-code",
  430. priority=40,
  431. default_model="glm-5.3",
  432. large_context_model="glm-5.3[1m]",
  433. fast_response_model="glm-5.3-flash",
  434. strengths=("code_execution", "large_context"),
  435. ),
  436. # Meta's Muse Code. `muse exec <prompt>` takes the prompt positionally
  437. # and META_API_KEY is the documented CI auth path. There is no
  438. # `muse auth status`, hence the empty auth probe. Muse Code documents
  439. # `--model <id>` for exec and defaults to muse-spark-1.2
  440. # (dev.meta.ai/docs/muse-code/configuration); dev.meta.ai/docs/models
  441. # recommends 1.3 for new work, so the service passes it.
  442. "muse": ServiceConfig(
  443. name="muse",
  444. command="muse",
  445. auth_method="api_key",
  446. auth_env_var="META_API_KEY",
  447. quota_limits=DEFAULT_MUSE_LIMITS,
  448. subcommand=("exec",),
  449. auth_files=("~/.config/muse/auth.json",),
  450. prompt_flag=None,
  451. temperature_flag=None,
  452. # muse 0.2.1 offers only a boolean --json, which this contract's
  453. # flag-and-value shape cannot express; --output-format exits 2.
  454. output_format_flag="--json",
  455. output_format_is_boolean=True,
  456. inline_files=True,
  457. auth_probe=(),
  458. install_hint="curl -fsSL https://dev.meta.ai/install.sh | sh",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 496 on GitHub
  459. priority=50,
  460. default_model="muse-spark-1.3",
  461. strengths=("code_execution", "large_context"),
  462. ),
  463. # `codex exec <prompt>`. auth_method is cli rather than api_key because
  464. # `codex login status` reports the real state whether the credential
  465. # came from OPENAI_API_KEY or an interactive login, and codex supports
  466. # both. Note openai/codex#9253: `codex login` can fail outright on a
  467. # headless host unless a workspace admin enabled device-code auth.
  468. "codex": ServiceConfig(
  469. name="codex",
  470. command="codex",
  471. auth_method="cli",
  472. auth_env_var=None,
  473. quota_limits=DEFAULT_CODEX_LIMITS,
  474. subcommand=("exec",),
  475. auth_files=("~/.codex/auth.json",),
  476. prompt_flag=None,
  477. temperature_flag=None,
  478. # codex-cli 0.77.0 has boolean --json plus --output-schema and
  479. # --output-last-message, both file paths. No --output-format:
  480. # passing it exits 2 on "unexpected argument".
  481. output_format_flag="--json",
  482. output_format_is_boolean=True,
  483. inline_files=True,
  484. auth_probe=("login", "status"),
  485. install_hint="npm install -g @openai/codex",
  486. login_hint="codex login",
  487. priority=60,
  488. strengths=("code_execution",),
  489. ),
  490. # `opencode run <prompt>`. Credentials resolve per provider, so the
  491. # probe lists what is configured rather than checking one variable.
  492. "opencode": ServiceConfig(
  493. name="opencode",
  494. command="opencode",
  495. auth_method="cli",
  496. auth_env_var=None,
  497. quota_limits=DEFAULT_OPENCODE_LIMITS,
  498. subcommand=("run",),
  499. auth_files=("~/.local/share/opencode/auth.json",),
  500. prompt_flag=None,
  501. temperature_flag=None,
  502. # opencode 1.18.18: "--format format: default (formatted) or
  503. # json (raw JSON events)". --output-format exits 1.
  504. output_format_flag="--format",
  505. inline_files=True,
  506. auth_probe=("auth", "list"),
  507. install_hint="npm install -g opencode-ai@latest",
  508. login_hint="opencode auth",
  509. priority=70,
  510. strengths=("code_execution",),
  511. ),
  512. # Muse Glimmer is open weights, not a CLI, so a local server fronts it.
  513. # Ollama takes the prompt on stdin, which is what keeps a large inlined
  514. # context off argv and under the 128 KiB execve ceiling. No quota and
  515. # no auth: the model runs on this machine.
  516. "glimmer": ServiceConfig(
  517. name="glimmer",
  518. command="ollama",
  519. auth_method="none",
  520. auth_env_var=None,
  521. quota_limits=None,
  522. subcommand=("run", "muse-glimmer:30b"),
  523. prompt_flag=None,
  524. temperature_flag=None,
  525. # ollama 0.13.1 `run --help`: "ollama run MODEL [PROMPT]", and the
  526. # flag list carries --format, --think, --verbose and no --model.
  527. # The model is the positional above. Passing a flag exits 1.
  528. model_flag=None,
  529. # ollama 0.13.1: "--format string Response format (e.g. json)".
  530. # --output-format exits 1 on "unknown flag".
  531. output_format_flag="--format",
  532. inline_files=True,
  533. stdin_prompt=True,
  534. auth_probe=(),
  535. install_hint=(
  536. "curl -fsSL https://ollama.com/install.sh | sh "
  537. "&& ollama pull muse-glimmer:30b"
  538. ),
  539. readiness_probe=("list",),
  540. readiness_expect="muse-glimmer:30b",
  541. readiness_hint="Pull it with: ollama pull muse-glimmer:30b",
  542. priority=80,
  543. ),
  544. }
  545. def credential_issues(service: ServiceConfig) -> list[str]:
  546. """Report credential problems that need no subprocess to establish.
  547. A provider has as many credential routes as it declares, and it is
  548. unauthenticated only when every one of them fails. muse states both
  549. of its own in one error message: run `muse login`, or set
  550. META_API_KEY, or save credentials to auth.json. Reporting either
  551. absence alone called a working install broken, in opposite
  552. directions.
  553. Shared with ``delegation_setup`` so the doctor's table and the
  554. chain's skip decision use one answer. A table that disagreed
  555. with the thing it describes would be worse than no table.
  556. """
  557. issues = credential_file_issues(service)
  558. if (
  559. service.auth_method == "api_key"
  560. and service.auth_env_var
  561. and not _env_satisfies(service)
  562. and not _has_credential_file(service)
  563. ):
  564. issues.append(f"Environment variable {service.auth_env_var} not set")
  565. return issues
  566. def credential_file_issues(service: ServiceConfig) -> list[str]:
  567. """Report what the declared credential files say about themselves.
  568. Split from ``credential_issues`` because the doctor reports unset
  569. variables through its own path and wants only these. Selecting them
  570. by searching the combined list for a substring worked until the
  571. expiry finding was worded differently, and silently dropped it.
  572. Empty when the environment already satisfies the provider, because a
  573. file is then one route among several and its state decides nothing.
  574. """
  575. if _env_satisfies(service):
  576. return []
  577. issues = [
  578. f"Credential {path} expired {expired_on}"
  579. for path, expired_on in _expired_credentials(service)
  580. ]
  581. if _has_credential_file(service) is False:
  582. issues.append(
  583. "No credential file found; looked for " + ", ".join(service.auth_files)
  584. )
  585. return issues
  586. def _env_satisfies(service: ServiceConfig) -> bool:
  587. """Report whether the provider's own auth variable is set."""
  588. return bool(service.auth_env_var and os.getenv(service.auth_env_var))
  589. def _expired_credentials(service: ServiceConfig) -> list[tuple[str, str]]:
  590. """Name each credential file that says, in itself, that it has expired.
  591. A credential on disk is not a credential that works. qwen's
  592. oauth_creds.json on the machine this was written for expired in March
  593. and was still there in August, so a presence check cleared it, the
  594. chain spent a call on it, and it answered an empty string at exit 0.
  595. Only a stated expiry counts. A file with no expiry field, an
  596. unparseable one, or a non-numeric value produces no finding, because
  597. ruling out a working provider costs more than the round trip this
  598. saves. codex writes `last_refresh`, which records a renewal rather
  599. than a deadline, and is deliberately not read as one.
  600. """
  601. now = time.time()
  602. expired: list[tuple[str, str]] = []
  603. for raw in service.auth_files:
  604. path = Path(raw).expanduser()
  605. try:
  606. payload = json.loads(path.read_text())
  607. except (OSError, ValueError):
  608. continue
  609. if not isinstance(payload, dict):
  610. continue
  611. for key in ("expiry_date", "expires_at", "expiry"):
  612. value = payload.get(key)
  613. if not isinstance(value, (int, float)) or isinstance(value, bool):
  614. continue
  615. # Epoch milliseconds where the value is too large to be seconds.
  616. seconds = value / 1000 if value > _EPOCH_MILLISECOND_FLOOR else value
  617. if seconds < now:
  618. expired.append(
  619. (raw, datetime.fromtimestamp(seconds).date().isoformat())
  620. )
  621. break
  622. return expired
  623. def _has_credential_file(service: ServiceConfig) -> bool | None:
  624. """Report whether any declared credential file is present.
  625. Returns None when the service declares none, so a caller can tell
  626. "not applicable" from "checked and absent". Only False rules a
  627. provider out; True means the question is still open, because a file
  628. on disk says nothing about whether the token inside it still works.
  629. """
  630. if not service.auth_files:
  631. return None
  632. return any(Path(path).expanduser().is_file() for path in service.auth_files)
  633. def _smart_delegate_model(service: ServiceConfig, requirement: str) -> str | None:
  634. """Resolve the model id ``smart_delegate`` selects for a service.
  635. The ids are fields of the service config, so registering a provider carries its
  636. own model choices with it. A service that declares none returns None and
  637. the CLI's own default applies. That is deliberate: the previous
  638. module-level table raised KeyError for any service registered without a
  639. matching edit here, which made a data addition fail at runtime rather
  640. than degrade.
  641. """
  642. preferred = {
  643. "large_context": service.large_context_model,
  644. "fast_response": service.fast_response_model,
  645. }.get(requirement)
  646. return preferred or service.default_model

Ratings and comments

Sign in to rate this skill.

Sign in

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