diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 8660a673c9b..7906c09d951 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -54,6 +54,7 @@ import { DestinationNotDirectoryError, DestinationUnavailableError, } from "./session/move.js" +import { ForkNotice } from "./session/fork-notice.js" import { SessionModelTransport } from "./session/model-transport.js" import { llmClient } from "./effect/app-node-platform.js" import { Snapshot } from "./snapshot.js" @@ -339,7 +340,7 @@ const layer = Layer.effect( fork: Effect.fn("Session.fork")(function* (input) { const parent = yield* result.get(input.sessionID) const boundary = yield* db - .select({ id: SessionMessageTable.id }) + .select({ id: SessionMessageTable.id, time: SessionMessageTable.time_created }) .from(SessionMessageTable) .where( and( @@ -379,7 +380,24 @@ const layer = Layer.effect( ...inherited, }) .pipe(Effect.provideService(SessionBlob.ForkMedia, media)) - return yield* result.get(sessionID).pipe(Effect.orDie) + const forked = yield* result.get(sessionID).pipe(Effect.orDie) + // Append-only: the notice is a new admission after the copied rows, so the + // copied prompt-cache prefix stays byte-identical. It waits in the inbox as a + // steer and never wakes this fork's runner on creation. + const copied = yield* store.messages({ sessionID, order: "asc" }).pipe(Effect.orDie) + const children = yield* store.list({ parentID: parent.id }).pipe(Effect.orDie) + const subagents = yield* ForkNotice.collect({ messages: copied, children, jobs }) + yield* result + .synthetic({ + sessionID, + description: "Fork notice", + text: ForkNotice.text({ forkOf: parent.id, title: parent.title, time: boundary.time, subagents }), + metadata: { source: "fork", forkOf: parent.id }, + resume: false, + }) + // A fresh message ID cannot conflict; keep the public error channel unchanged. + .pipe(Effect.catchTag("Session.SyntheticConflictError", Effect.die)) + return forked }), get: (sessionID) => sessions.forSession(sessionID).get(), environment: Effect.fn("Session.environment")(function* (input) { diff --git a/packages/core/src/session/fork-notice.ts b/packages/core/src/session/fork-notice.ts new file mode 100644 index 00000000000..1e1f3ee25f9 --- /dev/null +++ b/packages/core/src/session/fork-notice.ts @@ -0,0 +1,93 @@ +export * as ForkNotice from "./fork-notice.js" + +import { DateTime, Effect } from "effect" +import type { Session } from "@opencode/schema/session" +import type { Job } from "../job.js" +import type { SessionMessage } from "./message.js" + +export type Subagent = { + readonly sessionID: string + readonly description: string + readonly state: string +} + +const outstanding = "These subagents of the original were still outstanding when this fork was made:" + +const closing = + "Don't wait for these. Their results won't arrive here. Start a new subagent if this fork needs that work." + +/** + * Names the original's work that keeps reporting to the original: background + * launches in the copied history with no later report, and children that still + * hold a running subagent job. + */ +export const collect = (input: { + readonly messages: readonly SessionMessage.Info[] + readonly children: readonly Session.Info[] + readonly jobs: Pick +}): Effect.Effect => + Effect.gen(function* () { + // Map order keeps transcript order for launched entries while deduping by child. + const subagents = new Map() + input.messages.forEach((message, index) => { + if (message.type !== "assistant") return + for (const part of message.content) { + if (part.type !== "tool" || part.name !== "subagent" || part.state.status === "streaming") continue + if (part.state.input.background !== true) continue + const sessionID = part.state.metadata?.sessionID + if (typeof sessionID !== "string" || subagents.has(sessionID)) continue + if (input.messages.slice(index + 1).some((later) => mentions(later, report(sessionID)))) continue + const description = part.state.input.description + subagents.set(sessionID, { + sessionID, + description: typeof description === "string" ? description : "subagent", + state: "unreported", + }) + } + }) + for (const child of input.children) { + const job = yield* input.jobs.get(child.id) + // Finished jobs stay in the in-memory map, so only a running job is outstanding. + if (job?.type !== "subagent" || job.status !== "running") continue + subagents.set(child.id, { + sessionID: child.id, + description: job.title ?? child.title ?? "subagent", + state: job.status, + }) + } + return [...subagents.values()] + }) + +/** Includes the closing quote so one child id cannot prefix-match another. */ +const report = (sessionID: string) => ` { + if (message.type !== "assistant") return "text" in message && message.text.includes(needle) + return message.content.some((part) => { + if (part.type === "text") return part.text.includes(needle) + if (part.type !== "tool" || part.state.status === "streaming") return false + if (!("content" in part.state)) return false + return (part.state.content ?? []).some((content) => content.type === "text" && content.text.includes(needle)) + }) +} + +export const text = (input: { + readonly forkOf: Session.ID + readonly title?: string + readonly time: number + readonly subagents: readonly Subagent[] +}) => { + const title = input.title === undefined ? "untitled" : `"${input.title}"` + const first = + `This session is a fork of ${input.forkOf} (${title}), copied through its message at ` + + `${DateTime.formatIso(DateTime.makeUnsafe(input.time))}; work started before the fork keeps reporting to the original, not here.` + if (input.subagents.length === 0) return first + return [ + first, + "", + outstanding, + ...input.subagents.map((subagent) => `- ${subagent.sessionID} "${subagent.description}" (${subagent.state})`), + "", + closing, + ].join("\n") +} diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index 669711d8aed..e265bb7f1d6 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -163,7 +163,10 @@ export const Plugin = { ) if (existing !== undefined && existing.parentID !== context.sessionID) return yield* new ToolFailure({ - message: `Session ${existing.id} is not a child of the current session`, + message: + existing.parentID !== undefined && parent.fork?.sessionID === existing.parentID + ? `Session ${existing.id} belongs to the original session ${existing.parentID}; this session is a fork of it, so that subagent reports there. Start a new subagent here instead.` + : `Session ${existing.id} is not a child of the current session`, }) const override = input.model === undefined ? undefined : yield* resolveModel(input.model) // Continuing with a different agent switches the child, mirroring create semantics diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index ad0508e9eab..14acabedbba 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -16,6 +16,7 @@ import { Hash } from "@opencode/util/hash" import { Bus } from "@opencode/core/bus" import { EventTable } from "@opencode/core/event/sql" import { Instructions } from "@opencode/core/instructions/index" +import { Job } from "@opencode/core/job" import { Location } from "@opencode/core/location" import { Model } from "@opencode/core/model" import { Project } from "@opencode/core/project" @@ -53,6 +54,7 @@ const it = testEffect( SessionProjector.node, SessionStore.node, Session.node, + Job.node, SessionTransfer.node, InstructionEntry.node, ]), @@ -73,6 +75,7 @@ const durableIt = testEffect( SessionProjector.node, SessionStore.node, Session.node, + Job.node, SessionTransfer.node, InstructionEntry.node, ]), @@ -636,12 +639,17 @@ describe("Session.create", () => { expect(forked.parentID).toBeUndefined() expect(forkContext).toMatchObject([Expected.user("First"), { type: "synthetic", text: "parent note" }]) expect(forkContext.map((message) => message.id)).not.toEqual(parentContext.map((message) => message.id)) - expect(history).toHaveLength(1) + expect(history).toHaveLength(2) expect(history[0]).toMatchObject({ type: "session.forked", durable: { seq: 0 }, data: { sessionID: forked.id, parentID: parent.id }, }) + expect(history[1]).toMatchObject({ + type: "session.inbox.enqueued", + durable: { seq: 5 }, + data: { sessionID: forked.id, item: { type: "synthetic", delivery: "steer" } }, + }) expect(yield* SessionInbox.find(db, forkContext[0].id)).toBeUndefined() expect(yield* SessionInbox.find(db, forkContext[1].id)).toBeUndefined() expect( @@ -662,17 +670,190 @@ describe("Session.create", () => { yield* SessionInbox.promote(db, bus, forked.id, "steer") expect((yield* session.context(parent.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"]) - expect((yield* session.context(forked.id)).map((message) => message.type)).toEqual(["user", "synthetic", "user"]) + expect((yield* session.context(forked.id)).map((message) => message.type)).toEqual([ + "user", + "synthetic", + "synthetic", + "user", + ]) + expect((yield* session.context(forked.id)).at(-2)).toMatchObject({ + type: "synthetic", + text: expect.stringContaining(`This session is a fork of ${parent.id} ("Parent")`), + }) expect((yield* session.context(forked.id)).at(-1)).toMatchObject({ text: "Child continues" }) expect( Array.from(yield* Stream.runCollect(logEvents(session, forked.id))).map( (event): number | undefined => event.durable?.seq, ), - ).toEqual([0, 5, 6]) + ).toEqual([0, 5, 6, 7, 8]) expect(yield* SessionInbox.find(db, admitted.id)).toBeUndefined() }), ) + it.effect("tells a fork it is a fork when nothing is outstanding", () => + Effect.gen(function* () { + const session = yield* Session.Service + const bus = yield* Bus.Service + const { db } = yield* Database.Service + const parent = yield* session.create({ location, title: "Original" }) + yield* session.prompt({ sessionID: parent.id, text: "First", resume: false }) + yield* SessionInbox.promote(db, bus, parent.id, "steer") + + const forked = yield* session.fork({ sessionID: parent.id }) + const notice = (yield* session.inbox(forked.id)).filter((item) => item.type === "synthetic") + + expect(notice).toHaveLength(1) + expect(notice[0]).toMatchObject({ + sessionID: forked.id, + delivery: "steer", + payload: { description: "Fork notice", metadata: { source: "fork", forkOf: parent.id } }, + }) + const text = notice[0]?.type === "synthetic" ? notice[0].payload.text : "" + expect(text).toContain(`This session is a fork of ${parent.id} ("Original"), copied through its message at`) + expect(text).toContain("work started before the fork keeps reporting to the original, not here.") + expect(text).not.toContain("Don't wait for these") + + yield* SessionInbox.promote(db, bus, forked.id, "steer") + const context = yield* session.context(forked.id) + // The notice is appended after the copied rows, which keep their own identities. + expect(context.map((message) => message.type)).toEqual(["user", "synthetic"]) + expect(context[0]).toMatchObject({ text: "First" }) + expect(context[1]).toMatchObject({ type: "synthetic" }) + expect(context[1]?.id).toBe(notice[0]?.id) + }), + ) + + it.effect("names the original's running subagents in the fork notice", () => + Effect.gen(function* () { + const session = yield* Session.Service + const bus = yield* Bus.Service + const jobs = yield* Job.Service + const { db } = yield* Database.Service + const parent = yield* session.create({ location, title: "Original" }) + yield* session.prompt({ sessionID: parent.id, text: "First", resume: false }) + yield* SessionInbox.promote(db, bus, parent.id, "steer") + const child = yield* session.create({ parentID: parent.id, title: "background review" }) + yield* jobs.start({ + id: child.id, + type: "subagent", + title: "review the diff", + recovery: { + kind: "subagent", + parentSessionID: parent.id, + childSessionID: child.id, + agent: "reviewer", + description: "review the diff", + }, + run: Effect.never, + }) + // A finished job stays in the in-memory map; only a running one is outstanding. + const finished = yield* session.create({ parentID: parent.id, title: "done review" }) + yield* jobs.start({ + id: finished.id, + type: "subagent", + title: "already finished", + recovery: { + kind: "subagent", + parentSessionID: parent.id, + childSessionID: finished.id, + agent: "reviewer", + description: "already finished", + }, + run: Effect.succeed("done"), + }) + yield* jobs.wait({ id: finished.id }) + + const forked = yield* session.fork({ sessionID: parent.id }) + yield* SessionInbox.promote(db, bus, forked.id, "steer") + const context = yield* session.context(forked.id) + + expect(context).toHaveLength(2) + const text = context[1]?.type === "synthetic" ? context[1].text : "" + expect(text).toContain(`- ${child.id} "review the diff" (running)`) + expect(text).toContain( + "Don't wait for these. Their results won't arrive here. Start a new subagent if this fork needs that work.", + ) + yield* jobs.cancel(child.id) + }), + ) + + it.effect("names background launches in the copied history that never reported", () => + Effect.gen(function* () { + const session = yield* Session.Service + const bus = yield* Bus.Service + const { db } = yield* Database.Service + const parent = yield* session.create({ location }) + yield* session.prompt({ sessionID: parent.id, text: "Launch subagents", resume: false }) + yield* SessionInbox.promote(db, bus, parent.id, "steer") + const assistantMessageID = SessionMessage.ID.create() + const model = Model.Ref.make({ id: Model.ID.make("model"), providerID: Provider.ID.make("provider") }) + const unreported = Session.ID.create() + const reported = Session.ID.create() + const launch = (id: string, sessionID: Session.ID, description: string) => + Effect.gen(function* () { + yield* bus.publish(SessionEvent.Tool.Input.Started, { + sessionID: parent.id, + assistantMessageID, + id, + name: "subagent", + }) + yield* bus.publish(SessionEvent.Tool.Input.Ended, { + sessionID: parent.id, + assistantMessageID, + id, + text: JSON.stringify({ background: true, description }), + }) + yield* bus.publish(SessionEvent.Tool.Called, { + sessionID: parent.id, + assistantMessageID, + id, + input: { background: true, description }, + executed: true, + }) + yield* bus.publish(SessionEvent.Tool.Success, { + sessionID: parent.id, + assistantMessageID, + id, + content: [{ type: "text", text: "started" }], + metadata: { sessionID, status: "running" }, + executed: true, + }) + }) + + yield* bus.publish(SessionEvent.Step.Started, { + sessionID: parent.id, + assistantMessageID, + agent: Agent.ID.make("build"), + model, + started: 0, + }) + yield* launch("call_unreported", unreported, "review the diff") + yield* launch("call_reported", reported, "check the tests") + yield* session.synthetic({ + sessionID: parent.id, + text: `\ndone\n`, + resume: false, + }) + yield* SessionInbox.promote(db, bus, parent.id, "steer") + yield* bus.publish(SessionEvent.Step.Ended, { + sessionID: parent.id, + assistantMessageID, + finish: "stop", + cost: Money.USD.make(0), + tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }, + }) + + const forked = yield* session.fork({ sessionID: parent.id }) + yield* SessionInbox.promote(db, bus, forked.id, "steer") + const notice = (yield* session.context(forked.id)).at(-1) + + expect(notice).toMatchObject({ type: "synthetic" }) + const text = notice?.type === "synthetic" ? notice.text : "" + expect(text).toContain(`- ${unreported} "review the diff" (unreported)`) + expect(text).not.toContain(reported) + }), + ) + it.effect("keeps a fork untitled when its parent is untitled", () => Effect.gen(function* () { const session = yield* Session.Service diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index ff3041b565f..3f9394cf3d1 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -723,6 +723,50 @@ describe("SubagentTool", () => { ), ) + it.live("rejects continuing the original's subagent from a fork", () => + tmpdirScoped().pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const sessions = yield* Session.Service + const bus = yield* Bus.Service + const { db } = yield* Database.Service + const parent = yield* sessions.create({ location, model: parentModel }) + yield* sessions.prompt({ sessionID: parent.id, text: "First", resume: false }) + yield* SessionInbox.promote(db, bus, parent.id, "steer") + const child = yield* sessions.create({ + parentID: parent.id, + title: "original review", + agent: Agent.ID.make("reviewer"), + }) + const forked = yield* sessions.fork({ sessionID: parent.id }) + yield* withSubagent(parent.location) + const locations = yield* LocationServiceMap.Service + const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(forked.location))) + + expect( + yield* executeTool(registry, { + sessionID: forked.id, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-fork-child", + name: SubagentTool.name, + input: { agent: "reviewer", description: "follow up", prompt: "continue", sessionID: child.id }, + }, + }), + ).toEqual({ + status: "error", + error: { + type: "tool.execution", + message: `Session ${child.id} belongs to the original session ${parent.id}; this session is a fork of it, so that subagent reports there. Start a new subagent here instead.`, + }, + }) + }), + ), + ), + ) + it.live("runs the child on an explicitly requested model", () => tmpdirScoped().pipe( Effect.flatMap((dir) => diff --git a/packages/sdk/test/instances.test.ts b/packages/sdk/test/instances.test.ts index 87857bd0838..9b45704c08b 100644 --- a/packages/sdk/test/instances.test.ts +++ b/packages/sdk/test/instances.test.ts @@ -118,7 +118,15 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b expect(fork.fork?.sessionID).toBe(sessionID) const inherited = await first.sessions.prompt({ sessionID: fork.id, text: "Review the fork", resume: false }) expect(inherited.payload.text).toBe(`first:alpha@${directory.path}: Review the fork`) - expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([inherited]) + const forkInbox = await first.sessions.inbox.list({ sessionID: fork.id }) + expect(forkInbox.filter((item) => item.type === "user")).toEqual([inherited]) + expect(forkInbox.filter((item) => item.type === "synthetic")).toMatchObject([ + { + sessionID: fork.id, + delivery: "steer", + payload: { description: "Fork notice", metadata: { source: "fork", forkOf: sessionID } }, + }, + ]) expect(configured.toSorted()).toEqual(["first:alpha", "first:alpha", "first:beta", "second:alpha"]) expect(setups.toSorted()).toEqual(