Skip to content

Commit 676e030

Browse files
rajarshighoshalPremik
authored andcommitted
fix(opencode): add configurable timeout to Task tool
Task subagents had no timeout, so a hung subagent blocked the parent session indefinitely with no way to recover. Adds an optional timeout parameter (milliseconds), a RuntimeFlags-backed default, and a cancel-and-fail-on-timeout path, mirroring the Bash tool's existing timeout implementation. Closes anomalyco#15080
1 parent 485f565 commit 676e030

4 files changed

Lines changed: 148 additions & 2 deletions

File tree

‎packages/opencode/src/effect/runtime-flags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export class Service extends ConfigService.Service<Service>()("@opencode/Runtime
5151
experimentalIconDiscovery: enabledByExperimental("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY"),
5252
outputTokenMax: positiveInteger("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"),
5353
bashDefaultTimeoutMs: positiveInteger("OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"),
54+
taskDefaultTimeoutMs: positiveInteger("OPENCODE_EXPERIMENTAL_TASK_DEFAULT_TIMEOUT_MS"),
5455
experimentalNativeLlm: bool("OPENCODE_EXPERIMENTAL_NATIVE_LLM"),
5556
experimentalWebSockets: bool("OPENCODE_EXPERIMENTAL_WEBSOCKETS"),
5657
client: Config.string("OPENCODE_CLIENT").pipe(Config.withDefault("cli")),

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

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { Agent } from "../agent/agent"
1010
import { deriveSubagentSessionPermission } from "../agent/subagent-permissions"
1111
import type { SessionPrompt } from "../session/prompt"
1212
import { Config } from "@/config/config"
13+
import { PositiveInt } from "@opencode-ai/core/schema"
1314
import { Effect, Exit, Schema, Scope } from "effect"
1415
import { EffectBridge } from "@/effect/bridge"
1516
import { RuntimeFlags } from "@/effect/runtime-flags"
@@ -49,6 +50,7 @@ const BaseParameterFields = {
4950
"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)",
5051
}),
5152
command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }),
53+
timeout: Schema.optional(PositiveInt).annotate({ description: "Optional timeout in milliseconds" }),
5254
}
5355

5456
const BaseParameters = Schema.Struct(BaseParameterFields)
@@ -88,6 +90,7 @@ export const TaskTool = Tool.define(
8890
const scope = yield* Scope.Scope
8991
const flags = yield* RuntimeFlags.Service
9092
const database = yield* Database.Service
93+
const defaultTimeoutMs = flags.taskDefaultTimeoutMs ?? 5 * 60 * 1000
9194

9295
const run = Effect.fn("TaskTool.execute")(function* (
9396
params: Schema.Schema.Type<typeof Parameters>,
@@ -100,6 +103,12 @@ export const TaskTool = Tool.define(
100103
new Error("Background subagents require OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"),
101104
)
102105
}
106+
if (params.timeout !== undefined && params.timeout < 0) {
107+
return yield* Effect.fail(
108+
new Error(`Invalid timeout value: ${params.timeout}. Timeout must be a positive number.`),
109+
)
110+
}
111+
const timeoutMs = params.timeout ?? defaultTimeoutMs
103112

104113
const parent = yield* sessions.get(ctx.sessionID)
105114
let current = parent
@@ -331,10 +340,23 @@ export const TaskTool = Tool.define(
331340
}),
332341
() =>
333342
Effect.gen(function* () {
334-
const result = yield* Effect.raceFirst(
343+
const waited = Effect.raceFirst(
335344
background.wait({ id: nextSession.id }).pipe(Effect.map((waited) => waited.info)),
336345
background.waitForPromotion(nextSession.id),
337-
)
346+
).pipe(Effect.map((result) => ({ kind: "done" as const, result })))
347+
const timedOut = Effect.sleep(`${timeoutMs} millis`).pipe(Effect.map(() => ({ kind: "timeout" as const })))
348+
349+
const raced = yield* Effect.raceAll([waited, timedOut])
350+
if (raced.kind === "timeout") {
351+
yield* Effect.all([cancel, background.cancel(nextSession.id)], { discard: true })
352+
return yield* Effect.fail(
353+
new Error(
354+
`task tool terminated subagent after exceeding timeout ${timeoutMs} ms. If this task is expected to take longer, retry with a larger timeout value in milliseconds.`,
355+
),
356+
)
357+
}
358+
359+
const result = raced.result
338360
if (result?.metadata?.background === true) return backgroundResult()
339361
if (result?.status === "error") return yield* Effect.fail(new Error(result.error ?? "Task failed"))
340362
if (result?.status === "cancelled") return yield* Effect.fail(new Error("Task cancelled"))

‎packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,13 @@ exports[`tool parameters JSON Schema (wire shape) task 1`] = `
325325
"description": "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)",
326326
"type": "string",
327327
},
328+
"timeout": {
329+
"description": "Optional timeout in milliseconds",
330+
"exclusiveMinimum": 0,
331+
"maximum": 9007199254740991,
332+
"minimum": -9007199254740991,
333+
"type": "integer",
334+
},
328335
},
329336
"required": [
330337
"description",

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

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ const layer = (flags: Partial<RuntimeFlags.Info> = {}) =>
5757

5858
const it = testEffect(layer())
5959
const background = testEffect(layer({ experimentalBackgroundSubagents: true }))
60+
const shortTimeout = testEffect(layer({ taskDefaultTimeoutMs: 50 }))
6061

6162
function defer<T>() {
6263
let resolve!: (value: T | PromiseLike<T>) => void
@@ -467,6 +468,121 @@ describe("tool.task", () => {
467468
}),
468469
)
469470

471+
it.instance("execute terminates the task and cancels the child session on timeout", () =>
472+
Effect.gen(function* () {
473+
const { chat, assistant } = yield* seed()
474+
const tool = yield* TaskTool
475+
const def = yield* tool.init()
476+
const cancelled = defer<SessionID>()
477+
478+
const exit = yield* def
479+
.execute(
480+
{
481+
description: "inspect bug",
482+
prompt: "look into the cache key path",
483+
subagent_type: "general",
484+
timeout: 50,
485+
},
486+
{
487+
sessionID: chat.id,
488+
messageID: assistant.id,
489+
agent: "build",
490+
abort: new AbortController().signal,
491+
extra: {
492+
promptOps: {
493+
...stubOps(),
494+
cancel: (sessionID) => Effect.sync(() => cancelled.resolve(sessionID)),
495+
prompt: () => Effect.never,
496+
} satisfies TaskPromptOps,
497+
},
498+
messages: [],
499+
metadata: () => Effect.void,
500+
ask: () => Effect.void,
501+
},
502+
)
503+
.pipe(Effect.exit)
504+
505+
expect(Exit.isFailure(exit)).toBe(true)
506+
if (Exit.isFailure(exit)) {
507+
const err = Cause.squash(exit.cause)
508+
expect(String(err)).toContain("task tool terminated subagent after exceeding timeout 50 ms")
509+
expect(String(err)).toContain("retry with a larger timeout value in milliseconds")
510+
}
511+
512+
expect(yield* Effect.promise(() => cancelled.promise)).toBeTruthy()
513+
}),
514+
)
515+
516+
it.instance("rejects a negative timeout value", () =>
517+
Effect.gen(function* () {
518+
const { chat, assistant } = yield* seed()
519+
const tool = yield* TaskTool
520+
const def = yield* tool.init()
521+
522+
const exit = yield* def
523+
.execute(
524+
{
525+
description: "inspect bug",
526+
prompt: "look into the cache key path",
527+
subagent_type: "general",
528+
timeout: -1,
529+
},
530+
{
531+
sessionID: chat.id,
532+
messageID: assistant.id,
533+
agent: "build",
534+
abort: new AbortController().signal,
535+
extra: { promptOps: stubOps() },
536+
messages: [],
537+
metadata: () => Effect.void,
538+
ask: () => Effect.void,
539+
},
540+
)
541+
.pipe(Effect.exit)
542+
543+
expect(Exit.isFailure(exit)).toBe(true)
544+
}),
545+
)
546+
547+
shortTimeout.instance("uses RuntimeFlags taskDefaultTimeoutMs when timeout is omitted", () =>
548+
Effect.gen(function* () {
549+
const { chat, assistant } = yield* seed()
550+
const tool = yield* TaskTool
551+
const def = yield* tool.init()
552+
553+
const exit = yield* def
554+
.execute(
555+
{
556+
description: "inspect bug",
557+
prompt: "look into the cache key path",
558+
subagent_type: "general",
559+
},
560+
{
561+
sessionID: chat.id,
562+
messageID: assistant.id,
563+
agent: "build",
564+
abort: new AbortController().signal,
565+
extra: {
566+
promptOps: {
567+
...stubOps(),
568+
prompt: () => Effect.never,
569+
} satisfies TaskPromptOps,
570+
},
571+
messages: [],
572+
metadata: () => Effect.void,
573+
ask: () => Effect.void,
574+
},
575+
)
576+
.pipe(Effect.exit)
577+
578+
expect(Exit.isFailure(exit)).toBe(true)
579+
if (Exit.isFailure(exit)) {
580+
const err = Cause.squash(exit.cause)
581+
expect(String(err)).toContain("exceeding timeout 50 ms")
582+
}
583+
}),
584+
)
585+
470586
it.instance("execute creates a child when task_id does not exist", () =>
471587
Effect.gen(function* () {
472588
const sessions = yield* Session.Service

0 commit comments

Comments
 (0)