@ascenda-one/claude-code-hooks 0.1.28 → 0.1.34
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.
- package/README.md +80 -46
- package/dist/cli.js +3170 -618
- package/dist/cli.js.map +1 -1
- package/dist/hookHealth.js +21 -0
- package/dist/hookHealth.js.map +1 -0
- package/dist/launcher.js +14 -0
- package/dist/launcher.js.map +1 -0
- package/dist/liveDoctor.js +27 -0
- package/dist/liveDoctor.js.map +1 -0
- package/dist/liveEvent.js +95 -0
- package/dist/liveEvent.js.map +1 -0
- package/dist/mapClaudeEvent.js +68 -4
- package/dist/mapClaudeEvent.js.map +1 -1
- package/dist/paths.js +30 -1
- package/dist/paths.js.map +1 -1
- package/dist/setup.js +311 -95
- package/dist/setup.js.map +1 -1
- package/dist/types.js +2 -1
- package/dist/types.js.map +1 -1
- package/dist/usageLimitReset.js +207 -0
- package/dist/usageLimitReset.js.map +1 -0
- package/examples/settings.local.json +13 -10
- package/package.json +1 -1
package/dist/setup.js
CHANGED
|
@@ -2,9 +2,11 @@ import * as crypto from "crypto";
|
|
|
2
2
|
import * as fs from "fs";
|
|
3
3
|
import * as os from "os";
|
|
4
4
|
import * as path from "path";
|
|
5
|
-
import { ascendaHome, createPairingSession, defaultTokenFilePath, describeCollectorVersion, getPairingStatus, persistEventWriteToken, readTokenFile, renderSetupDisclosure } from "@ascenda-one/tool-kit";
|
|
5
|
+
import { ascendaHome, createPairingSession, hookRunnerCommand, installHookRunner, terminalStyle, defaultTokenFilePath, describeCollectorVersion, describeHookSetChanges, getPairingStatus, hookSetArgument, hookSetChanges, hookSetOfCommand, initiativesStatusLines, persistEventWriteToken, readTokenFile, renderSetupDisclosure, studyNoticeStatus } from "@ascenda-one/tool-kit";
|
|
6
6
|
import { DEFAULT_API_BASE_URL, envOverride, localOnlyInstall } from "./config.js";
|
|
7
|
-
import {
|
|
7
|
+
import { describeAge, readLastHook, resolveHookNode } from "./hookHealth.js";
|
|
8
|
+
import { LAUNCHER_OPTIONS } from "./launcher.js";
|
|
9
|
+
import { credentialsFilePath, hookBinPath, selfCommand, hookBundlePath, hookNoNodePath, hookNodeRecordPath, readCredentials, removeCredentials, writeCredentials } from "./paths.js";
|
|
8
10
|
import { ASCENDA_TOOL_TYPE } from "./types.js";
|
|
9
11
|
/**
|
|
10
12
|
* Hook events worth registering.
|
|
@@ -25,13 +27,38 @@ import { ASCENDA_TOOL_TYPE } from "./types.js";
|
|
|
25
27
|
* `PostToolUseFailure` is where Claude Code reports a tool call that failed; a
|
|
26
28
|
* failure never reaches `PostToolUse`. Leaving it out drops every failed call.
|
|
27
29
|
*
|
|
30
|
+
* `StopFailure` fires instead of `Stop` when an API error (a rate limit, an
|
|
31
|
+
* overloaded server, an expired login) ends the turn. It sends nothing to
|
|
32
|
+
* Ascenda: it exists for the live signal alone, which otherwise has no way to
|
|
33
|
+
* learn the turn is over and holds the gauge up until the session goes stale.
|
|
34
|
+
* That makes it the one registered hook the mapper deliberately maps to
|
|
35
|
+
* nothing, and `emitLive` in cli.ts is its other half. Its rate is bounded by
|
|
36
|
+
* API errors, so it costs almost nothing.
|
|
37
|
+
*
|
|
28
38
|
* `SessionEnd` closes the session `SessionStart` opened. It writes the end to
|
|
29
39
|
* the outbox and never waits on the network, so it fits the shared 1.5s
|
|
30
40
|
* Claude Code gives these hooks by default. It gets the same 5s timeout as
|
|
31
41
|
* the rest anyway: Node's startup, or npx resolving the package on the plugin
|
|
32
42
|
* channel, can eat most of 1.5s on a slow machine.
|
|
43
|
+
*
|
|
44
|
+
* `SubagentStart` and `SubagentStop` mark a subagent's span under its parent
|
|
45
|
+
* session. They're registered with no matcher, so every agent type fires them,
|
|
46
|
+
* including the empty type Claude Code's internal agents stop with. Their rate
|
|
47
|
+
* is one pair per subagent run, well below tool volume.
|
|
48
|
+
*/
|
|
49
|
+
const HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
|
|
50
|
+
/**
|
|
51
|
+
* The version of {@link HOOK_EVENTS}, written onto every registered command
|
|
52
|
+
* as `--hook-set <n>` and copied onto each live signal, so the desktop app
|
|
53
|
+
* can tell an install that predates `StopFailure` and say how to upgrade it.
|
|
54
|
+
*
|
|
55
|
+
* Set 1 is every registration without the flag. Set 2 added `StopFailure`
|
|
56
|
+
* and `Notification`, eleven events. Set 3 is the thirteen above, adding
|
|
57
|
+
* `SubagentStart` and `SubagentStop`. Bump this whenever the list changes,
|
|
58
|
+
* along with the plugin's `hooks/hooks.json` and `kCurrentHookSets` in the
|
|
59
|
+
* app.
|
|
33
60
|
*/
|
|
34
|
-
const
|
|
61
|
+
export const HOOK_SET = 3;
|
|
35
62
|
/**
|
|
36
63
|
* Claude Code's default timeout for `command` hooks is 600s. Telemetry that
|
|
37
64
|
* cannot complete in a few seconds is not worth waiting for, and a hung request
|
|
@@ -47,12 +74,13 @@ const HOOK_MARKER = "ascenda-claude-hook";
|
|
|
47
74
|
* its mapper actually writes: `modelId`/`modelClass` on SessionStart, the
|
|
48
75
|
* `autonomyMode` posture on most events, `gitAction` and `milestoneKind` off a
|
|
49
76
|
* recognised bash command, `linesChangedBucket` and `userModified` on a file
|
|
50
|
-
* write,
|
|
77
|
+
* write, `interruptionKind` on a Notification, and `subagentId` and
|
|
78
|
+
* `subagentClass` on a subagent's start and stop.
|
|
51
79
|
*
|
|
52
80
|
* It omits `context` deliberately: compaction and pressure events are sent,
|
|
53
81
|
* but no occupancy figure rides them, and the context line would claim one.
|
|
54
82
|
*/
|
|
55
|
-
export const SENDS = ["model", "posture", "git", "edits", "waiting"];
|
|
83
|
+
export const SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
|
|
56
84
|
const USAGE = `ascenda-claude-hook setup — wire Claude Code to Ascenda telemetry
|
|
57
85
|
|
|
58
86
|
npx @ascenda-one/claude-code-hooks setup [options]
|
|
@@ -60,9 +88,12 @@ const USAGE = `ascenda-claude-hook setup — wire Claude Code to Ascenda telemet
|
|
|
60
88
|
npx @ascenda-one/claude-code-hooks doctor
|
|
61
89
|
npx @ascenda-one/claude-code-hooks pair [--tool-type <type>]
|
|
62
90
|
npx @ascenda-one/claude-code-hooks uninstall
|
|
91
|
+
npx @ascenda-one/claude-code-hooks object <purpose> [--undo]
|
|
63
92
|
|
|
64
93
|
doctor prints the send journal, outbox and one live round trip
|
|
65
94
|
pair prints a code to paste into the app, then waits for confirmation
|
|
95
|
+
object stop being counted for a purpose your organisation counts unless
|
|
96
|
+
you object, from the next report; --undo reverses it
|
|
66
97
|
|
|
67
98
|
Options
|
|
68
99
|
--api-base-url <url> ingest host (default ${DEFAULT_API_BASE_URL})
|
|
@@ -71,7 +102,7 @@ Options
|
|
|
71
102
|
--token <eventWriteToken> reuse an existing token (stored 0600, never printed)
|
|
72
103
|
--no-pair install without pairing: local features on, nothing sent
|
|
73
104
|
(--no-pairing is accepted too)
|
|
74
|
-
--scope project
|
|
105
|
+
--scope user|project where hooks are registered (default user: every project)
|
|
75
106
|
--project-dir <path> project root for --scope project (default cwd)
|
|
76
107
|
--dry-run print what would change, write nothing
|
|
77
108
|
-h, --help
|
|
@@ -90,29 +121,38 @@ export async function runSetup(argv) {
|
|
|
90
121
|
return 0;
|
|
91
122
|
}
|
|
92
123
|
if (options.action === "status")
|
|
93
|
-
return printStatus(options);
|
|
124
|
+
return await printStatus(options);
|
|
94
125
|
if (options.action === "uninstall")
|
|
95
126
|
return uninstall(options);
|
|
96
127
|
const apiBaseUrl = (options.apiBaseUrl ?? readCredentials()?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
97
|
-
|
|
128
|
+
const ui = terminalStyle();
|
|
129
|
+
const row = (tone, label, value) => console.log(` ${ui.mark(tone)} ${label.padEnd(12)} ${value}`);
|
|
130
|
+
const detail = (label, value) => console.log(ui.dim(` ${label.padEnd(12)} ${value}`));
|
|
131
|
+
console.log(`${ui.bold("Ascenda setup")} ${ui.dim(`· Claude Code · ${apiBaseUrl}`)}`);
|
|
98
132
|
// Before pairing, not after: pairing is where the consent is given, and a
|
|
99
133
|
// statement printed underneath a completed pairing is a notification rather
|
|
100
134
|
// than a disclosure.
|
|
101
135
|
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
136
|
+
// A run that will not pair still prints it, because someone choosing to
|
|
137
|
+
// stay local is entitled to know what pairing would cost. But it goes at
|
|
138
|
+
// the end, under "pairing is optional": printed first, its "what this
|
|
139
|
+
// sends" read as what had just been installed, and the install that
|
|
140
|
+
// followed read as a degraded one.
|
|
141
|
+
if (options.pair)
|
|
142
|
+
console.log(`\n${renderSetupDisclosure({ sends: SENDS, displayName: "Claude Code" })}\n`);
|
|
143
|
+
else
|
|
144
|
+
console.log("");
|
|
109
145
|
const identity = await resolveIdentity(apiBaseUrl, options);
|
|
110
146
|
const unpaired = identity.pairing === "local-only";
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
147
|
+
// Asked for, as against tried and failed. The first is a finished install;
|
|
148
|
+
// the second is a pairing that did not happen and has to say so.
|
|
149
|
+
const chosenLocal = unpaired && !options.pair;
|
|
114
150
|
const binary = installBinary(options.dryRun);
|
|
115
|
-
|
|
151
|
+
const node = options.dryRun || process.platform === "win32" ? undefined : resolveHookNode();
|
|
152
|
+
if (node?.problem)
|
|
153
|
+
row("bad", "hook binary", `${tidyHome(binary)}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
|
|
154
|
+
else
|
|
155
|
+
row("ok", "hook binary", `${tidyHome(binary)}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
|
|
116
156
|
if (!options.dryRun) {
|
|
117
157
|
const now = new Date().toISOString();
|
|
118
158
|
writeCredentials({
|
|
@@ -124,38 +164,107 @@ export async function runSetup(argv) {
|
|
|
124
164
|
...(unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now })
|
|
125
165
|
});
|
|
126
166
|
}
|
|
127
|
-
|
|
167
|
+
if (isHomeProject(options)) {
|
|
168
|
+
detail("scope", "user (a project install in the home folder only loads when Claude Code starts there)");
|
|
169
|
+
options.scope = "user";
|
|
170
|
+
}
|
|
128
171
|
const settingsFile = settingsPath(options);
|
|
172
|
+
const before = ourHookSets(readSettingsFile(settingsFile));
|
|
129
173
|
const written = writeSettings(settingsFile, binary, options.dryRun);
|
|
130
174
|
if (written === null)
|
|
131
175
|
return 1;
|
|
132
|
-
|
|
176
|
+
const reach = options.scope === "user" ? "every project" : "this project only";
|
|
177
|
+
row("ok", "hooks", `${tidyHome(settingsFile)} ${ui.dim(`(${HOOK_EVENTS.length} events, ${reach}${written ? "" : ", already current"})`)}`);
|
|
178
|
+
const changes = describeHookSetChanges(hookSetChanges(before, HOOK_EVENTS), HOOK_SET);
|
|
179
|
+
if (changes)
|
|
180
|
+
detail("", changes);
|
|
181
|
+
// Both scopes fire. An install in the other one means every event runs
|
|
182
|
+
// twice and every count doubles, and an older install there may name a
|
|
183
|
+
// binary this run just replaced. Our entries are told apart from anyone
|
|
184
|
+
// else's by the marker, so they are moved rather than reported: this run's
|
|
185
|
+
// file keeps them, the other loses them, and its other hooks are untouched.
|
|
186
|
+
const otherFiles = new Set([
|
|
187
|
+
settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" }),
|
|
188
|
+
// The home folder's project file, where a project-scope setup run from
|
|
189
|
+
// `~` used to put them.
|
|
190
|
+
path.join(os.homedir(), ".claude", "settings.local.json")
|
|
191
|
+
]);
|
|
192
|
+
otherFiles.delete(settingsFile);
|
|
193
|
+
for (const otherFile of otherFiles) {
|
|
194
|
+
if (ourHookSets(readSettingsFile(otherFile)).size === 0)
|
|
195
|
+
continue;
|
|
196
|
+
if (options.dryRun) {
|
|
197
|
+
row("info", "moved", `would remove the copy in ${tidyHome(otherFile)}, so each event runs once`);
|
|
198
|
+
}
|
|
199
|
+
else if (removeOurHooks(otherFile)) {
|
|
200
|
+
row("ok", "moved", `removed the copy in ${tidyHome(otherFile)}, so each event runs once ${ui.dim("(backup beside it)")}`);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
row("warn", "note", `${tidyHome(otherFile)} registers these hooks too, so each event runs twice.`);
|
|
204
|
+
detail("", "Remove the ascenda-claude-hook entries from one of the two files.");
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (chosenLocal) {
|
|
208
|
+
row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
|
|
209
|
+
}
|
|
210
|
+
else if (unpaired) {
|
|
211
|
+
row("warn", "pairing", `not paired: ${identity.reason}`);
|
|
212
|
+
if (identity.hint)
|
|
213
|
+
detail("", identity.hint);
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
row("ok", "pairing", `${identity.toolInstallationId}${ui.dim(identity.pairing === "new" ? " (new)" : " (existing)")}`);
|
|
217
|
+
}
|
|
218
|
+
if (unpaired)
|
|
219
|
+
detail("installation", `${identity.toolInstallationId} (kept, so pairing later attaches to it)`);
|
|
220
|
+
detail("credentials", tidyHome(credentialsFilePath()));
|
|
133
221
|
if (options.dryRun) {
|
|
134
|
-
console.log("\nDry run
|
|
222
|
+
console.log("\nDry run. Nothing was written.");
|
|
135
223
|
return 0;
|
|
136
224
|
}
|
|
137
|
-
// Which half is live, spelled out
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
console.log("
|
|
147
|
-
|
|
225
|
+
// Which half is live, spelled out, and in the right key. A failed pairing
|
|
226
|
+
// that reads like a success is how someone comes to believe they paired;
|
|
227
|
+
// a chosen local install that reads like a failure is how someone new
|
|
228
|
+
// decides the install broke. The screen saver needs no pairing at all.
|
|
229
|
+
const self = selfCommand();
|
|
230
|
+
const next = (label, value) => console.log(` ${ui.bold(label.padEnd(6))} ${value}`);
|
|
231
|
+
console.log("");
|
|
232
|
+
if (chosenLocal) {
|
|
233
|
+
console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
|
|
234
|
+
console.log(" They run on this machine and need no account or pairing.");
|
|
235
|
+
}
|
|
236
|
+
else if (unpaired) {
|
|
237
|
+
console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
|
|
238
|
+
console.log(` Your sessions won't reach Ascenda's servers until pairing completes.`);
|
|
148
239
|
}
|
|
149
240
|
else {
|
|
150
|
-
console.log("
|
|
241
|
+
console.log(`${ui.mark("ok")} ${ui.bold("Done.")} Paired, and the hooks are installed.`);
|
|
242
|
+
}
|
|
243
|
+
console.log("");
|
|
244
|
+
next("Next", `${restartLine(options)} Then type ${ui.cyan("/hooks")}: Ascenda's are under ${options.scope === "user" ? "User" : "Local"}.`);
|
|
245
|
+
next("Check", ui.cyan(`${self} doctor`));
|
|
246
|
+
if (unpaired)
|
|
247
|
+
next(chosenLocal ? "Pair" : "Retry", `${ui.cyan(`${self} pair`)}${chosenLocal ? ui.dim(" (optional)") : ""}`);
|
|
248
|
+
if (chosenLocal) {
|
|
249
|
+
console.log("");
|
|
250
|
+
console.log(ui.dim(" Pairing sends the details below to Ascenda's servers, under the account the"));
|
|
251
|
+
console.log(ui.dim(" Ascenda app is signed in to when you confirm the code, so your sessions appear"));
|
|
252
|
+
console.log(ui.dim(" in the app. Until you pair, nothing leaves this machine."));
|
|
253
|
+
console.log("");
|
|
254
|
+
console.log(ui.dim(renderSetupDisclosure({ sends: SENDS, displayName: "Claude Code" }).split("\n").map((line) => ` ${line}`).join("\n")));
|
|
151
255
|
}
|
|
152
|
-
console.log(`Check anytime: npx @ascenda-one/claude-code-hooks status`);
|
|
153
256
|
return 0;
|
|
154
257
|
}
|
|
155
258
|
// ------------------------------------------------------------------ args ---
|
|
156
259
|
function parseArgs(argv) {
|
|
260
|
+
// User scope by default. The hooks drive surfaces that belong to the whole
|
|
261
|
+
// machine (the screen saver, the desktop app's gauges), so registering them
|
|
262
|
+
// in one project's file left every other project dark. And the common case
|
|
263
|
+
// made it worse: setup run from the home folder wrote
|
|
264
|
+
// ~/.claude/settings.local.json, which Claude Code reads only when it is
|
|
265
|
+
// started in the home folder itself.
|
|
157
266
|
const options = {
|
|
158
|
-
scope: "
|
|
267
|
+
scope: "user",
|
|
159
268
|
projectDir: process.env.CLAUDE_PROJECT_DIR ?? process.cwd(),
|
|
160
269
|
dryRun: false,
|
|
161
270
|
pair: true,
|
|
@@ -227,6 +336,15 @@ function parseArgs(argv) {
|
|
|
227
336
|
}
|
|
228
337
|
return options;
|
|
229
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* The home folder's `.claude/settings.local.json` is a project file for the
|
|
341
|
+
* project at `~`, not a user file: it loads only when Claude Code is started
|
|
342
|
+
* in the home folder. A project-scope install there looks right in `/hooks`
|
|
343
|
+
* from `~` and is missing everywhere else, so it is treated as user scope.
|
|
344
|
+
*/
|
|
345
|
+
function isHomeProject(options) {
|
|
346
|
+
return options.scope === "project" && path.resolve(options.projectDir) === path.resolve(os.homedir());
|
|
347
|
+
}
|
|
230
348
|
/**
|
|
231
349
|
* Reuse an existing pairing when one is already on the machine, otherwise
|
|
232
350
|
* create one. The local dev server auto-confirms; a real backend needs the
|
|
@@ -316,25 +434,30 @@ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
|
|
|
316
434
|
}
|
|
317
435
|
return { reason: "no confirmation within 5 minutes" };
|
|
318
436
|
}
|
|
437
|
+
function tidyHome(file) {
|
|
438
|
+
const home = os.homedir();
|
|
439
|
+
return file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
|
|
440
|
+
}
|
|
441
|
+
function restartLine(options) {
|
|
442
|
+
return options.scope === "user"
|
|
443
|
+
? "Restart Claude Code to load the hooks."
|
|
444
|
+
: "Restart Claude Code in this project to load the hooks.";
|
|
445
|
+
}
|
|
319
446
|
// ---------------------------------------------------------------- binary ---
|
|
320
447
|
/**
|
|
321
|
-
* Copy the running bundle to ~/.ascenda/bin
|
|
322
|
-
* temp directory that is not stable across
|
|
448
|
+
* Copy the running bundle to ~/.ascenda/bin, with the launcher that runs it.
|
|
449
|
+
* `npx` caches its download in a temp directory that is not stable across
|
|
450
|
+
* runs, so hooks must not point at it.
|
|
451
|
+
*
|
|
452
|
+
* The launcher is what the hook commands name; see launcher.ts for why a
|
|
453
|
+
* shell script stands between Claude Code and Node. It is seeded with the
|
|
454
|
+
* Node running this setup, and finds another on its own if that one goes.
|
|
455
|
+
*
|
|
456
|
+
* Windows has no `/bin/sh`, so it keeps the earlier shape: the bundle at the
|
|
457
|
+
* command's path, run by the Node that ran setup.
|
|
323
458
|
*/
|
|
324
459
|
function installBinary(dryRun) {
|
|
325
|
-
|
|
326
|
-
if (dryRun)
|
|
327
|
-
return target;
|
|
328
|
-
const source = process.argv[1];
|
|
329
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
330
|
-
// Same file when re-running an already-installed binary; copying it onto
|
|
331
|
-
// itself would truncate it.
|
|
332
|
-
if (path.resolve(source) !== path.resolve(target)) {
|
|
333
|
-
fs.copyFileSync(source, target);
|
|
334
|
-
}
|
|
335
|
-
if (process.platform !== "win32")
|
|
336
|
-
fs.chmodSync(target, 0o755);
|
|
337
|
-
return target;
|
|
460
|
+
return installHookRunner({ ...LAUNCHER_OPTIONS, dryRun });
|
|
338
461
|
}
|
|
339
462
|
// -------------------------------------------------------------- settings ---
|
|
340
463
|
function settingsPath(options) {
|
|
@@ -367,7 +490,7 @@ export function writeSettings(settingsFile, binary, dryRun) {
|
|
|
367
490
|
const hooks = { ...(settings.hooks ?? {}) };
|
|
368
491
|
for (const event of HOOK_EVENTS) {
|
|
369
492
|
const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
|
|
370
|
-
hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
|
|
493
|
+
hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}${hookSetArgument(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
|
|
371
494
|
}
|
|
372
495
|
const updated = { ...settings, hooks };
|
|
373
496
|
const serialised = `${JSON.stringify(updated, null, 2)}\n`;
|
|
@@ -386,12 +509,40 @@ export function writeSettings(settingsFile, binary, dryRun) {
|
|
|
386
509
|
return true;
|
|
387
510
|
}
|
|
388
511
|
/**
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
512
|
+
* The launcher alone: it finds Node itself (launcher.ts). Naming Node here
|
|
513
|
+
* pinned the exact version that ran setup, and a version manager removes
|
|
514
|
+
* that path long before anyone thinks to re-run setup.
|
|
515
|
+
*
|
|
516
|
+
* Windows keeps the pinned interpreter, having no launcher.
|
|
392
517
|
*/
|
|
393
518
|
function hookCommand(binary) {
|
|
394
|
-
return
|
|
519
|
+
return hookRunnerCommand(binary);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Takes our entries out of one settings file, keeping everything else.
|
|
523
|
+
* Returns false when the file could not be read or written.
|
|
524
|
+
*/
|
|
525
|
+
function removeOurHooks(settingsFile) {
|
|
526
|
+
try {
|
|
527
|
+
const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
528
|
+
const hooks = { ...(settings.hooks ?? {}) };
|
|
529
|
+
for (const event of Object.keys(hooks)) {
|
|
530
|
+
const kept = hooks[event].filter((group) => !isOurs(group));
|
|
531
|
+
if (kept.length)
|
|
532
|
+
hooks[event] = kept;
|
|
533
|
+
else
|
|
534
|
+
delete hooks[event];
|
|
535
|
+
}
|
|
536
|
+
const updated = { ...settings, hooks };
|
|
537
|
+
if (!Object.keys(hooks).length)
|
|
538
|
+
delete updated.hooks;
|
|
539
|
+
fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
|
|
540
|
+
fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}\n`, "utf8");
|
|
541
|
+
return true;
|
|
542
|
+
}
|
|
543
|
+
catch {
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
395
546
|
}
|
|
396
547
|
function isOurs(group) {
|
|
397
548
|
return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
|
|
@@ -420,19 +571,61 @@ export function findStaleHookCommands(settings, binary) {
|
|
|
420
571
|
return [...stale];
|
|
421
572
|
}
|
|
422
573
|
// --------------------------------------------------------------- lifecycle ---
|
|
574
|
+
/** A settings file, or an empty one when it is missing or unparseable. */
|
|
575
|
+
function readSettingsFile(settingsFile) {
|
|
576
|
+
try {
|
|
577
|
+
return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
return {};
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
/** Each event with one of our hooks, mapped to the hook set its command names. */
|
|
584
|
+
export function ourHookSets(settings) {
|
|
585
|
+
const sets = new Map();
|
|
586
|
+
for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
|
|
587
|
+
for (const group of groups ?? []) {
|
|
588
|
+
if (!isOurs(group))
|
|
589
|
+
continue;
|
|
590
|
+
for (const entry of group.hooks ?? []) {
|
|
591
|
+
if (typeof entry?.command !== "string")
|
|
592
|
+
continue;
|
|
593
|
+
const set = hookSetOfCommand(entry.command);
|
|
594
|
+
sets.set(event, Math.min(set, sets.get(event) ?? set));
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return sets;
|
|
599
|
+
}
|
|
423
600
|
/** Reads a settings file and counts our hooks in it. Missing or unparseable reads as none. */
|
|
424
601
|
function countRegistered(settingsFile, binary) {
|
|
425
|
-
const settings = (
|
|
426
|
-
try {
|
|
427
|
-
return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
428
|
-
}
|
|
429
|
-
catch {
|
|
430
|
-
return {};
|
|
431
|
-
}
|
|
432
|
-
})();
|
|
602
|
+
const settings = readSettingsFile(settingsFile);
|
|
433
603
|
return { settings, registered: HOOK_EVENTS.filter((event) => (settings.hooks?.[event] ?? []).some(isOurs)).length };
|
|
434
604
|
}
|
|
435
|
-
|
|
605
|
+
/**
|
|
606
|
+
* Where our hooks are registered, for `doctor`: the user file, the project
|
|
607
|
+
* file for `projectDir`, and the home folder's project file, each with a
|
|
608
|
+
* count. Only files that carry at least one of ours are listed.
|
|
609
|
+
*/
|
|
610
|
+
export function registrationSummary(projectDir) {
|
|
611
|
+
const binary = hookBinPath();
|
|
612
|
+
const files = new Map([
|
|
613
|
+
[settingsPath({ scope: "user", projectDir }), "user"],
|
|
614
|
+
[settingsPath({ scope: "project", projectDir }), "project"],
|
|
615
|
+
[path.join(os.homedir(), ".claude", "settings.local.json"), "project"]
|
|
616
|
+
]);
|
|
617
|
+
const found = [];
|
|
618
|
+
for (const [file, scope] of files) {
|
|
619
|
+
const { registered } = countRegistered(file, binary);
|
|
620
|
+
if (registered === 0)
|
|
621
|
+
continue;
|
|
622
|
+
found.push({ file, scope, registered, homeProject: path.resolve(file) === path.resolve(os.homedir(), ".claude", "settings.local.json") });
|
|
623
|
+
}
|
|
624
|
+
return found;
|
|
625
|
+
}
|
|
626
|
+
/** How many events setup registers, for the summary above. */
|
|
627
|
+
export const REGISTERED_EVENT_COUNT = HOOK_EVENTS.length;
|
|
628
|
+
async function printStatus(options) {
|
|
436
629
|
const credentials = readCredentials();
|
|
437
630
|
const settingsFile = settingsPath(options);
|
|
438
631
|
const binary = hookBinPath();
|
|
@@ -441,11 +634,11 @@ function printStatus(options) {
|
|
|
441
634
|
const here = countRegistered(settingsFile, binary);
|
|
442
635
|
const settings = here.settings;
|
|
443
636
|
const registered = here.registered;
|
|
444
|
-
// `status` checks one scope — the same default `setup` writes to
|
|
445
|
-
//
|
|
446
|
-
//
|
|
447
|
-
//
|
|
448
|
-
//
|
|
637
|
+
// `status` checks one scope — the same default `setup` writes to. A
|
|
638
|
+
// machine set up in the other one used to report a flat `0/7 registered`,
|
|
639
|
+
// which reads as "the install failed" rather than "you are looking in the
|
|
640
|
+
// other place". Look in the other scope before saying nothing is there,
|
|
641
|
+
// and name where it actually is.
|
|
449
642
|
const otherScope = { ...options, scope: options.scope === "user" ? "project" : "user" };
|
|
450
643
|
const otherFile = settingsPath(otherScope);
|
|
451
644
|
const elsewhere = registered === 0 && otherFile !== settingsFile
|
|
@@ -466,19 +659,56 @@ function printStatus(options) {
|
|
|
466
659
|
: "— no token for this pairing, so nothing can be sent"}`);
|
|
467
660
|
console.log("local features active — the session prompts and the live socket signal need no pairing");
|
|
468
661
|
console.log(`hook binary ${fs.existsSync(binary) ? binary : "— not installed"}`);
|
|
662
|
+
// Registered is not the same as runnable. Claude Code swallows a hook that
|
|
663
|
+
// cannot start, so "13/13 registered" used to sit beside a machine where
|
|
664
|
+
// no hook had ever run. Asked with a bare PATH, the way a Dock-launched
|
|
665
|
+
// Claude Code would ask.
|
|
666
|
+
const node = process.platform === "win32" ? undefined : resolveHookNode();
|
|
667
|
+
if (node) {
|
|
668
|
+
console.log(node.problem
|
|
669
|
+
? `node — ${node.problem}. Install Node 20 or newer, then run setup again`
|
|
670
|
+
: `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
|
|
671
|
+
}
|
|
672
|
+
const last = readLastHook();
|
|
673
|
+
console.log(last
|
|
674
|
+
? `last hook ${last.event}, ${describeAge(Date.now() - Date.parse(last.at))}`
|
|
675
|
+
: "last hook — none has run yet. Start Claude Code (restart it if it was open during setup), then check /hooks");
|
|
469
676
|
console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
|
|
470
677
|
if (elsewhere && elsewhere.registered > 0) {
|
|
471
678
|
console.log(` ${elsewhere.registered}/${HOOK_EVENTS.length} found in ${otherFile} (--scope ${otherScope.scope})`);
|
|
472
679
|
}
|
|
680
|
+
const where = registered > 0 ? { settings, scope: options.scope } : elsewhere && elsewhere.registered > 0 ? { settings: elsewhere.settings, scope: otherScope.scope } : undefined;
|
|
681
|
+
if (where) {
|
|
682
|
+
const oldest = Math.min(...ourHookSets(where.settings).values());
|
|
683
|
+
console.log(oldest < HOOK_SET
|
|
684
|
+
? `hook set ${oldest}, this version registers ${HOOK_SET}. Upgrade: npx @ascenda-one/claude-code-hooks setup${where.scope === "user" ? " --scope user" : ""}`
|
|
685
|
+
: `hook set ${HOOK_SET} (current)`);
|
|
686
|
+
}
|
|
473
687
|
if (stale.length) {
|
|
474
688
|
console.log(`stale hooks ${stale.length} not pointing at the installed binary — each one fails silently per event:`);
|
|
475
689
|
for (const command of stale)
|
|
476
690
|
console.log(` ${command}`);
|
|
477
691
|
console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
|
|
478
692
|
}
|
|
693
|
+
// For the person at the keyboard only. Nothing here is fetched for an
|
|
694
|
+
// install that isn't paired, and nothing from it reaches a hook or an agent.
|
|
695
|
+
const tokenValue = unpaired ? undefined : (tokenFile ? readTokenFile(tokenFile) : undefined) ?? envOverride("ASCENDA_EVENT_WRITE_TOKEN") ?? undefined;
|
|
696
|
+
const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
697
|
+
const [initiativeLines, notices] = await Promise.all([
|
|
698
|
+
initiativesStatusLines({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `${selfCommand()} pair` }),
|
|
699
|
+
studyNoticeStatus({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: "npx @ascenda-one/claude-code-hooks" })
|
|
700
|
+
]);
|
|
701
|
+
console.log("");
|
|
702
|
+
for (const line of initiativeLines)
|
|
703
|
+
console.log(line);
|
|
704
|
+
for (const line of notices.lines)
|
|
705
|
+
console.log(line);
|
|
706
|
+
// Only a person at a terminal has been shown the notice; see `markShown`.
|
|
707
|
+
if (process.stdout.isTTY)
|
|
708
|
+
await notices.markShown();
|
|
479
709
|
if (unpaired) {
|
|
480
|
-
console.log("\
|
|
481
|
-
console.log(
|
|
710
|
+
console.log("\nNot paired, which the screen saver and the live view don't need.");
|
|
711
|
+
console.log(`To send your sessions to Ascenda's servers, so they appear in the app: ${selfCommand()} pair`);
|
|
482
712
|
}
|
|
483
713
|
// User settings apply in every project, so hooks found there answer a
|
|
484
714
|
// project-scope check and the install is not broken. The reverse does not
|
|
@@ -486,7 +716,7 @@ function printStatus(options) {
|
|
|
486
716
|
// user` check that finds only project hooks still reports them missing.
|
|
487
717
|
const wired = registered === HOOK_EVENTS.length
|
|
488
718
|
|| (options.scope === "project" && elsewhere?.registered === HOOK_EVENTS.length);
|
|
489
|
-
const healthy = credentials?.toolInstallationId && wired && fs.existsSync(binary) && !stale.length;
|
|
719
|
+
const healthy = credentials?.toolInstallationId && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
|
|
490
720
|
return healthy ? 0 : 1;
|
|
491
721
|
}
|
|
492
722
|
/**
|
|
@@ -510,32 +740,18 @@ function uninstall(options) {
|
|
|
510
740
|
const unpaired = localOnlyInstall();
|
|
511
741
|
const settingsFile = settingsPath(options);
|
|
512
742
|
if (fs.existsSync(settingsFile)) {
|
|
513
|
-
|
|
514
|
-
const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
515
|
-
const hooks = { ...(settings.hooks ?? {}) };
|
|
516
|
-
for (const event of Object.keys(hooks)) {
|
|
517
|
-
const kept = hooks[event].filter((group) => !isOurs(group));
|
|
518
|
-
if (kept.length)
|
|
519
|
-
hooks[event] = kept;
|
|
520
|
-
else
|
|
521
|
-
delete hooks[event];
|
|
522
|
-
}
|
|
523
|
-
const updated = { ...settings, hooks };
|
|
524
|
-
if (!Object.keys(hooks).length)
|
|
525
|
-
delete updated.hooks;
|
|
526
|
-
fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
|
|
527
|
-
fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}\n`, "utf8");
|
|
528
|
-
console.log(`hooks removed from ${settingsFile}`);
|
|
529
|
-
}
|
|
530
|
-
catch {
|
|
743
|
+
if (!removeOurHooks(settingsFile)) {
|
|
531
744
|
console.error(`could not parse ${settingsFile} — remove the ascenda hook entries by hand`);
|
|
532
745
|
return 1;
|
|
533
746
|
}
|
|
747
|
+
console.log(`hooks removed from ${settingsFile}`);
|
|
534
748
|
}
|
|
535
|
-
const
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
749
|
+
for (const file of [hookBinPath(), hookBundlePath(), hookNodeRecordPath(), hookNoNodePath()]) {
|
|
750
|
+
if (!fs.existsSync(file))
|
|
751
|
+
continue;
|
|
752
|
+
fs.rmSync(file);
|
|
753
|
+
if (file === hookBinPath() || file === hookBundlePath())
|
|
754
|
+
console.log(`removed ${file}`);
|
|
539
755
|
}
|
|
540
756
|
const credentialsFile = credentialsFilePath();
|
|
541
757
|
if (fs.existsSync(credentialsFile)) {
|