intent-prompt-graph 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/integrations/claude/commands/ipg-log.md +10 -0
- package/integrations/claude/commands/ipg-rejected.md +10 -0
- package/integrations/claude/commands/ipg.md +10 -0
- package/integrations/omp/intent-graph.ts +65 -0
- package/integrations/omp/types.d.ts +30 -0
- package/package.json +47 -4
- package/src/cli.ts +212 -0
- package/src/config.ts +114 -0
- package/src/export.ts +71 -0
- package/src/harness/claude.ts +343 -0
- package/src/harness/harness.ts +32 -0
- package/src/harness/omp.ts +225 -0
- package/src/heuristic.ts +440 -0
- package/src/labeler.ts +496 -0
- package/src/model.ts +67 -0
- package/src/server.ts +173 -0
- package/src/session.ts +203 -0
- package/src/store.ts +122 -0
- package/src/tail.ts +89 -0
- package/web/app.ts +349 -0
- package/web/index.html +70 -0
- package/web/layout.ts +359 -0
- package/web/style.css +640 -0
- package/web/view.ts +654 -0
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,343 @@
|
|
|
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 nothing saved yet; 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
|
+
/** Folds text typed into the user channel: the owner's own words, or text the harness put there. */
|
|
243
|
+
const userText = (content: unknown, origin: unknown) => {
|
|
244
|
+
const blocks = textBlocks(content);
|
|
245
|
+
const raw = blocks.join("\n");
|
|
246
|
+
if (INTERRUPT_RE.test(raw)) return closeOpen();
|
|
247
|
+
// Newer records name their origin; without one, a leading wrapper tag marks harness text.
|
|
248
|
+
const kind = isObj(origin) ? origin.kind : undefined;
|
|
249
|
+
const text = (kind === "human" ? blocks : blocks.filter((b) => !WRAPPER_RE.test(b))).join("\n");
|
|
250
|
+
const injected = (kind !== undefined && kind !== "human") || opts.config.harnessText.some((re) => re.test(text));
|
|
251
|
+
if (!text || injected) {
|
|
252
|
+
// Mid-turn injections are ignored; idle ones become the next agent turn's trigger.
|
|
253
|
+
if (raw && !open) pending = { from: "owner", text: raw.slice(0, HARNESS_TEXT_MAX) };
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
closeOpen();
|
|
257
|
+
pending = undefined;
|
|
258
|
+
const t: Turn = { id, author: "owner", at, text, actions: [], open: false };
|
|
259
|
+
last = t;
|
|
260
|
+
changed.push(snap(t));
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
if (record.type === "user" && isObj(record.message)) {
|
|
264
|
+
const m = record.message;
|
|
265
|
+
// Tool output comes back in the user channel; it is never an owner turn.
|
|
266
|
+
if (Array.isArray(m.content) && m.content.some((b: unknown) => isObj(b) && b.type === "tool_result")) {
|
|
267
|
+
return changed;
|
|
268
|
+
}
|
|
269
|
+
// Written for the model or the transcript only; the owner neither typed nor saw them as prompts.
|
|
270
|
+
if (record.isMeta === true || record.isCompactSummary === true || record.isVisibleInTranscriptOnly === true) {
|
|
271
|
+
return changed;
|
|
272
|
+
}
|
|
273
|
+
userText(m.content, record.origin);
|
|
274
|
+
return changed;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (record.type === "assistant" && isObj(record.message)) {
|
|
278
|
+
const m = record.message;
|
|
279
|
+
// Error notices and other replies Claude Code wrote itself end the turn without adding text.
|
|
280
|
+
if (m.model === "<synthetic>" || record.isApiErrorMessage === true) {
|
|
281
|
+
closeOpen();
|
|
282
|
+
return changed;
|
|
283
|
+
}
|
|
284
|
+
const messageId = typeof m.id === "string" ? m.id : undefined;
|
|
285
|
+
let cur = open;
|
|
286
|
+
// A later block of a message whose earlier block already ended the turn.
|
|
287
|
+
if (!cur && last?.author === "agent" && messageId !== undefined && messageId === lastMessageId) cur = last;
|
|
288
|
+
if (!cur) {
|
|
289
|
+
cur = { id, author: "agent", at, text: "", actions: [], open: true };
|
|
290
|
+
if (last?.author === "owner") cur.openedBy = last.id;
|
|
291
|
+
if (pending) cur.trigger = pending;
|
|
292
|
+
pending = undefined;
|
|
293
|
+
open = cur;
|
|
294
|
+
last = cur;
|
|
295
|
+
}
|
|
296
|
+
lastMessageId = messageId;
|
|
297
|
+
const content = Array.isArray(m.content) ? m.content : [];
|
|
298
|
+
let visible = false;
|
|
299
|
+
for (const b of content) {
|
|
300
|
+
if (!isObj(b)) continue;
|
|
301
|
+
if (b.type === "text" && typeof b.text === "string" && b.text) {
|
|
302
|
+
cur.text = (cur.text ? `${cur.text}\n${b.text}` : b.text).slice(-TEXT_MAX);
|
|
303
|
+
visible = true;
|
|
304
|
+
} else if (b.type === "tool_use" && typeof b.name === "string") {
|
|
305
|
+
cur.actions.push(actionOf(b.name, b.input));
|
|
306
|
+
visible = true;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// tool_use and pause_turn continue the same turn; every other stop reason ends it. Each
|
|
310
|
+
// record of a message repeats the stop reason and thinking comes first, so a record with
|
|
311
|
+
// only thinking never ends the turn: the text record after it does.
|
|
312
|
+
const ends =
|
|
313
|
+
typeof m.stop_reason === "string" && m.stop_reason !== "tool_use" && m.stop_reason !== "pause_turn";
|
|
314
|
+
if (visible && ends && cur === open) {
|
|
315
|
+
cur.open = false;
|
|
316
|
+
open = null;
|
|
317
|
+
}
|
|
318
|
+
changed.push(snap(cur));
|
|
319
|
+
return changed;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// A message the owner sent while the agent was working arrives as an attachment.
|
|
323
|
+
if (record.type === "attachment" && isObj(record.attachment) && record.attachment.type === "queued_command") {
|
|
324
|
+
const a = record.attachment;
|
|
325
|
+
if (a.isMeta !== true) userText(a.prompt, a.origin);
|
|
326
|
+
return changed;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Written when the whole agent loop has finished.
|
|
330
|
+
if (record.type === "system" && record.subtype === "turn_duration") closeOpen();
|
|
331
|
+
return changed;
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export const claude: Harness = {
|
|
337
|
+
id: "claude",
|
|
338
|
+
locate,
|
|
339
|
+
resolve,
|
|
340
|
+
reader(_ref: SessionRef, opts: { config: Config }): Reader {
|
|
341
|
+
return claudeReader(opts);
|
|
342
|
+
},
|
|
343
|
+
};
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { 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 KEY_RE = /^[0-9a-zA-Z-]+$/;
|
|
12
|
+
|
|
13
|
+
export function agentDir(): string {
|
|
14
|
+
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".omp", "agent");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function sessionsDir(): string {
|
|
18
|
+
return join(agentDir(), "sessions");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function globFiles(dir: string, pattern: string): string[] {
|
|
22
|
+
if (!existsSync(dir)) return [];
|
|
23
|
+
return [...new Bun.Glob(pattern).scanSync({ cwd: dir, absolute: true })];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface Head {
|
|
27
|
+
id?: string;
|
|
28
|
+
cwd?: string;
|
|
29
|
+
title?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Reads the title slot (line 1) and the session header (line 2) from the first 4 KiB. */
|
|
33
|
+
function headOf(file: string): Head {
|
|
34
|
+
const fd = openSync(file, "r");
|
|
35
|
+
try {
|
|
36
|
+
const buf = Buffer.alloc(4096);
|
|
37
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
38
|
+
const head: Head = {};
|
|
39
|
+
for (const line of buf.toString("utf8", 0, n).split("\n")) {
|
|
40
|
+
let obj: Record<string, unknown>;
|
|
41
|
+
try {
|
|
42
|
+
obj = JSON.parse(line) as Record<string, unknown>;
|
|
43
|
+
} catch {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (obj.type === "title" && typeof obj.title === "string") head.title = obj.title;
|
|
47
|
+
if (obj.type === "session") {
|
|
48
|
+
head.id = obj.id as string;
|
|
49
|
+
head.cwd = obj.cwd as string;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return head;
|
|
53
|
+
} finally {
|
|
54
|
+
closeSync(fd);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refOf(file: string): SessionRef {
|
|
59
|
+
const head = headOf(file);
|
|
60
|
+
if (!head.id || !head.cwd) throw new Error(`no OMP session header in ${file}`);
|
|
61
|
+
return { harness: "omp", key: head.id, file, cwd: head.cwd, title: head.title };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function locate(opts: { sessionFile?: string; tty?: string; cwd: string }): Promise<SessionRef> {
|
|
65
|
+
if (opts.sessionFile) return refOf(opts.sessionFile);
|
|
66
|
+
const looked: string[] = [];
|
|
67
|
+
if (opts.tty) {
|
|
68
|
+
// Breadcrumb name: /dev/pts/9 → pts-9
|
|
69
|
+
const crumb = join(agentDir(), "terminal-sessions", opts.tty.replace(/^\/dev\//, "").replace(/\//g, "-"));
|
|
70
|
+
looked.push(crumb);
|
|
71
|
+
if (existsSync(crumb)) {
|
|
72
|
+
const target = readFileSync(crumb, "utf8").split("\n")[1]?.trim();
|
|
73
|
+
if (target && existsSync(target)) return refOf(target);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
looked.push(`newest sessions with cwd ${opts.cwd} under ${sessionsDir()}`);
|
|
77
|
+
let best: { file: string; mtime: number } | undefined;
|
|
78
|
+
for (const file of globFiles(sessionsDir(), "*/*.jsonl")) {
|
|
79
|
+
if (headOf(file).cwd !== opts.cwd) continue;
|
|
80
|
+
const mtime = statSync(file).mtimeMs;
|
|
81
|
+
if (!best || mtime > best.mtime) best = { file, mtime };
|
|
82
|
+
}
|
|
83
|
+
if (best) return refOf(best.file);
|
|
84
|
+
throw new Error(`no OMP session found; looked at: ${looked.join("; ")}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function resolve(key: string): Promise<SessionRef> {
|
|
88
|
+
if (!KEY_RE.test(key)) throw new Error(`invalid OMP session key: ${key}`);
|
|
89
|
+
const [file] = globFiles(sessionsDir(), `*/*_${key}.jsonl`);
|
|
90
|
+
if (!file) throw new Error(`no OMP session with key ${key} under ${sessionsDir()}`);
|
|
91
|
+
return refOf(file);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isObj(v: unknown): v is Record<string, unknown> {
|
|
95
|
+
return typeof v === "object" && v !== null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Owner user content: a string, or text blocks joined with newlines (images shown as [image]). */
|
|
99
|
+
function ownerText(content: unknown): string {
|
|
100
|
+
if (typeof content === "string") return content;
|
|
101
|
+
if (!Array.isArray(content)) return "";
|
|
102
|
+
return content
|
|
103
|
+
.map((b: unknown) => {
|
|
104
|
+
if (!isObj(b)) return "";
|
|
105
|
+
if (b.type === "text" && typeof b.text === "string") return b.text;
|
|
106
|
+
if (b.type === "image") return "[image]";
|
|
107
|
+
return "";
|
|
108
|
+
})
|
|
109
|
+
.filter(Boolean)
|
|
110
|
+
.join("\n");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Summary preference: arguments.i, then arguments.description, then the first string argument. */
|
|
114
|
+
function actionOf(name: string, args: unknown): Action {
|
|
115
|
+
const a = isObj(args) ? args : {};
|
|
116
|
+
let summary = Object.values(a).find((v): v is string => typeof v === "string") ?? "";
|
|
117
|
+
if (typeof a.description === "string") summary = a.description;
|
|
118
|
+
if (typeof a.i === "string") summary = a.i;
|
|
119
|
+
return { tool: name, summary: summary.slice(0, SUMMARY_MAX) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function snap(t: Turn): Turn {
|
|
123
|
+
return { ...t, actions: [...t.actions] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function ompReader(opts: { config: Config }): Reader {
|
|
127
|
+
let open: Turn | null = null;
|
|
128
|
+
let pending: Trigger | undefined;
|
|
129
|
+
let last: Turn | null = null;
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
push(record: unknown): Turn[] {
|
|
133
|
+
const changed: Turn[] = [];
|
|
134
|
+
if (!isObj(record)) return changed;
|
|
135
|
+
if (record.type === "title" || record.type === "session") return changed;
|
|
136
|
+
if (typeof record.id !== "string") return changed;
|
|
137
|
+
const id = record.id;
|
|
138
|
+
const at = Date.parse(String(record.timestamp)) || 0;
|
|
139
|
+
|
|
140
|
+
const closeOpen = () => {
|
|
141
|
+
if (!open) return;
|
|
142
|
+
open.open = false;
|
|
143
|
+
changed.push(snap(open));
|
|
144
|
+
open = null;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
if (record.type === "message" && isObj(record.message)) {
|
|
148
|
+
const m = record.message;
|
|
149
|
+
if (m.role === "user") {
|
|
150
|
+
const text = ownerText(m.content);
|
|
151
|
+
const hit = opts.config.harnessText.some((re) => re.test(text));
|
|
152
|
+
if (hit) {
|
|
153
|
+
// Mid-turn injections are ignored; idle ones become the next agent turn's trigger.
|
|
154
|
+
if (!open) pending = { from: "owner", text: text.slice(0, HARNESS_TEXT_MAX) };
|
|
155
|
+
return changed;
|
|
156
|
+
}
|
|
157
|
+
closeOpen();
|
|
158
|
+
pending = undefined;
|
|
159
|
+
const t: Turn = { id, author: "owner", at, text, actions: [], open: false };
|
|
160
|
+
last = t;
|
|
161
|
+
changed.push(snap(t));
|
|
162
|
+
} else if (m.role === "assistant") {
|
|
163
|
+
if (!open) {
|
|
164
|
+
const t: Turn = { id, author: "agent", at, text: "", actions: [], open: true };
|
|
165
|
+
if (last?.author === "owner") t.openedBy = last.id;
|
|
166
|
+
if (pending) t.trigger = pending;
|
|
167
|
+
pending = undefined;
|
|
168
|
+
open = t;
|
|
169
|
+
last = t;
|
|
170
|
+
}
|
|
171
|
+
const cur = open;
|
|
172
|
+
const content = Array.isArray(m.content) ? m.content : [];
|
|
173
|
+
for (const b of content) {
|
|
174
|
+
if (!isObj(b)) continue;
|
|
175
|
+
if (b.type === "text" && typeof b.text === "string" && b.text) {
|
|
176
|
+
cur.text = (cur.text ? `${cur.text}\n${b.text}` : b.text).slice(-TEXT_MAX);
|
|
177
|
+
} else if (b.type === "toolCall" && typeof b.name === "string") {
|
|
178
|
+
cur.actions.push(actionOf(b.name, b.arguments));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (m.stopReason === "stop" || m.stopReason === "aborted" || m.stopReason === "error") {
|
|
182
|
+
cur.open = false;
|
|
183
|
+
open = null;
|
|
184
|
+
}
|
|
185
|
+
changed.push(snap(cur));
|
|
186
|
+
}
|
|
187
|
+
return changed;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (record.type === "custom_message") {
|
|
191
|
+
if (record.display !== true) return changed;
|
|
192
|
+
if (record.attribution === "user") {
|
|
193
|
+
closeOpen();
|
|
194
|
+
pending = undefined;
|
|
195
|
+
const t: Turn = {
|
|
196
|
+
id,
|
|
197
|
+
author: "owner",
|
|
198
|
+
at,
|
|
199
|
+
text: ownerText(record.content),
|
|
200
|
+
actions: [],
|
|
201
|
+
open: false,
|
|
202
|
+
guest: true,
|
|
203
|
+
};
|
|
204
|
+
last = t;
|
|
205
|
+
changed.push(snap(t));
|
|
206
|
+
} else if (record.attribution === "agent" && !open) {
|
|
207
|
+
pending = { from: "agent", type: String(record.customType) };
|
|
208
|
+
}
|
|
209
|
+
return changed;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (record.type === "custom" && record.customType === "session_exit") closeOpen();
|
|
213
|
+
return changed;
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export const omp: Harness = {
|
|
219
|
+
id: "omp",
|
|
220
|
+
locate,
|
|
221
|
+
resolve,
|
|
222
|
+
reader(_ref: SessionRef, opts: { config: Config }): Reader {
|
|
223
|
+
return ompReader(opts);
|
|
224
|
+
},
|
|
225
|
+
};
|