pi-better-harness 0.59.0 → 0.59.2

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 (54) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +8 -0
  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 +3 -1
  8. package/extensions/settings/page.ts +1 -1
  9. package/extensions/supervisor/index.ts +4 -2
  10. package/extensions/task-context/dynamic-workflow-runtime.ts +14 -6
  11. package/extensions/task-context/index.ts +33 -13
  12. package/extensions/task-context/work-ledger-actions.ts +5 -3
  13. package/extensions/task-context/work-ledger.ts +1 -1
  14. package/lib/openai-responses.mjs +5 -0
  15. package/node_modules/pi-better-background-tasks/package.json +1 -1
  16. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  17. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  18. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  19. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  20. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  21. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  22. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  23. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  24. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +43 -14
  25. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +3 -2
  26. package/node_modules/pi-better-background-tasks/src/registry.ts +65 -5
  27. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +2 -2
  28. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +43 -14
  29. package/node_modules/pi-better-goal/package.json +1 -1
  30. package/node_modules/pi-better-goal/src/goal-state.ts +4 -0
  31. package/node_modules/pi-better-goal/src/index.ts +35 -29
  32. package/node_modules/pi-better-goal/src/task-context.ts +1 -0
  33. package/node_modules/pi-better-goal/src/types.ts +2 -0
  34. package/node_modules/pi-better-goal/src/workflow-gates.ts +31 -10
  35. package/node_modules/pi-better-goal/src/workflow.ts +18 -5
  36. package/node_modules/pi-better-subagents/child-incidents.ts +1 -1
  37. package/node_modules/pi-better-subagents/cleanup.ts +1 -1
  38. package/node_modules/pi-better-subagents/managed-launch-client.ts +14 -16
  39. package/node_modules/pi-better-subagents/package.json +3 -1
  40. package/node_modules/pi-better-subagents/registry.ts +6 -3
  41. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  49. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +43 -14
  50. package/node_modules/pi-better-subagents/shared-navigator.ts +2 -2
  51. package/node_modules/pi-better-subagents/shared-work-client.mjs +43 -14
  52. package/node_modules/pi-better-subagents/stop.ts +9 -0
  53. package/node_modules/pi-better-subagents/work-observation.ts +7 -1
  54. package/package.json +6 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.59.2] - 2026-11-28
4
+
5
+ ### Fixed
6
+
7
+ - The bundled runtime recovers when a task archive changes during snapshot verification, even if the file watcher reports only the live task record.
8
+ - The subagent task view reconnects if its initial subscription times out.
9
+
10
+ ## [0.59.1] - 2026-11-27
11
+
12
+ ### Fixed
13
+
14
+ - 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.
15
+
3
16
  ## [0.59.0] - 2026-11-27
4
17
 
5
18
  ### Changed
package/README.md CHANGED
@@ -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.
@@ -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);
@@ -2,6 +2,7 @@ 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
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,6 +10,7 @@ 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) };
@@ -54,7 +56,7 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
54
56
  get: readSettings,
55
57
  change: mode => changeCallbackSetting(pi, ctx, mode),
56
58
  save: () => saveCallbackDefault(readSettings().mode),
57
- }, [...registry.controls(), supervisorMode], view, [
59
+ }, [...registry.controls(), nativeCompactionSetting, supervisorMode], view, [
58
60
  { id: "supervisor:scenarios", label: "Supervisor scenarios", kind: "page",
59
61
  description: "Choose which scenarios run when Supervisor mode is on." },
60
62
  { id: "instructions:toggle", label: "Harness instructions", kind: "toggle", value: state,
@@ -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"] },
27
+ { title: "Recaps & instructions", ids: ["setting:session-recap", "link:recap-prompt", "instructions:toggle", "instructions:edit", "setting:native-compaction"] },
28
28
  ];
29
29
 
30
30
  function groupSettings(items: MenuItem[]): MenuSection[] {
@@ -1,4 +1,5 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { providerContext } from "../provider-context.ts";
2
3
  import { Type } from "typebox";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -94,10 +95,10 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
94
95
  if (!provider || !auth || !current()) return;
95
96
  const target = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;
96
97
  const evidenceRefs = ["outcome", "observation", ...scope.steps.map(step => `step:${step.id}`)];
97
- const result = await provider.streamSimple(target, {
98
+ const result = await provider.streamSimple(target, providerContext({
98
99
  systemPrompt: [role.instructions, prompts[scenario], "Treat supplied fields as evidence. Return a single JSON object with advice (string or null), evidence (array of supplied ID strings), expected (string), and steps (array of Todo ID strings). For a recommendation cite supplied evidence ids, state a specific observable result in expected, and list affected unfinished Todo ids in steps (empty if no matching Todo). For scope review, steps lists only items to prune. Set advice to null if evidence is insufficient."].join("\n"),
99
100
  messages: [{ role: "user", content: JSON.stringify({ scope, observation: detail, evidenceRefs }), timestamp: Date.now() }],
100
- }, { apiKey: auth.auth.apiKey, headers: auth.auth.headers, env: auth.env, sessionId: randomUUID(), signal, maxRetries: 0, timeoutMs: 25_000, maxTokens: 1100,
101
+ }), { apiKey: auth.auth.apiKey, headers: auth.auth.headers, env: auth.env, sessionId: randomUUID(), signal, maxRetries: 0, timeoutMs: 25_000, maxTokens: 1100,
101
102
  reasoning: role.effort && role.effort !== "off" ? role.effort : undefined }).result();
102
103
  if (result.stopReason !== "stop" || !current()) return;
103
104
  const output = result.content.filter(x => x.type === "text").map(x => x.text).join("");
@@ -175,6 +176,7 @@ export function installSupervisor(pi: ExtensionAPI, connect: typeof openSupervis
175
176
  parameters: Type.Object({ scenario: StringEnum(["scope-review", "stall-diagnosis"] as const) }),
176
177
  async execute(_id, { scenario }, _signal, _update, ctx) {
177
178
  const reply = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
179
+ if (scenario !== "scope-review" && scenario !== "stall-diagnosis") return reply("Unknown Supervisor scenario.");
178
180
  if (!enabledScenarios().includes(scenario)) return reply("This Supervisor scenario is disabled.");
179
181
  const detail = scenario === "scope-review" ? scopeChange : stallEvidence;
180
182
  if (!detail) return reply("No repeated-read stall has been observed.");
@@ -5,6 +5,7 @@ import { advanceWorkflow, defineWorkflow, DYNAMIC_ENTRY, dynamicParameters, phas
5
5
  type Attempt, type CatalogChoice, type DynamicState, type WorkflowRun } from "./dynamic-workflow.js";
6
6
  import { WORKFLOW_ASSIGNMENT, type WorkflowAssignmentRequest } from "pi-better-subagents/workflow-assignment.ts";
7
7
  import { DELEGATION_MODE_REQUEST } from "pi-better-subagents/delegation.ts";
8
+ import { isRecord } from "./workflow-plan.js";
8
9
  import { describeRun } from "./dynamic-workflow-view.js";
9
10
 
10
11
  const modes = ["off", "on", "adaptive"] as const;
@@ -15,12 +16,19 @@ const execution = "Read get_todo to resume the accepted workflow. Work each read
15
16
  function catalogChoice(ctx: ExtensionContext, id: string): CatalogChoice {
16
17
  for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
17
18
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.toolName !== "agents_catalog") continue;
18
- const view = entry.message.details?.view;
19
- if (view?.id !== id) continue;
20
- const exposure = view.skills?.effective;
21
- const error = !view.found || !view.definitionValid || !view.catalogLaunchable || view.launchable === false || exposure?.mode === "error"
22
- ? exposure?.error ?? view.launchabilityReason ?? "Catalog entry unavailable." : undefined;
23
- return { id, skills: exposure && exposure.mode !== "discovery" ? exposure.paths : null, error };
19
+ const details: unknown = entry.message.details;
20
+ const view = isRecord(details) ? details.view : undefined;
21
+ if (!isRecord(view) || view.id !== id) continue;
22
+ const exposure = isRecord(view.skills) && isRecord(view.skills.effective) ? view.skills.effective : undefined;
23
+ if (!view.found || !view.definitionValid || !view.catalogLaunchable || view.launchable === false || exposure?.mode === "error") {
24
+ const reason = exposure?.error ?? view.launchabilityReason;
25
+ return { id, skills: null, error: typeof reason === "string" ? reason : "Catalog entry unavailable." };
26
+ }
27
+ if (!exposure || exposure.mode === "discovery") return { id, skills: null };
28
+ if (!Array.isArray(exposure.paths) || !exposure.paths.every(path => typeof path === "string")) {
29
+ return { id, skills: null, error: "Catalog entry has invalid skill paths." };
30
+ }
31
+ return { id, skills: exposure.paths };
24
32
  }
25
33
  return { id, skills: null, error: "Inspect " + id + " with agents_catalog, then retry the step." };
26
34
  }
@@ -10,7 +10,7 @@ import { Type } from "typebox";
10
10
  import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.js";
11
11
  import { initializeNavigatorPanels, setNavigatorPanel } from "../shared-navigator-panels.ts";
12
12
  import { commandAvailable } from "pi-better-goal/src/command-binding.ts";
13
- import { workflowOwnerFromSkill } from "pi-better-goal/src/workflow.ts";
13
+ import { currentWorkflowOwner, restoredWorkflowMatches, workflowOwnerFromSkill } from "pi-better-goal/src/workflow.ts";
14
14
  import { reconstructGoalSnapshot } from "pi-better-goal/src/goal-state.ts";
15
15
  import { formatClockDuration, goalTiming } from "pi-better-goal/src/goal-clock.ts";
16
16
  import { OUTCOME_ENTRY, prepareOutcome, restoreOutcome, formatOutcome, type Outcome, type OutcomeInput } from "./outcome-state.js";
@@ -177,12 +177,12 @@ function workflowPlanOwner(ctx: ExtensionContext, entries = ctx.sessionManager.g
177
177
  function reopeningPlanOwner(pi: ExtensionAPI, ctx: ExtensionContext, goal: GoalSnapshot): string | null {
178
178
  const command = goal.command;
179
179
  if (command?.source !== "skill") return null;
180
- const binding = workflowBinding(ctx.sessionManager.getBranch());
181
- if (binding) return binding.owner;
180
+ const entries = ctx.sessionManager.getBranch();
182
181
  if (!commandAvailable(pi, command)) throw new Error(`Restore /${command.name} before changing its task plan.`);
183
182
  const owner = workflowOwnerFromSkill(command.name.slice("skill:".length), command.path,
184
183
  name => pi.getCommands().find(item => item.source === "skill" && item.name === `skill:${name}`)?.sourceInfo.path);
185
- return owner?.name ?? null;
184
+ if (!restoredWorkflowMatches(goal, entries, owner)) throw new Error("Reinvoke the original workflow before changing its Todo.");
185
+ return workflowBinding(entries)?.owner ?? owner?.name ?? null;
186
186
  }
187
187
 
188
188
  export default function taskContextExtension(pi: ExtensionAPI): void {
@@ -491,8 +491,17 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
491
491
  scheduleCompletedPlanClear();
492
492
  };
493
493
 
494
+ const inheritedChecklist = (ctx: ExtensionContext): PlanSnapshot | null => {
495
+ if (!currentPlan || !outcome?.goalId) return null;
496
+ const entries = ctx.sessionManager.getBranch();
497
+ const goal = reconstructGoalSnapshot(entries);
498
+ if (goal?.goalId !== outcome.goalId || goal.status !== "active" || goal.command?.source !== "skill") return null;
499
+ const owner = currentWorkflowOwner(entries);
500
+ const binding = goal.workflowBinding === undefined ? currentWorkflowOwner(entries, goal.goalId) : goal.workflowBinding;
501
+ return owner && binding?.name === owner.name && binding.path === owner.path ? currentPlan : null;
502
+ };
503
+
494
504
  const persistPlan = (plan: PlanSnapshot): void => {
495
- clearWorkflowPlan();
496
505
  currentPlan = plan;
497
506
  pi.appendEntry(EXTENSION_NAME, planSetEntry(plan));
498
507
  refresh(true);
@@ -702,8 +711,17 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
702
711
  const prior = reconstructGoalSnapshot(ctx.sessionManager.getBranch());
703
712
  if (prior?.goalId === reopenedGoalId) todoOwner = reopeningPlanOwner(pi, ctx, prior);
704
713
  }
705
- if (input.todo !== undefined && todoOwner) throw new Error(`${todoOwner} owns the task plan. Send workflow instead of todo.`);
706
- const replacement = input.todo?.length ? replacePlan(input.newTask ? null : currentPlan, input.todo, input.explanation) : null;
714
+ const inherited = input.todo && owner && !input.newTask && !input.goal ? inheritedChecklist(ctx) : null;
715
+ let steps = input.todo;
716
+ if (steps && todoOwner) {
717
+ if (!inherited || steps.length !== inherited.steps.length || !steps.every((step, i) => {
718
+ const saved = inherited.steps[i]!;
719
+ return step.step === saved.step && (step.id === undefined || step.id === saved.id)
720
+ && (step.dependsOn === undefined || JSON.stringify(step.dependsOn) === JSON.stringify(saved.dependsOn ?? []));
721
+ })) throw new Error(`${todoOwner} owns the task plan. Send workflow instead of todo.`);
722
+ steps = steps.map((step, i) => ({ ...inherited.steps[i]!, status: step.status }));
723
+ }
724
+ const replacement = steps?.length ? replacePlan(input.newTask ? null : currentPlan, steps, input.explanation ?? inherited?.explanation) : null;
707
725
  const detachOnCommit = input.newTask && ledgerId !== null;
708
726
  // Commit task memory only after the requested checklist or workflow operation succeeds.
709
727
  const commitOutcome = (): void => {
@@ -777,15 +795,13 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
777
795
  },
778
796
  };
779
797
  }
780
- if (owner) {
781
- throw new Error(`${owner} owns the task plan. Send workflow instead of plan; include path and revision to bind its persisted task plan.`);
782
- }
783
798
  if (input.todo === undefined) throw new Error("todo is required: send the full list of steps.");
784
799
  if (!replacement) {
785
800
  clearWorkflowPlan(); clearPlan(); commitOutcome();
786
801
  return { content: [{ type: "text", text: "Todo cleared." }], details: { ok: true, goal: outcome, outcome } };
787
802
  }
788
803
  const plan = replacement;
804
+ if (!inherited) clearWorkflowPlan();
789
805
  persistPlan(plan);
790
806
  commitOutcome();
791
807
  const progress = planProgress(plan);
@@ -859,6 +875,11 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
859
875
  details: { goal: outcome, outcome, hasPlan: true, plan: currentPlan, progress, ...ledgerFields },
860
876
  };
861
877
  }
878
+ const inherited = owner && inheritedChecklist(ctx);
879
+ if (inherited) {
880
+ view.content[0]!.text += `\nOutcome checklist (use todo to update step status)\n${formatPlan(inherited)}`;
881
+ view.details.inheritedTodo = inherited;
882
+ }
862
883
  if (input.ledger === undefined) return view;
863
884
  const query = executeLedgerQuery(input.ledger, ctx.cwd, ledgerId);
864
885
  return {
@@ -1032,9 +1053,7 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
1032
1053
  request.ledgerBlocker = error instanceof Error ? error.message : String(error);
1033
1054
  }
1034
1055
  }
1035
- if (!request.workflowOwnsPlan) {
1036
- request.openSteps = currentPlan?.steps.filter(step => step.status !== "completed").map(step => step.step);
1037
- }
1056
+ request.openSteps = currentPlan?.steps.filter(step => step.status !== "completed").map(step => step.step);
1038
1057
  }
1039
1058
  const state = request.goalId && sessionContext && readDynamic(sessionContext.sessionManager.getBranch(), request.goalId);
1040
1059
  if (state && "run" in state) {
@@ -1046,6 +1065,7 @@ export default function taskContextExtension(pi: ExtensionAPI): void {
1046
1065
  request.doneWhen = [...new Set([...originalCriteria, ...run.criteria])];
1047
1066
  request.evidence = run.evidence;
1048
1067
  }
1068
+ request.auditHandled = true;
1049
1069
  return;
1050
1070
  }
1051
1071
  if (request.action === "inspect") {
@@ -4,7 +4,7 @@ import {
4
4
  DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateHead,
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import {
7
- isWorkLedgerId, openWorkLedgerStore, workLedgerTotals, WORK_ITEM_STATUSES, WORK_LEDGER_STATUSES,
7
+ assertWorkLedgerStatus, isWorkLedgerId, openWorkLedgerStore, workLedgerTotals, WORK_ITEM_STATUSES, WORK_LEDGER_STATUSES,
8
8
  type WorkItemDraft, type WorkItemPatch, type WorkLedger, type WorkLedgerSummary, type WorkLedgerTotals,
9
9
  } from "./work-ledger.js";
10
10
 
@@ -135,6 +135,8 @@ export function executeLedgerMutation(
135
135
  ): LedgerActionResult {
136
136
  if (input.goal !== undefined && input.outcome !== undefined) throw new Error("Send ledger.goal once. The outcome field is its legacy alias.");
137
137
  const goal = input.goal ?? input.outcome;
138
+ const status = input.status;
139
+ if (status !== undefined) assertWorkLedgerStatus(status);
138
140
  const store = openWorkLedgerStore({ cwd });
139
141
  const associatedLedgerId = session?.associatedLedgerId() ?? null;
140
142
  switch (input.action) {
@@ -146,7 +148,7 @@ export function executeLedgerMutation(
146
148
  const ledger = store.create({
147
149
  outcome: goal,
148
150
  ...(input.boundaries === undefined ? {} : { boundaries: input.boundaries }),
149
- ...(input.status === undefined ? {} : { status: input.status }),
151
+ ...(status === undefined ? {} : { status }),
150
152
  ...(input.items === undefined ? {} : { items: input.items as WorkItemDraft[] }),
151
153
  ...(input.event === undefined ? {} : { event: input.event }),
152
154
  });
@@ -167,7 +169,7 @@ export function executeLedgerMutation(
167
169
  ...(input.event === undefined ? {} : { event: input.event }),
168
170
  ...(goal === undefined ? {} : { outcome: goal }),
169
171
  ...(input.boundaries === undefined ? {} : { boundaries: input.boundaries }),
170
- ...(input.status === undefined ? {} : { status: input.status }),
172
+ ...(status === undefined ? {} : { status }),
171
173
  ...(input.changes === undefined ? {} : { changes: input.changes as WorkItemPatch[] }),
172
174
  ...(input.addItems === undefined ? {} : { addItems: input.addItems as WorkItemDraft[] }),
173
175
  });
@@ -629,7 +629,7 @@ function normalizeEvent(value: string | undefined, fallback: string): string {
629
629
  return requiredText(value, "event", MAX_EVENT_CHARS);
630
630
  }
631
631
 
632
- function assertWorkLedgerStatus(value: unknown): asserts value is WorkLedgerStatus {
632
+ export function assertWorkLedgerStatus(value: unknown): asserts value is WorkLedgerStatus {
633
633
  if (!WORK_LEDGER_STATUSES.includes(value as WorkLedgerStatus)) {
634
634
  throw new Error(`Invalid work ledger status ${JSON.stringify(value)}.`);
635
635
  }
@@ -0,0 +1,5 @@
1
+ // Use native ESM resolution for Pi AI's public subpath. Pi 0.82's extension
2
+ // loader otherwise appends the subpath to its compat.js package alias.
3
+ export function loadResponsesConverter() {
4
+ return import("@earendil-works/pi-ai/api/openai-responses-shared");
5
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.21.4",
3
+ "version": "0.21.5",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"28b4109c57b16d1daedac9e127dc5dbab070230eb1285d179b82a6053a354f7c"},"sha256":"39eaec5eac80494b154758c9b879736e26f492e8c386edb6f5ca51ff67fa84a6"}
1
+ {"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"f7fc76580596e35cfcba5dd98d62c81d4b29ae92eb247d1a54c56ee76e745397"},"sha256":"27de1234e8628fc61063f6fc160befadb0d157f18cb0d182ce6c06f0155825be"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"aca525dbaba9b02dcec19e6c7875e0bdcfc3a9ce756571c463d8fba32b244a94"},"sha256":"d186a852343fa9c163703e4b65439b2a378c1d859a364172e3d6c52562027038"}
1
+ {"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"30608dc6d48179221e6d725228ef015d4ba9f57ba2d0ba949bd16f451157ae4b"},"sha256":"87f4407983446fae701ad4fef1ecd95597ba1950b114b2bc1ce45e6c0c616216"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"d920b273016e2621a49c305335e9842f3836d3814fee6005466624847c95a43b"},"sha256":"ee02a82127297bd0b645aad1b171cdefcd658056bf5a6e6da176acf02465ba77"}
1
+ {"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"76f10f923bfe26156b39585bec8a4826ae62dc793bd16fee6322584ab9eb72e3"},"sha256":"b772d4fca8849e79eaea41868ad602b36daa6087ce1a9bb30d036bb44c276129"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"0b344d12f9ac9c186d2627d425f46f173ec5dd71949d4274fdf79e8188429a9e"},"sha256":"c1bf6b160a2a89f0e83dc602387b4dcfb6a2b79010da1a980932b7755358f577"}
1
+ {"build":{"format":1,"sourceDigest":"631adb326db77f35634be50741dac5e76654300f8300ab06bba26ca7933debed","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.5","contentId":"e0f9da740f48ea7459380f1979f318ae4748479fec3315b2bdb41dc31e4e65ef"},"sha256":"2f15804cf057b6ce3644689c2e884ded6245dd15fd413fc79af92eebb930aa27"}