feat(core): add subagent context forks

This commit is contained in:
rekram1-node authored and Hona committed 2026-09-07 21:41:16 +00:00
1 parent ad31bff969
commit eb2d29d975
8 files changed
+347 -35

No files matched your search

+9
View File
@@ -518,6 +518,15 @@ export type SessionLogOutput =
readonly sessionID: Session.ID
readonly parentID: Session.ID
readonly boundary: Session.ForkBoundary
readonly start?: SessionMessage.ID | undefined
readonly child?:
| {
readonly type: "child"
readonly title?: string | undefined
readonly agent?: Agent.ID | undefined
readonly model?: Model.Ref | undefined
}
| undefined
readonly instructions?:
| { readonly [x: string & Brand.Brand<"Instruction.Key">]: string & Brand.Brand<"Instruction.Hash"> }
| undefined
@@ -1769,6 +1769,8 @@ export type SessionForked = {
sessionID: string
parentID: string
boundary: SessionForkBoundary
start?: string
child?: { type: "child"; title?: string; agent?: string; model?: ModelRef }
instructions?: { [x: string]: string }
instructionEntries?: InstructionEntrySnapshot
}
+86 -2
View File
@@ -4,7 +4,7 @@ export * from "./session/schema.js"
import { Effect, Layer, Schema, Context, Stream } from "effect"
import { LLMClient } from "@opencode/ai"
import { ListAnchor } from "@opencode/schema/session"
import { and, desc, eq } from "drizzle-orm"
import { and, asc, desc, eq, or, sql } from "drizzle-orm"
import { Project } from "./project.js"
import { Model } from "@opencode/schema/model"
import { Location } from "./location.js"
@@ -93,6 +93,12 @@ type CompactInput = Parameters<Session.Handle["compact"]>[0] & { sessionID: Sess
type ForkInput = {
sessionID: SessionSchema.ID
boundary: SessionSchema.ForkRequestBoundary
start?: SessionMessage.ID
child?: Pick<CreateBaseInput, "title" | "agent" | "model"> & { type: "child" }
}
type ForkChildInput = Pick<CreateBaseInput, "title" | "agent" | "model"> & {
sessionID: SessionSchema.ID
history: "all" | { last: number }
}
export {
@@ -122,6 +128,9 @@ export interface Interface {
readonly fork: (
input: ForkInput,
) => Effect.Effect<SessionSchema.Info, NotFoundError | MessageNotFoundError | ForkEmptyError>
readonly forkChild: (
input: ForkChildInput,
) => Effect.Effect<SessionSchema.Info, NotFoundError | MessageNotFoundError | ForkEmptyError>
readonly get: (sessionID: SessionSchema.ID) => Effect.Effect<SessionSchema.Info, NotFoundError>
readonly environment: (input: {
readonly sessionID: SessionSchema.ID
@@ -298,7 +307,13 @@ const layer = Layer.effect(
.where(
and(
eq(SessionMessageTable.session_id, input.sessionID),
input.boundary.type === "before" ? eq(SessionMessageTable.id, input.boundary.messageID) : undefined,
input.boundary.type === "before"
? eq(SessionMessageTable.id, input.boundary.messageID)
: and(
sql`${SessionMessageTable.type} != 'assistant' or json_extract(${SessionMessageTable.data}, '$.time.completed') is not null`,
sql`${SessionMessageTable.type} != 'shell' or json_extract(${SessionMessageTable.data}, '$.status') != 'running'`,
sql`${SessionMessageTable.type} != 'compaction' or json_extract(${SessionMessageTable.data}, '$.status') != 'running'`,
),
),
)
.orderBy(desc(SessionMessageTable.seq))
@@ -310,7 +325,24 @@ const layer = Layer.effect(
sessionID: input.sessionID,
messageID: input.boundary.messageID,
})
if (!boundary && input.child)
return yield* result.create({
parentID: parent.id,
title: input.child.title,
agent: input.child.agent,
model: input.child.model,
})
if (!boundary) return yield* new ForkEmptyError({ sessionID: input.sessionID })
const start = input.start
? yield* db
.select({ id: SessionMessageTable.id })
.from(SessionMessageTable)
.where(and(eq(SessionMessageTable.session_id, input.sessionID), eq(SessionMessageTable.id, input.start)))
.get()
.pipe(Effect.orDie)
: undefined
if (input.start && !start)
return yield* new MessageNotFoundError({ sessionID: input.sessionID, messageID: input.start })
const sessionID = SessionSchema.ID.create()
const inherited = yield* db
.transaction(() =>
@@ -327,10 +359,62 @@ const layer = Layer.effect(
sessionID,
parentID: parent.id,
boundary: { ...input.boundary, messageID: boundary.id },
start: start?.id,
child: input.child,
...inherited,
})
return yield* result.get(sessionID).pipe(Effect.orDie)
}),
forkChild: Effect.fn("Session.forkChild")(function* (input) {
if (input.history === "all")
return yield* result.fork({
sessionID: input.sessionID,
boundary: { type: "through" },
child: { type: "child", title: input.title, agent: input.agent, model: input.model },
})
const where = and(
eq(SessionMessageTable.session_id, input.sessionID),
or(
eq(SessionMessageTable.type, "user"),
and(
eq(SessionMessageTable.type, "synthetic"),
sql`json_extract(${SessionMessageTable.data}, '$.metadata.source') = 'subagent'`,
),
),
)
const selected = yield* db
.select({ id: SessionMessageTable.id })
.from(SessionMessageTable)
.where(where)
.orderBy(desc(SessionMessageTable.seq))
.limit(1)
.offset(input.history.last - 1)
.get()
.pipe(Effect.orDie)
const start =
selected ??
(yield* db
.select({ id: SessionMessageTable.id })
.from(SessionMessageTable)
.where(where)
.orderBy(asc(SessionMessageTable.seq))
.limit(1)
.get()
.pipe(Effect.orDie))
if (!start)
return yield* result.create({
parentID: input.sessionID,
title: input.title,
agent: input.agent,
model: input.model,
})
return yield* result.fork({
sessionID: input.sessionID,
boundary: { type: "through" },
start: start.id,
child: { type: "child", title: input.title, agent: input.agent, model: input.model },
})
}),
get: (sessionID) => sessions.forSession(sessionID).get(),
environment: Effect.fn("Session.environment")(function* (input) {
yield* result.get(input.sessionID)
+60 -19
View File
@@ -55,6 +55,29 @@ const forkTitle = (value?: string) => {
return `${value} (fork #1)`
}
const childForkMessage = (row: typeof SessionMessageTable.$inferSelect) => {
if (row.type === "user" || row.type === "system" || row.type === "skill") return { type: row.type, data: row.data }
const message = decodeMessage({ ...row.data, id: row.id, type: row.type })
if (message.type === "compaction")
return message.status === "completed" ? { type: row.type, data: row.data } : undefined
if (message.type !== "assistant" || !message.finish || message.finish === "tool-calls" || message.finish === "error")
return undefined
const content = message.content.filter((item) => item.type === "text" && item.text.length > 0)
if (content.length === 0) return undefined
const encoded = encodeMessage({
...message,
content,
snapshot: undefined,
providerState: undefined,
cost: undefined,
tokens: undefined,
retry: undefined,
})
const { id, type, ...data } = encoded
void id
return { type, data }
}
function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usage) {
return db
.update(SessionTable)
@@ -127,6 +150,18 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
.pipe(Effect.orDie)
if (!boundary)
return yield* Effect.die(new Error(`Fork boundary message not found: ${event.data.boundary.messageID}`))
const start = event.data.start
? yield* db
.select({ seq: SessionMessageTable.seq })
.from(SessionMessageTable)
.where(
and(eq(SessionMessageTable.session_id, event.data.parentID), eq(SessionMessageTable.id, event.data.start)),
)
.get()
.pipe(Effect.orDie)
: undefined
if (event.data.start && !start)
return yield* Effect.die(new Error(`Fork start message not found: ${event.data.start}`))
const copied = yield* db
.select({ seq: SessionMessageTable.seq })
.from(SessionMessageTable)
@@ -148,7 +183,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
.insert(SessionTable)
.values({
id: event.data.sessionID,
parent_id: null,
parent_id: event.data.child?.type === "child" ? event.data.parentID : null,
fork_session_id: event.data.parentID,
fork_boundary: event.data.boundary,
project_id: parent.project_id,
@@ -156,9 +191,9 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
slug: Slug.create(),
directory: parent.directory,
path: parent.path,
title: forkTitle(parent.title ?? undefined),
agent: parent.agent,
model: parent.model,
title: event.data.child?.title ?? forkTitle(parent.title ?? undefined),
agent: event.data.child?.agent ?? parent.agent,
model: event.data.child?.model ?? parent.model,
metadata: parent.metadata,
version: parent.version,
cost: 0,
@@ -188,7 +223,11 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
and(
eq(SessionMessageTable.session_id, event.data.parentID),
gt(SessionMessageTable.seq, cursor),
start ? gte(SessionMessageTable.seq, start.seq) : undefined,
lt(SessionMessageTable.seq, copiedSeq + 1),
event.data.child
? inArray(SessionMessageTable.type, ["user", "system", "skill", "assistant", "compaction"])
: undefined,
// Terminal events for active projections stay on the parent, so forks copy only settled history.
sql`${SessionMessageTable.type} != 'assistant' or json_extract(${SessionMessageTable.data}, '$.time.completed') is not null`,
sql`${SessionMessageTable.type} != 'shell' or json_extract(${SessionMessageTable.data}, '$.status') != 'running'`,
@@ -201,21 +240,23 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
.pipe(Effect.orDie)
if (rows.length === 0) break
yield* db
.insert(SessionMessageTable)
.values(
rows.map((row) => ({
id: SessionMessage.ID.make(`${SessionMessage.ID.fromEvent(event.id)}_${row.seq}`),
session_id: event.data.sessionID,
type: row.type,
seq: row.seq,
time_created: row.time_created,
time_updated: row.time_updated,
data: row.data,
})),
)
.run()
.pipe(Effect.orDie)
const messages = rows.flatMap((row) => {
const message = event.data.child?.type === "child" ? childForkMessage(row) : { type: row.type, data: row.data }
return message
? [
{
id: SessionMessage.ID.make(`${SessionMessage.ID.fromEvent(event.id)}_${row.seq}`),
session_id: event.data.sessionID,
type: message.type,
seq: row.seq,
time_created: row.time_created,
time_updated: row.time_updated,
data: message.data,
},
]
: []
})
if (messages.length > 0) yield* db.insert(SessionMessageTable).values(messages).run().pipe(Effect.orDie)
cursor = rows.at(-1)!.seq
}
+35 -13
View File
@@ -28,6 +28,10 @@ export const Input = Schema.Struct({
agent: Schema.String.annotate({ description: "The type of specialized agent to use for this task" }),
description: Schema.String.annotate({ description: "A short 3-5 word label for the task, displayed to the user" }),
prompt: Schema.String.annotate({ description: "The task for the subagent to perform" }),
fork_turns: Schema.optionalKey(Schema.String).annotate({
description:
"Optional number of turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3` to fork only the most recent turns.",
}),
sessionID: Schema.optionalKey(SessionSchema.ID).annotate({
description:
"Continue a specific previous subagent conversation by passing its sessionID. Calls without a sessionID start a new conversation.",
@@ -46,7 +50,7 @@ export const Output = Schema.Struct({
export const description = [
"Spawns an agent in a child session to work on the specified task.",
"The output includes a sessionID you can pass back later to continue that specific conversation with the subagent.",
"New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
"New child sessions inherit the parent context by default. Use fork_turns to control how much history is inherited.",
"Foreground (default) runs the subagent to completion and returns its final response.",
"Background mode (background=true) launches it asynchronously and returns immediately; you are notified when it finishes.",
"Use background only for independent work that can run while you continue elsewhere.",
@@ -79,6 +83,17 @@ export const Plugin = {
(error) => new ToolFailure({ message: `Parent session not found: ${context.sessionID}`, error }),
),
)
const forkValue = input.fork_turns?.trim().toLowerCase() || "all"
const forkCount = Number(forkValue)
if (
forkValue !== "none" &&
forkValue !== "all" &&
(!/^\d+$/.test(forkValue) || forkCount < 1 || !Number.isSafeInteger(forkCount))
)
return yield* new ToolFailure({
message: `Invalid fork_turns value '${input.fork_turns}'. Expected 'none', 'all', or a positive integer string.`,
})
const forkTurns = forkValue === "none" || forkValue === "all" ? forkValue : forkCount
let current = parent
let depth = 0
while (current.parentID) {
@@ -148,20 +163,27 @@ export const Plugin = {
// Model selection is policy/config/session state, not an LLM-facing tool argument.
const model = agent.model ?? parent.model
const childConfig = {
title: input.description,
agent: agent.id,
model,
}
const child =
existing ??
(yield* sessions
.create({
parentID: context.sessionID,
title: input.description,
agent: Agent.ID.make(input.agent),
model,
})
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Parent session not found: ${context.sessionID}`, error }),
),
))
(yield* (
forkTurns === "none"
? sessions.create({ parentID: context.sessionID, ...childConfig })
: sessions.forkChild({
sessionID: context.sessionID,
history: forkTurns === "all" ? "all" : { last: forkTurns },
...childConfig,
})
).pipe(
Effect.mapError(
(error) =>
new ToolFailure({ message: `Failed to create subagent session: ${error.message}`, error }),
),
))
const background = input.background === true
yield* context.progress({ sessionID: child.id, status: "running" })
+28 -1
View File
@@ -673,7 +673,7 @@ describe("Session.create", () => {
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const parent = yield* session.create({ location })
yield* session.prompt({ sessionID: parent.id, text: "Run both tools", resume: false })
const user = yield* session.prompt({ sessionID: parent.id, text: "Run both tools", 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") })
@@ -706,11 +706,38 @@ describe("Session.create", () => {
const forked = yield* session.fork({ sessionID: parent.id, boundary: { type: "through" } })
expect(forked.fork?.boundary).toEqual({ type: "through", messageID: user.id })
expect(yield* session.context(parent.id)).toMatchObject([
Expected.user("Run both tools"),
Expected.assistant({}, [{ type: "tool", id: "call_running", state: { status: "running" } }]),
])
expect(yield* session.context(forked.id)).toMatchObject([Expected.user("Run both tools")])
const recorded = yield* db
.select()
.from(EventTable)
.where(eq(EventTable.aggregate_id, forked.id))
.get()
.pipe(Effect.orDie)
if (!recorded) return yield* Effect.die(new Error("Fork event not found"))
yield* bus.publish(SessionEvent.Step.Ended, {
sessionID: parent.id,
assistantMessageID,
finish: "tool-calls",
cost: Money.USD.zero,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
})
yield* bus.remove(forked.id)
yield* db.delete(SessionTable).where(eq(SessionTable.id, forked.id)).run().pipe(Effect.orDie)
yield* bus.replay({
id: recorded.id,
created: recorded.created,
aggregateID: recorded.aggregate_id,
seq: recorded.seq,
type: recorded.type,
data: recorded.data,
})
expect(yield* session.context(forked.id)).toMatchObject([Expected.user("Run both tools")])
}),
)
+120
View File
@@ -433,6 +433,126 @@ describe("SubagentTool", () => {
),
)
it.live("forks all, recent, or no parent turns into a new child", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
).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 })
yield* withSubagent(parent.location)
const bus = yield* Bus.Service
const database = yield* Database.Service
const addUser = Effect.fn("SubagentTest.addUser")(function* (text: string) {
yield* sessions.prompt({ sessionID: parent.id, text, resume: false })
yield* SessionInbox.promote(database.db, bus, parent.id, "steer")
})
const addAssistant = Effect.fn("SubagentTest.addAssistant")(function* (
text: string,
finish: "stop" | "tool-calls",
reasoning?: string,
) {
const assistantMessageID = SessionMessage.ID.create()
yield* bus.publish(SessionEvent.Step.Started, {
sessionID: parent.id,
assistantMessageID,
agent: Agent.ID.make("build"),
model: parentModel,
})
if (reasoning) {
yield* bus.publish(SessionEvent.Reasoning.Started, {
sessionID: parent.id,
assistantMessageID,
ordinal: 0,
})
yield* bus.publish(SessionEvent.Reasoning.Ended, {
sessionID: parent.id,
assistantMessageID,
ordinal: 0,
text: reasoning,
})
}
yield* bus.publish(SessionEvent.Text.Started, {
sessionID: parent.id,
assistantMessageID,
ordinal: reasoning ? 1 : 0,
})
yield* bus.publish(SessionEvent.Text.Ended, {
sessionID: parent.id,
assistantMessageID,
ordinal: reasoning ? 1 : 0,
text,
})
yield* bus.publish(SessionEvent.Step.Ended, {
sessionID: parent.id,
assistantMessageID,
finish,
cost: Money.USD.make(1),
tokens,
})
})
yield* addUser("old task")
yield* addAssistant("old final answer", "stop", "private reasoning")
yield* addUser("recent task")
yield* addAssistant("working on it", "tool-calls")
yield* addUser("current task")
const locations = yield* LocationServiceMap.Service
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
const run = (id: string, fork_turns?: string) =>
executeTool(registry, {
sessionID: parent.id,
...toolIdentity,
call: {
type: "tool-call" as const,
id,
name: SubagentTool.name,
input: {
agent: "reviewer",
description: "review",
prompt: "review this",
...(fork_turns === undefined ? {} : { fork_turns }),
},
},
})
const all = yield* run("call-fork-all")
const allChild = yield* sessions.get(outputSessionID(all.metadata))
expect(allChild).toMatchObject({ parentID: parent.id, fork: { sessionID: parent.id } })
expect((yield* sessions.context(allChild.id)).slice(0, -1)).toMatchObject([
{ type: "user", text: "old task" },
{ type: "assistant", content: [{ type: "text", text: "old final answer" }] },
{ type: "user", text: "recent task" },
{ type: "user", text: "current task" },
])
const recent = yield* run("call-fork-recent", "2")
expect((yield* sessions.context(outputSessionID(recent.metadata))).slice(0, -1)).toMatchObject([
{ type: "user", text: "recent task" },
{ type: "user", text: "current task" },
])
const none = yield* run("call-fork-none", "none")
expect(yield* sessions.context(outputSessionID(none.metadata))).toMatchObject([
{ type: "assistant", content: [{ type: "text", text: childText }] },
])
expect(yield* run("call-fork-invalid", "0")).toEqual({
status: "error",
error: {
type: "tool.execution",
message: "Invalid fork_turns value '0'. Expected 'none', 'all', or a positive integer string.",
},
})
}),
),
),
)
it.live("continues an existing child session", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
+7
View File
@@ -174,6 +174,13 @@ export const Forked = Event.durable({
...Base,
parentID: SessionID,
boundary: SessionFork.Boundary,
start: SessionMessage.ID.pipe(optional),
child: Schema.Struct({
type: Schema.tag("child"),
title: Created.data.fields.title,
agent: Created.data.fields.agent,
model: Created.data.fields.model,
}).pipe(optional),
instructions: Instruction.Values.pipe(optional),
instructionEntries: InstructionEntry.Snapshot.pipe(optional),
},