pi-better-harness 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +30 -0
  3. package/extensions/recap/index.ts +173 -0
  4. package/extensions/recap/summary.ts +131 -0
  5. package/extensions/settings/copy.ts +3 -0
  6. package/extensions/settings/page.ts +2 -2
  7. package/extensions/task-context/dynamic-workflow-runtime.ts +185 -0
  8. package/extensions/task-context/dynamic-workflow-view.ts +176 -0
  9. package/extensions/task-context/dynamic-workflow.ts +142 -0
  10. package/extensions/task-context/index.ts +99 -13
  11. package/extensions/task-context/plan-presentation.ts +1 -1
  12. package/extensions/task-context/plan-widget.ts +5 -2
  13. package/extensions/task-context/workflow-diagram.ts +72 -0
  14. package/extensions/task-context/workflow-plan.ts +99 -56
  15. package/lib/install-settings.mjs +11 -2
  16. package/lib/instructions.mjs +20 -13
  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/src/managed-authority.ts +16 -0
  27. package/node_modules/pi-better-background-tasks/src/managed-client.ts +2 -2
  28. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +8 -4
  29. package/node_modules/pi-better-background-tasks/src/registry.ts +2 -0
  30. package/node_modules/pi-better-background-tasks/src/runtime.ts +3 -2
  31. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/expiry.ts +44 -0
  32. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/schema.ts +8 -1
  33. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +5 -0
  34. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  35. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/waits.ts +40 -32
  36. package/node_modules/pi-better-background-tasks/src/supervisor/emit-runner.mjs +1 -0
  37. package/node_modules/pi-better-background-tasks/src/supervisor/generated/runner.mjs +12 -7
  38. package/node_modules/pi-better-background-tasks/src/supervisor/generated/task-lifetime.mjs +9 -0
  39. package/node_modules/pi-better-background-tasks/src/supervisor/runner.ts +12 -7
  40. package/node_modules/pi-better-background-tasks/src/supervisor/types.ts +1 -1
  41. package/node_modules/pi-better-background-tasks/src/tools.ts +3 -2
  42. package/node_modules/pi-better-goal/package.json +1 -1
  43. package/node_modules/pi-better-goal/src/command-binding.ts +10 -3
  44. package/node_modules/pi-better-goal/src/index.ts +9 -8
  45. package/node_modules/pi-better-goal/src/task-context.ts +2 -0
  46. package/node_modules/pi-better-goal/src/workflow-gates.ts +3 -1
  47. package/node_modules/pi-better-subagents/README.md +2 -2
  48. package/node_modules/pi-better-subagents/cleanup.ts +4 -1
  49. package/node_modules/pi-better-subagents/docs/usage.md +5 -8
  50. package/node_modules/pi-better-subagents/index.ts +46 -27
  51. package/node_modules/pi-better-subagents/managed-launch-host.ts +26 -2
  52. package/node_modules/pi-better-subagents/managed-launch-port.ts +2 -0
  53. package/node_modules/pi-better-subagents/output-payload.ts +2 -0
  54. package/node_modules/pi-better-subagents/package.json +1 -1
  55. package/node_modules/pi-better-subagents/registry-cleanup-worker.mjs +22 -0
  56. package/node_modules/pi-better-subagents/registry.ts +18 -4
  57. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  58. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  59. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  60. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  61. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  62. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  63. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  64. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  65. package/node_modules/pi-better-subagents/settings-page.ts +10 -10
  66. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/expiry.ts +44 -0
  67. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +8 -1
  68. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +5 -0
  69. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  70. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/waits.ts +40 -32
  71. package/node_modules/pi-better-subagents/stop.ts +7 -5
  72. package/node_modules/pi-better-subagents/timing.ts +11 -4
  73. package/node_modules/pi-better-subagents/tools.ts +3 -2
  74. package/node_modules/pi-better-subagents/workflow-assignment.ts +35 -0
  75. package/node_modules/pi-better-subagents/workspace-files.ts +6 -6
  76. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.54.0] - 2026-11-25
4
+
5
+ ### Added
6
+
7
+ - Run task-defined workflows and display their progress in Todo. (#904)
8
+ - Show the Rush review and fix loop alongside delivery progress. A shipped unit counts as reviewed only when its recorded review matches the delivered commit.
9
+
10
+ ### Fixed
11
+
12
+ - Reject a replacement Todo when reopening an Outcome that owns a workflow plan. Keep the original plan available to its scheduler.
13
+ - Skip the instructions lock for unmarked dotfiles during sync and disable, so read-only dotfile directories can keep Harness instructions off.
14
+ - Bundle Goal 0.16.2, Background Tasks 0.20.3, and Subagents 0.38.0 with Server 0.7.3.
15
+
16
+ ## [0.53.0] - 2026-11-23
17
+
18
+ ### Added
19
+
20
+ - Enable session recaps in Harness settings and customize the recap prompt. (#885)
21
+
22
+ ### Fixed
23
+
24
+ - Expand a home-relative `PI_CODING_AGENT_DIR` when the CLI writes instructions or global settings.
25
+ - Bundle Background Tasks 0.20.2 and Subagents 0.37.2 with Server 0.7.2. Background tasks and subagents now have a 24-hour maximum lifetime.
26
+
3
27
  ## [0.52.0] - 2026-11-23
4
28
 
5
29
  ### Added
package/README.md CHANGED
@@ -65,6 +65,30 @@ Existing Plan session histories restore as Todo. Workflow task-plan files and
65
65
  revision checks stay unchanged; skills continue using their own records when the
66
66
  optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
67
67
 
68
+ ### Dynamic workflows
69
+
70
+ Run `/dynamic-workflow` to plan the current task once. In `/harness-settings`,
71
+ **Automatic dynamic workflows** defaults to **off**. **On** lets the planning agent
72
+ start a workflow. **Adaptive** lets it handle simple requests directly and use a
73
+ workflow for dependencies, role handoffs or repeated review. The command works
74
+ in every mode and keeps your saved preference.
75
+
76
+ The agent records an objective, acceptance criteria, required outputs and task
77
+ dependencies. Todo shows tasks on the left and dependencies and review loops on the right.
78
+ Task icons distinguish ready (○), working (●), waiting (·), optional standby (–),
79
+ failed (×), and completed (✓) steps. In mouse-enabled Pi, click a task to highlight
80
+ its stage and inspect its latest result. Use `/todo expand` to show every task.
81
+ Below 36 terminal columns, the diagram follows the list.
82
+ Independent tasks can run together. A join waits for each prerequisite's output.
83
+ If a reviewer requests changes, the revision opens and the revised artifact
84
+ returns to review. Delivery waits for approval of the current version.
85
+
86
+ The agent can select an inspected catalog role or named agent for a step.
87
+ The ordinary subagent launch applies the catalog skills and current permissions.
88
+ Harness associates the returned assignment and its verified result with the step.
89
+ Resume the session branch to continue from its saved outputs. A bound Goal also
90
+ requires evidence for its objective. A standalone workflow can finish on its own.
91
+
68
92
  The separate **Project work ledger** setting enables a durable project-scoped
69
93
  record of the overall outcome, boundaries, and high-level items. It stays off by
70
94
  default; turning it off removes ledger views and hints without deleting records.
@@ -261,6 +285,12 @@ prompt; in Instructions, it restores the prompt while preserving model/effort.
261
285
  A user Markdown override is archived when its prompt is reset. Saved defaults
262
286
  survive sessions and upgrades.
263
287
 
288
+ ### Session recap
289
+
290
+ In `/harness-settings`, **Session recap** enables a short summary above the editor after a conversation settles. It defaults to Off. **Recap prompt** opens the current instructions for editing. Save a blank prompt to restore the default or press Escape to keep your previous instructions. Both settings are saved as user defaults. Editing the prompt takes effect on the next summary.
291
+
292
+ Each recap uses a separate request to the model that answered. It sends a bounded selection of recent user and assistant text. Pi hosts with the public configured model streaming API can generate summaries; existing summaries restore locally on older hosts. Recap and the optional Next line stay on their session branch. The summary request has its own session identity and usage. The main model receives its usual prompt, tools and conversation.
293
+
264
294
  ### Harness instructions
265
295
 
266
296
  Open `/harness-settings` and toggle **Harness instructions** from **Off** to
@@ -0,0 +1,173 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Text } from "@earendil-works/pi-tui";
3
+ import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
4
+ import {
5
+ DEFAULT_PROMPT,
6
+ ENTRY,
7
+ latestAnswer,
8
+ restoredSummary,
9
+ summarize,
10
+ supportsRecap,
11
+ type Summary,
12
+ } from "./summary.ts";
13
+
14
+ type Preferences = { enabled?: boolean; prompt?: string };
15
+ const KEY = "sessionRecap";
16
+
17
+ function preferences(value: unknown): Preferences {
18
+ if (!value || typeof value !== "object") return {};
19
+ const { enabled, prompt } = value as Preferences;
20
+ return {
21
+ enabled: enabled === true,
22
+ prompt: typeof prompt === "string" && prompt.trim() && prompt.length <= 4096 ? prompt : undefined,
23
+ };
24
+ }
25
+
26
+ export default function recapExtension(pi: ExtensionAPI): void {
27
+ let prefs: Preferences = {};
28
+ let run: AbortController | undefined;
29
+ let answerId: string | undefined;
30
+
31
+ function cancel() {
32
+ run?.abort();
33
+ run = undefined;
34
+ answerId = undefined;
35
+ }
36
+
37
+ function display(ctx: ExtensionContext, summary?: Summary) {
38
+ if (ctx.mode !== "tui" || !ctx.hasUI) return;
39
+ ctx.ui.setWidget(
40
+ ENTRY,
41
+ summary
42
+ ? (_tui, theme) => {
43
+ const lines = [theme.bold("Recap") + " " + summary.recap];
44
+ if (summary.next) lines.push(theme.fg("accent", "Next") + " " + summary.next);
45
+ return new Text(lines.join("\n"), 0, 0);
46
+ }
47
+ : undefined,
48
+ { placement: "aboveEditor" },
49
+ );
50
+ }
51
+
52
+ function restore(ctx: ExtensionContext) {
53
+ cancel();
54
+ if (!prefs.enabled || ctx.mode !== "tui") return display(ctx);
55
+ const branch = ctx.sessionManager.getBranch();
56
+ const answer = latestAnswer(branch);
57
+ display(ctx, answer && restoredSummary(branch, answer.id));
58
+ }
59
+
60
+ function save(update: Preferences) {
61
+ prefs = updateHarnessSetting<Preferences>(KEY, (current) => ({ ...preferences(current), ...update }));
62
+ }
63
+
64
+ async function editPrompt(ctx: ExtensionCommandContext) {
65
+ const edit = await ctx.ui.editor("Recap prompt · clear to restore default", prefs.prompt || DEFAULT_PROMPT);
66
+ if (edit === undefined) return;
67
+ const prompt = edit.trim();
68
+ if (prompt.length > 4096) {
69
+ ctx.ui.notify("Recap prompt must fit within 4,096 characters.", "warning");
70
+ return;
71
+ }
72
+ save({ prompt: prompt && prompt !== DEFAULT_PROMPT ? prompt : undefined });
73
+ restore(ctx);
74
+ }
75
+
76
+ const toggle = {
77
+ id: "session-recap",
78
+ label: "Session recap",
79
+ values: ["Off", "On"],
80
+ description: "Summarize settled conversations above the editor using a separate model request.",
81
+ get: () => (prefs.enabled ? "On" : "Off"),
82
+ change(value: string, ctx: ExtensionCommandContext) {
83
+ if (value !== "On" && value !== "Off") throw new Error("Unknown Recap setting");
84
+ save({ enabled: value === "On" });
85
+ restore(ctx);
86
+ if (prefs.enabled && !supportsRecap(ctx))
87
+ ctx.ui.notify("Recap generation requires Pi's configured model streaming API.", "warning");
88
+ },
89
+ };
90
+ const promptLink = {
91
+ id: "recap-prompt",
92
+ label: "Recap prompt",
93
+ description: "Edit instructions used only by the summary model.",
94
+ command: "/recap-prompt",
95
+ open: editPrompt,
96
+ };
97
+ const register = () => {
98
+ pi.events.emit("harness-settings:register", toggle);
99
+ pi.events.emit("harness-settings:register", promptLink);
100
+ };
101
+ let unsubscribe: (() => void) | undefined;
102
+ pi.registerCommand("recap-prompt", {
103
+ description: "Edit the session recap instructions",
104
+ handler: (_args, ctx) => editPrompt(ctx),
105
+ });
106
+ pi.on("session_start", (_event, ctx) => {
107
+ try {
108
+ prefs = preferences(readHarnessSetting(KEY));
109
+ } catch {
110
+ prefs = {};
111
+ }
112
+ unsubscribe ??= pi.events.on("harness-settings:request", register);
113
+ register();
114
+ restore(ctx);
115
+ });
116
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
117
+ pi.on("agent_start", (_event, ctx) => {
118
+ cancel();
119
+ display(ctx);
120
+ });
121
+ pi.on("agent_end", (event, ctx) => {
122
+ if (!prefs.enabled || ctx.mode !== "tui") return;
123
+ const last = event.messages.at(-1);
124
+ const answer = latestAnswer(ctx.sessionManager.getBranch());
125
+ if (last?.role === "assistant" && last.stopReason === "stop" && last.timestamp === answer?.message.timestamp)
126
+ answerId = answer.id;
127
+ });
128
+ pi.on("agent_settled", (event, ctx) => {
129
+ const id = answerId;
130
+ answerId = undefined;
131
+ if (
132
+ !id ||
133
+ (event as { aborted?: boolean }).aborted ||
134
+ ctx.hasPendingMessages() ||
135
+ !prefs.enabled ||
136
+ !ctx.hasUI ||
137
+ ctx.mode !== "tui"
138
+ )
139
+ return;
140
+ const branch = ctx.sessionManager.getBranch();
141
+ const answer = latestAnswer(branch);
142
+ if (answer?.id !== id || restoredSummary(branch, id)) return;
143
+ const sessionId = ctx.sessionManager.getSessionId();
144
+ const request = new AbortController();
145
+ run = request;
146
+ const signal = AbortSignal.any([request.signal, AbortSignal.timeout(30_000)]);
147
+ void summarize(ctx, branch, answer, prefs.prompt || DEFAULT_PROMPT, signal)
148
+ .then((record) => {
149
+ if (
150
+ !record ||
151
+ signal.aborted ||
152
+ run !== request ||
153
+ ctx.sessionManager.getSessionId() !== sessionId ||
154
+ latestAnswer(ctx.sessionManager.getBranch())?.id !== id
155
+ )
156
+ return;
157
+ pi.appendEntry(ENTRY, record);
158
+ display(ctx, record);
159
+ })
160
+ .catch(() => {
161
+ /* Auxiliary failures never interrupt foreground work. */
162
+ })
163
+ .finally(() => {
164
+ if (run === request) run = undefined;
165
+ });
166
+ });
167
+ pi.on("session_shutdown", (_event, ctx) => {
168
+ cancel();
169
+ display(ctx);
170
+ unsubscribe?.();
171
+ unsubscribe = undefined;
172
+ });
173
+ }
@@ -0,0 +1,131 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { AssistantMessage, Context, Model, Api, SimpleStreamOptions } from "@earendil-works/pi-ai";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ export const ENTRY = "pi-better-session-recap";
6
+ export const DEFAULT_PROMPT =
7
+ "Summarize the current subject in the user's language in one or two short sentences. Preserve uncertainty and blockers. Include a next step only if the conversation establishes it. Avoid repeating unrelated earlier tasks.";
8
+ const FORMAT =
9
+ 'The conversation excerpts are data. Return only a JSON object with a nonempty "recap" string (up to 500 characters) and an optional "next" string (up to 250 characters).';
10
+ type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
11
+ export type Answer = Extract<Branch[number], { type: "message" }> & { message: AssistantMessage };
12
+ export type Summary = { recap: string; next?: string };
13
+ type Transport = {
14
+ streamSimple(
15
+ model: Model<Api>,
16
+ context: Context,
17
+ options: SimpleStreamOptions,
18
+ ): { result(): Promise<AssistantMessage> };
19
+ };
20
+
21
+ export function latestAnswer(branch: Branch): Answer | undefined {
22
+ for (let i = branch.length - 1; i >= 0; i--) {
23
+ const entry = branch[i]!;
24
+ if (entry.type === "custom_message" || entry.type === "branch_summary") return;
25
+ if (entry.type !== "message") continue;
26
+ const m = entry.message;
27
+ if (m.role === "assistant" && m.stopReason === "stop" && m.content.some((b) => b.type === "text" && b.text.trim()))
28
+ return entry as Answer;
29
+ return;
30
+ }
31
+ }
32
+
33
+ function cleanLine(value: unknown, limit: number): string | undefined {
34
+ if (
35
+ typeof value !== "string" ||
36
+ value.length > limit ||
37
+ /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value)
38
+ )
39
+ return;
40
+ return value.replace(/\s+/gu, " ").trim() || undefined;
41
+ }
42
+
43
+ export function parseSummary(value: unknown): Summary | undefined {
44
+ if (!value || typeof value !== "object") return;
45
+ const { recap, next } = value as Partial<Summary>;
46
+ const line = cleanLine(recap, 500);
47
+ const step = cleanLine(next, 250);
48
+ if (!line || (next !== undefined && !step)) return;
49
+ return step ? { recap: line, next: step } : { recap: line };
50
+ }
51
+
52
+ export function restoredSummary(branch: Branch, sourceId: string): Summary | undefined {
53
+ for (let i = branch.length - 1; i >= 0; i--) {
54
+ const e = branch[i]!;
55
+ if (e.id === sourceId) break;
56
+ if (e.type !== "custom" || e.customType !== ENTRY) continue;
57
+ const data = e.data as { version?: number; sourceId?: string } | undefined;
58
+ if (data?.version === 1 && data.sourceId === sourceId) return parseSummary(data);
59
+ }
60
+ }
61
+
62
+ // Work backwards to give the last exchange first claim on the input budget.
63
+ function excerpts(branch: Branch) {
64
+ const recent: Array<{ role: "user" | "assistant"; text: string }> = [];
65
+ let remaining = 12_000;
66
+ for (let i = branch.length - 1; i >= 0 && remaining > 0 && recent.length < 8; i--) {
67
+ const e = branch[i]!;
68
+ if (e.type !== "message") continue;
69
+ const m = e.message;
70
+ if (m.role !== "user" && !(m.role === "assistant" && m.stopReason === "stop")) continue;
71
+ const text =
72
+ typeof m.content === "string"
73
+ ? m.content
74
+ : m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
75
+ const limit = Math.min(remaining, 4000);
76
+ const excerpt =
77
+ text.length <= limit
78
+ ? text
79
+ : text.slice(0, Math.floor(limit / 2)) + "…" + text.slice(text.length - (Math.ceil(limit / 2) - 1));
80
+ if (excerpt.trim()) {
81
+ recent.push({ role: m.role, text: excerpt });
82
+ remaining -= excerpt.length;
83
+ }
84
+ }
85
+ return recent.reverse();
86
+ }
87
+
88
+ export function supportsRecap(ctx: ExtensionContext): boolean {
89
+ return typeof (ctx.modelRegistry as Partial<Transport>).streamSimple === "function";
90
+ }
91
+
92
+ export async function summarize(
93
+ ctx: ExtensionContext,
94
+ branch: Branch,
95
+ answer: Answer,
96
+ prompt: string,
97
+ signal: AbortSignal,
98
+ ) {
99
+ if (!supportsRecap(ctx)) return;
100
+ const model = ctx.modelRegistry.find(answer.message.provider, answer.message.model);
101
+ if (!model) return;
102
+ const transport = ctx.modelRegistry as typeof ctx.modelRegistry & Transport;
103
+ const result = await transport
104
+ .streamSimple(
105
+ model,
106
+ {
107
+ systemPrompt: prompt + "\n\n" + FORMAT,
108
+ messages: [{ role: "user", content: JSON.stringify(excerpts(branch)), timestamp: answer.message.timestamp }],
109
+ },
110
+ { sessionId: randomUUID(), transport: "sse", signal, timeoutMs: 30_000, maxRetries: 0, maxTokens: 1000 },
111
+ )
112
+ .result();
113
+ if (signal.aborted || result.stopReason !== "stop") return;
114
+ const text = result.content
115
+ .filter((b) => b.type === "text")
116
+ .map((b) => b.text)
117
+ .join("")
118
+ .trim();
119
+ if (!text || text.length > 6000) return;
120
+ const summary = parseSummary(JSON.parse(text));
121
+ if (!summary) return;
122
+ const { input, output, cacheRead, cacheWrite } = result.usage;
123
+ return {
124
+ version: 1,
125
+ sourceId: answer.id,
126
+ ...summary,
127
+ provider: model.provider,
128
+ model: model.id,
129
+ usage: { input, output, cacheRead, cacheWrite },
130
+ };
131
+ }
@@ -17,6 +17,9 @@ export const controlCopy = new Map<string, SettingCopy>([
17
17
  label: "Foreground wait guard",
18
18
  description: "Blocks recognized shell waits, such as watching CI or following logs. Pi gets a prompt to run them in the background so the session stays responsive.",
19
19
  }],
20
+ ["dynamic-workflow", {
21
+ description: "Choose when Pi can plan a workflow automatically. Adaptive uses workflows for dependencies, handoffs or review. /dynamic-workflow starts one run in every mode.",
22
+ }],
20
23
  ["outcome-todo", {
21
24
  label: "Outcome and Todo tools",
22
25
  description: "Lets Pi record what the session should deliver and track its progress as a checklist.",
@@ -19,11 +19,11 @@ const callbackDescription = (source: "session" | "default") => [
19
19
 
20
20
  // Keep each package page beside the controls used for the same task.
21
21
  const taskOrder = [
22
- "setting:outcome-todo", "setting:goal-auto-start", "link:goal", "setting:outcome-todo-ledger",
22
+ "setting:outcome-todo", "setting:dynamic-workflow", "setting:goal-auto-start", "link:goal", "setting:outcome-todo-ledger",
23
23
  "link:subagents", "link:agents", "link:sandbox",
24
24
  "setting:tool-call-guard", "setting:background-review-interval", CALLBACK_SETTING_ID,
25
25
  "setting:navigator-view", "setting:navigator-sticky", "setting:outcome-todo-display",
26
- "setting:tool-output", "setting:tool-animation",
26
+ "setting:tool-output", "setting:tool-animation", "setting:session-recap", "link:recap-prompt",
27
27
  ];
28
28
  const position = new Map(taskOrder.map((id, index) => [id, index]));
29
29
 
@@ -0,0 +1,185 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { reconstructGoalSnapshot } from "pi-better-goal/src/goal-state.ts";
3
+ import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.js";
4
+ import { advanceWorkflow, defineWorkflow, DYNAMIC_ENTRY, dynamicParameters, phase, readDynamic,
5
+ type Attempt, type CatalogChoice, type DynamicState, type WorkflowRun } from "./dynamic-workflow.js";
6
+ import { WORKFLOW_ASSIGNMENT, type WorkflowAssignmentRequest } from "pi-better-subagents/workflow-assignment.ts";
7
+ import { DELEGATION_MODE_REQUEST } from "pi-better-subagents/delegation.ts";
8
+ import { describeRun } from "./dynamic-workflow-view.js";
9
+
10
+ const modes = ["off", "on", "adaptive"] as const;
11
+ type Mode = typeof modes[number];
12
+ const planning = "Analyze the user's current intent. Use dynamic_workflow action define with the actual objective, observable criteria and task-specific steps. Express real dependencies and parallel branches. Where delegation is permitted, inspect suitable entries with agents_catalog before selecting their canonical ids. Use stages and review/revision only where the task needs them. Bind goalId only for the Goal this work delivers.";
13
+ const execution = "Read get_todo to resume the accepted workflow. Work each ready step, then submit its required output using the current runId and revision. For a catalog item, call subagent_spawn with workflow:{runId,step}, its selected role or agent, inheriting catalog settings. Inspect subagent_result after its callback. For review or revision, submit the current artifactVersion and findings or output. Finish with evidence for each objective criterion.";
14
+
15
+ function catalogChoice(ctx: ExtensionContext, id: string): CatalogChoice {
16
+ for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
17
+ 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 };
24
+ }
25
+ return { id, skills: null, error: "Inspect " + id + " with agents_catalog, then retry the step." };
26
+ }
27
+
28
+ export function registerDynamicWorkflow(pi: ExtensionAPI, owner: (ctx: ExtensionContext) => string | null, changed: () => void) {
29
+ let mode: Mode = "off";
30
+ let state: DynamicState | undefined;
31
+ let activeContext: ExtensionContext | undefined;
32
+ const run = () => state && "run" in state ? state.run : undefined;
33
+ const pending = () => !!state && "pending" in state;
34
+ const restore = (ctx: ExtensionContext) => {
35
+ activeContext = ctx;
36
+ state = readDynamic(ctx.sessionManager.getBranch());
37
+ };
38
+ const save = (next: DynamicState) => {
39
+ pi.appendEntry(DYNAMIC_ENTRY, next);
40
+ state = next;
41
+ changed();
42
+ };
43
+ const persist = (next: WorkflowRun) => save({ version: 1, run: next });
44
+ const clear = () => save({ version: 1, clear: true });
45
+ const setting = {
46
+ id: "dynamic-workflow", label: "Automatic dynamic workflows", values: [...modes], get: () => mode,
47
+ change(value: string) {
48
+ if (!modes.includes(value as Mode)) throw new Error("Unknown dynamic workflow mode.");
49
+ mode = updateHarnessSetting("dynamicWorkflow", () => value as Mode);
50
+ changed();
51
+ },
52
+ };
53
+ const loadMode = () => {
54
+ const saved = readHarnessSetting<Mode>("dynamicWorkflow");
55
+ mode = saved && modes.includes(saved) ? saved : "off";
56
+ };
57
+ const active = () => { const current = run(); return !!current && !current.evidence; };
58
+ const available = () => mode !== "off" || pending() || active();
59
+ const guidance = () => {
60
+ if (active()) return execution;
61
+ if (pending() || mode === "on") return planning;
62
+ if (mode === "adaptive") return "Handle simple single-action requests directly. For tasks with dependencies, role handoffs, parallel work or repeated review, consider a dynamic workflow. " + planning;
63
+ return undefined;
64
+ };
65
+ pi.registerCommand("dynamic-workflow", {
66
+ description: "Plan one workflow for the current task, or continue its active run",
67
+ handler: async (args, ctx) => {
68
+ restore(ctx);
69
+ const existingOwner = owner(ctx);
70
+ if (existingOwner) { ctx.ui.notify(existingOwner + " owns this Todo.", "warning"); return; }
71
+ const resume = active();
72
+ if (!resume && !pending()) save({ version: 1, pending: true });
73
+ pi.sendMessage({ customType: DYNAMIC_ENTRY + ":requested", display: true,
74
+ content: [resume ? "Continue the current dynamic workflow." : "Plan a dynamic workflow for the current task.", args.trim()].filter(Boolean).join("\n") },
75
+ { triggerTurn: true, deliverAs: "followUp" });
76
+ },
77
+ });
78
+ pi.registerTool({
79
+ name: "dynamic_workflow", label: "Dynamic workflow", description: "Define the task workflow once, record step results and versioned review verdicts, retry a failed assignment, or finish with objective evidence.",
80
+ parameters: dynamicParameters,
81
+ async execute(_key, input, _signal, _update, ctx) {
82
+ restore(ctx);
83
+ if (owner(ctx)) throw new Error(owner(ctx) + " owns the Todo.");
84
+ const current = run();
85
+ let next: WorkflowRun;
86
+ if (input.action === "define") {
87
+ if (current && !current.evidence) throw new Error("A workflow is already active.");
88
+ if (mode === "off" && !pending()) throw new Error("Automatic workflows are off. Use /dynamic-workflow for this task.");
89
+ if (!input.definition) throw new Error("Supply a workflow definition.");
90
+ const goal = reconstructGoalSnapshot(ctx.sessionManager.getBranch());
91
+ const goalId = input.definition.goalId ?? (goal?.status === "active" && goal.objective === input.definition.objective ? goal.goalId : undefined);
92
+ if (goalId && (goal?.goalId !== goalId || goal.status !== "active")) throw new Error("Bind only to the active Goal.");
93
+ const ids = [...new Set(input.definition.steps.flatMap(s => s.catalog ? [s.catalog] : []))];
94
+ next = defineWorkflow({ ...input.definition, goalId }, ids.map(id => catalogChoice(ctx, id)));
95
+ } else {
96
+ if (!current) throw new Error("No accepted workflow.");
97
+ next = advanceWorkflow(current, input);
98
+ if (input.action === "retry") {
99
+ const id = next.steps.find(s => s.id === input.step)?.catalog;
100
+ if (id) next.catalogChoices = next.catalogChoices.map(c => c.id === id ? catalogChoice(ctx, id) : c);
101
+ }
102
+ }
103
+ persist(next);
104
+ return { content: [{ type: "text", text: describeRun(next) }], details: { run: next } };
105
+ },
106
+ });
107
+
108
+ function recordWorker(current: WorkflowRun, stepId: string, worker: Attempt) {
109
+ persist({ ...current, revision: current.revision + 1, workers: { ...current.workers, [stepId]: worker } });
110
+ }
111
+ const unsubscribe = pi.events.on(WORKFLOW_ASSIGNMENT, (event: unknown) => {
112
+ const request = event as WorkflowAssignmentRequest;
113
+ const { input, ref } = request;
114
+ const ctx = activeContext;
115
+ const origin = request.ctx.sessionManager;
116
+ const originLeaf = origin.getLeafId?.();
117
+ if (!ctx || ctx.sessionManager.getSessionId() !== origin.getSessionId() ||
118
+ (originLeaf && !ctx.sessionManager.getBranch().some(entry => entry.id === originLeaf))) {
119
+ request.error = "The workflow assignment belongs to another session branch.";
120
+ return;
121
+ }
122
+ restore(ctx);
123
+ const current = run();
124
+ const s = current?.steps.find(step => step.id === ref.step);
125
+ if (!current || ref.runId !== current.id || !s?.catalog || owner(ctx)) {
126
+ request.error = "No matching active workflow assignment.";
127
+ return;
128
+ }
129
+ const state = phase(current, s);
130
+ if (state !== "ready") { request.error = s.title + " is " + state; return; }
131
+ const modeRequest: { mode?: string } = {};
132
+ pi.events.emit(DELEGATION_MODE_REQUEST, modeRequest);
133
+ const selected = s.catalog.startsWith("role.") ? "role" : "agent";
134
+ const value = selected === "role" ? s.catalog.slice(5) : s.catalog;
135
+ let error: string | undefined;
136
+ if (modeRequest.mode === "manual") error = "Automatic workflow delegation is disabled in manual mode.";
137
+ else if ((input[selected] !== value && input[selected] !== s.catalog) || input[selected === "role" ? "agent" : "role"] !== undefined
138
+ || input.session_id !== undefined || input.session_name !== undefined || input.skills !== undefined || input.clean === true) error = "Use the selected catalog entry and inherit its skills.";
139
+ recordWorker(current, s.id, { callId: request.callId, error });
140
+ if (error) { request.error = error; return; }
141
+ const needs = new Set(s.dependsOn);
142
+ const reviewer = s.review ? s : current.steps.find(item => item.review?.revision === s.id);
143
+ if (reviewer?.review) {
144
+ needs.add(reviewer.id);
145
+ needs.add(reviewer.review.artifact);
146
+ needs.add(reviewer.review.revision);
147
+ }
148
+ const prior = current.history.filter(h => needs.has(h.step)).map(h => h.step + ": " + h.result);
149
+ const prompt = [input.prompt, "Objective: " + current.objective, "Assignment: " + s.title,
150
+ "Required output: " + s.output, ...prior].join("\n");
151
+ request.admission = { prompt, settled(receipt) {
152
+ // Re-read the selected branch after asynchronous admission. A fork or a
153
+ // simultaneous independent launch may have changed the latest snapshot.
154
+ if (!activeContext || activeContext.sessionManager.getSessionId() !== origin.getSessionId()) return;
155
+ restore(activeContext);
156
+ const latest = run();
157
+ if (latest?.id === current.id && latest.workers[s.id]?.callId === request.callId) {
158
+ recordWorker(latest, s.id, { callId: request.callId, ...receipt });
159
+ }
160
+ } };
161
+ });
162
+ pi.on("tool_result", (event, ctx) => {
163
+ if (event.toolName !== "subagent_result") return;
164
+ restore(ctx);
165
+ const current = run();
166
+ if (!current || current.evidence) return;
167
+ const claim = Object.entries(current.workers).find(([, w]) => w.runId && w.runId === event.input.id);
168
+ if (!claim) return;
169
+ const [stepId, worker] = claim;
170
+ const details = event.details as { hasFinalAnswer?: boolean; outcome?: { outcome?: { outcome?: string; reason?: string } }; assignment?: { attemptId?: string; state?: string; reason?: string; verified?: boolean } } | undefined;
171
+ const a = details?.assignment;
172
+ if (event.isError || !a?.verified || a.attemptId !== worker.runId) return;
173
+ if (a.state === "completed" && !worker.result) {
174
+ const body = event.content.flatMap(b => b.type === "text" ? [b.text] : []).join("\n");
175
+ const durable = details?.outcome?.outcome;
176
+ const result = durable?.outcome === "succeeded" ? durable.reason : details?.hasFinalAnswer ? body : undefined;
177
+ if (result?.trim()) recordWorker(current, stepId, { ...worker, result });
178
+ else if (details?.hasFinalAnswer === false && !worker.error) recordWorker(current, stepId, { ...worker, error: "The worker finished without returning the required output." });
179
+ }
180
+ if ((a.state === "failed" || a.state === "cancelled") && !worker.error) {
181
+ recordWorker(current, stepId, { ...worker, error: a.reason || a.state });
182
+ }
183
+ });
184
+ return { run, pending, available, restore, setting, loadMode, guidance, clear, dispose: () => { activeContext = undefined; if (typeof unsubscribe === "function") unsubscribe(); } };
185
+ }