pi-better-server 0.7.2 → 0.8.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.
Files changed (47) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +146 -6
  3. package/src/runtime/background.ts +2 -2
  4. package/src/runtime/catalog.ts +30 -1
  5. package/src/runtime/ci-recovery.ts +172 -0
  6. package/src/runtime/domain/assignment-inbox.mjs +4 -0
  7. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  8. package/src/runtime/domain/assignment-observation.mjs +1 -0
  9. package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
  10. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  11. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  12. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  13. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  14. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +26 -0
  16. package/src/runtime/domain/background-service/observed-waits.ts +24 -0
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  19. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  20. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  21. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  22. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  23. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  24. package/src/runtime/domain/subagents/index.domain.mjs +6 -2
  25. package/src/runtime/domain/subagents/index.ts +7 -2
  26. package/src/runtime/domain/subagents/output-payload.domain.mjs +3 -1
  27. package/src/runtime/domain/subagents/output-payload.ts +2 -0
  28. package/src/runtime/domain/subagents/package.json +1 -1
  29. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  30. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  31. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  32. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  33. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  34. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  35. package/src/runtime/domain/subagents/tools.domain.mjs +3 -2
  36. package/src/runtime/domain/subagents/tools.ts +3 -2
  37. package/src/runtime/domain/subagents/workflow-assignment.domain.mjs +25 -0
  38. package/src/runtime/domain/subagents/workflow-assignment.ts +35 -0
  39. package/src/runtime/queries.ts +17 -3
  40. package/src/runtime/query-executor.ts +57 -5
  41. package/src/runtime/query-worker.mjs +6 -1
  42. package/src/runtime/read-model.ts +14 -5
  43. package/src/runtime/shared-read-diagnosis.ts +29 -0
  44. package/src/runtime/supervisor-admission.ts +42 -0
  45. package/src/runtime/supervisor-decisions.ts +60 -0
  46. package/src/server.ts +3 -3
  47. package/src/version.ts +1 -1
@@ -8,6 +8,8 @@ import { executionPhases, inventoryPhases } from "./read-watchdog-probe.ts";
8
8
  import { notifyWorkBudget } from "./work-budget.ts";
9
9
  import { HostSourceWatches } from "./source-watch.ts";
10
10
 
11
+ const INBOX_DIAGNOSTICS_WAIT_MS = 100;
12
+
11
13
  export interface EncodedRead { json: string }
12
14
  interface Waiter { connection: number; expiresAt: number; deadline: ReturnType<typeof setTimeout>; resolve(value: EncodedRead): void; reject(error: Error): void }
13
15
  interface Query {
@@ -16,7 +18,7 @@ interface Query {
16
18
  }
17
19
  export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
18
20
  interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
19
- interface WorkerMetrics { sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
21
+ interface WorkerMetrics { background?: Record<string, unknown>; sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
20
22
  export interface QueryExecutorOptions {
21
23
  queryCacheDiagnostics?: boolean;
22
24
  capacity?: number; timeoutMs?: number; maxConnections?: number; watchdogMs?: number;
@@ -50,9 +52,12 @@ export class WorkQueryExecutor {
50
52
  private watchdog?: ReturnType<typeof setInterval>;
51
53
  private watchdogCheck?: ReturnType<typeof setImmediate>;
52
54
  private lastResponse = performance.now();
55
+ private gracedHeartbeat?: bigint;
53
56
  private heartbeat!: BigInt64Array;
54
57
  private probe?: Int32Array;
55
58
  private workerMetrics: WorkerMetrics = {};
59
+ private inboxSample?: WorkReadModel["inboxDiagnostics"];
60
+ private inboxRequest?: { ready: Promise<boolean>; finish(fresh: boolean, error?: string): void };
56
61
  private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
57
62
  status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
58
63
  };
@@ -88,13 +93,20 @@ export class WorkQueryExecutor {
88
93
  let resumedAt = previousCheck;
89
94
  this.watchdog = setInterval(() => {
90
95
  const now = performance.now();
91
- // After system sleep both threads can resume with an expired heartbeat.
92
- if (now - previousCheck > watchdogMs) resumedAt = now;
96
+ const delayed = now - previousCheck > watchdogMs;
93
97
  previousCheck = now;
94
98
  if (this.closed || this.failure || now - Math.max(this.lastResponse, resumedAt) <= watchdogMs) return;
95
99
  // Drain queued worker responses before treating a delayed timer as worker silence.
96
100
  this.watchdogCheck ??= setImmediate(() => {
97
101
  this.watchdogCheck = undefined;
102
+ // After system sleep, allow a stale heartbeat one interval to advance.
103
+ const tick = Atomics.load(this.heartbeat, 0);
104
+ if (delayed && this.gracedHeartbeat !== tick &&
105
+ (tick === 0n || Number(process.hrtime.bigint() - tick) / 1e6 > watchdogMs)) {
106
+ this.gracedHeartbeat = tick;
107
+ resumedAt = performance.now();
108
+ return;
109
+ }
98
110
  this.checkWatchdog();
99
111
  });
100
112
  this.watchdogCheck.unref();
@@ -121,6 +133,7 @@ export class WorkQueryExecutor {
121
133
  }
122
134
 
123
135
  private startWorker() {
136
+ this.gracedHeartbeat = undefined;
124
137
  if (this.options.budgetBuffer) {
125
138
  // startWorker runs only initially or after the preceding thread exited.
126
139
  // A dead generation cannot retain source credits in the shared budget.
@@ -180,6 +193,7 @@ export class WorkQueryExecutor {
180
193
  this.workerGeneration++;
181
194
  this.internalRecoveryDemand = false;
182
195
  this.exited = false; this.failure = undefined; this.termination = undefined;
196
+ this.inboxSample = undefined;
183
197
  this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
184
198
  this.lastResponse = performance.now();
185
199
  this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
@@ -223,12 +237,21 @@ export class WorkQueryExecutor {
223
237
  return JSON.parse(result.json);
224
238
  }
225
239
 
240
+ sharedReadHealth() {
241
+ return { state: this.observation().status, generation: this.workerGeneration };
242
+ }
243
+
226
244
  observation() {
227
245
  return this.failure ? { ...this.lastObservation, status: "degraded" as const, reason: this.failure.message } : this.lastObservation;
228
246
  }
229
247
 
230
248
  metrics() {
231
- return { ...this.workerMetrics, sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
249
+ const unavailable = { available: false, received: null, applied: null, pending: null };
250
+ return { ...this.workerMetrics,
251
+ assignments: this.inboxSample?.assignments ?? unavailable,
252
+ background: { ...this.workerMetrics.background, changes: this.inboxSample?.backgroundChanges ?? unavailable },
253
+ inboxDiagnosticsObservedAt: this.inboxSample?.observedAt ?? null,
254
+ sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
232
255
  clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
233
256
  cancelled: this.cancelled, timeouts: this.timeouts, queueTimeouts: this.queueTimeouts, callerTimeouts: this.callerTimeouts,
234
257
  capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
@@ -238,9 +261,30 @@ export class WorkQueryExecutor {
238
261
  status: this.failure ? "degraded" : "ready" } };
239
262
  }
240
263
 
264
+ private sampleInbox(): Promise<boolean> {
265
+ if (this.failure || this.closed) return Promise.resolve(false);
266
+ if (this.inboxRequest) return this.inboxRequest.ready;
267
+
268
+ let finish!: (fresh: boolean, error?: string) => void;
269
+ const ready = new Promise<boolean>((resolve, reject) => {
270
+ // Return cached diagnostics on timeout, but keep the worker request single-flight until its reply.
271
+ const timer = setTimeout(() => resolve(false), INBOX_DIAGNOSTICS_WAIT_MS);
272
+ finish = (fresh, error) => {
273
+ clearTimeout(timer);
274
+ if (error) reject(new Error(error));
275
+ else resolve(fresh);
276
+ };
277
+ });
278
+ this.inboxRequest = { ready, finish };
279
+ this.worker.postMessage({ type: "inbox-diagnostics" });
280
+ return ready;
281
+ }
282
+
241
283
  private request(connection: number, input: Record<string, unknown>): Promise<EncodedRead> {
242
284
  if (connection !== 0 && !this.streams.has(connection)) return Promise.reject(new Error("runtime-unavailable: client disconnected"));
243
- if (input.type === "runtime_get_metrics") return Promise.resolve({ json: JSON.stringify(this.metrics()) });
285
+ if (input.type === "runtime_get_metrics") {
286
+ return this.sampleInbox().then(fresh => ({ json: JSON.stringify({ ...this.metrics(), inboxDiagnosticsFresh: fresh }) }));
287
+ }
244
288
  if (this.failure) {
245
289
  if (connection === 0) this.internalRecoveryDemand = true;
246
290
  this.scheduleRecovery(); return Promise.reject(this.failure);
@@ -315,6 +359,12 @@ export class WorkQueryExecutor {
315
359
  if (message.id === this.active?.id) { this.active = undefined; this.pump(); }
316
360
  return;
317
361
  }
362
+ if (message.type === "inbox-diagnostics") {
363
+ if (message.sample) this.inboxSample = message.sample;
364
+ this.inboxRequest?.finish(Boolean(message.sample), message.error);
365
+ this.inboxRequest = undefined;
366
+ return;
367
+ }
318
368
  if (message.metrics) this.workerMetrics = message.metrics;
319
369
  if (message.observation) this.lastObservation = message.observation;
320
370
  if (message.type === "terminal-logs") {
@@ -397,6 +447,8 @@ export class WorkQueryExecutor {
397
447
  if ([...this.queue, ...(this.active ? [this.active] : [])].some(query =>
398
448
  [...query.waiters].some(waiter => waiter.connection === 0))) this.internalRecoveryDemand = true;
399
449
  this.failure = error; this.lag.disable();
450
+ this.inboxRequest?.finish(false);
451
+ this.inboxRequest = undefined;
400
452
  for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) this.finish(query, error);
401
453
  this.queue = []; this.active = undefined;
402
454
  for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
@@ -85,7 +85,7 @@ let cacheBytes = 0, cacheHits = 0, queryCount = 0, serializationCount = 0;
85
85
  let revisionPending = false, revisionDirty = false;
86
86
  const durations = [];
87
87
  const cacheComparisons = workerData.queryCacheDiagnostics ? [] : undefined;
88
- const metrics = () => ({ ...model.metrics, background: model.backgroundMetrics, sqlite: { ...connections }, cacheHits, queryCount, serializationCount, eventEncoding: { ...queryEncodingMetrics }, cacheBytes,
88
+ const metrics = () => ({ ...model.indexCounters, background: model.backgroundCounters, sqlite: { ...connections }, cacheHits, queryCount, serializationCount, eventEncoding: { ...queryEncodingMetrics }, cacheBytes,
89
89
  cacheEntries: cache.size, queryDurationMs: [...durations], ...(cacheComparisons ? { cacheComparisons: [...cacheComparisons] } : {}) });
90
90
  const snapshot = model.snapshot.bind(model);
91
91
  model.snapshot = scope => observeExecution("snapshot", () => {
@@ -156,6 +156,11 @@ function session(id) {
156
156
  }
157
157
 
158
158
  parentPort.on("message", async message => {
159
+ if (message.type === "inbox-diagnostics") {
160
+ try { parentPort.postMessage({ type: "inbox-diagnostics", sample: model.inboxDiagnostics }); }
161
+ catch (error) { parentPort.postMessage({ type: "inbox-diagnostics", error: String(error).slice(0, 512) }); }
162
+ return;
163
+ }
159
164
  if (message.type === "heartbeat-consumed") { heartbeatPending = false; return; }
160
165
  if (message.type === "cancel") {
161
166
  const request = requests.get(message.id);
@@ -138,8 +138,9 @@ export class WorkReadModel {
138
138
  }
139
139
  return { available: false, received: null, applied: null, pending: null };
140
140
  }
141
- get metrics() {
142
- return { ...this.counters, assignments: this.assignmentMetrics, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
141
+ get metrics() { return { ...this.indexCounters, assignments: this.assignmentMetrics }; }
142
+ get indexCounters() {
143
+ return { ...this.counters, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
143
144
  indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size, sourceParentWatchers: this.rootParents.size, rootParentWatchers: this.rootParents.size };
144
145
  }
145
146
  readonly runs: string;
@@ -350,7 +351,13 @@ export class WorkReadModel {
350
351
  this.listeners.add(notify);
351
352
  return () => { this.listeners.delete(notify); release?.(); };
352
353
  }
353
- get backgroundMetrics() { return { ...this.background.metrics, registry: this.background.registryMetrics, changes: this.background.changeMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
354
+ get inboxDiagnostics() {
355
+ // The owner can yield while applying a batch. Only sample committed queue state.
356
+ if (this.db.isTransaction) return undefined;
357
+ return { assignments: this.assignmentMetrics, backgroundChanges: this.background.changeMetrics, observedAt: Date.now() };
358
+ }
359
+ get backgroundMetrics() { return { ...this.backgroundCounters, changes: this.background.changeMetrics }; }
360
+ get backgroundCounters() { return { ...this.background.metrics, registry: this.background.registryMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
354
361
  observation(reasons = this.observationInitialized ? this.livenessReasons({ refresh: false }) : []) {
355
362
  return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
356
363
  }
@@ -409,10 +416,12 @@ export class WorkReadModel {
409
416
  entry.used = now;
410
417
  return entry;
411
418
  }
419
+ prepareBackgroundQuery() {
420
+ this.background.prepareQuery();
421
+ }
412
422
  contentRevision(scope: WorkScope = {}) {
413
423
  if (scope.background) {
414
424
  if (scope.backgroundHistory) return String(this.revision);
415
- this.background.prepareQuery();
416
425
  return hash([this.revision, this.background.sourceRevision(scope)]);
417
426
  }
418
427
  const entry = this.scopeEntry(scope);
@@ -509,7 +518,7 @@ export class WorkReadModel {
509
518
  this.reader.acknowledgeChanges(changes, false);
510
519
  snapshot.commit();
511
520
  for (const row of updated) this.projected.set(row.meta.id, row);
512
- if (this.reader.changeMetrics.more || this.reader.changeMetrics.pending) this.dirty = true;
521
+ if (this.reader.hasPendingChanges) this.dirty = true;
513
522
  this.coordinator = snapshot.revision;
514
523
  this.counters.assignmentProjections += updated.length; this.counters.projections += updated.length;
515
524
  this.invalidations.assignmentInput += updated.length;
@@ -0,0 +1,29 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export type ReadHealth = "ready" | "rebuilding" | "degraded";
4
+
5
+ /** Group only facts about this daemon's read plane. Never return a scope, operation or owner. */
6
+ export class SharedReadDiagnosis {
7
+ private incident?: { id: string; state: ReadHealth; generation: number; recommendation: string };
8
+ private readonly owners = new Map<string, boolean>();
9
+ verified(owner: string, incident: unknown) {
10
+ if (!this.incident || this.incident.id !== incident || !this.owners.has(owner)) return false;
11
+ this.owners.set(owner, true);
12
+ return true;
13
+ }
14
+ inspect(state: ReadHealth, generation: number, owner: string) {
15
+ if (state === "ready") { this.incident = undefined; this.owners.clear(); return; }
16
+ if (this.incident?.state === state && this.incident.generation === generation) {
17
+ if (!this.owners.has(owner) && this.owners.size < 512) this.owners.set(owner, false);
18
+ return [...this.owners.values()].includes(true)
19
+ ? { ...this.incident, recommendation: "An affected read has recovered. Retry your original observation by ID to verify recovery in this session." }
20
+ : this.incident;
21
+ }
22
+ this.owners.clear();
23
+ this.owners.set(owner, false);
24
+ const recommendation = state === "rebuilding"
25
+ ? "The daemon is rebuilding its shared read inventory. Keep the original operation running. Retry its observation by the original ID once inventory is ready."
26
+ : "The daemon read worker is degraded. Check worker recovery, then read the original operation by ID to verify its state.";
27
+ return this.incident = { id: randomUUID(), state, generation, recommendation };
28
+ }
29
+ }
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ export type ReviewScenario = "stall-diagnosis" | "scope-review" | "commitment-followup";
6
+ export function reviewRevision(agentDir: string, scenario: string) {
7
+ try {
8
+ const raw = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8")).piBetterHarness?.supervisorMode;
9
+ if (raw?.enabled === true && Array.isArray(raw.scenarios) && raw.scenarios.includes(scenario))
10
+ return typeof raw.revision === "string" ? raw.revision : "initial";
11
+ } catch { /* Unreadable settings cannot authorize a review. */ }
12
+ }
13
+
14
+ /** One model analysis per daemon. Leases are short and disappear on daemon replacement. */
15
+ export class SupervisorAdmission {
16
+ private lease?: { token: string; owner: string; scenario: ReviewScenario; revision: string; expires: number };
17
+ private readonly revision: (scenario: ReviewScenario) => string | undefined;
18
+ private readonly now: () => number;
19
+ constructor(revision: (scenario: ReviewScenario) => string | undefined, now = Date.now) {
20
+ this.revision = revision;
21
+ this.now = now;
22
+ }
23
+ request(owner: string, command: Record<string, unknown>) {
24
+ const scenario = command.scenario;
25
+ if (scenario !== "stall-diagnosis" && scenario !== "scope-review" && scenario !== "commitment-followup") throw new Error("Unsupported Supervisor scenario");
26
+ const lease = this.lease;
27
+ const revision = this.revision(scenario);
28
+ if (lease && (lease.expires <= this.now() || lease.revision !== (lease.scenario === scenario ? revision : this.revision(lease.scenario)))) this.lease = undefined;
29
+ if (!revision) return { status: "disabled" };
30
+ if (command.action === "begin") {
31
+ if (this.lease) return { status: "busy" };
32
+ const token = randomUUID();
33
+ this.lease = { owner, scenario, token, revision, expires: this.now() + 45_000 };
34
+ return { status: "admitted", token };
35
+ }
36
+ if (command.action !== "finish" && command.action !== "release") throw new Error("Unsupported Supervisor action");
37
+ if (!this.lease || this.lease.owner !== owner || this.lease.scenario !== scenario || this.lease.token !== command.token)
38
+ return { status: "stale" };
39
+ this.lease = undefined;
40
+ return { status: command.action === "finish" ? "admitted" : "released" };
41
+ }
42
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import { join } from "node:path";
4
+
5
+ const fields = ["reference", "operation", "host", "resource", "effect"] as const;
6
+ type Scope = Record<typeof fields[number], string>;
7
+ const questionMs = 120_000;
8
+ export const decisionDurationMs = 60 * 60_000;
9
+
10
+ function exactScope(raw: unknown): Scope {
11
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Missing decision scope");
12
+ const scope = {} as Scope;
13
+ for (const key of fields) {
14
+ const text = (raw as Scope)[key];
15
+ if (typeof text !== "string" || !text.trim() || text !== text.trim() || text.length > 200 || /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u.test(text)) throw new Error("Invalid decision scope");
16
+ scope[key] = text;
17
+ }
18
+ if (Object.keys(raw).length !== fields.length) throw new Error("Unsupported decision scope field");
19
+ return scope;
20
+ }
21
+
22
+ /** One local user's answer to a specific proposal in a trusted workspace; execution still uses normal tool authorization. */
23
+ export function supervisorDecision(agentDir: string, owner: { cwd: string; sessionId: string; projectTrusted: boolean },
24
+ command: Record<string, unknown>, now = Date.now()) {
25
+ if (!owner.projectTrusted) throw new Error("Supervisor decisions require a trusted workspace");
26
+ const scope = exactScope(command.scope);
27
+ const key = createHash("sha256").update(JSON.stringify([owner.cwd, scope])).digest("hex");
28
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as typeof import("node:sqlite");
29
+ const db = new DatabaseSync(join(agentDir, "supervisor-decisions.sqlite"));
30
+ try {
31
+ db.exec("CREATE TABLE IF NOT EXISTS decisions(id TEXT PRIMARY KEY, state TEXT NOT NULL, expires INTEGER NOT NULL, owner TEXT NOT NULL, token TEXT NOT NULL)");
32
+ db.exec("CREATE INDEX IF NOT EXISTS decisions_expiry ON decisions(expires)");
33
+ db.exec("BEGIN IMMEDIATE");
34
+ db.prepare("DELETE FROM decisions WHERE expires <= ?").run(now);
35
+ const row = db.prepare("SELECT * FROM decisions WHERE id=?").get(key);
36
+ const lookup = () => ({ status: row?.state ?? "missing", expires: row?.expires });
37
+ let result;
38
+ if (command.action === "decision-query") result = lookup();
39
+ else if (command.action === "decision-request") {
40
+ if (row) result = lookup();
41
+ else {
42
+ const token = randomUUID();
43
+ db.prepare("INSERT INTO decisions VALUES(?, 'pending', ?, ?, ?)").run(key, now + questionMs, owner.sessionId, token);
44
+ result = { status: "ask", token, scope, workspace: owner.cwd, timeoutMs: questionMs, durationMinutes: decisionDurationMs / 60_000 };
45
+ }
46
+ } else if (command.action === "decision-answer") {
47
+ if (row?.state !== "pending" || row.owner !== owner.sessionId || row.token !== command.token) result = { status: "stale" };
48
+ else if (command.answer === "cancelled") {
49
+ db.prepare("DELETE FROM decisions WHERE id=?").run(key);
50
+ result = { status: "cancelled" };
51
+ } else {
52
+ if (command.answer !== "approved" && command.answer !== "denied") throw new Error("Invalid decision answer");
53
+ db.prepare("UPDATE decisions SET state=?, expires=?, token='' WHERE id=?").run(command.answer, now + decisionDurationMs, key);
54
+ result = { status: command.answer, expires: now + decisionDurationMs };
55
+ }
56
+ } else throw new Error("Unsupported decision action");
57
+ db.exec("COMMIT");
58
+ return result;
59
+ } finally { db.close(); }
60
+ }
package/src/server.ts CHANGED
@@ -103,7 +103,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
103
103
  const initializeBackground = () => backgroundInitialization ??= (() => {
104
104
  options.rpcEvidence?.event('background', 0, 'init-pending');
105
105
  return createBackgroundTools(realpathSync(getAgentDir()), instanceId!, () => Boolean(pendingUpgrade), scope => work().snapshot(scope), config.runtimeIdleMs,
106
- options.rpcEvidence ? (slot, phase) => options.rpcEvidence!.event('adapter', slot, phase) : undefined)
106
+ options.rpcEvidence ? (slot, phase) => options.rpcEvidence!.event('adapter', slot, phase) : undefined, catalog.sources)
107
107
  .then(host => { options.rpcEvidence?.event('background', 0, 'init-returned'); return backgroundTools = host; })
108
108
  .catch(error => { options.rpcEvidence?.event('background', 0, 'init-failed'); backgroundInitialization = undefined; throw error; });
109
109
  })();
@@ -140,7 +140,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
140
140
  }
141
141
  resultPorts.set(resultRoot, resultPort);
142
142
  if (controlStore.store.pendingTaskCancellations().length) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
143
- const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!);
143
+ const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!, () => workModel?.sharedReadHealth());
144
144
  const initializeLaunch = () => {
145
145
  if (!launchInitialization) {
146
146
  const pending = createSubagentLaunch(realpathSync(getAgentDir()), instanceId!, catalog, config.runtimeIdleMs);
@@ -367,7 +367,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
367
367
  catalogSubscription = subscription;
368
368
  return reply({ data: subscription.snapshot });
369
369
  }
370
- if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog"].includes(type)) {
370
+ if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog", "runtime_supervisor_review"].includes(type)) {
371
371
  if (!greeted) throw new Error(`${type} requires hello`);
372
372
  return reply({ data: catalogCommand(command) });
373
373
  }
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Kept equal to package.json `version`; a test pins that. */
2
- export const SERVER_VERSION = "0.7.2";
2
+ export const SERVER_VERSION = "0.8.0";
3
3
 
4
4
  export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };