From 37658dd2463122cced692fe73aed826bdfb0378b Mon Sep 17 00:00:00 2001 From: Gustav RLo <40185279+GustavBlack@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:16:41 -0800 Subject: [PATCH 1/5] fix(provider-omp): show subagents spawned by OMP's task tool The Pi adapter projected subagent cards only for the tool named "subagent" (pi-subagents). OMP's fan-out tool is named "task", so its calls fell through to generic dynamic_tool rows: no cards, no live progress, and background runs untracked. PiFlavor gains subagentToolName (pi: "subagent", omp: "task") and the adapter now projects OMP task calls: SingleResult.output for result text, assignment/task for the prompt, exitCode for status, running cards from details.progress[], background runs tracked by details.async.jobId and settled from the task-result blocks omp delivers through wait results. Replay tests recorded from omp 19.2.0 RPC cover foreground, parallel and async sequences. --- packages/provider-omp/src/server.ts | 1 + .../provider-pi/src/server/adapter.test.ts | 264 +++++++++++++++++- packages/provider-pi/src/server/adapter.ts | 188 ++++++++++--- packages/provider-pi/src/server/flavor.ts | 3 + 4 files changed, 415 insertions(+), 41 deletions(-) diff --git a/packages/provider-omp/src/server.ts b/packages/provider-omp/src/server.ts index b8c9d7785242e..dfcf5f76d9375 100644 --- a/packages/provider-omp/src/server.ts +++ b/packages/provider-omp/src/server.ts @@ -20,6 +20,7 @@ export const OMP_FLAVOR: PiFlavor = { probeDirName: "omp-status-probe", defaultAgentDirSegments: [".omp", "agent"], usageProvider: "omp", + subagentToolName: "task", }; const DEFAULT_OMP_SETTINGS = Schema.decodeSync(OmpSettings)({}); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index cdcf6199b6159..346961fc5f2ea 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -5,6 +5,7 @@ import { ChatAttachmentId, EnvironmentId, NodeId, + ProviderDriverKind, ProviderInstanceId, ProviderSessionId, ProviderThreadId, @@ -529,6 +530,8 @@ const makeAdapter = Effect.fnUntraced(function* ( launchArgs = "", forkFake?: FakePi, continuationRequests?: PiAdapterV2Options["continuationRequests"], + driverKind?: ProviderDriverKind, + subagentToolName?: string, ) { const spawner = forkFake === undefined @@ -570,6 +573,8 @@ const makeAdapter = Effect.fnUntraced(function* ( customModels: [], }, environment: {}, + ...(driverKind === undefined ? {} : { driverKind }), + ...(subagentToolName === undefined ? {} : { subagentToolName }), }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); }); @@ -581,8 +586,16 @@ const openRuntime = Effect.fnUntraced(function* ( forkFake?: FakePi, continuationRequests?: PiAdapterV2Options["continuationRequests"], initialNativeThreadId?: string, + flavorOverride?: { readonly driverKind: ProviderDriverKind; readonly subagentToolName?: string }, ) { - const adapter = yield* makeAdapter(fake, "", forkFake, continuationRequests); + const adapter = yield* makeAdapter( + fake, + "", + forkFake, + continuationRequests, + flavorOverride?.driverKind, + flavorOverride?.subagentToolName, + ); const runtime = yield* adapter.openSession({ threadId, providerSessionId, @@ -3833,6 +3846,255 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + const OMP_FLAVOR_OVERRIDE = { + driverKind: ProviderDriverKind.make("omp"), + subagentToolName: "task", + }; + + it.effect("projects OMP task tool progress and results as subagent cards", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + // Frames as omp 19.2.0 sends them for a blocking `task` call (async disabled). + yield* fake.emit({ + type: "tool_execution_update", + toolCallId: "call_omp_fg", + toolName: "task", + partialResult: { + content: [{ type: "text", text: "Running agent WriteGamma..." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 89, + progress: [ + { + index: 0, + id: "WriteGamma", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly:\n\n# Target\nCreate gamma.txt", + assignment: "# Target\nCreate gamma.txt", + }, + ], + }, + }, + }); + const running = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "running", + ); + assert.isTrue( + running.type === "subagent.updated" && + running.subagent.title === "sonic" && + running.subagent.prompt === "# Target\nCreate gamma.txt" && + running.subagent.childThreadId === null, + ); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_fg", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "..." }], + details: { + projectAgentsDir: null, + results: [ + { + index: 0, + id: "WriteGamma", + agent: "sonic", + agentSource: "bundled", + description: "Create gamma.txt with GAMMA content", + task: "Complete assignment thoroughly:\n\n# Target\nCreate gamma.txt", + assignment: "# Target\nCreate gamma.txt", + exitCode: 0, + output: "Created gamma.txt.", + }, + ], + totalDurationMs: 2700, + }, + }, + }); + const doneCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + assert.isTrue( + doneCard.type === "subagent.updated" && + doneCard.subagent.title === "sonic" && + doneCard.subagent.result === "Created gamma.txt.", + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("projects each OMP parallel task result as its own completed subagent", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_par", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "two task results" }], + details: { + projectAgentsDir: null, + results: [ + { + index: 0, + id: "AlphaWriter", + agent: "sonic", + agentSource: "bundled", + description: "Write alpha", + task: "Complete assignment thoroughly:\n\n# Target\nalpha.txt", + assignment: "# Target\nalpha.txt", + exitCode: 0, + output: "ALPHA written", + }, + { + index: 1, + id: "BetaWriter", + agent: "sonic", + agentSource: "bundled", + description: "Write beta", + task: "Complete assignment thoroughly:\n\n# Target\nbeta.txt", + assignment: "# Target\nbeta.txt", + exitCode: 0, + output: "BETA written", + }, + ], + totalDurationMs: 7100, + }, + }, + }); + const results: Array = []; + while (results.length < 2) { + const event = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + if (event.type === "subagent.updated") results.push(event.subagent.result ?? ""); + } + assert.deepEqual(results.sort(), ["ALPHA written", "BETA written"]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("tracks OMP background task runs until wait delivers their results", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + // Spawn end frame as omp 19.2.0 sends it over RPC: background job, no results yet. + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_bg", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "pending", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + const pendingSignal = yield* takeEvent((event) => event.type === "background_work.updated"); + assert.isTrue(pendingSignal.type === "background_work.updated" && pendingSignal.pending); + yield* fake.emit({ type: "turn_end", message: { role: "assistant", content: [] } }); + // The coordinator settles the job later via the wait tool; omp delivers the + // subagent's result as a task-result block inside the wait result's text. + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_wait", + toolName: "wait", + isError: false, + result: { + content: [ + { + type: "text", + text: '## Completed (1)\n\n### GammaWriter [task] — completed\n```\n\n\n\nCreated gamma.txt with GAMMA.\n\n\n```', + }, + ], + details: {}, + }, + }); + const doneCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + assert.isTrue( + doneCard.type === "subagent.updated" && + doneCard.subagent.title === "sonic" && + doneCard.subagent.result === "Created gamma.txt with GAMMA.", + ); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("shows the members of an async pi-subagents workflow as running subagents", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index f1adce3b9e8cd..17aadfc3fe4b5 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -209,6 +209,8 @@ export interface PiAdapterV2Options { readonly linkedToInferenceServer?: boolean; readonly driverKind?: ProviderDriverKind; readonly defaultBinary?: string; + /** Tool name projecting subagent cards; pi-subagents uses "subagent", OMP uses "task". */ + readonly subagentToolName?: string; readonly continuationRequests?: { readonly offer: ( request: ProviderContinuationRequests.ProviderContinuationRequest, @@ -321,13 +323,6 @@ function piToolOutput(result: unknown, toolName: string): unknown { }; } -function providerRef( - nativeId: string, - strength: "strong" | "weak" = "strong", -): OrchestrationV2ProviderRef { - return { driver: PI_PROVIDER, nativeId, strength }; -} - const PI_THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]); interface PiStreamItemState { @@ -477,6 +472,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const PI_PROVIDER = options.driverKind ?? PI_DRIVER_KIND; const defaultBinary = options.defaultBinary ?? "pi"; + const subagentToolName = options.subagentToolName ?? "subagent"; const providerRef = ( nativeId: string, strength: "strong" | "weak" = "strong", @@ -653,12 +649,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const customAnswerFollowUps = new Map(); const sessionApprovals = new Set(); // Async pi-subagents runs launched in this session, by async id, until they settle. + // omp `task` runs are tracked by job id; `members` names the spawned subagents + // so `wait` results can settle them. const piAsyncRuns = new Map< string, { readonly turn: ActivePiTurn; readonly toolCallId: string; readonly emitted: Map; + readonly members: Set; } >(); // The launch snapshot arrives before the tool result that names its run. @@ -1536,9 +1535,14 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...(viewedImagePath === undefined ? {} : { viewedImagePath }), }, }); - if (toolName === "subagent") { + if (toolName === subagentToolName) { yield* emitSubagentTasks(turn, toolCallId, resultRecord, completed); } + // omp settles background `task` runs through `wait` results; pi members + // arrive in the subagent-async widget instead. + if (toolName === "wait" && piAsyncRuns.size > 0) { + yield* settleOmpWaitResults(resultRecord); + } }); const emitSubagentTasks = Effect.fnUntraced(function* ( @@ -1549,40 +1553,76 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const details = recordField(resultRecord, "details"); const results = recordField(details, "results"); - if (!Array.isArray(results)) return; let emitted = false; - for (const [index, result] of results.entries()) { - const agent = recordString(result, "agent"); - const task = recordString(result, "task"); - if (agent === undefined || task === undefined) continue; - emitted = true; - const finished = completed || recordField(result, "finished") === true; - const stopReason = recordString(result, "stopReason"); - const interrupted = finished && stopReason === "aborted"; - const failed = - finished && - !interrupted && - ((recordNumber(result, "exitCode") ?? 0) !== 0 || stopReason === "error"); - const outputText = piSubagentOutput(result); - yield* emitSubagent(turn, toolCallId, `${recordNumber(result, "step") ?? index}`, { - agent, - task, - model: recordString(result, "model") ?? null, - status: interrupted - ? "interrupted" - : failed - ? "failed" - : finished - ? "completed" - : "running", - progress: !finished && outputText.length > 0 ? outputText.slice(0, 200) : undefined, - result: finished && outputText.length > 0 ? outputText.slice(0, 10_000) : null, - }); + if (Array.isArray(results)) { + for (const [index, result] of results.entries()) { + const agent = recordString(result, "agent"); + const task = recordString(result, "assignment") ?? recordString(result, "task"); + if (agent === undefined || task === undefined) continue; + emitted = true; + const finished = completed || recordField(result, "finished") === true; + const stopReason = recordString(result, "stopReason"); + const interrupted = finished && stopReason === "aborted"; + const failed = + finished && + !interrupted && + ((recordNumber(result, "exitCode") ?? 0) !== 0 || stopReason === "error"); + const outputText = piSubagentOutput(result); + yield* emitSubagent(turn, toolCallId, `${recordNumber(result, "step") ?? index}`, { + agent, + task, + model: recordString(result, "model") ?? null, + status: interrupted + ? "interrupted" + : failed + ? "failed" + : finished + ? "completed" + : "running", + progress: !finished && outputText.length > 0 ? outputText.slice(0, 200) : undefined, + result: finished && outputText.length > 0 ? outputText.slice(0, 10_000) : null, + }); + } } - // Async launches return no results; their members arrive in the subagent-async widget. - const asyncId = recordString(details, "asyncId"); - if (!emitted && asyncId !== undefined && !piAsyncRuns.has(asyncId)) { - const tracked = { turn, toolCallId, emitted: new Map() }; + // omp streams running members through `progress[]` while `results[]` is still empty. + if (!emitted) { + const progress = recordField(details, "progress"); + if (Array.isArray(progress)) { + for (const [index, entry] of progress.entries()) { + const agent = recordString(entry, "agent"); + if (agent === undefined) continue; + emitted = true; + const status = recordString(entry, "status") ?? "running"; + yield* emitSubagent(turn, toolCallId, recordString(entry, "id") ?? `${index}`, { + agent, + task: recordString(entry, "assignment") ?? recordString(entry, "task") ?? "", + model: null, + status: + status === "completed" + ? "completed" + : status === "failed" || status === "error" + ? "failed" + : status === "aborted" + ? "interrupted" + : "running", + result: null, + }); + } + } + } + // Async launches return no results; pi members arrive in the subagent-async + // widget, omp members in `wait` results. Track the run until it settles. + const asyncId = + recordString(details, "asyncId") ?? recordString(recordField(details, "async"), "jobId"); + if (asyncId !== undefined && !piAsyncRuns.has(asyncId)) { + const progress = recordField(details, "progress"); + const members = new Set( + (Array.isArray(progress) ? progress : []).flatMap((entry) => { + const id = recordString(entry, "id"); + return id === undefined ? [] : [id]; + }), + ); + const tracked = { turn, toolCallId, emitted: new Map(), members }; piAsyncRuns.set(asyncId, tracked); // Keeps the run ingesting after the coordinator's turn ends, until the run settles. yield* emit({ @@ -1596,6 +1636,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } }); + // omp delivers background `task` results through `wait` tool results as + // task-result blocks; settle the tracked run's members from them. + const settleOmpWaitResults = Effect.fnUntraced(function* (resultRecord: unknown) { + if (piAsyncRuns.size === 0) return; + const outputText = contentText(recordField(resultRecord, "content")); + if (outputText.length === 0) return; + const blockPattern = + /([\s\S]*?)<\/task-result>/g; + for (const match of outputText.matchAll(blockPattern)) { + const id = match[1]; + const agent = match[2]; + const status = match[3]; + const body = match[4]; + if ( + id === undefined || + agent === undefined || + status === undefined || + body === undefined + ) { + continue; + } + const trackedEntry = [...piAsyncRuns.entries()].find(([, tracked]) => + tracked.members.has(id), + ); + if (trackedEntry === undefined) continue; + const [runId, tracked] = trackedEntry; + const output = /([\s\S]*?)<\/output>/.exec(body)?.[1]?.trim() ?? ""; + const settled = + status === "completed" + ? "completed" + : status === "failed" || status === "error" + ? "failed" + : status === "aborted" + ? "interrupted" + : undefined; + if (settled === undefined) continue; + yield* emitSubagent(tracked.turn, tracked.toolCallId, id, { + agent, + task: "", + model: null, + status: settled, + result: output.length > 0 ? output.slice(0, 10_000) : null, + }); + tracked.members.delete(id); + if (tracked.members.size === 0) { + piAsyncRuns.delete(runId); + const providerTurnId = tracked.turn.providerTurn.id; + const stillPending = [...piAsyncRuns.values()].some( + (other) => other.turn.providerTurn.id === providerTurnId, + ); + if (!stillPending) { + yield* emit({ + type: "background_work.updated", + driver: PI_PROVIDER, + providerTurnId, + pending: false, + }); + } + } + } + }); + const emitSubagent = Effect.fnUntraced(function* ( turn: ActivePiTurn, toolCallId: string, @@ -4408,6 +4510,9 @@ function piSubagentOutput(result: unknown): string { const failure = recordString(result, "errorMessage") || recordString(result, "stderr"); if (failure !== undefined && failure.length > 0) return failure; } + // omp `task` results carry the subagent's final output in `output`. + const output = recordString(result, "output"); + if (output !== undefined && output.length > 0) return output; const messages = recordField(result, "messages"); if (!Array.isArray(messages)) return ""; for (let index = messages.length - 1; index >= 0; index -= 1) { @@ -4613,6 +4718,9 @@ export function createPiAdapterV2Driver(options: { linkedToInferenceServer: input.inferenceServerId !== undefined, driverKind: flavor.driverKind, defaultBinary: flavor.binaryName, + ...(flavor.subagentToolName === undefined + ? {} + : { subagentToolName: flavor.subagentToolName }), continuationRequests, }); }, diff --git a/packages/provider-pi/src/server/flavor.ts b/packages/provider-pi/src/server/flavor.ts index 09955ea5913f7..53f20e7d58034 100644 --- a/packages/provider-pi/src/server/flavor.ts +++ b/packages/provider-pi/src/server/flavor.ts @@ -9,6 +9,8 @@ export interface PiFlavor { readonly probeDirName: string; readonly defaultAgentDirSegments: readonly [string, ...string[]]; readonly usageProvider: UsageProviderKind; + /** Tool name this CLI uses for subagent fan-out (pi-subagents: "subagent"; OMP: "task"). */ + readonly subagentToolName?: string; } export const PI_FLAVOR: PiFlavor = { @@ -20,4 +22,5 @@ export const PI_FLAVOR: PiFlavor = { probeDirName: "pi-status-probe", defaultAgentDirSegments: [".pi", "agent"], usageProvider: "pi", + subagentToolName: "subagent", }; From b0d67b1d1053508904c2862c714b70665cb1f915 Mon Sep 17 00:00:00 2001 From: Gustav RLo <40185279+GustavBlack@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:33:52 -0800 Subject: [PATCH 2/5] fix(provider-omp): settle and gate OMP subagent projection per review Review of PR #31 found the OMP projection leaking running state and reaching into Pi's paths. Addressing each finding: - One member key across progress and results cards (id, then step/index), so the running card is the card that completes; the replay test now asserts the running subagent's id is the one that settles. - progress[] cards map to interrupted/failed when the tool ends without results (isError picks failed over interrupted). - Background runs track members as id -> agent, falling back to the job id when a spawn carries no progress ids; every parsed task-result block settles its member (completed/failed/error as-is, anything else as interrupted); task-result attributes parse in any order; runs still tracked when the agent settles are dropped as interrupted, releasing background_work. - The OMP-only paths (progress fallback, output preference, tracking guard, wait hook) are gated on the flavor, leaving Pi's behavior identical to main. Failing-first tests cover each case: orphan key, errored end without results, jobId-only spawn, cancelled status, attribute order, and agent_settled without wait. --- .../provider-pi/src/server/adapter.test.ts | 348 +++++++++++++++++- packages/provider-pi/src/server/adapter.ts | 193 ++++++---- 2 files changed, 477 insertions(+), 64 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 346961fc5f2ea..e74432f3fb25a 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -3935,10 +3935,13 @@ describe("PiAdapterV2", () => { const doneCard = yield* takeEvent( (event) => event.type === "subagent.updated" && event.subagent.status === "completed", ); + const runningId = running.type === "subagent.updated" ? running.subagent.id : null; assert.isTrue( doneCard.type === "subagent.updated" && doneCard.subagent.title === "sonic" && - doneCard.subagent.result === "Created gamma.txt.", + doneCard.subagent.result === "Created gamma.txt." && + runningId !== null && + doneCard.subagent.id === runningId, ); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); @@ -4095,6 +4098,349 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("ends OMP progress cards as failed when an errored task leaves no results", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + const progressDetails = { + projectAgentsDir: null, + results: [], + totalDurationMs: 89, + progress: [ + { + index: 0, + id: "WriteGamma", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nCreate gamma.txt", + }, + ], + }; + yield* fake.emit({ + type: "tool_execution_update", + toolCallId: "call_omp_abort", + toolName: "task", + partialResult: { + content: [{ type: "text", text: "Running agent WriteGamma..." }], + details: progressDetails, + }, + }); + yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "running", + ); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_abort", + toolName: "task", + isError: true, + result: { + content: [{ type: "text", text: "task failed" }], + details: progressDetails, + }, + }); + const endedCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "failed", + ); + assert.isTrue(endedCard.type === "subagent.updated" && endedCard.subagent.title === "sonic"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("settles an OMP background run that spawned without progress ids", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_solo", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `SoloJob` (job `SoloJob`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + agent: "sonic", + agentSource: "bundled", + status: "pending", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "SoloJob", type: "task" }, + }, + }, + }); + yield* takeEvent((event) => event.type === "background_work.updated"); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_wait", + toolName: "wait", + isError: false, + result: { + content: [ + { + type: "text", + text: '\n\n\nDone.\n\n', + }, + ], + details: {}, + }, + }); + const doneCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + assert.isTrue(doneCard.type === "subagent.updated" && doneCard.subagent.result === "Done."); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("settles OMP runs reported with non-terminal task-result statuses", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_cancel", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "pending", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + yield* takeEvent((event) => event.type === "background_work.updated"); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_wait", + toolName: "wait", + isError: false, + result: { + content: [ + { + type: "text", + text: '', + }, + ], + details: {}, + }, + }); + const interruptedCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "interrupted", + ); + assert.isTrue(interruptedCard.type === "subagent.updated"); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("parses OMP task-result blocks regardless of attribute order", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_order", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "pending", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + yield* takeEvent((event) => event.type === "background_work.updated"); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_wait", + toolName: "wait", + isError: false, + result: { + content: [ + { + type: "text", + text: '\n\n\nOK.\n\n', + }, + ], + details: {}, + }, + }); + const doneCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + assert.isTrue(doneCard.type === "subagent.updated" && doneCard.subagent.result === "OK."); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("interrupts OMP runs still tracked when the agent settles without waiting", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_never", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "pending", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + yield* takeEvent((event) => event.type === "background_work.updated"); + yield* fake.emit({ type: "agent_settled" }); + const interruptedCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "interrupted", + ); + assert.isTrue(interruptedCard.type === "subagent.updated"); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("shows the members of an async pi-subagents workflow as running subagents", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 17aadfc3fe4b5..b6fdc3a266246 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -473,6 +473,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const PI_PROVIDER = options.driverKind ?? PI_DRIVER_KIND; const defaultBinary = options.defaultBinary ?? "pi"; const subagentToolName = options.subagentToolName ?? "subagent"; + // OMP's `task` tool ships OMP-shaped details: progress[] updates, output results, + // async.jobId background runs, and settled results delivered through `wait`. + // pi-subagents ships results[] and settles through the subagent-async widget. + const ompTaskDetails = subagentToolName !== "subagent"; const providerRef = ( nativeId: string, strength: "strong" | "weak" = "strong", @@ -649,15 +653,16 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const customAnswerFollowUps = new Map(); const sessionApprovals = new Set(); // Async pi-subagents runs launched in this session, by async id, until they settle. - // omp `task` runs are tracked by job id; `members` names the spawned subagents - // so `wait` results can settle them. + // omp `task` runs are tracked by job id; `members` maps spawned subagent id -> + // agent label so `wait` results (and run teardown) can settle them. const piAsyncRuns = new Map< string, { readonly turn: ActivePiTurn; readonly toolCallId: string; readonly emitted: Map; - readonly members: Set; + readonly members: Map; + readonly omp: boolean; } >(); // The launch snapshot arrives before the tool result that names its run. @@ -1536,11 +1541,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }, }); if (toolName === subagentToolName) { - yield* emitSubagentTasks(turn, toolCallId, resultRecord, completed); + yield* emitSubagentTasks( + turn, + toolCallId, + resultRecord, + completed, + isError, + ompTaskDetails, + ); } // omp settles background `task` runs through `wait` results; pi members // arrive in the subagent-async widget instead. - if (toolName === "wait" && piAsyncRuns.size > 0) { + if (toolName === "wait" && ompTaskDetails && piAsyncRuns.size > 0) { yield* settleOmpWaitResults(resultRecord); } }); @@ -1550,6 +1562,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( toolCallId: string, resultRecord: unknown, completed: boolean, + isError: boolean, + ompTaskDetails: boolean, ) { const details = recordField(resultRecord, "details"); const results = recordField(details, "results"); @@ -1557,7 +1571,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (Array.isArray(results)) { for (const [index, result] of results.entries()) { const agent = recordString(result, "agent"); - const task = recordString(result, "assignment") ?? recordString(result, "task"); + const task = ompTaskDetails + ? (recordString(result, "assignment") ?? recordString(result, "task")) + : recordString(result, "task"); if (agent === undefined || task === undefined) continue; emitted = true; const finished = completed || recordField(result, "finished") === true; @@ -1567,8 +1583,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( finished && !interrupted && ((recordNumber(result, "exitCode") ?? 0) !== 0 || stopReason === "error"); - const outputText = piSubagentOutput(result); - yield* emitSubagent(turn, toolCallId, `${recordNumber(result, "step") ?? index}`, { + const outputText = piSubagentOutput(result, ompTaskDetails); + // One member key across progress and results, so the running card is + // the card that completes. omp results carry id; pi results carry step. + const memberKey = + recordString(result, "id") ?? `${recordNumber(result, "step") ?? index}`; + yield* emitSubagent(turn, toolCallId, memberKey, { agent, task, model: recordString(result, "model") ?? null, @@ -1584,29 +1604,41 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }); } } - // omp streams running members through `progress[]` while `results[]` is still empty. - if (!emitted) { + // omp streams running members through `progress[]` while `results[]` is + // still empty. pi-subagents has no progress[]; pi keeps main's behavior. + if (!emitted && ompTaskDetails) { const progress = recordField(details, "progress"); + const asyncJobId = recordString(recordField(details, "async"), "jobId"); if (Array.isArray(progress)) { for (const [index, entry] of progress.entries()) { const agent = recordString(entry, "agent"); if (agent === undefined) continue; emitted = true; const status = recordString(entry, "status") ?? "running"; - yield* emitSubagent(turn, toolCallId, recordString(entry, "id") ?? `${index}`, { - agent, - task: recordString(entry, "assignment") ?? recordString(entry, "task") ?? "", - model: null, - status: - status === "completed" - ? "completed" - : status === "failed" || status === "error" + yield* emitSubagent( + turn, + toolCallId, + recordString(entry, "id") ?? asyncJobId ?? `${index}`, + { + agent, + task: recordString(entry, "assignment") ?? recordString(entry, "task") ?? "", + model: null, + // The tool ended without results: its members never ran to + // completion, so non-terminal statuses end as interrupted/failed. + status: completed + ? isError ? "failed" - : status === "aborted" - ? "interrupted" - : "running", - result: null, - }); + : "interrupted" + : status === "completed" + ? "completed" + : status === "failed" || status === "error" + ? "failed" + : status === "aborted" + ? "interrupted" + : "running", + result: null, + }, + ); } } } @@ -1614,15 +1646,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( // widget, omp members in `wait` results. Track the run until it settles. const asyncId = recordString(details, "asyncId") ?? recordString(recordField(details, "async"), "jobId"); - if (asyncId !== undefined && !piAsyncRuns.has(asyncId)) { + if (asyncId !== undefined && !piAsyncRuns.has(asyncId) && (ompTaskDetails || !emitted)) { const progress = recordField(details, "progress"); - const members = new Set( - (Array.isArray(progress) ? progress : []).flatMap((entry) => { + const members = new Map(); + if (ompTaskDetails) { + for (const entry of Array.isArray(progress) ? progress : []) { const id = recordString(entry, "id"); - return id === undefined ? [] : [id]; - }), - ); - const tracked = { turn, toolCallId, emitted: new Map(), members }; + if (id === undefined) continue; + members.set(id, recordString(entry, "agent") ?? asyncId); + } + // A spawn without progress ids can only settle by its job id. + if (members.size === 0) members.set(asyncId, asyncId); + } + const tracked = { + turn, + toolCallId, + emitted: new Map(), + members, + omp: ompTaskDetails, + }; piAsyncRuns.set(asyncId, tracked); // Keeps the run ingesting after the coordinator's turn ends, until the run settles. yield* emit({ @@ -1642,36 +1684,33 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (piAsyncRuns.size === 0) return; const outputText = contentText(recordField(resultRecord, "content")); if (outputText.length === 0) return; - const blockPattern = - /([\s\S]*?)<\/task-result>/g; + const blockPattern = /]*)>([\s\S]*?)<\/task-result>/g; for (const match of outputText.matchAll(blockPattern)) { - const id = match[1]; - const agent = match[2]; - const status = match[3]; - const body = match[4]; - if ( - id === undefined || - agent === undefined || - status === undefined || - body === undefined - ) { - continue; - } + const attrs = match[1]; + const body = match[2]; + if (attrs === undefined || body === undefined) continue; + const attribute = (name: string) => { + const found = new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(attrs); + return found?.[1]; + }; + const id = attribute("id"); + const agent = attribute("agent"); + const status = attribute("status") ?? ""; + if (id === undefined || agent === undefined) continue; const trackedEntry = [...piAsyncRuns.entries()].find(([, tracked]) => tracked.members.has(id), ); if (trackedEntry === undefined) continue; const [runId, tracked] = trackedEntry; const output = /([\s\S]*?)<\/output>/.exec(body)?.[1]?.trim() ?? ""; + // Every parsed block settles its member: completed/failed/error map to + // themselves; anything else (aborted, cancelled, timeout, …) to interrupted. const settled = status === "completed" ? "completed" : status === "failed" || status === "error" ? "failed" - : status === "aborted" - ? "interrupted" - : undefined; - if (settled === undefined) continue; + : "interrupted"; yield* emitSubagent(tracked.turn, tracked.toolCallId, id, { agent, task: "", @@ -1682,19 +1721,44 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tracked.members.delete(id); if (tracked.members.size === 0) { piAsyncRuns.delete(runId); - const providerTurnId = tracked.turn.providerTurn.id; - const stillPending = [...piAsyncRuns.values()].some( - (other) => other.turn.providerTurn.id === providerTurnId, - ); - if (!stillPending) { - yield* emit({ - type: "background_work.updated", - driver: PI_PROVIDER, - providerTurnId, - pending: false, - }); - } + yield* clearPendingWhenTurnIdle(tracked); + } + } + }); + + // omp runs never settled by a `wait` result (the agent settled or was + // stopped first): mark their members interrupted and release the turn. + const dropUnsettledOmpRuns = Effect.fnUntraced(function* () { + for (const [runId, tracked] of piAsyncRuns) { + if (!tracked.omp) continue; + piAsyncRuns.delete(runId); + for (const [id, agent] of tracked.members) { + yield* emitSubagent(tracked.turn, tracked.toolCallId, id, { + agent, + task: "", + model: null, + status: "interrupted", + result: null, + }); } + yield* clearPendingWhenTurnIdle(tracked); + } + }); + + const clearPendingWhenTurnIdle = Effect.fnUntraced(function* (tracked: { + readonly turn: ActivePiTurn; + }) { + const providerTurnId = tracked.turn.providerTurn.id; + const stillPending = [...piAsyncRuns.values()].some( + (other) => other.turn.providerTurn.id === providerTurnId, + ); + if (!stillPending) { + yield* emit({ + type: "background_work.updated", + driver: PI_PROVIDER, + providerTurnId, + pending: false, + }); } }); @@ -2707,6 +2771,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } case "agent_settled": { + yield* dropUnsettledOmpRuns(); if (turn?.interrupted === true) { if (state === null) return; const liveState = yield* request({ type: "get_state" }, 2_000).pipe( @@ -4500,7 +4565,7 @@ function piAsyncSubagentStatus( } } -function piSubagentOutput(result: unknown): string { +function piSubagentOutput(result: unknown, preferOutput = false): string { const stopReason = recordString(result, "stopReason"); const failed = (recordNumber(result, "exitCode") ?? 0) !== 0 || @@ -4511,8 +4576,10 @@ function piSubagentOutput(result: unknown): string { if (failure !== undefined && failure.length > 0) return failure; } // omp `task` results carry the subagent's final output in `output`. - const output = recordString(result, "output"); - if (output !== undefined && output.length > 0) return output; + if (preferOutput) { + const output = recordString(result, "output"); + if (output !== undefined && output.length > 0) return output; + } const messages = recordField(result, "messages"); if (!Array.isArray(messages)) return ""; for (let index = messages.length - 1; index >= 0; index -= 1) { From cd612152189f13a9ce8ceb4ae041b7e42ac72abb Mon Sep 17 00:00:00 2001 From: Gustav RLo <40185279+GustavBlack@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:19:31 -0800 Subject: [PATCH 3/5] fix(provider-omp): settle OMP task runs on omp's session_settled OMP never emits Pi's `agent_settled`. Its RPC ends a stretch of agent activity with `agent_end` per run followed by one `session_settled` (coding-agent/src/modes/rpc/rpc-session-settle.ts), so the teardown added for review could not fire in a live OMP session: background `task` runs still tracked at agent end kept `background_work.updated pending: true`. The `agent_settled` case now also matches `session_settled`, gated on the OMP flavor so Pi's path is unchanged. The failing-first test replays omp 19.2.0 frames (`agent_end` then `session_settled`) and asserts the running card's id is the one that settles interrupted, with the run released. Verified against live omp 19.2.0 RPC: `session_settled` arrives once per turn after each `agent_end`, and no `agent_settled` frame exists. --- .../provider-pi/src/server/adapter.test.ts | 99 +++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 6 +- 2 files changed, 104 insertions(+), 1 deletion(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index e74432f3fb25a..166075a7036f4 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4441,6 +4441,105 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("interrupts OMP runs still tracked when omp's session settles", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_update", + toolCallId: "call_omp_never", + toolName: "task", + partialResult: { + content: [{ type: "text", text: "Running agent GammaWriter..." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 89, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + }, + }, + }); + const runningCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "running", + ); + assert.isTrue(runningCard.type === "subagent.updated"); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_never", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + const pendingSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && event.pending, + ); + assert.isTrue(pendingSignal.type === "background_work.updated"); + // Frames as omp 19.2.0 ends a stretch of activity: `agent_end` per run, then one + // `session_settled`; it never emits Pi's `agent_settled`. + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "session_settled" }); + const interruptedCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "interrupted", + ); + const runningId = runningCard.type === "subagent.updated" ? runningCard.subagent.id : null; + assert.isTrue( + interruptedCard.type === "subagent.updated" && + runningId !== null && + interruptedCard.subagent.id === runningId, + ); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("shows the members of an async pi-subagents workflow as running subagents", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index b6fdc3a266246..c05149ca68316 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -2770,7 +2770,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( yield* emitExtensionError(event); return; } - case "agent_settled": { + case "agent_settled": + // OMP never emits Pi's `agent_settled`: its RPC ends a stretch of agent + // activity with one `session_settled` after `agent_end` (rpc-session-settle). + case "session_settled": { + if (event["type"] === "session_settled" && !ompTaskDetails) return; yield* dropUnsettledOmpRuns(); if (turn?.interrupted === true) { if (state === null) return; From 6149df59205410f1414a1377bace22e7530143d4 Mon Sep 17 00:00:00 2001 From: Gustav RLo <40185279+GustavBlack@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:31:46 -0800 Subject: [PATCH 4/5] fix(provider-omp): keep background task runs tracked across omp's session settle Review blocker on #31: `session_settled` fires once per turn, and omp's settle predicate excludes deliveries it has suppressed (a `wait` in flight, a foreground job, a user-interrupted run). Dropping every tracked run at `session_settled` therefore killed runs that were still live: the card was marked interrupted while its job still worked, and a later `wait` could not settle it because the run was already gone from `piAsyncRuns`. Tracking now ends only with evidence: - Runs settle from `` blocks wherever omp emits them: `wait` tool results and the `async-result` custom message it records when a job finishes without a waiting agent (same envelope, now parsed once). - A stopped turn still abandons its runs at `session_settled` (they cannot keep running after Stop), and a closing transport drops them with the process. - A background spawn's `tool_execution_end` no longer interrupts its own cards: `details.async.state: "running"` means the job continues, so its progress rows keep their status. Aborted/errored calls still end non-terminal members as interrupted/failed. A spawn that already settled is not tracked at all (previously a pending leak). Failing-first: "settles an OMP background run from its async-result delivery", "settles an OMP background run from a wait in a later turn", "interrupts OMP runs when the stopped session closes" (all three fail on the previous commit; the first two assert the running card's id is the one that settles, and that `background_work` clears). Plus "settles the OMP turn when omp's session settles" for the turn-lifecycle path the review asked to cover. adapter.test.ts: 184 pass, 2 skip, 1 fail (pre-existing Windows fork-path assertion at :3277, fails identically without this change). Typecheck, format and lint clean for packages/provider-pi. --- .../provider-pi/src/server/adapter.test.ts | 274 +++++++++++++++++- packages/provider-pi/src/server/adapter.ts | 72 +++-- 2 files changed, 316 insertions(+), 30 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 166075a7036f4..d32e2e32f8b07 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4381,7 +4381,7 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); - it.effect("interrupts OMP runs still tracked when the agent settles without waiting", () => + it.effect("settles an OMP background run from its async-result delivery", () => Effect.gen(function* () { const fake = yield* makeFakePi; const { runtime, takeEvent } = yield* openRuntime( @@ -4428,12 +4428,39 @@ describe("PiAdapterV2", () => { }, }, }); - yield* takeEvent((event) => event.type === "background_work.updated"); - yield* fake.emit({ type: "agent_settled" }); - const interruptedCard = yield* takeEvent( - (event) => event.type === "subagent.updated" && event.subagent.status === "interrupted", + const spawnedCard = yield* takeEvent((event) => event.type === "subagent.updated"); + const pendingSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && event.pending, + ); + assert.isTrue(pendingSignal.type === "background_work.updated"); + // omp ends a stretch of agent activity with `agent_end` + `session_settled` + // while a background job can still finish: the run must survive it. + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "session_settled" }); + // omp then delivers the finished job as an async-result custom message + // carrying the same envelope a `wait` result returns. + yield* fake.emit({ + type: "message_end", + message: { + role: "custom", + customType: "async-result", + content: + '\nBackground job GammaWriter has completed.\nResume your work using the result below.\n\n\n\n\nCreated gamma.txt with GAMMA.\n\n\n', + }, + }); + const settledCard = yield* takeEvent( + (event) => + event.type === "subagent.updated" && + (event.subagent.status === "completed" || event.subagent.status === "interrupted"), + ); + const spawnedId = spawnedCard.type === "subagent.updated" ? spawnedCard.subagent.id : null; + assert.isTrue( + settledCard.type === "subagent.updated" && + settledCard.subagent.status === "completed" && + settledCard.subagent.result === "Created gamma.txt with GAMMA." && + spawnedId !== null && + settledCard.subagent.id === spawnedId, ); - assert.isTrue(interruptedCard.type === "subagent.updated"); const settledSignal = yield* takeEvent( (event) => event.type === "background_work.updated" && !event.pending, ); @@ -4441,7 +4468,7 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); - it.effect("interrupts OMP runs still tracked when omp's session settles", () => + it.effect("interrupts OMP runs still tracked when a stopped turn settles", () => Effect.gen(function* () { const fake = yield* makeFakePi; const { runtime, takeEvent } = yield* openRuntime( @@ -4461,6 +4488,8 @@ describe("PiAdapterV2", () => { }); yield* startTurn(runtime, providerThread); yield* fake.takeRequest("prompt"); + const started = yield* takeEvent((event) => event.type === "provider_turn.updated"); + if (started.type !== "provider_turn.updated") return yield* Effect.die("Missing turn"); yield* fake.emit({ type: "agent_start" }); yield* fake.emit({ type: "tool_execution_update", @@ -4520,8 +4549,9 @@ describe("PiAdapterV2", () => { (event) => event.type === "background_work.updated" && event.pending, ); assert.isTrue(pendingSignal.type === "background_work.updated"); - // Frames as omp 19.2.0 ends a stretch of activity: `agent_end` per run, then one - // `session_settled`; it never emits Pi's `agent_settled`. + // Stop abandons the runs the stopped turn left behind: their cards cannot keep + // running, and omp settles the stopped stretch with `agent_end` + `session_settled`. + yield* runtime.interruptTurn({ providerThread, providerTurnId: started.providerTurn.id }); yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); yield* fake.emit({ type: "session_settled" }); const interruptedCard = yield* takeEvent( @@ -4540,6 +4570,232 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("settles an OMP background run from a wait in a later turn", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_later", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + const runningCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "running", + ); + yield* takeEvent((event) => event.type === "background_work.updated" && event.pending); + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "session_settled" }); + const firstTurn = yield* takeEvent((event) => event.type === "turn.terminal"); + assert.isTrue(firstTurn.type === "turn.terminal"); + // The next turn waits for the job the first turn spawned; the run it needs to + // settle has to have survived omp's per-turn `session_settled`. + yield* startTurn( + runtime, + providerThread, + "default", + [], + "Wait for the subagent", + undefined, + 2, + ); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_wait_later", + toolName: "wait", + isError: false, + result: { + content: [ + { + type: "text", + text: '## Completed (1)\n\n### GammaWriter [task] — completed\n```\n\n\n\nWrote GAMMA.\n\n\n```', + }, + ], + details: {}, + }, + }); + const settledCard = yield* takeEvent( + (event) => + event.type === "subagent.updated" && + (event.subagent.status === "completed" || event.subagent.status === "interrupted"), + ); + const runningId = runningCard.type === "subagent.updated" ? runningCard.subagent.id : null; + assert.isTrue( + settledCard.type === "subagent.updated" && + settledCard.subagent.status === "completed" && + settledCard.subagent.result === "Wrote GAMMA." && + runningId !== null && + settledCard.subagent.id === runningId, + ); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("settles the OMP turn when omp's session settles", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "session_settled" }); + const terminal = yield* takeEvent((event) => event.type === "turn.terminal"); + assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + + it.effect("interrupts OMP runs when the stopped session closes", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime( + fake, + "default", + THREAD_ID, + SESSION_ID, + undefined, + undefined, + undefined, + OMP_FLAVOR_OVERRIDE, + ); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + const started = yield* takeEvent((event) => event.type === "provider_turn.updated"); + if (started.type !== "provider_turn.updated") return yield* Effect.die("Missing turn"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ + type: "tool_execution_update", + toolCallId: "call_omp_closed", + toolName: "task", + partialResult: { + content: [{ type: "text", text: "Running agent GammaWriter..." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 89, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + }, + }, + }); + yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "running", + ); + yield* fake.emit({ + type: "tool_execution_end", + toolCallId: "call_omp_closed", + toolName: "task", + isError: false, + result: { + content: [{ type: "text", text: "Spawned agent `GammaWriter` (job `GammaWriter`)." }], + details: { + projectAgentsDir: null, + results: [], + totalDurationMs: 2, + progress: [ + { + index: 0, + id: "GammaWriter", + agent: "sonic", + agentSource: "bundled", + status: "running", + task: "Complete assignment thoroughly", + assignment: "# Target\nWrite GAMMA", + }, + ], + async: { state: "running", jobId: "GammaWriter", type: "task" }, + }, + }, + }); + yield* takeEvent((event) => event.type === "background_work.updated" && event.pending); + // Stop on a paused/compaction turn terminates the session instead of aborting it; + // the tracked run goes with the process and must not stay pending. + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: started.providerTurn.id, + requestRuntimeRestart: true, + }); + const interruptedCard = yield* takeEvent( + (event) => event.type === "subagent.updated" && event.subagent.status === "interrupted", + ); + assert.isTrue(interruptedCard.type === "subagent.updated"); + const settledSignal = yield* takeEvent( + (event) => event.type === "background_work.updated" && !event.pending, + ); + assert.isTrue(settledSignal.type === "background_work.updated"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("shows the members of an async pi-subagents workflow as running subagents", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index c05149ca68316..283c4ae518c9f 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -1553,7 +1553,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( // omp settles background `task` runs through `wait` results; pi members // arrive in the subagent-async widget instead. if (toolName === "wait" && ompTaskDetails && piAsyncRuns.size > 0) { - yield* settleOmpWaitResults(resultRecord); + yield* settleOmpTaskResults(contentText(recordField(resultRecord, "content"))); } }); @@ -1567,6 +1567,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const details = recordField(resultRecord, "details"); const results = recordField(details, "results"); + // A background spawn's task call ends while its job still runs: its progress + // rows are not abandoned by the tool ending, only by a job that never reports. + const asyncState = recordString(recordField(details, "async"), "state"); + const runContinues = asyncState === "running" || asyncState === "pending"; let emitted = false; if (Array.isArray(results)) { for (const [index, result] of results.entries()) { @@ -1623,19 +1627,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( agent, task: recordString(entry, "assignment") ?? recordString(entry, "task") ?? "", model: null, - // The tool ended without results: its members never ran to - // completion, so non-terminal statuses end as interrupted/failed. - status: completed - ? isError - ? "failed" - : "interrupted" - : status === "completed" - ? "completed" - : status === "failed" || status === "error" + // A run that still reports progress keeps its status; one the tool + // abandoned ends its non-terminal members as interrupted/failed. + status: + completed && !runContinues + ? isError ? "failed" - : status === "aborted" - ? "interrupted" - : "running", + : "interrupted" + : status === "completed" + ? "completed" + : status === "failed" || status === "error" + ? "failed" + : status === "aborted" + ? "interrupted" + : "running", result: null, }, ); @@ -1643,10 +1648,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } } // Async launches return no results; pi members arrive in the subagent-async - // widget, omp members in `wait` results. Track the run until it settles. + // widget, omp members in `wait`/async-result blocks. Track until it settles. const asyncId = recordString(details, "asyncId") ?? recordString(recordField(details, "async"), "jobId"); - if (asyncId !== undefined && !piAsyncRuns.has(asyncId) && (ompTaskDetails || !emitted)) { + // A spawn that already settled (a blocking spawn reports the finished job) + // has nothing to track: its members arrived in `results`. + const asyncSettled = asyncState !== undefined && !runContinues; + if ( + asyncId !== undefined && + !asyncSettled && + !piAsyncRuns.has(asyncId) && + (ompTaskDetails || !emitted) + ) { const progress = recordField(details, "progress"); const members = new Map(); if (ompTaskDetails) { @@ -1678,11 +1691,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } }); - // omp delivers background `task` results through `wait` tool results as - // task-result blocks; settle the tracked run's members from them. - const settleOmpWaitResults = Effect.fnUntraced(function* (resultRecord: unknown) { + // omp delivers background `task` results through `` blocks: in + // `wait` tool results, and in the `async-result` follow-up message it records + // when a job finishes without a waiting agent. Both settle the tracked run. + const settleOmpTaskResults = Effect.fnUntraced(function* (outputText: string) { if (piAsyncRuns.size === 0) return; - const outputText = contentText(recordField(resultRecord, "content")); if (outputText.length === 0) return; const blockPattern = /]*)>([\s\S]*?)<\/task-result>/g; for (const match of outputText.matchAll(blockPattern)) { @@ -2592,8 +2605,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } case "message_end": { - if (turn === null) return; const message = event["message"]; + // omp records a finished background job as an `async-result` custom + // message carrying the same `` envelope a `wait` returns. + if ( + ompTaskDetails && + recordString(message, "role") === "custom" && + recordString(message, "customType") === "async-result" + ) { + yield* settleOmpTaskResults(contentText(recordField(message, "content"))); + return; + } + if (turn === null) return; if (recordString(message, "role") !== "assistant") return; yield* completeOpenStreamItems(turn); const reportedProvider = recordString(message, "provider"); @@ -2775,8 +2798,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( // activity with one `session_settled` after `agent_end` (rpc-session-settle). case "session_settled": { if (event["type"] === "session_settled" && !ompTaskDetails) return; - yield* dropUnsettledOmpRuns(); + // A `session_settled` proves no run is live, not that a background job + // finished (omp excludes suppressed deliveries), so only a stopped turn + // abandons its runs. Live runs settle from their `wait`/async-result + // results; a closing session drops them in the transport handler. if (turn?.interrupted === true) { + yield* dropUnsettledOmpRuns(); if (state === null) return; const liveState = yield* request({ type: "get_state" }, 2_000).pipe( Effect.orElseSucceed(() => undefined), @@ -3104,6 +3131,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( protocolError("Pi transport closed during rollback"), ); pendingWake = null; + // The process is gone along with every background job: settle the runs + // still tracked so their cards and `background_work` do not hang. + yield* dropUnsettledOmpRuns(); const interrupted = state?.activeTurn?.interrupted === true; if (state?.activeTurn != null) { state.activeTurn.failure = interrupted From 5f3ea951aa073117e1803d545ac41328be41380f Mon Sep 17 00:00:00 2001 From: Gustav RLo <40185279+GustavBlack@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:05:30 -0800 Subject: [PATCH 5/5] test(provider-pi): build historical-fork fixture paths with path.join `recovers a historical Pi fork recorded before turns stored the session file` built its fixture paths as `${dir}/original.jsonl` from the OS temp directory. The fork scans that directory with `path.join`, so on Windows the adapter passes `C:\tmp\x\original.jsonl` to `--fork` while the test expected the mixed-separator `C:\tmp\x/original.jsonl`: the same file, a different string, and the only failing test in adapter.test.ts on Windows. Join the fixture paths the way production does. On POSIX `path.join` yields the identical strings, so the assertion is unchanged there. adapter.test.ts is now 185 pass / 2 skip / 0 fail on Windows. --- packages/provider-pi/src/server/adapter.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index d32e2e32f8b07..738fd40e0139a 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CheckpointId, @@ -3225,9 +3226,11 @@ describe("PiAdapterV2", () => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const dir = yield* fs.makeTempDirectoryScoped(); - const oldFile = `${dir}/original.jsonl`; - const unrelatedFile = `${dir}/unrelated.jsonl`; - const currentFile = `${dir}/current.jsonl`; + // The fork scans the session directory with `path.join`, which normalizes the + // separator on Windows too: build these the same way so both sides match. + const oldFile = NodePath.join(dir, "original.jsonl"); + const unrelatedFile = NodePath.join(dir, "unrelated.jsonl"); + const currentFile = NodePath.join(dir, "current.jsonl"); const header = { type: "session", version: 3 }; const writeSession = (file: string, entries: ReadonlyArray) => fs.writeFileString(