pi-dev-flow 0.85.1 → 0.86.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.
@@ -0,0 +1,170 @@
1
+ /** dev-flow runtime — Fresh-session workers (flow_stage): transcripts, pi-web metadata, spawning. Moved out of extensions/dev-flow.ts as is (exports added). */
2
+ import { closeSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, type AgentSession } from "@earendil-works/pi-coding-agent";
5
+ import { digestTranscript, sq, featureTmpDir, type SessionHeaderInfo, type WorkerOp } from "../core.ts";
6
+ import { dfDir, now, sh } from "./base.ts";
7
+
8
+ /** Sessions spawned by flow_stage in this process: they get no [dev-flow] driver context injected
9
+ * (their brief is their whole context) — the guards still judge them like any session. */
10
+ export const workerSessions = new Set<string>();
11
+
12
+ /** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
13
+ export const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"], reflect: ["read", "bash"] };
14
+
15
+ /** Test-only timer override: the smoke suite drives the steer, the hard cut and the salvage grace in ms. */
16
+ export const workerTiming: { softMs?: number; hardMs?: number; graceMs?: number } = {};
17
+
18
+ /** The upstream dev-flow repo's issues in every state, for the reflect brief's dedupe — prefetched so
19
+ * the worker reads a list instead of looping gh searches. null = gh could not answer (the brief then
20
+ * falls back to the search recipe). */
21
+ export async function upstreamIssueList(root: string, repo: string): Promise<{ number: number; title: string; state: string }[] | null> {
22
+ if (!repo || process.env.DEV_FLOW_NO_ISSUES) return null;
23
+ const r = await sh(`gh issue list --repo ${sq(repo)} --state all --json number,title,state --limit 200`, root, 15_000);
24
+ if (!r.ok) return null;
25
+ try {
26
+ const a = JSON.parse(r.out) as { number?: unknown; title?: unknown; state?: unknown }[];
27
+ return Array.isArray(a) ? a.filter((i) => Number.isInteger(i?.number)).map((i) => ({ number: Number(i.number), title: String(i.title ?? ""), state: String(i.state ?? "") })) : null;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /** Seam: the smoke suite stubs the prefetch instead of calling gh against the real upstream. */
34
+ export const reflectSeams = { upstreamIssues: upstreamIssueList };
35
+
36
+ /** Build the reflect worker's transcript digests in the feature's scratch dir (driver first). A
37
+ * transcript that cannot be read is skipped — the brief still names the raw file. */
38
+ export function writeTranscriptDigests(root: string, slug: string, files: string[]): { transcript: string; digest: string }[] {
39
+ const dir = path.join(featureTmpDir(dfDir(root), slug), "reflect");
40
+ const out: { transcript: string; digest: string }[] = [];
41
+ for (const f of files) {
42
+ try {
43
+ mkdirSync(dir, { recursive: true });
44
+ const digest = path.join(dir, `${path.basename(f, ".jsonl")}.digest.txt`);
45
+ writeFileSync(digest, digestTranscript(readFileSync(f, "utf8")));
46
+ out.push({ transcript: f, digest });
47
+ } catch { /* unreadable transcript: the raw path stays in the brief */ }
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** Line 1 of every pi session file in `dir` — the header that names a worker's parent session. A
53
+ * file is read up to its first newline only (transcripts grow large); unreadable files are skipped. */
54
+ export function sessionHeaders(dir: string | undefined): SessionHeaderInfo[] {
55
+ if (!dir) return [];
56
+ let names: string[];
57
+ try { names = readdirSync(dir).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
58
+ const out: SessionHeaderInfo[] = [];
59
+ for (const n of names) {
60
+ const file = path.join(dir, n);
61
+ try {
62
+ const fd = openSync(file, "r");
63
+ try {
64
+ const buf = Buffer.alloc(16_384);
65
+ const len = readSync(fd, buf, 0, buf.length, 0);
66
+ const first = buf.subarray(0, len).toString("utf8").split("\n")[0];
67
+ const h = JSON.parse(first) as { type?: unknown; parentSession?: unknown };
68
+ if (h?.type === "session") out.push({ file, parentSession: typeof h.parentSession === "string" ? h.parentSession : undefined });
69
+ } finally { closeSync(fd); }
70
+ } catch { /* not a session file, or a header past the read window: skip */ }
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** What makes a worker show up in pi-web's Agents menu: pi-web classifies a subagent from the
76
+ * custom entries its own runtime writes into the child's session file (pi-web lib/subagents.ts
77
+ * readSubagentRun, fed by lib/session-reader.ts). Two placement rules the reader enforces:
78
+ * the meta entry must be the file's FIRST data entry (the scanner reads header + one line and
79
+ * calls anything else a fork), and a persisted `running` the host cannot prove live displays as
80
+ * `interrupted` — so while a worker runs it also claims a slot in pi-web's live run map
81
+ * (piwebLiveClaim), and the final result entry settles the row after.
82
+ * Unknown entry types are inert in plain pi, so stamping is unconditional. */
83
+ export const PIWEB_SUBAGENT = { meta: "pi-web:subagent", status: "pi-web:subagent-status", result: "pi-web:subagent-result" } as const;
84
+
85
+ export interface WorkerSubagentMeta {
86
+ parentId: string;
87
+ parentFile: string;
88
+ toolCallId: string;
89
+ profile: string;
90
+ description: string;
91
+ task: string;
92
+ }
93
+
94
+ /** Only version 1 + the two lineage strings are hard-validated by pi-web's reader; the rest is
95
+ * display. resourceSnapshot is deliberately absent: its presence pins the tool set strictly when
96
+ * pi-web reopens the child, and these workers are never resumed by pi-web. */
97
+ export function piwebWorkerMeta(m: WorkerSubagentMeta): Record<string, unknown> {
98
+ return {
99
+ version: 1,
100
+ parentSessionId: m.parentId,
101
+ parentSessionPath: m.parentFile,
102
+ parentToolCallId: m.toolCallId,
103
+ profile: m.profile,
104
+ description: m.description,
105
+ task: m.task,
106
+ runInBackground: false,
107
+ createdAt: now(),
108
+ };
109
+ }
110
+
111
+ /** Best-effort by contract: a stamp that will not write must never break the worker run —
112
+ * visibility, not function (same rule as the worker's setSessionName renames). */
113
+ export function piwebStamp(target: { appendCustomEntry?(customType: string, data?: unknown): unknown } | undefined, customType: string, data: unknown): void {
114
+ try { target?.appendCustomEntry?.(customType, data); } catch { /* visibility only */ }
115
+ }
116
+
117
+ /** pi-web proves a subagent live only from its own in-process tables (rpc-manager.ts
118
+ * subagentDisplayStatus: its session registry, or globalThis.__piSubagentRuns); anything else with
119
+ * a persisted `running` reads `interrupted`. pi-web hosts extensions in its server process, so the
120
+ * worker claims a slot in that map for the run — pi-web's private global, used only when pi-web
121
+ * created it (never created here: plain pi stays untouched, and a pi-web without it keeps the old
122
+ * mid-run `interrupted`). Side effects: the driver counts as having an unsettled subagent while the
123
+ * tool call runs (it is mid-call anyway); Stop/steer from the Agents menu still answer "not running",
124
+ * since pi-web holds no wrapper for this child — the driver's Stop aborts it. Returns an idempotent
125
+ * release that drops the slot only if it still holds this claim (pi-web's dropSubagentRun rule). */
126
+ export function piwebLiveClaim(sm: { getSessionId?(): string; getSessionFile?(): string | undefined } | undefined, m: WorkerSubagentMeta): (status: string) => void {
127
+ try {
128
+ const runs = (globalThis as { __piSubagentRuns?: unknown }).__piSubagentRuns;
129
+ const sessionId = sm?.getSessionId?.();
130
+ if (!(runs instanceof Map) || !sessionId) return () => {};
131
+ let settle: (run: unknown) => void = () => {};
132
+ const run = { sessionId, sessionPath: sm?.getSessionFile?.() ?? "", parentSessionId: m.parentId, parentToolCallId: m.toolCallId, profile: m.profile, description: m.description, task: m.task, runInBackground: false, status: "running", createdAt: now() };
133
+ const stored = { run, completion: new Promise((resolve) => { settle = resolve; }), abortRequested: false, dispatchedAt: Date.now() };
134
+ runs.set(sessionId, stored);
135
+ let released = false;
136
+ return (status) => {
137
+ if (released) return;
138
+ released = true;
139
+ try { if (runs.get(sessionId) === stored) runs.delete(sessionId); settle({ ...run, status, completedAt: now() }); } catch { /* visibility only */ }
140
+ };
141
+ } catch { return () => {}; }
142
+ }
143
+
144
+ /** The worker's display name — the Agents row and the session name: `<glyph> <slug> <what>`. The
145
+ * model's label often repeats the slug ("flow-list-widget review"), so the slug and stray separators
146
+ * are cut from it; with nothing left the op names the run. */
147
+ export function workerName(glyph: string, slug: string, op: string, label: unknown): string {
148
+ const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
149
+ const what = String(label ?? "").replace(/[\r\n]+/g, " ").replace(new RegExp(esc, "gi"), " ")
150
+ .replace(/^[\s·:|/,-]+|[\s·:|/,-]+$/g, "").replace(/\s{2,}/g, " ").slice(0, 40).trim();
151
+ return `${glyph} ${slug} ${what || op}`;
152
+ }
153
+
154
+ /** Seam that spawns a worker as a real pi session — tests replace `.run`. With the driver's session
155
+ * file and directory known, the worker's header links back to the driver (`parentSession`), so pi's
156
+ * picker nests it under the driver, and the pi-web meta lands as the file's first data entry. */
157
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string; subagent?: WorkerSubagentMeta }) => Promise<AgentSession> } = {
158
+ run: async ({ work, model, name, tools, parent, dir, subagent }) => {
159
+ const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
160
+ await loader.reload();
161
+ const sessionManager = parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
162
+ // The meta must be stamped here — before createAgentSession appends model_change/session_info,
163
+ // because pi-web's scanner classifies the child only from the first data entry after the header.
164
+ if (sessionManager && subagent) piwebStamp(sessionManager, PIWEB_SUBAGENT.meta, piwebWorkerMeta(subagent));
165
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
166
+ try { workerSessions.add(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the default context */ }
167
+ try { session.setSessionName(name); } catch { /* naming is visibility, not function */ }
168
+ return session;
169
+ },
170
+ };