pi-better-subagents 0.29.1 → 0.31.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 +14 -1
- 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/config.ts +5 -1
- package/docs/usage.md +10 -6
- package/finalization.ts +2 -0
- package/health-surface.mjs +2 -0
- package/index.ts +188 -38
- 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/settings-page.ts +16 -7
- 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/timing.ts +14 -7
- package/tools.ts +24 -7
- package/worker-waits.ts +245 -82
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ Use `pi-better-subagents` when you want Pi to launch independent agent work with
|
|
|
18
18
|
- Explicit tool allowlists for child sessions, and `skills` for prompt exposure: omit it to keep user-catalog discovery, pass `[]` for no skills, or pass absolute `SKILL.md` paths for exactly those. See [skill exposure](docs/usage.md#skill-exposure).
|
|
19
19
|
- Durable logs, result retrieval, and [failure observations](docs/failure-observations.md) independent of lifecycle status. A live child handles its own tool errors; the parent is woken only for actionable incidents, and children can classify handled failures with `failure_disposition`.
|
|
20
20
|
- Live background-work navigator for active runs.
|
|
21
|
-
- Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min),
|
|
21
|
+
- Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Change the timeout in `/subagents settings`; `0` disables it. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
|
|
22
22
|
|
|
23
23
|
Every single or batch launch automatically joins one shared supervision watcher in the
|
|
24
24
|
foreground Pi process. The last active run's exit or stop tears it down; a later
|
|
@@ -170,6 +170,19 @@ pi remove npm:pi-better-subagents
|
|
|
170
170
|
|
|
171
171
|
## More Detail
|
|
172
172
|
|
|
173
|
+
### Assignment Progress
|
|
174
|
+
|
|
175
|
+
Result tools, lists, navigation and Goal activity share five assignment states:
|
|
176
|
+
Running, Waiting, Completed, Failed and Cancelled. Process status is separate.
|
|
177
|
+
An exited attempt can still be Waiting, and its output remains readable.
|
|
178
|
+
Consuming a dependency wait does not by itself complete the assignment.
|
|
179
|
+
|
|
180
|
+
The projection exposes an opaque semantic `revision`, readable `reason`, attempt
|
|
181
|
+
identity, process status, termination evidence and retained evidence references.
|
|
182
|
+
Compare revisions for equality; unchanged observations keep the same revision.
|
|
183
|
+
Unavailable or unsupported coordinator reads report Waiting with an unverified
|
|
184
|
+
reason. See the [projection contract](../../docs/adr/0022-assignment-progress-projection.md).
|
|
185
|
+
|
|
173
186
|
- Repository: https://github.com/1aboveio/pi-better-harness
|
|
174
187
|
- Detailed notes: https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md
|
|
175
188
|
- License: https://github.com/1aboveio/pi-better-harness/blob/main/LICENSE
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join, relative, isAbsolute } from "node:path";
|
|
4
|
+
import { openSync, closeSync, fstatSync, readSync, realpathSync, constants } from "node:fs";
|
|
5
|
+
import { openStore, type OwnerIdentity, type AssignmentOutcomeRecord } from "./shared-operation-coordinator/index.ts";
|
|
6
|
+
import type { RunMeta } from "./registry.ts";
|
|
7
|
+
import { processStartToken } from "./registry.ts";
|
|
8
|
+
import type { PermissionSnapshot } from "./permission-policy.ts";
|
|
9
|
+
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
10
|
+
|
|
11
|
+
export const ASSIGNMENT_OUTCOMES_VERSION = 1;
|
|
12
|
+
const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
|
|
13
|
+
export function createOutcomeHost(): string {
|
|
14
|
+
return `assignment:${process.pid}:${encodeURIComponent(processStartToken(process.pid) ?? "unknown")}:${randomUUID()}`;
|
|
15
|
+
}
|
|
16
|
+
export function closeOutcomeHost(hostId: string): void {
|
|
17
|
+
closedHosts.add(hostId);
|
|
18
|
+
}
|
|
19
|
+
export function claimOutcome(meta: RunMeta, hostId: string): boolean {
|
|
20
|
+
const outcome = readOutcome(meta);
|
|
21
|
+
if (!outcome) return false;
|
|
22
|
+
return withStore((store) => {
|
|
23
|
+
const event = store.listOutbox().find((e) => e.eventId === outcome.eventId);
|
|
24
|
+
if (!event || ["delivered", "acknowledged"].includes(event.state)) return false;
|
|
25
|
+
if (event.dispatchClaim) {
|
|
26
|
+
if (event.dispatchClaim.claimedBy === hostId) return true;
|
|
27
|
+
const [prefix, pidText, token] = event.dispatchClaim.claimedBy.split(":");
|
|
28
|
+
let dead = closedHosts.has(event.dispatchClaim.claimedBy);
|
|
29
|
+
if (prefix === "assignment" && !dead) {
|
|
30
|
+
try { process.kill(Number(pidText), 0); } catch (error) { dead = (error as NodeJS.ErrnoException).code === "ESRCH"; }
|
|
31
|
+
const current = processStartToken(Number(pidText));
|
|
32
|
+
if (current && token !== "unknown" && encodeURIComponent(current) !== token) dead = true;
|
|
33
|
+
}
|
|
34
|
+
if (!dead) return false;
|
|
35
|
+
store.releaseOutbox({ eventId: event.eventId, claimToken: event.dispatchClaim.token, reason: "prior outcome delivery host exited" });
|
|
36
|
+
}
|
|
37
|
+
return store.claimOutbox({ type: "assignment-outcome", eventId: outcome.eventId, recipient: outcome.recipient, claimToken: `outcome_${randomUUID()}`, claimedBy: hostId, limit: 1 }).length === 1;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export interface AssignmentBinding { version: 1; assignmentId: string; owner: OwnerIdentity; recipient: OwnerIdentity }
|
|
41
|
+
export function coordinatorPath(): string {
|
|
42
|
+
return join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite");
|
|
43
|
+
}
|
|
44
|
+
function withStore<T>(body: (store: ReturnType<typeof openStore>) => T): T {
|
|
45
|
+
const store = openStore({ path: coordinatorPath() });
|
|
46
|
+
try { return body(store); } finally { store.close(); }
|
|
47
|
+
}
|
|
48
|
+
export function registerAssignmentAttempt(binding: AssignmentBinding, attemptId: string): void {
|
|
49
|
+
if (binding.version !== ASSIGNMENT_OUTCOMES_VERSION) throw new Error("Unsupported assignment outcome capability.");
|
|
50
|
+
withStore((store) => store.registerAssignment({ ...binding, attemptId }));
|
|
51
|
+
}
|
|
52
|
+
/** Called before any completion handoff, including callback:false and inactive parents. */
|
|
53
|
+
export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false): AssignmentOutcomeRecord | null {
|
|
54
|
+
const binding = meta.assignment;
|
|
55
|
+
if (!binding) return null;
|
|
56
|
+
return withStore((store) => {
|
|
57
|
+
const existing = store.getAssignmentOutcome(binding.assignmentId);
|
|
58
|
+
if (existing) return existing;
|
|
59
|
+
if (!["failed", "completed", "killed", "lost"].includes(meta.status) || (meta.status === "completed" && meta.park)) return null;
|
|
60
|
+
const waits = store.listWaits({ owner: binding.owner }).filter((w) => w.origin?.assignmentRef === binding.assignmentId);
|
|
61
|
+
// A published automatic attempt's exit belongs to bounded recovery first.
|
|
62
|
+
if (!recoveryFailure && meta.status !== "killed" && meta.operations?.resumeLaunchToken && waits.some((w) => !w.acknowledgement && ["resuming", "ready"].includes(w.phase))) return null;
|
|
63
|
+
// A coherent attempt exit does not establish interpretation or completion.
|
|
64
|
+
if (meta.status === "completed" && waits.some((w) => !w.acknowledgement)) return null;
|
|
65
|
+
return store.recordAssignmentOutcome({ ...binding, revision: 1,
|
|
66
|
+
outcome: meta.status === "completed" ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
|
|
67
|
+
reason: meta.failureReason || (meta.status === "completed" ? "Assigned work and required interpretation are complete." : `Assignment ended ${meta.status}; retained attempt evidence is available.`),
|
|
68
|
+
processUncertain: meta.status === "lost" || typeof meta.exitCode !== "number"
|
|
69
|
+
|| waits.some((w) => w.dependencies.some((d) => d.terminalRevision === 0)
|
|
70
|
+
|| store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0),
|
|
71
|
+
evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` }],
|
|
72
|
+
waits: waits.map((w) => ({ waitId: w.waitId, generation: w.generation, cancelEpoch: w.cancelEpoch })),
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function readOutcome(meta: RunMeta): AssignmentOutcomeRecord | null {
|
|
77
|
+
return meta.assignment ? withStore((store) => store.getAssignmentOutcome(meta.assignment!.assignmentId)) : null;
|
|
78
|
+
}
|
|
79
|
+
export function assignmentRetainsEvidence(meta: RunMeta): boolean {
|
|
80
|
+
if (!meta.assignment) return false;
|
|
81
|
+
return withStore((store) => {
|
|
82
|
+
const outcome = store.getAssignmentOutcome(meta.assignment!.assignmentId);
|
|
83
|
+
if (!outcome) return false;
|
|
84
|
+
if (!outcome.disposition) return true;
|
|
85
|
+
const waits = store.listWaits({ owner: outcome.owner }).filter((w) => w.origin?.assignmentRef === outcome.assignmentId);
|
|
86
|
+
return waits.some((w) => store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
export function receiptOutcome(meta: RunMeta, entryId: string): void {
|
|
90
|
+
const record = readOutcome(meta);
|
|
91
|
+
if (record) withStore((store) => store.receiptAssignmentOutcome({ assignmentId: record.assignmentId, recipient: record.recipient, revision: record.revision, entryId }));
|
|
92
|
+
}
|
|
93
|
+
export function outcomeTranscriptReceipt(entries: readonly unknown[], eventId: string): string | null {
|
|
94
|
+
for (const raw of entries) {
|
|
95
|
+
const entry = raw as { id?: string; type?: string; customType?: string; details?: { completionEventIds?: unknown }; message?: { role?: string; customType?: string; details?: { completionEventIds?: unknown } } };
|
|
96
|
+
const message = entry.type === "custom_message" ? entry
|
|
97
|
+
: entry.type === "message" && entry.message?.role === "custom" ? entry.message : null;
|
|
98
|
+
if (message?.customType !== "background-completion-batch") continue;
|
|
99
|
+
const ids = message.details?.completionEventIds;
|
|
100
|
+
if (Array.isArray(ids) && ids.includes(eventId)) return entry.id ?? eventId;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
function under(path: string, root: string): boolean {
|
|
105
|
+
const rel = relative(root, path);
|
|
106
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
107
|
+
}
|
|
108
|
+
export function inspectOutcome(meta: RunMeta, input: { recipient: OwnerIdentity; branchIds?: readonly string[]; permissions?: PermissionSnapshot; operationId?: string; revision?: number; disposition?: "consumed" | "dismissed"; note?: string }) {
|
|
109
|
+
if (input.disposition && !Number.isInteger(input.revision)) throw new Error("Outcome disposition requires the exact outcome_revision.");
|
|
110
|
+
if (!meta.assignment) throw new Error("This run has no durable assignment outcome capability.");
|
|
111
|
+
return withStore((store) => {
|
|
112
|
+
const outcome = store.getAssignmentOutcome(meta.assignment!.assignmentId);
|
|
113
|
+
if (!outcome || outcome.recipient.sessionId !== input.recipient.sessionId || outcome.recipient.workspace !== input.recipient.workspace
|
|
114
|
+
|| (outcome.recipient.branchId && outcome.recipient.branchId !== input.recipient.branchId && !input.branchIds?.includes(outcome.recipient.branchId))) throw new Error("Outcome belongs to a different parent session or branch.");
|
|
115
|
+
const policy = input.permissions?.permissions;
|
|
116
|
+
if (meta.operations?.policy.sandbox && !policy) throw new Error("Current mandatory read authority is unavailable.");
|
|
117
|
+
const readable = (path: string): string => {
|
|
118
|
+
const real = realpathSync(path);
|
|
119
|
+
if (credentialFilePaths(homedir()).some((p) => {
|
|
120
|
+
try { return under(real, realpathSync(p)); } catch { return under(real, p); }
|
|
121
|
+
})) throw new Error("Credential evidence access is refused.");
|
|
122
|
+
const access = under(real, realpathSync(input.recipient.workspace)) ? policy?.projectFiles : policy?.outsideProject;
|
|
123
|
+
if (policy?.enabled && access !== "read" && access !== "read-write") throw new Error("Current file read permission refuses this evidence.");
|
|
124
|
+
return real;
|
|
125
|
+
};
|
|
126
|
+
const waits = store.listWaits({ owner: outcome.owner }).filter((w) => w.origin?.assignmentRef === outcome.assignmentId);
|
|
127
|
+
let logs: Array<{ ref: string; text: string }> = [];
|
|
128
|
+
if (input.operationId) {
|
|
129
|
+
if (!waits.some((w) => w.dependencies.some((d) => d.operationId === input.operationId))) throw new Error("Operation is not an assignment dependency.");
|
|
130
|
+
logs = store.listOperationEvidence(input.operationId).filter((e) => e.kind === "log").slice(0, 2).map((e) => {
|
|
131
|
+
if (!isAbsolute(e.ref)) throw new Error("Legacy dependency log has no verified absolute path; inspect its retained summary instead.");
|
|
132
|
+
const fd = openSync(readable(e.ref), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
133
|
+
try {
|
|
134
|
+
const size = fstatSync(fd).size;
|
|
135
|
+
const bytes = Buffer.alloc(Math.min(size, 4096));
|
|
136
|
+
const count = readSync(fd, bytes, 0, bytes.length, Math.max(0, size - bytes.length));
|
|
137
|
+
return { ref: e.ref, text: bytes.subarray(0, count).toString("utf8") };
|
|
138
|
+
} finally { closeSync(fd); }
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
// Check retained references before recording an inspection, never a worker read.
|
|
142
|
+
const unavailableEvidence: string[] = [];
|
|
143
|
+
for (const pin of [...outcome.evidence, ...store.listEvidencePins({ waitId: outcome.eventId, generation: 1 })]) {
|
|
144
|
+
if ((pin.kind === "log" || pin.kind === "artifact") && isAbsolute(pin.ref)) {
|
|
145
|
+
try { readable(pin.ref); } catch (error) {
|
|
146
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
147
|
+
unavailableEvidence.push(pin.ref);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const request = { assignmentId: outcome.assignmentId, recipient: outcome.recipient, revision: input.revision ?? outcome.revision };
|
|
152
|
+
const record = input.disposition
|
|
153
|
+
? store.consumeAssignmentOutcome({ ...request, disposition: input.disposition, note: input.note ?? "" })
|
|
154
|
+
: store.inspectAssignmentOutcome(request);
|
|
155
|
+
return { outcome: record, unavailableEvidence, dependencies: waits.slice(0, 20).map((w) => ({ waitId: w.waitId, generation: w.generation, phase: w.phase, acknowledgement: w.acknowledgement, dependencies: w.dependencies.slice(0, 20) })), logs };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface AssignmentProjection {
|
|
2
|
+
state: "running" | "waiting" | "completed" | "failed" | "cancelled";
|
|
3
|
+
revision: string;
|
|
4
|
+
reason: string;
|
|
5
|
+
processStatus: string;
|
|
6
|
+
termination: string;
|
|
7
|
+
attemptId: string;
|
|
8
|
+
evidence: string[];
|
|
9
|
+
verified: boolean;
|
|
10
|
+
}
|
|
11
|
+
export function assignmentFor(meta: object, processStatus?: string, options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): AssignmentProjection;
|
|
12
|
+
export function projectAssignment(meta: object, processStatus: string, observation?: object): AssignmentProjection;
|
|
13
|
+
export function assignmentDiagnostic(assignment: AssignmentProjection): string;
|
|
14
|
+
export const ASSIGNMENT_STATES: string[];
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { readAssignmentWaits } from "./shared-operation-coordinator/assignment-observation.mjs";
|
|
6
|
+
|
|
7
|
+
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
8
|
+
|
|
9
|
+
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
10
|
+
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
11
|
+
const waits = observation.waits;
|
|
12
|
+
const pending = waits.find((wait) => !["consumed", "cancelled"].includes(wait.phase));
|
|
13
|
+
let state;
|
|
14
|
+
let reason;
|
|
15
|
+
if (observation.outcome) {
|
|
16
|
+
state = { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[observation.outcome.outcome];
|
|
17
|
+
reason = observation.outcome.reason;
|
|
18
|
+
} else if (waits[0]?.phase === "cancelled") {
|
|
19
|
+
state = "cancelled";
|
|
20
|
+
reason = waits[0]?.reason || "Assignment explicitly cancelled.";
|
|
21
|
+
} else if (!observation.verified && (meta.operations || meta.park)) {
|
|
22
|
+
state = "waiting";
|
|
23
|
+
reason = observation.reason;
|
|
24
|
+
} else if (pending) {
|
|
25
|
+
state = "waiting";
|
|
26
|
+
reason = pending.reason || (pending.phase === "ready" || pending.phase === "resuming"
|
|
27
|
+
? "Dependency evidence awaits worker interpretation."
|
|
28
|
+
: "Waiting for dependencies and supervised continuation.");
|
|
29
|
+
} else if (meta.status === "killed") {
|
|
30
|
+
state = "cancelled";
|
|
31
|
+
reason = "Assignment explicitly cancelled.";
|
|
32
|
+
} else if (processStatus === "running") {
|
|
33
|
+
state = "running";
|
|
34
|
+
reason = "Worker is advancing the assignment.";
|
|
35
|
+
} else if (meta.status === "failed") {
|
|
36
|
+
state = "failed";
|
|
37
|
+
reason = meta.failureReason || "Worker execution failed; retained evidence is available.";
|
|
38
|
+
} else if (meta.status === "completed" && !String(meta.lifecycleClassification ?? "").startsWith("incomplete") && (!meta.park || waits.some((wait) =>
|
|
39
|
+
wait.acknowledgement?.disposition === "assignment-complete"))) {
|
|
40
|
+
state = "completed";
|
|
41
|
+
reason = "Assigned work and required interpretation are complete.";
|
|
42
|
+
} else {
|
|
43
|
+
state = "waiting";
|
|
44
|
+
reason = meta.park && waits.some((wait) => wait.phase === "consumed")
|
|
45
|
+
? "Dependency interpretation recorded; assignment completion is not yet proven."
|
|
46
|
+
: "Execution outcome is unverified; supervised reconciliation is required.";
|
|
47
|
+
}
|
|
48
|
+
reason = String(reason ?? "Assignment state is unverified.").slice(0, 512);
|
|
49
|
+
const evidence = waits.slice(0, 8).map((wait) => `wait:${wait.waitId}:${wait.generation}`);
|
|
50
|
+
evidence.push(`run:${meta.id}:output.log`, `run:${meta.id}:meta.json`);
|
|
51
|
+
const revision = createHash("sha256").update(JSON.stringify([meta.rootRunId ?? meta.id, meta.id, state, reason, evidence])).digest("hex").slice(0, 16);
|
|
52
|
+
return { state, reason, revision, attemptId: meta.id, processStatus,
|
|
53
|
+
termination: !["running", "orphaned", "lost", "exited"].includes(processStatus)
|
|
54
|
+
&& (typeof meta.exitCode === "number" || meta.signal) ? "attempt exit recorded" : "unproven",
|
|
55
|
+
evidence, verified: observation.verified };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
|
|
59
|
+
export function assignmentFor(meta, processStatus = meta.status, options = {}) {
|
|
60
|
+
const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
|
|
61
|
+
const attempts = new Map([[meta.id, meta]]);
|
|
62
|
+
let current = meta;
|
|
63
|
+
try {
|
|
64
|
+
for (const id of (meta.operations || meta.park ? readdirSync(join(base, "runs")) : [])) {
|
|
65
|
+
try {
|
|
66
|
+
const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
|
|
67
|
+
if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
|
|
68
|
+
&& (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
|
|
69
|
+
} catch { /* A partial unrelated record must not hide a continuation. */ }
|
|
70
|
+
}
|
|
71
|
+
} catch { /* Registry gaps cannot establish a newer attempt. */ }
|
|
72
|
+
// Conversation roots survive explicit follow-ups. Only automatic resume edges
|
|
73
|
+
// join attempts into one assignment; manual continuation starts a new one.
|
|
74
|
+
const lineage = new Map([[meta.id, meta]]);
|
|
75
|
+
let ancestor = meta;
|
|
76
|
+
while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
|
|
77
|
+
ancestor = attempts.get(ancestor.resumedFrom);
|
|
78
|
+
lineage.set(ancestor.id, ancestor);
|
|
79
|
+
}
|
|
80
|
+
let added;
|
|
81
|
+
do {
|
|
82
|
+
added = false;
|
|
83
|
+
for (const candidate of attempts.values()) {
|
|
84
|
+
if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
|
|
85
|
+
lineage.set(candidate.id, candidate);
|
|
86
|
+
added = true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} while (added);
|
|
90
|
+
for (const candidate of lineage.values()) {
|
|
91
|
+
if (candidate.startedAt > current.startedAt) current = candidate;
|
|
92
|
+
}
|
|
93
|
+
const status = current.id === meta.id ? processStatus : current.status;
|
|
94
|
+
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
95
|
+
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
96
|
+
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
97
|
+
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
98
|
+
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
99
|
+
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
100
|
+
attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
|
|
101
|
+
? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
|
|
102
|
+
: current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
|
|
103
|
+
: { verified: true, waits: [] });
|
|
104
|
+
return projectAssignment(current, status, observation);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function assignmentDiagnostic(assignment) {
|
|
108
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
109
|
+
}
|
package/cleanup.ts
CHANGED
|
@@ -40,6 +40,11 @@ import {
|
|
|
40
40
|
} from "./continuation.ts";
|
|
41
41
|
import { processExists } from "./spawn.ts";
|
|
42
42
|
import { archiveCompletedAttempt, archivePublicationPending, listArchivedAttempts } from "./session-store.ts";
|
|
43
|
+
import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
|
|
44
|
+
|
|
45
|
+
function outcomeProtected(meta: RunMeta): boolean {
|
|
46
|
+
try { return assignmentRetainsEvidence(meta); } catch { return true; }
|
|
47
|
+
}
|
|
43
48
|
|
|
44
49
|
export const DEFAULT_CLEANUP_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
45
50
|
|
|
@@ -327,6 +332,11 @@ function planCleanupOccupancy(
|
|
|
327
332
|
): CleanupOccupancy {
|
|
328
333
|
const runIds = new Set<string>(protect?.runIds ?? []);
|
|
329
334
|
const paths = [...(protect?.paths ?? [])];
|
|
335
|
+
for (const meta of metas) {
|
|
336
|
+
if (outcomeProtected(meta)) {
|
|
337
|
+
runIds.add(meta.id);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
330
340
|
|
|
331
341
|
// A protected path may be the shared workspace or something inside it. The
|
|
332
342
|
// run whose removal would delete it is protected instead, because
|
|
@@ -569,6 +579,7 @@ function ageSweepEligible(
|
|
|
569
579
|
scope: CleanupScope,
|
|
570
580
|
): boolean {
|
|
571
581
|
if (!TERMINAL_CLEANUP_STATUSES.has(meta.status)) return false;
|
|
582
|
+
if (outcomeProtected(meta)) return false;
|
|
572
583
|
if (retained.has(meta.sessionId)) return false;
|
|
573
584
|
// The run directory still holds the only copy of this conversation's recipe.
|
|
574
585
|
if (scope.archivePending.has(meta.id)) return false;
|
|
@@ -986,6 +997,7 @@ function removeSizeCappedRun(
|
|
|
986
997
|
if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return "retained";
|
|
987
998
|
const fresh = readMeta(id) ?? meta;
|
|
988
999
|
if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
|
|
1000
|
+
if (outcomeProtected(fresh)) return "retained";
|
|
989
1001
|
if (scope.occupancy.runIds.has(fresh.id)) return "retained";
|
|
990
1002
|
if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
|
|
991
1003
|
errors.push(`${runDir(id)}: could not remove run artifacts`);
|
package/config.ts
CHANGED
|
@@ -195,6 +195,7 @@ export function writeSubagentSettings(
|
|
|
195
195
|
settings: {
|
|
196
196
|
delegationMode: DelegationMode;
|
|
197
197
|
maxConcurrent: number;
|
|
198
|
+
maxMinutes?: number;
|
|
198
199
|
/** Omit to preserve the saved value; `null` explicitly records discovery. */
|
|
199
200
|
defaultSkills?: string[] | null;
|
|
200
201
|
/** Omit to preserve the saved value. `0` disables that alert. */
|
|
@@ -207,12 +208,15 @@ export function writeSubagentSettings(
|
|
|
207
208
|
if (!isDelegationMode(settings.delegationMode)) throw new Error("Invalid delegation mode.");
|
|
208
209
|
if (!isConcurrencyCap(settings.maxConcurrent)) throw new Error("Concurrent subagents must be a positive whole number.");
|
|
209
210
|
const next: {
|
|
210
|
-
delegationMode: DelegationMode; maxConcurrent: number; defaultSkills?: string[] | null;
|
|
211
|
+
delegationMode: DelegationMode; maxConcurrent: number; maxMinutes?: number; defaultSkills?: string[] | null;
|
|
211
212
|
toolWaitMinutes?: number; stuckMinutes?: number;
|
|
212
213
|
} = {
|
|
213
214
|
delegationMode: settings.delegationMode,
|
|
214
215
|
maxConcurrent: settings.maxConcurrent,
|
|
215
216
|
};
|
|
217
|
+
if (settings.maxMinutes !== undefined) {
|
|
218
|
+
next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
|
|
219
|
+
}
|
|
216
220
|
if (Object.hasOwn(settings, "defaultSkills")) {
|
|
217
221
|
if (settings.defaultSkills === null) {
|
|
218
222
|
next.defaultSkills = null;
|
package/docs/usage.md
CHANGED
|
@@ -283,15 +283,18 @@ by the existing harness runtime.
|
|
|
283
283
|
Timeout control belongs to the harness, not to the prompt or the skill that
|
|
284
284
|
launched the run. A time limit written into a prompt is enforced by nothing, and
|
|
285
285
|
a parent that only notices late tends to kill a child that was still making
|
|
286
|
-
progress. Every run gets a tool-wait alert
|
|
287
|
-
|
|
288
|
-
agent from a stalled one.
|
|
286
|
+
progress. Every run gets a tool-wait alert, stall detection, and a 60-minute hard
|
|
287
|
+
timeout by default. Soft deadlines remain opt-in because total runtime does not
|
|
288
|
+
distinguish a slow agent from a stalled one.
|
|
289
|
+
Use Timeout (minutes) in `/subagents settings` to change the session default;
|
|
290
|
+
Ctrl+S saves it for future sessions. `0` disables the timeout. Changes apply to
|
|
291
|
+
new attempts, not runs already in progress.
|
|
289
292
|
|
|
290
293
|
| Control | Default | What happens |
|
|
291
294
|
|---------|---------|--------------|
|
|
292
295
|
| Soft deadline (`deadline_minutes`) | Off | When configured, the child gets one steering message (delivered through Pi's steer queue after its current tool call finishes): stop starting new work, commit or save what is done, and report what is complete, what is not, and where the work is. The parent gets one wake saying so. |
|
|
293
296
|
| Grace (`grace_minutes`) | 5 | Grace starts when the steering message actually reaches the child, which is after its current tool call. While the message is still waiting behind a running tool call, the deadline stop is held, so a test run that began just before the deadline is not killed mid-run. If the child has not finished by the end of grace, the harness stops it; the ordinary completion callback reports `killed; stopped: deadline`. A child that completes inside grace is not stopped; its surfaces say `deadline: finished in grace`. |
|
|
294
|
-
| Hard ceiling (`max_minutes`) |
|
|
297
|
+
| Hard ceiling (`max_minutes`) | 60 | When configured, the run is stopped at once, without grace or a steer, and reported as `stopped: ceiling`. The ceiling bounds the run, including a tool call that never ends and an orphaned run (child gone, its process group still alive). |
|
|
295
298
|
| Tool-wait window (`tool_wait_minutes`) | 5 | One tool call that stays open this long sends one factual parent wake for that call, including when it is a normal long test. Parallel calls alert independently. The alert never stops, cancels, or restarts the run, and a later call can alert on its own. |
|
|
296
299
|
| Stuck window (`stuck_minutes`) | 10 | No progress (see below) for this long wakes the parent once (`stuck`). It never stops the run. After new progress, a later stuck spell wakes again. Time inside a running tool call is excluded, so tool waiting and no-progress are reported separately. |
|
|
297
300
|
|
|
@@ -351,8 +354,9 @@ three times wakes the parent once as an `Action required` incident
|
|
|
351
354
|
deadline), `deadline: passed` (ended some other way after the deadline, for
|
|
352
355
|
example it crashed or a user stopped it), `stopped: ceiling`, or `stuck`. The spawn response lists the limits in force.
|
|
353
356
|
|
|
354
|
-
**Global defaults.** Precedence is spawn parameter, then
|
|
355
|
-
`config.json`, then the
|
|
357
|
+
**Global defaults.** Precedence is spawn parameter, then the session timeout
|
|
358
|
+
choice (for `max_minutes`), then environment, then `config.json`, then the
|
|
359
|
+
built-in default:
|
|
356
360
|
|
|
357
361
|
| Setting | Environment | `config.json` |
|
|
358
362
|
|---------|-------------|---------------|
|
package/finalization.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { buildCompletionDelivery } from "./completion.ts";
|
|
9
9
|
import { collectRunFailures, failurePath } from "./failures.ts";
|
|
10
10
|
import { observeFailures } from "./shared-failure-observations.ts";
|
|
11
|
+
import { commitAssignmentTerminal } from "./assignment-outcomes.ts";
|
|
11
12
|
import {
|
|
12
13
|
classifyChildExit,
|
|
13
14
|
type ChildExitOutcome,
|
|
@@ -114,6 +115,7 @@ export function finalizeRun(
|
|
|
114
115
|
}
|
|
115
116
|
}
|
|
116
117
|
writeMeta(meta);
|
|
118
|
+
commitAssignmentTerminal(meta);
|
|
117
119
|
if (!parked && park.record) {
|
|
118
120
|
// A park disposition existed but could not be proven on exit. Hold it in
|
|
119
121
|
// both durable copies (park.json + metadata) so nothing resumes it; the
|