opencode-subagent-tools 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,335 @@
1
+ import type { ToolEditor } from "@opencode/plugin/promise/tool"
2
+ import type { Config } from "../config"
3
+ import { toolError } from "../errors"
4
+ import {
5
+ CONTEXT_DELIVERY,
6
+ DELIVERY,
7
+ SEND_KIND,
8
+ SendAdmissionError,
9
+ applySendResult,
10
+ type Delivery,
11
+ type SendMessage,
12
+ type SendResultFields,
13
+ } from "../messages"
14
+ import { CHILD_STATUSES } from "../status"
15
+ import { maxLengthError, textLength } from "../text"
16
+ import {
17
+ MAX_DESCRIPTION_LENGTH,
18
+ readTextField,
19
+ readToolInput,
20
+ requireSessionID,
21
+ requireText,
22
+ } from "./input"
23
+ import { TOOL } from "./names"
24
+ import {
25
+ formatPropertyDescription,
26
+ resolveToolOutputStrategy,
27
+ type OutputStrategy,
28
+ } from "./output"
29
+
30
+ export interface SendOutput extends SendResultFields {
31
+ sessionID: string
32
+ delivery: Delivery
33
+ chars: number
34
+ resume: boolean
35
+ }
36
+
37
+ export interface ContextOutput extends SendResultFields {
38
+ sessionID: string
39
+ delivery: typeof CONTEXT_DELIVERY
40
+ chars: number
41
+ description?: string
42
+ }
43
+
44
+ const SEND_OUTPUT_SCHEMA = {
45
+ type: "object",
46
+ properties: {
47
+ sessionID: { type: "string" },
48
+ messageID: { type: "string" },
49
+ delivery: { type: "string", enum: Object.values(DELIVERY) },
50
+ chars: { type: "integer" },
51
+ resume: {
52
+ type: "boolean",
53
+ description: "Whether the message could wake an idle child.",
54
+ },
55
+ status: {
56
+ type: "string",
57
+ enum: [...CHILD_STATUSES],
58
+ description:
59
+ "Status observed before the message was accepted; a wake may not be reflected yet.",
60
+ },
61
+ pending: {
62
+ type: "boolean",
63
+ description: "True when the message was accepted without waking an idle child.",
64
+ },
65
+ },
66
+ required: ["sessionID", "delivery", "chars", "resume"],
67
+ additionalProperties: false,
68
+ } as const
69
+
70
+ const CONTEXT_OUTPUT_SCHEMA = {
71
+ type: "object",
72
+ properties: {
73
+ sessionID: { type: "string" },
74
+ messageID: { type: "string" },
75
+ delivery: { type: "string", enum: [CONTEXT_DELIVERY] },
76
+ chars: { type: "integer" },
77
+ description: { type: "string" },
78
+ status: {
79
+ type: "string",
80
+ enum: [...CHILD_STATUSES],
81
+ description:
82
+ "Status observed before the message was accepted; context does not wake the child.",
83
+ },
84
+ pending: { type: "boolean" },
85
+ },
86
+ required: ["sessionID", "delivery", "chars"],
87
+ additionalProperties: false,
88
+ } as const
89
+
90
+ export interface PromptSendConfig {
91
+ delivery: Delivery
92
+ failureLabel: string
93
+ outputStrategy: OutputStrategy
94
+ }
95
+
96
+ const ADMITTED_LABEL: Record<Delivery, string> = {
97
+ [DELIVERY.steer]: "Steering message sent to",
98
+ [DELIVERY.queue]: "Message queued for",
99
+ }
100
+
101
+ export interface SendDeps {
102
+ config: Config
103
+ sendMessage: SendMessage
104
+ }
105
+
106
+ /**
107
+ * Shared execute path for the two prompt-delivery tools. The requested
108
+ * delivery is fixed per tool; the output uses the delivery reported for the
109
+ * accepted message when provided.
110
+ */
111
+ const runPromptSend = async (
112
+ rawInput: unknown,
113
+ context: Parameters<SendMessage>[1],
114
+ config: PromptSendConfig,
115
+ { config: pluginConfig, sendMessage }: SendDeps,
116
+ ) => {
117
+ const { limits } = pluginConfig
118
+ const { outputStrategy } = config
119
+ const { input, format } = readToolInput(rawInput, outputStrategy)
120
+ const textError = maxLengthError(input.text, limits.maxTextLength, "text")
121
+ if (textError) return toolError(textError)
122
+ const sessionID = requireSessionID(input.sessionID)
123
+ const text = requireText(input.text, limits.maxTextLength)
124
+ const resume = input.resume === undefined ? true : input.resume === true
125
+ try {
126
+ const result = await sendMessage(
127
+ {
128
+ sessionID,
129
+ text,
130
+ kind: SEND_KIND.prompt,
131
+ delivery: config.delivery,
132
+ resume,
133
+ },
134
+ context,
135
+ config.failureLabel,
136
+ )
137
+ const delivery = result.admitted?.delivery ?? config.delivery
138
+ const admittedLabel = ADMITTED_LABEL[delivery]
139
+ const chars = textLength(result.admitted?.text ?? text)
140
+ const output: SendOutput = {
141
+ sessionID,
142
+ delivery,
143
+ chars,
144
+ resume,
145
+ }
146
+ applySendResult(output, result)
147
+ return outputStrategy.respond(
148
+ `${admittedLabel} ${sessionID}` +
149
+ (result.admitted?.id ? ` as ${result.admitted.id}` : "") +
150
+ ` (delivery=${delivery}, resume=${resume}, ${chars} chars).`,
151
+ output,
152
+ format,
153
+ )
154
+ } catch (error) {
155
+ if (error instanceof SendAdmissionError) return toolError(error.message)
156
+ throw error
157
+ }
158
+ }
159
+
160
+ const sendInputSchema = (
161
+ outputStrategy: OutputStrategy,
162
+ maxTextLength: number,
163
+ textDescription: string,
164
+ resumeDescription: string,
165
+ ) => ({
166
+ type: "object",
167
+ properties: {
168
+ sessionID: {
169
+ type: "string",
170
+ description: "Target session ID, e.g. ses_...",
171
+ },
172
+ text: {
173
+ type: "string",
174
+ description: `${textDescription} Maximum ${maxTextLength} characters; longer input is rejected.`,
175
+ },
176
+ resume: {
177
+ type: "boolean",
178
+ description: resumeDescription,
179
+ },
180
+ ...outputStrategy.formatProperty(
181
+ formatPropertyDescription(outputStrategy, "structured output"),
182
+ ),
183
+ },
184
+ required: ["sessionID", "text"],
185
+ additionalProperties: false,
186
+ })
187
+
188
+ export const registerSteerTool = (editor: ToolEditor, deps: SendDeps) => {
189
+ const { allowedOutputFormats, limits } = deps.config
190
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.steer)
191
+ editor.add({
192
+ name: TOOL.steer,
193
+ description:
194
+ "Send an instruction into a session at its next model request. " +
195
+ "Use it to correct course, add a constraint, or forbid a step. " +
196
+ "It does not interrupt current work: the message is delivered before the next request. " +
197
+ "By default an idle child is woken; set resume:false to accept the message without waking it. " +
198
+ "Use queue instead when the message should wait until the current task settles.",
199
+ input: sendInputSchema(
200
+ outputStrategy,
201
+ limits.maxTextLength,
202
+ "Instruction for the child.",
203
+ "Default true: wake an idle child and start a new turn. Set false to accept without waking; an idle child keeps the message pending until its next run.",
204
+ ),
205
+ output: outputStrategy.schema(SEND_OUTPUT_SCHEMA),
206
+ options: { namespace: deps.config.namespace },
207
+ execute: async (rawInput, context) =>
208
+ runPromptSend(
209
+ rawInput,
210
+ context,
211
+ {
212
+ delivery: DELIVERY.steer,
213
+ failureLabel: "Steer",
214
+ outputStrategy,
215
+ },
216
+ deps,
217
+ ),
218
+ })
219
+ }
220
+
221
+ export const registerQueueTool = (editor: ToolEditor, deps: SendDeps) => {
222
+ const { allowedOutputFormats, limits } = deps.config
223
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.queue)
224
+ editor.add({
225
+ name: TOOL.queue,
226
+ description:
227
+ "Queue a message for a session as its next independent turn. " +
228
+ "Unlike steer, it does not join the current run: it waits until the current task settles, then starts a separate turn. " +
229
+ "Use it for 'do this next' work. By default an idle child is woken; set resume:false to accept the message without waking it. " +
230
+ "Use steer instead to correct the current run.",
231
+ input: sendInputSchema(
232
+ outputStrategy,
233
+ limits.maxTextLength,
234
+ "Follow-up message.",
235
+ "Default true: wake an idle child and start the queued turn. Set false to accept without waking; an idle child keeps the message pending until its next run.",
236
+ ),
237
+ output: outputStrategy.schema(SEND_OUTPUT_SCHEMA),
238
+ options: { namespace: deps.config.namespace },
239
+ execute: async (rawInput, context) =>
240
+ runPromptSend(
241
+ rawInput,
242
+ context,
243
+ {
244
+ delivery: DELIVERY.queue,
245
+ failureLabel: "Queue",
246
+ outputStrategy,
247
+ },
248
+ deps,
249
+ ),
250
+ })
251
+ }
252
+
253
+ export const registerContextTool = (editor: ToolEditor, deps: SendDeps) => {
254
+ const { allowedOutputFormats, limits } = deps.config
255
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.context)
256
+ const { sendMessage } = deps
257
+
258
+ editor.add({
259
+ name: TOOL.context,
260
+ description:
261
+ "Inject context into a session without asking for a turn: a synthetic message. " +
262
+ "Delivered at the child's next step boundary; an idle child keeps it pending until it runs again. " +
263
+ "Use it for facts and intermediate results, not for instructions. " +
264
+ "For an instruction without waking, use steer with resume:false; for a follow-up turn, use queue.",
265
+ input: {
266
+ type: "object",
267
+ properties: {
268
+ sessionID: {
269
+ type: "string",
270
+ description: "Target session ID, e.g. ses_...",
271
+ },
272
+ text: {
273
+ type: "string",
274
+ description: `Context text. Maximum ${limits.maxTextLength} characters; longer input is rejected.`,
275
+ },
276
+ description: {
277
+ type: "string",
278
+ description: `Short label shown in the transcript. Maximum ${MAX_DESCRIPTION_LENGTH} characters.`,
279
+ },
280
+ ...outputStrategy.formatProperty(
281
+ formatPropertyDescription(outputStrategy, "structured output"),
282
+ ),
283
+ },
284
+ required: ["sessionID", "text"],
285
+ additionalProperties: false,
286
+ },
287
+ output: outputStrategy.schema(CONTEXT_OUTPUT_SCHEMA),
288
+ options: { namespace: deps.config.namespace },
289
+ execute: async (rawInput, context) => {
290
+ const { input, format } = readToolInput(rawInput, outputStrategy)
291
+ const textError = maxLengthError(input?.text, limits.maxTextLength, "text")
292
+ if (textError) return toolError(textError)
293
+ const descriptionField = readTextField(
294
+ input?.description,
295
+ MAX_DESCRIPTION_LENGTH,
296
+ "description",
297
+ )
298
+ if (descriptionField.error) return toolError(descriptionField.error)
299
+ const sessionID = requireSessionID(input?.sessionID)
300
+ const text = requireText(input?.text, limits.maxTextLength)
301
+ const description = descriptionField.text
302
+ try {
303
+ const result = await sendMessage(
304
+ {
305
+ sessionID,
306
+ text,
307
+ kind: SEND_KIND.synthetic,
308
+ resume: false,
309
+ description,
310
+ },
311
+ context,
312
+ "Context injection",
313
+ )
314
+ const chars = textLength(result.admitted?.text ?? text)
315
+ const output: ContextOutput = {
316
+ sessionID,
317
+ delivery: CONTEXT_DELIVERY,
318
+ chars,
319
+ }
320
+ if (description) output.description = description
321
+ applySendResult(output, result)
322
+ return outputStrategy.respond(
323
+ `Context injected into ${sessionID}` +
324
+ (result.admitted?.id ? ` as ${result.admitted.id}` : "") +
325
+ ` (${chars} chars).`,
326
+ output,
327
+ format,
328
+ )
329
+ } catch (error) {
330
+ if (error instanceof SendAdmissionError) return toolError(error.message)
331
+ throw error
332
+ }
333
+ },
334
+ })
335
+ }