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