tokenusage-cli 0.1.0 → 0.2.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 (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,279 +1,279 @@
1
- const fs = require("node:fs/promises");
2
- const path = require("node:path");
3
-
4
- const { ensureDir, readJson, writeJson } = require("./fs");
5
- const { buildNotifyCommand, notifyIdentity } = require("./notify-command");
6
-
7
- const DEFAULT_EVENT = "SessionEnd";
8
- const CLAUDE_USAGE_EVENTS = ["Stop", DEFAULT_EVENT];
9
-
10
- async function upsertClaudeHook({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
11
- return upsertClaudeHooks({ settingsPath, hookCommand, events: [event] });
12
- }
13
-
14
- async function upsertClaudeUsageHooks({ settingsPath, hookCommand }) {
15
- return upsertClaudeHooks({ settingsPath, hookCommand, events: CLAUDE_USAGE_EVENTS });
16
- }
17
-
18
- async function upsertClaudeHooks({ settingsPath, hookCommand, events }) {
19
- const existing = await readJson(settingsPath);
20
- const settings = normalizeSettings(existing);
21
- const hooks = normalizeHooks(settings.hooks);
22
- const nextHooks = { ...hooks };
23
- let changed = false;
24
-
25
- for (const event of normalizeEventList(events)) {
26
- const entries = normalizeEntries(hooks[event]);
27
- const normalized = normalizeEntriesForCommand(entries, hookCommand, event);
28
- let nextEntries = normalized.entries;
29
- if (!hasHook(nextEntries, hookCommand)) {
30
- nextEntries = nextEntries.concat([{ hooks: [{ type: "command", command: hookCommand, ...hookShell(hookCommand) }] }]);
31
- changed = true;
32
- }
33
- if (normalized.changed) changed = true;
34
- if (normalized.changed || nextEntries.length !== entries.length) {
35
- nextHooks[event] = nextEntries;
36
- }
37
- }
38
-
39
- if (!changed) return { changed: false, backupPath: null };
40
-
41
- const nextSettings = { ...settings, hooks: nextHooks };
42
- const backupPath = await writeClaudeSettings({ settingsPath, settings: nextSettings });
43
- return { changed: true, backupPath };
44
- }
45
-
46
- async function removeClaudeHook({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
47
- return removeClaudeHooks({ settingsPath, hookCommand, events: [event] });
48
- }
49
-
50
- async function removeClaudeUsageHooks({ settingsPath, hookCommand }) {
51
- return removeClaudeHooks({ settingsPath, hookCommand, events: CLAUDE_USAGE_EVENTS });
52
- }
53
-
54
- async function removeClaudeHooks({ settingsPath, hookCommand, events }) {
55
- const existing = await readJson(settingsPath);
56
- if (!existing) return { removed: false, skippedReason: "settings-missing" };
57
-
58
- const settings = normalizeSettings(existing);
59
- const hooks = normalizeHooks(settings.hooks);
60
- const nextHooks = { ...hooks };
61
- let removed = false;
62
- for (const event of normalizeEventList(events)) {
63
- const entries = normalizeEntries(hooks[event]);
64
- const nextEntries = [];
65
- for (const entry of entries) {
66
- const res = stripHookFromEntry(entry, hookCommand);
67
- if (res.removed) removed = true;
68
- if (res.entry) nextEntries.push(res.entry);
69
- }
70
- if (nextEntries.length > 0) nextHooks[event] = nextEntries;
71
- else delete nextHooks[event];
72
- }
73
-
74
- if (!removed) return { removed: false, skippedReason: "hook-missing" };
75
-
76
- const nextSettings = { ...settings };
77
- if (Object.keys(nextHooks).length > 0) nextSettings.hooks = nextHooks;
78
- else delete nextSettings.hooks;
79
-
80
- const backupPath = await writeClaudeSettings({ settingsPath, settings: nextSettings });
81
- return { removed: true, skippedReason: null, backupPath };
82
- }
83
-
84
- async function isClaudeHookConfigured({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
85
- return areClaudeHooksConfigured({ settingsPath, hookCommand, events: [event] });
86
- }
87
-
88
- async function areClaudeUsageHooksConfigured({ settingsPath, hookCommand }) {
89
- return areClaudeHooksConfigured({
90
- settingsPath,
91
- hookCommand,
92
- events: CLAUDE_USAGE_EVENTS,
93
- });
94
- }
95
-
96
- async function areClaudeHooksConfigured({ settingsPath, hookCommand, events }) {
97
- const settings = await readJson(settingsPath);
98
- if (!settings || typeof settings !== "object") return false;
99
- const hooks = settings.hooks;
100
- if (!hooks || typeof hooks !== "object") return false;
101
- return normalizeEventList(events).every((event) => {
102
- const entries = normalizeEntries(hooks[event]);
103
- return hasHook(entries, hookCommand);
104
- });
105
- }
106
-
107
- // Generic Session-hook command builder. CodeBuddy CLI is a Claude-Code fork
108
- // and uses the exact same settings.json hook schema, so this function works
109
- // for any source that accepts the `node notify.cjs --source=<name>` contract.
110
- function buildHookCommand(notifyPath, source, options) {
111
- const cmd = typeof notifyPath === "string" ? notifyPath : "";
112
- const src = typeof source === "string" && source ? source : "claude";
113
- return buildNotifyCommand(cmd, src, options);
114
- }
115
-
116
- function buildClaudeHookCommand(notifyPath, options) {
117
- return buildHookCommand(notifyPath, "claude", options);
118
- }
119
-
120
- function normalizeSettings(raw) {
121
- return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
122
- }
123
-
124
- function normalizeHooks(raw) {
125
- return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
126
- }
127
-
128
- function normalizeEntries(raw) {
129
- return Array.isArray(raw) ? raw.slice() : [];
130
- }
131
-
132
- function normalizeEventList(events) {
133
- const values = Array.isArray(events) ? events : [];
134
- return Array.from(new Set(values.filter((event) => typeof event === "string" && event)));
135
- }
136
-
137
- function normalizeCommand(cmd) {
138
- if (Array.isArray(cmd)) return cmd.map((v) => String(v)).join("\u0000");
139
- if (typeof cmd === "string") return cmd.trim();
140
- return null;
141
- }
142
-
143
- function hasHook(entries, hookCommand) {
144
- const shell = hookShell(hookCommand).shell;
145
- const configured = (hook) => normalizeCommand(hook?.command) === normalizeCommand(hookCommand) &&
146
- (!shell || (hook.shell === shell && !Object.hasOwn(hook, "args")));
147
- for (const entry of entries) {
148
- if (!entry || typeof entry !== "object") continue;
149
- if (entry.command && configured(entry)) return true;
150
- const hooks = Array.isArray(entry.hooks) ? entry.hooks : [];
151
- for (const hook of hooks) {
152
- if (hook && configured(hook)) return true;
153
- }
154
- }
155
- return false;
156
- }
157
-
158
- function stripHookFromEntry(entry, hookCommand) {
159
- if (!entry || typeof entry !== "object") return { entry, removed: false };
160
-
161
- if (entry.command) {
162
- if (commandsEqual(entry.command, hookCommand)) return { entry: null, removed: true };
163
- return { entry, removed: false };
164
- }
165
-
166
- const hooks = Array.isArray(entry.hooks) ? entry.hooks : null;
167
- if (!hooks) return { entry, removed: false };
168
-
169
- const nextHooks = hooks.filter((hook) => !commandsEqual(hook?.command, hookCommand));
170
- if (nextHooks.length === hooks.length) return { entry, removed: false };
171
- if (nextHooks.length === 0) return { entry: null, removed: true };
172
-
173
- return { entry: { ...entry, hooks: nextHooks }, removed: true };
174
- }
175
-
176
- function hookShell(command) {
177
- return typeof command === "string" && command.trimStart().startsWith("& '")
178
- ? { shell: "powershell" } : {};
179
- }
180
-
181
- function normalizeEntriesForCommand(entries, hookCommand, event) {
182
- const shell = hookShell(hookCommand);
183
- const repair = (hook) => {
184
- const next = { ...hook, type: "command", command: hookCommand, ...shell };
185
- if (shell.shell) delete next.args;
186
- return next;
187
- };
188
- let changed = false;
189
- const nextEntries = entries.map((entry) => {
190
- if (!entry || typeof entry !== "object") return entry;
191
- if (entry.command && commandsEqual(entry.command, hookCommand)) {
192
- if (entry.type !== "command" || entry.command !== hookCommand || (shell.shell && (entry.shell !== shell.shell || Object.hasOwn(entry, "args")))) {
193
- changed = true;
194
- return repair(entry);
195
- }
196
- return entry;
197
- }
198
- if (!Array.isArray(entry.hooks)) return entry;
199
- let hooksChanged = false;
200
- const nextHooks = entry.hooks.map((hook) => {
201
- if (hook && commandsEqual(hook.command, hookCommand)) {
202
- if (hook.type !== "command" || hook.command !== hookCommand || (shell.shell && (hook.shell !== shell.shell || Object.hasOwn(hook, "args")))) {
203
- hooksChanged = true;
204
- return repair(hook);
205
- }
206
- }
207
- return hook;
208
- });
209
- if (!hooksChanged) return entry;
210
- changed = true;
211
- return { ...entry, hooks: nextHooks };
212
- });
213
- const seen = new Set();
214
- const deduplicated = nextEntries.map((entry) => {
215
- const matcher = entry?.matcher;
216
- const scope = JSON.stringify(event === "Stop" || matcher == null || ["", "*", ".*"].includes(matcher) ? null : matcher);
217
- const keep = (hook) => {
218
- if (!commandsEqual(hook?.command, hookCommand)) return true;
219
- if (seen.has(scope)) { changed = true; return false; }
220
- seen.add(scope);
221
- return true;
222
- };
223
- if (entry?.command) return keep(entry) ? entry : null;
224
- if (!Array.isArray(entry?.hooks)) return entry;
225
- const hooks = entry.hooks.filter(keep);
226
- if (!hooks.length) return null;
227
- return hooks.length === entry.hooks.length ? entry : { ...entry, hooks };
228
- }).filter(Boolean);
229
- return { entries: deduplicated, changed };
230
- }
231
-
232
- function commandsEqual(a, b) {
233
- const left = normalizeCommand(a);
234
- const right = normalizeCommand(b);
235
- return Boolean(left && right && (left === right ||
236
- (notifyIdentity(left) && notifyIdentity(left) === notifyIdentity(right))));
237
- }
238
-
239
- function quoteArg(value) {
240
- const v = typeof value === "string" ? value : "";
241
- if (!v) return '""';
242
- if (/^[A-Za-z0-9_\-./:@]+$/.test(v)) return v;
243
- // Escape backslashes before quotes: a trailing backslash (Windows paths)
244
- // would otherwise escape the closing quote and corrupt the hook command.
245
- return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
246
- }
247
-
248
- async function writeClaudeSettings({ settingsPath, settings }) {
249
- await ensureDir(path.dirname(settingsPath));
250
- let backupPath = null;
251
- try {
252
- const st = await fs.stat(settingsPath);
253
- if (st && st.isFile()) {
254
- backupPath = `${settingsPath}.bak.${new Date().toISOString().replace(/[:.]/g, "-")}`;
255
- await fs.copyFile(settingsPath, backupPath);
256
- }
257
- } catch (_e) {
258
- // Ignore missing file.
259
- }
260
- await writeJson(settingsPath, settings);
261
- return backupPath;
262
- }
263
-
264
- module.exports = {
265
- CLAUDE_USAGE_EVENTS,
266
- upsertClaudeHook,
267
- upsertClaudeUsageHooks,
268
- removeClaudeHook,
269
- removeClaudeUsageHooks,
270
- isClaudeHookConfigured,
271
- areClaudeUsageHooksConfigured,
272
- buildClaudeHookCommand,
273
- buildHookCommand,
274
- // Aliases for callers that want a name unbiased toward Claude (the schema
275
- // applies equally to CodeBuddy and any future Claude-Code fork).
276
- upsertSessionHook: upsertClaudeHook,
277
- removeSessionHook: removeClaudeHook,
278
- isSessionHookConfigured: isClaudeHookConfigured,
279
- };
1
+ const fs = require("node:fs/promises");
2
+ const path = require("node:path");
3
+
4
+ const { ensureDir, readJson, writeJson } = require("./fs");
5
+ const { buildNotifyCommand, notifyIdentity } = require("./notify-command");
6
+
7
+ const DEFAULT_EVENT = "SessionEnd";
8
+ const CLAUDE_USAGE_EVENTS = ["Stop", DEFAULT_EVENT];
9
+
10
+ async function upsertClaudeHook({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
11
+ return upsertClaudeHooks({ settingsPath, hookCommand, events: [event] });
12
+ }
13
+
14
+ async function upsertClaudeUsageHooks({ settingsPath, hookCommand }) {
15
+ return upsertClaudeHooks({ settingsPath, hookCommand, events: CLAUDE_USAGE_EVENTS });
16
+ }
17
+
18
+ async function upsertClaudeHooks({ settingsPath, hookCommand, events }) {
19
+ const existing = await readJson(settingsPath);
20
+ const settings = normalizeSettings(existing);
21
+ const hooks = normalizeHooks(settings.hooks);
22
+ const nextHooks = { ...hooks };
23
+ let changed = false;
24
+
25
+ for (const event of normalizeEventList(events)) {
26
+ const entries = normalizeEntries(hooks[event]);
27
+ const normalized = normalizeEntriesForCommand(entries, hookCommand, event);
28
+ let nextEntries = normalized.entries;
29
+ if (!hasHook(nextEntries, hookCommand)) {
30
+ nextEntries = nextEntries.concat([{ hooks: [{ type: "command", command: hookCommand, ...hookShell(hookCommand) }] }]);
31
+ changed = true;
32
+ }
33
+ if (normalized.changed) changed = true;
34
+ if (normalized.changed || nextEntries.length !== entries.length) {
35
+ nextHooks[event] = nextEntries;
36
+ }
37
+ }
38
+
39
+ if (!changed) return { changed: false, backupPath: null };
40
+
41
+ const nextSettings = { ...settings, hooks: nextHooks };
42
+ const backupPath = await writeClaudeSettings({ settingsPath, settings: nextSettings });
43
+ return { changed: true, backupPath };
44
+ }
45
+
46
+ async function removeClaudeHook({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
47
+ return removeClaudeHooks({ settingsPath, hookCommand, events: [event] });
48
+ }
49
+
50
+ async function removeClaudeUsageHooks({ settingsPath, hookCommand }) {
51
+ return removeClaudeHooks({ settingsPath, hookCommand, events: CLAUDE_USAGE_EVENTS });
52
+ }
53
+
54
+ async function removeClaudeHooks({ settingsPath, hookCommand, events }) {
55
+ const existing = await readJson(settingsPath);
56
+ if (!existing) return { removed: false, skippedReason: "settings-missing" };
57
+
58
+ const settings = normalizeSettings(existing);
59
+ const hooks = normalizeHooks(settings.hooks);
60
+ const nextHooks = { ...hooks };
61
+ let removed = false;
62
+ for (const event of normalizeEventList(events)) {
63
+ const entries = normalizeEntries(hooks[event]);
64
+ const nextEntries = [];
65
+ for (const entry of entries) {
66
+ const res = stripHookFromEntry(entry, hookCommand);
67
+ if (res.removed) removed = true;
68
+ if (res.entry) nextEntries.push(res.entry);
69
+ }
70
+ if (nextEntries.length > 0) nextHooks[event] = nextEntries;
71
+ else delete nextHooks[event];
72
+ }
73
+
74
+ if (!removed) return { removed: false, skippedReason: "hook-missing" };
75
+
76
+ const nextSettings = { ...settings };
77
+ if (Object.keys(nextHooks).length > 0) nextSettings.hooks = nextHooks;
78
+ else delete nextSettings.hooks;
79
+
80
+ const backupPath = await writeClaudeSettings({ settingsPath, settings: nextSettings });
81
+ return { removed: true, skippedReason: null, backupPath };
82
+ }
83
+
84
+ async function isClaudeHookConfigured({ settingsPath, hookCommand, event = DEFAULT_EVENT }) {
85
+ return areClaudeHooksConfigured({ settingsPath, hookCommand, events: [event] });
86
+ }
87
+
88
+ async function areClaudeUsageHooksConfigured({ settingsPath, hookCommand }) {
89
+ return areClaudeHooksConfigured({
90
+ settingsPath,
91
+ hookCommand,
92
+ events: CLAUDE_USAGE_EVENTS,
93
+ });
94
+ }
95
+
96
+ async function areClaudeHooksConfigured({ settingsPath, hookCommand, events }) {
97
+ const settings = await readJson(settingsPath);
98
+ if (!settings || typeof settings !== "object") return false;
99
+ const hooks = settings.hooks;
100
+ if (!hooks || typeof hooks !== "object") return false;
101
+ return normalizeEventList(events).every((event) => {
102
+ const entries = normalizeEntries(hooks[event]);
103
+ return hasHook(entries, hookCommand);
104
+ });
105
+ }
106
+
107
+ // Generic Session-hook command builder. CodeBuddy CLI is a Claude-Code fork
108
+ // and uses the exact same settings.json hook schema, so this function works
109
+ // for any source that accepts the `node notify.cjs --source=<name>` contract.
110
+ function buildHookCommand(notifyPath, source, options) {
111
+ const cmd = typeof notifyPath === "string" ? notifyPath : "";
112
+ const src = typeof source === "string" && source ? source : "claude";
113
+ return buildNotifyCommand(cmd, src, options);
114
+ }
115
+
116
+ function buildClaudeHookCommand(notifyPath, options) {
117
+ return buildHookCommand(notifyPath, "claude", options);
118
+ }
119
+
120
+ function normalizeSettings(raw) {
121
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
122
+ }
123
+
124
+ function normalizeHooks(raw) {
125
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
126
+ }
127
+
128
+ function normalizeEntries(raw) {
129
+ return Array.isArray(raw) ? raw.slice() : [];
130
+ }
131
+
132
+ function normalizeEventList(events) {
133
+ const values = Array.isArray(events) ? events : [];
134
+ return Array.from(new Set(values.filter((event) => typeof event === "string" && event)));
135
+ }
136
+
137
+ function normalizeCommand(cmd) {
138
+ if (Array.isArray(cmd)) return cmd.map((v) => String(v)).join("\u0000");
139
+ if (typeof cmd === "string") return cmd.trim();
140
+ return null;
141
+ }
142
+
143
+ function hasHook(entries, hookCommand) {
144
+ const shell = hookShell(hookCommand).shell;
145
+ const configured = (hook) => normalizeCommand(hook?.command) === normalizeCommand(hookCommand) &&
146
+ (!shell || (hook.shell === shell && !Object.hasOwn(hook, "args")));
147
+ for (const entry of entries) {
148
+ if (!entry || typeof entry !== "object") continue;
149
+ if (entry.command && configured(entry)) return true;
150
+ const hooks = Array.isArray(entry.hooks) ? entry.hooks : [];
151
+ for (const hook of hooks) {
152
+ if (hook && configured(hook)) return true;
153
+ }
154
+ }
155
+ return false;
156
+ }
157
+
158
+ function stripHookFromEntry(entry, hookCommand) {
159
+ if (!entry || typeof entry !== "object") return { entry, removed: false };
160
+
161
+ if (entry.command) {
162
+ if (commandsEqual(entry.command, hookCommand)) return { entry: null, removed: true };
163
+ return { entry, removed: false };
164
+ }
165
+
166
+ const hooks = Array.isArray(entry.hooks) ? entry.hooks : null;
167
+ if (!hooks) return { entry, removed: false };
168
+
169
+ const nextHooks = hooks.filter((hook) => !commandsEqual(hook?.command, hookCommand));
170
+ if (nextHooks.length === hooks.length) return { entry, removed: false };
171
+ if (nextHooks.length === 0) return { entry: null, removed: true };
172
+
173
+ return { entry: { ...entry, hooks: nextHooks }, removed: true };
174
+ }
175
+
176
+ function hookShell(command) {
177
+ return typeof command === "string" && command.trimStart().startsWith("& '")
178
+ ? { shell: "powershell" } : {};
179
+ }
180
+
181
+ function normalizeEntriesForCommand(entries, hookCommand, event) {
182
+ const shell = hookShell(hookCommand);
183
+ const repair = (hook) => {
184
+ const next = { ...hook, type: "command", command: hookCommand, ...shell };
185
+ if (shell.shell) delete next.args;
186
+ return next;
187
+ };
188
+ let changed = false;
189
+ const nextEntries = entries.map((entry) => {
190
+ if (!entry || typeof entry !== "object") return entry;
191
+ if (entry.command && commandsEqual(entry.command, hookCommand)) {
192
+ if (entry.type !== "command" || entry.command !== hookCommand || (shell.shell && (entry.shell !== shell.shell || Object.hasOwn(entry, "args")))) {
193
+ changed = true;
194
+ return repair(entry);
195
+ }
196
+ return entry;
197
+ }
198
+ if (!Array.isArray(entry.hooks)) return entry;
199
+ let hooksChanged = false;
200
+ const nextHooks = entry.hooks.map((hook) => {
201
+ if (hook && commandsEqual(hook.command, hookCommand)) {
202
+ if (hook.type !== "command" || hook.command !== hookCommand || (shell.shell && (hook.shell !== shell.shell || Object.hasOwn(hook, "args")))) {
203
+ hooksChanged = true;
204
+ return repair(hook);
205
+ }
206
+ }
207
+ return hook;
208
+ });
209
+ if (!hooksChanged) return entry;
210
+ changed = true;
211
+ return { ...entry, hooks: nextHooks };
212
+ });
213
+ const seen = new Set();
214
+ const deduplicated = nextEntries.map((entry) => {
215
+ const matcher = entry?.matcher;
216
+ const scope = JSON.stringify(event === "Stop" || matcher == null || ["", "*", ".*"].includes(matcher) ? null : matcher);
217
+ const keep = (hook) => {
218
+ if (!commandsEqual(hook?.command, hookCommand)) return true;
219
+ if (seen.has(scope)) { changed = true; return false; }
220
+ seen.add(scope);
221
+ return true;
222
+ };
223
+ if (entry?.command) return keep(entry) ? entry : null;
224
+ if (!Array.isArray(entry?.hooks)) return entry;
225
+ const hooks = entry.hooks.filter(keep);
226
+ if (!hooks.length) return null;
227
+ return hooks.length === entry.hooks.length ? entry : { ...entry, hooks };
228
+ }).filter(Boolean);
229
+ return { entries: deduplicated, changed };
230
+ }
231
+
232
+ function commandsEqual(a, b) {
233
+ const left = normalizeCommand(a);
234
+ const right = normalizeCommand(b);
235
+ return Boolean(left && right && (left === right ||
236
+ (notifyIdentity(left) && notifyIdentity(left) === notifyIdentity(right))));
237
+ }
238
+
239
+ function quoteArg(value) {
240
+ const v = typeof value === "string" ? value : "";
241
+ if (!v) return '""';
242
+ if (/^[A-Za-z0-9_\-./:@]+$/.test(v)) return v;
243
+ // Escape backslashes before quotes: a trailing backslash (Windows paths)
244
+ // would otherwise escape the closing quote and corrupt the hook command.
245
+ return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
246
+ }
247
+
248
+ async function writeClaudeSettings({ settingsPath, settings }) {
249
+ await ensureDir(path.dirname(settingsPath));
250
+ let backupPath = null;
251
+ try {
252
+ const st = await fs.stat(settingsPath);
253
+ if (st && st.isFile()) {
254
+ backupPath = `${settingsPath}.bak.${new Date().toISOString().replace(/[:.]/g, "-")}`;
255
+ await fs.copyFile(settingsPath, backupPath);
256
+ }
257
+ } catch (_e) {
258
+ // Ignore missing file.
259
+ }
260
+ await writeJson(settingsPath, settings);
261
+ return backupPath;
262
+ }
263
+
264
+ module.exports = {
265
+ CLAUDE_USAGE_EVENTS,
266
+ upsertClaudeHook,
267
+ upsertClaudeUsageHooks,
268
+ removeClaudeHook,
269
+ removeClaudeUsageHooks,
270
+ isClaudeHookConfigured,
271
+ areClaudeUsageHooksConfigured,
272
+ buildClaudeHookCommand,
273
+ buildHookCommand,
274
+ // Aliases for callers that want a name unbiased toward Claude (the schema
275
+ // applies equally to CodeBuddy and any future Claude-Code fork).
276
+ upsertSessionHook: upsertClaudeHook,
277
+ removeSessionHook: removeClaudeHook,
278
+ isSessionHookConfigured: isClaudeHookConfigured,
279
+ };