@jaxonshaw/multi-model-kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.agents/plugins/marketplace.json +11 -0
  2. package/.claude-plugin/marketplace.json +8 -0
  3. package/.claude-plugin/plugin.json +5 -0
  4. package/.codex-plugin/plugin.json +6 -0
  5. package/INSTALL-AGENT.md +95 -0
  6. package/LICENSE +21 -0
  7. package/README.md +152 -2
  8. package/bin/byok-review +258 -0
  9. package/bin/claude-org +415 -0
  10. package/bin/model-route +303 -0
  11. package/bin/multi-model-kit +22 -0
  12. package/bin/quota-status +259 -0
  13. package/config/defaults.json +45 -0
  14. package/hooks/hooks.json +14 -0
  15. package/hooks/session-start.sh +77 -0
  16. package/install.sh +1606 -0
  17. package/mods/org-switch/.claude-plugin/plugin.json +5 -0
  18. package/mods/org-switch/hooks/hooks.json +1 -0
  19. package/mods/org-switch/hooks/register.ts +571 -0
  20. package/mods/org-switch/tsconfig.json +3 -0
  21. package/orgs.example.json +18 -0
  22. package/package.json +40 -4
  23. package/plugins/paseo-usage/bridge/capture-quota.cjs +59 -0
  24. package/plugins/paseo-usage/index.server.ts +47 -0
  25. package/plugins/paseo-usage/paseo-plugin.json +8 -0
  26. package/plugins/paseo-usage/server/usage.mjs +140 -0
  27. package/rules/multi-model.md +15 -0
  28. package/skills/dispatch/SKILL.md +148 -0
  29. package/skills/dispatch/references/brief-template.md +52 -0
  30. package/skills/dispatch/references/ce-config.example.yaml +19 -0
  31. package/skills/dispatch/references/paseo.md +87 -0
  32. package/skills/dispatch/references/roundtable.md +32 -0
  33. package/skills/dispatch/references/routing.md +83 -0
  34. package/skills/dispatch/references/watch-paseo.md +217 -0
  35. package/skills/dispatch/references/watch.md +42 -0
  36. package/skills/prompt-library/SKILL.md +60 -0
  37. package/skills/prompt-library/prompts/c01-first-principles.md +1 -0
  38. package/skills/prompt-library/prompts/c02-clarify-then-options.md +1 -0
  39. package/skills/prompt-library/prompts/c03-reframe-problem.md +1 -0
  40. package/skills/prompt-library/prompts/c04-second-order-effects.md +1 -0
  41. package/skills/prompt-library/prompts/c05-cross-domain.md +1 -0
  42. package/skills/prompt-library/prompts/c06-argue-against.md +1 -0
  43. package/skills/prompt-library/prompts/c07-git-history-legacy.md +1 -0
  44. package/skills/prompt-library/prompts/c08-onboarding-cost.md +1 -0
  45. package/skills/prompt-library/prompts/c09-slow-prs.md +1 -0
  46. package/skills/prompt-library/prompts/c10-rework-retro.md +1 -0
  47. package/skills/prompt-library/prompts/d01-complexity-to-system.md +11 -0
  48. package/skills/prompt-library/prompts/d02-motion.md +11 -0
  49. package/skills/task-handoff/SKILL.md +319 -0
  50. package/skills/task-handoff/references/handoff-template.md +134 -0
  51. package/skills/task-handoff/references/takeover-prompt.md +81 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "multi-model-kit",
3
+ "plugins": [
4
+ {
5
+ "name": "multi-model-kit",
6
+ "source": { "source": "local", "path": "./" },
7
+ "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" },
8
+ "category": "Productivity"
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "multi-model-kit",
3
+ "owner": { "name": "TheJason1997" },
4
+ "plugins": [
5
+ { "name": "multi-model-kit", "source": "./" },
6
+ { "name": "org-switch", "source": "./mods/org-switch" }
7
+ ]
8
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "multi-model-kit",
3
+ "version": "0.1.1",
4
+ "description": "Route work across coding models and keep task handoffs recoverable."
5
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "multi-model-kit",
3
+ "version": "0.1.1",
4
+ "description": "Route work across coding models and keep task handoffs recoverable.",
5
+ "skills": "./skills/"
6
+ }
@@ -0,0 +1,95 @@
1
+ # Install multi-model-kit for the current agent host
2
+
3
+ Run `npx @jaxonshaw/multi-model-kit`, or `sh install.sh` from a checkout. The
4
+ same arguments work with `multi-model-kit` after a global npm install. Python 3.8 or newer is required.
5
+
6
+ ## Get a plan and approval
7
+
8
+ 1. Run the installer with `--plan --json`. The plan reads local files and CLI
9
+ availability, then prints the selected host, actions, conflicts, routing and
10
+ fallback suggestions, takeover setting, and digest. It writes no files and
11
+ contacts no provider or daemon. npm itself may have to fetch the package
12
+ before it can run the installer.
13
+ 2. Show the user the plan. Resolve host choices and conflicts, then rerun the
14
+ plan. If `needsDecision` asks about legacy migration, ask the user to approve
15
+ removing the owned links and marker blocks shown in `migrateFromGlobal`.
16
+ The approved digest covers that migration. Use `--host claude`,
17
+ `--host codex`, `--host gemini`, or `--host antigravity` to select a host
18
+ explicitly. A Paseo or T3 session uses
19
+ the detected provider. Supply `--host paseo --provider codex`, for example,
20
+ if it cannot be detected. `--host all` explicitly targets all detected hosts.
21
+ 3. After the user approves that plan, use `--apply --digest DIGEST --yes` with
22
+ the same host and options. A changed plan requires fresh approval.
23
+ 4. Run `--check --json` with the same host options. It reports the three skills,
24
+ shared commands and Paseo daemon reachability. Confirm the plugin is loaded
25
+ in a new session. Codex may require trusting its `SessionStart` hook in
26
+ `/hooks`.
27
+
28
+ Use these commands from a checkout.
29
+
30
+ ```sh
31
+ sh install.sh --host codex --plan --json
32
+ sh install.sh --host codex --apply --digest DIGEST --yes
33
+ sh install.sh --host codex --check --json
34
+ ```
35
+
36
+ Without flags, a terminal with interactive stdin opens the five-step wizard.
37
+ Agent environments and redirected stdin use the non-interactive path. The
38
+ installer prints a plan and exits for a decision.
39
+ Claude and Codex use the native plugin managers. Gemini and Antigravity use
40
+ their shared skills and instruction directory. To use direct rule and skill
41
+ links for Claude or Codex, include `--global` in both plan and apply.
42
+ A Git checkout also supports `--migrate-to-plugin claude|codex` to remove
43
+ earlier global links and rule blocks after a manual native plugin install.
44
+
45
+ ### Settings that require a choice
46
+
47
+ - `--providers claude,gemini` records the user's approved subscriptions.
48
+ CLI availability alone cannot confirm a subscription. The plan suggests
49
+ replacements only from enabled providers. To adopt the suggestions, include
50
+ `--use-fallbacks` in a new plan for approval, or select assignments with
51
+ repeated `--role ROLE=PROVIDER`.
52
+ - Use `--workflow ce`, `--workflow direct`, or `--workflow custom` with
53
+ `--workflow-skill STAGE=SKILL`. An empty skill disables that stage. The
54
+ default keeps saved settings.
55
+ - Use `--enable-takeover` only after the user explicitly agrees in their own
56
+ words to automatic cross-provider takeover. Include it separately in both
57
+ plan and apply. General install approval is insufficient. The default is
58
+ off and a repeat install keeps the existing setting. Enabling this switch
59
+ acts as standing consent in the plain terminal (`claude-org`), whereas Paseo
60
+ and T3 Code still require explicit user consent for the current unit at
61
+ runtime. When `takeover.setting` is `"on"`, the plan lists any non-target
62
+ provider host lacking all three installed skills in `takeover.missingHosts`
63
+ (`[]` when `"off"`).
64
+ - Paseo can optionally install the bundled quota plugin with `--quota-plugin`
65
+ and capture agy quota with `--agy-snapshot`. Show the settings change and
66
+ get approval before adding `--agy-snapshot` to plan and apply. ZeroSub is a
67
+ separate, optional plugin for Claude accounts and Claude↔GPT forks. See
68
+ [ZeroSub’s installation guide](https://github.com/kapybara-org/zerosub).
69
+
70
+ ## Upgrade or uninstall
71
+
72
+ Plan and apply the new package with `--upgrade` to request an upgrade. A
73
+ version change in the durable npm store is also treated as an upgrade. The
74
+ installer lists active `mmk.*` sessions before upgrade or `--uninstall`.
75
+ If unattended apply needs a session decision, it lists the session IDs on
76
+ stderr and exits with status 2. Review the list with the user. Generate a
77
+ fresh plan with `--sessions keep` or `--sessions stop`, then get approval for
78
+ that plan. The plan shows the choice in `sessions`. Pass the same option to
79
+ apply. Adding or changing the option after planning invalidates the digest
80
+ and exits with status 3.
81
+
82
+ Uninstall previews owned links, marker blocks and native registrations before
83
+ asking for confirmation. For unattended uninstall, present the output of
84
+ `--uninstall --plan --json`, then pass
85
+ `--uninstall --apply --digest DIGEST --yes` after approval. Use `--host`
86
+ to limit removal to that host. Routing config is retained. The versioned
87
+ package store remains available for other local installs that may still link
88
+ to it.
89
+
90
+ | Exit | Meaning |
91
+ | --- | --- |
92
+ | 0 | Completed. Inspect `conflicts` and `needsDecision` in a plan before applying it. |
93
+ | 1 | Invalid input or an operational error. Read stderr. |
94
+ | 2 | User decision required. No input is read from a pipe. |
95
+ | 3 | Conflicting destination or stale digest. Review a fresh plan. |
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jaxon Xiao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,153 @@
1
- # Temporary Holding Version
1
+ # multi-model-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](https://github.com/TheJason1997/multi-model-kit/blob/main/README_ZH.md)
4
+
5
+ <p align="center">
6
+ <a href="https://thejason1997.github.io/multi-model-kit/">
7
+ <picture>
8
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/TheJason1997/multi-model-kit/main/docs/architecture/story-dark.svg">
9
+ <img src="https://raw.githubusercontent.com/TheJason1997/multi-model-kit/main/docs/architecture/story-light.svg" alt="Animated walkthrough: npx install wizard and shared config, Paseo workspace-first dispatch and small-tier routing, independent review, 85%/98% rate-limit takeover chain through agy, and disk-first checkpoints" width="100%">
10
+ </picture>
11
+ </a>
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://thejason1997.github.io/multi-model-kit/"><b>Open the interactive version</b></a>
16
+ (scrub the story, click any node, search, switch theme)
17
+ </p>
18
+
19
+ `multi-model-kit` is a lightweight toolkit of rules, skills, offline CLI scripts, and plugin manifests for coordinating AI coding models across Paseo, T3 Code, [Claude Code](https://claude.com/claude-code), Codex, Gemini CLI, and Antigravity (`agy`). Whether you subscribe to one, two, or all three model providers, it routes tasks to the right model tier, isolates subtask edits in dedicated git worktrees, pairs authors with independent reviewers, and keeps work recoverable across context compaction, rate limits, and machines—with no server or database required.
20
+
21
+ ## What it does
22
+
23
+ - **Works with your actual subscriptions:** Coordinates one, two, or three providers (`claude`, `codex`, `gemini`) from a single `config.json`, adapting fallback chains automatically to the accounts you enable.
24
+ - **Plugs into your workflow:** Connects your preferred skills for brainstorming, planning, doc review, and execution—or runs directly with all workflow stages skipped.
25
+ - **Right-sizes model tiers:** Sends routine lookups, test runs, formatting, translations, and mechanical edits to fast small-tier models while keeping complex implementation, debugging, long-form docs, and architecture on medium and large tiers.
26
+ - **Isolates subtask workspaces:** Runs subtasks inside separate git worktrees so subagents never edit your main working tree directly; only the lead verifies receipts and commits integrated work.
27
+ - **Enforces independent review:** Routes code review to an uninvolved provider whenever available, or falls back to a different model tier or clean-context second read on single-provider setups.
28
+ - **Handles rate limits smoothly:** Enters quota-saving mode at 85% usage and switches accounts, re-dispatches subtasks, or hands off along a configured fallback path at 98% instead of stalling mid-task.
29
+ - **Survives compaction and handoffs:** Writes a compact task board and pre-compaction checkpoint to `.handoff.md` on disk first, keeping state intact across context compaction, session restarts, and cloud-to-local handoffs.
30
+
31
+ ## Architecture
32
+
33
+ Each diagram is interactive—click any node to trace its upstream inputs and downstream outputs:
34
+
35
+ - **[Overview](https://thejason1997.github.io/multi-model-kit/architecture/overview.html):** Shows how a single `config.json` drives `model-route` across Paseo, T3 Code, and terminal channels, letting whichever enabled provider receives your prompt act as the lead.
36
+
37
+ - **[Dispatch & review](https://thejason1997.github.io/multi-model-kit/architecture/dispatch.html):** Traces how routine lookups batch onto small-tier models with source spot-checks, while implementation units run in isolated worktrees and go through independent review before merge.
38
+
39
+ - **[Rate limits](https://thejason1997.github.io/multi-model-kit/architecture/quota.html):** Illustrates how `quota-status` unifies the 85% / 98% usage thresholds and coordinates fallback paths across Paseo, T3 Code, and terminal sessions.
40
+
41
+ - **[Handoff & recovery](https://thejason1997.github.io/multi-model-kit/architecture/handoff.html):** Covers disk-first `.handoff.md` checkpoints across context compaction, lead handoffs, isolated subtask branches, and cloud or mobile handback signals.
42
+
43
+ - **[Interactive story](https://thejason1997.github.io/multi-model-kit/architecture/story.html):** Walks end-to-end through installation, workspace-isolated dispatch, independent review, rate-limit recovery, and checkpoint restore in one step-by-step view.
44
+
45
+ At runtime, whichever enabled model receives your task acts as the **lead**, owning task breakdown, verification, and git commits. Before delegating work, the lead queries **`model-route`** offline to resolve the preferred model and ordered fallback candidates for a role, and checks `quota-status` to select a healthy quota pool. **Subtasks** run in isolated workspaces or worktrees to handle focused research, implementation, tests, or review, returning structured receipts without committing. Progress, workspace references, and pre-compaction checkpoints live on the disk-backed **board** (`.handoff.md`), while a lightweight cross-provider **watcher** in Paseo or T3 Code monitors quota and session health in the background to assist with recovery and handoffs. Detailed coordination rules, host-specific protocols, and edge cases are documented in [skills/dispatch/](https://github.com/TheJason1997/multi-model-kit/tree/main/skills/dispatch/) and [skills/task-handoff/](https://github.com/TheJason1997/multi-model-kit/tree/main/skills/task-handoff/).
46
+
47
+ ## Installation
48
+
49
+ ### Quick install
50
+
51
+ Core scripts require POSIX `sh` and `python3` (3.8+); the `npx` / `npm` installer and optional `agy` snapshot capture also require Node.js. Make sure `~/.local/bin` is on your `PATH`.
52
+
53
+ ```sh
54
+ # Run the interactive wizard directly via npx:
55
+ npx @jaxonshaw/multi-model-kit
56
+
57
+ # Or install the CLI globally:
58
+ npm i -g @jaxonshaw/multi-model-kit
59
+ multi-model-kit
60
+
61
+ # Or install from a source checkout:
62
+ git clone https://github.com/TheJason1997/multi-model-kit.git
63
+ cd multi-model-kit
64
+ sh install.sh
65
+ ```
66
+
67
+ Running without flags in an interactive terminal launches a five-step wizard to select your target host, subscribed providers, role routing, and workflow, previewing every change before staging durable command and skill links under `~/.local/share/multi-model-kit/current`.
68
+
69
+ ### Agent-assisted install & uninstall
70
+
71
+ - **Non-interactive plan and apply:** AI agents can run `--plan --json` (side-effect-free) to generate an install plan and `digest`, present it for approval, and apply it with `--apply --digest "$digest" --yes`; see [INSTALL-AGENT.md](https://github.com/TheJason1997/multi-model-kit/blob/main/INSTALL-AGENT.md) for the full contract and exit codes.
72
+
73
+ ```sh
74
+ npx @jaxonshaw/multi-model-kit --plan --json
75
+ npx @jaxonshaw/multi-model-kit --apply --digest "$digest" --yes
76
+ ```
77
+
78
+ - **Opt-in takeover (`--enable-takeover`):** Automatic cross-provider takeover is off by default and is only enabled when `--enable-takeover` is explicitly passed in both `--plan` and `--apply`.
79
+ - **Uninstall:** Run `npx @jaxonshaw/multi-model-kit --uninstall` (or `sh install.sh --uninstall`, or `--uninstall --plan --json` / `--apply` for agents) to remove installed plugins, rule blocks, and command links while keeping `~/.config/multi-model-kit/config.json`.
80
+
81
+ ### Host setup
82
+
83
+ - **Paseo (preferred channel):** Run the wizard inside Paseo or pass `--host paseo --provider <claude|codex|gemini>`. Paseo dispatches subtasks natively across isolated worktrees and provider sessions without extra dispatch plugins.
84
+ - **T3 Code:** Pass `--host t3 --provider <claude|codex|gemini>` to install rules, skills, and routing commands for your session provider. T3 Code coordinates subtasks and fallback switches through native worktree delegation and thread configuration.
85
+ - **Terminal (Claude Code / Codex / Gemini CLI):** Pass `--host claude`, `--host codex`, `--host gemini`, `--host antigravity`, or `--host terminal`. Claude Code and Codex register native plugins by default (pass `--global` for instruction-file marker blocks and skill symlinks), while Gemini CLI and Antigravity share `~/.gemini/GEMINI.md` and `~/.gemini/skills/` (you can also install only the skills via `npx skills add TheJason1997/multi-model-kit`, or pair plain-terminal cross-model dispatch with Compound Engineering).
86
+
87
+ ### Optional components
88
+
89
+ - **[ZeroSub](https://github.com/kapybara-org/zerosub):** Pairs with Paseo to manage multiple Claude organizations and automatic session forking on rate limits.
90
+ - **[Paseo usage plugin](https://github.com/TheJason1997/multi-model-kit/blob/main/plugins/paseo-usage/README.md):** Read-only daemon plugin (`--quota-plugin`, Paseo 0.18.1+) that surfaces ZeroSub orgs and optional `agy` status-line quota snapshots (`--agy-snapshot`) in `paseo usage`.
91
+ - **`claude-org`:** Terminal launcher (`bin/claude-org` with `mods/org-switch`) for two-org Claude Code setups, providing automatic org switching at 98% usage and optional foreground takeover.
92
+ - **`byok-review`:** Read-only CLI (`bin/byok-review`) that strips recognized credentials from a UTF-8 diff file before sending it to a configured BYOK HTTP endpoint for code review.
93
+
94
+ ## Configuration
95
+
96
+ User settings live at `~/.config/multi-model-kit/config.json` (or `$XDG_CONFIG_HOME/multi-model-kit/config.json`). If you subscribe to all three providers (`claude`, `codex`, `gemini`) and use the default role mappings, no config file is needed—`model-route` falls back to `config/defaults.json` automatically. Create `config.json` via the wizard or by hand to choose `enabled` providers and `fallback` order, override per-role `roles` or provider `models` (`small`, `medium`, `large`), adjust `quota` thresholds (default `85` / `98`), toggle `takeover` (`"on"` / `"off"`), customize `workflow` slots (`brainstorm`, `plan`, `doc-review`, `work`), set `terminalDispatch` (`"ce"` or `"none"`), toggle `autoload`, or configure BYOK `connections`.
97
+
98
+ `model-route` runs completely offline without network calls or file writes. After updating `config.json`, run `model-route --preview` to inspect the resolved primary model and fallback chain for every role at once, or query a single role, workflow setting, or quota snapshot directly:
99
+
100
+ ```json
101
+ {
102
+ "enabled": ["claude", "codex"],
103
+ "fallback": ["codex", "claude"],
104
+ "roles": {
105
+ "lead": { "provider": "claude", "tier": "large", "effort": "high" },
106
+ "implement": { "provider": "claude", "tier": "medium", "effort": "medium" },
107
+ "review": { "provider": "codex", "tier": "medium", "effort": "medium" }
108
+ },
109
+ "quota": { "softPct": 85, "switchPct": 98 },
110
+ "workflow": {},
111
+ "terminalDispatch": "none"
112
+ }
113
+ ```
114
+
115
+ ```sh
116
+ model-route --preview
117
+ model-route implement
118
+ model-route --settings
119
+ quota-status --json
120
+ ```
121
+
122
+ ## What's inside
123
+
124
+ | Path | Description |
125
+ |---|---|
126
+ | `package.json`, `bin/multi-model-kit`, `install.sh` | npm launcher, interactive wizard, `--plan`/`--apply` agent installer, `--check`, and `--uninstall`. |
127
+ | `INSTALL-AGENT.md` | Non-interactive agent installation, upgrade, uninstall, and exit-code contract. |
128
+ | `config/defaults.json` | Default roles, model tiers, `roleModels`, 85% / 98% quota thresholds, workflow slots, and fallback order. |
129
+ | `bin/model-route` | Offline POSIX `sh` + `python3` router (`model-route <role>`, `--preview`, `--settings`, and `review` resolution). |
130
+ | `bin/quota-status` | Quota reader aggregating `org-switch` records, `paseo usage --json`, and `agy` snapshots (`--json` and text output). |
131
+ | `bin/claude-org`, `mods/org-switch/` | Optional two-org Claude Code terminal launcher, window usage tracker, and foreground takeover helper. |
132
+ | `bin/byok-review` | Optional read-only diff review CLI with credential redaction for configured HTTP endpoints. |
133
+ | `plugins/paseo-usage/` | Optional read-only Paseo usage plugin (`multi-model-kit-usage`) for ZeroSub Claude orgs and `agy` snapshots. |
134
+ | `rules/multi-model.md` | Shared global coordination rules loaded via native plugin `SessionStart` hooks or `--global` markers. |
135
+ | `skills/dispatch/` | Routing tables, Paseo / T3 / terminal channel guides, watcher protocols, brief templates, and roundtable rules. |
136
+ | `skills/task-handoff/` | `.handoff.md` task board template, pre-compaction checkpoints, takeover prompts, and cross-machine handoff guides. |
137
+ | `skills/prompt-library/` | 12 thinking prompts and task-based selection guide. |
138
+ | `hooks/`, `.claude-plugin/`, `.codex-plugin/`, `.agents/plugins/` | Native plugin and marketplace manifests plus `SessionStart` hook for Claude Code and Codex. |
139
+ | `docs/architecture/` | Interactive HTML diagrams, light/dark animated SVGs, JSON sources, and `build.sh`. |
140
+
141
+ Rules and skills are authored in Chinese; models follow them in any conversation language.
142
+
143
+ ## Rebuild the diagrams
144
+
145
+ The diagrams are generated with [Archify](https://github.com/tt-a1i/archify) from `docs/architecture/src/*.json`:
146
+
147
+ ```sh
148
+ sh docs/architecture/build.sh /path/to/archify/bin/archify.mjs
149
+ ```
150
+
151
+ ## License
152
+
153
+ [MIT](https://github.com/TheJason1997/multi-model-kit/blob/main/LICENSE)
@@ -0,0 +1,258 @@
1
+ #!/bin/sh
2
+ # Preserve the caller's stdin for confirmation while Python reads the script.
3
+ exec python3 -I -B - "$0" "$@" 3<&0 <<'PY'
4
+ import argparse
5
+ from http.client import HTTPException
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ from urllib.error import HTTPError
13
+ from urllib.parse import quote, urlsplit
14
+ from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
15
+
16
+
17
+ EXAMPLE = """配置文件:${XDG_CONFIG_HOME:-$HOME/.config}/multi-model-kit/config.json
18
+ {
19
+ "connections": {
20
+ "review": {
21
+ "protocol": "openai-compatible",
22
+ "baseUrl": "https://api.example.test/v1",
23
+ "model": "example-review-model",
24
+ "keyEnv": "REVIEW_API_KEY"
25
+ }
26
+ }
27
+ }
28
+ protocol 支持 openai-compatible、anthropic、gemini。Key 从 keyEnv 指定的环境变量读取。
29
+ 示例:byok-review review changes.diff
30
+ """
31
+ PROMPT = "只读审查下面的 diff。只指出能说明触发条件和发生路径的严重问题。如果没有,明确说明。"
32
+ KEY_PATTERN = re.compile(
33
+ r"(?<![A-Za-z0-9])(?:sk-[A-Za-z0-9_-]{8,}|AIza[A-Za-z0-9_-]{12,}|"
34
+ r"(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{8,}|xox[bp]-[A-Za-z0-9-]{8,}|"
35
+ r"(?:AKIA|ASIA)[A-Z0-9]{12,}|(?:sk_live_|glpat-|hf_|npm_|xai-)[A-Za-z0-9_-]{8,}|"
36
+ r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|LS0tLS1CRUdJTi)"
37
+ )
38
+ ASSIGNMENT = re.compile(
39
+ r"""(?:(?P<leading>^\s*(?:export\s+)?(?:(?:const|let|var)\s+)?["']?"""
40
+ r"""(?:(?:[a-z0-9_]+_)?(?:key|token|secret|password|passwd|passphrase|credentials?)"""
41
+ r"""|api[-_]?key|x-api-key))|"""
42
+ r"""(?<![\w-])(?P<name>[\w-]{0,64}(?:key|token|secret|password|passwd|passphrase|credentials?)[\w-]{0,64}))"""
43
+ r"""["']?\s*[=:](?!=)[ \t]*"""
44
+ r"""(?P<value>"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|"""
45
+ r"""(?:\$\{[^}]*\}|[^\s"',)\]};])+)""",
46
+ re.IGNORECASE,
47
+ )
48
+ PLACEHOLDER = re.compile(r"\$\{[^}]*\}|<[^<>]*>")
49
+ AUTH = re.compile(
50
+ r"""\bauthorization["']?\s*:\s*["']?(?:bearer|basic)\s+[^\s"']{8,}""",
51
+ re.IGNORECASE,
52
+ )
53
+ URL_CREDENTIALS = re.compile(r"""[a-zA-Z0-9+.-]://[^\s:/@?#"'<>]+:[^\s/@?#"'<>]+@""")
54
+ PRIVATE_KEY = re.compile(r"-----(BEGIN|END) ([A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?)-----")
55
+ BARE_BASE64 = re.compile(r"[A-Za-z0-9+/=]{40,}")
56
+ REDACTED = "[REDACTED]"
57
+
58
+
59
+ class ReviewError(Exception):
60
+ pass
61
+
62
+
63
+ class NoRedirect(HTTPRedirectHandler):
64
+ def redirect_request(self, *_args):
65
+ return None
66
+
67
+
68
+ def load_connection(script, name):
69
+ config_home = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
70
+ config_path = config_home / "multi-model-kit" / "config.json"
71
+ try:
72
+ raw_config = config_path.read_bytes()
73
+ except FileNotFoundError:
74
+ raise ReviewError("配置文件不存在,请参阅 --help。") from None
75
+ except OSError:
76
+ raise ReviewError("无法读取配置文件。") from None
77
+ validator = Path(script).resolve().with_name("model-route")
78
+ result = subprocess.run(
79
+ [str(validator), "--settings", "--config-stdin"], input=raw_config,
80
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
81
+ env={"PATH": os.environ.get("PATH", os.defpath)},
82
+ )
83
+ if result.returncode:
84
+ raise ReviewError("配置无效,请核对 --help 中的示例。")
85
+ connection = json.loads(raw_config.decode("utf-8")).get("connections", {}).get(name)
86
+ if connection is None:
87
+ raise ReviewError("找不到指定连接,请参阅 --help。")
88
+ return connection
89
+
90
+
91
+ def has_credential_assignment(line):
92
+ for assignment in ASSIGNMENT.finditer(line):
93
+ name, value = assignment.group("name", "value")
94
+ if name and name.lower() in ("keyenv", "key_env", "key-env"):
95
+ continue
96
+ if value.startswith(("'", '"')):
97
+ value = value[1:-1]
98
+ if value and not PLACEHOLDER.fullmatch(value) and (assignment.group("leading") or len(value) >= 8):
99
+ return True
100
+ return False
101
+
102
+
103
+ def redact(diff, key):
104
+ lines = []
105
+ count = 0
106
+ private_blocks = set()
107
+ for line in diff.splitlines(keepends=True):
108
+ # Added and removed private key blocks may be interleaved in a diff.
109
+ prefix = line[:1]
110
+ sides = (prefix,) if prefix in ("+", "-") else ("+", "-")
111
+ was_private = bool(private_blocks)
112
+ for action, label in PRIVATE_KEY.findall(line):
113
+ for side in sides:
114
+ entry = (side, label)
115
+ if action == "BEGIN":
116
+ private_blocks.add(entry)
117
+ else:
118
+ private_blocks.discard(entry)
119
+ if action == "BEGIN" and not was_private:
120
+ lines.append(REDACTED + "\n")
121
+ count += 1
122
+ was_private = True
123
+ if was_private or private_blocks:
124
+ continue
125
+ content = line[1:] if prefix in ("+", "-", " ") else line
126
+ if (key in line or KEY_PATTERN.search(line) or URL_CREDENTIALS.search(line)
127
+ or AUTH.search(content) or has_credential_assignment(content)
128
+ or BARE_BASE64.fullmatch(content.strip())):
129
+ lines.append(REDACTED + "\n")
130
+ count += 1
131
+ else:
132
+ lines.append(line)
133
+ return "".join(lines), count
134
+
135
+
136
+ def request_for(connection, diff, key):
137
+ protocol = connection["protocol"]
138
+ model = connection["model"]
139
+ prompt = f"{PROMPT}\n\n{diff}"
140
+ headers = {"Content-Type": "application/json"}
141
+ if protocol == "gemini":
142
+ version = "v1beta"
143
+ path = f"models/{quote(model, safe='')}:generateContent"
144
+ body = {"contents": [{"parts": [{"text": prompt}]}]}
145
+ headers["x-goog-api-key"] = key
146
+ else:
147
+ version = "v1"
148
+ body = {"model": model, "messages": [{"role": "user", "content": prompt}]}
149
+ if protocol == "anthropic":
150
+ path = "messages"
151
+ body["max_tokens"] = 4096
152
+ headers["x-api-key"] = key
153
+ headers["anthropic-version"] = "2023-06-01"
154
+ else:
155
+ path = "chat/completions"
156
+ headers["Authorization"] = f"Bearer {key}"
157
+ base = connection["baseUrl"].rstrip("/")
158
+ if not urlsplit(base).path.endswith(f"/{version}"):
159
+ base += f"/{version}"
160
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")
161
+ return Request(f"{base}/{path}", data=data, headers=headers, method="POST")
162
+
163
+
164
+ def fetch_review(request, protocol):
165
+ try:
166
+ # Send credentials only to the configured endpoint, even on redirects.
167
+ opener = build_opener(ProxyHandler({}), NoRedirect())
168
+ with opener.open(request, timeout=300) as response:
169
+ result = json.load(response)
170
+ except HTTPError as error:
171
+ error.close()
172
+ raise ReviewError(f"审查请求失败(HTTP {error.code})。") from None
173
+ except (OSError, HTTPException, ValueError) as error:
174
+ if isinstance(error, json.JSONDecodeError):
175
+ raise ReviewError("接收方返回了无效的 JSON。") from None
176
+ raise ReviewError("无法完成审查请求。") from None
177
+
178
+ try:
179
+ if protocol == "openai-compatible":
180
+ review = result["choices"][0]["message"]["content"]
181
+ else:
182
+ if protocol == "anthropic":
183
+ blocks = result["content"]
184
+ texts = [block["text"] for block in blocks if block.get("type") == "text"]
185
+ else:
186
+ parts = result["candidates"][0]["content"]["parts"]
187
+ texts = [part["text"] for part in parts if "text" in part and not part.get("thought")]
188
+ review = "\n".join(texts)
189
+ if isinstance(review, str) and review.strip():
190
+ return review
191
+ except (AttributeError, KeyError, IndexError, TypeError):
192
+ pass
193
+ raise ReviewError("接收方未返回审查文本。")
194
+
195
+
196
+ def visible(text, key):
197
+ text = text.replace(key, REDACTED)
198
+ return "".join(char if char.isprintable() or char in "\n\t" else ascii(char)[1:-1] for char in text)
199
+
200
+
201
+ def main():
202
+ parser = argparse.ArgumentParser(
203
+ prog="byok-review", usage="%(prog)s <连接名> <diff 文件> [--yes]",
204
+ description="扫描并剔除识别到的密钥,再把选定 diff 发送给配置的模型做只读审查。",
205
+ epilog=EXAMPLE, formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False,
206
+ )
207
+ parser.add_argument("connection", metavar="连接名")
208
+ parser.add_argument("diff", metavar="diff 文件", type=Path)
209
+ parser.add_argument("--yes", action="store_true", help="跳过交互确认")
210
+ args = parser.parse_args(sys.argv[2:])
211
+
212
+ connection = load_connection(sys.argv[1], args.connection)
213
+ key_env = connection["keyEnv"]
214
+ key = os.environ.get(key_env)
215
+ if not key:
216
+ raise ReviewError(f"请设置环境变量 {key_env}。")
217
+ if not re.fullmatch(r"[!-~]+", key):
218
+ raise ReviewError("环境变量中的 Key 格式无效。")
219
+ if any(key in connection[field] for field in ("baseUrl", "model")):
220
+ raise ReviewError("接收方配置含有 Key,请检查 baseUrl 和 model。")
221
+
222
+ try:
223
+ diff, count = redact(args.diff.read_text(encoding="utf-8"), key)
224
+ except (OSError, UnicodeError):
225
+ raise ReviewError("无法读取 UTF-8 diff 文件。") from None
226
+ request = request_for(connection, diff, key)
227
+ protocol = connection["protocol"]
228
+ # netloc includes a custom port, which is part of the destination.
229
+ host = urlsplit(connection["baseUrl"]).netloc
230
+ print(visible(f"接收方 {args.connection}({protocol},{host},{connection['model']})", key), file=sys.stderr)
231
+ print(visible(f"计费方:环境变量 {key_env} 对应的账户", key), file=sys.stderr)
232
+ print(f"剔除 {count} 处,最终发送 {len(request.data)} 字节(JSON 请求体)。", file=sys.stderr)
233
+ if not args.yes:
234
+ with os.fdopen(3, encoding="utf-8", errors="replace") as terminal:
235
+ if not terminal.isatty():
236
+ print("需要用户确认。请在终端运行或使用 --yes。", file=sys.stderr)
237
+ return 2
238
+ print("即将发送的 diff", file=sys.stderr)
239
+ print(visible(diff, key), file=sys.stderr)
240
+ print("确认发送? [y/N] ", end="", flush=True, file=sys.stderr)
241
+ if terminal.readline().strip().lower() not in ("y", "yes"):
242
+ return 2
243
+
244
+ print(visible(fetch_review(request, protocol), key))
245
+ return 0
246
+
247
+
248
+ try:
249
+ sys.exit(main())
250
+ except ReviewError as error:
251
+ print(f"byok-review: {error}", file=sys.stderr)
252
+ sys.exit(1)
253
+ except KeyboardInterrupt:
254
+ sys.exit(130)
255
+ except OSError:
256
+ print("byok-review: 本地操作失败。", file=sys.stderr)
257
+ sys.exit(1)
258
+ PY