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,527 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import type { ToolEditor } from "@opencode/plugin/promise/tool"
3
+ import type { Access } from "../access"
4
+ import type { Config } from "../config"
5
+ import { encodeCursor, isAfterCursor, readCursor } from "../cursor"
6
+ import type { Discovery } from "../discovery"
7
+ import { errorMessage, toolError } from "../errors"
8
+ import { INTERRUPT_OUTCOME, interruptOutcome } from "../interrupt"
9
+ import type { LiveStore } from "../live-state"
10
+ import { guardTarget, type Guard } from "../permissions"
11
+ import { CHILD_STATUSES, STATUS, TERMINAL_STATUSES, type ChildStatus } from "../status"
12
+ import { MAX_REASON_LENGTH, readTextField, readToolInput } from "./input"
13
+ import { TOOL } from "./names"
14
+ import { formatPropertyDescription, resolveToolOutputStrategy } from "./output"
15
+
16
+ export const CANCEL_INTERRUPT = INTERRUPT_OUTCOME
17
+
18
+ export type CancelInterrupt = (typeof CANCEL_INTERRUPT)[keyof typeof CANCEL_INTERRUPT]
19
+
20
+ export const CANCEL_READ_BACK = {
21
+ ok: "ok",
22
+ failed: "failed",
23
+ notRead: "not-read",
24
+ } as const
25
+
26
+ export type CancelReadBack = (typeof CANCEL_READ_BACK)[keyof typeof CANCEL_READ_BACK]
27
+
28
+ export interface CancelDescendantsTarget {
29
+ sessionID: string
30
+ interrupt: CancelInterrupt
31
+ readBack: CancelReadBack
32
+ status?: ChildStatus
33
+ error?: string
34
+ }
35
+
36
+ export interface CancelDescendantsOutput {
37
+ known: number
38
+ considered: number
39
+ running: number
40
+ beforeCursorRunning?: number
41
+ targets: CancelDescendantsTarget[]
42
+ remaining: number
43
+ aborted: boolean
44
+ reason?: string
45
+ cursor?: string
46
+ warning?: string
47
+ }
48
+
49
+ const CANCEL_DESCENDANTS_TARGET_SCHEMA = {
50
+ type: "object",
51
+ properties: {
52
+ sessionID: { type: "string" },
53
+ interrupt: {
54
+ type: "string",
55
+ enum: Object.values(CANCEL_INTERRUPT),
56
+ description:
57
+ "accepted: server accepted; rejected: no active execution; failed: call threw; unknown: aborted or no definitive answer.",
58
+ },
59
+ readBack: {
60
+ type: "string",
61
+ enum: Object.values(CANCEL_READ_BACK),
62
+ description:
63
+ "ok: status check succeeded and status is set; failed: status check failed; not-read: not attempted or aborted.",
64
+ },
65
+ status: { type: "string", enum: [...CHILD_STATUSES] },
66
+ error: { type: "string" },
67
+ },
68
+ required: ["sessionID", "interrupt", "readBack"],
69
+ additionalProperties: false,
70
+ } as const
71
+
72
+ const CANCEL_DESCENDANTS_OUTPUT_SCHEMA = {
73
+ type: "object",
74
+ properties: {
75
+ known: {
76
+ type: "integer",
77
+ description:
78
+ "All discovered descendants in the current pass, before the cursor is applied.",
79
+ },
80
+ considered: {
81
+ type: "integer",
82
+ description: "Descendants after the cursor.",
83
+ },
84
+ running: {
85
+ type: "integer",
86
+ description: "Running descendants among considered.",
87
+ },
88
+ beforeCursorRunning: {
89
+ type: "integer",
90
+ description:
91
+ "Running descendants before the cursor window; re-run without a cursor to include them.",
92
+ },
93
+ targets: {
94
+ type: "array",
95
+ description: "Attempted targets, newest launch first.",
96
+ items: CANCEL_DESCENDANTS_TARGET_SCHEMA,
97
+ },
98
+ remaining: {
99
+ type: "integer",
100
+ description: "Running targets not attempted; use cursor to continue.",
101
+ },
102
+ aborted: {
103
+ type: "boolean",
104
+ description:
105
+ "True when the call stopped before the batch completed; inspect targets and remaining, then retry.",
106
+ },
107
+ reason: { type: "string" },
108
+ cursor: { type: "string" },
109
+ warning: { type: "string" },
110
+ },
111
+ required: ["known", "considered", "running", "targets", "remaining", "aborted"],
112
+ additionalProperties: false,
113
+ } as const
114
+
115
+ const isTerminalTarget = (target: CancelDescendantsTarget): boolean =>
116
+ target.readBack === CANCEL_READ_BACK.ok &&
117
+ target.status !== undefined &&
118
+ TERMINAL_STATUSES.has(target.status)
119
+
120
+ const INTERRUPT_SUMMARY_LABEL: Readonly<Record<CancelInterrupt, string>> = {
121
+ [CANCEL_INTERRUPT.accepted]: "interrupt accepted",
122
+ [CANCEL_INTERRUPT.rejected]: "interrupt rejected",
123
+ [CANCEL_INTERRUPT.failed]: "interrupt failed",
124
+ [CANCEL_INTERRUPT.unknown]: "interrupt outcome unknown",
125
+ }
126
+
127
+ const INTERRUPT_SUMMARY_ORDER: readonly CancelInterrupt[] = Object.values(
128
+ CANCEL_INTERRUPT,
129
+ ).filter((outcome) => outcome !== CANCEL_INTERRUPT.accepted)
130
+
131
+ const READ_BACK_SUMMARY_LABEL: Readonly<Record<CancelReadBack, string>> = {
132
+ [CANCEL_READ_BACK.ok]: "read-back ok",
133
+ [CANCEL_READ_BACK.failed]: "read-back failed",
134
+ [CANCEL_READ_BACK.notRead]: "read-back not completed",
135
+ }
136
+
137
+ const countInterrupts = (
138
+ targets: readonly CancelDescendantsTarget[],
139
+ ): ReadonlyMap<string, number> => {
140
+ const counts = new Map<string, number>(
141
+ Object.values(CANCEL_INTERRUPT).map((outcome) => [outcome, 0]),
142
+ )
143
+ for (const target of targets) {
144
+ counts.set(target.interrupt, (counts.get(target.interrupt) ?? 0) + 1)
145
+ }
146
+ return counts
147
+ }
148
+
149
+ const countReadBacks = (
150
+ targets: readonly CancelDescendantsTarget[],
151
+ ): ReadonlyMap<string, number> => {
152
+ const counts = new Map<string, number>(
153
+ Object.values(CANCEL_READ_BACK).map((outcome) => [outcome, 0]),
154
+ )
155
+ for (const target of targets) {
156
+ counts.set(target.readBack, (counts.get(target.readBack) ?? 0) + 1)
157
+ }
158
+ return counts
159
+ }
160
+
161
+ const READ_BACK_DETAIL: ReadonlyMap<CancelReadBack, string> = new Map([
162
+ [CANCEL_READ_BACK.failed, READ_BACK_SUMMARY_LABEL[CANCEL_READ_BACK.failed]],
163
+ [CANCEL_READ_BACK.notRead, READ_BACK_SUMMARY_LABEL[CANCEL_READ_BACK.notRead]],
164
+ ])
165
+
166
+ type TargetDetail = (target: CancelDescendantsTarget) => string | undefined
167
+
168
+ const INTERRUPT_DETAIL: ReadonlyMap<CancelInterrupt, TargetDetail> = new Map([
169
+ [
170
+ CANCEL_INTERRUPT.accepted,
171
+ (target: CancelDescendantsTarget) => READ_BACK_DETAIL.get(target.readBack),
172
+ ],
173
+ [
174
+ CANCEL_INTERRUPT.rejected,
175
+ (target: CancelDescendantsTarget) =>
176
+ READ_BACK_DETAIL.get(target.readBack) ??
177
+ (target.status === STATUS.running
178
+ ? "interrupt rejected; state still says running"
179
+ : undefined),
180
+ ],
181
+ [
182
+ CANCEL_INTERRUPT.failed,
183
+ (target: CancelDescendantsTarget) =>
184
+ `interrupt failed: ${target.error ?? "unknown error"}`,
185
+ ],
186
+ [CANCEL_INTERRUPT.unknown, () => "interrupt outcome unknown"],
187
+ ])
188
+
189
+ const targetDetail = (target: CancelDescendantsTarget): string => {
190
+ const detail = INTERRUPT_DETAIL.get(target.interrupt)?.(target)
191
+ if (detail) return detail
192
+ if (target.status === STATUS.running) return "still running"
193
+ if (target.status === STATUS.unknown) return "status unknown"
194
+ return target.status ?? "status unavailable"
195
+ }
196
+
197
+ export const summarizeCancelDescendants = (
198
+ targets: readonly CancelDescendantsTarget[],
199
+ remaining: number,
200
+ cursor?: string,
201
+ ): string => {
202
+ if (targets.length === 0) {
203
+ if (remaining === 0) return "No running subagents needed an interrupt."
204
+ return `No interrupts were attempted; ${remaining} running subagent(s) left${
205
+ cursor ? `; use cursor ${cursor} to continue` : "; retry with the same cursor"
206
+ }.`
207
+ }
208
+
209
+ const interruptCounts = countInterrupts(targets)
210
+ const readBackCounts = countReadBacks(targets)
211
+ const terminal = targets.filter(isTerminalTarget).length
212
+ const stillRunning = targets.filter(
213
+ (target) =>
214
+ target.readBack === CANCEL_READ_BACK.ok && target.status === STATUS.running,
215
+ ).length
216
+ const readBackNotRead = targets.filter(
217
+ (target) =>
218
+ target.readBack === CANCEL_READ_BACK.notRead &&
219
+ (target.interrupt === CANCEL_INTERRUPT.accepted ||
220
+ target.interrupt === CANCEL_INTERRUPT.rejected),
221
+ ).length
222
+ const statusUnknown = targets.filter(
223
+ (target) =>
224
+ target.readBack === CANCEL_READ_BACK.ok && target.status === STATUS.unknown,
225
+ ).length
226
+
227
+ const accepted = interruptCounts.get(CANCEL_INTERRUPT.accepted) ?? 0
228
+ const parts: string[] = [
229
+ `Interrupt accepted for ${accepted} of ${targets.length} target(s)`,
230
+ ]
231
+ for (const outcome of INTERRUPT_SUMMARY_ORDER) {
232
+ const count = interruptCounts.get(outcome) ?? 0
233
+ if (count > 0) parts.push(`${count} ${INTERRUPT_SUMMARY_LABEL[outcome]}`)
234
+ }
235
+ const knownInterrupts = new Set<string>(Object.values(CANCEL_INTERRUPT))
236
+ for (const [outcome, count] of interruptCounts) {
237
+ if (!knownInterrupts.has(outcome) && count > 0) {
238
+ parts.push(`${count} interrupt ${outcome}`)
239
+ }
240
+ }
241
+ if (terminal > 0) parts.push(`${terminal} terminal`)
242
+ if (stillRunning > 0) parts.push(`${stillRunning} still running`)
243
+ const readBackFailed = readBackCounts.get(CANCEL_READ_BACK.failed) ?? 0
244
+ if (readBackFailed > 0) {
245
+ parts.push(`${readBackFailed} ${READ_BACK_SUMMARY_LABEL[CANCEL_READ_BACK.failed]}`)
246
+ }
247
+ if (readBackNotRead > 0) {
248
+ parts.push(`${readBackNotRead} ${READ_BACK_SUMMARY_LABEL[CANCEL_READ_BACK.notRead]}`)
249
+ }
250
+ const knownReadBacks = new Set<string>(Object.values(CANCEL_READ_BACK))
251
+ for (const [outcome, count] of readBackCounts) {
252
+ if (!knownReadBacks.has(outcome) && count > 0) {
253
+ parts.push(`${count} read-back ${outcome}`)
254
+ }
255
+ }
256
+ if (statusUnknown > 0) parts.push(`${statusUnknown} status unknown`)
257
+
258
+ let text = `${parts[0]}${parts.length > 1 ? `: ${parts.slice(1).join(", ")}` : ""}.`
259
+ if (remaining > 0) {
260
+ text += ` ${remaining} running subagent(s) left${
261
+ cursor ? `; use cursor ${cursor} to continue` : "; retry with the same cursor"
262
+ }.`
263
+ }
264
+
265
+ const details = targets
266
+ .filter((target) => !isTerminalTarget(target))
267
+ .map((target) => `${target.sessionID} (${targetDetail(target)})`)
268
+ if (details.length > 0) text += `\n${details.join("\n")}`
269
+ return text
270
+ }
271
+
272
+ export interface CancelDescendantsDeps {
273
+ config: Config
274
+ access: Access
275
+ discovery: Discovery
276
+ guard: Guard
277
+ live: LiveStore
278
+ session: Plugin.Context["session"]
279
+ }
280
+
281
+ export const registerCancelDescendantsTool = (
282
+ editor: ToolEditor,
283
+ { config, access, discovery, guard, live, session }: CancelDescendantsDeps,
284
+ ) => {
285
+ const { allowedOutputFormats, limits } = config
286
+ const outputStrategy = resolveToolOutputStrategy(
287
+ allowedOutputFormats,
288
+ TOOL.cancelDescendants,
289
+ )
290
+
291
+ editor.add({
292
+ name: TOOL.cancelDescendants,
293
+ description:
294
+ "Stop the running descendants of the calling session, including grandchildren, " +
295
+ `up to ${limits.maxCancelBatch} at a time. ` +
296
+ "There is no sessionID argument; it always stays in the caller's subtree. " +
297
+ "The batch is checked in one permission request and reports each target in targets. " +
298
+ "Use cursor while remaining is above 0. Cursor retries skip failed, unknown, rejected, and not-read targets. " +
299
+ "Nested cancellation can wake an intermediate parent; re-run list and cancel it again if it resumed. " +
300
+ "Discovery can miss running descendants. Use cancel for one target; this is a destructive batch and a soft interrupt, not a hard abort.",
301
+ input: {
302
+ type: "object",
303
+ properties: {
304
+ reason: {
305
+ type: "string",
306
+ description: `Short reason, recorded in the result. Maximum ${MAX_REASON_LENGTH} characters.`,
307
+ },
308
+ cursor: {
309
+ type: "string",
310
+ description:
311
+ "Cursor from a previous cancel_descendants call; pass it back unchanged.",
312
+ },
313
+ ...outputStrategy.formatProperty(
314
+ formatPropertyDescription(outputStrategy, "a short summary"),
315
+ ),
316
+ },
317
+ additionalProperties: false,
318
+ },
319
+ output: outputStrategy.schema(CANCEL_DESCENDANTS_OUTPUT_SCHEMA),
320
+ options: { namespace: config.namespace },
321
+ execute: async (rawInput, context) => {
322
+ const { input, format } = readToolInput(rawInput, outputStrategy)
323
+ const reasonField = readTextField(input?.reason, MAX_REASON_LENGTH, "reason")
324
+ if (reasonField.error) return toolError(reasonField.error)
325
+ const reason = reasonField.text
326
+ const reasonText = reason ? ` (${reason})` : ""
327
+ const caller = context?.sessionID
328
+ if (!caller) {
329
+ return toolError(
330
+ "Refusing: the calling session is unknown, so the subtree to cancel cannot be determined.",
331
+ )
332
+ }
333
+ const cursorResult = readCursor(input?.cursor, {
334
+ tool: TOOL.cancelDescendants,
335
+ root: caller,
336
+ })
337
+ if (cursorResult.error) {
338
+ return toolError(cursorResult.error)
339
+ }
340
+ const cursor = cursorResult.cursor
341
+ if (context?.signal?.aborted) {
342
+ return toolError("Aborted before discovery.")
343
+ }
344
+
345
+ const respond = (content: string, output: CancelDescendantsOutput) =>
346
+ outputStrategy.respond(content, output, format)
347
+
348
+ const found = await discovery.discoverRows(caller, context?.signal)
349
+ const warningMessage =
350
+ "discovery was incomplete; some running subagents may not have been stopped."
351
+ const warning = found.complete ? "" : `\nWarning: ${warningMessage}`
352
+ const known = found.rows
353
+ const afterCursor = cursor
354
+ ? known.filter((row) => isAfterCursor(row, cursor))
355
+ : known
356
+ const running = afterCursor.filter((row) => row.status === STATUS.running)
357
+ const beforeCursorRunning = cursor
358
+ ? known.filter(
359
+ (row) =>
360
+ !(row.launchedAt === cursor.launchedAt && row.id === cursor.id) &&
361
+ !isAfterCursor(row, cursor) &&
362
+ row.status === STATUS.running,
363
+ ).length
364
+ : 0
365
+ const cursorNote =
366
+ beforeCursorRunning > 0
367
+ ? `\nNote: ${beforeCursorRunning} running subagent(s) are before this cursor window; re-run without a cursor to include them.`
368
+ : ""
369
+
370
+ const emptyOutput = (aborted = false): CancelDescendantsOutput => ({
371
+ known: known.length,
372
+ considered: afterCursor.length,
373
+ running: running.length,
374
+ ...(beforeCursorRunning > 0 ? { beforeCursorRunning } : {}),
375
+ targets: [],
376
+ remaining: running.length,
377
+ aborted,
378
+ ...(reason ? { reason } : {}),
379
+ })
380
+ const finish = (content: string, output: CancelDescendantsOutput) =>
381
+ found.complete
382
+ ? respond(content + cursorNote, output)
383
+ : respond(content + cursorNote + warning, {
384
+ ...output,
385
+ warning: warningMessage,
386
+ })
387
+ const abortBeforeInterrupts = () =>
388
+ finish(
389
+ `Aborted before any interrupt was requested.${reasonText}`,
390
+ emptyOutput(true),
391
+ )
392
+
393
+ if (context?.signal?.aborted) return abortBeforeInterrupts()
394
+
395
+ if (known.length === 0) {
396
+ return finish(
397
+ `Nothing to stop for ${caller}: no subagents discovered. ` +
398
+ `Run ${config.namespace}_${TOOL.list} to see discovered sessions.${reasonText}`,
399
+ emptyOutput(),
400
+ )
401
+ }
402
+
403
+ if (afterCursor.length === 0) {
404
+ return finish(
405
+ `Cursor is past the end: ${known.length} known subagent(s).${reasonText}`,
406
+ emptyOutput(),
407
+ )
408
+ }
409
+
410
+ if (running.length === 0) {
411
+ return finish(
412
+ `No running subagents among ${afterCursor.length} known${cursor ? " after the cursor" : ""}.${reasonText}`,
413
+ emptyOutput(),
414
+ )
415
+ }
416
+
417
+ const targets = running.slice(0, limits.maxCancelBatch)
418
+ if (context?.signal?.aborted) return abortBeforeInterrupts()
419
+
420
+ // Evaluate the whole batch before interrupting anything: a denial
421
+ // must surface as a tool error without leaving a partial batch behind.
422
+ await guard(
423
+ targets.map((target) => guardTarget(target, target.id)),
424
+ context,
425
+ )
426
+ if (context?.signal?.aborted) return abortBeforeInterrupts()
427
+
428
+ const results: CancelDescendantsTarget[] = []
429
+ let aborted = false
430
+
431
+ for (const target of targets) {
432
+ if (context?.signal?.aborted) {
433
+ aborted = true
434
+ break
435
+ }
436
+
437
+ let interrupt: CancelInterrupt
438
+ try {
439
+ const result = (await session.interrupt(
440
+ { sessionID: target.id, resume: false },
441
+ { signal: context?.signal },
442
+ )) as { interrupted?: boolean } | undefined
443
+ interrupt = interruptOutcome(result)
444
+ } catch (error) {
445
+ if (context?.signal?.aborted) {
446
+ results.push({
447
+ sessionID: target.id,
448
+ interrupt: CANCEL_INTERRUPT.unknown,
449
+ readBack: CANCEL_READ_BACK.notRead,
450
+ error: "aborted during interrupt; outcome unknown",
451
+ })
452
+ aborted = true
453
+ break
454
+ }
455
+ results.push({
456
+ sessionID: target.id,
457
+ interrupt: CANCEL_INTERRUPT.failed,
458
+ readBack: CANCEL_READ_BACK.notRead,
459
+ error: errorMessage(error),
460
+ })
461
+ continue
462
+ }
463
+
464
+ if (context?.signal?.aborted) {
465
+ results.push({
466
+ sessionID: target.id,
467
+ interrupt,
468
+ readBack: CANCEL_READ_BACK.notRead,
469
+ error: "aborted before read-back; outcome unknown",
470
+ })
471
+ aborted = true
472
+ break
473
+ }
474
+ const { info: after, ok } = await access.getSession(target.id, context?.signal)
475
+ if (!ok || !after) {
476
+ if (context?.signal?.aborted) {
477
+ results.push({
478
+ sessionID: target.id,
479
+ interrupt,
480
+ readBack: CANCEL_READ_BACK.notRead,
481
+ error: "aborted during read-back; outcome unknown",
482
+ })
483
+ aborted = true
484
+ break
485
+ }
486
+ results.push({
487
+ sessionID: target.id,
488
+ interrupt,
489
+ readBack: CANCEL_READ_BACK.failed,
490
+ error: "read-back failed",
491
+ })
492
+ continue
493
+ }
494
+ results.push({
495
+ sessionID: target.id,
496
+ interrupt,
497
+ readBack: CANCEL_READ_BACK.ok,
498
+ status: live.statusFor(after, target.id),
499
+ })
500
+ }
501
+
502
+ const remaining = Math.max(0, running.length - results.length)
503
+ const nextCursor =
504
+ remaining > 0 && results.length > 0
505
+ ? encodeCursor(targets[results.length - 1], {
506
+ tool: TOOL.cancelDescendants,
507
+ root: caller,
508
+ })
509
+ : undefined
510
+ const output: CancelDescendantsOutput = {
511
+ known: known.length,
512
+ considered: afterCursor.length,
513
+ running: running.length,
514
+ ...(beforeCursorRunning > 0 ? { beforeCursorRunning } : {}),
515
+ targets: results,
516
+ remaining,
517
+ aborted,
518
+ }
519
+ if (reason) output.reason = reason
520
+ if (nextCursor) output.cursor = nextCursor
521
+
522
+ const summary = summarizeCancelDescendants(results, remaining, nextCursor)
523
+ const abortText = aborted ? " Aborted before the batch completed." : ""
524
+ return finish(summary + reasonText + abortText, output)
525
+ },
526
+ })
527
+ }