diff --git a/packages/core/src/session/subagent-job.ts b/packages/core/src/session/subagent-job.ts index 33a5432c381..d9b8ddc4413 100644 --- a/packages/core/src/session/subagent-job.ts +++ b/packages/core/src/session/subagent-job.ts @@ -17,9 +17,17 @@ import { SubagentMetadata } from "./subagent-metadata.js" type Recovery = Extract +// A foreground continuation of a backgrounded child claims that child's running generation: it +// silences the busy period it waits for, then returns the answer itself. +export type Claim = { + readonly generation: number + readonly notify: boolean +} + export type Input = { readonly recovery: Recovery readonly notify: boolean + readonly claimed?: Claim } type Completion = Pick & { @@ -37,6 +45,8 @@ export interface Interface { complete: (input: Completion) => Effect.Effect background: (input: Input) => Effect.Effect notify: (recovery: Recovery, startedAt: number) => Effect.Effect + claim: (recovery: Recovery) => Effect.Effect + release: (recovery: Recovery, claim: Claim) => Effect.Effect } export class Service extends Context.Service()("@opencode/SubagentJob") {} @@ -77,6 +87,25 @@ const make: Effect.Effect< }).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void)) }) + // A foreground continuation of a running backgrounded child holds its own answer, so it silences + // that busy period before its prompt is admitted: core settlement and the observer forked by the + // original launch both read this preference, and either would report a duplicate. Only a + // backgrounded generation carries a notificationID; a foreground generation keeps the block path. + const claim = Effect.fn("SubagentJob.claim")(function* (recovery: Recovery) { + const job = yield* jobs.get(recovery.childSessionID) + if (job?.status !== "running" || job.notificationID === undefined) return undefined + const session = yield* sessions + .get(recovery.childSessionID) + .pipe(Effect.catchTag("Session.NotFoundError", () => Effect.succeed(undefined))) + if (session === undefined) return undefined + const notify = SubagentMetadata.notify(session.metadata) + if (SubagentMetadata.withNotify(session.metadata, false) !== undefined) yield* writeNotify(recovery, false) + return { generation: job.started_at, notify } + }) + + // A prompt that never reached the child leaves the original launch owing its report. + const release = (recovery: Recovery, claim: Claim) => writeNotify(recovery, claim.notify) + // Resume once for launch, then wait until the child is idle. A backgrounded job also waits for // its background work and input, so its report carries the final answer; a foreground caller // takes the answer inline as soon as the child stops. Never resume just to inspect settlement: @@ -205,8 +234,10 @@ const make: Effect.Effect< complete, start: (input: Input) => Effect.gen(function* () { - yield* writeNotify(input.recovery, input.notify) - return yield* jobs.start({ + // A claim keeps the child silent until its foreground caller returns the answer. Writing the + // caller's own preference here would reopen the duplicate report the claim exists to prevent. + yield* writeNotify(input.recovery, input.claimed ? false : input.notify) + const info = yield* jobs.start({ id: input.recovery.childSessionID, type: "subagent", title: input.recovery.description, @@ -214,6 +245,11 @@ const make: Effect.Effect< recovery: input.recovery, run: run(input.recovery.childSessionID, jobs.isBackgrounded(input.recovery.childSessionID)), }) + // The claimed generation settled before the join, so start forked a new foreground + // generation: it reports through its own blocker, and this call's preference comes back. + if (input.claimed && info.started_at !== input.claimed.generation) + yield* writeNotify(input.recovery, input.notify) + return info }).pipe(Effect.setContext(context)), background: Effect.fn("SubagentJob.background")(function* (input: Input) { yield* writeNotify(input.recovery, input.notify) @@ -221,6 +257,8 @@ const make: Effect.Effect< if (info) yield* notify(input.recovery, info.started_at) }), notify, + claim, + release, }) }) diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index 4982234ad23..fd067fd1e46 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -27,6 +27,18 @@ const backgroundResult = (sessionID: SessionSchema.ID) => ({ ].join("\n"), }) +// Both wait paths end here: the inline answer a foreground caller returns, or a failure that keeps +// the sessionID visible so the model can continue the child. +const inline = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, info: Job.Info | undefined) { + if (info?.status === "error") + return yield* new ToolFailure({ + message: `Subagent failed (sessionID: ${sessionID}): ${info.error ?? "unknown error"}`, + }) + if (info?.status === "cancelled") + return yield* new ToolFailure({ message: `Subagent cancelled (sessionID: ${sessionID})` }) + return { sessionID, status: "completed" as const, output: info?.output ?? SubagentCompletion.NO_TEXT } +}) + export const Input = Schema.Struct({ agent: Schema.String.annotate({ description: @@ -204,8 +216,20 @@ export const Plugin = { const background = input.background !== false const notify = input.notify !== false + const recovery = { + kind: "subagent" as const, + parentSessionID: context.sessionID, + childSessionID: child.id, + agent: agent.name, + description: input.description, + } yield* context.progress({ sessionID: child.id, status: "running" }) + // A foreground continuation of a backgrounded child waits for that job itself, so it + // silences the child before the prompt can settle: neither core settlement nor the + // original launch's observer may report the busy period this caller returns inline. + const claimed = existing !== undefined && !background ? yield* subagents.claim(recovery) : undefined + // Standard prompt admission outside the job: Job.start joining a running child skips // its run effect, and the default wake starts an idle child or steers a running one. // A new child admits only, so the job owns the first drain and its foreground block @@ -223,46 +247,35 @@ export const Plugin = { Effect.mapError( (error) => new ToolFailure({ message: `Failed to prompt subagent: ${child.id}`, error }), ), + // A prompt that never reached the child leaves the original launch owing its report. + Effect.tapError(() => (claimed === undefined ? Effect.void : subagents.release(recovery, claimed))), ) - const recovery = { - kind: "subagent" as const, - parentSessionID: context.sessionID, - childSessionID: child.id, - agent: agent.name, - description: input.description, - } - yield* subagents.start({ recovery, notify }) + const started = yield* subagents.start({ recovery, notify, claimed }) if (background) { yield* subagents.background({ recovery, notify }) return backgroundResult(child.id) } - const result = yield* jobs.block({ id: child.id, sessionID: context.sessionID }).pipe( - Effect.onInterrupt(() => - Effect.all([sessions.interrupt(child.id), jobs.cancel(child.id)], { - discard: true, - }), - ), + const stopChild = Effect.onInterrupt(() => + Effect.all([sessions.interrupt(child.id), jobs.cancel(child.id)], { + discard: true, + }), ) + // The joined generation is already backgrounded, so jobs.block would return a running + // handle at once; await its done instead. A wait does not consume recovery jobs, and + // it resolves on completion, failure and cancellation alike. + if (claimed !== undefined && started.started_at === claimed.generation) + return yield* inline(child.id, (yield* jobs.wait({ id: child.id }).pipe(stopChild)).info) + + const result = yield* jobs.block({ id: child.id, sessionID: context.sessionID }).pipe(stopChild) if (result?.type === "backgrounded") { // The observer clears the durable marker even for a silent child. yield* subagents.notify(recovery, result.info.started_at) return backgroundResult(child.id) } - // Failure surfaces keep the sessionID visible so the model can continue the child. - if (result?.info.status === "error") - return yield* new ToolFailure({ - message: `Subagent failed (sessionID: ${child.id}): ${result.info.error ?? "unknown error"}`, - }) - if (result?.info.status === "cancelled") - return yield* new ToolFailure({ message: `Subagent cancelled (sessionID: ${child.id})` }) - return { - sessionID: child.id, - status: "completed" as const, - output: result?.info.output ?? SubagentCompletion.NO_TEXT, - } + return yield* inline(child.id, result?.info) }).pipe( Effect.map((output) => ({ output, diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 3c9e15730c4..7aca288cb1e 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect" +import { Deferred, Effect, Fiber, Layer, Option, Schema, Stream } from "effect" import { LanguageModel } from "@opencode/ai/effect" import { OpenAIChat } from "@opencode/ai/protocols" import { TestLLM } from "@opencode/ai/testing" @@ -757,6 +757,81 @@ describe("SubagentTool", () => { ), ) + it.live("a foreground follow-up waits for a running background child and returns its answer inline", () => + tmpdirScoped().pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const sessions = yield* Session.Service + const parent = yield* sessions.create({ location, model: parentModel }) + const child = yield* sessions.create({ + parentID: parent.id, + title: "review", + agent: Agent.ID.make("reviewer"), + model: childModel, + }) + yield* withSubagent(parent.location) + const locations = yield* LocationServiceMap.Service + const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) + const jobs = yield* Job.Service + const gate = yield* Deferred.make() + // Recovery is what lets the launch's backgrounding assign a notificationID; a foreground + // generation has none, and no backgrounded generation exists to claim without one. + yield* jobs.start({ + id: child.id, + type: SubagentTool.name, + recovery: { + kind: "subagent", + parentSessionID: parent.id, + childSessionID: child.id, + agent: "reviewer", + description: "review", + }, + run: Deferred.await(gate).pipe(Effect.as(childText)), + }) + const followUp = (id: string, input: { background?: boolean }) => + executeTool(registry, { + sessionID: parent.id, + ...toolIdentity, + call: { + type: "tool-call", + id, + name: SubagentTool.name, + input: { agent: "reviewer", description: "follow up", prompt: id, sessionID: child.id, ...input }, + }, + }) + + // No flag: background is the default, so this backgrounds the child's running generation. + expect(yield* followUp("call-launch", {})).toMatchObject({ + metadata: { sessionID: child.id, status: "running" }, + }) + + const fiber = yield* followUp("call-wait", { background: false }).pipe( + Effect.forkScoped({ startImmediately: true }), + ) + // The child is still running, so the foreground continuation waits instead of handing back + // a running handle the way a block would. + expect(Option.isNone(yield* Fiber.join(fiber).pipe(Effect.timeoutOption("250 millis")))).toBe(true) + expect((yield* sessions.get(child.id)).metadata?.["subagent.notify"]).toBe(false) + + yield* Deferred.succeed(gate, undefined) + const result = yield* Fiber.join(fiber).pipe(Effect.timeout("2 seconds")) + expect(result).toMatchObject({ metadata: { sessionID: child.id, status: "completed" } }) + expect(result.content).toEqual([{ type: "text", text: completedOutput(child.id) }]) + + // The foreground caller returns the answer, so neither the job's observer nor core + // settlement may report the same busy period to the parent. + yield* jobs.pendingBackground.pipe( + Effect.repeat({ until: (pending) => pending.length === 0 }), + Effect.timeout("2 seconds"), + ) + expect((yield* sessions.inbox(parent.id)).filter((item) => item.type === "synthetic")).toEqual([]) + expect((yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")).toEqual([]) + }), + ), + ), + ) + it.live("rejects unrelated children and switches agents on continuation", () => tmpdirScoped().pipe( Effect.flatMap((dir) =>