@maheidem/pi-delegate 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/rpc-jsonl.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * delegate — strict LF-delimited JSONL parser for child RPC stdout
3
+ * (NFR-003: NEVER Node's `readline`).
4
+ *
5
+ * Rules (§9.7):
6
+ * - split only on LF (\n);
7
+ * - strip ONE trailing CR per record (CRLF children tolerated);
8
+ * - U+2028/U+2029 inside JSON strings stay data (no line-based splitting);
9
+ * - incomplete final buffer retained until the next chunk or close();
10
+ * - maximum individual record size (default 8 MiB) → oversize diagnostic;
11
+ * - malformed records are classified diagnostics, never silently dropped;
12
+ * - bounded malformed threshold → protocol failure.
13
+ */
14
+
15
+ export interface RpcRecord {
16
+ /** Exact record bytes before the delimiter (CR already stripped). */
17
+ raw: Buffer;
18
+ /** Parsed JSON value, or null when the record is malformed. */
19
+ parsed: unknown;
20
+ malformed: boolean;
21
+ }
22
+
23
+ export type RpcRecordClassification =
24
+ | { kind: "prompt_response"; ok: boolean; id: string }
25
+ | { kind: "message_end"; stopReason?: string }
26
+ | { kind: "tool_event"; phase: "start" | "update" | "end"; toolName?: string }
27
+ | { kind: "agent_settled" }
28
+ | { kind: "agent_end" }
29
+ | { kind: "extension_ui_request"; id: string }
30
+ | { kind: "extension_error" }
31
+ | { kind: "unknown"; type?: string }
32
+ | { kind: "malformed" };
33
+
34
+ export interface RpcParserOptions {
35
+ maxRecordBytes?: number;
36
+ malformedThreshold?: number;
37
+ onOversized?: (size: number) => void;
38
+ onMalformed?: (raw: Buffer, index: number) => void;
39
+ }
40
+
41
+ export const DEFAULT_MAX_RECORD_BYTES = 8 * 1024 * 1024; // 8 MiB
42
+ export const DEFAULT_MALFORMED_THRESHOLD = 10;
43
+
44
+ export class RpcJsonlParser {
45
+ private buffer: Buffer = Buffer.alloc(0);
46
+ private malformedCount = 0;
47
+ private readonly maxRecordBytes: number;
48
+ private readonly malformedThreshold: number;
49
+ private readonly onOversized?: (size: number) => void;
50
+ private readonly onMalformed?: (raw: Buffer, index: number) => void;
51
+ private recordIndex = 0;
52
+ /** True once an oversized record was observed (fatal by contract). */
53
+ oversized = false;
54
+
55
+ constructor(options: RpcParserOptions = {}) {
56
+ this.maxRecordBytes = options.maxRecordBytes ?? DEFAULT_MAX_RECORD_BYTES;
57
+ this.malformedThreshold = options.malformedThreshold ?? DEFAULT_MALFORMED_THRESHOLD;
58
+ this.onOversized = options.onOversized;
59
+ this.onMalformed = options.onMalformed;
60
+ }
61
+
62
+ get malformedRecords(): number {
63
+ return this.malformedCount;
64
+ }
65
+
66
+ get exceededMalformedThreshold(): boolean {
67
+ return this.malformedCount > this.malformedThreshold;
68
+ }
69
+
70
+ /** Feed a stdout chunk; returns zero or more complete records. */
71
+ feed(chunk: Buffer | string): RpcRecord[] {
72
+ const incoming = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
73
+ this.buffer = this.buffer.length === 0 ? incoming : Buffer.concat([this.buffer, incoming]);
74
+ const out: RpcRecord[] = [];
75
+
76
+ for (;;) {
77
+ const lf = this.buffer.indexOf(0x0a); // LF only
78
+ if (lf === -1) break;
79
+ let recordBytes = this.buffer.subarray(0, lf);
80
+ // Strip ONE trailing CR (CRLF tolerance). U+2028/2029 are 0xE2
81
+ // 0x80 0xA8/0xA9 in UTF-8 and are never 0x0d — safe.
82
+ if (recordBytes.length > 0 && recordBytes[recordBytes.length - 1] === 0x0d) {
83
+ recordBytes = recordBytes.subarray(0, recordBytes.length - 1);
84
+ }
85
+ this.buffer = this.buffer.subarray(lf + 1);
86
+ out.push(this.acceptRecord(recordBytes));
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /** Flush any incomplete final record (captured on process close). */
92
+ close(): RpcRecord[] {
93
+ if (this.buffer.length === 0) return [];
94
+ const recordBytes = this.buffer;
95
+ this.buffer = Buffer.alloc(0);
96
+ return [this.acceptRecord(recordBytes)];
97
+ }
98
+
99
+ private acceptRecord(raw: Buffer): RpcRecord {
100
+ const size = raw.length;
101
+ if (size > this.maxRecordBytes) {
102
+ this.oversized = true;
103
+ this.onOversized?.(size);
104
+ return { raw, parsed: null, malformed: true };
105
+ }
106
+ const index = this.recordIndex++;
107
+ let parsed: unknown;
108
+ let malformed = false;
109
+ try {
110
+ parsed = JSON.parse(raw.toString("utf8"));
111
+ } catch {
112
+ parsed = null;
113
+ malformed = true;
114
+ this.malformedCount += 1;
115
+ this.onMalformed?.(raw, index);
116
+ }
117
+ return { raw, parsed, malformed };
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Classify one parsed RPC record into a semantic action for the runner.
123
+ * Unknown-but-valid events return kind "unknown" and MUST still be
124
+ * persisted; they are ignored semantically only.
125
+ */
126
+ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
127
+ if (record.malformed || !record.parsed || typeof record.parsed !== "object") {
128
+ return { kind: "malformed" };
129
+ }
130
+ const obj = record.parsed as Record<string, unknown>;
131
+ switch (obj.type) {
132
+ case "response": {
133
+ const ok = obj.error === undefined && obj.success !== false;
134
+ return { kind: "prompt_response", ok, id: typeof obj.id === "string" ? obj.id : "" };
135
+ }
136
+ case "message_end": {
137
+ const message = (obj.message ?? {}) as Record<string, unknown>;
138
+ return {
139
+ kind: "message_end",
140
+ stopReason: typeof message.stopReason === "string" ? message.stopReason : undefined,
141
+ };
142
+ }
143
+ case "tool_execution_start":
144
+ return {
145
+ kind: "tool_event",
146
+ phase: "start",
147
+ toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
148
+ };
149
+ case "tool_execution_update":
150
+ return {
151
+ kind: "tool_event",
152
+ phase: "update",
153
+ toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
154
+ };
155
+ case "tool_execution_end":
156
+ return {
157
+ kind: "tool_event",
158
+ phase: "end",
159
+ toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
160
+ };
161
+ case "agent_settled":
162
+ return { kind: "agent_settled" };
163
+ case "agent_end":
164
+ return { kind: "agent_end" };
165
+ case "extension_ui_request":
166
+ return { kind: "extension_ui_request", id: typeof obj.id === "string" ? obj.id : "" };
167
+ case "extension_error":
168
+ return { kind: "extension_error" };
169
+ default:
170
+ return { kind: "unknown", type: typeof obj.type === "string" ? obj.type : undefined };
171
+ }
172
+ }
package/run-store.ts ADDED
@@ -0,0 +1,326 @@
1
+ /**
2
+ * delegate — private run-store: paths, permissions, atomic metadata,
3
+ * append-only evidence streams, retention, orphan recovery.
4
+ *
5
+ * Directory mode 0700, file mode 0600 (POL-006). Raw stdout JSONL and
6
+ * stderr are append-only; metadata is atomically replaced on transitions.
7
+ * Terminal states are immutable: a replacement may add final diagnostics
8
+ * but never moves one terminal state to another (§9.1).
9
+ */
10
+
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+ import * as crypto from "node:crypto";
14
+ import type {
15
+ DelegatePaths,
16
+ DelegateRequest,
17
+ RunMetadataV1,
18
+ RunState,
19
+ TranscriptRecordV1,
20
+ } from "./types.ts";
21
+ import { EMPTY_USAGE, isTerminalRunState } from "./types.ts";
22
+ import { atomicWriteJson } from "./config.ts";
23
+
24
+ export function makeRunId(now: Date = new Date()): string {
25
+ // del_<UTC-basic-timestamp>_<8-random-hex>, e.g. del_20260901T143022Z_a1b2c3d4
26
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
27
+ const hex = crypto.randomBytes(4).toString("hex");
28
+ return `del_${stamp}_${hex}`;
29
+ }
30
+
31
+ export function runPaths(agentDir: string, runId: string): DelegatePaths & {
32
+ metadataPath: string;
33
+ transcriptPath: string;
34
+ stderrPath: string;
35
+ } {
36
+ const runsDir = path.join(agentDir, "delegate", "runs");
37
+ return {
38
+ agentDir,
39
+ configPath: path.join(agentDir, "delegate", "config.json"),
40
+ runsDir,
41
+ metadataPath: path.join(runsDir, `${runId}.json`),
42
+ transcriptPath: path.join(runsDir, `${runId}.jsonl`),
43
+ stderrPath: path.join(runsDir, `${runId}.stderr.log`),
44
+ };
45
+ }
46
+
47
+ export function pathsForAgentDir(agentDir: string): DelegatePaths {
48
+ const p = runPaths(agentDir, "");
49
+ return { agentDir, configPath: p.configPath, runsDir: p.runsDir };
50
+ }
51
+
52
+ function ensurePrivateDir(dir: string): void {
53
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ // mkdir mode does not re-tighten existing directories; enforce 0700.
55
+ try {
56
+ fs.chmodSync(dir, 0o700);
57
+ } catch {
58
+ // best effort on platforms without POSIX chmod semantics
59
+ }
60
+ }
61
+
62
+ function assertSafeRunId(runId: string): void {
63
+ if (!/^del_[0-9TZ]+_[0-9a-f]{8}$/.test(runId)) {
64
+ throw new Error(`E_STORE: unsafe run id '${runId}'`);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Create a new run: metadata (created) + open append streams BEFORE spawn
70
+ * so startup output is never lost. The caller owns the returned handles
71
+ * and MUST close them in finally.
72
+ */
73
+ export interface OpenedRun {
74
+ metadata: RunMetadataV1;
75
+ paths: ReturnType<typeof runPaths>;
76
+ stdout: fs.WriteStream;
77
+ stderr: fs.WriteStream;
78
+ }
79
+
80
+ export function openRun(agentDir: string, request: DelegateRequest): OpenedRun {
81
+ const runId = makeRunId();
82
+ const paths = runPaths(agentDir, runId);
83
+ ensurePrivateDir(paths.runsDir);
84
+
85
+ const metadata: RunMetadataV1 = {
86
+ schemaVersion: 1,
87
+ runId,
88
+ state: "created",
89
+ role: request.role,
90
+ source: request.source,
91
+ cwd: request.cwd,
92
+ task: request.task,
93
+ taskSha256: crypto.createHash("sha256").update(request.task, "utf8").digest("hex"),
94
+ model: request.parentModel,
95
+ thinkingLevel: request.thinkingLevel,
96
+ createdAt: new Date().toISOString(),
97
+ usage: { ...EMPTY_USAGE },
98
+ transcriptPath: paths.transcriptPath,
99
+ stderrPath: paths.stderrPath,
100
+ };
101
+ atomicWriteJson(paths.metadataPath, metadata);
102
+
103
+ const stdout = openAppendStream(paths.transcriptPath);
104
+ const stderr = openAppendStream(paths.stderrPath);
105
+ return { metadata, paths, stdout, stderr };
106
+ }
107
+
108
+ export function openAppendStream(filePath: string): fs.WriteStream {
109
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
110
+ // Open synchronously so fd exists before the first append — evidence is
111
+ // durable even if completion is read immediately after finalize.
112
+ const fd = fs.openSync(filePath, "a", 0o600);
113
+ const mk = fs.createWriteStream as unknown as (
114
+ source: unknown,
115
+ options: { fd: number; autoClose: boolean },
116
+ ) => fs.WriteStream;
117
+ return mk(undefined, { fd, autoClose: true });
118
+ }
119
+
120
+ /**
121
+ * Append one captured raw stdout record to the transcript envelope.
122
+ * Synchronous (O_APPEND) so evidence is durable before completion signals
123
+ * are surfaced (§9). Returns the bytes written.
124
+ */
125
+ export function appendTranscriptRecord(
126
+ stdoutStream: fs.WriteStream,
127
+ sequence: number,
128
+ receivedAt: string,
129
+ rawBytes: Buffer,
130
+ ): void {
131
+ const record: TranscriptRecordV1 = {
132
+ schemaVersion: 1,
133
+ sequence,
134
+ receivedAt,
135
+ stream: "stdout",
136
+ rawBase64: rawBytes.toString("base64"),
137
+ };
138
+ const line = JSON.stringify(record) + "\n";
139
+ const fd = (stdoutStream as unknown as { fd: number | null }).fd;
140
+ if (typeof fd === "number") {
141
+ fs.appendFileSync(fd, line, "utf8");
142
+ } else {
143
+ stdoutStream.write(line);
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Atomically replace run metadata. Terminal states are immutable:
149
+ * `next.state` must equal the current terminal state when the run is
150
+ * already terminal (additional diagnostics may still be merged).
151
+ */
152
+ export function updateRunMetadata(
153
+ agentDir: string,
154
+ runId: string,
155
+ mutate: (current: RunMetadataV1) => Partial<RunMetadataV1>,
156
+ ): RunMetadataV1 {
157
+ assertSafeRunId(runId);
158
+ const paths = runPaths(agentDir, runId);
159
+ let current: RunMetadataV1;
160
+ try {
161
+ current = JSON.parse(fs.readFileSync(paths.metadataPath, "utf8")) as RunMetadataV1;
162
+ } catch {
163
+ throw new Error(`E_STORE: metadata missing for run ${runId}`);
164
+ }
165
+ const patch = mutate(current);
166
+ if (
167
+ patch.state !== undefined &&
168
+ isTerminalRunState(current.state) &&
169
+ patch.state !== current.state &&
170
+ isTerminalRunState(patch.state)
171
+ ) {
172
+ throw new Error(`E_STORE: terminal state ${current.state} is immutable for run ${runId}`);
173
+ }
174
+ const next: RunMetadataV1 = { ...current, ...patch };
175
+ atomicWriteJson(paths.metadataPath, next);
176
+ return next;
177
+ }
178
+
179
+ export function readRunMetadata(agentDir: string, runId: string): RunMetadataV1 | null {
180
+ assertSafeRunId(runId);
181
+ const paths = runPaths(agentDir, runId);
182
+ try {
183
+ return JSON.parse(fs.readFileSync(paths.metadataPath, "utf8")) as RunMetadataV1;
184
+ } catch {
185
+ return null;
186
+ }
187
+ }
188
+
189
+ export interface RunSummary {
190
+ runId: string;
191
+ state: RunState;
192
+ role: RunMetadataV1["role"];
193
+ createdAt: string;
194
+ startedAt?: string;
195
+ finishedAt?: string;
196
+ durationMs?: number;
197
+ mtimeMs: number;
198
+ }
199
+
200
+ /** List runs newest-first (by metadata mtime, falling back to createdAt). */
201
+ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
202
+ const p = pathsForAgentDir(agentDir);
203
+ let names: string[];
204
+ try {
205
+ names = fs.readdirSync(p.runsDir);
206
+ } catch {
207
+ return [];
208
+ }
209
+ const summaries: RunSummary[] = [];
210
+ for (const name of names) {
211
+ const match = /^(del_[0-9TZ]+_[0-9a-f]{8})\.json$/;
212
+ const m = name.match(match);
213
+ if (!m) continue;
214
+ const runId = m[1];
215
+ try {
216
+ const meta = JSON.parse(
217
+ fs.readFileSync(path.join(p.runsDir, name), "utf8"),
218
+ ) as RunMetadataV1;
219
+ if (meta.schemaVersion !== 1 || typeof meta.runId !== "string") continue;
220
+ let mtimeMs = 0;
221
+ try {
222
+ mtimeMs = fs.statSync(path.join(p.runsDir, name)).mtimeMs;
223
+ } catch {
224
+ mtimeMs = 0;
225
+ }
226
+ summaries.push({
227
+ runId,
228
+ state: meta.state,
229
+ role: meta.role,
230
+ createdAt: meta.createdAt,
231
+ startedAt: meta.startedAt,
232
+ finishedAt: meta.finishedAt,
233
+ durationMs:
234
+ meta.startedAt && meta.finishedAt
235
+ ? Date.parse(meta.finishedAt) - Date.parse(meta.startedAt)
236
+ : undefined,
237
+ mtimeMs,
238
+ });
239
+ } catch {
240
+ // unreadable metadata: leave alone; retention will not touch it
241
+ }
242
+ }
243
+ summaries.sort((a, b) => b.mtimeMs - a.mtimeMs || (b.createdAt > a.createdAt ? 1 : -1));
244
+ return summaries.slice(0, limit);
245
+ }
246
+
247
+ /**
248
+ * Startup orphan recovery (§10.6): nonterminal metadata with no owned
249
+ * process becomes `crashed` with E_ORPHANED_RUN. This process NEVER kills
250
+ * a PID found in stale metadata. Returns the touched run IDs.
251
+ */
252
+ export function markOrphanedRuns(agentDir: string): string[] {
253
+ const touched: string[] = [];
254
+ for (const summary of listRuns(agentDir)) {
255
+ if (isTerminalRunState(summary.state)) continue;
256
+ try {
257
+ const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
258
+ state: "crashed",
259
+ errorCode: "E_ORPHANED_RUN",
260
+ errorMessage: "Run store started with this run nonterminal and no owned child process.",
261
+ finishedAt: current.finishedAt ?? new Date().toISOString(),
262
+ }));
263
+ if (next.state === "crashed") touched.push(summary.runId);
264
+ } catch {
265
+ // skip
266
+ }
267
+ }
268
+ return touched;
269
+ }
270
+
271
+ /**
272
+ * Retention (§10.6): remove oldest terminal runs until BOTH maxRuns and
273
+ * maxRunAgeDays are satisfied. Never removes active/nonterminal runs from
274
+ * the current process (pass `protectedRunId`) or files that cannot be
275
+ * confidently associated with a valid run ID. Failures are warning-only.
276
+ */
277
+ export function enforceRetention(
278
+ agentDir: string,
279
+ maxRuns: number,
280
+ maxRunAgeDays: number,
281
+ protectedRunId?: string,
282
+ ): { removed: number; warnings: string[] } {
283
+ const warnings: string[] = [];
284
+ let removed = 0;
285
+ const p = pathsForAgentDir(agentDir);
286
+ let all: RunSummary[];
287
+ try {
288
+ all = listRuns(agentDir, 10_000);
289
+ } catch (error) {
290
+ return { removed: 0, warnings: [`E_STORE: could not list runs: ${(error as Error).message}`] };
291
+ }
292
+
293
+ const now = Date.now();
294
+ const ageCutoff = now - maxRunAgeDays * 86_400_000;
295
+
296
+ // Terminal, non-protected runs, oldest first — two independent rules:
297
+ // age (older than cutoff) and count (oldest surplus beyond maxRuns).
298
+ const ordered = all
299
+ .filter((s) => isTerminalRunState(s.state) && s.runId !== protectedRunId)
300
+ .sort((a, b) => a.mtimeMs - b.mtimeMs || (a.createdAt < b.createdAt ? -1 : 1));
301
+
302
+ const terminalCount = all.filter((s) => isTerminalRunState(s.state)).length;
303
+ const surplus = Math.max(0, terminalCount - maxRuns);
304
+ const ageRemove = ordered.filter((s) => new Date(s.createdAt).getTime() < ageCutoff);
305
+ const countRemove = ordered.slice(0, surplus);
306
+ const toRemove = [...new Set([...ageRemove, ...countRemove])];
307
+
308
+ for (const candidate of toRemove) {
309
+ const files = [
310
+ path.join(p.runsDir, `${candidate.runId}.json`),
311
+ path.join(p.runsDir, `${candidate.runId}.jsonl`),
312
+ path.join(p.runsDir, `${candidate.runId}.stderr.log`),
313
+ ];
314
+ try {
315
+ for (const file of files) {
316
+ if (fs.existsSync(file)) fs.unlinkSync(file);
317
+ }
318
+ removed += 1;
319
+ } catch (error) {
320
+ warnings.push(
321
+ `E_STORE: retention could not remove ${candidate.runId}: ${(error as Error).message}`,
322
+ );
323
+ }
324
+ }
325
+ return { removed, warnings };
326
+ }