pi-better-harness 0.58.0 → 0.59.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +17 -9
  3. package/extensions/minimal-output/hook.ts +2 -2
  4. package/extensions/native-compaction/index.ts +123 -0
  5. package/extensions/native-compaction/provider.ts +90 -0
  6. package/extensions/provider-context.ts +6 -0
  7. package/extensions/settings/index.ts +20 -9
  8. package/extensions/settings/menu.ts +126 -0
  9. package/extensions/settings/page.ts +74 -84
  10. package/extensions/settings/supervisor.ts +33 -13
  11. package/extensions/supervisor/index.ts +4 -2
  12. package/extensions/task-context/dynamic-workflow-runtime.ts +14 -6
  13. package/extensions/task-context/index.ts +33 -13
  14. package/extensions/task-context/work-ledger-actions.ts +5 -3
  15. package/extensions/task-context/work-ledger.ts +1 -1
  16. package/lib/openai-responses.mjs +5 -0
  17. package/node_modules/pi-better-background-tasks/package.json +1 -1
  18. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  19. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  20. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  21. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  22. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  23. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  24. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  25. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  26. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +33 -13
  27. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +3 -2
  28. package/node_modules/pi-better-background-tasks/src/registry.ts +65 -5
  29. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +2 -2
  30. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +33 -13
  31. package/node_modules/pi-better-goal/package.json +1 -1
  32. package/node_modules/pi-better-goal/src/goal-state.ts +4 -0
  33. package/node_modules/pi-better-goal/src/index.ts +35 -29
  34. package/node_modules/pi-better-goal/src/task-context.ts +1 -0
  35. package/node_modules/pi-better-goal/src/types.ts +2 -0
  36. package/node_modules/pi-better-goal/src/workflow-gates.ts +31 -10
  37. package/node_modules/pi-better-goal/src/workflow.ts +18 -5
  38. package/node_modules/pi-better-subagents/child-incidents.ts +1 -1
  39. package/node_modules/pi-better-subagents/cleanup.ts +1 -1
  40. package/node_modules/pi-better-subagents/index.ts +8 -3
  41. package/node_modules/pi-better-subagents/managed-launch-client.ts +14 -16
  42. package/node_modules/pi-better-subagents/package.json +1 -1
  43. package/node_modules/pi-better-subagents/registry.ts +4 -3
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  50. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  51. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  52. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +33 -13
  53. package/node_modules/pi-better-subagents/settings-page.ts +51 -31
  54. package/node_modules/pi-better-subagents/shared-navigator.ts +2 -2
  55. package/node_modules/pi-better-subagents/shared-work-client.mjs +33 -13
  56. package/node_modules/pi-better-subagents/stop.ts +9 -0
  57. package/package.json +6 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.59.1] - 2026-11-27
4
+
5
+ ### Fixed
6
+
7
+ - Bundle the Goal workflow, interrupted subagent launch, and Windows cleanup fixes from Goal 0.18.1, Subagents 0.40.1, and Background Tasks 0.21.5.
8
+
9
+ ## [0.59.0] - 2026-11-27
10
+
11
+ ### Changed
12
+
13
+ - Browse Harness settings by function. Switches show their current value, page links show `›`, and prompt editors show **Edit…**. Narrow terminals display values below their labels.
14
+ - Use **Supervisor mode** to turn supervision on or off. **Supervisor scenarios** lets you choose scenarios even while supervision is off.
15
+
3
16
  ## [0.58.0] - 2026-11-27
4
17
 
5
18
  ### Changed
package/README.md CHANGED
@@ -214,14 +214,14 @@ pi -e ./packages/pi-better-harness/extensions/minimal-output/index.ts
214
214
 
215
215
  ## Harness Settings
216
216
 
217
- The bundled harness provides `/harness-settings`, using Pi's native settings
218
- list. Work planning comes first, followed by delegation and sandbox access,
219
- background waits and completion delivery, then display settings. It opens
220
- the settings screens of loaded Sandbox and Subagents
221
- packages without duplicating their configuration, plus the **Agent catalog** shortcut
222
- to the `/agents` catalog. `/sandbox`, `/subagents settings`, `/agents`, and
223
- `/goal settings` remain available in standalone installations.
224
- Packages without a settings screen are not listed. Pi's `/settings` is unchanged.
217
+ Open `/harness-settings` to browse settings by function. Use the up and down
218
+ keys to move between settings. Each row shows its current value, a `›` for a
219
+ page, or **Edit…** for a prompt editor. Enter or Space activates the focused
220
+ row. Escape returns from a child page to the row that opened it.
221
+
222
+ **Agents & permissions** includes the settings pages of loaded Sandbox and
223
+ Subagents packages and the **Agent catalog** shortcut. Standalone installations
224
+ also provide `/sandbox`, `/subagents settings`, `/agents`, and `/goal settings`.
225
225
 
226
226
  **Navigator layout** selects **Flat list** (the default) or **Tree**. Flatten keeps the Subagents
227
227
  and Background Tasks groups and includes tasks launched by subagents. Tree puts
@@ -271,6 +271,14 @@ prompt; in Instructions, it restores the prompt while preserving model/effort.
271
271
  A user Markdown override is archived when its prompt is reset. Saved defaults
272
272
  survive sessions and upgrades.
273
273
 
274
+ ### OpenAI native compaction
275
+
276
+ Turn on **OpenAI native compaction** under **Recaps & instructions** in `/harness-settings` to use the provider’s native compressor for manual `/compact` and automatic compaction. The switch defaults to Off and applies to future compactions. It supports GPT models on OpenAI Responses and Codex Responses routes. If the standalone endpoint is unavailable, Harness tries the Responses compaction trigger. Routes without either capability use Pi’s summary.
277
+
278
+ Pi saves the complete compacted window in the session journal alongside the boundary of the recent messages it kept. Restarting before that write leaves the previous history available for retry. After the write, Pi can reopen the session and reuse the saved window. Switching to another route restores the original Pi history for that route.
279
+
280
+ The first request with a newly compacted prefix can be cold. Later turns reuse the same prefix, including across a restart. Cache hit rate depends on the length of the reusable input and the provider. To run the metered acceptance check, set `PI_NATIVE_COMPACTION_LIVE=1` and run `node --import tsx --test --test-name-pattern 'live GPT' packages/pi-better-harness/test/native-compaction.test.mjs` from the repository root with a configured `OPENAI_API_KEY`. The check reports each turn and requires more than 95% cached input on each of three warm follow-ups.
281
+
274
282
  ### Session recap
275
283
 
276
284
  Enable **Session recap** in `/harness-settings` to add a one-line summary to the conversation transcript. The default is Off. Expand the entry with Pi’s expand-output shortcut to read the full text and any agreed next step. Saved recaps scroll with the conversation and reappear on their original branch.
@@ -333,7 +341,7 @@ pi -e ./packages/pi-better-harness/extensions/settings/index.ts
333
341
 
334
342
  ### Agent Supervisor
335
343
 
336
- 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.
344
+ In `/harness-settings`, use **Supervisor scenarios** to choose which scenarios to run. **Supervisor mode** turns that selection on or off. You can edit the selection while the mode is off. 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.
337
345
 
338
346
  | Scenario | What the owner receives |
339
347
  | --- | --- |
@@ -580,7 +580,7 @@ export function installMinimalOutputHook(prototype: ToolPrototype, getTheme?: ()
580
580
  const seenCompactions = new WeakSet<CompactionComponent>();
581
581
  if (compactionPrototype) {
582
582
  const originalRender = compactionPrototype.render;
583
- const render = function(this: CompactionComponent, width: number): string[] {
583
+ const render = function(this: CompactionComponent, width: number) {
584
584
  if (!seenCompactions.has(this)) { seenCompactions.add(this); compactions.add(new WeakRef(this)); }
585
585
  if (!current.enabled || this.expanded) return originalRender.call(this, width);
586
586
  const detail = `from ${this.message.tokensBefore.toLocaleString()} tokens`;
@@ -615,7 +615,7 @@ export function installMinimalOutputHook(prototype: ToolPrototype, getTheme?: ()
615
615
  const mouseDescriptor = Object.getOwnPropertyDescriptor(customMessagePrototype, "handleMouse");
616
616
  const messages = new Set<WeakRef<CustomMessageComponent>>();
617
617
  const seenMessages = new WeakSet<CustomMessageComponent>();
618
- const render = function(this: CustomMessageComponent, width: number): string[] {
618
+ const render = function(this: CustomMessageComponent, width: number) {
619
619
  if (!seenMessages.has(this)) { seenMessages.add(this); messages.add(new WeakRef(this)); }
620
620
  if (!current.enabled || this._expanded) return originalRender.call(this, width);
621
621
  if (width <= 0) return [];
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import {
4
+ convertToLlm, getLatestCompactionEntry, sessionEntryToContextMessages,
5
+ type CompactionEntry, type ExtensionAPI, type ExtensionContext, type SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
8
+ import { providerContext } from "../provider-context.ts";
9
+ import { compactWindow, route, supportsCompaction, type Item } from "./provider.ts";
10
+
11
+ const requireFromExtension = createRequire(import.meta.url);
12
+ type ResponsesConverter = Pick<typeof import("@earendil-works/pi-ai/api/openai-responses-shared"), "convertResponsesMessages">;
13
+
14
+ const key = "openaiNativeCompaction";
15
+ const summaryPrefix = "OpenAI compacted the earlier conversation. Checkpoint ";
16
+ const responsesProviders = new Set(["openai", "openai-codex", "opencode"]);
17
+ type Checkpoint = CompactionEntry & { details: { format: "openai-responses-v1"; route: string; output: Item[] } };
18
+
19
+ function native(entry?: SessionEntry | null): entry is Checkpoint {
20
+ return entry?.type === "compaction" && entry.fromHook === true &&
21
+ (entry.details as Partial<Checkpoint["details"]>)?.format === "openai-responses-v1";
22
+ }
23
+
24
+ // Encrypted items belong to one route. Recover the archived Pi messages for other
25
+ // models or for a subsequent ordinary Pi compaction. Keep earlier Pi summaries.
26
+ function archivedPrefix(branch: SessionEntry[], checkpoint: Checkpoint) {
27
+ const cut = branch.findIndex(entry => entry.id === checkpoint.firstKeptEntryId);
28
+ const before = branch.slice(0, branch.findIndex(entry => entry.id === checkpoint.id));
29
+ const ordinary = getLatestCompactionEntry(before.filter(entry => !native(entry)));
30
+ const start = ordinary ? branch.findIndex(entry => entry.id === ordinary.firstKeptEntryId) : 0;
31
+ return [...(ordinary ? sessionEntryToContextMessages(ordinary) : []),
32
+ ...branch.slice(Math.max(0, start), cut).filter(entry => entry.type !== "compaction").flatMap(sessionEntryToContextMessages)];
33
+ }
34
+
35
+ export const nativeCompactionSetting = {
36
+ id: "native-compaction", label: "OpenAI native compaction", values: ["Off", "On"],
37
+ description: "Use native compaction for GPT models on supported Responses endpoints. Applies to future compactions.",
38
+ get: () => readHarnessSetting(key) === true ? "On" : "Off",
39
+ change: (value: string) => { updateHarnessSetting(key, () => value === "On"); },
40
+ };
41
+
42
+ export default function registerNativeCompaction(pi: ExtensionAPI) {
43
+ const marker = randomUUID();
44
+ let replay: Checkpoint | undefined;
45
+ let portable: ReturnType<typeof archivedPrefix> | undefined;
46
+ function select(entry: CompactionEntry | null) {
47
+ replay = native(entry) ? entry : undefined;
48
+ portable = undefined;
49
+ }
50
+ const restore = (_event: unknown, ctx: ExtensionContext) => select(getLatestCompactionEntry(ctx.sessionManager.getBranch()));
51
+ pi.on("session_start", restore);
52
+ pi.on("session_tree", restore);
53
+ pi.on("session_compact", event => select(event.compactionEntry));
54
+ pi.on("session_before_compact", async (event, ctx) => {
55
+ const { preparation, branchEntries, signal } = event;
56
+ const previous = getLatestCompactionEntry(branchEntries);
57
+ const model = ctx.model;
58
+ const previousNative = native(previous) ? previous : undefined;
59
+ const restoreForPi = () => {
60
+ if (!previousNative) return;
61
+ preparation.messagesToSummarize = [...archivedPrefix(branchEntries, previousNative), ...preparation.messagesToSummarize];
62
+ preparation.previousSummary = undefined;
63
+ };
64
+ try {
65
+ if (!supportsCompaction(model) || readHarnessSetting(key) !== true) {
66
+ restoreForPi();
67
+ return;
68
+ }
69
+ let prefix: Item[] = [];
70
+ let messages = [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages];
71
+ if (previousNative && previousNative.details.route === route(model)) {
72
+ prefix = previousNative.details.output;
73
+ } else if (previous) {
74
+ const history = previousNative ? archivedPrefix(branchEntries, previousNative) : sessionEntryToContextMessages(previous);
75
+ messages = [...history, ...messages];
76
+ }
77
+ const { loadResponsesConverter } = requireFromExtension("../../lib/openai-responses.mjs") as {
78
+ loadResponsesConverter(): Promise<ResponsesConverter>;
79
+ };
80
+ const { convertResponsesMessages } = await loadResponsesConverter();
81
+ const items = convertResponsesMessages(model, providerContext({ messages: convertToLlm(messages) }), responsesProviders);
82
+ const output = await compactWindow(ctx, model, [...prefix, ...items], event.customInstructions, signal);
83
+ signal.throwIfAborted();
84
+ if (!output) {
85
+ restoreForPi();
86
+ return;
87
+ }
88
+ // Pi commits summary, cut point and output as one journal entry after the hook returns.
89
+ return { compaction: {
90
+ summary: summaryPrefix + randomUUID(), firstKeptEntryId: preparation.firstKeptEntryId,
91
+ tokensBefore: preparation.tokensBefore, details: { format: "openai-responses-v1", route: route(model), output },
92
+ } };
93
+ } catch (error) {
94
+ if (!signal.aborted) ctx.ui.notify(`Native compaction stopped: ${error instanceof Error ? error.message : String(error)}`, "warning");
95
+ return { cancel: true };
96
+ }
97
+ });
98
+
99
+ pi.on("context", (event, ctx) => {
100
+ if (!replay) return;
101
+ const index = event.messages.findIndex(message => message.role === "compactionSummary" && message.summary === replay?.summary);
102
+ if (index < 0) return;
103
+ const summary = event.messages[index];
104
+ const replacement = supportsCompaction(ctx.model) && replay.details.route === route(ctx.model)
105
+ ? [{ role: "user" as const, content: marker, timestamp: summary.timestamp }]
106
+ : (portable ??= archivedPrefix(ctx.sessionManager.getBranch(), replay));
107
+ const tail = event.messages.slice(index + 1).filter(message => message.role !== "compactionSummary");
108
+ return { messages: [...event.messages.slice(0, index), ...replacement, ...tail] };
109
+ });
110
+
111
+ pi.on("before_provider_request", (event, ctx) => {
112
+ if (!replay || !supportsCompaction(ctx.model) || replay.details.route !== route(ctx.model)) return;
113
+ const payload = event.payload as { model?: string; input?: Item[]; instructions?: string } | undefined;
114
+ if (payload?.model !== ctx.model.id || !Array.isArray(payload.input)) return;
115
+ const index = payload.input.findIndex(item => item.role === "user" && Array.isArray(item.content) &&
116
+ item.content.length === 1 && item.content[0]?.type === "input_text" && item.content[0].text === marker);
117
+ if (index < 0) return;
118
+ // Some Responses gateways insert a long, uncached instructions suffix when
119
+ // the field is absent. Pi already sends its full system prompt in input.
120
+ return { ...payload, instructions: payload.instructions ?? "Follow the instructions in the conversation.",
121
+ input: [...payload.input.slice(0, index), ...replay.details.output, ...payload.input.slice(index + 1)] };
122
+ });
123
+ }
@@ -0,0 +1,90 @@
1
+ import { createHash } from "node:crypto";
2
+ import OpenAI from "openai";
3
+ import type { Api, Model } from "@earendil-works/pi-ai";
4
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+
6
+ export type Item = Record<string, unknown>;
7
+ type StreamEvent = { type: string; response?: { status: string; output?: Item[] } };
8
+
9
+ export function supportsCompaction(model?: Model<Api>): model is Model<Api> {
10
+ return !!model && /^(?:openai\/)?gpt-/i.test(model.id) &&
11
+ (model.api === "openai-responses" || model.api === "openai-codex-responses");
12
+ }
13
+
14
+ export function route(model: Model<Api>): string {
15
+ const identity = [model.api, model.provider, model.baseUrl.replace(/\/+$/, ""), model.id];
16
+ return createHash("sha256").update(JSON.stringify(identity)).digest("hex");
17
+ }
18
+
19
+ function compactedWindow(output: unknown): Item[] | undefined {
20
+ if (Array.isArray(output) && output.every(item => item && typeof item === "object") &&
21
+ output.some(item => item.type === "compaction" && typeof item.encrypted_content === "string" && item.encrypted_content.length)) {
22
+ return output;
23
+ }
24
+ return undefined;
25
+ }
26
+
27
+ function unavailable(error: unknown) {
28
+ if (!(error instanceof OpenAI.APIError)) return false;
29
+ return [404, 405, 501].includes(error.status ?? 0) ||
30
+ ([400, 422].includes(error.status ?? 0) &&
31
+ /unsupported|not supported|(?:invalid|unknown).*compaction_trigger|context_length_exceeded/i.test(error.message));
32
+ }
33
+
34
+ export async function compactWindow(ctx: ExtensionContext, model: Model<Api>, input: object[], focus: string | undefined, signal: AbortSignal) {
35
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
36
+ if (!auth.ok) throw new Error(auth.error);
37
+ // Preserve null overrides so the OpenAI client also omits its own default headers.
38
+ const headers: Record<string, string | null> = Object.fromEntries(
39
+ [...Object.entries(model.headers ?? {}), ...Object.entries(auth.headers ?? {})]
40
+ .map(([name, value]) => [name.toLowerCase(), value]),
41
+ );
42
+ let baseURL = model.baseUrl.replace(/\/+$/, "");
43
+ const codex = model.api === "openai-codex-responses";
44
+ if (codex) {
45
+ baseURL = baseURL.replace(/\/codex(?:\/responses)?$/, "") + "/codex";
46
+ const claims = JSON.parse(Buffer.from(auth.apiKey?.split(".")[1] ?? "", "base64url").toString());
47
+ const accountId = claims["https://api.openai.com/auth"]?.chatgpt_account_id;
48
+ if (typeof accountId !== "string") throw new Error("Codex account ID unavailable");
49
+ headers["chatgpt-account-id"] = accountId;
50
+ headers.originator = "pi";
51
+ }
52
+ const sessionId = ctx.sessionManager.getSessionId();
53
+ headers[codex ? "session-id" : "session_id"] = sessionId;
54
+ // Credentials come exclusively from this Pi route, including gateways using custom headers.
55
+ if (!auth.apiKey && headers.authorization == null && headers["cf-aig-authorization"] == null) {
56
+ throw new Error("No credentials configured for the active Responses route");
57
+ }
58
+ const client = new OpenAI({ baseURL, apiKey: auth.apiKey ?? "unused", defaultHeaders: headers, maxRetries: 0 });
59
+ const instructions = [ctx.getSystemPrompt(), focus].filter(Boolean).join("\n\n");
60
+ const body = { model: model.id, input, instructions };
61
+ try {
62
+ const response = await client.post<{ output: Item[] }>("/responses/compact", { body, signal });
63
+ const output = compactedWindow(response.output);
64
+ if (!output) throw new Error("Compact endpoint returned no encrypted compaction item");
65
+ return output;
66
+ } catch (error) {
67
+ signal.throwIfAborted();
68
+ if (!unavailable(error) && !(error instanceof OpenAI.APIError && error.status === 502)) throw error;
69
+ }
70
+
71
+ // Some Responses gateways only expose the explicit trigger on their streaming endpoint.
72
+ try {
73
+ const stream = await client.post<AsyncIterable<StreamEvent>>("/responses", {
74
+ body: { ...body, input: [...input, { type: "compaction_trigger" }], store: false, stream: true, prompt_cache_key: sessionId },
75
+ stream: true, signal,
76
+ });
77
+ for await (const event of stream) {
78
+ if (event.type === "response.completed" && event.response?.status === "completed") {
79
+ // An older endpoint may ignore the trigger and generate an ordinary reply.
80
+ const output = compactedWindow(event.response.output);
81
+ if (output || event.response.output?.some(item => item.type === "message")) return output;
82
+ throw new Error("Compaction completed without a usable output window");
83
+ }
84
+ }
85
+ throw new Error("Compaction stream ended before response.completed");
86
+ } catch (error) {
87
+ signal.throwIfAborted();
88
+ if (!unavailable(error)) throw error;
89
+ }
90
+ }
@@ -0,0 +1,6 @@
1
+ import * as piAI from "@earendil-works/pi-ai";
2
+ import type { Context, Provider } from "@earendil-works/pi-ai";
3
+
4
+ // Pi 1.6 providers receive a transcript with the system prompt in its first message.
5
+ export const providerContext: (context: Context) => Parameters<Provider["streamSimple"]>[1] =
6
+ Reflect.get(piAI, "normalizeContext") ?? ((context: Context) => context);
@@ -1,7 +1,8 @@
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
+ import { openSupervisorScenarios, readSupervisorSettings, setSupervisorEnabled } from "./supervisor.ts";
5
+ import registerNativeCompaction, { nativeCompactionSetting } from "../native-compaction/index.ts";
5
6
  import { chooseHarnessSetting } from "./page.ts";
6
7
  import { createSettingsRegistry } from "./registry.ts";
7
8
  import { changeCallbackSetting, getCallbackSettings, saveCallbackDefault } from "pi-better-background-tasks/src/shared-callback-batcher.ts";
@@ -9,9 +10,19 @@ import { changeCallbackSetting, getCallbackSettings, saveCallbackDefault } from
9
10
  import { getNavigatorView, loadNavigatorView, setNavigatorView } from "pi-better-background-tasks/src/shared-navigator.ts";
10
11
 
11
12
  export default function harnessSettingsExtension(pi: ExtensionAPI): void {
13
+ registerNativeCompaction(pi);
12
14
  const registry = createSettingsRegistry(pi);
13
15
  const view = { id: "navigator-view", label: "View", values: ["tree", "flatten"],
14
16
  get: getNavigatorView, change: (value: string) => setNavigatorView(value) };
17
+ const supervisorMode = {
18
+ id: "supervisor-mode", label: "Supervisor mode", values: ["Off", "On"],
19
+ description: "Run the selected scenarios for sessions sharing this agent directory. Turning the mode off keeps your selections.",
20
+ get() {
21
+ try { return readSupervisorSettings().enabled ? "On" : "Off"; }
22
+ catch { return "Unavailable"; }
23
+ },
24
+ change(value: string) { setSupervisorEnabled(value === "On"); },
25
+ };
15
26
  pi.on("session_start", () => { try { loadNavigatorView(); } catch { /* settings command reports read errors */ } });
16
27
  pi.on("session_start", () => registry.refresh());
17
28
  pi.on("session_shutdown", () => registry.dispose());
@@ -45,21 +56,21 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
45
56
  get: readSettings,
46
57
  change: mode => changeCallbackSetting(pi, ctx, mode),
47
58
  save: () => saveCallbackDefault(readSettings().mode),
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." },
51
- { id: "instructions:toggle", label: "Harness instructions", currentValue: state, values: [state],
59
+ }, [...registry.controls(), nativeCompactionSetting, supervisorMode], view, [
60
+ { id: "supervisor:scenarios", label: "Supervisor scenarios", kind: "page",
61
+ description: "Choose which scenarios run when Supervisor mode is on." },
62
+ { id: "instructions:toggle", label: "Harness instructions", kind: "toggle", value: state,
52
63
  description: "Toggle the global APPEND_SYSTEM.md block. Applies on startup or /reload." },
53
- ...(prompt === undefined ? [] : [{ id: "instructions:edit", label: "Instructions prompt", currentValue: "Edit",
54
- values: ["Edit"], description: "Edit the Markdown included in the Harness block." }]),
64
+ ...(prompt === undefined ? [] : [{ id: "instructions:edit", label: "Instructions prompt", kind: "editor" as const,
65
+ description: "Edit the Markdown included in the Harness block." }]),
55
66
  ]);
56
67
  } catch (error) {
57
68
  ctx.ui.notify(`Settings unavailable: ${error instanceof Error ? error.message : String(error)}`, "error");
58
69
  return;
59
70
  }
60
71
  if (!selected) return;
61
- if (selected === "supervisor:open") {
62
- try { await openSupervisorSettings(ctx); }
72
+ if (selected === "supervisor:scenarios") {
73
+ try { await openSupervisorScenarios(ctx); }
63
74
  catch (error) { ctx.ui.notify(`Supervisor mode: ${error instanceof Error ? error.message : String(error)}`, "error"); }
64
75
  continue;
65
76
  }
@@ -0,0 +1,126 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ export interface MenuItem {
5
+ id: string;
6
+ label: string;
7
+ kind: "toggle" | "choice" | "page" | "editor";
8
+ value?: string;
9
+ description?: string;
10
+ }
11
+
12
+ export interface MenuSection {
13
+ title: string;
14
+ items: MenuItem[];
15
+ }
16
+
17
+ const verbs = { toggle: "toggle", choice: "change", page: "open", editor: "edit" };
18
+
19
+ export function createSettingsMenu(options: {
20
+ title: string;
21
+ sections: MenuSection[];
22
+ selected?: string;
23
+ theme: Theme;
24
+ height: () => number;
25
+ activate: (item: MenuItem) => void;
26
+ back: () => void;
27
+ }) {
28
+ const { theme } = options;
29
+ const rows = options.sections.flatMap(section => section.items.map(item => ({ section, item })));
30
+ const labelWidth = Math.max(0, ...rows.map(({ item }) => visibleWidth(item.label)));
31
+ let cursor = Math.max(0, rows.findIndex(({ item }) => item.id === options.selected));
32
+ let first = 0;
33
+ let feedback = "";
34
+
35
+ function renderItem(item: MenuItem, active: boolean, width: number): string[] {
36
+ const value = item.kind === "page" ? [item.value, "›"].filter(Boolean).join(" ")
37
+ : item.kind === "editor" ? "Edit…" : item.value ?? "";
38
+ const link = item.kind === "page" || item.kind === "editor";
39
+ const trailing = active && !link ? theme.inverse(value) : theme.fg(active ? "accent" : "muted", value);
40
+ const label = (active ? "> " : " ") + theme.fg(active ? "accent" : "text", item.label);
41
+ if (labelWidth + visibleWidth(value) + 4 <= width) {
42
+ return [label + " ".repeat(labelWidth - visibleWidth(item.label) + 2) + trailing];
43
+ }
44
+ return [truncateToWidth(label, width, "…"), truncateToWidth(" " + trailing, width, "…")];
45
+ }
46
+
47
+ return {
48
+ report(text: string, error = false) { feedback = theme.fg(error ? "error" : "text", text); },
49
+ invalidate() {},
50
+ handleInput(data: string) {
51
+ const kb = getKeybindings();
52
+ if (kb.matches(data, "tui.select.cancel")) { options.back(); return; }
53
+ const row = rows[cursor];
54
+ if (!row) return;
55
+ if (kb.matches(data, "tui.select.up")) cursor = (cursor + rows.length - 1) % rows.length;
56
+ else if (kb.matches(data, "tui.select.down")) cursor = (cursor + 1) % rows.length;
57
+ else if (kb.matches(data, "tui.select.confirm") || matchesKey(data, "space")) {
58
+ options.activate(row.item);
59
+ return;
60
+ } else return;
61
+ feedback = "";
62
+ },
63
+ render(width: number) {
64
+ const w = Math.max(1, width);
65
+ const title = theme.bold(theme.fg("text", options.title));
66
+ const row = rows[cursor];
67
+ if (!row) return [title, " No settings available"].map(line => truncateToWidth(line, w));
68
+
69
+ // Inline settings share the terminal with the conversation, work panels and Pi footer.
70
+ const height = Math.max(1, Math.floor(options.height() * 2 / 3));
71
+ const lines = rows.map(({ item }, i) => renderItem(item, i === cursor, w));
72
+ const focused = lines[cursor]!;
73
+ if (height < focused.length + 2) return focused.slice(0, height);
74
+ const indent = " ";
75
+ const wrap = (s: string) => wrapTextWithAnsi(s, Math.max(1, w - indent.length)).map(line => indent + line);
76
+ const help = row.item.description ? wrap(row.item.description) : [];
77
+ const kb = getKeybindings();
78
+ const key = (binding: "tui.select.confirm" | "tui.select.cancel") => {
79
+ const name = kb.getKeys(binding)[0] ?? "";
80
+ return name === "escape" ? "Esc" : name.length > 1 ? name.charAt(0).toUpperCase() + name.slice(1) : name;
81
+ };
82
+ const confirm = key("tui.select.confirm");
83
+ const cancel = key("tui.select.cancel");
84
+ const action = [confirm, confirm === "Space" ? "" : "Space"].filter(Boolean).join("/");
85
+ const hint = wrap([action + " to " + verbs[row.item.kind], cancel && cancel + " back"].filter(Boolean).join(" · "));
86
+ const status = feedback ? wrap(feedback) : [];
87
+ const headerGap = height >= 8 ? [""] : [];
88
+ const minBody = 1 + focused.length;
89
+ const available = height - 1 - headerGap.length;
90
+ const footRoom = Math.max(0, available - minBody - 1);
91
+ const keys = [...status, ...hint.map(line => theme.fg("dim", line))].slice(0, footRoom);
92
+ const helpRoom = Math.min(Math.floor(height / 3), footRoom - keys.length - 1);
93
+ const details = help.slice(0, Math.max(0, helpRoom));
94
+ const footer = [...details, ...(details.length ? [""] : []), ...keys];
95
+ if (footer.length) footer.unshift("");
96
+ const budget = Math.min(16, available - footer.length);
97
+
98
+ // Scroll whole rows and repeat the first visible section heading after a scroll.
99
+ let start = cursor;
100
+ let used = 1 + lines[cursor]!.length;
101
+ while (start > first) {
102
+ const cost = lines[start - 1]!.length + (rows[start - 1]!.section === rows[start]!.section ? 0 : 2);
103
+ if (used + cost > budget) break;
104
+ used += cost;
105
+ start--;
106
+ }
107
+ first = start;
108
+ const body: string[] = [];
109
+ let end = first;
110
+ for (; end < rows.length; end++) {
111
+ const { section } = rows[end]!;
112
+ const heading = end === first || rows[end - 1]!.section !== section;
113
+ const gap = heading && body.length > 0;
114
+ const cost = Number(gap) + Number(heading) + lines[end]!.length;
115
+ if (body.length && body.length + cost > budget) break;
116
+ if (gap) body.push("");
117
+ if (heading) body.push(theme.fg("muted", theme.bold(section.title)));
118
+ body.push(...lines[end]!);
119
+ }
120
+ const count = ` ${cursor + 1}/${rows.length}`;
121
+ const showCount = (first > 0 || end < rows.length) && visibleWidth(title + count) <= w;
122
+ return [title + (showCount ? theme.fg("dim", count) : ""), ...headerGap, ...body, ...footer]
123
+ .map(line => truncateToWidth(line, w, "…"));
124
+ },
125
+ };
126
+ }