Skip to content

feat(packages): pi-delegation + pi-subagents — portable pure-pi subagent layer - #302

Merged
Rinat S (rsolmano) merged 13 commits into
mainfrom
subagents-packages
Aug 28, 2026
Merged

feat(packages): pi-delegation + pi-subagents — portable pure-pi subagent layer#302
Rinat S (rsolmano) merged 13 commits into
mainfrom
subagents-packages

Conversation

@SBOne-Kenobi

@SBOne-Kenobi Rustam Sadykov (SBOne-Kenobi) commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator

Summary

Layer 1/3 of the subagents stack: the portable pure-pi delegation layer — two new packages that let a pi agent session spawn and drive child agent sessions, with no ThinkRail dependency. ThinkRail host embedding lands in layer 2 and UI integration in layer 3.

Stack: #302 (this)#303 (host) ← #304 (web).

Changes

  • packages/pi-delegation — the delegation core: createChild plus a run-owning handle per child AgentSession, hidden-child lineage, per-parent concurrency, an in-memory run registry, lifecycle events, turn caps, cancellation, and per-run usage/outcome reporting.
  • Runtime compatibility — exact parent ModelRuntime reuse remains preferred for embedders. The standalone fallback mirrors opaque provider registrations from the parent extension context through Pi's public ModelRegistry APIs before each spawn and removes stale mirrors. Each parent lineage owns its fallback runtime and mirror set, so synchronizing one parent cannot mutate another parent's active children.
  • packages/pi-subagents — the zero-config Agent + get_subagent_result extension over pi-delegation: trusted definition discovery, foreground/parallel/background runs, bounded results, completion follow-ups, lineage checks, and session-scoped fallback cleanup.
  • Lifecycle consistency — entering running now updates the snapshot status, details status, and onUpdate before the run-started event.
  • Specs and architecture — both package specs carry their boundaries and decision logs; architecture decision Context and session live info #16 records the portable package layer while keeping ThinkRail host composition in the next PR.

Testing

  • bun run test — all 14 workspace test tasks green; pi-delegation 29 pass and pi-subagents 24 pass.
  • bun run typecheck — all 14 workspace typecheck tasks green.
  • bun run check:deps, bun run check:boundaries, bun run check:seams, and bun run lint — green.
  • Synthetic regressions — zero-config subagents delegate through a provider registered by another extension, stale registrations are removed, and different parents' fallback runtimes remain isolated.
  • Black-box Central smoke with anthropic/claude-haiku-4-5 — standalone fallback foreground delegation and background completion/follow-up both passed.

@github-actions

github-actions Bot commented Aug 26, 2026

Copy link
Copy Markdown

🌐 Vibecoding website preview

Preview https://pr-302.thinkrail-vibecoding.pages.dev
Commit c2d977b

This comment updates in place on every push that touches the vibecoding website or shared build inputs.

@github-actions

github-actions Bot commented Aug 26, 2026

Copy link
Copy Markdown

🌐 Website preview

Preview retired when this pull request closed.

@SBOne-Kenobi Rustam Sadykov (SBOne-Kenobi) changed the title subagents packages feat(packages): pi-delegation + pi-subagents — portable pure-pi subagent layer Aug 26, 2026

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread architecture.md Outdated
Comment thread packages/pi-delegation/src/service.ts Outdated

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-subagents/src/extension.ts
Comment thread packages/pi-subagents/src/extension.ts Outdated

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-delegation/src/service.ts Outdated
jetbrains-air[bot]
jetbrains-air Bot previously approved these changes Aug 27, 2026

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved — ready to merge.

jetbrains-air[bot]
jetbrains-air Bot previously approved these changes Aug 27, 2026

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved — ready to merge.

Rinat S (rsolmano) pushed a commit that referenced this pull request Aug 28, 2026
…nding, error results keep details

Review findings on the subagents stack (#302/#303/#304):
- pi-delegation: a run's finalText/usage derive from a baseline captured
  before prompt() (per-run deltas), never the child session's cumulative
  totals — a reusable child no longer reports stale text or double-counted
  usage on sequential runs.
- pi-delegation: modelRuntime accepts a live provider function resolved per
  createChild, so an embedder with generational runtimes (Central
  connect/disconnect) never pins children to the generation the service was
  created under.
- pi-subagents: an error outcome's thrown tool result keeps the run's final
  details — stashed by toolCallId, re-injected via a tool_result override —
  so a failed run's transcript stays openable.
All three pinned by regression tests verified to fail on the unfixed code.
Rinat S (rsolmano) pushed a commit that referenced this pull request Aug 28, 2026
…eage, parent-retained runtime, stash sweep

Review findings on #302/#303 plus same-class hardening:
- pi-subagents: the zero-config fallback service disposes its parent's
  children on session_shutdown (a vanilla-pi background child no longer
  outlives its session); embedder-injected services stay untouched.
- pi-subagents: get_subagent_result enforces lineage — another parent's
  child on the shared service takes the unknown-id path (pinned, bites).
- pi-delegation: ParentContext optionally carries the parent's retained
  ModelRuntime; createChild prefers it over the service binding, so an
  embedder with per-session runtime generations gives children their
  parent's generation (pinned, bites). Host half lands in layer 2.
- pi-subagents: the errored-details stash is swept on turn_end and
  session_shutdown so an aborted finalization cannot strand entries.

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-delegation/src/service.ts Outdated

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved — ready to merge.

…ent layer

pi-delegation: delegation core — child AgentSessions spawned from a parent
session (hidden children, per-scope store, concurrency semaphore, run
registry). pi-subagents: the Agent tool extension over it (foreground await +
background completion injection, per-call definition discovery, built-in
roles). Architecture decision #14 records the layering; AGENTS.md lists the
packages. Squashed from subagent-research-planning (layer 1/3).
…nding, error results keep details

Review findings on the subagents stack (#302/#303/#304):
- pi-delegation: a run's finalText/usage derive from a baseline captured
  before prompt() (per-run deltas), never the child session's cumulative
  totals — a reusable child no longer reports stale text or double-counted
  usage on sequential runs.
- pi-delegation: modelRuntime accepts a live provider function resolved per
  createChild, so an embedder with generational runtimes (Central
  connect/disconnect) never pins children to the generation the service was
  created under.
- pi-subagents: an error outcome's thrown tool result keeps the run's final
  details — stashed by toolCallId, re-injected via a tool_result override —
  so a failed run's transcript stays openable.
All three pinned by regression tests verified to fail on the unfixed code.
…eage, parent-retained runtime, stash sweep

Review findings on #302/#303 plus same-class hardening:
- pi-subagents: the zero-config fallback service disposes its parent's
  children on session_shutdown (a vanilla-pi background child no longer
  outlives its session); embedder-injected services stay untouched.
- pi-subagents: get_subagent_result enforces lineage — another parent's
  child on the shared service takes the unknown-id path (pinned, bites).
- pi-delegation: ParentContext optionally carries the parent's retained
  ModelRuntime; createChild prefers it over the service binding, so an
  embedder with per-session runtime generations gives children their
  parent's generation (pinned, bites). Host half lands in layer 2.
- pi-subagents: the errored-details stash is swept on turn_end and
  session_shutdown so an aborted finalization cannot strand entries.
…ry at session shutdown

A detached run's continuation no longer sends its completion (triggerTurn)
into a session that received session_shutdown — a wasted provider turn racing
teardown. Parent-turn aborts still deliver. Pinned by emitting session_shutdown
through the public extension runner; harness resolveParent now projects any
registered live session so a dedicated session can spawn the child.
…iting any abort in disposeChildrenOf

Aborting a running child frees its semaphore slot; with the sequential
mark-and-abort loop suspended on a later abort, a still-unmarked queued
sibling won the slot and issued a provider request mid-cascade. Marking the
captured set first lands it on the existing disposed-before-start guard.
Pinned with two running + one queued child (limit 2) — the loop must suspend
on a second abort for the release to beat the marks.
…ildren

ThinkRail-Todo: 01a047b5-14db-7a7e-8538-09b72f147467/t_5fdc507c7af6
ThinkRail-Todo: 01a047b5-14db-7a7e-8538-09b72f147467/t_083134006835

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-delegation/src/service.ts Outdated
@rsolmano
Rinat S (rsolmano) dismissed stale reviews from Olga Lavrichenko (OLavrik) and themself via ede47bb August 28, 2026 20:12

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-delegation/src/service.ts

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes — please address the blocking inline finding.

Comment thread packages/pi-delegation/src/service.ts

@jetbrains-air jetbrains-air Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved — ready to merge.

@rsolmano
Rinat S (rsolmano) merged commit 8bca48c into main Aug 28, 2026
8 checks passed
@rsolmano
Rinat S (rsolmano) deleted the subagents-packages branch August 28, 2026 21:44
Iaroslav (Rick) Postovalov (CommanderTvis) added a commit to CommanderTvis/thinkrail that referenced this pull request Aug 31, 2026
The engine stops being pi-in-process and becomes any ACP agent the host
launches as a child and speaks JSON-RPC to over stdio. A fatal agent or
provider fault now kills one supervised child, not the host.

packages/acp — the ACP client, and the only client-side package allowed to
name an ACP type. connection/ spawns and negotiates (tolerating an agent
that writes a banner before its first message), client/ implements what we
offer agents (fs, terminals, permissions, elicitation, MCP over the ACP
channel), translate/ is the single seam where protocol shapes become
ThinkRail shapes, registry/ resolves the published agent registry, and
testing/ validates a committed frame corpus against the SDK's own schema
so an SDK bump fails here rather than in production.

packages/contracts — chatProtocol.ts replaces piProtocol.ts: ThinkRail's own
transcript model, a delta event union with three write modes, and a
ChatCapabilities record carrying one field per UI-visible affordance, so
panels read a negotiated record instead of probing the agent. The package
now imports nothing at all.

packages/pi-agent — the bundled first-party agent wrapping pi, launched as
`thinkrail acp-pi`. It is the only package permitted to import pi, and it
carries the four signals ACP has no words for (retry, compaction, queue,
steering) in a namespaced _meta.

packages/server — the host: an ACP session manager over its own append-only
transcript store, so history, search, jump-to-message and reopen work with
every agent rather than only those implementing ACP's optional session/load.
Credentials belong to the agent now; auth is the policy layer over the six
ACP credential operations plus the Central lifecycle the host must own.

apps/web — renders the ThinkRail transcript model, never an ACP shape, and
gates every control on the negotiated capability record.

scripts/check-architecture.ts makes the module boundaries a gate rather than
a convention: the ACP SDK stops at five sub-modules of packages/acp plus
packages/pi-agent, and pi stops at packages/pi-agent.

Rebased onto main. Carried through unchanged: the bottom workbench panel,
terminal reservations, Pino host logging, browser history navigation, the
subprocess budget, the Remix icon pack, the numeric spacing scale, the
gh-CLI Open PR module and the Cloudflare website.

Re-landed on the ACP wire, where the shapes differ:

- Mid-stream queue editing. The host owns the steering queue, so
  session.clearQueue and session.removeQueued need none of the
  drain-and-re-queue emulation pi's all-or-nothing clearQueue forced.
  queue_changed carries the queued texts beside the depths, and
  session.abort restores them; SessionQueueContent holds PromptContent so an
  image-bearing queue restores losslessly.
- The native /compact command moves to the agent side. ACP already carries a
  command list, so packages/pi-agent advertises compact and intercepts it in
  session/prompt — no session.compact wire method, and any agent that
  advertises its own compact command gets the same affordance for free.
- Plan review (reviewer + reflector sessions, the verdict gate, the auto-fix
  cycle) runs on AgentSessionManager: sessions are created through it and
  configured by config-option value, sends are synchronous so the rollback
  keys off a throw rather than an acceptance window, settlement is observed
  as turn_settled, and notices land as durable notice markers. The reviewer
  policy is agent-neutral on the wire — reviewModel/reviewEffort are opaque
  config-option values, not a pi Model.
- Extensions get a real theme (JetBrains#316): plainTextTheme moves into
  packages/pi-agent beside the bridge it serves, replacing an empty object
  cast, and an extension failure is named to the client before the session
  registers.

Rebased again onto the Electrobun desktop packaging (JetBrains#317). The desktop app
drives the same host, so `createServer` now answers `{ port, stop, shutdown }`
with the ACP teardown behind `shutdown()`, `bootHost` runs under upstream's
host-ownership lease, and `apps/cli` takes the shared build-support and
artifact-probe modules. `artifactProbes.ts` is ported to the ACP wire — the
model catalog is read from a session's config options, Central status from
`agent.providers`, the trash probe seeds a host transcript, and the retired
`provider.loginStart` OAuth leg becomes an `agent.authMethods` probe that the
CLI smoke runs beside its own `acp-pi` initialize legs. Upstream's
`check:boundaries` table learns the ACP layout (`packages/acp`,
`packages/pi-agent`, and the server/cli edges into them); it runs alongside
`check:arch`, which keeps policing the pi and ACP-SDK import invariants.

Rebased again onto the subagent layer (JetBrains#302/JetBrains#303/JetBrains#304), frontend-local
workbench layouts (JetBrains#338), newest-first chat order (JetBrains#327) and Try-again
recovery (JetBrains#345).

- pi-delegation and pi-subagents are pi packages, so the delegation host
  moves from packages/server into packages/pi-agent and scopes child
  sessions by an encoding of the worktree cwd — the agent has no workspace
  ids. The Agent card registers through the existing tool-renderer seam
  unchanged; the pi-only subagent-completion custom message drops, because
  under ACP the child's result already arrives on the Agent tool call.
- subagent.getTranscript becomes the first ThinkRail _ext round-trip: the
  host asks the agent over dev.thinkrail.v1/subagent/transcript and the
  agent answers with ChatMessages, so the child transcript reaches the UI
  without the host owning sessions it never created.
- Layouts leave the wire with upstream: layout.get/layout.replace, the
  layout module and the layout.changed channel are gone, and the workbench
  frame is the web's own state.
- The desktop's generated entry registers only the trash helpers now; the
  bundled pi runtime belongs to the agent process, which registers its own.
- Try-again attaches to an error notice, since notices replace the pi-era
  error turn.

Deliberately not carried: the reviewer model/effort pickers in Settings (ACP
has no session-less config read to source the options from — the auto-fix
toggle stays), and useTranscriptSync's revision fence (this transcript model
is one fold over one event log, so a reloaded transcript is the live object
graph by construction).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BFWLfHUiKpPbiAHxiD75BJ
Iaroslav (Rick) Postovalov (CommanderTvis) added a commit to CommanderTvis/thinkrail that referenced this pull request Aug 31, 2026
The engine stops being pi-in-process and becomes any ACP agent the host
launches as a child and speaks JSON-RPC to over stdio. A fatal agent or
provider fault now kills one supervised child, not the host.

packages/acp — the ACP client, and the only client-side package allowed to
name an ACP type. connection/ spawns and negotiates (tolerating an agent
that writes a banner before its first message), client/ implements what we
offer agents (fs, terminals, permissions, elicitation, MCP over the ACP
channel), translate/ is the single seam where protocol shapes become
ThinkRail shapes, registry/ resolves the published agent registry, and
testing/ validates a committed frame corpus against the SDK's own schema
so an SDK bump fails here rather than in production.

packages/contracts — chatProtocol.ts replaces piProtocol.ts: ThinkRail's own
transcript model, a delta event union with three write modes, and a
ChatCapabilities record carrying one field per UI-visible affordance, so
panels read a negotiated record instead of probing the agent. The package
now imports nothing at all.

packages/pi-agent — the bundled first-party agent wrapping pi, launched as
`thinkrail acp-pi`. It is the only package permitted to import pi, and it
carries the four signals ACP has no words for (retry, compaction, queue,
steering) in a namespaced _meta.

packages/server — the host: an ACP session manager over its own append-only
transcript store, so history, search, jump-to-message and reopen work with
every agent rather than only those implementing ACP's optional session/load.
Credentials belong to the agent now; auth is the policy layer over the six
ACP credential operations plus the Central lifecycle the host must own.

apps/web — renders the ThinkRail transcript model, never an ACP shape, and
gates every control on the negotiated capability record.

scripts/check-architecture.ts makes the module boundaries a gate rather than
a convention: the ACP SDK stops at five sub-modules of packages/acp plus
packages/pi-agent, and pi stops at packages/pi-agent.

Rebased onto main. Carried through unchanged: the bottom workbench panel,
terminal reservations, Pino host logging, browser history navigation, the
subprocess budget, the Remix icon pack, the numeric spacing scale, the
gh-CLI Open PR module and the Cloudflare website.

Re-landed on the ACP wire, where the shapes differ:

- Mid-stream queue editing. The host owns the steering queue, so
  session.clearQueue and session.removeQueued need none of the
  drain-and-re-queue emulation pi's all-or-nothing clearQueue forced.
  queue_changed carries the queued texts beside the depths, and
  session.abort restores them; SessionQueueContent holds PromptContent so an
  image-bearing queue restores losslessly.
- The native /compact command moves to the agent side. ACP already carries a
  command list, so packages/pi-agent advertises compact and intercepts it in
  session/prompt — no session.compact wire method, and any agent that
  advertises its own compact command gets the same affordance for free.
- Plan review (reviewer + reflector sessions, the verdict gate, the auto-fix
  cycle) runs on AgentSessionManager: sessions are created through it and
  configured by config-option value, sends are synchronous so the rollback
  keys off a throw rather than an acceptance window, settlement is observed
  as turn_settled, and notices land as durable notice markers. The reviewer
  policy is agent-neutral on the wire — reviewModel/reviewEffort are opaque
  config-option values, not a pi Model.
- Extensions get a real theme (JetBrains#316): plainTextTheme moves into
  packages/pi-agent beside the bridge it serves, replacing an empty object
  cast, and an extension failure is named to the client before the session
  registers.

Rebased again onto the Electrobun desktop packaging (JetBrains#317). The desktop app
drives the same host, so `createServer` now answers `{ port, stop, shutdown }`
with the ACP teardown behind `shutdown()`, `bootHost` runs under upstream's
host-ownership lease, and `apps/cli` takes the shared build-support and
artifact-probe modules. `artifactProbes.ts` is ported to the ACP wire — the
model catalog is read from a session's config options, Central status from
`agent.providers`, the trash probe seeds a host transcript, and the retired
`provider.loginStart` OAuth leg becomes an `agent.authMethods` probe that the
CLI smoke runs beside its own `acp-pi` initialize legs. Upstream's
`check:boundaries` table learns the ACP layout (`packages/acp`,
`packages/pi-agent`, and the server/cli edges into them); it runs alongside
`check:arch`, which keeps policing the pi and ACP-SDK import invariants.

Rebased again onto the subagent layer (JetBrains#302/JetBrains#303/JetBrains#304), frontend-local
workbench layouts (JetBrains#338), newest-first chat order (JetBrains#327) and Try-again
recovery (JetBrains#345).

- pi-delegation and pi-subagents are pi packages, so the delegation host
  moves from packages/server into packages/pi-agent and scopes child
  sessions by an encoding of the worktree cwd — the agent has no workspace
  ids. The Agent card registers through the existing tool-renderer seam
  unchanged; the pi-only subagent-completion custom message drops, because
  under ACP the child's result already arrives on the Agent tool call.
- subagent.getTranscript becomes the first ThinkRail _ext round-trip: the
  host asks the agent over dev.thinkrail.v1/subagent/transcript and the
  agent answers with ChatMessages, so the child transcript reaches the UI
  without the host owning sessions it never created.
- Layouts leave the wire with upstream: layout.get/layout.replace, the
  layout module and the layout.changed channel are gone, and the workbench
  frame is the web's own state.
- The desktop's generated entry registers only the trash helpers now; the
  bundled pi runtime belongs to the agent process, which registers its own.
- Try-again attaches to an error notice, since notices replace the pi-era
  error turn.

Rebased again onto the off-the-event-loop git reads (JetBrains#265). The review and
todo read paths are async now, so the host's review send, todo fix request
and review snapshot await them; the plan-fix flow keeps upstream's per-item
latch (claim on entry, release in a finally) around our synchronous ACP
send, and firstOpenWorkspace follows listWorkspaces into a promise.

Deliberately not carried: the reviewer model/effort pickers in Settings (ACP
has no session-less config read to source the options from — the auto-fix
toggle stays), and useTranscriptSync's revision fence (this transcript model
is one fold over one event log, so a reloaded transcript is the live object
graph by construction).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BFWLfHUiKpPbiAHxiD75BJ
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.

3 participants