pi-better-harness 0.54.0 → 0.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +52 -55
- package/extensions/settings/copy.ts +6 -5
- package/extensions/settings/index.ts +8 -0
- package/extensions/settings/page.ts +2 -2
- package/extensions/settings/supervisor.ts +64 -0
- package/extensions/supervisor/commitments.ts +126 -0
- package/extensions/supervisor/decisions.ts +80 -0
- package/extensions/supervisor/evidence.ts +53 -0
- package/extensions/supervisor/index.ts +206 -0
- package/extensions/supervisor/shared-fault.ts +62 -0
- package/extensions/task-context/compact-task-header.ts +19 -4
- package/extensions/task-context/dynamic-workflow-view.ts +19 -109
- package/extensions/task-context/index.ts +119 -97
- package/extensions/task-context/outcome-state.ts +9 -6
- package/extensions/task-context/plan-presentation.ts +29 -9
- package/extensions/task-context/preferences.ts +9 -15
- package/extensions/task-context/work-ledger-actions.ts +30 -17
- package/extensions/task-context/work-ledger-session.ts +4 -2
- package/extensions/task-context/workflow-diagram.ts +59 -63
- package/extensions/task-context/workflow-plan.ts +70 -11
- package/extensions/task-context/workflow-view.ts +74 -0
- package/node_modules/pi-better-background-tasks/package.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
- 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.gz +0 -0
- 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.gz +0 -0
- 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.gz +0 -0
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/src/ci-observation.ts +118 -0
- package/node_modules/pi-better-background-tasks/src/managed-client.ts +6 -2
- package/node_modules/pi-better-background-tasks/src/managed-frontend.ts +36 -6
- package/node_modules/pi-better-background-tasks/src/observed-waits.ts +33 -6
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +1 -0
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/discovery.ts +7 -4
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/operations.ts +5 -11
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/schema.ts +54 -1
- package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +5 -5
- package/node_modules/pi-better-background-tasks/src/supervisor/generated/identity.mjs +5 -0
- package/node_modules/pi-better-background-tasks/src/supervisor/identity.ts +6 -0
- package/node_modules/pi-better-background-tasks/src/supervisor/supervisor.ts +3 -4
- package/node_modules/pi-better-goal/README.md +18 -14
- package/node_modules/pi-better-goal/package.json +1 -1
- package/node_modules/pi-better-goal/src/assignment-inbox.mjs +4 -0
- package/node_modules/pi-better-goal/src/index.ts +143 -76
- package/node_modules/pi-better-goal/src/settings-page.ts +2 -2
- package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +1 -0
- package/node_modules/pi-better-goal/src/task-context.ts +15 -2
- package/node_modules/pi-better-goal/src/workflow.ts +9 -3
- package/node_modules/pi-better-subagents/catalog-schema.ts +1 -0
- package/node_modules/pi-better-subagents/cleanup.ts +6 -8
- package/node_modules/pi-better-subagents/docs/agent-catalog.md +1 -0
- package/node_modules/pi-better-subagents/package.json +1 -1
- package/node_modules/pi-better-subagents/registry.ts +11 -6
- package/node_modules/pi-better-subagents/retained-result.ts +2 -3
- package/node_modules/pi-better-subagents/roles/role.supervisor.md +16 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
- 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.gz +0 -0
- 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.gz +0 -0
- 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.gz +0 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-subagents/shared-catalog.ts +14 -2
- package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-inbox.mjs +4 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/discovery.ts +7 -4
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/operations.ts +5 -11
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +54 -1
- package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +5 -5
- package/node_modules/pi-better-subagents/supervisor-client.d.mts +11 -0
- package/node_modules/pi-better-subagents/supervisor-client.mjs +34 -0
- package/node_modules/pi-better-subagents/worker-waits.ts +3 -3
- package/node_modules/pi-better-subagents/workspace-files.ts +27 -5
- package/package.json +7 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.56.0] - 2026-11-26
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- The saved objective in Todo is now called Goal. Start it from the Todo panel and use `/goal pause` and `/goal resume` to control the current Todo.
|
|
8
|
+
- Harness settings has one switch for automatically starting Goals. Existing saved objectives remain available for manual start.
|
|
9
|
+
- Bundle Goal 0.17.0, Background Tasks 0.21.1, and Subagents 0.39.1.
|
|
10
|
+
|
|
11
|
+
## [0.55.0] - 2026-11-25
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- 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)
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- 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)
|
|
20
|
+
|
|
3
21
|
## [0.54.0] - 2026-11-25
|
|
4
22
|
|
|
5
23
|
### Added
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<img src="https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/brand/logo.png" alt="Pi Better Harness logo" width="128" height="128" />
|
|
4
4
|
|
|
5
|
-
`pi-better-harness` is a Pi meta package for an opt-in foreground write sandbox, delegated subagents, durable background tasks, synchronous SSH commands, goal tracking, and
|
|
5
|
+
`pi-better-harness` is a Pi meta package for an opt-in foreground write sandbox, delegated subagents, durable background tasks, synchronous SSH commands, goal tracking, and Goal & Todo.
|
|
6
6
|
|
|
7
7
|
## Quick Answer
|
|
8
8
|
|
|
@@ -13,57 +13,43 @@ Use `pi-better-harness` when you want the full working set for Pi. It manages:
|
|
|
13
13
|
- `pi-better-background-tasks` for durable shell tasks and watchers.
|
|
14
14
|
- `pi-better-ssh` for short remote commands over reusable SSH connections.
|
|
15
15
|
- `pi-better-goal` for explicit triggers, pause/resume, and background-aware continuation.
|
|
16
|
-
- Harness-owned
|
|
16
|
+
- Harness-owned Goal & Todo for session context and checklist progress. Saved work appears in the panel. Automatic Goal execution defaults to Off.
|
|
17
17
|
|
|
18
18
|
`pi-better-read-aloud` is intentionally not included yet.
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`get_todo`
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
Hooks enable `update_todo`, `get_todo`, capture, matching Goal lifecycle bridge
|
|
51
|
-
writes, outcome updates, and automated cleanup. With hooks enabled, Harness records
|
|
52
|
-
a hidden, persistent outcome update at the next agent start only when its content
|
|
53
|
-
changes. It does not rebuild reminders before each model call. Turning hooks off stops those
|
|
54
|
-
hooks without deleting saved state or starting a turn. `/goal` and skills never
|
|
55
|
-
enable them.
|
|
56
|
-
|
|
57
|
-
In `/harness-settings`, **Auto-start Goal** optionally starts
|
|
58
|
-
a Goal after a successful explicit outcome save with an objective and nonempty
|
|
59
|
-
`doneWhen` criteria. It defaults Off; `/goal settings auto-start-from-outcome on`
|
|
60
|
-
enables it. Existing active, paused or budget-limited Goals stay unchanged, and
|
|
61
|
-
restoring state or toggling settings never starts work. The outcome and Todo are
|
|
62
|
-
preserved; subsequent continuation follows the existing Goal controls.
|
|
20
|
+
<a id="outcome--todo"></a>
|
|
21
|
+
## Goal & Todo
|
|
22
|
+
|
|
23
|
+
The Goal records what the user wants to achieve. Its Todo lists the steps. The
|
|
24
|
+
panel shows checklist progress on the left and Goal status on the right. A
|
|
25
|
+
saved Goal has a **Start Goal** button. Click it or press **Alt+G** to start work
|
|
26
|
+
with the existing checklist. Use `/goal pause` to interrupt
|
|
27
|
+
foreground work and hold continuation. Both commands use the current Todo,
|
|
28
|
+
including checklists saved before a Goal was attached.
|
|
29
|
+
|
|
30
|
+
`/harness-settings` has one Goal setting, **Auto-start Goals** (default **Off**).
|
|
31
|
+
Turn it on to start a newly saved Goal with acceptance criteria, restart explicitly
|
|
32
|
+
reopened work, or bind a Goal when invoking `/skill:rush-issues` or
|
|
33
|
+
`/skill:resolve-issues`. Changing the switch takes effect on the next such action.
|
|
34
|
+
With it off, use `/goal resume` to start saved work manually.
|
|
35
|
+
|
|
36
|
+
The panel shows `goal saved` before execution starts and `goal active` with a
|
|
37
|
+
clock while it runs. Use `/todo` to reveal the panel and `/todo expand` to see
|
|
38
|
+
all steps. `get_todo` returns the full Goal and Todo, including acceptance criteria
|
|
39
|
+
and boundaries. Completing a step updates checklist progress. The Goal stays
|
|
40
|
+
open until its completion is recorded.
|
|
41
|
+
|
|
42
|
+
Use `update_todo({ goal: { objective, doneWhen, boundaries }, todo })` to save
|
|
43
|
+
work. Any of `doneWhen`, `boundaries` and `todo` may be omitted. Set
|
|
44
|
+
`newTask: true` for an unrelated task. Existing session records, settings and
|
|
45
|
+
clients using the legacy `outcome` field remain supported.
|
|
46
|
+
|
|
47
|
+
Todo uses the same workflow view for a bound task plan and a dynamic workflow.
|
|
48
|
+
It shows tasks on the left and the workflow diagram on the right. Below 36 terminal
|
|
49
|
+
columns, the diagram follows the task list.
|
|
63
50
|
|
|
64
51
|
Existing Plan session histories restore as Todo. Workflow task-plan files and
|
|
65
|
-
revision checks
|
|
66
|
-
optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
|
|
52
|
+
revision checks continue to govern workflow-owned plans. See the [usage guide](docs/usage.md#goal--todo).
|
|
67
53
|
|
|
68
54
|
### Dynamic workflows
|
|
69
55
|
|
|
@@ -74,11 +60,10 @@ workflow for dependencies, role handoffs or repeated review. The command works
|
|
|
74
60
|
in every mode and keeps your saved preference.
|
|
75
61
|
|
|
76
62
|
The agent records an objective, acceptance criteria, required outputs and task
|
|
77
|
-
dependencies.
|
|
63
|
+
dependencies. The diagram shows dependencies and review loops.
|
|
78
64
|
Task icons distinguish ready (○), working (●), waiting (·), optional standby (–),
|
|
79
65
|
failed (×), and completed (✓) steps. In mouse-enabled Pi, click a task to highlight
|
|
80
66
|
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
67
|
Independent tasks can run together. A join waits for each prerequisite's output.
|
|
83
68
|
If a reviewer requests changes, the revision opens and the revised artifact
|
|
84
69
|
returns to review. Delivery waits for approval of the current version.
|
|
@@ -127,7 +112,7 @@ For project-local Pi settings:
|
|
|
127
112
|
npx pi-better-harness install --local
|
|
128
113
|
```
|
|
129
114
|
|
|
130
|
-
The installer also registers Harness with filters for its own settings, minimal output, and
|
|
115
|
+
The installer also registers Harness with filters for its own settings, minimal output, and Goal & Todo extensions. It removes an old `pi-better-plan` registration in the selected scope. The component packages keep their separate identities. Pi's normal installation prompts and errors still apply.
|
|
131
116
|
|
|
132
117
|
The single-bundle installation remains available:
|
|
133
118
|
|
|
@@ -141,8 +126,7 @@ Cloud provider and requires Pi's `registerVirtualModel` API.
|
|
|
141
126
|
|
|
142
127
|
After a normal bundle install or `pi update`, Harness masks any separately loaded
|
|
143
128
|
`pi-better-plan` package before Pi registers its tools, `/plan` command, widgets,
|
|
144
|
-
or prompt hooks. This applies in either load order,
|
|
145
|
-
hooks are off. The old registration and cached files may remain, but are inactive while
|
|
129
|
+
or prompt hooks. This applies in either load order. The old registration and cached files may remain, but are inactive while
|
|
146
130
|
Harness is loaded. Settings and session history are not rewritten. The explicit
|
|
147
131
|
installer above removes the old registration in its selected scope instead.
|
|
148
132
|
|
|
@@ -231,7 +215,7 @@ pi -e ./packages/pi-better-harness/extensions/minimal-output/index.ts
|
|
|
231
215
|
The bundled harness provides `/harness-settings`, using Pi's native settings
|
|
232
216
|
list. Work planning comes first, followed by delegation and sandbox access,
|
|
233
217
|
background waits and completion delivery, then display settings. It opens
|
|
234
|
-
the settings screens of loaded Sandbox
|
|
218
|
+
the settings screens of loaded Sandbox and Subagents
|
|
235
219
|
packages without duplicating their configuration, plus the **Agent catalog** shortcut
|
|
236
220
|
to the `/agents` catalog. `/sandbox`, `/subagents settings`, `/agents`, and
|
|
237
221
|
`/goal settings` remain available in standalone installations.
|
|
@@ -245,7 +229,7 @@ Worker-owned tasks expose status and logs; their execution remains managed by th
|
|
|
245
229
|
owning agent. Older worker tasks appear when a retained assignment wait proves
|
|
246
230
|
their parent, so unrelated sessions are never inferred from a reused conversation.
|
|
247
231
|
|
|
248
|
-
**Pin work panels** controls the shared navigator used by Goal
|
|
232
|
+
**Pin work panels** controls the shared navigator used by Goal & Todo,
|
|
249
233
|
Subagents, and Background Tasks. **On** (the default) keeps it above the input;
|
|
250
234
|
**Off** places it in the conversation so it scrolls with chat. Changes apply
|
|
251
235
|
immediately and save under `piBetterHarness.navigator` for future sessions.
|
|
@@ -343,9 +327,22 @@ The hub is TUI-only and is included by the installer. To load the settings exten
|
|
|
343
327
|
pi -e ./packages/pi-better-harness/extensions/settings/index.ts
|
|
344
328
|
```
|
|
345
329
|
|
|
330
|
+
### Agent Supervisor
|
|
331
|
+
|
|
332
|
+
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.
|
|
333
|
+
|
|
334
|
+
| Scenario | What the owner receives |
|
|
335
|
+
| --- | --- |
|
|
336
|
+
| 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. |
|
|
337
|
+
| Diagnose stalled Goals | A diagnostic review after repeated identical successful repository reads return the same evidence throughout the stall interval. |
|
|
338
|
+
| Review Goal scope | A review of changed Todo steps against the latest user instruction and Goal. The owner chooses which steps to keep or prune. Use `supervisor_review` for an on-demand review. |
|
|
339
|
+
| 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. |
|
|
340
|
+
| 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. |
|
|
341
|
+
| 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>`. |
|
|
342
|
+
|
|
346
343
|
## When To Use
|
|
347
344
|
|
|
348
|
-
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.
|
|
345
|
+
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. Goal & Todo is available through Harness.
|
|
349
346
|
|
|
350
347
|
## Compatibility
|
|
351
348
|
|
|
@@ -11,7 +11,8 @@ export const controlCopy = new Map<string, SettingCopy>([
|
|
|
11
11
|
description: "When the session is waiting for a local task with callbacks on, Pi asks the main agent to review it after this long without progress. Each review shows elapsed time and the last check or output.",
|
|
12
12
|
}],
|
|
13
13
|
["goal-auto-start", {
|
|
14
|
-
|
|
14
|
+
label: "Auto-start Goals",
|
|
15
|
+
description: "Start a Goal when Pi saves acceptance criteria, reopens completed work, or runs an issue workflow. When off, use /goal resume to start saved work.",
|
|
15
16
|
}],
|
|
16
17
|
["tool-call-guard", {
|
|
17
18
|
label: "Foreground wait guard",
|
|
@@ -21,7 +22,7 @@ export const controlCopy = new Map<string, SettingCopy>([
|
|
|
21
22
|
description: "Choose when Pi can plan a workflow automatically. Adaptive uses workflows for dependencies, handoffs or review. /dynamic-workflow starts one run in every mode.",
|
|
22
23
|
}],
|
|
23
24
|
["outcome-todo", {
|
|
24
|
-
label: "
|
|
25
|
+
label: "Goal and Todo tools",
|
|
25
26
|
description: "Lets Pi record what the session should deliver and track its progress as a checklist.",
|
|
26
27
|
}],
|
|
27
28
|
["outcome-todo-ledger", {
|
|
@@ -29,8 +30,8 @@ export const controlCopy = new Map<string, SettingCopy>([
|
|
|
29
30
|
description: "Lets sessions attach a saved project checklist and carry its progress across sessions. Use /ledger to list or attach a ledger.",
|
|
30
31
|
}],
|
|
31
32
|
["outcome-todo-display", {
|
|
32
|
-
label: "
|
|
33
|
-
description: "Shows the
|
|
33
|
+
label: "Goal and Todo panel",
|
|
34
|
+
description: "Shows the saved Goal, its execution status, and Todo steps. The panel also works with the tools off.",
|
|
34
35
|
}],
|
|
35
36
|
["navigator-sticky", {
|
|
36
37
|
label: "Pin work panels",
|
|
@@ -58,7 +59,7 @@ export const linkCopy = new Map<string, SettingCopy>([
|
|
|
58
59
|
description: "Browse the agents Pi can delegate to and manage their profiles.",
|
|
59
60
|
}],
|
|
60
61
|
["goal", {
|
|
61
|
-
label: "Goal settings",
|
|
62
|
+
label: "Goal execution settings",
|
|
62
63
|
description: "Choose when Goals continue automatically, resume from conversation, or pause on Escape.",
|
|
63
64
|
}],
|
|
64
65
|
["sandbox", {
|
|
@@ -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;
|
|
@@ -19,10 +19,10 @@ const callbackDescription = (source: "session" | "default") => [
|
|
|
19
19
|
|
|
20
20
|
// Keep each package page beside the controls used for the same task.
|
|
21
21
|
const taskOrder = [
|
|
22
|
-
"setting:
|
|
22
|
+
"setting:goal-auto-start", "setting:dynamic-workflow", "setting:outcome-todo-ledger",
|
|
23
23
|
"link:subagents", "link:agents", "link:sandbox",
|
|
24
24
|
"setting:tool-call-guard", "setting:background-review-interval", CALLBACK_SETTING_ID,
|
|
25
|
-
"setting:navigator-view", "setting:navigator-sticky",
|
|
25
|
+
"setting:navigator-view", "setting:navigator-sticky",
|
|
26
26
|
"setting:tool-output", "setting:tool-animation", "setting:session-recap", "link:recap-prompt",
|
|
27
27
|
];
|
|
28
28
|
const position = new Map(taskOrder.map((id, index) => [id, index]));
|
|
@@ -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 Goals"],
|
|
10
|
+
["scope-review", "Review Goal 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 Goal.");
|
|
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 Goal.");
|
|
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 Goal 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 Goal");
|
|
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
|
+
}
|