@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.
@@ -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
+ }
@@ -0,0 +1,87 @@
1
+ import { type Runner } from "./keychain.js";
2
+ import { type Requester } from "./run.js";
3
+ import { type HookEnv, type HookPaths, type KeyStoreKind } from "./state.js";
4
+ /**
5
+ * `work-hook install <copy>` and `work-hook uninstall` (K's Work slice, decisions S6 and S7, plan
6
+ * section 6b), run by a person in their own terminal:
7
+ *
8
+ * 1. checks the key in `YOUGROW_WORK_KEY` with this copy of YouGrow (`GET /api/v2/work/me`), or,
9
+ * when it isn't set, the key an earlier install saved for the same copy, so the line that
10
+ * updates the hook needs no new key;
11
+ * 2. shows the five entries it adds to their own `~/.claude/settings.json`, and asks;
12
+ * 3. copies the hook's modules to `~/.yougrow/hook/<version>/` and writes `~/.yougrow/work-hook.mjs`,
13
+ * the file Claude Code runs, so no event waits on npx or the network to start;
14
+ * 4. saves the key in the system keychain, or `~/.yougrow/work-key` readable only by them;
15
+ * 5. adds the entries beside every hook they have, after a dated backup of the file.
16
+ *
17
+ * Never a project's `.claude/settings.json`, which is often committed, and never Claude Code's own
18
+ * `env` settings: every command an agent runs would then hold the key.
19
+ */
20
+ /** The marker every entry's command holds, so install and uninstall find their own and no other. */
21
+ export declare const HOOK_COMMAND_MARK = ".yougrow/work-hook.mjs";
22
+ export type ClaudeEvent = "SessionStart" | "Stop" | "PreCompact" | "PostCompact" | "SessionEnd";
23
+ export interface HookEntry {
24
+ matcher?: string;
25
+ hooks: Array<{
26
+ type: "command";
27
+ command: string;
28
+ timeout?: number;
29
+ async?: boolean;
30
+ }>;
31
+ }
32
+ /** The five entries, as plan section 6b lists them: SessionStart, PreCompact and SessionEnd wait a few seconds; Stop and PostCompact run in the background. */
33
+ export declare function hookEntries(o?: {
34
+ cloud?: boolean;
35
+ }): Record<ClaudeEvent, HookEntry>;
36
+ /** The entries as they read in a settings file, each event's in a list: what install shows, and `work-hook entries` prints. */
37
+ export declare function entriesText(entries: Record<ClaudeEvent, HookEntry>): string;
38
+ export type MergeResult = {
39
+ ok: true;
40
+ settings: Record<string, unknown>;
41
+ replaced: number;
42
+ } | {
43
+ ok: false;
44
+ why: string;
45
+ };
46
+ /**
47
+ * The person's settings with the hook's entries in them, beside every other hook. Entries from an
48
+ * earlier install are taken out first, so installing again replaces them; nothing else changes.
49
+ * `entries` null takes them out only (uninstall).
50
+ */
51
+ export declare function mergeSettings(current: unknown, entries: Record<ClaudeEvent, HookEntry> | null): MergeResult;
52
+ /** The person's own Claude Code settings: `~/.claude/settings.json`, or in CLAUDE_CONFIG_DIR when it is set. Never a project's. */
53
+ export declare function userSettingsFile(home: string, env: HookEnv): string;
54
+ /** The JavaScript files the hook is made of, beside this one in the package. */
55
+ export declare function hookFilesIn(dir: string): string[];
56
+ /**
57
+ * Copy the hook's modules into `~/.yougrow/hook/<version>-<hash>/` and point the file Claude Code
58
+ * runs at them. Each copy has its own folder, so a hook running while this runs keeps the files
59
+ * it started with; older folders are removed after.
60
+ */
61
+ export declare function placeHook(paths: HookPaths, sourceDir: string): string;
62
+ /** The file Claude Code runs. Whatever fails, it ends quietly, so it never stops a chat. */
63
+ export declare function launcherText(folder: string): string;
64
+ export interface InstallDeps {
65
+ paths: HookPaths;
66
+ env: HookEnv;
67
+ platform: NodeJS.Platform;
68
+ now: () => Date;
69
+ /** Where the hook's own files are: the package's dist/workHook. */
70
+ hookSource: string;
71
+ request: Requester;
72
+ run: Runner;
73
+ out: (text: string) => void;
74
+ /** Ask a yes or no question in the person's terminal; null when nobody can answer. */
75
+ ask: (question: string) => Promise<boolean | null>;
76
+ }
77
+ export interface InstallOptions {
78
+ url: string | null;
79
+ yes: boolean;
80
+ keyStore: KeyStoreKind | null;
81
+ }
82
+ /** `work-hook install`: answers the exit code. Nothing on this computer changes until the person says yes. */
83
+ export declare function install(o: InstallOptions, d: InstallDeps): Promise<number>;
84
+ /** `work-hook uninstall`: takes the hook's entries out, forgets the key and removes the hook's files. */
85
+ export declare function uninstall(o: {
86
+ yes: boolean;
87
+ }, d: InstallDeps): Promise<number>;