Skip to content

Commit 41ef069

Browse files
Apply PR #24174: feat(core): add background subagent support
2 parents 99c66aa + 80aeb78 commit 41ef069

12 files changed

Lines changed: 809 additions & 61 deletions

File tree

packages/opencode/src/cli/cmd/tui/routes/session/index.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2006,7 +2006,9 @@ function Task(props: ToolProps<typeof TaskTool>) {
20062006

20072007
const content = createMemo(() => {
20082008
if (!props.input.description) return ""
2009-
let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${props.input.description}`]
2009+
const description =
2010+
props.metadata.background === true ? `${props.input.description} (background)` : props.input.description
2011+
let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${description}`]
20102012

20112013
if (isRunning() && tools().length > 0) {
20122014
// content[0] += ` · ${tools().length} toolcalls`

packages/opencode/src/session/prompt.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ export const layer = Layer.effect(
118118
cancel: (sessionID: SessionID) => run.fork(cancel(sessionID)),
119119
resolvePromptParts: (template: string) => resolvePromptParts(template),
120120
prompt: (input: PromptInput) => prompt(input),
121+
loop: (input: LoopInput) => loop(input),
122+
fork: (effect: Effect.Effect<void, never, never>) => {
123+
run.fork(effect)
124+
},
121125
} satisfies TaskPromptOps
122126
})
123127

packages/opencode/src/tool/registry.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { GlobTool } from "./glob"
77
import { GrepTool } from "./grep"
88
import { ReadTool } from "./read"
99
import { TaskTool } from "./task"
10+
import { TaskStatusTool } from "./task_status"
1011
import { TodoWriteTool } from "./todo"
1112
import { WebFetchTool } from "./webfetch"
1213
import { WriteTool } from "./write"
@@ -50,6 +51,7 @@ import { Agent } from "../agent/agent"
5051
import { Git } from "@/git"
5152
import { Skill } from "../skill"
5253
import { Permission } from "@/permission"
54+
import { SessionStatus } from "@/session/status"
5355

5456
const log = Log.create({ service: "tool.registry" })
5557

@@ -82,6 +84,7 @@ export const layer: Layer.Layer<
8284
| Agent.Service
8385
| Skill.Service
8486
| Session.Service
87+
| SessionStatus.Service
8588
| Provider.Service
8689
| Git.Service
8790
| LSP.Service
@@ -121,6 +124,7 @@ export const layer: Layer.Layer<
121124
const greptool = yield* GrepTool
122125
const patchtool = yield* ApplyPatchTool
123126
const skilltool = yield* SkillTool
127+
const taskstatus = yield* TaskStatusTool
124128
const agent = yield* Agent.Service
125129

126130
const state = yield* InstanceState.make<State>(
@@ -201,6 +205,7 @@ export const layer: Layer.Layer<
201205
edit: Tool.init(edit),
202206
write: Tool.init(writetool),
203207
task: Tool.init(task),
208+
taskstatus: Tool.init(taskstatus),
204209
fetch: Tool.init(webfetch),
205210
todo: Tool.init(todo),
206211
search: Tool.init(websearch),
@@ -226,6 +231,7 @@ export const layer: Layer.Layer<
226231
tool.edit,
227232
tool.write,
228233
tool.task,
234+
tool.taskstatus,
229235
tool.fetch,
230236
tool.todo,
231237
tool.search,
@@ -345,6 +351,7 @@ export const defaultLayer = Layer.suspend(() =>
345351
Layer.provide(Skill.defaultLayer),
346352
Layer.provide(Agent.defaultLayer),
347353
Layer.provide(Session.defaultLayer),
354+
Layer.provide(SessionStatus.defaultLayer),
348355
Layer.provide(Provider.defaultLayer),
349356
Layer.provide(Git.defaultLayer),
350357
Layer.provide(LSP.defaultLayer),

packages/opencode/src/tool/task.ts

Lines changed: 151 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
import * as Tool from "./tool"
22
import DESCRIPTION from "./task.txt"
33
import { Session } from "@/session/session"
4+
import { Bus } from "../bus"
45
import { SessionID, MessageID } from "../session/schema"
56
import { MessageV2 } from "../session/message-v2"
67
import { Agent } from "../agent/agent"
78
import type { SessionPrompt } from "../session/prompt"
89
import { Config } from "@/config/config"
9-
import { Effect, Schema } from "effect"
10+
import { SessionStatus } from "@/session/status"
11+
import { TuiEvent } from "@/cli/cmd/tui/event"
12+
import { Cause, Effect, Option, Schema } from "effect"
1013

1114
export interface TaskPromptOps {
1215
cancel(sessionID: SessionID): void
1316
resolvePromptParts(template: string): Effect.Effect<SessionPrompt.PromptInput["parts"]>
1417
prompt(input: SessionPrompt.PromptInput): Effect.Effect<MessageV2.WithParts>
18+
loop(input: SessionPrompt.LoopInput): Effect.Effect<MessageV2.WithParts>
19+
fork(effect: Effect.Effect<void, never, never>): void
1520
}
1621

1722
const id = "task"
@@ -20,24 +25,65 @@ export const Parameters = Schema.Struct({
2025
description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }),
2126
prompt: Schema.String.annotate({ description: "The task for the agent to perform" }),
2227
subagent_type: Schema.String.annotate({ description: "The type of specialized agent to use for this task" }),
23-
task_id: Schema.optional(Schema.String).annotate({
28+
task_id: Schema.optional(SessionID).annotate({
2429
description:
2530
"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)",
2631
}),
2732
command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }),
33+
background: Schema.optional(Schema.Boolean).annotate({
34+
description: "When true, launch the subagent in the background and return immediately",
35+
}),
2836
})
2937

38+
function output(sessionID: SessionID, text: string) {
39+
return [
40+
`task_id: ${sessionID} (for resuming to continue this task if needed)`,
41+
"",
42+
"<task_result>",
43+
text,
44+
"</task_result>",
45+
].join("\n")
46+
}
47+
48+
function backgroundOutput(sessionID: SessionID) {
49+
return [
50+
`task_id: ${sessionID} (for polling this task with task_status)`,
51+
"state: running",
52+
"",
53+
"<task_result>",
54+
"Background task started. Continue your current work and call task_status when you need the result.",
55+
"</task_result>",
56+
].join("\n")
57+
}
58+
59+
function backgroundMessage(input: { sessionID: SessionID; description: string; state: "completed" | "error"; text: string }) {
60+
const tag = input.state === "completed" ? "task_result" : "task_error"
61+
const title =
62+
input.state === "completed"
63+
? `Background task completed: ${input.description}`
64+
: `Background task failed: ${input.description}`
65+
return [title, `task_id: ${input.sessionID}`, `state: ${input.state}`, `<${tag}>`, input.text, `</${tag}>`].join(
66+
"\n",
67+
)
68+
}
69+
70+
function errorText(error: unknown) {
71+
if (error instanceof Error) return error.message
72+
return String(error)
73+
}
74+
3075
export const TaskTool = Tool.define(
3176
id,
3277
Effect.gen(function* () {
3378
const agent = yield* Agent.Service
79+
const bus = yield* Bus.Service
3480
const config = yield* Config.Service
3581
const sessions = yield* Session.Service
82+
const status = yield* SessionStatus.Service
3683

37-
const run = Effect.fn("TaskTool.execute")(function* (
38-
params: Schema.Schema.Type<typeof Parameters>,
39-
ctx: Tool.Context,
40-
) {
84+
const run = Effect.fn(
85+
"TaskTool.execute",
86+
)(function* (params: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) {
4187
const cfg = yield* config.get()
4288

4389
if (!ctx.extra?.bypassAgentCheck) {
@@ -62,7 +108,7 @@ export const TaskTool = Tool.define(
62108

63109
const taskID = params.task_id
64110
const session = taskID
65-
? yield* sessions.get(SessionID.make(taskID)).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
111+
? yield* sessions.get(taskID).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
66112
: undefined
67113
const nextSession =
68114
session ??
@@ -103,19 +149,107 @@ export const TaskTool = Tool.define(
103149
modelID: msg.info.modelID,
104150
providerID: msg.info.providerID,
105151
}
152+
const parentModel = {
153+
modelID: msg.info.modelID,
154+
providerID: msg.info.providerID,
155+
}
156+
const background = params.background === true
157+
158+
const metadata = {
159+
sessionId: nextSession.id,
160+
model,
161+
...(background ? { background: true } : {}),
162+
}
106163

107164
yield* ctx.metadata({
108165
title: params.description,
109-
metadata: {
110-
sessionId: nextSession.id,
111-
model,
112-
},
166+
metadata,
113167
})
114168

115169
const ops = ctx.extra?.promptOps as TaskPromptOps
116170
if (!ops) return yield* Effect.fail(new Error("TaskTool requires promptOps in ctx.extra"))
117171

118-
const messageID = MessageID.ascending()
172+
const runTask = Effect.fn("TaskTool.runTask")(function* () {
173+
const parts = yield* ops.resolvePromptParts(params.prompt)
174+
const result = yield* ops.prompt({
175+
messageID: MessageID.ascending(),
176+
sessionID: nextSession.id,
177+
model: {
178+
modelID: model.modelID,
179+
providerID: model.providerID,
180+
},
181+
agent: next.name,
182+
tools: {
183+
...(canTodo ? {} : { todowrite: false }),
184+
...(canTask ? {} : { task: false }),
185+
...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])),
186+
},
187+
parts,
188+
})
189+
return result.parts.findLast((item) => item.type === "text")?.text ?? ""
190+
})
191+
192+
const continueIfIdle = Effect.fn("TaskTool.continueIfIdle")(function* (input: {
193+
userID: MessageID
194+
state: "completed" | "error"
195+
}) {
196+
if ((yield* status.get(ctx.sessionID)).type !== "idle") return
197+
const latest = yield* sessions.findMessage(ctx.sessionID, (item) => item.info.role === "user")
198+
if (Option.isNone(latest)) return
199+
if (latest.value.info.id !== input.userID) return
200+
yield* bus.publish(TuiEvent.ToastShow, {
201+
title: input.state === "completed" ? "Background task complete" : "Background task failed",
202+
message:
203+
input.state === "completed"
204+
? `Background task \"${params.description}\" finished. Resuming the main thread.`
205+
: `Background task \"${params.description}\" failed. Resuming the main thread.`,
206+
variant: input.state === "completed" ? "success" : "error",
207+
duration: 5000,
208+
})
209+
yield* ops.loop({ sessionID: ctx.sessionID }).pipe(Effect.ignore)
210+
})
211+
212+
if (background) {
213+
const inject = Effect.fn("TaskTool.injectBackgroundResult")(function* (state: "completed" | "error", text: string) {
214+
const message = yield* ops.prompt({
215+
sessionID: ctx.sessionID,
216+
noReply: true,
217+
model: parentModel,
218+
agent: ctx.agent,
219+
parts: [
220+
{
221+
type: "text",
222+
synthetic: true,
223+
text: backgroundMessage({
224+
sessionID: nextSession.id,
225+
description: params.description,
226+
state,
227+
text,
228+
}),
229+
},
230+
],
231+
})
232+
yield* continueIfIdle({ userID: message.info.id, state })
233+
})
234+
235+
ops.fork(
236+
runTask().pipe(
237+
Effect.matchCauseEffect({
238+
onSuccess: (text) => inject("completed", text),
239+
onFailure: (cause) =>
240+
inject("error", errorText(Cause.squash(cause))).pipe(Effect.catchCause(() => Effect.void)),
241+
}),
242+
Effect.catchCause(() => Effect.void),
243+
Effect.asVoid,
244+
),
245+
)
246+
247+
return {
248+
title: params.description,
249+
metadata,
250+
output: backgroundOutput(nextSession.id),
251+
}
252+
}
119253

120254
function cancel() {
121255
ops.cancel(nextSession.id)
@@ -127,50 +261,24 @@ export const TaskTool = Tool.define(
127261
}),
128262
() =>
129263
Effect.gen(function* () {
130-
const parts = yield* ops.resolvePromptParts(params.prompt)
131-
const result = yield* ops.prompt({
132-
messageID,
133-
sessionID: nextSession.id,
134-
model: {
135-
modelID: model.modelID,
136-
providerID: model.providerID,
137-
},
138-
agent: next.name,
139-
tools: {
140-
...(canTodo ? {} : { todowrite: false }),
141-
...(canTask ? {} : { task: false }),
142-
...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])),
143-
},
144-
parts,
145-
})
146-
264+
const text = yield* runTask()
147265
return {
148266
title: params.description,
149-
metadata: {
150-
sessionId: nextSession.id,
151-
model,
152-
},
153-
output: [
154-
`task_id: ${nextSession.id} (for resuming to continue this task if needed)`,
155-
"",
156-
"<task_result>",
157-
result.parts.findLast((item) => item.type === "text")?.text ?? "",
158-
"</task_result>",
159-
].join("\n"),
267+
metadata,
268+
output: output(nextSession.id, text),
160269
}
161270
}),
162271
() =>
163272
Effect.sync(() => {
164273
ctx.abort.removeEventListener("abort", cancel)
165274
}),
166275
)
167-
})
276+
}, Effect.orDie)
168277

169278
return {
170279
description: DESCRIPTION,
171280
parameters: Parameters,
172-
execute: (params: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) =>
173-
run(params, ctx).pipe(Effect.orDie),
281+
execute: run,
174282
}
175283
}),
176284
)

packages/opencode/src/tool/task.txt

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ When NOT to use the Task tool:
1414

1515
Usage notes:
1616
1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
17-
2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session.
18-
3. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
19-
4. The agent's outputs should generally be trusted
20-
5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
21-
6. 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.
17+
2. By default, task waits for completion and returns the result immediately, along with a task_id you can reuse later to continue the same subagent session.
18+
3. Set background=true to launch asynchronously. In background mode, continue your current work without waiting.
19+
4. For background runs, use task_status(task_id=..., wait=false) to poll, or wait=true to block until done (optionally with timeout_ms).
20+
5. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
21+
6. The agent's outputs should generally be trusted
22+
7. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
23+
8. 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.
2224

2325
Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above):
2426

0 commit comments

Comments
 (0)