intent-prompt-graph 0.0.0-stage → 0.1.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/src/config.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ export const DEFAULT_PORT = 4761;
6
+ export const DEFAULT_IDLE_EXIT_MINUTES = 15;
7
+
8
+ export type LabelerProvider = "openai" | "claude-cli";
9
+
10
+ export interface LabelerConfig {
11
+ provider?: LabelerProvider;
12
+ baseUrl?: string;
13
+ model?: string;
14
+ apiKeyEnv?: string;
15
+ /** Optional binary/path override when provider is "claude-cli" (defaults to "claude"). */
16
+ command?: string;
17
+ }
18
+
19
+ /**
20
+ * Checks whether a labeler configuration has the required fields for its provider.
21
+ *
22
+ * Args:
23
+ * cfg (LabelerConfig | undefined): Labeler section from config.json.
24
+ *
25
+ * Returns:
26
+ * boolean: True when the configured provider has enough information to run.
27
+ */
28
+ export function isLabelerConfigured(cfg: LabelerConfig | undefined): boolean {
29
+ if (!cfg?.model) return false;
30
+ if (cfg.provider === "claude-cli") return true;
31
+ return Boolean(cfg.baseUrl);
32
+ }
33
+
34
+ export interface Config {
35
+ harnessText: RegExp[];
36
+ labeler?: LabelerConfig;
37
+ /** Loopback port of the daemon. */
38
+ port: number;
39
+ /** The daemon exits after this many minutes with no open SSE client. */
40
+ idleExitMinutes: number;
41
+ }
42
+
43
+ export function configFile(env: NodeJS.ProcessEnv = process.env): string {
44
+ const base = env.XDG_CONFIG_HOME || join(homedir(), ".config");
45
+ return join(base, "intent-prompt-graph", "config.json");
46
+ }
47
+
48
+ /** Missing file → defaults. Invalid JSON, non-array, non-string entries, or bad regex throw. */
49
+ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
50
+ let raw: string;
51
+ try {
52
+ raw = readFileSync(configFile(env), "utf8");
53
+ } catch (err) {
54
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
55
+ return { harnessText: [], port: DEFAULT_PORT, idleExitMinutes: DEFAULT_IDLE_EXIT_MINUTES };
56
+ }
57
+ throw err;
58
+ }
59
+ const json: unknown = JSON.parse(raw);
60
+ const list = field(json, "harnessText") ?? [];
61
+ if (!Array.isArray(list) || list.some((p) => typeof p !== "string")) {
62
+ throw new Error("config.harnessText must be an array of regex strings");
63
+ }
64
+ const labelerValue = field(json, "labeler");
65
+ const labeler = labelerValue === undefined ? undefined : parseLabeler(labelerValue);
66
+ return {
67
+ harnessText: list.map((p) => new RegExp(p)),
68
+ labeler,
69
+ port: parsePort(field(json, "port")),
70
+ idleExitMinutes: parseIdleExitMinutes(field(json, "idleExitMinutes")),
71
+ };
72
+ }
73
+
74
+ /** Reads one property of a JSON value; anything that is not an object has no fields. */
75
+ function field(value: unknown, key: string): unknown {
76
+ return typeof value === "object" && value !== null ? Reflect.get(value, key) : undefined;
77
+ }
78
+
79
+ function parsePort(value: unknown): number {
80
+ if (value === undefined) return DEFAULT_PORT;
81
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535) {
82
+ throw new Error("config.port must be an integer from 1 to 65535");
83
+ }
84
+ return value;
85
+ }
86
+
87
+ function parseIdleExitMinutes(value: unknown): number {
88
+ if (value === undefined) return DEFAULT_IDLE_EXIT_MINUTES;
89
+ if (typeof value !== "number" || !(value > 0)) {
90
+ throw new Error("config.idleExitMinutes must be a positive number");
91
+ }
92
+ return value;
93
+ }
94
+
95
+ function parseLabeler(value: unknown): LabelerConfig {
96
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
97
+ throw new Error("config.labeler must be an object");
98
+ }
99
+ const out: LabelerConfig = {};
100
+ const provider = field(value, "provider");
101
+ if (provider !== undefined) {
102
+ if (provider !== "openai" && provider !== "claude-cli") {
103
+ throw new Error('config.labeler.provider must be "openai" or "claude-cli"');
104
+ }
105
+ out.provider = provider;
106
+ }
107
+ for (const key of ["baseUrl", "model", "apiKeyEnv", "command"] as const) {
108
+ const v = field(value, key);
109
+ if (v === undefined) continue;
110
+ if (typeof v !== "string") throw new Error(`config.labeler.${key} must be a string`);
111
+ out[key] = v;
112
+ }
113
+ return out;
114
+ }
package/src/export.ts ADDED
@@ -0,0 +1,71 @@
1
+ import type { GraphNode, NodeKind, SessionGraph } from "./model";
2
+
3
+ export interface DecisionLogOptions {
4
+ /** "rejected" returns only the block meant to be pasted into an agent prompt. */
5
+ only?: "rejected";
6
+ }
7
+
8
+ const REJECTED_LEAD = "Already rejected in this session; do not propose again:";
9
+
10
+ /** Collapses every whitespace run (newlines included) so the text stays on one markdown line. */
11
+ function oneLine(text: string): string {
12
+ return text.replace(/\s+/g, " ").trim();
13
+ }
14
+
15
+ /** `**title** — detail`, or just the bold title when there is no detail. */
16
+ function entry(title: string, detail: string, mark = ""): string {
17
+ const head = `**${oneLine(title)}**${mark}`;
18
+ const tail = oneLine(detail);
19
+ return tail ? `${head} — ${tail}` : head;
20
+ }
21
+
22
+ function bullet(node: GraphNode, mark = ""): string {
23
+ return `- ${entry(node.title, node.rationale || node.desc, mark)}`;
24
+ }
25
+
26
+ /**
27
+ * Renders a session graph as a markdown decision log: goal, chosen and rejected paths,
28
+ * decisions and loops. Sections follow `graph.nodes` order and are omitted when empty.
29
+ * `side` nodes are not part of the log.
30
+ *
31
+ * Args:
32
+ * graph (SessionGraph): The LLM or heuristic graph of one session.
33
+ * opts (DecisionLogOptions | undefined): `only: "rejected"` returns just a lead line plus one
34
+ * bullet per `rejected` node, to paste into an agent prompt.
35
+ *
36
+ * Returns:
37
+ * string: Markdown ending in a newline. Empty when `only: "rejected"` finds nothing rejected.
38
+ */
39
+ export function renderDecisionLog(graph: SessionGraph, opts: DecisionLogOptions = {}): string {
40
+ const byKind = (...kinds: NodeKind[]) => graph.nodes.filter((n) => kinds.includes(n.kind));
41
+
42
+ if (opts.only === "rejected") {
43
+ const rejected = byKind("rejected");
44
+ if (rejected.length === 0) return "";
45
+ return `${[REJECTED_LEAD, ...rejected.map((n) => bullet(n))].join("\n")}\n`;
46
+ }
47
+
48
+ const blocks: string[] = [`# ${oneLine(graph.title)}`];
49
+ const section = (heading: string, lines: string[]) => {
50
+ if (lines.length > 0) blocks.push(`## ${heading}\n${lines.join("\n")}`);
51
+ };
52
+
53
+ const goals = byKind("goal");
54
+ // A lone goal reads as a sentence; several goals become a list so they stay apart.
55
+ section(
56
+ "Goal",
57
+ goals.map((n) => (goals.length === 1 ? entry(n.title, n.desc) : `- ${entry(n.title, n.desc)}`)),
58
+ );
59
+ section("Chosen", byKind("chosen").map((n) => bullet(n)));
60
+ section(
61
+ "Rejected",
62
+ byKind("rejected", "option").map((n) => bullet(n, n.kind === "option" ? " (not chosen)" : "")),
63
+ );
64
+ section("Decisions", byKind("decision").map((n) => bullet(n)));
65
+ section(
66
+ "Loops",
67
+ byKind("loop").map((n) => `- ${oneLine(n.title)}${n.rounds === undefined ? "" : ` × ${n.rounds}`}`),
68
+ );
69
+ blocks.push(`Source: ${graph.mode === "llm" ? "LLM graph" : "heuristic outline (no labeler)"}`);
70
+ return `${blocks.join("\n\n")}\n`;
71
+ }
@@ -0,0 +1,349 @@
1
+ import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, join } from "node:path";
4
+ import type { Config } from "../config";
5
+ import type { Action, Trigger, Turn } from "../model";
6
+ import type { Harness, Reader, SessionRef } from "./harness";
7
+
8
+ const HARNESS_TEXT_MAX = 400;
9
+ const TEXT_MAX = 20_000;
10
+ const SUMMARY_MAX = 120;
11
+ const CHUNK = 1 << 20;
12
+ /** A session id is a UUID; it is also the file name, so nothing else may pass. */
13
+ const KEY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+ /** Claude Code cuts a project directory name at this length and appends a hash. */
15
+ const PROJECT_NAME_MAX = 200;
16
+ /**
17
+ * Text Claude Code wrote into the user channel itself: it starts with a lowercase tag such as
18
+ * <command-name>, <local-command-stdout>, <system-reminder>, <bash-input> or <task-notification>.
19
+ * Same test as Claude Code's own "is this a real prompt" check.
20
+ */
21
+ const WRAPPER_RE = /^\s*<[a-z][\w-]*[\s>]/;
22
+ /** Marker Claude Code writes when the owner pressed Esc. */
23
+ const INTERRUPT_RE = /^\[Request interrupted by user[^\]]*\]/;
24
+
25
+ function claudeDir(): string {
26
+ return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
27
+ }
28
+
29
+ function projectsDir(): string {
30
+ return join(claudeDir(), "projects");
31
+ }
32
+
33
+ function isObj(v: unknown): v is Record<string, unknown> {
34
+ return typeof v === "object" && v !== null;
35
+ }
36
+
37
+ function parseObj(text: string): Record<string, unknown> | undefined {
38
+ try {
39
+ const v: unknown = JSON.parse(text);
40
+ return isObj(v) ? v : undefined;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ function newest(files: string[]): string | undefined {
47
+ let best: { file: string; mtime: number } | undefined;
48
+ for (const file of files) {
49
+ const mtime = statSync(file).mtimeMs;
50
+ if (!best || mtime > best.mtime) best = { file, mtime };
51
+ }
52
+ return best?.file;
53
+ }
54
+
55
+ /** Session files matching a glob under the projects dir (one level: subagent files lie deeper). */
56
+ function sessionFiles(pattern: string): string[] {
57
+ if (!existsSync(projectsDir())) return [];
58
+ return [...new Bun.Glob(pattern).scanSync({ cwd: projectsDir(), absolute: true })];
59
+ }
60
+
61
+ /** Calls fn with every complete line of the file, read in 1 MiB chunks. */
62
+ function eachLine(file: string, fn: (line: Buffer) => void): void {
63
+ const fd = openSync(file, "r");
64
+ try {
65
+ const buf = Buffer.allocUnsafe(CHUNK);
66
+ let carry: Buffer | undefined;
67
+ for (let n = readSync(fd, buf, 0, CHUNK, null); n > 0; n = readSync(fd, buf, 0, CHUNK, null)) {
68
+ const view = buf.subarray(0, n);
69
+ let start = 0;
70
+ for (let nl = view.indexOf(0x0a); nl !== -1; nl = view.indexOf(0x0a, start)) {
71
+ const part = view.subarray(start, nl);
72
+ fn(carry ? Buffer.concat([carry, part]) : part);
73
+ carry = undefined;
74
+ start = nl + 1;
75
+ }
76
+ // `buf` is reused by the next read, so the unfinished line is copied out.
77
+ if (start < n) carry = Buffer.concat(carry ? [carry, view.subarray(start)] : [view.subarray(start)]);
78
+ }
79
+ } finally {
80
+ closeSync(fd);
81
+ }
82
+ }
83
+
84
+ interface Head {
85
+ sessionId?: string;
86
+ cwd?: string;
87
+ title?: string;
88
+ }
89
+
90
+ /**
91
+ * Reads the working directory from the first record that carries one, and the title from the
92
+ * title records. Claude Code appends its title records again after later writes, so the whole
93
+ * file is scanned, but only lines that can hold a title are parsed.
94
+ */
95
+ function headOf(file: string): Head {
96
+ const head: Head = {};
97
+ let custom: string | undefined;
98
+ let ai: string | undefined;
99
+ let summary: string | undefined;
100
+ eachLine(file, (line) => {
101
+ const needCwd = head.cwd === undefined;
102
+ if (!needCwd && !line.includes('-title"') && !line.includes('"type":"summary"')) return;
103
+ const obj = parseObj(line.toString("utf8"));
104
+ if (!obj) return;
105
+ if (needCwd && typeof obj.cwd === "string") {
106
+ head.cwd = obj.cwd;
107
+ if (typeof obj.sessionId === "string") head.sessionId = obj.sessionId;
108
+ }
109
+ if (obj.type === "custom-title" && typeof obj.customTitle === "string") custom = obj.customTitle;
110
+ else if (obj.type === "ai-title" && typeof obj.aiTitle === "string") ai = obj.aiTitle;
111
+ else if (obj.type === "summary" && typeof obj.summary === "string") summary = obj.summary;
112
+ });
113
+ // The owner's own title wins over the generated one, as in Claude Code's session list.
114
+ head.title = custom || ai || summary || undefined;
115
+ return head;
116
+ }
117
+
118
+ function refOf(file: string): SessionRef {
119
+ const head = headOf(file);
120
+ const name = basename(file, ".jsonl");
121
+ // The file name is the session id; a renamed copy still carries the id in its records.
122
+ const key = KEY_RE.test(name) ? name : head.sessionId;
123
+ if (!head.cwd || !key || !KEY_RE.test(key)) throw new Error(`no Claude Code session records in ${file}`);
124
+ return { harness: "claude", key, file, cwd: head.cwd, title: head.title };
125
+ }
126
+
127
+ /** Parent pid: field 4 of /proc/<pid>/stat on Linux, `ps -o ppid=` where there is no /proc. */
128
+ function parentPid(pid: number): number | undefined {
129
+ let field: string | undefined;
130
+ try {
131
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
132
+ // Field 2 (the command name) may hold spaces and parentheses; the rest follows its last ")".
133
+ field = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1];
134
+ } catch {
135
+ try {
136
+ field = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]).stdout.toString().trim();
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ const ppid = Number(field);
142
+ return field && Number.isInteger(ppid) ? ppid : undefined;
143
+ }
144
+
145
+ /** The pids above this process, nearest first, up to but not including pid 1. */
146
+ function ancestorPids(): number[] {
147
+ const pids: number[] = [];
148
+ for (let pid: number | undefined = process.ppid; pid !== undefined && pid > 1 && pids.length < 64; pid = parentPid(pid)) {
149
+ pids.push(pid);
150
+ }
151
+ return pids;
152
+ }
153
+
154
+ /** Project directory name of a working directory, as a glob (long names end in a hash). */
155
+ function projectGlob(cwd: string): string {
156
+ const name = cwd.replace(/[^a-zA-Z0-9]/g, "-");
157
+ return name.length <= PROJECT_NAME_MAX ? name : `${name.slice(0, PROJECT_NAME_MAX)}-*`;
158
+ }
159
+
160
+ async function locate(opts: { sessionFile?: string; tty?: string; cwd: string }): Promise<SessionRef> {
161
+ if (opts.sessionFile) return refOf(opts.sessionFile);
162
+ const looked: string[] = [];
163
+ // Claude Code runs commands as its own children, so the session that started us is an ancestor.
164
+ // Each running Claude Code process registers its session id under sessions/<pid>.json.
165
+ const sessions = join(claudeDir(), "sessions");
166
+ const pids = ancestorPids();
167
+ looked.push(`${join(sessions, "<pid>.json")} for ancestor pids ${pids.join(", ")}`);
168
+ for (const pid of pids) {
169
+ const registered = join(sessions, `${pid}.json`);
170
+ if (!existsSync(registered)) continue;
171
+ const id = parseObj(readFileSync(registered, "utf8"))?.sessionId;
172
+ if (typeof id !== "string" || !KEY_RE.test(id)) continue;
173
+ const file = newest(sessionFiles(`*/${id}.jsonl`));
174
+ if (file) return refOf(file);
175
+ // Falling back to another session of this directory would show the wrong conversation.
176
+ throw new Error(
177
+ `Claude Code session ${id} (pid ${pid}) has no transcript yet (send a first message); looked for ${join(projectsDir(), "*", `${id}.jsonl`)}`,
178
+ );
179
+ }
180
+ const glob = projectGlob(opts.cwd);
181
+ looked.push(`newest session under ${join(projectsDir(), glob)}`);
182
+ const file = newest(sessionFiles(`${glob}/*.jsonl`));
183
+ if (file) return refOf(file);
184
+ throw new Error(`no Claude Code session found; looked at: ${looked.join("; ")}`);
185
+ }
186
+
187
+ async function resolve(key: string): Promise<SessionRef> {
188
+ if (!KEY_RE.test(key)) throw new Error(`invalid Claude Code session key: ${key}`);
189
+ const file = newest(sessionFiles(`*/${key}.jsonl`));
190
+ if (!file) throw new Error(`no Claude Code session with key ${key} under ${projectsDir()}`);
191
+ return refOf(file);
192
+ }
193
+
194
+ /** Text of each block of user content: a string is one block; images show as [image]. */
195
+ function textBlocks(content: unknown): string[] {
196
+ if (typeof content === "string") return [content];
197
+ if (!Array.isArray(content)) return [];
198
+ return content
199
+ .map((b: unknown) => {
200
+ if (!isObj(b)) return "";
201
+ if (b.type === "text" && typeof b.text === "string") return b.text;
202
+ if (b.type === "image") return "[image]";
203
+ return "";
204
+ })
205
+ .filter(Boolean);
206
+ }
207
+
208
+ /** Summary preference: input.description, then the first string input value. */
209
+ function actionOf(name: string, input: unknown): Action {
210
+ const a = isObj(input) ? input : {};
211
+ let summary = Object.values(a).find((v): v is string => typeof v === "string") ?? "";
212
+ if (typeof a.description === "string") summary = a.description;
213
+ return { tool: name, summary: summary.slice(0, SUMMARY_MAX) };
214
+ }
215
+
216
+ function snap(t: Turn): Turn {
217
+ return { ...t, actions: [...t.actions] };
218
+ }
219
+
220
+ function claudeReader(opts: { config: Config }): Reader {
221
+ let open: Turn | null = null;
222
+ let pending: Trigger | undefined;
223
+ let last: Turn | null = null;
224
+ /** API message id of the newest assistant record in `last`; one message spans several records. */
225
+ let lastMessageId: string | undefined;
226
+
227
+ return {
228
+ push(record: unknown): Turn[] {
229
+ const changed: Turn[] = [];
230
+ // Bookkeeping records (mode, last-prompt, api-request, cost-state …) carry no uuid.
231
+ if (!isObj(record) || typeof record.uuid !== "string" || record.isSidechain === true) return changed;
232
+ const id = record.uuid;
233
+ const at = Date.parse(String(record.timestamp)) || 0;
234
+
235
+ const closeOpen = () => {
236
+ if (!open) return;
237
+ open.open = false;
238
+ changed.push(snap(open));
239
+ open = null;
240
+ };
241
+
242
+ /**
243
+ * Folds text from the user channel: the owner's own words, or text the harness put there.
244
+ * `typed` marks a prompt the owner submitted as text, as opposed to a command or its output.
245
+ */
246
+ const userText = (content: unknown, origin: unknown, typed: boolean) => {
247
+ const blocks = textBlocks(content);
248
+ const raw = blocks.join("\n");
249
+ if (INTERRUPT_RE.test(raw)) return closeOpen();
250
+ // A leading wrapper tag marks harness text, unless the whole typed prompt merely starts with a tag.
251
+ const own = blocks.filter((b) => !WRAPPER_RE.test(b));
252
+ const text = (typed && own.length === 0 ? blocks : own).join("\n");
253
+ const kind = isObj(origin) ? origin.kind : undefined;
254
+ const injected = (kind !== undefined && kind !== "human") || opts.config.harnessText.some((re) => re.test(text));
255
+ if (!text || injected) {
256
+ // Mid-turn injections are ignored; idle ones become the next agent turn's trigger.
257
+ if (raw && !open) pending = { from: "owner", text: raw.slice(0, HARNESS_TEXT_MAX) };
258
+ return;
259
+ }
260
+ closeOpen();
261
+ pending = undefined;
262
+ const t: Turn = { id, author: "owner", at, text, actions: [], open: false };
263
+ last = t;
264
+ changed.push(snap(t));
265
+ };
266
+
267
+ if (record.type === "user" && isObj(record.message)) {
268
+ const m = record.message;
269
+ // Tool output comes back in the user channel; it is never an owner turn.
270
+ if (Array.isArray(m.content) && m.content.some((b: unknown) => isObj(b) && b.type === "tool_result")) {
271
+ return changed;
272
+ }
273
+ // Written for the model or the transcript only; the owner neither typed nor saw them as prompts.
274
+ if (record.isMeta === true || record.isCompactSummary === true || record.isVisibleInTranscriptOnly === true) {
275
+ return changed;
276
+ }
277
+ // Typed, queued and SDK prompts name their source; slash commands and `!` shell lines do not.
278
+ const source = record.promptSource;
279
+ userText(m.content, record.origin, typeof source === "string" && source !== "system");
280
+ return changed;
281
+ }
282
+
283
+ if (record.type === "assistant" && isObj(record.message)) {
284
+ const m = record.message;
285
+ // Error notices and other replies Claude Code wrote itself end the turn without adding text.
286
+ if (m.model === "<synthetic>" || record.isApiErrorMessage === true) {
287
+ closeOpen();
288
+ return changed;
289
+ }
290
+ const messageId = typeof m.id === "string" ? m.id : undefined;
291
+ let cur = open;
292
+ // A later block of a message whose earlier block already ended the turn.
293
+ if (!cur && last?.author === "agent" && messageId !== undefined && messageId === lastMessageId) cur = last;
294
+ if (!cur) {
295
+ cur = { id, author: "agent", at, text: "", actions: [], open: true };
296
+ if (last?.author === "owner") cur.openedBy = last.id;
297
+ if (pending) cur.trigger = pending;
298
+ pending = undefined;
299
+ open = cur;
300
+ last = cur;
301
+ }
302
+ lastMessageId = messageId;
303
+ const content = Array.isArray(m.content) ? m.content : [];
304
+ let visible = false;
305
+ for (const b of content) {
306
+ if (!isObj(b)) continue;
307
+ if (b.type === "text" && typeof b.text === "string" && b.text) {
308
+ cur.text = (cur.text ? `${cur.text}\n${b.text}` : b.text).slice(-TEXT_MAX);
309
+ visible = true;
310
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
311
+ cur.actions.push(actionOf(b.name, b.input));
312
+ visible = true;
313
+ }
314
+ }
315
+ // tool_use and pause_turn continue the same turn; every other stop reason ends it. Each
316
+ // record of a message repeats the stop reason and thinking comes first, so a record with
317
+ // only thinking never ends the turn: the text record after it does.
318
+ const ends =
319
+ typeof m.stop_reason === "string" && m.stop_reason !== "tool_use" && m.stop_reason !== "pause_turn";
320
+ if (visible && ends && cur === open) {
321
+ cur.open = false;
322
+ open = null;
323
+ }
324
+ changed.push(snap(cur));
325
+ return changed;
326
+ }
327
+
328
+ // A message the owner sent while the agent was working arrives as an attachment.
329
+ if (record.type === "attachment" && isObj(record.attachment) && record.attachment.type === "queued_command") {
330
+ const a = record.attachment;
331
+ if (a.isMeta !== true) userText(a.prompt, a.origin, isObj(a.origin) && a.origin.kind === "human");
332
+ return changed;
333
+ }
334
+
335
+ // Written when the whole agent loop has finished.
336
+ if (record.type === "system" && record.subtype === "turn_duration") closeOpen();
337
+ return changed;
338
+ },
339
+ };
340
+ }
341
+
342
+ export const claude: Harness = {
343
+ id: "claude",
344
+ locate,
345
+ resolve,
346
+ reader(_ref: SessionRef, opts: { config: Config }): Reader {
347
+ return claudeReader(opts);
348
+ },
349
+ };
@@ -0,0 +1,32 @@
1
+ import type { Config } from "../config";
2
+ import type { Turn } from "../model";
3
+ import { claude } from "./claude";
4
+ import { omp } from "./omp";
5
+
6
+ export interface SessionRef {
7
+ harness: string;
8
+ key: string;
9
+ file: string;
10
+ cwd: string;
11
+ title?: string;
12
+ }
13
+
14
+ /** Folds one raw record into the turn list; returns every turn it created or changed. */
15
+ export interface Reader {
16
+ push(record: unknown): Turn[];
17
+ }
18
+
19
+ export interface Harness {
20
+ id: string;
21
+ locate(opts: { sessionFile?: string; tty?: string; cwd: string }): Promise<SessionRef>;
22
+ resolve(key: string): Promise<SessionRef>;
23
+ reader(ref: SessionRef, opts: { config: Config }): Reader;
24
+ }
25
+
26
+ export const harnesses = { omp, claude } as const;
27
+ export type HarnessId = keyof typeof harnesses;
28
+
29
+ /** Own-property lookup, so ids such as "toString" are not harnesses. */
30
+ export function harnessById(id: string): Harness | undefined {
31
+ return Object.hasOwn(harnesses, id) ? harnesses[id as HarnessId] : undefined;
32
+ }