@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
package/install.sh ADDED
@@ -0,0 +1,1606 @@
1
+ #!/bin/sh
2
+ set -eu
3
+
4
+ repo=$(CDPATH= cd -P "$(dirname "$0")" && pwd)
5
+ link_root=${MMK_LINK_ROOT:-$repo}
6
+ existing_root=${MMK_EXISTING_ROOT:-}
7
+ legacy_root=${MMK_LEGACY_ROOT:-}
8
+ if [ ! -e "$repo/.git" ] && [ -f "$repo/package.json" ]; then
9
+ MMK_PACKAGED=1
10
+ export MMK_PACKAGED
11
+ fi
12
+ rule_file=$repo/rules/multi-model.md
13
+ begin='<!-- BEGIN multi-model-kit -->'
14
+ end='<!-- END multi-model-kit -->'
15
+
16
+ run_wizard() {
17
+ MMK_STDIN_TTY=0
18
+ if [ -t 0 ]; then MMK_STDIN_TTY=1; fi
19
+ export MMK_STDIN_TTY
20
+ python3 -I -B - "$repo" "$@" <<'PYTHON'
21
+ import argparse
22
+ import hashlib
23
+ import json
24
+ import os
25
+ from pathlib import Path
26
+ import re
27
+ import shlex
28
+ import shutil
29
+ import stat
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+
34
+ ERROR, DECISION, CONFLICT = 1, 2, 3
35
+ NAME = "multi-model-kit"
36
+ PLUGIN = f"{NAME}@{NAME}"
37
+ SKILLS = ("dispatch", "prompt-library", "task-handoff")
38
+ COMMANDS = ("model-route", "quota-status")
39
+ CODEX_SESSION_ENV = ("CODEX_PLUGIN_ROOT", "CODEX_THREAD_ID", "CODEX_SESSION_ID")
40
+ PROVIDERS = ("claude", "codex", "gemini")
41
+ HOSTS = (*PROVIDERS, "antigravity", "paseo", "t3", "terminal", "all")
42
+ LABELS = dict(zip(PROVIDERS, ("Claude", "Codex", "Gemini")))
43
+ ROOT = Path(sys.argv[1])
44
+ HOME = Path.home()
45
+ CLAUDE = Path(os.environ.get("CLAUDE_CONFIG_DIR") or HOME / ".claude")
46
+ CODEX = Path(os.environ.get("CODEX_HOME") or HOME / ".codex")
47
+ GEMINI = HOME / ".gemini"
48
+ CONFIG = Path(os.environ.get("XDG_CONFIG_HOME") or HOME / ".config") / NAME / "config.json"
49
+ RECEIPT = CONFIG.with_name("install-receipt.json")
50
+ STORE = HOME / ".local/share" / NAME
51
+ CURRENT = STORE / "current"
52
+ AGY = GEMINI / "antigravity-cli/settings.json"
53
+ QUOTA_ID = "multi-model-kit-usage"
54
+ ZERO_SUB_URL = "https://github.com/kapybara-org/zerosub"
55
+ PATHS = {
56
+ "claude": (CLAUDE / "CLAUDE.md", CLAUDE / "skills"),
57
+ "codex": (CODEX / "AGENTS.md", HOME / ".agents/skills"),
58
+ "gemini": (GEMINI / "GEMINI.md", GEMINI / "skills"),
59
+ }
60
+ DEFAULTS = json.loads((ROOT / "config/defaults.json").read_text())
61
+ MANIFEST = ROOT / "package.json"
62
+ PACKAGE = json.loads(MANIFEST.read_text()) if MANIFEST.is_file() else {}
63
+ VERSION = PACKAGE.get("version", "checkout")
64
+ PACKAGED = os.environ.get("MMK_PACKAGED") == "1"
65
+
66
+
67
+ class InstallError(Exception):
68
+ def __init__(self, message, code=ERROR):
69
+ super().__init__(message)
70
+ self.code = code
71
+
72
+
73
+ class ArgumentParser(argparse.ArgumentParser):
74
+ def error(self, message):
75
+ raise InstallError(message)
76
+
77
+
78
+ def read_object(path):
79
+ try:
80
+ data = json.loads(path.read_text(encoding="utf-8"))
81
+ except FileNotFoundError:
82
+ return {}
83
+ if not isinstance(data, dict):
84
+ raise InstallError(f"{path}: expected a JSON object")
85
+ return data
86
+
87
+
88
+ def dump(value):
89
+ print(json.dumps(value, ensure_ascii=False, indent=2), flush=True)
90
+
91
+
92
+ def fingerprint(path):
93
+ """Record content and link identity without exposing file contents."""
94
+ try:
95
+ info = path.lstat()
96
+ except FileNotFoundError:
97
+ return None
98
+ except OSError:
99
+ return ["inaccessible"]
100
+ kind = stat.S_IFMT(info.st_mode)
101
+ result = [kind, stat.S_IMODE(info.st_mode), info.st_dev, info.st_ino]
102
+ if stat.S_ISLNK(kind):
103
+ result.append(os.readlink(path))
104
+ try:
105
+ info = path.stat()
106
+ except OSError:
107
+ return result
108
+ result.extend((info.st_dev, info.st_ino, stat.S_IMODE(info.st_mode)))
109
+ if stat.S_ISREG(info.st_mode):
110
+ try:
111
+ result.append(hashlib.sha256(path.read_bytes()).hexdigest())
112
+ except OSError:
113
+ result.append("unreadable")
114
+ return result
115
+
116
+
117
+ def snapshot(paths):
118
+ return {str(path): fingerprint(path) for path in sorted(set(paths))}
119
+
120
+
121
+ def atomic_json(path, value):
122
+ # Write through a user-managed config symlink without replacing it.
123
+ path = path.resolve()
124
+ path.parent.mkdir(parents=True, exist_ok=True)
125
+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
126
+ try:
127
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
128
+ json.dump(value, stream, ensure_ascii=False, indent=2)
129
+ stream.write("\n")
130
+ if path.is_file():
131
+ shutil.copymode(path, temporary)
132
+ os.replace(temporary, path)
133
+ finally:
134
+ Path(temporary).unlink(missing_ok=True)
135
+
136
+
137
+ def current_host():
138
+ env = os.environ
139
+ agy_session = env.get("AGY_SESSION_ID") or env.get("ANTIGRAVITY_SESSION_ID")
140
+ provider = None
141
+ if any(env.get(key) for key in ("CLAUDE_PLUGIN_ROOT", "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")):
142
+ provider = "claude"
143
+ elif any(env.get(key) for key in CODEX_SESSION_ENV):
144
+ provider = "codex"
145
+ elif agy_session or env.get("GEMINI_CLI") or env.get("GEMINI_SESSION_ID"):
146
+ provider = "gemini"
147
+ commands = connection_info()
148
+ detected = [name for name, (rules, _) in PATHS.items()
149
+ if rules.parent.is_dir() or commands[name]]
150
+ if shutil.which("agy") or agy_session:
151
+ detected.append("antigravity")
152
+ paseo = env.get("PASEO_AGENT_ID") or env.get("PASEO_WORKSPACE_ID")
153
+ t3 = any(env.get(key) for key in ("T3CODE_THREAD_ID", "T3_THREAD_ID", "T3CODE_AGENT_ID", "T3_AGENT_ID"))
154
+ if paseo or shutil.which("paseo"):
155
+ detected.append("paseo")
156
+ if t3 or shutil.which("t3"):
157
+ detected.append("t3")
158
+ if provider and provider not in detected:
159
+ detected.append(provider)
160
+ if not provider:
161
+ candidates = [name for name, (rules, _) in PATHS.items() if rules.parent.is_dir()]
162
+ if not candidates:
163
+ candidates = [name for name in PROVIDERS if name in detected]
164
+ provider = candidates[0] if len(candidates) == 1 else None
165
+ session_host = "antigravity" if provider == "gemini" and agy_session else provider
166
+ host = "paseo" if paseo else "t3" if t3 else session_host
167
+ return host, provider, detected
168
+
169
+
170
+ def target_hosts(args):
171
+ current, provider, detected = current_host()
172
+ host = args.host or current
173
+ if host == "all":
174
+ targets = [name for name in PROVIDERS
175
+ if PATHS[name][0].parent.is_dir() or (not args.global_install and name in detected)]
176
+ elif host in ("t3", "paseo"):
177
+ targets = [args.provider or provider] if args.provider or provider else []
178
+ if not targets:
179
+ return host, [], detected, "Choose the provider running in this host with --provider."
180
+ elif host in PROVIDERS:
181
+ targets = [host]
182
+ elif host == "antigravity":
183
+ targets = ["gemini"]
184
+ elif host == "terminal":
185
+ targets = []
186
+ else:
187
+ return host, [], detected, "Choose a host with --host."
188
+ return host, targets, detected, None
189
+
190
+
191
+ def run(argv, *, capture=False, input_text=None, timeout=25):
192
+ return subprocess.run(argv, check=False, text=True, timeout=timeout,
193
+ input=input_text, stdin=subprocess.DEVNULL if input_text is None else None,
194
+ stdout=subprocess.PIPE if capture else sys.stderr,
195
+ stderr=subprocess.PIPE if capture else None)
196
+
197
+
198
+ def checked(argv, **kwargs):
199
+ proc = run(argv, **kwargs)
200
+ if proc.returncode:
201
+ raise InstallError(proc.stderr.strip() if proc.stderr else f"{argv[0]} command failed.",
202
+ CONFLICT if proc.returncode == CONFLICT else ERROR)
203
+ return proc.stdout
204
+
205
+
206
+ def global_command(root, *flags, source=None, existing=None, legacy=None):
207
+ env = {**os.environ, "MMK_INTERNAL_GLOBAL": "1", "MMK_LINK_ROOT": str(source or root),
208
+ "MMK_EXISTING_ROOT": str(existing) if existing else "",
209
+ "MMK_LEGACY_ROOT": str(legacy) if legacy else ""}
210
+ return subprocess.run(["sh", str(root / "install.sh"), "--internal-global", *flags],
211
+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True)
212
+
213
+
214
+ def global_flags(host):
215
+ return ["--target", LABELS[host]] if host else ["--commands-only"]
216
+
217
+
218
+ def native_directory(host):
219
+ return CLAUDE / "plugins" if host == "claude" else CODEX
220
+
221
+
222
+ def same_native_directory(host, owned):
223
+ directory = native_directory(host)
224
+ if owned.get("pluginDirectory"):
225
+ recorded = Path(owned["pluginDirectory"])
226
+ else:
227
+ recorded = Path(owned["directory"])
228
+ if host == "claude":
229
+ recorded /= "plugins"
230
+ try:
231
+ return directory.samefile(recorded)
232
+ except FileNotFoundError:
233
+ return directory.resolve() == recorded.resolve()
234
+
235
+
236
+ def is_legacy_checkout(root):
237
+ manifest = root / ".claude-plugin/plugin.json"
238
+ if ((root / ".git").exists() and (root / "rules/multi-model.md").is_file()
239
+ and not manifest.is_symlink()):
240
+ try:
241
+ return read_object(manifest).get("name") == NAME
242
+ except (InstallError, OSError, ValueError):
243
+ pass
244
+ return False
245
+
246
+
247
+ def legacy_checkout():
248
+ # Both commands must point to the corresponding binaries in a kit checkout
249
+ # before we adopt it. Remember that origin after the links move to current
250
+ # so other hosts can still migrate their own legacy skill links later.
251
+ roots = []
252
+ for name in COMMANDS:
253
+ link = HOME / ".local/bin" / name
254
+ if not link.is_symlink() or not link.is_file():
255
+ break
256
+ target = link.resolve()
257
+ if target.name != name or target.parent.name != "bin":
258
+ break
259
+ roots.append(target.parent.parent)
260
+ if len(roots) == len(COMMANDS) and roots[0] == roots[1] and is_legacy_checkout(roots[0]):
261
+ return roots[0]
262
+
263
+ recorded = read_object(RECEIPT).get("legacyCheckout")
264
+ if isinstance(recorded, str):
265
+ root = Path(recorded)
266
+ if root.is_absolute() and is_legacy_checkout(root):
267
+ return root
268
+ return None
269
+
270
+
271
+ def command_retargets(legacy_root, files):
272
+ if not (PACKAGED and files and legacy_root and ROOT != legacy_root):
273
+ return []
274
+ result = []
275
+ for name in COMMANDS:
276
+ link = HOME / ".local/bin" / name
277
+ old = legacy_root / "bin" / name
278
+ if link.is_symlink() and link.is_file() and link.resolve() == old:
279
+ result.append({"path": str(link), "from": str(old), "to": str(CURRENT / "bin" / name)})
280
+ return result
281
+
282
+
283
+ def retarget_commands(links, receipt, legacy_root):
284
+ # Recheck the approved sources before changing either link.
285
+ for item in links:
286
+ link = Path(item["path"])
287
+ if not link.is_symlink() or link.resolve() != Path(item["from"]):
288
+ raise InstallError(f"Command link changed during installation: {link}", CONFLICT)
289
+ receipt["legacyCheckout"] = str(legacy_root)
290
+ atomic_json(RECEIPT, receipt)
291
+ with tempfile.TemporaryDirectory(prefix=".mmk-links-", dir=HOME / ".local/bin") as temporary:
292
+ for item in links:
293
+ link = Path(item["path"])
294
+ prepared = Path(temporary) / link.name
295
+ prepared.symlink_to(item["to"])
296
+ os.replace(prepared, link)
297
+
298
+
299
+ def has_global_install(host, roots):
300
+ instruction, skills = PATHS[host]
301
+ if instruction.is_file() and b"<!-- BEGIN multi-model-kit -->" in instruction.read_bytes().splitlines():
302
+ return True
303
+ return any((skills / name).is_symlink() and (skills / name).resolve() == root / "skills" / name
304
+ for root in roots if root for name in SKILLS)
305
+
306
+
307
+ def global_removals(host, owned_root, legacy_root):
308
+ flags = ["--remove-target", LABELS[host]] if host else ["--remove-commands"]
309
+ return global_command(ROOT, *flags, "--preflight", "--list-removals",
310
+ existing=owned_root, legacy=legacy_root)
311
+
312
+
313
+ def native_files(host):
314
+ if host == "claude":
315
+ directory = CLAUDE / "plugins"
316
+ return [directory / "installed_plugins.json", directory / "known_marketplaces.json",
317
+ CLAUDE / "settings.json"]
318
+ return [CODEX / "config.toml", CODEX / "plugins/cache" / NAME / NAME]
319
+
320
+
321
+ def identity(value):
322
+ if value:
323
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
324
+ return None
325
+
326
+
327
+ def native_state(host):
328
+ installed, markets, *_ = native_files(host)
329
+ if host == "claude":
330
+ registrations = read_object(installed).get("plugins", {}).get(PLUGIN, [])
331
+ entry = read_object(markets).get(NAME)
332
+ roots = [Path(item["installPath"]) for item in registrations if item.get("installPath")]
333
+ enabled_plugins = read_object(CLAUDE / "settings.json").get("enabledPlugins") or {}
334
+ enabled = enabled_plugins.get(PLUGIN, True)
335
+ return identity(registrations), identity(entry), roots if enabled else []
336
+
337
+ content = installed.read_text(encoding="utf-8") if installed.is_file() else ""
338
+
339
+ def section(table, name):
340
+ escaped = re.escape(name)
341
+ expression = (rf"""(?m)^[ \t]*\[{table}\.(?:["']{escaped}["']|{escaped})\][ \t]*$"""
342
+ r"(?:\n(?![ \t]*\[)[^\n]*)*")
343
+ match = re.search(expression, content)
344
+ return match.group().strip() if match else None
345
+
346
+ registration = section("plugins", PLUGIN)
347
+ market = section("marketplaces", NAME)
348
+ roots = sorted(markets.glob("*/"), reverse=True)
349
+ enabled = not registration or not re.search(r"(?m)^\s*enabled\s*=\s*false\b", registration)
350
+ return identity(registration or [str(root) for root in roots]), identity(market), roots if enabled else []
351
+
352
+
353
+ def connection_info():
354
+ return {"claude": bool(shutil.which("claude")),
355
+ "codex": bool(shutil.which("codex")),
356
+ "gemini": bool(shutil.which("agy") or shutil.which("gemini"))}
357
+
358
+
359
+ def role_preview(config):
360
+ output = checked([str(ROOT / "bin/model-route"), "--preview", "--config-stdin"],
361
+ capture=True, input_text=json.dumps(config))
362
+ routes = json.loads(output)
363
+ return {role: {key: route[key] for key in ("primary", "alternatives")}
364
+ for role, route in routes.items()}
365
+
366
+
367
+ def configured(args, config):
368
+ proposal = dict(config)
369
+ if args.providers is not None:
370
+ proposal["enabled"] = list(dict.fromkeys(args.providers.split(",")))
371
+ if args.role:
372
+ proposal["roles"] = {role: settings.copy() for role, settings in config.get("roles", {}).items()}
373
+ for override in args.role:
374
+ role, separator, provider = override.partition("=")
375
+ if not separator or provider not in proposal.get("enabled", DEFAULTS["enabled"]):
376
+ raise InstallError(f"Invalid role assignment {override!r}. Use role=enabled-provider.")
377
+ proposal["roles"].setdefault(role, {})["provider"] = provider
378
+ if args.workflow == "ce":
379
+ proposal.update(workflow=DEFAULTS["workflow"], terminalDispatch="ce")
380
+ elif args.workflow == "direct":
381
+ proposal.update(workflow={}, terminalDispatch="none")
382
+ elif args.workflow == "custom":
383
+ if not args.workflow_skill:
384
+ raise InstallError("Custom workflow requires at least one --workflow-skill stage=skill.")
385
+ workflow = dict(proposal.get("workflow", DEFAULTS["workflow"]))
386
+ for override in args.workflow_skill:
387
+ stage, separator, skill = override.partition("=")
388
+ if not separator or stage not in DEFAULTS["workflow"]:
389
+ raise InstallError(f"Invalid workflow slot: {override!r}")
390
+ workflow[stage] = skill
391
+ proposal.update(workflow=workflow)
392
+ if args.enable_takeover:
393
+ proposal["takeover"] = "on"
394
+ routes = role_preview(proposal)
395
+ enabled = proposal.get("enabled", DEFAULTS["enabled"])
396
+ suggestions = {}
397
+ for role, info in routes.items():
398
+ desired = proposal.get("roles", {}).get(role, {}).get("provider", DEFAULTS["roles"][role]["provider"])
399
+ if desired not in enabled and info["primary"]:
400
+ suggestions[role] = info["primary"]
401
+ if args.use_fallbacks:
402
+ proposal["roles"] = {role: settings.copy() for role, settings in proposal.get("roles", {}).items()}
403
+ for role, route in suggestions.items():
404
+ proposal["roles"].setdefault(role, {})["provider"] = route["provider"]
405
+ routes = role_preview(proposal)
406
+ return proposal, routes, suggestions
407
+
408
+
409
+ def legacy_status(host, existing=None, legacy=None):
410
+ result = global_command(ROOT, "--check", *global_flags(host), existing=existing, legacy=legacy)
411
+ if result.returncode:
412
+ raise InstallError(result.stderr.strip())
413
+ return {line.rsplit(": ", 1)[0]: line.rsplit(": ", 1)[1] for line in result.stdout.splitlines()}
414
+
415
+
416
+ def visible_skills(host):
417
+ paths = [PATHS[host][1]]
418
+ if host in ("claude", "codex"):
419
+ _, _, roots = native_state(host)
420
+ paths.extend(root / "skills" for root in roots)
421
+ plug_root = os.environ.get(f"{host.upper()}_PLUGIN_ROOT")
422
+ if plug_root:
423
+ paths.append(Path(plug_root) / "skills")
424
+ return {name: any((directory / name / "SKILL.md").is_file() for directory in paths)
425
+ for name in SKILLS}
426
+
427
+
428
+ def payload_files():
429
+ # Use the same allowlist for installation and for npm. Deliberately avoid
430
+ # traversing files outside it, even when running from a checkout.
431
+ for entry in sorted(set(PACKAGE.get("files", ())) | {"package.json", "LICENSE"}):
432
+ path = ROOT / entry
433
+ candidates = path.rglob("*") if path.is_dir() else [path]
434
+ for file in sorted(candidates):
435
+ if file.is_file() and not file.is_symlink():
436
+ yield file.relative_to(ROOT)
437
+
438
+
439
+ def payload_digest(directory, files):
440
+ hashes = {str(file): hashlib.sha256((directory / file).read_bytes()).hexdigest() for file in files}
441
+ return hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest()
442
+
443
+
444
+ def native_catalog(host):
445
+ path = Path(".claude-plugin/marketplace.json" if host == "claude" else ".agents/plugins/marketplace.json")
446
+ manifest = read_object(ROOT / path)
447
+ plugin = next(item for item in manifest["plugins"] if item["name"] == NAME)
448
+ if host == "claude":
449
+ plugin["source"] = "./current"
450
+ else:
451
+ plugin["source"]["path"] = "./current"
452
+ manifest["plugins"] = [plugin]
453
+ return STORE / path, manifest
454
+
455
+
456
+ def catalog_conflict(path, manifest):
457
+ return path.is_symlink() or (path.exists() and (not path.is_file() or read_object(path) != manifest))
458
+
459
+
460
+ def uses_store(args, native):
461
+ return (PACKAGED or native or args.quota_plugin or args.agy_snapshot) and bool(PACKAGE)
462
+
463
+
464
+ def matches_payload(target, files, expected):
465
+ if target.is_symlink() or not target.is_dir():
466
+ return False
467
+ actual = set()
468
+ for file in target.rglob("*"):
469
+ if file.is_symlink():
470
+ return False
471
+ if file.is_dir():
472
+ continue
473
+ if not file.is_file():
474
+ return False
475
+ actual.add(file.relative_to(target))
476
+ return actual == set(files) and payload_digest(target, files) == expected
477
+
478
+
479
+ def stage(files, expected):
480
+ STORE.mkdir(parents=True, exist_ok=True)
481
+ target = STORE / VERSION
482
+ if target.exists() or target.is_symlink():
483
+ if not matches_payload(target, files, expected):
484
+ raise InstallError(f"Package contents differ at {target}. Install a different version.", CONFLICT)
485
+ else:
486
+ try:
487
+ with tempfile.TemporaryDirectory(prefix=".install-", dir=STORE) as temporary:
488
+ prepared = Path(temporary) / VERSION
489
+ for file in files:
490
+ destination = prepared / file
491
+ destination.parent.mkdir(parents=True, exist_ok=True)
492
+ shutil.copy2(ROOT / file, destination)
493
+ prepared.rename(target)
494
+ except OSError:
495
+ if not matches_payload(target, files, expected):
496
+ raise
497
+ if CURRENT.is_symlink() and os.readlink(CURRENT) == VERSION:
498
+ return target
499
+ with tempfile.TemporaryDirectory(prefix=".link-", dir=STORE) as temporary:
500
+ link = Path(temporary) / "current"
501
+ link.symlink_to(VERSION, target_is_directory=True)
502
+ os.replace(link, CURRENT)
503
+ return target
504
+
505
+
506
+ def inspect_agy(receipt):
507
+ settings = read_object(AGY)
508
+ status_line = settings.get("statusLine", {})
509
+ if not isinstance(status_line, dict) or not isinstance(status_line.get("command", ""), str):
510
+ raise InstallError(f"{AGY}: statusLine.command must be a string.")
511
+ capture = shlex.join(["node", str(CURRENT / "plugins/paseo-usage/bridge/capture-quota.cjs")])
512
+ own = receipt.get("agy", {})
513
+ if status_line.get("command") == capture or own.get("installed") == status_line:
514
+ return settings, status_line
515
+ installed = {**status_line, "type": "command", "command": capture}
516
+ if status_line.get("command"):
517
+ # Feed the same stdin to both commands while preserving the custom
518
+ # status line stdout and exit status.
519
+ original = status_line["command"]
520
+ script = f'input=$(cat); printf "%s" "$input" | {capture} >/dev/null 2>&1; printf "%s" "$input" | sh -c {shlex.quote(original)}'
521
+ installed["command"] = shlex.join(["sh", "-c", script])
522
+ return settings, installed
523
+
524
+
525
+ def make_plan(args):
526
+ host, targets, detected, decision = target_hosts(args)
527
+ receipt = read_object(RECEIPT)
528
+ config = read_object(CONFIG)
529
+ proposal, routes, suggestions = configured(args, config)
530
+ paths = [CONFIG, RECEIPT, *(HOME / ".local/bin" / name for name in COMMANDS)]
531
+ existing_root = installed_root()
532
+ use_existing = PACKAGED or bool(PACKAGE and not args.global_install)
533
+ owned_root = existing_root if use_existing else None
534
+ legacy_root = legacy_checkout() if use_existing else None
535
+ commands = global_command(ROOT, "--preflight", "--commands-only", existing=owned_root, legacy=legacy_root)
536
+ conflicts = []
537
+ if commands.returncode == CONFLICT:
538
+ conflicts.append(commands.stderr.strip())
539
+ elif commands.returncode:
540
+ raise InstallError(commands.stderr.strip())
541
+
542
+ actions = []
543
+ native = []
544
+ global_targets = []
545
+ migrations = []
546
+ for target in targets:
547
+ instruction, skills = PATHS[target]
548
+ paths.extend([instruction.parent, instruction, skills, *(skills / name for name in SKILLS)])
549
+ if args.global_install or target == "gemini":
550
+ proc = global_command(ROOT, "--preflight", *global_flags(target),
551
+ existing=owned_root, legacy=legacy_root)
552
+ if proc.returncode == CONFLICT:
553
+ if proc.stderr.strip() not in conflicts:
554
+ conflicts.append(proc.stderr.strip())
555
+ elif proc.returncode:
556
+ raise InstallError(proc.stderr.strip())
557
+ actions.append({"action": "installSkillsAndRules", "host": target, "skills": str(skills)})
558
+ global_targets.append(target)
559
+ continue
560
+ paths.extend(native_files(target))
561
+ installed, market, roots = native_state(target)
562
+ paths.extend(root / "skills" / name / "SKILL.md" for root in roots for name in SKILLS)
563
+ owned = receipt.get("native", {}).get(target, {})
564
+ if owned and not same_native_directory(target, owned):
565
+ conflicts.append(f"{target} is registered under a different config directory.")
566
+ elif installed and installed != owned.get("plugin"):
567
+ actions.append({"action": "keepExistingPlugin", "host": target})
568
+ elif market and market != owned.get("marketplace"):
569
+ conflicts.append(f"{target} already has a different marketplace named {NAME}.")
570
+ elif not shutil.which(target):
571
+ conflicts.append(f"{target} CLI is required for native installation.")
572
+ elif not PACKAGE:
573
+ conflicts.append(f"{target} native installation requires package.json.")
574
+ else:
575
+ path, catalog = native_catalog(target)
576
+ paths.append(path)
577
+ if catalog_conflict(path, catalog):
578
+ conflicts.append(f"{path} already contains a different marketplace catalog.")
579
+ native.append(target)
580
+ actions.append({"action": "installNativePlugin", "host": target, "plugin": PLUGIN})
581
+ if (target in native or roots) and has_global_install(target, (ROOT, owned_root, legacy_root)):
582
+ removal = global_removals(target, owned_root, legacy_root)
583
+ if removal.returncode:
584
+ conflicts.append(removal.stderr.strip())
585
+ elif removal.stdout:
586
+ migrations.append(target)
587
+ actions.append({"action": "migrateFromGlobal", "host": target,
588
+ "remove": removal.stdout.splitlines()})
589
+
590
+ if args.quota_plugin and not shutil.which("paseo"):
591
+ conflicts.append("Paseo CLI is required to install the optional quota plugin.")
592
+ if args.agy_snapshot:
593
+ paths.append(AGY)
594
+ inspect_agy(receipt)
595
+ if args.quota_plugin or args.agy_snapshot:
596
+ if host not in ("paseo", "all"):
597
+ conflicts.append("Paseo options require --host paseo or --host all.")
598
+
599
+ files = list(payload_files()) if uses_store(args, native) else []
600
+ package_hash = payload_digest(ROOT, files) if files else None
601
+ if files:
602
+ paths.extend([STORE, STORE / VERSION, CURRENT])
603
+ actions.insert(0, {"action": "stagePackage", "path": str(STORE / VERSION)})
604
+ target = STORE / VERSION
605
+ if target.exists() or target.is_symlink():
606
+ try:
607
+ identical = matches_payload(target, files, package_hash)
608
+ except OSError:
609
+ identical = False
610
+ if not identical:
611
+ conflicts.append(f"Package contents differ at {target}. Install a different version.")
612
+ if CURRENT.exists() and not CURRENT.is_symlink():
613
+ conflicts.append(f"{CURRENT} already exists and is not a package link.")
614
+ if CURRENT.is_symlink() and (CURRENT.resolve().parent != STORE.resolve() or not CURRENT.is_dir()):
615
+ conflicts.append(f"{CURRENT} is not a link to an installed package version.")
616
+
617
+ actions.append({"action": "linkSharedCommands", "path": str(HOME / ".local/bin")})
618
+ retargets = command_retargets(legacy_root, files)
619
+ if retargets:
620
+ actions.append({"action": "retargetCommands", "links": retargets})
621
+ if not os.access(HOME / ".local/bin", os.W_OK | os.X_OK):
622
+ conflicts.append(f"Cannot replace command links: {HOME / '.local/bin'} is not writable.")
623
+ if config != proposal:
624
+ changes = {key: value for key, value in proposal.items() if value != config.get(key)}
625
+ actions.append({"action": "updateConfig", "path": str(CONFIG), "changes": changes})
626
+ if args.quota_plugin:
627
+ actions.append({"action": "installPaseoQuotaPlugin"})
628
+ if args.agy_snapshot:
629
+ actions.append({"action": "captureAgyQuota", "path": str(AGY),
630
+ "preserveExistingStatusLine": True})
631
+
632
+ previous_version = CURRENT.resolve().name if CURRENT.is_symlink() and CURRENT.is_dir() else None
633
+ native_upgrade = any(receipt.get("native", {}).get(target, {}).get("version", VERSION) != VERSION
634
+ for target in native)
635
+ upgrade = (args.upgrade or native_upgrade or bool(migrations)
636
+ or bool(files and previous_version and previous_version != VERSION))
637
+ if upgrade:
638
+ actions.insert(0, {"action": "reviewActivePaseoSessions"})
639
+ takeover = proposal.get("takeover", DEFAULTS["takeover"])
640
+ result = {
641
+ "host": host,
642
+ "targets": targets,
643
+ "detectedHosts": detected,
644
+ "actions": actions,
645
+ "conflicts": conflicts,
646
+ "sessions": args.sessions,
647
+ "needsDecision": decision or (f"Approve migration from the old global install for {', '.join(migrations)}."
648
+ if migrations else None),
649
+ "subscriptions": {
650
+ "enabled": proposal.get("enabled", DEFAULTS["enabled"]),
651
+ "disabled": [name for name in PROVIDERS if name not in proposal.get("enabled", DEFAULTS["enabled"])],
652
+ "verified": False,
653
+ "cliAvailable": connection_info(),
654
+ },
655
+ "fallbackSuggestions": suggestions,
656
+ "rolePreview": routes,
657
+ "takeover": {
658
+ "setting": takeover,
659
+ "missingHosts": [provider for provider in PROVIDERS
660
+ if provider not in targets and not all(visible_skills(provider).values())]
661
+ if takeover == "on" else [],
662
+ },
663
+ }
664
+ digest_input = {"plan": result, "destinations": snapshot(paths), "package": package_hash,
665
+ "source": snapshot([ROOT / "install.sh", ROOT / "bin/model-route",
666
+ ROOT / "config/defaults.json", ROOT / "rules/multi-model.md"])}
667
+ # Source inode numbers differ when the same archive is unpacked again.
668
+ digest_input["source"] = {Path(path).name: value[-1] if value else None
669
+ for path, value in digest_input["source"].items()}
670
+ result["digest"] = hashlib.sha256(json.dumps(digest_input, sort_keys=True).encode()).hexdigest()
671
+ return (result, proposal, receipt, native, global_targets, files, package_hash, upgrade,
672
+ owned_root, legacy_root, migrations, decision, retargets)
673
+
674
+
675
+ def tty():
676
+ if (os.environ.get("MMK_STDIN_TTY") != "1"
677
+ or os.environ.get("CLAUDECODE") or os.environ.get("PASEO_AGENT_ID")
678
+ or any(os.environ.get(key) for key in CODEX_SESSION_ENV)):
679
+ return None
680
+ try:
681
+ return open("/dev/tty", "r+", buffering=1)
682
+ except OSError:
683
+ # Some Python builds reject a read/write stream on a character device.
684
+ try:
685
+ return open("/dev/tty", "r", buffering=1)
686
+ except OSError:
687
+ return None
688
+
689
+
690
+ def ask(terminal, prompt, default=None):
691
+ hint = f" [{default}]" if default is not None else ""
692
+ print(f"{prompt}{hint}: ", end="", file=sys.stderr, flush=True)
693
+ answer = terminal.readline()
694
+ if not answer:
695
+ raise InstallError("Input ended before approval.", DECISION)
696
+ return answer.strip() or default or ""
697
+
698
+
699
+ def choose(terminal, prompt, options, default=None):
700
+ while True:
701
+ answer = ask(terminal, f"{prompt} ({'/'.join(options)})", default)
702
+ if answer in options:
703
+ return answer
704
+ print("Choose one of the listed options.", file=sys.stderr)
705
+
706
+
707
+ def confirm(terminal, prompt):
708
+ return choose(terminal, prompt, ("y", "n"), "n") == "y"
709
+
710
+
711
+ def wizard(args, terminal):
712
+ current, provider, detected = current_host()
713
+ print(f"1/5 Host. Detected: {', '.join(detected) or 'none'}.", file=sys.stderr)
714
+ if not args.host:
715
+ args.host = choose(terminal, "Install into", HOSTS, current)
716
+ if args.host in ("paseo", "t3") and not args.provider:
717
+ args.provider = choose(terminal, "Provider running this session", PROVIDERS, provider)
718
+ print("2/5 Subscriptions and connections.", file=sys.stderr)
719
+ print("CLI availability: " + ", ".join(f"{name}={'found' if found else 'missing'}"
720
+ for name, found in connection_info().items()), file=sys.stderr)
721
+ config = read_object(CONFIG)
722
+ if args.providers is None:
723
+ args.providers = ask(terminal, "Enter subscribed providers (claude,codex,gemini), or Enter to keep current settings") or None
724
+ if args.host == "paseo":
725
+ print(f"ZeroSub is optional for Claude accounts and Claude↔GPT forks. See ZeroSub’s installation guide: {ZERO_SUB_URL}",
726
+ file=sys.stderr)
727
+ args.quota_plugin = args.quota_plugin or confirm(terminal, "Install the bundled Paseo quota plugin?")
728
+ args.agy_snapshot = args.agy_snapshot or confirm(terminal, "Change agy settings to capture status-line quota?")
729
+ if config.get("takeover", "off") == "off":
730
+ args.enable_takeover = args.enable_takeover or confirm(terminal, "Enable automatic cross-provider takeover?")
731
+ print("3/5 Role assignments.", file=sys.stderr)
732
+ _, _, suggestions = configured(args, config)
733
+ if suggestions:
734
+ print("Suggested replacements for disabled providers:", file=sys.stderr)
735
+ for role, replacement in suggestions.items():
736
+ print(f" {role}: {replacement['provider']} {replacement['model']}", file=sys.stderr)
737
+ assignment = choose(terminal, "Assignment", ("keep", "fallbacks", "roles"), "keep")
738
+ if assignment == "fallbacks":
739
+ args.use_fallbacks = True
740
+ elif assignment == "roles":
741
+ args.role.extend(ask(terminal, "Enter role=provider assignments separated by spaces").split())
742
+ print("4/5 Workflow.", file=sys.stderr)
743
+ if not args.workflow:
744
+ args.workflow = choose(terminal, "Workflow", ("keep", "ce", "custom", "direct"), "keep")
745
+ if args.workflow == "custom" and not args.workflow_skill:
746
+ for stage in DEFAULTS["workflow"]:
747
+ choice = ask(terminal, f"{stage} skill (Enter keeps it; '-' clears it)")
748
+ if choice:
749
+ args.workflow_skill.append(f"{stage}={'' if choice == '-' else choice}")
750
+ if not args.workflow_skill:
751
+ args.workflow = "keep"
752
+ print("5/5 Preview and apply.", file=sys.stderr)
753
+
754
+
755
+ def paseo_session_rows():
756
+ if not shutil.which("paseo"):
757
+ return []
758
+ result = run(["paseo", "ls", "--global", "--background", "--json"], capture=True)
759
+ if result.returncode:
760
+ raise InstallError("Could not list sessions in the Paseo daemon. Confirm its state before proceeding.", DECISION)
761
+ data = json.loads(result.stdout)
762
+ rows = data.get("agents", data.get("items", data.get("data"))) if isinstance(data, dict) else data
763
+ if not isinstance(rows, list):
764
+ raise InstallError("Paseo returned an unrecognized session list.", DECISION)
765
+ active = []
766
+ for row in rows:
767
+ labels = row.get("labels") or row.get("tags") or {}
768
+ state = row.get("status") or row.get("state")
769
+ if isinstance(state, dict):
770
+ state = state.get("type") or state.get("status")
771
+ if row.get("archivedAt") or state in ("idle", "archived", "stopped", "completed", "failed", "error"):
772
+ continue
773
+ if any(isinstance(label, str) and label.startswith("mmk.") for label in labels):
774
+ agent = row.get("id") or row.get("agentId")
775
+ if isinstance(agent, str) and agent and not agent.startswith("-"):
776
+ active.append(agent)
777
+ return list(dict.fromkeys(active))
778
+
779
+
780
+ def handle_sessions(choice, terminal):
781
+ active = paseo_session_rows()
782
+ if not active:
783
+ return
784
+ print("Active multi-model-kit Paseo sessions:", file=sys.stderr)
785
+ for agent in active:
786
+ print(f" {agent}", file=sys.stderr)
787
+ if choice:
788
+ stop = choice == "stop"
789
+ elif terminal:
790
+ stop = confirm(terminal, "Stop those sessions?")
791
+ else:
792
+ raise InstallError("Decide whether to stop those sessions (--sessions stop or keep).", DECISION)
793
+ if stop:
794
+ if os.environ.get("PASEO_AGENT_ID") in active:
795
+ raise InstallError("Stop the current installer session from another terminal.", DECISION)
796
+ for agent in active:
797
+ checked(["paseo", "stop", agent])
798
+
799
+
800
+ def print_global(result):
801
+ if result.stdout:
802
+ print(result.stdout, end="")
803
+ if result.stderr:
804
+ print(result.stderr, end="", file=sys.stderr)
805
+ if result.returncode:
806
+ raise InstallError("Could not finish the global installation.",
807
+ CONFLICT if result.returncode == CONFLICT else ERROR)
808
+
809
+
810
+ def install_native(host, receipt, upgrade):
811
+ registrations = receipt.setdefault("native", {})
812
+ owned = registrations.setdefault(host, {"pluginDirectory": str(native_directory(host).resolve())})
813
+ installed, market, _ = native_state(host)
814
+ if (installed and installed != owned.get("plugin")) or (market and market != owned.get("marketplace")):
815
+ raise InstallError(f"{host} plugin registration changed during installation.", CONFLICT)
816
+ path, catalog = native_catalog(host)
817
+ if catalog_conflict(path, catalog):
818
+ raise InstallError(f"{path} changed during installation.", CONFLICT)
819
+ if not path.exists():
820
+ atomic_json(path, catalog)
821
+ if not market:
822
+ # The CLI resolves marketplace paths. Register the physical parent so
823
+ # the catalog's relative source still follows current after an upgrade.
824
+ checked([host, "plugin", "marketplace", "add", str(STORE)])
825
+ market = native_state(host)[1]
826
+ if not market:
827
+ raise InstallError(f"{host} did not report the local marketplace after installation.")
828
+ owned["marketplace"] = market
829
+ atomic_json(RECEIPT, receipt)
830
+ if not installed or upgrade:
831
+ if installed and host == "claude":
832
+ checked([host, "plugin", "update", PLUGIN])
833
+ else:
834
+ checked([host, "plugin", "install" if host == "claude" else "add", PLUGIN])
835
+ installed = native_state(host)[0]
836
+ if not installed:
837
+ raise InstallError(f"{host} did not report the plugin after installation.")
838
+ owned.update(plugin=installed, version=VERSION)
839
+ atomic_json(RECEIPT, receipt)
840
+
841
+
842
+ def quota_plugin_installed():
843
+ data = json.loads(checked(["paseo", "plugin", "ls", "--json"], capture=True))
844
+ entries = data.get("plugins", data.get("data")) if isinstance(data, dict) else data
845
+ if not isinstance(entries, list):
846
+ raise InstallError("Paseo returned an unrecognized plugin list.")
847
+ return next((entry for entry in entries if isinstance(entry, dict) and entry.get("id") == QUOTA_ID), None)
848
+
849
+
850
+ def install_optional(args, receipt, upgrade):
851
+ if args.quota_plugin:
852
+ plugin = quota_plugin_installed()
853
+ if not plugin:
854
+ checked(["paseo", "plugin", "install", str(CURRENT / "plugins/paseo-usage"),
855
+ "--id", QUOTA_ID], timeout=60)
856
+ plugin = quota_plugin_installed()
857
+ if not plugin or not plugin.get("path"):
858
+ raise InstallError("Paseo did not report the quota plugin path after installation.")
859
+ receipt["quotaPlugin"] = plugin["path"]
860
+ atomic_json(RECEIPT, receipt)
861
+ elif upgrade and plugin.get("path") == receipt.get("quotaPlugin"):
862
+ checked(["paseo", "plugin", "reload", QUOTA_ID], timeout=60)
863
+ if args.agy_snapshot:
864
+ settings, installed = inspect_agy(receipt)
865
+ if settings.get("statusLine") != installed:
866
+ receipt["agy"] = {"original": settings.get("statusLine"), "installed": installed}
867
+ atomic_json(RECEIPT, receipt)
868
+ settings["statusLine"] = installed
869
+ atomic_json(AGY, settings)
870
+
871
+
872
+ def apply_plan(args, terminal, details):
873
+ (plan, proposal, receipt, native, global_targets, files, package_hash, upgrade,
874
+ owned_root, legacy_root, migrations, decision, retargets) = details
875
+ if args.apply and args.digest != plan["digest"]:
876
+ raise InstallError("Install plan has changed. Request a fresh --plan --json.", CONFLICT)
877
+ if plan["conflicts"]:
878
+ raise InstallError("\n".join(plan["conflicts"]), CONFLICT)
879
+ if decision:
880
+ raise InstallError(decision, DECISION)
881
+ config_before = fingerprint(CONFIG)
882
+ if upgrade:
883
+ handle_sessions(args.sessions, terminal)
884
+ root = stage(files, package_hash) if files else ROOT
885
+ source = CURRENT if files else root
886
+ for host in native:
887
+ install_native(host, receipt, upgrade)
888
+ for host in global_targets:
889
+ print_global(global_command(root, *global_flags(host), source=source,
890
+ existing=owned_root, legacy=legacy_root))
891
+ if not global_targets:
892
+ print_global(global_command(root, "--commands-only", source=source,
893
+ existing=owned_root, legacy=legacy_root))
894
+ for host in migrations:
895
+ print_global(global_command(root, "--remove-target", LABELS[host],
896
+ existing=owned_root, legacy=legacy_root))
897
+ if retargets:
898
+ retarget_commands(retargets, receipt, legacy_root)
899
+ install_optional(args, receipt, upgrade)
900
+ if proposal != read_object(CONFIG):
901
+ if config_before != fingerprint(CONFIG):
902
+ raise InstallError("Routing config changed during installation. Request a fresh plan.", CONFLICT)
903
+ atomic_json(CONFIG, proposal)
904
+
905
+
906
+ def installed_root():
907
+ if CURRENT.is_symlink() and CURRENT.is_dir() and CURRENT.resolve().parent == STORE.resolve():
908
+ return CURRENT.resolve()
909
+ return ROOT
910
+
911
+
912
+ def make_uninstall_plan(args):
913
+ receipt = read_object(RECEIPT)
914
+ owned_root = installed_root()
915
+ legacy_root = legacy_checkout()
916
+ if args.host and args.host != "all":
917
+ host, targets, _, decision = target_hosts(args)
918
+ else:
919
+ host, targets, decision = "all", list(PROVIDERS), None
920
+
921
+ paths = [RECEIPT]
922
+ actions = []
923
+ conflicts = []
924
+ global_targets = []
925
+ for target in targets:
926
+ if has_global_install(target, (ROOT, owned_root, legacy_root)):
927
+ result = global_removals(target, owned_root, legacy_root)
928
+ if result.returncode:
929
+ conflicts.append(result.stderr.strip())
930
+ elif result.stdout:
931
+ removed = result.stdout.splitlines()
932
+ paths.extend(Path(path) for path in removed)
933
+ actions.append({"action": "removeGlobalLinksAndRuleBlock", "host": target, "paths": removed})
934
+ global_targets.append(target)
935
+ owned = receipt.get("native", {}).get(target)
936
+ if owned and same_native_directory(target, owned):
937
+ paths.extend(native_files(target))
938
+ plugin, market, _ = native_state(target)
939
+ removing_plugin = bool(plugin and plugin == owned.get("plugin"))
940
+ if removing_plugin:
941
+ actions.append({"action": "removeNativePlugin", "host": target, "plugin": PLUGIN})
942
+ if (not plugin or removing_plugin) and market and market == owned.get("marketplace"):
943
+ actions.append({"action": "removeLocalMarketplace", "host": target, "marketplace": NAME})
944
+
945
+ if args.host in (None, "all", "paseo"):
946
+ if receipt.get("quotaPlugin"):
947
+ actions.append({"action": "removeOwnedPaseoQuotaPlugin", "plugin": QUOTA_ID})
948
+ if receipt.get("agy"):
949
+ paths.append(AGY)
950
+ if read_object(AGY).get("statusLine") == receipt["agy"]["installed"]:
951
+ actions.append({"action": "restoreAgyStatusLine", "path": str(AGY)})
952
+ if args.host in (None, "all", "terminal"):
953
+ result = global_removals(None, owned_root, legacy_root)
954
+ if result.returncode:
955
+ conflicts.append(result.stderr.strip())
956
+ elif result.stdout:
957
+ removed = result.stdout.splitlines()
958
+ paths.extend(Path(path) for path in removed)
959
+ actions.append({"action": "removeSharedCommandLinks", "paths": removed})
960
+
961
+ plan = {"operation": "uninstall", "host": host, "actions": actions,
962
+ "conflicts": conflicts, "sessions": args.sessions, "needsDecision": decision}
963
+ plan["digest"] = identity({"plan": plan, "destinations": snapshot(paths)})
964
+ return plan, receipt, targets, global_targets, owned_root, legacy_root
965
+
966
+
967
+ def uninstall(args, terminal):
968
+ plan, receipt, targets, global_targets, owned_root, legacy_root = make_uninstall_plan(args)
969
+ if args.plan:
970
+ dump(plan)
971
+ return 0
972
+ if args.apply and args.digest != plan["digest"]:
973
+ raise InstallError("Uninstall plan changed. Request a fresh --uninstall --plan --json.", CONFLICT)
974
+ if not args.apply:
975
+ dump(plan)
976
+ if plan["conflicts"]:
977
+ raise InstallError("\n".join(plan["conflicts"]), CONFLICT)
978
+ if plan["needsDecision"]:
979
+ raise InstallError(plan["needsDecision"], DECISION)
980
+ if not args.apply:
981
+ if terminal is None:
982
+ handle_sessions(None, None)
983
+ raise InstallError("An approved uninstall plan is required.", DECISION)
984
+ if not confirm(terminal, "Uninstall the items listed above?"):
985
+ return DECISION
986
+ handle_sessions(args.sessions, terminal)
987
+ if make_uninstall_plan(args)[0]["digest"] != plan["digest"]:
988
+ raise InstallError("Uninstall targets changed during confirmation.", CONFLICT)
989
+
990
+ registrations = receipt.get("native", {})
991
+ for host in targets:
992
+ owned = registrations.get(host)
993
+ if owned and same_native_directory(host, owned):
994
+ plugin, marketplace, _ = native_state(host)
995
+ # A user may have replaced either registration after adoption.
996
+ if plugin and plugin == owned.get("plugin"):
997
+ checked([host, "plugin", "uninstall" if host == "claude" else "remove", PLUGIN])
998
+ owned.pop("plugin")
999
+ atomic_json(RECEIPT, receipt)
1000
+ plugin = None
1001
+ if not plugin and marketplace and marketplace == owned.get("marketplace"):
1002
+ checked([host, "plugin", "marketplace", "remove", NAME])
1003
+ registrations.pop(host)
1004
+ atomic_json(RECEIPT, receipt)
1005
+ if host in global_targets:
1006
+ print_global(global_command(ROOT, "--remove-target", LABELS[host],
1007
+ existing=owned_root, legacy=legacy_root))
1008
+ if args.host in (None, "all", "paseo"):
1009
+ if receipt.get("quotaPlugin"):
1010
+ plugin = quota_plugin_installed()
1011
+ if plugin and plugin.get("path") == receipt["quotaPlugin"]:
1012
+ checked(["paseo", "plugin", "remove", QUOTA_ID])
1013
+ receipt.pop("quotaPlugin")
1014
+ atomic_json(RECEIPT, receipt)
1015
+ if receipt.get("agy"):
1016
+ settings = read_object(AGY)
1017
+ agy = receipt.pop("agy")
1018
+ if settings.get("statusLine") == agy["installed"]:
1019
+ if agy["original"] is None:
1020
+ settings.pop("statusLine")
1021
+ else:
1022
+ settings["statusLine"] = agy["original"]
1023
+ atomic_json(AGY, settings)
1024
+ atomic_json(RECEIPT, receipt)
1025
+ if args.host in (None, "all", "terminal"):
1026
+ print_global(global_command(ROOT, "--remove-commands", existing=owned_root, legacy=legacy_root))
1027
+ if args.host in (None, "all") and receipt.pop("legacyCheckout", None) and any(receipt.values()):
1028
+ atomic_json(RECEIPT, receipt)
1029
+ if RECEIPT.is_file() and not any(receipt.values()):
1030
+ RECEIPT.unlink()
1031
+ return 0
1032
+
1033
+
1034
+ def check_installation(args):
1035
+ host, targets, detected, decision = target_hosts(args)
1036
+ reachable = None
1037
+ if shutil.which("paseo"):
1038
+ try:
1039
+ status = run(["paseo", "status", "--json"], capture=True, timeout=5)
1040
+ reachable = False
1041
+ if status.returncode == 0:
1042
+ data = json.loads(status.stdout)
1043
+ if isinstance(data, dict):
1044
+ data = data.get("data", data)
1045
+ connection = data.get("connectedDaemon")
1046
+ reachable = (connection == "reachable" if connection is not None
1047
+ else data.get("status") == "running")
1048
+ except (OSError, ValueError, subprocess.TimeoutExpired):
1049
+ reachable = False
1050
+ result = {
1051
+ "host": host,
1052
+ "targets": targets,
1053
+ "detectedHosts": detected,
1054
+ "needsDecision": decision,
1055
+ "daemon": {"reachable": reachable},
1056
+ "skills": {target: visible_skills(target) for target in targets},
1057
+ "commands": legacy_status(None, existing=installed_root(), legacy=legacy_checkout()),
1058
+ }
1059
+ if args.json:
1060
+ dump(result)
1061
+ else:
1062
+ print(f"Host: {host or 'unknown'}")
1063
+ for target, skills in result["skills"].items():
1064
+ for name, visible in skills.items():
1065
+ print(f"{target} skill {name}: {'installed' if visible else 'missing'}")
1066
+ for name, status in result["commands"].items():
1067
+ print(f"{name}: {status}")
1068
+ return DECISION if decision else 0
1069
+
1070
+
1071
+ def arguments():
1072
+ parser = ArgumentParser(prog=NAME, allow_abbrev=False)
1073
+ mode = parser.add_mutually_exclusive_group()
1074
+ for flag in ("plan", "apply", "check"):
1075
+ mode.add_argument(f"--{flag}", action="store_true")
1076
+ parser.add_argument("--uninstall", action="store_true",
1077
+ help="Preview, approve, or interactively remove owned installation items")
1078
+ parser.add_argument("--host", choices=HOSTS)
1079
+ parser.add_argument("--provider", choices=PROVIDERS, help="Inner provider for Paseo or T3")
1080
+ parser.add_argument("--json", action="store_true")
1081
+ parser.add_argument("--yes", action="store_true")
1082
+ parser.add_argument("--digest")
1083
+ parser.add_argument("--global", dest="global_install", action="store_true",
1084
+ help="Link skills and rules directly instead of using native plugin managers")
1085
+ parser.add_argument("--providers", help="Comma-separated list of subscribed and approved providers")
1086
+ parser.add_argument("--role", action="append", default=[], metavar="ROLE=PROVIDER")
1087
+ parser.add_argument("--use-fallbacks", action="store_true")
1088
+ parser.add_argument("--workflow", choices=("keep", "ce", "custom", "direct"))
1089
+ parser.add_argument("--workflow-skill", action="append", default=[], metavar="STAGE=SKILL")
1090
+ parser.add_argument("--enable-takeover", action="store_true")
1091
+ parser.add_argument("--quota-plugin", action="store_true")
1092
+ parser.add_argument("--agy-snapshot", action="store_true")
1093
+ parser.add_argument("--upgrade", action="store_true")
1094
+ parser.add_argument("--sessions", choices=("keep", "stop"))
1095
+ args = parser.parse_args(sys.argv[2:])
1096
+ if args.apply and (not args.yes or not args.digest):
1097
+ raise InstallError("--apply requires --digest from the approved plan and --yes.", DECISION)
1098
+ if args.digest and not args.apply:
1099
+ parser.error("--digest is only valid with --apply")
1100
+ if args.yes and not args.apply:
1101
+ raise InstallError("Use --plan --json and --apply --digest for unattended changes.", DECISION)
1102
+ if args.uninstall and (args.check or args.global_install or args.providers or args.role
1103
+ or args.use_fallbacks or args.workflow or args.enable_takeover
1104
+ or args.agy_snapshot or args.quota_plugin or args.upgrade):
1105
+ parser.error("--uninstall accepts host, plan, approval, and session options")
1106
+ if args.workflow_skill and args.workflow != "custom":
1107
+ parser.error("--workflow-skill requires --workflow custom")
1108
+ if args.provider and args.host and args.host not in ("paseo", "t3"):
1109
+ parser.error("--provider applies only to Paseo or T3")
1110
+ return args
1111
+
1112
+
1113
+ def main():
1114
+ args = arguments()
1115
+ if PACKAGE and (not isinstance(VERSION, str) or
1116
+ not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.+-]+)?", VERSION)):
1117
+ raise InstallError("package.json requires a version suitable for an npm release.")
1118
+ if args.check:
1119
+ return check_installation(args)
1120
+ if args.plan and not args.uninstall:
1121
+ dump(make_plan(args)[0])
1122
+ return 0
1123
+ terminal = tty() if not (args.plan or args.yes or args.apply) else None
1124
+ try:
1125
+ if args.uninstall:
1126
+ return uninstall(args, terminal)
1127
+ if not args.apply and not args.yes and terminal:
1128
+ wizard(args, terminal)
1129
+ details = make_plan(args)
1130
+ dump({key: value for key, value in details[0].items()
1131
+ if key not in ("rolePreview", "fallbackSuggestions")})
1132
+ if details[0]["conflicts"]:
1133
+ raise InstallError("\n".join(details[0]["conflicts"]), CONFLICT)
1134
+ if not confirm(terminal, "Apply this plan?"):
1135
+ return DECISION
1136
+ approved = details[0]["digest"]
1137
+ details = make_plan(args)
1138
+ if details[0]["digest"] != approved:
1139
+ raise InstallError("Install plan changed during the preview.", CONFLICT)
1140
+ else:
1141
+ details = make_plan(args)
1142
+ if not args.yes:
1143
+ dump(details[0])
1144
+ raise InstallError("A terminal or an approved plan is required.", DECISION)
1145
+ apply_plan(args, terminal, details)
1146
+ return 0
1147
+ finally:
1148
+ if terminal:
1149
+ terminal.close()
1150
+
1151
+
1152
+ try:
1153
+ sys.exit(main())
1154
+ except InstallError as error:
1155
+ print(error, file=sys.stderr)
1156
+ sys.exit(error.code)
1157
+ except (ValueError, OSError, subprocess.SubprocessError) as error:
1158
+ print(f"multi-model-kit: {error}", file=sys.stderr)
1159
+ sys.exit(ERROR)
1160
+ PYTHON
1161
+ }
1162
+
1163
+ if [ "${MMK_PACKAGED-}" != 1 ] && [ "$#" -eq 4 ] && [ "$*" = '--host all --global --yes' ]; then
1164
+ MMK_INTERNAL_GLOBAL=1
1165
+ set -- --internal-global
1166
+ fi
1167
+ case ${1-} in
1168
+ --internal-global)
1169
+ [ "${MMK_INTERNAL_GLOBAL-}" = 1 ] || exit 2
1170
+ shift
1171
+ ;;
1172
+ --migrate-to-plugin|--check)
1173
+ case "$*" in
1174
+ --check)
1175
+ if [ "${MMK_PACKAGED-}" = 1 ] ||
1176
+ [ -e "$HOME/.local/share/multi-model-kit/current" ] ||
1177
+ [ -L "$HOME/.local/share/multi-model-kit/current" ]; then
1178
+ run_wizard "$@"; exit $?
1179
+ fi
1180
+ ;;
1181
+ --migrate-to-plugin\ claude|--migrate-to-plugin\ codex|--migrate-to-plugin\ claude\ --check|--migrate-to-plugin\ codex\ --check|--check\ --migrate-to-plugin\ claude|--check\ --migrate-to-plugin\ codex)
1182
+ [ "${MMK_PACKAGED-}" != 1 ] || { run_wizard "$@"; exit $?; }
1183
+ ;;
1184
+ *) run_wizard "$@"; exit $? ;;
1185
+ esac
1186
+ ;;
1187
+
1188
+ *) run_wizard "$@"; exit $? ;;
1189
+ esac
1190
+
1191
+ usage() {
1192
+ printf 'Usage: %s [--check] [--migrate-to-plugin <claude|codex>]\n' "$0" >&2
1193
+ exit 1
1194
+ }
1195
+
1196
+ check=false
1197
+ migrate=
1198
+ selected=
1199
+ preflight=false
1200
+ list_removals=false
1201
+ commands_remove=false
1202
+ while [ "$#" -gt 0 ]; do
1203
+ case $1 in
1204
+ --check) check=true ;;
1205
+ --preflight) preflight=true ;;
1206
+ --list-removals) list_removals=true ;;
1207
+ --target) selected=$2; shift ;;
1208
+ --commands-only) selected=none ;;
1209
+ --remove-commands) commands_remove=true ;;
1210
+ --remove-target) migrate=$2; shift ;;
1211
+ --migrate-to-plugin)
1212
+ [ -z "$migrate" ] || usage
1213
+ case ${2-} in
1214
+ claude) migrate=Claude; shift ;;
1215
+ codex) migrate=Codex; shift ;;
1216
+ *) usage ;;
1217
+ esac
1218
+ ;;
1219
+ *) usage ;;
1220
+ esac
1221
+ shift
1222
+ done
1223
+ if "$check" && [ -n "$migrate" ]; then
1224
+ printf '%s\n' '--check reports global installation status, not a migration preview.' >&2
1225
+ migrate=
1226
+ fi
1227
+
1228
+ read_settings() {
1229
+ settings=$("$repo/bin/model-route" --settings)
1230
+ # model-route emits autoload as the first property of its settings object.
1231
+ case $settings in
1232
+ '{"autoload": true,'*) rules_enabled=true ;;
1233
+ '{"autoload": false,'*) rules_enabled=false ;;
1234
+ *) printf 'Cannot read autoload from model-route --settings\n' >&2; exit 1 ;;
1235
+ esac
1236
+ }
1237
+
1238
+ skill_status() {
1239
+ if [ -L "$2" ] && destination=$(CDPATH= cd -P "$2" 2>/dev/null && pwd) &&
1240
+ { [ "$destination" = "$1" ] ||
1241
+ { [ -n "$existing_root" ] && [ "$destination" = "$existing_root/skills/${1##*/}" ]; } ||
1242
+ { [ -n "$legacy_root" ] && [ "$destination" = "$legacy_root/skills/${1##*/}" ]; }; }; then
1243
+ printf 'installed\n'
1244
+ elif [ -e "$2" ] || [ -L "$2" ]; then
1245
+ printf 'conflict\n'
1246
+ else
1247
+ printf 'missing\n'
1248
+ fi
1249
+ }
1250
+
1251
+ # Keep file bytes intact and put the next marker on its own line.
1252
+ write_lines() {
1253
+ cat "$1" || return
1254
+ if [ -s "$1" ] && [ "$(tail -c 1 "$1" | wc -l)" -eq 0 ]; then
1255
+ printf '\n'
1256
+ fi
1257
+ }
1258
+
1259
+ # True when the file has no markers, or exactly one pair in order.
1260
+ markers_ok() {
1261
+ LC_ALL=C awk -v begin="$begin" -v end="$end" '
1262
+ $0 == begin { b++; if (!bl) bl = NR }
1263
+ $0 == end { e++; if (!el) el = NR }
1264
+ $0 == begin "\r" || $0 == end "\r" { crlf = 1 }
1265
+ END { exit !(!crlf && ((b == 0 && e == 0) || (b == 1 && e == 1 && bl < el))) }
1266
+ ' "$1"
1267
+ }
1268
+
1269
+ render_rules() {
1270
+ if [ -f "$1" ]; then
1271
+ bounds=$(LC_ALL=C awk -v begin="$begin" -v end="$end" '
1272
+ $0 == begin && !start { start = NR }
1273
+ $0 == end && start { print start, NR; exit }
1274
+ ' "$1") || return
1275
+ if [ -n "$bounds" ]; then
1276
+ first=${bounds% *}
1277
+ last=${bounds#* }
1278
+ if "$rules_enabled"; then
1279
+ head -n "$first" "$1" || return
1280
+ write_lines "$rule_file" || return
1281
+ tail -n "+$last" "$1"
1282
+ else
1283
+ if [ "$first" -gt 1 ]; then
1284
+ head -n "$((first - 1))" "$1" || return
1285
+ fi
1286
+ tail -n "+$((last + 1))" "$1"
1287
+ fi
1288
+ return
1289
+ fi
1290
+ if ! "$rules_enabled"; then
1291
+ cat "$1"
1292
+ return
1293
+ fi
1294
+ write_lines "$1" || return
1295
+ fi
1296
+ "$rules_enabled" || return 0
1297
+ printf '%s\n' "$begin" || return
1298
+ write_lines "$rule_file" || return
1299
+ printf '%s\n' "$end"
1300
+ }
1301
+
1302
+ blocked_directory() {
1303
+ [ ! -d "$1" ] && { [ -e "$1" ] || [ -L "$1" ]; }
1304
+ }
1305
+
1306
+ # True when the path, or its nearest existing ancestor, is a directory files can be created in.
1307
+ can_create_in() {
1308
+ dir=$1
1309
+ while [ ! -e "$dir" ] && [ ! -L "$dir" ]; do
1310
+ dir=${dir%/*}
1311
+ done
1312
+ [ -d "$dir" ] && [ -w "$dir" ] && [ -x "$dir" ]
1313
+ }
1314
+
1315
+ inspect_target() {
1316
+ for skill in "$repo"/skills/*; do
1317
+ [ -d "$skill" ] || continue
1318
+ name=${skill##*/}
1319
+ target=$skill_dir/$name
1320
+ if ! "$enabled"; then
1321
+ status=skipped
1322
+ elif blocked_directory "${skill_dir%/*}" || blocked_directory "$skill_dir"; then
1323
+ status=conflict
1324
+ else
1325
+ source=$(CDPATH= cd -P "$skill" && pwd)
1326
+ status=$(skill_status "$source" "$target")
1327
+ if [ "$status" = missing ] && ! can_create_in "$skill_dir"; then
1328
+ status=conflict
1329
+ fi
1330
+ fi
1331
+ if "$check"; then
1332
+ printf '%sskill %s: %s\n' "$label" "$name" "$status"
1333
+ elif [ "$status" = conflict ]; then
1334
+ printf 'Cannot install skill %s: %s or its parent is already in use\n' "$name" "$target" >&2
1335
+ exit 3
1336
+ fi
1337
+ done
1338
+ inspect_rules
1339
+ }
1340
+
1341
+ inspect_rules() {
1342
+ rule_dir=${instruction_file%/*}
1343
+ if ! "$enabled"; then
1344
+ status=skipped
1345
+ elif [ -L "$instruction_file" ] && [ ! -e "$instruction_file" ]; then
1346
+ status=conflict
1347
+ reason='is a dangling link'
1348
+ elif [ -d "$rule_dir" ] && [ ! -x "$rule_dir" ]; then
1349
+ status=conflict
1350
+ reason='is in a directory that is not searchable'
1351
+ elif [ -f "$instruction_file" ]; then
1352
+ if ! markers_ok "$instruction_file"; then
1353
+ status=conflict
1354
+ reason='has unpaired or repeated markers'
1355
+ elif ! "$rules_enabled" && ! grep -Fxq -- "$begin" "$instruction_file"; then
1356
+ status=disabled
1357
+ elif [ ! -w "$instruction_file" ]; then
1358
+ status=conflict
1359
+ reason='is not writable'
1360
+ elif ! "$rules_enabled"; then
1361
+ status=outdated
1362
+ elif "$check" && ! grep -Fxq -- "$begin" "$instruction_file"; then
1363
+ status=missing
1364
+ elif "$check" && ! render_rules "$instruction_file" | cmp -s "$instruction_file" -; then
1365
+ status=outdated
1366
+ else
1367
+ status=installed
1368
+ fi
1369
+ elif [ -e "$instruction_file" ]; then
1370
+ status=conflict
1371
+ reason='is not a regular file'
1372
+ elif ! "$rules_enabled"; then
1373
+ status=disabled
1374
+ else
1375
+ status=missing
1376
+ fi
1377
+ case $status in
1378
+ installed|missing|outdated)
1379
+ if ! can_create_in "$rule_dir"; then
1380
+ status=conflict
1381
+ reason='is in a directory that is not writable'
1382
+ fi
1383
+ ;;
1384
+ esac
1385
+ if "$check"; then
1386
+ printf '%srules %s: %s\n' "$label" "${instruction_file##*/}" "$status"
1387
+ elif [ "$status" = conflict ]; then
1388
+ action=install
1389
+ "$rules_enabled" || action=remove
1390
+ printf 'Cannot %s rules: %s %s\n' "$action" "$instruction_file" "$reason" >&2
1391
+ exit 3
1392
+ fi
1393
+ }
1394
+
1395
+ owns_skill() {
1396
+ [ "$(skill_status "$(CDPATH= cd -P "$1" && pwd)" "$2")" = installed ]
1397
+ }
1398
+
1399
+ inspect_migration() {
1400
+ "$enabled" || return 0
1401
+ read_settings
1402
+ rules_enabled=false
1403
+ inspect_rules
1404
+ migration_rule=
1405
+ [ "$status" != outdated ] || migration_rule=$instruction_file
1406
+
1407
+ for dir in "${skill_dir%/*}" "$skill_dir"; do
1408
+ if blocked_directory "$dir" || { [ -d "$dir" ] && [ ! -x "$dir" ]; }; then
1409
+ printf 'Cannot inspect %s skills: %s is not a searchable directory\n' "$host" "$dir" >&2
1410
+ exit 1
1411
+ fi
1412
+ done
1413
+ if [ -d "$skill_dir" ] && [ ! -r "$skill_dir" ]; then
1414
+ printf 'Cannot inspect %s skills: %s is not readable\n' "$host" "$skill_dir" >&2
1415
+ exit 1
1416
+ fi
1417
+
1418
+ migration_skills=
1419
+ if "$list_removals" && [ -n "$migration_rule" ]; then
1420
+ printf '%s\n' "$migration_rule"
1421
+ fi
1422
+ for skill in "$repo"/skills/*; do
1423
+ [ -d "$skill" ] || continue
1424
+ owns_skill "$skill" "$skill_dir/${skill##*/}" || continue
1425
+ migration_skills=$skill_dir
1426
+ if "$list_removals"; then
1427
+ printf '%s\n' "$skill_dir/${skill##*/}"
1428
+ else
1429
+ break
1430
+ fi
1431
+ done
1432
+ for_each_target inspect_shared_target
1433
+ if [ -n "$migration_skills" ] && ! can_create_in "$skill_dir"; then
1434
+ printf 'Cannot remove %s skills: %s is not writable\n' "$host" "$skill_dir" >&2
1435
+ exit 1
1436
+ fi
1437
+ }
1438
+
1439
+ inspect_shared_target() {
1440
+ "$enabled" && [ "$host" != "$migrate" ] || return 0
1441
+ # Compare device and inode to follow symlinks and detect hard links.
1442
+ if [ -n "$migration_rule" ] && [ "$migration_rule" -ef "$instruction_file" ]; then
1443
+ printf 'Cannot migrate %s: rules %s share a file with %s rules %s\n' \
1444
+ "$migrate" "$migration_rule" "$host" "$instruction_file" >&2
1445
+ exit 1
1446
+ fi
1447
+ if [ -n "$migration_skills" ] && [ "$migration_skills" -ef "$skill_dir" ]; then
1448
+ printf 'Cannot migrate %s: skills %s share a directory with %s skills %s\n' \
1449
+ "$migrate" "$migration_skills" "$host" "$skill_dir" >&2
1450
+ exit 1
1451
+ fi
1452
+ }
1453
+
1454
+ update_rules() (
1455
+ "$enabled" || return 0
1456
+ if ! "$rules_enabled"; then
1457
+ [ -f "$instruction_file" ] && grep -Fxq -- "$begin" "$instruction_file" || return 0
1458
+ fi
1459
+ candidate=$(mktemp "${instruction_file%/*}/.${instruction_file##*/}.XXXXXX")
1460
+ trap 'rm -f "$candidate"' 0
1461
+ if [ -f "$instruction_file" ]; then
1462
+ cp -p "$instruction_file" "$candidate"
1463
+ fi
1464
+ render_rules "$instruction_file" > "$candidate"
1465
+
1466
+ if cmp -s "$instruction_file" "$candidate"; then
1467
+ :
1468
+ elif [ -L "$instruction_file" ]; then
1469
+ # Write through the link so the user's real file is updated.
1470
+ cat "$candidate" > "$instruction_file"
1471
+ else
1472
+ mv -f "$candidate" "$instruction_file"
1473
+ fi
1474
+ )
1475
+
1476
+ install_target() {
1477
+ "$enabled" || return 0
1478
+ mkdir -p "$skill_dir"
1479
+ if "$rules_enabled"; then mkdir -p "${instruction_file%/*}"; fi
1480
+ update_rules
1481
+ for skill in "$repo"/skills/*; do
1482
+ [ -d "$skill" ] || continue
1483
+ target=$skill_dir/${skill##*/}
1484
+ [ -L "$target" ] || ln -s "$link_root/skills/${skill##*/}" "$skill_dir"
1485
+ done
1486
+ }
1487
+
1488
+ migrate_target() {
1489
+ "$enabled" || return 0
1490
+ update_rules
1491
+ for skill in "$repo"/skills/*; do
1492
+ [ -d "$skill" ] || continue
1493
+ target=$skill_dir/${skill##*/}
1494
+ if owns_skill "$skill" "$target"; then
1495
+ rm "$target"
1496
+ fi
1497
+ done
1498
+ }
1499
+
1500
+ with_target() (
1501
+ [ -z "$2" ] || [ "$2" = "$3" ] || return 0
1502
+ host=$3
1503
+ label=$4
1504
+ instruction_file=$5
1505
+ skill_dir=$6
1506
+ enabled=true
1507
+ if [ -z "$selected" ] && [ ! -d "${instruction_file%/*}" ]; then
1508
+ enabled=false
1509
+ fi
1510
+ "$1"
1511
+ )
1512
+
1513
+ for_each_target() {
1514
+ claude_home=${CLAUDE_CONFIG_DIR:-$HOME/.claude}
1515
+ codex_home=${CODEX_HOME:-$HOME/.codex}
1516
+ with_target "$1" "${2-}" Claude '' "$claude_home/CLAUDE.md" "$claude_home/skills"
1517
+ with_target "$1" "${2-}" Codex 'Codex ' "$codex_home/AGENTS.md" "$HOME/.agents/skills"
1518
+ with_target "$1" "${2-}" Gemini 'Gemini ' "$HOME/.gemini/GEMINI.md" "$HOME/.gemini/skills"
1519
+ }
1520
+
1521
+ command_status() {
1522
+ if [ -L "$command_link" ]; then
1523
+ if [ ! -e "$command_link" ]; then
1524
+ printf 'conflict\n'
1525
+ return
1526
+ fi
1527
+ destination=$(readlink "$command_link") || return
1528
+ case $destination in
1529
+ /*) ;;
1530
+ *) destination=$command_dir/$destination ;;
1531
+ esac
1532
+ if parent=$(CDPATH= cd -P "${destination%/*}/" 2>/dev/null && pwd) &&
1533
+ { [ "$parent/${destination##*/}" = "$command_source" ] ||
1534
+ { [ -n "$existing_root" ] && [ "$parent/${destination##*/}" = "$existing_root/bin/$name" ]; } ||
1535
+ { [ -n "$legacy_root" ] && [ "$parent/${destination##*/}" = "$legacy_root/bin/$name" ]; }; }; then
1536
+ printf 'installed\n'
1537
+ else
1538
+ printf 'conflict\n'
1539
+ fi
1540
+ elif [ -e "$command_link" ] || ! can_create_in "$command_dir"; then
1541
+ printf 'conflict\n'
1542
+ else
1543
+ printf 'missing\n'
1544
+ fi
1545
+ }
1546
+
1547
+ for_each_command() (
1548
+ command_dir=$HOME/.local/bin
1549
+ for name in quota-status model-route; do
1550
+ command_link=$command_dir/$name
1551
+ command_source=$repo/bin/$name
1552
+ status=$(command_status)
1553
+ if "$check"; then
1554
+ printf 'command %s: %s\n' "$name" "$status"
1555
+ elif [ "$1" = inspect ] && [ "$status" = conflict ]; then
1556
+ if [ -L "$command_link" ] && [ ! -e "$command_link" ]; then
1557
+ printf 'Cannot install command %s: %s is a dangling link. Remove that link and request a fresh plan.\n' "$name" "$command_link" >&2
1558
+ else
1559
+ printf 'Cannot install command %s: %s or its parent is unavailable\n' "$name" "$command_link" >&2
1560
+ fi
1561
+ exit 3
1562
+ elif [ "$1" = remove ] && [ "$status" = installed ]; then
1563
+ if "$list_removals"; then printf '%s\n' "$command_link"; fi
1564
+ if ! "$preflight"; then rm "$command_link"; fi
1565
+ elif [ "$1" = install ] && [ "$status" = missing ]; then
1566
+ mkdir -p "$command_dir"
1567
+ ln -s "$link_root/bin/$name" "$command_dir"
1568
+ fi
1569
+ done
1570
+ )
1571
+
1572
+ # Check every destination before writing to any of them.
1573
+ if "$commands_remove"; then
1574
+ for_each_command remove
1575
+ exit 0
1576
+ fi
1577
+ if [ -n "$migrate" ]; then
1578
+ for_each_target inspect_migration "$migrate"
1579
+ if "$preflight"; then exit 0; fi
1580
+ rules_enabled=false
1581
+ for_each_target migrate_target "$migrate"
1582
+ exit 0
1583
+ fi
1584
+ read_settings
1585
+ for_each_target inspect_target "$selected"
1586
+ for_each_command inspect
1587
+ if "$check" || "$preflight"; then exit 0; fi
1588
+
1589
+ for_each_target install_target "$selected"
1590
+ for_each_command install
1591
+ if [ ! -d "$HOME/.claude" ] && [ ! -d "$HOME/.codex" ] && [ ! -d "$HOME/.gemini" ]; then
1592
+ printf 'No Claude, Codex, or Gemini config directory found. Installed shared commands only.\n'
1593
+ fi
1594
+ case :${PATH-}: in
1595
+ *":$HOME/.local/bin:"*) ;;
1596
+ *) printf 'Add ~/.local/bin to your PATH to run quota-status and model-route.\n' >&2 ;;
1597
+ esac
1598
+ cat <<'EOF'
1599
+
1600
+ The development workflow defaults to compound-engineering. See the README for
1601
+ installation commands for each host.
1602
+ In ~/.config/multi-model-kit/config.json, set workflow entries to your own skill
1603
+ names or use an empty string to skip a stage. Set workflow to {} to disable all
1604
+ stages. If compound-engineering is unavailable in your terminal, set
1605
+ terminalDispatch to "none".
1606
+ EOF