@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,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hook's copy of the scan a coding session's words go through before Work keeps them (K's
|
|
3
|
+
* Work slice, decision S11): transcript lines, compaction summaries and the commits' first lines.
|
|
4
|
+
* It runs here, on the person's computer, before anything leaves it, and again on the server
|
|
5
|
+
* before anything is kept.
|
|
6
|
+
*
|
|
7
|
+
* Everything below this comment is the same as the app's src/lib/work/sessions/scan.ts, line for
|
|
8
|
+
* line: change both together. The SDK's test/workHook.scan.test.ts checks they match, and the made
|
|
9
|
+
* up vectors in test/scan-vectors.ts hold both to the same answers.
|
|
10
|
+
*
|
|
11
|
+
* What it finds is replaced with a label and the rest of the line is kept: private keys, Work keys
|
|
12
|
+
* and tokens of known shapes, Authorization headers and passwords in addresses, random looking
|
|
13
|
+
* values given to key, secret, token and password names, email addresses (except at example and
|
|
14
|
+
* test domains), phone numbers written with + or tel:, card numbers and IBANs that pass their
|
|
15
|
+
* checks, and images. A tool result that read a secret file goes whole, in transcript.ts.
|
|
16
|
+
*
|
|
17
|
+
* Honest limit: it finds the shapes it knows. A secret of a new shape, a person's name or a postal
|
|
18
|
+
* address can still get through.
|
|
19
|
+
*/
|
|
20
|
+
/** The version of this table. A part says which one scanned it; the server refuses older ones. */
|
|
21
|
+
export const SCAN_VERSION = 1;
|
|
22
|
+
/** The oldest scan version the server takes a part from. */
|
|
23
|
+
export const SCAN_VERSION_MIN = 1;
|
|
24
|
+
export const REMOVED_KINDS = ["private_key", "api_key", "token", "password", "secret", "secret_file", "email", "phone", "card", "bank_account", "image"];
|
|
25
|
+
/** What each label says. A secret file's label names the file instead. */
|
|
26
|
+
export const REMOVED_WORDS = {
|
|
27
|
+
private_key: "private key",
|
|
28
|
+
api_key: "API key",
|
|
29
|
+
token: "token",
|
|
30
|
+
password: "password",
|
|
31
|
+
secret: "secret",
|
|
32
|
+
email: "email address",
|
|
33
|
+
phone: "phone number",
|
|
34
|
+
card: "card number",
|
|
35
|
+
bank_account: "bank account",
|
|
36
|
+
image: "image",
|
|
37
|
+
};
|
|
38
|
+
/** The label a removal leaves: "[removed: API key]", or "[removed: contents of .env.local]" for a secret file. */
|
|
39
|
+
export function removedLabel(kind, file) {
|
|
40
|
+
if (kind === "secret_file")
|
|
41
|
+
return `[removed: contents of ${file ?? "a secret file"}]`;
|
|
42
|
+
return `[removed: ${REMOVED_WORDS[kind]}]`;
|
|
43
|
+
}
|
|
44
|
+
/** Counts added together. */
|
|
45
|
+
export function addRemoved(a, b) {
|
|
46
|
+
const out = { ...a };
|
|
47
|
+
for (const k of REMOVED_KINDS)
|
|
48
|
+
if (b[k])
|
|
49
|
+
out[k] = (out[k] ?? 0) + b[k];
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** How many things the counts name. */
|
|
53
|
+
export function removedTotal(c) {
|
|
54
|
+
return REMOVED_KINDS.reduce((n, k) => n + (c[k] ?? 0), 0);
|
|
55
|
+
}
|
|
56
|
+
// --- Checks a pattern's match must also pass ---------------------------------------------------
|
|
57
|
+
/** The Luhn check card numbers carry. */
|
|
58
|
+
export function passesLuhn(digits) {
|
|
59
|
+
let sum = 0;
|
|
60
|
+
for (let i = 0; i < digits.length; i++) {
|
|
61
|
+
let d = digits.charCodeAt(digits.length - 1 - i) - 48;
|
|
62
|
+
if (d < 0 || d > 9)
|
|
63
|
+
return false;
|
|
64
|
+
if (i % 2 === 1) {
|
|
65
|
+
d *= 2;
|
|
66
|
+
if (d > 9)
|
|
67
|
+
d -= 9;
|
|
68
|
+
}
|
|
69
|
+
sum += d;
|
|
70
|
+
}
|
|
71
|
+
return sum % 10 === 0;
|
|
72
|
+
}
|
|
73
|
+
/** A card number's first digits, for the networks that issue cards. */
|
|
74
|
+
const CARD_PREFIX = /^(?:4|5[1-5]|2[2-7]|3[47]|3[068]|35|6011|65|64[4-9]|62)/;
|
|
75
|
+
/** The IBAN check: the country and check digits moved to the end, as a number, leave 1 after dividing by 97. */
|
|
76
|
+
export function passesIban(iban) {
|
|
77
|
+
const s = iban.replace(/\s+/g, "").toUpperCase();
|
|
78
|
+
if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(s))
|
|
79
|
+
return false;
|
|
80
|
+
const moved = s.slice(4) + s.slice(0, 4);
|
|
81
|
+
let rest = 0;
|
|
82
|
+
for (const ch of moved) {
|
|
83
|
+
const code = ch.charCodeAt(0);
|
|
84
|
+
const part = code >= 65 ? String(code - 55) : ch;
|
|
85
|
+
for (const d of part)
|
|
86
|
+
rest = (rest * 10 + (d.charCodeAt(0) - 48)) % 97;
|
|
87
|
+
}
|
|
88
|
+
return rest === 1;
|
|
89
|
+
}
|
|
90
|
+
/** Bits a character, over the value's own characters. */
|
|
91
|
+
function entropy(v) {
|
|
92
|
+
const seen = new Map();
|
|
93
|
+
for (const ch of v)
|
|
94
|
+
seen.set(ch, (seen.get(ch) ?? 0) + 1);
|
|
95
|
+
let e = 0;
|
|
96
|
+
for (const n of seen.values()) {
|
|
97
|
+
const p = n / v.length;
|
|
98
|
+
e -= p * Math.log2(p);
|
|
99
|
+
}
|
|
100
|
+
return e;
|
|
101
|
+
}
|
|
102
|
+
/** A value that names something else (an environment variable, a function, a placeholder), never a secret itself. */
|
|
103
|
+
const REFERENCE = /^(?:\$|%|\{|\[|<|process\.env|import\.meta|os\.environ|env\.|getenv|this\.|self\.|secrets\.|vars\.|true$|false$|null$|undefined$|none$|string$|number$|boolean$)/i;
|
|
104
|
+
const PLACEHOLDER = /(?:x{4,}|\*{3,}|\.{3}|your[_-]|changeme|example|placeholder|redacted|removed|dummy|sample|fake[_-]?|test[_-]?(?:key|token|secret))/i;
|
|
105
|
+
/**
|
|
106
|
+
* Whether a value given to a key, secret, token or password name looks random: long enough, more
|
|
107
|
+
* than one kind of character, and not a word, a reference or a placeholder. A password may be
|
|
108
|
+
* shorter than a key.
|
|
109
|
+
*/
|
|
110
|
+
export function looksRandom(v, o) {
|
|
111
|
+
if (REFERENCE.test(v) || PLACEHOLDER.test(v))
|
|
112
|
+
return false;
|
|
113
|
+
const min = o.password ? 8 : 12;
|
|
114
|
+
if (v.length < min)
|
|
115
|
+
return false;
|
|
116
|
+
const kinds = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((r) => r.test(v)).length;
|
|
117
|
+
if (kinds < 2)
|
|
118
|
+
return false;
|
|
119
|
+
// An identifier such as someFunctionName or SOME_CONSTANT reads as words, not as a secret.
|
|
120
|
+
if (!/\d/.test(v) && /^[A-Za-z]+(?:[_-][A-Za-z]+)*$/.test(v))
|
|
121
|
+
return false;
|
|
122
|
+
return entropy(v) >= (o.password ? 2.5 : 3);
|
|
123
|
+
}
|
|
124
|
+
// --- Email addresses ----------------------------------------------------------------------------
|
|
125
|
+
/** Domains made for examples and tests: addresses there are kept. */
|
|
126
|
+
function exampleDomain(domain) {
|
|
127
|
+
const d = domain.toLowerCase();
|
|
128
|
+
return /(?:^|\.)example\.(?:com|org|net)$/.test(d) || /\.(?:example|test|invalid)$/.test(d) || d === "example" || d === "test" || d === "invalid";
|
|
129
|
+
}
|
|
130
|
+
const W = "(?<![A-Za-z0-9_])";
|
|
131
|
+
const E = "(?![A-Za-z0-9_])";
|
|
132
|
+
/** In this order: what has a sure shape first, then names and values, then personal details. */
|
|
133
|
+
const RULES = [
|
|
134
|
+
// Private key blocks, whole, to their END line (or to the end of the text when it is cut).
|
|
135
|
+
{ kind: "private_key", re: /-----BEGIN ((?:[A-Z0-9]+ )*)PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END \1PRIVATE KEY(?: BLOCK)?-----|$)/g },
|
|
136
|
+
// A Work key's shape: ygw_, its id, its secret and its checksum.
|
|
137
|
+
{ kind: "api_key", re: new RegExp(`${W}ygw_[a-z2-7]{20}_[A-Za-z0-9_-]{49}(?![A-Za-z0-9_-])`, "g") },
|
|
138
|
+
// GitHub tokens.
|
|
139
|
+
{ kind: "token", re: new RegExp(`${W}(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za-z0-9_]{22,255})${E}`, "g") },
|
|
140
|
+
// Google API keys and access tokens.
|
|
141
|
+
{ kind: "api_key", re: new RegExp(`${W}AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9_-])`, "g") },
|
|
142
|
+
{ kind: "token", re: new RegExp(`${W}ya29\\.[0-9A-Za-z_-]{20,}`, "g") },
|
|
143
|
+
// AWS access key ids.
|
|
144
|
+
{ kind: "api_key", re: /(?<![A-Z0-9])(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}(?![A-Z0-9])/g },
|
|
145
|
+
// Slack tokens.
|
|
146
|
+
{ kind: "token", re: new RegExp(`${W}(?:xox[abposr]-[0-9A-Za-z-]{10,}|xapp-\\d-[0-9A-Za-z-]{10,})`, "g") },
|
|
147
|
+
// Stripe secret and restricted keys, and webhook signing secrets.
|
|
148
|
+
{ kind: "api_key", re: new RegExp(`${W}(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{10,}${E}`, "g") },
|
|
149
|
+
{ kind: "secret", re: new RegExp(`${W}whsec_[0-9A-Za-z]{16,}${E}`, "g") },
|
|
150
|
+
// npm tokens.
|
|
151
|
+
{ kind: "token", re: new RegExp(`${W}npm_[A-Za-z0-9]{36}${E}`, "g") },
|
|
152
|
+
// Anthropic keys, then OpenAI keys (which must hold a digit, so a long name with dashes stays).
|
|
153
|
+
{ kind: "api_key", re: new RegExp(`${W}sk-ant-[A-Za-z0-9_-]{20,}`, "g") },
|
|
154
|
+
{ kind: "api_key", re: new RegExp(`${W}sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}`, "g"), replace: (m) => (/\d/.test(m[0]) ? removedLabel("api_key") : null) },
|
|
155
|
+
// JSON web tokens.
|
|
156
|
+
{ kind: "token", re: new RegExp(`${W}eyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}`, "g") },
|
|
157
|
+
// Authorization and API key header values: the header and its scheme stay.
|
|
158
|
+
{
|
|
159
|
+
kind: "password",
|
|
160
|
+
re: /(?<![A-Za-z0-9_-])((?:proxy-)?authorization|x-api-key|api-key|x-auth-token)(["']?\s*[:=]\s*["']?)((?:bearer|basic|token|bot)\s+)?([^\s"',;]+)/gi,
|
|
161
|
+
replace: (m) => (m[4].startsWith("[removed") || REFERENCE.test(m[4]) ? null : `${m[1]}${m[2]}${m[3] ?? ""}${removedLabel("password")}`),
|
|
162
|
+
},
|
|
163
|
+
// A password in an address: scheme://user:password@host.
|
|
164
|
+
{
|
|
165
|
+
kind: "password",
|
|
166
|
+
re: /(?<![A-Za-z0-9+.-])([a-z][a-z0-9+.-]{1,20}:\/\/[^\s:/@"'<>]{1,200}:)([^\s@/"'<>]{1,200})(@)/gi,
|
|
167
|
+
replace: (m) => (REFERENCE.test(m[2]) || m[2].startsWith("[removed") ? null : `${m[1]}${removedLabel("password")}${m[3]}`),
|
|
168
|
+
},
|
|
169
|
+
// A value given to a name that ends in key, secret, token or password, when it looks random.
|
|
170
|
+
{
|
|
171
|
+
kind: "secret",
|
|
172
|
+
re: /(?<![A-Za-z0-9_.-])([A-Za-z0-9_.-]{0,60}?(key|secret|token|password|passwd|pwd)s?["']?\s*(?:=>|:|=)\s*["']?)([^\s"'`,;()[\]{}<>]{1,400})/gi,
|
|
173
|
+
replace: (m) => (m[3].startsWith("[removed") || !looksRandom(m[3], { password: /^p/i.test(m[2]) }) ? null : `${m[1]}${removedLabel("secret")}`),
|
|
174
|
+
},
|
|
175
|
+
// Images written into text.
|
|
176
|
+
{ kind: "image", re: /data:image\/[a-z0-9.+-]{1,30};base64,[A-Za-z0-9+/=]{16,}/gi },
|
|
177
|
+
// Email addresses, but example and test domains, and git's own ssh user (git@host:owner/repo).
|
|
178
|
+
{
|
|
179
|
+
kind: "email",
|
|
180
|
+
re: /(?<![A-Za-z0-9._%+-])([A-Za-z0-9._%+-]{1,64})@((?:[A-Za-z0-9-]{1,63}\.){1,8}[A-Za-z]{2,24})(?![A-Za-z0-9-])/g,
|
|
181
|
+
replace: (m) => (exampleDomain(m[2]) || m[1].toLowerCase() === "git" ? null : removedLabel("email")),
|
|
182
|
+
},
|
|
183
|
+
// Phone numbers written with + or tel:, 8 to 15 digits.
|
|
184
|
+
{
|
|
185
|
+
kind: "phone",
|
|
186
|
+
re: /(?:tel:|(?<![\w+])\+)(\d[\d ().-]{5,22}\d)(?!\d)/gi,
|
|
187
|
+
replace: (m) => {
|
|
188
|
+
const digits = m[1].replace(/\D/g, "");
|
|
189
|
+
return digits.length >= 8 && digits.length <= 15 ? removedLabel("phone") : null;
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
// Card numbers: 13 to 19 digits, in groups or not, from a card network, that pass the Luhn check.
|
|
193
|
+
{
|
|
194
|
+
kind: "card",
|
|
195
|
+
re: /(?<![\d-])(?:\d[ -]?){12,18}\d(?![\d-])/g,
|
|
196
|
+
replace: (m) => {
|
|
197
|
+
const digits = m[0].replace(/\D/g, "");
|
|
198
|
+
return digits.length >= 13 && digits.length <= 19 && CARD_PREFIX.test(digits) && passesLuhn(digits) ? removedLabel("card") : null;
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
// IBANs, in groups of four or not, that pass their check.
|
|
202
|
+
{
|
|
203
|
+
kind: "bank_account",
|
|
204
|
+
re: /(?<![A-Za-z0-9])[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?(?![A-Za-z0-9])/g,
|
|
205
|
+
replace: (m) => (passesIban(m[0]) ? removedLabel("bank_account") : null),
|
|
206
|
+
},
|
|
207
|
+
];
|
|
208
|
+
/** One text through the table: every match replaced with its label, and how many of each. */
|
|
209
|
+
export function scanText(text) {
|
|
210
|
+
const removed = {};
|
|
211
|
+
if (!text)
|
|
212
|
+
return { text, removed };
|
|
213
|
+
let out = text;
|
|
214
|
+
for (const rule of RULES) {
|
|
215
|
+
rule.re.lastIndex = 0;
|
|
216
|
+
// A quick look first: most text holds nothing, and most rules find nothing.
|
|
217
|
+
if (!rule.re.test(out))
|
|
218
|
+
continue;
|
|
219
|
+
rule.re.lastIndex = 0;
|
|
220
|
+
out = out.replace(rule.re, (...args) => {
|
|
221
|
+
const groups = args.slice(0, -2);
|
|
222
|
+
const match = Object.assign([...groups], { index: args[args.length - 2], input: out });
|
|
223
|
+
const next = rule.replace ? rule.replace(match) : removedLabel(rule.kind);
|
|
224
|
+
if (next === null)
|
|
225
|
+
return groups[0];
|
|
226
|
+
removed[rule.kind] = (removed[rule.kind] ?? 0) + 1;
|
|
227
|
+
return next;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
return { text: out, removed };
|
|
231
|
+
}
|
|
232
|
+
/** The labels a text already holds, by kind: what the hook removed before it sent the text. */
|
|
233
|
+
export function labelsIn(text) {
|
|
234
|
+
const out = {};
|
|
235
|
+
if (!text.includes("[removed: "))
|
|
236
|
+
return out;
|
|
237
|
+
const byWords = new Map(Object.entries(REMOVED_WORDS).map(([k, v]) => [v, k]));
|
|
238
|
+
for (const m of text.matchAll(/\[removed: (contents of [^\]\n]{1,200}|[a-zA-Z ]{1,40})\]/g)) {
|
|
239
|
+
const words = m[1];
|
|
240
|
+
const kind = words.startsWith("contents of ") ? "secret_file" : byWords.get(words);
|
|
241
|
+
if (kind)
|
|
242
|
+
out[kind] = (out[kind] ?? 0) + 1;
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
// --- Secret files --------------------------------------------------------------------------------
|
|
247
|
+
/**
|
|
248
|
+
* Whether a file is one whose contents are secret: `.env` files other than `.env.example`, `.pem`,
|
|
249
|
+
* `.key`, `.p12` and `.pfx` files, `id_rsa` and the other ssh keys, `credentials*.json`, service
|
|
250
|
+
* account files, `.npmrc`, `.netrc` and `.pypirc`: the same kind of list a repo's own Claude Code
|
|
251
|
+
* settings deny reading. Answers the file's own name, or null.
|
|
252
|
+
*/
|
|
253
|
+
export function secretFileName(path) {
|
|
254
|
+
const name = path.split(/[\\/]/).pop() ?? "";
|
|
255
|
+
if (!name)
|
|
256
|
+
return null;
|
|
257
|
+
const n = name.toLowerCase();
|
|
258
|
+
if (n === ".env" || (n.startsWith(".env.") && n !== ".env.example"))
|
|
259
|
+
return name;
|
|
260
|
+
if (/\.(?:pem|key|p12|pfx)$/.test(n))
|
|
261
|
+
return name;
|
|
262
|
+
if (/^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.|$)/.test(n) && !n.endsWith(".pub"))
|
|
263
|
+
return name;
|
|
264
|
+
if (/^credentials.*\.json$/.test(n) || /service[-_]?account.*\.json$/.test(n))
|
|
265
|
+
return name;
|
|
266
|
+
if (n === ".npmrc" || n === ".netrc" || n === ".pypirc")
|
|
267
|
+
return name;
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
/** The secret file a tool call reads, by its name and input: Read and Grep by their path, Bash by any path its command names. */
|
|
271
|
+
export function secretFileOfCall(tool, input) {
|
|
272
|
+
const o = input && typeof input === "object" ? input : {};
|
|
273
|
+
const paths = [];
|
|
274
|
+
for (const k of ["file_path", "path", "notebook_path"])
|
|
275
|
+
if (typeof o[k] === "string")
|
|
276
|
+
paths.push(o[k]);
|
|
277
|
+
if (tool === "Bash" && typeof o.command === "string")
|
|
278
|
+
paths.push(...o.command.split(/[\s'"`;|&<>()=]+/).filter(Boolean));
|
|
279
|
+
for (const p of paths) {
|
|
280
|
+
const hit = secretFileName(p);
|
|
281
|
+
if (hit)
|
|
282
|
+
return hit;
|
|
283
|
+
}
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the Work hook keeps on the person's computer (K's Work slice, plan section 6b), all under
|
|
3
|
+
* `~/.yougrow/`, readable only by them:
|
|
4
|
+
*
|
|
5
|
+
* - `work-hook.mjs`: the file Claude Code runs, written by `work-hook install`, and `hook/`, the
|
|
6
|
+
* hook's own modules it loads, copied from the package, so no event waits on npx or the
|
|
7
|
+
* network to start;
|
|
8
|
+
* - `work-hook.json`: this copy's address and where the key is saved (never the key);
|
|
9
|
+
* - `work-key`: the key, only where no keychain is there to keep it (keychain.ts);
|
|
10
|
+
* - `notice.txt`: a line the next SessionStart prints once (the hook is out of date);
|
|
11
|
+
* - `sessions/<Claude Code's session id>.json`: one a chat: its Work session id, how far it has
|
|
12
|
+
* sent the transcript, the next part, the scan's running state and the last send. Deleted 30
|
|
13
|
+
* days after the chat's last event.
|
|
14
|
+
*
|
|
15
|
+
* Nothing here holds a transcript's words, except the scanned compaction summaries waiting to be
|
|
16
|
+
* sent again after a failed send.
|
|
17
|
+
*/
|
|
18
|
+
/** The environment the hook reads: a few named variables, never all of it. */
|
|
19
|
+
export type HookEnv = Readonly<Record<string, string | undefined>>;
|
|
20
|
+
/** The package version this hook ships in; a part's answers and the update line name it. */
|
|
21
|
+
export declare const HOOK_VERSION = "0.6.0";
|
|
22
|
+
export declare const HOOK_PACKAGE = "@yougrowai/node";
|
|
23
|
+
/** A chat's state is deleted this long after its last event. */
|
|
24
|
+
export declare const STATE_KEEP_MS: number;
|
|
25
|
+
/** A lock older than this was left by a hook that stopped; it is taken over. */
|
|
26
|
+
export declare const LOCK_STALE_MS: number;
|
|
27
|
+
export interface HookPaths {
|
|
28
|
+
home: string;
|
|
29
|
+
dir: string;
|
|
30
|
+
hookFile: string;
|
|
31
|
+
/** The hook's modules, one folder a version. */
|
|
32
|
+
hookRoot: string;
|
|
33
|
+
config: string;
|
|
34
|
+
keyFile: string;
|
|
35
|
+
sessions: string;
|
|
36
|
+
flushLock: string;
|
|
37
|
+
notice: string;
|
|
38
|
+
}
|
|
39
|
+
export declare function pathsFor(home?: string): HookPaths;
|
|
40
|
+
/**
|
|
41
|
+
* Claude Code's own session id, the only thing a state file is named by: never a path. It starts
|
|
42
|
+
* with a letter or a digit, as Work's own check does, so it never reads as a flag.
|
|
43
|
+
*/
|
|
44
|
+
export declare const AGENT_SESSION_ID: RegExp;
|
|
45
|
+
export type KeyStoreKind = "keychain" | "secret_service" | "file";
|
|
46
|
+
/** `~/.yougrow/work-hook.json`: this copy, and where the key is saved. */
|
|
47
|
+
export interface HookConfig {
|
|
48
|
+
v: 1;
|
|
49
|
+
/** This copy of YouGrow, as an origin: `https://app.hearth.example`. */
|
|
50
|
+
url: string;
|
|
51
|
+
store: KeyStoreKind;
|
|
52
|
+
/** The account the key is saved under: the copy's host. */
|
|
53
|
+
account: string;
|
|
54
|
+
installedAt: string;
|
|
55
|
+
version: string;
|
|
56
|
+
}
|
|
57
|
+
/** Where the transcript stands, as Work's last answer said it. */
|
|
58
|
+
export type TranscriptState = {
|
|
59
|
+
on: true;
|
|
60
|
+
nextPart: number;
|
|
61
|
+
offset: number;
|
|
62
|
+
minScan: number;
|
|
63
|
+
} | {
|
|
64
|
+
on: false;
|
|
65
|
+
why: string;
|
|
66
|
+
message: string;
|
|
67
|
+
};
|
|
68
|
+
/** A compaction summary, scanned, whose send failed: sent again with the next event. */
|
|
69
|
+
export interface PendingCompact {
|
|
70
|
+
trigger: "auto" | "manual";
|
|
71
|
+
summary: string;
|
|
72
|
+
at: number;
|
|
73
|
+
}
|
|
74
|
+
/** The start event as first sent, kept when Work didn't answer, so a later event can start the session. */
|
|
75
|
+
export type StartBody = Record<string, unknown>;
|
|
76
|
+
/** `~/.yougrow/sessions/<id>.json`: one chat. */
|
|
77
|
+
export interface SessionState {
|
|
78
|
+
v: 1;
|
|
79
|
+
agentSessionId: string;
|
|
80
|
+
/** Work's session id, `ws_…`, once Work has answered a start. */
|
|
81
|
+
session: string | null;
|
|
82
|
+
/** Claude Code's transcript file on this computer: read here, never sent. */
|
|
83
|
+
transcriptPath: string | null;
|
|
84
|
+
cwd: string | null;
|
|
85
|
+
/** The commit the chat started on, and the last head the stop event sent. */
|
|
86
|
+
startHead: string | null;
|
|
87
|
+
sentHead: string | null;
|
|
88
|
+
turns: number;
|
|
89
|
+
startedAt: number;
|
|
90
|
+
lastEventAt: number;
|
|
91
|
+
/** When the last stop event went to Work: at most one a minute. */
|
|
92
|
+
lastStopAt: number | null;
|
|
93
|
+
/** What PreCompact prints, from Work's last answer. */
|
|
94
|
+
facts: string | null;
|
|
95
|
+
transcript: TranscriptState | null;
|
|
96
|
+
/** How far into Claude Code's file the hook has read and sent (or left out). */
|
|
97
|
+
offset: number;
|
|
98
|
+
nextPart: number;
|
|
99
|
+
/** The tool calls that read a secret file, waiting for their results. */
|
|
100
|
+
scan: {
|
|
101
|
+
secretCalls: Array<{
|
|
102
|
+
id: string;
|
|
103
|
+
file: string;
|
|
104
|
+
}>;
|
|
105
|
+
};
|
|
106
|
+
lastPartAt: number | null;
|
|
107
|
+
/** Parts Work refused as not transcript lines, skipped so the hook never sends one again. */
|
|
108
|
+
refusedParts: number;
|
|
109
|
+
/** Why Work refused this chat's start, when sending it again won't change that: no later event sends until the next start. */
|
|
110
|
+
refused: string | null;
|
|
111
|
+
pending: PendingCompact[];
|
|
112
|
+
/** The start Work never answered, sent again before the next event. */
|
|
113
|
+
retryStart: StartBody | null;
|
|
114
|
+
}
|
|
115
|
+
export declare function newSessionState(agentSessionId: string, now: number): SessionState;
|
|
116
|
+
/** A folder only its person can open. */
|
|
117
|
+
export declare function ensureDir(dir: string): void;
|
|
118
|
+
/** Write a file whole, readable only by its person: a reader never sees half of it. */
|
|
119
|
+
export declare function writeFileAtomic(file: string, data: string | Buffer, mode?: number): void;
|
|
120
|
+
export declare function readConfig(paths: HookPaths): HookConfig | null;
|
|
121
|
+
export declare function writeConfig(paths: HookPaths, config: HookConfig): void;
|
|
122
|
+
export declare function stateFile(paths: HookPaths, agentSessionId: string): string;
|
|
123
|
+
export declare function readState(paths: HookPaths, agentSessionId: string): SessionState | null;
|
|
124
|
+
/**
|
|
125
|
+
* Change a chat's state: read the newest copy, change it, write it whole. The events change the
|
|
126
|
+
* session's fields and the transcript upload its own, so reading just before each write keeps
|
|
127
|
+
* both.
|
|
128
|
+
*/
|
|
129
|
+
export declare function updateState(paths: HookPaths, agentSessionId: string, now: number, change: (s: SessionState) => SessionState): SessionState;
|
|
130
|
+
/** Every chat this computer has state for, newest first. */
|
|
131
|
+
export declare function listStates(paths: HookPaths): SessionState[];
|
|
132
|
+
/** Delete what a chat left once it has been quiet for 30 days: its state and any lock. */
|
|
133
|
+
export declare function cleanUp(paths: HookPaths, now: number, keepMs?: number): number;
|
|
134
|
+
/**
|
|
135
|
+
* Take a lock file, so two uploads of one chat never overlap. A lock left by a hook that stopped
|
|
136
|
+
* (its process gone, or older than 10 minutes) is taken over. Answers a release, or null when
|
|
137
|
+
* another hook holds it.
|
|
138
|
+
*/
|
|
139
|
+
export declare function takeLock(file: string, now: number, staleMs?: number): (() => void) | null;
|
|
140
|
+
export declare function lockFile(paths: HookPaths, agentSessionId: string): string;
|
|
141
|
+
/** Keep a line for the next SessionStart on this computer to print, once. */
|
|
142
|
+
export declare function keepNotice(paths: HookPaths, text: string): void;
|
|
143
|
+
/** The line kept for this start, taken so no other start prints it again. */
|
|
144
|
+
export declare function takeNotice(paths: HookPaths): string | null;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
/** The package version this hook ships in; a part's answers and the update line name it. */
|
|
5
|
+
export const HOOK_VERSION = "0.6.0";
|
|
6
|
+
export const HOOK_PACKAGE = "@yougrowai/node";
|
|
7
|
+
const DAY_MS = 86_400_000;
|
|
8
|
+
/** A chat's state is deleted this long after its last event. */
|
|
9
|
+
export const STATE_KEEP_MS = 30 * DAY_MS;
|
|
10
|
+
/** A lock older than this was left by a hook that stopped; it is taken over. */
|
|
11
|
+
export const LOCK_STALE_MS = 10 * 60_000;
|
|
12
|
+
export function pathsFor(home = os.homedir()) {
|
|
13
|
+
const dir = path.join(home, ".yougrow");
|
|
14
|
+
return {
|
|
15
|
+
home,
|
|
16
|
+
dir,
|
|
17
|
+
hookFile: path.join(dir, "work-hook.mjs"),
|
|
18
|
+
hookRoot: path.join(dir, "hook"),
|
|
19
|
+
config: path.join(dir, "work-hook.json"),
|
|
20
|
+
keyFile: path.join(dir, "work-key"),
|
|
21
|
+
sessions: path.join(dir, "sessions"),
|
|
22
|
+
flushLock: path.join(dir, "flush.lock"),
|
|
23
|
+
notice: path.join(dir, "notice.txt"),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Claude Code's own session id, the only thing a state file is named by: never a path. It starts
|
|
28
|
+
* with a letter or a digit, as Work's own check does, so it never reads as a flag.
|
|
29
|
+
*/
|
|
30
|
+
export const AGENT_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
|
|
31
|
+
export function newSessionState(agentSessionId, now) {
|
|
32
|
+
return {
|
|
33
|
+
v: 1,
|
|
34
|
+
agentSessionId,
|
|
35
|
+
session: null,
|
|
36
|
+
transcriptPath: null,
|
|
37
|
+
cwd: null,
|
|
38
|
+
startHead: null,
|
|
39
|
+
sentHead: null,
|
|
40
|
+
turns: 0,
|
|
41
|
+
startedAt: now,
|
|
42
|
+
lastEventAt: now,
|
|
43
|
+
lastStopAt: null,
|
|
44
|
+
facts: null,
|
|
45
|
+
transcript: null,
|
|
46
|
+
offset: 0,
|
|
47
|
+
nextPart: 1,
|
|
48
|
+
scan: { secretCalls: [] },
|
|
49
|
+
lastPartAt: null,
|
|
50
|
+
refusedParts: 0,
|
|
51
|
+
refused: null,
|
|
52
|
+
pending: [],
|
|
53
|
+
retryStart: null,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
57
|
+
/** A folder only its person can open. */
|
|
58
|
+
export function ensureDir(dir) {
|
|
59
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
60
|
+
try {
|
|
61
|
+
fs.chmodSync(dir, 0o700);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// Windows keeps its own permissions.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Write a file whole, readable only by its person: a reader never sees half of it. */
|
|
68
|
+
export function writeFileAtomic(file, data, mode = 0o600) {
|
|
69
|
+
ensureDir(path.dirname(file));
|
|
70
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
71
|
+
fs.writeFileSync(tmp, data, { mode });
|
|
72
|
+
try {
|
|
73
|
+
fs.chmodSync(tmp, mode);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// Windows keeps its own permissions.
|
|
77
|
+
}
|
|
78
|
+
fs.renameSync(tmp, file);
|
|
79
|
+
}
|
|
80
|
+
function readJson(file) {
|
|
81
|
+
try {
|
|
82
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function readConfig(paths) {
|
|
89
|
+
const c = readJson(paths.config);
|
|
90
|
+
if (!isObject(c) || c.v !== 1 || typeof c.url !== "string" || typeof c.account !== "string")
|
|
91
|
+
return null;
|
|
92
|
+
if (c.store !== "keychain" && c.store !== "secret_service" && c.store !== "file")
|
|
93
|
+
return null;
|
|
94
|
+
return c;
|
|
95
|
+
}
|
|
96
|
+
export function writeConfig(paths, config) {
|
|
97
|
+
writeFileAtomic(paths.config, `${JSON.stringify(config, null, 2)}\n`);
|
|
98
|
+
}
|
|
99
|
+
export function stateFile(paths, agentSessionId) {
|
|
100
|
+
if (!AGENT_SESSION_ID.test(agentSessionId))
|
|
101
|
+
throw new Error("not a session id");
|
|
102
|
+
return path.join(paths.sessions, `${agentSessionId}.json`);
|
|
103
|
+
}
|
|
104
|
+
export function readState(paths, agentSessionId) {
|
|
105
|
+
if (!AGENT_SESSION_ID.test(agentSessionId))
|
|
106
|
+
return null;
|
|
107
|
+
const s = readJson(stateFile(paths, agentSessionId));
|
|
108
|
+
if (!isObject(s) || s.v !== 1 || s.agentSessionId !== agentSessionId)
|
|
109
|
+
return null;
|
|
110
|
+
const base = newSessionState(agentSessionId, typeof s.startedAt === "number" ? s.startedAt : 0);
|
|
111
|
+
return { ...base, ...s, scan: isObject(s.scan) && Array.isArray(s.scan.secretCalls) ? s.scan : base.scan, pending: Array.isArray(s.pending) ? s.pending : [] };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Change a chat's state: read the newest copy, change it, write it whole. The events change the
|
|
115
|
+
* session's fields and the transcript upload its own, so reading just before each write keeps
|
|
116
|
+
* both.
|
|
117
|
+
*/
|
|
118
|
+
export function updateState(paths, agentSessionId, now, change) {
|
|
119
|
+
const cur = readState(paths, agentSessionId) ?? newSessionState(agentSessionId, now);
|
|
120
|
+
const next = { ...change(cur), lastEventAt: now };
|
|
121
|
+
writeFileAtomic(stateFile(paths, agentSessionId), `${JSON.stringify(next)}\n`);
|
|
122
|
+
return next;
|
|
123
|
+
}
|
|
124
|
+
/** Every chat this computer has state for, newest first. */
|
|
125
|
+
export function listStates(paths) {
|
|
126
|
+
let names;
|
|
127
|
+
try {
|
|
128
|
+
names = fs.readdirSync(paths.sessions);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
const out = [];
|
|
134
|
+
for (const n of names) {
|
|
135
|
+
const m = /^([A-Za-z0-9][A-Za-z0-9_-]{7,127})\.json$/.exec(n);
|
|
136
|
+
if (!m)
|
|
137
|
+
continue;
|
|
138
|
+
const s = readState(paths, m[1]);
|
|
139
|
+
if (s)
|
|
140
|
+
out.push(s);
|
|
141
|
+
}
|
|
142
|
+
return out.sort((a, b) => b.lastEventAt - a.lastEventAt);
|
|
143
|
+
}
|
|
144
|
+
/** Delete what a chat left once it has been quiet for 30 days: its state and any lock. */
|
|
145
|
+
export function cleanUp(paths, now, keepMs = STATE_KEEP_MS) {
|
|
146
|
+
let names;
|
|
147
|
+
try {
|
|
148
|
+
names = fs.readdirSync(paths.sessions);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
let n = 0;
|
|
154
|
+
for (const name of names.slice(0, 2_000)) {
|
|
155
|
+
if (!/^[A-Za-z0-9_-]{8,128}\.(?:json|lock)$/.test(name) && !name.endsWith(".tmp"))
|
|
156
|
+
continue;
|
|
157
|
+
const file = path.join(paths.sessions, name);
|
|
158
|
+
try {
|
|
159
|
+
if (now - fs.statSync(file).mtimeMs > keepMs) {
|
|
160
|
+
fs.unlinkSync(file);
|
|
161
|
+
n += 1;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// Gone already.
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return n;
|
|
169
|
+
}
|
|
170
|
+
// --- Locks ---------------------------------------------------------------------------------------
|
|
171
|
+
function alive(pid) {
|
|
172
|
+
try {
|
|
173
|
+
process.kill(pid, 0);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
return err.code === "EPERM";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Take a lock file, so two uploads of one chat never overlap. A lock left by a hook that stopped
|
|
182
|
+
* (its process gone, or older than 10 minutes) is taken over. Answers a release, or null when
|
|
183
|
+
* another hook holds it.
|
|
184
|
+
*/
|
|
185
|
+
export function takeLock(file, now, staleMs = LOCK_STALE_MS) {
|
|
186
|
+
ensureDir(path.dirname(file));
|
|
187
|
+
const mine = JSON.stringify({ pid: process.pid, at: now });
|
|
188
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
189
|
+
try {
|
|
190
|
+
const fd = fs.openSync(file, "wx", 0o600);
|
|
191
|
+
fs.writeSync(fd, mine);
|
|
192
|
+
fs.closeSync(fd);
|
|
193
|
+
return () => {
|
|
194
|
+
try {
|
|
195
|
+
if (fs.readFileSync(file, "utf8") === mine)
|
|
196
|
+
fs.unlinkSync(file);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// Taken over or gone.
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
if (err.code !== "EEXIST")
|
|
205
|
+
return null;
|
|
206
|
+
const held = readJson(file);
|
|
207
|
+
const pid = isObject(held) && typeof held.pid === "number" ? held.pid : null;
|
|
208
|
+
const at = isObject(held) && typeof held.at === "number" ? held.at : 0;
|
|
209
|
+
const stale = now - at > staleMs || (pid !== null && pid !== process.pid && !alive(pid));
|
|
210
|
+
if (!stale)
|
|
211
|
+
return null;
|
|
212
|
+
try {
|
|
213
|
+
fs.unlinkSync(file);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
export function lockFile(paths, agentSessionId) {
|
|
223
|
+
if (!AGENT_SESSION_ID.test(agentSessionId))
|
|
224
|
+
throw new Error("not a session id");
|
|
225
|
+
return path.join(paths.sessions, `${agentSessionId}.lock`);
|
|
226
|
+
}
|
|
227
|
+
// --- The one line the next start prints ----------------------------------------------------------
|
|
228
|
+
/** Keep a line for the next SessionStart on this computer to print, once. */
|
|
229
|
+
export function keepNotice(paths, text) {
|
|
230
|
+
writeFileAtomic(paths.notice, `${text.replace(/[\r\n]+/g, " ").slice(0, 600)}\n`);
|
|
231
|
+
}
|
|
232
|
+
/** The line kept for this start, taken so no other start prints it again. */
|
|
233
|
+
export function takeNotice(paths) {
|
|
234
|
+
let text;
|
|
235
|
+
try {
|
|
236
|
+
text = fs.readFileSync(paths.notice, "utf8").trim();
|
|
237
|
+
fs.unlinkSync(paths.notice);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
return text || null;
|
|
243
|
+
}
|