@yougrowai/node 0.5.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 +98 -3
- package/dist/cjs/server.d.ts +1 -1
- 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
package/README.md
CHANGED
|
@@ -25,7 +25,9 @@ const { YouGrow } = require("@yougrowai/node");
|
|
|
25
25
|
const { createVerifier, contextResponse } = require("@yougrowai/node/server");
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
Server-side only: your secret must never reach a browser or app bundle.
|
|
28
|
+
Server-side only: your secret must never reach a browser or app bundle. The one
|
|
29
|
+
exception is the `work-hook` command, for a person's own computer: see
|
|
30
|
+
[Record Claude Code chats in Work](#record-claude-code-chats-in-work-work-hook).
|
|
29
31
|
|
|
30
32
|
> Status: 0.x. The HTTP API is versioned (`/api/v2`); the SDK's own API may
|
|
31
33
|
> still change before 1.0.
|
|
@@ -288,8 +290,10 @@ app.post("/yougrow/context", express.raw({ type: "application/json" }), async (r
|
|
|
288
290
|
const v = await verifier.verify({ headers: req.headers, rawBody: req.body, direction: "context" });
|
|
289
291
|
if (!v.ok) return res.status(401).end();
|
|
290
292
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
+
// entity is { id, kind } when the email is about one of the user's entities
|
|
294
|
+
// (a workspace, a project…): answer for that one. Otherwise it's absent.
|
|
295
|
+
const { userId, entity } = JSON.parse(req.body.toString("utf8"));
|
|
296
|
+
const u = await loadOnboardingState(userId, entity);
|
|
293
297
|
res.type("json").send(
|
|
294
298
|
contextResponse({
|
|
295
299
|
steps: u.steps, // [{ id, label, done, url }]
|
|
@@ -364,6 +368,97 @@ at https://yougrow.ai/developers.
|
|
|
364
368
|
`test/vectors.json` (included in this package) holds reference tokens for
|
|
365
369
|
checking your own verifier.
|
|
366
370
|
|
|
371
|
+
## Record Claude Code chats in Work (`work-hook`)
|
|
372
|
+
|
|
373
|
+
The one part of this package for a person's own computer rather than a server.
|
|
374
|
+
`work-hook` records each Claude Code chat as a coding session in YouGrow Work,
|
|
375
|
+
through that person's Work key: the task it worked on, the repo and branch, its
|
|
376
|
+
commits, its compaction summaries and, where the organisation keeps them, its
|
|
377
|
+
transcript. The next chat on the task starts with the last one's closing note.
|
|
378
|
+
|
|
379
|
+
Make a key on **Work keys** in YouGrow (Claude Code, Read and write back, with
|
|
380
|
+
Record coding sessions ticked), then run these in your own terminal, with your
|
|
381
|
+
copy's address in place of `https://app.hearth.example`:
|
|
382
|
+
|
|
383
|
+
```sh
|
|
384
|
+
(
|
|
385
|
+
printf 'Paste your Work key, then press Enter: '
|
|
386
|
+
read -rs YOUGROW_WORK_KEY
|
|
387
|
+
echo
|
|
388
|
+
export YOUGROW_WORK_KEY
|
|
389
|
+
npx -y @yougrowai/node@0.6.0 work-hook install https://app.hearth.example
|
|
390
|
+
)
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Paste the lines as one block. When it asks for your Work key, paste the key and
|
|
394
|
+
press Enter: nothing shows as you paste, and your shell history keeps only the
|
|
395
|
+
variable's name. The key stays inside the block and is gone from the terminal
|
|
396
|
+
when it ends. `install`:
|
|
397
|
+
|
|
398
|
+
- checks the key with your copy of YouGrow, shows what it will change and asks
|
|
399
|
+
first (`--yes` skips the question);
|
|
400
|
+
- copies the hook to `~/.yougrow/`, so no chat waits on npx or the network to
|
|
401
|
+
start;
|
|
402
|
+
- saves the key in macOS Keychain, in the Secret Service on Linux (through
|
|
403
|
+
`secret-tool`), or else in `~/.yougrow/work-key`, readable only by you
|
|
404
|
+
(`--key-store file` picks the file);
|
|
405
|
+
- adds five hooks to your own `~/.claude/settings.json`, beside the hooks you
|
|
406
|
+
have, after a dated backup of the file. It never writes a project's
|
|
407
|
+
`.claude/settings.json`, which is often committed, and never Claude Code's
|
|
408
|
+
`env` settings, where every command an agent runs would hold the key.
|
|
409
|
+
|
|
410
|
+
Claude Code picks the hooks up by itself, in every folder you trust.
|
|
411
|
+
|
|
412
|
+
| Claude Code event | What the hook does |
|
|
413
|
+
|---|---|
|
|
414
|
+
| `SessionStart` (waits up to 10 seconds) | Starts or finds the session. Prints the lines Work answers, which Claude Code adds to the chat before the first prompt |
|
|
415
|
+
| `Stop` (in the background) | At most once a minute: the turns and the new commits. Then the transcript's new lines, in parts |
|
|
416
|
+
| `PreCompact` (waits up to 5 seconds) | Prints the session's facts, so the summary keeps the task, branch and pull request. Sends nothing |
|
|
417
|
+
| `PostCompact` (in the background) | Claude Code's summary, after the scan |
|
|
418
|
+
| `SessionEnd` (waits up to 5 seconds) | The end and its reason. Anything left to send goes in the background, or with the next start |
|
|
419
|
+
|
|
420
|
+
**What leaves your computer:** Claude Code's session id, the model, the chat's
|
|
421
|
+
title, the repo as `owner/name` (never its address), the branch, commit ids and
|
|
422
|
+
their first lines, the folder's own name (never its path), the summaries and,
|
|
423
|
+
when transcripts are on, the conversation: messages, tool calls and tool
|
|
424
|
+
results. Claude Code's own bookkeeping lines, thinking signatures, images and
|
|
425
|
+
subagents' own files stay on your computer.
|
|
426
|
+
|
|
427
|
+
**The scan:** before anything is sent, the hook replaces what it recognises with
|
|
428
|
+
a label such as `[removed: API key]`: private keys, Work keys and tokens of known
|
|
429
|
+
shapes, `Authorization` headers and passwords in addresses, random values given
|
|
430
|
+
to names ending in `KEY`, `SECRET`, `TOKEN` or `PASSWORD`, the contents of secret
|
|
431
|
+
files an agent read (`.env.local`, key files), email addresses outside example
|
|
432
|
+
domains, phone numbers, card and bank numbers, and images. Work scans
|
|
433
|
+
everything again before it keeps it. A scan finds only the shapes it knows, so a
|
|
434
|
+
secret of a new shape or a person's name can still get through.
|
|
435
|
+
|
|
436
|
+
**It never stops a chat:** whatever fails, it exits 0 and prints nothing, except
|
|
437
|
+
one line at start when Work isn't recording, such as "Work isn't recording this
|
|
438
|
+
chat: the Work key on this computer was revoked. Make a new one on Work keys."
|
|
439
|
+
|
|
440
|
+
To update the hook, run the `install` line again: without `YOUGROW_WORK_KEY` in
|
|
441
|
+
the terminal, it uses the key it saved for that copy, so no new key is needed.
|
|
442
|
+
To take it out, with its key and its
|
|
443
|
+
files: `npx -y @yougrowai/node@0.6.0 work-hook uninstall`. Sessions already in
|
|
444
|
+
Work stay there.
|
|
445
|
+
|
|
446
|
+
### Cloud sessions
|
|
447
|
+
|
|
448
|
+
Your own settings don't reach Claude Code on the web, so a team that wants its
|
|
449
|
+
cloud sessions recorded commits the hooks to its repo's `.claude/settings.json`.
|
|
450
|
+
`npx -y @yougrowai/node@0.6.0 work-hook entries --cloud` prints them. They hold
|
|
451
|
+
no key and run `work-hook run <event>`, which does nothing unless
|
|
452
|
+
`YOUGROW_WORK_URL` is set on the cloud environment. Give the environment the
|
|
453
|
+
key as a network secret for your copy's host, so the session never holds it.
|
|
454
|
+
On a computer where the hook is installed, `work-hook run` does nothing, so no
|
|
455
|
+
chat is recorded twice.
|
|
456
|
+
|
|
457
|
+
## Upgrading from 0.5
|
|
458
|
+
|
|
459
|
+
- New: the `work-hook` command, for a person's own computer. The client and
|
|
460
|
+
`@yougrowai/node/server` are unchanged.
|
|
461
|
+
|
|
367
462
|
## Upgrading from 0.4
|
|
368
463
|
|
|
369
464
|
- New: `entities` in `users.update` and on the state it returns, `entityId` on
|
package/dist/cjs/server.d.ts
CHANGED
|
@@ -108,7 +108,7 @@ export interface ContextFact {
|
|
|
108
108
|
}
|
|
109
109
|
export interface ContextInsight {
|
|
110
110
|
id: string;
|
|
111
|
-
/** A complete, TRUE sentence — the only
|
|
111
|
+
/** A complete, TRUE sentence — the only way an email says what the user's numbers mean. */
|
|
112
112
|
sentence: string;
|
|
113
113
|
factIds?: string[];
|
|
114
114
|
weight?: number;
|
package/dist/server.d.ts
CHANGED
|
@@ -108,7 +108,7 @@ export interface ContextFact {
|
|
|
108
108
|
}
|
|
109
109
|
export interface ContextInsight {
|
|
110
110
|
id: string;
|
|
111
|
-
/** A complete, TRUE sentence — the only
|
|
111
|
+
/** A complete, TRUE sentence — the only way an email says what the user's numbers mean. */
|
|
112
112
|
sentence: string;
|
|
113
113
|
factIds?: string[];
|
|
114
114
|
weight?: number;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* The command line. The launcher in ~/.yougrow passes `launcher`, and runs events only.
|
|
4
|
+
*
|
|
5
|
+
* `npx -y @yougrowai/node@0.6.0 work-hook install ...` runs the package's one bin with every word
|
|
6
|
+
* after the package, `work-hook` included, so a leading `work-hook` is dropped: the documented
|
|
7
|
+
* lines and `work-hook install ...` from an installed bin both work.
|
|
8
|
+
*/
|
|
9
|
+
export declare function main(given: string[], o?: {
|
|
10
|
+
launcher?: boolean;
|
|
11
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import * as readline from "node:readline";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { HOOK_EVENTS } from "./events.js";
|
|
7
|
+
import { runProgram } from "./keychain.js";
|
|
8
|
+
import { httpRequest, realRunDeps, runHookEvent } from "./run.js";
|
|
9
|
+
import { HOOK_VERSION, pathsFor } from "./state.js";
|
|
10
|
+
/**
|
|
11
|
+
* The `work-hook` command (K's Work slice, decision S6), in `@yougrowai/node` from 0.6.0:
|
|
12
|
+
*
|
|
13
|
+
* work-hook install <copy> [--yes] [--key-store file] on your own computer, once
|
|
14
|
+
* work-hook uninstall [--yes]
|
|
15
|
+
* work-hook entries [--cloud] prints the hooks, changes nothing
|
|
16
|
+
* work-hook <start|stop|precompact|compact|end> what Claude Code runs, through ~/.yougrow/work-hook.mjs
|
|
17
|
+
* work-hook run <event> a repo's committed hooks, for cloud sessions
|
|
18
|
+
*
|
|
19
|
+
* A hook event never gets in the way: it ends within its time, exits 0 whatever fails, and prints
|
|
20
|
+
* only the lines SessionStart and PreCompact are for.
|
|
21
|
+
*/
|
|
22
|
+
/** How long each event may take, inside the timeout its entry gives Claude Code. */
|
|
23
|
+
const BUDGET_MS = {
|
|
24
|
+
start: 9_000,
|
|
25
|
+
precompact: 4_000,
|
|
26
|
+
end: 4_500,
|
|
27
|
+
stop: 330_000,
|
|
28
|
+
compact: 330_000,
|
|
29
|
+
flush: 600_000,
|
|
30
|
+
};
|
|
31
|
+
const USAGE = [
|
|
32
|
+
`work-hook ${HOOK_VERSION}: records your Claude Code chats as coding sessions in YouGrow Work.`,
|
|
33
|
+
"",
|
|
34
|
+
" work-hook install https://your.copy.example [--yes] [--key-store file]",
|
|
35
|
+
" Reads the key from YOUGROW_WORK_KEY; without one, it prints the lines that ask for it.",
|
|
36
|
+
" Run again to update the hook: without YOUGROW_WORK_KEY it uses the key it saved for that copy.",
|
|
37
|
+
" work-hook uninstall [--yes]",
|
|
38
|
+
" work-hook entries [--cloud] the hooks install adds, or a repo's hooks for cloud sessions",
|
|
39
|
+
"",
|
|
40
|
+
"Claude Code runs the rest itself.",
|
|
41
|
+
].join("\n");
|
|
42
|
+
const isEvent = (v) => !!v && HOOK_EVENTS.includes(v);
|
|
43
|
+
function flag(args, name) {
|
|
44
|
+
return args.includes(name);
|
|
45
|
+
}
|
|
46
|
+
function option(args, name) {
|
|
47
|
+
const i = args.indexOf(name);
|
|
48
|
+
if (i >= 0)
|
|
49
|
+
return args[i + 1] ?? null;
|
|
50
|
+
const joined = args.find((a) => a.startsWith(`${name}=`));
|
|
51
|
+
return joined ? joined.slice(name.length + 1) : null;
|
|
52
|
+
}
|
|
53
|
+
/** A yes or no from the person's terminal, or null when there is no terminal to ask in. */
|
|
54
|
+
function askInTerminal(question) {
|
|
55
|
+
if (!process.stdin.isTTY)
|
|
56
|
+
return Promise.resolve(null);
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
59
|
+
rl.question(question, (answer) => {
|
|
60
|
+
rl.close();
|
|
61
|
+
resolve(/^\s*y(es)?\s*$/i.test(answer));
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Write and wait until it has gone: a pipe on macOS takes writes later, and the process ends after. */
|
|
66
|
+
function writeOut(text) {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
if (!process.stdout.write(`${text}\n`, () => resolve()))
|
|
69
|
+
process.stdout.once("drain", () => resolve());
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** One hook event, ended by its budget whatever happens. Prints only what the event is for. */
|
|
73
|
+
async function event(name, mode) {
|
|
74
|
+
const watchdog = setTimeout(() => process.exit(0), BUDGET_MS[name]);
|
|
75
|
+
watchdog.unref();
|
|
76
|
+
const printed = [];
|
|
77
|
+
try {
|
|
78
|
+
await runHookEvent(name, mode, realRunDeps(mode, (text) => printed.push(writeOut(text))));
|
|
79
|
+
await Promise.all(printed);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// Never in the way.
|
|
83
|
+
}
|
|
84
|
+
process.exit(0);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The command line. The launcher in ~/.yougrow passes `launcher`, and runs events only.
|
|
88
|
+
*
|
|
89
|
+
* `npx -y @yougrowai/node@0.6.0 work-hook install ...` runs the package's one bin with every word
|
|
90
|
+
* after the package, `work-hook` included, so a leading `work-hook` is dropped: the documented
|
|
91
|
+
* lines and `work-hook install ...` from an installed bin both work.
|
|
92
|
+
*/
|
|
93
|
+
export async function main(given, o = {}) {
|
|
94
|
+
const argv = given[0] === "work-hook" ? given.slice(1) : given;
|
|
95
|
+
const [first, second] = argv;
|
|
96
|
+
if (isEvent(first))
|
|
97
|
+
return event(first, "installed");
|
|
98
|
+
if (first === "run")
|
|
99
|
+
return isEvent(second) ? event(second, "run") : process.exit(0);
|
|
100
|
+
if (o.launcher)
|
|
101
|
+
return process.exit(0);
|
|
102
|
+
const args = argv.slice(1);
|
|
103
|
+
const out = (text) => process.stdout.write(`${text}\n`);
|
|
104
|
+
if (first === "install" || first === "uninstall") {
|
|
105
|
+
const { install, uninstall } = await import("./install.js");
|
|
106
|
+
const store = option(args, "--key-store");
|
|
107
|
+
if (store !== null && store !== "file" && store !== "keychain" && store !== "secret_service") {
|
|
108
|
+
out("--key-store takes file, keychain or secret_service.");
|
|
109
|
+
process.exit(2);
|
|
110
|
+
}
|
|
111
|
+
const deps = {
|
|
112
|
+
paths: pathsFor(),
|
|
113
|
+
env: process.env,
|
|
114
|
+
platform: process.platform,
|
|
115
|
+
now: () => new Date(),
|
|
116
|
+
hookSource: path.dirname(fileURLToPath(import.meta.url)),
|
|
117
|
+
request: httpRequest,
|
|
118
|
+
run: runProgram,
|
|
119
|
+
out,
|
|
120
|
+
ask: askInTerminal,
|
|
121
|
+
};
|
|
122
|
+
const url = args.find((a) => !a.startsWith("--") && a !== store) ?? null;
|
|
123
|
+
const code = first === "install" ? await install({ url, yes: flag(args, "--yes"), keyStore: store }, deps) : await uninstall({ yes: flag(args, "--yes") }, deps);
|
|
124
|
+
process.exit(code);
|
|
125
|
+
}
|
|
126
|
+
if (first === "entries") {
|
|
127
|
+
const { entriesText, hookEntries } = await import("./install.js");
|
|
128
|
+
out(entriesText(hookEntries({ cloud: flag(args, "--cloud") })));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (first === "--version" || first === "version") {
|
|
132
|
+
out(HOOK_VERSION);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
out(USAGE);
|
|
136
|
+
if (first && first !== "help" && first !== "--help" && first !== "-h")
|
|
137
|
+
process.exit(2);
|
|
138
|
+
}
|
|
139
|
+
/** Whether this file is the program node started, not a module another one loaded. */
|
|
140
|
+
function isEntry() {
|
|
141
|
+
const entry = process.argv[1];
|
|
142
|
+
if (!entry)
|
|
143
|
+
return false;
|
|
144
|
+
try {
|
|
145
|
+
return fs.realpathSync(entry) === fs.realpathSync(fileURLToPath(import.meta.url));
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (isEntry())
|
|
152
|
+
void main(process.argv.slice(2));
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type Commit, type GitFacts } from "./git.js";
|
|
2
|
+
import { type HookEnv } from "./state.js";
|
|
3
|
+
/**
|
|
4
|
+
* The events the hook sends Work (K's Work slice, plan section 6b), built from what Claude Code
|
|
5
|
+
* hands each hook on its standard input. Pure. They match HookEventSchema in the app's
|
|
6
|
+
* src/lib/work/sessions/types.ts; a field that doesn't fit its shape is left out, never sent.
|
|
7
|
+
*
|
|
8
|
+
* | Claude Code's event | The hook sends |
|
|
9
|
+
* |---|---|
|
|
10
|
+
* | SessionStart | `start`: the ids, how it started, the model, the title, where it runs, the repo, branch, head and folder |
|
|
11
|
+
* | Stop | `stop`, at most once a minute: turns, the head and branch, and the commits since the start |
|
|
12
|
+
* | PreCompact | nothing: it prints the facts Work last answered |
|
|
13
|
+
* | PostCompact | `compact`: Claude Code's summary, after the scan here |
|
|
14
|
+
* | SessionEnd | `end`: the reason |
|
|
15
|
+
*/
|
|
16
|
+
export declare const EVENT_VERSION = 1;
|
|
17
|
+
export declare const HOOK_EVENTS: readonly ["start", "stop", "precompact", "compact", "end", "flush"];
|
|
18
|
+
export type HookEventName = (typeof HOOK_EVENTS)[number];
|
|
19
|
+
declare const START_SOURCES: readonly ["startup", "resume", "clear", "compact", "fork"];
|
|
20
|
+
declare const END_REASONS: readonly ["clear", "resume", "logout", "prompt_input_exit", "other"];
|
|
21
|
+
/** A compaction summary's characters, as Work keeps them. */
|
|
22
|
+
export declare const SUMMARY_MAX = 40000;
|
|
23
|
+
/** A compact event's body, at most, with its summary. */
|
|
24
|
+
export declare const COMPACT_BODY_MAX = 200000;
|
|
25
|
+
/** What Claude Code hands a hook on its standard input: only the fields the hook reads. */
|
|
26
|
+
export interface HookInput {
|
|
27
|
+
sessionId: string;
|
|
28
|
+
transcriptPath: string | null;
|
|
29
|
+
cwd: string | null;
|
|
30
|
+
source?: (typeof START_SOURCES)[number];
|
|
31
|
+
model?: string;
|
|
32
|
+
title?: string;
|
|
33
|
+
trigger?: "auto" | "manual";
|
|
34
|
+
summary?: string;
|
|
35
|
+
reason?: (typeof END_REASONS)[number];
|
|
36
|
+
}
|
|
37
|
+
/** Claude Code's hook input, or null when it isn't one the hook can use. */
|
|
38
|
+
export declare function parseHookInput(text: string): HookInput | null;
|
|
39
|
+
/** Where the chat runs: a cloud session names its claude.ai id, with `cse_` read as `session_`. */
|
|
40
|
+
export declare function whereOf(env: HookEnv): {
|
|
41
|
+
where: "local";
|
|
42
|
+
} | {
|
|
43
|
+
where: "cloud";
|
|
44
|
+
cloudId: string;
|
|
45
|
+
};
|
|
46
|
+
/** A cloud session's address on claude.ai, as the docs build it. */
|
|
47
|
+
export declare function cloudAddress(cloudId: string): string;
|
|
48
|
+
export declare function startEvent(input: HookInput, git: GitFacts, env: HookEnv): Record<string, unknown>;
|
|
49
|
+
export declare function stopEvent(agentSessionId: string, o: {
|
|
50
|
+
turns: number;
|
|
51
|
+
git: GitFacts;
|
|
52
|
+
commits: Commit[] | null;
|
|
53
|
+
}): Record<string, unknown>;
|
|
54
|
+
/** A compaction summary as it leaves the computer: scanned, then cut to what Work keeps. */
|
|
55
|
+
export declare function scannedSummary(summary: string): string | null;
|
|
56
|
+
/** The compact event, its body under 200 KB: a summary dense with characters JSON escapes is cut further. */
|
|
57
|
+
export declare function compactEvent(agentSessionId: string, o: {
|
|
58
|
+
trigger: "auto" | "manual";
|
|
59
|
+
summary: string;
|
|
60
|
+
}): Record<string, unknown>;
|
|
61
|
+
export declare function endEvent(agentSessionId: string, reason: HookInput["reason"]): Record<string, unknown>;
|
|
62
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { folderOf } from "./git.js";
|
|
3
|
+
import { scanText } from "./scan.js";
|
|
4
|
+
import { AGENT_SESSION_ID } from "./state.js";
|
|
5
|
+
/**
|
|
6
|
+
* The events the hook sends Work (K's Work slice, plan section 6b), built from what Claude Code
|
|
7
|
+
* hands each hook on its standard input. Pure. They match HookEventSchema in the app's
|
|
8
|
+
* src/lib/work/sessions/types.ts; a field that doesn't fit its shape is left out, never sent.
|
|
9
|
+
*
|
|
10
|
+
* | Claude Code's event | The hook sends |
|
|
11
|
+
* |---|---|
|
|
12
|
+
* | SessionStart | `start`: the ids, how it started, the model, the title, where it runs, the repo, branch, head and folder |
|
|
13
|
+
* | Stop | `stop`, at most once a minute: turns, the head and branch, and the commits since the start |
|
|
14
|
+
* | PreCompact | nothing: it prints the facts Work last answered |
|
|
15
|
+
* | PostCompact | `compact`: Claude Code's summary, after the scan here |
|
|
16
|
+
* | SessionEnd | `end`: the reason |
|
|
17
|
+
*/
|
|
18
|
+
export const EVENT_VERSION = 1;
|
|
19
|
+
export const HOOK_EVENTS = ["start", "stop", "precompact", "compact", "end", "flush"];
|
|
20
|
+
const MODEL = /^[A-Za-z0-9._:[\]/-]{1,60}$/;
|
|
21
|
+
const CLOUD_SESSION_ID = /^session_[A-Za-z0-9]{1,120}$/;
|
|
22
|
+
const START_SOURCES = ["startup", "resume", "clear", "compact", "fork"];
|
|
23
|
+
const END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
|
|
24
|
+
const TITLE_MAX = 120;
|
|
25
|
+
/** A compaction summary's characters, as Work keeps them. */
|
|
26
|
+
export const SUMMARY_MAX = 40_000;
|
|
27
|
+
/** A compact event's body, at most, with its summary. */
|
|
28
|
+
export const COMPACT_BODY_MAX = 200_000;
|
|
29
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
30
|
+
const oneOf = (v, all) => (typeof v === "string" && all.includes(v) ? v : undefined);
|
|
31
|
+
/** The transcript file, when it is a full path to a `.jsonl` file: it is read here and never sent. */
|
|
32
|
+
function transcriptPathOf(v) {
|
|
33
|
+
const p = str(v);
|
|
34
|
+
return p && path.isAbsolute(p) && p.endsWith(".jsonl") && !p.includes("\0") ? p : null;
|
|
35
|
+
}
|
|
36
|
+
/** Claude Code's hook input, or null when it isn't one the hook can use. */
|
|
37
|
+
export function parseHookInput(text) {
|
|
38
|
+
let raw;
|
|
39
|
+
try {
|
|
40
|
+
raw = JSON.parse(text);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
46
|
+
return null;
|
|
47
|
+
const o = raw;
|
|
48
|
+
const sessionId = str(o.session_id);
|
|
49
|
+
if (!sessionId || !AGENT_SESSION_ID.test(sessionId))
|
|
50
|
+
return null;
|
|
51
|
+
const model = typeof o.model === "string" ? o.model : o.model && typeof o.model === "object" ? str(o.model.id) : undefined;
|
|
52
|
+
const cwd = str(o.cwd);
|
|
53
|
+
return {
|
|
54
|
+
sessionId,
|
|
55
|
+
transcriptPath: transcriptPathOf(o.transcript_path),
|
|
56
|
+
cwd: cwd && path.isAbsolute(cwd) ? cwd : null,
|
|
57
|
+
source: oneOf(o.source, START_SOURCES),
|
|
58
|
+
model: model && MODEL.test(model) ? model : undefined,
|
|
59
|
+
title: str(o.session_title),
|
|
60
|
+
trigger: oneOf(o.trigger, ["auto", "manual"]),
|
|
61
|
+
summary: str(o.compact_summary),
|
|
62
|
+
reason: oneOf(o.reason, END_REASONS) ?? (typeof o.reason === "string" ? "other" : undefined),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** One line, scanned, at most `max` characters. */
|
|
66
|
+
function line(text, max) {
|
|
67
|
+
const one = scanText(text.replace(/\s+/g, " ").trim()).text;
|
|
68
|
+
if (!one)
|
|
69
|
+
return undefined;
|
|
70
|
+
return one.length <= max ? one : `${one.slice(0, max - 1)}…`;
|
|
71
|
+
}
|
|
72
|
+
/** Where the chat runs: a cloud session names its claude.ai id, with `cse_` read as `session_`. */
|
|
73
|
+
export function whereOf(env) {
|
|
74
|
+
if (env.CLAUDE_CODE_REMOTE !== "true")
|
|
75
|
+
return { where: "local" };
|
|
76
|
+
const id = (env.CLAUDE_CODE_REMOTE_SESSION_ID ?? "").replace(/^cse_/, "session_");
|
|
77
|
+
return CLOUD_SESSION_ID.test(id) ? { where: "cloud", cloudId: id } : { where: "local" };
|
|
78
|
+
}
|
|
79
|
+
/** A cloud session's address on claude.ai, as the docs build it. */
|
|
80
|
+
export function cloudAddress(cloudId) {
|
|
81
|
+
return `https://claude.ai/code/${cloudId}`;
|
|
82
|
+
}
|
|
83
|
+
export function startEvent(input, git, env) {
|
|
84
|
+
const folder = input.cwd ? folderOf(input.cwd) : undefined;
|
|
85
|
+
const title = input.title ? line(input.title, TITLE_MAX) : undefined;
|
|
86
|
+
return {
|
|
87
|
+
v: EVENT_VERSION,
|
|
88
|
+
event: "start",
|
|
89
|
+
agentSessionId: input.sessionId,
|
|
90
|
+
source: input.source ?? "startup",
|
|
91
|
+
...(input.model ? { model: input.model } : {}),
|
|
92
|
+
...(title ? { title } : {}),
|
|
93
|
+
...whereOf(env),
|
|
94
|
+
...(git.repo ? { repo: git.repo } : {}),
|
|
95
|
+
...(git.branch ? { branch: git.branch } : {}),
|
|
96
|
+
...(git.head ? { head: git.head } : {}),
|
|
97
|
+
...(folder ? { folder } : {}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function stopEvent(agentSessionId, o) {
|
|
101
|
+
return {
|
|
102
|
+
v: EVENT_VERSION,
|
|
103
|
+
event: "stop",
|
|
104
|
+
agentSessionId,
|
|
105
|
+
turns: Math.max(0, Math.min(1_000_000, Math.floor(o.turns))),
|
|
106
|
+
...(o.git.head ? { head: o.git.head } : {}),
|
|
107
|
+
...(o.git.branch ? { branch: o.git.branch } : {}),
|
|
108
|
+
...(o.commits && o.commits.length ? { commits: o.commits } : {}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** A compaction summary as it leaves the computer: scanned, then cut to what Work keeps. */
|
|
112
|
+
export function scannedSummary(summary) {
|
|
113
|
+
const text = scanText(summary.trim()).text.trim();
|
|
114
|
+
if (!text)
|
|
115
|
+
return null;
|
|
116
|
+
if (text.length <= SUMMARY_MAX)
|
|
117
|
+
return text;
|
|
118
|
+
let cut = text.slice(0, SUMMARY_MAX - 1);
|
|
119
|
+
const code = cut.charCodeAt(cut.length - 1);
|
|
120
|
+
if (code >= 0xd800 && code <= 0xdbff)
|
|
121
|
+
cut = cut.slice(0, -1);
|
|
122
|
+
return `${cut}…`;
|
|
123
|
+
}
|
|
124
|
+
/** The compact event, its body under 200 KB: a summary dense with characters JSON escapes is cut further. */
|
|
125
|
+
export function compactEvent(agentSessionId, o) {
|
|
126
|
+
let summary = o.summary;
|
|
127
|
+
for (;;) {
|
|
128
|
+
const body = { v: EVENT_VERSION, event: "compact", agentSessionId, trigger: o.trigger, summary };
|
|
129
|
+
if (Buffer.byteLength(JSON.stringify(body)) <= COMPACT_BODY_MAX || summary.length < 100)
|
|
130
|
+
return body;
|
|
131
|
+
summary = `${summary.slice(0, Math.floor(summary.length * 0.8))}…`;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
export function endEvent(agentSessionId, reason) {
|
|
135
|
+
return { v: EVENT_VERSION, event: "end", agentSessionId, reason: reason ?? "other" };
|
|
136
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Runner } from "./keychain.js";
|
|
2
|
+
/** The newest commits a stop sends, as Work keeps them. */
|
|
3
|
+
export declare const COMMITS_SENT = 50;
|
|
4
|
+
export interface SessionRepo {
|
|
5
|
+
provider: "github" | "gitlab" | "other";
|
|
6
|
+
name: string;
|
|
7
|
+
}
|
|
8
|
+
export interface GitFacts {
|
|
9
|
+
repo?: SessionRepo;
|
|
10
|
+
branch?: string;
|
|
11
|
+
head?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface Commit {
|
|
14
|
+
sha: string;
|
|
15
|
+
subject: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A remote's address as `owner/name` and its host's kind, or null for a folder on this computer or
|
|
19
|
+
* an address it can't read. `https://user:pass@github.com/hearth/orders-site.git`,
|
|
20
|
+
* `git@github.com:hearth/orders-site.git` and `ssh://git@gitlab.com/hearth/shop/site.git` all
|
|
21
|
+
* give their path, with nothing before the host.
|
|
22
|
+
*/
|
|
23
|
+
export declare function repoOf(remote: string): SessionRepo | null;
|
|
24
|
+
/** The folder's own name, never its path, scanned: a synced drive's folder can hold an email address. */
|
|
25
|
+
export declare function folderOf(cwd: string): string | undefined;
|
|
26
|
+
/** One line, scanned, at most 120 characters: a commit's first line as Work keeps it. */
|
|
27
|
+
export declare function subjectOf(text: string): string;
|
|
28
|
+
/** The repo, branch and head of the chat's folder, as far as git answers in time. */
|
|
29
|
+
export declare function gitFacts(cwd: string, run: Runner, timeoutMs?: number): Promise<GitFacts>;
|
|
30
|
+
/**
|
|
31
|
+
* The commits after `from` up to `to`, oldest first, the newest 50 at most; null when git can't
|
|
32
|
+
* tell. `git log` prints newest first, so its list is turned round: Work keeps a session's commits
|
|
33
|
+
* in the order they were made, newest last.
|
|
34
|
+
*/
|
|
35
|
+
export declare function commitsBetween(cwd: string, from: string, to: string, run: Runner, timeoutMs?: number): Promise<Commit[] | null>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { scanText } from "./scan.js";
|
|
3
|
+
/**
|
|
4
|
+
* What the hook reads from the chat's folder with git (K's Work slice, plan section 6b): the repo
|
|
5
|
+
* as `owner/name` from `origin` (never its address, so never a user or password in it), the
|
|
6
|
+
* branch, the head commit, the folder's own name (never its path), and the commits since the chat
|
|
7
|
+
* started, each its id and first line. The branch, the folder's name and each first line go
|
|
8
|
+
* through the scan (decision S11). git runs with no shell, a short timeout, no prompt and no
|
|
9
|
+
* fsmonitor, and without the key in its environment.
|
|
10
|
+
*/
|
|
11
|
+
const BRANCH = /^[^\s~^:?*[\\\x00-\x1f\x7f]{1,200}$/;
|
|
12
|
+
const SHA = /^[0-9a-f]{7,64}$/;
|
|
13
|
+
const REPO_NAME = /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+){1,9}$/;
|
|
14
|
+
const FOLDER = /^[^/\\\x00-\x1f\x7f]{1,80}$/;
|
|
15
|
+
/** The newest commits a stop sends, as Work keeps them. */
|
|
16
|
+
export const COMMITS_SENT = 50;
|
|
17
|
+
const SUBJECT_MAX = 120;
|
|
18
|
+
/**
|
|
19
|
+
* A remote's address as `owner/name` and its host's kind, or null for a folder on this computer or
|
|
20
|
+
* an address it can't read. `https://user:pass@github.com/hearth/orders-site.git`,
|
|
21
|
+
* `git@github.com:hearth/orders-site.git` and `ssh://git@gitlab.com/hearth/shop/site.git` all
|
|
22
|
+
* give their path, with nothing before the host.
|
|
23
|
+
*/
|
|
24
|
+
export function repoOf(remote) {
|
|
25
|
+
const url = remote.trim();
|
|
26
|
+
if (!url || /[\s\x00-\x1f]/.test(url))
|
|
27
|
+
return null;
|
|
28
|
+
let host;
|
|
29
|
+
let repoPath;
|
|
30
|
+
const scp = /^(?:[A-Za-z0-9._-]+@)?([A-Za-z0-9.-]+):(?!\/\/)(.+)$/.exec(url);
|
|
31
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) {
|
|
32
|
+
let u;
|
|
33
|
+
try {
|
|
34
|
+
u = new URL(url);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (u.protocol === "file:" || !u.hostname)
|
|
40
|
+
return null;
|
|
41
|
+
host = u.hostname;
|
|
42
|
+
repoPath = u.pathname;
|
|
43
|
+
}
|
|
44
|
+
else if (scp && !/^[A-Za-z]:$/.test(`${scp[1]}:`)) {
|
|
45
|
+
host = scp[1];
|
|
46
|
+
repoPath = scp[2];
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const name = repoPath.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
52
|
+
if (!REPO_NAME.test(name) || name.length > 200)
|
|
53
|
+
return null;
|
|
54
|
+
const h = host.toLowerCase();
|
|
55
|
+
const provider = h === "github.com" || h === "www.github.com" ? "github" : h === "gitlab.com" || h === "www.gitlab.com" ? "gitlab" : "other";
|
|
56
|
+
return { provider, name };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A folder's name or a branch through the scan, as Work keeps it: an address or a key in it is
|
|
60
|
+
* replaced, and a name the scan changed so that it no longer fits its shape is left out.
|
|
61
|
+
*/
|
|
62
|
+
function scannedName(name, shape) {
|
|
63
|
+
if (!shape.test(name))
|
|
64
|
+
return undefined;
|
|
65
|
+
const kept = scanText(name).text;
|
|
66
|
+
return shape.test(kept) ? kept : undefined;
|
|
67
|
+
}
|
|
68
|
+
/** The folder's own name, never its path, scanned: a synced drive's folder can hold an email address. */
|
|
69
|
+
export function folderOf(cwd) {
|
|
70
|
+
const name = path.basename(cwd);
|
|
71
|
+
return name ? scannedName(name, FOLDER) : undefined;
|
|
72
|
+
}
|
|
73
|
+
/** One line, scanned, at most 120 characters: a commit's first line as Work keeps it. */
|
|
74
|
+
export function subjectOf(text) {
|
|
75
|
+
const line = scanText(text.replace(/[\r\n\t]+/g, " ").trim()).text;
|
|
76
|
+
return line.length <= SUBJECT_MAX ? line : `${line.slice(0, SUBJECT_MAX - 1)}…`;
|
|
77
|
+
}
|
|
78
|
+
async function git(run, cwd, args, timeoutMs) {
|
|
79
|
+
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" };
|
|
80
|
+
const r = await run("git", ["-c", "core.fsmonitor=false", ...args], { cwd, timeoutMs, env }).catch(() => ({ code: 1, stdout: "" }));
|
|
81
|
+
return r.code === 0 ? r.stdout : null;
|
|
82
|
+
}
|
|
83
|
+
/** The repo, branch and head of the chat's folder, as far as git answers in time. */
|
|
84
|
+
export async function gitFacts(cwd, run, timeoutMs = 1_500) {
|
|
85
|
+
const [remote, branch, head] = await Promise.all([
|
|
86
|
+
git(run, cwd, ["remote", "get-url", "origin"], timeoutMs),
|
|
87
|
+
git(run, cwd, ["rev-parse", "--abbrev-ref", "HEAD"], timeoutMs),
|
|
88
|
+
git(run, cwd, ["rev-parse", "HEAD"], timeoutMs),
|
|
89
|
+
]);
|
|
90
|
+
const out = {};
|
|
91
|
+
const repo = remote ? repoOf(remote) : null;
|
|
92
|
+
if (repo)
|
|
93
|
+
out.repo = repo;
|
|
94
|
+
const b = branch?.trim();
|
|
95
|
+
const scanned = b && b !== "HEAD" ? scannedName(b, BRANCH) : undefined;
|
|
96
|
+
if (scanned)
|
|
97
|
+
out.branch = scanned;
|
|
98
|
+
const h = head?.trim();
|
|
99
|
+
if (h && SHA.test(h))
|
|
100
|
+
out.head = h;
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The commits after `from` up to `to`, oldest first, the newest 50 at most; null when git can't
|
|
105
|
+
* tell. `git log` prints newest first, so its list is turned round: Work keeps a session's commits
|
|
106
|
+
* in the order they were made, newest last.
|
|
107
|
+
*/
|
|
108
|
+
export async function commitsBetween(cwd, from, to, run, timeoutMs = 2_000) {
|
|
109
|
+
if (!SHA.test(from) || !SHA.test(to))
|
|
110
|
+
return null;
|
|
111
|
+
if (from === to)
|
|
112
|
+
return [];
|
|
113
|
+
const out = await git(run, cwd, ["log", `--max-count=${COMMITS_SENT}`, "--format=%H%x1f%s", `${from}..${to}`], timeoutMs);
|
|
114
|
+
if (out === null)
|
|
115
|
+
return null;
|
|
116
|
+
const commits = [];
|
|
117
|
+
for (const line of out.split("\n")) {
|
|
118
|
+
const [sha, subject] = line.split("\x1f");
|
|
119
|
+
if (!sha || !SHA.test(sha))
|
|
120
|
+
continue;
|
|
121
|
+
commits.push({ sha, subject: subjectOf(subject ?? "") });
|
|
122
|
+
}
|
|
123
|
+
return commits.reverse();
|
|
124
|
+
}
|