pi-better-server 0.2.4 → 0.3.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/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
/** Read-only, bounded projection input. Never creates/migrates a database. */
|
|
6
|
+
export function readAssignmentWaits(path, owner, connection) {
|
|
7
|
+
let db;
|
|
8
|
+
try {
|
|
9
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
10
|
+
db = connection ?? new DatabaseSync(path, { readOnly: true });
|
|
11
|
+
// v4 adds repair accounting; the observed wait/outcome fields are unchanged.
|
|
12
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
|
|
13
|
+
return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
|
|
14
|
+
}
|
|
15
|
+
const rows = db.prepare(`SELECT wait_id, generation, phase, phase_reason,
|
|
16
|
+
acknowledgement_json, cancel_epoch FROM waits
|
|
17
|
+
WHERE owner_kind = 'worker-conversation' AND owner_session_id = ? AND owner_workspace = ?
|
|
18
|
+
${owner.assignmentId ? "AND json_extract(origin_json, '$.assignmentRef') = ?" : `AND (
|
|
19
|
+
EXISTS (SELECT 1 FROM json_each(?) AS attempt
|
|
20
|
+
WHERE attempt.value = json_extract(waits.origin_json, '$.attemptId')
|
|
21
|
+
OR attempt.value = json_extract(waits.park_json, '$.attemptId'))
|
|
22
|
+
OR EXISTS (SELECT 1 FROM resume_claims AS claim, json_each(?) AS attempt
|
|
23
|
+
WHERE claim.wait_id = waits.wait_id AND claim.generation = waits.generation
|
|
24
|
+
AND claim.attempt_id = attempt.value)
|
|
25
|
+
OR EXISTS (SELECT 1 FROM json_each(?) AS ref
|
|
26
|
+
WHERE json_extract(ref.value, '$.waitId') = waits.wait_id
|
|
27
|
+
AND json_extract(ref.value, '$.generation') = waits.generation)
|
|
28
|
+
)`}
|
|
29
|
+
ORDER BY created_at DESC, generation DESC LIMIT 100`).all(owner.sessionId, owner.workspace,
|
|
30
|
+
...(owner.assignmentId ? [owner.assignmentId] : [JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.waitRefs ?? [])]));
|
|
31
|
+
const record = owner.assignmentId ? db.prepare("SELECT record_json FROM assignment_outcomes WHERE assignment_id = ?").get(owner.assignmentId) : null;
|
|
32
|
+
const outcome = record ? JSON.parse(record.record_json) : null;
|
|
33
|
+
if (outcome && (outcome.owner.sessionId !== owner.sessionId || outcome.owner.workspace !== owner.workspace)) throw new Error("Foreign assignment outcome");
|
|
34
|
+
return { verified: true, outcome, waits: rows.map((row) => ({
|
|
35
|
+
waitId: row.wait_id, generation: row.generation, phase: row.phase,
|
|
36
|
+
reason: row.phase_reason, cancelEpoch: row.cancel_epoch,
|
|
37
|
+
acknowledgement: row.acknowledgement_json ? JSON.parse(row.acknowledgement_json) : null,
|
|
38
|
+
})) };
|
|
39
|
+
} catch {
|
|
40
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
41
|
+
} finally {
|
|
42
|
+
if (!connection) db?.close();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A root read model owns this connection; ordinary observers remain one-shot. */
|
|
47
|
+
export function createAssignmentReader(path) {
|
|
48
|
+
let db;
|
|
49
|
+
let identity;
|
|
50
|
+
const statements = new Map();
|
|
51
|
+
return {
|
|
52
|
+
revision() {
|
|
53
|
+
const { statSync } = createRequire(import.meta.url)("node:fs");
|
|
54
|
+
const stat = statSync(path, { bigint: true });
|
|
55
|
+
const next = `${stat.dev}:${stat.ino}`;
|
|
56
|
+
if (identity !== next) {
|
|
57
|
+
db?.close();
|
|
58
|
+
db = undefined;
|
|
59
|
+
statements.clear();
|
|
60
|
+
identity = next;
|
|
61
|
+
}
|
|
62
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
63
|
+
db ??= new DatabaseSync(path, { readOnly: true });
|
|
64
|
+
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
65
|
+
},
|
|
66
|
+
read(owner) {
|
|
67
|
+
try {
|
|
68
|
+
this.revision();
|
|
69
|
+
return readAssignmentWaits(path, owner, { prepare(sql) {
|
|
70
|
+
if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
|
|
71
|
+
return statements.get(sql);
|
|
72
|
+
} });
|
|
73
|
+
} catch {
|
|
74
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
conversationRevisions() {
|
|
78
|
+
try {
|
|
79
|
+
this.revision();
|
|
80
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
|
|
81
|
+
const hashes = new Map();
|
|
82
|
+
const add = (sessionId, workspace, value) => {
|
|
83
|
+
const key = JSON.stringify([sessionId, workspace]);
|
|
84
|
+
if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
|
|
85
|
+
hashes.get(key).update(JSON.stringify(value));
|
|
86
|
+
};
|
|
87
|
+
// One source pass per changed database revision, instead of one
|
|
88
|
+
// projection/query/log parse for every historical attempt.
|
|
89
|
+
for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
|
|
90
|
+
FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
|
|
91
|
+
FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
|
|
92
|
+
add(row.owner_session_id, row.owner_workspace, row);
|
|
93
|
+
}
|
|
94
|
+
for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
|
|
95
|
+
const record = JSON.parse(row.record_json);
|
|
96
|
+
add(record.owner.sessionId, record.owner.workspace, record);
|
|
97
|
+
}
|
|
98
|
+
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
99
|
+
} catch { return undefined; }
|
|
100
|
+
},
|
|
101
|
+
close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function createAssignmentProjector(options?: { attempts?: any[]; observe?: (owner: any) => any }): (meta: any, processStatus?: string) => any;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/assignment-projection.mjs. Do not edit directly.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { readAssignmentWaits } from "./assignment-observation.mjs";
|
|
8
|
+
|
|
9
|
+
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
10
|
+
const observations = new AsyncLocalStorage();
|
|
11
|
+
|
|
12
|
+
/** Bind an immutable observation to one read call, never to a supervision loop. */
|
|
13
|
+
export function withAssignmentObservations(rows, read) {
|
|
14
|
+
return observations.run(new Map(rows.map(row => [row.meta.id, row.assignment])), read);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
18
|
+
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
19
|
+
const waits = observation.waits;
|
|
20
|
+
const pending = waits.find((wait) => !["consumed", "cancelled"].includes(wait.phase));
|
|
21
|
+
let state;
|
|
22
|
+
let reason;
|
|
23
|
+
if (observation.outcome) {
|
|
24
|
+
state = { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[observation.outcome.outcome];
|
|
25
|
+
reason = observation.outcome.reason;
|
|
26
|
+
} else if (waits[0]?.phase === "cancelled") {
|
|
27
|
+
state = "cancelled";
|
|
28
|
+
reason = waits[0]?.reason || "Assignment explicitly cancelled.";
|
|
29
|
+
} else if (!observation.verified && (meta.operations || meta.park)) {
|
|
30
|
+
state = "waiting";
|
|
31
|
+
reason = observation.reason;
|
|
32
|
+
} else if (pending) {
|
|
33
|
+
state = "waiting";
|
|
34
|
+
reason = pending.reason || (pending.phase === "ready" || pending.phase === "resuming"
|
|
35
|
+
? "Dependency evidence awaits worker interpretation."
|
|
36
|
+
: "Waiting for dependencies and supervised continuation.");
|
|
37
|
+
} else if (meta.status === "killed") {
|
|
38
|
+
state = "cancelled";
|
|
39
|
+
reason = "Assignment explicitly cancelled.";
|
|
40
|
+
} else if (processStatus === "running") {
|
|
41
|
+
state = "running";
|
|
42
|
+
reason = "Worker is advancing the assignment.";
|
|
43
|
+
} else if (meta.status === "failed") {
|
|
44
|
+
state = "failed";
|
|
45
|
+
reason = meta.failureReason || "Worker execution failed; retained evidence is available.";
|
|
46
|
+
} else if (meta.status === "completed" && !String(meta.lifecycleClassification ?? "").startsWith("incomplete") && (!meta.park || waits.some((wait) =>
|
|
47
|
+
wait.acknowledgement?.disposition === "assignment-complete"))) {
|
|
48
|
+
state = "completed";
|
|
49
|
+
reason = "Assigned work and required interpretation are complete.";
|
|
50
|
+
} else {
|
|
51
|
+
state = "waiting";
|
|
52
|
+
reason = meta.park && waits.some((wait) => wait.phase === "consumed")
|
|
53
|
+
? "Dependency interpretation recorded; assignment completion is not yet proven."
|
|
54
|
+
: "Execution outcome is unverified; supervised reconciliation is required.";
|
|
55
|
+
}
|
|
56
|
+
reason = String(reason ?? "Assignment state is unverified.").slice(0, 512);
|
|
57
|
+
const evidence = waits.slice(0, 8).map((wait) => `wait:${wait.waitId}:${wait.generation}`);
|
|
58
|
+
evidence.push(`run:${meta.id}:output.log`, `run:${meta.id}:meta.json`);
|
|
59
|
+
const revision = createHash("sha256").update(JSON.stringify([meta.rootRunId ?? meta.id, meta.id, state, reason, evidence])).digest("hex").slice(0, 16);
|
|
60
|
+
return { state, reason, revision, attemptId: meta.id, processStatus,
|
|
61
|
+
termination: !["running", "orphaned", "lost", "exited"].includes(processStatus)
|
|
62
|
+
&& (typeof meta.exitCode === "number" || meta.signal) ? "attempt exit recorded" : "unproven",
|
|
63
|
+
evidence, verified: observation.verified };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
|
|
67
|
+
export function assignmentFor(meta, processStatus = meta.status, options = {}) {
|
|
68
|
+
return createAssignmentProjector(options)(meta, processStatus);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function readAttempt(base, id) {
|
|
72
|
+
try {
|
|
73
|
+
const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
|
|
74
|
+
return candidate && typeof candidate === "object" ? candidate : undefined;
|
|
75
|
+
} catch { /* A partial unrelated record must not hide a continuation. */ }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const attemptIndexes = new Map();
|
|
79
|
+
const UNCOMMITTED_RETRY_MS = 1_000;
|
|
80
|
+
const conversationKey = (sessionId, cwd) => JSON.stringify([sessionId, cwd]);
|
|
81
|
+
|
|
82
|
+
function removeIdentity(index, id) {
|
|
83
|
+
const key = index.identities.get(id);
|
|
84
|
+
if (key === undefined) return;
|
|
85
|
+
index.identities.delete(id);
|
|
86
|
+
const group = index.byConversation.get(key);
|
|
87
|
+
group.delete(id);
|
|
88
|
+
if (!group.size) index.byConversation.delete(key);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function setIdentity(index, id, candidate) {
|
|
92
|
+
const key = conversationKey(candidate.sessionId, candidate.cwd);
|
|
93
|
+
if (index.identities.get(id) === key) return;
|
|
94
|
+
removeIdentity(index, id);
|
|
95
|
+
index.identities.set(id, key);
|
|
96
|
+
let group = index.byConversation.get(key);
|
|
97
|
+
if (!group) index.byConversation.set(key, group = new Set());
|
|
98
|
+
group.add(id);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function runsSignature(base) {
|
|
102
|
+
try {
|
|
103
|
+
const stat = statSync(join(base, "runs"), { bigint: true });
|
|
104
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
105
|
+
} catch { return undefined; }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function prepareAttemptIndex(options) {
|
|
109
|
+
const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
|
|
110
|
+
const signature = runsSignature(base);
|
|
111
|
+
if (!signature) {
|
|
112
|
+
attemptIndexes.delete(base);
|
|
113
|
+
return { index: { base, byConversation: new Map() } };
|
|
114
|
+
}
|
|
115
|
+
let index = attemptIndexes.get(base);
|
|
116
|
+
let initialAttempts;
|
|
117
|
+
if (!index) {
|
|
118
|
+
let ids;
|
|
119
|
+
try { ids = new Set(readdirSync(join(base, "runs"))); }
|
|
120
|
+
catch { return { index: { base, byConversation: new Map() } }; }
|
|
121
|
+
index = { base, signature, ids, identities: new Map(), byConversation: new Map(),
|
|
122
|
+
uncommitted: new Set(), nextRetryAt: Date.now() + UNCOMMITTED_RETRY_MS };
|
|
123
|
+
initialAttempts = new Map();
|
|
124
|
+
for (const id of ids) {
|
|
125
|
+
const candidate = readAttempt(base, id);
|
|
126
|
+
if (candidate) {
|
|
127
|
+
setIdentity(index, id, candidate);
|
|
128
|
+
initialAttempts.set(id, candidate);
|
|
129
|
+
}
|
|
130
|
+
else index.uncommitted.add(id);
|
|
131
|
+
}
|
|
132
|
+
attemptIndexes.set(base, index);
|
|
133
|
+
if (attemptIndexes.size > 8) attemptIndexes.delete(attemptIndexes.keys().next().value);
|
|
134
|
+
} else if (index.signature !== signature) {
|
|
135
|
+
let ids;
|
|
136
|
+
try { ids = new Set(readdirSync(join(base, "runs"))); }
|
|
137
|
+
catch {
|
|
138
|
+
attemptIndexes.delete(base);
|
|
139
|
+
return { index: { base, byConversation: new Map() } };
|
|
140
|
+
}
|
|
141
|
+
for (const id of index.ids) {
|
|
142
|
+
if (ids.has(id)) continue;
|
|
143
|
+
removeIdentity(index, id);
|
|
144
|
+
index.uncommitted.delete(id);
|
|
145
|
+
}
|
|
146
|
+
for (const id of ids) {
|
|
147
|
+
if (index.ids.has(id)) continue;
|
|
148
|
+
const candidate = readAttempt(base, id);
|
|
149
|
+
if (candidate) setIdentity(index, id, candidate);
|
|
150
|
+
else index.uncommitted.add(id);
|
|
151
|
+
}
|
|
152
|
+
index.ids = ids;
|
|
153
|
+
index.signature = signature;
|
|
154
|
+
}
|
|
155
|
+
if (Date.now() >= index.nextRetryAt) {
|
|
156
|
+
for (const id of index.uncommitted) {
|
|
157
|
+
const candidate = readAttempt(base, id);
|
|
158
|
+
if (!candidate) continue;
|
|
159
|
+
setIdentity(index, id, candidate);
|
|
160
|
+
index.uncommitted.delete(id);
|
|
161
|
+
}
|
|
162
|
+
index.nextRetryAt = Date.now() + UNCOMMITTED_RETRY_MS;
|
|
163
|
+
}
|
|
164
|
+
return { index, initialAttempts };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readConversationAttempts(index, meta, initialAttempts) {
|
|
168
|
+
const matches = [];
|
|
169
|
+
for (const id of index.byConversation.get(conversationKey(meta.sessionId, meta.cwd)) ?? []) {
|
|
170
|
+
const fresh = initialAttempts?.get(id) ?? readAttempt(index.base, id);
|
|
171
|
+
if (!fresh) {
|
|
172
|
+
removeIdentity(index, id);
|
|
173
|
+
index.uncommitted.add(id);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
setIdentity(index, id, fresh);
|
|
177
|
+
if (fresh.sessionId === meta.sessionId && fresh.cwd === meta.cwd) matches.push(fresh);
|
|
178
|
+
}
|
|
179
|
+
return matches;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One synchronous UI refresh shares a snapshot; the next refresh reads disk again. */
|
|
183
|
+
export function createAssignmentProjector(options = {}) {
|
|
184
|
+
let prepared;
|
|
185
|
+
const snapshots = new Map();
|
|
186
|
+
const readSnapshot = (meta) => {
|
|
187
|
+
if (options.attempts) return options.attempts;
|
|
188
|
+
const key = conversationKey(meta.sessionId, meta.cwd);
|
|
189
|
+
if (!snapshots.has(key)) {
|
|
190
|
+
prepared ??= prepareAttemptIndex(options);
|
|
191
|
+
snapshots.set(key, readConversationAttempts(prepared.index, meta, prepared.initialAttempts));
|
|
192
|
+
}
|
|
193
|
+
return snapshots.get(key);
|
|
194
|
+
};
|
|
195
|
+
return (meta, processStatus = meta.status) => observations.getStore()?.get(meta.id) ?? assignmentFromSnapshot(meta, processStatus, options,
|
|
196
|
+
() => readSnapshot(meta));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
200
|
+
const attempts = new Map([[meta.id, meta]]);
|
|
201
|
+
let current = meta;
|
|
202
|
+
if (meta.operations || meta.park) {
|
|
203
|
+
for (const candidate of readSnapshot()) {
|
|
204
|
+
if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
|
|
205
|
+
&& (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// Conversation roots survive explicit follow-ups. Only automatic resume edges
|
|
209
|
+
// join attempts into one assignment; manual continuation starts a new one.
|
|
210
|
+
const lineage = new Map([[meta.id, meta]]);
|
|
211
|
+
let ancestor = meta;
|
|
212
|
+
while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
|
|
213
|
+
ancestor = attempts.get(ancestor.resumedFrom);
|
|
214
|
+
lineage.set(ancestor.id, ancestor);
|
|
215
|
+
}
|
|
216
|
+
let added;
|
|
217
|
+
do {
|
|
218
|
+
added = false;
|
|
219
|
+
for (const candidate of attempts.values()) {
|
|
220
|
+
if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
|
|
221
|
+
lineage.set(candidate.id, candidate);
|
|
222
|
+
added = true;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
} while (added);
|
|
226
|
+
for (const candidate of lineage.values()) {
|
|
227
|
+
if (candidate.startedAt > current.startedAt) current = candidate;
|
|
228
|
+
}
|
|
229
|
+
const status = current.id === meta.id ? processStatus : current.status;
|
|
230
|
+
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
231
|
+
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
232
|
+
? (options.observe ?? ((owner) => readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"), owner)))(
|
|
233
|
+
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
234
|
+
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
235
|
+
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
236
|
+
attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
|
|
237
|
+
? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
|
|
238
|
+
: current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
|
|
239
|
+
: { verified: true, waits: [] });
|
|
240
|
+
return projectAssignment(current, status, observation);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function assignmentDiagnostic(assignment, options = {}) {
|
|
244
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}.${options.includeEvidence === false ? "" : ` Evidence: ${assignment.evidence.join(", ")}`}`;
|
|
245
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export function validateCondition(condition) {
|
|
2
|
+
if ((condition.type === "json_path_equals" || condition.type === "json_path_exists") && !parseJsonPath(condition.path)) {
|
|
3
|
+
return `unsupported JSON path: ${condition.path}. Use a root-prefixed path such as $.status or $.terminalFailure.`;
|
|
4
|
+
}
|
|
5
|
+
return undefined;
|
|
6
|
+
}
|
|
7
|
+
export function evaluateCondition(condition, result) {
|
|
8
|
+
switch (condition.type) {
|
|
9
|
+
case "exit_code":
|
|
10
|
+
return { matched: result.exitCode === condition.equals, value: result.exitCode };
|
|
11
|
+
case "stdout_contains":
|
|
12
|
+
return { matched: result.stdout.includes(condition.value) };
|
|
13
|
+
case "stderr_contains":
|
|
14
|
+
return { matched: result.stderr.includes(condition.value) };
|
|
15
|
+
case "json_path_equals": {
|
|
16
|
+
const resolved = resolveJsonPath(result.stdout, condition.path);
|
|
17
|
+
if (!resolved.ok)
|
|
18
|
+
return { matched: false, error: resolved.error };
|
|
19
|
+
return { matched: deepEqual(resolved.value, condition.value), value: resolved.value };
|
|
20
|
+
}
|
|
21
|
+
case "json_path_exists": {
|
|
22
|
+
const resolved = resolveJsonPath(result.stdout, condition.path);
|
|
23
|
+
return resolved.ok ? { matched: true, value: resolved.value } : { matched: false, error: resolved.error };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function resolveJsonPath(jsonText, path) {
|
|
28
|
+
let current;
|
|
29
|
+
try {
|
|
30
|
+
current = JSON.parse(jsonText);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
return { ok: false, error: `stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}` };
|
|
34
|
+
}
|
|
35
|
+
const tokens = parseJsonPath(path);
|
|
36
|
+
if (!tokens)
|
|
37
|
+
return { ok: false, error: `unsupported JSON path: ${path}` };
|
|
38
|
+
for (const token of tokens) {
|
|
39
|
+
if (typeof token === "number") {
|
|
40
|
+
if (!Array.isArray(current) || token < 0 || token >= current.length) {
|
|
41
|
+
return { ok: false, error: `JSON path not found: ${path}` };
|
|
42
|
+
}
|
|
43
|
+
current = current[token];
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (current === null || typeof current !== "object" || !(token in current)) {
|
|
47
|
+
return { ok: false, error: `JSON path not found: ${path}` };
|
|
48
|
+
}
|
|
49
|
+
current = current[token];
|
|
50
|
+
}
|
|
51
|
+
return { ok: true, value: current };
|
|
52
|
+
}
|
|
53
|
+
function parseJsonPath(path) {
|
|
54
|
+
if (!path.startsWith("$"))
|
|
55
|
+
return undefined;
|
|
56
|
+
const tokens = [];
|
|
57
|
+
let i = 1;
|
|
58
|
+
while (i < path.length) {
|
|
59
|
+
if (path[i] === ".") {
|
|
60
|
+
i += 1;
|
|
61
|
+
const start = i;
|
|
62
|
+
while (i < path.length && /[A-Za-z0-9_$-]/.test(path[i]))
|
|
63
|
+
i += 1;
|
|
64
|
+
if (i === start)
|
|
65
|
+
return undefined;
|
|
66
|
+
tokens.push(path.slice(start, i));
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (path[i] === "[") {
|
|
70
|
+
const end = path.indexOf("]", i);
|
|
71
|
+
if (end === -1)
|
|
72
|
+
return undefined;
|
|
73
|
+
const raw = path.slice(i + 1, end).trim();
|
|
74
|
+
const quoted = raw.match(/^['\"](.+)['\"]$/);
|
|
75
|
+
if (quoted) {
|
|
76
|
+
tokens.push(quoted[1]);
|
|
77
|
+
}
|
|
78
|
+
else if (/^\d+$/.test(raw)) {
|
|
79
|
+
tokens.push(Number(raw));
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
i = end + 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
return tokens;
|
|
90
|
+
}
|
|
91
|
+
function deepEqual(a, b) {
|
|
92
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
93
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
/**
|
|
3
|
+
* Process start-token reads.
|
|
4
|
+
*
|
|
5
|
+
* `ps` is a process spawn. Reading it on a rendering path — once per task, per
|
|
6
|
+
* frame, for every terminal task kept in the panel — is a measurable CPU drain
|
|
7
|
+
* on its own, and it competes with the very commands the panel is showing.
|
|
8
|
+
*
|
|
9
|
+
* Two rules keep that bounded:
|
|
10
|
+
*
|
|
11
|
+
* 1. A pid's start token is immutable for the life of that pid, so a short-lived
|
|
12
|
+
* memo is safe. Entries expire so a recycled pid is re-read rather than
|
|
13
|
+
* mistaking the previous owner's token for the current one, and failures are
|
|
14
|
+
* memoized too, so a pid that cannot be read is not retried on every frame.
|
|
15
|
+
* 2. Callers that decide to *signal* a pid can ask for a fresh read. Liveness
|
|
16
|
+
* display may use the memo; authorization may not.
|
|
17
|
+
*/
|
|
18
|
+
/** How long one pid→token answer is trusted. Short enough to bound pid reuse. */
|
|
19
|
+
const TOKEN_MEMO_TTL_MS = 1_000;
|
|
20
|
+
/** Bound on memo entries; the panel is small, but a long session is not. */
|
|
21
|
+
const TOKEN_MEMO_MAX_ENTRIES = 512;
|
|
22
|
+
const tokenMemo = new Map();
|
|
23
|
+
function readTokenUncached(pid) {
|
|
24
|
+
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
|
|
25
|
+
return undefined;
|
|
26
|
+
try {
|
|
27
|
+
const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
28
|
+
encoding: "utf8",
|
|
29
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
30
|
+
timeout: 2_000,
|
|
31
|
+
}).trim();
|
|
32
|
+
return output || undefined;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function remember(pid, token, now) {
|
|
39
|
+
if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
|
|
40
|
+
// Drop expired entries first; only evict live ones if that was not enough.
|
|
41
|
+
for (const [candidate, entry] of tokenMemo) {
|
|
42
|
+
if (now - entry.readAt >= TOKEN_MEMO_TTL_MS)
|
|
43
|
+
tokenMemo.delete(candidate);
|
|
44
|
+
}
|
|
45
|
+
if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
|
|
46
|
+
const oldest = tokenMemo.keys().next();
|
|
47
|
+
if (!oldest.done)
|
|
48
|
+
tokenMemo.delete(oldest.value);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
tokenMemo.set(pid, { token, readAt: now });
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Start token for `pid`, memoized for {@link TOKEN_MEMO_TTL_MS}.
|
|
55
|
+
*
|
|
56
|
+
* Suitable for liveness and display. A caller that is about to send a signal
|
|
57
|
+
* must use {@link readProcessStartTokenFresh} instead.
|
|
58
|
+
*/
|
|
59
|
+
export function readProcessStartToken(pid) {
|
|
60
|
+
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
|
|
61
|
+
return undefined;
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
const entry = tokenMemo.get(pid);
|
|
64
|
+
if (entry && now - entry.readAt < TOKEN_MEMO_TTL_MS)
|
|
65
|
+
return entry.token;
|
|
66
|
+
const token = readTokenUncached(pid);
|
|
67
|
+
remember(pid, token, now);
|
|
68
|
+
return token;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Start token for `pid`, always read from the OS.
|
|
72
|
+
*
|
|
73
|
+
* Used where the answer authorizes a signal, so a recycled pid cannot inherit
|
|
74
|
+
* a memoized identity.
|
|
75
|
+
*/
|
|
76
|
+
export function readProcessStartTokenFresh(pid) {
|
|
77
|
+
if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
|
|
78
|
+
return undefined;
|
|
79
|
+
const token = readTokenUncached(pid);
|
|
80
|
+
remember(pid, token, Date.now());
|
|
81
|
+
return token;
|
|
82
|
+
}
|
|
83
|
+
/** Drop every memoized identity. Tests and reloads start from a clean slate. */
|
|
84
|
+
export function clearProcessIdentityMemo() {
|
|
85
|
+
tokenMemo.clear();
|
|
86
|
+
}
|
|
87
|
+
const selfStartToken = readTokenUncached(process.pid);
|
|
88
|
+
export function currentProcessStartToken() {
|
|
89
|
+
return selfStartToken;
|
|
90
|
+
}
|
|
91
|
+
export function processIdentityAlive(pid, recordedStartToken, recordedAt) {
|
|
92
|
+
if (!pid || pid <= 0)
|
|
93
|
+
return false;
|
|
94
|
+
try {
|
|
95
|
+
process.kill(pid, 0);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code !== "EPERM")
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
const current = readProcessStartToken(pid);
|
|
102
|
+
if (recordedStartToken && current)
|
|
103
|
+
return recordedStartToken === current;
|
|
104
|
+
if (!recordedStartToken && current && recordedAt !== undefined) {
|
|
105
|
+
const currentStartedAt = Date.parse(current);
|
|
106
|
+
if (Number.isFinite(currentStartedAt) && currentStartedAt > recordedAt + 2_000)
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|