@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 +21 -0
- package/README.md +119 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +18 -0
- package/dist/craft.d.ts +14 -0
- package/dist/craft.js +41 -0
- package/dist/git.d.ts +52 -0
- package/dist/git.js +140 -0
- package/dist/hook.d.ts +24 -0
- package/dist/hook.js +194 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/paths.d.ts +8 -0
- package/dist/paths.js +14 -0
- package/dist/protocol.d.ts +68 -0
- package/dist/protocol.js +36 -0
- package/dist/providers.d.ts +36 -0
- package/dist/providers.js +32 -0
- package/dist/reader.d.ts +19 -0
- package/dist/reader.js +54 -0
- package/dist/redact.d.ts +1 -0
- package/dist/redact.js +29 -0
- package/dist/select.d.ts +20 -0
- package/dist/select.js +36 -0
- package/dist/testsignal.d.ts +18 -0
- package/dist/testsignal.js +70 -0
- package/dist/touched.d.ts +8 -0
- package/dist/touched.js +31 -0
- package/package.json +56 -4
- package/schema/session-record.schema.json +104 -0
- package/src/cli.ts +18 -0
- package/src/craft.ts +39 -0
- package/src/git.ts +165 -0
- package/src/hook.ts +189 -0
- package/src/index.ts +10 -0
- package/src/paths.ts +16 -0
- package/src/protocol.ts +97 -0
- package/src/providers.ts +71 -0
- package/src/reader.ts +56 -0
- package/src/redact.ts +30 -0
- package/src/select.ts +38 -0
- package/src/testsignal.ts +62 -0
- package/src/touched.ts +29 -0
package/src/cli.ts
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.ts';
|
|
9
|
+
|
|
10
|
+
process.on('uncaughtException', () => process.exit(0));
|
|
11
|
+
|
|
12
|
+
const chunks: Buffer[] = [];
|
|
13
|
+
for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
|
|
14
|
+
try {
|
|
15
|
+
runHook(Buffer.concat(chunks).toString('utf8'), providerFromArgs(process.argv.slice(2)));
|
|
16
|
+
} catch {
|
|
17
|
+
// Never fail loudly.
|
|
18
|
+
}
|
package/src/craft.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
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
|
+
|
|
6
|
+
/** TODO/FIXME added by an edit (new ones minus those already there). */
|
|
7
|
+
export function todosAdded(tool: string, input: unknown): number {
|
|
8
|
+
if (!input || typeof input !== 'object') return 0;
|
|
9
|
+
const o = input as Record<string, unknown>;
|
|
10
|
+
const count = (v: unknown) => (typeof v === 'string' ? (v.match(/\b(TODO|FIXME)\b/g) ?? []).length : 0);
|
|
11
|
+
if (/^(Edit|replace)$/.test(tool)) return Math.max(0, count(o.new_string) - count(o.old_string));
|
|
12
|
+
if (tool === 'MultiEdit' && Array.isArray(o.edits)) {
|
|
13
|
+
return (o.edits as Record<string, unknown>[]).reduce((n, e) => n + Math.max(0, count(e.new_string) - count(e.old_string)), 0);
|
|
14
|
+
}
|
|
15
|
+
if (/^(Write|write_file)$/.test(tool)) return count(o.content);
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Longest definition in a file, in lines: from one top-level definition
|
|
21
|
+
* (`function`, `def`, `fn`, `func`, `class`, `export …`) to the next. Plenty
|
|
22
|
+
* of heuristic to tell whether there is a 500-line monster in there.
|
|
23
|
+
*/
|
|
24
|
+
export function longestDefinition(text: string): number {
|
|
25
|
+
const lines = text.split('\n');
|
|
26
|
+
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)/;
|
|
27
|
+
let best = 0, from = -1;
|
|
28
|
+
lines.forEach((l, i) => {
|
|
29
|
+
if (START.test(l)) {
|
|
30
|
+
if (from >= 0) best = Math.max(best, i - from);
|
|
31
|
+
from = i;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
if (from >= 0) best = Math.max(best, lines.length - from);
|
|
35
|
+
return best;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A definition longer than this is spaghetti. */
|
|
39
|
+
export const SPAGHETTI_LINES = 500;
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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.ts';
|
|
12
|
+
import type { SessionRecord } from './protocol.ts';
|
|
13
|
+
|
|
14
|
+
const execFileAsync = promisify(execFile);
|
|
15
|
+
|
|
16
|
+
/** Runs a git query in a directory; null if it fails. */
|
|
17
|
+
export type Runner = (cwd: string) => Promise<string | null>;
|
|
18
|
+
|
|
19
|
+
const NEGATIVE_TTL_MS = 10 * 60_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Root of the git repository containing a directory, cached. A session opened
|
|
23
|
+
* in `repo/apps/server/src` belongs to `repo`, and two sessions in different
|
|
24
|
+
* subdirectories of the same repository are recognised as one project. A
|
|
25
|
+
* directory's root does not change, so it is asked once; directories that are
|
|
26
|
+
* not repositories are remembered only for a while (someone may `git init`).
|
|
27
|
+
*/
|
|
28
|
+
export function repoRootCache(run: Runner, now: () => number = Date.now) {
|
|
29
|
+
const known = new Map<string, { root: string | null; at: number }>();
|
|
30
|
+
return async (cwd: string): Promise<string | null> => {
|
|
31
|
+
const hit = known.get(cwd);
|
|
32
|
+
if (hit && (hit.root !== null || now() - hit.at < NEGATIVE_TTL_MS)) return hit.root;
|
|
33
|
+
const out = (await run(cwd))?.trim() || null;
|
|
34
|
+
known.set(cwd, { root: out, at: now() });
|
|
35
|
+
return out;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface HeadInfo {
|
|
40
|
+
/** Detached HEAD (not on any branch). */
|
|
41
|
+
detached: boolean;
|
|
42
|
+
/** Date of the last commit, ms epoch; absent in a repository without commits. */
|
|
43
|
+
lastCommit?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `git log -1 --format=%ct%n%D` → HeadInfo. The second line holds the refs:
|
|
48
|
+
* "HEAD -> main, origin/main" on a branch, "HEAD, …" when detached.
|
|
49
|
+
*/
|
|
50
|
+
export function parseHead(out: string): HeadInfo | null {
|
|
51
|
+
const [ct, refs = ''] = out.trim().split('\n');
|
|
52
|
+
const secs = Number(ct);
|
|
53
|
+
if (!ct || !Number.isFinite(secs)) return null;
|
|
54
|
+
return { detached: !/\bHEAD -> /.test(refs), lastCommit: secs * 1000 };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** HEAD of each repository, asked at most once per `ttlMs`. */
|
|
58
|
+
export function headCache(run: Runner, ttlMs = 60_000, now: () => number = Date.now) {
|
|
59
|
+
const known = new Map<string, { info: HeadInfo | null; at: number }>();
|
|
60
|
+
return async (root: string): Promise<HeadInfo | null> => {
|
|
61
|
+
const hit = known.get(root);
|
|
62
|
+
if (hit && now() - hit.at < ttlMs) return hit.info;
|
|
63
|
+
const out = await run(root);
|
|
64
|
+
const info = out ? parseHead(out) : null;
|
|
65
|
+
known.set(root, { info, at: now() });
|
|
66
|
+
return info;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A session record plus what git says about its working directory. */
|
|
71
|
+
export interface EnrichedSession extends SessionRecord {
|
|
72
|
+
/** Root of the git repository containing `cwd`; `project` is then its name. */
|
|
73
|
+
repo?: string;
|
|
74
|
+
/** Detached HEAD in its repository. */
|
|
75
|
+
detached?: boolean;
|
|
76
|
+
/** Date of the last commit on its branch, ms epoch. */
|
|
77
|
+
lastCommit?: number;
|
|
78
|
+
/** Date of the repository's first commit, ms epoch (unknown in shallow clones). */
|
|
79
|
+
repoBorn?: number;
|
|
80
|
+
/** Some file it touched has a definition longer than `SPAGHETTI_LINES`. */
|
|
81
|
+
spaghetti?: boolean;
|
|
82
|
+
/** Uncommitted files. */
|
|
83
|
+
dirty?: number;
|
|
84
|
+
/** Paths of those files, relative to the repository root, as `git status` gives them. */
|
|
85
|
+
dirtyFiles?: string[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const git = (args: string[], timeout = 2000): Runner => async (cwd) => {
|
|
89
|
+
try {
|
|
90
|
+
return (await execFileAsync('git', args, { cwd, timeout })).stdout;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** Parses `git status --porcelain` into a count and paths (renames keep the new path). */
|
|
97
|
+
export function parseStatus(out: string): { count: number; files: string[] } {
|
|
98
|
+
const lines = out.split('\n').filter((l) => l.trim().length > 0);
|
|
99
|
+
const files = lines.map((l) => l.slice(3).split(' -> ').pop()!.replace(/^"|"$/g, ''));
|
|
100
|
+
return { count: lines.length, files };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* An enricher with its own caches: repository roots (forever), HEAD (one
|
|
105
|
+
* minute), first commit (six hours) and long definitions (per file version).
|
|
106
|
+
* `git status` runs on every call, since it is what changes.
|
|
107
|
+
*/
|
|
108
|
+
export function createGitEnricher(run: (args: string[]) => Runner = (args) => git(args)) {
|
|
109
|
+
const repoRoot = repoRootCache(run(['rev-parse', '--show-toplevel']));
|
|
110
|
+
const headOf = headCache(run(['log', '-1', '--format=%ct%n%D']));
|
|
111
|
+
const born = new Map<string, { born: number | null; at: number }>();
|
|
112
|
+
const long = new Map<string, { mtime: number; long: boolean }>();
|
|
113
|
+
|
|
114
|
+
async function bornOf(root: string): Promise<number | null> {
|
|
115
|
+
const hit = born.get(root);
|
|
116
|
+
if (hit && Date.now() - hit.at < 6 * 3_600_000) return hit.born;
|
|
117
|
+
let value: number | null = null;
|
|
118
|
+
// In a shallow clone the root commit is a graft with the wrong date.
|
|
119
|
+
if ((await run(['rev-parse', '--is-shallow-repository'])(root))?.trim() === 'false') {
|
|
120
|
+
const out = await run(['log', '--max-parents=0', '--format=%at', 'HEAD'], )(root);
|
|
121
|
+
const times = (out ?? '').split('\n').map(Number).filter((n) => n > 0);
|
|
122
|
+
if (times.length) value = Math.min(...times) * 1000;
|
|
123
|
+
}
|
|
124
|
+
born.set(root, { born: value, at: Date.now() });
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isSpaghetti(path: string): boolean {
|
|
129
|
+
if (!/\.(ts|tsx|js|jsx|mjs|py|go|rs|java|kt|cs|php|rb|c|cc|cpp|h|swift)$/.test(path)) return false;
|
|
130
|
+
try {
|
|
131
|
+
const st = statSync(path);
|
|
132
|
+
const hit = long.get(path);
|
|
133
|
+
if (hit && hit.mtime === st.mtimeMs) return hit.long;
|
|
134
|
+
const value = st.size < 2_000_000 && longestDefinition(readFileSync(path, 'utf8')) > SPAGHETTI_LINES;
|
|
135
|
+
if (long.size > 500) long.clear();
|
|
136
|
+
long.set(path, { mtime: st.mtimeMs, long: value });
|
|
137
|
+
return value;
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return async function enrich<T extends SessionRecord>(rec: T): Promise<T & EnrichedSession> {
|
|
144
|
+
const out: T & EnrichedSession = { ...rec };
|
|
145
|
+
if (!rec.cwd || !existsSync(rec.cwd)) return out;
|
|
146
|
+
const root = await repoRoot(rec.cwd);
|
|
147
|
+
if (root) {
|
|
148
|
+
out.repo = root;
|
|
149
|
+
out.project = basename(root);
|
|
150
|
+
const head = await headOf(root);
|
|
151
|
+
if (head?.detached) out.detached = true;
|
|
152
|
+
if (head?.lastCommit) out.lastCommit = head.lastCommit;
|
|
153
|
+
const b = await bornOf(root);
|
|
154
|
+
if (b) out.repoBorn = b;
|
|
155
|
+
}
|
|
156
|
+
if (rec.files?.some(isSpaghetti)) out.spaghetti = true;
|
|
157
|
+
const status = await run(['status', '--porcelain'])(rec.cwd);
|
|
158
|
+
if (status !== null) {
|
|
159
|
+
const s = parseStatus(status);
|
|
160
|
+
out.dirty = s.count;
|
|
161
|
+
out.dirtyFiles = s.files;
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
};
|
|
165
|
+
}
|
package/src/hook.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
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.ts';
|
|
11
|
+
import { defaultSessionsDir, sessionFile } from './paths.ts';
|
|
12
|
+
import { SCHEMA_VERSION, TALKS_TO_DUCK, type SessionRecord, type SessionState } from './protocol.ts';
|
|
13
|
+
import { adapterFor } from './providers.ts';
|
|
14
|
+
import { redact } from './redact.ts';
|
|
15
|
+
import { commandFailed, testOutcome } from './testsignal.ts';
|
|
16
|
+
import { touchedFiles } from './touched.ts';
|
|
17
|
+
|
|
18
|
+
/** Field of `tool_input` that best identifies the call, by tool. */
|
|
19
|
+
const TOOL_ARG_KEYS = ['command', 'file_path', 'path', 'pattern', 'url', 'query', 'prompt'] as const;
|
|
20
|
+
|
|
21
|
+
/** Summarises `tool_input` into a readable fragment. */
|
|
22
|
+
function summarizeToolInput(input: unknown): string {
|
|
23
|
+
if (typeof input === 'string') return input;
|
|
24
|
+
if (typeof input !== 'object' || input === null) return '';
|
|
25
|
+
const obj = input as Record<string, unknown>;
|
|
26
|
+
for (const key of TOOL_ARG_KEYS) {
|
|
27
|
+
const v = obj[key];
|
|
28
|
+
if (typeof v === 'string' && v.length > 0) return v;
|
|
29
|
+
}
|
|
30
|
+
return '';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `permission_prompt` → `Permission prompt`. */
|
|
34
|
+
function humanize(value: string): string {
|
|
35
|
+
const spaced = value.replace(/[_-]+/g, ' ').trim();
|
|
36
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Storage cap, not a display one: clients know their real width and can wrap
|
|
41
|
+
* over several lines; cutting here at one line's length would lose the rest
|
|
42
|
+
* for good. Secrets are redacted **before** cutting, so that an ellipsis can
|
|
43
|
+
* never leave half a secret in sight.
|
|
44
|
+
*/
|
|
45
|
+
function truncate(text: string, max = 240): string {
|
|
46
|
+
const flat = redact(text).replace(/\s+/g, ' ').trim();
|
|
47
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type HookResult = { remove: true; sessionId: string } | { record: SessionRecord };
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The new record for this event, given the previous one (or that the session
|
|
54
|
+
* ended). `since` is kept while the state does not change: clients show "how
|
|
55
|
+
* long has it been waiting", which would reset on every event otherwise.
|
|
56
|
+
*/
|
|
57
|
+
export function handleEvent(provider: string, data: Record<string, any>, prev: SessionRecord | null, now: number, cwd = process.cwd()): HookResult {
|
|
58
|
+
const e = adapterFor(provider).normalize(data, cwd);
|
|
59
|
+
const event = e.event;
|
|
60
|
+
if (event === 'SessionEnd') return { remove: true, sessionId: e.sessionId };
|
|
61
|
+
|
|
62
|
+
// SessionStart also arrives on resume and right after compacting the
|
|
63
|
+
// context: the session is the same one and must not lose what it has
|
|
64
|
+
// accumulated (duck, streaks, TODOs). Only a real start or a `/clear` resets.
|
|
65
|
+
const source = e.source.toLowerCase();
|
|
66
|
+
const continued = event === 'SessionStart' && (source === 'compact' || source === 'resume');
|
|
67
|
+
|
|
68
|
+
let state: SessionState = 'active';
|
|
69
|
+
let detail = '';
|
|
70
|
+
switch (event) {
|
|
71
|
+
case 'SessionStart':
|
|
72
|
+
state = source === 'compact' ? 'active' : 'idle';
|
|
73
|
+
detail = humanize(e.source);
|
|
74
|
+
break;
|
|
75
|
+
case 'PreCompact':
|
|
76
|
+
detail = 'Compacting context';
|
|
77
|
+
break;
|
|
78
|
+
case 'UserPromptSubmit':
|
|
79
|
+
detail = e.prompt;
|
|
80
|
+
break;
|
|
81
|
+
case 'PreToolUse':
|
|
82
|
+
case 'PostToolUse':
|
|
83
|
+
case 'PostToolUseFailure': {
|
|
84
|
+
const arg = summarizeToolInput(e.toolInput);
|
|
85
|
+
detail = arg ? `${e.tool}: ${arg}` : e.tool;
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
case 'Notification': {
|
|
89
|
+
// Documented matchers: permission_prompt | idle_prompt | auth_success |
|
|
90
|
+
// elicitation_* | agent_*.
|
|
91
|
+
const kind = e.notification.toLowerCase();
|
|
92
|
+
if (kind.includes('permission') || kind.includes('elicitation')) state = 'permission';
|
|
93
|
+
else if (kind.includes('idle') || kind.includes('wait')) state = 'waiting';
|
|
94
|
+
detail = humanize(e.notification);
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case 'Stop':
|
|
98
|
+
case 'SubagentStop':
|
|
99
|
+
state = 'ready';
|
|
100
|
+
detail = e.lastMessage;
|
|
101
|
+
break;
|
|
102
|
+
default:
|
|
103
|
+
detail = e.fallback;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const record: SessionRecord = {
|
|
107
|
+
schemaVersion: SCHEMA_VERSION,
|
|
108
|
+
session_id: e.sessionId,
|
|
109
|
+
provider: adapterFor(provider).name,
|
|
110
|
+
state,
|
|
111
|
+
detail: truncate(detail),
|
|
112
|
+
project: basename(e.cwd),
|
|
113
|
+
cwd: e.cwd,
|
|
114
|
+
since: prev && prev.state === state && typeof prev.since === 'number' ? prev.since : now,
|
|
115
|
+
updated: now,
|
|
116
|
+
event: event || 'Unknown',
|
|
117
|
+
};
|
|
118
|
+
const files = touchedFiles(prev?.files, event, e.tool, e.toolInput, e.cwd);
|
|
119
|
+
if (files?.length) record.files = files;
|
|
120
|
+
record.started = event === 'SessionStart' && !continued ? now : prev?.started ?? prev?.since ?? now;
|
|
121
|
+
// Red tests are remembered until the next run; a new session starts clean.
|
|
122
|
+
const outcome = testOutcome(event, e.tool, e.toolInput, e.toolResponse);
|
|
123
|
+
const failed = outcome ? outcome === 'fail' : event === 'SessionStart' && !continued ? false : prev?.testsFailed;
|
|
124
|
+
if (failed) record.testsFailed = true;
|
|
125
|
+
const bad = commandFailed(event, e.tool, e.toolInput, e.toolResponse);
|
|
126
|
+
if (bad ?? (event === 'PreToolUse' ? false : prev?.lastFailed)) record.lastFailed = true;
|
|
127
|
+
const fresh = event === 'SessionStart' && !continued;
|
|
128
|
+
const streak = bad === true ? (prev?.failStreak ?? 0) + 1 : bad === false || fresh ? 0 : prev?.failStreak ?? 0;
|
|
129
|
+
if (streak) 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) record.talkStreak = talk;
|
|
133
|
+
if (!fresh && (talk >= TALKS_TO_DUCK || prev?.duck)) record.duck = true;
|
|
134
|
+
const compactAt = event === 'PreCompact' ? now : fresh ? undefined : prev?.compactAt;
|
|
135
|
+
if (compactAt) record.compactAt = compactAt;
|
|
136
|
+
const todos = (fresh ? 0 : prev?.todos ?? 0) + (event === 'PostToolUse' ? todosAdded(e.tool, e.toolInput) : 0);
|
|
137
|
+
if (todos) record.todos = todos;
|
|
138
|
+
return { record };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The previous record, if it is readable. */
|
|
142
|
+
function previous(path: string): SessionRecord | null {
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(readFileSync(path, 'utf8')) as SessionRecord;
|
|
145
|
+
} catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** `--provider <name>` from the command line; `claude` by default. */
|
|
151
|
+
export function providerFromArgs(argv: string[]): string {
|
|
152
|
+
const i = argv.indexOf('--provider');
|
|
153
|
+
return i >= 0 && argv[i + 1] ? argv[i + 1]!.toLowerCase() : 'claude';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Applies one event (the JSON text a CLI sends on stdin) to the sessions
|
|
158
|
+
* directory. The write is atomic (temporary file in the same directory, then
|
|
159
|
+
* rename), so readers never see half a JSON file.
|
|
160
|
+
*
|
|
161
|
+
* Returns what it did, so a wrapper can also keep its own log of the event;
|
|
162
|
+
* null when the input was empty or not JSON.
|
|
163
|
+
*/
|
|
164
|
+
export function runHook(input: string, provider: string, dir = defaultSessionsDir(), now = Date.now()): HookResult | null {
|
|
165
|
+
const text = input.trim();
|
|
166
|
+
if (!text) return null;
|
|
167
|
+
let data: Record<string, any>;
|
|
168
|
+
try {
|
|
169
|
+
data = JSON.parse(text);
|
|
170
|
+
} catch {
|
|
171
|
+
return null; // Not JSON: ignore quietly.
|
|
172
|
+
}
|
|
173
|
+
const id = adapterFor(provider).normalize(data, process.cwd()).sessionId;
|
|
174
|
+
const path = sessionFile(dir, id);
|
|
175
|
+
const result = handleEvent(provider, data, previous(path), now);
|
|
176
|
+
if ('remove' in result) {
|
|
177
|
+
rmSync(path, { force: true });
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
mkdirSync(dir, { recursive: true });
|
|
181
|
+
const temp = join(dir, `.${id}.${process.pid}.tmp`);
|
|
182
|
+
try {
|
|
183
|
+
writeFileSync(temp, JSON.stringify(result.record, null, 2), 'utf8');
|
|
184
|
+
renameSync(temp, path);
|
|
185
|
+
} catch {
|
|
186
|
+
rmSync(temp, { force: true });
|
|
187
|
+
}
|
|
188
|
+
return result;
|
|
189
|
+
}
|
package/src/index.ts
ADDED
|
@@ -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/src/paths.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Where session files live: `$AGENT_SESSIONS_DIR`, or `sessions/` inside
|
|
6
|
+
* `$AIMONITOR_DIR` (default `~/.aimonitor`), where the first client of this
|
|
7
|
+
* protocol has always kept them.
|
|
8
|
+
*/
|
|
9
|
+
export function defaultSessionsDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
10
|
+
return env.AGENT_SESSIONS_DIR ?? join(env.AIMONITOR_DIR ?? join(homedir(), '.aimonitor'), 'sessions');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The file of one session. */
|
|
14
|
+
export function sessionFile(dir: string, sessionId: string): string {
|
|
15
|
+
return join(dir, `${sessionId}.json`);
|
|
16
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session protocol: what a hook writes for each AI coding session, one
|
|
3
|
+
* JSON file per session, and what any client (a panel, a status bar, a
|
|
4
|
+
* microcontroller) can read. `schema/session-record.schema.json` describes the
|
|
5
|
+
* same record for clients in other languages.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Version of the record format. Bumped on any incompatible change. */
|
|
9
|
+
export const SCHEMA_VERSION = 1;
|
|
10
|
+
|
|
11
|
+
/** The CLIs this package knows how to read events from (see providers.ts). */
|
|
12
|
+
export type KnownProvider = 'claude' | 'gemini';
|
|
13
|
+
/** A provider name; known ones get their event names translated. */
|
|
14
|
+
export type Provider = KnownProvider | (string & {});
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What the session needs from you, from most to least urgent:
|
|
18
|
+
*
|
|
19
|
+
* - `permission`: blocked on a permission prompt;
|
|
20
|
+
* - `waiting`: idle, waiting for your input;
|
|
21
|
+
* - `ready`: finished its turn;
|
|
22
|
+
* - `active`: working;
|
|
23
|
+
* - `idle`: just started (or resumed), nothing asked yet.
|
|
24
|
+
*/
|
|
25
|
+
export type SessionState = 'permission' | 'waiting' | 'ready' | 'active' | 'idle';
|
|
26
|
+
|
|
27
|
+
export const SESSION_STATES: readonly SessionState[] = ['permission', 'waiting', 'ready', 'active', 'idle'];
|
|
28
|
+
|
|
29
|
+
/** Higher = more urgent. Decides which session leads. */
|
|
30
|
+
export const STATE_PRIORITY: Readonly<Record<SessionState, number>> = {
|
|
31
|
+
permission: 4,
|
|
32
|
+
waiting: 3,
|
|
33
|
+
ready: 2,
|
|
34
|
+
active: 1,
|
|
35
|
+
idle: 0,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** States in which the session is asking for the operator. */
|
|
39
|
+
export const CLAIMS: ReadonlySet<SessionState> = new Set<SessionState>(['permission', 'waiting', 'ready']);
|
|
40
|
+
|
|
41
|
+
/** Consecutive talk-only turns (no tools) that set `duck`. */
|
|
42
|
+
export const TALKS_TO_DUCK = 2;
|
|
43
|
+
|
|
44
|
+
/** One session, as the hook writes it to `<sessions dir>/<session_id>.json`. */
|
|
45
|
+
export interface SessionRecord {
|
|
46
|
+
schemaVersion: typeof SCHEMA_VERSION;
|
|
47
|
+
session_id: string;
|
|
48
|
+
provider: Provider;
|
|
49
|
+
state: SessionState;
|
|
50
|
+
/** Tool call or message, secrets redacted, at most 240 characters. */
|
|
51
|
+
detail: string;
|
|
52
|
+
/** Basename of `cwd`. */
|
|
53
|
+
project: string;
|
|
54
|
+
/** Full working directory of the session. */
|
|
55
|
+
cwd?: string;
|
|
56
|
+
/** When it entered the current state, ms epoch. Kept while the state does not change. */
|
|
57
|
+
since: number;
|
|
58
|
+
/** When the session started, ms epoch. */
|
|
59
|
+
started?: number;
|
|
60
|
+
/** Last write, ms epoch. */
|
|
61
|
+
updated: number;
|
|
62
|
+
/** Name of the hook event that produced the record. */
|
|
63
|
+
event: string;
|
|
64
|
+
/** Files the session edited or wrote, absolute, most recent first (at most 20). */
|
|
65
|
+
files?: string[];
|
|
66
|
+
/** The last shell command failed. */
|
|
67
|
+
lastFailed?: boolean;
|
|
68
|
+
/** Consecutive failed shell commands. */
|
|
69
|
+
failStreak?: number;
|
|
70
|
+
/** Consecutive turns with talk only, no tools. */
|
|
71
|
+
talkStreak?: number;
|
|
72
|
+
/** `talkStreak` reached `TALKS_TO_DUCK` at some point in this session. */
|
|
73
|
+
duck?: boolean;
|
|
74
|
+
/** Last context compaction (PreCompact), ms epoch. */
|
|
75
|
+
compactAt?: number;
|
|
76
|
+
/** TODO/FIXME added during the session. */
|
|
77
|
+
todos?: number;
|
|
78
|
+
/** The last test run of the session failed (see testsignal.ts). */
|
|
79
|
+
testsFailed?: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Does `x` look like a record of this schema version? Checks the fields clients rely on. */
|
|
83
|
+
export function isSessionRecord(x: unknown): x is SessionRecord {
|
|
84
|
+
if (typeof x !== 'object' || x === null) return false;
|
|
85
|
+
const r = x as Record<string, unknown>;
|
|
86
|
+
return (
|
|
87
|
+
r.schemaVersion === SCHEMA_VERSION &&
|
|
88
|
+
typeof r.session_id === 'string' &&
|
|
89
|
+
typeof r.provider === 'string' &&
|
|
90
|
+
SESSION_STATES.includes(r.state as SessionState) &&
|
|
91
|
+
typeof r.detail === 'string' &&
|
|
92
|
+
typeof r.project === 'string' &&
|
|
93
|
+
typeof r.since === 'number' &&
|
|
94
|
+
typeof r.updated === 'number' &&
|
|
95
|
+
typeof r.event === 'string'
|
|
96
|
+
);
|
|
97
|
+
}
|
package/src/providers.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider adapters: how to read an event from each CLI's hook payload.
|
|
3
|
+
*
|
|
4
|
+
* Every CLI sends a JSON object on stdin, but field names differ. An adapter
|
|
5
|
+
* turns that object into a `HookEvent` with canonical names (Claude Code's
|
|
6
|
+
* event names: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse,
|
|
7
|
+
* PostToolUseFailure, Notification, Stop, SubagentStop, PreCompact,
|
|
8
|
+
* SessionEnd). Adding a CLI means adding an adapter here, with its fixtures
|
|
9
|
+
* in the tests; the state machine in hook.ts does not change.
|
|
10
|
+
*/
|
|
11
|
+
import type { KnownProvider } from './protocol.ts';
|
|
12
|
+
|
|
13
|
+
export interface HookEvent {
|
|
14
|
+
/** Canonical event name ('' if absent). */
|
|
15
|
+
event: string;
|
|
16
|
+
sessionId: string;
|
|
17
|
+
cwd: string;
|
|
18
|
+
tool: string;
|
|
19
|
+
toolInput: unknown;
|
|
20
|
+
toolResponse: unknown;
|
|
21
|
+
/** Why a session started: startup, resume, compact, clear… */
|
|
22
|
+
source: string;
|
|
23
|
+
/** Notification kind or message. */
|
|
24
|
+
notification: string;
|
|
25
|
+
prompt: string;
|
|
26
|
+
/** The assistant's last message, on Stop. */
|
|
27
|
+
lastMessage: string;
|
|
28
|
+
/** Free text for events this package does not know. */
|
|
29
|
+
fallback: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ProviderAdapter {
|
|
33
|
+
name: string;
|
|
34
|
+
normalize(data: Record<string, any>, cwd: string): HookEvent;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Event names that differ from Claude Code's, per provider. */
|
|
38
|
+
const ALIASES: Record<string, Record<string, string>> = {};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The field names Claude Code uses, with the alternatives Gemini CLI and
|
|
42
|
+
* hand-written scripts have been seen to send.
|
|
43
|
+
*/
|
|
44
|
+
function generic(provider: string) {
|
|
45
|
+
return (data: Record<string, any>, cwd: string): HookEvent => {
|
|
46
|
+
const raw: string = data.hook_event_name || data.event || data.type || '';
|
|
47
|
+
return {
|
|
48
|
+
event: ALIASES[provider]?.[raw] ?? raw,
|
|
49
|
+
sessionId: data.session_id || data.sessionId || 'global',
|
|
50
|
+
cwd: data.cwd || cwd,
|
|
51
|
+
tool: String(data.tool_name ?? data.tool?.name ?? data.tool ?? ''),
|
|
52
|
+
toolInput: data.tool_input ?? data.tool?.arguments,
|
|
53
|
+
toolResponse: data.tool_response,
|
|
54
|
+
source: String(data.source ?? data.session_start_type ?? ''),
|
|
55
|
+
notification: String(data.notification_type ?? data.notificationType ?? data.message ?? ''),
|
|
56
|
+
prompt: String(data.prompt ?? ''),
|
|
57
|
+
lastMessage: String(data.last_assistant_message ?? ''),
|
|
58
|
+
fallback: String(data.detail ?? data.message ?? data.command ?? ''),
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const PROVIDERS: Readonly<Record<KnownProvider, ProviderAdapter>> = {
|
|
64
|
+
claude: { name: 'claude', normalize: generic('claude') },
|
|
65
|
+
gemini: { name: 'gemini', normalize: generic('gemini') },
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** The adapter for a provider name; unknown names read the generic field names. */
|
|
69
|
+
export function adapterFor(name: string): ProviderAdapter {
|
|
70
|
+
return (PROVIDERS as Record<string, ProviderAdapter>)[name] ?? { name, normalize: generic(name) };
|
|
71
|
+
}
|
package/src/reader.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the sessions directory, for clients.
|
|
3
|
+
*/
|
|
4
|
+
import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { defaultSessionsDir, sessionFile } from './paths.ts';
|
|
7
|
+
import { isSessionRecord, type SessionRecord } from './protocol.ts';
|
|
8
|
+
import { pruneZombies } from './select.ts';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Every valid record in the directory. Files that are half-written,
|
|
12
|
+
* unreadable or of another schema version are skipped, never thrown.
|
|
13
|
+
*/
|
|
14
|
+
export function readSessions(dir = defaultSessionsDir()): SessionRecord[] {
|
|
15
|
+
if (!existsSync(dir)) return [];
|
|
16
|
+
const out: SessionRecord[] = [];
|
|
17
|
+
for (const name of readdirSync(dir)) {
|
|
18
|
+
if (!name.endsWith('.json')) continue;
|
|
19
|
+
try {
|
|
20
|
+
const rec: unknown = JSON.parse(readFileSync(join(dir, name), 'utf8'));
|
|
21
|
+
if (isSessionRecord(rec)) out.push(rec);
|
|
22
|
+
} catch {
|
|
23
|
+
// Skip it: the hook rewrites it on the next event.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ReapOptions {
|
|
30
|
+
/** An `active` session silent for longer than this is dead. */
|
|
31
|
+
zombieMs: number;
|
|
32
|
+
/** Any session silent for longer than this is dead, whatever its state. */
|
|
33
|
+
staleMs: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Drops dead sessions **and deletes their files**. `SessionEnd` does not
|
|
38
|
+
* arrive when a terminal is killed or the machine sleeps; without this, those
|
|
39
|
+
* records would stay forever. Deleting is safe: if the session is alive after
|
|
40
|
+
* all, its next event writes the file again. Returns the live ones.
|
|
41
|
+
*/
|
|
42
|
+
export function reap<T extends SessionRecord>(records: T[], now: number, o: ReapOptions, dir = defaultSessionsDir(), onReap: (r: T) => void = () => {}): T[] {
|
|
43
|
+
const alive = pruneZombies(records, now, o.zombieMs, o.staleMs);
|
|
44
|
+
if (alive.length === records.length) return alive;
|
|
45
|
+
const keep = new Set(alive.map((r) => r.session_id));
|
|
46
|
+
for (const r of records) {
|
|
47
|
+
if (keep.has(r.session_id)) continue;
|
|
48
|
+
try {
|
|
49
|
+
rmSync(sessionFile(dir, r.session_id), { force: true });
|
|
50
|
+
onReap(r);
|
|
51
|
+
} catch {
|
|
52
|
+
// Filtering it out is enough to show the right thing.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return alive;
|
|
56
|
+
}
|