pi-workflow-engine 0.11.0 → 0.12.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 (73) hide show
  1. package/.pi/extensions/pi-workflow-engine/index.ts +255 -97
  2. package/.pi/extensions/pi-workflow-engine/src/advisory-schema.ts +0 -4
  3. package/.pi/extensions/pi-workflow-engine/src/agent-attempt.ts +3 -1
  4. package/.pi/extensions/pi-workflow-engine/src/agent-limits.ts +35 -0
  5. package/.pi/extensions/pi-workflow-engine/src/agent-replay.ts +27 -4
  6. package/.pi/extensions/pi-workflow-engine/src/agent-retry.ts +116 -0
  7. package/.pi/extensions/pi-workflow-engine/src/agent-runner-types.ts +49 -45
  8. package/.pi/extensions/pi-workflow-engine/src/agent-runner.ts +95 -26
  9. package/.pi/extensions/pi-workflow-engine/src/agent-session-providers.ts +50 -0
  10. package/.pi/extensions/pi-workflow-engine/src/agent-session.ts +158 -203
  11. package/.pi/extensions/pi-workflow-engine/src/agent-skills.ts +48 -42
  12. package/.pi/extensions/pi-workflow-engine/src/agent-workspace.ts +11 -3
  13. package/.pi/extensions/pi-workflow-engine/src/background-workflow-tool.ts +75 -0
  14. package/.pi/extensions/pi-workflow-engine/src/background-workflows.ts +492 -0
  15. package/.pi/extensions/pi-workflow-engine/src/budget.ts +3 -3
  16. package/.pi/extensions/pi-workflow-engine/src/cancellation.ts +38 -0
  17. package/.pi/extensions/pi-workflow-engine/src/command-completions.ts +36 -0
  18. package/.pi/extensions/pi-workflow-engine/src/concurrency.ts +70 -4
  19. package/.pi/extensions/pi-workflow-engine/src/diff-capture.ts +16 -130
  20. package/.pi/extensions/pi-workflow-engine/src/discovery.ts +9 -5
  21. package/.pi/extensions/pi-workflow-engine/src/dynamax.ts +109 -60
  22. package/.pi/extensions/pi-workflow-engine/src/engine.ts +166 -18
  23. package/.pi/extensions/pi-workflow-engine/src/filesystem-error.ts +4 -0
  24. package/.pi/extensions/pi-workflow-engine/src/inline-workflow.ts +2 -2
  25. package/.pi/extensions/pi-workflow-engine/src/journal.ts +12 -6
  26. package/.pi/extensions/pi-workflow-engine/src/model-profile-command.ts +167 -0
  27. package/.pi/extensions/pi-workflow-engine/src/model-profiles.ts +310 -0
  28. package/.pi/extensions/pi-workflow-engine/src/options.ts +88 -1
  29. package/.pi/extensions/pi-workflow-engine/src/pi-compat.ts +32 -0
  30. package/.pi/extensions/pi-workflow-engine/src/progress-types.ts +50 -0
  31. package/.pi/extensions/pi-workflow-engine/src/progress.ts +72 -117
  32. package/.pi/extensions/pi-workflow-engine/src/provider-usage-limit.ts +189 -0
  33. package/.pi/extensions/pi-workflow-engine/src/research-contract.ts +89 -0
  34. package/.pi/extensions/pi-workflow-engine/src/research-evidence.ts +289 -0
  35. package/.pi/extensions/pi-workflow-engine/src/resume-context.ts +74 -38
  36. package/.pi/extensions/pi-workflow-engine/src/review/code-review-orchestration.ts +49 -0
  37. package/.pi/extensions/pi-workflow-engine/src/review/review-report.ts +1 -1
  38. package/.pi/extensions/pi-workflow-engine/src/review/review-results-flow.ts +2 -1
  39. package/.pi/extensions/pi-workflow-engine/src/review/review-results-viewer.ts +11 -30
  40. package/.pi/extensions/pi-workflow-engine/src/review/review-session-coordinator.ts +5 -5
  41. package/.pi/extensions/pi-workflow-engine/src/review/review-snapshot.ts +3 -4
  42. package/.pi/extensions/pi-workflow-engine/src/review-diff-target.ts +130 -0
  43. package/.pi/extensions/pi-workflow-engine/src/session-identity.ts +6 -0
  44. package/.pi/extensions/pi-workflow-engine/src/structured-output.ts +32 -0
  45. package/.pi/extensions/pi-workflow-engine/src/tool-capabilities.ts +44 -0
  46. package/.pi/extensions/pi-workflow-engine/src/tool-source-identity.ts +1 -4
  47. package/.pi/extensions/pi-workflow-engine/src/tree-fingerprint.ts +1 -4
  48. package/.pi/extensions/pi-workflow-engine/src/types.ts +49 -15
  49. package/.pi/extensions/pi-workflow-engine/src/ui/dynamax-editor-decoration.ts +220 -0
  50. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-format.ts +26 -6
  51. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-inspector.ts +88 -46
  52. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-result-renderer.ts +2 -1
  53. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-viewer-layout.ts +51 -0
  54. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-widget.ts +12 -67
  55. package/.pi/extensions/pi-workflow-engine/src/usage.ts +124 -16
  56. package/.pi/extensions/pi-workflow-engine/src/workflow-advisory-utils.ts +23 -3
  57. package/.pi/extensions/pi-workflow-engine/src/workflow-execution.ts +1 -1
  58. package/.pi/extensions/pi-workflow-engine/src/workflow-run-background.ts +72 -0
  59. package/.pi/extensions/pi-workflow-engine/src/workflow-run-controller.ts +354 -0
  60. package/.pi/extensions/pi-workflow-engine/src/workflow-run-history.ts +162 -0
  61. package/.pi/extensions/pi-workflow-engine/src/workflow-run-record.ts +632 -0
  62. package/.pi/extensions/pi-workflow-engine/src/workflow-run-store.ts +172 -0
  63. package/.pi/extensions/pi-workflow-engine/src/workflow-usage-limit-scheduler.ts +80 -0
  64. package/.pi/extensions/pi-workflow-engine/src/workflows.ts +2 -0
  65. package/.pi/extensions/pi-workflow-engine/src/worktree.ts +40 -3
  66. package/.pi/extensions/pi-workflow-engine/workflows/code-review.ts +18 -42
  67. package/.pi/extensions/pi-workflow-engine/workflows/diagnose.ts +10 -17
  68. package/.pi/extensions/pi-workflow-engine/workflows/perf-review.ts +8 -15
  69. package/.pi/extensions/pi-workflow-engine/workflows/refactor-scout.ts +8 -15
  70. package/.pi/extensions/pi-workflow-engine/workflows/research.ts +170 -0
  71. package/README.md +72 -141
  72. package/USAGE.md +211 -17
  73. package/package.json +1 -1
package/USAGE.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  `pi-workflow-engine` adds zero-dependency Dynamax workflows to pi: opt into live, parallel subagents for the tasks that need a custom investigation instead of one long prompt. Most users only need these surfaces:
4
4
 
5
+ This release requires **pi 0.80.10 or newer**. pi remains host-provided rather
6
+ than bundled by this package, and the extension rejects older runtimes at load
7
+ time with an update message.
8
+
5
9
  - `/workflow <name> [args]` to run a saved workflow directly.
6
10
  - `/workflow:*` commands for related actions such as inspector reopening and Dynamax control.
7
11
  - `dynamax` as a literal one-shot opt-in token when you want the host agent to author a one-off inline workflow for investigation/review.
@@ -16,6 +20,7 @@ From inside a repo:
16
20
  /workflow refactor-scout src/
17
21
  /workflow diagnose "typecheck fails after the schema change"
18
22
  /workflow perf-review "workflow startup latency"
23
+ /workflow research "Compare the current Node.js and Bun test-runner watch modes; prefer official docs"
19
24
  ```
20
25
 
21
26
  The built-in workflows are advisory by default. They inspect, verify, and report; they do **not** edit files. Saved or inline workflows can opt individual agents into disposable git worktrees when they need reviewable patches.
@@ -29,11 +34,63 @@ Useful flags:
29
34
  /workflow code-review --review-viewer # alias for --result-viewer
30
35
  /workflow:results # reopen the latest code-review findings without rerunning
31
36
  /workflow code-review --concurrency=4 # cap concurrent subagents
37
+ /workflow code-review --max-agents=20 # cap total live agent calls in the run
38
+ /workflow code-review --agent-timeout-ms=600000 # abort one live agent after 10 minutes
39
+ /workflow code-review --agent-retries=2 # retry classified transient provider failures
32
40
  /workflow code-review --budget=50000 # output-token ceiling for subagents
33
41
  /workflow code-review --resume <run-id> # replay matching completed agent calls
42
+ /workflow code-review --resume <run-id> --resume-edited # reuse unchanged calls after a workflow edit
34
43
  /workflow code-review --refresh # rediscover newly added workflow files
44
+ /workflow:runs # browse recent durable project runs
45
+ /workflow:inspector <run-id> # inspect one retained run directly
46
+ /workflow:models # inspect small/medium/big model routes
47
+ ```
48
+
49
+ ## Workflow model profiles
50
+
51
+ Workflow authors can route a stage through `profile: "small"`, `"medium"`, or
52
+ `"big"` without hard-coding a provider. Inspect the effective routes with:
53
+
54
+ ```text
55
+ /workflow:models
56
+ /workflow:models set small openai/gpt-5-mini low
57
+ /workflow:models set medium anthropic/claude-sonnet-4-5 medium --project
58
+ /workflow:models clear medium --project
35
59
  ```
36
60
 
61
+ `set` and `clear` use the user scope unless `--project` is present. User profiles
62
+ live at `~/.pi/agent/workflow-models.json`; project profiles live at
63
+ `<project>/.pi/workflow-models.json` and override the user file one profile at a
64
+ time. A minimal file is:
65
+
66
+ ```json
67
+ {
68
+ "profiles": {
69
+ "small": {
70
+ "model": "openai/gpt-5-mini",
71
+ "thinkingLevel": "low"
72
+ },
73
+ "big": {
74
+ "model": "anthropic/claude-opus-4-5"
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ Models must be exact `provider/model` identities already available to pi. The
81
+ file accepts only `model` and optional `thinkingLevel`; provider credentials and
82
+ secrets stay in pi's provider configuration. The engine never ranks models by
83
+ price, model-name substrings, or assumed capability.
84
+
85
+ Routing is resolved per field: an agent's explicit `model` or `thinkingLevel`
86
+ wins, then its requested profile, then host inheritance. A configured profile
87
+ without `thinkingLevel` inherits the host effort. An entirely unconfigured tier
88
+ uses the host model and the built-in bounded effort for that tier (`low`,
89
+ `medium`, or `high` respectively); `/workflow:models` labels that route as a host
90
+ fallback. Invalid JSON, unknown fields, malformed identities, and configured
91
+ models missing from pi's registry fail with the config path and a corrective
92
+ command instead of selecting another model.
93
+
37
94
  ## Built-in workflows
38
95
 
39
96
  | Name | Purpose |
@@ -42,9 +99,27 @@ Useful flags:
42
99
  | `refactor-scout` | Finds small, safe refactor opportunities. |
43
100
  | `diagnose` | Investigates a bug, failing command, or regression. |
44
101
  | `perf-review` | Reviews a slow path or performance concern. |
102
+ | `research` | Gathers current external evidence, independently verifies claims, and returns a cited synthesis. |
45
103
 
46
104
  `code-review` auto-detects a diff when you do not pass args. If there is an open GitHub PR for the current branch, it uses the cumulative PR diff; otherwise it falls back to branch-vs-main/master or `HEAD~1`. Per-commit `gh pr diff --patch` input is rejected because it can surface superseded code. If diff capture fails, the review fails instead of returning an empty report or "no findings."
47
105
 
106
+ ### External research capabilities
107
+
108
+ `research` requires at least one installed pi tool whose metadata identifies it
109
+ as external web search, browsing, or HTTP(S) page extraction. Local grep/find
110
+ tools do not satisfy this check. The workflow does not bundle a scraper or a
111
+ paid API; install or enable the web capability you prefer, then restart or
112
+ reload pi so subagent sessions can see it.
113
+
114
+ The workflow bounds decomposition to four lanes and verification to twelve
115
+ claims, while the engine's concurrency, total-agent, timeout, cancellation, and
116
+ token-budget limits still apply. Gatherers retain direct page titles and URLs;
117
+ search-results URLs are rejected, sources are canonicalized and deduplicated,
118
+ and separate verifier agents classify claims as supported, conflicting,
119
+ uncertain, inferred, or rejected before synthesis. External research calls use
120
+ `resume: "off"` because live web evidence, time, and service state are outside
121
+ the journal's deterministic replay surface.
122
+
48
123
  ## Use Dynamax for custom workflows
49
124
 
50
125
  Use `dynamax` when the built-in workflows are not specific enough and you want the main pi agent to author a temporary workflow for the current question. It is the fastest path from "this needs multiple angles" to a live fan-out, verifier pass, and synthesized result.
@@ -73,6 +148,30 @@ The workflow inspector and code-review results viewer are also registered as fir
73
148
 
74
149
  When only the literal `dynamax` token is used, the opt-in is one-shot: the next agent run receives the workflow permission reminder, stays visibly active for that run, then clears after the run ends. When `/workflow:dynamax on` is used, the opt-in is sticky for the current pi session until `/workflow:dynamax off`. Sticky mode, one-shot pending mode, and active Dynamax workflow runs show compact TUI status with `/workflow:dynamax on|off` and the inspector shortcut; off mode clears that status line.
75
150
 
151
+ ### Prompt editor cue
152
+
153
+ In TUI mode, every standalone `dynamax` token receives one bounded
154
+ moving-shine sweep, then remains as a static multi-colour cue. Longer identifiers
155
+ such as `notdynamax`, `dynamaxing`, and `dynamax_mode` are deliberately left
156
+ alone. The cue affects rendering only; one-shot and sticky activation semantics
157
+ are unchanged.
158
+
159
+ The default effect is `shine`. Set `PI_DYNAMAX_EFFECT=static` for a motionless
160
+ cue or `PI_DYNAMAX_EFFECT=off` to disable it. A non-empty `NO_COLOR` also
161
+ disables the default cue; an explicit `PI_DYNAMAX_EFFECT` value takes precedence.
162
+
163
+ The implementation follows pi 0.80.10's [official `CustomEditor`
164
+ pattern](https://pi.dev/docs/latest/extensions#custom-editor): it decorates only
165
+ the editor's rendered lines, retaining the wrapped editor's input, cursor,
166
+ deletion, paste, multiline, undo, completion, IME, and app-keybinding behavior.
167
+
168
+ If an editor extension is already registered, pi-workflow-engine composes its
169
+ factory and adds only the Dynamax render hook. If that editor cannot be
170
+ composed, an explicit warning is shown and pi's stock-compatible `CustomEditor`
171
+ is used so highlighting is never silently disabled. Pi editor registration is
172
+ still last-writer-wins; the previous editor is restored on shutdown only while
173
+ the Dynamax decorator still owns the registration.
174
+
76
175
  When the host agent calls the `workflow` tool from a TUI session, pi opens the live workflow inspector for that run. The compact workflow widget still shows the latest moving status above the editor, but the inspector is the richer view for phases, agents, findings, and logs.
77
176
 
78
177
  Configure either shortcut by creating `~/.pi/agent/extensions/pi-workflow-engine.json`:
@@ -106,7 +205,7 @@ const GapAnalysis = Type.Object({
106
205
  });
107
206
  const gaps = await api.agent(
108
207
  `Identify only material gaps that require another agent:\n${JSON.stringify(firstPass)}`,
109
- { schema: GapAnalysis, thinkingLevel: "low" },
208
+ { schema: GapAnalysis, profile: "small" },
110
209
  );
111
210
 
112
211
  const followUpItems = gaps?.items.slice(0, MAX_FOLLOW_UPS) ?? [];
@@ -114,7 +213,7 @@ const followUps = followUpItems.length
114
213
  ? (await api.parallel(
115
214
  followUpItems.map((item) => () =>
116
215
  api.agent(`Resolve this gap and cite evidence: ${JSON.stringify(item)}`, {
117
- thinkingLevel: "low",
216
+ profile: "small",
118
217
  }),
119
218
  ),
120
219
  )).filter((result) => result !== null)
@@ -122,7 +221,7 @@ const followUps = followUpItems.length
122
221
 
123
222
  return api.agent(
124
223
  `Synthesize the first pass and any follow-ups:\n${JSON.stringify({ firstPass, followUps })}`,
125
- { thinkingLevel: "medium" },
224
+ { profile: "medium" },
126
225
  );
127
226
  ```
128
227
 
@@ -138,12 +237,64 @@ Workflow results are rendered in pi with:
138
237
  - recommendations;
139
238
  - next steps;
140
239
  - run stats when available;
141
- - workflow-level token and cost totals gathered from subagent sessions when provider usage is available.
240
+ - workflow-level fresh-input, cache-read, cache-write, output, and cost totals gathered from subagent sessions when provider usage is available.
142
241
 
143
242
  These workflow usage totals are separate from `--perf`, which is internal timing only. They are also separate from pi's built-in footer and `/session` totals, which may still show host-session usage only unless pi core adds a first-class extension usage API. If a model has no pricing configured, token totals can be non-zero while displayed cost remains `$0.000`.
144
243
 
244
+ The result, inspector overview, compact widget, and status line all use the same usage summary. Providers with a complete breakdown show `fresh`, `cache read`, `cache write`, and `output` separately. Zero cache components are omitted. If a provider reports only some components, the summary labels mixed-run component totals with `≥` and preserves the provider's aggregate `total`; if it reports no components, the summary falls back to aggregate `tokens`. Costs are summed from provider session totals and are never inferred from local pricing.
245
+
145
246
  During a run, pi shows live phases and subagent status. Use `--inspect` if you want a larger live view while the workflow is active, then `/workflow:inspector` if you want to bring the last completed inspector back up afterward.
146
247
 
248
+ ### Durable run records
249
+
250
+ Every workflow run writes a versioned project-local record to `.pi/.workflow-runs/<run-id>.run.json`; its agent replay journal remains `.pi/.workflow-runs/<run-id>.jsonl`. The same run ID appears in execution metadata, progress snapshots, result details, and both filenames. Records distinguish `queued`, `running`, `completed`, `failed`, `stopped`, and `paused` lifecycle states and retain resolved scalar options, timestamps, compact progress, summary usage, and the final result or error.
251
+
252
+ Record replacement is atomic, corrupt or unsupported-version files are ignored independently, and the newest 50 run records are retained. Journal retention remains 50 files. Both record and journal files are excluded from repository resume fingerprints, so checkpoint writes do not invalidate replay.
253
+
254
+ Persistence is intentionally bounded and private by default. Raw workflow args, prompts, subagent transcripts, progress logs, lane details, agent errors, environment data, credentials, and tool-output-shaped fields are not stored. Final results are limited to bounded plain JSON; credential- and transcript-shaped fields are redacted, and unsupported or cyclic results are marked unavailable instead of executing accessors or breaking the workflow. Loading history only parses these data files and never imports or executes workflow code.
255
+
256
+ ### Background workflows
257
+
258
+ The host-facing `workflow` tool accepts `background: true`. It returns as soon as the run ID and origin metadata are durably recorded, while the normal workflow engine continues in-process with the same concurrency, budget, worktree, progress, usage, and resume rules. Synchronous execution remains the default, and the `/workflow` slash command remains synchronous.
259
+
260
+ Background runs are detached from the initiating tool-call signal, so the host agent can finish that turn and continue the conversation. When the run completes or fails, the extension waits for the originating session to become idle and inserts one concise `workflow-result` message containing the run ID, terminal state, and summary. Delivery state is stored with the run record; on reload, the extension checks both that state and the session message history before retrying, which suppresses duplicates even if persistence failed immediately after message insertion.
261
+
262
+ Provider usage-window continuation is a separate, explicit background option:
263
+
264
+ ```json
265
+ {
266
+ "name": "code-review",
267
+ "background": true,
268
+ "autoResumeOnUsageLimit": true,
269
+ "usageLimitMaxAttempts": 3,
270
+ "usageLimitMaxDelayMs": 21600000
271
+ }
272
+ ```
273
+
274
+ It is off by default and schedules only registered file workflows whose invocation had no arguments; inline scripts and argument-bearing runs still pause safely but require an explicit manual decision because their executable input is not persisted. A recognized provider usage or quota failure aborts the current fan-out before queued agents can open new sessions, preserves the replay journal, and records a sanitized provider message, provider identity, reset hint, total attempt number, and next eligible time. Transport failures and ordinary provider errors keep the existing per-agent `agentRetries` behavior and do not create a provider-limit pause.
275
+
276
+ Reset parsing accepts provider duration hints such as `retry-after: 60` and `x-ratelimit-reset-tokens: 6m0s`, plus future RFC3339 timestamps. Missing, past, or malformed hints use a 60-second fallback; delays are clamped to at least 5 seconds and at most `usageLimitMaxDelayMs`. The default maximum is three total run attempts, including the initial run. When the eligible time arrives, the extension starts a new background run with `resumeFromRunId`; after a process restart, it re-arms only the remaining delay. `/workflow:runs resume` and `/workflow:runs stop` cancel any pending timer, and the attempt cap prevents an infinite resume loop.
277
+
278
+ The equivalent environment defaults are `PI_WORKFLOW_USAGE_LIMIT_AUTO_RESUME=1`, `PI_WORKFLOW_USAGE_LIMIT_MAX_ATTEMPTS`, and `PI_WORKFLOW_USAGE_LIMIT_MAX_DELAY_MS`. Per-tool-call values take precedence.
279
+
280
+ A graceful pi session shutdown aborts active background work and records it as `paused` instead of successful. Reopening the same session after an ungraceful process exit also reconciles a retained `queued` or `running` background record to `paused`. Resuming the originating pi session delivers that interruption once. If the originating session no longer exists, the record remains in `.pi/.workflow-runs/`, delivery is marked unavailable, and a fallback is written to stderr. Background mode is supported in long-lived TUI and RPC sessions; `print` and `json` modes reject it because those processes exit after the prompt. This feature is in-process rather than a daemon: a hard process kill cannot keep model work running, but the last atomic run checkpoint remains available.
281
+
282
+ ### Recent runs and lifecycle actions
283
+
284
+ `/workflow:runs` opens pi's native selection UI with a bounded list of recent project runs. Each option includes an accessible state label, workflow name, age, duration, usage summary, and full run ID. Choose a run, then choose one of the lifecycle actions currently valid for it: inspect, stop, resume, or restart. The background activity line is present only while this session owns active background work.
285
+
286
+ The same operations are available without the selection UI:
287
+
288
+ ```text
289
+ /workflow:runs inspect <run-id>
290
+ /workflow:runs stop <run-id>
291
+ /workflow:runs resume <run-id>
292
+ /workflow:runs restart <run-id>
293
+ /workflow:inspector <run-id>
294
+ ```
295
+
296
+ Inspect is always safe. Stop is available for a background run active in the current session and for a retained paused run with a pending resume timer. Resume is limited to paused registered workflows whose source fingerprint is unchanged and whose invocation had no redacted arguments; it starts a new background run ID with `resumeFromRunId` journal replay. Restart is limited to completed, failed, or stopped registered workflows that had no arguments and also creates a new background run ID. Inline workflows and argument-bearing invocations are intentionally not relaunched because their executable input was not persisted. In `print` and `json` modes, list and inspect return formatted text without opening TUI components, while resume/restart report that background execution requires TUI or RPC mode.
297
+
147
298
  Code-review findings are rendered as a formatted result message by default. pi no longer asks whether to open the findings viewer. Use `--result-viewer` or `--review-viewer` when you want to inspect findings interactively, press `enter` to expand/collapse the nicely formatted finding text, and use `1`-`9` to jump directly to a visible finding. The viewer is centred, scales to the terminal, and shows the visible finding/detail ranges while scrolling. `/workflow:results` or `ctrl+shift+r` reopens the most recent validated code-review report in the current pi session without rerunning the workflow; selections reset when it reopens.
148
299
 
149
300
  The Fix action revalidates the exact reviewed PR/ref/index/working-tree snapshot, then runs each selected finding through its own worktree-isolated agent and returns the finding ID, validation summary, patch, and changed status. Failed attempts do not discard successful previews, no patch is applied to your active tree automatically, and a moved or unverifiable review target is rejected rather than patched against the wrong code. The original review and all Fix previews retained in that pi session share one output-token budget. Reopening the viewer does not reset it, finalized preview usage is always deducted, and only one preview can run at a time.
@@ -156,9 +307,16 @@ Every workflow result includes a run id. Resume with:
156
307
 
157
308
  ```text
158
309
  /workflow code-review --resume <run-id> HEAD~3
310
+ /workflow code-review --resume <run-id> --resume-edited HEAD~3
159
311
  ```
160
312
 
161
- The `workflow` tool exposes the same feature as `resumeFromRunId`. Replay is explicit for agents that share the workflow directory and automatic for isolated patch-producing agents:
313
+ The `workflow` tool exposes the same features as `resumeFromRunId` and the opt-in `resumeEditedWorkflow: true`. By default, any workflow source change invalidates every prior call. Edited-workflow resume waives only that source-fingerprint mismatch: repository state, runtime, model, system prompt, thinking level, prompt, schema, ordered skills, tools, isolation, and all other replay checks must still match.
314
+
315
+ With edited-workflow resume enabled, unchanged calls are reused while changed or newly added calls run live. Matching uses a stable behavioral hash, not call or completion order. Repeated identical calls are deliberately ambiguous and run live unless each logical call has a stable, distinct `cacheKey`. The new run record retains the opt-in policy and reports cached and live agent totals. The engine only inspects the prior run's JSON journal; it never loads or executes the prior workflow source.
316
+
317
+ This option can return a result produced before an orchestration edit when that call's explicit identity did not change. Use it only when the unchanged call is still semantically valid in the edited workflow, and prefer stable `cacheKey` values for repeated logical calls. Omit `--resume-edited` or `resumeEditedWorkflow` for the fail-closed default.
318
+
319
+ Replay is explicit for agents that share the workflow directory and automatic for isolated patch-producing agents:
162
320
 
163
321
  | Agent call | Default during resume | Override |
164
322
  | --- | --- | --- |
@@ -205,14 +363,14 @@ export default async function run({ agent, parallel, phase, args }: WorkflowApi)
205
363
  schema: Finding,
206
364
  tools: SEARCH_TOOLS,
207
365
  toolHints: SEARCH_TOOL_HINTS,
208
- thinkingLevel: "low",
366
+ profile: "small",
209
367
  resume: "read-only",
210
368
  }),
211
369
  () => agent(`Find edge cases: ${args}`, {
212
370
  schema: Finding,
213
371
  tools: SEARCH_TOOLS,
214
372
  toolHints: SEARCH_TOOL_HINTS,
215
- thinkingLevel: "low",
373
+ profile: "small",
216
374
  resume: "read-only",
217
375
  }),
218
376
  ]),
@@ -220,7 +378,7 @@ export default async function run({ agent, parallel, phase, args }: WorkflowApi)
220
378
 
221
379
  phase("Synthesize");
222
380
  return agent(`Summarize: ${JSON.stringify(findings)}`, {
223
- thinkingLevel: "medium",
381
+ profile: "medium",
224
382
  tools: [],
225
383
  resume: "read-only",
226
384
  });
@@ -239,15 +397,33 @@ Core primitives:
239
397
  | `progress(event)` | Emits counters, summaries, and lane items. |
240
398
  | `workflow(ref, args?)` | Runs another workflow inline as a sub-step and returns its result. |
241
399
 
242
- Use settled mode when the workflow must distinguish a successful `null` from a failed branch. It preserves input order and returns `{ ok: true, value }` or `{ ok: false, error: { name?, message } }` for every thunk. Genuine workflow cancellation still rejects the whole `parallel()` call and cancels siblings.
400
+ Schema agents accept structured output only through the validated, terminating `final_answer` tool. If the first response omits it, the engine makes at most **two repair attempts** (three prompt attempts total). Repair prompts expose only `final_answer` when the active pi session supports tool restriction. Clean exhaustion throws `WorkflowStructuredOutputError` with code `WORKFLOW_STRUCTURED_OUTPUT_NONCOMPLIANCE`; provider failures and host cancellation still propagate unchanged.
401
+
402
+ Use settled mode when the workflow must distinguish a successful `null` from a failed branch. It preserves input order and returns `{ ok: true, value }` or `{ ok: false, error: { name?, message, code?, details? } }` for every thunk. Default parallel mode still turns recoverable structured-output exhaustion into a `null` slot, while settled mode retains the typed code and attempt details. Genuine workflow cancellation still rejects the whole `parallel()` call and cancels siblings.
243
403
 
244
- Set `thinkingLevel` on fan-out agents. Otherwise many subagents can inherit an expensive global reasoning level.
404
+ Direct schema calls can catch the typed failure instead of receiving an unexplained `null`:
245
405
 
246
- `tools` is a strict allowlist. If you set `tools: ["read", "bash"]`, extension tools such as `ast-grep`, `mgrep`, `fffind`, or `ffgrep` are hidden from that subagent. Add `toolHints: ["search"]` to dynamically expose installed grep/find/search-like tools while keeping the concrete base allowlist portable. The built-in advisory workflows use `tools: ["read", "bash", "grep", "find", "ls"]` plus `toolHints: ["search"]`.
406
+ ```ts
407
+ try {
408
+ return await agent("Return the result.", { schema: ResultSchema });
409
+ } catch (error) {
410
+ if (error instanceof Error && "code" in error && error.code === "WORKFLOW_STRUCTURED_OUTPUT_NONCOMPLIANCE") {
411
+ log("The agent did not produce compliant structured output.");
412
+ return undefined;
413
+ }
414
+ throw error;
415
+ }
416
+ ```
417
+
418
+ Set a model `profile` on each stage so users can tune workflow routing centrally.
419
+ Use explicit `model` or `thinkingLevel` only when that one call intentionally
420
+ overrides its profile.
421
+
422
+ `tools` is a strict allowlist. If you set `tools: ["read", "bash"]`, extension tools such as `ast-grep`, `mgrep`, `fffind`, or `ffgrep` are hidden from that subagent. Add `toolHints: ["search"]` to dynamically expose installed grep/find/search-like tools while keeping the concrete base allowlist portable. Use `toolHints: ["external-search"]` for installed web search, browsing, and URL-extraction tools; `requireToolHints: true` fails before prompting unless each requested capability matched. The built-in advisory workflows use `tools: ["read", "bash", "grep", "find", "ls"]` plus `toolHints: ["search"]`.
247
423
 
248
424
  Subagents receive no skills by default. Opt in per agent with `skills: ["skill-name"]`; if `tools` is also restricted, the engine automatically keeps `read` available so the subagent can load the selected `SKILL.md`. When `skills` is omitted, clear prompt text such as `/skill:name`, `include skill name`, or `use the name skill` is also treated as an opt-in. Pass `skills: []` to suppress that inference.
249
425
 
250
- Set `model` only when a subagent should use a specific model. Bare ids keep the Anthropic shorthand; `provider/id` targets built-in, custom, or local providers. Omitted models inherit the host/session default; malformed or unknown explicit refs fail fast.
426
+ Set `model` only when a subagent should use a specific model. Bare ids keep the Anthropic shorthand; `provider/id` targets built-in, custom, or local providers. Explicit models override a requested profile; calls with neither inherit the host/session default. Malformed or unknown explicit refs fail fast.
251
427
 
252
428
  ### Mutating agents in worktrees
253
429
 
@@ -257,7 +433,7 @@ Use `isolation: "worktree"` only for agents that should edit files. The agent ru
257
433
  const edit = await agent("Rename this helper and update its call sites.", {
258
434
  tools: ["read", "bash", "edit", "grep", "find", "ls"],
259
435
  isolation: "worktree",
260
- thinkingLevel: "medium",
436
+ profile: "medium",
261
437
  });
262
438
 
263
439
  if (edit.changed) {
@@ -272,7 +448,7 @@ Cleanup is a required finalizer. The engine attempts every registered worktree r
272
448
 
273
449
  ### Compose workflows
274
450
 
275
- `workflow(ref, args?)` runs a registered workflow by name as a sub-step, returning its result. The child shares the parent run's concurrency cap, abort signal, and perf timing, and its phases nest under `<name> ▸ <phase>` in the live UI.
451
+ `workflow(ref, args?)` runs a registered workflow by name as a sub-step, returning its result. The child shares the parent run's concurrency cap, total-agent limit, per-agent timeout, abort signal, and perf timing, and its phases nest under `<name> ▸ <phase>` in the live UI.
276
452
 
277
453
  ```ts
278
454
  export default async function run({ workflow }: WorkflowApi) {
@@ -312,8 +488,8 @@ export default async function run({ agent, parallel, phase, args }) {
312
488
  phase("Find");
313
489
  const Finding = Type.Object({ summary: Type.String() });
314
490
  const findings = await parallel([
315
- () => agent(`Find correctness issues: ${args}`, { schema: Finding, thinkingLevel: "low" }),
316
- () => agent(`Find edge cases: ${args}`, { schema: Finding, thinkingLevel: "low" }),
491
+ () => agent(`Find correctness issues: ${args}`, { schema: Finding, profile: "small" }),
492
+ () => agent(`Find edge cases: ${args}`, { schema: Finding, profile: "small" }),
317
493
  ]);
318
494
  return { summary: JSON.stringify(findings) };
319
495
  }
@@ -325,6 +501,7 @@ Inline rules:
325
501
  - default-export an async workflow function;
326
502
  - no imports or dynamic `import()`;
327
503
  - use the injected `Type` object for schemas;
504
+ - request `profile: "small"`, `"medium"`, or `"big"` instead of hard-coding provider models when the stage is portable;
328
505
  - add `skills: ["skill-name"]` per `agent()` call when a subagent should use a pi skill; no skills are exposed by default;
329
506
  - no extra exports or code after the default export.
330
507
 
@@ -338,10 +515,27 @@ Only tune these when a workflow is too slow, too expensive, or too noisy:
338
515
  | --- | --- |
339
516
  | `--concurrency=N` / `PI_WORKFLOW_CONCURRENCY=N` | Cap concurrent subagents. Default is `min(8, max(2, CPU count))`. |
340
517
  | `--parallel-limit=N` / `PI_WORKFLOW_PARALLEL_SUBMISSION_LIMIT=N` | Limit eager `parallel()` submission. |
341
- | `--budget=N` / `PI_WORKFLOW_BUDGET=N` | Set an output-token ceiling for completed subagents. `agent()` throws `WorkflowBudgetExceededError` before starting another agent once the ceiling is reached; agents already running may overshoot because the engine does not reserve per-agent estimates. |
518
+ | `--max-agents=N` / `PI_WORKFLOW_MAX_AGENTS=N` | Cap live model calls across the complete run, including sub-workflows. Default `64`; values are clamped to `1`–`10000`. Replay hits do not consume the cap. The `workflow` tool field is `maxAgents`. |
519
+ | `--agent-timeout-ms=N` / `PI_WORKFLOW_AGENT_TIMEOUT_MS=N` | Abort one live agent after this duration. Default `1800000` (30 minutes); values are clamped to `1000`–`86400000`. The session is aborted and its isolated worktree is cleaned up. The `workflow` tool field is `agentTimeoutMs`. |
520
+ | `--agent-retries=N` / `PI_WORKFLOW_AGENT_RETRIES=N` | Retry terminal assistant failures that pi classifies as transient provider or transport errors. Default `0`; values are clamped to `0`–`10`. Backoff starts at one second, doubles, and caps at 30 seconds. The `workflow` tool field is `agentRetries`. |
521
+ | `--budget=N` / `PI_WORKFLOW_BUDGET=N` | Set an output-token ceiling across recorded subagent attempts, including failed provider attempts. `agent()` throws `WorkflowBudgetExceededError` before starting another model request once the ceiling is reached; agents already running may overshoot because the engine does not reserve per-agent estimates. |
342
522
  | `--perf` / `PI_WORKFLOW_PERF=1` | Include internal timing aggregates. Usage/cost totals are reported separately from perf. |
343
523
  | `PI_WORKFLOW_LANE_ITEM_LIMIT=N` | Cap retained progress lane items. |
344
524
 
525
+ These controls bound different dimensions: concurrency limits how many agents
526
+ are active together, `max-agents` limits how many live model calls the run may
527
+ start in total, `agent-timeout-ms` bounds one active call (including retry
528
+ backoff), and `budget` limits recorded output tokens. Every retry consumes
529
+ another live-agent admission and remains inside the original timeout, budget,
530
+ and abort scope. Usage from failed attempts is retained, so it can exhaust the
531
+ budget before the next retry begins. Host cancellation takes precedence over
532
+ limit and timeout failures.
533
+
534
+ Workflow subagents disable pi's session-level automatic retry so this run-level
535
+ policy is authoritative and visible in the existing agent progress row. Invalid
536
+ models, schema-contract failures, exhausted budgets, agent limits, worktree
537
+ failures, timeouts, and host aborts are never provider-retried.
538
+
345
539
  ## Common fixes
346
540
 
347
541
  - **Unknown workflow**: confirm the extension is loaded with `pi list`; use `--refresh` for new drop-ins.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-workflow-engine",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Zero-dependency Dynamax workflows for pi: live parallel subagents, typed handoffs, synthesized results.",
6
6
  "keywords": [