@tranhoangnguyen0310/pi-flow-external 1.9.0-external.0 → 2.0.0-external.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.
package/AGENTS.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  This fork changes the original pi-flow contract: `Agent` is not a generic Pi subagent launcher. It delegates only to external Claude Code, Codex CLI, and Antigravity harnesses.
6
6
 
7
- - Ordinary driver tools: `Agent`, read-only `external_help`, and optional `workflow`. `pi_flow_profile_create` is active only inside `/external profile create`.
7
+ - Ordinary driver tools: `Agent`, read-only `external_help`, `external_runs`, and optional `workflow`. `pi_flow_profile_create` is active only inside `/external profile create`.
8
8
  - User operations use `/external`; `/pi-flow-profile create` is a temporary deprecated alias.
9
- - Extension-owned concurrency, timeout, and global default-harness settings live in `$PI_CODING_AGENT_DIR/pi-flow-external/settings.json`. Profile backend/model/thinking metadata remains in `subagents/*.md`; project-specific harness defaults are deferred to issue #26.
9
+ - Extension-owned concurrency, timeout, and global default-harness settings live in `$PI_CODING_AGENT_DIR/pi-flow-external/settings.json`. Profile backend/model/thinking metadata remains in `subagents/*.md`. A trusted project may override `defaultHarness` via `.pi/pi-flow-external/settings.json` (that key only, read-only to the extension); explicit call harness > project default > global default.
10
10
  - Every `Agent` call requires `description`, `prompt`, and either `role` with optional `harness` (`agy`, `claude`, or `codex`) or the legacy exact-profile `subagent_type`. The selectors cannot be combined. Without `harness`, use the global `defaultHarness` setting (initially `agy`).
11
11
  - Valid profiles come from `~/.pi/agent/subagents/*.md` and set `backend: claude`, `backend: codex`, or `backend: agy`. Use matching names such as `claude-*`, `codex-*`, or `agy-*`; the assisted creator enforces that convention.
12
12
  - A default roster ships with the extension and seeds once on session start: five code-oriented roles (explorer, planner, implementer, reviewer, qa) plus the generalist worker, one storage profile per backend (18 files, but six advertised roles). Seeding never overwrites existing files and respects later deletions. Roles outside the default roster (such as debugger) are user-created via `/external profile create`.
@@ -16,6 +16,7 @@ This fork changes the original pi-flow contract: `Agent` is not a generic Pi sub
16
16
  - External backends use their own tools and permission mechanisms. Codex tiers map to its `--sandbox` axis. Claude falls back to `--permission-mode auto` when its effective UID is 0 because Claude refuses bypass mode under root. Execution lanes (implementer, debugger, qa, worker) require shell command authority to inspect repositories and run tests; on Claude (where headless edit auto-denies all Bash commands), execution lanes maintain a danger floor so agents are not artificially handcuffed. Antigravity (`agy`) has no granular headless permission mode — its default sandbox denies even read-only tools — so every agy run is unsandboxed (`--dangerously-skip-permissions`) and `readonly`/`edit` on agy are advisory profile-body instructions, not a boundary. Run them only in trusted repositories and state whether the task is read-only or may edit files.
17
17
  - Children receive no parent history by default. `Agent` and workflow `agent()` can opt into `context: {mode: "recent", turns: N}` (last N user turns, including the current one) or `{mode: "full"}` (available post-compaction conversation). Snapshots exclude system instructions, thinking, tool-result metadata, and pending calls; unsupported content/images and more than 1 MiB fail explicitly. Use the smallest sufficient snapshot plus a clear task, absolute paths, and read-only/edit intent. Shared context goes to the external harness and private local evidence; avoid unnecessary sensitive history. `resume` continues an existing child and cannot be combined with sharing. Workflow children select from one frozen parent snapshot, and replay fingerprints include the transferred context.
18
18
  - Backend-native nested agents may use a different workspace. Include explicit absolute paths and required context when asking an external backend to delegate further.
19
+ - `Agent` and `workflow` block by default; `background: true` returns a stable handle after validation/registration. Background work is owned by the originating session, not by the launching tool call or a daemon. Blocking-call interruption cancels work; wait interruption only stops waiting. Orderly session shutdown requests cancellation with bounded cleanup. A crash or unconfirmed shutdown leaves unfinished evidence interrupted/uncertain; restart never adopts live work.
19
20
 
20
21
  ## Delegation transparency invariants
21
22
 
@@ -23,7 +24,8 @@ This fork changes the original pi-flow contract: `Agent` is not a generic Pi sub
23
24
  - `unsandboxed external CLI` and `external host access` disclose the real execution boundary. Never present a read-only prompt as permission enforcement: on agy every run is unsandboxed regardless of tier, so the profile body — not the tier — is what asks the agent to stay read-only.
24
25
  - Keep direct intent visible during execution. Workflow access belongs once at the workflow level, not on every child row.
25
26
  - Parent-context sharing is a disclosure, not a silent optimization: the intent card names the mode before launch, and receipts name the mode and shared/requested turns. Shared conversation content leaves for the external harness and lands in local evidence, so never describe sharing as internal or free.
26
- - Keep default progress bounded and human-readable. Expanded output may reveal existing record paths, backend-event counts, workflow IDs, and journal paths.
27
+ - Keep default progress bounded and human-readable. Expanded terminal output shows bounded canonical output and a full-ID `/external runs` route; record paths, backend-event counts, workflow IDs, and journal paths remain advanced evidence.
28
+ - `/external runs` must use the same registry/readers as `external_runs`. Every hidden workflow child and truncated output/diagnostic page needs a cursor-backed navigation path; never add a silent hard cap.
27
29
  - Progress snapshots drive live presentation; persisted summaries and event logs remain the durable evidence source. Do not create a second UI-only record format.
28
30
 
29
31
  ## Receipt and evidence invariants
@@ -34,10 +36,13 @@ This fork changes the original pi-flow contract: `Agent` is not a generic Pi sub
34
36
  - Settings retention automatically prunes eligible completed records beyond `maxRunRecords`; active, interrupted, incomplete, and damaged records are not eligible.
35
37
  - Structured nested-agent activity may extend the wall-clock deadline once, by one fresh base timeout, capped at twice the original deadline.
36
38
  - Do not automatically retry failed or aborted external runs. Preserve the receipt and retry only when the user asks. Exception: the agy backend retries once on infrastructure-classified failures (auth, eligibility, network); the retry is disclosed in the receipt details (`retries`, `retryOf`) and never applies to agent-level failures, aborts, or timeouts.
39
+ - `external_runs` is session/project scoped. `list` pages runs and workflow roots; `inspect` pages summaries/output/diagnostics; `wait` returns outcomes only for the selected one/any/all target set and never cancels pending work; `cancel` targets one stable ID and preserves its reason. No routine run event sends a parent message or notification.
37
40
 
38
41
  ## Workflow contract
39
42
 
40
- `workflow` remains trusted JavaScript orchestration over the same external-only role roster. Every workflow `agent()` child uses the same `role`/optional `harness` resolution as `Agent`, with legacy exact-profile `subagent_type` available as an escape hatch.
43
+ `workflow` remains trusted JavaScript orchestration over the same external-only role roster. Its first statement declares `meta.apiVersion: 1`; missing/unsupported versions fail before child launch. Every workflow `agent()` child uses the same `role`/optional `harness` resolution as `Agent`, with legacy exact-profile `subagent_type` available as an escape hatch. Successful calls return their value; failed, cancelled, and timed-out calls throw structured catchable child errors. Explicitly handled errors permit siblings to finish; escaping errors fail the workflow and drain active siblings.
44
+
45
+ Replay is explicit through a persisted `scriptPath` plus `resumeFromRunId`. Reuse only the longest unchanged successful prefix; changed or unsuccessful calls and their suffix execute again. Never describe script recomposition as making child reruns free or side-effect-free. There is no live steering or automatic repaired-script retry.
41
46
 
42
47
  Use workflows for requested fan-out or multi-agent orchestration across Claude/Codex/Antigravity lanes. Do not route native Pi subagents through `workflow`.
43
48
 
@@ -52,5 +57,6 @@ Use workflows for requested fan-out or multi-agent orchestration across Claude/C
52
57
  ## Verification and release
53
58
 
54
59
  - Run `npm run check`, `npm pack --dry-run --json`, and `npm audit --omit=dev --audit-level=high` before release.
55
- - Follow `docs/field-testing.md` for real-backend checks and `docs/releasing.md` for versioning, npm authentication, prerelease tags, 2FA, and registry verification.
60
+ - Follow `docs/field-testing.md` for real-backend checks and `docs/releasing.md` for the automated release flow, versioning, trusted publishing, and registry verification.
61
+ - Releases are automated: merging a PR that bumps the version (labelled `release:patch|minor|major|prerelease`, or `release:none` to skip) tags the commit, publishes to npm via OIDC trusted publishing, and creates the GitHub release. `release:none` PRs must not change shipped files without a bump; CI enforces the label/version/CHANGELOG contract.
56
62
  - Never republish an existing npm version or force-push release history.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,57 @@
2
2
 
3
3
  All notable changes to pi-flow external are documented here.
4
4
 
5
+ ## Unreleased
6
+
7
+ ## [2.0.0-external.0] - 2026-09-14
8
+
9
+ Child observation and workflow-aware supervision. Full design: `docs/plans/2026-09-14-child-observation-and-supervision-design.md`.
10
+
11
+ ### Breaking
12
+
13
+ - Workflows must declare `meta.apiVersion: 1`. Unversioned or unsupported scripts are rejected before any child launches, with recomposition guidance; one current contract, no legacy failure mode.
14
+ - `agent()` throws a structured, catchable `ChildRunError` (outcome, run ID, reason, output/diagnostic references) for failed, cancelled, or timed-out children instead of returning `null`. Composition helpers no longer swallow child failures; unhandled errors terminate the workflow and cancel remaining children. Errors escaping user `catch` blocks propagate.
15
+ - Replay is a new explicit attempt with longest unchanged successful-prefix reuse; historical cancellations do not carry forward, and replay evidence from another project or an incompatible API contract is rejected.
16
+
17
+ ### Added
18
+
19
+ - Background (session-owned) `Agent` and `workflow` execution: runs survive tool-call returns and parent turns; interrupting a wait stops waiting only; closing the session cancels its work. Blocking calls keep interruption-cancels semantics.
20
+ - `external_runs` tool: `list` (session/project scoped), `inspect` (summary/output/diagnostics with bounded pages and opaque cursors), `wait` (one/any/all selected runs; outcome-only, no routine wake-ups; `all` escalates on unhandled workflow failure), `cancel` (scoped child/workflow, requested vs confirmed distinguished).
21
+ - Stable run IDs from queueing through evidence retrieval, including cancelled-while-queued runs.
22
+ - Readable partial and final child output recovered from run evidence across failure, cancellation, and timeout for all three backends, with preliminary/final/interrupted labels.
23
+ - Interactive `/external runs` navigation: run list, every workflow child, paged output/diagnostics, and selected-run cancellation; expanded receipts show bounded canonical output and freshness.
24
+ - Run listings show process-started vs first-activity, activity freshness, and interrupted/uncertain state for crashed or restarted sessions — never falsely `running`.
25
+ - POSIX process-tree termination on cancellation (group SIGTERM→SIGKILL regardless of leader exit) and bounded shutdown draining with honest uncertainty reporting.
26
+
27
+ ### Fixed
28
+
29
+ - Failed executable launches no longer recorded as `process started`; preallocated run records settle on resume-validation failure; discarded workflow chain rejections (including `undefined`) cannot yield successful completion; agy streamed deltas no longer duplicate the canonical result; live vs durable evidence states are reconciled for inspection; cancelled cleanup siblings remain discoverable in workflow journals.
30
+
31
+ ### Notes
32
+
33
+ - Windows process-tree termination is covered by mocked `taskkill` tests only. Real-provider field checks are opt-in per `docs/field-testing.md`.
34
+
35
+ ## [1.10.0-external.1] - 2026-09-12
36
+
37
+ Automated releases, adapted from [pi-bro](https://github.com/tranhoangnguyen03/pi-bro)'s pipeline.
38
+
39
+ ### Added
40
+
41
+ - Automated releases: PR CI validates release metadata (version bump, matching `release:` label, lockfile, CHANGELOG section), and merging a bump PR tags the commit, publishes to npm via OIDC trusted publishing, and creates the GitHub release. `release:none` skips. A daily sync-check watches for npm/GitHub drift.
42
+
43
+ ## [1.10.0-external.0] - 2026-09-12
44
+
45
+ Lets a trusted project pin its own default external harness, closing [#26](https://github.com/tranhoangnguyen03/pi-flow-external/issues/26).
46
+
47
+ ### Added
48
+
49
+ - Project default-harness override: `<project>/.pi/pi-flow-external/settings.json` with `defaultHarness` sets the default external harness for trusted projects only. Precedence is unchanged elsewhere: an explicit call `harness` wins, then the trusted project default, then the global setting. The file is read-only to the extension, accepts `defaultHarness` only, and invalid or untrusted overrides are ignored with disclosed warnings — a role without a profile on the effective harness still fails with an actionable error instead of silently switching harnesses.
50
+ - `/external settings` reports the effective `defaultHarness` and its source (`(project: <path>)` or `(global)`), plus the project-override location and any project-file warnings.
51
+
52
+ ### Fixed
53
+
54
+ - Delegating to agy on an older Antigravity CLI now fails with an actionable hint instead of Go's raw `flag provided but not defined: -input-format` usage dump: the error names the unsupported flag, the agy 1.1.15+ requirement for `--input-format stream-json`, and the `agy update` remedy, closing [#36](https://github.com/tranhoangnguyen03/pi-flow-external/issues/36).
55
+
5
56
  ## [1.9.0-external.0] - 2026-09-08
6
57
 
7
58
  Lets the parent decide how much of its own conversation an external child starts with, closing [#30](https://github.com/tranhoangnguyen03/pi-flow-external/issues/30).
package/CONTEXT.md CHANGED
@@ -8,11 +8,13 @@ This package is a fork of pi-flow whose `Agent` and `workflow` tools are reserve
8
8
  - **Native Pi subagent:** A subagent exposed by Pi's native subagent system. This fork intentionally does not route it through `Agent`.
9
9
  - **Agent call:** A direct external delegation selected by `role` and optional `harness`, or by legacy exact-profile `subagent_type`.
10
10
  - **Parent context:** An opt-in frozen text snapshot: `none` (default), `recent` with last N user turns including the current turn, or `full` available post-compaction conversation. It is background for a new external conversation, not a native session clone, system-prompt inheritance, or guaranteed cache reuse. Sharing excludes thinking and pending calls and cannot be combined with child `resume`. Workflow children share one invocation-time snapshot; prior child outputs remain explicit inputs.
11
- - **Workflow call:** Trusted JavaScript orchestration that may fan out several explicit external `agent()` calls.
11
+ - **Workflow call:** Trusted JavaScript orchestration beginning with `meta.apiVersion: 1` that may fan out several explicit external `agent()` calls. Each child returns a value or throws a catchable `ChildRunError`; escaping child errors fail the workflow and drain siblings.
12
+ - **Background run:** A validated, registered `Agent` or `workflow` invocation that returns a stable handle while work remains owned by the originating session. It is not a daemon or cross-session job.
13
+ - **Run supervision:** `external_runs` list/inspect/wait/cancel over stable IDs. Wait observes selected terminal outcomes without cancelling pending work; output and diagnostics use opaque cursors.
12
14
  - **Delegation intent:** The backend, profile, task label, profile purpose, and workspace shown to the user before and during direct execution.
13
15
  - **Access disclosure:** A visible statement of effective external CLI access and the external-host boundary; it does not create a sandbox or read-only guarantee.
14
16
  - **Evidence ID:** The short terminal reference to a persisted external run.
15
- - **Expanded receipt:** On-demand record or workflow-journal paths plus bounded evidence metadata.
17
+ - **Expanded receipt:** Bounded canonical output, full run navigation, and advanced record or workflow-journal evidence.
16
18
  - **Successful receipt:** A zero-exit run with a recognized backend terminal-success event and a non-empty result.
17
19
  - **Complete failure evidence:** The backend failed, but its event log and summary were persisted consistently.
18
20
  - **Incomplete record:** Local evidence is missing, malformed, or internally inconsistent; it must not be reported as trustworthy merely because the backend status says `done`.
@@ -27,7 +29,7 @@ The split is global and intentional to avoid tool ambiguity across projects. The
27
29
 
28
30
  ## User control surface
29
31
 
30
- User operations are namespaced under `/external`: status, Doctor, settings, profiles, profile creation, profile clean-up, workflows, runs, and help. Extension-owned concurrency, timeout, and global default-harness settings live in `$PI_CODING_AGENT_DIR/pi-flow-external/settings.json`; profiles remain authoritative for downstream backend/model/thinking metadata. Project-specific default harnesses are deferred to issue #26.
32
+ User operations are namespaced under `/external`: status, Doctor, settings, profiles, profile creation, profile clean-up, workflows, interactive run navigation, durable run summary/pruning, and help. `/external runs` uses the same registry/readers as `external_runs`, including every cursor-paged workflow child and output/diagnostic page. Extension-owned concurrency, timeout, and global default-harness settings live in `$PI_CODING_AGENT_DIR/pi-flow-external/settings.json`; profiles remain authoritative for downstream backend/model/thinking metadata. A trusted project may override only `defaultHarness`.
31
33
 
32
34
  ## Design stance
33
35
 
@@ -37,6 +39,8 @@ Role resolution is mechanical, not model-routed: a profile whose name begins wit
37
39
 
38
40
  The always-visible parent guidance is limited to a compact role catalog and essential routing/safety facts. Catalog availability reflects configured profiles, not CLI installation or authentication. `external_help` supplies descriptions, permission details, workflow APIs/examples, and trust-aware saved-workflow discovery only when requested.
39
41
 
42
+ Workflow replay is explicit and successful-prefix-only. A persisted script resumed with `resumeFromRunId` reuses the longest unchanged prefix whose fingerprints and outcomes are successful; the first changed or unsuccessful call and its suffix run again. Script recomposition is cheap, but child execution can cost money or repeat side effects. There is no automatic repaired-script replay, completion-order winner selection, or live steering.
43
+
40
44
  Applied to Antigravity (`agy`), that stance is absolute: the harness offers no granular headless permission mode — its default sandbox (`proceed-in-sandbox`) hard-denies even read-only tools like `read_url_content`, and `--dangerously-skip-permissions` is the only unsandboxed mode. So every agy run is unsandboxed, and `readonly`/`edit` on agy profiles are advisory instructions carried by the profile body, never an enforced boundary. We disclose that plainly (`unsandboxed external CLI`) rather than pretend a read-only tier restrains what the harness will actually allow.
41
45
 
42
46
  ## Known inelegance
@@ -46,4 +50,4 @@ A standardized role roster needs one file per role per backend (e.g. `claude-qa`
46
50
 
47
51
  ## Evidence boundary
48
52
 
49
- Normal external runs write best-effort local records under `~/.pi/agent/pi-flow-external/runs/` unless `PI_FLOW_EXTERNAL_RUNS_DIR` overrides it. The TUI shows short evidence IDs by default and exposes record/journal paths only through expanded output. Redaction is best-effort. Settings retention automatically prunes eligible completed records while preserving active, interrupted, incomplete, and damaged records. Failed/aborted runs are not retried automatically, except one agy retry for infrastructure-classified failures (disclosed via receipt `retries`/`retryOf`).
53
+ Normal external runs write best-effort local records under `~/.pi/agent/pi-flow-external/runs/` unless `PI_FLOW_EXTERNAL_RUNS_DIR` overrides it. The TUI shows short evidence IDs by default and exposes bounded output, full run navigation, and record/journal paths through expanded output. Redaction is best-effort. Settings retention automatically prunes eligible completed records while preserving active, interrupted, incomplete, and damaged records. Failed/aborted runs are not retried automatically, except one agy retry for infrastructure-classified failures (disclosed via receipt `retries`/`retryOf`). Blocking-call interruption cancels owned work; wait interruption does not. Graceful session shutdown requests cancellation with bounded drain. Crash/unconfirmed shutdown leaves unfinished records interrupted or uncertain, with no restart takeover or guaranteed retrospective process termination.
package/README.md CHANGED
@@ -6,11 +6,12 @@ External agent delegation for [pi](https://github.com/earendil-works/pi) through
6
6
  - [Codex CLI](https://github.com/openai/codex) profiles with `backend: codex`
7
7
  - Antigravity profiles with `backend: agy`
8
8
 
9
- The ordinary driver has three tools (`workflow` can be disabled):
9
+ The ordinary driver has four tools (`workflow` can be disabled):
10
10
 
11
11
  - `Agent` resolves and runs one external role.
12
12
  - `workflow` orchestrates multiple external roles with trusted JavaScript.
13
13
  - `external_help` returns role details, permission behavior, or workflow guidance on demand.
14
+ - `external_runs` lists, inspects, waits for, and cancels session-owned runs.
14
15
 
15
16
  `Agent` and `workflow` accept external roles with an optional harness override. Use pi's native subagent system for Pi-backed agents. The `pi_flow_profile_create` finalizer is active only during `/external profile create`.
16
17
 
@@ -96,7 +97,9 @@ All user commands use the `/external` namespace:
96
97
  | `/external profile create` | Create and smoke-test a profile |
97
98
  | `/external profile clean-up` | Archive retired pi-flow default profiles |
98
99
  | `/external workflows` | List saved workflows |
99
- | `/external runs` | Summarize recorded external runs |
100
+ | `/external runs` | Interactively browse current-session runs, every workflow child, paged output/diagnostics, and cancellation |
101
+ | `/external runs summary` | Summarize durable run records |
102
+ | `/external runs --prune` | Prune eligible completed run records |
100
103
  | `/external help` | Show the command reference |
101
104
 
102
105
  `/external doctor` verifies CLI availability, not provider authentication.
@@ -205,18 +208,43 @@ Workspace /path/to/project
205
208
 
206
209
  The `Context` line appears only when the parent shares conversation content, so extra data leaving for the external harness is visible before the run. Completed rows summarize what was actually shared (`context recent 4/5 turns`).
207
210
 
208
- Completed rows show a short evidence identifier and result preview. Press **Ctrl+O** (the default tool-expansion binding) to reveal the local record path plus structured backend-event count:
211
+ Completed rows show a short evidence identifier and result preview. Press **Ctrl+O** (the default tool-expansion binding) to reveal bounded canonical output, its full run ID, a `/external runs` navigation hint, and advanced local evidence details:
209
212
 
210
213
  ```text
211
214
  ✓ Claude Code(claude-explorer, Map repository architecture) 42s evidence 8f21a004 -> Architecture mapped.
215
+ Final output
216
+ Architecture mapped.
217
+ Run run_... · /external runs for full paged output and diagnostics
212
218
  Evidence ~/.pi/agent/pi-flow-external/runs/run_... · 15 backend events
213
219
  ```
214
220
 
215
- Workflows show access once at the workflow level, retain done/active/queued/failed counts, and expose child evidence plus the workflow journal when expanded. Raw backend events remain in local records rather than flooding the default terminal view.
221
+ Workflows show access once at the workflow level, retain done/active/queued/failed counts, and expose bounded final output plus the workflow journal when expanded. Hidden child rows remain reachable through `/external runs`. Active rows report last-activity freshness independently of the spinner. Raw backend events remain in local records rather than flooding the default terminal view.
222
+
223
+ ## Background runs and supervision
224
+
225
+ `Agent` and `workflow` are blocking by default. Add `background: true` to return a stable `run_...` or `wf_...` handle after validation and registration while the originating Pi session continues to own the work:
226
+
227
+ ```ts
228
+ Agent({
229
+ description: "Long repository audit",
230
+ prompt: "Audit /absolute/repo read-only.",
231
+ role: "reviewer",
232
+ background: true,
233
+ });
234
+ ```
235
+
236
+ Use `external_runs` with these actions:
237
+
238
+ - `list`: current session/project runs; use `cursor` for run pages and `workflowCursor` for workflow pages. `workflowRunId` filters children of one workflow.
239
+ - `inspect`: `runId`, `view: "summary" | "output" | "diagnostics"`, and optional opaque `cursor`/`limitBytes`. Follow `nextCursor` to avoid truncation.
240
+ - `wait`: one `runId` or selected `runIds`, with `mode: "any" | "all"`. It returns terminal outcomes plus still-pending IDs; an unsuccessful workflow returns early even in `all` mode. It never chooses a winner or cancels pending work.
241
+ - `cancel`: one `runId` and optional reason. Whole-workflow cancellation stops active children; targeted child cancellation remains a catchable workflow outcome. Cancellation does not roll back edits or other side effects.
242
+
243
+ Interrupting a blocking `Agent`/`workflow` call cancels its work. Interrupting `external_runs wait` stops only that wait. Background work survives its launching tool return and ordinary parent turns, but not the owning session: orderly session shutdown requests cancellation and waits for bounded cleanup. This is not a daemon. After a host crash or unconfirmed shutdown, unfinished evidence is `interrupted_or_uncertain`; restart restores evidence access, never live ownership or guaranteed retrospective process termination. No routine activity wakes the parent, and live steering is not supported.
216
244
 
217
245
  ## Workflow usage
218
246
 
219
- The `workflow` tool runs trusted JavaScript that calls one or more external roles and returns a JSON-serializable result. Every `agent()` child uses the same `role`/optional `harness` resolution as direct `Agent` calls, with legacy exact `subagent_type` also supported.
247
+ The `workflow` tool runs trusted JavaScript that calls one or more external roles and returns a JSON-serializable result. Its first statement must be the current declaration `export const meta = { apiVersion: 1, name, description }`; missing or unsupported versions fail before any child launches. Every `agent()` child uses the same `role`/optional `harness` resolution as direct `Agent` calls, with legacy exact `subagent_type` also supported.
220
248
 
221
249
  Saved workflows are discovered on demand through `external_help({ topic: "workflow" })`; project `.pi/workflows` entries are included only when Pi reports the project trusted.
222
250
 
@@ -226,7 +254,9 @@ Example request:
226
254
  Use the workflow tool to ask role "explorer" on harness "claude" for an architecture map and role "reviewer" on harness "codex" for a risk review, then synthesize their findings.
227
255
  ```
228
256
 
229
- Direct `Agent` calls and workflow children share the same concurrency and timeout controls. Workflow `agent(prompt, { role, context: { mode: "recent", turns: 5 } })` accepts the same context modes. Every child selects from one parent snapshot frozen at workflow invocation; earlier child results must still be passed explicitly. Replay fingerprints include the transferred context, so changes invalidate cached results.
257
+ Direct `Agent` calls and workflow children share the same concurrency and timeout controls. Workflow `agent(prompt, { role, context: { mode: "recent", turns: 5 } })` accepts the same context modes. Every current-version `agent()` returns its value or throws a catchable `ChildRunError` with `runId`, `outcome` (`failed`, `cancelled`, or `timed_out`), `message`, and output/diagnostic references. Catch an optional failure explicitly; an uncaught child error fails the workflow and drains active siblings. `parallel` and `pipeline` preserve this contract and never convert failure to `null`.
258
+
259
+ Every child selects from one parent snapshot and effective settings frozen at workflow invocation; earlier child results must still be passed explicitly. `resumeFromRunId` is explicit replay for a persisted `scriptPath`: it reuses only the longest unchanged prefix of successful child calls. The API version, transferred context, prompt, selection, and relevant options participate in fingerprints. The first changed, failed, cancelled, or timed-out call and everything after it executes again. Recomposition is cheap, but rerun children may cost money or repeat side effects; the runtime never retries or replays a repaired script automatically.
230
260
 
231
261
  ## Permission tiers, budgets, and resume
232
262
 
@@ -260,7 +290,21 @@ Normally this resolves to `~/.pi/agent/pi-flow-external/settings.json`:
260
290
  }
261
291
  ```
262
292
 
263
- Version 1 and 2 files migrate on read: recognized keys carry over, missing `defaultHarness` becomes `agy`, unknown keys warn, and invalid values fall back per-key. `defaultHarness` is global only; project overrides are deferred to issue #26. `maxRunRecords` prunes the oldest completed run records at session start and via `/external runs --prune`; records still running or interrupted are never pruned, and `0` keeps everything.
293
+ Version 1 and 2 files migrate on read: recognized keys carry over, missing `defaultHarness` becomes `agy`, unknown keys warn, and invalid values fall back per-key. `maxRunRecords` prunes the oldest completed run records at session start and via `/external runs --prune`; records still running or interrupted are never pruned, and `0` keeps everything.
294
+
295
+ ### Project default-harness override
296
+
297
+ A trusted project can override the global `defaultHarness` without touching global settings or duplicating profiles. Create:
298
+
299
+ ```text
300
+ <project>/.pi/pi-flow-external/settings.json
301
+ ```
302
+
303
+ ```json
304
+ { "defaultHarness": "claude" }
305
+ ```
306
+
307
+ The override applies only when Pi marks the project trusted, supports `defaultHarness` only, and is never created or written by the extension. Precedence: an explicit `harness` in the call wins, then the trusted project default, then the global setting. `/external settings` reports the effective harness and its source; an untrusted or invalid project file is ignored with a warning, and a role that has no profile on the effective harness fails with an actionable error instead of silently switching harnesses. Edit the file and run `/reload`.
264
308
 
265
309
  Edit the file and run `/reload`. Startup flags override extension factory options, which override this file, which overrides built-in defaults.
266
310
 
@@ -306,7 +350,10 @@ A failed backend can still have complete diagnostic evidence. Treat `incompleteR
306
350
  - **Claude rejects `--dangerously-skip-permissions` under root:** reload the current extension version; root runs use Claude's `auto` permission mode.
307
351
  - **Nested agent cannot find the repository:** include the repository's absolute path and required context in the prompt.
308
352
  - **Child is missing earlier decisions:** share the smallest sufficient parent context (`context: { mode: "recent", turns: N }` or `{ mode: "full" }`), or restate the missing decisions in the prompt.
309
- - **Run failed with complete records:** inspect the run's `summary.json` and `events.ndjson`; do not retry automatically unless requested.
353
+ - **Workflow rejected before any child launched:** the script is missing or using an unsupported `meta.apiVersion` declaration. Recompose it starting with `export const meta = { apiVersion: 1, name, description }`; nothing ran, so nothing needs cleanup.
354
+ - **Run shows `interrupted_or_uncertain`:** the host exited before the run's termination was confirmed. Treat its evidence as interrupted — partial output may be readable via `/external runs` — but never resume live ownership after restart; start a new run or replay explicitly.
355
+ - **Inspection cursor fails as stale:** the run's content changed while paging (live updates or registry handoff). Restart the inspection from the first page; cursors are single-sequence continuation tokens.
356
+ - **Run failed with complete records:** read its output and diagnostics via `/external runs`, or inspect `summary.json`/`events.ndjson` directly; do not retry automatically unless requested.
310
357
  - **Sensitive content appears in evidence:** remove the affected run directory. Local redaction is not a secrecy boundary.
311
358
 
312
359
  ## Development
@@ -324,7 +371,9 @@ export PI_CODING_AGENT_DIR="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
324
371
  npm run e2e -- --backend claude
325
372
  npm run e2e -- --backend codex
326
373
  npm run e2e -- --backend agy
374
+ npm run e2e -- --backend claude --workflow
327
375
  npm run e2e -- --backend codex --workflow
376
+ npm run e2e -- --backend agy --workflow
328
377
  ```
329
378
 
330
379
  See [`docs/field-testing.md`](docs/field-testing.md) for provider checks and [`docs/releasing.md`](docs/releasing.md) for the release process.
@@ -39,15 +39,29 @@ Defaults:
39
39
 
40
40
  Override with `--model`, `--thinking`, `--root-model`, or `--root-thinking`. Use `--keep` only when evidence inspection is necessary; it preserves sensitive output and the temporary profile path printed by the runner.
41
41
 
42
- ## Workflow receipt
42
+ ## Supervised workflow receipt
43
43
 
44
- When workflow runtime, scheduling, or tool integration changes:
44
+ When workflow runtime, scheduling, supervision, or tool integration changes, run the affected backend; run all three before release:
45
45
 
46
46
  ```bash
47
+ npm run e2e -- --backend claude --workflow
47
48
  npm run e2e -- --backend codex --workflow
49
+ npm run e2e -- --backend agy --workflow
48
50
  ```
49
51
 
50
- This runs two children through one workflow and requires two complete receipts. One backend is enough because direct backend checks validate adapter-specific transport.
52
+ Each command declares `meta.apiVersion: 1`, starts a two-child workflow with `background: true`, waits for the selected workflow through `external_runs`, inspects its summary/output, requires two complete child receipts, and verifies the read-only fixture stayed clean. Forced multi-page cursor behavior remains covered by deterministic offline tests; this check exercises real workflow child handling without duplicating those semantics.
53
+
54
+ ## Change-triggered interruption and output check
55
+
56
+ When adapter cancellation, process-tree termination, partial output, or supervision changes, run the affected backend:
57
+
58
+ ```bash
59
+ npm run e2e -- --backend claude --interrupt
60
+ npm run e2e -- --backend codex --interrupt
61
+ npm run e2e -- --backend agy --interrupt
62
+ ```
63
+
64
+ The runner starts a background `Agent`, cancels its stable ID with an explicit reason, waits for its `cancelled` outcome, and asks `external_runs` for every available output and diagnostic page. A very early cancellation may legitimately have diagnostics but no assistant text; the durable receipt must still be `aborted`/`cancelled` with the exact reason. Do not retry a failure automatically. Use `--keep` for one deliberate evidence inspection, then remove the printed run root and temporary profile.
51
65
 
52
66
  ## Natural-language routing smoke
53
67
 
@@ -80,13 +94,18 @@ Local fixture tests own selection, boundary, and failure behavior; this check on
80
94
 
81
95
  Do not run damaged-record and expected-failure provider scenarios manually. Their behavior is deterministic and belongs in the local fixture tests.
82
96
 
97
+ ## Change-triggered project default-harness check
98
+
99
+ Run only when project default-harness resolution changes. In a fresh Pi session against a trusted read-only fixture containing `.pi/pi-flow-external/settings.json` with `"defaultHarness": "claude"`, verify `/external settings` reports `defaultHarness: claude (project: ...)`, delegate one read-only task with `role` only (no `harness`) and verify the receipt names a `claude-*` profile, then confirm an explicit `harness: "codex"` call still routes to codex. Repeat once in the same fixture with trust removed and confirm the override is ignored with a warning.
100
+
83
101
  ## Release minimum
84
102
 
85
103
  Before a runtime release:
86
104
 
87
105
  1. Run `npm run check`.
88
106
  2. Run all three direct backend receipts.
89
- 3. Run one workflow receipt.
90
- 4. Run the natural-language routing smoke only if role discovery, tool descriptions, or coordinator guidance changed.
91
- 5. Run the nested timeout check only if nested detection or timeout behavior changed.
92
- 6. Remove temporary evidence and profiles.
107
+ 3. Run all three supervised workflow receipts.
108
+ 4. Run interruption checks for adapters whose cancellation/output path changed.
109
+ 5. Run the natural-language routing smoke only if role discovery, tool descriptions, or coordinator guidance changed.
110
+ 6. Run the nested timeout check only if nested detection or timeout behavior changed.
111
+ 7. Remove temporary evidence and profiles.
package/docs/releasing.md CHANGED
@@ -1,70 +1,97 @@
1
1
  # Releasing to npm
2
2
 
3
- Release only from a clean, reviewed `main` commit. npm versions are immutable: never attempt to republish an existing version, and never force-push release history.
3
+ Releases are automated. Merging a PR that bumps `package.json`'s version tags
4
+ the commit, publishes to npm via OIDC trusted publishing (no npm token or 2FA
5
+ in CI), and creates the GitHub release. npm versions are immutable: never
6
+ republish an existing version, and never force-push release history.
4
7
 
5
- ## 1. Confirm repository and registry state
8
+ ## Versioning
6
9
 
7
- ```bash
8
- git switch main
9
- git pull --ff-only origin main
10
- git status --short
11
- npm whoami
12
- npm view @tranhoangnguyen0310/pi-flow-external dist-tags --json
13
- npm view @tranhoangnguyen0310/pi-flow-external versions --json
14
- ```
10
+ Versions are always `X.Y.Z-external.N`:
15
11
 
16
- Choose a version not present in the registry. Prerelease versions such as `1.0.10-external.5` require an explicit npm dist-tag at publish time.
12
+ - A core bump (patch/minor/major) resets the counter: `1.9.0-external.1` → `1.10.0-external.0`.
13
+ - A same-core publish increments it: `1.9.0-external.0` → `1.9.0-external.1`.
17
14
 
18
- ## 2. Bump without tagging
15
+ Bump on the PR branch with:
19
16
 
20
17
  ```bash
21
18
  npm version <new-version> --no-git-tag-version
22
- git diff -- package.json package-lock.json
23
19
  ```
24
20
 
25
- Do not create a Git tag until the package is confirmed in the registry.
21
+ Do not create Git tags manually; the release workflow owns them.
26
22
 
27
- ## 3. Run the release gate
23
+ ## The PR contract (CI-enforced)
28
24
 
29
- ```bash
30
- npm run check
31
- git diff --check
32
- npm pack --dry-run --json
33
- npm audit --omit=dev --audit-level=high
34
- ```
25
+ CI validates release metadata on every PR to `main`, and re-validates when
26
+ labels change:
35
27
 
36
- Inspect the dry-run manifest. Confirm the expected version and required files, including `index.ts`, `README.md`, runtime sources, `scripts/field-report.mjs`, and operational docs. Development E2E scripts and tests must not be shipped. Runtime vulnerabilities block release; do not use `npm audit fix --force` as an automatic release step.
28
+ - The version must be a clean bump of the published npm version (patch,
29
+ minor, major with `external.0`, or `prerelease` with `external.N+1`).
30
+ - Exactly one label matches the bump: `release:patch`, `release:minor`,
31
+ `release:major`, or `release:prerelease`. A no-release PR carries
32
+ `release:none` instead and must not bump the version.
33
+ - Changing shipped files (the `files` list in `package.json`, plus
34
+ `package.json`/`package-lock.json`) without a version bump fails.
35
+ - `package-lock.json` must carry the same version (run `npm install` after
36
+ bumping).
37
+ - `CHANGELOG.md` must have a `## [X.Y.Z-external.N] - YYYY-MM-DD` section for
38
+ the new version.
37
39
 
38
- Run the essential real-provider gate from [`field-testing.md`](field-testing.md): all three direct backends and one workflow. Also run its natural-language routing smoke when discovery or coordinator guidance changed, and its nested timeout scenario when nested detection or timeout behavior changed.
40
+ ## What merging does
39
41
 
40
- ## 4. Review and merge the version bump
42
+ `release.yml` runs on every push to `main`:
41
43
 
42
- Commit the bump and documentation/code changes on a branch, push it, and open a PR to `main`. Merge only after CI and read-only review have no Critical or Important blockers. Pull the merged commit locally and repeat the clean-tree/version check before publishing.
44
+ 1. **verify** — `npm run check`, `npm pack --dry-run --json`, and
45
+ `npm audit --omit=dev --audit-level=high` on the merged commit. The same
46
+ gate AGENTS.md requires locally.
47
+ 2. **release** — only when the version differs from npm's latest:
48
+ - tags `vX.Y.Z-external.N` and checks out the tagged tree, so publishing
49
+ always happens from the source the tag points at;
50
+ - publishes with `--provenance --ignore-scripts`, skipping if npm already
51
+ has the version;
52
+ - creates the GitHub release with the CHANGELOG section as notes and a
53
+ full-changelog compare link, only after npm serves the version.
43
54
 
44
- ## 5. Authenticate npm
55
+ Every step is idempotent: a failed run can be re-run and resumes at the first
56
+ missing artifact. Runs are serialized (`concurrency: release`).
45
57
 
46
- The coordinator's npm credential is independent from GitHub and backend CLI credentials.
58
+ ## One-time setup
47
59
 
48
- ```bash
49
- npm login --auth-type=web
50
- npm whoami
51
- ```
60
+ Already done or needed once, manually:
52
61
 
53
- Do not paste npm tokens, one-time passwords, or browser authentication URLs into issues, PRs, logs, or agent prompts.
62
+ - On npmjs.com, link `@tranhoangnguyen0310/pi-flow-external` as a trusted
63
+ publisher bound to repository `tranhoangnguyen03/pi-flow-external` and
64
+ workflow filename `release.yml`.
65
+ - Create the labels `release:patch`, `release:minor`, `release:major`,
66
+ `release:prerelease`, `release:none`.
67
+ - Prove trusted publishing without publishing: Actions → release → Run
68
+ workflow with `verify_only`. The `oidc-check` job exchanges an OIDC token
69
+ with npm and reports the claims npm will match.
54
70
 
55
- ## 6. Publish with an explicit tag
71
+ ## Before pushing a release PR
56
72
 
57
- For the package's current prerelease line:
73
+ Run the same gate CI will run, so the PR is green on arrival:
58
74
 
59
75
  ```bash
60
- npm publish --access public --tag latest
76
+ npm run check
77
+ git diff --check
78
+ npm pack --dry-run --json
79
+ npm audit --omit=dev --audit-level=high
61
80
  ```
62
81
 
63
- npm may require publish-time browser/2FA approval even after `npm login`. Open the URL printed by npm and complete approval. If the command exits with `EOTP`, verify that the version is still absent, finish authentication, and rerun the exact publish command. Do not bump again unless the registry actually accepted the version.
82
+ Inspect the dry-run manifest: expected version and files, including
83
+ `index.ts`, `README.md`, runtime sources, `scripts/field-report.mjs`, and
84
+ operational docs. Development E2E scripts and tests must not be shipped.
85
+
86
+ Run the essential real-provider gate from [`field-testing.md`](field-testing.md)
87
+ before merging: all three direct backends and one workflow, plus its
88
+ natural-language routing smoke when discovery or coordinator guidance changed,
89
+ and its nested timeout scenario when nested detection or timeout behavior
90
+ changed.
64
91
 
65
- ## 7. Verify the registry
92
+ ## After the release
66
93
 
67
- Registry metadata can take a few seconds to converge:
94
+ Confirm the registry:
68
95
 
69
96
  ```bash
70
97
  npm view @tranhoangnguyen0310/pi-flow-external@<new-version> version
@@ -72,11 +99,11 @@ npm view @tranhoangnguyen0310/pi-flow-external dist-tags --json
72
99
  npm view @tranhoangnguyen0310/pi-flow-external@<new-version> dist --json
73
100
  ```
74
101
 
75
- The explicit version and `latest` dist-tag must both resolve to the release. Compare the reported shasum/integrity with the successful publish notice when available.
102
+ `latest` must resolve to the release (automation publishes with the default
103
+ `latest` dist-tag; override only for an intentional non-latest channel).
76
104
 
77
- ## 8. Post-release check
78
-
79
- Install the exact published version into a temporary Pi agent directory so an older global installation cannot produce a false pass:
105
+ Install the exact published version into a temporary Pi agent directory so an
106
+ older global installation cannot produce a false pass:
80
107
 
81
108
  ```bash
82
109
  export VERIFY_AGENT_DIR="$(mktemp -d /tmp/pi-flow-release-check.XXXXXX)"
@@ -88,4 +115,31 @@ rm -rf "$VERIFY_AGENT_DIR"
88
115
  unset VERIFY_AGENT_DIR
89
116
  ```
90
117
 
91
- Confirm `pi list` shows the exact version and both commands are available. Keep resulting evidence private and remove the temporary agent directory afterward.
118
+ Confirm `pi list` shows the exact version and both commands are available.
119
+ Keep resulting evidence private and remove the temporary agent directory
120
+ afterward.
121
+
122
+ ## Drift watchdog
123
+
124
+ `sync-check.yml` runs daily and compares npm's latest with the latest GitHub
125
+ release. On drift above the pre-automation baseline (`1.9.0-external.0`) it
126
+ opens or comments on a "Release drift" issue and closes it once back in sync.
127
+ Fix drift by re-running the release workflow, never by manual publishing.
128
+
129
+ ## Emergency manual publish
130
+
131
+ Only when automation itself is broken. Follow the normal PR contract
132
+ (version, lockfile, CHANGELOG, review), then:
133
+
134
+ ```bash
135
+ git switch main && git pull --ff-only origin main && git status --short
136
+ npm whoami # npm login --auth-type=web if needed; npm may require publish-time 2FA
137
+ npm publish --access public --provenance --ignore-scripts
138
+ ```
139
+
140
+ Then create the tag and GitHub release exactly as `release.yml` would
141
+ (`vX.Y.Z-external.N`, CHANGELOG section as notes), verify the registry as
142
+ above, and file an issue about the broken automation. Do not paste npm
143
+ tokens, one-time passwords, or browser authentication URLs into issues, PRs,
144
+ logs, or agent prompts. If a publish attempt fails, verify whether the
145
+ registry accepted the version before retrying; never bump to retry.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tranhoangnguyen0310/pi-flow-external",
3
- "version": "1.9.0-external.0",
3
+ "version": "2.0.0-external.0",
4
4
  "description": "External Claude Code, Codex CLI, and Antigravity delegation for pi.",
5
5
  "type": "module",
6
6
  "main": "./index.ts",