@yougrowai/node 0.4.0 → 0.6.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.
- package/README.md +125 -3
- package/dist/cjs/index.d.ts +35 -0
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/server.d.ts +1 -1
- package/dist/index.d.ts +35 -0
- package/dist/index.js +2 -2
- package/dist/server.d.ts +1 -1
- package/dist/workHook/cli.d.ts +11 -0
- package/dist/workHook/cli.js +152 -0
- package/dist/workHook/events.d.ts +62 -0
- package/dist/workHook/events.js +136 -0
- package/dist/workHook/git.d.ts +35 -0
- package/dist/workHook/git.js +124 -0
- package/dist/workHook/install.d.ts +87 -0
- package/dist/workHook/install.js +339 -0
- package/dist/workHook/keychain.d.ts +71 -0
- package/dist/workHook/keychain.js +173 -0
- package/dist/workHook/run.d.ts +83 -0
- package/dist/workHook/run.js +427 -0
- package/dist/workHook/scan.d.ts +63 -0
- package/dist/workHook/scan.js +285 -0
- package/dist/workHook/state.d.ts +144 -0
- package/dist/workHook/state.js +243 -0
- package/dist/workHook/transcript.d.ts +123 -0
- package/dist/workHook/transcript.js +415 -0
- package/package.json +2 -1
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { forgetKey, isWorkKey, KEY_SERVICE, readSavedKey, saveKey, STORE_WORDS, storesFor } from "./keychain.js";
|
|
5
|
+
import { copyOrigin } from "./run.js";
|
|
6
|
+
import { ensureDir, HOOK_PACKAGE, HOOK_VERSION, readConfig, writeConfig, writeFileAtomic } from "./state.js";
|
|
7
|
+
/**
|
|
8
|
+
* `work-hook install <copy>` and `work-hook uninstall` (K's Work slice, decisions S6 and S7, plan
|
|
9
|
+
* section 6b), run by a person in their own terminal:
|
|
10
|
+
*
|
|
11
|
+
* 1. checks the key in `YOUGROW_WORK_KEY` with this copy of YouGrow (`GET /api/v2/work/me`), or,
|
|
12
|
+
* when it isn't set, the key an earlier install saved for the same copy, so the line that
|
|
13
|
+
* updates the hook needs no new key;
|
|
14
|
+
* 2. shows the five entries it adds to their own `~/.claude/settings.json`, and asks;
|
|
15
|
+
* 3. copies the hook's modules to `~/.yougrow/hook/<version>/` and writes `~/.yougrow/work-hook.mjs`,
|
|
16
|
+
* the file Claude Code runs, so no event waits on npx or the network to start;
|
|
17
|
+
* 4. saves the key in the system keychain, or `~/.yougrow/work-key` readable only by them;
|
|
18
|
+
* 5. adds the entries beside every hook they have, after a dated backup of the file.
|
|
19
|
+
*
|
|
20
|
+
* Never a project's `.claude/settings.json`, which is often committed, and never Claude Code's own
|
|
21
|
+
* `env` settings: every command an agent runs would then hold the key.
|
|
22
|
+
*/
|
|
23
|
+
/** The marker every entry's command holds, so install and uninstall find their own and no other. */
|
|
24
|
+
export const HOOK_COMMAND_MARK = ".yougrow/work-hook.mjs";
|
|
25
|
+
const LAUNCH = 'node "$HOME/.yougrow/work-hook.mjs"';
|
|
26
|
+
/** The five entries, as plan section 6b lists them: SessionStart, PreCompact and SessionEnd wait a few seconds; Stop and PostCompact run in the background. */
|
|
27
|
+
export function hookEntries(o = {}) {
|
|
28
|
+
const command = (event) => (o.cloud ? `npx -y ${HOOK_PACKAGE}@${HOOK_VERSION} work-hook run ${event}` : `${LAUNCH} ${event}`);
|
|
29
|
+
// A cloud session starts npx on its first event, so its start waits longer.
|
|
30
|
+
return {
|
|
31
|
+
SessionStart: { matcher: "startup|resume|clear|compact|fork", hooks: [{ type: "command", command: command("start"), timeout: o.cloud ? 30 : 10 }] },
|
|
32
|
+
Stop: { hooks: [{ type: "command", command: command("stop"), async: true }] },
|
|
33
|
+
PreCompact: { hooks: [{ type: "command", command: command("precompact"), timeout: o.cloud ? 30 : 5 }] },
|
|
34
|
+
PostCompact: { hooks: [{ type: "command", command: command("compact"), async: true }] },
|
|
35
|
+
SessionEnd: { hooks: [{ type: "command", command: command("end"), timeout: o.cloud ? 15 : 5 }] },
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** The entries as they read in a settings file, each event's in a list: what install shows, and `work-hook entries` prints. */
|
|
39
|
+
export function entriesText(entries) {
|
|
40
|
+
return JSON.stringify({ hooks: Object.fromEntries(Object.entries(entries).map(([event, entry]) => [event, [entry]])) }, null, 2);
|
|
41
|
+
}
|
|
42
|
+
const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
43
|
+
const isOurs = (h) => isObject(h) && typeof h.command === "string" && (h.command.includes(HOOK_COMMAND_MARK) || /work-hook run /.test(h.command));
|
|
44
|
+
/**
|
|
45
|
+
* The person's settings with the hook's entries in them, beside every other hook. Entries from an
|
|
46
|
+
* earlier install are taken out first, so installing again replaces them; nothing else changes.
|
|
47
|
+
* `entries` null takes them out only (uninstall).
|
|
48
|
+
*/
|
|
49
|
+
export function mergeSettings(current, entries) {
|
|
50
|
+
if (!isObject(current))
|
|
51
|
+
return { ok: false, why: "it holds something other than one JSON object" };
|
|
52
|
+
const hooks = current.hooks === undefined ? {} : current.hooks;
|
|
53
|
+
if (!isObject(hooks))
|
|
54
|
+
return { ok: false, why: "its hooks aren't a JSON object" };
|
|
55
|
+
const next = { ...hooks };
|
|
56
|
+
let replaced = 0;
|
|
57
|
+
const events = new Set([...Object.keys(hooks), ...(entries ? Object.keys(entries) : [])]);
|
|
58
|
+
for (const event of events) {
|
|
59
|
+
const list = hooks[event];
|
|
60
|
+
if (list !== undefined && !Array.isArray(list))
|
|
61
|
+
return { ok: false, why: `its ${event} hooks aren't a list` };
|
|
62
|
+
const kept = [];
|
|
63
|
+
for (const group of list ?? []) {
|
|
64
|
+
if (!isObject(group) || !Array.isArray(group.hooks)) {
|
|
65
|
+
kept.push(group);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const others = group.hooks.filter((h) => !isOurs(h));
|
|
69
|
+
replaced += group.hooks.length - others.length;
|
|
70
|
+
if (others.length)
|
|
71
|
+
kept.push(others.length === group.hooks.length ? group : { ...group, hooks: others });
|
|
72
|
+
}
|
|
73
|
+
const ours = entries?.[event];
|
|
74
|
+
if (ours)
|
|
75
|
+
kept.push(ours);
|
|
76
|
+
if (kept.length)
|
|
77
|
+
next[event] = kept;
|
|
78
|
+
else
|
|
79
|
+
delete next[event];
|
|
80
|
+
}
|
|
81
|
+
const settings = { ...current, hooks: next };
|
|
82
|
+
if (!Object.keys(next).length)
|
|
83
|
+
delete settings.hooks;
|
|
84
|
+
return { ok: true, settings, replaced };
|
|
85
|
+
}
|
|
86
|
+
// --- Files -------------------------------------------------------------------------------------
|
|
87
|
+
/** The person's own Claude Code settings: `~/.claude/settings.json`, or in CLAUDE_CONFIG_DIR when it is set. Never a project's. */
|
|
88
|
+
export function userSettingsFile(home, env) {
|
|
89
|
+
const dir = env.CLAUDE_CONFIG_DIR && path.isAbsolute(env.CLAUDE_CONFIG_DIR) ? env.CLAUDE_CONFIG_DIR : path.join(home, ".claude");
|
|
90
|
+
return path.join(dir, "settings.json");
|
|
91
|
+
}
|
|
92
|
+
/** The settings file as it is now, through a link to where it lives (a dotfiles folder keeps its link). */
|
|
93
|
+
function readSettings(file) {
|
|
94
|
+
let real = file;
|
|
95
|
+
try {
|
|
96
|
+
real = fs.realpathSync(file);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return { ok: true, exists: false, value: {}, text: "", file, mode: 0o600 };
|
|
100
|
+
}
|
|
101
|
+
let text;
|
|
102
|
+
let mode;
|
|
103
|
+
try {
|
|
104
|
+
text = fs.readFileSync(real, "utf8");
|
|
105
|
+
mode = fs.statSync(real).mode & 0o777;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return { ok: false, why: "it can't be read", file: real };
|
|
109
|
+
}
|
|
110
|
+
if (!text.trim())
|
|
111
|
+
return { ok: true, exists: true, value: {}, text, file: real, mode };
|
|
112
|
+
try {
|
|
113
|
+
return { ok: true, exists: true, value: JSON.parse(text), text, file: real, mode };
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return { ok: false, why: "it isn't plain JSON", file: real };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** A file written whole, keeping its mode; its folder is made only if it isn't there, and never changed. */
|
|
120
|
+
function writeKeepingMode(file, text, mode) {
|
|
121
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
122
|
+
const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
|
|
123
|
+
fs.writeFileSync(tmp, text, { mode });
|
|
124
|
+
fs.chmodSync(tmp, mode);
|
|
125
|
+
fs.renameSync(tmp, file);
|
|
126
|
+
}
|
|
127
|
+
const stamp = (now) => now.toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
|
|
128
|
+
/** The JavaScript files the hook is made of, beside this one in the package. */
|
|
129
|
+
export function hookFilesIn(dir) {
|
|
130
|
+
return fs
|
|
131
|
+
.readdirSync(dir)
|
|
132
|
+
.filter((f) => /^[a-z]+\.js$/.test(f))
|
|
133
|
+
.sort();
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Copy the hook's modules into `~/.yougrow/hook/<version>-<hash>/` and point the file Claude Code
|
|
137
|
+
* runs at them. Each copy has its own folder, so a hook running while this runs keeps the files
|
|
138
|
+
* it started with; older folders are removed after.
|
|
139
|
+
*/
|
|
140
|
+
export function placeHook(paths, sourceDir) {
|
|
141
|
+
const files = hookFilesIn(sourceDir);
|
|
142
|
+
if (!files.includes("cli.js"))
|
|
143
|
+
throw new Error("the hook's files aren't in this package");
|
|
144
|
+
const hash = createHash("sha256");
|
|
145
|
+
const contents = files.map((f) => {
|
|
146
|
+
const body = fs.readFileSync(path.join(sourceDir, f));
|
|
147
|
+
hash.update(`${f}\0`).update(body).update("\0");
|
|
148
|
+
return [f, body];
|
|
149
|
+
});
|
|
150
|
+
const name = `${HOOK_VERSION}-${hash.digest("hex").slice(0, 8)}`;
|
|
151
|
+
ensureDir(paths.dir);
|
|
152
|
+
ensureDir(paths.hookRoot);
|
|
153
|
+
const target = path.join(paths.hookRoot, name);
|
|
154
|
+
if (!fs.existsSync(path.join(target, "cli.js"))) {
|
|
155
|
+
const tmp = path.join(paths.hookRoot, `.tmp-${process.pid}-${randomBytes(3).toString("hex")}`);
|
|
156
|
+
ensureDir(tmp);
|
|
157
|
+
for (const [f, body] of contents)
|
|
158
|
+
fs.writeFileSync(path.join(tmp, f), body, { mode: 0o600 });
|
|
159
|
+
fs.writeFileSync(path.join(tmp, "package.json"), `${JSON.stringify({ type: "module" })}\n`, { mode: 0o600 });
|
|
160
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
161
|
+
fs.renameSync(tmp, target);
|
|
162
|
+
}
|
|
163
|
+
writeFileAtomic(paths.hookFile, launcherText(name), 0o700);
|
|
164
|
+
for (const other of fs.readdirSync(paths.hookRoot)) {
|
|
165
|
+
if (other !== name)
|
|
166
|
+
fs.rmSync(path.join(paths.hookRoot, other), { recursive: true, force: true });
|
|
167
|
+
}
|
|
168
|
+
return target;
|
|
169
|
+
}
|
|
170
|
+
/** The file Claude Code runs. Whatever fails, it ends quietly, so it never stops a chat. */
|
|
171
|
+
export function launcherText(folder) {
|
|
172
|
+
return [
|
|
173
|
+
"#!/usr/bin/env node",
|
|
174
|
+
`// The YouGrow Work hook, written by \`work-hook install\` (${HOOK_PACKAGE} ${HOOK_VERSION}).`,
|
|
175
|
+
"// Claude Code runs it from your ~/.claude/settings.json. It loads its modules from the folder",
|
|
176
|
+
"// named below. Whatever fails, it ends quietly, so it never stops a chat.",
|
|
177
|
+
"try {",
|
|
178
|
+
` const { main } = await import("./hook/${folder}/cli.js");`,
|
|
179
|
+
" await main(process.argv.slice(2), { launcher: true });",
|
|
180
|
+
"} catch {",
|
|
181
|
+
" process.exit(0);",
|
|
182
|
+
"}",
|
|
183
|
+
"",
|
|
184
|
+
].join("\n");
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The lines that install with a key typed in: one ( ... ) block that says it is waiting for the
|
|
188
|
+
* key, so no pasted line is taken as the key and the key is gone from the terminal when it ends.
|
|
189
|
+
* The same block Work keys shows (src/lib/work/keys/screenWords.ts).
|
|
190
|
+
*/
|
|
191
|
+
function keyLines(url) {
|
|
192
|
+
return [
|
|
193
|
+
"(",
|
|
194
|
+
"printf 'Paste your Work key, then press Enter: '",
|
|
195
|
+
"read -rs YOUGROW_WORK_KEY",
|
|
196
|
+
"echo",
|
|
197
|
+
"export YOUGROW_WORK_KEY",
|
|
198
|
+
`npx -y ${HOOK_PACKAGE}@${HOOK_VERSION} work-hook install ${url}`,
|
|
199
|
+
")",
|
|
200
|
+
];
|
|
201
|
+
}
|
|
202
|
+
const USAGE = "Usage: npx -y @yougrowai/node work-hook install https://your.copy.example [--yes] [--key-store file]";
|
|
203
|
+
/** What Work's whoami says about recording, read loosely: the hook works whatever it says. */
|
|
204
|
+
function whoamiLines(body) {
|
|
205
|
+
if (!body)
|
|
206
|
+
return [];
|
|
207
|
+
const out = [];
|
|
208
|
+
const key = isObject(body.key) ? body.key : null;
|
|
209
|
+
if (key && typeof key.name === "string")
|
|
210
|
+
out.push(`Work knows this key: ${[key.name, key.app, key.access].filter((x) => typeof x === "string").join(", ")}.`);
|
|
211
|
+
const sessions = isObject(body.sessions) && typeof body.sessions.records === "string" ? body.sessions.records : null;
|
|
212
|
+
if (sessions)
|
|
213
|
+
out.push(sessions);
|
|
214
|
+
if (typeof body.transcripts === "string")
|
|
215
|
+
out.push(body.transcripts);
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
/** The key an earlier install saved on this computer, when it was for this same copy; else null. */
|
|
219
|
+
async function savedKeyFor(url, d) {
|
|
220
|
+
const before = readConfig(d.paths);
|
|
221
|
+
if (!before || copyOrigin(before.url) !== url)
|
|
222
|
+
return null;
|
|
223
|
+
return readSavedKey({ store: before.store, account: before.account }, { paths: d.paths, run: d.run });
|
|
224
|
+
}
|
|
225
|
+
/** `work-hook install`: answers the exit code. Nothing on this computer changes until the person says yes. */
|
|
226
|
+
export async function install(o, d) {
|
|
227
|
+
const url = copyOrigin(o.url);
|
|
228
|
+
if (!url) {
|
|
229
|
+
d.out(o.url ? `${o.url} isn't an address the hook sends to: it takes https, or http on this computer only.` : "Name your copy of YouGrow.");
|
|
230
|
+
d.out(USAGE);
|
|
231
|
+
return 2;
|
|
232
|
+
}
|
|
233
|
+
const given = d.env.YOUGROW_WORK_KEY?.trim();
|
|
234
|
+
// Updating the hook: with no key in this terminal, the one an earlier install saved for the same
|
|
235
|
+
// copy, so the line Review and the hook give works as written. A key given always wins.
|
|
236
|
+
const saved = given ? null : await savedKeyFor(url, d);
|
|
237
|
+
const key = given || saved;
|
|
238
|
+
if (!isWorkKey(key)) {
|
|
239
|
+
d.out(given ? "YOUGROW_WORK_KEY isn't a whole Work key. Copy it again from Work keys, then paste these as one block:" : "Paste these into your own terminal as one block, and paste your Work key when it asks:");
|
|
240
|
+
for (const l of keyLines(url))
|
|
241
|
+
d.out(` ${l}`);
|
|
242
|
+
return 2;
|
|
243
|
+
}
|
|
244
|
+
if (saved)
|
|
245
|
+
d.out("Using the key the earlier install saved on this computer.");
|
|
246
|
+
const me = await d.request({ method: "GET", url: `${url}/api/v2/work/me`, headers: { authorization: `Bearer ${key}` }, timeoutMs: 15_000 });
|
|
247
|
+
if (me.status !== 200) {
|
|
248
|
+
const message = me.body && typeof me.body.message === "string" ? me.body.message : null;
|
|
249
|
+
d.out(me.status === 0 ? `${url} didn't answer, so nothing was installed. Check the address and try again.` : `Work at ${url} didn't take this key, so nothing was installed.${message ? ` ${message}` : ""}`);
|
|
250
|
+
if (saved && me.status !== 0) {
|
|
251
|
+
d.out("Make a new key on Work keys, then paste these as one block and paste the new key when it asks:");
|
|
252
|
+
for (const l of keyLines(url))
|
|
253
|
+
d.out(` ${l}`);
|
|
254
|
+
}
|
|
255
|
+
return 1;
|
|
256
|
+
}
|
|
257
|
+
for (const l of whoamiLines(me.body))
|
|
258
|
+
d.out(l);
|
|
259
|
+
const settingsFile = userSettingsFile(d.paths.home, d.env);
|
|
260
|
+
const read = readSettings(settingsFile);
|
|
261
|
+
const entries = hookEntries();
|
|
262
|
+
if (!read.ok) {
|
|
263
|
+
d.out(`${read.file} wasn't changed: ${read.why}. Add these hooks to it yourself, then run install again:`);
|
|
264
|
+
d.out(entriesText(entries));
|
|
265
|
+
return 1;
|
|
266
|
+
}
|
|
267
|
+
const merged = mergeSettings(read.value, entries);
|
|
268
|
+
if (!merged.ok) {
|
|
269
|
+
d.out(`${read.file} wasn't changed: ${merged.why}. Add these hooks to it yourself:`);
|
|
270
|
+
d.out(entriesText(entries));
|
|
271
|
+
return 1;
|
|
272
|
+
}
|
|
273
|
+
const now = d.now();
|
|
274
|
+
const backup = `${read.file}.yougrow-${stamp(now)}.bak`;
|
|
275
|
+
d.out("");
|
|
276
|
+
d.out(`This adds five hooks to ${read.file}, your own Claude Code settings, beside the hooks you have${merged.replaced ? " (it replaces the ones an earlier install added)" : ""}:`);
|
|
277
|
+
d.out(entriesText(entries));
|
|
278
|
+
d.out(read.exists ? `It keeps a copy of the file as it is now: ${backup}` : "The file isn't there yet, so it is made.");
|
|
279
|
+
d.out(`The hook goes in ${d.paths.dir}, and the key in ${STORE_WORDS[o.keyStore ?? storesFor(d.platform)[0]]}. No project's settings change.`);
|
|
280
|
+
if (!o.yes) {
|
|
281
|
+
const yes = await d.ask("Add them? (y/N) ");
|
|
282
|
+
if (yes === null) {
|
|
283
|
+
d.out("Run this in your own terminal to answer, or add --yes.");
|
|
284
|
+
return 1;
|
|
285
|
+
}
|
|
286
|
+
if (!yes) {
|
|
287
|
+
d.out("Nothing was changed.");
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
placeHook(d.paths, d.hookSource);
|
|
292
|
+
const account = new URL(url).host;
|
|
293
|
+
const store = await saveKey({ account, key, platform: d.platform, ...(o.keyStore ? { only: o.keyStore } : {}) }, { paths: d.paths, run: d.run });
|
|
294
|
+
if (!store) {
|
|
295
|
+
d.out("The key couldn't be saved on this computer, so the hooks weren't added.");
|
|
296
|
+
return 1;
|
|
297
|
+
}
|
|
298
|
+
const before = readConfig(d.paths);
|
|
299
|
+
if (before && (before.store !== store || before.account !== account))
|
|
300
|
+
await forgetKey({ store: before.store, account: before.account }, { paths: d.paths, run: d.run }).catch(() => null);
|
|
301
|
+
writeConfig(d.paths, { v: 1, url, store, account, installedAt: now.toISOString(), version: HOOK_VERSION });
|
|
302
|
+
if (read.exists)
|
|
303
|
+
writeKeepingMode(backup, read.text, read.mode);
|
|
304
|
+
writeKeepingMode(read.file, `${JSON.stringify(merged.settings, null, 2)}\n`, read.exists ? read.mode : 0o600);
|
|
305
|
+
d.out("");
|
|
306
|
+
d.out(`Done. The key is in ${STORE_WORDS[store]}${store === "file" ? "" : `, under ${KEY_SERVICE}`}.`);
|
|
307
|
+
d.out("Claude Code picks the hooks up by itself, in every folder you trust. Each chat from now on is a coding session in Work.");
|
|
308
|
+
d.out("To stop: npx -y @yougrowai/node work-hook uninstall");
|
|
309
|
+
return 0;
|
|
310
|
+
}
|
|
311
|
+
/** `work-hook uninstall`: takes the hook's entries out, forgets the key and removes the hook's files. */
|
|
312
|
+
export async function uninstall(o, d) {
|
|
313
|
+
const read = readSettings(userSettingsFile(d.paths.home, d.env));
|
|
314
|
+
const merged = read.ok ? mergeSettings(read.value, null) : null;
|
|
315
|
+
if (!o.yes) {
|
|
316
|
+
const yes = await d.ask(`This takes the Work hook out of ${read.file}, forgets its key and removes ${d.paths.dir}. Go ahead? (y/N) `);
|
|
317
|
+
if (yes !== true) {
|
|
318
|
+
d.out(yes === null ? "Run this in your own terminal to answer, or add --yes." : "Nothing was changed.");
|
|
319
|
+
return 1;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (read.ok && merged?.ok && merged.replaced > 0) {
|
|
323
|
+
writeKeepingMode(`${read.file}.yougrow-${stamp(d.now())}.bak`, read.text, read.mode);
|
|
324
|
+
writeKeepingMode(read.file, `${JSON.stringify(merged.settings, null, 2)}\n`, read.mode);
|
|
325
|
+
d.out(`Took ${merged.replaced} hooks out of ${read.file}.`);
|
|
326
|
+
}
|
|
327
|
+
else if (!read.ok || !merged?.ok) {
|
|
328
|
+
d.out(`${read.file} wasn't changed: ${!read.ok ? read.why : merged && !merged.ok ? merged.why : "it can't be read"}. Take out the hooks whose command names ${HOOK_COMMAND_MARK} yourself.`);
|
|
329
|
+
}
|
|
330
|
+
const config = readConfig(d.paths);
|
|
331
|
+
if (config)
|
|
332
|
+
await forgetKey({ store: config.store, account: config.account }, { paths: d.paths, run: d.run }).catch(() => null);
|
|
333
|
+
for (const p of [d.paths.hookFile, d.paths.config, d.paths.keyFile, d.paths.notice, d.paths.flushLock])
|
|
334
|
+
fs.rmSync(p, { force: true });
|
|
335
|
+
for (const p of [d.paths.hookRoot, d.paths.sessions])
|
|
336
|
+
fs.rmSync(p, { recursive: true, force: true });
|
|
337
|
+
d.out("The Work hook is gone from this computer. Sessions already in Work stay there.");
|
|
338
|
+
return 0;
|
|
339
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type HookEnv, type HookPaths, type KeyStoreKind } from "./state.js";
|
|
2
|
+
/**
|
|
3
|
+
* Where the hook keeps a person's Work key (K's Work slice, decision S7):
|
|
4
|
+
*
|
|
5
|
+
* - `install` saves it in the system keychain: macOS Keychain through the `security` tool, or the
|
|
6
|
+
* Secret Service on Linux through `secret-tool`; else in `~/.yougrow/work-key`, readable only by
|
|
7
|
+
* its person. The installed hook reads it only from there (readSavedKey), never from the
|
|
8
|
+
* environment: a terminal's `YOUGROW_WORK_KEY` may be another app's key, and every chat started
|
|
9
|
+
* from that terminal would send it.
|
|
10
|
+
* - `YOUGROW_WORK_KEY` in the environment is for `install` itself, and for `work-hook run` in a
|
|
11
|
+
* cloud environment or a script (readKey).
|
|
12
|
+
*
|
|
13
|
+
* Never Claude Code's own `env` settings (every command an agent runs would hold it), a repo file
|
|
14
|
+
* or a chat. The key never goes on a command line, where other programs could read it: `security`
|
|
15
|
+
* takes it on its interactive input and `secret-tool` on its standard input.
|
|
16
|
+
*/
|
|
17
|
+
export declare const KEY_SERVICE = "yougrow-work";
|
|
18
|
+
/** The account a key is saved under: this copy's host, with its port when it has one. */
|
|
19
|
+
export declare const ACCOUNT: RegExp;
|
|
20
|
+
/** A program run with its input on stdin: its exit code and what it printed. Tests pass a fake. */
|
|
21
|
+
export type Runner = (file: string, args: readonly string[], o: {
|
|
22
|
+
input?: string;
|
|
23
|
+
timeoutMs: number;
|
|
24
|
+
cwd?: string;
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
26
|
+
}) => Promise<{
|
|
27
|
+
code: number;
|
|
28
|
+
stdout: string;
|
|
29
|
+
}>;
|
|
30
|
+
/** Runs a program with no shell, and a child environment without the key. */
|
|
31
|
+
export declare const runProgram: Runner;
|
|
32
|
+
/** CRC32, as zlib computes it; written out because zlib.crc32 needs Node 22 and the SDK runs on 18. */
|
|
33
|
+
export declare function crc32(text: string): number;
|
|
34
|
+
/** A key's last 6 characters: the CRC32 of everything before, in base62. */
|
|
35
|
+
export declare function workKeyChecksum(body: string): string;
|
|
36
|
+
/** Whether a string is a whole Work key with a good checksum. Reads nothing. */
|
|
37
|
+
export declare function isWorkKey(key: unknown): key is string;
|
|
38
|
+
/** The stores to try on this platform, best first. */
|
|
39
|
+
export declare function storesFor(platform: NodeJS.Platform): KeyStoreKind[];
|
|
40
|
+
/** What each store is called in what install prints. */
|
|
41
|
+
export declare const STORE_WORDS: Record<KeyStoreKind, string>;
|
|
42
|
+
export interface KeyStoreDeps {
|
|
43
|
+
paths: HookPaths;
|
|
44
|
+
run: Runner;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Save the key in the best store this computer has, and answer which. A store is used only when
|
|
48
|
+
* the key reads back from it; the private file is the last place.
|
|
49
|
+
*/
|
|
50
|
+
export declare function saveKey(o: {
|
|
51
|
+
account: string;
|
|
52
|
+
key: string;
|
|
53
|
+
platform: NodeJS.Platform;
|
|
54
|
+
only?: KeyStoreKind;
|
|
55
|
+
}, d: KeyStoreDeps): Promise<KeyStoreKind | null>;
|
|
56
|
+
/** The key `install` saved, from its store only: what the installed hook sends. */
|
|
57
|
+
export declare function readSavedKey(o: {
|
|
58
|
+
store: KeyStoreKind;
|
|
59
|
+
account: string;
|
|
60
|
+
}, d: KeyStoreDeps): Promise<string | null>;
|
|
61
|
+
/** The key `work-hook run` uses: the environment's when it is a Work key, else the saved one. */
|
|
62
|
+
export declare function readKey(o: {
|
|
63
|
+
store: KeyStoreKind;
|
|
64
|
+
account: string;
|
|
65
|
+
env: HookEnv;
|
|
66
|
+
}, d: KeyStoreDeps): Promise<string | null>;
|
|
67
|
+
/** Remove the saved key from its store. */
|
|
68
|
+
export declare function forgetKey(o: {
|
|
69
|
+
store: KeyStoreKind;
|
|
70
|
+
account: string;
|
|
71
|
+
}, d: KeyStoreDeps): Promise<void>;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import { writeFileAtomic } from "./state.js";
|
|
4
|
+
/**
|
|
5
|
+
* Where the hook keeps a person's Work key (K's Work slice, decision S7):
|
|
6
|
+
*
|
|
7
|
+
* - `install` saves it in the system keychain: macOS Keychain through the `security` tool, or the
|
|
8
|
+
* Secret Service on Linux through `secret-tool`; else in `~/.yougrow/work-key`, readable only by
|
|
9
|
+
* its person. The installed hook reads it only from there (readSavedKey), never from the
|
|
10
|
+
* environment: a terminal's `YOUGROW_WORK_KEY` may be another app's key, and every chat started
|
|
11
|
+
* from that terminal would send it.
|
|
12
|
+
* - `YOUGROW_WORK_KEY` in the environment is for `install` itself, and for `work-hook run` in a
|
|
13
|
+
* cloud environment or a script (readKey).
|
|
14
|
+
*
|
|
15
|
+
* Never Claude Code's own `env` settings (every command an agent runs would hold it), a repo file
|
|
16
|
+
* or a chat. The key never goes on a command line, where other programs could read it: `security`
|
|
17
|
+
* takes it on its interactive input and `secret-tool` on its standard input.
|
|
18
|
+
*/
|
|
19
|
+
export const KEY_SERVICE = "yougrow-work";
|
|
20
|
+
const KEY_LABEL = "YouGrow Work key";
|
|
21
|
+
/** The account a key is saved under: this copy's host, with its port when it has one. */
|
|
22
|
+
export const ACCOUNT = /^[A-Za-z0-9.-]{1,253}(?::\d{1,5})?$/;
|
|
23
|
+
/** Runs a program with no shell, and a child environment without the key. */
|
|
24
|
+
export const runProgram = (file, args, o) => new Promise((resolve) => {
|
|
25
|
+
const env = { ...(o.env ?? process.env) };
|
|
26
|
+
delete env.YOUGROW_WORK_KEY;
|
|
27
|
+
let child;
|
|
28
|
+
try {
|
|
29
|
+
child = execFile(file, [...args], { timeout: o.timeoutMs, cwd: o.cwd, env, maxBuffer: 1024 * 1024, windowsHide: true, encoding: "utf8" }, (err, stdout) => {
|
|
30
|
+
const code = err ? (typeof err.code === "number" ? (err.code) : 1) : 0;
|
|
31
|
+
resolve({ code, stdout: typeof stdout === "string" ? stdout : "" });
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
resolve({ code: 127, stdout: "" });
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
child.on("error", () => resolve({ code: 127, stdout: "" }));
|
|
39
|
+
if (child.stdin) {
|
|
40
|
+
child.stdin.on("error", () => { });
|
|
41
|
+
child.stdin.end(o.input ?? "");
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
// --- The key's shape -----------------------------------------------------------------------------
|
|
45
|
+
/** `ygw_`, the key id (20 base32), the secret (43 base64url) and a 6 character checksum: as the app's src/lib/work/keys/token.ts. */
|
|
46
|
+
const KEY_SHAPE = /^ygw_[a-z2-7]{20}_[A-Za-z0-9_-]{43}[A-Za-z0-9]{6}$/;
|
|
47
|
+
const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
48
|
+
let crcTable = null;
|
|
49
|
+
/** CRC32, as zlib computes it; written out because zlib.crc32 needs Node 22 and the SDK runs on 18. */
|
|
50
|
+
export function crc32(text) {
|
|
51
|
+
if (!crcTable) {
|
|
52
|
+
crcTable = new Uint32Array(256);
|
|
53
|
+
for (let n = 0; n < 256; n += 1) {
|
|
54
|
+
let c = n;
|
|
55
|
+
for (let k = 0; k < 8; k += 1)
|
|
56
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
57
|
+
crcTable[n] = c >>> 0;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
let crc = 0xffffffff;
|
|
61
|
+
for (const byte of Buffer.from(text, "utf8"))
|
|
62
|
+
crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
|
63
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
64
|
+
}
|
|
65
|
+
/** A key's last 6 characters: the CRC32 of everything before, in base62. */
|
|
66
|
+
export function workKeyChecksum(body) {
|
|
67
|
+
let n = crc32(body);
|
|
68
|
+
let out = "";
|
|
69
|
+
for (let i = 0; i < 6; i += 1) {
|
|
70
|
+
out = BASE62[n % 62] + out;
|
|
71
|
+
n = Math.floor(n / 62);
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
/** Whether a string is a whole Work key with a good checksum. Reads nothing. */
|
|
76
|
+
export function isWorkKey(key) {
|
|
77
|
+
if (typeof key !== "string" || !KEY_SHAPE.test(key))
|
|
78
|
+
return false;
|
|
79
|
+
return workKeyChecksum(key.slice(0, 68)) === key.slice(68);
|
|
80
|
+
}
|
|
81
|
+
// --- The stores ----------------------------------------------------------------------------------
|
|
82
|
+
/** The stores to try on this platform, best first. */
|
|
83
|
+
export function storesFor(platform) {
|
|
84
|
+
if (platform === "darwin")
|
|
85
|
+
return ["keychain", "file"];
|
|
86
|
+
if (platform === "linux")
|
|
87
|
+
return ["secret_service", "file"];
|
|
88
|
+
return ["file"];
|
|
89
|
+
}
|
|
90
|
+
/** What each store is called in what install prints. */
|
|
91
|
+
export const STORE_WORDS = {
|
|
92
|
+
keychain: "your macOS Keychain",
|
|
93
|
+
secret_service: "your system keyring (Secret Service)",
|
|
94
|
+
file: "~/.yougrow/work-key, readable only by you",
|
|
95
|
+
};
|
|
96
|
+
async function saveIn(kind, account, key, d) {
|
|
97
|
+
if (!isWorkKey(key) || !ACCOUNT.test(account))
|
|
98
|
+
return false;
|
|
99
|
+
if (kind === "keychain") {
|
|
100
|
+
// On security's own input, never its command line. A key and an account are letters, digits
|
|
101
|
+
// and . _ : -, so neither needs quoting.
|
|
102
|
+
const line = `add-generic-password -U -s ${KEY_SERVICE} -a ${account} -w ${key}\n`;
|
|
103
|
+
const r = await d.run("/usr/bin/security", ["-i"], { input: line, timeoutMs: 5_000 });
|
|
104
|
+
return r.code === 0 && (await readFrom(kind, account, d)) === key;
|
|
105
|
+
}
|
|
106
|
+
if (kind === "secret_service") {
|
|
107
|
+
const r = await d.run("secret-tool", ["store", `--label=${KEY_LABEL}`, "service", KEY_SERVICE, "account", account], { input: key, timeoutMs: 5_000 });
|
|
108
|
+
return r.code === 0 && (await readFrom(kind, account, d)) === key;
|
|
109
|
+
}
|
|
110
|
+
writeFileAtomic(d.paths.keyFile, `${key}\n`, 0o600);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
async function readFrom(kind, account, d) {
|
|
114
|
+
if (kind === "keychain") {
|
|
115
|
+
const r = await d.run("/usr/bin/security", ["find-generic-password", "-s", KEY_SERVICE, "-a", account, "-w"], { timeoutMs: 3_000 });
|
|
116
|
+
const key = r.stdout.trim();
|
|
117
|
+
return r.code === 0 && isWorkKey(key) ? key : null;
|
|
118
|
+
}
|
|
119
|
+
if (kind === "secret_service") {
|
|
120
|
+
const r = await d.run("secret-tool", ["lookup", "service", KEY_SERVICE, "account", account], { timeoutMs: 3_000 });
|
|
121
|
+
const key = r.stdout.trim();
|
|
122
|
+
return r.code === 0 && isWorkKey(key) ? key : null;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const key = fs.readFileSync(d.paths.keyFile, "utf8").trim();
|
|
126
|
+
return isWorkKey(key) ? key : null;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Save the key in the best store this computer has, and answer which. A store is used only when
|
|
134
|
+
* the key reads back from it; the private file is the last place.
|
|
135
|
+
*/
|
|
136
|
+
export async function saveKey(o, d) {
|
|
137
|
+
const kinds = o.only ? [o.only] : storesFor(o.platform);
|
|
138
|
+
for (const kind of kinds) {
|
|
139
|
+
if (await saveIn(kind, o.account, o.key, d).catch(() => false)) {
|
|
140
|
+
// A key saved in a keychain leaves no copy in the file.
|
|
141
|
+
if (kind !== "file")
|
|
142
|
+
forgetFile(d.paths);
|
|
143
|
+
return kind;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
/** The key `install` saved, from its store only: what the installed hook sends. */
|
|
149
|
+
export async function readSavedKey(o, d) {
|
|
150
|
+
return readFrom(o.store, o.account, d).catch(() => null);
|
|
151
|
+
}
|
|
152
|
+
/** The key `work-hook run` uses: the environment's when it is a Work key, else the saved one. */
|
|
153
|
+
export async function readKey(o, d) {
|
|
154
|
+
if (isWorkKey(o.env.YOUGROW_WORK_KEY))
|
|
155
|
+
return o.env.YOUGROW_WORK_KEY;
|
|
156
|
+
return readSavedKey(o, d);
|
|
157
|
+
}
|
|
158
|
+
function forgetFile(paths) {
|
|
159
|
+
try {
|
|
160
|
+
fs.unlinkSync(paths.keyFile);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
// None there.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Remove the saved key from its store. */
|
|
167
|
+
export async function forgetKey(o, d) {
|
|
168
|
+
if (o.store === "keychain")
|
|
169
|
+
await d.run("/usr/bin/security", ["delete-generic-password", "-s", KEY_SERVICE, "-a", o.account], { timeoutMs: 3_000 }).catch(() => null);
|
|
170
|
+
if (o.store === "secret_service")
|
|
171
|
+
await d.run("secret-tool", ["clear", "service", KEY_SERVICE, "account", o.account], { timeoutMs: 3_000 }).catch(() => null);
|
|
172
|
+
forgetFile(d.paths);
|
|
173
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type HookEventName } from "./events.js";
|
|
2
|
+
import { type Runner } from "./keychain.js";
|
|
3
|
+
import { type HookEnv, type HookPaths, type SessionState, type TranscriptState } from "./state.js";
|
|
4
|
+
import { type HttpAnswer, type PartSender } from "./transcript.js";
|
|
5
|
+
/**
|
|
6
|
+
* The Work hook's events (K's Work slice, plan section 6b and decision S8), as Claude Code runs
|
|
7
|
+
* them. It never gets in the way: whatever fails, it exits 0 and prints nothing, except the lines
|
|
8
|
+
* SessionStart and PreCompact are for.
|
|
9
|
+
*
|
|
10
|
+
* - SessionStart (waits up to 10 seconds): starts or finds the session; prints the lines Work
|
|
11
|
+
* answers, which Claude Code adds to the model's context before the first prompt, or the one
|
|
12
|
+
* line that says why Work isn't recording. Then any transcript a chat left unsent goes, in the
|
|
13
|
+
* background.
|
|
14
|
+
* - Stop (in the background): last active, turns and new commits, at most once a minute a chat;
|
|
15
|
+
* then the transcript's new lines, at most 4 parts.
|
|
16
|
+
* - PreCompact (waits up to 5 seconds): prints the session's facts for the summary to keep. It
|
|
17
|
+
* sends nothing.
|
|
18
|
+
* - PostCompact (in the background): Claude Code's summary, after the scan.
|
|
19
|
+
* - SessionEnd (waits up to 5 seconds): the end and its reason; the rest of the transcript goes in
|
|
20
|
+
* the background, or with the next start on this computer.
|
|
21
|
+
*
|
|
22
|
+
* It sends only to this copy's `/api/v2/work/sessions/` routes, with the key as a Bearer header.
|
|
23
|
+
*/
|
|
24
|
+
export declare const START_TIMEOUT_MS = 6000;
|
|
25
|
+
export declare const END_TIMEOUT_MS = 3000;
|
|
26
|
+
export declare const ASYNC_TIMEOUT_MS = 15000;
|
|
27
|
+
export declare const PART_TIMEOUT_MS = 60000;
|
|
28
|
+
/** A stop goes to Work at most once a minute a chat. */
|
|
29
|
+
export declare const STOP_EVERY_MS = 60000;
|
|
30
|
+
export type Requester = (o: {
|
|
31
|
+
method: "GET" | "POST" | "PUT";
|
|
32
|
+
url: string;
|
|
33
|
+
headers: Record<string, string>;
|
|
34
|
+
body?: Buffer;
|
|
35
|
+
timeoutMs: number;
|
|
36
|
+
}) => Promise<HttpAnswer>;
|
|
37
|
+
/**
|
|
38
|
+
* A copy's address as its origin, or null: https, or http on this computer only (`npm run local`).
|
|
39
|
+
* Never one with a user or password in it.
|
|
40
|
+
*/
|
|
41
|
+
export declare function copyOrigin(text: string | undefined | null): string | null;
|
|
42
|
+
/** One request with Node's own http and https, never longer than `timeoutMs` in all. */
|
|
43
|
+
export declare const httpRequest: Requester;
|
|
44
|
+
export interface RunDeps {
|
|
45
|
+
paths: HookPaths;
|
|
46
|
+
env: HookEnv;
|
|
47
|
+
now: () => number;
|
|
48
|
+
readInput: () => Promise<string>;
|
|
49
|
+
print: (text: string) => void;
|
|
50
|
+
request: Requester;
|
|
51
|
+
run: Runner;
|
|
52
|
+
/** Send what chats left unsent, in a process of its own that Claude Code never waits for. */
|
|
53
|
+
spawnFlush: () => void;
|
|
54
|
+
}
|
|
55
|
+
/** Where the hook sends, and with what key. The cloud's proxy adds the key when the session holds none. */
|
|
56
|
+
export interface Connection {
|
|
57
|
+
url: string;
|
|
58
|
+
key: string | null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The installed hook reads its copy from `~/.yougrow/work-hook.json` and its key from where
|
|
62
|
+
* `install` saved it, never from the environment: a `YOUGROW_WORK_KEY` a Claude Code inherits from
|
|
63
|
+
* its terminal may be another app's key. `work-hook run`, for a repo's committed hooks in cloud sessions,
|
|
64
|
+
* reads both from the environment, and does nothing unless `YOUGROW_WORK_URL` is set, or when
|
|
65
|
+
* this computer has the hook installed (which records its chats already).
|
|
66
|
+
*/
|
|
67
|
+
export declare function connectionFor(mode: "installed" | "run", d: Pick<RunDeps, "paths" | "env" | "run">): Promise<Connection | null>;
|
|
68
|
+
export declare function partSender(c: Connection, d: Pick<RunDeps, "request">): PartSender;
|
|
69
|
+
/** The transcript's state as Work's answer says it. */
|
|
70
|
+
export declare function transcriptOf(v: unknown): TranscriptState | null;
|
|
71
|
+
/**
|
|
72
|
+
* Work's answer to an event, into the chat's state: its session, the facts PreCompact prints, and
|
|
73
|
+
* where the transcript stands. The part to send next is Work's; where the hook reads from is the
|
|
74
|
+
* further of Work's and its own, so lines a person removed with the session never go again.
|
|
75
|
+
*/
|
|
76
|
+
export declare function withAnswer(s: SessionState, body: Record<string, unknown>): SessionState;
|
|
77
|
+
/** Run one hook event. Never throws: Claude Code's chat goes on whatever happens here. */
|
|
78
|
+
export declare function runHookEvent(event: HookEventName, mode: "installed" | "run", d: RunDeps): Promise<void>;
|
|
79
|
+
/** Claude Code's input on stdin, whole, at most 8 MB and 2 seconds. */
|
|
80
|
+
export declare function readStdin(maxBytes?: number, timeoutMs?: number): Promise<string>;
|
|
81
|
+
/** The flush as its own process, detached, so Claude Code never waits for it. */
|
|
82
|
+
export declare function spawnFlushProcess(mode: "installed" | "run"): void;
|
|
83
|
+
export declare function realRunDeps(mode: "installed" | "run", print: (text: string) => void): RunDeps;
|