opencode-subagent-tools 0.1.0 → 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/src/tools/list.ts CHANGED
@@ -1,61 +1,69 @@
1
- import type { ToolEditor } from "@opencode/plugin/promise/tool"
2
- import type { Access } from "../access"
3
- import { limitInteger, type Config } from "../config"
4
- import { encodeCursor, isAfterCursor, readCursor } from "../cursor"
5
- import type { Discovery } from "../discovery"
6
- import { toolError } from "../errors"
7
- import { age, ageSeconds, compactNumber, formatCost } from "../format"
8
- import { MAX_PROMPT_PREVIEW_LENGTH } from "../session"
9
- import type { SessionRow } from "../session-row"
1
+ import type { ToolEditor } from "@opencode/plugin/promise/tool";
2
+ import type { Access } from "../access";
10
3
  import {
11
- CHILD_STATUSES,
12
- isChildStatus,
13
- statusUsageMayLag,
14
- type ChildStatus,
15
- } from "../status"
16
- import { clip, isUnsafeControlCode } from "../text"
17
- import { TOKEN_USAGE_SCHEMA, tokensUsed, type TokenUsage } from "../tokens"
18
- import { readOptionalSessionID, readToolInput } from "./input"
19
- import { TOOL } from "./names"
20
- import { formatPropertyDescription, resolveToolOutputStrategy } from "./output"
4
+ BACKGROUND_JOB_SCHEMA,
5
+ backgroundJobLabel,
6
+ type BackgroundJobInfo,
7
+ } from "../background";
8
+ import { limitInteger, type Config } from "../config";
9
+ import { encodeCursor, isAfterCursor, readCursor } from "../cursor";
10
+ import type { Discovery } from "../discovery";
11
+ import { toolError } from "../errors";
12
+ import { age, ageSeconds, compactNumber, formatCost } from "../format";
13
+ import { MAX_PROMPT_PREVIEW_LENGTH } from "../session";
14
+ import type { SessionRow } from "../session-row";
15
+ import { RUN_STATUS, RUN_STATUSES, isRunStatus, type RunStatus } from "../status";
16
+ import { clip, isUnsafeControlCode } from "../text";
17
+ import { TOKEN_USAGE_SCHEMA, tokensUsed, type TokenUsage } from "../tokens";
18
+ import { readOptionalSessionID, readToolInput } from "./input";
19
+ import { TOOL } from "./names";
20
+ import { formatPropertyDescription, resolveToolOutputStrategy } from "./output";
21
21
 
22
- const STATUS_COLUMN_WIDTH = Math.max(...CHILD_STATUSES.map((status) => status.length))
23
- const DISCOVERY_WARNING = "discovery was incomplete; some subagents may be missing."
24
- const DISCOVERY_WARNING_TEXT = `\nWarning: ${DISCOVERY_WARNING}`
22
+ const RUN_STATUS_COLUMN_WIDTH = Math.max(...RUN_STATUSES.map((status) => status.length));
23
+ const DISCOVERY_WARNING = "discovery was incomplete; some subagents may be missing.";
24
+ const DISCOVERY_WARNING_TEXT = `\nWarning: ${DISCOVERY_WARNING}`;
25
25
 
26
26
  export interface ListRowUsage {
27
- costUSD?: number
28
- tokens?: TokenUsage
29
- tokensUsed?: number
27
+ costUSD?: number;
28
+ tokens?: TokenUsage;
29
+ tokensUsed?: number;
30
30
  }
31
31
 
32
32
  export interface ListRowOutput {
33
- id: string
34
- parentID?: string
35
- agent?: string
36
- title?: string
37
- titleTruncated?: boolean
38
- status: ChildStatus
39
- ageSeconds?: number
40
- launchedAt: number
41
- /** Usage is as of the last persisted step; running/unknown children may lag. */
42
- usageMayLag?: boolean
43
- usage?: ListRowUsage
33
+ id: string;
34
+ parentID?: string;
35
+ agent?: string;
36
+ title?: string;
37
+ titleTruncated?: boolean;
38
+ status: RunStatus;
39
+ /** The session's own execution or background work; descendants are excluded. */
40
+ active: boolean;
41
+ /** The session or any discovered descendant is active. */
42
+ subtreeActive: boolean;
43
+ activeDescendants?: boolean;
44
+ backgroundJob?: BackgroundJobInfo;
45
+ ageSeconds?: number;
46
+ launchedAt: number;
47
+ /** Usage is as of the last persisted step; active or unknown children may lag. */
48
+ usageMayLag?: boolean;
49
+ usage?: ListRowUsage;
44
50
  }
45
51
 
46
52
  export interface ListOutput {
47
- root: string
48
- statuses: ChildStatus[]
49
- discoveryComplete: boolean
50
- warning?: string
51
- known: number
52
- matching: number
53
- window: number
54
- remaining: number
55
- remainingPages: number
56
- cursor?: string
57
- counts: Record<ChildStatus, number>
58
- rows: ListRowOutput[]
53
+ root: string;
54
+ statuses: RunStatus[];
55
+ discoveryComplete: boolean;
56
+ warning?: string;
57
+ known: number;
58
+ activeCount: number;
59
+ subtreeActiveCount: number;
60
+ matching: number;
61
+ window: number;
62
+ remaining: number;
63
+ remainingPages: number;
64
+ cursor?: string;
65
+ counts: Record<RunStatus, number>;
66
+ rows: ListRowOutput[];
59
67
  }
60
68
 
61
69
  const LIST_ROW_USAGE_SCHEMA = {
@@ -66,7 +74,7 @@ const LIST_ROW_USAGE_SCHEMA = {
66
74
  tokensUsed: { type: "integer" },
67
75
  },
68
76
  additionalProperties: false,
69
- } as const
77
+ } as const;
70
78
 
71
79
  const LIST_OUTPUT_SCHEMA = {
72
80
  type: "object",
@@ -74,7 +82,7 @@ const LIST_OUTPUT_SCHEMA = {
74
82
  root: { type: "string" },
75
83
  statuses: {
76
84
  type: "array",
77
- items: { type: "string", enum: [...CHILD_STATUSES] },
85
+ items: { type: "string", enum: [...RUN_STATUSES] },
78
86
  },
79
87
  discoveryComplete: {
80
88
  type: "boolean",
@@ -84,7 +92,18 @@ const LIST_OUTPUT_SCHEMA = {
84
92
  warning: { type: "string" },
85
93
  known: {
86
94
  type: "integer",
87
- description: "All discovered sessions before the status filter and cursor.",
95
+ description:
96
+ "All discovered sessions before the status and activity filters and cursor.",
97
+ },
98
+ activeCount: {
99
+ type: "integer",
100
+ description:
101
+ "All discovered sessions with their own active execution or background job, before filters.",
102
+ },
103
+ subtreeActiveCount: {
104
+ type: "integer",
105
+ description:
106
+ "All discovered sessions that are active or have an active descendant, before filters.",
88
107
  },
89
108
  matching: {
90
109
  type: "integer",
@@ -108,11 +127,11 @@ const LIST_OUTPUT_SCHEMA = {
108
127
  counts: {
109
128
  type: "object",
110
129
  description:
111
- "Counts for all discovered sessions, before the status filter and cursor.",
130
+ "Counts for all discovered sessions, before the status and activity filters and cursor.",
112
131
  properties: Object.fromEntries(
113
- CHILD_STATUSES.map((status) => [status, { type: "integer" }]),
132
+ RUN_STATUSES.map((status) => [status, { type: "integer" }]),
114
133
  ),
115
- required: [...CHILD_STATUSES],
134
+ required: [...RUN_STATUSES],
116
135
  additionalProperties: false,
117
136
  },
118
137
  rows: {
@@ -125,16 +144,30 @@ const LIST_OUTPUT_SCHEMA = {
125
144
  agent: { type: "string" },
126
145
  title: { type: "string" },
127
146
  titleTruncated: { type: "boolean" },
128
- status: { type: "string", enum: [...CHILD_STATUSES] },
147
+ status: { type: "string", enum: [...RUN_STATUSES] },
148
+ active: {
149
+ type: "boolean",
150
+ description:
151
+ "True when the session itself is running, unknown, or owns a background job.",
152
+ },
153
+ subtreeActive: {
154
+ type: "boolean",
155
+ description: "True when the session or any discovered descendant is active.",
156
+ },
157
+ activeDescendants: {
158
+ type: "boolean",
159
+ description: "True only when a discovered descendant is active.",
160
+ },
161
+ backgroundJob: BACKGROUND_JOB_SCHEMA,
129
162
  ageSeconds: { type: "integer" },
130
163
  launchedAt: { type: "number" },
131
164
  usageMayLag: {
132
165
  type: "boolean",
133
- description: "True when the session is running or unknown; usage may lag.",
166
+ description: "True when the session is active or unknown; usage may lag.",
134
167
  },
135
168
  usage: LIST_ROW_USAGE_SCHEMA,
136
169
  },
137
- required: ["id", "status", "launchedAt"],
170
+ required: ["id", "status", "active", "subtreeActive", "launchedAt"],
138
171
  additionalProperties: false,
139
172
  },
140
173
  },
@@ -144,6 +177,8 @@ const LIST_OUTPUT_SCHEMA = {
144
177
  "statuses",
145
178
  "discoveryComplete",
146
179
  "known",
180
+ "activeCount",
181
+ "subtreeActiveCount",
147
182
  "matching",
148
183
  "window",
149
184
  "remaining",
@@ -152,40 +187,63 @@ const LIST_OUTPUT_SCHEMA = {
152
187
  "rows",
153
188
  ],
154
189
  additionalProperties: false,
155
- } as const
190
+ } as const;
156
191
 
157
192
  const requestedStatuses = (
158
193
  value: unknown,
159
- ): { statuses: Set<ChildStatus>; invalid: string[]; error?: string } => {
194
+ ): { statuses: Set<RunStatus>; invalid: string[]; error?: string } => {
160
195
  if (value === undefined) {
161
- return { statuses: new Set(CHILD_STATUSES), invalid: [] }
196
+ return { statuses: new Set(RUN_STATUSES), invalid: [] };
162
197
  }
163
198
  if (!Array.isArray(value)) {
164
199
  return {
165
- statuses: new Set<ChildStatus>(),
200
+ statuses: new Set<RunStatus>(),
166
201
  invalid: [],
167
202
  error: "statuses must be an array of statuses; omit it to include all.",
168
- }
203
+ };
169
204
  }
170
- const valid: ChildStatus[] = []
171
- const invalid: string[] = []
205
+ const valid: RunStatus[] = [];
206
+ const invalid: string[] = [];
172
207
  for (const raw of value) {
173
208
  if (typeof raw !== "string") {
174
- invalid.push(String(raw))
175
- continue
209
+ invalid.push(String(raw));
210
+ continue;
176
211
  }
177
- const status = raw.trim().toLowerCase()
178
- if (isChildStatus(status)) valid.push(status)
179
- else if (status.length > 0) invalid.push(raw)
212
+ const status = raw.trim().toLowerCase();
213
+ if (isRunStatus(status)) valid.push(status);
214
+ else if (status.length > 0) invalid.push(raw);
180
215
  }
181
216
  return {
182
217
  statuses: new Set(valid),
183
218
  invalid,
184
- }
185
- }
219
+ };
220
+ };
186
221
 
187
- const statusesLabel = (statuses: Set<ChildStatus>): string =>
188
- statuses.size === CHILD_STATUSES.length ? "all" : [...statuses].join(", ")
222
+ const statusesLabel = (statuses: Set<RunStatus>): string =>
223
+ statuses.size === RUN_STATUSES.length ? "all" : [...statuses].join(", ");
224
+
225
+ const readOptionalBoolean = (
226
+ value: unknown,
227
+ field: string,
228
+ ): { value?: boolean; error?: string } => {
229
+ if (value === undefined) return {};
230
+ if (typeof value === "boolean") return { value };
231
+ return { error: `${field} must be a boolean; omit it to include all rows.` };
232
+ };
233
+
234
+ const filterDescription = (
235
+ statuses: Set<RunStatus>,
236
+ active: boolean | undefined,
237
+ subtreeActive: boolean | undefined,
238
+ ): string => {
239
+ const parts: string[] = [];
240
+ if (statuses.size !== RUN_STATUSES.length) {
241
+ parts.push(`statuses: ${statusesLabel(statuses)}`);
242
+ }
243
+ if (active !== undefined) parts.push(`active: ${active}`);
244
+ if (subtreeActive !== undefined) parts.push(`subtreeActive: ${subtreeActive}`);
245
+ return parts.length > 0 ? parts.join("; ") : "the current filters";
246
+ };
189
247
 
190
248
  const escapeText = (value: string): string =>
191
249
  Array.from(
@@ -195,14 +253,21 @@ const escapeText = (value: string): string =>
195
253
  .replace(/[\r\n\t]/g, " "),
196
254
  )
197
255
  .map((char) => (isUnsafeControlCode(char.codePointAt(0) ?? 0) ? "?" : char))
198
- .join("")
256
+ .join("");
199
257
 
200
258
  const rowText = (row: SessionRow): string => {
201
- const usageMayLag = statusUsageMayLag(row.status)
202
- const title = clip(row.title, MAX_PROMPT_PREVIEW_LENGTH)
259
+ const usageMayLag = row.active || row.status === RUN_STATUS.unknown;
260
+ const title = clip(row.title, MAX_PROMPT_PREVIEW_LENGTH);
261
+ const activity = row.active ? "active" : row.subtreeActive ? "subtree" : "";
262
+ const background = row.backgroundJob
263
+ ? `background=${backgroundJobLabel(row.backgroundJob)}`
264
+ : "";
203
265
  return [
204
266
  escapeText(row.id),
205
- row.status.padEnd(STATUS_COLUMN_WIDTH),
267
+ row.status.padEnd(RUN_STATUS_COLUMN_WIDTH),
268
+ activity,
269
+ background,
270
+ row.activeDescendants ? "descendants=active" : "",
206
271
  `agent=${escapeText(row.agent ?? "?")}`,
207
272
  `age=${row.launchedAt > 0 ? age(row.launchedAt) : "?"}`,
208
273
  row.cost !== undefined ? `cost=${formatCost(row.cost)}` : "",
@@ -212,51 +277,56 @@ const rowText = (row: SessionRow): string => {
212
277
  title ? `title="${escapeText(title)}"` : "",
213
278
  ]
214
279
  .filter(Boolean)
215
- .join(" ")
216
- }
280
+ .join(" ");
281
+ };
217
282
 
218
- const countStatuses = (rows: readonly SessionRow[]): Record<ChildStatus, number> => {
219
- const counts = Object.fromEntries(
220
- CHILD_STATUSES.map((status) => [status, 0]),
221
- ) as Record<ChildStatus, number>
222
- for (const row of rows) counts[row.status]++
223
- return counts
224
- }
283
+ const countStatuses = (rows: readonly SessionRow[]): Record<RunStatus, number> => {
284
+ const counts = Object.fromEntries(RUN_STATUSES.map((status) => [status, 0])) as Record<
285
+ RunStatus,
286
+ number
287
+ >;
288
+ for (const row of rows) counts[row.status]++;
289
+ return counts;
290
+ };
225
291
 
226
292
  const rowOutput = (row: SessionRow): ListRowOutput => {
227
293
  const output: ListRowOutput = {
228
294
  id: row.id,
229
295
  status: row.status,
296
+ active: row.active,
297
+ subtreeActive: row.subtreeActive,
230
298
  launchedAt: row.launchedAt,
231
- }
232
- if (row.parentID !== undefined) output.parentID = row.parentID
233
- if (row.agent !== undefined) output.agent = row.agent
234
- if (row.title !== undefined) output.title = row.title
235
- if (row.titleTruncated) output.titleTruncated = true
236
- if (row.launchedAt > 0) output.ageSeconds = ageSeconds(row.launchedAt)
237
- if (statusUsageMayLag(row.status)) {
238
- output.usageMayLag = true
299
+ };
300
+ if (row.parentID !== undefined) output.parentID = row.parentID;
301
+ if (row.agent !== undefined) output.agent = row.agent;
302
+ if (row.title !== undefined) output.title = row.title;
303
+ if (row.titleTruncated) output.titleTruncated = true;
304
+ if (row.activeDescendants) output.activeDescendants = true;
305
+ if (row.backgroundJob) output.backgroundJob = row.backgroundJob;
306
+ if (row.launchedAt > 0) output.ageSeconds = ageSeconds(row.launchedAt);
307
+ if (row.active || row.status === RUN_STATUS.unknown) {
308
+ output.usageMayLag = true;
239
309
  }
240
310
  if (row.cost !== undefined || row.tokens) {
241
- const usage: ListRowUsage = {}
242
- if (row.cost !== undefined) usage.costUSD = row.cost
311
+ const usage: ListRowUsage = {};
312
+ if (row.cost !== undefined) usage.costUSD = row.cost;
243
313
  if (row.tokens) {
244
- usage.tokens = row.tokens
245
- usage.tokensUsed = tokensUsed(row.tokens)
314
+ usage.tokens = row.tokens;
315
+ usage.tokensUsed = tokensUsed(row.tokens);
246
316
  }
247
- output.usage = usage
317
+ output.usage = usage;
248
318
  }
249
- return output
250
- }
319
+ return output;
320
+ };
251
321
 
252
322
  interface PaginationSummary {
253
- shown: number
254
- afterCursor: number
255
- allMatches: number
256
- limit: number
257
- remainingPages: number
258
- nextCursor?: string
259
- hasCursor: boolean
323
+ shown: number;
324
+ afterCursor: number;
325
+ allMatches: number;
326
+ limit: number;
327
+ remainingPages: number;
328
+ nextCursor?: string;
329
+ hasCursor: boolean;
260
330
  }
261
331
 
262
332
  const paginationSummary = ({
@@ -271,39 +341,40 @@ const paginationSummary = ({
271
341
  const pageLabel =
272
342
  remainingPages === 0
273
343
  ? "last page"
274
- : `${remainingPages} ${remainingPages === 1 ? "page" : "pages"} remaining`
344
+ : `${remainingPages} ${remainingPages === 1 ? "page" : "pages"} remaining`;
275
345
  if (nextCursor) {
276
346
  if (hasCursor) {
277
- return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}. Use cursor ${nextCursor} to continue.`
347
+ return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}. Use cursor ${nextCursor} to continue.`;
278
348
  }
279
- return `\nShowing ${shown} of ${allMatches} matches (limit ${limit}); ${pageLabel}. Use cursor ${nextCursor} to continue.`
349
+ return `\nShowing ${shown} of ${allMatches} matches (limit ${limit}); ${pageLabel}. Use cursor ${nextCursor} to continue.`;
280
350
  }
281
351
  if (hasCursor) {
282
- return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}.`
352
+ return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}.`;
283
353
  }
284
- return ""
285
- }
354
+ return "";
355
+ };
286
356
 
287
357
  export interface ListDeps {
288
- config: Config
289
- access: Access
290
- discovery: Discovery
358
+ config: Config;
359
+ access: Access;
360
+ discovery: Discovery;
291
361
  }
292
362
 
293
363
  export const registerListTool = (
294
364
  editor: ToolEditor,
295
365
  { config, access, discovery }: ListDeps,
296
366
  ) => {
297
- const { allowedOutputFormats, limits } = config
298
- const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.list)
367
+ const { allowedOutputFormats, limits } = config;
368
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.list);
299
369
 
300
370
  editor.add({
301
371
  name: TOOL.list,
302
372
  description:
303
- "List subagent sessions from the server's session tree, newest launch first, with observed status. " +
373
+ "List subagent sessions from the server's session tree, newest launch first, with observed status and activity. " +
304
374
  "Defaults to the caller's subtree; pass parentID for any subtree. " +
305
- "By default all statuses are included; pass statuses to filter, and use limit/cursor to page through large sets. " +
306
- "Rows include status, age, cost, and cumulative token usage when available. " +
375
+ "`status` describes the last or current execution; use `active` and `subtreeActive` to find work that is still in progress. " +
376
+ "By default all statuses are included; pass statuses, active, or subtreeActive to filter, and use limit/cursor to page through large sets. " +
377
+ "Rows include status, activity, background jobs, age, cost, and cumulative token usage when available. " +
307
378
  "Discovery is limited, so results can be incomplete; a warning is included when that is possible.",
308
379
  input: {
309
380
  type: "object",
@@ -316,10 +387,20 @@ export const registerListTool = (
316
387
  statuses: {
317
388
  type: "array",
318
389
  minItems: 1,
319
- maxItems: CHILD_STATUSES.length,
320
- items: { type: "string", enum: [...CHILD_STATUSES] },
390
+ maxItems: RUN_STATUSES.length,
391
+ items: { type: "string", enum: [...RUN_STATUSES] },
392
+ description:
393
+ "Execution statuses to include. `finished` means the last execution succeeded, not that the delegated task is complete. Omit to include all statuses; an empty array is rejected.",
394
+ },
395
+ active: {
396
+ type: "boolean",
397
+ description:
398
+ "Filter on the session's own activity: running, unknown, or owning a background job. Omit to include both active and inactive rows.",
399
+ },
400
+ subtreeActive: {
401
+ type: "boolean",
321
402
  description:
322
- "Statuses to include. Omit to include all statuses; pass one or more to filter. An empty array is rejected.",
403
+ "Filter on the session or any discovered descendant. Omit to include both active and inactive subtrees.",
323
404
  },
324
405
  ...outputStrategy.formatProperty(
325
406
  formatPropertyDescription(outputStrategy, "the human-readable table"),
@@ -340,73 +421,96 @@ export const registerListTool = (
340
421
  output: outputStrategy.schema(LIST_OUTPUT_SCHEMA),
341
422
  options: { namespace: config.namespace },
342
423
  execute: async (rawInput, context) => {
343
- const { input, format } = readToolInput(rawInput, outputStrategy)
344
- const requested = readOptionalSessionID(input?.parentID)
424
+ const { input, format } = readToolInput(rawInput, outputStrategy);
425
+ const requested = readOptionalSessionID(input?.parentID);
345
426
  if (input?.parentID !== undefined && requested === undefined) {
346
- return toolError("parentID is invalid; use the exact ID reported by the server.")
427
+ return toolError("parentID is invalid; use the exact ID reported by the server.");
347
428
  }
348
- const caller = context?.sessionID
349
- const statusFilter = requestedStatuses(input?.statuses)
429
+ const caller = context?.sessionID;
430
+ const statusFilter = requestedStatuses(input?.statuses);
350
431
  if (statusFilter.error) {
351
- return toolError(statusFilter.error)
432
+ return toolError(statusFilter.error);
352
433
  }
353
434
  if (statusFilter.invalid.length > 0) {
354
- const shown = statusFilter.invalid.slice(0, 5).join(", ")
435
+ const shown = statusFilter.invalid.slice(0, 5).join(", ");
355
436
  const more =
356
437
  statusFilter.invalid.length > 5
357
438
  ? `, and ${statusFilter.invalid.length - 5} more`
358
- : ""
439
+ : "";
359
440
  return toolError(
360
- `Unknown status(es): ${shown}${more}. Use one or more of: ${CHILD_STATUSES.join(", ")}.`,
361
- )
441
+ `Unknown status(es): ${shown}${more}. Use one or more of: ${RUN_STATUSES.join(", ")}.`,
442
+ );
362
443
  }
363
- const statuses = statusFilter.statuses
444
+ const statuses = statusFilter.statuses;
364
445
  if (statuses.size === 0) {
365
446
  return toolError(
366
- `statuses must contain at least one status. Omit statuses to include all, or pass one or more of: ${CHILD_STATUSES.join(", ")}.`,
367
- )
447
+ `statuses must contain at least one status. Omit statuses to include all, or pass one or more of: ${RUN_STATUSES.join(", ")}.`,
448
+ );
368
449
  }
369
- const limit = limitInteger(input?.limit, limits.maxListRows, 1, limits.maxListRows)
450
+ const activeField = readOptionalBoolean(input?.active, "active");
451
+ if (activeField.error) return toolError(activeField.error);
452
+ const subtreeActiveField = readOptionalBoolean(
453
+ input?.subtreeActive,
454
+ "subtreeActive",
455
+ );
456
+ if (subtreeActiveField.error) return toolError(subtreeActiveField.error);
457
+ const activeFilter = activeField.value;
458
+ const subtreeActiveFilter = subtreeActiveField.value;
459
+ const limit = limitInteger(input?.limit, limits.maxListRows, 1, limits.maxListRows);
370
460
 
371
461
  if (requested && requested !== caller) {
372
- const parent = await access.getSession(requested, context?.signal)
462
+ const parent = await access.getSession(requested, context?.signal);
373
463
  if (context?.signal?.aborted) {
374
- return toolError("Aborted before the parent could be read.")
464
+ return toolError("Aborted before the parent could be read.");
375
465
  }
376
466
  if (!parent.ok || !parent.info) {
377
- return toolError(`Parent session ${requested} could not be read.`)
467
+ return toolError(`Parent session ${requested} could not be read.`);
378
468
  }
379
469
  }
380
470
 
381
- const root = requested ?? caller
471
+ const root = requested ?? caller;
382
472
  if (!root) {
383
473
  return toolError(
384
474
  "Refusing: the calling session is unknown; pass parentID or call from a session.",
385
- )
475
+ );
386
476
  }
387
- const filterKey = [...statuses].toSorted().join(",")
477
+ const filterKey = [
478
+ [...statuses].toSorted().join(","),
479
+ activeFilter === undefined ? "" : `active=${activeFilter}`,
480
+ subtreeActiveFilter === undefined ? "" : `subtreeActive=${subtreeActiveFilter}`,
481
+ ]
482
+ .filter(Boolean)
483
+ .join("|");
388
484
  const cursorResult = readCursor(input?.cursor, {
389
485
  tool: TOOL.list,
390
486
  root,
391
487
  filter: filterKey,
392
- })
488
+ });
393
489
  if (cursorResult.error) {
394
- return toolError(cursorResult.error)
490
+ return toolError(cursorResult.error);
395
491
  }
396
- const cursor = cursorResult.cursor
492
+ const cursor = cursorResult.cursor;
397
493
  if (context?.signal?.aborted) {
398
- return toolError("Aborted before discovery.")
494
+ return toolError("Aborted before discovery.");
399
495
  }
400
496
 
401
- const found = await discovery.discoverRows(root, context?.signal)
497
+ const found = await discovery.discoverRows(root, context?.signal);
402
498
  if (context?.signal?.aborted) {
403
- return toolError("Aborted during discovery.")
499
+ return toolError("Aborted during discovery.");
404
500
  }
405
- const warning = found.complete ? "" : DISCOVERY_WARNING_TEXT
406
- const allMatches = found.rows.filter((row) => statuses.has(row.status))
501
+ const warning = found.complete ? "" : DISCOVERY_WARNING_TEXT;
502
+ const allMatches = found.rows.filter(
503
+ (row) =>
504
+ statuses.has(row.status) &&
505
+ (activeFilter === undefined || row.active === activeFilter) &&
506
+ (subtreeActiveFilter === undefined ||
507
+ row.subtreeActive === subtreeActiveFilter),
508
+ );
509
+ const activeCount = found.rows.filter((row) => row.active).length;
510
+ const subtreeActiveCount = found.rows.filter((row) => row.subtreeActive).length;
407
511
  const afterCursor = cursor
408
512
  ? allMatches.filter((row) => isAfterCursor(row, cursor))
409
- : allMatches
513
+ : allMatches;
410
514
 
411
515
  const outputFor = (
412
516
  page: readonly SessionRow[],
@@ -421,36 +525,38 @@ export const registerListTool = (
421
525
  statuses: [...statuses],
422
526
  discoveryComplete: found.complete,
423
527
  known: found.rows.length,
528
+ activeCount,
529
+ subtreeActiveCount,
424
530
  matching,
425
531
  window,
426
532
  remaining,
427
533
  remainingPages,
428
534
  counts: countStatuses(found.rows),
429
535
  rows: page.map(rowOutput),
430
- }
536
+ };
431
537
  if (!found.complete) {
432
- output.warning = DISCOVERY_WARNING
538
+ output.warning = DISCOVERY_WARNING;
433
539
  }
434
- if (nextCursor) output.cursor = nextCursor
435
- return output
436
- }
540
+ if (nextCursor) output.cursor = nextCursor;
541
+ return output;
542
+ };
437
543
  const respond = (content: string, output: ListOutput) =>
438
- outputStrategy.respond(content, output, format)
544
+ outputStrategy.respond(content, output, format);
439
545
 
440
546
  if (found.rows.length === 0) {
441
547
  return respond(
442
548
  `No subagents discovered for ${root}.` + warning,
443
549
  outputFor([], 0, 0, 0, 0),
444
- )
550
+ );
445
551
  }
446
552
 
447
- const label = statusesLabel(statuses)
448
553
  if (allMatches.length === 0) {
554
+ const filters = filterDescription(statuses, activeFilter, subtreeActiveFilter);
449
555
  return respond(
450
- `${found.rows.length} known subagent(s) for ${root}, none match statuses: ${label}.` +
556
+ `${found.rows.length} known subagent(s) for ${root}, none match ${filters}.` +
451
557
  warning,
452
558
  outputFor([], 0, 0, 0, 0),
453
- )
559
+ );
454
560
  }
455
561
 
456
562
  if (afterCursor.length === 0) {
@@ -458,10 +564,10 @@ export const registerListTool = (
458
564
  `Cursor is past the end: ${found.rows.length} known subagent(s) for ${root}.` +
459
565
  warning,
460
566
  outputFor([], allMatches.length, 0, 0, 0),
461
- )
567
+ );
462
568
  }
463
569
 
464
- const shown = afterCursor.slice(0, limit)
570
+ const shown = afterCursor.slice(0, limit);
465
571
  const nextCursor =
466
572
  afterCursor.length > shown.length
467
573
  ? encodeCursor(shown[shown.length - 1], {
@@ -469,10 +575,10 @@ export const registerListTool = (
469
575
  root,
470
576
  filter: filterKey,
471
577
  })
472
- : undefined
473
- const remaining = Math.max(0, afterCursor.length - shown.length)
474
- const remainingPages = Math.ceil(remaining / limit)
475
- const beforeCursor = allMatches.length - afterCursor.length
578
+ : undefined;
579
+ const remaining = Math.max(0, afterCursor.length - shown.length);
580
+ const remainingPages = Math.ceil(remaining / limit);
581
+ const beforeCursor = allMatches.length - afterCursor.length;
476
582
  const summary = paginationSummary({
477
583
  shown: shown.length,
478
584
  afterCursor: afterCursor.length,
@@ -481,11 +587,11 @@ export const registerListTool = (
481
587
  remainingPages,
482
588
  nextCursor,
483
589
  hasCursor: cursor !== undefined,
484
- })
590
+ });
485
591
  const beforeCursorNote =
486
592
  cursor && beforeCursor > 0
487
593
  ? `\nNote: ${beforeCursor} matching row(s) are before this cursor window (previous pages or new children); re-run without a cursor to include new children.`
488
- : ""
594
+ : "";
489
595
  return respond(
490
596
  shown.map(rowText).join("\n") + summary + beforeCursorNote + warning,
491
597
  outputFor(
@@ -496,7 +602,7 @@ export const registerListTool = (
496
602
  remainingPages,
497
603
  nextCursor,
498
604
  ),
499
- )
605
+ );
500
606
  },
501
- })
502
- }
607
+ });
608
+ };