Skip to content

Commit c8101e7

Browse files
Claude Agentclaude
andcommitted
feat(opencode): per-task timeout for foreground subagents (nested-agents Issue 5)
Optional per-task timeout for foreground `task` spawns, set via the new `timeout` tool-param (milliseconds, wins) or the `experimental.subagent_task_timeout` config default. On expiry the subtree is aborted through the SAME cancel path as an explicit cancel (ops.cancel seeds Session.descendants into SessionRunState.cancel; background.cancel closes the job scope and awaits its interrupt finalizers), so the release-race fix (5582da5) stays intact, no orphan job survives, and the foreground parent surfaces a typed SubagentTimeoutError in its transcript instead of hanging. Background tasks are unaffected (decoupled, notified out-of-band). Without a timeout, behavior is byte-identical to before. The timeout arm only sleeps then fails: with raceFirst the loser is interrupted the moment the winner settles, so failing first interrupts the wait arm before background.cancel could flip the job to "cancelled" and let that branch win the race (which would surface "Task cancelled" instead of the typed timeout); the catchIf then runs the abort and re-fails. Single-source clamp helper SubagentLimits.taskTimeout(cfg, override) and a typed SubagentTimeoutError live in subagent-limits.ts alongside maxDepth/the existing typed errors. Tests in test/session/nested-timeout.test.ts. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 81ea40c commit c8101e7

5 files changed

Lines changed: 554 additions & 3 deletions

File tree

‎packages/core/src/v1/config/config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ export const Info = Schema.Struct({
218218
description:
219219
"Maximum subagent nesting depth (the root session is depth 1; clamped to 1..10). Default 5. Set 2 to restore the previous spawn behavior (the root spawns, subagents do not) — additionally the workflow tool is removed at the limit (security fix) and custom agents that previously nested without limit are bounded; 1 is the kill switch that removes the task and workflow tools entirely.",
220220
}),
221+
subagent_task_timeout: Schema.optional(PositiveInt).annotate({
222+
description:
223+
"Default timeout in milliseconds for foreground subagent tasks (the `task` tool). When it elapses the subtree is aborted via the same cancel path as an explicit cancel (no orphan job) and the spawn fails with a typed timeout error in the parent's transcript. Overridable per call via the task tool's `timeout` parameter. Unset (default) means no timeout.",
224+
}),
221225
policies: Schema.optional(Schema.mutable(Schema.Array(ConfigExperimental.Policy))).annotate({
222226
description: "Policy statements applied to supported resources, such as provider access",
223227
}),

‎packages/opencode/src/session/subagent-limits.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,27 @@ export function maxDepth(cfg: ConfigV1.Info): number {
5151
return Math.min(Math.max(Math.trunc(raw), 1), HARD_MAX_DEPTH)
5252
}
5353

54+
/**
55+
* Resolves the effective per-task timeout (milliseconds) for a spawn — the
56+
* single source of truth for `experimental.subagent_task_timeout` and the
57+
* optional `timeout` tool-param (design-final §2.2 follow-up Issue 5). The
58+
* tool-param wins over the config default; only finite, positive integers
59+
* count, so a `0`/negative/NaN override falls back to the config default and
60+
* an absent or invalid config default means "no timeout" (unchanged behavior).
61+
* Returns `undefined` when no timeout applies.
62+
*/
63+
export function taskTimeout(cfg: ConfigV1.Info, override?: number): number | undefined {
64+
// The config key ships with the default-opening track; the cast keeps this
65+
// helper typed against ConfigV1.Info before and after the schema gains it.
66+
const fallback = (cfg.experimental as { subagent_task_timeout?: number } | undefined)?.subagent_task_timeout
67+
for (const raw of [override, fallback]) {
68+
if (typeof raw !== "number" || !Number.isFinite(raw)) continue
69+
const ms = Math.trunc(raw)
70+
if (ms > 0) return ms
71+
}
72+
return undefined
73+
}
74+
5475
/**
5576
* Appended to the task tool description on levels 2..max−1 so subagents know
5677
* their remaining delegation budget instead of discovering it by failed calls.
@@ -126,6 +147,23 @@ export const budgetError = () =>
126147
"Turn budget exhausted: cannot start another subagent. Finish the remaining work directly within this session.",
127148
})
128149

150+
/**
151+
* Raised when a foreground subagent task exceeds its per-task timeout (Issue
152+
* 5). The subtree is aborted through the SAME cancel path as an explicit
153+
* cancel before this error surfaces, so no orphan job survives; the foreground
154+
* parent loop sees it as a task error in its transcript and continues.
155+
*/
156+
export class SubagentTimeoutError extends Schema.TaggedErrorClass<SubagentTimeoutError>()("SubagentTimeoutError", {
157+
message: Schema.String,
158+
timeout: Schema.Finite,
159+
}) {}
160+
161+
export const timeoutError = (input: { timeout: number }) =>
162+
new SubagentTimeoutError({
163+
...input,
164+
message: `Subagent task timed out after ${input.timeout}ms and was aborted. The delegated work did not finish in time; do the remaining work directly in this session or retry with a larger timeout.`,
165+
})
166+
129167
/**
130168
* Raised when the parent-chain walk exceeds LINEAGE_ITERATION_CAP (corrupt or
131169
* cyclic session parents). Callers treat this like "depth ≥ limit": spawning

‎packages/opencode/src/tool/task.ts‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ const BaseParameterFields = {
6868
"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)",
6969
}),
7070
command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }),
71+
timeout: Schema.optional(Schema.Number).annotate({
72+
description:
73+
"Optional timeout in milliseconds for this foreground task. When it elapses the subagent (and its whole subtree) is aborted and this call fails with a timeout error; do the work yourself or retry with a larger value. Overrides experimental.subagent_task_timeout. Ignored for background tasks.",
74+
}),
7175
}
7276

7377
const BaseParameters = Schema.Struct(BaseParameterFields)
@@ -408,15 +412,40 @@ export const TaskTool = Tool.define(
408412
runCancel.fork(cancel)
409413
}
410414

415+
// Per-task timeout (design-final §2.2 follow-up Issue 5): tool param wins
416+
// over experimental.subagent_task_timeout; only foreground tasks are
417+
// gated (background tasks are decoupled and notified out-of-band, so the
418+
// param is ignored there). The timeout arm only SLEEPS then fails — it
419+
// does NOT cancel inline: with raceFirst the loser is interrupted the
420+
// moment the winner settles, so failing first interrupts the wait arm
421+
// before background.cancel could flip the job to "cancelled" and let that
422+
// branch win the race (which would surface "Task cancelled" instead of
423+
// the typed timeout). The catchIf below runs the abort on the SAME cancel
424+
// path as an explicit cancel — ops.cancel seeds Session.descendants into
425+
// SessionRunState.cancel and background.cancel closes the job scope and
426+
// awaits its interrupt finalizers, so the release race (5582da5a8) stays
427+
// closed and no orphan job survives — then re-fails so the foreground
428+
// parent loop surfaces the error in its transcript instead of hanging.
429+
const timeoutMs = SubagentLimits.taskTimeout(cfg, params.timeout)
430+
const timeoutArm: Effect.Effect<never, SubagentLimits.SubagentTimeoutError> =
431+
timeoutMs === undefined
432+
? Effect.never
433+
: Effect.sleep(`${timeoutMs} millis`).pipe(
434+
Effect.andThen(Effect.fail(SubagentLimits.timeoutError({ timeout: timeoutMs }))),
435+
)
436+
411437
return yield* Effect.acquireUseRelease(
412438
Effect.sync(() => {
413439
ctx.abort.addEventListener("abort", onAbort)
414440
}),
415441
() =>
416442
Effect.gen(function* () {
417443
const result = yield* Effect.raceFirst(
418-
background.wait({ id: nextSession.id }).pipe(Effect.map((waited) => waited.info)),
419-
background.waitForPromotion(nextSession.id),
444+
Effect.raceFirst(
445+
background.wait({ id: nextSession.id }).pipe(Effect.map((waited) => waited.info)),
446+
background.waitForPromotion(nextSession.id),
447+
),
448+
timeoutArm,
420449
)
421450
if (result?.metadata?.background === true) return backgroundResult()
422451
if (result?.status === "error") return yield* Effect.fail(new Error(result.error ?? "Task failed"))
@@ -426,7 +455,16 @@ export const TaskTool = Tool.define(
426455
metadata,
427456
output: renderOutput({ sessionID: nextSession.id, state: "completed", text: result?.output ?? "" }),
428457
}
429-
}),
458+
}).pipe(
459+
Effect.catchIf(
460+
(error): error is SubagentLimits.SubagentTimeoutError =>
461+
error instanceof SubagentLimits.SubagentTimeoutError,
462+
(error) =>
463+
Effect.all([cancel, background.cancel(nextSession.id)], { discard: true }).pipe(
464+
Effect.andThen(Effect.fail(error)),
465+
),
466+
),
467+
),
430468
(_, exit) =>
431469
Effect.gen(function* () {
432470
if (Exit.hasInterrupts(exit))

‎packages/opencode/src/tool/task.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ Usage notes:
1919
7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
2020
8. Agents may themselves delegate to deeper sub-agents. Nesting is allowed up to a configured maximum depth (your own session counts as one level; the root session is depth 1). On the deepest level this tool is not available — an agent there must do the remaining work itself and report results in its final message.
2121
9. task_id can only resume tasks that THIS session started itself (its own direct children). Passing the id of a parent, sibling, or unrelated session fails; an unknown id starts a fresh session.
22+
10. You may set an optional timeout (milliseconds) for a foreground task. If the subagent does not finish within it, the whole subtree is aborted and the call returns a timeout error — then do the remaining work yourself or retry with a larger timeout. The timeout is ignored for background tasks.

0 commit comments

Comments
 (0)