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/LICENSE +21 -0
- package/README.md +157 -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 +349 -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 +350 -0
- package/web/style.css +647 -0
- package/web/view.ts +669 -0
package/src/labeler.ts
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
import type { LabelerConfig } from "./config";
|
|
2
|
+
import type { Author, EdgeKind, GraphEdge, GraphNode, NodeKind, SessionGraph, Turn } from "./model";
|
|
3
|
+
|
|
4
|
+
export const OWNER_CHARS = 800;
|
|
5
|
+
export const AGENT_CHARS = 1200;
|
|
6
|
+
export const TRIGGER_CHARS = 400;
|
|
7
|
+
export const TITLE_CHARS = 100;
|
|
8
|
+
export const DESC_CHARS = 240;
|
|
9
|
+
export const RATIONALE_CHARS = 400;
|
|
10
|
+
export const BADGE_CHARS = 32;
|
|
11
|
+
export const EDGE_LABEL_CHARS = 40;
|
|
12
|
+
export const GUEST_PLACEHOLDER = "[guest message withheld]";
|
|
13
|
+
export const TIMEOUT_MS = 90_000;
|
|
14
|
+
|
|
15
|
+
export const NODE_KINDS: readonly NodeKind[] = ["goal", "chosen", "rejected", "option", "decision", "loop", "side"];
|
|
16
|
+
export const EDGE_KINDS: readonly EdgeKind[] = ["chosen", "rejected", "option", "decision", "loop", "side"];
|
|
17
|
+
|
|
18
|
+
export interface RedactedTurn {
|
|
19
|
+
ref: string;
|
|
20
|
+
author: Author;
|
|
21
|
+
at: number;
|
|
22
|
+
guest?: true;
|
|
23
|
+
text?: string;
|
|
24
|
+
tools?: Record<string, number>;
|
|
25
|
+
openedBy?: string;
|
|
26
|
+
trigger?: { from: "owner"; text: string };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface GraphExtractInput {
|
|
30
|
+
sessionTitle?: string;
|
|
31
|
+
/** Slim outline of the graph built so far; when present the model replies with a patch, not the full graph. */
|
|
32
|
+
existingGraph?: {
|
|
33
|
+
title: string;
|
|
34
|
+
nodes: { id: string; kind: NodeKind; title: string; rounds?: number }[];
|
|
35
|
+
edges: { from: string; to: string; kind: EdgeKind }[];
|
|
36
|
+
};
|
|
37
|
+
turns: RedactedTurn[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const SYSTEM_PROMPT = `You convert a coding-agent conversation into a Decision & Path Graph (directed acyclic graph).
|
|
41
|
+
|
|
42
|
+
Your goal is to help the human owner understand the entire session in 5 seconds:
|
|
43
|
+
1. What problem/goal started the session ("goal")
|
|
44
|
+
2. What options/alternatives were proposed but NOT chosen ("option")
|
|
45
|
+
3. What paths or proposals were explicitly rejected or killed and WHY ("rejected")
|
|
46
|
+
4. What decisions, pivots, constraints, or course corrections happened ("decision")
|
|
47
|
+
5. What final paths, architectures, or fixes were chosen/verified ("chosen")
|
|
48
|
+
6. Repetitive check/review/polling loops collapsed into a single node ("loop", with "rounds")
|
|
49
|
+
7. Tangential clarifying questions branched off the main spine ("side")
|
|
50
|
+
|
|
51
|
+
Rules:
|
|
52
|
+
- Synthesize crisp, specific titles (<= 8 words). NEVER copy filler openers like "You're right", "Okay", "Not quite", or raw file paths as titles.
|
|
53
|
+
- When the owner rejects or pushes back on an agent proposal, mark the AGENT's rejected proposal as "rejected" (with the owner's objection as "rationale") and branch the owner's new direction as "decision" or "chosen".
|
|
54
|
+
- Merge repetitive back-and-forth checks (like "chk agn" / "chk now" or repeated CI/blocker status polls) into ONE "loop" node with all their turn refs in "turnIds" and an integer "rounds".
|
|
55
|
+
- Keep the graph concise and high-signal (typically 5-18 nodes). Do not create separate nodes for routine acknowledgements.
|
|
56
|
+
- Connect nodes with directed edges (from -> to) using kinds: "chosen", "rejected", "option", "decision", "loop", "side", with a short edge "label" (<= 4 words). Every non-goal node should be reachable from the goal.
|
|
57
|
+
- Without "existingGraph", return the complete first graph for the given turns.
|
|
58
|
+
- If "existingGraph" is provided, it outlines the graph built so far (node id, kind, title, rounds; edge from, to, kind). Reply with a PATCH for the new turns, NOT the whole graph: "nodes" holds ONLY nodes that are new or changed, and "edges" holds ONLY new edges. NEVER repeat an unchanged node. Nodes you leave out are kept exactly as they are; you cannot delete a node.
|
|
59
|
+
- To change an existing node, return its "id" plus ONLY the fields that change (e.g. "kind" with a matching "badge" and "rationaleLabel", or "rounds"). "turnIds" on a changed node lists only the newly added turn refs; they are added to the ones it already has.
|
|
60
|
+
- New nodes need ids not used in "existingGraph". New edges may connect new and existing node ids. To change the kind or label of an existing edge, return it again with the same "from" and "to".
|
|
61
|
+
- An empty "nodes" array is valid when the new turns add nothing to an existing graph.
|
|
62
|
+
- Every new node must include: "id", "kind", "badge" (2-3 uppercase words), "title" (<= 10 words), "desc" (1-2 concise sentences), "rationaleLabel" (e.g. "Why chosen" / "Why rejected"), "rationale" (clear concrete reason), "turnIds" (array of turn refs from the input).
|
|
63
|
+
|
|
64
|
+
Reply with raw JSON only (no markdown fences, no commentary before or after):
|
|
65
|
+
{"title":"...","nodes":[...],"edges":[{"from":"...","to":"...","kind":"...","label":"..."}]}`;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Returns the system prompt used for LLM Decision & Path Graph extraction.
|
|
69
|
+
*
|
|
70
|
+
* Args:
|
|
71
|
+
* None
|
|
72
|
+
*
|
|
73
|
+
* Returns:
|
|
74
|
+
* string: The system prompt text.
|
|
75
|
+
*/
|
|
76
|
+
export function systemPrompt(): string {
|
|
77
|
+
return SYSTEM_PROMPT;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Extracts I5-compliant visible text from a turn (redacting guest text and capping lengths).
|
|
82
|
+
*
|
|
83
|
+
* Args:
|
|
84
|
+
* turn (Turn): Source turn from the transcript.
|
|
85
|
+
*
|
|
86
|
+
* Returns:
|
|
87
|
+
* string: Redacted and length-capped text safe to send to an external labeler.
|
|
88
|
+
*/
|
|
89
|
+
function visibleText(turn: Turn): string {
|
|
90
|
+
if (turn.guest) return GUEST_PLACEHOLDER;
|
|
91
|
+
if (turn.author === "owner") return turn.text.slice(0, OWNER_CHARS);
|
|
92
|
+
return turn.text.slice(-AGENT_CHARS);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Computes the exact text a turn contributes to the labeler payload for batch-size budgeting.
|
|
97
|
+
*
|
|
98
|
+
* Args:
|
|
99
|
+
* turn (Turn): Source turn.
|
|
100
|
+
*
|
|
101
|
+
* Returns:
|
|
102
|
+
* string: Concatenated visible text and owner-origin trigger text.
|
|
103
|
+
*/
|
|
104
|
+
export function payloadText(turn: Turn): string {
|
|
105
|
+
const trigger = turn.trigger?.from === "owner" ? turn.trigger.text.slice(0, TRIGGER_CHARS) : "";
|
|
106
|
+
return visibleText(turn) + trigger;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Counts tool invocations by tool name without leaking tool arguments or outputs (I5).
|
|
111
|
+
*
|
|
112
|
+
* Args:
|
|
113
|
+
* turn (Turn): Agent turn containing actions.
|
|
114
|
+
*
|
|
115
|
+
* Returns:
|
|
116
|
+
* Record<string, number>: Map of tool name to call count.
|
|
117
|
+
*/
|
|
118
|
+
function countTools(turn: Turn): Record<string, number> {
|
|
119
|
+
const counts: Record<string, number> = {};
|
|
120
|
+
for (const action of turn.actions) counts[action.tool] = (counts[action.tool] ?? 0) + 1;
|
|
121
|
+
return counts;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Builds an I5-compliant redacted representation of a single turn for the LLM extractor.
|
|
126
|
+
*
|
|
127
|
+
* Args:
|
|
128
|
+
* turn (Turn): Source turn.
|
|
129
|
+
*
|
|
130
|
+
* Returns:
|
|
131
|
+
* RedactedTurn: Redacted turn object with capped text, tool counts, and owner trigger only.
|
|
132
|
+
*/
|
|
133
|
+
export function redactTurn(turn: Turn): RedactedTurn {
|
|
134
|
+
const out: RedactedTurn = { ref: turn.id, author: turn.author, at: turn.at };
|
|
135
|
+
if (turn.guest) out.guest = true;
|
|
136
|
+
const text = visibleText(turn);
|
|
137
|
+
if (text) out.text = text;
|
|
138
|
+
if (turn.author === "agent") {
|
|
139
|
+
out.tools = countTools(turn);
|
|
140
|
+
if (turn.openedBy) out.openedBy = turn.openedBy;
|
|
141
|
+
if (turn.trigger?.from === "owner") out.trigger = { from: "owner", text: turn.trigger.text.slice(0, TRIGGER_CHARS) };
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function bad(message: string): Error {
|
|
147
|
+
return new Error(`labeler output: ${message}`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function parseJson(text: string): unknown {
|
|
151
|
+
try {
|
|
152
|
+
return JSON.parse(text);
|
|
153
|
+
} catch {
|
|
154
|
+
const start = text.indexOf("{");
|
|
155
|
+
const end = text.lastIndexOf("}");
|
|
156
|
+
if (start >= 0 && end > start) {
|
|
157
|
+
try {
|
|
158
|
+
return JSON.parse(text.slice(start, end + 1));
|
|
159
|
+
} catch {
|
|
160
|
+
// Fall through to uniform error below.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
throw bad("not valid JSON");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function optionalString(obj: Record<string, unknown>, key: string, max: number): string | undefined {
|
|
168
|
+
const v = obj[key];
|
|
169
|
+
return typeof v === "string" && v.trim() ? v.trim().slice(0, max) : undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function nonEmptyString(obj: Record<string, unknown>, key: string, max: number, fallback?: string): string {
|
|
173
|
+
const v = optionalString(obj, key, max) ?? fallback;
|
|
174
|
+
if (v === undefined) throw bad(`missing or empty string "${key}"`);
|
|
175
|
+
return v;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function nodeKind(rec: Record<string, unknown>, id: string): NodeKind {
|
|
179
|
+
const kind = NODE_KINDS.find((k) => k === rec.kind);
|
|
180
|
+
if (!kind) throw bad(`invalid node kind for ${id}`);
|
|
181
|
+
return kind;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function replyTurnIds(rec: Record<string, unknown>): string[] {
|
|
185
|
+
const raw: unknown[] = Array.isArray(rec.turnIds) ? rec.turnIds : [];
|
|
186
|
+
return raw.filter((x): x is string => typeof x === "string" && x.trim().length > 0);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function replyRounds(rec: Record<string, unknown>): number | undefined {
|
|
190
|
+
return typeof rec.rounds === "number" && Number.isInteger(rec.rounds) && rec.rounds > 1 ? rec.rounds : undefined;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Latest known timestamp among turnIds, never lower than floor. */
|
|
194
|
+
function latestAt(turnIds: readonly string[], turnTimestamps: ReadonlyMap<string, number>, floor: number): number {
|
|
195
|
+
let at = floor;
|
|
196
|
+
for (const tid of turnIds) {
|
|
197
|
+
const ts = turnTimestamps.get(tid);
|
|
198
|
+
if (ts !== undefined && ts > at) at = ts;
|
|
199
|
+
}
|
|
200
|
+
return at;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Builds a node the graph does not have yet; every required field must be present or defaultable.
|
|
205
|
+
*
|
|
206
|
+
* Args:
|
|
207
|
+
* id (string): Validated node id.
|
|
208
|
+
* rec (Record<string, unknown>): Raw node object from the reply.
|
|
209
|
+
* turnTimestamps (ReadonlyMap<string, number>): Known turn timestamps keyed by turn id.
|
|
210
|
+
*
|
|
211
|
+
* Returns:
|
|
212
|
+
* GraphNode: Validated new node.
|
|
213
|
+
*/
|
|
214
|
+
function newNode(id: string, rec: Record<string, unknown>, turnTimestamps: ReadonlyMap<string, number>): GraphNode {
|
|
215
|
+
const kind = nodeKind(rec, id);
|
|
216
|
+
const title = nonEmptyString(rec, "title", TITLE_CHARS);
|
|
217
|
+
const desc = nonEmptyString(rec, "desc", DESC_CHARS, title);
|
|
218
|
+
const badge = nonEmptyString(rec, "badge", BADGE_CHARS, kind.toUpperCase());
|
|
219
|
+
const rationaleLabel = nonEmptyString(rec, "rationaleLabel", 48, kind === "rejected" ? "Why rejected" : "Why chosen");
|
|
220
|
+
const rationale = nonEmptyString(rec, "rationale", RATIONALE_CHARS, desc);
|
|
221
|
+
const turnIds = replyTurnIds(rec);
|
|
222
|
+
const node: GraphNode = { id, kind, badge, title, desc, rationaleLabel, rationale, turnIds, at: latestAt(turnIds, turnTimestamps, 0) };
|
|
223
|
+
const rounds = replyRounds(rec);
|
|
224
|
+
if (rounds !== undefined) node.rounds = rounds;
|
|
225
|
+
return node;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Applies a partial reply node to a node the graph already has. Omitted fields keep the old value,
|
|
230
|
+
* turnIds are unioned (old order first) and `at` never moves backwards.
|
|
231
|
+
*
|
|
232
|
+
* Args:
|
|
233
|
+
* old (GraphNode): Node from the existing graph (not mutated).
|
|
234
|
+
* rec (Record<string, unknown>): Raw node object from the reply.
|
|
235
|
+
* turnTimestamps (ReadonlyMap<string, number>): Known turn timestamps keyed by turn id.
|
|
236
|
+
*
|
|
237
|
+
* Returns:
|
|
238
|
+
* GraphNode: Updated copy of the node.
|
|
239
|
+
*/
|
|
240
|
+
function updatedNode(old: GraphNode, rec: Record<string, unknown>, turnTimestamps: ReadonlyMap<string, number>): GraphNode {
|
|
241
|
+
const turnIds = [...new Set([...old.turnIds, ...replyTurnIds(rec)])];
|
|
242
|
+
const node: GraphNode = {
|
|
243
|
+
id: old.id,
|
|
244
|
+
kind: rec.kind === undefined ? old.kind : nodeKind(rec, old.id),
|
|
245
|
+
badge: optionalString(rec, "badge", BADGE_CHARS) ?? old.badge,
|
|
246
|
+
title: optionalString(rec, "title", TITLE_CHARS) ?? old.title,
|
|
247
|
+
desc: optionalString(rec, "desc", DESC_CHARS) ?? old.desc,
|
|
248
|
+
rationaleLabel: optionalString(rec, "rationaleLabel", 48) ?? old.rationaleLabel,
|
|
249
|
+
rationale: optionalString(rec, "rationale", RATIONALE_CHARS) ?? old.rationale,
|
|
250
|
+
turnIds,
|
|
251
|
+
at: latestAt(turnIds, turnTimestamps, old.at),
|
|
252
|
+
};
|
|
253
|
+
const rounds = replyRounds(rec) ?? old.rounds;
|
|
254
|
+
if (rounds !== undefined) node.rounds = rounds;
|
|
255
|
+
return node;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Validates the LLM's Decision & Path Graph JSON reply and merges it into the existing graph.
|
|
260
|
+
* Without an existing graph the reply is the complete first graph. With one, the reply is a patch:
|
|
261
|
+
* its nodes are added or partially update a node with the same id, its edges are added or replace
|
|
262
|
+
* the kind/label of the existing edge with the same from+to. The reply can never delete anything.
|
|
263
|
+
* Node errors throw so callers never commit corrupt graphs; an unusable edge is dropped on its own.
|
|
264
|
+
*
|
|
265
|
+
* Args:
|
|
266
|
+
* raw (string): Raw assistant message content (may be wrapped in a markdown code fence).
|
|
267
|
+
* turnTimestamps (ReadonlyMap<string, number>): Known turn timestamps keyed by turn id.
|
|
268
|
+
* existing (SessionGraph | undefined): Graph the reply patches (not mutated); omit for a first graph.
|
|
269
|
+
*
|
|
270
|
+
* Returns:
|
|
271
|
+
* SessionGraph: Validated, merged SessionGraph in "llm" mode.
|
|
272
|
+
*/
|
|
273
|
+
export function parseGraphOutput(raw: string, turnTimestamps: ReadonlyMap<string, number>, existing?: SessionGraph): SessionGraph {
|
|
274
|
+
const text = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
275
|
+
const json = parseJson(text);
|
|
276
|
+
if (typeof json !== "object" || json === null) throw bad("root is not an object");
|
|
277
|
+
const root = json as Record<string, unknown>;
|
|
278
|
+
|
|
279
|
+
if (!Array.isArray(root.nodes)) throw bad(existing ? "nodes must be an array" : "nodes must be a non-empty array");
|
|
280
|
+
if (!existing && root.nodes.length === 0) throw bad("nodes must be a non-empty array");
|
|
281
|
+
const rawEdges: unknown[] = Array.isArray(root.edges) ? root.edges : [];
|
|
282
|
+
|
|
283
|
+
const title = optionalString(root, "title", TITLE_CHARS) ?? existing?.title ?? "Session Decision Graph";
|
|
284
|
+
|
|
285
|
+
// Insertion-ordered: existing nodes keep their position, new nodes are appended.
|
|
286
|
+
const byId = new Map<string, GraphNode>();
|
|
287
|
+
for (const n of existing?.nodes ?? []) byId.set(n.id, n);
|
|
288
|
+
const seenIds = new Set<string>();
|
|
289
|
+
|
|
290
|
+
for (const item of root.nodes) {
|
|
291
|
+
if (typeof item !== "object" || item === null) throw bad("node is not an object");
|
|
292
|
+
const rec = item as Record<string, unknown>;
|
|
293
|
+
const id = nonEmptyString(rec, "id", 48);
|
|
294
|
+
if (seenIds.has(id)) throw bad(`duplicate node id ${id}`);
|
|
295
|
+
seenIds.add(id);
|
|
296
|
+
const old = byId.get(id);
|
|
297
|
+
byId.set(id, old ? updatedNode(old, rec, turnTimestamps) : newNode(id, rec, turnTimestamps));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const edges: GraphEdge[] = existing ? [...existing.edges] : [];
|
|
301
|
+
const pairKey = (from: string, to: string) => `${from}\u0000${to}`;
|
|
302
|
+
const slotByPair = new Map<string, number>();
|
|
303
|
+
const usedEdgeIds = new Set<string>();
|
|
304
|
+
edges.forEach((e, slot) => {
|
|
305
|
+
const key = pairKey(e.from, e.to);
|
|
306
|
+
if (!slotByPair.has(key)) slotByPair.set(key, slot);
|
|
307
|
+
usedEdgeIds.add(e.id);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
let edgeSeq = edges.length;
|
|
311
|
+
for (const item of rawEdges) {
|
|
312
|
+
if (typeof item !== "object" || item === null) continue;
|
|
313
|
+
const rec = item as Record<string, unknown>;
|
|
314
|
+
const from = optionalString(rec, "from", 48);
|
|
315
|
+
const to = optionalString(rec, "to", 48);
|
|
316
|
+
if (from === undefined || to === undefined || from === to) continue;
|
|
317
|
+
if (!byId.has(from) || !byId.has(to)) continue;
|
|
318
|
+
const kind = EDGE_KINDS.find((k) => k === rec.kind);
|
|
319
|
+
if (!kind) continue;
|
|
320
|
+
const label = optionalString(rec, "label", EDGE_LABEL_CHARS);
|
|
321
|
+
|
|
322
|
+
const key = pairKey(from, to);
|
|
323
|
+
const slot = slotByPair.get(key);
|
|
324
|
+
let id = slot === undefined ? undefined : edges[slot]?.id;
|
|
325
|
+
if (id === undefined) {
|
|
326
|
+
do {
|
|
327
|
+
id = `e${++edgeSeq}`;
|
|
328
|
+
} while (usedEdgeIds.has(id));
|
|
329
|
+
usedEdgeIds.add(id);
|
|
330
|
+
}
|
|
331
|
+
const edge: GraphEdge = { id, from, to, kind };
|
|
332
|
+
if (label !== undefined) edge.label = label;
|
|
333
|
+
if (slot === undefined) {
|
|
334
|
+
slotByPair.set(key, edges.length);
|
|
335
|
+
edges.push(edge);
|
|
336
|
+
} else {
|
|
337
|
+
edges[slot] = edge;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return { title, nodes: [...byId.values()], edges, mode: "llm" };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Extracts assistant message content from an OpenAI-compatible chat completion response.
|
|
346
|
+
*
|
|
347
|
+
* Args:
|
|
348
|
+
* body (unknown): Parsed JSON response body.
|
|
349
|
+
*
|
|
350
|
+
* Returns:
|
|
351
|
+
* unknown: The content string if present, otherwise undefined.
|
|
352
|
+
*/
|
|
353
|
+
function messageContent(body: unknown): unknown {
|
|
354
|
+
if (typeof body !== "object" || body === null || !("choices" in body) || !Array.isArray(body.choices)) return undefined;
|
|
355
|
+
const choices: unknown[] = body.choices;
|
|
356
|
+
const first: unknown = choices[0];
|
|
357
|
+
if (typeof first !== "object" || first === null || !("message" in first)) return undefined;
|
|
358
|
+
const msg: unknown = first.message;
|
|
359
|
+
if (typeof msg !== "object" || msg === null || !("content" in msg)) return undefined;
|
|
360
|
+
return msg.content;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Invokes the local Claude Code CLI in non-interactive print mode to extract the Decision & Path Graph.
|
|
365
|
+
* Disables session persistence and built-in tools so no ~/.claude history or side effects occur.
|
|
366
|
+
*
|
|
367
|
+
* Args:
|
|
368
|
+
* cfg (LabelerConfig): Labeler config with model and optional command override.
|
|
369
|
+
* input (GraphExtractInput): Redacted turns and optional slim outline of the existing graph.
|
|
370
|
+
* turnTimestamps (ReadonlyMap<string, number>): Known turn timestamps for node ordering.
|
|
371
|
+
* existing (SessionGraph | undefined): Graph the reply is merged into; omit for a first graph.
|
|
372
|
+
* env (NodeJS.ProcessEnv): Environment variables passed to the subprocess.
|
|
373
|
+
*
|
|
374
|
+
* Returns:
|
|
375
|
+
* Promise<SessionGraph>: Validated, merged LLM-extracted Decision & Path Graph.
|
|
376
|
+
*/
|
|
377
|
+
async function extractViaClaudeCli(
|
|
378
|
+
cfg: LabelerConfig,
|
|
379
|
+
input: GraphExtractInput,
|
|
380
|
+
turnTimestamps: ReadonlyMap<string, number>,
|
|
381
|
+
existing: SessionGraph | undefined,
|
|
382
|
+
env: NodeJS.ProcessEnv,
|
|
383
|
+
): Promise<SessionGraph> {
|
|
384
|
+
if (!cfg.model) {
|
|
385
|
+
throw new Error("labeler not configured: set labeler.model in config.json");
|
|
386
|
+
}
|
|
387
|
+
const cmd = cfg.command || "claude";
|
|
388
|
+
const proc = Bun.spawn(
|
|
389
|
+
[
|
|
390
|
+
cmd,
|
|
391
|
+
"-p",
|
|
392
|
+
"--model",
|
|
393
|
+
cfg.model,
|
|
394
|
+
"--no-session-persistence",
|
|
395
|
+
// No user/project/local settings: the owner's CLAUDE.md, hooks and "language" must not shape the graph.
|
|
396
|
+
"--setting-sources",
|
|
397
|
+
"",
|
|
398
|
+
"--tools",
|
|
399
|
+
"",
|
|
400
|
+
"--system-prompt",
|
|
401
|
+
SYSTEM_PROMPT,
|
|
402
|
+
"--output-format",
|
|
403
|
+
"text",
|
|
404
|
+
],
|
|
405
|
+
{
|
|
406
|
+
stdin: "pipe",
|
|
407
|
+
stdout: "pipe",
|
|
408
|
+
stderr: "pipe",
|
|
409
|
+
env,
|
|
410
|
+
},
|
|
411
|
+
);
|
|
412
|
+
proc.stdin.write(JSON.stringify(input));
|
|
413
|
+
proc.stdin.end();
|
|
414
|
+
|
|
415
|
+
let timedOut = false;
|
|
416
|
+
const timer = setTimeout(() => {
|
|
417
|
+
timedOut = true;
|
|
418
|
+
proc.kill();
|
|
419
|
+
}, TIMEOUT_MS);
|
|
420
|
+
timer.unref();
|
|
421
|
+
|
|
422
|
+
try {
|
|
423
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
424
|
+
new Response(proc.stdout).text(),
|
|
425
|
+
new Response(proc.stderr).text(),
|
|
426
|
+
proc.exited,
|
|
427
|
+
]);
|
|
428
|
+
if (timedOut) throw new Error(`claude-cli timed out after ${TIMEOUT_MS}ms`);
|
|
429
|
+
if (exitCode !== 0) {
|
|
430
|
+
const detail = (stderr.trim() || stdout.trim()).slice(0, 240);
|
|
431
|
+
throw new Error(`claude-cli exited ${exitCode}: ${detail}`);
|
|
432
|
+
}
|
|
433
|
+
if (!stdout.trim()) throw new Error("claude-cli returned empty output");
|
|
434
|
+
return parseGraphOutput(stdout, turnTimestamps, existing);
|
|
435
|
+
} finally {
|
|
436
|
+
clearTimeout(timer);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Calls the configured labeler backend (OpenAI-compatible HTTP endpoint or local Claude CLI)
|
|
442
|
+
* to extract the first Decision & Path Graph, or a patch that is merged into the existing one.
|
|
443
|
+
*
|
|
444
|
+
* Args:
|
|
445
|
+
* cfg (LabelerConfig): Provider, endpoint/command, model, and optional apiKeyEnv.
|
|
446
|
+
* input (GraphExtractInput): Redacted turns and optional slim outline of the existing graph.
|
|
447
|
+
* turnTimestamps (ReadonlyMap<string, number>): Known turn timestamps for node ordering.
|
|
448
|
+
* existing (SessionGraph | undefined): Full graph that `input.existingGraph` outlines; the reply
|
|
449
|
+
* is merged into it. Omit for a first graph.
|
|
450
|
+
* env (NodeJS.ProcessEnv): Environment map used to resolve apiKeyEnv or subprocess env.
|
|
451
|
+
*
|
|
452
|
+
* Returns:
|
|
453
|
+
* Promise<SessionGraph>: Validated, merged LLM-extracted Decision & Path Graph.
|
|
454
|
+
*/
|
|
455
|
+
export async function extractGraph(
|
|
456
|
+
cfg: LabelerConfig,
|
|
457
|
+
input: GraphExtractInput,
|
|
458
|
+
turnTimestamps: ReadonlyMap<string, number>,
|
|
459
|
+
existing?: SessionGraph,
|
|
460
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
461
|
+
): Promise<SessionGraph> {
|
|
462
|
+
if (cfg.provider === "claude-cli") {
|
|
463
|
+
return extractViaClaudeCli(cfg, input, turnTimestamps, existing, env);
|
|
464
|
+
}
|
|
465
|
+
if (!cfg.baseUrl || !cfg.model) {
|
|
466
|
+
throw new Error("labeler not configured: set labeler.baseUrl and labeler.model in config.json");
|
|
467
|
+
}
|
|
468
|
+
const headers: Record<string, string> = { "content-type": "application/json" };
|
|
469
|
+
if (cfg.apiKeyEnv) {
|
|
470
|
+
const key = env[cfg.apiKeyEnv];
|
|
471
|
+
if (!key) throw new Error(`labeler.apiKeyEnv names ${cfg.apiKeyEnv}, which is not set`);
|
|
472
|
+
headers.authorization = `Bearer ${key}`;
|
|
473
|
+
}
|
|
474
|
+
const res = await fetch(`${cfg.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
|
|
475
|
+
method: "POST",
|
|
476
|
+
headers,
|
|
477
|
+
body: JSON.stringify({
|
|
478
|
+
model: cfg.model,
|
|
479
|
+
temperature: 0,
|
|
480
|
+
max_tokens: 4096,
|
|
481
|
+
response_format: { type: "json_object" },
|
|
482
|
+
messages: [
|
|
483
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
484
|
+
{ role: "user", content: JSON.stringify(input) },
|
|
485
|
+
],
|
|
486
|
+
}),
|
|
487
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
488
|
+
});
|
|
489
|
+
if (!res.ok) {
|
|
490
|
+
const detail = (await res.text()).slice(0, 200);
|
|
491
|
+
throw new Error(`labeler HTTP ${res.status}: ${detail}`);
|
|
492
|
+
}
|
|
493
|
+
const content = messageContent(await res.json());
|
|
494
|
+
if (typeof content !== "string") throw new Error("labeler response has no message content");
|
|
495
|
+
return parseGraphOutput(content, turnTimestamps, existing);
|
|
496
|
+
}
|
package/src/model.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export type Author = "owner" | "agent";
|
|
2
|
+
|
|
3
|
+
export interface Action {
|
|
4
|
+
tool: string;
|
|
5
|
+
summary: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type Trigger = { from: "owner"; text: string } | { from: "agent"; type: string };
|
|
9
|
+
|
|
10
|
+
export interface Turn {
|
|
11
|
+
id: string;
|
|
12
|
+
author: Author;
|
|
13
|
+
at: number;
|
|
14
|
+
text: string;
|
|
15
|
+
actions: Action[];
|
|
16
|
+
openedBy?: string;
|
|
17
|
+
trigger?: Trigger;
|
|
18
|
+
guest?: true;
|
|
19
|
+
open: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Semantic node categories in the Decision & Path Graph. */
|
|
23
|
+
export type NodeKind = "goal" | "chosen" | "rejected" | "option" | "decision" | "loop" | "side";
|
|
24
|
+
|
|
25
|
+
/** Semantic edge categories connecting decision-graph nodes. */
|
|
26
|
+
export type EdgeKind = "chosen" | "rejected" | "option" | "decision" | "loop" | "side";
|
|
27
|
+
|
|
28
|
+
export interface GraphNode {
|
|
29
|
+
id: string;
|
|
30
|
+
kind: NodeKind;
|
|
31
|
+
/** Short uppercase tag shown in the node header (e.g. "ROOT PROBLEM", "KILLED BY OWNER"). */
|
|
32
|
+
badge: string;
|
|
33
|
+
title: string;
|
|
34
|
+
desc: string;
|
|
35
|
+
/** Heading for the inspector rationale box (e.g. "Why chosen", "Why rejected"). */
|
|
36
|
+
rationaleLabel: string;
|
|
37
|
+
rationale: string;
|
|
38
|
+
/** Source turn IDs that produced this node. */
|
|
39
|
+
turnIds: string[];
|
|
40
|
+
/** Timestamp (ms) of the latest turn contributing to this node. */
|
|
41
|
+
at: number;
|
|
42
|
+
/** Number of collapsed rounds when kind === "loop". */
|
|
43
|
+
rounds?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface GraphEdge {
|
|
47
|
+
id: string;
|
|
48
|
+
from: string;
|
|
49
|
+
to: string;
|
|
50
|
+
kind: EdgeKind;
|
|
51
|
+
label?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SessionGraph {
|
|
55
|
+
title: string;
|
|
56
|
+
nodes: GraphNode[];
|
|
57
|
+
edges: GraphEdge[];
|
|
58
|
+
/** "llm" when produced by the configured LLM extractor; "heuristic" for deterministic fallback. */
|
|
59
|
+
mode: "llm" | "heuristic";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type ServerEvent =
|
|
63
|
+
| { type: "snapshot"; session: string; turns: Turn[]; graph: SessionGraph; labelerError?: string }
|
|
64
|
+
| { type: "turn"; turn: Turn }
|
|
65
|
+
| { type: "graph"; graph: SessionGraph }
|
|
66
|
+
| { type: "labeler"; error?: string }
|
|
67
|
+
| { type: "reset" };
|