Repository navigation
Expand file tree
/
Copy pathsubagent.ts
More file actions
276 lines (261 loc) · 12.6 KB
/
Copy pathsubagent.ts
File metadata and controls
276 lines (261 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
export * as SubagentTool from "./subagent.js"
import { ToolFailure } from "@opencode/ai/effect"
import type { Context } from "@opencode/plugin/effect/plugin"
import type { SessionHooks } from "@opencode/plugin/effect/session"
import { Effect, Predicate, Schema } from "effect"
import { Agent } from "../../agent.js"
import { Config } from "../../config.js"
import { Job } from "../../job.js"
import { Model } from "../../model.js"
import { Permission } from "../../permission.js"
import { Session } from "../../session.js"
import { SessionSchema } from "../../session/schema.js"
import { SubagentJob } from "../../session/subagent-job.js"
export const name = "subagent"
const backgroundResult = (sessionID: SessionSchema.ID) => ({
sessionID,
status: "running" as const,
output: [
`The subagent is working in the background (sessionID: ${sessionID}). You will receive a <subagent> message when it goes idle, and again after each later round of work.`,
"DO NOT sleep, poll, proactively check on its progress, or duplicate this subagent's work.",
"Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.",
"To send it follow-ups or change its instructions while it runs, call subagent again with this sessionID.",
].join("\n"),
})
export const Input = Schema.Struct({
agent: Schema.String.annotate({
description:
"The type of specialized agent to use for this task. If the user asks for a subagent by a name that is not one of the available subagents, they most likely mean a model: pick a suitable agent and pass the name through the model parameter instead.",
}),
description: Schema.String.annotate({ description: "A short 3-5 word label for the task, displayed to the user" }),
prompt: Schema.String.annotate({ description: "The task for the subagent to perform" }),
model: Schema.optionalKey(Schema.String).annotate({
description:
'NEVER set this unless the user explicitly asks for a particular model or variant. It must be a chat model; image and decision models can\'t run subagents. The value is written as "providerID/modelID", or "providerID/modelID#variant" to include a variant. Do not guess the ID: look the model up with the models tool, filtering to your own provider first.',
}),
sessionID: Schema.optionalKey(SessionSchema.ID).annotate({
description: "Send a follow-up to an existing subagent, running or finished. Omit to start a new one.",
}),
})
export const Output = Schema.Struct({
sessionID: SessionSchema.ID,
status: Schema.Literal("running"),
output: Schema.String,
})
export const description = [
"Spawns an agent in a child session to work on the specified task.",
"Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `<subagent>` message each time the child goes idle, including after later work.",
"Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll, or proactively check on the child's progress.",
"New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
"Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.",
].join("\n")
export const Plugin = {
id: "opencode.tool.subagent",
effect: Effect.fn("SubagentTool.Plugin")(function* (ctx: Context) {
const sessions = yield* Session.Service
const jobs = yield* Job.Service
const agents = yield* Agent.Service
const config = yield* Config.Service
const permission = yield* Permission.Service
const models = yield* Model.Service
const subagents = yield* SubagentJob.Service
const resolveModel = Effect.fn("SubagentTool.resolveModel")(function* (input: string) {
const ref = yield* Effect.try({
try: () => Model.Ref.parse(input),
catch: () =>
new ToolFailure({
message: `Invalid model "${input}". Use "providerID/modelID" or "providerID/modelID#variant".`,
}),
})
const model = (yield* models.available()).find(
(model) => model.providerID === ref.providerID && model.id === ref.id,
)
if (model === undefined) {
const other = (yield* models.available(["image", "decision"])).find(
(model) => model.providerID === ref.providerID && model.id === ref.id,
)
return yield* new ToolFailure({
message: other
? `Model "${ref.providerID}/${ref.id}" is ${other.type === "image" ? "an image" : "a decision"} model; subagents need a chat model. Use the models tool to find one.`
: `Model "${ref.providerID}/${ref.id}" is not available. Use the models tool to see what is available.`,
})
}
if (ref.variant !== undefined && !model.variants.some((variant) => variant.id === ref.variant))
return yield* new ToolFailure({
message:
model.variants.length === 0
? `Model "${ref.providerID}/${ref.id}" has no variants. Omit the variant.`
: `Variant "${ref.variant}" is not available for "${ref.providerID}/${ref.id}". Available: ${model.variants.map((variant) => variant.id).join(", ")}.`,
})
return ref
})
yield* ctx.tool
.transform((editor) =>
editor.add({
name,
options: { codemode: false },
description,
input: Input,
output: Output,
execute: (input, context) =>
Effect.gen(function* () {
const parent = yield* sessions
.get(context.sessionID)
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Parent session not found: ${context.sessionID}`, error }),
),
)
let current = parent
let depth = 0
while (current.parentID) {
depth++
current = yield* sessions
.get(current.parentID)
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Parent session not found: ${current.parentID}`, error }),
),
)
}
const limit = Config.latest(yield* config.entries(), "experimental")?.subagent_depth ?? 1
if (depth >= limit)
return yield* new ToolFailure({
message: `Subagent depth limit reached (${limit}). Increase "experimental.subagent_depth" to allow nested subagents.`,
})
const agent = yield* agents.resolve(input.agent)
if (agent === undefined) return yield* new ToolFailure({ message: `Unknown agent: ${input.agent}` })
if (agent.mode === "primary")
return yield* new ToolFailure({ message: `Agent ${input.agent} cannot run as a subagent` })
yield* permission
.assert({
action: name,
resources: [agent.id],
save: [agent.id],
...Permission.invocation(context),
})
.pipe(Effect.mapError((error) => new ToolFailure({ message: `Subagent denied: ${agent.id}`, error })))
const existing =
input.sessionID === undefined
? undefined
: yield* sessions
.get(input.sessionID)
.pipe(
Effect.mapError(
(error) =>
new ToolFailure({ message: `Subagent session not found: ${input.sessionID}`, error }),
),
)
if (existing !== undefined && existing.parentID !== context.sessionID)
return yield* new ToolFailure({
message: `Session ${existing.id} is not a child of the current session`,
})
const override = input.model === undefined ? undefined : yield* resolveModel(input.model)
// Continuing with a different agent switches the child, mirroring create semantics
// where an explicit model wins over the agent's configured model, which wins over the inherited one.
if (existing !== undefined) {
const switched = existing.agent !== agent.id
const model = override ?? (switched ? agent.model : undefined)
yield* Effect.all([
switched ? sessions.switchAgent({ sessionID: existing.id, agent: agent.id }) : Effect.void,
model === undefined ? Effect.void : sessions.switchModel({ sessionID: existing.id, model }),
]).pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Failed to switch subagent session: ${existing.id}`, error }),
),
)
}
const model = override ?? agent.model ?? parent.model
const child =
existing ??
(yield* sessions
.create({
parentID: context.sessionID,
title: input.description,
agent: agent.id,
model,
})
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Parent session not found: ${context.sessionID}`, error }),
),
))
// A child that is not draining yet must be admitted without waking: the job's resume
// owns the start, so the period cannot run before its boundary is registered.
const running =
existing !== undefined &&
((yield* sessions.active).has(existing.id) || (yield* jobs.get(existing.id))?.status === "running")
yield* context.progress({ sessionID: child.id, status: "running" })
yield* sessions
.prompt({
sessionID: child.id,
text:
existing === undefined
? ["You are a subagent spawned by another session.", input.prompt].join("\n")
: input.prompt,
...(running ? {} : { resume: false }),
})
.pipe(
Effect.mapError(
(error) => new ToolFailure({ message: `Failed to prompt subagent: ${child.id}`, error }),
),
)
const recovery = {
kind: "subagent" as const,
parentSessionID: context.sessionID,
childSessionID: child.id,
agent: agent.name,
description: input.description,
}
yield* subagents.start(recovery)
return backgroundResult(child.id)
}).pipe(
Effect.map((output) => ({
output,
content: output.output,
metadata: { sessionID: output.sessionID, status: output.status },
})),
),
}),
)
.pipe(Effect.orDie)
yield* ctx.tool.hook("execute.before", (event) =>
Effect.sync(() => {
if (event.tool !== name || !Predicate.isObject(event.input)) return
if (event.input.model !== "" && event.input.sessionID !== "") return
const input = { ...event.input }
if (input.model === "") delete input.model
if (input.sessionID === "") delete input.sessionID
event.input = input
}),
)
const hook = (event: SessionHooks["context"]) =>
Effect.gen(function* () {
const tool = event.tools[name]
if (!tool) return
const selected = yield* agents.resolve(event.agent)
if (!selected) return
const available = (yield* agents.list())
.filter(
(agent) =>
agent.mode !== "primary" &&
!agent.hidden &&
Permission.evaluate(name, agent.id, selected.permissions).effect !== "deny",
)
.toSorted((a, b) => a.id.localeCompare(b.id))
if (available.length === 0) return
tool.description = [
tool.description,
"",
"Available subagents:",
...available.map(
(agent) =>
`- ${agent.id}: ${agent.description ?? "This subagent should only be called when explicitly requested."}`,
),
].join("\n")
})
yield* ctx.session.hook("context", hook)
yield* ctx.session.hook("compaction", hook)
yield* ctx.session.hook("generate", hook)
}),
}