pi-better-harness 0.68.2 → 0.68.4
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/CHANGELOG.md +12 -0
- package/README.md +30 -13
- package/bin/pi-better-doctor.mjs +23 -0
- package/docs/runtime-doctor.md +60 -0
- package/extensions/execution-policy.ts +1 -1
- package/extensions/minimal-output/index.ts +60 -47
- package/extensions/runtime-doctor/index.ts +67 -0
- package/extensions/settings/commands.ts +1 -1
- package/extensions/settings/copy.ts +1 -7
- package/extensions/settings/index.ts +2 -1
- package/extensions/settings/page.ts +9 -4
- package/extensions/settings/runtime-modes.ts +25 -0
- package/extensions/settings/supervisor.ts +1 -0
- package/extensions/shared-harness-settings.ts +5 -0
- package/extensions/shared-runtime-mode-settings.ts +25 -0
- package/extensions/shared-runtime-mode.ts +108 -0
- package/extensions/supervisor/commitments.ts +56 -18
- package/extensions/supervisor/delivery-progress.ts +50 -0
- package/extensions/supervisor/delivery.ts +146 -0
- package/extensions/supervisor/index.ts +41 -14
- package/extensions/supervisor/recipient.ts +291 -0
- package/extensions/tool-call-guard/waits.ts +1 -1
- package/lib/console-daemon.mjs +12 -1
- package/lib/console-icons.svg +4 -0
- package/lib/console-shell.mjs +40 -2
- package/lib/console-ui.mjs +92 -7
- package/lib/local-session-ui.mjs +15 -8
- package/lib/prompt-ui.mjs +6 -1
- package/lib/prompt-web.mjs +3 -2
- package/lib/prompt.css +31 -0
- package/lib/runtime-doctor.mjs +12 -0
- package/lib/supervisor-ui.mjs +324 -0
- package/node_modules/pi-better-background-tasks/README.md +12 -2
- package/node_modules/pi-better-background-tasks/package.json +4 -3
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/win32-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/scripts/private-runtime/format.mjs +1 -0
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/client.mjs +34 -11
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/root.mjs +38 -28
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/startup-worker.mjs +4 -0
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/windows-directory.mjs +73 -37
- package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +4 -4
- package/node_modules/pi-better-background-tasks/runtime-client/src/startup/artifact.mjs +39 -10
- package/node_modules/pi-better-background-tasks/runtime-client/src/startup/stage-local.mjs +96 -42
- package/node_modules/pi-better-background-tasks/src/adapter-contract.ts +5 -4
- package/node_modules/pi-better-background-tasks/src/direct-frontend.ts +196 -0
- package/node_modules/pi-better-background-tasks/src/direct-windows-job.mjs +18 -0
- package/node_modules/pi-better-background-tasks/src/execution-mode.ts +16 -0
- package/node_modules/pi-better-background-tasks/src/goal-provider.ts +3 -1
- package/node_modules/pi-better-background-tasks/src/index.ts +13 -15
- package/node_modules/pi-better-background-tasks/src/managed-authority.ts +27 -1
- package/node_modules/pi-better-background-tasks/src/managed-client.ts +29 -8
- package/node_modules/pi-better-background-tasks/src/managed-frontend.ts +131 -8
- package/node_modules/pi-better-background-tasks/src/navigator-provider.ts +45 -10
- package/node_modules/pi-better-background-tasks/src/observed-waits.ts +9 -3
- package/node_modules/pi-better-background-tasks/src/output.ts +58 -16
- package/node_modules/pi-better-background-tasks/src/process.ts +85 -7
- package/node_modules/pi-better-background-tasks/src/prompt.ts +11 -6
- package/node_modules/pi-better-background-tasks/src/registry.ts +11 -1
- package/node_modules/pi-better-background-tasks/src/runtime.ts +105 -22
- package/node_modules/pi-better-background-tasks/src/shared-execution-policy.ts +1 -1
- package/node_modules/pi-better-background-tasks/src/shared-harness-commands.ts +1 -1
- package/node_modules/pi-better-background-tasks/src/shared-harness-copy.ts +1 -7
- package/node_modules/pi-better-background-tasks/src/shared-harness-page.ts +9 -4
- package/node_modules/pi-better-background-tasks/src/shared-harness-settings.ts +5 -0
- package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +87 -39
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/index.ts +21 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/errors.ts +6 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/schema.ts +9 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +3 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/supervisor-review-schema.ts +65 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/supervisor-reviews.ts +534 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/validate.ts +14 -5
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/waits.ts +2 -1
- package/node_modules/pi-better-background-tasks/src/shared-runtime-fallback-state.ts +45 -0
- package/node_modules/pi-better-background-tasks/src/shared-runtime-mode-settings.ts +25 -0
- package/node_modules/pi-better-background-tasks/src/shared-runtime-mode.ts +108 -0
- package/node_modules/pi-better-background-tasks/src/shared-sandbox-core.ts +2 -0
- package/node_modules/pi-better-background-tasks/src/shared-sandbox-diagnostics.ts +8 -5
- package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +4 -4
- package/node_modules/pi-better-background-tasks/src/stall.ts +2 -2
- package/node_modules/pi-better-background-tasks/src/supervisor/README.md +4 -4
- package/node_modules/pi-better-background-tasks/src/supervisor/emit-runner.mjs +34 -20
- package/node_modules/pi-better-background-tasks/src/supervisor/generated/direct-windows-job.mjs +20 -0
- package/node_modules/pi-better-background-tasks/src/supervisor/generated/process.mjs +119 -17
- package/node_modules/pi-better-background-tasks/src/tools.ts +44 -4
- package/node_modules/pi-better-background-tasks/src/types.ts +5 -0
- package/node_modules/pi-better-background-tasks/src/work-observation.ts +3 -1
- package/node_modules/pi-better-goal/src/shared-harness-commands.ts +1 -1
- package/node_modules/pi-better-goal/src/shared-harness-copy.ts +1 -7
- package/node_modules/pi-better-goal/src/shared-harness-page.ts +9 -4
- package/node_modules/pi-better-goal/src/shared-harness-settings.ts +5 -0
- package/node_modules/pi-better-sandbox/shared-harness-commands.ts +1 -1
- package/node_modules/pi-better-sandbox/shared-harness-copy.ts +1 -7
- package/node_modules/pi-better-sandbox/shared-harness-page.ts +9 -4
- package/node_modules/pi-better-sandbox/shared-harness-settings.ts +5 -0
- package/node_modules/pi-better-sandbox/shared-sandbox-core.ts +2 -0
- package/node_modules/pi-better-sandbox/shared-sandbox-diagnostics.ts +8 -5
- package/node_modules/pi-better-subagents/README.md +13 -9
- package/node_modules/pi-better-subagents/batch.mjs +32 -0
- package/node_modules/pi-better-subagents/catalog-host-admission.ts +32 -16
- package/node_modules/pi-better-subagents/child-operations.ts +8 -0
- package/node_modules/pi-better-subagents/config.ts +24 -14
- package/node_modules/pi-better-subagents/direct-owner.ts +9 -4
- package/node_modules/pi-better-subagents/effective-settings.ts +8 -4
- package/node_modules/pi-better-subagents/index.ts +102 -39
- package/node_modules/pi-better-subagents/managed-launch-client.ts +19 -5
- package/node_modules/pi-better-subagents/package.json +2 -2
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/win32-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/scripts/private-runtime/format.mjs +1 -0
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/client.mjs +34 -11
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/root.mjs +38 -28
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/startup-worker.mjs +4 -0
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/windows-directory.mjs +73 -37
- package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +4 -4
- package/node_modules/pi-better-subagents/runtime-client/src/startup/artifact.mjs +39 -10
- package/node_modules/pi-better-subagents/runtime-client/src/startup/stage-local.mjs +96 -42
- package/node_modules/pi-better-subagents/settings-page.ts +9 -7
- package/node_modules/pi-better-subagents/shared-catalog.ts +28 -7
- package/node_modules/pi-better-subagents/shared-execution-policy.ts +1 -1
- package/node_modules/pi-better-subagents/shared-harness-commands.ts +1 -1
- package/node_modules/pi-better-subagents/shared-harness-copy.ts +1 -7
- package/node_modules/pi-better-subagents/shared-harness-page.ts +9 -4
- package/node_modules/pi-better-subagents/shared-harness-settings.ts +5 -0
- package/node_modules/pi-better-subagents/shared-navigator.ts +87 -39
- package/node_modules/pi-better-subagents/shared-operation-coordinator/index.ts +21 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/errors.ts +6 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +9 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +3 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/supervisor-review-schema.ts +65 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/supervisor-reviews.ts +534 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/validate.ts +14 -5
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/waits.ts +2 -1
- package/node_modules/pi-better-subagents/shared-runtime-fallback-state.ts +45 -0
- package/node_modules/pi-better-subagents/shared-runtime-mode-settings.ts +25 -0
- package/node_modules/pi-better-subagents/shared-runtime-mode.ts +108 -0
- package/node_modules/pi-better-subagents/shared-sandbox-core.ts +2 -0
- package/node_modules/pi-better-subagents/shared-sandbox-diagnostics.ts +8 -5
- package/node_modules/pi-better-subagents/shared-work-client.mjs +4 -4
- package/node_modules/pi-better-subagents/spawn.ts +16 -11
- package/package.json +12 -6
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Generated from packages/harness-settings/runtime-mode-settings.ts. Do not edit directly.
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting, type HarnessSettingsSeams } from "./shared-harness-settings.ts";
|
|
5
|
+
import { isExecutionMode, isExecutionOverride, legacySubagentsModePath, readRuntimeModeSnapshot, type RuntimeComponent } from "./shared-runtime-mode.ts";
|
|
6
|
+
|
|
7
|
+
function settingsObject(value: unknown): Record<string, unknown> {
|
|
8
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime mode settings must be a JSON object.");
|
|
9
|
+
return value as Record<string, unknown>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function readRuntimeModes(seams: HarnessSettingsSeams = {}) {
|
|
13
|
+
const { global, subagents, backgroundTasks } = readRuntimeModeSnapshot(dirname(harnessSettingsPath(seams)), path => JSON.parse(readFileSync(path, "utf8")));
|
|
14
|
+
return { global, subagents, backgroundTasks };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** For operator-facing commands and settings controls only. */
|
|
18
|
+
export function writeRuntimeMode(target: RuntimeComponent | "runtime", mode: unknown, seams: HarnessSettingsSeams = {}): void {
|
|
19
|
+
if (!(target === "runtime" ? isExecutionMode(mode) : isExecutionOverride(mode))) throw new Error("Invalid runtime execution mode.");
|
|
20
|
+
if (target === "subagents") {
|
|
21
|
+
// Preserve every legacy Subagents setting when persisting the override.
|
|
22
|
+
readHarnessSetting("subagents", seams, { path: legacySubagentsModePath(dirname(harnessSettingsPath(seams))), parse: settingsObject });
|
|
23
|
+
}
|
|
24
|
+
updateHarnessSetting(target, previous => ({ ...(previous === undefined ? {} : settingsObject(previous)), executionMode: mode }), seams);
|
|
25
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Generated from packages/harness-settings/runtime-mode.ts. Do not edit directly.
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export const EXECUTION_MODES = ["auto", "managed", "direct"] as const;
|
|
5
|
+
export const EXECUTION_OVERRIDES = ["inherit", ...EXECUTION_MODES] as const;
|
|
6
|
+
export type ExecutionMode = typeof EXECUTION_MODES[number];
|
|
7
|
+
export type ExecutionOverride = typeof EXECUTION_OVERRIDES[number];
|
|
8
|
+
export type RuntimeComponent = "subagents" | "backgroundTasks";
|
|
9
|
+
export type RuntimeBackend = "managed" | "direct";
|
|
10
|
+
|
|
11
|
+
export interface ResolvedRuntimeMode {
|
|
12
|
+
requestedMode: ExecutionOverride;
|
|
13
|
+
effectiveMode: ExecutionMode;
|
|
14
|
+
source: "component" | "global" | "default";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function isExecutionMode(value: unknown): value is ExecutionMode {
|
|
18
|
+
return EXECUTION_MODES.some(mode => mode === value);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function isExecutionOverride(value: unknown): value is ExecutionOverride {
|
|
22
|
+
return value === "inherit" || isExecutionMode(value);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function resolveRuntimeMode(global: unknown, override: unknown): ResolvedRuntimeMode {
|
|
26
|
+
if (isExecutionMode(override)) return { requestedMode: override, effectiveMode: override, source: "component" };
|
|
27
|
+
if (isExecutionMode(global)) return { requestedMode: "inherit", effectiveMode: global, source: "global" };
|
|
28
|
+
return { requestedMode: "inherit", effectiveMode: "auto", source: "default" };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const legacySubagentsModePath = (agentDir: string) => join(agentDir, "extensions", "pi-better-subagents-config.json");
|
|
32
|
+
|
|
33
|
+
/** Resolve saved modes without locking, migrating, or writing settings. */
|
|
34
|
+
export function readRuntimeModeSnapshot(agentDir: string, readJson: (path: string) => unknown) {
|
|
35
|
+
function object(value: unknown): Record<string, unknown> {
|
|
36
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime mode settings must be a JSON object.");
|
|
37
|
+
return value as Record<string, unknown>;
|
|
38
|
+
}
|
|
39
|
+
let settings: Record<string, unknown>;
|
|
40
|
+
try { settings = object(readJson(join(agentDir, "settings.json"))); }
|
|
41
|
+
catch (error) {
|
|
42
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
43
|
+
settings = {};
|
|
44
|
+
}
|
|
45
|
+
const harness = Object.hasOwn(settings, "piBetterHarness") ? object(settings.piBetterHarness) : {};
|
|
46
|
+
const subagentsLegacy = !Object.hasOwn(harness, "subagents");
|
|
47
|
+
let subagents = harness.subagents;
|
|
48
|
+
if (subagentsLegacy) {
|
|
49
|
+
try { subagents = object(readJson(legacySubagentsModePath(agentDir))); }
|
|
50
|
+
catch { /* An unreadable legacy override leaves the modern settings in force. */ }
|
|
51
|
+
}
|
|
52
|
+
const modeOf = (section: unknown) => (section as { executionMode?: unknown } | undefined)?.executionMode;
|
|
53
|
+
const global = modeOf(harness.runtime);
|
|
54
|
+
return {
|
|
55
|
+
global: isExecutionMode(global) ? global : "auto" as const,
|
|
56
|
+
subagents: resolveRuntimeMode(global, modeOf(subagents)),
|
|
57
|
+
backgroundTasks: resolveRuntimeMode(global, modeOf(harness.backgroundTasks)),
|
|
58
|
+
subagentsLegacy,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type RuntimeFailureReason = "infrastructure-unavailable" | "policy-refused" | "unsafe-trust-boundary"
|
|
63
|
+
| "cancelled" | "unsupported-capability" | "outcome-unknown";
|
|
64
|
+
|
|
65
|
+
export interface RuntimeFailure {
|
|
66
|
+
reason: RuntimeFailureReason;
|
|
67
|
+
stage: string;
|
|
68
|
+
message: string;
|
|
69
|
+
// Evidence for the entire submission, including every item in a batch.
|
|
70
|
+
admission: "not-submitted" | "confirmed-not-admitted" | "unknown" | "partial" | "admitted";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Use only at the canonical installer call, before the caller creates an admission grant. */
|
|
74
|
+
export function managedStartupFailure(error: unknown): RuntimeFailure | undefined {
|
|
75
|
+
if (!(error instanceof Error)) return;
|
|
76
|
+
const startup = error as Error & { code?: string; phase?: unknown };
|
|
77
|
+
if (startup.code === "MANAGED_STARTUP_UNAVAILABLE" && typeof startup.phase === "string" && startup.phase) {
|
|
78
|
+
return { reason: "infrastructure-unavailable", stage: startup.phase, message: error.message, admission: "not-submitted" };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type RuntimeAvailability = { status: "untested" | "available" } | { status: "unavailable"; failure: RuntimeFailure };
|
|
83
|
+
|
|
84
|
+
export interface RuntimeModeStatus extends ResolvedRuntimeMode {
|
|
85
|
+
version: 1;
|
|
86
|
+
component: RuntimeComponent;
|
|
87
|
+
backends: Record<RuntimeBackend, { supported: boolean; availability: RuntimeAvailability }>;
|
|
88
|
+
backend?: RuntimeBackend;
|
|
89
|
+
fallback?: RuntimeFailure;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export const RUNTIME_MODE_STATUS_REQUEST = "harness-runtime-mode:request-v1";
|
|
93
|
+
export interface RuntimeModeStatusRequest {
|
|
94
|
+
reply(status: RuntimeModeStatus): void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function canFallbackToDirect(input: {
|
|
98
|
+
mode: ExecutionMode;
|
|
99
|
+
managedFailure: RuntimeFailure;
|
|
100
|
+
supportsDirect: boolean;
|
|
101
|
+
directPreflight: "passed" | "denied" | "untested";
|
|
102
|
+
cancelled: boolean;
|
|
103
|
+
}): boolean {
|
|
104
|
+
const { mode, managedFailure, supportsDirect, directPreflight, cancelled } = input;
|
|
105
|
+
return mode === "auto" && !cancelled && supportsDirect && directPreflight === "passed"
|
|
106
|
+
&& managedFailure.reason === "infrastructure-unavailable"
|
|
107
|
+
&& (managedFailure.admission === "not-submitted" || managedFailure.admission === "confirmed-not-admitted");
|
|
108
|
+
}
|
|
@@ -5,11 +5,13 @@ import { Type } from "typebox";
|
|
|
5
5
|
import { enabledScenarios } from "../settings/supervisor.ts";
|
|
6
6
|
import { OUTCOME_ENTRY } from "../task-context/outcome-state.ts";
|
|
7
7
|
|
|
8
|
+
export const REVIEW_COOLDOWN_MS = 45_000;
|
|
8
9
|
const ENTRY = "pi-better-harness:supervisor-commitment";
|
|
9
10
|
type Status = "accepted" | "attempted" | "failed" | "verified";
|
|
10
11
|
type Commitment = { id: string; outcome: string; action: string; verification: string; status: Status;
|
|
11
|
-
evidence?: string; observed?: string; reminder?: number };
|
|
12
|
+
evidence?: string; observed?: string; reminder?: number; recheckAt?: number };
|
|
12
13
|
type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
|
|
14
|
+
export type FailureReview = { commitment: string; retry: boolean; stillFailed: (branch: Branch) => boolean };
|
|
13
15
|
function outcomeId(branch: Branch) {
|
|
14
16
|
for (let i = branch.length - 1; i >= 0; i--) {
|
|
15
17
|
const e = branch[i]!;
|
|
@@ -28,34 +30,65 @@ function records(branch: Branch) {
|
|
|
28
30
|
}
|
|
29
31
|
return items;
|
|
30
32
|
}
|
|
33
|
+
const nextStep: Record<Status, string> = {
|
|
34
|
+
accepted: "Record the recovery attempt and its observed result.",
|
|
35
|
+
failed: "Record a different recovery attempt when there is new evidence.",
|
|
36
|
+
attempted: "Verify the expected result with a separate tool call.",
|
|
37
|
+
verified: "Verification complete.",
|
|
38
|
+
};
|
|
31
39
|
function describe(c: Commitment) {
|
|
32
40
|
return [`${c.id} · ${c.status}: ${c.action}`, `Verify: ${c.verification}`, c.observed, c.evidence && `Tool result: ${c.evidence}`,
|
|
33
|
-
c.reminder && `Reminder: ${new Date(c.reminder).toISOString()}`].filter(Boolean).join("\n");
|
|
41
|
+
`Next: ${nextStep[c.status]}`, c.reminder && `Reminder: ${new Date(c.reminder).toISOString()}`].filter(Boolean).join("\n");
|
|
34
42
|
}
|
|
35
|
-
export function registerCommitments(pi: ExtensionAPI, onFailure: (
|
|
43
|
+
export function registerCommitments(pi: ExtensionAPI, onFailure: (
|
|
44
|
+
ctx: ExtensionContext, observation: string, failure: FailureReview
|
|
45
|
+
) => void) {
|
|
36
46
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
47
|
+
let generation = 0;
|
|
37
48
|
const enabled = () => enabledScenarios().includes("commitment-followup");
|
|
38
49
|
function clear() { clearTimeout(timer); timer = undefined; }
|
|
50
|
+
function reviewFailure(ctx: ExtensionContext, c: Commitment, retry: boolean) {
|
|
51
|
+
const owner = generation;
|
|
52
|
+
onFailure(ctx, JSON.stringify({ commitment: c.id, failedRecovery: c.action, expected: c.verification, observed: c.observed }), {
|
|
53
|
+
commitment: c.id, retry,
|
|
54
|
+
stillFailed(branch) {
|
|
55
|
+
if (generation !== owner) return false;
|
|
56
|
+
const item = records(branch).get(c.id);
|
|
57
|
+
return item?.status === "failed" && item.evidence === c.evidence;
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
}
|
|
39
61
|
function schedule(ctx: ExtensionContext) {
|
|
40
62
|
clear();
|
|
41
63
|
if (!enabled()) return;
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
64
|
+
const items = records(ctx.sessionManager.getBranch());
|
|
65
|
+
let deadline = Infinity;
|
|
66
|
+
for (const c of items.values()) {
|
|
67
|
+
if (c.status !== "verified") deadline = Math.min(deadline, c.reminder ?? Infinity);
|
|
68
|
+
if (c.status === "failed") deadline = Math.min(deadline, c.recheckAt ?? Infinity);
|
|
69
|
+
}
|
|
70
|
+
if (!Number.isFinite(deadline)) return;
|
|
45
71
|
timer = setTimeout(() => {
|
|
46
72
|
if (!enabled()) return;
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
for (const c of records(ctx.sessionManager.getBranch()).values()) {
|
|
75
|
+
const remind = c.status !== "verified" && c.reminder !== undefined && c.reminder <= now;
|
|
76
|
+
const check = c.status === "failed" && c.recheckAt !== undefined && c.recheckAt <= now;
|
|
77
|
+
if (!remind && !check) continue;
|
|
78
|
+
const next = { ...c };
|
|
79
|
+
if (remind) delete next.reminder;
|
|
80
|
+
if (check) delete next.recheckAt;
|
|
81
|
+
pi.appendEntry(ENTRY, next);
|
|
82
|
+
if (remind) pi.sendMessage({ customType: ENTRY, content: describe(next), display: true }, { triggerTurn: false });
|
|
83
|
+
if (check) reviewFailure(ctx, next, true);
|
|
51
84
|
}
|
|
52
85
|
schedule(ctx);
|
|
53
|
-
}, Math.max(0,
|
|
86
|
+
}, Math.max(0, deadline - Date.now()));
|
|
54
87
|
timer.unref();
|
|
55
88
|
}
|
|
56
|
-
pi.on("session_shutdown", clear);
|
|
57
|
-
pi.on("session_start", (_e, ctx) => schedule(ctx));
|
|
58
|
-
pi.on("session_tree", (_e, ctx) => schedule(ctx));
|
|
89
|
+
pi.on("session_shutdown", () => { generation++; clear(); });
|
|
90
|
+
pi.on("session_start", (_e, ctx) => { generation++; schedule(ctx); });
|
|
91
|
+
pi.on("session_tree", (_e, ctx) => { generation++; schedule(ctx); });
|
|
59
92
|
pi.on("agent_start", (_e, ctx) => schedule(ctx));
|
|
60
93
|
pi.registerCommand("supervisor-followup", {
|
|
61
94
|
description: "Show recovery commitments, or request one reminder with: remind <id> <minutes>",
|
|
@@ -102,7 +135,12 @@ export function registerCommitments(pi: ExtensionAPI, onFailure: (ctx: Extension
|
|
|
102
135
|
if (!c) throw new Error("Unknown commitment in this Goal.");
|
|
103
136
|
if (p.action === "status") return reply(describe(c));
|
|
104
137
|
|
|
105
|
-
|
|
138
|
+
// Updating a deadline does not invalidate tool evidence observed since the last action.
|
|
139
|
+
const latest = branch.findIndex(e => {
|
|
140
|
+
if (e.type !== "custom" || e.customType !== ENTRY) return false;
|
|
141
|
+
const item = e.data as Commitment;
|
|
142
|
+
return item?.id === c.id && item.status === c.status && item.evidence === c.evidence;
|
|
143
|
+
});
|
|
106
144
|
const evidence = branch.slice(latest + 1).find(e => e.type === "message" && e.message.role === "toolResult" &&
|
|
107
145
|
e.message.toolCallId === p.toolCallId && !e.message.toolName.startsWith("supervisor_"));
|
|
108
146
|
if (c.evidence === p.toolCallId && c.evidence) {
|
|
@@ -114,12 +152,12 @@ export function registerCommitments(pi: ExtensionAPI, onFailure: (ctx: Extension
|
|
|
114
152
|
if (!p.observation?.trim()) throw new Error("Describe what the tool result establishes.");
|
|
115
153
|
const next: Commitment = { ...c, status: evidence.message.isError ? "failed" : p.action === "verify" ? "verified" : "attempted",
|
|
116
154
|
evidence: evidence.message.toolCallId, observed: p.observation.trim() };
|
|
155
|
+
if (next.status === "failed") next.recheckAt = Date.now() + REVIEW_COOLDOWN_MS;
|
|
156
|
+
else delete next.recheckAt;
|
|
117
157
|
if (next.status === "verified") delete next.reminder;
|
|
118
158
|
pi.appendEntry(ENTRY, next);
|
|
119
159
|
schedule(ctx);
|
|
120
|
-
if (next.status === "failed")
|
|
121
|
-
commitment: next.id, failedRecovery: next.action, expected: next.verification, observed: next.observed,
|
|
122
|
-
}));
|
|
160
|
+
if (next.status === "failed") reviewFailure(ctx, next, false);
|
|
123
161
|
return reply(describe(next));
|
|
124
162
|
},
|
|
125
163
|
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { supervisorOutcome } from "pi-better-background-tasks/src/ci-observation.ts";
|
|
4
|
+
import { deliveryProgressForOperator, recordOperatorDeliveryProgress } from "pi-better-server/src/runtime/delivery-drift-intake.ts";
|
|
5
|
+
import { deliveryWatchTarget, exactHead } from "pi-better-server/src/runtime/delivery-watch-terminal.ts";
|
|
6
|
+
|
|
7
|
+
function progressContext(ctx: ExtensionContext) {
|
|
8
|
+
if (!ctx.isProjectTrusted()) return;
|
|
9
|
+
const manager = ctx.sessionManager;
|
|
10
|
+
const branch = manager.getBranch();
|
|
11
|
+
const outcome = supervisorOutcome(branch);
|
|
12
|
+
if (!outcome) return;
|
|
13
|
+
return { workspace: realpathSync(ctx.cwd), sessionId: manager.getSessionId(), sessionFile: manager.getSessionFile(),
|
|
14
|
+
branchIds: branch.map(entry => entry.id), outcome, outcomeTimestamp: branch.find(entry => entry.id === outcome.id)?.timestamp };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The interactive operator is the verifier. Agent tool calls have no attestation action. */
|
|
18
|
+
export function registerDeliveryProgress(pi: Pick<ExtensionAPI, "registerCommand">) {
|
|
19
|
+
pi.registerCommand("supervisor-verify-delivery", {
|
|
20
|
+
description: "Record independently verified progress for a tracked PR and the active Outcome.",
|
|
21
|
+
async handler(args, ctx) {
|
|
22
|
+
if (!ctx.hasUI) return;
|
|
23
|
+
const [subject, head, evidenceUrl, extra] = args.trim().split(/\s+/);
|
|
24
|
+
const match = /^([^#]+)#([1-9]\d*)$/.exec(subject ?? "");
|
|
25
|
+
const target = match && deliveryWatchTarget(match[1], Number(match[2]));
|
|
26
|
+
if (!target || !exactHead(head) || !evidenceUrl || extra) {
|
|
27
|
+
return ctx.ui.notify("Use /harness-settings supervisor-verify-delivery owner/repo#PR full-head-SHA https://verification-permalink", "warning");
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const root = realpathSync(getAgentDir());
|
|
31
|
+
const context = progressContext(ctx);
|
|
32
|
+
const binding = context && deliveryProgressForOperator(root, context, target, head, evidenceUrl);
|
|
33
|
+
if (!binding) return ctx.ui.notify("No matching tracked candidate and active Outcome, or invalid HTTPS evidence link.", "warning");
|
|
34
|
+
const confirmed = await ctx.ui.confirm("Record verified delivery progress?", [
|
|
35
|
+
`${target.repository}#${target.pullRequest} at ${head}`,
|
|
36
|
+
`Outcome criterion: ${binding.criterion}`,
|
|
37
|
+
`Evidence: ${evidenceUrl}`,
|
|
38
|
+
"Confirm only if you checked that this evidence shows new progress toward the criterion on this exact head.",
|
|
39
|
+
].join("\n"));
|
|
40
|
+
if (!confirmed) return;
|
|
41
|
+
const current = progressContext(ctx);
|
|
42
|
+
const recorded = current && recordOperatorDeliveryProgress(root, current, target, head, binding.scope, evidenceUrl);
|
|
43
|
+
if (!recorded) return ctx.ui.notify("The tracked candidate or active Outcome changed. Verification was not recorded.", "warning");
|
|
44
|
+
ctx.ui.notify(recorded === "duplicate" ? "This verification was already recorded." : "Verified delivery progress recorded.", "info");
|
|
45
|
+
} catch {
|
|
46
|
+
ctx.ui.notify("Verified delivery progress could not be recorded.", "error");
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { parseSessionEntries, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { OUTCOME_ENTRY, type Outcome } from "../task-context/outcome-state.ts";
|
|
4
|
+
|
|
5
|
+
export const SUPERVISOR_DELIVERY = "pi-better-harness:supervisor-delivery";
|
|
6
|
+
|
|
7
|
+
export interface ApprovedSupervisorDelivery {
|
|
8
|
+
readonly deliveryId: string;
|
|
9
|
+
readonly owner: Readonly<{ workspace: string; sessionId: string; branchId: string }>;
|
|
10
|
+
readonly outcomeId: string;
|
|
11
|
+
readonly approvedText: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type SupervisorDeliveryState = "pending" | "in-flight" | "indeterminate";
|
|
15
|
+
export type SupervisorDeliveryResult =
|
|
16
|
+
| { status: "receipt"; deliveryId: string; entryId: string; deliveredAt: number }
|
|
17
|
+
| { status: "pending"; reason: "recipient-unavailable" | "scope-changed" | "transcript-unavailable" | "boundary-unavailable" | "claim-unavailable" }
|
|
18
|
+
| { status: "in-flight" }
|
|
19
|
+
| { status: "indeterminate"; reason: "no-receipt" | "conflicting-entry" | "claim-failed"; error?: unknown };
|
|
20
|
+
|
|
21
|
+
type RecipientContext = Pick<ExtensionContext, "cwd" | "sessionManager" | "isIdle">;
|
|
22
|
+
type DeliveryRecipient = {
|
|
23
|
+
currentContext(): RecipientContext | undefined;
|
|
24
|
+
/** The existing delivery and Goal rules permit an idle, no-turn append at this boundary. */
|
|
25
|
+
allowsNoTurnAppend(ctx: RecipientContext): boolean;
|
|
26
|
+
/** Atomically and durably move this exact delivery from never-attempted pending to in-flight. */
|
|
27
|
+
claimPending(delivery: ApprovedSupervisorDelivery): Promise<boolean>;
|
|
28
|
+
/** Invoke append synchronously only while the claiming attachment is still the writer. */
|
|
29
|
+
appendAsCurrentWriter(append: () => void): boolean;
|
|
30
|
+
/** Attest that the same writer returned before invoking sendMessage. */
|
|
31
|
+
releaseUnsentClaim?(delivery: ApprovedSupervisorDelivery): Promise<void>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function inScope(leaf: string | null, entries: Map<string, SessionEntry>, delivery: ApprovedSupervisorDelivery) {
|
|
35
|
+
let branchMatches = false;
|
|
36
|
+
let outcomeMatches = false;
|
|
37
|
+
for (let remaining = entries.size; leaf !== null && remaining > 0; remaining--) {
|
|
38
|
+
const entry = entries.get(leaf);
|
|
39
|
+
if (!entry) return false;
|
|
40
|
+
branchMatches ||= entry.id === delivery.owner.branchId;
|
|
41
|
+
if (!outcomeMatches && entry.type === "custom" && entry.customType === OUTCOME_ENTRY) {
|
|
42
|
+
const data = entry.data as { version?: number; outcome?: Outcome } | undefined;
|
|
43
|
+
if (entry.id !== delivery.outcomeId || data?.version !== 1 || data.outcome?.status !== "active"
|
|
44
|
+
|| typeof data.outcome.objective !== "string" || !data.outcome.objective.trim()) return false;
|
|
45
|
+
outcomeMatches = true;
|
|
46
|
+
}
|
|
47
|
+
if (branchMatches && outcomeMatches) return true;
|
|
48
|
+
leaf = entry.parentId;
|
|
49
|
+
}
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function inspectTranscript(ctx: RecipientContext, delivery: ApprovedSupervisorDelivery) {
|
|
54
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
55
|
+
if (!file) return;
|
|
56
|
+
let transcript: string;
|
|
57
|
+
try {
|
|
58
|
+
transcript = readFileSync(file, "utf8");
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// A file path can exist in SessionManager before Pi flushes any entries.
|
|
63
|
+
if (!transcript.endsWith("\n")) return;
|
|
64
|
+
const [header, ...entries] = parseSessionEntries(transcript);
|
|
65
|
+
if (header?.type !== "session" || header.id !== delivery.owner.sessionId) return;
|
|
66
|
+
const index = new Map<string, SessionEntry>();
|
|
67
|
+
const matches = [];
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
if (!entry || entry.type === "session") continue;
|
|
70
|
+
index.set(entry.id, entry);
|
|
71
|
+
if (entry.type === "custom_message" && entry.customType === SUPERVISOR_DELIVERY
|
|
72
|
+
&& (entry.details as { deliveryId?: string } | undefined)?.deliveryId === delivery.deliveryId) matches.push(entry);
|
|
73
|
+
}
|
|
74
|
+
const match = matches[0];
|
|
75
|
+
if (!match) return { index };
|
|
76
|
+
const deliveredAt = Date.parse(match.timestamp);
|
|
77
|
+
const proof: SupervisorDeliveryResult = matches.length === 1 && match.content === delivery.approvedText && Number.isFinite(deliveredAt)
|
|
78
|
+
&& match.display === true && inScope(match.parentId, index, delivery)
|
|
79
|
+
? { status: "receipt", deliveryId: delivery.deliveryId, entryId: match.id, deliveredAt }
|
|
80
|
+
: { status: "indeterminate", reason: "conflicting-entry" };
|
|
81
|
+
return { index, proof };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Call at a recipient delivery boundary. The context and send API must belong to the same attachment.
|
|
85
|
+
* The caller owns the immutable approval and a durable claim that survives reconnect and lease expiry.
|
|
86
|
+
* Only a confirmed pre-send refusal on the claiming writer can release the claim. An orphaned
|
|
87
|
+
* claim is reconciled from persisted transcript evidence. */
|
|
88
|
+
export async function reconcileSupervisorDelivery(
|
|
89
|
+
pi: Pick<ExtensionAPI, "sendMessage">,
|
|
90
|
+
recipient: DeliveryRecipient,
|
|
91
|
+
delivery: ApprovedSupervisorDelivery,
|
|
92
|
+
state: SupervisorDeliveryState,
|
|
93
|
+
): Promise<SupervisorDeliveryResult> {
|
|
94
|
+
const observe = (maySend: boolean): SupervisorDeliveryResult | { status: "ready"; ctx: RecipientContext } => {
|
|
95
|
+
const ctx = recipient.currentContext();
|
|
96
|
+
if (!ctx || workspace(ctx.cwd) !== delivery.owner.workspace || ctx.sessionManager.getSessionId() !== delivery.owner.sessionId)
|
|
97
|
+
return { status: "pending", reason: "recipient-unavailable" };
|
|
98
|
+
const transcript = inspectTranscript(ctx, delivery);
|
|
99
|
+
if (transcript?.proof) return transcript.proof;
|
|
100
|
+
if (!transcript) return { status: "pending", reason: "transcript-unavailable" };
|
|
101
|
+
if (!inScope(ctx.sessionManager.getLeafId(), transcript.index, delivery))
|
|
102
|
+
return { status: "pending", reason: "scope-changed" };
|
|
103
|
+
if (!maySend || !ctx.isIdle() || !recipient.allowsNoTurnAppend(ctx))
|
|
104
|
+
return { status: "pending", reason: "boundary-unavailable" };
|
|
105
|
+
return { status: "ready", ctx };
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const initial = observe(state === "pending");
|
|
109
|
+
if (initial.status === "receipt" || initial.status === "indeterminate") return initial;
|
|
110
|
+
if (state === "in-flight") return { status: "in-flight" };
|
|
111
|
+
if (state === "indeterminate") return { status: "indeterminate", reason: "no-receipt" };
|
|
112
|
+
if (initial.status !== "ready") return initial;
|
|
113
|
+
const manager = initial.ctx.sessionManager;
|
|
114
|
+
try {
|
|
115
|
+
if (!(await recipient.claimPending(delivery))) return { status: "pending", reason: "claim-unavailable" };
|
|
116
|
+
} catch (error) {
|
|
117
|
+
return { status: "indeterminate", reason: "claim-failed", error };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const current = observe(true);
|
|
121
|
+
if (current.status !== "ready") {
|
|
122
|
+
if (current.status === "pending" && current.reason !== "recipient-unavailable"
|
|
123
|
+
&& recipient.currentContext() === initial.ctx && initial.ctx.sessionManager === manager) {
|
|
124
|
+
await recipient.releaseUnsentClaim?.(delivery);
|
|
125
|
+
}
|
|
126
|
+
return current;
|
|
127
|
+
}
|
|
128
|
+
if (current.ctx !== initial.ctx || current.ctx.sessionManager !== manager)
|
|
129
|
+
return { status: "pending", reason: "recipient-unavailable" };
|
|
130
|
+
let error: unknown;
|
|
131
|
+
try {
|
|
132
|
+
if (!recipient.appendAsCurrentWriter(() => pi.sendMessage({
|
|
133
|
+
customType: SUPERVISOR_DELIVERY, content: delivery.approvedText, display: true,
|
|
134
|
+
details: { deliveryId: delivery.deliveryId },
|
|
135
|
+
}, { triggerTurn: false }))) return { status: "pending", reason: "recipient-unavailable" };
|
|
136
|
+
} catch (cause) {
|
|
137
|
+
error = cause;
|
|
138
|
+
}
|
|
139
|
+
// A successful call can still lack a persisted entry. Evidence comes from the actual custom message.
|
|
140
|
+
const proof = inspectTranscript(current.ctx, delivery)?.proof;
|
|
141
|
+
return proof ?? { status: "indeterminate", reason: "no-receipt", ...(error === undefined ? {} : { error }) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function workspace(cwd: string) {
|
|
145
|
+
try { return realpathSync(cwd); } catch { return undefined; }
|
|
146
|
+
}
|
|
@@ -8,28 +8,33 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
|
|
|
8
8
|
import { openSupervisorClient } from "pi-better-subagents/supervisor-client.mjs";
|
|
9
9
|
import { goalStallThresholds } from "pi-better-goal/src/stall.ts";
|
|
10
10
|
import { DEFAULT_STALL_THRESHOLDS } from "pi-better-goal/src/shared-stall-detector.ts";
|
|
11
|
-
import { enabledScenarios } from "../settings/supervisor.ts";
|
|
12
|
-
import { registerCommitments } from "./commitments.ts";
|
|
11
|
+
import { enabledScenarios, scenarioRevision } from "../settings/supervisor.ts";
|
|
12
|
+
import { registerCommitments, REVIEW_COOLDOWN_MS, type FailureReview } from "./commitments.ts";
|
|
13
13
|
import { registerDecisionTool } from "./decisions.ts";
|
|
14
14
|
import { registerSharedFault } from "./shared-fault.ts";
|
|
15
|
+
import { registerDeliveryProgress } from "./delivery-progress.ts";
|
|
16
|
+
import { registerSupervisorRecipient } from "./recipient.ts";
|
|
15
17
|
import { digest, ENTRY, readFingerprint, RepeatedRead, scopeEvidence, type Scenario } from "./evidence.ts";
|
|
16
18
|
|
|
17
19
|
const prompts = {
|
|
18
|
-
"commitment-followup": "The owner tried an accepted recovery and recorded an observed failure. Recommend a materially different remedy only when the new evidence supports it. Suppress rewordings of the accepted action, untested guesses and status-only updates.",
|
|
20
|
+
"commitment-followup": "The owner tried an accepted recovery and recorded an observed failure. Recommend a materially different remedy only when the new evidence supports it. Suppress rewordings of the accepted action or any previous remedy, untested guesses and status-only updates.",
|
|
19
21
|
"stall-diagnosis": "The owner repeated an identical read with identical results across the stall interval. Compare competing explanations, including productive research or external waits. Recommend a different, specific check only when the evidence supports a cause. Name what result would advance the current acceptance criterion.",
|
|
20
22
|
"scope-review": "Review unfinished Todo steps against the latest user instruction, objective and boundaries. Preserve necessary investigation. If a step clearly falls outside scope, cite its id and reason, name work to retain and propose a partial plan revision for the owner. Leave running work and artifacts to their owners.",
|
|
21
23
|
};
|
|
22
24
|
const FEEDBACK = "pi-better-harness:supervisor-progress";
|
|
23
|
-
type Receipt = { scopeTargets?: string; outcome: string; plan?: string; evidence: string[]; expected: string; steps: string[]; key: string; scenario: Scenario; advice: string | null; revision: string; catalogRevision: string; role: { instructions: string; model: string; effort?: string | null } };
|
|
25
|
+
type Receipt = { commitment?: string; scopeTargets?: string; outcome: string; plan?: string; evidence: string[]; expected: string; steps: string[]; key: string; scenario: Scenario; advice: string | null; revision: string; catalogRevision: string; role: { instructions: string; model: string; effort?: string | null } };
|
|
24
26
|
function supervisor(pi: ExtensionAPI) {
|
|
25
27
|
installSupervisor(pi, openSupervisorClient);
|
|
26
28
|
}
|
|
27
29
|
export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervisorClient) {
|
|
30
|
+
registerSupervisorRecipient(pi);
|
|
31
|
+
registerDeliveryProgress(pi);
|
|
28
32
|
registerSharedFault(pi, connect);
|
|
29
33
|
registerDecisionTool(pi, connect);
|
|
30
|
-
registerCommitments(pi, (ctx, evidence) => { void review(ctx, "commitment-followup", evidence); });
|
|
34
|
+
registerCommitments(pi, (ctx, evidence, failure) => { void review(ctx, "commitment-followup", evidence, true, failure); });
|
|
31
35
|
const repeats = new RepeatedRead();
|
|
32
36
|
let pending: AbortController | undefined;
|
|
37
|
+
let available: Promise<void> | undefined;
|
|
33
38
|
let pendingScenario: Scenario | undefined;
|
|
34
39
|
let readKey: string | undefined;
|
|
35
40
|
let reviewedShape: string | undefined;
|
|
@@ -56,9 +61,18 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
|
|
|
56
61
|
scope.steps.map(step => [step.id, step.step])]));
|
|
57
62
|
}
|
|
58
63
|
|
|
59
|
-
async function review(ctx: ExtensionContext, scenario: Scenario, detail: string, publish = true) {
|
|
60
|
-
|
|
64
|
+
async function review(ctx: ExtensionContext, scenario: Scenario, detail: string, publish = true, failure?: FailureReview) {
|
|
65
|
+
const setting = scenarioRevision(scenario);
|
|
66
|
+
if (!setting) return;
|
|
67
|
+
// Several failures can mature at the same deadline. Serialize their reviews.
|
|
68
|
+
while (pending && available && failure) {
|
|
69
|
+
if (!failure.stillFailed(ctx.sessionManager.getBranch())) return;
|
|
70
|
+
await available;
|
|
71
|
+
if (scenarioRevision(scenario) !== setting) return;
|
|
72
|
+
}
|
|
73
|
+
if (pending) return;
|
|
61
74
|
const branch = ctx.sessionManager.getBranch();
|
|
75
|
+
if (failure && !failure.stillFailed(branch)) return;
|
|
62
76
|
const scope = scopeEvidence(branch);
|
|
63
77
|
if (!scope || (scenario === "scope-review" && !scope.steps.some(s => s.status !== "completed"))) return;
|
|
64
78
|
// A repeated read's first-observed timestamp changes on reconnect. Its evidence does not.
|
|
@@ -67,18 +81,30 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
|
|
|
67
81
|
const cached = branch.find(e => e.type === "custom" && e.customType === ENTRY && (e.data as Receipt)?.key === key);
|
|
68
82
|
if (cached?.type === "custom") return (cached.data as Receipt).advice ?? "No intervention recommended.";
|
|
69
83
|
const previous = lastAttempt.get(scenario);
|
|
70
|
-
|
|
84
|
+
// The persisted deadline already gates a scheduled retry.
|
|
85
|
+
if (publish && !failure?.retry && previous?.key === key && Date.now() - previous.at < REVIEW_COOLDOWN_MS) return;
|
|
86
|
+
const commitment = failure?.commitment;
|
|
87
|
+
const priorRemedies = commitment ? branch.flatMap(entry => {
|
|
88
|
+
if (entry.type !== "custom" || entry.customType !== ENTRY) return [];
|
|
89
|
+
const receipt = entry.data as Receipt;
|
|
90
|
+
return receipt.commitment === commitment && receipt.advice ? [receipt.advice] : [];
|
|
91
|
+
}) : [];
|
|
71
92
|
lastAttempt.set(scenario, { key, at: Date.now() });
|
|
72
93
|
const generation = serial;
|
|
73
94
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
74
95
|
const controller = new AbortController();
|
|
96
|
+
let release!: () => void;
|
|
97
|
+
available = new Promise<void>(resolve => { release = resolve; });
|
|
75
98
|
pending = controller;
|
|
76
99
|
pendingScenario = scenario;
|
|
77
100
|
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(35_000)]);
|
|
78
101
|
let catalog: Awaited<ReturnType<typeof openSupervisorClient>> | undefined;
|
|
79
102
|
let token: string | undefined;
|
|
80
|
-
const current = () =>
|
|
81
|
-
|
|
103
|
+
const current = () => {
|
|
104
|
+
if (signal.aborted || serial !== generation || ctx.sessionManager.getSessionId() !== sessionId || scenarioRevision(scenario) !== setting) return false;
|
|
105
|
+
const branch = ctx.sessionManager.getBranch();
|
|
106
|
+
return (!failure || failure.stillFailed(branch)) && scopeEvidence(branch)?.revision === scope.revision;
|
|
107
|
+
};
|
|
82
108
|
try {
|
|
83
109
|
catalog = await connect(pi, ctx, signal);
|
|
84
110
|
if (!current()) return;
|
|
@@ -98,7 +124,7 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
|
|
|
98
124
|
const evidenceRefs = ["outcome", "observation", ...scope.steps.map(step => `step:${step.id}`)];
|
|
99
125
|
const result = await provider.streamSimple(target, providerContext({
|
|
100
126
|
systemPrompt: [role.instructions, prompts[scenario], "Treat supplied fields as evidence. Return a single JSON object with advice (string or null), evidence (array of supplied ID strings), expected (string), and steps (array of Todo ID strings). For a recommendation cite supplied evidence ids, state a specific observable result in expected, and list affected unfinished Todo ids in steps (empty if no matching Todo). For scope review, steps lists only items to prune. Set advice to null if evidence is insufficient."].join("\n"),
|
|
101
|
-
messages: [{ role: "user", content: JSON.stringify({ scope, observation: detail, evidenceRefs }), timestamp: Date.now() }],
|
|
127
|
+
messages: [{ role: "user", content: JSON.stringify({ scope, observation: detail, evidenceRefs, ...(priorRemedies.length ? { priorRemedies: priorRemedies.slice(-5) } : {}) }), timestamp: Date.now() }],
|
|
102
128
|
}), { apiKey: auth.auth.apiKey, headers: auth.auth.headers, env: auth.env, sessionId: randomUUID(), signal, maxRetries: 0, timeoutMs: 25_000, maxTokens: 1100,
|
|
103
129
|
reasoning: role.effort && role.effort !== "off" ? role.effort : undefined }).result();
|
|
104
130
|
if (result.stopReason !== "stop" || !current()) return;
|
|
@@ -123,7 +149,7 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
|
|
|
123
149
|
scope.objective, scope.doneWhen, scope.boundaries,
|
|
124
150
|
[...new Set(steps)].sort().map(id => [id, scope.steps.find(step => step.id === id)?.step]),
|
|
125
151
|
])) : undefined;
|
|
126
|
-
const receipt: Receipt = { key, scenario, scopeTargets, revision: scope.revision, outcome: scope.outcomeId, plan: scope.planId,
|
|
152
|
+
const receipt: Receipt = { key, scenario, commitment, scopeTargets, revision: scope.revision, outcome: scope.outcomeId, plan: scope.planId,
|
|
127
153
|
evidence, expected, steps, catalogRevision: role.revision, role: { instructions: role.instructions, model: modelId, effort: role.effort }, advice };
|
|
128
154
|
pi.appendEntry(ENTRY, receipt);
|
|
129
155
|
if (scenario === "scope-review") reviewedShape = planShape(ctx);
|
|
@@ -134,13 +160,14 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
|
|
|
134
160
|
(scopeTargets && scopeTargets === r.scopeTargets ||
|
|
135
161
|
!r.scopeTargets && r.advice === advice && r.expected === expected && JSON.stringify(r.steps) === JSON.stringify(steps));
|
|
136
162
|
});
|
|
137
|
-
if (advice && publish && !alreadySuggested) pi.sendMessage({ customType: ENTRY, content: `${advice}\nVerify: ${expected}`, details: { evidence, key }, display: true }, { deliverAs: "steer", triggerTurn: false });
|
|
163
|
+
if (advice && publish && !alreadySuggested && !priorRemedies.includes(advice)) pi.sendMessage({ customType: ENTRY, content: `${advice}\nVerify: ${expected}`, details: { evidence, key }, display: true }, { deliverAs: "steer", triggerTurn: false });
|
|
138
164
|
return advice ?? "No intervention recommended.";
|
|
139
165
|
} catch { /* An unavailable diagnostic leaves the owner's original operation running. */ }
|
|
140
166
|
finally {
|
|
141
167
|
try { if (token) await catalog?.review(scenario, "release", token); } catch { /* Lease expires independently. */ }
|
|
142
168
|
catalog?.close();
|
|
143
|
-
if (pending === controller) pending = undefined;
|
|
169
|
+
if (pending === controller) { pending = undefined; available = undefined; }
|
|
170
|
+
release();
|
|
144
171
|
}
|
|
145
172
|
}
|
|
146
173
|
function recordProgress(ctx: ExtensionContext) {
|