pi-better-subagents 0.30.0 → 0.32.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/README.md +13 -0
- package/assignment-outcomes.ts +157 -0
- package/assignment-projection.d.mts +14 -0
- package/assignment-projection.mjs +109 -0
- package/cleanup.ts +12 -0
- package/docs/usage.md +14 -0
- package/finalization.ts +2 -0
- package/health-surface.mjs +2 -0
- package/historical-attention.ts +35 -0
- package/index.ts +206 -48
- package/list.mjs +7 -1
- package/navigator.mjs +23 -10
- package/outage-observations.ts +73 -0
- package/output-payload.ts +25 -6
- package/package.json +3 -1
- package/registry.ts +16 -3
- package/session-store.ts +1 -1
- package/shared-callback-batcher.ts +8 -3
- package/shared-operation-coordinator/assignment-observation.mjs +43 -0
- package/shared-operation-coordinator/index.ts +5 -0
- package/shared-operation-coordinator/src/assignment-outcomes.ts +172 -0
- package/shared-operation-coordinator/src/discovery.ts +128 -0
- package/shared-operation-coordinator/src/errors.ts +2 -0
- package/shared-operation-coordinator/src/operations.ts +88 -6
- package/shared-operation-coordinator/src/outbox.ts +11 -2
- package/shared-operation-coordinator/src/recovery.ts +55 -0
- package/shared-operation-coordinator/src/rows.ts +2 -1
- package/shared-operation-coordinator/src/schema.ts +114 -2
- package/shared-operation-coordinator/src/store.ts +83 -1
- package/shared-operation-coordinator/src/types.ts +46 -1
- package/shared-operation-coordinator/src/waits.ts +47 -5
- package/task-policy.ts +2 -0
- package/tools.ts +24 -7
- package/worker-waits.ts +258 -94
package/navigator.mjs
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* with visible-width-aware truncation.
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
|
+
import { assignmentFor } from "./assignment-projection.mjs";
|
|
27
28
|
import {
|
|
28
29
|
formatNavigatorHealthFacts,
|
|
29
30
|
statusThemeColor,
|
|
@@ -42,6 +43,11 @@ export const NAVIGATOR_STATUS_KEY = "subagents-nav";
|
|
|
42
43
|
|
|
43
44
|
export const CLOSE_CONFIRM_STATUS_KEY = "subagents-close";
|
|
44
45
|
|
|
46
|
+
function isStoppableView(row) {
|
|
47
|
+
const processStatus = row?.assignment?.processStatus ?? row?.attemptStatus ?? row?.status;
|
|
48
|
+
return processStatus === "running" || processStatus === "orphaned";
|
|
49
|
+
}
|
|
50
|
+
|
|
45
51
|
/** Legacy footer helpers no longer write status. */
|
|
46
52
|
export function navigatorFooterHint(count) {
|
|
47
53
|
return null;
|
|
@@ -64,7 +70,7 @@ export function applyNavigatorFooter(ui, count) {
|
|
|
64
70
|
export function closeConfirmHint(row) {
|
|
65
71
|
if (!row) return null;
|
|
66
72
|
const label = (row.name != null && String(row.name).length > 0) ? String(row.name) : String(row.id);
|
|
67
|
-
const stoppable = row
|
|
73
|
+
const stoppable = isStoppableView(row);
|
|
68
74
|
return stoppable ? `x again to stop ${label}` : `x again to dismiss ${label}`;
|
|
69
75
|
}
|
|
70
76
|
|
|
@@ -182,20 +188,18 @@ export function pendingNavigatorPark(meta) {
|
|
|
182
188
|
return park?.version === 1 && ["parking", "waiting", "ready", "resuming", "held"].includes(park.phase) ? park : undefined;
|
|
183
189
|
}
|
|
184
190
|
|
|
185
|
-
function navigatorDisplayStatus(meta, status) {
|
|
186
|
-
return status === "running" || status === "orphaned" ? status : pendingNavigatorPark(meta)?.phase ?? status;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
191
|
export function buildNavigatorRows(metas, deps) {
|
|
190
192
|
const now = deps.now ?? Date.now();
|
|
191
193
|
return metas.map((m) => {
|
|
192
|
-
const
|
|
194
|
+
const assignment = assignmentFor(m, deps.effectiveStatus(m));
|
|
195
|
+
const status = assignment.state;
|
|
193
196
|
const health = typeof deps.healthFor === "function" ? deps.healthFor(m) : undefined;
|
|
194
197
|
const effort = typeof deps.effortFor === "function" ? deps.effortFor(m) : (m.effort ?? m.modelEffort);
|
|
195
198
|
const tool = typeof deps.toolFor === "function" ? (deps.toolFor(m) || "") : "";
|
|
196
199
|
return {
|
|
197
200
|
id: m.id,
|
|
198
201
|
name: m.name,
|
|
202
|
+
assignment,
|
|
199
203
|
status,
|
|
200
204
|
model: deps.shortModel(m.model),
|
|
201
205
|
// Optional effort stays adjacent to model when the host exposes it.
|
|
@@ -332,7 +336,7 @@ export function buildNavigatorLines(state, opts = {}) {
|
|
|
332
336
|
const rows = state.rows ?? [];
|
|
333
337
|
const lines = [commandSheetRule(`Subagents · ${rows.length}`, width)];
|
|
334
338
|
const selected = rows.length > 0 ? rows[state.selected] : null;
|
|
335
|
-
const stoppable = selected
|
|
339
|
+
const stoppable = isStoppableView(selected);
|
|
336
340
|
const action = stoppable ? "x stop" : (selected ? "x dismiss" : null);
|
|
337
341
|
lines.push(` ${["↑↓ select", "Enter view", action, "Esc close"].filter(Boolean).join(" · ")}`);
|
|
338
342
|
lines.push("");
|
|
@@ -383,7 +387,8 @@ export function buildNavigatorDetail(id, deps) {
|
|
|
383
387
|
const now = deps.now ?? Date.now();
|
|
384
388
|
const parsed = deps.parseRun(id);
|
|
385
389
|
const toolCalls = parsed.toolCalls ?? [];
|
|
386
|
-
const
|
|
390
|
+
const assignment = assignmentFor(meta, deps.effectiveStatus(meta));
|
|
391
|
+
const status = assignment.state;
|
|
387
392
|
const running = status === "running" || status === "orphaned";
|
|
388
393
|
const health = typeof deps.healthFor === "function" ? deps.healthFor(meta) : undefined;
|
|
389
394
|
const effortRaw = typeof deps.effortFor === "function"
|
|
@@ -395,6 +400,7 @@ export function buildNavigatorDetail(id, deps) {
|
|
|
395
400
|
role: meta.catalog?.roleName || (meta.catalog?.roleId ? String(meta.catalog.roleId).replace(/^role\./, "") : undefined) || undefined,
|
|
396
401
|
park: pendingNavigatorPark(meta),
|
|
397
402
|
attemptStatus: deps.effectiveStatus(meta),
|
|
403
|
+
assignment,
|
|
398
404
|
status,
|
|
399
405
|
model: deps.shortModel(meta.model),
|
|
400
406
|
effort: effortRaw ? String(effortRaw) : undefined,
|
|
@@ -475,11 +481,17 @@ export function buildDetailLines(detail, opts = {}) {
|
|
|
475
481
|
const statusRaw = String(detail.status ?? "?");
|
|
476
482
|
const statusText = colorize ? fg(statusThemeColor(statusRaw), statusRaw) : statusRaw;
|
|
477
483
|
|
|
478
|
-
const stoppable = detail
|
|
484
|
+
const stoppable = isStoppableView(detail);
|
|
479
485
|
const action = stoppable ? "x stop" : "x dismiss";
|
|
480
486
|
lines.push(` ← back · ${action} · Esc close`);
|
|
481
487
|
lines.push("");
|
|
482
488
|
lines.push(` status ${statusText}`);
|
|
489
|
+
if (detail.assignment) {
|
|
490
|
+
lines.push(` revision ${detail.assignment.revision}`);
|
|
491
|
+
lines.push(` reason ${detail.assignment.reason}`);
|
|
492
|
+
lines.push(` process ${detail.assignment.processStatus}; termination ${detail.assignment.termination}`);
|
|
493
|
+
for (const ref of detail.assignment.evidence) lines.push(` evidence ${ref}`);
|
|
494
|
+
}
|
|
483
495
|
lines.push(` id ${detail.id ?? "?"}`);
|
|
484
496
|
if (detail.role) lines.push(` role ${detail.role}`);
|
|
485
497
|
|
|
@@ -509,6 +521,7 @@ export function buildDetailLines(detail, opts = {}) {
|
|
|
509
521
|
// detail header already shows a non-running effective status (legacy
|
|
510
522
|
// dead-running metadata → effective "exited" must read as terminal).
|
|
511
523
|
let live = h?.process?.liveness;
|
|
524
|
+
if (detail.assignment) live = `${detail.assignment.processStatus}; termination ${detail.assignment.termination}`;
|
|
512
525
|
if (!live || (detail.status !== "running" && live === "supervised")) {
|
|
513
526
|
live = detail.status === "orphaned" ? "orphaned"
|
|
514
527
|
: detail.status === "lost" ? "lost"
|
|
@@ -766,7 +779,7 @@ export function createNavigatorOverlayComponent(rows, deps, tui, theme, done) {
|
|
|
766
779
|
if (detailId == null) return null;
|
|
767
780
|
// Prefer live detail snapshot (status may have changed while armed).
|
|
768
781
|
if (detail && detail.id === detailId) {
|
|
769
|
-
return { id: detail.id, name: detail.name, status: detail.status };
|
|
782
|
+
return { id: detail.id, name: detail.name, status: detail.status, assignment: detail.assignment, attemptStatus: detail.attemptStatus };
|
|
770
783
|
}
|
|
771
784
|
const fromList = (state.rows ?? []).find((r) => r && r.id === detailId);
|
|
772
785
|
return fromList ?? { id: detailId, name: detailId, status: "completed" };
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Versioned reconciliation evidence in the existing durable conversation store. */
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { durableSubagentRoot } from "./session-store.ts";
|
|
6
|
+
import type { ParkRecord, RunMeta } from "./registry.ts";
|
|
7
|
+
|
|
8
|
+
export interface OutageObservation {
|
|
9
|
+
version: 1;
|
|
10
|
+
id: string;
|
|
11
|
+
observedRevision: { generation: number; claimId: string | null; launchToken: string | null; cancelled?: true };
|
|
12
|
+
coordinatorEvidence?: ParkRecord["observedCoordinator"];
|
|
13
|
+
meta: RunMeta;
|
|
14
|
+
record: ParkRecord;
|
|
15
|
+
attempt?: RunMeta;
|
|
16
|
+
resolved?: true;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function directory(): string { return join(durableSubagentRoot(), "observations-v1"); }
|
|
20
|
+
|
|
21
|
+
function publish(path: string, value: unknown): void {
|
|
22
|
+
mkdirSync(directory(), { recursive: true, mode: 0o700 });
|
|
23
|
+
const temporary = join(directory(), `.${randomBytes(12).toString("hex")}.tmp`);
|
|
24
|
+
try {
|
|
25
|
+
writeFileSync(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
|
26
|
+
const fd = openSync(temporary, "r");
|
|
27
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
28
|
+
renameSync(temporary, path);
|
|
29
|
+
const dir = openSync(directory(), "r");
|
|
30
|
+
try { fsyncSync(dir); } finally { closeSync(dir); }
|
|
31
|
+
} finally {
|
|
32
|
+
try { unlinkSync(temporary); } catch { /* Already published. */ }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function assertObservationStorage(): void {
|
|
37
|
+
try { publish(join(directory(), "storage-probe.json"), { version: 1 }); }
|
|
38
|
+
catch (error) { throw new Error(`Degraded supervision: durable conversation storage unavailable; new parking refused (${String(error)}).`); }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function retainObservation(meta: RunMeta, record: ParkRecord, attempt?: RunMeta): OutageObservation {
|
|
42
|
+
const observedRevision = { generation: record.generation, claimId: record.resumeClaimId ?? null,
|
|
43
|
+
launchToken: record.resumeLaunchToken ?? null, ...(record.phase === "cancelled" ? { cancelled: true as const } : {}) };
|
|
44
|
+
const id = createHash("sha256").update(JSON.stringify([meta.assignment?.assignmentId ?? meta.id,
|
|
45
|
+
record.waitId, observedRevision])).digest("hex");
|
|
46
|
+
const path = join(directory(), `${id}.json`);
|
|
47
|
+
try {
|
|
48
|
+
const existing = JSON.parse(readFileSync(path, "utf8")) as OutageObservation;
|
|
49
|
+
if (existing.version !== 1 || existing.id !== id) throw new Error("Invalid observation identity");
|
|
50
|
+
return existing;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
53
|
+
}
|
|
54
|
+
const report: OutageObservation = { version: 1, id, observedRevision, coordinatorEvidence: record.observedCoordinator,
|
|
55
|
+
meta, record, ...(attempt ? { attempt } : {}) };
|
|
56
|
+
publish(path, report);
|
|
57
|
+
return report;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function pendingObservations(): OutageObservation[] {
|
|
61
|
+
let names: string[];
|
|
62
|
+
try { names = readdirSync(directory()); }
|
|
63
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
|
|
64
|
+
return names.filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).map((name) => {
|
|
65
|
+
const report = JSON.parse(readFileSync(join(directory(), name), "utf8")) as OutageObservation;
|
|
66
|
+
if (report.version !== 1 || `${report.id}.json` !== name) throw new Error("Unsupported or corrupt outage observation");
|
|
67
|
+
return report;
|
|
68
|
+
}).filter((report) => !report.resolved);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function resolveObservation(report: OutageObservation): void {
|
|
72
|
+
publish(join(directory(), `${report.id}.json`), { ...report, resolved: true });
|
|
73
|
+
}
|
package/output-payload.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* omitted. Every cursor is bound to the selected session scope.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { assignmentFor, assignmentDiagnostic } from "./assignment-projection.mjs";
|
|
11
12
|
import { statSync } from "node:fs";
|
|
12
13
|
import {
|
|
13
14
|
assemblePriorityEnvelope,
|
|
@@ -97,6 +98,7 @@ export type LoadedRun =
|
|
|
97
98
|
| { kind: "unreadable"; detail: string };
|
|
98
99
|
|
|
99
100
|
export type SubagentToolSession = {
|
|
101
|
+
inspectOutcome?: (meta: RunMeta, params: Record<string, unknown>, ctx?: unknown) => unknown;
|
|
100
102
|
/** Current session origin; `ctx` is the tool call's host context when available. */
|
|
101
103
|
getActiveOrigin?: (ctx?: unknown) => RunCallbackOrigin | undefined;
|
|
102
104
|
};
|
|
@@ -192,6 +194,7 @@ export function ownership(meta: RunMeta, origin: RunCallbackOrigin, parentPid =
|
|
|
192
194
|
/** Lifecycle metadata and log identity. A metadata-only transition is a change. */
|
|
193
195
|
function contentRevisionFor(id: string, meta: RunMeta): string {
|
|
194
196
|
return lifecycleContentRevision([
|
|
197
|
+
assignmentFor(meta, effectiveStatus(meta)).revision,
|
|
195
198
|
meta.status,
|
|
196
199
|
String(effectiveStatus(meta)),
|
|
197
200
|
meta.exitCode ?? null,
|
|
@@ -201,6 +204,17 @@ function contentRevisionFor(id: string, meta: RunMeta): string {
|
|
|
201
204
|
], logPathFor(id));
|
|
202
205
|
}
|
|
203
206
|
|
|
207
|
+
function assignmentLabel(meta: RunMeta): string {
|
|
208
|
+
const a = assignmentFor(meta, effectiveStatus(meta));
|
|
209
|
+
return a.state;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function projectionDiagnostic(meta: RunMeta): string {
|
|
213
|
+
const assignment = assignmentFor(meta, effectiveStatus(meta));
|
|
214
|
+
return meta.operations || meta.park || assignment.state !== effectiveStatus(meta)
|
|
215
|
+
? assignmentDiagnostic(assignment) : "";
|
|
216
|
+
}
|
|
217
|
+
|
|
204
218
|
function elapsedFor(meta: RunMeta, now = Date.now()): string {
|
|
205
219
|
return fmtElapsed((meta.endedAt ?? now) - meta.startedAt);
|
|
206
220
|
}
|
|
@@ -523,10 +537,11 @@ export function assembleRunningResult(
|
|
|
523
537
|
scopeKey = defaultScope(),
|
|
524
538
|
timingLine?: string,
|
|
525
539
|
): string {
|
|
540
|
+
timingLine = [timingLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
|
|
526
541
|
const st = String(effectiveStatus(meta));
|
|
527
542
|
const terminal = st !== "running" && st !== "orphaned";
|
|
528
543
|
const ctx = callContext(id, meta, request, scopeKey, "subagent_result", terminal);
|
|
529
|
-
const identity = `[${id} · ${
|
|
544
|
+
const identity = `[${id} · ${assignmentLabel(meta)} · ${elapsedFor(meta)}]`;
|
|
530
545
|
if (wantsIncidentPage(request)) return assembleIncidentPage(ctx, identity);
|
|
531
546
|
const unchanged = maybeUnchanged(ctx, identity);
|
|
532
547
|
if (unchanged) return unchanged;
|
|
@@ -554,7 +569,7 @@ function assembleRaw(
|
|
|
554
569
|
): string {
|
|
555
570
|
const terminal = status !== "running" && status !== "orphaned";
|
|
556
571
|
const ctx = callContext(id, meta, request, scopeKey, surface === "result" ? "subagent_result" : "subagent_output", terminal);
|
|
557
|
-
const identity = outputIdentity(id,
|
|
572
|
+
const identity = outputIdentity(id, assignmentLabel(meta), elapsedFor(meta));
|
|
558
573
|
const unchanged = maybeUnchanged(ctx, identity);
|
|
559
574
|
if (unchanged) return unchanged;
|
|
560
575
|
const run = parseRun(id);
|
|
@@ -565,7 +580,7 @@ function assembleRaw(
|
|
|
565
580
|
identity: `${identity} raw retained log${wantsTail(request) ? " · newest first" : ""}`,
|
|
566
581
|
// Raw evidence keeps whole excerpts and evidence paths.
|
|
567
582
|
failure: failureSection(ctx, continuing ? CONTINUATION_FAILURE_BYTES : 1024, "full"),
|
|
568
|
-
diagnostics: joinSections([changeDiagnostics(ctx), optInFacts(run, request), parserDiagnostics(run)]),
|
|
583
|
+
diagnostics: joinSections([projectionDiagnostic(meta), changeDiagnostics(ctx), optInFacts(run, request), parserDiagnostics(run)]),
|
|
569
584
|
gaps: logGaps(id),
|
|
570
585
|
verbatim: (remaining) => rawPage(ctx, pageCursorFor(request.cursor), remaining),
|
|
571
586
|
verbatimReserve: Math.floor(maxBytes / 2),
|
|
@@ -580,11 +595,12 @@ export function assembleSubagentOutput(
|
|
|
580
595
|
healthLine = "",
|
|
581
596
|
scopeKey = defaultScope(),
|
|
582
597
|
): string {
|
|
598
|
+
healthLine = [healthLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
|
|
583
599
|
const st = String(effectiveStatus(meta));
|
|
584
600
|
if (isRawMode(request.mode) || cursorKind(request.cursor) === "f") return assembleRaw(id, meta, st, request, "output", scopeKey);
|
|
585
601
|
const terminal = st !== "running" && st !== "orphaned";
|
|
586
602
|
const ctx = callContext(id, meta, request, scopeKey, "subagent_output", terminal);
|
|
587
|
-
const identity = outputIdentity(id,
|
|
603
|
+
const identity = outputIdentity(id, assignmentLabel(meta), elapsedFor(meta));
|
|
588
604
|
if (wantsIncidentPage(request)) return assembleIncidentPage(ctx, identity);
|
|
589
605
|
const unchanged = maybeUnchanged(ctx, identity);
|
|
590
606
|
if (unchanged) return unchanged;
|
|
@@ -633,9 +649,10 @@ export function assembleOrphanedResult(
|
|
|
633
649
|
request: PayloadRequest = {},
|
|
634
650
|
scopeKey = defaultScope(),
|
|
635
651
|
): string {
|
|
652
|
+
healthLine = [healthLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
|
|
636
653
|
if (isRawMode(request.mode) || cursorKind(request.cursor) === "f") return assembleRaw(id, meta, "orphaned", request, "result", scopeKey);
|
|
637
654
|
const ctx = callContext(id, meta, request, scopeKey, "subagent_result", false);
|
|
638
|
-
const identity = `[${id} ·
|
|
655
|
+
const identity = `[${id} · ${assignmentLabel(meta)} · ${elapsedFor(meta)}]`;
|
|
639
656
|
if (wantsIncidentPage(request)) return assembleIncidentPage(ctx, identity);
|
|
640
657
|
const unchanged = maybeUnchanged(ctx, identity);
|
|
641
658
|
if (unchanged) return unchanged;
|
|
@@ -677,13 +694,14 @@ export function assembleSubagentResult(
|
|
|
677
694
|
healthLine = "",
|
|
678
695
|
scopeKey = defaultScope(),
|
|
679
696
|
): string {
|
|
697
|
+
healthLine = [healthLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
|
|
680
698
|
const st = effectiveStatus(meta);
|
|
681
699
|
if (isRawMode(request.mode) || cursorKind(request.cursor) === "f") return assembleRaw(id, meta, String(st), request, "result", scopeKey);
|
|
682
700
|
const ctx = callContext(id, meta, request, scopeKey, "subagent_result", true);
|
|
683
701
|
const exit = meta.exitCode === undefined ? "?" : String(meta.exitCode);
|
|
684
702
|
const run = parseRunForLifecycle(id);
|
|
685
703
|
const lifecycle = resolveLifecycle(meta, run);
|
|
686
|
-
const identity = resultIdentity(id,
|
|
704
|
+
const identity = resultIdentity(id, assignmentLabel(meta), exit, elapsedFor(meta), lifecycle.classification);
|
|
687
705
|
if (wantsIncidentPage(request)) return assembleIncidentPage(ctx, identity);
|
|
688
706
|
const unchanged = maybeUnchanged(ctx, identity);
|
|
689
707
|
if (unchanged) return unchanged;
|
|
@@ -849,6 +867,7 @@ export function listRevisions(
|
|
|
849
867
|
contentRevision: revisionOf(items.map((item) => [
|
|
850
868
|
item.id,
|
|
851
869
|
item.status,
|
|
870
|
+
item.meta ? assignmentFor(item.meta, effectiveStatus(item.meta)).revision : null,
|
|
852
871
|
item.meta?.status ?? null,
|
|
853
872
|
item.meta?.exitCode ?? null,
|
|
854
873
|
item.meta?.endedAt ?? null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-subagents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -54,7 +54,9 @@
|
|
|
54
54
|
"files": [
|
|
55
55
|
"*.ts",
|
|
56
56
|
"*.mjs",
|
|
57
|
+
"*.d.mts",
|
|
57
58
|
"shared-operation-coordinator/**/*.ts",
|
|
59
|
+
"shared-operation-coordinator/assignment-observation.mjs",
|
|
58
60
|
"config.json",
|
|
59
61
|
"README.md",
|
|
60
62
|
"roles/**/*.md",
|
package/registry.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import type { RunTiming } from "./timing.ts";
|
|
16
|
+
import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
|
|
16
17
|
import type { SkillExposureSource } from "./skills.ts";
|
|
17
18
|
import { execFileSync } from "node:child_process";
|
|
18
19
|
import { createHash, randomBytes } from "node:crypto";
|
|
@@ -138,6 +139,8 @@ export interface LaunchRecipe {
|
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
export interface RunMeta {
|
|
142
|
+
outcomeSupport?: { version: 1; available: boolean; reason?: string };
|
|
143
|
+
assignment?: import("./assignment-outcomes.ts").AssignmentBinding;
|
|
141
144
|
id: string;
|
|
142
145
|
name?: string;
|
|
143
146
|
status: RunStatus;
|
|
@@ -364,6 +367,8 @@ export interface ParkRecord {
|
|
|
364
367
|
continuationNote?: string;
|
|
365
368
|
/** Verified saved-conversation checkpoint. */
|
|
366
369
|
checkpoint?: ParkCheckpointIdentity;
|
|
370
|
+
/** Last verified coordinator evidence; observation only, never admission authority. */
|
|
371
|
+
observedCoordinator?: { cancelEpoch: number; dependencies: readonly { operationId: string; terminalRevision: number }[] };
|
|
367
372
|
parkedAt: number;
|
|
368
373
|
updatedAt: number;
|
|
369
374
|
/** Why the wait is held instead of continuing. */
|
|
@@ -408,6 +413,7 @@ export interface RunOperationsBinding {
|
|
|
408
413
|
/** Worker policy captured at launch; Background intersects it, never the child. */
|
|
409
414
|
policy: {
|
|
410
415
|
version: 1;
|
|
416
|
+
mandatoryPermissions?: boolean;
|
|
411
417
|
sandbox: unknown;
|
|
412
418
|
tools: readonly string[];
|
|
413
419
|
clean: boolean;
|
|
@@ -440,13 +446,17 @@ function parseParkRecord(value: unknown): ParkRecord | undefined {
|
|
|
440
446
|
* The mirror keeps listings, the Goal provider and cleanup from needing a second
|
|
441
447
|
* read; the file remains the authoritative copy for this attempt.
|
|
442
448
|
*/
|
|
443
|
-
export function writeParkRecord(id: string, record: ParkRecord): void {
|
|
449
|
+
export function writeParkRecord(id: string, record: ParkRecord, options: { ifAbsent?: boolean } = {}): void {
|
|
444
450
|
if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error("Invalid run ID.");
|
|
445
451
|
mkdirSync(runDir(id), { recursive: true });
|
|
446
452
|
const path = parkRecordPath(id);
|
|
447
453
|
const temp = join(dirname(path), `.park.${randomBytes(6).toString("hex")}.tmp`);
|
|
448
454
|
writeFileSync(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" });
|
|
449
|
-
|
|
455
|
+
if (options.ifAbsent) {
|
|
456
|
+
try { linkSync(temp, path); }
|
|
457
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") return; throw error; }
|
|
458
|
+
finally { unlinkSync(temp); }
|
|
459
|
+
} else renameSync(temp, path);
|
|
450
460
|
const meta = readMeta(id);
|
|
451
461
|
if (meta && (meta.park?.phase !== record.phase
|
|
452
462
|
|| meta.park?.heldReason !== record.heldReason
|
|
@@ -527,6 +537,8 @@ export function recordTaskRuntimeProvenance(id: string): void {
|
|
|
527
537
|
* uses this, so no provenance outlives its run. Throws when the run directory cannot be removed.
|
|
528
538
|
*/
|
|
529
539
|
export function removeRunDirectory(id: string): void {
|
|
540
|
+
const meta = readMeta(id);
|
|
541
|
+
if (meta && assignmentRetainsEvidence(meta)) throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
|
|
530
542
|
rmSync(runDir(id), { recursive: true, force: true });
|
|
531
543
|
removeTaskRuntimeProvenance(id);
|
|
532
544
|
}
|
|
@@ -1223,9 +1235,10 @@ export function observeArchivePublication(id: string, error?: unknown): void {
|
|
|
1223
1235
|
} catch { /* the journal is best-effort; retaining the run is the safety net */ }
|
|
1224
1236
|
}
|
|
1225
1237
|
|
|
1226
|
-
export function writeMeta(meta: RunMeta): void {
|
|
1238
|
+
export function writeMeta(meta: RunMeta, options: { ifAbsent?: boolean } = {}): void {
|
|
1227
1239
|
mkdirSync(runDir(meta.id), { recursive: true });
|
|
1228
1240
|
withRunMetaLock(meta.id, (owns) => {
|
|
1241
|
+
if (options.ifAbsent && existsSync(metaPathFor(meta.id))) return;
|
|
1229
1242
|
metaWriteBarrier?.();
|
|
1230
1243
|
if (!owns()) throw new MetadataLockLost();
|
|
1231
1244
|
writeMetaFile(meta);
|
package/session-store.ts
CHANGED
|
@@ -55,7 +55,7 @@ const ARCHIVE_META_KEYS = [
|
|
|
55
55
|
"dismissedAt",
|
|
56
56
|
// A parked attempt's disposition and operation binding outlive the volatile
|
|
57
57
|
// run directory: the resume path and cleanup protection read this record.
|
|
58
|
-
"park", "operations",
|
|
58
|
+
"park", "operations", "assignment", "pidStartTime",
|
|
59
59
|
] as const satisfies readonly (keyof RunMeta)[];
|
|
60
60
|
|
|
61
61
|
interface ArchivedAttemptRecord {
|
|
@@ -119,12 +119,14 @@ export interface CallbackBatchHost {
|
|
|
119
119
|
/** Older Pi shares this object; newer Pi supplies per-extension wrappers. */
|
|
120
120
|
events?: object;
|
|
121
121
|
sendMessage(
|
|
122
|
-
message: { customType: string; content: string; display: boolean },
|
|
122
|
+
message: { customType: string; content: string; display: boolean; details?: unknown },
|
|
123
123
|
options: Record<string, unknown>,
|
|
124
124
|
): unknown;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
export interface CallbackBatchEvent {
|
|
128
|
+
receiptId?: string;
|
|
129
|
+
inspectId?: string;
|
|
128
130
|
source: CallbackSource;
|
|
129
131
|
id: string;
|
|
130
132
|
label: string;
|
|
@@ -332,8 +334,8 @@ function boundedStatus(value: unknown): string {
|
|
|
332
334
|
return count < notes.length ? `${kept}${omission(notes.length - count)}` : kept;
|
|
333
335
|
}
|
|
334
336
|
|
|
335
|
-
function inspectFor(event: Pick<CallbackBatchEvent, "id" | "detailTool">): string {
|
|
336
|
-
const id = boundedField(event.id, MAX_ID_BYTES);
|
|
337
|
+
function inspectFor(event: Pick<CallbackBatchEvent, "id" | "detailTool" | "inspectId">): string {
|
|
338
|
+
const id = boundedField(event.inspectId ?? event.id, MAX_ID_BYTES);
|
|
337
339
|
return event.detailTool === "bg_task_status"
|
|
338
340
|
? `bg_task_status id=${id}`
|
|
339
341
|
: `subagent_result id=${JSON.stringify(id)}`;
|
|
@@ -665,6 +667,7 @@ export function createCallbackBatcher(
|
|
|
665
667
|
const representedItems = deliverable.filter(([, item]) => representedSet.has(item.event));
|
|
666
668
|
const overflowItems = deliverable.filter(([, item]) => !representedSet.has(item.event));
|
|
667
669
|
|
|
670
|
+
const receiptDetails = { completionEventIds: representedItems.map(([, item]) => item.event.receiptId).filter((id): id is string => Boolean(id)) };
|
|
668
671
|
try {
|
|
669
672
|
// Pi may defer the requested run while settled handlers finish, leaving
|
|
670
673
|
// isIdle() true. Permit no second handoff until a run starts.
|
|
@@ -674,12 +677,14 @@ export function createCallbackBatcher(
|
|
|
674
677
|
customType: "background-completion-batch",
|
|
675
678
|
content: packed.text,
|
|
676
679
|
display: true,
|
|
680
|
+
...(receiptDetails.completionEventIds.length ? { details: receiptDetails } : {}),
|
|
677
681
|
},
|
|
678
682
|
// Newer Pi requires triggerTurn for steering too; false only appends
|
|
679
683
|
// a custom message at the turn boundary without continuing the agent.
|
|
680
684
|
{ deliverAs: mode, triggerTurn: true },
|
|
681
685
|
);
|
|
682
686
|
} catch {
|
|
687
|
+
receiptDetails.completionEventIds.length = 0;
|
|
683
688
|
awaitingRun = false;
|
|
684
689
|
for (const [key] of deliverable) inFlight.delete(key);
|
|
685
690
|
const retryItems = [...deliverable, ...pending.entries()]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
|
|
4
|
+
/** Read-only, bounded projection input. Never creates/migrates a database. */
|
|
5
|
+
export function readAssignmentWaits(path, owner) {
|
|
6
|
+
let db;
|
|
7
|
+
try {
|
|
8
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
9
|
+
db = new DatabaseSync(path, { readOnly: true });
|
|
10
|
+
// v4 adds repair accounting; the observed wait/outcome fields are unchanged.
|
|
11
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
|
|
12
|
+
return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
|
|
13
|
+
}
|
|
14
|
+
const rows = db.prepare(`SELECT wait_id, generation, phase, phase_reason,
|
|
15
|
+
acknowledgement_json, cancel_epoch FROM waits
|
|
16
|
+
WHERE owner_kind = 'worker-conversation' AND owner_session_id = ? AND owner_workspace = ?
|
|
17
|
+
${owner.assignmentId ? "AND json_extract(origin_json, '$.assignmentRef') = ?" : `AND (
|
|
18
|
+
EXISTS (SELECT 1 FROM json_each(?) AS attempt
|
|
19
|
+
WHERE attempt.value = json_extract(waits.origin_json, '$.attemptId')
|
|
20
|
+
OR attempt.value = json_extract(waits.park_json, '$.attemptId'))
|
|
21
|
+
OR EXISTS (SELECT 1 FROM resume_claims AS claim, json_each(?) AS attempt
|
|
22
|
+
WHERE claim.wait_id = waits.wait_id AND claim.generation = waits.generation
|
|
23
|
+
AND claim.attempt_id = attempt.value)
|
|
24
|
+
OR EXISTS (SELECT 1 FROM json_each(?) AS ref
|
|
25
|
+
WHERE json_extract(ref.value, '$.waitId') = waits.wait_id
|
|
26
|
+
AND json_extract(ref.value, '$.generation') = waits.generation)
|
|
27
|
+
)`}
|
|
28
|
+
ORDER BY created_at DESC, generation DESC LIMIT 100`).all(owner.sessionId, owner.workspace,
|
|
29
|
+
...(owner.assignmentId ? [owner.assignmentId] : [JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.waitRefs ?? [])]));
|
|
30
|
+
const record = owner.assignmentId ? db.prepare("SELECT record_json FROM assignment_outcomes WHERE assignment_id = ?").get(owner.assignmentId) : null;
|
|
31
|
+
const outcome = record ? JSON.parse(record.record_json) : null;
|
|
32
|
+
if (outcome && (outcome.owner.sessionId !== owner.sessionId || outcome.owner.workspace !== owner.workspace)) throw new Error("Foreign assignment outcome");
|
|
33
|
+
return { verified: true, outcome, waits: rows.map((row) => ({
|
|
34
|
+
waitId: row.wait_id, generation: row.generation, phase: row.phase,
|
|
35
|
+
reason: row.phase_reason, cancelEpoch: row.cancel_epoch,
|
|
36
|
+
acknowledgement: row.acknowledgement_json ? JSON.parse(row.acknowledgement_json) : null,
|
|
37
|
+
})) };
|
|
38
|
+
} catch {
|
|
39
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
40
|
+
} finally {
|
|
41
|
+
db?.close();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
* to be durable.
|
|
46
46
|
*/
|
|
47
47
|
export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
|
|
48
|
+
export type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./src/assignment-outcomes.ts";
|
|
48
49
|
export type {
|
|
49
50
|
AcknowledgeDisposition,
|
|
50
51
|
AcknowledgeResultInput,
|
|
@@ -53,6 +54,7 @@ export type {
|
|
|
53
54
|
CancelWaitResult,
|
|
54
55
|
ClaimOutboxInput,
|
|
55
56
|
ClaimResumeInput,
|
|
57
|
+
DiscoveryClaimRecord,
|
|
56
58
|
EvidenceKind,
|
|
57
59
|
EvidencePinRecord,
|
|
58
60
|
EvidenceReadRecord,
|
|
@@ -85,6 +87,8 @@ export type {
|
|
|
85
87
|
RegisterOperationResult,
|
|
86
88
|
RegisterWaitInput,
|
|
87
89
|
RegisterWaitResult,
|
|
90
|
+
ReleaseDiscoveryClaimInput,
|
|
91
|
+
ReleaseSupervisionInput,
|
|
88
92
|
ReleaseOutboxInput,
|
|
89
93
|
ReleaseResumeClaimInput,
|
|
90
94
|
ReleaseResumeClaimResult,
|
|
@@ -98,6 +102,7 @@ export type {
|
|
|
98
102
|
TerminalOutcome,
|
|
99
103
|
TransitionWaitPhaseInput,
|
|
100
104
|
TransitionWaitPhaseResult,
|
|
105
|
+
TryClaimDiscoveryInput,
|
|
101
106
|
WaitAcknowledgement,
|
|
102
107
|
WaitDependencyInput,
|
|
103
108
|
WaitDependencyRecord,
|