Skip to content

feat(subagents): integrate the external pi-subagents package (engine swap + full UI integration) - #3

Merged
dreadster3 merged 2 commits into
mainfrom
integration/pi-subagents
Sep 28, 2026
Merged

dreadster3 merged 2 commits into
mainfrom
integration/pi-subagents

Conversation

@dreadster3

Copy link
Copy Markdown
Owner

Summary

Full integration of the external pi-subagents package, replacing pi-web's built-in subagent engine (merged in #1) plus the complete UI integration phase (merged in #2).

Engine swap (#1)

  • Removed the built-in subagent runtime (lib/subagent-*.ts, /api/subagents/settings, steer/abort routes, built-in profiles, SUBAGENT_CONTROLLER); legacy readers kept for old sessions
  • pi-web now respects a user-installed pi-subagents extension — no npm dependency, no package imports anywhere

UI integration (#2)

  • Agent catalog: builtin/package/user/project agents in the Agents panel with source badges, sourced from files only; differential-verified against the runtime's discoverAgentsAll() (zero semantic divergences)
  • Live sessions: pi-subagents child sessions grouped in the session tree, live progress (status · tool · elapsed · turns) via the async-status widget + 4 s poll, per-step join, orphans hidden, nested delete cascade
  • Schema-faithful editor: profiles authored in pi-subagents frontmatter (inherit* flags, systemPromptMode, excludeTools, extensions tri-state, async, allowedAgents incl. deny-all, timeouts, acceptanceRole, advertise); legacy files migrate on save; tool checkboxes enumerate the real builtin + extension tool registry; raw entries (mcp:server) round-trip instead of being stripped
  • Builtin controls: disable via agentOverrides.<name>.disabled (settings), with honest provenance (user/project override vs bulk disableBuiltins); duplicate/eject = verbatim shadowing copy per pi-subagents semantics
  • Agents tab: running agents by default, "Show completed" toggle
  • Prompt display for read-only builtin/package rows (byte-identical to the runtime's own extraction)

Every feature went through independent review cycles (implement → review → remediate → re-review), with differential probes against the installed pi-subagents 0.71.0. Demo mirror synced throughout (byte-identical copies + mock fixtures).

Verification

  • npx tsc --noEmit: 0 errors (root + demo)
  • eslint: clean
  • npm test (env -u PI_WEB_IDLE_TIMEOUT_MS): 1386/1387 — sole failure is the pre-existing environmental lib/skill-lock.test.mjs

Known documented divergences

Relative agentScanDirs resolution; agentExcludeDirs/wildcards; agentOverridesByProvider; stricter frontmatter parsing; runtime-throw vs graceful-degrade on invalid overrides; foreground-run progress relies on the mtime+liveness heuristic (package-side limitation).

dreadster3 and others added 2 commits September 26, 2026 13:40
…ubagents (#1)

Remove the built-in pi-web subagent engine entirely; subagent delegation
now comes from the user-installed pi-subagents package (a standard pi
extension, not an npm dependency). Pi Web no longer strips or manages it.

Removed:
- lib/subagent-{runtime,extension,queue,prompt,input,settings}.ts + tests
- /api/subagents/settings route (builtInEnabled/maxConcurrent settings)
- /api/subagents/[id] POST (steer/abort); route is GET-only legacy now
- built-in profiles (general-purpose/explore/plan) and their injection
- preferPiWebSubagentExtension stripping logic in rpc-manager

Kept:
- legacy session readers (pi-web:subagent metadata) so historical
  sessions keep rendering in the session tree and chat
- agent-profile file editor (/api/subagents/profiles GET/PUT/DELETE);
  pi-subagents reads/writes the same profile files
- SubagentToolDetails type relocated to lib/api-types.ts

AgentsConfig is now a pure profile editor; 8 dead i18n keys removed
(en/zh-CN/zh-TW). Demo mirror synced (pi-subagents 'subagent' tool entry,
rewritten tutorial prose, no removed-engine tools). New ADR 0006
supersedes ADRs 0003/0005; AGENTS.md and demo README updated.
…in the UI (#2)

* refactor(subagents): replace built-in engine with user-installed pi-subagents

Remove the built-in pi-web subagent engine entirely; subagent delegation
now comes from the user-installed pi-subagents package (a standard pi
extension, not an npm dependency). Pi Web no longer strips or manages it.

Removed:
- lib/subagent-{runtime,extension,queue,prompt,input,settings}.ts + tests
- /api/subagents/settings route (builtInEnabled/maxConcurrent settings)
- /api/subagents/[id] POST (steer/abort); route is GET-only legacy now
- built-in profiles (general-purpose/explore/plan) and their injection
- preferPiWebSubagentExtension stripping logic in rpc-manager

Kept:
- legacy session readers (pi-web:subagent metadata) so historical
  sessions keep rendering in the session tree and chat
- agent-profile file editor (/api/subagents/profiles GET/PUT/DELETE);
  pi-subagents reads/writes the same profile files
- SubagentToolDetails type relocated to lib/api-types.ts

AgentsConfig is now a pure profile editor; 8 dead i18n keys removed
(en/zh-CN/zh-TW). Demo mirror synced (pi-subagents 'subagent' tool entry,
rewritten tutorial prose, no removed-engine tools). New ADR 0006
supersedes ADRs 0003/0005; AGENTS.md and demo README updated.

* feat(subagents): surface live pi-subagents sessions and progress

Reconstruct parent/child relations for user-installed pi-subagents runs from
disk and the extension's async-status widget, mapping into the existing
relation.kind === "subagent" UI (session families, Agents panel) without a
rewrite. Legacy pi-web:subagent metadata keeps working unchanged.

- lib/pi-subagents-runs.ts: read async-subagent-runs/*/status.json across
  every pi-subagents temp root; map runner state to panel status.
- lib/pi-subagents-snapshot.ts: parse PI_SUBAGENT_ASYNC_JSON: widget lines
  (pure, shared with the demo).
- session-list-scanner: bounded nested enumeration of <projectDir>/<parentBase>
  child session.jsonl files, deduped, without touching artifacts.
- session-reader: derive subagent relations from the child layout, joining
  async run status for live state; foreground children read completed unless
  their parent session is live and the transcript was just written.
- AgentSessionPanel: show live current tool / elapsed / turn and tool counts
  from the widget snapshot, falling back to relation.status.
- i18n agentSwitcher.run.* + status.stopped; demo mock child session.

Verified on the real session tree: 55 pi-subagents children derived, 0
orphans, 26 legacy relations unchanged.

* feat(agents): show the pi-subagents agent catalog in the Agents panel

The panel could only edit profile files under ~/.pi/agent/agents and the
project dirs, so the 13 pi-subagents built-ins (oracle/advisor, scout,
worker, reviewer, ...) and package-provided agents were invisible even though
the runtime dispatches them.

lib/pi-subagents-catalog.ts reads the same files pi-subagents' own discovery
reads — the installed package's agents/, its package manifests, the user dirs
(PI_SUBAGENT_EXTRA_AGENT_DIRS, settings agentScanDirs, ~/.pi/agent/agents,
~/.agents) and the nearest project root's .agents and .pi/agents — without
importing the package (its exports map forbids src/*). It applies
subagents.agentOverrides, defaultModel/defaultProvider/defaultThinking, and
disableBuiltins, and marks same-name rows a higher-precedence source shadows.
It never throws: a missing package or malformed file means "no entry".

GET /api/subagents/catalog?cwd= reuses the profiles route's cwd validation.
AgentsConfig fetches it in parallel with profiles and renders read-only rows
grouped by source, leaving the editor untouched; a failed or empty catalog
falls back to today's profiles-only view.

lib/subagents.ts now discovers (and writes) project profiles at the nearest
project root rather than the session cwd, matching pi-subagents, so a session
opened in a subdirectory sees the same profiles the runtime loads.

The demo mirrors the new files byte-identically and answers the route from
mock/captured/subagent-catalog.json.

* fix(subagents): correct live pi-subagents progress, joins, orphans, delete cascade

Address the Phase 2b review findings for live pi-subagents child sessions:

- AppShell: drop the id/state-only update guard so label, activity and
  timestamps reach the Agents panel instead of freezing the progress line.
- ChatWindow/useAgentSession: apply the `subagent-async` widget in the busy
  reconcile branch, and poll wrapper state every 4s while the snapshot still
  has a non-terminal run (stops once terminal or the wrapper is gone) so
  detached runs refresh while the parent sits idle.
- session-reader: an async child takes its own step's status, not the run
  aggregate, and records the snapshot step node id (`stepRunId`) so a
  multi-step chain maps one run to many rows. Orphaned children keep a dangling
  `subagent` relation (parent id from the directory name) instead of surfacing
  as top-level sessions. `findSessionPathById` also walks nested
  `<parentBase>/**/session.jsonl` so cold deep links resolve.
- AgentSessionPanel: join snapshot nodes by `stepRunId`, then run id, then
  path/name substring; the shared, unit-tested `lib/pi-subagents-progress.ts`
  helper keeps each chain step's own progress and never lets a workflow
  aggregate overwrite a step row.
- DELETE /api/sessions/[id]: remove the session's `<parentBase>/` pi-subagents
  tree, and prune a deleted child's empty run/child directories.
- Nits: first-complete-line snapshot parse, split demo store line, drop the
  never-present totalTokens/totalCost fields, include `label` in the
  ChatWindow key, simplify the "(no messages)" description path.

Tests: new lib/pi-subagents-progress.test.mjs, AppShell.subagent-runs,
ChatWindow.subagent-poll, nested delete cascade + empty-dir prune, nested path
resolution, multi-step chain status/identity, orphan relation; updated panel,
runs, relations, reconcile and session-reader tests. Mirrored demo files stay
byte-identical apart from documented demo-only divergence.

* fix(subagents): normalize step statuses, gate and abort the 4s poll

- pi-subagents-runs: map the on-disk step spellings `pending`→`queued` and
  `completed`→`complete` like the package's own projection, and fall an
  unknown or absent step status back to the run state instead of `failed`.
- ChatWindow: only poll wrapper state while the tab is visible (the
  visibilitychange nudge fetches only when visible again) and abort the
  in-flight fetch on cleanup so a stale response cannot apply widgets.
- session-list-scanner/session-reader: share the `(no messages)` placeholder
  constant so the two cannot drift.

Tests: pin both step spellings + `pending` + unknown/absent fallback; pin the
visibility gate and abort controller in the subagent-poll source test. Demo
ChatWindow mirrors only the fix logic and keeps its documented divergence.

* fix(agents): align catalog discovery with pi-subagents and render project rows

Render the project-scope catalog group the panel already fetched but never
showed, and close the discovery fidelity gaps a reviewer verified live
against pi-subagents 0.71.0:

- apply defaults before overrides so model:false/thinking:false survive
- mirror the applyBuiltinOverrides bulk-disable ladder with override shields
- keep thinking:false as an explicit off the default cannot overwrite
- prune nested .git dirs during the agent walk
- align package enumeration with collectPackageSubagentPaths (project root
  package, installed package and settings roots, project-scope before
  user-scope)
- fold package: frontmatter into the runtime name
- document remaining intentional divergences and the un-gated project reads

* fix(agents): honor disableThinking, drop unrecognized overrides, dedupe builtins

The catalog now mirrors pi-subagents' builtin ladder for
subagents.disableThinking (project value suppresses the user value;
an override that sets thinking survives), drops override entries whose
fields are all unrecognized so they cannot shield a builtin, and keeps
only the first configured pi-subagents install for the builtin dirs so
a user+project install no longer duplicates every builtin row.

* feat(agents): author pi-subagents-format agent profiles

Reshape the agent-profile editor from the removed pi-web engine's schema onto
the installed pi-subagents frontmatter dialect (camelCase keys, raw tool
selectors, tri-state extensions). The old editor wrote keys pi-subagents
ignores and silently dropped mcp:/package tool names on save.

- lib/subagents.ts: new SubagentProfile; parse all pi-subagents keys, migrate
  legacy load_skills/load_extensions/inherit_context/run_in_background/
  prompt_mode/disallowed_tools/max_turns-era files, drop retired keys on save,
  keep tools raw, validate the unions and positive ints.
- app/api/subagents/tools: GET enumerates builtin + extension tools via
  createAgentSessionServices (no session started), cached 60s per cwd.
- AgentsConfig: grouped collapsible sections, tri-state tools/extensions,
  raw-entry chips, no enable switch (agentOverrides owns that).
- i18n en/zh-CN/zh-TW parity; demo mirrors + fixtures.

* fix(agents): preserve presence-sensitive profile fields

Review findings F1–F8 against the pi-subagents frontmatter dialect:

- add the missing `agents.allowNestedSubagents` key to all three locales
  and the demo mirrors so the Launch toggle stops rendering a raw key.
- reject `toolTimeoutMs > 2147483647` on save, the bound pi-subagents
  throws on, and cap the number input.
- keep `allowedAgents` presence-sensitive: a bare key now parses to `[]`
  with an `allowedAgentsDenyAll` marker, and the editor's new "Deny all
  descendants" checkbox writes `allowedAgents: ''` instead of dropping it.
- parse `thinking: false` as `"off"` so an explicit off survives a save.
- normalize the legacy `skill` alias into `skills` and drop the alias.
- bound the tools-route per-cwd cache to 32 entries.
- reject commas in the raw-entry inputs with an inline note.
- reset the raw-entry inputs on profile switch, create, and duplicate.

* fix(subagents): mirror skill-alias precedence, reset raw entries on delete, doc managed keys

* feat(agents): default the panel to running agents with a Show completed toggle

The Agents panel listed every subagent session running-first, so a family
with many finished runs buried the live ones. Default the list to active
subagents (running/starting) and add a header checkbox to reveal terminal
rows, composing with the existing search filter.

A single subagentStatus() helper owns the badge/status precedence; the
list-level status map calls it with the same inputs, so the filter and the
row badge cannot disagree. The empty state distinguishes "no matches" from
"no running agents" and offers the toggle when terminal rows are hidden.

Adds agentSwitcher.showCompleted and agentSwitcher.noRunning (en/zh-CN/zh-TW)
and mirrors the component and locale files into demo/.

* feat(agents): disable and duplicate read-only pi-subagents agents

Built-in and package catalog rows were read-only: pi-subagents owns their
enable/disable through `subagents.agentOverrides.<name>.disabled` in settings,
and `eject` copies a bundled agent into an editable file, but nothing in the
panel wrote either.

- lib/subagent-overrides.ts: setSubagentOverrideDisabled writes only the user
  settings file (the `<agentDir>/settings.json` the SDK's FileSettingsStorage
  derives). Disable sets `disabled: true`; enable deletes that key and prunes an
  empty override entry, `agentOverrides`, then `subagents` like pi-subagents'
  own enable action. Everything else survives via a targeted JSON mutation and
  the shared atomic write, keeping the file mode. PUT /api/subagents/overrides
  exposes it with the profiles route's cwd allow-list and JSON/origin checks.
- lib/subagents.ts: ejectSubagentProfile copies a catalog file verbatim into the
  global or project agent dir, conflicts on an existing name (409), and returns
  the parsed profile. POST /api/subagents/eject requires the source to be a file
  the catalog discovered for the cwd and defaults the name to the source's
  canonical runtime name so the copy shadows it.
- AgentsConfig: the read-only catalog detail gets a Disabled switch that PUTs
  the override then refetches profiles + catalog, and a Duplicate flow that
  picks a scope, prefills the canonical name, and POSTs the eject. A
  project-scope disable locks the switch with a hint (project wins in the
  disable ladder); the row's effective disabled state is never re-derived.
- i18n keys in en/zh-CN/zh-TW + demo mirrors; demo mock answers both routes
  from in-memory state.

Tests: override write semantics (create/cleanup/idempotence/pruning/permissions)
and eject copy semantics (verbatim/conflict/name/validation/both scopes);
overrides PUT and eject route happy paths, 409, and security rejections;
component source tests for the toggle and duplicate wiring.

* fix(i18n): add missing agentSwitcher.status.queued label

* fix(agents): correct disable provenance, eject scope, symlink writes

Review findings on the disable/duplicate built-in controls:

- Disable provenance (was wrong): the catalog row's `overriddenBy` is file
  shadowing, not the reason a row is disabled. Add `disabledSource`
  ({ scope, via }) to `AgentCatalogAgent`, set whenever the effective
  `disabled === true`: the builtin ladder records a project/user override or
  `disableBuiltins` bulk at its scope, and a custom row applies user then
  project distinctly. The same-name winner's `disabled` + `disabledSource`
  are projected onto every shadowed row, since the winner is what the runtime
  dispatches. AgentsConfig locks the switch only when the user-scope toggle
  could not undo the disable (bulk at either scope, or a project override);
  a user override stays switchable. i18n hint keys reworked to scope/via-aware
  copy in en/zh-CN/zh-TW plus mirrors.
- Symlinked settings write-through: resolve the settings path with
  realpathSync before the atomic rename so a dotfile-managed link survives.
- Eject scope: `ejectSubagentProfile` and POST /api/subagents/eject now only
  accept `builtin`/`package` sources, matching pi-subagents' handleEject; the
  UI hides Duplicate on user/project rows.
- Failed-parse cleanup: delete the written copy before returning the 400.
- Documentation: AGENTS.md notes the symlink-safe unlocked writer (parity with
  pi-subagents) and the disable-provenance semantics.

Demo fixture/mock surface `disabledSource` for disabled rows (bulk, user
override, project override) so the hint path is demonstrable.

Tests updated/added: catalog disabledSource + shadow propagation, symlinked
settings write-through, eject scope rejection + failed-parse cleanup, and the
UI predicate source test.

* feat(agents): show the system prompt for read-only catalog agents

* chore: trigger CI (review completed, no changes requested)

---------

Co-authored-by: pi-web-agent <[email protected]>
@dreadster3
dreadster3 merged commit 009dcb7 into main Sep 28, 2026
4 checks passed
@dreadster3
dreadster3 deleted the integration/pi-subagents branch September 28, 2026 01:53
@github-actions github-actions Bot mentioned this pull request Oct 5, 2026
This was referenced Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant