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..738fd40e0139a 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -1,10 +1,12 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CheckpointId, ChatAttachmentId, EnvironmentId, NodeId, + ProviderDriverKind, ProviderInstanceId, ProviderSessionId, ProviderThreadId, @@ -529,6 +531,8 @@ const makeAdapter = Effect.fnUntraced(function* ( launchArgs = "", forkFake?: FakePi, continuationRequests?: PiAdapterV2Options["continuationRequests"], + driverKind?: ProviderDriverKind, + subagentToolName?: string, ) { const spawner = forkFake === undefined @@ -570,6 +574,8 @@ const makeAdapter = Effect.fnUntraced(function* ( customModels: [], }, environment: {}, + ...(driverKind === undefined ? {} : { driverKind }), + ...(subagentToolName === undefined ? {} : { subagentToolName }), }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); }); @@ -581,8 +587,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, @@ -3212,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( @@ -3833,6 +3849,956 @@ 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", + ); + 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." && + runningId !== null && + doneCard.subagent.id === runningId, + ); + }).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("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("settles an OMP background run from its async-result delivery", () => + 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" }, + }, + }, + }); + 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, + ); + 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("interrupts OMP runs still tracked when a stopped turn 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"); + 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_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"); + // 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( + (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("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 f1adce3b9e8cd..283c4ae518c9f 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,11 @@ 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", @@ -653,12 +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` 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: Map; + readonly omp: boolean; } >(); // The launch snapshot arrives before the tool result that names its run. @@ -1536,8 +1540,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...(viewedImagePath === undefined ? {} : { viewedImagePath }), }, }); - if (toolName === "subagent") { - yield* emitSubagentTasks(turn, toolCallId, resultRecord, completed); + if (toolName === subagentToolName) { + 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" && ompTaskDetails && piAsyncRuns.size > 0) { + yield* settleOmpTaskResults(contentText(recordField(resultRecord, "content"))); } }); @@ -1546,43 +1562,122 @@ 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"); - if (!Array.isArray(results)) return; + // 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; - 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 = 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; + 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, 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, + 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. 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") ?? asyncJobId ?? `${index}`, + { + agent, + task: recordString(entry, "assignment") ?? recordString(entry, "task") ?? "", + model: null, + // 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" + : "interrupted" + : 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`/async-result blocks. Track until it settles. + const asyncId = + recordString(details, "asyncId") ?? recordString(recordField(details, "async"), "jobId"); + // 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) { + for (const entry of Array.isArray(progress) ? progress : []) { + const id = recordString(entry, "id"); + 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({ @@ -1596,6 +1691,90 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } }); + // 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; + if (outputText.length === 0) return; + const blockPattern = /]*)>([\s\S]*?)<\/task-result>/g; + for (const match of outputText.matchAll(blockPattern)) { + 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" + : "interrupted"; + 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); + 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, + }); + } + }); + const emitSubagent = Effect.fnUntraced(function* ( turn: ActivePiTurn, toolCallId: string, @@ -2426,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"); @@ -2604,8 +2793,17 @@ 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; + // 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), @@ -2933,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 @@ -4398,7 +4599,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 || @@ -4408,6 +4609,11 @@ 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`. + 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) { @@ -4613,6 +4819,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", };