@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/dist/paths.js ADDED
@@ -0,0 +1,14 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * Where session files live: `$AGENT_SESSIONS_DIR`, or `sessions/` inside
5
+ * `$AIMONITOR_DIR` (default `~/.aimonitor`), where the first client of this
6
+ * protocol has always kept them.
7
+ */
8
+ export function defaultSessionsDir(env = process.env) {
9
+ return env.AGENT_SESSIONS_DIR ?? join(env.AIMONITOR_DIR ?? join(homedir(), '.aimonitor'), 'sessions');
10
+ }
11
+ /** The file of one session. */
12
+ export function sessionFile(dir, sessionId) {
13
+ return join(dir, `${sessionId}.json`);
14
+ }
@@ -0,0 +1,68 @@
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
+ /** Version of the record format. Bumped on any incompatible change. */
8
+ export declare const SCHEMA_VERSION = 1;
9
+ /** The CLIs this package knows how to read events from (see providers.ts). */
10
+ export type KnownProvider = 'claude' | 'gemini';
11
+ /** A provider name; known ones get their event names translated. */
12
+ export type Provider = KnownProvider | (string & {});
13
+ /**
14
+ * What the session needs from you, from most to least urgent:
15
+ *
16
+ * - `permission`: blocked on a permission prompt;
17
+ * - `waiting`: idle, waiting for your input;
18
+ * - `ready`: finished its turn;
19
+ * - `active`: working;
20
+ * - `idle`: just started (or resumed), nothing asked yet.
21
+ */
22
+ export type SessionState = 'permission' | 'waiting' | 'ready' | 'active' | 'idle';
23
+ export declare const SESSION_STATES: readonly SessionState[];
24
+ /** Higher = more urgent. Decides which session leads. */
25
+ export declare const STATE_PRIORITY: Readonly<Record<SessionState, number>>;
26
+ /** States in which the session is asking for the operator. */
27
+ export declare const CLAIMS: ReadonlySet<SessionState>;
28
+ /** Consecutive talk-only turns (no tools) that set `duck`. */
29
+ export declare const TALKS_TO_DUCK = 2;
30
+ /** One session, as the hook writes it to `<sessions dir>/<session_id>.json`. */
31
+ export interface SessionRecord {
32
+ schemaVersion: typeof SCHEMA_VERSION;
33
+ session_id: string;
34
+ provider: Provider;
35
+ state: SessionState;
36
+ /** Tool call or message, secrets redacted, at most 240 characters. */
37
+ detail: string;
38
+ /** Basename of `cwd`. */
39
+ project: string;
40
+ /** Full working directory of the session. */
41
+ cwd?: string;
42
+ /** When it entered the current state, ms epoch. Kept while the state does not change. */
43
+ since: number;
44
+ /** When the session started, ms epoch. */
45
+ started?: number;
46
+ /** Last write, ms epoch. */
47
+ updated: number;
48
+ /** Name of the hook event that produced the record. */
49
+ event: string;
50
+ /** Files the session edited or wrote, absolute, most recent first (at most 20). */
51
+ files?: string[];
52
+ /** The last shell command failed. */
53
+ lastFailed?: boolean;
54
+ /** Consecutive failed shell commands. */
55
+ failStreak?: number;
56
+ /** Consecutive turns with talk only, no tools. */
57
+ talkStreak?: number;
58
+ /** `talkStreak` reached `TALKS_TO_DUCK` at some point in this session. */
59
+ duck?: boolean;
60
+ /** Last context compaction (PreCompact), ms epoch. */
61
+ compactAt?: number;
62
+ /** TODO/FIXME added during the session. */
63
+ todos?: number;
64
+ /** The last test run of the session failed (see testsignal.ts). */
65
+ testsFailed?: boolean;
66
+ }
67
+ /** Does `x` look like a record of this schema version? Checks the fields clients rely on. */
68
+ export declare function isSessionRecord(x: unknown): x is SessionRecord;
@@ -0,0 +1,36 @@
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
+ /** Version of the record format. Bumped on any incompatible change. */
8
+ export const SCHEMA_VERSION = 1;
9
+ export const SESSION_STATES = ['permission', 'waiting', 'ready', 'active', 'idle'];
10
+ /** Higher = more urgent. Decides which session leads. */
11
+ export const STATE_PRIORITY = {
12
+ permission: 4,
13
+ waiting: 3,
14
+ ready: 2,
15
+ active: 1,
16
+ idle: 0,
17
+ };
18
+ /** States in which the session is asking for the operator. */
19
+ export const CLAIMS = new Set(['permission', 'waiting', 'ready']);
20
+ /** Consecutive talk-only turns (no tools) that set `duck`. */
21
+ export const TALKS_TO_DUCK = 2;
22
+ /** Does `x` look like a record of this schema version? Checks the fields clients rely on. */
23
+ export function isSessionRecord(x) {
24
+ if (typeof x !== 'object' || x === null)
25
+ return false;
26
+ const r = x;
27
+ return (r.schemaVersion === SCHEMA_VERSION &&
28
+ typeof r.session_id === 'string' &&
29
+ typeof r.provider === 'string' &&
30
+ SESSION_STATES.includes(r.state) &&
31
+ typeof r.detail === 'string' &&
32
+ typeof r.project === 'string' &&
33
+ typeof r.since === 'number' &&
34
+ typeof r.updated === 'number' &&
35
+ typeof r.event === 'string');
36
+ }
@@ -0,0 +1,36 @@
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
+ export interface HookEvent {
13
+ /** Canonical event name ('' if absent). */
14
+ event: string;
15
+ sessionId: string;
16
+ cwd: string;
17
+ tool: string;
18
+ toolInput: unknown;
19
+ toolResponse: unknown;
20
+ /** Why a session started: startup, resume, compact, clear… */
21
+ source: string;
22
+ /** Notification kind or message. */
23
+ notification: string;
24
+ prompt: string;
25
+ /** The assistant's last message, on Stop. */
26
+ lastMessage: string;
27
+ /** Free text for events this package does not know. */
28
+ fallback: string;
29
+ }
30
+ export interface ProviderAdapter {
31
+ name: string;
32
+ normalize(data: Record<string, any>, cwd: string): HookEvent;
33
+ }
34
+ export declare const PROVIDERS: Readonly<Record<KnownProvider, ProviderAdapter>>;
35
+ /** The adapter for a provider name; unknown names read the generic field names. */
36
+ export declare function adapterFor(name: string): ProviderAdapter;
@@ -0,0 +1,32 @@
1
+ /** Event names that differ from Claude Code's, per provider. */
2
+ const ALIASES = {};
3
+ /**
4
+ * The field names Claude Code uses, with the alternatives Gemini CLI and
5
+ * hand-written scripts have been seen to send.
6
+ */
7
+ function generic(provider) {
8
+ return (data, cwd) => {
9
+ const raw = data.hook_event_name || data.event || data.type || '';
10
+ return {
11
+ event: ALIASES[provider]?.[raw] ?? raw,
12
+ sessionId: data.session_id || data.sessionId || 'global',
13
+ cwd: data.cwd || cwd,
14
+ tool: String(data.tool_name ?? data.tool?.name ?? data.tool ?? ''),
15
+ toolInput: data.tool_input ?? data.tool?.arguments,
16
+ toolResponse: data.tool_response,
17
+ source: String(data.source ?? data.session_start_type ?? ''),
18
+ notification: String(data.notification_type ?? data.notificationType ?? data.message ?? ''),
19
+ prompt: String(data.prompt ?? ''),
20
+ lastMessage: String(data.last_assistant_message ?? ''),
21
+ fallback: String(data.detail ?? data.message ?? data.command ?? ''),
22
+ };
23
+ };
24
+ }
25
+ export const PROVIDERS = {
26
+ claude: { name: 'claude', normalize: generic('claude') },
27
+ gemini: { name: 'gemini', normalize: generic('gemini') },
28
+ };
29
+ /** The adapter for a provider name; unknown names read the generic field names. */
30
+ export function adapterFor(name) {
31
+ return PROVIDERS[name] ?? { name, normalize: generic(name) };
32
+ }
@@ -0,0 +1,19 @@
1
+ import { type SessionRecord } from './protocol.ts';
2
+ /**
3
+ * Every valid record in the directory. Files that are half-written,
4
+ * unreadable or of another schema version are skipped, never thrown.
5
+ */
6
+ export declare function readSessions(dir?: string): SessionRecord[];
7
+ export interface ReapOptions {
8
+ /** An `active` session silent for longer than this is dead. */
9
+ zombieMs: number;
10
+ /** Any session silent for longer than this is dead, whatever its state. */
11
+ staleMs: number;
12
+ }
13
+ /**
14
+ * Drops dead sessions **and deletes their files**. `SessionEnd` does not
15
+ * arrive when a terminal is killed or the machine sleeps; without this, those
16
+ * records would stay forever. Deleting is safe: if the session is alive after
17
+ * all, its next event writes the file again. Returns the live ones.
18
+ */
19
+ export declare function reap<T extends SessionRecord>(records: T[], now: number, o: ReapOptions, dir?: string, onReap?: (r: T) => void): T[];
package/dist/reader.js ADDED
@@ -0,0 +1,54 @@
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.js";
7
+ import { isSessionRecord } from "./protocol.js";
8
+ import { pruneZombies } from "./select.js";
9
+ /**
10
+ * Every valid record in the directory. Files that are half-written,
11
+ * unreadable or of another schema version are skipped, never thrown.
12
+ */
13
+ export function readSessions(dir = defaultSessionsDir()) {
14
+ if (!existsSync(dir))
15
+ return [];
16
+ const out = [];
17
+ for (const name of readdirSync(dir)) {
18
+ if (!name.endsWith('.json'))
19
+ continue;
20
+ try {
21
+ const rec = JSON.parse(readFileSync(join(dir, name), 'utf8'));
22
+ if (isSessionRecord(rec))
23
+ out.push(rec);
24
+ }
25
+ catch {
26
+ // Skip it: the hook rewrites it on the next event.
27
+ }
28
+ }
29
+ return out;
30
+ }
31
+ /**
32
+ * Drops dead sessions **and deletes their files**. `SessionEnd` does not
33
+ * arrive when a terminal is killed or the machine sleeps; without this, those
34
+ * records would stay forever. Deleting is safe: if the session is alive after
35
+ * all, its next event writes the file again. Returns the live ones.
36
+ */
37
+ export function reap(records, now, o, dir = defaultSessionsDir(), onReap = () => { }) {
38
+ const alive = pruneZombies(records, now, o.zombieMs, o.staleMs);
39
+ if (alive.length === records.length)
40
+ return alive;
41
+ const keep = new Set(alive.map((r) => r.session_id));
42
+ for (const r of records) {
43
+ if (keep.has(r.session_id))
44
+ continue;
45
+ try {
46
+ rmSync(sessionFile(dir, r.session_id), { force: true });
47
+ onReap(r);
48
+ }
49
+ catch {
50
+ // Filtering it out is enough to show the right thing.
51
+ }
52
+ }
53
+ return alive;
54
+ }
@@ -0,0 +1 @@
1
+ export declare function redact(text: string): string;
package/dist/redact.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Secrets that must not end up on a screen.
3
+ *
4
+ * `detail` carries the command as typed, and the screen may be a panel anyone
5
+ * walking by can read: a `curl` with a published calendar URL, a variable with
6
+ * a token or an `Authorization:` header would be shown in full. The record is
7
+ * also stored on disk, so the secret would outlive the command.
8
+ *
9
+ * The list is deliberately short and specific: hiding too much turns messages
10
+ * into noise and defeats the point, which is reading at a glance what each
11
+ * session is doing.
12
+ */
13
+ const SECRETS = [
14
+ // Secret Google Calendar addresses and the like.
15
+ [/private-[0-9a-f]{16,}/gi, 'private-<hidden>'],
16
+ // Credentials inside a URL.
17
+ [/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, '$1<hidden>@'],
18
+ // Headers and parameters with a telling name. `Authorization` consumes two
19
+ // words: with a single `\S+` it hid "Bearer" and left the token in sight,
20
+ // which is exactly the mistake this must not make.
21
+ [/\b(authorization)\s*:\s*(?:\S+[ \t]+)?\S+/gi, '$1: <hidden>'],
22
+ [/\bbearer[ \t]+\S+/gi, 'Bearer <hidden>'],
23
+ [/\b(api[-_]?key|access[-_]?token|token|secret|password|passwd|pwd)\b(\s*[=:]\s*)\S+/gi, '$1$2<hidden>'],
24
+ // Token formats recognisable at a glance.
25
+ [/\b(gh[pousr]_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g, '<hidden>'],
26
+ ];
27
+ export function redact(text) {
28
+ return SECRETS.reduce((acc, [re, to]) => acc.replace(re, to), text);
29
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Generic choices any client makes over a set of sessions.
3
+ */
4
+ import { type SessionRecord } from './protocol.ts';
5
+ type Timed = Pick<SessionRecord, 'state' | 'since' | 'updated'>;
6
+ /** Is this session asking for the operator? */
7
+ export declare function claims(r: Pick<SessionRecord, 'state'>): boolean;
8
+ /**
9
+ * Drops sessions that no longer exist. There are two deadlines because the
10
+ * signals differ: an `active` session says it is working, so a silent one is
11
+ * dead soon; the others legitimately wait for the operator and deserve much
12
+ * more slack, but not eternity.
13
+ */
14
+ export declare function pruneZombies<T extends Timed>(records: T[], now: number, zombieMs: number, staleMs: number): T[];
15
+ /**
16
+ * Display order: first the ones asking for you, by state priority and, within
17
+ * a state, the one waiting longest. Then the rest, most recent activity first.
18
+ */
19
+ export declare function order<T extends Timed>(records: T[]): T[];
20
+ export {};
package/dist/select.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Generic choices any client makes over a set of sessions.
3
+ */
4
+ import { CLAIMS, STATE_PRIORITY } from "./protocol.js";
5
+ /** Is this session asking for the operator? */
6
+ export function claims(r) {
7
+ return CLAIMS.has(r.state);
8
+ }
9
+ /**
10
+ * Drops sessions that no longer exist. There are two deadlines because the
11
+ * signals differ: an `active` session says it is working, so a silent one is
12
+ * dead soon; the others legitimately wait for the operator and deserve much
13
+ * more slack, but not eternity.
14
+ */
15
+ export function pruneZombies(records, now, zombieMs, staleMs) {
16
+ return records.filter((r) => now - r.updated <= (r.state === 'active' ? zombieMs : staleMs));
17
+ }
18
+ /**
19
+ * Display order: first the ones asking for you, by state priority and, within
20
+ * a state, the one waiting longest. Then the rest, most recent activity first.
21
+ */
22
+ export function order(records) {
23
+ return [...records].sort((a, b) => {
24
+ const ca = claims(a) ? 1 : 0;
25
+ const cb = claims(b) ? 1 : 0;
26
+ if (ca !== cb)
27
+ return cb - ca;
28
+ const pa = STATE_PRIORITY[a.state];
29
+ const pb = STATE_PRIORITY[b.state];
30
+ if (pa !== pb)
31
+ return pb - pa;
32
+ if (ca === 1)
33
+ return a.since - b.since;
34
+ return b.updated - a.updated;
35
+ });
36
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Did the tests fail? The hook checks after every shell command that looks
3
+ * like a test run, reading its output. Pure and cheap: it is on the path of
4
+ * every tool call.
5
+ *
6
+ * It is a heuristic over text, not a verdict: when unclear it says nothing
7
+ * (null) and the previous value is kept.
8
+ */
9
+ export declare const TEST_COMMAND: RegExp;
10
+ /** 'fail', 'ok', or null if this was not a test run or the output is unclear. */
11
+ export declare function testOutcome(event: string, tool: string, input: unknown, response: unknown): 'fail' | 'ok' | null;
12
+ /**
13
+ * Did the last shell command fail? Claude Code reports non-zero exits with the
14
+ * `PostToolUseFailure` event (it has to be in the hooks); Gemini and others
15
+ * carry the exit code in the response. A rebase with conflicts is also
16
+ * recognised by its text. null = it was not a shell command.
17
+ */
18
+ export declare function commandFailed(event: string, tool: string, input: unknown, response: unknown): boolean | null;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Did the tests fail? The hook checks after every shell command that looks
3
+ * like a test run, reading its output. Pure and cheap: it is on the path of
4
+ * every tool call.
5
+ *
6
+ * It is a heuristic over text, not a verdict: when unclear it says nothing
7
+ * (null) and the previous value is kept.
8
+ */
9
+ export const TEST_COMMAND = /\b(npm (run )?test|pnpm test|yarn test|pytest|vitest|jest|cargo test|go test|node --test|mvn test|gradle test|phpunit|rspec)\b/;
10
+ const FAIL = [
11
+ /\b[1-9]\d* (failed|failing|failures?|errors?)\b/i,
12
+ /^ℹ fail [1-9]/m,
13
+ /^not ok\b/m,
14
+ /\bFAIL(ED)?\b/,
15
+ /\bTests?:\s+[1-9]\d* failed/i,
16
+ /^✖ /m,
17
+ ];
18
+ const OK = [/\b0 failed\b/i, /^ℹ fail 0\b/m, /\b\d+ passed\b/i, /\ball tests passed\b/i, /\bOK \(\d+ tests?\)/, /\btest result: ok\b/];
19
+ function text(response) {
20
+ if (typeof response === 'string')
21
+ return response;
22
+ if (response && typeof response === 'object') {
23
+ const o = response;
24
+ return [o.stdout, o.stderr, o.output, o.result].filter((v) => typeof v === 'string').join('\n') || JSON.stringify(response).slice(0, 50_000);
25
+ }
26
+ return '';
27
+ }
28
+ /** 'fail', 'ok', or null if this was not a test run or the output is unclear. */
29
+ export function testOutcome(event, tool, input, response) {
30
+ if (event !== 'PostToolUse' || !/^(Bash|run_shell_command)$/.test(tool))
31
+ return null;
32
+ const cmd = input && typeof input === 'object' ? String(input.command ?? '') : '';
33
+ if (!TEST_COMMAND.test(cmd))
34
+ return null;
35
+ const r = response && typeof response === 'object' ? response : {};
36
+ const code = [r.exit_code, r.exitCode, r.returnCode, r.code].find((v) => typeof v === 'number');
37
+ if (code !== undefined)
38
+ return code === 0 ? 'ok' : 'fail';
39
+ const out = text(response).slice(-50_000);
40
+ if (!out)
41
+ return null;
42
+ // "0 failed" wins over a stray FAIL inside a test name.
43
+ if (OK.some((re) => re.test(out)) && !/\b[1-9]\d* failed\b/i.test(out) && !/^ℹ fail [1-9]/m.test(out))
44
+ return 'ok';
45
+ if (FAIL.some((re) => re.test(out)))
46
+ return 'fail';
47
+ return null;
48
+ }
49
+ /**
50
+ * Did the last shell command fail? Claude Code reports non-zero exits with the
51
+ * `PostToolUseFailure` event (it has to be in the hooks); Gemini and others
52
+ * carry the exit code in the response. A rebase with conflicts is also
53
+ * recognised by its text. null = it was not a shell command.
54
+ */
55
+ export function commandFailed(event, tool, input, response) {
56
+ if (!/^(Bash|run_shell_command)$/.test(tool))
57
+ return null;
58
+ if (event === 'PostToolUseFailure')
59
+ return true;
60
+ if (event !== 'PostToolUse')
61
+ return null;
62
+ const r = response && typeof response === 'object' ? response : {};
63
+ const code = [r.exit_code, r.exitCode, r.returnCode, r.code].find((v) => typeof v === 'number');
64
+ if (code !== undefined)
65
+ return code !== 0;
66
+ const cmd = input && typeof input === 'object' ? String(input.command ?? '') : '';
67
+ if (/\bgit\s+rebase\b/.test(cmd) && /\b(CONFLICT|could not apply|error: )/.test(text(response).slice(-20_000)))
68
+ return true;
69
+ return false;
70
+ }
@@ -0,0 +1,8 @@
1
+ /** Cap of the list: enough to spot recent clashes without bloating the JSON. */
2
+ export declare const MAX_FILES = 20;
3
+ /**
4
+ * The list after this event, or the previous one unchanged. Emptied when a
5
+ * session starts: a new session has touched nothing yet, and inheriting the
6
+ * previous list would report phantom clashes.
7
+ */
8
+ export declare function touchedFiles(prev: string[] | undefined, event: string, tool: string, input: unknown, cwd: string): string[] | undefined;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Files a session has touched, so that a client can tell when two sessions
3
+ * step on each other. Called by the hook on every event, so it is pure and
4
+ * cheap: no I/O, it only merges the event into the previous list.
5
+ */
6
+ import { isAbsolute, join } from 'node:path';
7
+ /** Cap of the list: enough to spot recent clashes without bloating the JSON. */
8
+ export const MAX_FILES = 20;
9
+ /** Tools that write, from Claude Code and Gemini CLI. */
10
+ const WRITERS = /^(edit|multiedit|write|notebookedit|write_file|replace|edit_file)$/i;
11
+ /**
12
+ * The list after this event, or the previous one unchanged. Emptied when a
13
+ * session starts: a new session has touched nothing yet, and inheriting the
14
+ * previous list would report phantom clashes.
15
+ */
16
+ export function touchedFiles(prev, event, tool, input, cwd) {
17
+ if (event === 'SessionStart')
18
+ return undefined;
19
+ if (event !== 'PreToolUse' && event !== 'PostToolUse')
20
+ return prev;
21
+ if (!WRITERS.test(tool))
22
+ return prev;
23
+ if (typeof input !== 'object' || input === null)
24
+ return prev;
25
+ const o = input;
26
+ const raw = [o.file_path, o.notebook_path, o.path].find((v) => typeof v === 'string' && v.length > 0);
27
+ if (!raw)
28
+ return prev;
29
+ const file = isAbsolute(raw) ? raw : join(cwd, raw);
30
+ return [file, ...(prev ?? []).filter((f) => f !== file)].slice(0, MAX_FILES);
31
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@loksly/agent-sessions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "A tiny file protocol for the state of AI coding sessions (Claude Code, Gemini CLI\u2026): a zero-dependency hook that writes it and helpers to read it.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Loksly",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Loksly/aimonitor.git",
11
+ "directory": "packages/agent-sessions"
12
+ },
13
+ "keywords": [
14
+ "claude-code",
15
+ "gemini-cli",
16
+ "hooks",
17
+ "ai-agents",
18
+ "status",
19
+ "dashboard"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./git": {
28
+ "source": "./src/git.ts",
29
+ "types": "./dist/git.d.ts",
30
+ "default": "./dist/git.js"
31
+ },
32
+ "./cli": {
33
+ "source": "./src/cli.ts",
34
+ "types": "./dist/cli.d.ts",
35
+ "default": "./dist/cli.js"
36
+ },
37
+ "./schema.json": "./schema/session-record.schema.json"
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "src",
42
+ "!src/**/*.test.ts",
43
+ "schema",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "engines": {
48
+ "node": ">=20"
49
+ },
50
+ "scripts": {
51
+ "build": "tsc -p tsconfig.json && chmod +x dist/cli.js",
52
+ "test": "node --conditions=source --import tsx --test 'src/**/*.test.ts'",
53
+ "check": "tsc -p tsconfig.json --noEmit"
54
+ },
55
+ "bin": {
56
+ "agent-sessions-hook": "./dist/cli.js"
57
+ }
58
+ }
@@ -0,0 +1,104 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/Loksly/aimonitor/packages/agent-sessions/schema/session-record.schema.json",
4
+ "title": "Agent session record",
5
+ "description": "One AI coding session, as written by the agent-sessions hook to <sessions dir>/<session_id>.json.",
6
+ "type": "object",
7
+ "required": [
8
+ "schemaVersion",
9
+ "session_id",
10
+ "provider",
11
+ "state",
12
+ "detail",
13
+ "project",
14
+ "since",
15
+ "updated",
16
+ "event"
17
+ ],
18
+ "properties": {
19
+ "schemaVersion": {
20
+ "const": 1
21
+ },
22
+ "session_id": {
23
+ "type": "string"
24
+ },
25
+ "provider": {
26
+ "type": "string",
27
+ "description": "claude, gemini, or another CLI name."
28
+ },
29
+ "state": {
30
+ "enum": [
31
+ "permission",
32
+ "waiting",
33
+ "ready",
34
+ "active",
35
+ "idle"
36
+ ],
37
+ "description": "From most to least urgent: blocked on a permission prompt, waiting for input, finished its turn, working, just started."
38
+ },
39
+ "detail": {
40
+ "type": "string",
41
+ "maxLength": 240,
42
+ "description": "Tool call or message, secrets redacted."
43
+ },
44
+ "project": {
45
+ "type": "string",
46
+ "description": "Basename of cwd."
47
+ },
48
+ "cwd": {
49
+ "type": "string"
50
+ },
51
+ "since": {
52
+ "type": "number",
53
+ "description": "When it entered the current state, ms epoch."
54
+ },
55
+ "started": {
56
+ "type": "number",
57
+ "description": "When the session started, ms epoch."
58
+ },
59
+ "updated": {
60
+ "type": "number",
61
+ "description": "Last write, ms epoch."
62
+ },
63
+ "event": {
64
+ "type": "string",
65
+ "description": "Hook event that produced the record."
66
+ },
67
+ "files": {
68
+ "type": "array",
69
+ "items": {
70
+ "type": "string"
71
+ },
72
+ "maxItems": 20,
73
+ "description": "Files edited or written, absolute, most recent first."
74
+ },
75
+ "lastFailed": {
76
+ "type": "boolean"
77
+ },
78
+ "failStreak": {
79
+ "type": "integer",
80
+ "minimum": 1
81
+ },
82
+ "talkStreak": {
83
+ "type": "integer",
84
+ "minimum": 1
85
+ },
86
+ "duck": {
87
+ "type": "boolean",
88
+ "description": "talkStreak reached 2 at some point in this session."
89
+ },
90
+ "compactAt": {
91
+ "type": "number",
92
+ "description": "Last context compaction, ms epoch."
93
+ },
94
+ "todos": {
95
+ "type": "integer",
96
+ "minimum": 1,
97
+ "description": "TODO/FIXME added during the session."
98
+ },
99
+ "testsFailed": {
100
+ "type": "boolean"
101
+ }
102
+ },
103
+ "additionalProperties": true
104
+ }