Skip to content

fix(omp): keep child sessions from reporting into the parent pane - #20611

Merged
nwparker merged 9 commits into
mainfrom
nwparker/omp-child-session-owner
Sep 19, 2026
Merged

nwparker merged 9 commits into
mainfrom
nwparker/omp-child-session-owner

Conversation

@nwparker

@nwparker nwparker commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​483 $\color{#cf222e}{\Huge{\mathbf{−}}}$​16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​467
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​108 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​91

OMP loads Orca’s status extension again for in-process task children. Those children share the parent PID, so the PID guard lets a child overwrite the parent pane’s session metadata and send a false completion notification.

The extension binds each pane and launch to the first SessionManager to deliver a status callback. In normal root-first OMP startup this is the root manager: later child callbacks are rejected before metadata changes or status handling, while root events continue across extension reload and session changes. Existing cross-process ownership and completion settling remain intact.

Closes #9181

Also prevents the current-OMP child preview/session-ID corruption reported in #9348 and #16353. Previously corrupted saved records are not repaired.

Validation

  • Independent review approved 2d948aac5948287674dbab6840b0d8de488e8d1e; 88 focused tests passed independently. Implementation run: 171 Pi tests plus node typecheck, lint and formatting passed.
  • Actual OMP loader, ExtensionRunner context construction, file-backed SessionManager and real HTTP verify eight root events across module reload, newSession(), persisted-file resume/reload, and shutdown while children drain. Positive HTTP delivery uses a bounded deadline; loader/runner/server errors are asserted. Independent smoke rerun passed.
  • Reproduce with ORCA_BACKGROUND_LAUNCH=1 bun tests/tools/omp-child-session-runtime-smoke.mjs /path/to/oh-my-pi. The OMP checkout is read-only. Lifecycle events and their ordering are controlled by the probe; no full TUI or model-driven task turn was run.
  • Continuous regressions now cover generated hooks → normalization → renderer state → quit capture → serialized schema hydration → startup command. Root prompt, assistant preview and resume UUID survive child events. These simulate callbacks and persistence; they are not an actual app restart.
  • /resume manager continuity is supported by source inspection plus actual setSessionFile runtime exercise. Historical shared-event-bus OMP versions were not runtime-tested. Legacy callbacks without a SessionManager retain existing behavior because their ownership cannot be distinguished.

Compared with merged #8545 and #8826: this extends their process guard and preserves their settlement behavior with the missing in-process session boundary.

Adversarial review — 2026-09-14

Overall risk: medium; not approved for automatic merge. Normal root-first TUI new/resume/reload behavior is exercised, but the ownership mechanism assumes root callbacks arrive first.

  • Reproduced startup-ordering limitation: a custom extension earlier in root session_start dispatch can initialize a child before Orca receives the root callback. The child then owns pane status and root updates are suppressed. Reproduced through actual OMP loader/ExtensionRunner/SessionManager and real HTTP; the early extension/child initialization is controlled by the probe. This can produce incorrect preview/completion/resume metadata for that configuration.
  • Multi-root limitation: a second root SessionManager in the same process and pane/launch remains suppressed. Current OMP ACP can create such managers; no first-class Orca OMP ACP launcher was found. Ordinary TUI new/resume/reload preserve the original manager.
  • No safe heuristic patch: public extension context lacks authoritative task/root identity. Session ancestry also exists on legitimate forked roots, and UI presence excludes legitimate headless roots. Releasing ownership on shutdown or timeout permits draining children to take over. A robust general solution needs authoritative runtime root/subagent provenance.
  • Same-process mutation of pane/launch environment can misroute stale callbacks; ordinary fixed-environment CLI reachability is unconfirmed. The unit test description now accurately states the narrower distinct-key scenario it exercises.

Follow-up changes strengthen validation only; they do not claim to fix these compatibility boundaries. Current upstream checkout tested: e7546987ca526eac8f605fac19ef9805b8f01898. No historical-version, native-Windows, full model-driven task or app-restart proof claimed for this follow-up.

Follow-up 2d10236e40c: 40 focused tests, node typecheck, changed-code quality and independently rerun actual OMP runtime smoke passed. All latest-head CI checks completed successfully (or skipped where not applicable). Two independent subagent reviews and Fable through Orca orchestration completed. Fable independently reran 173 tests, the actual runtime smoke, and the child-first reproduction; it rates the PR medium-low, while the coordinator retains medium overall because the reproduced ordering defect remains.

Fable review adjudication: its proposed /tan regression is not accepted as established: current tan-command-controller passes disableExtensionDiscovery: true without extension paths, and SDK discovery therefore does not load this extension. Its titlebar ownership observation concerns a separate pre-existing mechanism; not changed in this PR. Stock startup source tracing did not identify the child-first defect there, but this is not a universal runtime/third-party-extension compatibility proof. Fable task completed successfully and its supervised terminal was released.

Released OMP provenance follow-up

ELI5

OMP runs the status extension for the parent and its in-process task children. Released OMP does not expose the computed child/main flag in ExtensionContext, so the original ctx.agentKind guard is unavailable at runtime. This update uses the real session manager parent header and nested task transcript path when a root owner is already known, while keeping a nested transcript eligible when no owner is known because it may be a resumed main session.

Proof

  • ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/pi/omp-session-status-owner.test.ts — 10 passed.
  • pnpm exec oxfmt --check ... — passed.
  • Targeted oxlint — passed.
  • pnpm tc:node — passed.
  • OMP prefill/ownership integration tests: 17 passed, including reasonless session_start and Windows nested paths.
  • OMP source audit: /Users/nwparker/projects/oh-my-pi, clean checkout; ExtensionRunner.createContext() has no agentKind, and task children use nested transcript paths.

The exact child-first/no-metadata race remains an upstream OMP capability gap. A timeout heuristic would risk silencing a valid resumed child session, so this change does not introduce that user-facing trade-off. A complete fence needs OMP to expose its already-computed agentKind through ExtensionRunner.createContext.

@nwparker
nwparker marked this pull request as ready for review September 14, 2026 11:49

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • In-process child ownership guard — new src/main/pi/omp-session-status-owner-source.ts emits ownsSessionStatus(ctx) and wraps every generated status handler in onStatus. It binds the pane (ORCA_PANE_KEY + ORCA_AGENT_LAUNCH_TOKEN) to the first SessionManager it observes, keyed on globalThis[Symbol.for('orca.omp.status-session-owners')] so the binding survives module reload and OMP's "rebind factories without re-evaluating the module graph" child path; any later, different manager is dropped before metadata changes or post().
  • Handler registration rename — agent-status-handler-source.ts now registers all status hooks through onStatus(...) instead of pi.on(...), and adds an empty onStatus('session_start', () => {}) so the root claims ownership at the earliest event. The guard applies to every kind but is inert for pi/prime-agent, where isOmpRuntime() is false.
  • Recovery regression coverage — tests/e2e/omp-child-session-recovery.unit.test.ts drives generated hooks through normalization, store state, quit capture, sleep-record schema hydration and resume startup, asserting the root prompt/preview/session survive an active child and the child UUID never reaches the serialized record.
  • Runtime smoke script — tests/tools/omp-child-session-runtime-smoke.mjs exercises the real OMP loader/EventBus/in-memory SessionManager with real HTTP (manual, not collected).
  • Harness alignment — existing OMP extension tests now mutate one sessionManager object instead of swapping identities, matching the ownership contract.

The load-bearing assumption checks out against upstream OMP: ExtensionRunner pins ctx.sessionManager at construction, subagent runners own a distinct manager, and root setSessionFile (/resume) and #resetToNewSession (/new) mutate the same manager in place — so the root keeps one identity for the pane's lifetime, and it is also the identity whose getSessionId() produced the child corruption this fixes. Focused tests (171 in src/main/pi), pnpm tc:node and check:code-quality:changed are all green.

ℹ️ Ownership is sticky for the pane's lifetime

ownsSessionStatus binds the pane to the first manager it sees and never releases it, so a manager that is replaced on the same pane+launch token is suppressed permanently with no recovery path. That is the intended trade for the false-child-completion bug, and today's OMP keeps the root manager stable across resume/new/reload — but it means the pane would go silent rather than self-heal if OMP ever rebinds a live pane to a fresh manager. Noting it as the invariant future OMP session-lifecycle changes must preserve; no change needed in this PR.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 441cd543-ec1d-49c0-85da-4672eb72a2a8

📥 Commits

Reviewing files that changed from the base of the PR and between 25b30f7 and 2ddd31de0b65526c7009750787726acd8b35eafe.

📒 Files selected for processing (3)
  • docs/reference/omp-runtime-session-provenance.md
  • src/main/pi/omp-session-status-owner-source.ts
  • src/main/pi/omp-session-status-owner.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/reference/omp-runtime-session-provenance.md

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The OMP status extension tracks session ownership by pane and launch token. Generated handlers use onStatus and suppress events from non-owning child sessions. Ownership checks use session identity, parent metadata, and normalized nested transcript paths. Tests cover reload, resume, session switching, root-state recovery, metadata capture, and real runtime delivery.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 7 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR meets the coding requirements in #9181. The OMP ownership handler rejects agentKind === "sub" sessions and prevents child callbacks from fetching, claiming pane metadata, or dispatching statu…
Out of Scope Changes check ✅ Passed The changes stay within #9181. Handler registration changes route the existing status and completion logic through the ownership fence. Tests validate the reported false-completion failure and related…
Title check ✅ Passed The title clearly identifies the main change: preventing OMP child sessions from reporting into the parent pane.
Description check ✅ Passed The description provides a detailed explanation of the problem, implementation, linked issues, testing, validation results, limitations, and compatibility considerations. It does not use every templat…
Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 7 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch nwparker/omp-child-session-owner

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Runtime smoke test now drives the real runner — tests/tools/omp-child-session-runtime-smoke.mjs replaces hand-invoked handlers with OMP's actual ExtensionRunner + SessionManager (file-backed root, in-memory child), bounded HTTP delivery checks, error capture, and setSessionFile resume; it asserts the child stays quiet while root agent_start/agent_end survive module reload, newSession(), and resume.
  • Unit test renamed for accuracy — the separate-pane case in omp-session-status-owner.test.ts is retitled to describe the distinct pane/launch ownership key it actually exercises, rather than implying full same-process pane isolation.

The new smoke assertions are able to fail: without the ownership guard the child's session_start/agent_start/agent_end would post, breaking assertQuiet(1), and the final ['agent_start','agent_end'] × 4 check is exact rather than permissive. No production code changed in this delta.

️ Strengthened runtime evidence still has no CI enforcement

The real-ExtensionRunner path is now the strongest evidence in the PR, but the script is deliberately uncollected (tests/tools/*.test.mjs only) and needs a read-only OMP checkout, so nothing in CI fails if the ownership guard regresses against a future runtime binding change. The collected regression coverage remains simulation-only; that is a conscious trade rather than a defect, just worth carrying forward.

Technical details
# Runtime smoke has no automated gate

## Affected sites
- `tests/tools/omp-child-session-runtime-smoke.mjs:1` — manual entry point, requires an external OMP checkout path argument.
- `config/vitest.config.ts:36` — collects `tests/tools/**/*.test.mjs`; this file is `*-smoke.mjs`, so it is skipped.

## Required outcome
- Record the gap so future edits to the extension/runner binding know the real-runtime path is not protected by CI.

## Open questions for the human
- Is a pinned/versioned OMP dependency feasible for CI, or is the manual smoke run the intended permanent posture?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b3a596c3-06bc-4c31-ac01-0266de2652d2

📥 Commits

Reviewing files that changed from the base of the PR and between 7309a30 and 2d10236.

📒 Files selected for processing (2)
  • src/main/pi/omp-session-status-owner.test.ts
  • tests/tools/omp-child-session-runtime-smoke.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/pi/omp-session-status-owner.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

}
const assertQuiet = async (expectedCount) => {
// Suppressed events have no completion callback; allow local HTTP dispatch to settle.
await delay(100)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Wait for the complete status-post timeout.

runner.emit() returns before asynchronous HTTP delivery completes. The generated extension permits status delivery to remain pending for 1000 ms, but assertQuiet() waits only 100 ms.

A delayed child post can arrive after this assertion. It can then satisfy a later expectedCount assertion and hide the ownership regression.

Use a quiet period longer than HOOK_POST_TIMEOUT_MS, or add explicit delivery synchronization.

Proposed fix
-    await delay(100)
+    await delay(1100)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await delay(100)
await delay(1100)

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 053fa99f-8e3d-4b7c-8ce6-5c6c57908e2c

📥 Commits

Reviewing files that changed from the base of the PR and between 2d10236 and eb63ea2.

📒 Files selected for processing (3)
  • docs/reference/omp-runtime-session-provenance.md
  • src/main/pi/omp-session-status-owner-source.ts
  • src/main/pi/omp-session-status-owner.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

' // SessionManager survives reload/new/resume; task children own a different instance.',
' function ownsSessionStatus(ctx): boolean {',
' if (!isOmpRuntime()) return true',
' if (ctx?.agentKind === "sub") return false',

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,80p' src/main/pi/omp-session-status-owner-source.ts
sed -n '1,120p' docs/reference/omp-runtime-session-provenance.md
rg -n 'agentKind|createContext|ExtensionRunner|omp-agent|@.*omp' package.json pnpm-lock.yaml yarn.lock package-lock.json src tests 2>/dev/null | head -240

Repository: stablyai/orca

Length of output: 50372


🏁 Script executed:

set -e
printf '%s\n' '--- manifests and OMP references ---'
rg -n -i --glob 'package.json' --glob 'pnpm-lock.yaml' --glob 'package-lock.json' --glob 'yarn.lock' --glob 'npm-shrinkwrap.json' 'omp|open.*model|e7546987|agentKind' . | head -160
printf '%s\n' '--- focused files ---'
sed -n '1,230p' tests/tools/omp-child-session-runtime-smoke.mjs
sed -n '1,230p' src/main/pi/omp-session-status-owner.test.ts
printf '%s\n' '--- runner/source locations ---'
rg -n --hidden -g '!node_modules/**' -g '!dist/**' -g '!build/**' 'class ExtensionRunner|createContext\s*\(|agentKind' src tests packages apps 2>/dev/null | head -220

Repository: stablyai/orca

Length of output: 41587


🌐 Web query:

"e7546987ca526eac8f605fac19ef9805b8f01898" OMP ExtensionRunner createContext agentKind

💡 Result:

<search_synthesis>
The terms ExtensionRunner, createContext, and agentKind are associated with the codebase for a coding agent system, specifically referenced in discussions and implementations related to &#39;Oh My Pi&#39; (OMP) [1][2]. In this architecture, ExtensionRunner is a class responsible for managing extension lifecycles and context [3][4][5]. The createContext method generates the ExtensionContext object, which provides extensions with access to the agent&#39;s current state (e.g., UI, session manager, and model registry) [3][6][5]. The specific reference to agentKind relates to feature requests and discussions about exposing subagent identity (e.g., "main" vs "sub" agent) within the extension context or lifecycle event handlers [1][2]. Developers have sought to add fields like agentKind, agentId, and parentAgentId to the ExtensionContext interface to allow extensions to distinguish between root and sub-agent events [2]. While the core ExtensionRunner logic manages core execution and tool invocation, these identity-related fields are part of ongoing efforts to achieve parity for subagent extensions within the system [1][2]. The alphanumeric string e7546987ca526eac8f605fac19ef9805b8f01898 does not appear to be a recognized identifier, commit hash, or technical reference within the public repositories or documentation related to this project. It resembles a transaction or address hash, which are commonly found in blockchain-related data but are not relevant to the technical implementation of the OMP coding agent [7][8][9][10][11].
</search_synthesis>

<source_evidence>

<title>feat(extensions): expose agent identity on ctx (main vs sub, agent type, definition path) — closes `#5985` and the subagent extension parity gap</title> GitHub issue 10228 in can1357/oh-my-pi (link omitted to avoid creating a cross-reference) Agent identity on the extension context: `ctx.agentIdentity = { kind, depth, agentId, displayName, parentId?, definition?: { type, source, filePath?, frontmatter? }, parentChain? }`. ... - **omp.** Nothing. `ExtensionContext` does not expose `kind`, `depth`, `agentId`, `displayName`, `parentId`, the definition, or its frontmatter. The host knows all of this internally — `#agentKind` is derived at session creation (`sdk.ts:1714`), `parentId` comes from `AgentRef`, the parsed definition comes from `parseAgent` — and uses it to gate `session_stop` on the main agent and to render the spawn tree. But an extension sees none of it. ... One optional field on `ExtensionContext` — additive, no breaking change (existing extensions never read it). The agent registry already stores `id/displayName/kind/parentId`; the session already computes `agentKind` at creation. Wiring is threading one new `contextActions` field through `runner.initialize()` the same way `getModel` is threaded, plus one `AgentRegistry` lookup at context build time. `definition` is populated only for definition-backed children (wake/revive synthesizes bare definitions, so `definition?` stays genuinely optional there); `parentChain` is always computable by walking `parentId` up the registry. ... The raw frontmatter passthrough on `AgentDefinition` is a one-line companion: `parseAgent` already parses the YAML; only the unknown keys are dropped, so `{ ...fields, frontmatter }` (frontmatter as parsed, minus nothing) makes extension-defined agent config readable without any schema. `settings.getRaw` is a separate, larger item (typed `get` must not break), tracked independently. ... - **Direct closure**: `#5985` (main vs subagent identity on lifecycle handlers — this is the exact field), `#8599` (per-subagent tool scoping: frontmatter passthrough turns tools:/disallowedTools: into real per-agent rules), `#7557` (per-agent extension frontmatter: identity + frontmatter), `#7056` (main-only tool restriction: kind is the discriminator), `#2834` [closed-question: main Stop-hook parity — directly answered by kind === "main"], `#4753` (Herdr session identity: root-vs-sub identity contract), `#8259` (structured spawn event: needs agentId/depth/parentId), `#2574` (ctx.agents.spawn primitive: identity + parentChain complete its hub story). ... - omp docs: `docs/skills/authoring-extensions.md` (ExtensionAPI surface); `docs/task-agent-discovery.md`. - Identity source code: `sdk.ts:1711-1714`, `registry/agent-registry.ts:72-99`, `task/executor.ts:3178-3327` (spawn wiring), `extensibility/extensions/runner.ts:createContext` (runner.ts:1147-1197). - Upstream examples: `@gotgenes/opencode-agent-identity`; Claude Code hooks reference (code.claude.com/docs/en/hooks); Claude-Code-Agent-Monitor README; disler/claude-code-hooks-mastery; anthropics/claude-code `#29068`. ... - omp source: `src/extensibility/{extensions,hooks,custom-tools}`, `src/tools/*`, `src/session/agent-session.ts`, `src/task/*`, `src/sdk.ts`, `docs/*.md` (extensions, extension-loading, hooks, system-prompt-customization, task-agent-discovery, agent-hub, mcp-server-tool-authoring, non-compaction-retry-policy, advisor-watchdog, sdk, settings, bash-tool-runtime); `extensibility/legacy-pi-compat.ts`, `legacy-pi-coding-agent-shim.ts`, `legacy-pi-ai-shim.ts` (wave-2 ... : live `parseAgent`/`parseFrontmatter` probes (unknown-key retention, malformed-YAML recovery), ` ... _SCHEMA`/`dropSettingsGroupShadows` probes, `@opencode-ai/[email protected]` ... `@kilocode/plugin ... 7.5.6` ... , package names ... code.claude. ... docs/en/hooks.md` ... -input-fields + ... agentStart/ ... /sub-agents.md` frontmatter table; ... 64, ... 764, ... (GitHub search, Aug ... > Classified as `enhancement`. Engaging with the design; not implementing uninvited (the prepared branch notwithstanding) — the API shape is a maintainer call. > > ## The core ask is sound and cheap > > The narrow piece — an optional `ctx.agentIdentity` on `ExtensionC…[truncated] <title>feat(extensions): expose main vs subagent identity to lifecycle handlers</title> GitHub issue 5985 in can1357/oh-my-pi (link omitted to avoid creating a cross-reference) OMP already distinguishes top-level and in-process subagent sessions internally, but that identity is not exposed to extensions. ... , `createAgentSession` derives: ... ```ts const agentKind = (options.taskDepth ?? 0) > 0 || options.parentTaskPrefix ? "sub" : "main"; ``` ... However, `ExtensionContext` and the `agent_start` / `agent_end` lifecycle payloads expose none of `agentKind`, `taskDepth`, or `parentAgentId`: ... As a result, an extension observing a shared in-process event surface cannot reliably tell whether a lifecycle event belongs to the visible root agent or to a task/eval subagent. ... Expose stable read-only session identity to extensions, preferably: ... ```ts interface ExtensionContext { agentKind: "main" | "sub"; agentId?: string; parentAgentId?: string; taskDepth?: number; } ``` ... The minimum required field is `agentKind`. It could alternatively be included in agent lifecycle event payloads if that better matches the event architecture. ... - top-level interactive, print, and RPC sessions report `agentKind: "main"`; - in-process task and eval children report `agentKind: "sub"`; - nested children retain their actual depth/parent identity when those optional fields are exposed; - existing extensions remain compatible. ... from an in-process ... agent_end ... PID, tool-name ... or UI heuristics. ... nested subagent. ... remains stable across ... lifecycle events. ... > Thanks for the detailed writeup — the internal/external identity gap is real and the data already exists to close it. > > **Restating the ask:** expose the session&`#39`;s `agentKind` (`"main" | "sub"`), and optionally `agentId` / `parentAgentId` / `taskDepth`, to extensions so a lifecycle observer can tell a root `agent_end` from an in-process child `agent_end` without PID / tool-name / `hasUI` heuristics. > > **Feasibility:** high. All four values are already derived and held per-session — no new plumbing to compute them: > - `agentKind` is computed in `createAgentSession` (`packages/coding-agent/src/sdk.ts:1618`) and stored on the session as `#agentKind` (`session/agent-session.ts:2019`, `2824`); > - `taskDepth`, `parentAgentId`, `agentId` are all already session config (`sdk.ts:514`, `520`, `534`) and flow through to the agent registry (`sdk.ts:2596-2598`, `kind`/`parentId`/`displayName`). > > So this is a surface-exposure change, not a semantics change. > > **Placement — the one real design decision:** you offer `ExtensionContext` fields vs. lifecycle-event payload, and I think the "shared in-process event surface" detail in your use case actually forces the answer toward the **payload** (or at least makes it the safer minimum). > > `ExtensionContext` (`extensibility/extensions/types.ts:410-461`) is per-session and read-only, which reads clean. But your Orca scenario is an extension watching a *shared* event stream where root and child events interleave in one process. If the identity lives only on the observing extension&`#39`;s `ctx`, that `ctx` corresponds to whichever session the extension was installed on (typically the root) — not necessarily the session that *emitted* the `agent_end`. That&`#39`;s exactly the confusion you&`#39`;re trying to remove. Riding the identity on `AgentStartEvent` / `AgentEndEvent` (`extensibility/shared-events.ts:186-200`) makes each event self-describing regardless of which ctx observes it. > > My suggestion: put the identity on the **event payload** as the load-bearing fix, and optionally mirror it on `ExtensionContext` for the common case of a per-session extension. If maintainers want only one, the event payload is the one that satisfies your first acceptance criterion. > > **Open questions for a maintainer to decide:** ... > 2. Field set: is `agentKind` alone enough for v1, or ship `agentId` / `parentAgentId` / `taskDepth` together? The latter three are…[truncated] <title>packages/coding-agent/src/extensibility/extensions/runner.ts</title> https://github.com/can1357/oh-my-pi/blob/c0d0ad76/packages/coding-agent/src/extensibility/extensions/runner.ts export class ExtensionRunner { `#uiContext`: ExtensionUIContext; `#errorListeners`: Set = new Set(); `#getModel`: () => Model | undefined = () => undefined; `#isIdleFn`: () => boolean = () => true; `#waitForIdleFn`: () => Promise = async () => {}; `#abortFn`: () => void = () => {}; `#hasPendingMessagesFn`: () => boolean = () => false; `#getContextUsageFn`: () => ContextUsage | undefined = () => undefined; `#compactFn`: (instructionsOrOptions?: string | CompactOptions) => Promise = async () => {}; `#getSystemPromptFn`: () => string[] = () => []; `#newSessionHandler`: NewSessionHandler = async () => ({ cancelled: false }); `#branchHandler`: BranchHandler = async () => ({ cancelled: false }); `#navigateTreeHandler`: NavigateTreeHandler = async () => ({ cancelled: false }); `#switchSessionHandler`: SwitchSessionHandler = async () => ({ cancelled: false }); `#reloadHandler`: () => Promise = async () => {}; `#shutdownHandler`: ShutdownHandler = () => {}; `#getMemoryFn`?: () => MemoryRuntimeContext | undefined; `#commandDiagnostics`: Array<{ type: string; message: string; path: string }> = []; `#initialized` = false; /** * Buffer for `credential_disabled` events received via {`@link` emitCredentialDisabled} * before {`@link` initialize} has run. Drained through {`@link` emit} once initialize sets * up the runtime context, so extension handlers see a populated UI/runtime context * rather than the constructor&`#39`;s no-op default. Bounded at * {`@link` MAX_PENDING_CREDENTIAL_DISABLED}; oldest entries are dropped under pressure. */ `#pendingCredentialDisabled`: CredentialDisabledEvent[] = []; constructor( private readonly extensions: Extension[], private readonly runtime: ExtensionRuntime, private readonly cwd: string, private readonly sessionManager: SessionManager, private readonly modelRegistry: ModelRegistry, getMemory?: () => MemoryRuntimeContext | undefined, private readonly settings?: Settings, private readonly localProtocolOptions?: LocalProtocolOptions, ) { this.#uiContext = noOpUIContext; this.#getMemoryFn = getMemory; } initialize( actions: ExtensionActions, contextActions: ExtensionContextActions, commandContextActions?: ExtensionCommandContextActions, uiContext?: ExtensionUIContext, ): void { // Copy actions into the shared runtime (all extension APIs reference this) this.runtime.sendMessage = actions.sendMessage; this.runtime.sendUserMessage = actions.sendUserMessage; this.runtime.appendEntry = actions.appendEntry; this.runtime.getActiveTools = actions.getActiveTools; this.runtime.getAllTools = actions.getAllTools; this.runtime.setActiveTools = actions.setActiveTools; this.runtime.getCommands = actions.getCommands; this.runtime.setModel = actions.setModel; this.runtime.getThinkingLevel = actions.getThinkingLevel; this.runtime.setThinkingLevel = actions.setThinkingLevel; this.runtime.getSessionName = actions.getSessionName; this.runtime.setSessionName = actions.setSessionName; // Context actions (required) this.#getModel = contextActions.getModel; this.#isIdleFn = contextActions.isIdle; this.#abortFn = contextActions.abort; this.#hasPending ... Fn = contextActions.hasPendingMessages; this.#shutdownHandler ... contextActions.shutdown; this.#getSystemPromptFn ... contextActions.getSystemPrompt ... (optional, only ... if (command ... Actions) { ... this.#getContext ... ContextActions.getContext ... get(name); ... ) { return command; } } return ... createContext(): ExtensionContext { const getModel = this.#getModel; return { ui: this.#uiContext, getContextUsage: () => this.#getContextUsageFn(), compact: instructionsOrOptions => this.#compactFn(instructionsOrOptions), hasUI: this.hasUI(), cwd: this.cwd, sessionManager: this.sessionManager, modelRegistry: this.modelRegistry, get model() { return getModel(); }, models: createExtensionModelQuery(this.modelRegistry, this.settings, getModel), isIdle: () => this.#isIdleFn(), abort: () => this.#abortFn(), hasPendingMessages: () =…[truncated] <title>Result 4</title> https://cdn.jsdelivr.net/npm/@oh-my-pi/[email protected]/src/extensibility/extensions/runner.ts export class ExtensionRunner { `#uiContext`: ExtensionUIContext; `#errorListeners`: Set = new Set(); `#getModel`: () => Model | undefined = () => undefined; `#isIdleFn`: () => boolean = () => true; `#waitForIdleFn`: () => Promise = async () => {}; `#abortFn`: () => void = () => {}; `#hasPendingMessagesFn`: () => boolean = () => false; `#getContextUsageFn`: () => ContextUsage | undefined = () => undefined; `#compactFn`: (instructionsOrOptions?: string | CompactOptions) => Promise = async () => {}; `#getSystemPromptFn`: () => string[] = () => []; `#newSessionHandler`: NewSessionHandler = async () => ({ cancelled: false }); `#branchHandler`: BranchHandler = async () => ({ cancelled: false }); `#navigateTreeHandler`: NavigateTreeHandler = async () => ({ cancelled: false }); `#switchSessionHandler`: SwitchSessionHandler = async () => ({ cancelled: false }); `#reloadHandler`: () => Promise = async () => {}; `#shutdownHandler`: ShutdownHandler = () => {}; `#getMemoryFn`?: () => MemoryRuntimeContext | undefined; `#commandDiagnostics`: Array<{ type: string; message: string; path: string }> = []; `#initialized` = false; /** * ... toolCallId ... 512 ... ToolCalls. ... (`${toolCallId ... /** Consumes a {`@link` markToolCallEmitted ... true when the loop already emitted ... consumeToolCall ... itted(toolCallId ... string, toolName: string ... boolean { return this.#emittedToolCalls.delete(`${toolCallId}:${toolName}`); } ... constructor( private readonly extensions: Extension[], private readonly runtime: ExtensionRuntime, private readonly cwd: string, private readonly sessionManager: SessionManager, private readonly modelRegistry: ModelRegistry, getMemory?: () => MemoryRuntimeContext | undefined, private readonly settings?: Settings, private readonly localProtocolOptions?: LocalProtocolOptions, ) { this.#uiContext = noOpUIContext; this.#getMemoryFn = getMemory; } initialize( actions: ExtensionActions, contextActions: ExtensionContextActions, commandContextActions?: ExtensionCommandContextActions, uiContext?: ExtensionUIContext, ): void { // Copy actions into the shared runtime (all extension APIs reference this) this.runtime.sendMessage = actions.sendMessage; this.runtime.sendUserMessage = actions.sendUserMessage; this.runtime.appendEntry = actions.appendEntry; this.runtime.getActiveTools = actions.getActiveTools; this.runtime.getAllTools = actions.getAllTools; this.runtime.setActiveTools = actions.setActiveTools; this.runtime.getCommands = actions.getCommands; this.runtime.setModel = actions.setModel; this.runtime.getThinkingLevel = actions.getThinkingLevel; this.runtime.setThinkingLevel = actions.setThinkingLevel; this.runtime.getServiceTiers = actions.getServiceTiers ?? throwUnsupportedServiceTierAction; this.runtime.setServiceTier = actions.setServiceTier ?? throwUnsupportedServiceTierAction; this.runtime.getSessionName = actions.getSessionName; this.runtime.setSessionName = actions.setSessionName; // Context actions (required) this.#getModel = contextActions.getModel; this.#isIdleFn = contextActions.isIdle; this.#abortFn = contextActions.abort; this.#hasPendingMessagesFn = contextActions.hasPendingMessages; this.#shutdownHandler = contextActions.shutdown; this.#getSystemPromptFn = contextActions.getSystemPrompt; // Command context actions (optional, only for interactive mode) if (commandContextActions) { this.#waitForIdleFn = commandContextActions.waitForIdle; this.#new ... Handler = commandContextActions.newSession; this.#branchHandler = commandContextActions.branch; this.#navigateTreeHandler ... commandContextActions.navigateTree; this.# ... commandContextActions. ... ; this.# ... ; this ... ; this.# ... compact; ... uiContext ?? ... UIContext; ... .#initialized = true; ... getCommand(name: string): ... Command | undefined ... for (let index = this.extensions.length - 1; index >= 0; index -= 1) { const command = this.extensions[index]?.commands.get(name); if (command) { return c…[truncated] <title>packages/coding-agent/src/core/extensions/runner.ts at 38f18be4 · earendil-works/pi</title> https://github.com/badlogic/pi-mono/blob/38f18be4/packages/coding-agent/src/core/extensions/runner.ts export class ExtensionRunner { private extensions: Extension[]; private runtime: ExtensionRuntime; private uiContext: ExtensionUIContext; private mode: ExtensionMode = "print"; private cwd: string; private sessionManager: SessionManager; private modelRegistry: ModelRegistry; private errorListeners: Set<ExtensionErrorListener> = new Set(); private getModel: () => Model<any> | undefined = () => undefined; private isIdleFn: () => boolean = () => true; private getSignalFn: () => AbortSignal | undefined = () => undefined; private waitForIdleFn: () => Promise<void> = async () => {}; private abortFn: () => void = () => {}; private hasPendingMessagesFn: () => boolean = () => false; private getContextUsageFn: () => ContextUsage | undefined = () => undefined; private compactFn: (options?: CompactOptions) => void = () => {}; private getSystemPromptFn: () => string = () => ""; private getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd }); private newSessionHandler: NewSessionHandler = async () => ({ cancelled: false }); private forkHandler: ForkHandler = async () => ({ cancelled: false }); private navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false }); private switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false }); private reloadHandler: ReloadHandler = async () => {}; private shutdownHandler: ShutdownHandler = () => {}; ... private shortcut ... private stale ... : string | undefined; ... [], ... , cwd ... string, session ... SessionManager, modelRegistry ... ModelRegistry, ) ... .extensions = ... ; ... ; ... .uiContext = noOpUIContext; ... .cwd = cwd; ... = sessionManager; this.modelRegistry = modelRegistry; } ... ( actions: ExtensionActions, context ... : ExtensionContextActions, providerActions?: ... : string, config ... ProviderConfig) => void; unregisterProvider?: (name: string) => void; }, ): void ... // Copy actions into the shared runtime (all extension APIs reference this) ... .runtime.sendMessage = actions.sendMessage; ... .runtime.sendUserMessage = actions.sendUserMessage; ... .appendEntry ... actions.appendEntry; ... ; ... ; this.runtime ... setLabel = actions.setLabel; this.runtime ... getActiveTools = actions.getActiveTools; this.runtime.getAllTools ... actions.getAllTools; this. ... .setActiveTools ... actions.setActiveTools ... .runtime. ... this.runtime ... getThinkingLevel = actions ... getThinkingLevel; this.runtime ... setThinkingLevel = actions.setThinkingLevel; ... ; ... contextActions.get ... ; ... ; ... compact; this.getSystemPromptFn ... getSystemPrompt; ... .getSystemPromptOptionsFn ... contextActions.getSystemPromptOptions ?? (() => ... /** * Create an ExtensionContext for use in event handlers and tool execution. * Context values are resolved at call time, so changes via bindCore/bindUI are reflected. */ createContext(): ExtensionContext { const runner = this; const getModel = this.getModel; return { get ui() { runner.assertActive(); return runner.uiContext; }, get mode() { runner.assertActive(); return runner.mode; }, get hasUI() { runner.assertActive(); return runner.hasUI(); }, get cwd() { runner.assertActive(); return runner.cwd; }, get sessionManager() { runner.assertActive(); return runner.sessionManager; }, get modelRegistry() { runner.assertActive(); return runner.modelRegistry; }, get model() { runner.assertActive(); return getModel(); }, isIdle: () => { runner.assertActive(); return runner.isIdleFn(); }, get signal() { runner.assertActive(); return runner.getSignalFn(); }, abort: () => { runner.assertActive(); runner.abortFn(); }, hasPendingMessages: () => { runner.assertActive(); return runner.hasPendingMessagesFn(); }, shutdown: () => { runner.assertActive(); runner.shutdownHandler(); }, getContextUsage: () => { runner.assertActive(); return runner.getContextUsageFn(); }, …[truncated]

Citations:


Expose agentKind before relying on this filter.

The current OMP ExtensionRunner.createContext contract does not expose agentKind. A child callback without that field can claim the first manager owner. A later root callback then fails the manager check, so child status can control the pane.

Ship the runtime context change with this filter. Add a regression test where the child callback arrives first without agentKind.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one documentation-hygiene nit below.

Reviewed changes

This re-review covers the single commit pushed since the prior pullfrog review at 2d10236 — a forward-compatible runtime-provenance guard with its regression tests and a reference doc.

  • Added an agentKind === 'sub' short-circuit to the generated ownsSessionStatus, so a child callback is rejected before it can claim a pane when OMP exposes runtime provenance, while runtimes without the field fall through to the existing SessionManager identity guard.
  • Added regression coverage proving an earlier child callback is rejected and that a former child transcript resumed as the runtime main session still reports — the rejection test fails without the guard (verified by ablation).
  • Documented the provenance contract, its unreleased OMP runtime dependency, and the remaining multi-root/ordering limits in docs/reference/omp-runtime-session-provenance.md.

The new guard is inert on today's released runtimes (OMP does not yet expose ctx.agentKind) and is already behind the isOmpRuntime() check, so it changes nothing for pi/prime-agent and is safe to ship ahead of the runtime proposal.

ℹ️ Nitpicks

  • docs/reference/omp-runtime-session-provenance.md is only tracked because it was force-added: docs/** ignores it (.gitignore:96) and there is no matching !docs/reference/omp-runtime-session-provenance.md negation. This mirrors the repo's existing reference-doc norm and is not a blocker, but adding the allow-list line would make the page reproducible from a clean git add.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

ℹ️ No critical issues — one provenance-clarity suggestion inline.

Reviewed changes

This re-review covers the commit pushed since the prior pullfrog review at eb63ea2 — a rework of the OMP ownership guard to derive provenance from the session manager, plus a rewrite of its reference doc.

  • Replaced the ctx.agentKind-only short-circuit with sessionProvenance(ctx), which snapshots getSessionId() / getSessionFile() / getHeader().parentSession from the manager, and stores that snapshot as the pane owner.
  • Rejected a different manager when its parentSession matches the owner's file or id, or when its transcript is nested under the owner's file, and still rejected it otherwise.
  • Rewrote docs/reference/omp-runtime-session-provenance.md to describe the released-runtime fallback and the unresolved child-first ambiguity.
  • Added a unit test for the parent-metadata/nested-path rejection and dropped agentKind: 'main' from the resumed-child test so it models released OMP.

The new code is behaviorally inert — see the inline note — so this does not change what ships, but the doc and the test title now describe a distinction the code does not make.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +36 to +39
' if (owner.manager === current.manager) return true',
' if (current.parent === owner.file || current.parent === owner.id) return false',
' if (isNestedTaskTranscript(owner.file, current.file)) return false',
' return false',

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.

These three provenance checks all fall through to return false, so once an owner exists the decision is exactly owner.manager === current.manager — the parent and nested-path branches never change the outcome. I collapsed them to that identity check locally and all 44 focused tests (including the new parent-metadata test) still pass, so the distinction is not actually exercised. If it is being kept as groundwork for a future OMP agentKind, a comment saying every non-owner manager is rejected would avoid implying the metadata drives the decision; otherwise the helpers and branches can go.

Technical details
# Provenance branches do not affect the ownership decision

## Affected sites
- `src/main/pi/omp-session-status-owner-source.ts:36` — `owner.manager === current.manager` returns true for the same manager
- `src/main/pi/omp-session-status-owner-source.ts:37` — `current.parent === owner.file || current.parent === owner.id` returns false
- `src/main/pi/omp-session-status-owner-source.ts:38` — `isNestedTaskTranscript(owner.file, current.file)` returns false
- `src/main/pi/omp-session-status-owner-source.ts:39` — unconditional `return false`
- `src/main/pi/omp-session-status-owner.test.ts:93` — the new parent-metadata test also passes under the pre-change guard

## Required outcome
- The code and `docs/reference/omp-runtime-session-provenance.md` agree on what drives rejection. The doc says the guard "uses the session manager's parent header and nested task transcript path", but any different manager is rejected regardless, so the metadata currently has no effect.

## Suggested approach (optional)
- Collapse to `if (owner) return owner.manager === current.manager`, or keep the branches with a comment that all non-owner managers are rejected and the provenance reads are retained for a future `agentKind` fence.
- `isNestedTaskTranscript` compares with a literal `/` (`candidateFile.startsWith(`${root}/`)`), so it returns false for Windows-style paths — harmless while the result is discarded, but a trap if it ever becomes load-bearing.

## Open questions for the human (optional)
- Is `getHeader().parentSession` a released OMP field, and is it a transcript file path or a session id? The code compares it against both `owner.file` and `owner.id`, which suggests the contract is not pinned down.

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.

[Bug]: OMP in-process subagent yield triggers a false top-level completion notification

1 participant