pi-workflow-engine 0.10.3 → 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 (88) hide show
  1. package/.pi/extensions/pi-workflow-engine/index.ts +418 -213
  2. package/.pi/extensions/pi-workflow-engine/src/advisory-schema.ts +11 -4
  3. package/.pi/extensions/pi-workflow-engine/src/agent-attempt.ts +147 -0
  4. package/.pi/extensions/pi-workflow-engine/src/agent-limits.ts +35 -0
  5. package/.pi/extensions/pi-workflow-engine/src/agent-replay.ts +399 -0
  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 +91 -0
  8. package/.pi/extensions/pi-workflow-engine/src/agent-runner.ts +154 -530
  9. package/.pi/extensions/pi-workflow-engine/src/agent-session-identity.ts +256 -0
  10. package/.pi/extensions/pi-workflow-engine/src/agent-session-providers.ts +50 -0
  11. package/.pi/extensions/pi-workflow-engine/src/agent-session.ts +368 -0
  12. package/.pi/extensions/pi-workflow-engine/src/agent-skills.ts +87 -39
  13. package/.pi/extensions/pi-workflow-engine/src/agent-workspace.ts +89 -0
  14. package/.pi/extensions/pi-workflow-engine/src/background-workflow-tool.ts +75 -0
  15. package/.pi/extensions/pi-workflow-engine/src/background-workflows.ts +492 -0
  16. package/.pi/extensions/pi-workflow-engine/src/budget.ts +10 -3
  17. package/.pi/extensions/pi-workflow-engine/src/cancellation.ts +55 -3
  18. package/.pi/extensions/pi-workflow-engine/src/command-completions.ts +36 -0
  19. package/.pi/extensions/pi-workflow-engine/src/concurrency.ts +230 -61
  20. package/.pi/extensions/pi-workflow-engine/src/diff-capture.ts +38 -55
  21. package/.pi/extensions/pi-workflow-engine/src/discovery.ts +70 -17
  22. package/.pi/extensions/pi-workflow-engine/src/dynamax-shortcuts.ts +59 -13
  23. package/.pi/extensions/pi-workflow-engine/src/dynamax.ts +123 -63
  24. package/.pi/extensions/pi-workflow-engine/src/engine.ts +357 -75
  25. package/.pi/extensions/pi-workflow-engine/src/filesystem-error.ts +4 -0
  26. package/.pi/extensions/pi-workflow-engine/src/finalizers.ts +66 -0
  27. package/.pi/extensions/pi-workflow-engine/src/identity-canonicalization.ts +138 -0
  28. package/.pi/extensions/pi-workflow-engine/src/identity-fingerprint.ts +15 -0
  29. package/.pi/extensions/pi-workflow-engine/src/inline-workflow.ts +10 -5
  30. package/.pi/extensions/pi-workflow-engine/src/journal.ts +156 -66
  31. package/.pi/extensions/pi-workflow-engine/src/model-profile-command.ts +167 -0
  32. package/.pi/extensions/pi-workflow-engine/src/model-profiles.ts +310 -0
  33. package/.pi/extensions/pi-workflow-engine/src/options.ts +96 -6
  34. package/.pi/extensions/pi-workflow-engine/src/pi-compat.ts +32 -0
  35. package/.pi/extensions/pi-workflow-engine/src/process-runner.ts +203 -39
  36. package/.pi/extensions/pi-workflow-engine/src/progress-types.ts +50 -0
  37. package/.pi/extensions/pi-workflow-engine/src/progress.ts +74 -122
  38. package/.pi/extensions/pi-workflow-engine/src/provider-usage-limit.ts +189 -0
  39. package/.pi/extensions/pi-workflow-engine/src/replay-path-identity.ts +48 -0
  40. package/.pi/extensions/pi-workflow-engine/src/research-contract.ts +89 -0
  41. package/.pi/extensions/pi-workflow-engine/src/research-evidence.ts +289 -0
  42. package/.pi/extensions/pi-workflow-engine/src/resume-context.ts +701 -0
  43. package/.pi/extensions/pi-workflow-engine/src/review/code-review-orchestration.ts +49 -0
  44. package/.pi/extensions/pi-workflow-engine/src/review/github-pr-comments.ts +75 -16
  45. package/.pi/extensions/pi-workflow-engine/src/review/review-actions.ts +83 -17
  46. package/.pi/extensions/pi-workflow-engine/src/review/review-budget.ts +45 -0
  47. package/.pi/extensions/pi-workflow-engine/src/review/review-fix-workflow.ts +117 -0
  48. package/.pi/extensions/pi-workflow-engine/src/review/review-handoff.ts +14 -66
  49. package/.pi/extensions/pi-workflow-engine/src/review/review-issues.ts +38 -12
  50. package/.pi/extensions/pi-workflow-engine/src/review/review-report.ts +42 -0
  51. package/.pi/extensions/pi-workflow-engine/src/review/review-results-flow.ts +18 -22
  52. package/.pi/extensions/pi-workflow-engine/src/review/review-results-viewer.ts +128 -56
  53. package/.pi/extensions/pi-workflow-engine/src/review/review-session-coordinator.ts +153 -0
  54. package/.pi/extensions/pi-workflow-engine/src/review/review-snapshot.ts +294 -0
  55. package/.pi/extensions/pi-workflow-engine/src/review-diff-target.ts +130 -0
  56. package/.pi/extensions/pi-workflow-engine/src/session-identity.ts +6 -0
  57. package/.pi/extensions/pi-workflow-engine/src/structured-output.ts +32 -0
  58. package/.pi/extensions/pi-workflow-engine/src/tool-capabilities.ts +44 -0
  59. package/.pi/extensions/pi-workflow-engine/src/tool-source-identity.ts +150 -0
  60. package/.pi/extensions/pi-workflow-engine/src/tree-fingerprint.ts +401 -0
  61. package/.pi/extensions/pi-workflow-engine/src/types.ts +87 -25
  62. package/.pi/extensions/pi-workflow-engine/src/ui/dynamax-editor-decoration.ts +220 -0
  63. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-format.ts +26 -6
  64. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-inspector.ts +88 -46
  65. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-result-renderer.ts +7 -70
  66. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-viewer-layout.ts +51 -0
  67. package/.pi/extensions/pi-workflow-engine/src/ui/workflow-widget.ts +12 -67
  68. package/.pi/extensions/pi-workflow-engine/src/unknown-error.ts +8 -0
  69. package/.pi/extensions/pi-workflow-engine/src/usage.ts +124 -16
  70. package/.pi/extensions/pi-workflow-engine/src/workflow-advisory-utils.ts +23 -3
  71. package/.pi/extensions/pi-workflow-engine/src/workflow-execution.ts +121 -0
  72. package/.pi/extensions/pi-workflow-engine/src/workflow-module.ts +19 -1
  73. package/.pi/extensions/pi-workflow-engine/src/workflow-run-background.ts +72 -0
  74. package/.pi/extensions/pi-workflow-engine/src/workflow-run-controller.ts +354 -0
  75. package/.pi/extensions/pi-workflow-engine/src/workflow-run-history.ts +162 -0
  76. package/.pi/extensions/pi-workflow-engine/src/workflow-run-record.ts +632 -0
  77. package/.pi/extensions/pi-workflow-engine/src/workflow-run-store.ts +172 -0
  78. package/.pi/extensions/pi-workflow-engine/src/workflow-usage-limit-scheduler.ts +80 -0
  79. package/.pi/extensions/pi-workflow-engine/src/workflows.ts +30 -3
  80. package/.pi/extensions/pi-workflow-engine/src/worktree.ts +321 -43
  81. package/.pi/extensions/pi-workflow-engine/workflows/code-review.ts +62 -64
  82. package/.pi/extensions/pi-workflow-engine/workflows/diagnose.ts +17 -17
  83. package/.pi/extensions/pi-workflow-engine/workflows/perf-review.ts +15 -16
  84. package/.pi/extensions/pi-workflow-engine/workflows/refactor-scout.ts +15 -15
  85. package/.pi/extensions/pi-workflow-engine/workflows/research.ts +170 -0
  86. package/README.md +82 -207
  87. package/USAGE.md +295 -21
  88. package/package.json +9 -9
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.
@@ -27,12 +32,65 @@ Useful flags:
27
32
  /workflow:inspector # open the current or last workflow inspector
28
33
  /workflow code-review --result-viewer # explicitly open the findings viewer
29
34
  /workflow code-review --review-viewer # alias for --result-viewer
35
+ /workflow:results # reopen the latest code-review findings without rerunning
30
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
31
40
  /workflow code-review --budget=50000 # output-token ceiling for subagents
32
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
33
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
34
59
  ```
35
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
+
36
94
  ## Built-in workflows
37
95
 
38
96
  | Name | Purpose |
@@ -41,8 +99,26 @@ Useful flags:
41
99
  | `refactor-scout` | Finds small, safe refactor opportunities. |
42
100
  | `diagnose` | Investigates a bug, failing command, or regression. |
43
101
  | `perf-review` | Reviews a slow path or performance concern. |
102
+ | `research` | Gathers current external evidence, independently verifies claims, and returns a cited synthesis. |
44
103
 
45
- `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 that PR diff; otherwise it falls back to branch-vs-main/master or `HEAD~1`.
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."
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.
46
122
 
47
123
  ## Use Dynamax for custom workflows
48
124
 
@@ -68,26 +144,89 @@ Sticky mode and inspector shortcut:
68
144
  /workflow:dynamax status
69
145
  ```
70
146
 
71
- The workflow inspector is also registered as a first-class shortcut shown by `/hotkeys`; the default is `ctrl+shift+m`. `ctrl+o` is intentionally not used because pi already uses it for tool-output expansion and tree filtering.
147
+ The workflow inspector and code-review results viewer are also registered as first-class shortcuts shown by `/hotkeys`. The defaults are `ctrl+shift+m` for the inspector and `ctrl+shift+r` for the latest review results. `ctrl+o` is intentionally not used because pi already uses it for tool-output expansion and tree filtering.
72
148
 
73
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.
74
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
+
75
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.
76
176
 
77
- Configure the inspector shortcut by creating `~/.pi/agent/extensions/pi-workflow-engine.json`:
177
+ Configure either shortcut by creating `~/.pi/agent/extensions/pi-workflow-engine.json`:
78
178
 
79
179
  ```json
80
180
  {
81
181
  "shortcuts": {
82
- "inspector": "ctrl+shift+x"
182
+ "inspector": "ctrl+shift+x",
183
+ "results": "ctrl+shift+y"
83
184
  }
84
185
  }
85
186
  ```
86
187
 
87
- Set `"inspector": null` to disable the shortcut while keeping `/workflow:dynamax` and `/workflow:inspector` available.
188
+ Set either shortcut to `null` to disable it while keeping `/workflow:inspector` and `/workflow:results` available.
88
189
 
89
190
  With Dynamax enabled, the host agent usually calls the `workflow` tool with `script`: a one-off inline workflow tailored to your prompt. It can still call a saved workflow by `name` when one already fits.
90
191
 
192
+ ### Adaptive multi-pass authoring
193
+
194
+ A single fan-out is still the default when it can answer the question. When the first pass may reveal gaps, conflicts, weak claims, or missing evidence, an inline workflow can inspect those intermediate results and commission only the follow-up work the LLM says is needed:
195
+
196
+ ```ts
197
+ const firstPass = (await api.parallel(initialTasks)).filter((result) => result !== null);
198
+
199
+ const MAX_FOLLOW_UPS = 4;
200
+ const GapAnalysis = Type.Object({
201
+ items: Type.Array(
202
+ Type.Object({ question: Type.String(), reason: Type.String() }),
203
+ { maxItems: MAX_FOLLOW_UPS },
204
+ ),
205
+ });
206
+ const gaps = await api.agent(
207
+ `Identify only material gaps that require another agent:\n${JSON.stringify(firstPass)}`,
208
+ { schema: GapAnalysis, profile: "small" },
209
+ );
210
+
211
+ const followUpItems = gaps?.items.slice(0, MAX_FOLLOW_UPS) ?? [];
212
+ const followUps = followUpItems.length
213
+ ? (await api.parallel(
214
+ followUpItems.map((item) => () =>
215
+ api.agent(`Resolve this gap and cite evidence: ${JSON.stringify(item)}`, {
216
+ profile: "small",
217
+ }),
218
+ ),
219
+ )).filter((result) => result !== null)
220
+ : [];
221
+
222
+ return api.agent(
223
+ `Synthesize the first pass and any follow-ups:\n${JSON.stringify({ firstPass, followUps })}`,
224
+ { profile: "medium" },
225
+ );
226
+ ```
227
+
228
+ The structured gap-analysis result lets ordinary TypeScript decide whether a second pass exists. Put a hard `maxItems` bound on LLM-authored task lists and defensively slice before fan-out. Prefer conditionals and bounded loops over new iteration, quorum, graph, reduction, or retry primitives, and do not generate follow-up agents when the first pass is already sufficient.
229
+
91
230
  ## Workflow results
92
231
 
93
232
  Workflow results are rendered in pi with:
@@ -98,13 +237,69 @@ Workflow results are rendered in pi with:
98
237
  - recommendations;
99
238
  - next steps;
100
239
  - run stats when available;
101
- - 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.
102
241
 
103
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`.
104
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
+
105
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.
106
247
 
107
- 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.
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
+
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.
299
+
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.
301
+
302
+ Inline GitHub comments are available only for findings captured from a verified PR target. Before posting, the engine revalidates the reviewed snapshot and requires the current PR head to match; identical comments on that head are skipped.
108
303
 
109
304
  ### Resume a run
110
305
 
@@ -112,11 +307,33 @@ Every workflow result includes a run id. Resume with:
112
307
 
113
308
  ```text
114
309
  /workflow code-review --resume <run-id> HEAD~3
310
+ /workflow code-review --resume <run-id> --resume-edited HEAD~3
115
311
  ```
116
312
 
117
- The `workflow` tool exposes the same feature as `resumeFromRunId`. Resume replays completed `agent()` results from `.pi/.workflow-runs/<run-id>.jsonl` while the agent call index and prompt/options hash still match. After the first missing or changed call, the rest of the run executes live and writes a new journal under the new run id. Cached results do not add usage or budget spend for the resumed run.
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.
118
314
 
119
- Resume only caches completed `agent()` calls. It does not snapshot arbitrary workflow local variables or in-flight tool work. Keep prompts and agent options deterministic across reruns if you want cache hits.
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:
320
+
321
+ | Agent call | Default during resume | Override |
322
+ | --- | --- | --- |
323
+ | Shared workspace | Runs live | `resume: "read-only"` opts into repository-wide Git-visible replay; `resumeInputs` adds ignored paths under the workflow cwd |
324
+ | `isolation: "worktree"` | Replays when identity matches | `resume: "off"` forces a live run |
325
+
326
+ Use `resume: "read-only"` only when the shared agent is advisory. In Git repositories the engine resolves the repository root and binds replay to HEAD, staged and unstaged tracked changes, index modes, and bounded non-ignored untracked contents across that whole worktree, even when pi starts in a subdirectory. Add ignored or generated files under the workflow cwd with cwd-relative `resumeInputs`; explicitly named ignored paths are fingerprinted directly and cannot escape that cwd. The complete identity is checked before accepting a hit, after execution, and again after cleanup. A changed surface turns a hit into a live run and prevents unsafe recording. Tracked symlinks, submodules, and unsupported index states fail closed. Use `resume: "off"` when the call may inspect undeclared ignored files, external paths, services, environment, or clock state.
327
+
328
+ Journals use replay contract v2. A hit requires the same prompt/options and execution identity: repository-wide Git-visible state plus explicitly declared ignored inputs, workflow source provenance, coding-agent runtime version, effective system prompt/provider/model/thinking level, ordered selected skill contents, and ordered executable tool definitions plus source fingerprints. Unverifiable, cyclic, oversized, symlinked, submodule-backed, or mutable identity surfaces fail closed and run live. A tool-free structured agent uses a capability identity instead of hashing a workspace it cannot observe; an isolated agent binds replay to both the commit and tree objects of its exact prepared worktree baseline, including deterministic normalized snapshots for repositories with no commits. Each resumed run writes a fresh journal under its new run id, and cached results do not add usage or budget spend.
329
+
330
+ Cached values are revalidated before use: text must still be text, structured output must satisfy the current typebox schema, and an isolated patch must have consistent metadata and pass `git apply --check --binary` against its fresh baseline worktree. A malformed or stale value runs live.
331
+
332
+ Invalidations appear in progress output with a concise reason. Legacy v1 journals and early v2 entries without effective-session identity are parsed for compatibility but always miss. Git repositories with no commits and non-Git directories remain supported. Git control data and engine-owned workflow journals cannot be declared as inputs; if a Git-visible or explicit surface exceeds safety bounds, that call runs live.
333
+
334
+ Statically loaded built-ins fingerprint and revalidate their bounded extension source tree so imported helper changes invalidate replay, while inline workflows use the compiler-provided script fingerprint. Dynamically discovered and programmatic modules are intentionally non-replayable because their transitive runtime imports or captured closures cannot be bound to an immutable source snapshot.
335
+
336
+ Resume only caches completed `agent()` calls. It does not snapshot arbitrary workflow local variables, in-flight tool work, environment or clock state, external services, or generated inputs outside the captured repository/workflow/skill/tool surfaces. Use `resume: "off"` for calls that depend on those values, and keep prompts and options deterministic when you want cache hits.
120
337
 
121
338
  ## Author a saved workflow
122
339
 
@@ -142,13 +359,29 @@ export default async function run({ agent, parallel, phase, args }: WorkflowApi)
142
359
  phase("Find");
143
360
  const findings = compactResults(
144
361
  await parallel([
145
- () => agent(`Find correctness issues: ${args}`, { schema: Finding, tools: SEARCH_TOOLS, toolHints: SEARCH_TOOL_HINTS, thinkingLevel: "low" }),
146
- () => agent(`Find edge cases: ${args}`, { schema: Finding, tools: SEARCH_TOOLS, toolHints: SEARCH_TOOL_HINTS, thinkingLevel: "low" }),
362
+ () => agent(`Find correctness issues: ${args}`, {
363
+ schema: Finding,
364
+ tools: SEARCH_TOOLS,
365
+ toolHints: SEARCH_TOOL_HINTS,
366
+ profile: "small",
367
+ resume: "read-only",
368
+ }),
369
+ () => agent(`Find edge cases: ${args}`, {
370
+ schema: Finding,
371
+ tools: SEARCH_TOOLS,
372
+ toolHints: SEARCH_TOOL_HINTS,
373
+ profile: "small",
374
+ resume: "read-only",
375
+ }),
147
376
  ]),
148
377
  );
149
378
 
150
379
  phase("Synthesize");
151
- return agent(`Summarize: ${JSON.stringify(findings)}`, { thinkingLevel: "medium" });
380
+ return agent(`Summarize: ${JSON.stringify(findings)}`, {
381
+ profile: "medium",
382
+ tools: [],
383
+ resume: "read-only",
384
+ });
152
385
  }
153
386
  ```
154
387
 
@@ -158,18 +391,39 @@ Core primitives:
158
391
  | --- | --- |
159
392
  | `agent(prompt, opts)` | Runs one isolated subagent. With `schema`, returns validated structured data. |
160
393
  | `parallel(thunks)` | Runs thunks concurrently and waits for all; recoverable failures become `null` slots. |
394
+ | `parallel(thunks, { settled: true })` | Retains each success or recoverable failure as a serialisable discriminated result. |
161
395
  | `pipeline(items, ...stages)` | Runs each item through stages independently; a failed item becomes `null`. |
162
396
  | `phase(title)` / `log(message)` | Updates workflow progress UI. |
163
397
  | `progress(event)` | Emits counters, summaries, and lane items. |
164
398
  | `workflow(ref, args?)` | Runs another workflow inline as a sub-step and returns its result. |
165
399
 
166
- Set `thinkingLevel` on fan-out agents. Otherwise many subagents can inherit an expensive global reasoning level.
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.
167
403
 
168
- `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"]`.
404
+ Direct schema calls can catch the typed failure instead of receiving an unexplained `null`:
405
+
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"]`.
169
423
 
170
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.
171
425
 
172
- 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.
173
427
 
174
428
  ### Mutating agents in worktrees
175
429
 
@@ -179,7 +433,7 @@ Use `isolation: "worktree"` only for agents that should edit files. The agent ru
179
433
  const edit = await agent("Rename this helper and update its call sites.", {
180
434
  tools: ["read", "bash", "edit", "grep", "find", "ls"],
181
435
  isolation: "worktree",
182
- thinkingLevel: "medium",
436
+ profile: "medium",
183
437
  });
184
438
 
185
439
  if (edit.changed) {
@@ -188,11 +442,13 @@ if (edit.changed) {
188
442
  return { summary: edit.result };
189
443
  ```
190
444
 
191
- Isolated agents require the workflow `cwd` to be inside a git work tree. Outside git, the agent fails fast rather than silently mutating the shared directory. The return value is `{ result, patch, changed }`, where `result` is the normal text or structured `agent()` result and `patch` is a `git diff HEAD` patch. Worktree setup costs disk and git process time, so keep it opt-in for mutating/parallel-edit stages.
445
+ Isolated agents require the workflow `cwd` to be inside a git work tree. Outside git, the agent fails fast rather than silently mutating the shared directory. The return value is `{ result, patch, changed }`, where `result` is the normal text or structured `agent()` result and `patch` is a `git diff HEAD` patch. Worktree results are replayable by default; add `resume: "off"` when their inputs are not fully captured. Worktree setup costs disk and git process time, so keep it opt-in for mutating/parallel-edit stages.
446
+
447
+ Cleanup is a required finalizer. The engine attempts every registered worktree removal, retains failed paths for another cleanup attempt, and fails the workflow with the aggregated cleanup error if any worktree still cannot be removed. Advisory finalizers such as UI snapshots and journal pruning do not replace an otherwise valid workflow result.
192
448
 
193
449
  ### Compose workflows
194
450
 
195
- `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.
196
452
 
197
453
  ```ts
198
454
  export default async function run({ workflow }: WorkflowApi) {
@@ -232,8 +488,8 @@ export default async function run({ agent, parallel, phase, args }) {
232
488
  phase("Find");
233
489
  const Finding = Type.Object({ summary: Type.String() });
234
490
  const findings = await parallel([
235
- () => agent(`Find correctness issues: ${args}`, { schema: Finding, thinkingLevel: "low" }),
236
- () => 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" }),
237
493
  ]);
238
494
  return { summary: JSON.stringify(findings) };
239
495
  }
@@ -245,6 +501,7 @@ Inline rules:
245
501
  - default-export an async workflow function;
246
502
  - no imports or dynamic `import()`;
247
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;
248
505
  - add `skills: ["skill-name"]` per `agent()` call when a subagent should use a pi skill; no skills are exposed by default;
249
506
  - no extra exports or code after the default export.
250
507
 
@@ -258,10 +515,27 @@ Only tune these when a workflow is too slow, too expensive, or too noisy:
258
515
  | --- | --- |
259
516
  | `--concurrency=N` / `PI_WORKFLOW_CONCURRENCY=N` | Cap concurrent subagents. Default is `min(8, max(2, CPU count))`. |
260
517
  | `--parallel-limit=N` / `PI_WORKFLOW_PARALLEL_SUBMISSION_LIMIT=N` | Limit eager `parallel()` submission. |
261
- | `--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. |
262
522
  | `--perf` / `PI_WORKFLOW_PERF=1` | Include internal timing aggregates. Usage/cost totals are reported separately from perf. |
263
523
  | `PI_WORKFLOW_LANE_ITEM_LIMIT=N` | Cap retained progress lane items. |
264
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
+
265
539
  ## Common fixes
266
540
 
267
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.10.3",
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": [
@@ -35,7 +35,7 @@
35
35
  "image": "https://raw.githubusercontent.com/timbrinded/pi-workflow-engine/master/assets/preview.png"
36
36
  },
37
37
  "scripts": {
38
- "typecheck": "tsgo --noEmit",
38
+ "typecheck": "tsc --noEmit",
39
39
  "test": "bun test --timeout=30000",
40
40
  "test:changedlines": "bun test tests/changedlines.test.ts",
41
41
  "test:concurrency": "bun test tests/concurrency.test.ts",
@@ -46,17 +46,17 @@
46
46
  "bench:discovery": "bun run scripts/bench/discovery.ts",
47
47
  "bench:startup": "bun run scripts/bench/startup.ts",
48
48
  "bench:ui": "bun run scripts/bench/ui.ts",
49
- "prepublishOnly": "tsgo --noEmit && bun run test"
49
+ "prepublishOnly": "tsc --noEmit && bun run test"
50
50
  },
51
51
  "peerDependencies": {
52
- "@earendil-works/pi-agent-core": "0.79.10",
53
- "@earendil-works/pi-ai": "0.79.10",
54
- "@earendil-works/pi-coding-agent": "0.79.10",
55
- "@earendil-works/pi-tui": "0.79.10",
56
- "typebox": "1.3.0"
52
+ "@earendil-works/pi-agent-core": "*",
53
+ "@earendil-works/pi-ai": "*",
54
+ "@earendil-works/pi-coding-agent": "*",
55
+ "@earendil-works/pi-tui": "*",
56
+ "typebox": "*"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/node": "^22.20.0",
60
- "@typescript/native-preview": "^7.0.0-dev.20260623.1"
60
+ "typescript": "^7.0.2"
61
61
  }
62
62
  }