From e5eb2f39a1956b31afce47c043d4a78e481df9b8 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Wed, 4 Nov 2026 14:44:58 -0800 Subject: [PATCH] feat(core): report a settled subagent child to its parent from core A child Session with a parent now sends one `` synthetic to its parent when its coordinator busy period settles, without the subagent tool observing it. - `SubagentReport` snapshots job state (blocked, get, recovery, remembered period) inside `settled` before the terminal publish, then maps the outcome to completed/error/cancelled and admits through a local inbox adapter that mirrors `Session.synthetic` (steer delivery, wake only a live, non-reverting parent). `execution.ts` gains `SessionInbox.node`; `Session.Service` stays out of the execution layer. - Reports are keyed to the job's notification ID when a backgrounded live job owns the period, so the SubagentJob observer and restart recovery reconcile the same admission instead of adding a second message. A jobless period gets a fresh ID; a period whose job finished or was cancelled mid-flight stays silent because its observer already reported it. - Suppressed for shutdown interruption (restart owns it), a missing child or parent, a silent child, a foreground block, a running job without a notification ID, and a period that finished without an assistant message. - `SubagentCompletion.deliver` now takes a structural synthetic adapter, so the settle report does not need `Session.Service`. The report never calls `completeBackground`: the durable marker must outlive admission. - `Job.Interface` gains a `recovery` reader; `Job.Info` deliberately keeps it out so snapshots cannot leak it. The replay test in `tool-subagent.test.ts` now asserts the marker exists at admission instead of being `completed`, because settlement admits while the job is still running; it replays a completed row to model the crash it covers. --- packages/core/src/job.ts | 7 + packages/core/src/session/execution.ts | 47 +++-- .../src/session/execution/subagent-report.ts | 158 ++++++++++++++++ .../core/src/session/subagent-completion.ts | 18 +- packages/core/test/subagent-report.test.ts | 178 ++++++++++++++++++ packages/core/test/tool-subagent.test.ts | 16 +- 6 files changed, 401 insertions(+), 23 deletions(-) create mode 100644 packages/core/src/session/execution/subagent-report.ts create mode 100644 packages/core/test/subagent-report.test.ts diff --git a/packages/core/src/job.ts b/packages/core/src/job.ts index 066fe26abc7..55a5a56870c 100644 --- a/packages/core/src/job.ts +++ b/packages/core/src/job.ts @@ -116,6 +116,8 @@ export type BackgroundAllInput = { export interface Interface { readonly get: (id: string) => Effect.Effect + // Recovery data stays out of Info so job snapshots (JobList, the server map) cannot leak it. + readonly recovery: (id: string) => Effect.Effect // True only while a foreground caller holds a block registration for this job. Settlement, // cancellation and backgrounding clear it, so read it before awaiting anything else. readonly isBlocked: (id: string) => Effect.Effect @@ -289,6 +291,10 @@ export const make = Effect.gen(function* () { return job !== undefined && job.blockingSessions.size > 0 }) + const recovery: Interface["recovery"] = Effect.fn("Job.recovery")(function* (id) { + return (yield* SynchronizedRef.get(state.jobs)).get(id)?.recovery + }) + const start: Interface["start"] = Effect.fnUntraced(function* (input) { return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { @@ -543,6 +549,7 @@ export const make = Effect.gen(function* () { return Service.of({ get, + recovery, isBlocked, start, wait, diff --git a/packages/core/src/session/execution.ts b/packages/core/src/session/execution.ts index ce11a7a0f97..afd1acc3c46 100644 --- a/packages/core/src/session/execution.ts +++ b/packages/core/src/session/execution.ts @@ -13,6 +13,7 @@ import { SessionSchema } from "./schema.js" import { SessionStore } from "./store.js" import { toSessionError } from "./to-session-error.js" import { SessionInbox } from "./inbox.js" +import { SubagentReport } from "./execution/subagent-report.js" export interface Interface { /** Snapshots active execution owned by this process. */ @@ -58,6 +59,7 @@ export const layer = Layer.effect( const instances = yield* Instance.Service const bus = yield* Bus.Service const jobs = yield* Job.Service + const inbox = yield* SessionInbox.Service const db = (yield* Database.Service).db const reportLifecycle = (sessionID: SessionSchema.ID, effect: Effect.Effect) => effect.pipe( @@ -106,11 +108,21 @@ export const layer = Layer.effect( Reloaded: (result) => drain(sessionID, result.force, result.continuation, promotable, result.stepped), }) }) + const reports = SubagentReport.make({ + store, + jobs, + inbox, + // The coordinator is created below; a report only runs after a busy period has settled. + wake: (sessionID) => coordinator.wake(sessionID), + }) const coordinator = yield* SessionRunCoordinator.make({ started: (sessionID) => reportLifecycle( sessionID, - bus.publish(SessionEvent.Execution.Started, { sessionID }, claimOnCommit(sessionID)), + Effect.gen(function* () { + yield* reports.started(sessionID).pipe(Effect.ignoreCause) + yield* bus.publish(SessionEvent.Execution.Started, { sessionID }, claimOnCommit(sessionID)) + }), ), drain: (sessionID, force, promotable) => drain(sessionID, force, undefined, promotable), // One terminal observation per busy period, covering every coalesced drain. @@ -119,11 +131,12 @@ export const layer = Layer.effect( sessionID, Effect.gen(function* () { const outcome = terminal(exit, reason) + // Read before cancel and before the terminal publish: cancellation, job settlement and + // backgrounding all clear the blocking registrations this decision depends on. + const snap = yield* reports.snapshot(sessionID) if (outcome.type === "succeeded") { yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID }, releaseOnCommit(sessionID)) - return - } - if (outcome.type === "interrupted") { + } else if (outcome.type === "interrupted") { // Deliberate stops release the claim; shutdown keeps it for restart continuity. if (outcome.reason !== "shutdown") yield* jobs.cancel(sessionID) yield* bus.publish( @@ -131,16 +144,22 @@ export const layer = Layer.effect( { sessionID, reason: outcome.reason }, outcome.reason === "shutdown" ? undefined : releaseOnCommit(sessionID), ) - return + } else { + yield* bus.publish( + SessionEvent.Execution.Failed, + { + sessionID, + error: outcome.error, + }, + releaseOnCommit(sessionID), + ) } - yield* bus.publish( - SessionEvent.Execution.Failed, - { - sessionID, - error: outcome.error, - }, - releaseOnCommit(sessionID), - ) + // The claim is released above, so the parent observes this child's terminal first. The + // report must never fail: a settled hook that dies takes the busy period down for every + // waiter, including the subagent job draining this child. + yield* reports + .report(sessionID, outcome, snap) + .pipe(Effect.ignoreCause({ log: "Error", message: "Failed to report subagent completion" })) }), ), }) @@ -176,7 +195,7 @@ export const layer = Layer.effect( export const node = makeGlobalNode({ service: Service, layer, - deps: [SessionStore.node, Instance.node, Bus.node, Database.node, Job.node], + deps: [SessionStore.node, Instance.node, Bus.node, Database.node, Job.node, SessionInbox.node], }) /** Low-level compatibility layer for callers that only need durable Session recording. */ diff --git a/packages/core/src/session/execution/subagent-report.ts b/packages/core/src/session/execution/subagent-report.ts new file mode 100644 index 00000000000..20e8d5297ff --- /dev/null +++ b/packages/core/src/session/execution/subagent-report.ts @@ -0,0 +1,158 @@ +export * as SubagentReport from "./subagent-report.js" + +import { Effect } from "effect" +import type { Job } from "../../job.js" +import { SessionInbox } from "../inbox.js" +import { SessionMessage } from "../message.js" +import type { SessionSchema } from "../schema.js" +import type { SessionStore } from "../store.js" +import { SubagentCompletion } from "../subagent-completion.js" +import { SubagentMetadata } from "../subagent-metadata.js" + +type Recovery = Extract + +/** The terminal outcome of one busy period, the same mapping execution publishes. */ +export type Outcome = + | { readonly type: "succeeded" } + | { readonly type: "failed"; readonly error: { readonly message: string } } + | { readonly type: "interrupted"; readonly reason: "user" | "shutdown" } + +/** + * Job state read at settlement. Cancellation, backgrounding and job completion all clear it, so + * the snapshot must be taken before any of those happen in the same busy period. + */ +export type Snapshot = { + readonly blocked: boolean + readonly job: Job.Info | undefined + readonly recovery: Job.Recovery | undefined + readonly remembered: boolean +} + +export type Deps = { + readonly store: SessionStore.Interface + readonly jobs: Job.Interface + readonly inbox: SessionInbox.Interface + readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect +} + +/** + * Reports a settled subagent busy period to its parent, once per busy period, through a local + * inbox adapter. Observers and restart recovery keep their own delivery: every path admits the + * same notification ID, so first admission wins and the parent sees one message. + */ +export const make = (deps: Deps) => { + // Busy periods that began with a running job. That job owns its report whenever it finishes or + // is cancelled before settlement, so settlement must not send a second one. + const jobPeriods = new Set() + + const started = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { + const job = yield* deps.jobs.get(sessionID) + if (job?.status === "running") jobPeriods.add(sessionID) + // A finished entry from an earlier generation must not make a re-prompt silently reconcile. + else jobPeriods.delete(sessionID) + }) + + const snapshot = Effect.fnUntraced(function* (sessionID: SessionSchema.ID): Effect.fn.Return { + const remembered = jobPeriods.delete(sessionID) + return { + blocked: yield* deps.jobs.isBlocked(sessionID), + job: yield* deps.jobs.get(sessionID), + recovery: yield* deps.jobs.recovery(sessionID), + remembered, + } + }) + + // The same assistant message the SubagentJob run and restart recovery read: the newest + // completed assistant answer, whose text becomes the report body. + const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { + const messages = yield* deps.store.messages({ sessionID, order: "desc", limit: 20 }) + return messages.find( + (message) => message.type === "assistant" && message.time.completed !== undefined && message.error === undefined, + ) + }) + + const report = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, outcome: Outcome, snap: Snapshot) { + // Shutdown keeps the claim, and restart owns the report that resumes it. + if (outcome.type === "interrupted" && outcome.reason === "shutdown") return + const child = yield* deps.store.get(sessionID) + if (!child?.parentID) return + if (!SubagentMetadata.notify(child.metadata)) return + const parentID = child.parentID + if (!(yield* deps.store.get(parentID))) return + // A foreground caller receives this result inline through its own blocking registration. + if (snap.blocked) return + const live = snap.job?.status === "running" ? snap.job : undefined + // A running job without a notification is a foreground spawn whose block has not registered, + // or one whose block already returned. Either way that job owns the result. + if (live && !live.notificationID) return + // A job that finished or was cancelled mid-period already reported through its observer. + if (!live && snap.remembered) return + + const recovery = subagentRecovery(live?.notificationID ? snap.recovery : undefined, child, parentID) + const status = outcome.type === "succeeded" ? "completed" : outcome.type === "interrupted" ? "cancelled" : "error" + const assistant = status === "completed" ? yield* lastAssistant(child.id) : undefined + // A period that succeeded without finishing an assistant message was not a turn: a move, a + // compaction or a recovered notice settles that way, and a spawn that never ran reports + // through the tool's inline error instead. + if (status === "completed" && assistant === undefined) return + const output = status === "completed" ? SubagentCompletion.text(assistant) : undefined + const error = outcome.type === "failed" ? outcome.error.message : undefined + const notificationID = live?.notificationID + + yield* SubagentCompletion.deliver( + // Mirrors Session.synthetic without Session.Service: admit one steer synthetic, then wake + // only a live parent that is not staging a revert. + { + synthetic: (input) => + Effect.uninterruptible( + Effect.gen(function* () { + const admitted = yield* deps.inbox.admit({ + id: input.id ?? SessionMessage.ID.create(), + sessionID: input.sessionID, + item: { + type: "synthetic", + payload: SessionInbox.SyntheticPayload.make({ + text: input.text, + description: input.description, + metadata: input.metadata, + }), + delivery: "steer", + }, + }) + if (input.resume !== false && !(yield* deps.store.get(input.sessionID))?.revert) + yield* deps.wake(input.sessionID) + return admitted + }), + ), + }, + // The durable marker outlives admission: the job's observer or restart clears it with the + // same ID later. Clearing it here would erase a row those paths still reconcile against. + { completeBackground: () => Effect.void }, + { + status, + ...(output === undefined ? {} : { output }), + ...(error === undefined ? {} : { error }), + ...(notificationID === undefined ? {} : { notificationID }), + recovery, + }, + ) + }) + + return { started, snapshot, report } +} + +/** A live job's recovery already carries the spawn's agent name and description. */ +function subagentRecovery( + recovery: Job.Recovery | undefined, + child: SessionSchema.Info, + parentID: SessionSchema.ID, +): Recovery { + if (recovery?.kind === "subagent") return recovery + return { + kind: "subagent", + parentSessionID: parentID, + childSessionID: child.id, + agent: child.agent ?? "subagent", + description: child.title ?? "Subagent", + } +} diff --git a/packages/core/src/session/subagent-completion.ts b/packages/core/src/session/subagent-completion.ts index 79a00e112aa..138054ad7e6 100644 --- a/packages/core/src/session/subagent-completion.ts +++ b/packages/core/src/session/subagent-completion.ts @@ -2,11 +2,21 @@ export * as SubagentCompletion from "./subagent-completion.js" import { Effect } from "effect" import type { Job } from "../job.js" -import type { Session } from "../session.js" import type { SessionMessage } from "./message.js" +import type { SessionSchema } from "./schema.js" export const NO_TEXT = "Subagent completed without a text response." +/** The Session.synthetic input a completion needs, without depending on Session.Service. */ +export type SyntheticInput = { + readonly id?: SessionMessage.ID + readonly sessionID: SessionSchema.ID + readonly text: string + readonly description?: string + readonly metadata?: Record + readonly resume?: boolean +} + export function text(message: SessionMessage.Info | undefined) { if (message?.type !== "assistant") return NO_TEXT return ( @@ -18,8 +28,10 @@ export function text(message: SessionMessage.Info | undefined) { ) } -export const deliver = Effect.fnUntraced(function* ( - sessions: Pick, +export const deliver = Effect.fnUntraced(function* ( + sessions: { + readonly synthetic: (input: SyntheticInput) => Effect.Effect + }, jobs: Pick, input: Pick & { recovery: Extract diff --git a/packages/core/test/subagent-report.test.ts b/packages/core/test/subagent-report.test.ts new file mode 100644 index 00000000000..48b1f868f74 --- /dev/null +++ b/packages/core/test/subagent-report.test.ts @@ -0,0 +1,178 @@ +import { describe, expect } from "bun:test" +import { eq } from "drizzle-orm" +import { Effect, Layer } from "effect" +import { LanguageModel } from "@opencode/ai/effect" +import { OpenAIChat } from "@opencode/ai/protocols" +import { TestLLM } from "@opencode/ai/testing" +import { Agent } from "@opencode/core/agent" +import { Database } from "@opencode/core/database/database" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { LayerNodePlatform } from "@opencode/core/effect/app-node-platform" +import { Watcher } from "@opencode/core/filesystem/watcher" +import { Job } from "@opencode/core/job" +import { LocationServiceMap } from "@opencode/core/location-service-map" +import { Model } from "@opencode/core/model" +import { Provider } from "@opencode/core/provider" +import { AbsolutePath } from "@opencode/core/schema" +import { Session } from "@opencode/core/session" +import { SessionSchema } from "@opencode/core/session/schema" +import { SessionRunnerModel } from "@opencode/core/session/runner/model" +import { SessionTable } from "@opencode/core/session/sql" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Global } from "@opencode/util/global" +import { tempGlobalLayer } from "./fixture/global" +import { offlineModels } from "./fixture/models" +import { tmpdirScoped } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" + +const childText = "Review complete" +const llmLayer = TestLLM.testLayer({ fallback: TestLLM.text(childText, "review") }) +const it = testEffect( + Layer.merge( + llmLayer, + AppNodeBuilder.build(LayerNode.group([Database.node, Session.node, Job.node, LocationServiceMap.node]), [ + Global.node.replace(tempGlobalLayer), + offlineModels, + Watcher.node.replace(Watcher.configured({ enabled: false })), + LayerNodePlatform.llmClient.replace(llmLayer), + SessionRunnerModel.node.replace( + Layer.succeed(SessionRunnerModel.Service, { + resolve: () => + Effect.succeed( + SessionRunnerModel.resolved( + LanguageModel.make({ id: "review", provider: "test", route: OpenAIChat.route }), + { + capabilities: { tools: true, input: ["text"], output: ["text"] }, + cost: [], + limit: { context: 200_000, output: 32_000 }, + }, + ), + ), + }), + ), + ]), + ), +) + +const parentModel = Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }) + +/** A parent and its child in one directory, configured so the child may run without prompts. */ +const family = Effect.fnUntraced(function* (metadata?: SessionSchema.Metadata) { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => + Bun.write( + `${dir.path}/opencode.json`, + JSON.stringify({ + agents: { reviewer: { mode: "subagent" } }, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }), + ), + ) + const sessions = yield* Session.Service + const parent = yield* sessions.create({ + location: { directory: AbsolutePath.make(dir.path) }, + agent: Agent.ID.make("build"), + model: parentModel, + }) + const child = yield* sessions.create({ + parentID: parent.id, + agent: Agent.ID.make("reviewer"), + title: "Review fixture", + ...(metadata === undefined ? {} : { metadata }), + }) + return { sessions, parent, child } +}) + +const synthetics = (sessions: Session.Interface, sessionID: Session.ID) => + sessions.context(sessionID).pipe( + Effect.map((messages) => messages.filter((message) => message.type === "synthetic")), + ) + +describe("subagent report", () => { + it.live("reports a directly prompted child to its parent once", () => + Effect.gen(function* () { + const { sessions, parent, child } = yield* family() + yield* sessions.prompt({ sessionID: child.id, text: "Review the fixture" }) + yield* sessions.wait(child.id) + yield* sessions.wait(parent.id) + + const reports = yield* synthetics(sessions, parent.id) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + description: "Review fixture", + metadata: { source: "subagent", childID: child.id, agent: "reviewer", state: "completed" }, + }) + expect(reports[0]?.text).toContain(` + Effect.gen(function* () { + const { sessions, parent, child } = yield* family() + yield* sessions.prompt({ sessionID: child.id, text: "Review the fixture" }) + yield* sessions.wait(child.id) + yield* sessions.wait(parent.id) + yield* sessions.prompt({ sessionID: child.id, text: "Review it again" }) + yield* sessions.wait(child.id) + yield* sessions.wait(parent.id) + + const reports = yield* synthetics(sessions, parent.id) + expect(reports).toHaveLength(2) + expect(new Set(reports.map((report) => report.id)).size).toBe(2) + expect(reports.map((report) => report.metadata)).toEqual([ + expect.objectContaining({ childID: child.id, state: "completed" }), + expect.objectContaining({ childID: child.id, state: "completed" }), + ]) + }), + ) + + it.live("stays silent when the child asked not to notify", () => + Effect.gen(function* () { + const { sessions, parent, child } = yield* family({ "subagent.notify": false }) + yield* sessions.prompt({ sessionID: child.id, text: "Review the fixture" }) + yield* sessions.wait(child.id) + yield* sessions.wait(parent.id) + + expect(yield* synthetics(sessions, parent.id)).toEqual([]) + }), + ) + + it.live("reports a user interruption as cancelled", () => + Effect.gen(function* () { + const { sessions, parent, child } = yield* family() + const llm = yield* TestLLM.Test + const gate = yield* llm.gate() + yield* sessions.prompt({ sessionID: child.id, text: "Review the fixture" }) + yield* gate.started + yield* sessions.interrupt(child.id) + yield* gate.release + yield* sessions.wait(child.id) + yield* sessions.wait(parent.id) + + const reports = yield* synthetics(sessions, parent.id) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + metadata: { source: "subagent", childID: child.id, state: "cancelled" }, + }) + }), + ) + + it.live("settles without a parent", () => + Effect.gen(function* () { + const { sessions, child } = yield* family() + const database = yield* Database.Service + yield* database.db + .update(SessionTable) + .set({ parent_id: Session.ID.make("ses_missing_parent") }) + .where(eq(SessionTable.id, child.id)) + .run() + yield* sessions.prompt({ sessionID: child.id, text: "Review the fixture" }) + + yield* sessions.wait(child.id) + expect((yield* sessions.get(child.id)).parentID).toBe(Session.ID.make("ses_missing_parent")) + }), + ) +}) diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index e8e28b54385..aaec8ee80dc 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -237,8 +237,10 @@ describe("SubagentTool", () => { if (event.data.sessionID !== parent.id || event.data.item.type !== "synthetic") return notifications.push(event.data.inboxID) const marker = (yield* jobs.pendingBackground).find((job) => job.notificationID === event.data.inboxID) - // The marker must survive until admission commits, not merely until delivery starts. - expect(marker?.status).toBe("completed") + // The durable marker must survive until admission commits, not merely until delivery + // starts. Settlement now admits while the job is still running, so the marker is not + // yet terminal here; the job's own observer clears it with the same ID afterwards. + expect(marker).toBeDefined() if (marker) yield* Deferred.succeed(admitted, marker) }), ) @@ -271,7 +273,9 @@ describe("SubagentTool", () => { }), ]) - // Reproduce a crash after admission but before acknowledgment using the real persisted row. + // Reproduce a crash after the job persisted its completed marker but before it was + // acknowledged. Admission now happens while the job is still running, so the marker + // captured at enqueue is not yet terminal: replay the durable row the job leaves behind. const database = yield* Database.Service yield* database.db .insert(JobTable) @@ -282,9 +286,9 @@ describe("SubagentTool", () => { child_session_id: outputSessionID(result.metadata), kind: marker.recovery.kind, title: "background review", - status: marker.status, - output: marker.output ?? null, - error: marker.error ?? null, + status: "completed", + output: childText, + error: null, recovery: marker.recovery, }) .run()