pi-better-harness 0.60.0 → 0.61.1
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 +16 -0
- package/README.md +46 -3
- package/bin/pi-better-harness.mjs +1 -1
- package/extensions/harness-instructions/examples.md +20 -8
- package/extensions/harness-instructions/modules/collaboration.md +1 -1
- package/extensions/harness-instructions/modules/communication.md +1 -1
- package/extensions/harness-instructions/modules/decisions.md +1 -1
- package/extensions/harness-instructions/modules/engineering.md +1 -1
- package/extensions/harness-instructions/modules/ownership.md +1 -1
- package/extensions/harness-instructions/modules/verification.md +1 -1
- package/extensions/settings/page.ts +1 -1
- package/extensions/task-context/dynamic-workflow-runtime.ts +6 -1
- package/lib/cli.mjs +18 -4
- package/lib/console-daemon.mjs +70 -0
- package/lib/console-ui.mjs +157 -0
- package/lib/console.html +3 -0
- package/lib/instructions.mjs +7 -4
- package/lib/prompt-cases.mjs +8 -6
- package/lib/prompt-history.mjs +148 -0
- package/lib/prompt-layout.mjs +15 -0
- package/lib/prompt-manager.mjs +81 -0
- package/lib/prompt-report.mjs +74 -0
- package/lib/prompt-revisions.mjs +232 -16
- package/lib/prompt-sessions.mjs +92 -0
- package/lib/prompt-task.mjs +3 -1
- package/lib/prompt-tools.mjs +156 -37
- package/lib/prompt-tui.mjs +111 -0
- package/lib/prompt-ui.mjs +269 -0
- package/lib/prompt-web.mjs +136 -0
- package/lib/prompt.css +10 -0
- package/lib/prompt.html +22 -0
- package/lib/web-ui-flag.mjs +5 -0
- 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-goal/package.json +1 -1
- package/node_modules/pi-better-goal/src/workflow-gates.ts +24 -0
- package/node_modules/pi-better-subagents/catalog-runtime.ts +13 -1
- package/node_modules/pi-better-subagents/index.ts +11 -0
- package/node_modules/pi-better-subagents/package.json +1 -1
- 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 +5 -2
- package/package.json +6 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.61.1] - 2026-11-29
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- Reopening a completed Goal restores the workflow plan bound after its most recent handback and resume. Bundles Goal 0.18.2.
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Carry the workflow's acceptance criteria into worker assignments.
|
|
12
|
+
|
|
13
|
+
## [0.61.0] - 2026-11-29
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- Manage prompt revisions from the Pi Prompt manager. For local testing, run `PI_HARNESS_WEB_UI=1 pi-better-harness web` to inspect the daemon, view sessions and try prompt experiments in the browser. Web commands, browser actions and session sharing are disabled by default.
|
|
18
|
+
|
|
3
19
|
## [0.60.0] - 2026-11-28
|
|
4
20
|
|
|
5
21
|
### Changed
|
package/README.md
CHANGED
|
@@ -335,14 +335,57 @@ precedence over automatic discovery.
|
|
|
335
335
|
|
|
336
336
|
### Try a prompt edit
|
|
337
337
|
|
|
338
|
+
The Web UI is off by default. Run `PI_HARNESS_WEB_UI=1 pi-better-harness web`
|
|
339
|
+
to inspect the local server, sessions and inventories. To open **Prompts → Edit**
|
|
340
|
+
directly, run `PI_HARNESS_WEB_UI=1 pi-better-harness instructions web`.
|
|
341
|
+
To use the browser actions from Pi, start `PI_HARNESS_WEB_UI=1 pi` and
|
|
342
|
+
choose **Open in browser** in `/harness-settings → Prompt manager`. All use
|
|
343
|
+
the current Pi agent directory (`PI_CODING_AGENT_DIR`). The CLI prints a
|
|
344
|
+
private loopback URL and opens the browser. Set `BROWSER=none` to print
|
|
345
|
+
the URL only. Stop the CLI to close the server.
|
|
346
|
+
|
|
347
|
+
Each bundled module retains its package original and position. Edit its local
|
|
348
|
+
override, toggle inclusion, or use **Reset to original**. Turning a slot off
|
|
349
|
+
retains its override for the next time it is enabled.
|
|
350
|
+
User modules have separate names, text and order, including when a user module
|
|
351
|
+
shares a name with a bundled module. Enabled bundled modules render first.
|
|
352
|
+
Package updates retain the toggles and user text. Historical snapshots keep
|
|
353
|
+
their original rendering. The manager shows the scope of matching upstream
|
|
354
|
+
validation or says when evidence is missing.
|
|
355
|
+
|
|
356
|
+
Select a revision, edit the local composition and save a candidate. Review
|
|
357
|
+
the parent and active diffs before publishing. Manual publication and
|
|
358
|
+
rollback appear in activation history. Reload Pi to load the installed
|
|
359
|
+
revision. Off, saved-text and custom-file configurations retain their source.
|
|
360
|
+
|
|
361
|
+
To evaluate a complete session, run `/prompt-task-capture <manifest.json>`
|
|
362
|
+
before the task. The manifest specifies the number of user turns, required
|
|
363
|
+
workspace files and expected final file contents. In **Replay → Evaluate
|
|
364
|
+
sessions**, review the recommended tasks from connected sessions and their
|
|
365
|
+
expectation sources. Each arm restores the starting Git checkout and working
|
|
366
|
+
files. A later user turn runs when the preceding reply matches the historical
|
|
367
|
+
one, or when the reviewed manifest explicitly lists that turn in
|
|
368
|
+
`independentTurns`. The report includes each file check and the reason for
|
|
369
|
+
any unscored session.
|
|
370
|
+
|
|
371
|
+
To compare a candidate on one response, capture it with `/prompt-capture` or load
|
|
372
|
+
a reviewed suite with `/prompt-import`. The TUI can use its current session
|
|
373
|
+
directly. For the browser, choose **Connect browser** in the TUI and select
|
|
374
|
+
the named Pi session on the page. The connection lasts until disconnect,
|
|
375
|
+
reload or session shutdown. Select a captured request or a suite and model
|
|
376
|
+
in **Replay** and choose the two saved revisions. Results and judgments stay in the agent directory and
|
|
377
|
+
can be reopened from either interface. Promotion requires a reviewed result
|
|
378
|
+
for the displayed baseline and candidate.
|
|
379
|
+
|
|
338
380
|
Enable the modular instructions and reload Pi. For existing overrides, remove
|
|
339
381
|
`instructionsPrompt` and `instructionsFile` from the global Harness settings
|
|
340
382
|
before syncing. Use a streaming `openai-completions` model for response replay.
|
|
341
383
|
|
|
342
384
|
1. Run `/prompt-capture`, then send the writing request you want to evaluate,
|
|
343
385
|
for example "Unit checks passed and deployment verification is pending. Can we close delivery?"
|
|
344
|
-
2. Ask the agent to list modules, read `verification`, and use
|
|
345
|
-
create a
|
|
386
|
+
2. Ask the agent to list modules, read `bundled:verification`, and use
|
|
387
|
+
`prompt_edit` to create a `user:verification` module requiring the pending
|
|
388
|
+
check in the first sentence. To replace a bundled rule, turn it off in the manager.
|
|
346
389
|
3. Ask it to run `prompt_replay` with the case and candidate IDs, inspect
|
|
347
390
|
both new responses, and use `prompt_compare` to record the rubric and judgment.
|
|
348
391
|
4. Request `prompt_promote` for those revisions and the evaluation ID. Confirm
|
|
@@ -403,7 +446,7 @@ An empty import argument restores the bundled cases.
|
|
|
403
446
|
To use evaluated cases for an edit, enable `/prompt-learning on`. Ask the
|
|
404
447
|
agent to select two distinct baseline failures with the same failure category
|
|
405
448
|
and one passing counterexample. With `prompt_propose`, it supplies those IDs
|
|
406
|
-
and a
|
|
449
|
+
and a user module edit. Inspect the before/after samples, then use
|
|
407
450
|
`prompt_judge_proposal` and `prompt_promote` or clear the pending proposal
|
|
408
451
|
with `/prompt-learning discard`. Learning is disabled in a fresh session.
|
|
409
452
|
|
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
# Default module cases
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
|
6
|
-
|
|
|
7
|
-
|
|
|
8
|
-
|
|
|
9
|
-
| engineering |
|
|
10
|
-
|
|
|
3
|
+
The 2026-11-27 *Prompt Engineering gap analysis* examined historical delivery decisions, prompt assembly, writing and engineering guidance. This batch imports the cross-project behaviors into the six existing slots. The table gives an example that should trigger each rule and a control that should produce a different action. Only the Markdown in `modules/` is rendered into the global prompt.
|
|
4
|
+
|
|
5
|
+
| Module | Source in the gap analysis | Positive case | Control |
|
|
6
|
+
| --- | --- | --- | --- |
|
|
7
|
+
| collaboration | §§1–2, Developer / resolve-issues ownership and the Dynamic Workflow handoff that omitted a separately stored acceptance criterion. The brief comparison demonstrated the omission in assembled text. | A worker implements a profile page. Pass it the agreed expired-session behavior or its exact reference. Give the reviewer the same criterion. | A read-only investigation gives its findings to the owner. A handoff cannot grant permission to push a branch. Follow the repo's specific handoff format when present. |
|
|
8
|
+
| communication | §4, plain-language evaluation case 100 in English and Chinese. The established distinction is whether a qualification changes the reader's decision. | Asked whether one local replay passed, answer with its observed result. | Asked whether delivery can close, disclose the outstanding agreed check and the decision it affects. |
|
|
9
|
+
| engineering | §3, the engineering and resolve-issues implementation guides. The validated-value and retryable-operation pair covers both unnecessary support code and real invariants. | A display-label edit uses the typed value returned by the existing parser. Handle the supported inputs. | A charge request can time out after the upstream system accepts it. Retain the same idempotency key across its retry. |
|
|
10
|
+
| verification | §§4–5, the readiness pair and the Wave 1 handoff replay that recovered the original user action and expected result. One comparison per scenario supports retaining the case, not a reliability estimate. | A handoff says a workflow passed. Trace it to the original request: the user signs in and reads an authorized record. Check that behavior in the target environment. | A database write is outside that read-only requirement. Keep valid evidence for the environment it covered and target the missing check. |
|
|
11
|
+
| ownership | §5, user correction and evidence reuse, together with the existing Harness Outcome lifecycle. The gap analysis proposed a longer fresh/resumed-session comparison. | The user corrects the target client midway. Resume the authorized task with the outstanding check on that client. | If a necessary device is unavailable, record the missing observation and how to resume. For a request limited to a status report, answer the question. |
|
|
12
|
+
| decisions | §3, better-review findings grounded in a supported failure or an unmet binding requirement. Existing review guidance allows zero blockers. | A retry can duplicate an accepted charge. Identify the triggering sequence and the caller guarantee it breaks. | When a hypothetical input is outside the supported contract and no requirement covers it, it cannot justify blocking the change. |
|
|
13
|
+
|
|
14
|
+
## Replay and evaluation
|
|
15
|
+
|
|
16
|
+
For a first fork replay, prefer an authorized session just before the user asks about one test result or whether the task is ready. Compare the same turn under the previous and proposed bundles. The report should answer the decision asked and retain any material limit. Repeat with the contrasting question. The existing deterministic writing fixture can check capture and result plumbing. It cannot establish the wording's effect on a live model.
|
|
17
|
+
|
|
18
|
+
For full-session evaluation, prefer a complete handoff with a documented user action and end state, then a complete task involving a supported retry. Fix the expected read-only outcome or single financial effect before either arm runs. Score the actual result, the acceptance check performed and any extra gate the agent introduced. Unknown expectations or missing starting state need to be supplied before a session can be scored.
|
|
19
|
+
|
|
20
|
+
The role that owns a branch push and the fields transferred by a workflow belong to the role and dispatcher. Keep those fixes in their owning components. The phrase “passed” in a historical record applies to the run and scope it identifies. It grants no validation to this new bundle digest.
|
|
21
|
+
|
|
22
|
+
[Initial seed and cases](https://github.com/1aboveio/pi-better-harness/issues/947) · [Prompt ownership and replay](../../../../docs/adr/0033-modular-prompts-and-replay.md) · [Goal and Todo lifecycle](../../../../docs/adr/0030-goal-and-todo-lifecycle.md) · [Replay fixtures](../../test/prompt-experiments.test.mjs)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Follow the current project's instructions
|
|
1
|
+
Follow the current project's more specific instructions. When handing work to someone else, pass on the applicable acceptance criteria or their exact source. Identify which actions the recipient owns and which still belong to another person or role.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
Lead with the answer to the question the user is deciding. For a question about one run, give that run's result. Include a limitation when it changes the user's understanding or next action. Leave out disclaimers that only answer an imagined objection.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Preserve
|
|
1
|
+
Preserve the behavior callers rely on. When an issue would block delivery, identify the unmet requirement or a supported input and the failure it produces. When the evidence supports no blocking finding, say so.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Reuse
|
|
1
|
+
Reuse the boundary that already validates an input or handles a retry. Add a guard, fallback or compatibility path when a supported input, explicit requirement or demonstrated failure calls for it. Preserve existing guarantees for money movement, tenant isolation, data integrity and cleanup.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
When asked to finish delivery, carry the
|
|
1
|
+
When asked to finish delivery, carry the next authorized step through to an observable result. After a correction, update the task and resume from the remaining acceptance check. If progress is blocked, name the missing input or decision and what would let the work continue.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
When reporting
|
|
1
|
+
Derive acceptance from the requested user action and expected outcome. If a handoff omits them, recover them from the original request or its acceptance check. Reuse evidence for the behavior and environment it covered. When reporting readiness, distinguish what passed, what is running and what still needs verification.
|
|
@@ -24,7 +24,7 @@ const groups = [
|
|
|
24
24
|
{ title: "Background work", ids: ["setting:tool-call-guard", "setting:background-review-interval", CALLBACK_SETTING_ID] },
|
|
25
25
|
{ title: "Work display", ids: ["setting:navigator-view", "setting:navigator-sticky", "setting:outcome-todo-display", "setting:tool-output", "setting:tool-animation"] },
|
|
26
26
|
{ title: "Supervision", ids: ["setting:supervisor-mode", "supervisor:scenarios"] },
|
|
27
|
-
{ title: "Recaps & instructions", ids: ["setting:session-recap", "link:recap-prompt", "instructions:toggle", "instructions:edit", "setting:native-compaction"] },
|
|
27
|
+
{ title: "Recaps & instructions", ids: ["setting:session-recap", "link:recap-prompt", "instructions:toggle", "link:prompt-manager", "instructions:edit", "setting:native-compaction"] },
|
|
28
28
|
];
|
|
29
29
|
|
|
30
30
|
function groupSettings(items: MenuItem[]): MenuSection[] {
|
|
@@ -154,8 +154,13 @@ export function registerDynamicWorkflow(pi: ExtensionAPI, owner: (ctx: Extension
|
|
|
154
154
|
needs.add(reviewer.review.revision);
|
|
155
155
|
}
|
|
156
156
|
const prior = current.history.filter(h => needs.has(h.step)).map(h => h.step + ": " + h.result);
|
|
157
|
+
const callerPrompt = typeof input.prompt === "string" ? input.prompt : "";
|
|
158
|
+
const criteria = current.criteria.filter(criterion => !callerPrompt.includes(criterion));
|
|
157
159
|
const prompt = [input.prompt, "Objective: " + current.objective, "Assignment: " + s.title,
|
|
158
|
-
"Required output: " + s.output,
|
|
160
|
+
"Required output: " + s.output,
|
|
161
|
+
...(criteria.length ? ["Workflow acceptance criteria (overall objective; apply within this assignment):",
|
|
162
|
+
...criteria.map(criterion => "- " + criterion)] : []),
|
|
163
|
+
...prior].join("\n");
|
|
159
164
|
request.admission = { prompt, settled(receipt) {
|
|
160
165
|
// Re-read the selected branch after asynchronous admission. A fork or a
|
|
161
166
|
// simultaneous independent launch may have changed the latest snapshot.
|
package/lib/cli.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { configureHarnessResources, defaultAgentDir, preflightHarnessInstall } from "./install-settings.mjs";
|
|
6
6
|
import { activeRevision } from "./prompt-revisions.mjs";
|
|
7
7
|
import { manageInstructions } from "./instructions.mjs";
|
|
8
|
+
import { webUiDisabledMessage, webUiEnabled } from "./web-ui-flag.mjs";
|
|
8
9
|
|
|
9
10
|
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
10
11
|
const { version } = JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8"));
|
|
@@ -21,8 +22,10 @@ export const componentPackages = [
|
|
|
21
22
|
"pi-better-goal",
|
|
22
23
|
];
|
|
23
24
|
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
function usage() {
|
|
26
|
+
const web = webUiEnabled();
|
|
27
|
+
return `Usage: pi-better-harness <install|uninstall> [--local]
|
|
28
|
+
pi-better-harness instructions <preview|enable|sync|disable${web ? "|web" : ""}>${web ? "\n pi-better-harness web" : ""}
|
|
26
29
|
|
|
27
30
|
Commands:
|
|
28
31
|
instructions Manage the Harness block in the global APPEND_SYSTEM.md
|
|
@@ -33,6 +36,7 @@ Options:
|
|
|
33
36
|
-l, --local Use project-local Pi settings
|
|
34
37
|
-h, --help Show this help
|
|
35
38
|
-v, --version Show the package version`;
|
|
39
|
+
}
|
|
36
40
|
|
|
37
41
|
function scopeArgs(local) {
|
|
38
42
|
return local ? ["--local"] : [];
|
|
@@ -48,7 +52,7 @@ export function run(argv, options = {}) {
|
|
|
48
52
|
const stderr = options.stderr ?? process.stderr;
|
|
49
53
|
|
|
50
54
|
if (argv.includes("--help") || argv.includes("-h")) {
|
|
51
|
-
stdout.write(`${usage}\n`);
|
|
55
|
+
stdout.write(`${usage()}\n`);
|
|
52
56
|
return 0;
|
|
53
57
|
}
|
|
54
58
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
@@ -59,6 +63,16 @@ export function run(argv, options = {}) {
|
|
|
59
63
|
const local = argv.includes("--local") || argv.includes("-l");
|
|
60
64
|
const positional = argv.filter((arg) => !["--local", "-l"].includes(arg));
|
|
61
65
|
const command = positional[0];
|
|
66
|
+
const serverPage = command === "web" && positional.length === 1;
|
|
67
|
+
const promptPage = command === "instructions" && positional.length === 2 && positional[1] === "web";
|
|
68
|
+
if (!local && (serverPage || promptPage)) {
|
|
69
|
+
if (!webUiEnabled()) {
|
|
70
|
+
stderr.write(webUiDisabledMessage + "\n");
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
return import("./prompt-web.mjs").then(m => m.launchPromptWeb(
|
|
74
|
+
options.agentDir ?? defaultAgentDir(), stdout, serverPage ? "/server" : "/prompts/edit"));
|
|
75
|
+
}
|
|
62
76
|
if (command === "instructions" && !local && positional.length === 2 && ["preview", "enable", "sync", "disable"].includes(positional[1])) {
|
|
63
77
|
try {
|
|
64
78
|
if (positional[1] === "preview") {
|
|
@@ -74,7 +88,7 @@ export function run(argv, options = {}) {
|
|
|
74
88
|
}
|
|
75
89
|
}
|
|
76
90
|
if (!command || positional.length !== 1 || !["install", "uninstall"].includes(command)) {
|
|
77
|
-
stderr.write(`${usage}\n`);
|
|
91
|
+
stderr.write(`${usage()}\n`);
|
|
78
92
|
return 2;
|
|
79
93
|
}
|
|
80
94
|
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { register } from "tsx/esm/api";
|
|
7
|
+
|
|
8
|
+
let registered = false;
|
|
9
|
+
|
|
10
|
+
async function serverModule(dir, file) {
|
|
11
|
+
let root;
|
|
12
|
+
for (const from of [import.meta.url, join(resolve(dir),"npm","package.json")]) {
|
|
13
|
+
try { root = dirname(createRequire(from).resolve("pi-better-server/package.json")); }
|
|
14
|
+
catch (error) { if (error.code !== "MODULE_NOT_FOUND") throw error; continue; }
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
if (!root) {
|
|
18
|
+
let launcher = process.env.PI_SERVER_COMMAND || process.env.PI_SERVER_LAUNCHER;
|
|
19
|
+
if (!launcher) {
|
|
20
|
+
try { launcher = JSON.parse(readFileSync(join(homedir(),".pi","remote-server.json"),"utf8")).launcher; }
|
|
21
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
22
|
+
}
|
|
23
|
+
if (!launcher) throw Error("The pi-better-server installation is unavailable.");
|
|
24
|
+
root = join(dirname(dirname(realpathSync(launcher))),"server");
|
|
25
|
+
if (JSON.parse(readFileSync(join(root,"package.json"),"utf8")).name !== "pi-better-server") throw Error("Invalid server installation.");
|
|
26
|
+
}
|
|
27
|
+
if (!registered) { register(); registered = true; }
|
|
28
|
+
return import(pathToFileURL(join(root,"src",file)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function consoleDaemon(dir,args) {
|
|
32
|
+
let serverDir = process.env.PI_SERVER_DIR || join(dir,"server");
|
|
33
|
+
try {
|
|
34
|
+
const registration = JSON.parse(readFileSync(join(dir,"server-registration-v1.json"),"utf8"));
|
|
35
|
+
if (registration.version !== 1 || registration.agentDir !== realpathSync(dir) || registration.serverDir !== realpathSync(registration.serverDir))
|
|
36
|
+
throw Error("Invalid daemon registration.");
|
|
37
|
+
serverDir = registration.serverDir;
|
|
38
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
39
|
+
const {DaemonClient} = await serverModule(dir,"client.ts");
|
|
40
|
+
const {socketPathFor} = await serverModule(dir,"runtime/socket.ts");
|
|
41
|
+
if (args.action === "console_start") {
|
|
42
|
+
const {ensureDaemon} = await serverModule(dir,"startup/ensure.ts");
|
|
43
|
+
await ensureDaemon({agentDir:dir,serverDir});
|
|
44
|
+
}
|
|
45
|
+
let client;
|
|
46
|
+
try {
|
|
47
|
+
let root;
|
|
48
|
+
try { root = realpathSync(dir); } catch (error) { if (error.code !== "ENOENT") throw error; root = resolve(dir); }
|
|
49
|
+
client = await DaemonClient.connect(socketPathFor(serverDir),{signal:AbortSignal.timeout(2500),hello:{runtimeRoot:root}});
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (args.action !== "console_status") throw error;
|
|
52
|
+
if (["ENOENT","ECONNREFUSED"].includes(error.code)) {
|
|
53
|
+
const {inspectDaemonOwner} = await serverModule(dir,"daemon-owner.ts");
|
|
54
|
+
const owner = inspectDaemonOwner(serverDir);
|
|
55
|
+
if (["missing","dead"].includes(owner.status)) return {status:"Stopped",dir,serverDir,observedAt:new Date().toISOString()};
|
|
56
|
+
}
|
|
57
|
+
return {status:error.name === "HandshakeError" ? "Incompatible" : "Unreachable",reason:error.message,dir,serverDir,observedAt:new Date().toISOString()};
|
|
58
|
+
}
|
|
59
|
+
const observedAt = new Date().toISOString();
|
|
60
|
+
const timer = setTimeout(() => client.close(),5000);
|
|
61
|
+
const call = async (type,fields) => (await client.call({type,...fields})).data;
|
|
62
|
+
try {
|
|
63
|
+
if (args.action === "console_frame") return await call("console_frame",{sessionId:args.sessionId});
|
|
64
|
+
if (args.action === "console_inventory") return await call("console_inventory",{sessionId:args.sessionId,inventory:args.inventory});
|
|
65
|
+
const {sessions} = await call("list_sessions");
|
|
66
|
+
let upgrade,upgradeError;
|
|
67
|
+
try { upgrade = await call("runtime_upgrade_status"); } catch (error) { upgradeError = error.message; }
|
|
68
|
+
return {dir,serverDir,status:"Running",observedAt,hello:client.server,sessions,upgrade,upgradeError};
|
|
69
|
+
} finally { clearTimeout(timer); client.close(); }
|
|
70
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
const el = id => document.getElementById(id);
|
|
2
|
+
const token = location.hash.slice(1) || sessionStorage.getItem("prompt-token");
|
|
3
|
+
if (token) sessionStorage.setItem("prompt-token",token);
|
|
4
|
+
history.replaceState(null,"",location.pathname + location.search);
|
|
5
|
+
const [,page,sessionId] = location.pathname.split("/");
|
|
6
|
+
const current = document.querySelector('header a[href="/' + page + '"]');
|
|
7
|
+
current?.setAttribute("aria-current","page");
|
|
8
|
+
el("title").textContent = sessionId ? "Session TUI" : current?.textContent;
|
|
9
|
+
function node(tag,text) {
|
|
10
|
+
const n = document.createElement(tag);
|
|
11
|
+
if (text !== undefined) n.textContent = text;
|
|
12
|
+
return n;
|
|
13
|
+
}
|
|
14
|
+
async function api(action,args = {}) {
|
|
15
|
+
const res = await fetch("/api",{method:"POST",headers:{authorization:"Bearer " + token,"content-type":"application/json"},body:JSON.stringify({action,...args})});
|
|
16
|
+
if (res.status === 403) throw Error("Open the private URL printed by the launcher.");
|
|
17
|
+
const data = await res.json();
|
|
18
|
+
if (!res.ok) throw Error(data.error);
|
|
19
|
+
return data.result;
|
|
20
|
+
}
|
|
21
|
+
function report(error) { el("notice").textContent = error.message; }
|
|
22
|
+
function button(text,fn) { const b = node("button",text); b.onclick = () => Promise.resolve().then(fn).catch(report); return b; }
|
|
23
|
+
function link(label,url) { const a = node("a",label); a.href = url; return a; }
|
|
24
|
+
function field(name,control) { const label = node("label",name); label.append(control); return label; }
|
|
25
|
+
function select(items) { const s = node("select"); s.append(...items.map(([id,label])=>new Option(label,id))); return s; }
|
|
26
|
+
const controls = el("controls"), content = el("content");
|
|
27
|
+
function sessions(data) {
|
|
28
|
+
const filter = node("input"); filter.type = "checkbox";
|
|
29
|
+
filter.checked = new URLSearchParams(location.search).has("needsInput");
|
|
30
|
+
controls.append(field("Needs input ",filter));
|
|
31
|
+
const draw = () => {
|
|
32
|
+
content.replaceChildren();
|
|
33
|
+
const rows = data.sessions.filter(row => !filter.checked || row.needsInput.length);
|
|
34
|
+
for (const [cwd,group] of Object.entries(Object.groupBy(rows,r=>r.cwd))) {
|
|
35
|
+
content.append(node("h2",cwd));
|
|
36
|
+
for (const row of group) {
|
|
37
|
+
const anchor = link(row.name || row.sessionId,"/sessions/"+encodeURIComponent(row.sessionId));
|
|
38
|
+
anchor.id = "session-" + row.sessionId;
|
|
39
|
+
anchor.onclick = () => sessionStorage.setItem("console-back",JSON.stringify({path:location.pathname+location.search,id:anchor.id}));
|
|
40
|
+
const p = node("p"); p.append(anchor," · ",row.needsInput.length ? "Needs input" : row.status); content.append(p);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (!rows.length) content.append(node("p","No matching sessions."));
|
|
44
|
+
};
|
|
45
|
+
filter.onchange = () => { history.replaceState(null,"",location.pathname+(filter.checked ? "?needsInput" : "")); draw(); };
|
|
46
|
+
draw();
|
|
47
|
+
const back = JSON.parse(sessionStorage.getItem("console-back") || "null");
|
|
48
|
+
if (back?.path === location.pathname+location.search) el(back.id)?.focus();
|
|
49
|
+
}
|
|
50
|
+
function detail() {
|
|
51
|
+
const back = JSON.parse(sessionStorage.getItem("console-back") || "null");
|
|
52
|
+
controls.append(link("Back to sessions",back?.path || "/sessions"));
|
|
53
|
+
const screen = node("pre"), meta = node("pre"); screen.className = "terminal";
|
|
54
|
+
content.append(screen,meta);
|
|
55
|
+
let generation = 0, timer, previous;
|
|
56
|
+
const read = async () => {
|
|
57
|
+
const request = generation;
|
|
58
|
+
try {
|
|
59
|
+
const frame = await api("console_frame",{sessionId});
|
|
60
|
+
if (request !== generation) return;
|
|
61
|
+
const encoded = JSON.stringify(frame);
|
|
62
|
+
if (encoded !== previous) {
|
|
63
|
+
el("notice").textContent = frame.kind === "companion" ? "Companion terminal · Read only" : "Hosted session · Passive TUI";
|
|
64
|
+
if (frame.cursor) {
|
|
65
|
+
const lines = frame.screen.split("\n"), y = frame.cursor.y, x = frame.cursor.x;
|
|
66
|
+
const line = Array.from(lines[y] ?? "");
|
|
67
|
+
const cursor = node("mark",line[x] ?? " ");
|
|
68
|
+
screen.replaceChildren(lines.slice(0,y).map(l=>l+"\n").join("")+line.slice(0,x).join(""),cursor,line.slice(x+1).join("")+"\n"+lines.slice(y+1).join("\n"));
|
|
69
|
+
} else screen.textContent = frame.screen;
|
|
70
|
+
meta.textContent = [frame.name,frame.sessionId,frame.cwd,frame.branch,frame.leaf,...frame.questions.map(q=>JSON.stringify(q))].filter(Boolean).join("\n");
|
|
71
|
+
previous = encoded;
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (request !== generation) return;
|
|
75
|
+
previous = undefined; screen.textContent = ""; meta.textContent = ""; report(error);
|
|
76
|
+
}
|
|
77
|
+
timer = setTimeout(read,750);
|
|
78
|
+
};
|
|
79
|
+
addEventListener("pagehide",()=>{ generation++; clearTimeout(timer); });
|
|
80
|
+
addEventListener("pageshow",e=>{ if(e.persisted) read(); });
|
|
81
|
+
read();
|
|
82
|
+
}
|
|
83
|
+
async function inventory(data) {
|
|
84
|
+
const catalog = page === "catalog";
|
|
85
|
+
const choices = catalog ? (await api("state")).connections.map(r=>[r.id,r.name]) : data.sessions.filter(r=>r.live).map(r=>[r.sessionId,r.name || r.sessionId]);
|
|
86
|
+
const scope = select([["","Select session"],...choices]), query = node("input");
|
|
87
|
+
query.type = "search"; controls.append(field("Session",scope),field("Search",query));
|
|
88
|
+
const format = select([["Tree","Tree"],["Flat","Flat"]]), status = select([["","All"],["Active","Active"],["Registered","Registered"]]);
|
|
89
|
+
format.id = "tools-view";
|
|
90
|
+
if (page === "tools") controls.append(field("View",format),field("Status",status));
|
|
91
|
+
const access = select([["project","Host context"],["personal","Personal only"]]);
|
|
92
|
+
if (catalog) controls.append(field("Scope",access));
|
|
93
|
+
let rows = [], selected, generation = 0;
|
|
94
|
+
const draw = () => {
|
|
95
|
+
content.replaceChildren();
|
|
96
|
+
const list = rows.filter(r=>(!status.value || r.status === status.value) && [r.name,r.description,r.source].join(" ").toLowerCase().includes(query.value.toLowerCase()));
|
|
97
|
+
const info = node("pre");
|
|
98
|
+
const pick = row => { selected = row; info.textContent = JSON.stringify(row,null,2); };
|
|
99
|
+
if (list.includes(selected)) pick(selected);
|
|
100
|
+
if (page === "tools" && format.value === "Flat") {
|
|
101
|
+
const table = node("table"), head = node("tr"); head.append(...["Tool","Source","Session status","Description"].map(s=>node("th",s))); table.append(head);
|
|
102
|
+
for (const row of list) { const tr = node("tr"), name = node("td"); name.append(button(row.name,()=>pick(row))); tr.append(name,...[row.source,row.status,row.description].map(s=>node("td",s))); table.append(tr); }
|
|
103
|
+
content.append(table);
|
|
104
|
+
} else for (const [source,items] of Object.entries(Object.groupBy(list,r=>r.source || "Unknown source"))) {
|
|
105
|
+
const group = node("details"); group.open = true; group.append(node("summary",source));
|
|
106
|
+
for (const row of items) group.append(button(row.name,()=>pick(row))); content.append(group);
|
|
107
|
+
}
|
|
108
|
+
if (!list.length && scope.value && !el("notice").textContent) content.append(node("p","No matching entries."));
|
|
109
|
+
content.append(info);
|
|
110
|
+
};
|
|
111
|
+
const load = async () => {
|
|
112
|
+
const request = ++generation;
|
|
113
|
+
rows = []; selected = null; content.replaceChildren(); el("notice").textContent = "";
|
|
114
|
+
if (!scope.value) return;
|
|
115
|
+
try {
|
|
116
|
+
const next = catalog ? await api("catalog_read",{session:scope.value,personal:access.value==="personal"}) :
|
|
117
|
+
await api("console_inventory",{sessionId:scope.value,inventory:page});
|
|
118
|
+
if (request !== generation) return;
|
|
119
|
+
rows = next.map(row=>({...row,source:row.source === "builtin" ? "Built-in" : row.source || "Unknown source"})); draw();
|
|
120
|
+
} catch (error) { if (request === generation) report(error); }
|
|
121
|
+
};
|
|
122
|
+
scope.onchange = access.onchange = load;
|
|
123
|
+
query.oninput = format.onchange = status.onchange = draw;
|
|
124
|
+
if (choices.length) { scope.value = choices[0][0]; await load(); }
|
|
125
|
+
else el("notice").textContent = catalog ? "Connect a Pi session with a catalog host." : "No live session available.";
|
|
126
|
+
}
|
|
127
|
+
async function overview(action = "console_status") {
|
|
128
|
+
controls.replaceChildren(); content.replaceChildren(); el("notice").textContent = "";
|
|
129
|
+
if (sessionId) return detail();
|
|
130
|
+
controls.append(button("Refresh",()=>overview()));
|
|
131
|
+
if (page === "catalog") return inventory();
|
|
132
|
+
const data = await api(action);
|
|
133
|
+
if (page === "server") {
|
|
134
|
+
const hello = data.hello;
|
|
135
|
+
controls.append(node("h2",data.status),node("p",data.dir),node("p","Observed "+data.observedAt));
|
|
136
|
+
if (hello) sessionStorage.setItem("console-last-handshake",JSON.stringify({at:data.observedAt,instance:hello.instanceId}));
|
|
137
|
+
else {
|
|
138
|
+
const last = JSON.parse(sessionStorage.getItem("console-last-handshake") || "null");
|
|
139
|
+
if (last) controls.append(node("p","Last successful handshake (stale): "+last.instance+" · "+last.at));
|
|
140
|
+
}
|
|
141
|
+
if (hello) controls.append(node("pre",JSON.stringify({instance:hello.instanceId,build:hello.build ?? "Unavailable",piSDK:hello.piVersion,protocol:hello.protocolVersion},null,2)),
|
|
142
|
+
node("p",data.upgradeError ? "Upgrade status unavailable · "+data.upgradeError : data.upgrade ? "Upgrade · "+data.upgrade.phase : "No recorded upgrade"));
|
|
143
|
+
if (data.upgrade) {
|
|
144
|
+
if (data.upgrade.reason) controls.append(node("p",data.upgrade.reason));
|
|
145
|
+
for (const blocker of data.upgrade.blockers ?? []) {
|
|
146
|
+
const p = node("p",JSON.stringify(blocker));
|
|
147
|
+
const row = data.sessions.find(r=>r.sessionId === blocker.sessionId || r.sessionId === blocker.id);
|
|
148
|
+
if (row) p.append(" ",link(row.name || row.sessionId,"/sessions/"+encodeURIComponent(row.sessionId)));
|
|
149
|
+
controls.append(p);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (data.status === "Stopped") controls.append(button("Start server",()=>overview("console_start")));
|
|
153
|
+
}
|
|
154
|
+
if (data.status !== "Running") { el("notice").textContent = data.reason || data.status; return; }
|
|
155
|
+
if (["server","sessions"].includes(page)) sessions(data); else await inventory(data);
|
|
156
|
+
}
|
|
157
|
+
overview().catch(report);
|
package/lib/console.html
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Pi Better Harness</title><link rel="stylesheet" href="/manager.css"></head>
|
|
2
|
+
<body><header><strong>Pi Better Harness</strong><a href="/server">Server</a><a href="/sessions">Sessions</a><a href="/catalog">Agent Catalog</a><a href="/mcp">MCP</a><a href="/skills">Skills</a><a href="/tools">Tools</a><a href="/prompts/edit">Prompts</a></header>
|
|
3
|
+
<main class="console"><article><h1 id="title"></h1><p id="notice" role="status"></p><section id="controls"></section><section id="content"></section></article></main><script type="module" src="/console.js"></script></body></html>
|
package/lib/instructions.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
|
-
import { activeRevision, begin, end, readRevision, selectRevision } from "./prompt-revisions.mjs";
|
|
4
|
+
import { activeRevision, begin, end, readRevision, selectRevision, upgradeComposition } from "./prompt-revisions.mjs";
|
|
5
5
|
import { acquire, defaultAgentDir, writeDestination } from "./install-settings.mjs";
|
|
6
6
|
|
|
7
7
|
function sourceSettings(agentDir) {
|
|
@@ -10,14 +10,17 @@ function sourceSettings(agentDir) {
|
|
|
10
10
|
return settings.piBetterHarness ?? {};
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
function sourceText(agentDir, target) {
|
|
13
|
+
function sourceText(agentDir, target, upgrade) {
|
|
14
14
|
const { instructionsPrompt: prompt, instructionsFile: source } = sourceSettings(agentDir);
|
|
15
15
|
if (source === false) return null;
|
|
16
16
|
if (typeof prompt === "string") return validateInstructionsPrompt(prompt);
|
|
17
17
|
if (source !== undefined && (typeof source !== "string" || !source.trim())) {
|
|
18
18
|
throw new Error("piBetterHarness.instructionsFile must be a file path or false.");
|
|
19
19
|
}
|
|
20
|
-
if (source === undefined)
|
|
20
|
+
if (source === undefined) {
|
|
21
|
+
if (upgrade) upgradeComposition(agentDir);
|
|
22
|
+
return activeRevision(agentDir).rendered;
|
|
23
|
+
}
|
|
21
24
|
const path = resolve(agentDir, source);
|
|
22
25
|
if (resolve(path) === resolve(target) || realpathSync(path) === target) {
|
|
23
26
|
throw new Error("The instructions source must be separate from APPEND_SYSTEM.md.");
|
|
@@ -118,7 +121,7 @@ export function manageInstructions(action, agentDir = defaultAgentDir(), edit) {
|
|
|
118
121
|
edit.saveSource();
|
|
119
122
|
}
|
|
120
123
|
if (!range && action !== "enable") return false;
|
|
121
|
-
const content = action === "disable" ? null : sourceText(agentDir, target);
|
|
124
|
+
const content = action === "disable" ? null : sourceText(agentDir, target, !edit);
|
|
122
125
|
if (content === null && action === "enable") throw new Error("Set instructionsFile to a path or remove the false setting before enabling.");
|
|
123
126
|
const eol = text.match(/\r?\n/)?.[0] ?? "\n";
|
|
124
127
|
const block = content === null ? "" : [begin, content.replace(/\r?\n/g, eol), end, ""].join(eol);
|
package/lib/prompt-cases.mjs
CHANGED
|
@@ -52,20 +52,20 @@ function score(text, rubric) {
|
|
|
52
52
|
return { status: missing.length || unexpected.length ? "fail" : "pass", missing, unexpected };
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
export async function evaluateCases(cases, baseline, candidate, sampleCount, resolveModel, generate, signal) {
|
|
55
|
+
export async function evaluateCases(cases, baseline, candidate, sampleCount, resolveModel, generate, signal, checkpoint) {
|
|
56
56
|
const results = [];
|
|
57
57
|
for (const c of cases) {
|
|
58
|
-
const row = { id: c.id, failure: c.failure, rubric: c.rubric, samples: [] };
|
|
58
|
+
const row = { id: c.id, input:c.payload, level:c.level, expected: c.expected, counterexample: c.counterexample, failure: c.failure, rubric: c.rubric, samples: [] };
|
|
59
59
|
results.push(row);
|
|
60
|
-
if (c.level !== "response") { row.status = "unsupported"; continue; }
|
|
61
|
-
if (!c.payload?.messages?.some(m => m.role === "user")) { row.status = "missing_input"; continue; }
|
|
62
60
|
try {
|
|
61
|
+
if (c.level !== "response") { row.status = "unsupported"; row.error = "Requires " + c.level + " replay"; continue; }
|
|
62
|
+
if (!c.payload?.messages?.some(m => m.role === "user")) { row.status = "missing_input"; row.error = "Missing original user input"; continue; }
|
|
63
63
|
const model = resolveModel(c);
|
|
64
64
|
if (model?.api !== "openai-completions" || c.payload.stream !== true || (c.payload.n ?? 1) !== 1) {
|
|
65
|
-
row.status = "unsupported"; continue;
|
|
65
|
+
row.status = "unsupported"; row.error = "Requires a supported model and single streamed response"; continue;
|
|
66
66
|
}
|
|
67
67
|
const template = c.payload.messages.filter(m => ["developer", "system"].includes(m.role) && typeof m.content === "string" && m.content.includes(portablePrompt));
|
|
68
|
-
if (template.length !== 1 || template[0].content.split(portablePrompt).length !== 2) { row.status = "missing_input"; continue; }
|
|
68
|
+
if (template.length !== 1 || template[0].content.split(portablePrompt).length !== 2) { row.status = "missing_input"; row.error = "Missing or ambiguous managed prompt slot"; continue; }
|
|
69
69
|
const index = c.payload.messages.indexOf(template[0]);
|
|
70
70
|
const { messages, ...settings } = c.payload;
|
|
71
71
|
row.config = { ...settings, provider: model.provider, model: model.id };
|
|
@@ -80,10 +80,12 @@ export async function evaluateCases(cases, baseline, candidate, sampleCount, res
|
|
|
80
80
|
const answer = await generate(body, model);
|
|
81
81
|
sample[arm] = { text: answer.text, ...(answer.finish === "stop" && !answer.requiresTurnReplay
|
|
82
82
|
? score(answer.text, c.rubric) : { status: "inconclusive", finish: answer.finish }) };
|
|
83
|
+
checkpoint?.(results);
|
|
83
84
|
}
|
|
84
85
|
}
|
|
85
86
|
row.status = "scored";
|
|
86
87
|
} catch (error) { row.status = signal?.aborted ? "cancelled" : "error"; row.error = error.message; }
|
|
88
|
+
finally { checkpoint?.(results); }
|
|
87
89
|
}
|
|
88
90
|
return { active: baseline.id, candidate: candidate.id, sampleCount, results };
|
|
89
91
|
}
|