Skip to content

Commit 452da0b

Browse files
Apply PR #24174: feat(core): add background subagent support
2 parents 86fc702 + 80aeb78 commit 452da0b

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
@@ -1997,7 +1997,9 @@ function Task(props: ToolProps<typeof TaskTool>) {
19971997

19981998
const content = createMemo(() => {
19991999
if (!props.input.description) return ""
2000-
let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${props.input.description}`]
2000+
const description =
2001+
props.metadata.background === true ? `${props.input.description} (background)` : props.input.description
2002+
let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${description}`]
20012003

20022004
if (isRunning() && tools().length > 0) {
20032005
// 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"
@@ -49,6 +50,7 @@ import { Agent } from "../agent/agent"
4950
import { Git } from "@/git"
5051
import { Skill } from "../skill"
5152
import { Permission } from "@/permission"
53+
import { SessionStatus } from "@/session/status"
5254

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

@@ -81,6 +83,7 @@ export const layer: Layer.Layer<
8183
| Agent.Service
8284
| Skill.Service
8385
| Session.Service
86+
| SessionStatus.Service
8487
| Provider.Service
8588
| Git.Service
8689
| LSP.Service
@@ -119,6 +122,7 @@ export const layer: Layer.Layer<
119122
const greptool = yield* GrepTool
120123
const patchtool = yield* ApplyPatchTool
121124
const skilltool = yield* SkillTool
125+
const taskstatus = yield* TaskStatusTool
122126
const agent = yield* Agent.Service
123127

124128
const state = yield* InstanceState.make<State>(
@@ -199,6 +203,7 @@ export const layer: Layer.Layer<
199203
edit: Tool.init(edit),
200204
write: Tool.init(writetool),
201205
task: Tool.init(task),
206+
taskstatus: Tool.init(taskstatus),
202207
fetch: Tool.init(webfetch),
203208
todo: Tool.init(todo),
204209
search: Tool.init(websearch),
@@ -223,6 +228,7 @@ export const layer: Layer.Layer<
223228
tool.edit,
224229
tool.write,
225230
tool.task,
231+
tool.taskstatus,
226232
tool.fetch,
227233
tool.todo,
228234
tool.search,
@@ -341,6 +347,7 @@ export const defaultLayer = Layer.suspend(() =>
341347
Layer.provide(Skill.defaultLayer),
342348
Layer.provide(Agent.defaultLayer),
343349
Layer.provide(Session.defaultLayer),
350+
Layer.provide(SessionStatus.defaultLayer),
344351
Layer.provide(Provider.defaultLayer),
345352
Layer.provide(Git.defaultLayer),
346353
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 parent = yield* sessions.get(ctx.sessionID)
68114
const nextSession =
@@ -107,19 +153,107 @@ export const TaskTool = Tool.define(
107153
modelID: msg.info.modelID,
108154
providerID: msg.info.providerID,
109155
}
156+
const parentModel = {
157+
modelID: msg.info.modelID,
158+
providerID: msg.info.providerID,
159+
}
160+
const background = params.background === true
161+
162+
const metadata = {
163+
sessionId: nextSession.id,
164+
model,
165+
...(background ? { background: true } : {}),
166+
}
110167

111168
yield* ctx.metadata({
112169
title: params.description,
113-
metadata: {
114-
sessionId: nextSession.id,
115-
model,
116-
},
170+
metadata,
117171
})
118172

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

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

124258
function cancel() {
125259
ops.cancel(nextSession.id)
@@ -131,50 +265,24 @@ export const TaskTool = Tool.define(
131265
}),
132266
() =>
133267
Effect.gen(function* () {
134-
const parts = yield* ops.resolvePromptParts(params.prompt)
135-
const result = yield* ops.prompt({
136-
messageID,
137-
sessionID: nextSession.id,
138-
model: {
139-
modelID: model.modelID,
140-
providerID: model.providerID,
141-
},
142-
agent: next.name,
143-
tools: {
144-
...(canTodo ? {} : { todowrite: false }),
145-
...(canTask ? {} : { task: false }),
146-
...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])),
147-
},
148-
parts,
149-
})
150-
268+
const text = yield* runTask()
151269
return {
152270
title: params.description,
153-
metadata: {
154-
sessionId: nextSession.id,
155-
model,
156-
},
157-
output: [
158-
`task_id: ${nextSession.id} (for resuming to continue this task if needed)`,
159-
"",
160-
"<task_result>",
161-
result.parts.findLast((item) => item.type === "text")?.text ?? "",
162-
"</task_result>",
163-
].join("\n"),
271+
metadata,
272+
output: output(nextSession.id, text),
164273
}
165274
}),
166275
() =>
167276
Effect.sync(() => {
168277
ctx.abort.removeEventListener("abort", cancel)
169278
}),
170279
)
171-
})
280+
}, Effect.orDie)
172281

173282
return {
174283
description: DESCRIPTION,
175284
parameters: Parameters,
176-
execute: (params: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) =>
177-
run(params, ctx).pipe(Effect.orDie),
285+
execute: run,
178286
}
179287
}),
180288
)

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)