claudeup 6.3.2 → 6.5.0

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 (72) hide show
  1. package/package.json +4 -4
  2. package/src/__tests__/catalog-notice.test.ts +3 -3
  3. package/src/__tests__/cli-live.test.ts +9 -2
  4. package/src/__tests__/cli-update-view.test.ts +2 -2
  5. package/src/__tests__/footer-hints.test.ts +40 -0
  6. package/src/__tests__/gap-fill-versions.test.ts +24 -24
  7. package/src/__tests__/gitignore-prerun.test.ts +6 -13
  8. package/src/__tests__/hook-import-policy.test.ts +90 -0
  9. package/src/__tests__/hook-process.test.ts +256 -0
  10. package/src/__tests__/hook-registration.test.ts +224 -0
  11. package/src/__tests__/manifest.test.ts +134 -0
  12. package/src/__tests__/marketplace-badge.test.ts +1 -1
  13. package/src/__tests__/marketplaces.test.ts +0 -1
  14. package/src/__tests__/model-visuals.test.tsx +793 -0
  15. package/src/__tests__/models-adapter.test.ts +317 -0
  16. package/src/__tests__/models-cli.test.ts +173 -0
  17. package/src/__tests__/models-core.test.ts +640 -0
  18. package/src/__tests__/models-manager.test.ts +497 -0
  19. package/src/__tests__/models-screen-state.test.ts +259 -0
  20. package/src/__tests__/moved-marketplace.test.ts +7 -8
  21. package/src/__tests__/plugin-contents.test.ts +1 -1
  22. package/src/__tests__/profile-adopt.test.ts +1 -1
  23. package/src/__tests__/profile-materializer.test.ts +48 -2
  24. package/src/__tests__/resolver.test.ts +43 -6
  25. package/src/__tests__/settings-file.test.ts +179 -0
  26. package/src/__tests__/symlink-manager.test.ts +65 -1
  27. package/src/__tests__/tabbar-layout.test.ts +40 -2
  28. package/src/__tests__/theme-adaptive-colors.test.ts +48 -1
  29. package/src/__tests__/version-snapshot.test.ts +4 -4
  30. package/src/cli/doctor.ts +90 -0
  31. package/src/cli/hook.ts +129 -0
  32. package/src/cli/models.ts +214 -0
  33. package/src/cli/router.ts +12 -0
  34. package/src/data/gitignore-defaults.ts +4 -1
  35. package/src/data/gitignore-reasons.ts +0 -4
  36. package/src/data/marketplaces.ts +1 -15
  37. package/src/data/models-presets.ts +270 -0
  38. package/src/data/predefined-profiles.ts +12 -21
  39. package/src/data/settings-catalog.ts +11 -4
  40. package/src/main.tsx +51 -82
  41. package/src/services/hook-registration.ts +218 -0
  42. package/src/services/manifest.ts +84 -0
  43. package/src/services/models-core.ts +628 -0
  44. package/src/services/models-manager.ts +606 -0
  45. package/src/services/plugin-manager.ts +2 -3
  46. package/src/services/profile-materializer.ts +17 -0
  47. package/src/services/resolver.ts +13 -2
  48. package/src/services/settings-file.ts +69 -0
  49. package/src/services/styles-manager.ts +23 -45
  50. package/src/services/symlink-manager.ts +57 -11
  51. package/src/tui.tsx +112 -0
  52. package/src/types/bun.d.ts +21 -0
  53. package/src/types/index.ts +14 -0
  54. package/src/ui/App.tsx +15 -3
  55. package/src/ui/adapters/modelsAdapter.ts +170 -0
  56. package/src/ui/adapters/pluginsAdapter.ts +1 -1
  57. package/src/ui/components/TabBar.tsx +9 -4
  58. package/src/ui/components/layout/FooterHints.tsx +20 -3
  59. package/src/ui/components/layout/ScreenLayout.tsx +87 -7
  60. package/src/ui/components/primitives/MetaText.tsx +27 -1
  61. package/src/ui/renderers/modelRenderers.tsx +1004 -0
  62. package/src/ui/renderers/modelVisuals.tsx +853 -0
  63. package/src/ui/renderers/skillRenderers.tsx +13 -3
  64. package/src/ui/renderers/styleRenderers.tsx +7 -3
  65. package/src/ui/screens/ModelsScreen.tsx +478 -0
  66. package/src/ui/screens/PluginsScreen.tsx +1 -1
  67. package/src/ui/screens/StylesScreen.tsx +8 -13
  68. package/src/ui/screens/index.ts +1 -0
  69. package/src/ui/state/reducer.ts +94 -0
  70. package/src/ui/state/types.ts +65 -2
  71. package/src/ui/theme-mode.ts +116 -0
  72. package/src/ui/theme.ts +26 -0
@@ -13,7 +13,12 @@ import {
13
13
  async function materialize(
14
14
  project: string,
15
15
  name: string,
16
- files: { settings?: object; mcp?: object; skills?: boolean },
16
+ files: {
17
+ settings?: object;
18
+ mcp?: object;
19
+ skills?: boolean;
20
+ models?: object;
21
+ },
17
22
  ) {
18
23
  const dir = profileDir(name, project);
19
24
  await fs.ensureDir(dir);
@@ -21,6 +26,7 @@ async function materialize(
21
26
  await fs.writeJson(join(dir, "settings.json"), files.settings);
22
27
  if (files.mcp) await fs.writeJson(join(dir, "mcp.json"), files.mcp);
23
28
  if (files.skills) await fs.ensureDir(join(dir, "skills"));
29
+ if (files.models) await fs.writeJson(join(dir, "models.json"), files.models);
24
30
  }
25
31
 
26
32
  describe("symlink-manager", () => {
@@ -108,6 +114,64 @@ describe("symlink-manager", () => {
108
114
  );
109
115
  });
110
116
 
117
+ test("links models.json when the profile has routing", async () => {
118
+ await materialize(project, "frontend", {
119
+ settings: { a: 1 },
120
+ models: { version: 1, preset: "fable-advisor" },
121
+ });
122
+ await activateProfile("frontend", project);
123
+
124
+ const link = join(project, ".claude", "models.json");
125
+ expect((await lstat(link)).isSymbolicLink()).toBe(true);
126
+ expect((await fs.readJson(link)).preset).toBe("fable-advisor");
127
+ });
128
+
129
+ // A dangling .claude/models.json is a repo-wide hazard: `.claude/` is
130
+ // committed, so it would ship to every teammate and point at a directory
131
+ // that only exists on the machine that made it.
132
+ test("a profile without routing gets no models link at all", async () => {
133
+ await materialize(project, "frontend", { settings: { a: 1 } });
134
+ await activateProfile("frontend", project);
135
+
136
+ const link = join(project, ".claude", "models.json");
137
+ expect(await fs.pathExists(link)).toBe(false);
138
+ await expect(lstat(link)).rejects.toThrow();
139
+ });
140
+
141
+ test("switching to a profile without routing removes the previous link", async () => {
142
+ await materialize(project, "routed", {
143
+ settings: { which: "routed" },
144
+ models: { version: 1, preset: "fable-advisor" },
145
+ });
146
+ await materialize(project, "plain", { settings: { which: "plain" } });
147
+
148
+ await activateProfile("routed", project);
149
+ expect(
150
+ (await lstat(join(project, ".claude", "models.json"))).isSymbolicLink(),
151
+ ).toBe(true);
152
+
153
+ await activateProfile("plain", project);
154
+ await expect(
155
+ lstat(join(project, ".claude", "models.json")),
156
+ ).rejects.toThrow();
157
+ });
158
+
159
+ // Removal is scoped to links INTO _profiles/. A real models.json a project
160
+ // wrote by hand is not claudeup's to delete.
161
+ test("a real models.json file is never clobbered by activation", async () => {
162
+ await materialize(project, "plain", { settings: { a: 1 } });
163
+ await fs.outputJson(join(project, ".claude", "models.json"), {
164
+ version: 1,
165
+ preset: "hand-written",
166
+ });
167
+
168
+ await activateProfile("plain", project);
169
+
170
+ expect(
171
+ (await fs.readJson(join(project, ".claude", "models.json"))).preset,
172
+ ).toBe("hand-written");
173
+ });
174
+
111
175
  test("activeProfile returns null when settings.json is a real file", async () => {
112
176
  await fs.ensureDir(join(project, ".claude"));
113
177
  await fs.writeJson(join(project, ".claude", "settings.json"), { a: 1 });
@@ -4,13 +4,18 @@ import { TABS, barWidth, layoutTabs } from "../ui/components/TabBar.js";
4
4
  const FULL = TABS.map((t) => `${t.key}:${t.label}`);
5
5
  const FULL_WIDTH = barWidth(FULL);
6
6
 
7
+ /** The widest the compacted bar ever gets — whichever active label is longest. */
8
+ const WIDEST_COMPACT = Math.max(
9
+ ...TABS.map((tab) => barWidth(layoutTabs(TABS, tab.screen, 0))),
10
+ );
11
+
7
12
  describe("tab bar layout", () => {
8
13
  test("shows every label when the bar fits", () => {
9
14
  expect(layoutTabs(TABS, "plugins", FULL_WIDTH)).toEqual(FULL);
10
15
  });
11
16
 
12
17
  test("drops inactive labels when the bar does not fit", () => {
13
- // A 94-column pane leaves ~90 usable, and nine full tabs need ~99 — the
18
+ // A 94-column pane leaves ~90 usable, and ten full tabs need ~110 — the
14
19
  // width at which OpenTUI clipped each cell into a meaningless stub.
15
20
  const texts = layoutTabs(TABS, "styles", 90);
16
21
  expect(texts).toContain("9:Styles");
@@ -24,6 +29,26 @@ describe("tab bar layout", () => {
24
29
  expect(barWidth(layoutTabs(TABS, "styles", 90))).toBeLessThanOrEqual(90);
25
30
  });
26
31
 
32
+ test("the full bar no longer fits a standard window, so compacting is the norm", () => {
33
+ // The tenth tab pushed the full bar past 100 columns. That is not a
34
+ // regression — it is why the compact form has to stay readable, and why
35
+ // the test below measures it rather than assuming.
36
+ expect(FULL_WIDTH).toBeGreaterThan(100);
37
+ expect(layoutTabs(TABS, "models", 100)).not.toEqual(FULL);
38
+ });
39
+
40
+ test("the compact bar fits an 80-column terminal, on every tab", () => {
41
+ // The real question a tenth tab raises. ScreenLayout pads the bar by 1
42
+ // each side inside a container padded by 1, so an 80-column terminal
43
+ // leaves 76 — and the widest compact bar is well under it.
44
+ expect(WIDEST_COMPACT).toBeLessThanOrEqual(76);
45
+ for (const tab of TABS) {
46
+ expect(barWidth(layoutTabs(TABS, tab.screen, 76))).toBeLessThanOrEqual(
47
+ 76,
48
+ );
49
+ }
50
+ });
51
+
27
52
  test("keeps the label of whichever tab is active", () => {
28
53
  for (const tab of TABS) {
29
54
  const texts = layoutTabs(TABS, tab.screen, 40);
@@ -46,7 +71,9 @@ describe("tab bar layout", () => {
46
71
 
47
72
  test("every tab key is a digit the global handler binds", () => {
48
73
  // The compact bar shows only the number, so the number must be the key
49
- // that actually navigates.
74
+ // that actually navigates. Models is keyed "0" and sits last, because the
75
+ // number row reads 1…9 then 0 — the order here and the order under the
76
+ // fingers have to agree.
50
77
  expect(TABS.map((t) => t.key)).toEqual([
51
78
  "1",
52
79
  "2",
@@ -57,6 +84,17 @@ describe("tab bar layout", () => {
57
84
  "7",
58
85
  "8",
59
86
  "9",
87
+ "0",
60
88
  ]);
89
+ expect(TABS.at(-1)).toEqual({
90
+ key: "0",
91
+ label: "Models",
92
+ screen: "models",
93
+ });
94
+ });
95
+
96
+ test("no two tabs share a key or a screen", () => {
97
+ expect(new Set(TABS.map((t) => t.key)).size).toBe(TABS.length);
98
+ expect(new Set(TABS.map((t) => t.screen)).size).toBe(TABS.length);
61
99
  });
62
100
  });
@@ -96,7 +96,18 @@ describe("contrast maths", () => {
96
96
 
97
97
  // ─── The palette ──────────────────────────────────────────────────────────────
98
98
 
99
- const ACCENTS = Object.entries(brand).filter(([name]) => name !== "ink");
99
+ /**
100
+ * Inks we paint on a fill WE own, so they are measured against that fill and
101
+ * not against the terminal. They cannot satisfy the both-backgrounds rule and
102
+ * are not supposed to: `selectionDim` is a light grey chosen for the selection
103
+ * purple, which on a cream terminal would be invisible — and is never drawn
104
+ * there.
105
+ */
106
+ const OWN_FILL_INKS = new Set(["ink", "selectionDim"]);
107
+
108
+ const ACCENTS = Object.entries(brand).filter(
109
+ ([name]) => !OWN_FILL_INKS.has(name),
110
+ );
100
111
 
101
112
  describe("accents are legible on light AND dark terminals", () => {
102
113
  test("the palette is non-empty (guards the loops below)", () => {
@@ -131,6 +142,42 @@ describe("accents are legible on light AND dark terminals", () => {
131
142
  expect(failures).toEqual([]);
132
143
  });
133
144
 
145
+ test("a SELECTED row has two legible inks, and the page palette is not among them", () => {
146
+ // Found on a screenshot: `(default)` was drawn in `theme.colors.muted` on
147
+ // the selection purple and simply was not there. Every page-level tone
148
+ // fails the same way — they are chosen against the terminal's background,
149
+ // and the selection fill is neither of the two references.
150
+ const bg = theme.selection.bg;
151
+ expect(contrastRatio(theme.selection.fg, bg)).toBeGreaterThanOrEqual(
152
+ INK_CONTRAST,
153
+ );
154
+ expect(contrastRatio(theme.selection.dim, bg)).toBeGreaterThanOrEqual(
155
+ UI_CONTRAST,
156
+ );
157
+
158
+ // And it must READ as secondary next to the primary ink, or the
159
+ // distinction it exists to make is not visible.
160
+ expect(
161
+ contrastRatio(theme.selection.dim, theme.selection.fg),
162
+ ).toBeGreaterThan(1.2);
163
+ expect(contrastRatio(theme.selection.dim, bg)).toBeLessThan(
164
+ contrastRatio(theme.selection.fg, bg),
165
+ );
166
+ });
167
+
168
+ test("the meta tones are exactly why a selected row cannot use them", () => {
169
+ // The negative half of the rule above, kept measurable: if a future
170
+ // palette change made one of these legible on the selection, the
171
+ // selection-aware branch in MetaText would still be right, but this test
172
+ // would tell us the reasoning had changed.
173
+ const unreadable = Object.entries(theme.meta).filter(
174
+ ([, hex]) => contrastRatio(hex, theme.selection.bg) < UI_CONTRAST,
175
+ );
176
+ expect(unreadable.map(([name]) => name).sort()).toEqual(
177
+ Object.keys(theme.meta).sort(),
178
+ );
179
+ });
180
+
134
181
  test("the three scope colours are perceptually far apart", () => {
135
182
  // They render as single-character squares, where a subtle shift is not
136
183
  // readable at all. Deferring to ANSI put project and local on slots 2 and 3,
@@ -159,13 +159,13 @@ describe("per-project baselines", () => {
159
159
 
160
160
  test("saving one project preserves the others", async () => {
161
161
  await withSandbox(async () => {
162
- await saveSeenVersions("/proj/a", { "gtd@magus": "2.0.0" });
163
- await saveSeenVersions("/proj/b", { "gtd@magus": "2.0.1" });
162
+ await saveSeenVersions("/proj/a", { "designer@magus": "2.0.0" });
163
+ await saveSeenVersions("/proj/b", { "designer@magus": "2.0.1" });
164
164
  expect(await loadSeenVersions("/proj/a")).toEqual({
165
- "gtd@magus": "2.0.0",
165
+ "designer@magus": "2.0.0",
166
166
  });
167
167
  expect(await loadSeenVersions("/proj/b")).toEqual({
168
- "gtd@magus": "2.0.1",
168
+ "designer@magus": "2.0.1",
169
169
  });
170
170
  });
171
171
  });
package/src/cli/doctor.ts CHANGED
@@ -6,15 +6,26 @@
6
6
  * This is the check that would have caught a dead `tmux-mcp`.
7
7
  * 2. Profile symlink integrity — the active profile's links resolve.
8
8
  * 3. Convention compliance — .gitignore + CLAUDE.md blocks (ported engine).
9
+ * 4. Model routing — config validity, hook registration, and drift.
9
10
  */
10
11
 
11
12
  import path from "node:path";
12
13
  import fs from "fs-extra";
13
14
  import { checkBinaries, missingBinaries } from "../services/doctor-bins.js";
14
15
  import { checkProject, fixDoctorIssues } from "../services/doctor.js";
16
+ import {
17
+ isAgentModelHookRegistered,
18
+ registerAgentModelHook,
19
+ } from "../services/hook-registration.js";
15
20
  import { readManifest } from "../services/manifest.js";
21
+ import {
22
+ readModelsConfig,
23
+ readModelsStatus,
24
+ reapplyModels,
25
+ } from "../services/models-manager.js";
16
26
  import { resolveAllProfiles } from "../services/resolver.js";
17
27
  import { activeProfile, profileDir } from "../services/symlink-manager.js";
28
+ import { resolveExecutable } from "../utils/command-utils.js";
18
29
 
19
30
  export async function runDoctorCommand(args: string[]): Promise<number> {
20
31
  const fix = args.includes("--fix");
@@ -98,10 +109,89 @@ export async function runDoctorCommand(args: string[]): Promise<number> {
98
109
  }
99
110
  }
100
111
 
112
+ // 4. Model routing.
113
+ problems += await checkModels(projectPath, fix);
114
+
101
115
  if (problems === 0) console.log("\n✓ No problems found.");
102
116
  return problems > 0 && !fix ? 1 : 0;
103
117
  }
104
118
 
119
+ /**
120
+ * Model routing health. Silent when the project has no routing at all — an
121
+ * absent `models.json` is the normal state, not a finding.
122
+ *
123
+ * Ordered by what blocks what: an invalid config routes nothing and cannot be
124
+ * fixed from here (the values are a human's decision); an unregistered hook
125
+ * routes nothing no matter how good the config is; drift only matters once
126
+ * both of those are sound.
127
+ */
128
+ async function checkModels(projectPath: string, fix: boolean): Promise<number> {
129
+ const { config, errors, path: file } = await readModelsConfig(projectPath);
130
+ if (config === null && errors.length === 0) return 0;
131
+
132
+ console.log("\nModel routing:");
133
+ let problems = 0;
134
+
135
+ if (errors.length > 0) {
136
+ console.log(` ✗ ${file} is invalid — nothing is routed:`);
137
+ for (const e of errors) {
138
+ console.log(` ${e.path || "(root)"}: ${e.message}`);
139
+ }
140
+ console.log(
141
+ " Not auto-fixable: these are choices, not damage. Edit the file (or",
142
+ );
143
+ console.log(" re-run `claudeup models use <preset>`) and check again.");
144
+ // An invalid config is worth exactly one problem, not one per message —
145
+ // the count drives the exit code, not the severity.
146
+ return 1;
147
+ }
148
+
149
+ // The hook is what applies the routing. Without it the config is inert.
150
+ if (await isAgentModelHookRegistered()) {
151
+ console.log(" ✓ agent-model hook registered at user scope.");
152
+ } else if (fix) {
153
+ await registerAgentModelHook();
154
+ console.log(" ✓ agent-model hook registered at user scope (fixed).");
155
+ } else {
156
+ console.log(
157
+ " ✗ agent-model hook is not registered — the config is there, but nothing runs it.",
158
+ );
159
+ console.log(" Fix: claudeup doctor --fix");
160
+ problems++;
161
+ }
162
+
163
+ // The hook runs as a bare `claudeup`, deliberately (an absolute path dies on
164
+ // the next upgrade) — so PATH has to carry it. Warn only: PATH inside a
165
+ // Claude Code session is not necessarily PATH here.
166
+ if (!(await resolveExecutable("claudeup"))) {
167
+ console.log(
168
+ " • `claudeup` is not on PATH in this shell. The hook invokes it by name,",
169
+ );
170
+ console.log(
171
+ " so it must resolve in the shell Claude Code spawns hooks from.",
172
+ );
173
+ }
174
+
175
+ const status = await readModelsStatus(projectPath);
176
+ if (status.state === "stale") {
177
+ console.log(" ✗ settings have drifted from the config:");
178
+ for (const line of status.drift) console.log(` ${line}`);
179
+ if (fix) {
180
+ await reapplyModels(projectPath);
181
+ console.log(" Re-applied the config (fixed).");
182
+ } else {
183
+ console.log(" Fix: claudeup doctor --fix");
184
+ problems++;
185
+ }
186
+ } else if (status.state === "on") {
187
+ console.log(` ✓ preset "${status.preset}" applied, no drift.`);
188
+ }
189
+
190
+ for (const warning of status.warnings) console.log(` ⚠ ${warning}`);
191
+
192
+ return problems;
193
+ }
194
+
105
195
  /** Which of the active profile's expected symlinks are missing or dangling. */
106
196
  async function danglingLinks(
107
197
  name: string,
@@ -0,0 +1,129 @@
1
+ /**
2
+ * `claudeup hook agent-model` — the PreToolUse hook Claude Code runs on every Agent call.
3
+ *
4
+ * This is the hottest path claudeup has: Claude Code spawns it once per subagent dispatch, in
5
+ * every session on the machine, and waits for it. Two consequences shape the whole file.
6
+ *
7
+ * IT MUST BE FAST. `main.tsx` routes here before it loads the project's `.env` and before it
8
+ * imports the router or the TUI, so nothing in this module may import `src/ui/` or anything
9
+ * that pulls in `@opentui`. `src/__tests__/hook-import-policy.test.ts` fails the build if that
10
+ * ever regresses. Measured: 0.02s on this path against 0.16s once the router is loaded.
11
+ *
12
+ * IT MUST FAIL OPEN. Every error path exits 0 with empty stdout, which Claude Code reads as
13
+ * "no opinion". A hook that throws, blocks, or exits non-zero takes the user's subagents with
14
+ * it, and the failure would surface as delegation mysteriously not working — in every project,
15
+ * not just the one with the bad config. Silence is always the safe answer, so it is the
16
+ * default and the fallback.
17
+ *
18
+ * It never writes a file, never exits 2, and never reads a `.env`.
19
+ */
20
+ import { existsSync, readFileSync } from "node:fs";
21
+ import { dirname, join, parse } from "node:path";
22
+ import {
23
+ type ModelsConfig,
24
+ evaluateAgentHook,
25
+ validateModelsConfig,
26
+ } from "../services/models-core.js";
27
+
28
+ /** How far up the tree to look for a config before giving up. */
29
+ const MAX_WALK_UP = 32;
30
+
31
+ /**
32
+ * Find the nearest `.claude/models.json` at or above `startDir`.
33
+ *
34
+ * The walk matters: a session's cwd is frequently a subdirectory of the project, and this repo
35
+ * in particular runs most work inside git worktrees. Anchoring on the hook payload's `cwd`
36
+ * rather than `process.cwd()` is deliberate — Claude Code tells us where the session is, and
37
+ * that is not necessarily where this process was started.
38
+ */
39
+ export function findModelsConfig(startDir: string): string | null {
40
+ let dir = startDir;
41
+ const root = parse(dir).root;
42
+ for (let i = 0; i < MAX_WALK_UP; i += 1) {
43
+ const candidate = join(dir, ".claude", "models.json");
44
+ if (existsSync(candidate)) return candidate;
45
+ if (dir === root) return null;
46
+ const parent = dirname(dir);
47
+ if (parent === dir) return null;
48
+ dir = parent;
49
+ }
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * Read and validate a config. Returns null for every unusable state — missing, unreadable,
55
+ * unparseable, or invalid — because the hook's answer to all four is the same: do nothing.
56
+ *
57
+ * An invalid config is NOT an error here even though it is one everywhere else. `models use`
58
+ * refuses to write one, `claudeup install` refuses to apply one, and `doctor` reports one; by
59
+ * the time a session is running, the only useful behaviour left is to get out of the way.
60
+ */
61
+ export function loadConfig(path: string): ModelsConfig | null {
62
+ let raw: unknown;
63
+ try {
64
+ raw = JSON.parse(readFileSync(path, "utf8"));
65
+ } catch {
66
+ return null;
67
+ }
68
+ if (validateModelsConfig(raw).length > 0) return null;
69
+ return raw as ModelsConfig;
70
+ }
71
+
72
+ async function readStdin(): Promise<string> {
73
+ // A hook always receives its payload on stdin. Guard the TTY case anyway so that a human
74
+ // typing the subcommand by hand gets an immediate no-op instead of a hang.
75
+ if (process.stdin.isTTY) return "";
76
+ const chunks: Uint8Array[] = [];
77
+ for await (const chunk of Bun.stdin.stream()) chunks.push(chunk);
78
+ return Buffer.concat(chunks).toString("utf8");
79
+ }
80
+
81
+ export async function runHookCommand(args: string[]): Promise<number> {
82
+ // `hook` with no recognised name is a no-op rather than a usage error: this process is
83
+ // wired into someone's session, and printing to stdout would be interpreted as a decision.
84
+ if (args[0] !== "agent-model") {
85
+ await readStdin();
86
+ return 0;
87
+ }
88
+
89
+ try {
90
+ const raw = await readStdin();
91
+ if (raw.trim().length === 0) return 0;
92
+
93
+ let payload: Record<string, unknown>;
94
+ try {
95
+ payload = JSON.parse(raw) as Record<string, unknown>;
96
+ } catch {
97
+ return 0;
98
+ }
99
+
100
+ // `cwd` is the session's directory, which is not this process's cwd.
101
+ const cwd =
102
+ typeof payload.cwd === "string" && payload.cwd.length > 0
103
+ ? payload.cwd
104
+ : process.cwd();
105
+ const configPath = findModelsConfig(cwd);
106
+ const config = configPath === null ? null : loadConfig(configPath);
107
+
108
+ const decision = evaluateAgentHook(
109
+ {
110
+ tool_name:
111
+ typeof payload.tool_name === "string" ? payload.tool_name : undefined,
112
+ tool_input:
113
+ typeof payload.tool_input === "object" && payload.tool_input !== null
114
+ ? (payload.tool_input as Record<string, unknown>)
115
+ : undefined,
116
+ cwd,
117
+ },
118
+ config,
119
+ );
120
+
121
+ if (decision.kind === "update")
122
+ process.stdout.write(JSON.stringify(decision.output));
123
+ return 0;
124
+ } catch {
125
+ // Belt and braces. Nothing above should throw, and if it ever does the session must
126
+ // not notice.
127
+ return 0;
128
+ }
129
+ }