@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 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.
@@ -145,6 +147,27 @@ record an event twice. A key that was already recorded resolves
145
147
  - Up to 50 steps, 50 facts and 50 traits per user. Step ids are lower-case
146
148
  letters, digits, `_` and `-`; trait keys start with a letter.
147
149
 
150
+ ### Several workspaces, brands or projects
151
+
152
+ When a person can have several of something, send them as `entities`, by your
153
+ own id. Each has a `kind` (your word for it; required the first time), a
154
+ `name`, the `parentId` it sits inside, the person's `role` (`owner`, `member` or
155
+ `invited`), and its own `steps` and `facts`. Each merges like the user, and
156
+ `null` removes one:
157
+
158
+ ```ts
159
+ await yg.users.update(user.id, {
160
+ entities: {
161
+ brand_123: { kind: "brand", name: "Acme", role: "owner", steps: { run_audit: audit.finishedAt } },
162
+ brand_456: null, // deleted in your product
163
+ },
164
+ });
165
+ await yg.events.track(user.id, "audit.completed", { entityId: "brand_123" });
166
+ ```
167
+
168
+ Journeys choose which of them each email is about, so send them all rather than
169
+ picking one. Up to 50 per user.
170
+
148
171
  A user YouGrow hasn't seen is created by their first update.
149
172
  `users.get(userId)` returns the state as YouGrow holds it, plus what YouGrow
150
173
  decided: journey `enrolments`, and `optOuts` (unsubscribes made in YouGrow's
@@ -267,8 +290,10 @@ app.post("/yougrow/context", express.raw({ type: "application/json" }), async (r
267
290
  const v = await verifier.verify({ headers: req.headers, rawBody: req.body, direction: "context" });
268
291
  if (!v.ok) return res.status(401).end();
269
292
 
270
- const { userId } = JSON.parse(req.body.toString("utf8"));
271
- const u = await loadOnboardingState(userId);
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);
272
297
  res.type("json").send(
273
298
  contextResponse({
274
299
  steps: u.steps, // [{ id, label, done, url }]
@@ -343,6 +368,103 @@ at https://yougrow.ai/developers.
343
368
  `test/vectors.json` (included in this package) holds reference tokens for
344
369
  checking your own verifier.
345
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
+
462
+ ## Upgrading from 0.4
463
+
464
+ - New: `entities` in `users.update` and on the state it returns, `entityId` on
465
+ `events.track`, and `entityId` on enrolments from `users.get`. Nothing
466
+ existing changed.
467
+
346
468
  ## Upgrading from 0.3
347
469
 
348
470
  - A network failure or timeout that outlasts the retries now rejects with a
@@ -12,6 +12,34 @@
12
12
  * status throws a YouGrowError straight away.
13
13
  */
14
14
  export type ConsentBasis = "consent" | "soft_opt_in" | "corporate_subscriber" | "none";
15
+ /** How a person relates to one of their entities. Only what they own counts toward their onboarding. */
16
+ export type EntityRole = "owner" | "member" | "invited";
17
+ /**
18
+ * One of the things a person has several of — a workspace, a brand, a project —
19
+ * in a write. It merges like the user; `kind` is required the first time.
20
+ */
21
+ export interface EntityPatch {
22
+ /** What it is, in your product's words: "brand", "workspace", "project". */
23
+ kind?: string;
24
+ name?: string | null;
25
+ /** The entity it sits inside, e.g. a brand's workspace. */
26
+ parentId?: string | null;
27
+ role?: EntityRole | null;
28
+ steps?: Record<string, string | null>;
29
+ facts?: Record<string, number | string | boolean | null>;
30
+ /** When the person last worked on it. */
31
+ activeAt?: string | null;
32
+ }
33
+ /** One entity as YouGrow holds it. */
34
+ export interface EntityState {
35
+ kind: string;
36
+ name: string | null;
37
+ parentId: string | null;
38
+ role: EntityRole | null;
39
+ steps: Record<string, string>;
40
+ facts: Record<string, string | number | boolean>;
41
+ activeAt: string | null;
42
+ }
15
43
  /**
16
44
  * Any subset of a user's state, as a JSON Merge Patch (RFC 7396): fields sent
17
45
  * replace YouGrow's, fields left out stay, `null` clears, and `steps`, `facts`
@@ -42,6 +70,8 @@ export interface UserPatch {
42
70
  facts?: Record<string, number | string | boolean | null>;
43
71
  /** Anything else journeys branch on (null removes a key). */
44
72
  traits?: Record<string, string | number | boolean | null>;
73
+ /** The things this person has several of (workspaces, brands…), by your id; null removes one. */
74
+ entities?: Record<string, EntityPatch | null>;
45
75
  /** When you read this state. A write older than the stored one is ignored. */
46
76
  updatedAt?: string;
47
77
  }
@@ -62,15 +92,18 @@ export interface UserState {
62
92
  steps: Record<string, string>;
63
93
  facts: Record<string, string | number | boolean>;
64
94
  traits: Record<string, string | number | boolean>;
95
+ entities: Record<string, EntityState>;
65
96
  updatedAt: string | null;
66
97
  }
67
98
  /** `users.get` adds what YouGrow decided: journeys and opt-outs. */
68
99
  export interface UserView extends UserState {
100
+ /** `entityId`: the entity an enrolment is about, when its journey is about one of them. */
69
101
  enrolments: Array<{
70
102
  journeyId: string;
71
103
  status: string;
72
104
  mode: string;
73
105
  enrolledAt: string;
106
+ entityId?: string | null;
74
107
  }>;
75
108
  /** Unsubscribes made in YouGrow's emails. They hold until the person lifts them; the API can't. */
76
109
  optOuts: Array<{
@@ -165,6 +198,8 @@ export interface TrackOptions {
165
198
  occurredAt?: string;
166
199
  /** The same key is recorded once. Defaults to a random key per call, so the SDK's own retries never count twice. */
167
200
  idempotencyKey?: string;
201
+ /** The entity it happened to (one of the user's `entities`), e.g. the brand an audit ran on. */
202
+ entityId?: string;
168
203
  }
169
204
  export interface UsersApi {
170
205
  /** Merge a patch into one user's state; creates the user if YouGrow hasn't seen them. */
package/dist/cjs/index.js CHANGED
@@ -93,9 +93,9 @@ class YouGrow {
93
93
  this.events = {
94
94
  track: async (userId, event, options = {}) => {
95
95
  const path = `${userPath(userId)}/events`;
96
- const { properties, occurredAt } = options;
96
+ const { properties, occurredAt, entityId } = options;
97
97
  // One key for every attempt, so a retry is never recorded twice.
98
- const body = { event, properties, occurredAt, idempotencyKey: options.idempotencyKey ?? (0, node_crypto_1.randomUUID)() };
98
+ const body = { event, properties, occurredAt, entityId, idempotencyKey: options.idempotencyKey ?? (0, node_crypto_1.randomUUID)() };
99
99
  return (await this.#send("POST", path, JSON.stringify(body)));
100
100
  },
101
101
  };
@@ -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 place numbers about the user appear. */
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/index.d.ts CHANGED
@@ -12,6 +12,34 @@
12
12
  * status throws a YouGrowError straight away.
13
13
  */
14
14
  export type ConsentBasis = "consent" | "soft_opt_in" | "corporate_subscriber" | "none";
15
+ /** How a person relates to one of their entities. Only what they own counts toward their onboarding. */
16
+ export type EntityRole = "owner" | "member" | "invited";
17
+ /**
18
+ * One of the things a person has several of — a workspace, a brand, a project —
19
+ * in a write. It merges like the user; `kind` is required the first time.
20
+ */
21
+ export interface EntityPatch {
22
+ /** What it is, in your product's words: "brand", "workspace", "project". */
23
+ kind?: string;
24
+ name?: string | null;
25
+ /** The entity it sits inside, e.g. a brand's workspace. */
26
+ parentId?: string | null;
27
+ role?: EntityRole | null;
28
+ steps?: Record<string, string | null>;
29
+ facts?: Record<string, number | string | boolean | null>;
30
+ /** When the person last worked on it. */
31
+ activeAt?: string | null;
32
+ }
33
+ /** One entity as YouGrow holds it. */
34
+ export interface EntityState {
35
+ kind: string;
36
+ name: string | null;
37
+ parentId: string | null;
38
+ role: EntityRole | null;
39
+ steps: Record<string, string>;
40
+ facts: Record<string, string | number | boolean>;
41
+ activeAt: string | null;
42
+ }
15
43
  /**
16
44
  * Any subset of a user's state, as a JSON Merge Patch (RFC 7396): fields sent
17
45
  * replace YouGrow's, fields left out stay, `null` clears, and `steps`, `facts`
@@ -42,6 +70,8 @@ export interface UserPatch {
42
70
  facts?: Record<string, number | string | boolean | null>;
43
71
  /** Anything else journeys branch on (null removes a key). */
44
72
  traits?: Record<string, string | number | boolean | null>;
73
+ /** The things this person has several of (workspaces, brands…), by your id; null removes one. */
74
+ entities?: Record<string, EntityPatch | null>;
45
75
  /** When you read this state. A write older than the stored one is ignored. */
46
76
  updatedAt?: string;
47
77
  }
@@ -62,15 +92,18 @@ export interface UserState {
62
92
  steps: Record<string, string>;
63
93
  facts: Record<string, string | number | boolean>;
64
94
  traits: Record<string, string | number | boolean>;
95
+ entities: Record<string, EntityState>;
65
96
  updatedAt: string | null;
66
97
  }
67
98
  /** `users.get` adds what YouGrow decided: journeys and opt-outs. */
68
99
  export interface UserView extends UserState {
100
+ /** `entityId`: the entity an enrolment is about, when its journey is about one of them. */
69
101
  enrolments: Array<{
70
102
  journeyId: string;
71
103
  status: string;
72
104
  mode: string;
73
105
  enrolledAt: string;
106
+ entityId?: string | null;
74
107
  }>;
75
108
  /** Unsubscribes made in YouGrow's emails. They hold until the person lifts them; the API can't. */
76
109
  optOuts: Array<{
@@ -165,6 +198,8 @@ export interface TrackOptions {
165
198
  occurredAt?: string;
166
199
  /** The same key is recorded once. Defaults to a random key per call, so the SDK's own retries never count twice. */
167
200
  idempotencyKey?: string;
201
+ /** The entity it happened to (one of the user's `entities`), e.g. the brand an audit ran on. */
202
+ entityId?: string;
168
203
  }
169
204
  export interface UsersApi {
170
205
  /** Merge a patch into one user's state; creates the user if YouGrow hasn't seen them. */
package/dist/index.js CHANGED
@@ -88,9 +88,9 @@ export class YouGrow {
88
88
  this.events = {
89
89
  track: async (userId, event, options = {}) => {
90
90
  const path = `${userPath(userId)}/events`;
91
- const { properties, occurredAt } = options;
91
+ const { properties, occurredAt, entityId } = options;
92
92
  // One key for every attempt, so a retry is never recorded twice.
93
- const body = { event, properties, occurredAt, idempotencyKey: options.idempotencyKey ?? randomUUID() };
93
+ const body = { event, properties, occurredAt, entityId, idempotencyKey: options.idempotencyKey ?? randomUUID() };
94
94
  return (await this.#send("POST", path, JSON.stringify(body)));
95
95
  },
96
96
  };
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 place numbers about the user appear. */
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 {};