@loksly/agent-sessions 0.0.0-stage → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loksly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # @loksly/agent-sessions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A tiny file protocol for the state of your AI coding sessions (Claude Code,
4
+ Gemini CLI, …), so that anything can show which session needs you: an LCD
5
+ panel, a status bar, a tmux segment, a microcontroller on your desk.
6
+
7
+ - **A hook** (`agent-sessions-hook`) that your CLI calls on every event. It
8
+ writes one JSON file per session, atomically, with no dependencies and no
9
+ network. It never fails loudly: it exits 0 whatever happens.
10
+ - **A protocol**: the record format, versioned, with a
11
+ [JSON Schema](schema/session-record.schema.json) for clients in any language.
12
+ - **Helpers to read it**: list sessions, order them by urgency, reap dead
13
+ ones, and optionally enrich them with git data.
14
+
15
+ ## The record
16
+
17
+ `~/.aimonitor/sessions/<session_id>.json` (see *Where files live* below):
18
+
19
+ ```json
20
+ {
21
+ "schemaVersion": 1,
22
+ "session_id": "7377b6e2-…",
23
+ "provider": "claude",
24
+ "state": "permission",
25
+ "detail": "Bash: npm publish",
26
+ "project": "my-repo",
27
+ "cwd": "/home/me/my-repo",
28
+ "since": 1791662627994,
29
+ "updated": 1791662627994,
30
+ "event": "Notification"
31
+ }
32
+ ```
33
+
34
+ `state`, from most to least urgent:
35
+
36
+ | State | Meaning |
37
+ |---|---|
38
+ | `permission` | Blocked on a permission prompt. |
39
+ | `waiting` | Idle, waiting for your input. |
40
+ | `ready` | Finished its turn. |
41
+ | `active` | Working. |
42
+ | `idle` | Just started or resumed. |
43
+
44
+ `since` is when it entered that state, so a client can show *how long it has
45
+ been waiting*. Optional fields carry signals for richer clients: `files`
46
+ touched, `lastFailed`/`failStreak` for shell commands, `testsFailed`, `todos`
47
+ added, `talkStreak`/`duck` (turns spent talking without tools), `compactAt`.
48
+ Secrets in `detail` (tokens, `Authorization` headers, credentials in URLs) are
49
+ redacted before writing.
50
+
51
+ ## Wiring the hook
52
+
53
+ ```sh
54
+ npm install -g @loksly/agent-sessions
55
+ ```
56
+
57
+ **Claude Code**, in `~/.claude/settings.json` (one entry per event you want):
58
+
59
+ ```json
60
+ {
61
+ "hooks": {
62
+ "SessionStart": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
63
+ "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
64
+ "PreToolUse": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
65
+ "PostToolUse": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
66
+ "PostToolUseFailure": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
67
+ "Notification": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
68
+ "Stop": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
69
+ "SubagentStop": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
70
+ "PreCompact": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }],
71
+ "SessionEnd": [{ "hooks": [{ "type": "command", "command": "agent-sessions-hook", "timeout": 5 }] }]
72
+ }
73
+ }
74
+ ```
75
+
76
+ **Gemini CLI**: the same command with `--provider gemini`.
77
+
78
+ ## Reading it
79
+
80
+ ```ts
81
+ import { readSessions, order, reap, claims } from '@loksly/agent-sessions';
82
+
83
+ const live = reap(readSessions(), Date.now(), { zombieMs: 15 * 60_000, staleMs: 2 * 3600_000 });
84
+ for (const s of order(live)) console.log(claims(s) ? '!' : ' ', s.state, s.project, s.detail);
85
+ ```
86
+
87
+ With git data (repository root, HEAD, uncommitted files):
88
+
89
+ ```ts
90
+ import { createGitEnricher } from '@loksly/agent-sessions/git';
91
+ const enrich = createGitEnricher();
92
+ const rich = await Promise.all(live.map(enrich)); // adds repo, dirty, dirtyFiles, detached, lastCommit…
93
+ ```
94
+
95
+ From any other language, read the JSON files and validate them against
96
+ `schema/session-record.schema.json` (also exported as
97
+ `@loksly/agent-sessions/schema.json`).
98
+
99
+ ## Where files live
100
+
101
+ `$AGENT_SESSIONS_DIR`, or `sessions/` inside `$AIMONITOR_DIR`
102
+ (default `~/.aimonitor`).
103
+
104
+ ## Adding a CLI
105
+
106
+ Each CLI sends its own JSON on stdin. `src/providers.ts` turns it into a
107
+ canonical event; adding a provider means an adapter there plus its payloads
108
+ replayed through the conformance story in `src/hook.test.ts`. The state
109
+ machine does not change.
110
+
111
+ ## Contributing
112
+
113
+ This package lives in the [aimonitor](https://github.com/Loksly/aimonitor)
114
+ repository under `packages/agent-sessions`, whose dashboard for Thermalright
115
+ LCD panels is its first client. Issues and pull requests are welcome there.
116
+ Run `npm test` from the package directory.
117
+
118
+ ## License
119
+
120
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `agent-sessions-hook [--provider claude|gemini|…]`: reads one hook event
4
+ * from stdin and updates the session's file. Wire it as a command hook in your
5
+ * CLI's settings. It exits 0 whatever happens: a failing hook must never get
6
+ * in the way of the session it observes.
7
+ */
8
+ import { providerFromArgs, runHook } from "./hook.js";
9
+ process.on('uncaughtException', () => process.exit(0));
10
+ const chunks = [];
11
+ for await (const chunk of process.stdin)
12
+ chunks.push(chunk);
13
+ try {
14
+ runHook(Buffer.concat(chunks).toString('utf8'), providerFromArgs(process.argv.slice(2)));
15
+ }
16
+ catch {
17
+ // Never fail loudly.
18
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Craft signals taken from hook events and from the files a session touches.
3
+ * Pure and cheap: the hook ones are on the path of every tool call.
4
+ */
5
+ /** TODO/FIXME added by an edit (new ones minus those already there). */
6
+ export declare function todosAdded(tool: string, input: unknown): number;
7
+ /**
8
+ * Longest definition in a file, in lines: from one top-level definition
9
+ * (`function`, `def`, `fn`, `func`, `class`, `export …`) to the next. Plenty
10
+ * of heuristic to tell whether there is a 500-line monster in there.
11
+ */
12
+ export declare function longestDefinition(text: string): number;
13
+ /** A definition longer than this is spaghetti. */
14
+ export declare const SPAGHETTI_LINES = 500;
package/dist/craft.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Craft signals taken from hook events and from the files a session touches.
3
+ * Pure and cheap: the hook ones are on the path of every tool call.
4
+ */
5
+ /** TODO/FIXME added by an edit (new ones minus those already there). */
6
+ export function todosAdded(tool, input) {
7
+ if (!input || typeof input !== 'object')
8
+ return 0;
9
+ const o = input;
10
+ const count = (v) => (typeof v === 'string' ? (v.match(/\b(TODO|FIXME)\b/g) ?? []).length : 0);
11
+ if (/^(Edit|replace)$/.test(tool))
12
+ return Math.max(0, count(o.new_string) - count(o.old_string));
13
+ if (tool === 'MultiEdit' && Array.isArray(o.edits)) {
14
+ return o.edits.reduce((n, e) => n + Math.max(0, count(e.new_string) - count(e.old_string)), 0);
15
+ }
16
+ if (/^(Write|write_file)$/.test(tool))
17
+ return count(o.content);
18
+ return 0;
19
+ }
20
+ /**
21
+ * Longest definition in a file, in lines: from one top-level definition
22
+ * (`function`, `def`, `fn`, `func`, `class`, `export …`) to the next. Plenty
23
+ * of heuristic to tell whether there is a 500-line monster in there.
24
+ */
25
+ export function longestDefinition(text) {
26
+ const lines = text.split('\n');
27
+ const START = /^(export\s+)?(default\s+)?(async\s+)?(function\b|def\s|fn\s|func\s|class\s|const\s+\w+\s*=\s*(async\s*)?\(|(public|private|protected|static)\s)/;
28
+ let best = 0, from = -1;
29
+ lines.forEach((l, i) => {
30
+ if (START.test(l)) {
31
+ if (from >= 0)
32
+ best = Math.max(best, i - from);
33
+ from = i;
34
+ }
35
+ });
36
+ if (from >= 0)
37
+ best = Math.max(best, lines.length - from);
38
+ return best;
39
+ }
40
+ /** A definition longer than this is spaghetti. */
41
+ export const SPAGHETTI_LINES = 500;
package/dist/git.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { SessionRecord } from './protocol.ts';
2
+ /** Runs a git query in a directory; null if it fails. */
3
+ export type Runner = (cwd: string) => Promise<string | null>;
4
+ /**
5
+ * Root of the git repository containing a directory, cached. A session opened
6
+ * in `repo/apps/server/src` belongs to `repo`, and two sessions in different
7
+ * subdirectories of the same repository are recognised as one project. A
8
+ * directory's root does not change, so it is asked once; directories that are
9
+ * not repositories are remembered only for a while (someone may `git init`).
10
+ */
11
+ export declare function repoRootCache(run: Runner, now?: () => number): (cwd: string) => Promise<string | null>;
12
+ export interface HeadInfo {
13
+ /** Detached HEAD (not on any branch). */
14
+ detached: boolean;
15
+ /** Date of the last commit, ms epoch; absent in a repository without commits. */
16
+ lastCommit?: number;
17
+ }
18
+ /**
19
+ * `git log -1 --format=%ct%n%D` → HeadInfo. The second line holds the refs:
20
+ * "HEAD -> main, origin/main" on a branch, "HEAD, …" when detached.
21
+ */
22
+ export declare function parseHead(out: string): HeadInfo | null;
23
+ /** HEAD of each repository, asked at most once per `ttlMs`. */
24
+ export declare function headCache(run: Runner, ttlMs?: number, now?: () => number): (root: string) => Promise<HeadInfo | null>;
25
+ /** A session record plus what git says about its working directory. */
26
+ export interface EnrichedSession extends SessionRecord {
27
+ /** Root of the git repository containing `cwd`; `project` is then its name. */
28
+ repo?: string;
29
+ /** Detached HEAD in its repository. */
30
+ detached?: boolean;
31
+ /** Date of the last commit on its branch, ms epoch. */
32
+ lastCommit?: number;
33
+ /** Date of the repository's first commit, ms epoch (unknown in shallow clones). */
34
+ repoBorn?: number;
35
+ /** Some file it touched has a definition longer than `SPAGHETTI_LINES`. */
36
+ spaghetti?: boolean;
37
+ /** Uncommitted files. */
38
+ dirty?: number;
39
+ /** Paths of those files, relative to the repository root, as `git status` gives them. */
40
+ dirtyFiles?: string[];
41
+ }
42
+ /** Parses `git status --porcelain` into a count and paths (renames keep the new path). */
43
+ export declare function parseStatus(out: string): {
44
+ count: number;
45
+ files: string[];
46
+ };
47
+ /**
48
+ * An enricher with its own caches: repository roots (forever), HEAD (one
49
+ * minute), first commit (six hours) and long definitions (per file version).
50
+ * `git status` runs on every call, since it is what changes.
51
+ */
52
+ export declare function createGitEnricher(run?: (args: string[]) => Runner): <T extends SessionRecord>(rec: T) => Promise<T & EnrichedSession>;
package/dist/git.js ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Optional enrichment from git: which repository a session is in, its HEAD,
3
+ * uncommitted files and a few craft signals. Kept out of the main entry point
4
+ * (import `@loksly/agent-sessions/git`) because it runs `git` and the hook
5
+ * must stay light.
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { readFileSync, statSync, existsSync } from 'node:fs';
9
+ import { basename } from 'node:path';
10
+ import { promisify } from 'node:util';
11
+ import { longestDefinition, SPAGHETTI_LINES } from "./craft.js";
12
+ const execFileAsync = promisify(execFile);
13
+ const NEGATIVE_TTL_MS = 10 * 60_000;
14
+ /**
15
+ * Root of the git repository containing a directory, cached. A session opened
16
+ * in `repo/apps/server/src` belongs to `repo`, and two sessions in different
17
+ * subdirectories of the same repository are recognised as one project. A
18
+ * directory's root does not change, so it is asked once; directories that are
19
+ * not repositories are remembered only for a while (someone may `git init`).
20
+ */
21
+ export function repoRootCache(run, now = Date.now) {
22
+ const known = new Map();
23
+ return async (cwd) => {
24
+ const hit = known.get(cwd);
25
+ if (hit && (hit.root !== null || now() - hit.at < NEGATIVE_TTL_MS))
26
+ return hit.root;
27
+ const out = (await run(cwd))?.trim() || null;
28
+ known.set(cwd, { root: out, at: now() });
29
+ return out;
30
+ };
31
+ }
32
+ /**
33
+ * `git log -1 --format=%ct%n%D` → HeadInfo. The second line holds the refs:
34
+ * "HEAD -> main, origin/main" on a branch, "HEAD, …" when detached.
35
+ */
36
+ export function parseHead(out) {
37
+ const [ct, refs = ''] = out.trim().split('\n');
38
+ const secs = Number(ct);
39
+ if (!ct || !Number.isFinite(secs))
40
+ return null;
41
+ return { detached: !/\bHEAD -> /.test(refs), lastCommit: secs * 1000 };
42
+ }
43
+ /** HEAD of each repository, asked at most once per `ttlMs`. */
44
+ export function headCache(run, ttlMs = 60_000, now = Date.now) {
45
+ const known = new Map();
46
+ return async (root) => {
47
+ const hit = known.get(root);
48
+ if (hit && now() - hit.at < ttlMs)
49
+ return hit.info;
50
+ const out = await run(root);
51
+ const info = out ? parseHead(out) : null;
52
+ known.set(root, { info, at: now() });
53
+ return info;
54
+ };
55
+ }
56
+ const git = (args, timeout = 2000) => async (cwd) => {
57
+ try {
58
+ return (await execFileAsync('git', args, { cwd, timeout })).stdout;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ };
64
+ /** Parses `git status --porcelain` into a count and paths (renames keep the new path). */
65
+ export function parseStatus(out) {
66
+ const lines = out.split('\n').filter((l) => l.trim().length > 0);
67
+ const files = lines.map((l) => l.slice(3).split(' -> ').pop().replace(/^"|"$/g, ''));
68
+ return { count: lines.length, files };
69
+ }
70
+ /**
71
+ * An enricher with its own caches: repository roots (forever), HEAD (one
72
+ * minute), first commit (six hours) and long definitions (per file version).
73
+ * `git status` runs on every call, since it is what changes.
74
+ */
75
+ export function createGitEnricher(run = (args) => git(args)) {
76
+ const repoRoot = repoRootCache(run(['rev-parse', '--show-toplevel']));
77
+ const headOf = headCache(run(['log', '-1', '--format=%ct%n%D']));
78
+ const born = new Map();
79
+ const long = new Map();
80
+ async function bornOf(root) {
81
+ const hit = born.get(root);
82
+ if (hit && Date.now() - hit.at < 6 * 3_600_000)
83
+ return hit.born;
84
+ let value = null;
85
+ // In a shallow clone the root commit is a graft with the wrong date.
86
+ if ((await run(['rev-parse', '--is-shallow-repository'])(root))?.trim() === 'false') {
87
+ const out = await run(['log', '--max-parents=0', '--format=%at', 'HEAD'])(root);
88
+ const times = (out ?? '').split('\n').map(Number).filter((n) => n > 0);
89
+ if (times.length)
90
+ value = Math.min(...times) * 1000;
91
+ }
92
+ born.set(root, { born: value, at: Date.now() });
93
+ return value;
94
+ }
95
+ function isSpaghetti(path) {
96
+ if (!/\.(ts|tsx|js|jsx|mjs|py|go|rs|java|kt|cs|php|rb|c|cc|cpp|h|swift)$/.test(path))
97
+ return false;
98
+ try {
99
+ const st = statSync(path);
100
+ const hit = long.get(path);
101
+ if (hit && hit.mtime === st.mtimeMs)
102
+ return hit.long;
103
+ const value = st.size < 2_000_000 && longestDefinition(readFileSync(path, 'utf8')) > SPAGHETTI_LINES;
104
+ if (long.size > 500)
105
+ long.clear();
106
+ long.set(path, { mtime: st.mtimeMs, long: value });
107
+ return value;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ return async function enrich(rec) {
114
+ const out = { ...rec };
115
+ if (!rec.cwd || !existsSync(rec.cwd))
116
+ return out;
117
+ const root = await repoRoot(rec.cwd);
118
+ if (root) {
119
+ out.repo = root;
120
+ out.project = basename(root);
121
+ const head = await headOf(root);
122
+ if (head?.detached)
123
+ out.detached = true;
124
+ if (head?.lastCommit)
125
+ out.lastCommit = head.lastCommit;
126
+ const b = await bornOf(root);
127
+ if (b)
128
+ out.repoBorn = b;
129
+ }
130
+ if (rec.files?.some(isSpaghetti))
131
+ out.spaghetti = true;
132
+ const status = await run(['status', '--porcelain'])(rec.cwd);
133
+ if (status !== null) {
134
+ const s = parseStatus(status);
135
+ out.dirty = s.count;
136
+ out.dirtyFiles = s.files;
137
+ }
138
+ return out;
139
+ };
140
+ }
package/dist/hook.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { type SessionRecord } from './protocol.ts';
2
+ export type HookResult = {
3
+ remove: true;
4
+ sessionId: string;
5
+ } | {
6
+ record: SessionRecord;
7
+ };
8
+ /**
9
+ * The new record for this event, given the previous one (or that the session
10
+ * ended). `since` is kept while the state does not change: clients show "how
11
+ * long has it been waiting", which would reset on every event otherwise.
12
+ */
13
+ export declare function handleEvent(provider: string, data: Record<string, any>, prev: SessionRecord | null, now: number, cwd?: string): HookResult;
14
+ /** `--provider <name>` from the command line; `claude` by default. */
15
+ export declare function providerFromArgs(argv: string[]): string;
16
+ /**
17
+ * Applies one event (the JSON text a CLI sends on stdin) to the sessions
18
+ * directory. The write is atomic (temporary file in the same directory, then
19
+ * rename), so readers never see half a JSON file.
20
+ *
21
+ * Returns what it did, so a wrapper can also keep its own log of the event;
22
+ * null when the input was empty or not JSON.
23
+ */
24
+ export declare function runHook(input: string, provider: string, dir?: string, now?: number): HookResult | null;
package/dist/hook.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The hook: turns one event from an AI coding CLI into the session's record.
3
+ *
4
+ * It runs on the path of every tool call, so: no network, no heavy imports,
5
+ * and it never fails loudly. `handleEvent` is the pure part (state machine and
6
+ * counters); `runHook` adds reading the previous record and the atomic write.
7
+ */
8
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { basename, join } from 'node:path';
10
+ import { todosAdded } from "./craft.js";
11
+ import { defaultSessionsDir, sessionFile } from "./paths.js";
12
+ import { SCHEMA_VERSION, TALKS_TO_DUCK } from "./protocol.js";
13
+ import { adapterFor } from "./providers.js";
14
+ import { redact } from "./redact.js";
15
+ import { commandFailed, testOutcome } from "./testsignal.js";
16
+ import { touchedFiles } from "./touched.js";
17
+ /** Field of `tool_input` that best identifies the call, by tool. */
18
+ const TOOL_ARG_KEYS = ['command', 'file_path', 'path', 'pattern', 'url', 'query', 'prompt'];
19
+ /** Summarises `tool_input` into a readable fragment. */
20
+ function summarizeToolInput(input) {
21
+ if (typeof input === 'string')
22
+ return input;
23
+ if (typeof input !== 'object' || input === null)
24
+ return '';
25
+ const obj = input;
26
+ for (const key of TOOL_ARG_KEYS) {
27
+ const v = obj[key];
28
+ if (typeof v === 'string' && v.length > 0)
29
+ return v;
30
+ }
31
+ return '';
32
+ }
33
+ /** `permission_prompt` → `Permission prompt`. */
34
+ function humanize(value) {
35
+ const spaced = value.replace(/[_-]+/g, ' ').trim();
36
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
37
+ }
38
+ /**
39
+ * Storage cap, not a display one: clients know their real width and can wrap
40
+ * over several lines; cutting here at one line's length would lose the rest
41
+ * for good. Secrets are redacted **before** cutting, so that an ellipsis can
42
+ * never leave half a secret in sight.
43
+ */
44
+ function truncate(text, max = 240) {
45
+ const flat = redact(text).replace(/\s+/g, ' ').trim();
46
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
47
+ }
48
+ /**
49
+ * The new record for this event, given the previous one (or that the session
50
+ * ended). `since` is kept while the state does not change: clients show "how
51
+ * long has it been waiting", which would reset on every event otherwise.
52
+ */
53
+ export function handleEvent(provider, data, prev, now, cwd = process.cwd()) {
54
+ const e = adapterFor(provider).normalize(data, cwd);
55
+ const event = e.event;
56
+ if (event === 'SessionEnd')
57
+ return { remove: true, sessionId: e.sessionId };
58
+ // SessionStart also arrives on resume and right after compacting the
59
+ // context: the session is the same one and must not lose what it has
60
+ // accumulated (duck, streaks, TODOs). Only a real start or a `/clear` resets.
61
+ const source = e.source.toLowerCase();
62
+ const continued = event === 'SessionStart' && (source === 'compact' || source === 'resume');
63
+ let state = 'active';
64
+ let detail = '';
65
+ switch (event) {
66
+ case 'SessionStart':
67
+ state = source === 'compact' ? 'active' : 'idle';
68
+ detail = humanize(e.source);
69
+ break;
70
+ case 'PreCompact':
71
+ detail = 'Compacting context';
72
+ break;
73
+ case 'UserPromptSubmit':
74
+ detail = e.prompt;
75
+ break;
76
+ case 'PreToolUse':
77
+ case 'PostToolUse':
78
+ case 'PostToolUseFailure': {
79
+ const arg = summarizeToolInput(e.toolInput);
80
+ detail = arg ? `${e.tool}: ${arg}` : e.tool;
81
+ break;
82
+ }
83
+ case 'Notification': {
84
+ // Documented matchers: permission_prompt | idle_prompt | auth_success |
85
+ // elicitation_* | agent_*.
86
+ const kind = e.notification.toLowerCase();
87
+ if (kind.includes('permission') || kind.includes('elicitation'))
88
+ state = 'permission';
89
+ else if (kind.includes('idle') || kind.includes('wait'))
90
+ state = 'waiting';
91
+ detail = humanize(e.notification);
92
+ break;
93
+ }
94
+ case 'Stop':
95
+ case 'SubagentStop':
96
+ state = 'ready';
97
+ detail = e.lastMessage;
98
+ break;
99
+ default:
100
+ detail = e.fallback;
101
+ }
102
+ const record = {
103
+ schemaVersion: SCHEMA_VERSION,
104
+ session_id: e.sessionId,
105
+ provider: adapterFor(provider).name,
106
+ state,
107
+ detail: truncate(detail),
108
+ project: basename(e.cwd),
109
+ cwd: e.cwd,
110
+ since: prev && prev.state === state && typeof prev.since === 'number' ? prev.since : now,
111
+ updated: now,
112
+ event: event || 'Unknown',
113
+ };
114
+ const files = touchedFiles(prev?.files, event, e.tool, e.toolInput, e.cwd);
115
+ if (files?.length)
116
+ record.files = files;
117
+ record.started = event === 'SessionStart' && !continued ? now : prev?.started ?? prev?.since ?? now;
118
+ // Red tests are remembered until the next run; a new session starts clean.
119
+ const outcome = testOutcome(event, e.tool, e.toolInput, e.toolResponse);
120
+ const failed = outcome ? outcome === 'fail' : event === 'SessionStart' && !continued ? false : prev?.testsFailed;
121
+ if (failed)
122
+ record.testsFailed = true;
123
+ const bad = commandFailed(event, e.tool, e.toolInput, e.toolResponse);
124
+ if (bad ?? (event === 'PreToolUse' ? false : prev?.lastFailed))
125
+ record.lastFailed = true;
126
+ const fresh = event === 'SessionStart' && !continued;
127
+ const streak = bad === true ? (prev?.failStreak ?? 0) + 1 : bad === false || fresh ? 0 : prev?.failStreak ?? 0;
128
+ if (streak)
129
+ record.failStreak = streak;
130
+ // A turn ends with Stop; any tool call in between resets the talk streak.
131
+ const talk = fresh || event === 'PreToolUse' ? 0 : event === 'Stop' ? (prev?.talkStreak ?? 0) + (prev?.event === 'UserPromptSubmit' ? 1 : 0) : prev?.talkStreak ?? 0;
132
+ if (talk)
133
+ record.talkStreak = talk;
134
+ if (!fresh && (talk >= TALKS_TO_DUCK || prev?.duck))
135
+ record.duck = true;
136
+ const compactAt = event === 'PreCompact' ? now : fresh ? undefined : prev?.compactAt;
137
+ if (compactAt)
138
+ record.compactAt = compactAt;
139
+ const todos = (fresh ? 0 : prev?.todos ?? 0) + (event === 'PostToolUse' ? todosAdded(e.tool, e.toolInput) : 0);
140
+ if (todos)
141
+ record.todos = todos;
142
+ return { record };
143
+ }
144
+ /** The previous record, if it is readable. */
145
+ function previous(path) {
146
+ try {
147
+ return JSON.parse(readFileSync(path, 'utf8'));
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ /** `--provider <name>` from the command line; `claude` by default. */
154
+ export function providerFromArgs(argv) {
155
+ const i = argv.indexOf('--provider');
156
+ return i >= 0 && argv[i + 1] ? argv[i + 1].toLowerCase() : 'claude';
157
+ }
158
+ /**
159
+ * Applies one event (the JSON text a CLI sends on stdin) to the sessions
160
+ * directory. The write is atomic (temporary file in the same directory, then
161
+ * rename), so readers never see half a JSON file.
162
+ *
163
+ * Returns what it did, so a wrapper can also keep its own log of the event;
164
+ * null when the input was empty or not JSON.
165
+ */
166
+ export function runHook(input, provider, dir = defaultSessionsDir(), now = Date.now()) {
167
+ const text = input.trim();
168
+ if (!text)
169
+ return null;
170
+ let data;
171
+ try {
172
+ data = JSON.parse(text);
173
+ }
174
+ catch {
175
+ return null; // Not JSON: ignore quietly.
176
+ }
177
+ const id = adapterFor(provider).normalize(data, process.cwd()).sessionId;
178
+ const path = sessionFile(dir, id);
179
+ const result = handleEvent(provider, data, previous(path), now);
180
+ if ('remove' in result) {
181
+ rmSync(path, { force: true });
182
+ return result;
183
+ }
184
+ mkdirSync(dir, { recursive: true });
185
+ const temp = join(dir, `.${id}.${process.pid}.tmp`);
186
+ try {
187
+ writeFileSync(temp, JSON.stringify(result.record, null, 2), 'utf8');
188
+ renameSync(temp, path);
189
+ }
190
+ catch {
191
+ rmSync(temp, { force: true });
192
+ }
193
+ return result;
194
+ }
@@ -0,0 +1,10 @@
1
+ export * from './protocol.ts';
2
+ export * from './paths.ts';
3
+ export * from './reader.ts';
4
+ export * from './select.ts';
5
+ export { handleEvent, runHook, providerFromArgs, type HookResult } from './hook.ts';
6
+ export { PROVIDERS, adapterFor, type HookEvent, type ProviderAdapter } from './providers.ts';
7
+ export { redact } from './redact.ts';
8
+ export { touchedFiles, MAX_FILES } from './touched.ts';
9
+ export { testOutcome, commandFailed, TEST_COMMAND } from './testsignal.ts';
10
+ export { todosAdded, longestDefinition, SPAGHETTI_LINES } from './craft.ts';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./protocol.js";
2
+ export * from "./paths.js";
3
+ export * from "./reader.js";
4
+ export * from "./select.js";
5
+ export { handleEvent, runHook, providerFromArgs } from "./hook.js";
6
+ export { PROVIDERS, adapterFor } from "./providers.js";
7
+ export { redact } from "./redact.js";
8
+ export { touchedFiles, MAX_FILES } from "./touched.js";
9
+ export { testOutcome, commandFailed, TEST_COMMAND } from "./testsignal.js";
10
+ export { todosAdded, longestDefinition, SPAGHETTI_LINES } from "./craft.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Where session files live: `$AGENT_SESSIONS_DIR`, or `sessions/` inside
3
+ * `$AIMONITOR_DIR` (default `~/.aimonitor`), where the first client of this
4
+ * protocol has always kept them.
5
+ */
6
+ export declare function defaultSessionsDir(env?: NodeJS.ProcessEnv): string;
7
+ /** The file of one session. */
8
+ export declare function sessionFile(dir: string, sessionId: string): string;