claude-night-market
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.
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
Markdown
[](/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
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "claude-night-market",
- "version": "1.10.3",
- "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",
- "owner": {
- "name": "athola",
- "email": "athola@users.noreply.github.com"
- },
- "renames": {
- "conservation": "conserve",
- "pensieve": "pensive"
- },
- "plugins": [
- {
- "name": "abstract",
- "source": "./plugins/abstract",
- "description": "Skill authoring, hook development, evaluation frameworks, and escalation governance for the Claude Code plugin ecosystem",
- "version": "1.10.3",
- "keywords": ["meta", "skill-authoring", "hooks", "evaluation"]
- },
- {
- "name": "attune",
- "source": "./plugins/attune",
- "description": "Full-cycle project development: brainstorm, specify, plan, initialize, execute, and polish with war-room deliberation for strategic decisions",
- "version": "1.10.3",
- "keywords": ["project-lifecycle", "brainstorming", "planning", "scaffolding"]
- },
- {
- "name": "archetypes",
- "source": "./plugins/archetypes",
- "description": "Architecture paradigm selection and implementation planning: 14 paradigms from functional-core to hexagonal to microservices",
- "version": "1.10.3",
- "keywords": ["architecture", "design-patterns", "hexagonal", "cqrs", "microservices"]
- },
- {
- "name": "cartograph",
- "source": "./plugins/cartograph",
- "description": "Codebase visualization: architecture, data flow, dependency, call chains, community detection, and class diagrams via Mermaid Chart MCP",
- "version": "1.10.3",
- "keywords": ["visualization", "diagram", "mermaid", "architecture", "data-flow", "call-chain", "community-detection"]
- },
- {
- "name": "conjure",
- "source": "./plugins/conjure",
- "description": "Delegate tasks to external LLMs (Gemini, Qwen) with cheapest-capable model selection while retaining strategic oversight",
- "version": "1.10.3",
- "keywords": ["llm-delegation", "multi-model", "gemini", "qwen"]
- },
- {
- "name": "conserve",
- "source": "./plugins/conserve",
- "description": "Context optimization, bloat detection, CPU/GPU monitoring, and token conservation for efficient Claude Code sessions",
- "version": "1.10.3",
- "keywords": ["optimization", "performance", "bloat-detection", "token-conservation"]
- },
- {
- "name": "hookify",
- "source": "./plugins/hookify",
- "description": "Behavioral rules engine: create safety hooks through markdown configuration with pattern matching and zero-code rule authoring",
- "version": "1.10.3",
- "keywords": ["hooks", "safety", "behavioral-rules", "configuration"]
- },
- {
- "name": "imbue",
- "source": "./plugins/imbue",
- "description": "TDD enforcement, proof-of-work validation, scope guarding, rigorous reasoning, and research-enriched feature review with RICE/WSJF/Kano scoring",
- "version": "1.10.3",
- "keywords": ["tdd", "quality-gates", "proof-of-work", "scope-guard"]
- },
- {
- "name": "leyline",
- "source": "./plugins/leyline",
- "description": "Foundation infrastructure: auth flows, quota management, error patterns, markdown formatting, trust verification, and injection detection",
- "version": "1.10.3",
- "keywords": ["infrastructure", "auth", "security", "injection-detection", "quota"]
- },
- {
- "name": "memory-palace",
- "source": "./plugins/memory-palace",
- "description": "Spatial knowledge organization with memory palace techniques: build, navigate, and maintain virtual memory structures with PR review capture",
- "version": "1.10.3",
- "keywords": ["memory", "knowledge-management", "spatial-organization", "recall"]
- },
- {
- "name": "minister",
- "source": "./plugins/minister",
- "description": "GitHub issue management, label taxonomy, and initiative tracking: turns repositories, issues, and projects into status dashboards",
- "version": "1.10.3",
- "keywords": ["project-management", "github-issues", "tracking", "dashboards"]
- },
- {
- "name": "parseltongue",
- "source": "./plugins/parseltongue",
- "description": "Python development suite: testing, performance optimization, async patterns, and packaging guidance",
- "version": "1.10.3",
- "keywords": ["python", "testing", "async", "packaging", "performance"]
- },
- {
- "name": "pensive",
- "source": "./plugins/pensive",
- "description": "Multi-discipline code review: architecture, bugs, APIs, blast radius analysis, security, tests, Makefiles, and NASA Power of 10 analysis",
- "version": "1.10.3",
- "keywords": ["code-review", "architecture-review", "bug-hunting", "blast-radius", "security-review"]
- },
- {
- "name": "phantom",
- "source": "./plugins/phantom",
- "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",
- "version": "1.10.3",
- "keywords": ["computer-use", "desktop", "automation", "screenshot", "mouse", "keyboard", "gui"]
- },
- {
- "name": "sanctum",
- "source": "./plugins/sanctum",
- "description": "Git workflows: commit messages, PR preparation, documentation updates, version management, sessions, and deferred-item capture",
- "version": "1.10.3",
- "keywords": ["git", "commits", "pull-requests", "version-management"]
- },
- {
- "name": "scribe",
- "source": "./plugins/scribe",
- "description": "Documentation review, cleanup, and generation with AI slop detection, style learning, and human-quality writing enforcement",
- "version": "1.10.3",
- "keywords": ["documentation", "slop-detection", "writing", "style"]
- },
- {
- "name": "scry",
- "source": "./plugins/scry",
- "description": "Media generation: terminal recordings (VHS), browser recordings (Playwright), GIF processing, and media composition",
- "version": "1.10.3",
- "keywords": ["media", "recordings", "vhs", "playwright", "gif"]
- },
- {
- "name": "spec-kit",
- "source": "./plugins/spec-kit",
- "description": "Specification-driven development: structured specs, implementation planning, and task orchestration for systematic feature delivery",
- "version": "1.10.3",
- "keywords": ["specifications", "planning", "task-orchestration", "feature-delivery"]
- },
- {
- "name": "egregore",
- "source": "./plugins/egregore",
- "description": "Autonomous agent orchestrator: parallel worktree execution, agent specialization, cross-item learning, and crash recovery",
- "version": "1.10.3",
- "keywords": ["autonomous-agents", "orchestration", "parallel-execution", "worktrees"]
- },
- {
- "name": "gauntlet",
- "source": "./plugins/gauntlet",
- "description": "Codebase learning through knowledge extraction, code knowledge graph, adaptive challenges, and spaced repetition for developer onboarding and fluency",
- "version": "1.10.3",
- "keywords": ["learning", "onboarding", "knowledge", "challenges", "spaced-repetition", "code-graph"]
- },
- {
- "name": "herald",
- "source": "./plugins/herald",
- "description": "Standalone notification system: GitHub issue alerts and webhook support for Slack, Discord, and generic endpoints.",
- "version": "1.10.3",
- "keywords": ["notifications", "alerts", "webhooks", "github-issues", "slack", "discord"]
- },
- {
- "name": "oracle",
- "source": "./plugins/oracle",
- "description": "ONNX Runtime inference daemon for ML-enhanced plugin capabilities with local model inference over HTTP and opt-in activation",
- "version": "1.10.3",
- "keywords": ["ml", "inference", "onnx", "scoring", "daemon"]
- },
- {
- "name": "tome",
- "source": "./plugins/tome",
- "description": "Multi-source research: code archaeology, community discourse (HN, Reddit), academic literature (arXiv, Semantic Scholar), and TRIZ cross-domain analysis",
- "version": "1.10.3",
- "keywords": ["research", "code-archaeology", "academic", "triz", "literature-review"]
- }
- ]
- }
README.md · README · 239 lines
- # Claude Night Market
- [](CHANGELOG.md)
- [](LICENSE)
- [](book/src/plugins/)
- [](book/src/reference/capabilities-reference.md)
- [](https://code.claude.com/docs/en/overview)
- **A plugin marketplace for Claude Code.** Install only the
- plugins you need to run git workflows, code review,
- spec-driven development, and autonomous agents from inside
- your Claude Code session.
- *Written for a practitioner: someone who already uses Claude Code and
- wants to know what these plugins do and whether to install them. If you
- are new to Claude Code, start with the
- [official docs](https://code.claude.com/docs/en/overview). For the
- design rationale behind a plugin, see
- [the book](book/src/plugins/).*
- <p align="center">
- <img src="assets/gifs/skills-showcase.gif" alt="Night Market skills in action" width="720">
- </p>
- ## Install
- 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.
- ```bash
- # 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`.
- ## Everyday Use
- Night Market is built around the loop you already work in.
- A typical feature runs end to end on a handful of commands:
- 1. **Start a feature.** `/attune:mission` routes you through
- brainstorm, specify, plan, and execute phases.
- 2. **Write the code.** `imbue` enforces a failing test before
- the implementation is written.
- 3. **Review before you push.** `/full-review` runs a
- multi-discipline pass; `/refine-code` cleans up duplication
- and dead code.
- 4. **Ship it.** `/prepare-pr` runs quality gates and drafts a
- description that says who the change is for, where it lands
- inside and outside the codebase, and when it is fully
- integrated.
- 5. **Pick up where you left off.** `/catchup` rebuilds context
- from recent git history after a break.
- The commands you reach for most:
- | Task | Command |
- |------|---------|
- | Run the project lifecycle | `/attune:mission` |
- | Initialize a new project | `/attune:arch-init` |
- | Review a PR | `/full-review` |
- | Address review feedback | `/fix-pr` |
- | Implement an issue | `/do-issue` |
- | Prepare a pull request | `/prepare-pr` |
- | Write a spec | `/speckit-specify` |
- | Catch up on changes | `/catchup` |
- | Package project knowledge as skills | `/attune:skill-library` |
- | Clean up the codebase | `/unbloat` |
- | Pressure-test a decision | `/attune:war-room` |
- Full task-by-task walkthroughs are in the
- [Common Workflows Guide][workflows].
- ## What's Inside
- 23 plugins in four layers. Each installs independently, and
- dependencies pull their shared runtime automatically.
- **Foundation** is the base every other layer builds on:
- `leyline` (auth, quotas, error patterns, trust verification),
- `sanctum` (git, commits, PR prep, sessions), and `imbue`
- (TDD enforcement, proof-of-work, scope guarding).
- **Utility** handles cross-cutting concerns: `conserve` (context
- and token optimization), `conjure` (delegation to seven external
- model CLIs plus a local runner), `hookify` (a behavioral rules
- engine with a security catalog), `egregore` (autonomous agent
- orchestration), `herald` (notifications), and `oracle` (local ML
- inference).
- **Domain** is where the day-to-day work happens: `pensive` (code
- and architecture review), `attune` (project lifecycle), `spec-kit`
- (spec-driven development), `parseltongue` (Python), `minister`
- (GitHub issues and DORA metrics), `memory-palace` (knowledge
- organization), `archetypes` (architecture paradigms), `gauntlet`
- (codebase learning), `phantom` (computer use), `scribe`
- (documentation and slop detection), `scry` (recordings), `tome`
- (research), and `cartograph` (codebase visualization).
- **Meta** improves the system itself: `abstract` (skill authoring,
- hook development, evaluation, and skill-stability tracking).
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/architecture-dark.svg">
- <img alt="Plugin architecture across Foundation, Utility, Domain, and Meta layers" src="assets/architecture-light.svg">
- </picture>
- The full skill, command, and agent inventory is in the
- [Capabilities Reference](book/src/reference/capabilities-reference.md).
- ## Safety
- > ⚠️ Plugins run inside your Claude Code session and can read or
- > edit your repo, run shell commands, and call external services.
- > **Review any plugin before installing it.**
- Five guards reduce the blast radius, but none replace your own
- review:
- - **TDD gates** (`imbue`) block implementation writes that lack a
- failing test.
- - **Destructive-command blockers** (`conserve`, `hookify`)
- auto-approve safe commands and halt or warn on `rm -rf`,
- `git push --force`, and production-shaped targets.
- - **Credential-read denial** (`conserve`) refuses `cat`, `head`,
- `grep`, `rg` and `git show` on `.env`, `.netrc`, credential files
- and SSH keys.
- - **External-content sanitizing** (`leyline`) strips invisible
- characters from web fetches and other external-tool output, and
- blocks prompt-injection phrases before the model reads them.
- - **Additive-bias audits** (`leyline`) flag unjustified additions
- before commit.
- [CONSTITUTION.md](CONSTITUTION.md) holds the rules that override any
- conflicting skill or hook, each paired with what checks it.
- [STEWARDSHIP.md](STEWARDSHIP.md) is the maintenance contract.
- ## Network and data
- Three parts of the marketplace reach off your machine, and each can be
- turned off. Two hooks use your existing GitHub credentials, and both do
- nothing when `gh` is unauthenticated or the network is unavailable.
- - **Star prompt** (`leyline`, `hooks/auto-star-repo.sh`). On session
- start it checks whether you have starred this repository, through
- `gh` or a `GITHUB_TOKEN` / `GH_TOKEN` variable. It reads star status,
- asks once per session, and never stars without your consent.
- `CLAUDE_NIGHT_MARKET_NO_STAR_PROMPT=1` disables it.
- - **Learnings posting** (`abstract`, `hooks/post_learnings_stop.py`).
- On session stop, when `~/.claude/skills/LEARNINGS.md` has content, it
- posts a skill-usage discussion through `gh` and may promote
- high-severity items to issues. The target is `target_repo` in
- `~/.claude/skills/discussions/config.json`, else the current repo.
- It is on by default. `auto_post_learnings: false` in that file
- disables it.
- - **Delegation** (`conjure`, also reached by `attune` missions and
- `egregore` steps) sends the prompt and the file contents it carries to
- the first external model CLI that answers, in the order Gemini, Qwen,
- MiniMax, GLM, Muse, Codex, OpenCode, under the credentials you
- configured for it. It runs by default. `CONJURE_DELEGATION=off`
- declines it for one run, and `"enabled": false` in
- `~/.claude/hooks/delegation/config.json` declines it on one machine.
- When no provider answers, the work stays on your machine.
- ## Plugin Development
- ```bash
- make validate-all
- make lint && make test # checks only; rewrites nothing
- make fix # ruff format + ruff check --fix
- ```
- A plugin directory holds `.claude-plugin/plugin.json` (metadata)
- plus any of `commands/`, `skills/`, `hooks/`, `agents/`,
- `workflows/`, and `tests/`, with a `Makefile` and
- `pyproject.toml`. A `workflows/` script orchestrates several
- subagents at once and runs only when you ask for one. Copy the
- layout from an existing plugin such as `plugins/abstract`, then
- see the [Plugin Development Guide][dev-guide] for structure and
- naming conventions. Working on this repo needs **Python 3.12+**
- and **GNU make 3.82+**. The guide covers both, including why
- Xcode's make 3.81 reports a green build it did not run.
- ## Documentation
- - [Installation Guide](book/src/getting-started/installation.md)
- - [Quick Start](book/src/getting-started/quick-start.md)
- - [Common Workflows][workflows]
- - [Plugin Development Guide][dev-guide]
- - [Capabilities Reference](book/src/reference/capabilities-reference.md)
- - [Tutorials](book/src/tutorials/README.md)
- - [Architecture Decision Records](docs/adr/)
- - [CHANGELOG](CHANGELOG.md)
- Per-plugin pages are in `book/src/plugins/`.
- ## Stewardship and Contributing
- Every plugin is entrusted to the community: steward rather than
- own, and think several iterations ahead. Each plugin maintains
- its own tests and docs; run `make test` at the repo root to
- execute every suite, and `/stewardship-health` to view per-plugin
- health. Contribution guidelines are in the
- [Plugin Development Guide][dev-guide].
- ## Acknowledgements
- Night Market builds on [Anthropic Claude Code][claude-code] and
- integrates with [github/spec-kit][spec-kit-upstream] (v1.4.0) and
- [obra/superpowers][superpowers-upstream] (v7.0.2, see the
- [integration guide][superpowers-doc]). Its AI involvement is declared
- under the [Quillx][quillx] disclosure standard as 3/5 (Adapted):
- human-directed, AI-generated, and meaningfully edited.
- ## License
- [MIT](LICENSE)
- [claude-code]: https://docs.anthropic.com/en/docs/build-with-claude/claude-code
- [dev-guide]: docs/plugin-development-guide.md
- [workflows]: book/src/getting-started/common-workflows.md
- [spec-kit-upstream]: https://github.com/github/spec-kit
- [superpowers-upstream]: https://github.com/obra/superpowers
- [superpowers-doc]: book/src/reference/superpowers-integration.md
- [quillx]: https://github.com/QAInsights/Quillx
- [install]: book/src/getting-started/installation.md
plugins/conjure/scripts/delegation_services.py · Bundled script · 709 lines · 2 findings marked
- """Service registry, config contract and credential checks for delegation.
- Split out of ``delegation_executor`` so the data a provider is described
- by, and the checks that read that data without spawning anything, can be
- changed without touching the process that spawns. Imports flow one way:
- this module never imports ``Delegator``.
- """
- from __future__ import annotations
- import json
- import os
- import re
- import time
- from dataclasses import MISSING, dataclass, field, fields, replace
- from datetime import datetime
- from pathlib import Path
- from typing import Any
- from scripts.quota_tracker import (
- DEFAULT_CODEX_LIMITS,
- DEFAULT_GEMINI_LIMITS,
- DEFAULT_GLM_LIMITS,
- DEFAULT_MINIMAX_LIMITS,
- DEFAULT_MUSE_LIMITS,
- DEFAULT_OPENCODE_LIMITS,
- DEFAULT_QWEN_LIMITS,
- )
- # Spawning a binary by name trusts whatever PATH resolves it to, so every name
- # this module spawns is recorded here with the package that publishes it and a
- # source a reviewer can check. A service whose command is absent from this map
- # fails its test rather than reaching a user's shell.
- VERIFIED_BINARIES: dict[str, dict[str, str]] = {
- "gemini": {
- "package": "@google/gemini-cli",
- "publisher": "Google",
- "install": "npm install -g @google/gemini-cli",
- "source": "https://github.com/google-gemini/gemini-cli",
- },
- "qwen": {
- "package": "@qwen-code/qwen-code",
- "publisher": "Alibaba / QwenLM",
- "install": "npm install -g @qwen-code/qwen-code",
- "source": "https://github.com/QwenLM/qwen-code",
- },
- "mmx": {
- "package": "mmx-cli",
- "publisher": "MiniMax-AI",
- "install": "npm install -g mmx-cli",
- "source": "https://github.com/MiniMax-AI/cli",
- },
- # Spawned by the endpoint-swap services, which run the stock binary
- # against a different base URL rather than shipping a CLI of their own.
- "claude": {
- "package": "@anthropic-ai/claude-code",
- "publisher": "Anthropic",
- "install": "npm install -g @anthropic-ai/claude-code",
- "source": "https://github.com/anthropics/claude-code",
- },
- # Meta publishes no npm or PyPI artifact for Muse Code: the documented
- # install is a script served from Meta's own domain.
- "muse": {
- "package": "muse-code (standalone installer)",
- "publisher": "Meta",
- "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
- "source": "https://dev.meta.ai/docs/muse-code",
- },
- "codex": {
- "package": "@openai/codex",
- "publisher": "OpenAI",
- "install": "npm install -g @openai/codex",
- "source": "https://github.com/openai/codex",
- },
- "opencode": {
- "package": "opencode-ai",
- "publisher": "SST",
- "install": "npm install -g opencode-ai@latest",
- "source": "https://github.com/sst/opencode",
- },
- "ollama": {
- "package": "ollama",
- "publisher": "Ollama",
- "install": "curl -fsSL https://ollama.com/install.sh | sh",
- "source": "https://github.com/ollama/ollama",
- },
- }
- # Above this, an epoch timestamp is milliseconds rather than seconds. The
- # boundary is in the year 5138 read as seconds, so no real deadline is
- # ambiguous.
- _EPOCH_MILLISECOND_FLOOR = 100_000_000_000
- #: The values ``delegation_executor`` and the verifier actually branch on.
- #: Kept as a frozenset beside the type rather than an Enum, because these
- #: configs are built from YAML and an Enum would push the same string
- #: validation up to every construction site.
- AUTH_METHODS = frozenset({"api_key", "cli", "none"})
- @dataclass(frozen=True)
- class ServiceConfig:
- """Configuration for a delegation service.
- Frozen because the registry is shared. ``Delegator.__init__`` copies
- the ``SERVICES`` mapping and not its values, so every Delegator in a
- process holds these same objects; while this was mutable, one field
- assignment rewrote the contract process wide. ``_apply_overrides``
- already builds a new object with ``replace``, so nothing needed to
- assign.
- The trailing fields describe the CLI contract. They exist because the
- supported CLIs genuinely diverge: ``mmx`` puts text generation behind a
- ``text chat`` subcommand, names its prompt flag ``--message``, spells
- output format ``--output``, and has no ``@path`` context syntax.
- Defaults reproduce the Gemini contract, so existing services and custom
- entries in ``config.json`` are unaffected.
- A default is a claim about a CLI, not a neutral placeholder: a provider
- that leaves ``output_format_flag`` alone is asserting that its binary
- spells the flag ``--output-format``. Four did not, and the mismatch
- only surfaced when a caller passed the matching option. Probe the
- binary before trusting a default here.
- """
- name: str
- command: str
- #: One of :data:`AUTH_METHODS`. Validated in ``__post_init__`` because
- #: ``_apply_overrides`` checks field *names* and not their values, so
- #: "apikey" constructed cleanly and then silently skipped both the auth
- #: probe and the API-key check: a service that looked configured and
- #: authenticated against nothing.
- auth_method: str
- auth_env_var: str | None = None
- quota_limits: dict[str, int] | None = None
- # Tuple rather than list: a default_factory field would read as required
- # to _missing_required_fields and silently skip valid custom configs.
- subcommand: tuple[str, ...] = ()
- # None means the prompt is positional. ``muse exec <prompt>``,
- # ``codex exec <prompt>`` and ``opencode run <prompt>`` all take it that
- # way, so a flag name is not universal enough to be mandatory.
- prompt_flag: str | None = "-p"
- # Long form of the prompt flag, used to attach a dash-leading prompt as
- # ``--prompt=-x``. A separator does not protect a flag's value: probed on
- # 2026-08-22, ``gemini -p -- --help`` still printed the help page while
- # ``gemini --prompt=--help`` reached authentication. Positional providers
- # need no entry here and take ``--`` instead. The default pairs with
- # the default ``-p``: both are the Gemini spelling.
- prompt_long_flag: str | None = "--prompt"
- # None where the CLI takes no format value. muse and codex offer only a
- # boolean ``--json``, which a flag-and-value pair cannot express.
- # How this CLI is told which model to use. `--model` was hardcoded at
- # the call site while the comment above it claimed every flag spelling
- # comes from the config, and it is not universal: `ollama run --help`
- # (0.13.1) lists no --model at all, because `ollama run MODEL [PROMPT]`
- # takes the model positionally. None means the model is not passed as a
- # flag. Recorded from each CLI's own --help: gemini 0.26.0, qwen, codex,
- # opencode and muse document `-m, --model`; `claude --model` and
- # `mmx text chat --model` likewise.
- model_flag: str | None = "--model"
- output_format_flag: str | None = "--output-format"
- # True when the flag above takes no value. `muse exec --json` and
- # `codex exec --json` are booleans: "Emit machine-readable JSONL
- # events on stdout", read off each binary's own --help. The
- # key-and-value shape cannot express that, since `--json json` lands
- # "json" as a positional and both providers take the prompt
- # positionally, so the request used to be dropped in silence.
- output_format_is_boolean: bool = False
- temperature_flag: str | None = "--temperature"
- inline_files: bool = False
- # Prompt on stdin rather than argv. execve caps a single argument at
- # 128 KiB, which a large inlined context exceeds.
- stdin_prompt: bool = False
- # Environment applied to the child only. An endpoint-swap harness runs a
- # stock binary against a different base URL, which is environment, not
- # argv. Values may reference the caller's variables as ``${VAR}`` so a
- # credential is named here rather than stored here.
- env: dict[str, str] = field(default_factory=dict)
- # Probes, because not every CLI answers --version or `auth status`.
- version_probe: tuple[str, ...] = ("--version",)
- auth_probe: tuple[str, ...] = ("auth", "status")
- # Files the CLI writes its credentials to, ``~`` accepted. The check is
- # one-directional: all of them absent means the CLI cannot be
- # authenticated, and any of them present means only that the question
- # stays open. Presence is never evidence of a working credential.
- # `opencode auth list` exits 0 naming a credentials path that does not
- # exist, and `codex login status` prints "Logged in using ChatGPT" over
- # a refresh token that has already been spent.
- auth_files: tuple[str, ...] = ()
- # Text in the auth probe's own output that means the credential was
- # refused, whatever the exit code. qwen 0.4.0 prints
- # "[API Error: 401 Incorrect API key provided...]" and exits 0, and
- # its delegation envelope reports "is_error": false over the same
- # text, so the exit code is not a signal for this CLI and the output
- # is the only honest one. Matched case-insensitively.
- auth_failure_markers: tuple[str, ...] = ()
- # A check beyond "the binary exists". `ollama --version` answers
- # whenever ollama is installed, and says nothing about whether the
- # model named in `subcommand` was ever pulled, so `--verify` reported
- # OK for a provider that fails at spawn. The probe runs
- # `command + readiness_probe` and requires `readiness_expect` in its
- # output.
- readiness_probe: tuple[str, ...] = ()
- readiness_expect: str = ""
- readiness_hint: str = ""
- # Shown when the binary is missing, so a failure names its own remedy.
- install_hint: str = ""
- # How an operator logs this CLI in, when the CLI owns its own
- # credentials. Recorded only where the command was read off the
- # installed binary's own help output, never inferred from the
- # binary name: an invented login command is the same class of
- # error as an invented install command.
- login_hint: str = ""
- # Selection metadata. smart_delegate derives both its candidate order and
- # its model choice from these, so registering a provider is the only step
- # needed to make it selectable. The previous design kept the order and the
- # model ids in module-level dicts that had to be edited in step with
- # SERVICES, and forgetting either one failed silently or raised KeyError.
- priority: int = 50
- default_model: str | None = None
- large_context_model: str | None = None
- fast_response_model: str | None = None
- # Requirement keys this service is preferred for, e.g. ("code_execution",).
- # This is how "qwen is the one for code execution" survives the move off
- # the hardcoded if/elif chain without becoming a branch per provider.
- strengths: tuple[str, ...] = ()
- def __post_init__(self) -> None:
- """Reject a config the argv builder or the verifier cannot honor.
- ``_apply_overrides`` validates field names, not their values, so
- each of these constructed cleanly and failed later. A misspelled
- ``auth_method`` matched neither the ``api_key`` branch nor the
- ``cli`` one, and the service reported itself configured while
- authenticating against nothing. The pairings below fail the same
- way, one at argv time and the rest by checking nothing.
- """
- if self.auth_method not in AUTH_METHODS:
- self._refuse(
- f"auth_method {self.auth_method!r} is not one of {sorted(AUTH_METHODS)}"
- )
- # _prompt_argv needs the long form to attach a dash-leading prompt,
- # and raises at call time without it.
- if (
- self.prompt_flag is not None
- and not self.stdin_prompt
- and not self.prompt_long_flag
- ):
- self._refuse(
- f"prompt_long_flag is required with prompt_flag "
- f"{self.prompt_flag!r}, or a dash-leading prompt cannot be sent"
- )
- # build_command appends the flag alone. With no flag the request
- # for machine-readable output is dropped without a word.
- if self.output_format_is_boolean and self.output_format_flag is None:
- self._refuse("output_format_is_boolean needs an output_format_flag")
- # credential_issues and the doctor both skip an api_key provider
- # that names no variable, so it reads as configured.
- if self.auth_method == "api_key" and not self.auth_env_var:
- self._refuse("auth_env_var is required when auth_method is 'api_key'")
- # verify_service reads these only after running readiness_probe.
- for name in ("readiness_expect", "readiness_hint"):
- if getattr(self, name) and not self.readiness_probe:
- self._refuse(f"{name} is never checked without a readiness_probe")
- def _refuse(self, reason: str) -> None:
- raise ValueError(f"{self.name!r}: {reason}")
- def _apply_overrides(
- current: ServiceConfig, service_name: str, overrides: Any
- ) -> ServiceConfig:
- """Return ``current`` with the fields named in ``overrides`` replaced.
- Every field the config file does not mention keeps the value it
- already had, so a partial override cannot reset the CLI contract.
- An unrecognized field name raises rather than being ignored, matching
- the new-service branch (CJR-003: config load must not swallow
- unexpected errors).
- """
- if not isinstance(overrides, dict):
- msg = f"service config for {service_name!r} must be an object"
- raise TypeError(msg)
- known = {f.name for f in fields(ServiceConfig)}
- unknown = set(overrides) - known
- if unknown:
- msg = (
- f"unknown ServiceConfig field(s) for {service_name!r}: "
- f"{', '.join(sorted(unknown))}"
- )
- raise TypeError(msg)
- return replace(current, **{k: v for k, v in overrides.items() if k != "name"})
- def _missing_required_fields(service_config: Any) -> set[str]:
- """Return required ServiceConfig fields absent from a known-only config.
- Only returns missing names when ``service_config`` is a dict whose keys
- are all recognised ServiceConfig fields: such an entry is incomplete and
- should be skipped. A dict with unknown keys (or a non-dict) returns an
- empty set so the caller lets construction raise instead of silently
- skipping malformed config (CJR-003).
- """
- if not isinstance(service_config, dict):
- return set()
- known = {f.name for f in fields(ServiceConfig)}
- keys = set(service_config)
- if not keys <= known:
- return set()
- required = {
- f.name
- for f in fields(ServiceConfig)
- if f.default is MISSING and f.default_factory is MISSING
- }
- return required - keys
- _ENV_REFERENCE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
- def _env_ref(variable: str) -> str:
- """Name the caller variable holding a credential, for an env overlay.
- An overlay stores the name of the variable, never the value, so nothing
- secret is written into this file or into config.json. Building the
- reference here rather than writing the literal keeps that intent
- explicit, and stops a secret scanner from reading a template as a
- hardcoded credential.
- """
- return f"${{{variable}}}"
- def resolve_env_overlay(service: ServiceConfig) -> tuple[dict[str, str], list[str]]:
- """Expand ``${VAR}`` references in a service's environment overlay.
- Returns the resolved overlay and the names of any referenced variables
- that are unset. A credential is named in the config rather than stored
- there, so an unset reference is a configuration error worth reporting
- rather than a value to guess: substituting an empty string would send an
- unauthenticated request and surface as a confusing downstream 401.
- """
- resolved: dict[str, str] = {}
- missing: list[str] = []
- for key, template in service.env.items():
- def _substitute(match: re.Match[str]) -> str:
- variable = match.group(1)
- value = os.getenv(variable)
- if value is None:
- missing.append(variable)
- return ""
- return value
- resolved[key] = _ENV_REFERENCE.sub(_substitute, template)
- return resolved, missing
- SERVICES: dict[str, ServiceConfig] = {
- "gemini": ServiceConfig(
- name="gemini",
- command="gemini",
- auth_method="api_key",
- auth_env_var="GEMINI_API_KEY",
- quota_limits=DEFAULT_GEMINI_LIMITS,
- prompt_long_flag="--prompt",
- # gemini 0.26.0 documents -p, -m and -o/--output-format and no
- # temperature flag. Passing one exits 1 on "Unknown argument".
- temperature_flag=None,
- install_hint="npm install -g @google/gemini-cli",
- priority=10,
- # gemini-3.8-flash is the newest stable model. The only 1M Pro is a
- # preview; ai.google.dev/gemini-api/docs/deprecations dates its end.
- default_model="gemini-3.8-flash",
- large_context_model="gemini-3.1-pro-preview",
- fast_response_model="gemini-3.8-flash",
- strengths=("large_context", "fast_response"),
- ),
- "qwen": ServiceConfig(
- name="qwen",
- command="qwen",
- auth_method="cli",
- auth_env_var=None,
- quota_limits=DEFAULT_QWEN_LIMITS,
- prompt_long_flag="--prompt",
- # `qwen --help` lists no auth subcommand, so the inherited
- # ("auth", "status") probe was delivered to the model as the
- # prompt "auth status" and billed as a completion. It answered
- # `[API Error: 401 ...]` and exited 0, so it reported success
- # while paying for a rejected call, on every chain walk.
- # Credentials are in oauth_creds.json, which a `qwen` run
- # writes. settings.json exists without them and is not the
- # file to test.
- auth_probe=(),
- auth_files=("~/.qwen/oauth_creds.json",),
- # qwen 0.4.0 spells it -o/--output-format like gemini, so the
- # default stands. The earlier "--format" exited 1 as an unknown
- # argument. No temperature flag exists either.
- temperature_flag=None,
- install_hint="npm install -g @qwen-code/qwen-code",
- auth_failure_markers=("API Error: 401", "Incorrect API key"),
- priority=20,
- # The auth file above is Qwen OAuth, which accepts only coder-model
- # and silently replaces any other --model with it. One id serves
- # every requirement, and naming it keeps the usage log truthful.
- default_model="coder-model",
- strengths=("code_execution",),
- ),
- # The official MiniMax CLI is npm ``mmx-cli``, which installs a
- # binary named ``mmx``. The name ``minimax`` belongs to an unrelated
- # third-party npm package, so it must not be spawned here.
- # ``mmx auth login`` writes credentials to ~/.mmx/config.json. There
- # is no MINIMAX_API_KEY env var to check, and ``mmx auth status`` is
- # the documented way to verify them.
- "minimax": ServiceConfig(
- name="minimax",
- command="mmx",
- auth_method="cli",
- auth_env_var=None,
- quota_limits=DEFAULT_MINIMAX_LIMITS,
- subcommand=("text", "chat"),
- auth_files=("~/.mmx/config.json",),
- prompt_flag="--message",
- prompt_long_flag="--message",
- output_format_flag="--output",
- # `mmx text chat --help` documents "--temperature <n> Sampling
- # temperature (0.0, 1.0]". Declaring None dropped it silently.
- temperature_flag="--temperature",
- inline_files=True,
- install_hint="npm install -g mmx-cli",
- login_hint="mmx auth login",
- priority=30,
- default_model="MiniMax-M3.1-Flash",
- large_context_model="MiniMax-M3",
- fast_response_model="MiniMax-M3.1-Flash",
- strengths=("code_execution",),
- ),
- # GLM has no CLI of its own. Z.ai serves an Anthropic-compatible
- # endpoint, so the stock claude binary reaches it by environment
- # alone. ANTHROPIC_AUTH_TOKEN is the documented variable. Putting the
- # key in ANTHROPIC_API_KEY is the most common way to get a 401 here.
- # Model ids from https://docs.z.ai/devpack/latest-model. Z.ai's own
- # Claude Code mapping (docs.z.ai/devpack/tool/claude) puts the Haiku
- # slot on glm-5.3-flash, which is the fast-response id here.
- "glm": ServiceConfig(
- name="glm",
- command="claude",
- auth_method="api_key",
- auth_env_var="ZAI_API_KEY",
- quota_limits=DEFAULT_GLM_LIMITS,
- # `claude --help` documents "claude [options] [prompt]" and
- # "-p, --print", so -p selects non-interactive mode and the
- # prompt is positional. Declaring it as prompt_flag worked by
- # coincidence and put glm in the wrong escaping group. As a
- # subcommand it takes `--` like the other positional providers.
- subcommand=("-p",),
- prompt_flag=None,
- temperature_flag=None,
- env={
- "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
- "ANTHROPIC_AUTH_TOKEN": _env_ref("ZAI_API_KEY"),
- },
- auth_probe=(),
- install_hint="npm install -g @anthropic-ai/claude-code",
- priority=40,
- default_model="glm-5.3",
- large_context_model="glm-5.3[1m]",
- fast_response_model="glm-5.3-flash",
- strengths=("code_execution", "large_context"),
- ),
- # Meta's Muse Code. `muse exec <prompt>` takes the prompt positionally
- # and META_API_KEY is the documented CI auth path. There is no
- # `muse auth status`, hence the empty auth probe. Muse Code documents
- # `--model <id>` for exec and defaults to muse-spark-1.2
- # (dev.meta.ai/docs/muse-code/configuration); dev.meta.ai/docs/models
- # recommends 1.3 for new work, so the service passes it.
- "muse": ServiceConfig(
- name="muse",
- command="muse",
- auth_method="api_key",
- auth_env_var="META_API_KEY",
- quota_limits=DEFAULT_MUSE_LIMITS,
- subcommand=("exec",),
- auth_files=("~/.config/muse/auth.json",),
- prompt_flag=None,
- temperature_flag=None,
- # muse 0.2.1 offers only a boolean --json, which this contract's
- # flag-and-value shape cannot express; --output-format exits 2.
- output_format_flag="--json",
- output_format_is_boolean=True,
- inline_files=True,
- auth_probe=(),
- 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
- priority=50,
- default_model="muse-spark-1.3",
- strengths=("code_execution", "large_context"),
- ),
- # `codex exec <prompt>`. auth_method is cli rather than api_key because
- # `codex login status` reports the real state whether the credential
- # came from OPENAI_API_KEY or an interactive login, and codex supports
- # both. Note openai/codex#9253: `codex login` can fail outright on a
- # headless host unless a workspace admin enabled device-code auth.
- "codex": ServiceConfig(
- name="codex",
- command="codex",
- auth_method="cli",
- auth_env_var=None,
- quota_limits=DEFAULT_CODEX_LIMITS,
- subcommand=("exec",),
- auth_files=("~/.codex/auth.json",),
- prompt_flag=None,
- temperature_flag=None,
- # codex-cli 0.77.0 has boolean --json plus --output-schema and
- # --output-last-message, both file paths. No --output-format:
- # passing it exits 2 on "unexpected argument".
- output_format_flag="--json",
- output_format_is_boolean=True,
- inline_files=True,
- auth_probe=("login", "status"),
- install_hint="npm install -g @openai/codex",
- login_hint="codex login",
- priority=60,
- strengths=("code_execution",),
- ),
- # `opencode run <prompt>`. Credentials resolve per provider, so the
- # probe lists what is configured rather than checking one variable.
- "opencode": ServiceConfig(
- name="opencode",
- command="opencode",
- auth_method="cli",
- auth_env_var=None,
- quota_limits=DEFAULT_OPENCODE_LIMITS,
- subcommand=("run",),
- auth_files=("~/.local/share/opencode/auth.json",),
- prompt_flag=None,
- temperature_flag=None,
- # opencode 1.18.18: "--format format: default (formatted) or
- # json (raw JSON events)". --output-format exits 1.
- output_format_flag="--format",
- inline_files=True,
- auth_probe=("auth", "list"),
- install_hint="npm install -g opencode-ai@latest",
- login_hint="opencode auth",
- priority=70,
- strengths=("code_execution",),
- ),
- # Muse Glimmer is open weights, not a CLI, so a local server fronts it.
- # Ollama takes the prompt on stdin, which is what keeps a large inlined
- # context off argv and under the 128 KiB execve ceiling. No quota and
- # no auth: the model runs on this machine.
- "glimmer": ServiceConfig(
- name="glimmer",
- command="ollama",
- auth_method="none",
- auth_env_var=None,
- quota_limits=None,
- subcommand=("run", "muse-glimmer:30b"),
- prompt_flag=None,
- temperature_flag=None,
- # ollama 0.13.1 `run --help`: "ollama run MODEL [PROMPT]", and the
- # flag list carries --format, --think, --verbose and no --model.
- # The model is the positional above. Passing a flag exits 1.
- model_flag=None,
- # ollama 0.13.1: "--format string Response format (e.g. json)".
- # --output-format exits 1 on "unknown flag".
- output_format_flag="--format",
- inline_files=True,
- stdin_prompt=True,
- auth_probe=(),
- install_hint=(
- "curl -fsSL https://ollama.com/install.sh | sh "
- "&& ollama pull muse-glimmer:30b"
- ),
- readiness_probe=("list",),
- readiness_expect="muse-glimmer:30b",
- readiness_hint="Pull it with: ollama pull muse-glimmer:30b",
- priority=80,
- ),
- }
- def credential_issues(service: ServiceConfig) -> list[str]:
- """Report credential problems that need no subprocess to establish.
- A provider has as many credential routes as it declares, and it is
- unauthenticated only when every one of them fails. muse states both
- of its own in one error message: run `muse login`, or set
- META_API_KEY, or save credentials to auth.json. Reporting either
- absence alone called a working install broken, in opposite
- directions.
- Shared with ``delegation_setup`` so the doctor's table and the
- chain's skip decision use one answer. A table that disagreed
- with the thing it describes would be worse than no table.
- """
- issues = credential_file_issues(service)
- if (
- service.auth_method == "api_key"
- and service.auth_env_var
- and not _env_satisfies(service)
- and not _has_credential_file(service)
- ):
- issues.append(f"Environment variable {service.auth_env_var} not set")
- return issues
- def credential_file_issues(service: ServiceConfig) -> list[str]:
- """Report what the declared credential files say about themselves.
- Split from ``credential_issues`` because the doctor reports unset
- variables through its own path and wants only these. Selecting them
- by searching the combined list for a substring worked until the
- expiry finding was worded differently, and silently dropped it.
- Empty when the environment already satisfies the provider, because a
- file is then one route among several and its state decides nothing.
- """
- if _env_satisfies(service):
- return []
- issues = [
- f"Credential {path} expired {expired_on}"
- for path, expired_on in _expired_credentials(service)
- ]
- if _has_credential_file(service) is False:
- issues.append(
- "No credential file found; looked for " + ", ".join(service.auth_files)
- )
- return issues
- def _env_satisfies(service: ServiceConfig) -> bool:
- """Report whether the provider's own auth variable is set."""
- return bool(service.auth_env_var and os.getenv(service.auth_env_var))
- def _expired_credentials(service: ServiceConfig) -> list[tuple[str, str]]:
- """Name each credential file that says, in itself, that it has expired.
- A credential on disk is not a credential that works. qwen's
- oauth_creds.json on the machine this was written for expired in March
- and was still there in August, so a presence check cleared it, the
- chain spent a call on it, and it answered an empty string at exit 0.
- Only a stated expiry counts. A file with no expiry field, an
- unparseable one, or a non-numeric value produces no finding, because
- ruling out a working provider costs more than the round trip this
- saves. codex writes `last_refresh`, which records a renewal rather
- than a deadline, and is deliberately not read as one.
- """
- now = time.time()
- expired: list[tuple[str, str]] = []
- for raw in service.auth_files:
- path = Path(raw).expanduser()
- try:
- payload = json.loads(path.read_text())
- except (OSError, ValueError):
- continue
- if not isinstance(payload, dict):
- continue
- for key in ("expiry_date", "expires_at", "expiry"):
- value = payload.get(key)
- if not isinstance(value, (int, float)) or isinstance(value, bool):
- continue
- # Epoch milliseconds where the value is too large to be seconds.
- seconds = value / 1000 if value > _EPOCH_MILLISECOND_FLOOR else value
- if seconds < now:
- expired.append(
- (raw, datetime.fromtimestamp(seconds).date().isoformat())
- )
- break
- return expired
- def _has_credential_file(service: ServiceConfig) -> bool | None:
- """Report whether any declared credential file is present.
- Returns None when the service declares none, so a caller can tell
- "not applicable" from "checked and absent". Only False rules a
- provider out; True means the question is still open, because a file
- on disk says nothing about whether the token inside it still works.
- """
- if not service.auth_files:
- return None
- return any(Path(path).expanduser().is_file() for path in service.auth_files)
- def _smart_delegate_model(service: ServiceConfig, requirement: str) -> str | None:
- """Resolve the model id ``smart_delegate`` selects for a service.
- The ids are fields of the service config, so registering a provider carries its
- own model choices with it. A service that declares none returns None and
- the CLI's own default applies. That is deliberate: the previous
- module-level table raised KeyError for any service registered without a
- matching edit here, which made a data addition fail at runtime rather
- than degrade.
- """
- preferred = {
- "large_context": service.large_context_model,
- "fast_response": service.fast_response_model,
- }.get(requirement)
- return preferred or service.default_model
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.