pi-better-harness 0.54.0 → 0.55.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 (50) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -2
  3. package/extensions/settings/index.ts +8 -0
  4. package/extensions/settings/supervisor.ts +64 -0
  5. package/extensions/supervisor/commitments.ts +126 -0
  6. package/extensions/supervisor/decisions.ts +80 -0
  7. package/extensions/supervisor/evidence.ts +53 -0
  8. package/extensions/supervisor/index.ts +206 -0
  9. package/extensions/supervisor/shared-fault.ts +62 -0
  10. package/extensions/task-context/dynamic-workflow-view.ts +18 -108
  11. package/extensions/task-context/index.ts +3 -2
  12. package/extensions/task-context/plan-presentation.ts +29 -9
  13. package/extensions/task-context/workflow-diagram.ts +59 -63
  14. package/extensions/task-context/workflow-plan.ts +70 -11
  15. package/extensions/task-context/workflow-view.ts +74 -0
  16. package/node_modules/pi-better-background-tasks/package.json +1 -1
  17. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  18. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  19. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  20. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  21. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  22. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  23. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  24. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  25. package/node_modules/pi-better-background-tasks/src/ci-observation.ts +118 -0
  26. package/node_modules/pi-better-background-tasks/src/managed-client.ts +6 -2
  27. package/node_modules/pi-better-background-tasks/src/managed-frontend.ts +36 -6
  28. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +24 -0
  29. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +1 -0
  30. package/node_modules/pi-better-goal/package.json +1 -1
  31. package/node_modules/pi-better-goal/src/assignment-inbox.mjs +4 -0
  32. package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +1 -0
  33. package/node_modules/pi-better-subagents/catalog-schema.ts +1 -0
  34. package/node_modules/pi-better-subagents/docs/agent-catalog.md +1 -0
  35. package/node_modules/pi-better-subagents/package.json +1 -1
  36. package/node_modules/pi-better-subagents/roles/role.supervisor.md +16 -0
  37. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  38. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  39. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  40. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  41. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  45. package/node_modules/pi-better-subagents/shared-catalog.ts +14 -2
  46. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-inbox.mjs +4 -0
  47. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  48. package/node_modules/pi-better-subagents/supervisor-client.d.mts +11 -0
  49. package/node_modules/pi-better-subagents/supervisor-client.mjs +34 -0
  50. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.55.0] - 2026-11-25
4
+
5
+ ### Added
6
+
7
+ - Enable Agent Supervisor in Harness settings to recover interrupted CI observation, diagnose stalled Outcomes and shared daemon faults, review scope, consolidate authorization requests, and follow up on recovery commitments. Each scenario is opt-in. (#896)
8
+
9
+ ### Fixed
10
+
11
+ - Bound task plans and dynamic workflows now share a Todo view. At 36 terminal columns or wider, the task list appears to the left of the workflow diagram and review loops. In narrower terminals the diagram follows the list. Long provider status text stays within the compact list. (#908)
12
+
3
13
  ## [0.54.0] - 2026-11-25
4
14
 
5
15
  ### Added
package/README.md CHANGED
@@ -61,6 +61,10 @@ enables it. Existing active, paused or budget-limited Goals stay unchanged, and
61
61
  restoring state or toggling settings never starts work. The outcome and Todo are
62
62
  preserved; subsequent continuation follows the existing Goal controls.
63
63
 
64
+ Todo uses the same workflow view for a bound task plan and a dynamic workflow.
65
+ It shows tasks on the left and the workflow diagram on the right. Below 36 terminal
66
+ columns, the diagram follows the task list.
67
+
64
68
  Existing Plan session histories restore as Todo. Workflow task-plan files and
65
69
  revision checks stay unchanged; skills continue using their own records when the
66
70
  optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
@@ -74,11 +78,10 @@ workflow for dependencies, role handoffs or repeated review. The command works
74
78
  in every mode and keeps your saved preference.
75
79
 
76
80
  The agent records an objective, acceptance criteria, required outputs and task
77
- dependencies. Todo shows tasks on the left and dependencies and review loops on the right.
81
+ dependencies. The diagram shows dependencies and review loops.
78
82
  Task icons distinguish ready (○), working (●), waiting (·), optional standby (–),
79
83
  failed (×), and completed (✓) steps. In mouse-enabled Pi, click a task to highlight
80
84
  its stage and inspect its latest result. Use `/todo expand` to show every task.
81
- Below 36 terminal columns, the diagram follows the list.
82
85
  Independent tasks can run together. A join waits for each prerequisite's output.
83
86
  If a reviewer requests changes, the revision opens and the revised artifact
84
87
  returns to review. Delivery waits for approval of the current version.
@@ -343,6 +346,19 @@ The hub is TUI-only and is included by the installer. To load the settings exten
343
346
  pi -e ./packages/pi-better-harness/extensions/settings/index.ts
344
347
  ```
345
348
 
349
+ ### Agent Supervisor
350
+
351
+ Open **Supervisor mode** in `/harness-settings`. Turn it on and select the scenarios to run. First use starts with an empty selection. Settings apply to sessions sharing the Pi agent directory. Turning the mode off preserves the selection and lets existing tasks continue.
352
+
353
+ | Scenario | What the owner receives |
354
+ | --- | --- |
355
+ | CI observation recovery | A suggestion to resume observation of the original GitHub run when its local watcher exits and a fresh check confirms the run is active. Use `supervisor_consult` for the managed observer. |
356
+ | Diagnose stalled Outcomes | A diagnostic review after repeated identical successful repository reads return the same evidence throughout the stall interval. |
357
+ | Review Outcome scope | A review of changed Todo steps against the latest user instruction and Outcome. The owner chooses which steps to keep or prune. Use `supervisor_review` for an on-demand review. |
358
+ | Shared daemon fault diagnosis | A shared read-plane diagnosis with an owner-specific verification step when a runtime read fails and the daemon confirms degraded or rebuilding inventory. |
359
+ | Consolidate authorization requests | Owners in a trusted workspace can use `supervisor_request_decision` for the same proposal. The dialog shows the reference, operation, host, resource, side effect, workspace and validity period. Execution still needs the permissions normally required by the tool. |
360
+ | Follow up on recovery commitments | Use `supervisor_followup` to record the action, expected verification and actual tool results. Read progress with `/supervisor-followup`. Request one reminder with `/supervisor-followup remind <id> <minutes>`. |
361
+
346
362
  ## When To Use
347
363
 
348
364
  Use the installer when you want every core extension with standalone package identities. Install an individual package instead when you only need the sandbox, subagents, shell task supervision, synchronous SSH, goal tracking, or model routing. Outcome & Todo is available through Harness.
@@ -1,6 +1,7 @@
1
1
  import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentInstructions, manageInstructions, validateInstructionsPrompt } from "../../lib/instructions.mjs";
3
3
  import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
4
+ import { openSupervisorSettings } from "./supervisor.ts";
4
5
  import { chooseHarnessSetting } from "./page.ts";
5
6
  import { createSettingsRegistry } from "./registry.ts";
6
7
  import { changeCallbackSetting, getCallbackSettings, saveCallbackDefault } from "pi-better-background-tasks/src/shared-callback-batcher.ts";
@@ -45,6 +46,8 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
45
46
  change: mode => changeCallbackSetting(pi, ctx, mode),
46
47
  save: () => saveCallbackDefault(readSettings().mode),
47
48
  }, registry.controls(), view, [
49
+ { id: "supervisor:open", label: "Supervisor mode", currentValue: "Open", values: ["Open"],
50
+ description: "Choose the supervision scenarios shared by this agent directory." },
48
51
  { id: "instructions:toggle", label: "Harness instructions", currentValue: state, values: [state],
49
52
  description: "Toggle the global APPEND_SYSTEM.md block. Applies on startup or /reload." },
50
53
  ...(prompt === undefined ? [] : [{ id: "instructions:edit", label: "Instructions prompt", currentValue: "Edit",
@@ -55,6 +58,11 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
55
58
  return;
56
59
  }
57
60
  if (!selected) return;
61
+ if (selected === "supervisor:open") {
62
+ try { await openSupervisorSettings(ctx); }
63
+ catch (error) { ctx.ui.notify(`Supervisor mode: ${error instanceof Error ? error.message : String(error)}`, "error"); }
64
+ continue;
65
+ }
58
66
  if (selected.startsWith("instructions:")) {
59
67
  try {
60
68
  if (readError) throw readError;
@@ -0,0 +1,64 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { statSync } from "node:fs";
3
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4
+ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
5
+
6
+ const key = "supervisorMode";
7
+ const options = new Map([
8
+ ["ci-observation", "CI observation recovery"],
9
+ ["stall-diagnosis", "Diagnose stalled Outcomes"],
10
+ ["scope-review", "Review Outcome scope"],
11
+ ["shared-fault", "Shared daemon fault diagnosis"],
12
+ ["shared-decisions", "Consolidate authorization requests"],
13
+ ["commitment-followup", "Follow up on recovery commitments"],
14
+ ]);
15
+
16
+ function decode(raw: unknown): { enabled: boolean; scenarios: string[]; revision?: string } {
17
+ if (raw === undefined) return { enabled: false, scenarios: [] };
18
+ if (typeof raw !== "object" || raw === null || !("enabled" in raw) ||
19
+ typeof raw.enabled !== "boolean" || !("scenarios" in raw) || !Array.isArray(raw.scenarios) ||
20
+ !raw.scenarios.every((id: unknown) => typeof id === "string")) {
21
+ throw new Error("Invalid Supervisor mode settings.");
22
+ }
23
+ return { enabled: raw.enabled, scenarios: raw.scenarios, revision: "revision" in raw && typeof raw.revision === "string" ? raw.revision : undefined };
24
+ }
25
+
26
+ // Atomic settings writes replace the inode. Avoid locking and parsing on every observed tool.
27
+ let cache: { stamp: string; scenarios: string[]; revision: string } | undefined;
28
+ export function enabledScenarios(): string[] {
29
+ try {
30
+ const path = harnessSettingsPath();
31
+ const file = statSync(path, { throwIfNoEntry: false });
32
+ if (!file) return [];
33
+ const stamp = [path, file.dev, file.ino, file.ctimeMs, file.size].join("/");
34
+ if (cache?.stamp === stamp) return cache.scenarios;
35
+ const setting = decode(readHarnessSetting(key));
36
+ cache = { stamp, revision: setting.revision ?? "initial", scenarios: setting.enabled ? setting.scenarios : [] };
37
+ return cache.scenarios;
38
+ } catch { return []; }
39
+ }
40
+
41
+ export function scenarioRevision(scenario: string) {
42
+ if (enabledScenarios().includes(scenario)) return cache?.revision;
43
+ }
44
+
45
+ export async function openSupervisorSettings(ctx: Pick<ExtensionCommandContext, "ui">): Promise<void> {
46
+ while (true) {
47
+ const { enabled, scenarios } = decode(readHarnessSetting(key));
48
+ const mode = enabled ? "Turn Supervisor mode off" : "Turn Supervisor mode on";
49
+ const rows = [...options].map(([id, label]) => ({ id, selected: scenarios.includes(id), label: `[${scenarios.includes(id) ? "x" : " "}] ${label}` }));
50
+ const choices = enabled ? [mode, ...rows.map(row => row.label)] : [mode];
51
+ const choice = await ctx.ui.select("Supervisor mode", choices);
52
+ const row = rows.find(item => item.label === choice);
53
+ if (choice === undefined) return;
54
+ updateHarnessSetting(key, raw => {
55
+ const current = decode(raw);
56
+ if (choice === mode) return current.enabled === !enabled ? raw : { ...current, enabled: !enabled, revision: randomUUID() };
57
+ if (!current.enabled || !row) return raw;
58
+ const updated = new Set(current.scenarios);
59
+ if (row.selected) updated.delete(row.id);
60
+ else updated.add(row.id);
61
+ return updated.size === current.scenarios.length ? raw : { ...current, scenarios: [...updated], revision: randomUUID() };
62
+ });
63
+ }
64
+ }
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { StringEnum } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { enabledScenarios } from "../settings/supervisor.ts";
6
+ import { OUTCOME_ENTRY } from "../task-context/outcome-state.ts";
7
+
8
+ const ENTRY = "pi-better-harness:supervisor-commitment";
9
+ type Status = "accepted" | "attempted" | "failed" | "verified";
10
+ type Commitment = { id: string; outcome: string; action: string; verification: string; status: Status;
11
+ evidence?: string; observed?: string; reminder?: number };
12
+ type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
13
+ function outcomeId(branch: Branch) {
14
+ for (let i = branch.length - 1; i >= 0; i--) {
15
+ const e = branch[i]!;
16
+ if (e.type === "custom" && e.customType === OUTCOME_ENTRY)
17
+ return (e.data as { outcome?: { status?: string } })?.outcome?.status === "active" ? e.id : undefined;
18
+ }
19
+ }
20
+ function records(branch: Branch) {
21
+ const outcome = outcomeId(branch);
22
+ const items = new Map<string, Commitment>();
23
+ if (!outcome) return items;
24
+ for (const e of branch) {
25
+ if (e.type !== "custom" || e.customType !== ENTRY) continue;
26
+ const item = e.data as Commitment;
27
+ if (item?.outcome === outcome && typeof item.id === "string") items.set(item.id, item);
28
+ }
29
+ return items;
30
+ }
31
+ function describe(c: Commitment) {
32
+ 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");
34
+ }
35
+ export function registerCommitments(pi: ExtensionAPI, onFailure: (ctx: ExtensionContext, evidence: string) => void) {
36
+ let timer: ReturnType<typeof setTimeout> | undefined;
37
+ const enabled = () => enabledScenarios().includes("commitment-followup");
38
+ function clear() { clearTimeout(timer); timer = undefined; }
39
+ function schedule(ctx: ExtensionContext) {
40
+ clear();
41
+ if (!enabled()) return;
42
+ const due = [...records(ctx.sessionManager.getBranch()).values()]
43
+ .filter(c => c.status !== "verified" && c.reminder !== undefined).sort((a, b) => a.reminder! - b.reminder!)[0];
44
+ if (!due) return;
45
+ timer = setTimeout(() => {
46
+ if (!enabled()) return;
47
+ const current = records(ctx.sessionManager.getBranch()).get(due.id);
48
+ if (current?.reminder === due.reminder && current?.status !== "verified") {
49
+ pi.appendEntry(ENTRY, { ...current, reminder: undefined });
50
+ pi.sendMessage({ customType: ENTRY, content: describe({ ...due, reminder: undefined }), display: true }, { triggerTurn: false });
51
+ }
52
+ schedule(ctx);
53
+ }, Math.max(0, due.reminder! - Date.now()));
54
+ timer.unref();
55
+ }
56
+ pi.on("session_shutdown", clear);
57
+ pi.on("session_start", (_e, ctx) => schedule(ctx));
58
+ pi.on("session_tree", (_e, ctx) => schedule(ctx));
59
+ pi.on("agent_start", (_e, ctx) => schedule(ctx));
60
+ pi.registerCommand("supervisor-followup", {
61
+ description: "Show recovery commitments, or request one reminder with: remind <id> <minutes>",
62
+ handler: async (args, ctx) => {
63
+ if (!enabled()) return ctx.ui.notify("Commitment follow-up is disabled.", "info");
64
+ const items = records(ctx.sessionManager.getBranch());
65
+ if (!args.trim()) return ctx.ui.notify([...items.values()].map(describe).join("\n\n") || "No recorded recovery commitments.", "info");
66
+ const match = /^remind\s+(\S+)\s+(\d+)$/.exec(args.trim());
67
+ const c = match && items.get(match[1]!);
68
+ const minutes = match && Number(match[2]);
69
+ if (!c || c.status === "verified" || !minutes || minutes > 1440)
70
+ return ctx.ui.notify("Use remind <open commitment id> <1–1440 minutes>.", "warning");
71
+ pi.appendEntry(ENTRY, { ...c, reminder: Date.now() + minutes * 60_000 });
72
+ schedule(ctx);
73
+ ctx.ui.notify(`Reminder scheduled in ${minutes} minutes.`, "info");
74
+ },
75
+ });
76
+ pi.registerTool({
77
+ name: "supervisor_followup", label: "Recovery commitments",
78
+ description: "Record an agreed recovery and its expected verification, or check progress without sending another reminder. Attach the tool call ID for attempts and a separate successful verification. Use status to answer follow-up questions.",
79
+ parameters: Type.Object({
80
+ action: StringEnum(["accept", "attempt", "verify", "status"] as const), id: Type.Optional(Type.String()),
81
+ recovery: Type.Optional(Type.String({ maxLength: 500 })), verification: Type.Optional(Type.String({ maxLength: 500 })),
82
+ toolCallId: Type.Optional(Type.String({ maxLength: 256 })), observation: Type.Optional(Type.String({ maxLength: 500 })),
83
+ }),
84
+ async execute(_id, p, _signal, _update, ctx) {
85
+ const reply = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
86
+ if (!enabled()) return reply("Commitment follow-up is disabled.");
87
+ const branch = ctx.sessionManager.getBranch();
88
+ const outcome = outcomeId(branch);
89
+ if (!outcome) return reply("No active Outcome.");
90
+ const items = records(branch);
91
+ if (p.action === "status" && !p.id) return reply([...items.values()].map(describe).join("\n\n") || "No recorded commitments.");
92
+ if (p.action === "accept") {
93
+ const action = p.recovery?.trim(), verification = p.verification?.trim();
94
+ if (!action || !verification) throw new Error("Supply the recovery action and its verification condition.");
95
+ const existing = [...items.values()].find(c => c.action === action && c.verification === verification && c.status !== "verified");
96
+ if (existing) return reply(describe(existing));
97
+ const c: Commitment = { id: randomUUID(), outcome, status: "accepted", action, verification };
98
+ pi.appendEntry(ENTRY, c);
99
+ return reply(describe(c));
100
+ }
101
+ const c = items.get(p.id ?? "");
102
+ if (!c) throw new Error("Unknown commitment in this Outcome.");
103
+ if (p.action === "status") return reply(describe(c));
104
+
105
+ const latest = branch.map(e => e.type === "custom" && e.customType === ENTRY && (e.data as Commitment)?.id === c.id).lastIndexOf(true);
106
+ const evidence = branch.slice(latest + 1).find(e => e.type === "message" && e.message.role === "toolResult" &&
107
+ e.message.toolCallId === p.toolCallId && !e.message.toolName.startsWith("supervisor_"));
108
+ if (c.evidence === p.toolCallId && c.evidence) {
109
+ if (p.action === "verify" && c.status === "attempted") throw new Error("Verification requires a separate observed result.");
110
+ return reply(describe(c));
111
+ }
112
+ if (!evidence || evidence.type !== "message" || evidence.message.role !== "toolResult") throw new Error("Provide a new tool result from this branch after the last commitment update.");
113
+ if (c.status === "verified" || p.action === "verify" && c.status !== "attempted") throw new Error("Record a successful attempt before verification.");
114
+ if (!p.observation?.trim()) throw new Error("Describe what the tool result establishes.");
115
+ const next: Commitment = { ...c, status: evidence.message.isError ? "failed" : p.action === "verify" ? "verified" : "attempted",
116
+ evidence: evidence.message.toolCallId, observed: p.observation.trim() };
117
+ if (next.status === "verified") delete next.reminder;
118
+ pi.appendEntry(ENTRY, next);
119
+ schedule(ctx);
120
+ if (next.status === "failed") onFailure(ctx, JSON.stringify({
121
+ commitment: next.id, failedRecovery: next.action, expected: next.verification, observed: next.observed,
122
+ }));
123
+ return reply(describe(next));
124
+ },
125
+ });
126
+ }
@@ -0,0 +1,80 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import type { openSupervisorClient } from "pi-better-subagents/supervisor-client.mjs";
5
+ import { scenarioRevision } from "../settings/supervisor.ts";
6
+ import { digest, scopeEvidence } from "./evidence.ts";
7
+
8
+ const ENTRY = "pi-better-harness:supervisor-decision";
9
+ type DecisionRecord = { owner: string; proposal: string; outcome: string; status: string; expires?: number; result?: string; successful?: boolean };
10
+
11
+ export function registerDecisionTool(pi: ExtensionAPI, connect: typeof openSupervisorClient) {
12
+ const field = (description: string) => Type.String({ minLength: 1, maxLength: 200, description });
13
+ pi.registerTool({
14
+ name: "supervisor_request_decision",
15
+ label: "Supervisor decision",
16
+ description: "Ask the user once about a proposed action shared by owners in this trusted workspace. Reuse the same exact proposal when checking back. Apply the normal tool permission checks when acting. Once the covered effect has been checked, record its observed tool result using verifyToolCallId.",
17
+ parameters: Type.Object({
18
+ reference: field("Stable identifier for this proposed change, shared by the affected owners."),
19
+ operation: field("Exact action requiring a decision."), host: field("Exact host or service."),
20
+ verifyToolCallId: Type.Optional(field("Original tool result that verified the authorized effect in this session.")),
21
+ resource: field("Concrete resource affected."), effect: field("Exact side effect to authorize."),
22
+ }),
23
+ async execute(_id, { verifyToolCallId, ...proposal }, abort, _update, ctx) {
24
+ const reply = (status: string) => ({ content: [{ type: "text" as const, text: `Supervisor decision: ${status}` }], details: { status } });
25
+ const setting = scenarioRevision("shared-decisions");
26
+ if (!setting) return reply("disabled");
27
+ const session = ctx.sessionManager.getSessionId();
28
+ const branch = ctx.sessionManager.getBranch();
29
+ const scope = scopeEvidence(branch);
30
+ const revision = scope?.revision;
31
+ if (!scope || !revision || !ctx.isProjectTrusted()) return reply("requires an active Outcome in a trusted workspace");
32
+ const current = () => ctx.sessionManager.getSessionId() === session &&
33
+ scopeEvidence(ctx.sessionManager.getBranch())?.revision === revision && scenarioRevision("shared-decisions") === setting;
34
+ const key = digest(JSON.stringify([proposal.reference, proposal.operation, proposal.host, proposal.resource, proposal.effect]));
35
+ const index = branch.map(e => {
36
+ if (e.type !== "custom" || e.customType !== ENTRY) return false;
37
+ const r = e.data as DecisionRecord;
38
+ return r.proposal === key && r.outcome === scope.outcomeId && r.owner === session;
39
+ }).lastIndexOf(true);
40
+ const entry = branch[index];
41
+ const last = entry?.type === "custom" ? entry.data as DecisionRecord : undefined;
42
+ if (verifyToolCallId) {
43
+ if (last?.status !== "approved") return reply("no approved decision in this Outcome");
44
+ if (last.result === verifyToolCallId) return reply(last.successful ? "verified" : "verification failed");
45
+ const proof = branch.slice(index + 1).find(e => e.type === "message" && e.message.role === "toolResult" &&
46
+ e.message.toolCallId === verifyToolCallId && !e.message.toolName.startsWith("supervisor_"));
47
+ if (proof?.type !== "message" || proof.message.role !== "toolResult") return reply("missing observed result after approval");
48
+ pi.appendEntry(ENTRY, { ...last, result: verifyToolCallId, successful: !proof.message.isError } satisfies DecisionRecord);
49
+ return reply(proof.message.isError ? "verification failed" : "verified");
50
+ }
51
+ const deadline = AbortSignal.timeout(125_000);
52
+ const signal = abort ? AbortSignal.any([deadline, abort]) : deadline;
53
+ const client = await connect(pi, ctx, signal);
54
+ try {
55
+ let result = await client.decision(ctx.hasUI ? "decision-request" : "decision-query", proposal);
56
+ if (result.status === "ask") {
57
+ const token = result.token;
58
+ const lines = Object.entries(proposal).map(([k, v]) => `${k}: ${v}`);
59
+ const scope = `${lines.join("\n")}\n\nApplies for ${result.durationMinutes} minutes to owners requesting this exact action in ${result.workspace}.`;
60
+ const choice = current() && !signal.aborted ? await ctx.ui.select(scope, ["Approve", "Deny"], { signal, timeout: result.timeoutMs }) : undefined;
61
+ const answer = !current() || signal.aborted || !choice ? "cancelled" : choice === "Approve" ? "approved" : "denied";
62
+ result = await client.decision("decision-answer", proposal, token, answer);
63
+ } else {
64
+ // Other owners wait for this question's answer without opening another dialog.
65
+ while (result.status === "pending" && current() && !signal.aborted) {
66
+ await delay(1500, undefined, { signal });
67
+ result = await client.decision("decision-query", proposal);
68
+ }
69
+ }
70
+ if (!current()) return reply("stale");
71
+ if (result.status === "approved" || result.status === "denied") {
72
+ if (last?.status !== result.status || last.expires !== result.expires)
73
+ pi.appendEntry(ENTRY, { owner: session, proposal: key, outcome: scope.outcomeId, status: result.status, expires: result.expires } satisfies DecisionRecord);
74
+ else if (last.result) return reply(`${result.status} · ${last.successful ? "verified" : "verification failed"}`);
75
+ }
76
+ return reply(result.status);
77
+ } finally { client.close(); }
78
+ },
79
+ });
80
+ }
@@ -0,0 +1,53 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ExtensionContext, ToolResultEvent } from "@earendil-works/pi-coding-agent";
3
+ import { OUTCOME_ENTRY, type Outcome } from "../task-context/outcome-state.ts";
4
+ import { EXTENSION_NAME, type PlanEntry } from "../task-context/types.ts";
5
+
6
+ export type Scenario = "stall-diagnosis" | "scope-review" | "commitment-followup";
7
+ type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
8
+ export const ENTRY = "pi-better-harness:supervisor-review";
9
+ export const digest = (text: string) => createHash("sha256").update(text).digest("hex");
10
+
11
+ /** Keep the fingerprint local. File contents and raw tool output never enter a model prompt here. */
12
+ export function readFingerprint(event: ToolResultEvent) {
13
+ if (event.isError || !["read", "grep", "find", "ls"].includes(event.toolName)) return;
14
+ const hash = createHash("sha256");
15
+ hash.update(JSON.stringify(event.input));
16
+ for (const block of event.content) {
17
+ if (block.type !== "text" || block.text.length > 64_000) return;
18
+ hash.update(JSON.stringify(block.text));
19
+ }
20
+ return { tool: event.toolName, target: typeof event.input.path === "string" ? event.input.path.slice(-250) : "current workspace", fingerprint: hash.digest("hex") };
21
+ }
22
+ export class RepeatedRead {
23
+ private last?: { fingerprint: string; since: number; count: number };
24
+ reset() { this.last = undefined; }
25
+ record(value: string, now: number, minimumAge: number) {
26
+ if (this.last?.fingerprint !== value) this.last = { fingerprint: value, since: now, count: 0 };
27
+ this.last.count++;
28
+ if (this.last.count >= 3 && now - this.last.since >= minimumAge) return this.last.since;
29
+ }
30
+ }
31
+
32
+ export function scopeEvidence(branch: Branch) {
33
+ const newest = [...branch].reverse();
34
+ const outcomeEntry = newest.find(entry => entry.type === "custom" && entry.customType === OUTCOME_ENTRY);
35
+ const outcome = outcomeEntry?.type === "custom" && (outcomeEntry.data as { outcome?: Outcome })?.outcome;
36
+ if (!outcome || outcome.status !== "active" || typeof outcome.objective !== "string") return;
37
+ const user = newest.find(entry => entry.type === "message" && entry.message.role === "user");
38
+ const content = user?.type === "message" && user.message.role === "user" ? user.message.content : "";
39
+ const lastInstruction = typeof content === "string" ? content : content.filter(x => x.type === "text").map(x => x.text).join("\n");
40
+ const plan = newest.find(entry => entry.type === "custom" && entry.customType === EXTENSION_NAME &&
41
+ ["set", "clear"].includes((entry.data as PlanEntry | undefined)?.kind ?? ""));
42
+ const data = plan?.type === "custom" ? plan.data as PlanEntry : undefined;
43
+ const steps = data?.kind === "set" && Array.isArray(data.plan?.steps) ? data.plan.steps.slice(0, 50).map(s => ({ id: s.id, step: s.step, status: s.status })) : [];
44
+ return {
45
+ outcomeId: outcomeEntry!.id,
46
+ planId: data?.kind === "set" ? data.plan.planId : undefined,
47
+ revision: [outcomeEntry!.id, user?.id, plan?.id].join("/"),
48
+ objective: outcome.objective.slice(0, 2000),
49
+ doneWhen: outcome.doneWhen?.slice(0, 8).map(s => s.slice(0, 400)),
50
+ boundaries: outcome.boundaries?.slice(0, 8).map(s => s.slice(0, 400)),
51
+ lastInstruction: lastInstruction.slice(-2000), steps,
52
+ };
53
+ }
@@ -0,0 +1,206 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { Type } from "typebox";
3
+ import { randomUUID } from "node:crypto";
4
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+
6
+ import { openSupervisorClient } from "pi-better-subagents/supervisor-client.mjs";
7
+ import { goalStallThresholds } from "pi-better-goal/src/stall.ts";
8
+ import { DEFAULT_STALL_THRESHOLDS } from "pi-better-goal/src/shared-stall-detector.ts";
9
+ import { enabledScenarios } from "../settings/supervisor.ts";
10
+ import { registerCommitments } from "./commitments.ts";
11
+ import { registerDecisionTool } from "./decisions.ts";
12
+ import { registerSharedFault } from "./shared-fault.ts";
13
+ import { digest, ENTRY, readFingerprint, RepeatedRead, scopeEvidence, type Scenario } from "./evidence.ts";
14
+
15
+ const prompts = {
16
+ "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.",
17
+ "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.",
18
+ "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.",
19
+ };
20
+ const FEEDBACK = "pi-better-harness:supervisor-progress";
21
+ 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 } };
22
+ export default function supervisor(pi: ExtensionAPI) {
23
+ installSupervisor(pi, openSupervisorClient);
24
+ }
25
+ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervisorClient) {
26
+ registerSharedFault(pi, connect);
27
+ registerDecisionTool(pi, connect);
28
+ registerCommitments(pi, (ctx, evidence) => { void review(ctx, "commitment-followup", evidence); });
29
+ const repeats = new RepeatedRead();
30
+ let pending: AbortController | undefined;
31
+ let pendingScenario: Scenario | undefined;
32
+ let readKey: string | undefined;
33
+ let reviewedShape: string | undefined;
34
+ let stallEvidence: string | undefined;
35
+ const lastAttempt = new Map<Scenario, { key: string; at: number }>();
36
+ let serial = 0;
37
+ const reset = () => { repeats.reset(); readKey = undefined; stallEvidence = undefined; serial++; pending?.abort(); pending = undefined; };
38
+ const newBranch = () => { reset(); reviewedShape = undefined; lastAttempt.clear(); };
39
+ pi.on("session_start", newBranch);
40
+ pi.on("session_tree", newBranch);
41
+ pi.on("session_shutdown", reset);
42
+ pi.on("input", () => { reset(); });
43
+ pi.on("before_agent_start", () => {
44
+ const selected = enabledScenarios();
45
+ const hints = [];
46
+ if (selected.includes("shared-decisions")) hints.push("For an exact action that several owners need the user to authorize, use supervisor_request_decision with the same proposal reference and exact effects.");
47
+ if (selected.includes("commitment-followup")) hints.push("When committing to a recovery, record its action and verification condition with supervisor_followup. Record attempts and verification using observed tool result IDs. Use status for progress inquiries.");
48
+ if (hints.length) return { message: { customType: "pi-better-harness:supervisor-controls", content: hints.join("\n"), display: false } };
49
+ });
50
+
51
+ function planShape(ctx: ExtensionContext) {
52
+ const scope = scopeEvidence(ctx.sessionManager.getBranch());
53
+ return scope && digest(JSON.stringify([scope.objective, scope.doneWhen, scope.boundaries, scope.lastInstruction,
54
+ scope.steps.map(step => [step.id, step.step])]));
55
+ }
56
+
57
+ async function review(ctx: ExtensionContext, scenario: Scenario, detail: string, publish = true) {
58
+ if (pending || !enabledScenarios().includes(scenario)) return;
59
+ const branch = ctx.sessionManager.getBranch();
60
+ const scope = scopeEvidence(branch);
61
+ if (!scope || (scenario === "scope-review" && !scope.steps.some(s => s.status !== "completed"))) return;
62
+ // A repeated read's first-observed timestamp changes on reconnect. Its evidence does not.
63
+ const observationId = scenario === "stall-diagnosis" ? readKey ?? detail : detail;
64
+ const key = digest(JSON.stringify([scenario, scope.revision, observationId]));
65
+ const cached = branch.find(e => e.type === "custom" && e.customType === ENTRY && (e.data as Receipt)?.key === key);
66
+ if (cached?.type === "custom") return (cached.data as Receipt).advice ?? "No intervention recommended.";
67
+ const previous = lastAttempt.get(scenario);
68
+ if (publish && previous?.key === key && Date.now() - previous.at < 45_000) return;
69
+ lastAttempt.set(scenario, { key, at: Date.now() });
70
+ const generation = serial;
71
+ const sessionId = ctx.sessionManager.getSessionId();
72
+ const controller = new AbortController();
73
+ pending = controller;
74
+ pendingScenario = scenario;
75
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(35_000)]);
76
+ let catalog: Awaited<ReturnType<typeof openSupervisorClient>> | undefined;
77
+ let token: string | undefined;
78
+ const current = () => !signal.aborted && serial === generation && ctx.sessionManager.getSessionId() === sessionId &&
79
+ enabledScenarios().includes(scenario) && scopeEvidence(ctx.sessionManager.getBranch())?.revision === scope.revision;
80
+ try {
81
+ catalog = await connect(pi, ctx, signal);
82
+ if (!current()) return;
83
+ const admission = await catalog.review(scenario, "begin");
84
+ token = admission.token;
85
+ if (!token) return;
86
+ const role = await catalog.role();
87
+ const modelId = role?.model;
88
+ if (!role || typeof modelId !== "string" || !current()) return;
89
+ const slash = modelId.indexOf("/");
90
+ const model = ctx.modelRegistry.find(modelId.slice(0, slash), modelId.slice(slash + 1));
91
+ if (!model) return;
92
+ const provider = ctx.modelRegistry.getProvider(model.provider);
93
+ const auth = provider && await ctx.modelRegistry.getProviderAuth(model.provider);
94
+ if (!provider || !auth || !current()) return;
95
+ const target = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;
96
+ const evidenceRefs = ["outcome", "observation", ...scope.steps.map(step => `step:${step.id}`)];
97
+ const result = await provider.streamSimple(target, {
98
+ 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"),
99
+ messages: [{ role: "user", content: JSON.stringify({ scope, observation: detail, evidenceRefs }), timestamp: Date.now() }],
100
+ }, { apiKey: auth.auth.apiKey, headers: auth.auth.headers, env: auth.env, sessionId: randomUUID(), signal, maxRetries: 0, timeoutMs: 25_000, maxTokens: 1100,
101
+ reasoning: role.effort && role.effort !== "off" ? role.effort : undefined }).result();
102
+ if (result.stopReason !== "stop" || !current()) return;
103
+ const output = result.content.filter(x => x.type === "text").map(x => x.text).join("");
104
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(output.trim());
105
+ const answer = JSON.parse(fenced?.[1] ?? output);
106
+ const { advice } = answer;
107
+ const cited = answer.evidence ?? [];
108
+ if (!Array.isArray(cited) || cited.length > 52) return;
109
+ const evidence: string[] = cited.map(item => typeof item === "string" ? item : item?.id);
110
+ const steps: string[] = answer.steps ?? [];
111
+ const expected: string = answer.expected ?? "";
112
+ if (!evidence.every(id => evidenceRefs.includes(id)) ||
113
+ !Array.isArray(steps) || steps.length > 50 || !steps.every(id => scope.steps.some(step => step.id === id && step.status !== "completed")) ||
114
+ typeof expected !== "string" || expected.length > 500) return;
115
+ if (advice && (!evidence.length || !expected.trim() || scenario === "scope-review" && !steps.length)) return;
116
+ if (advice !== null && (typeof advice !== "string" || !advice.trim() || advice.length > 2400)) return;
117
+ if ((await catalog.review(scenario, "finish", token)).status !== "admitted" || !current()) return;
118
+ token = undefined;
119
+ // Identify a pruning suggestion by the work it removes, even if a later answer rephrases it.
120
+ const scopeTargets = scenario === "scope-review" && steps.length ? digest(JSON.stringify([
121
+ scope.objective, scope.doneWhen, scope.boundaries,
122
+ [...new Set(steps)].sort().map(id => [id, scope.steps.find(step => step.id === id)?.step]),
123
+ ])) : undefined;
124
+ const receipt: Receipt = { key, scenario, scopeTargets, revision: scope.revision, outcome: scope.outcomeId, plan: scope.planId,
125
+ evidence, expected, steps, catalogRevision: role.revision, role: { instructions: role.instructions, model: modelId, effort: role.effort }, advice };
126
+ pi.appendEntry(ENTRY, receipt);
127
+ if (scenario === "scope-review") reviewedShape = planShape(ctx);
128
+ const alreadySuggested = scenario === "scope-review" && branch.some(e => {
129
+ if (e.type !== "custom" || e.customType !== ENTRY) return false;
130
+ const r = e.data as Receipt;
131
+ return r.scenario === scenario && r.outcome === scope.outcomeId && r.plan === scope.planId &&
132
+ (scopeTargets && scopeTargets === r.scopeTargets ||
133
+ !r.scopeTargets && r.advice === advice && r.expected === expected && JSON.stringify(r.steps) === JSON.stringify(steps));
134
+ });
135
+ if (advice && publish && !alreadySuggested) pi.sendMessage({ customType: ENTRY, content: `${advice}\nVerify: ${expected}`, details: { evidence, key }, display: true }, { deliverAs: "steer", triggerTurn: false });
136
+ return advice ?? "No intervention recommended.";
137
+ } catch { /* An unavailable diagnostic leaves the owner's original operation running. */ }
138
+ finally {
139
+ try { if (token) await catalog?.review(scenario, "release", token); } catch { /* Lease expires independently. */ }
140
+ catalog?.close();
141
+ if (pending === controller) pending = undefined;
142
+ }
143
+ }
144
+ function recordProgress(ctx: ExtensionContext) {
145
+ if (!enabledScenarios().length) return;
146
+ const branch = ctx.sessionManager.getBranch(), scope = scopeEvidence(branch);
147
+ if (!scope?.planId) return;
148
+ const prior = new Map<string, string>();
149
+ for (const e of branch) if (e.type === "custom" && e.customType === FEEDBACK) {
150
+ const f = e.data as { key: string; observed: string };
151
+ prior.set(f.key, f.observed);
152
+ }
153
+ for (const e of branch) {
154
+ if (e.type !== "custom" || e.customType !== ENTRY) continue;
155
+ const r = e.data as Receipt;
156
+ if (!r.advice || r.plan !== scope.planId || r.outcome !== scope.outcomeId || !r.steps?.length) continue;
157
+ const observed = r.steps.filter(id => r.scenario === "scope-review"
158
+ ? !scope.steps.some(s => s.id === id) : scope.steps.some(s => s.id === id && s.status === "completed")).sort().join(", ");
159
+ if (observed && prior.get(r.key) !== observed) {
160
+ pi.appendEntry(FEEDBACK, { key: r.key, observed, scenario: r.scenario, outcome: r.outcome, revision: scope.revision,
161
+ status: observed.split(", ").length === r.steps.length ? "observed" : "partially observed" });
162
+ }
163
+ }
164
+ }
165
+ const scopeChange = "The owner revised the Outcome or Todo.";
166
+ function reviewPlan(ctx: ExtensionContext) {
167
+ if (enabledScenarios().includes("scope-review") && planShape(ctx) !== reviewedShape)
168
+ void review(ctx, "scope-review", scopeChange);
169
+ }
170
+ // User instructions can revise scope without updating Todo in the same turn.
171
+ pi.on("agent_end", (_event, ctx) => { reviewPlan(ctx); });
172
+ pi.registerTool({
173
+ name: "supervisor_review", label: "Review Outcome",
174
+ description: "Consult Supervisor about scope or a possible progress stall. Shares the proactive review and returns prior advice without another push.",
175
+ parameters: Type.Object({ scenario: StringEnum(["scope-review", "stall-diagnosis"] as const) }),
176
+ async execute(_id, { scenario }, _signal, _update, ctx) {
177
+ const reply = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
178
+ if (!enabledScenarios().includes(scenario)) return reply("This Supervisor scenario is disabled.");
179
+ const detail = scenario === "scope-review" ? scopeChange : stallEvidence;
180
+ if (!detail) return reply("No repeated-read stall has been observed.");
181
+ return reply(await review(ctx, scenario, detail, false) ?? "No completed review available for the current evidence.");
182
+ },
183
+ });
184
+ pi.on("tool_result", (event, ctx) => {
185
+ if (event.toolName.startsWith("supervisor_")) return;
186
+ if (event.toolName === "update_todo" && !event.isError) {
187
+ reset();
188
+ recordProgress(ctx);
189
+ if (event.input.todo || event.input.outcome) reviewPlan(ctx);
190
+ return;
191
+ }
192
+ if (!enabledScenarios().includes("stall-diagnosis")) { repeats.reset(); return; }
193
+ const value = readFingerprint(event);
194
+ if (value?.fingerprint !== readKey) {
195
+ if (pendingScenario === "stall-diagnosis") pending?.abort();
196
+ readKey = value?.fingerprint;
197
+ stallEvidence = undefined;
198
+ }
199
+ if (!value) { repeats.reset(); return; }
200
+ const since = repeats.record(value.fingerprint, Date.now(), goalStallThresholds().stallMs ?? DEFAULT_STALL_THRESHOLDS.stallMs);
201
+ if (since !== undefined) {
202
+ stallEvidence = `Repeated successful ${value.tool} calls on ${value.target} since ${new Date(since).toISOString()} with identical arguments and output. Evidence ${value.fingerprint}.`;
203
+ void review(ctx, "stall-diagnosis", stallEvidence);
204
+ }
205
+ });
206
+ }