@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,303 @@
1
+ #!/bin/sh
2
+ # Resolve a role or read effective settings without contacting any provider.
3
+ exec python3 -I -B - "$0" "$@" 3<&0 <<'PY'
4
+ import argparse
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import sys
10
+ from urllib.parse import urlsplit
11
+
12
+
13
+ TIERS = ("small", "medium", "large")
14
+ EFFORTS = ("low", "medium", "high")
15
+ SETTINGS = ("autoload", "workflow", "terminalDispatch")
16
+ PASEO_MODES = {"claude": "auto", "codex": "auto-review", "gemini": None}
17
+
18
+
19
+ def read_json(path, missing_ok=False):
20
+ try:
21
+ with path.open(encoding="utf-8") as stream:
22
+ return json.load(stream)
23
+ except FileNotFoundError as error:
24
+ if missing_ok:
25
+ return {}
26
+ raise ValueError(f"{path}: {error.strerror}") from error
27
+ except (OSError, ValueError) as error:
28
+ raise ValueError(f"{path}: {error}") from error
29
+
30
+
31
+ def fields(value, allowed, path=""):
32
+ if not isinstance(value, dict):
33
+ raise ValueError(f"{path or 'config.json'}: expected an object")
34
+ for key, item in value.items():
35
+ field = f"{path}.{key}" if path else key
36
+ if key not in allowed:
37
+ raise ValueError(f"{field}: unknown field")
38
+ yield key, item, field
39
+
40
+
41
+ def require(condition, path, message):
42
+ if not condition:
43
+ raise ValueError(f"{path}: {message}")
44
+
45
+
46
+ def choice(value, allowed, path):
47
+ require(isinstance(value, str) and value in allowed, path,
48
+ f"expected one of {', '.join(allowed)}")
49
+
50
+
51
+ def choices(value, allowed, path):
52
+ require(isinstance(value, list), path, "expected an array")
53
+ for index, item in enumerate(value):
54
+ choice(item, allowed, f"{path}[{index}]")
55
+
56
+
57
+ def model_name(value, path):
58
+ require(isinstance(value, str) and bool(value.strip()), path, "expected a non-empty model name")
59
+
60
+
61
+ def valid_base_url(value):
62
+ if not isinstance(value, str) or any(char.isspace() or not char.isprintable() for char in value):
63
+ return False
64
+ if any(char in value for char in "\\?#"):
65
+ return False
66
+ try:
67
+ url = urlsplit(value)
68
+ port = url.port
69
+ except ValueError:
70
+ return False
71
+ return (bool(url.hostname) and url.username is None
72
+ and (port is None or port > 0)
73
+ and (url.scheme == "https"
74
+ or (url.scheme == "http" and url.hostname in ("127.0.0.1", "localhost"))))
75
+
76
+
77
+ def validate_connections(value, path):
78
+ allowed = ("protocol", "baseUrl", "model", "keyEnv")
79
+ require(isinstance(value, dict), path, "expected an object")
80
+ for name, connection in value.items():
81
+ connection_path = f"{path}.{name}"
82
+ require(bool(name.strip()) and all(char.isprintable() for char in name), path,
83
+ "expected a non-empty printable connection name")
84
+ for prop, setting, field in fields(connection, allowed, connection_path):
85
+ if prop == "protocol":
86
+ choice(setting, ("openai-compatible", "anthropic", "gemini"), field)
87
+ elif prop == "baseUrl":
88
+ require(valid_base_url(setting), field, "expected an HTTPS base URL or loopback HTTP URL")
89
+ elif prop == "model":
90
+ model_name(setting, field)
91
+ require(setting.isprintable(), field, "expected a printable model name")
92
+ else:
93
+ require(isinstance(setting, str) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", setting),
94
+ field, "expected an environment variable name")
95
+ for prop in allowed:
96
+ require(prop in connection, f"{connection_path}.{prop}", "required")
97
+
98
+
99
+ def validate(config, defaults):
100
+ providers = defaults["models"]
101
+ roles = defaults["roles"]
102
+ allowed_fields = ("enabled", "fallback", "roles", "models", "roleModels", "smallModels",
103
+ "quota", "takeover", "connections", *SETTINGS)
104
+ for key, value, path in fields(config, allowed_fields):
105
+ if key in ("enabled", "fallback"):
106
+ choices(value, providers, path)
107
+ require(key != "enabled" or value, path, "must enable at least one provider")
108
+ elif key == "roles":
109
+ allowed = {"provider": providers, "tier": TIERS, "effort": EFFORTS}
110
+ for _, role, role_path in fields(value, roles, path):
111
+ for prop, setting, field in fields(role, (*allowed, "fallback"), role_path):
112
+ if prop == "fallback":
113
+ choices(setting, providers, field)
114
+ else:
115
+ choice(setting, allowed[prop], field)
116
+ elif key == "models":
117
+ for _, models, provider_path in fields(value, providers, path):
118
+ for _, model, field in fields(models, TIERS, provider_path):
119
+ model_name(model, field)
120
+ elif key == "roleModels":
121
+ for _, models, role_path in fields(value, roles, path):
122
+ for _, model, field in fields(models, providers, role_path):
123
+ model_name(model, field)
124
+ elif key == "smallModels":
125
+ for _, small, provider_path in fields(value, providers, path):
126
+ for prop, setting, field in fields(small, ("model", "roles"), provider_path):
127
+ if prop == "model":
128
+ model_name(setting, field)
129
+ else:
130
+ choices(setting, roles, field)
131
+ for prop in ("model", "roles"):
132
+ require(prop in small, f"{provider_path}.{prop}", "required")
133
+ elif key == "quota":
134
+ quota = defaults["quota"].copy()
135
+ for name, pct, field in fields(value, quota, path):
136
+ require(type(pct) is int and 0 < pct <= 100, field, "expected an integer from 1 to 100")
137
+ quota[name] = pct
138
+ require(quota["softPct"] < quota["switchPct"], path, "softPct must be less than switchPct")
139
+ elif key == "takeover":
140
+ choice(value, ("on", "off"), path)
141
+ elif key == "connections":
142
+ validate_connections(value, path)
143
+ elif key == "workflow":
144
+ for _, skill, field in fields(value, defaults["workflow"], path):
145
+ require(isinstance(skill, str) and (skill == "" or bool(skill.strip())), field,
146
+ "expected a skill name or an empty string")
147
+ elif key == "autoload":
148
+ require(isinstance(value, bool), path, "expected a boolean")
149
+ else:
150
+ choice(value, ("ce", "none"), path)
151
+
152
+
153
+ def resolve_model(defaults, config, provider, role, tier, effort, role_model=None):
154
+ overrides = config.get("models", {}).get(provider, {})
155
+ models = defaults["models"][provider]
156
+ small = config.get("smallModels", {}).get(provider)
157
+ model = overrides.get(tier, models.get(tier))
158
+ if tier != "small" and role_model is not None:
159
+ model = role_model
160
+ elif model is None:
161
+ tier, effort = "medium", "high"
162
+ model = overrides.get(tier, models[tier])
163
+ elif tier == "small" and tier not in overrides and small and role in small["roles"]:
164
+ model = small["model"]
165
+ return {"provider": provider, "model": model, "tier": tier, "effort": effort,
166
+ "paseoMode": PASEO_MODES[provider]}
167
+
168
+
169
+ def route(args, config, defaults, preview=False):
170
+ role = args.role
171
+ default_role = defaults["roles"][role]
172
+ user_role = config.get("roles", {}).get(role, {})
173
+ preference = {**default_role, **user_role}
174
+ preferred, tier, effort = (preference[key] for key in ("provider", "tier", "effort"))
175
+ tier = args.tier or tier
176
+ enabled = dict.fromkeys(config.get("enabled", defaults["enabled"]))
177
+ fallback = user_role.get("fallback", config.get("fallback", default_role.get("fallback", defaults["fallback"])))
178
+ providers = [provider for provider in dict.fromkeys([preferred, *fallback]) if provider in enabled]
179
+ notes = []
180
+ review_mode = None
181
+ authors = args.authors
182
+ if not preview and role == "review" and len(enabled) == 1 and len(authors) <= 1:
183
+ require(args.author_models, "--author-model", "required when only one provider is enabled")
184
+ authors = authors or [next(iter(enabled))]
185
+ if role == "watcher":
186
+ providers = [provider for provider in providers if PASEO_MODES[provider] is not None]
187
+ independent = [provider for provider in providers if provider not in authors]
188
+ if providers and not independent:
189
+ notes.append("All enabled watcher candidates were excluded by --author.")
190
+ providers = independent
191
+ elif authors:
192
+ independent = [provider for provider in providers if provider not in authors]
193
+ if independent:
194
+ providers = independent
195
+ review_mode = "cross-provider"
196
+
197
+ role_models = {**defaults["roleModels"].get(role, {}), **config.get("roleModels", {}).get(role, {})}
198
+ if tier != "small":
199
+ for provider, model in role_models.items():
200
+ if not providers or provider != preferred or providers[0] != preferred:
201
+ notes.append(f"Skipping role model {model} for {provider}; role models do not apply to fallback providers.")
202
+
203
+ def resolve(provider, model_tier):
204
+ role_model = role_models.get(provider) if provider == preferred else None
205
+ return resolve_model(defaults, config, provider, role, model_tier, effort, role_model)
206
+
207
+ if providers and providers[0] in authors:
208
+ reviewer = providers[0]
209
+ author_models = {model for author, model in zip(authors, args.author_models) if author == reviewer}
210
+ require(author_models, "--author-model", "required for same-provider review")
211
+ if tier == "small":
212
+ tier = "medium"
213
+ notes.append("Same-provider review uses medium or large models.")
214
+ other_tier = "large" if tier == "medium" else "medium"
215
+ primary = resolve(reviewer, tier)
216
+ if primary["model"] in author_models:
217
+ alternative = resolve(reviewer, other_tier)
218
+ if alternative["model"] not in author_models:
219
+ primary, tier = alternative, other_tier
220
+ if primary["model"] in author_models:
221
+ review_mode = "same-model"
222
+ notes.append("Every eligible second-read model was used by an author.")
223
+ else:
224
+ review_mode = "same-provider"
225
+ notes.append("Using a different model from the author's provider.")
226
+ choices = [primary]
227
+ else:
228
+ choices = [resolve(provider, tier) for provider in providers]
229
+
230
+ for candidate in choices:
231
+ if candidate["tier"] != tier:
232
+ notes.append(f"{candidate['provider']} has no {tier} model. "
233
+ f"Using {candidate['model']} at {candidate['tier']} tier with high effort.")
234
+ if any(candidate["paseoMode"] is None for candidate in choices):
235
+ notes.append("agy sessions cannot call Paseo tools.")
236
+ if preferred not in enabled:
237
+ notes.append(f"Preferred provider {preferred} is disabled.")
238
+ if not choices:
239
+ notes.append("No enabled provider is available in the configured route.")
240
+ return {"primary": choices[0] if choices else None, "alternatives": choices[1:],
241
+ "reviewMode": review_mode, "notes": notes, "effortCap": EFFORTS[-1]}
242
+
243
+
244
+ def main():
245
+ parser = argparse.ArgumentParser(prog="model-route", allow_abbrev=False)
246
+ parser.add_argument("role", nargs="?")
247
+ parser.add_argument("--author", dest="authors", action="append", default=[], help="Author provider (repeatable)")
248
+ parser.add_argument("--author-model", dest="author_models", action="append", default=[],
249
+ help="Author model (one per --author in the same order, when supplied)")
250
+ parser.add_argument("--tier", choices=TIERS)
251
+ parser.add_argument("--settings", action="store_true")
252
+ parser.add_argument("--preview", action="store_true", help="Preview all roles offline")
253
+ parser.add_argument("--config-stdin", action="store_true", help=argparse.SUPPRESS)
254
+ args = parser.parse_args(sys.argv[2:])
255
+
256
+ defaults_path = Path(sys.argv[1]).resolve().parent.parent / "config" / "defaults.json"
257
+ defaults = read_json(defaults_path)
258
+ config_home = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
259
+ if args.config_stdin:
260
+ with os.fdopen(3, encoding="utf-8") as stream:
261
+ config = json.load(stream)
262
+ else:
263
+ config = read_json(config_home / "multi-model-kit" / "config.json", missing_ok=True)
264
+ validate(config, defaults)
265
+
266
+ if args.preview:
267
+ require(not (args.settings or args.role or args.authors or args.author_models or args.tier),
268
+ "--preview", "cannot be combined with role, author, or settings options")
269
+ result = {}
270
+ for role in defaults["roles"]:
271
+ args.role = role
272
+ # The first-dispatch preview resolves the reviewer using the actual
273
+ # author's identity. Here we only preview the configured route.
274
+ result[role] = route(args, config, defaults, preview=True)
275
+ elif args.settings:
276
+ require(args.role is None and not args.authors and not args.author_models
277
+ and args.tier is None,
278
+ "--settings", "cannot be combined with a role or author options")
279
+ result = {key: config.get(key, defaults[key]) for key in SETTINGS}
280
+ if result["workflow"]:
281
+ result["workflow"] = {**defaults["workflow"], **result["workflow"]}
282
+ else:
283
+ choice(args.role, defaults["roles"], "role")
284
+ if args.authors:
285
+ require(args.role in ("review", "watcher"), "--author", "only valid for review and watcher")
286
+ for author in args.authors:
287
+ choice(author, defaults["models"], "--author")
288
+ if args.author_models:
289
+ require(args.role == "review", "--author-model", "only valid for review")
290
+ require(len(args.author_models) == (len(args.authors) or 1), "--author-model",
291
+ "supply one model per --author in the same order")
292
+ for model in args.author_models:
293
+ model_name(model, "--author-model")
294
+ result = route(args, config, defaults)
295
+ print(json.dumps(result))
296
+
297
+
298
+ try:
299
+ main()
300
+ except ValueError as error:
301
+ print(f"model-route: {error}", file=sys.stderr)
302
+ sys.exit(2)
303
+ PY
@@ -0,0 +1,22 @@
1
+ #!/bin/sh
2
+ set -eu
3
+
4
+ # npm places a symlink in .bin (or in the global bin directory).
5
+ script=$0
6
+ while [ -L "$script" ]; do
7
+ directory=$(CDPATH= cd -P "$(dirname "$script")" && pwd)
8
+ script=$(readlink "$script")
9
+ case $script in
10
+ /*) ;;
11
+ *) script=$directory/$script ;;
12
+ esac
13
+ done
14
+ root=$(CDPATH= cd -P "$(dirname "$script")/.." && pwd)
15
+
16
+ if [ ! -e "$root/.git" ]; then
17
+ # The installer stages this payload only after approval, so plan and check
18
+ # work directly from the npm cache without creating persistent files.
19
+ MMK_PACKAGED=1
20
+ export MMK_PACKAGED
21
+ fi
22
+ exec sh "$root/install.sh" "$@"
@@ -0,0 +1,259 @@
1
+ #!/bin/sh
2
+ # quota-status — print the org-switch mod's last rate-limit readings: the
3
+ # current org, its windows, whether it is saving quota, and the other orgs'
4
+ # last readings. Run it before each unit; while it says "省额度模式: 开", the
5
+ # main session only dispatches and reviews.
6
+ #
7
+ # When the current org has a window at the hard threshold, a last line names
8
+ # the org to move to (and its T3 Code instance, `t3Instance` in orgs.json).
9
+ #
10
+ # --json includes Paseo usage and the agy status-bar snapshot. Both modes
11
+ # report Paseo query failures. The current org is $CLAUDE_ORG, else the org read most recently.
12
+ set -u
13
+
14
+ store=$HOME/.claude/plugins/store
15
+ exec python3 -I - "$store" "${CLAUDE_ORG-}" "$0" "$@" <<'PY'
16
+ import argparse, glob, json, os, re, shutil, subprocess, sys, time
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ store, org, me = sys.argv[1:4]
21
+ parser = argparse.ArgumentParser(prog='quota-status')
22
+ parser.add_argument('--json', action='store_true')
23
+ args = parser.parse_args(sys.argv[4:])
24
+ root = Path(me).resolve().parent.parent
25
+ now = time.time() * 1000
26
+ max_age = 30 * 60_000
27
+
28
+ def read_json(path):
29
+ with open(path, encoding='utf-8') as stream:
30
+ return json.load(stream)
31
+
32
+ def thresholds():
33
+ defaults = read_json(root / 'config/defaults.json')['quota']
34
+ soft, switch = defaults['softPct'], defaults['switchPct']
35
+ home = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
36
+ try:
37
+ overrides = read_json(home / 'multi-model-kit/config.json').get('quota', {})
38
+ if isinstance(overrides, dict):
39
+ s, h = overrides.get('softPct', soft), overrides.get('switchPct', switch)
40
+ if type(s) is int and type(h) is int and 0 < s < h <= 100:
41
+ soft, switch = s, h
42
+ except (OSError, ValueError, AttributeError):
43
+ pass
44
+ value = os.environ.get('CLAUDE_ORG_SOFT_PCT', '').strip()
45
+ if re.fullmatch(r'[+]?[0-9]{1,3}', value) and 0 < int(value) < switch:
46
+ soft = int(value)
47
+ return soft, switch
48
+
49
+ soft_pct, switch_pct = thresholds()
50
+
51
+ # Every store file that parses (the mod's file name depends on how it was loaded). Readings are
52
+ # checked one by one, so a bad entry never hides a good one beside it. The newest reading and
53
+ # latest "every model held off" record win per org.
54
+ def number(x):
55
+ return type(x) in (int, float) and float('-inf') < x < float('inf')
56
+
57
+ def good(l):
58
+ w = l.get('windows')
59
+ return isinstance(w, dict) and number(l.get('seenAt', 0)) and all(isinstance(x, dict) and number(x.get('percentUsed', 0)) for x in w.values())
60
+ ledgers, blocks, broken = {}, {}, False
61
+ for p in glob.glob(os.path.join(store, 'org-switch_*.json')):
62
+ try:
63
+ d = read_json(p)
64
+ except (OSError, ValueError):
65
+ broken = True
66
+ continue
67
+ ls = {k[7:]: v for k, v in d.items() if k.startswith('ledger:')} if isinstance(d, dict) else {}
68
+ for o, l in ls.items():
69
+ if not (isinstance(l, dict) and good(l)):
70
+ broken = True
71
+ continue
72
+ if o not in ledgers or l.get('seenAt', 0) > ledgers[o].get('seenAt', 0):
73
+ ledgers[o] = l
74
+ for k, b in (d.items() if isinstance(d, dict) else ()):
75
+ if k.startswith('block:') and isinstance(b, dict) and b.get('kind') == 'all' and number(b.get('until')):
76
+ blocks[k[6:]] = max(blocks.get(k[6:], 0), b['until'])
77
+
78
+ def ts(value):
79
+ if not isinstance(value, str):
80
+ return None
81
+ try:
82
+ return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000
83
+ except (ValueError, OverflowError, OSError):
84
+ return None
85
+
86
+ def iso(ms):
87
+ if ms is None:
88
+ return None
89
+ try:
90
+ return datetime.fromtimestamp(ms / 1000, timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
91
+ except (ValueError, OverflowError, OSError):
92
+ return None
93
+
94
+ def fresh(observed):
95
+ return observed is not None and now - observed <= max_age
96
+
97
+ def reading_state(observed, reset, used):
98
+ # Use only grows until its window resets, so a stale reading with a future reset is still a
99
+ # lower bound: at the switch line it stays limited, at the soft line it stays saving.
100
+ passed = reset is not None and reset <= now
101
+ if used is None or not fresh(observed) and (reset is None or passed or used < soft_pct):
102
+ return 'unknown'
103
+ if passed:
104
+ return 'ok'
105
+ if used >= switch_pct:
106
+ return 'limited'
107
+ return 'saving' if used >= soft_pct else 'ok'
108
+
109
+ def quota_row(source, source_id, pool, window, observed, reset, used, usable=True, blocked=False):
110
+ state = reading_state(observed, reset, used) if usable else 'unknown'
111
+ if blocked:
112
+ state = 'limited'
113
+ return {
114
+ 'source': source, 'sourceId': source_id, 'pool': pool, 'window': window,
115
+ 'seenAt': iso(observed), 'resetsAt': iso(reset), 'usedPct': used,
116
+ 'state': state, 'availableForReturn': state in ('ok', 'saving') or (reset is not None and reset <= now),
117
+ }
118
+
119
+ def external_rows(source, source_id, pool, data, observed, usable=True):
120
+ for window in data if isinstance(data, list) else []:
121
+ if not isinstance(window, dict) or not isinstance(window.get('id'), str):
122
+ continue
123
+ used = window.get('usedPct')
124
+ yield quota_row(source, source_id, pool, window['id'], observed, ts(window.get('resetsAt')),
125
+ used if number(used) and 0 <= used <= 100 else None, usable)
126
+
127
+ def paseo_reports():
128
+ paseo = shutil.which('paseo')
129
+ if not paseo:
130
+ return []
131
+ try:
132
+ result = subprocess.run([paseo, 'usage', '--json'], capture_output=True, check=True, timeout=3)
133
+ reports = json.loads(result.stdout)
134
+ except (OSError, ValueError, subprocess.SubprocessError):
135
+ return None
136
+ return reports if isinstance(reports, list) else None
137
+
138
+ def paseo_rows(reports):
139
+ if reports is None:
140
+ yield quota_row('paseo', None, None, None, None, None, None)
141
+ return
142
+ for entry in reports:
143
+ if not isinstance(entry, dict):
144
+ continue
145
+ source_id, pool, report = entry.get('sourceId'), entry.get('id'), entry.get('report')
146
+ if not isinstance(source_id, str) or not isinstance(pool, str) or not isinstance(report, dict):
147
+ continue
148
+ # Paseo's ZeroSub IDs are hashed; org-switch stores independent org aliases.
149
+ usable = report.get('status') == 'available'
150
+ observed = ts(report.get('observedAt'))
151
+ if observed is None:
152
+ observed = ts(entry.get('successfulAt'))
153
+ if usable and observed is None:
154
+ observed = ts(entry.get('fetchedAt'))
155
+ rows = list(external_rows('paseo', source_id, pool, report.get('windows'), observed, usable))
156
+ yield from rows or [quota_row('paseo', source_id, pool, None, observed, None, None)]
157
+
158
+ def agy_rows():
159
+ try:
160
+ snapshot = read_json(Path.home() / '.gemini/antigravity-cli/paseo-quota.json')
161
+ except (OSError, ValueError):
162
+ return
163
+ if not isinstance(snapshot, dict):
164
+ return
165
+ windows = snapshot.get('windows')
166
+ if not isinstance(windows, list):
167
+ return
168
+ observed = ts(snapshot.get('observedAt'))
169
+ for pool in ('gemini', '3p'):
170
+ matching = [w for w in windows if isinstance(w, dict) and w.get('id') in (pool + '-5h', pool + '-weekly')]
171
+ yield from external_rows('agy', 'antigravity', pool, matching, observed)
172
+
173
+ reports = paseo_reports()
174
+ if args.json:
175
+ rows = []
176
+ for name in sorted(ledgers.keys() | blocks.keys()):
177
+ ledger = ledgers.get(name, {})
178
+ observed = ledger.get('seenAt') or None
179
+ for window, reading in ledger.get('windows', {}).items():
180
+ rows.append(quota_row('org-switch', 'claude-orgs', name, window, observed,
181
+ ts(reading.get('resetsAt')), reading.get('percentUsed')))
182
+ if name in blocks:
183
+ rows.append(quota_row('org-switch', 'claude-orgs', name, 'block', None,
184
+ blocks[name], None, blocked=blocks[name] > now))
185
+ rows.extend(paseo_rows(reports))
186
+ rows.extend(agy_rows())
187
+ print(json.dumps(rows))
188
+ sys.exit(0)
189
+
190
+ if reports is None:
191
+ print('Paseo 额度: 未知(查询失败)')
192
+ if not ledgers:
193
+ print('读数文件读不出来(空文件或不是 JSON)' if broken else '还没有读数')
194
+ sys.exit(0)
195
+ if not re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', org):
196
+ org = max(ledgers, key=lambda o: ledgers[o].get('seenAt', 0))
197
+
198
+ def short(k):
199
+ return {'five_hour': '5h', 'seven_day': '7d'}.get(k, k)
200
+
201
+ def span(ms):
202
+ m = round(ms / 60000)
203
+ return '%d min' % m if m < 60 else '%.1f h' % (m / 60) if m < 2880 else '%d d' % round(m / 1440)
204
+
205
+ def windows(l):
206
+ out = []
207
+ for k, w in (l.get('windows') or {}).items():
208
+ s = '%s %s%%' % (short(k), round(w.get('percentUsed', 0)))
209
+ t = ts(w.get('resetsAt'))
210
+ if t is not None:
211
+ s += ' (resets in %s)' % span(t - now) if t > now else ' (reset since)'
212
+ out.append(s)
213
+ return ', '.join(out) or 'no reading'
214
+
215
+ def seen(l):
216
+ return 'seen %s ago' % span(max(0, now - l.get('seenAt', now)))
217
+
218
+ print('org: %s' % org)
219
+ l = ledgers.get(org)
220
+ print('%s: %s' % (org, windows(l) + '; ' + seen(l) if l else 'no reading'))
221
+ states = {reading_state(l.get('seenAt'), ts(w.get('resetsAt')), w.get('percentUsed'))
222
+ for w in l['windows'].values()} if l else set()
223
+ print('省额度模式: %s' % ('开' if states & {'saving', 'limited'} else '未知(读数已过期)' if 'unknown' in states else '关'))
224
+ for o in sorted(ledgers):
225
+ if o != org:
226
+ print('%s: %s; %s' % (o, windows(ledgers[o]), seen(ledgers[o])))
227
+
228
+ def free_at(o):
229
+ # Now, unless a window at the threshold has not reset yet (then its latest reset), or the org is
230
+ # held off. A full window that does not say when it resets is unknown: never free.
231
+ at = max(now, blocks.get(o, 0))
232
+ for w in ledgers[o]['windows'].values():
233
+ if w.get('percentUsed', 0) < switch_pct:
234
+ continue
235
+ t = ts(w.get('resetsAt'))
236
+ if t is None:
237
+ return float('inf')
238
+ at = max(at, t)
239
+ return at
240
+
241
+ def instance(o):
242
+ # orgs.json sits one level above the real bin/ (the script may be called through a link).
243
+ try:
244
+ cfg = read_json(root / 'orgs.json')
245
+ i = next(x for x in cfg['orgs'] if isinstance(x, dict) and x.get('key') == o).get('t3Instance')
246
+ except Exception:
247
+ return None
248
+ return i if isinstance(i, str) and re.fullmatch(r'[A-Za-z0-9._-]{1,64}', i) else None
249
+
250
+ if l and free_at(org) > now:
251
+ others = sorted((free_at(o), -ledgers[o].get('seenAt', 0), o) for o in ledgers if o != org)
252
+ if others and others[0][0] <= now:
253
+ o = others[0][2]
254
+ i = instance(o)
255
+ print('建议换到: %s%s' % (o, '(T3 实例 %s)' % i if i else ''))
256
+ else:
257
+ first = min([free_at(org)] + [x[0] for x in others])
258
+ print('建议换到: 无(都受限,%s)' % ('恢复时间未知' if first == float('inf') else '最早 %s 后恢复' % span(first - now)))
259
+ PY
@@ -0,0 +1,45 @@
1
+ {
2
+ "enabled": ["claude", "codex", "gemini"],
3
+ "roles": {
4
+ "fetch": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["gemini", "claude"]},
5
+ "search": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["gemini", "claude"]},
6
+ "locate": {"provider": "claude", "tier": "small", "effort": "low", "fallback": ["codex"]},
7
+ "triage": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["claude", "gemini"]},
8
+ "format": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["claude", "gemini"]},
9
+ "receipt": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["claude", "gemini"]},
10
+ "test": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["claude", "gemini"]},
11
+ "translate": {"provider": "gemini", "tier": "small", "effort": "low", "fallback": ["claude"]},
12
+ "mechanical": {"provider": "claude", "tier": "small", "effort": "medium", "fallback": ["codex"]},
13
+ "visual": {"provider": "codex", "tier": "small", "effort": "low", "fallback": ["claude"]},
14
+ "watcher": {"provider": "claude", "tier": "small", "effort": "low", "fallback": ["codex"]},
15
+ "research": {"provider": "codex", "tier": "medium", "effort": "medium"},
16
+ "write": {"provider": "gemini", "tier": "medium", "effort": "medium"},
17
+ "write-long": {"provider": "gemini", "tier": "medium", "effort": "medium"},
18
+ "implement": {"provider": "claude", "tier": "medium", "effort": "medium"},
19
+ "backend": {"provider": "codex", "tier": "medium", "effort": "medium"},
20
+ "design": {"provider": "claude", "tier": "medium", "effort": "medium"},
21
+ "debug": {"provider": "codex", "tier": "medium", "effort": "medium"},
22
+ "review": {"provider": "codex", "tier": "medium", "effort": "medium"},
23
+ "lead": {"provider": "claude", "tier": "large", "effort": "high"}
24
+ },
25
+ "models": {
26
+ "claude": {"small": "claude-sonnet-5-5", "medium": "claude-opus-5-5", "large": "claude-fable-5-2"},
27
+ "codex": {"small": "gpt-6.1-terra", "medium": "gpt-6.2-sol", "large": "gpt-6.2-astra"},
28
+ "gemini": {"small": "gemini-4-hydrogen", "medium": "gemini-4-neon"}
29
+ },
30
+ "roleModels": {
31
+ "write-long": {"gemini": "gemini-4-carbon"}
32
+ },
33
+ "fallback": ["claude", "codex", "gemini"],
34
+ "quota": {"softPct": 85, "switchPct": 98},
35
+ "takeover": "off",
36
+ "connections": {},
37
+ "autoload": true,
38
+ "workflow": {
39
+ "brainstorm": "ce-brainstorm",
40
+ "plan": "ce-plan",
41
+ "doc-review": "ce-doc-review",
42
+ "work": "ce-work"
43
+ },
44
+ "terminalDispatch": "ce"
45
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh\""
9
+ }
10
+ ]
11
+ }
12
+ ]
13
+ }
14
+ }