Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/core/src/v1/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ export const Info = Schema.Struct({
subagent_depth: Schema.optional(NonNegativeInt).annotate({
description: "Maximum subagent nesting depth. Defaults to 1, which prevents subagents from launching subagents.",
}),
subagent_max_children: Schema.optional(NonNegativeInt).annotate({
description: "Lifetime cap on direct children a subagent may spawn. Root sessions are exempt. Defaults to 32.",
}),
username: Schema.optional(Schema.String).annotate({
description: "Custom username to display in conversations instead of system username",
}),
Expand Down
47 changes: 33 additions & 14 deletions packages/opencode/src/tool/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Effect, Exit, Schema, Scope } from "effect"
import { EffectBridge } from "@/effect/bridge"
import { RuntimeFlags } from "@/effect/runtime-flags"
import { Database } from "@opencode-ai/core/database/database"
import { KeyedMutex } from "@opencode-ai/core/effect/keyed-mutex"

export interface TaskPromptOps {
cancel(sessionID: SessionID): Effect.Effect<void>
Expand Down Expand Up @@ -88,6 +89,7 @@ export const TaskTool = Tool.define(
const scope = yield* Scope.Scope
const flags = yield* RuntimeFlags.Service
const database = yield* Database.Service
const childLocks = KeyedMutex.makeUnsafe<SessionID>()

const run = Effect.fn("TaskTool.execute")(function* (
params: Schema.Schema.Type<typeof Parameters>,
Expand Down Expand Up @@ -116,6 +118,8 @@ export const TaskTool = Tool.define(
)
}

const maxChildren = cfg.subagent_max_children ?? 32

if (!ctx.extra?.bypassAgentCheck) {
yield* ctx.ask({
permission: id,
Expand Down Expand Up @@ -155,21 +159,36 @@ export const TaskTool = Tool.define(
]
const nextSession =
session ??
(yield* sessions.create({
parentID: ctx.sessionID,
title: params.description + ` (@${next.name} subagent)`,
agent: next.name,
permission: [
...childPermission,
...childToolDenies.filter(
(deny) =>
!childPermission.some(
(rule) =>
rule.permission === deny.permission && rule.pattern === deny.pattern && rule.action === deny.action,
(yield* childLocks.withLock(ctx.sessionID)(
Effect.gen(function* () {
// Session execution is process-local, so this makes counting and child creation atomic for same-parent spawns.
// Serialization is verified in packages/core/test/effect/keyed-mutex.test.ts.
// Root sessions (depth=0) are exempt — the orchestrator is operator-supervised and may dispatch hundreds.
const children = depth > 0 ? yield* sessions.children(ctx.sessionID) : []
if (children.length >= maxChildren) {
return yield* Effect.fail(
new Error(
`Subagent child limit reached (${maxChildren}). Increase "subagent_max_children" to allow more direct subagents.`,
),
),
],
}))
)
}
return yield* sessions.create({
parentID: ctx.sessionID,
title: params.description + ` (@${next.name} subagent)`,
agent: next.name,
permission: [
...childPermission,
...childToolDenies.filter(
(deny) =>
!childPermission.some(
(rule) =>
rule.permission === deny.permission && rule.pattern === deny.pattern && rule.action === deny.action,
),
),
],
})
}),
))

const msg = yield* MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID }).pipe(
Effect.provideService(Database.Service, database),
Expand Down
207 changes: 207 additions & 0 deletions packages/opencode/test/tool/task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,213 @@ describe("tool.task", () => {
{ config: { subagent_depth: 2 } },
)

it.instance(
"caps direct children at the default limit",
() =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const { chat, assistant } = yield* seed()
const child = yield* sessions.create({ parentID: chat.id, title: "subagent" })
const nestedAssistant = yield* sessions.updateMessage({
...assistant,
id: MessageID.ascending(),
parentID: MessageID.ascending(),
sessionID: child.id,
})
const tool = yield* TaskTool
const def = yield* tool.init()
const execute = () =>
def.execute(
{
description: "inspect bug",
prompt: "look into the cache key path",
subagent_type: "general",
},
{
sessionID: child.id,
messageID: nestedAssistant.id,
agent: "general",
abort: new AbortController().signal,
extra: { promptOps: stubOps() },
messages: [],
metadata: () => Effect.void,
ask: () => Effect.void,
},
)

yield* Effect.forEach(Array.from({ length: 32 }), execute)
expect(yield* sessions.children(child.id)).toHaveLength(32)

const exit = yield* execute().pipe(Effect.exit)
expect(Exit.isFailure(exit)).toBe(true)
if (Exit.isFailure(exit)) expect(Cause.pretty(exit.cause)).toContain("subagent_max_children")
}),
{ config: { subagent_depth: 2 } },
)

it.instance(
"respects a custom direct child limit",
() =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const { chat, assistant } = yield* seed()
const child = yield* sessions.create({ parentID: chat.id, title: "subagent" })
const nestedAssistant = yield* sessions.updateMessage({
...assistant,
id: MessageID.ascending(),
parentID: MessageID.ascending(),
sessionID: child.id,
})
const tool = yield* TaskTool
const def = yield* tool.init()
const execute = () =>
def.execute(
{
description: "inspect bug",
prompt: "look into the cache key path",
subagent_type: "general",
},
{
sessionID: child.id,
messageID: nestedAssistant.id,
agent: "general",
abort: new AbortController().signal,
extra: { promptOps: stubOps() },
messages: [],
metadata: () => Effect.void,
ask: () => Effect.void,
},
)

yield* execute()
const exit = yield* execute().pipe(Effect.exit)
expect(Exit.isFailure(exit)).toBe(true)
if (Exit.isFailure(exit)) expect(Cause.pretty(exit.cause)).toContain("subagent_max_children")
}),
{ config: { subagent_max_children: 1, subagent_depth: 2 } },
)

it.instance(
"does not cap root sessions",
() =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const { chat, assistant } = yield* seed()
const tool = yield* TaskTool
const def = yield* tool.init()
const execute = () =>
def.execute(
{
description: "inspect bug",
prompt: "look into the cache key path",
subagent_type: "general",
},
{
sessionID: chat.id,
messageID: assistant.id,
agent: "build",
abort: new AbortController().signal,
extra: { promptOps: stubOps() },
messages: [],
metadata: () => Effect.void,
ask: () => Effect.void,
},
)

yield* Effect.forEach(Array.from({ length: 5 }), execute)
expect(yield* sessions.children(chat.id)).toHaveLength(5)
}),
{ config: { subagent_max_children: 1 } },
)

it.instance(
"concurrent spawns respect the cap",
() =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const { chat, assistant } = yield* seed()
const child = yield* sessions.create({ parentID: chat.id, title: "subagent" })
const nestedAssistant = yield* sessions.updateMessage({
...assistant,
id: MessageID.ascending(),
parentID: MessageID.ascending(),
sessionID: child.id,
})
const tool = yield* TaskTool
const def = yield* tool.init()
const execute = () =>
def.execute(
{
description: "inspect bug",
prompt: "look into the cache key path",
subagent_type: "general",
},
{
sessionID: child.id,
messageID: nestedAssistant.id,
agent: "general",
abort: new AbortController().signal,
extra: { promptOps: stubOps() },
messages: [],
metadata: () => Effect.void,
ask: () => Effect.void,
},
)

const results = yield* Effect.all([execute().pipe(Effect.exit), execute().pipe(Effect.exit)], {
concurrency: "unbounded",
})
expect(results.filter(Exit.isSuccess)).toHaveLength(1)
expect(results.filter(Exit.isFailure)).toHaveLength(1)
}),
{ config: { subagent_max_children: 1, subagent_depth: 2 } },
)

it.instance(
"checks depth before direct child limits",
() =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const { chat, assistant } = yield* seed()
const child = yield* sessions.create({ parentID: chat.id, title: "child" })
const nestedAssistant = yield* sessions.updateMessage({
...assistant,
id: MessageID.ascending(),
parentID: MessageID.ascending(),
sessionID: child.id,
})
const tool = yield* TaskTool
const def = yield* tool.init()

const exit = yield* def
.execute(
{
description: "inspect bug",
prompt: "look into the cache key path",
subagent_type: "general",
},
{
sessionID: child.id,
messageID: nestedAssistant.id,
agent: "general",
abort: new AbortController().signal,
extra: { promptOps: stubOps() },
messages: [],
metadata: () => Effect.void,
ask: () => Effect.void,
},
)
.pipe(Effect.exit)

expect(Exit.isFailure(exit)).toBe(true)
if (Exit.isFailure(exit)) {
expect(Cause.pretty(exit.cause)).toContain("subagent_depth")
expect(Cause.pretty(exit.cause)).not.toContain("subagent_max_children")
}
}),
{ config: { subagent_depth: 1, subagent_max_children: 0 } },
)

it.instance(
"execute shapes child permissions for task, todowrite, and primary tools",
() =>
Expand Down
Loading