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.
- package/CHANGELOG.md +27 -0
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/SECURITY.md +36 -0
- package/SKILL.md +305 -0
- package/docs/configuration.md +238 -0
- package/docs/development.md +78 -0
- package/docs/installation.md +137 -0
- package/docs/limitations.md +120 -0
- package/docs/reference.md +347 -0
- package/docs/security-model.md +79 -0
- package/package.json +74 -4
- package/src/access.ts +236 -0
- package/src/config.ts +143 -0
- package/src/cursor.ts +112 -0
- package/src/discovery.ts +151 -0
- package/src/errors.ts +18 -0
- package/src/events.ts +190 -0
- package/src/format.ts +34 -0
- package/src/index.ts +116 -0
- package/src/interrupt.ts +20 -0
- package/src/live-state.ts +90 -0
- package/src/messages.ts +196 -0
- package/src/permissions.ts +62 -0
- package/src/session-row.ts +55 -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 +527 -0
- package/src/tools/cancel.ts +205 -0
- package/src/tools/index.ts +39 -0
- package/src/tools/input.ts +73 -0
- package/src/tools/list.ts +502 -0
- package/src/tools/names.ts +11 -0
- package/src/tools/output.ts +169 -0
- package/src/tools/send.ts +335 -0
- package/src/tools/usage.ts +396 -0
|
@@ -0,0 +1,502 @@
|
|
|
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"
|
|
10
|
+
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"
|
|
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}`
|
|
25
|
+
|
|
26
|
+
export interface ListRowUsage {
|
|
27
|
+
costUSD?: number
|
|
28
|
+
tokens?: TokenUsage
|
|
29
|
+
tokensUsed?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
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
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
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[]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const LIST_ROW_USAGE_SCHEMA = {
|
|
62
|
+
type: "object",
|
|
63
|
+
properties: {
|
|
64
|
+
costUSD: { type: "number" },
|
|
65
|
+
tokens: TOKEN_USAGE_SCHEMA,
|
|
66
|
+
tokensUsed: { type: "integer" },
|
|
67
|
+
},
|
|
68
|
+
additionalProperties: false,
|
|
69
|
+
} as const
|
|
70
|
+
|
|
71
|
+
const LIST_OUTPUT_SCHEMA = {
|
|
72
|
+
type: "object",
|
|
73
|
+
properties: {
|
|
74
|
+
root: { type: "string" },
|
|
75
|
+
statuses: {
|
|
76
|
+
type: "array",
|
|
77
|
+
items: { type: "string", enum: [...CHILD_STATUSES] },
|
|
78
|
+
},
|
|
79
|
+
discoveryComplete: {
|
|
80
|
+
type: "boolean",
|
|
81
|
+
description:
|
|
82
|
+
"Whether discovery walked the whole subtree, not whether all rows fit on this page.",
|
|
83
|
+
},
|
|
84
|
+
warning: { type: "string" },
|
|
85
|
+
known: {
|
|
86
|
+
type: "integer",
|
|
87
|
+
description: "All discovered sessions before the status filter and cursor.",
|
|
88
|
+
},
|
|
89
|
+
matching: {
|
|
90
|
+
type: "integer",
|
|
91
|
+
description:
|
|
92
|
+
"Matching sessions in the current discovery snapshot, before the cursor.",
|
|
93
|
+
},
|
|
94
|
+
window: {
|
|
95
|
+
type: "integer",
|
|
96
|
+
description:
|
|
97
|
+
"Matching sessions after the cursor; equals matching on the first page.",
|
|
98
|
+
},
|
|
99
|
+
remaining: {
|
|
100
|
+
type: "integer",
|
|
101
|
+
description: "Matching sessions in the window not returned on this page.",
|
|
102
|
+
},
|
|
103
|
+
remainingPages: {
|
|
104
|
+
type: "integer",
|
|
105
|
+
description: "Pages left in this cursor walk.",
|
|
106
|
+
},
|
|
107
|
+
cursor: { type: "string" },
|
|
108
|
+
counts: {
|
|
109
|
+
type: "object",
|
|
110
|
+
description:
|
|
111
|
+
"Counts for all discovered sessions, before the status filter and cursor.",
|
|
112
|
+
properties: Object.fromEntries(
|
|
113
|
+
CHILD_STATUSES.map((status) => [status, { type: "integer" }]),
|
|
114
|
+
),
|
|
115
|
+
required: [...CHILD_STATUSES],
|
|
116
|
+
additionalProperties: false,
|
|
117
|
+
},
|
|
118
|
+
rows: {
|
|
119
|
+
type: "array",
|
|
120
|
+
items: {
|
|
121
|
+
type: "object",
|
|
122
|
+
properties: {
|
|
123
|
+
id: { type: "string" },
|
|
124
|
+
parentID: { type: "string" },
|
|
125
|
+
agent: { type: "string" },
|
|
126
|
+
title: { type: "string" },
|
|
127
|
+
titleTruncated: { type: "boolean" },
|
|
128
|
+
status: { type: "string", enum: [...CHILD_STATUSES] },
|
|
129
|
+
ageSeconds: { type: "integer" },
|
|
130
|
+
launchedAt: { type: "number" },
|
|
131
|
+
usageMayLag: {
|
|
132
|
+
type: "boolean",
|
|
133
|
+
description: "True when the session is running or unknown; usage may lag.",
|
|
134
|
+
},
|
|
135
|
+
usage: LIST_ROW_USAGE_SCHEMA,
|
|
136
|
+
},
|
|
137
|
+
required: ["id", "status", "launchedAt"],
|
|
138
|
+
additionalProperties: false,
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
required: [
|
|
143
|
+
"root",
|
|
144
|
+
"statuses",
|
|
145
|
+
"discoveryComplete",
|
|
146
|
+
"known",
|
|
147
|
+
"matching",
|
|
148
|
+
"window",
|
|
149
|
+
"remaining",
|
|
150
|
+
"remainingPages",
|
|
151
|
+
"counts",
|
|
152
|
+
"rows",
|
|
153
|
+
],
|
|
154
|
+
additionalProperties: false,
|
|
155
|
+
} as const
|
|
156
|
+
|
|
157
|
+
const requestedStatuses = (
|
|
158
|
+
value: unknown,
|
|
159
|
+
): { statuses: Set<ChildStatus>; invalid: string[]; error?: string } => {
|
|
160
|
+
if (value === undefined) {
|
|
161
|
+
return { statuses: new Set(CHILD_STATUSES), invalid: [] }
|
|
162
|
+
}
|
|
163
|
+
if (!Array.isArray(value)) {
|
|
164
|
+
return {
|
|
165
|
+
statuses: new Set<ChildStatus>(),
|
|
166
|
+
invalid: [],
|
|
167
|
+
error: "statuses must be an array of statuses; omit it to include all.",
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const valid: ChildStatus[] = []
|
|
171
|
+
const invalid: string[] = []
|
|
172
|
+
for (const raw of value) {
|
|
173
|
+
if (typeof raw !== "string") {
|
|
174
|
+
invalid.push(String(raw))
|
|
175
|
+
continue
|
|
176
|
+
}
|
|
177
|
+
const status = raw.trim().toLowerCase()
|
|
178
|
+
if (isChildStatus(status)) valid.push(status)
|
|
179
|
+
else if (status.length > 0) invalid.push(raw)
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
statuses: new Set(valid),
|
|
183
|
+
invalid,
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const statusesLabel = (statuses: Set<ChildStatus>): string =>
|
|
188
|
+
statuses.size === CHILD_STATUSES.length ? "all" : [...statuses].join(", ")
|
|
189
|
+
|
|
190
|
+
const escapeText = (value: string): string =>
|
|
191
|
+
Array.from(
|
|
192
|
+
value
|
|
193
|
+
.replace(/\\/g, "\\\\")
|
|
194
|
+
.replace(/"/g, '\\"')
|
|
195
|
+
.replace(/[\r\n\t]/g, " "),
|
|
196
|
+
)
|
|
197
|
+
.map((char) => (isUnsafeControlCode(char.codePointAt(0) ?? 0) ? "?" : char))
|
|
198
|
+
.join("")
|
|
199
|
+
|
|
200
|
+
const rowText = (row: SessionRow): string => {
|
|
201
|
+
const usageMayLag = statusUsageMayLag(row.status)
|
|
202
|
+
const title = clip(row.title, MAX_PROMPT_PREVIEW_LENGTH)
|
|
203
|
+
return [
|
|
204
|
+
escapeText(row.id),
|
|
205
|
+
row.status.padEnd(STATUS_COLUMN_WIDTH),
|
|
206
|
+
`agent=${escapeText(row.agent ?? "?")}`,
|
|
207
|
+
`age=${row.launchedAt > 0 ? age(row.launchedAt) : "?"}`,
|
|
208
|
+
row.cost !== undefined ? `cost=${formatCost(row.cost)}` : "",
|
|
209
|
+
row.tokens ? `used=${compactNumber(tokensUsed(row.tokens))}` : "",
|
|
210
|
+
usageMayLag ? "usage=lagging" : "",
|
|
211
|
+
row.parentID ? `parent=${escapeText(row.parentID)}` : "parent=?",
|
|
212
|
+
title ? `title="${escapeText(title)}"` : "",
|
|
213
|
+
]
|
|
214
|
+
.filter(Boolean)
|
|
215
|
+
.join(" ")
|
|
216
|
+
}
|
|
217
|
+
|
|
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
|
+
}
|
|
225
|
+
|
|
226
|
+
const rowOutput = (row: SessionRow): ListRowOutput => {
|
|
227
|
+
const output: ListRowOutput = {
|
|
228
|
+
id: row.id,
|
|
229
|
+
status: row.status,
|
|
230
|
+
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
|
|
239
|
+
}
|
|
240
|
+
if (row.cost !== undefined || row.tokens) {
|
|
241
|
+
const usage: ListRowUsage = {}
|
|
242
|
+
if (row.cost !== undefined) usage.costUSD = row.cost
|
|
243
|
+
if (row.tokens) {
|
|
244
|
+
usage.tokens = row.tokens
|
|
245
|
+
usage.tokensUsed = tokensUsed(row.tokens)
|
|
246
|
+
}
|
|
247
|
+
output.usage = usage
|
|
248
|
+
}
|
|
249
|
+
return output
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
interface PaginationSummary {
|
|
253
|
+
shown: number
|
|
254
|
+
afterCursor: number
|
|
255
|
+
allMatches: number
|
|
256
|
+
limit: number
|
|
257
|
+
remainingPages: number
|
|
258
|
+
nextCursor?: string
|
|
259
|
+
hasCursor: boolean
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const paginationSummary = ({
|
|
263
|
+
shown,
|
|
264
|
+
afterCursor,
|
|
265
|
+
allMatches,
|
|
266
|
+
limit,
|
|
267
|
+
remainingPages,
|
|
268
|
+
nextCursor,
|
|
269
|
+
hasCursor,
|
|
270
|
+
}: PaginationSummary): string => {
|
|
271
|
+
const pageLabel =
|
|
272
|
+
remainingPages === 0
|
|
273
|
+
? "last page"
|
|
274
|
+
: `${remainingPages} ${remainingPages === 1 ? "page" : "pages"} remaining`
|
|
275
|
+
if (nextCursor) {
|
|
276
|
+
if (hasCursor) {
|
|
277
|
+
return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}. Use cursor ${nextCursor} to continue.`
|
|
278
|
+
}
|
|
279
|
+
return `\nShowing ${shown} of ${allMatches} matches (limit ${limit}); ${pageLabel}. Use cursor ${nextCursor} to continue.`
|
|
280
|
+
}
|
|
281
|
+
if (hasCursor) {
|
|
282
|
+
return `\nShowing ${shown} of ${afterCursor} in this cursor window (${allMatches} matching total); ${pageLabel}.`
|
|
283
|
+
}
|
|
284
|
+
return ""
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export interface ListDeps {
|
|
288
|
+
config: Config
|
|
289
|
+
access: Access
|
|
290
|
+
discovery: Discovery
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export const registerListTool = (
|
|
294
|
+
editor: ToolEditor,
|
|
295
|
+
{ config, access, discovery }: ListDeps,
|
|
296
|
+
) => {
|
|
297
|
+
const { allowedOutputFormats, limits } = config
|
|
298
|
+
const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.list)
|
|
299
|
+
|
|
300
|
+
editor.add({
|
|
301
|
+
name: TOOL.list,
|
|
302
|
+
description:
|
|
303
|
+
"List subagent sessions from the server's session tree, newest launch first, with observed status. " +
|
|
304
|
+
"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. " +
|
|
307
|
+
"Discovery is limited, so results can be incomplete; a warning is included when that is possible.",
|
|
308
|
+
input: {
|
|
309
|
+
type: "object",
|
|
310
|
+
properties: {
|
|
311
|
+
parentID: {
|
|
312
|
+
type: "string",
|
|
313
|
+
description:
|
|
314
|
+
"Parent session ID. Defaults to the calling session; any parent is accepted.",
|
|
315
|
+
},
|
|
316
|
+
statuses: {
|
|
317
|
+
type: "array",
|
|
318
|
+
minItems: 1,
|
|
319
|
+
maxItems: CHILD_STATUSES.length,
|
|
320
|
+
items: { type: "string", enum: [...CHILD_STATUSES] },
|
|
321
|
+
description:
|
|
322
|
+
"Statuses to include. Omit to include all statuses; pass one or more to filter. An empty array is rejected.",
|
|
323
|
+
},
|
|
324
|
+
...outputStrategy.formatProperty(
|
|
325
|
+
formatPropertyDescription(outputStrategy, "the human-readable table"),
|
|
326
|
+
),
|
|
327
|
+
limit: {
|
|
328
|
+
type: "integer",
|
|
329
|
+
minimum: 1,
|
|
330
|
+
maximum: limits.maxListRows,
|
|
331
|
+
description: `Maximum rows to return. Defaults to ${limits.maxListRows}; values outside 1 to ${limits.maxListRows} are rejected.`,
|
|
332
|
+
},
|
|
333
|
+
cursor: {
|
|
334
|
+
type: "string",
|
|
335
|
+
description: "Cursor from a previous list call; pass it back unchanged.",
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
additionalProperties: false,
|
|
339
|
+
},
|
|
340
|
+
output: outputStrategy.schema(LIST_OUTPUT_SCHEMA),
|
|
341
|
+
options: { namespace: config.namespace },
|
|
342
|
+
execute: async (rawInput, context) => {
|
|
343
|
+
const { input, format } = readToolInput(rawInput, outputStrategy)
|
|
344
|
+
const requested = readOptionalSessionID(input?.parentID)
|
|
345
|
+
if (input?.parentID !== undefined && requested === undefined) {
|
|
346
|
+
return toolError("parentID is invalid; use the exact ID reported by the server.")
|
|
347
|
+
}
|
|
348
|
+
const caller = context?.sessionID
|
|
349
|
+
const statusFilter = requestedStatuses(input?.statuses)
|
|
350
|
+
if (statusFilter.error) {
|
|
351
|
+
return toolError(statusFilter.error)
|
|
352
|
+
}
|
|
353
|
+
if (statusFilter.invalid.length > 0) {
|
|
354
|
+
const shown = statusFilter.invalid.slice(0, 5).join(", ")
|
|
355
|
+
const more =
|
|
356
|
+
statusFilter.invalid.length > 5
|
|
357
|
+
? `, and ${statusFilter.invalid.length - 5} more`
|
|
358
|
+
: ""
|
|
359
|
+
return toolError(
|
|
360
|
+
`Unknown status(es): ${shown}${more}. Use one or more of: ${CHILD_STATUSES.join(", ")}.`,
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
const statuses = statusFilter.statuses
|
|
364
|
+
if (statuses.size === 0) {
|
|
365
|
+
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
|
+
)
|
|
368
|
+
}
|
|
369
|
+
const limit = limitInteger(input?.limit, limits.maxListRows, 1, limits.maxListRows)
|
|
370
|
+
|
|
371
|
+
if (requested && requested !== caller) {
|
|
372
|
+
const parent = await access.getSession(requested, context?.signal)
|
|
373
|
+
if (context?.signal?.aborted) {
|
|
374
|
+
return toolError("Aborted before the parent could be read.")
|
|
375
|
+
}
|
|
376
|
+
if (!parent.ok || !parent.info) {
|
|
377
|
+
return toolError(`Parent session ${requested} could not be read.`)
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const root = requested ?? caller
|
|
382
|
+
if (!root) {
|
|
383
|
+
return toolError(
|
|
384
|
+
"Refusing: the calling session is unknown; pass parentID or call from a session.",
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
const filterKey = [...statuses].toSorted().join(",")
|
|
388
|
+
const cursorResult = readCursor(input?.cursor, {
|
|
389
|
+
tool: TOOL.list,
|
|
390
|
+
root,
|
|
391
|
+
filter: filterKey,
|
|
392
|
+
})
|
|
393
|
+
if (cursorResult.error) {
|
|
394
|
+
return toolError(cursorResult.error)
|
|
395
|
+
}
|
|
396
|
+
const cursor = cursorResult.cursor
|
|
397
|
+
if (context?.signal?.aborted) {
|
|
398
|
+
return toolError("Aborted before discovery.")
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const found = await discovery.discoverRows(root, context?.signal)
|
|
402
|
+
if (context?.signal?.aborted) {
|
|
403
|
+
return toolError("Aborted during discovery.")
|
|
404
|
+
}
|
|
405
|
+
const warning = found.complete ? "" : DISCOVERY_WARNING_TEXT
|
|
406
|
+
const allMatches = found.rows.filter((row) => statuses.has(row.status))
|
|
407
|
+
const afterCursor = cursor
|
|
408
|
+
? allMatches.filter((row) => isAfterCursor(row, cursor))
|
|
409
|
+
: allMatches
|
|
410
|
+
|
|
411
|
+
const outputFor = (
|
|
412
|
+
page: readonly SessionRow[],
|
|
413
|
+
matching: number,
|
|
414
|
+
window: number,
|
|
415
|
+
remaining: number,
|
|
416
|
+
remainingPages: number,
|
|
417
|
+
nextCursor?: string,
|
|
418
|
+
): ListOutput => {
|
|
419
|
+
const output: ListOutput = {
|
|
420
|
+
root,
|
|
421
|
+
statuses: [...statuses],
|
|
422
|
+
discoveryComplete: found.complete,
|
|
423
|
+
known: found.rows.length,
|
|
424
|
+
matching,
|
|
425
|
+
window,
|
|
426
|
+
remaining,
|
|
427
|
+
remainingPages,
|
|
428
|
+
counts: countStatuses(found.rows),
|
|
429
|
+
rows: page.map(rowOutput),
|
|
430
|
+
}
|
|
431
|
+
if (!found.complete) {
|
|
432
|
+
output.warning = DISCOVERY_WARNING
|
|
433
|
+
}
|
|
434
|
+
if (nextCursor) output.cursor = nextCursor
|
|
435
|
+
return output
|
|
436
|
+
}
|
|
437
|
+
const respond = (content: string, output: ListOutput) =>
|
|
438
|
+
outputStrategy.respond(content, output, format)
|
|
439
|
+
|
|
440
|
+
if (found.rows.length === 0) {
|
|
441
|
+
return respond(
|
|
442
|
+
`No subagents discovered for ${root}.` + warning,
|
|
443
|
+
outputFor([], 0, 0, 0, 0),
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const label = statusesLabel(statuses)
|
|
448
|
+
if (allMatches.length === 0) {
|
|
449
|
+
return respond(
|
|
450
|
+
`${found.rows.length} known subagent(s) for ${root}, none match statuses: ${label}.` +
|
|
451
|
+
warning,
|
|
452
|
+
outputFor([], 0, 0, 0, 0),
|
|
453
|
+
)
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (afterCursor.length === 0) {
|
|
457
|
+
return respond(
|
|
458
|
+
`Cursor is past the end: ${found.rows.length} known subagent(s) for ${root}.` +
|
|
459
|
+
warning,
|
|
460
|
+
outputFor([], allMatches.length, 0, 0, 0),
|
|
461
|
+
)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const shown = afterCursor.slice(0, limit)
|
|
465
|
+
const nextCursor =
|
|
466
|
+
afterCursor.length > shown.length
|
|
467
|
+
? encodeCursor(shown[shown.length - 1], {
|
|
468
|
+
tool: TOOL.list,
|
|
469
|
+
root,
|
|
470
|
+
filter: filterKey,
|
|
471
|
+
})
|
|
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
|
|
476
|
+
const summary = paginationSummary({
|
|
477
|
+
shown: shown.length,
|
|
478
|
+
afterCursor: afterCursor.length,
|
|
479
|
+
allMatches: allMatches.length,
|
|
480
|
+
limit,
|
|
481
|
+
remainingPages,
|
|
482
|
+
nextCursor,
|
|
483
|
+
hasCursor: cursor !== undefined,
|
|
484
|
+
})
|
|
485
|
+
const beforeCursorNote =
|
|
486
|
+
cursor && beforeCursor > 0
|
|
487
|
+
? `\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
|
+
: ""
|
|
489
|
+
return respond(
|
|
490
|
+
shown.map(rowText).join("\n") + summary + beforeCursorNote + warning,
|
|
491
|
+
outputFor(
|
|
492
|
+
shown,
|
|
493
|
+
allMatches.length,
|
|
494
|
+
afterCursor.length,
|
|
495
|
+
remaining,
|
|
496
|
+
remainingPages,
|
|
497
|
+
nextCursor,
|
|
498
|
+
),
|
|
499
|
+
)
|
|
500
|
+
},
|
|
501
|
+
})
|
|
502
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { JsonSchema } from "effect"
|
|
2
|
+
import { OUTPUT_FORMAT, normalizeOutputFormats, type OutputFormat } from "../config"
|
|
3
|
+
import { TOOL, type ToolName } from "./names"
|
|
4
|
+
|
|
5
|
+
export interface OutputResult {
|
|
6
|
+
readonly content: string
|
|
7
|
+
readonly output?: unknown
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface OutputFormatProperty {
|
|
11
|
+
readonly format?: {
|
|
12
|
+
readonly type: "string"
|
|
13
|
+
readonly enum: readonly OutputFormat[]
|
|
14
|
+
readonly description: string
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type ResponseFactory = (content: string, output: unknown) => OutputResult
|
|
19
|
+
|
|
20
|
+
interface FormatHandler {
|
|
21
|
+
/** Response when this format is the only allowed one. */
|
|
22
|
+
readonly solo: ResponseFactory
|
|
23
|
+
/** Response when this format is selected among several allowed formats. */
|
|
24
|
+
readonly combined: ResponseFactory
|
|
25
|
+
/** Output schema when this format is the only allowed one. */
|
|
26
|
+
readonly soloSchema: (
|
|
27
|
+
schema: JsonSchema.JsonSchema,
|
|
28
|
+
) => JsonSchema.JsonSchema | undefined
|
|
29
|
+
/** Output schema contribution when several formats are allowed. */
|
|
30
|
+
readonly combinedSchema: (schema: JsonSchema.JsonSchema) => JsonSchema.JsonSchema
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const TEXT_HANDLER: FormatHandler = {
|
|
34
|
+
solo: (content) => ({ content }),
|
|
35
|
+
combined: (content) => ({ content, output: content }),
|
|
36
|
+
soloSchema: () => undefined,
|
|
37
|
+
combinedSchema: () => ({ type: "string" }),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const JSON_HANDLER: FormatHandler = {
|
|
41
|
+
solo: (content, output) => ({ content, output }),
|
|
42
|
+
combined: (content, output) => ({ content, output }),
|
|
43
|
+
soloSchema: (schema) => schema,
|
|
44
|
+
combinedSchema: (schema) => schema,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const FORMAT_HANDLERS: Readonly<Record<OutputFormat, FormatHandler>> = {
|
|
48
|
+
[OUTPUT_FORMAT.text]: TEXT_HANDLER,
|
|
49
|
+
[OUTPUT_FORMAT.json]: JSON_HANDLER,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const FORMAT_HANDLER_MAP: ReadonlyMap<OutputFormat, FormatHandler> = new Map(
|
|
53
|
+
Object.entries(FORMAT_HANDLERS) as Array<[OutputFormat, FormatHandler]>,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
export interface OutputStrategy {
|
|
57
|
+
/** Formats this strategy accepts, in canonical order. */
|
|
58
|
+
readonly formats: readonly OutputFormat[]
|
|
59
|
+
/** The effective default when format is omitted or invalid. */
|
|
60
|
+
readonly defaultFormat: OutputFormat
|
|
61
|
+
/** The per-call format input property, or an empty object when there is no choice. */
|
|
62
|
+
readonly formatProperty: (description: string) => OutputFormatProperty
|
|
63
|
+
/** The tool output schema, or undefined when output is text-only. */
|
|
64
|
+
readonly schema: (schema: JsonSchema.JsonSchema) => JsonSchema.JsonSchema | undefined
|
|
65
|
+
/** Resolve the effective format for this call. */
|
|
66
|
+
readonly selectFormat: (requested: unknown) => OutputFormat
|
|
67
|
+
/** Build the tool result for the selected format. */
|
|
68
|
+
readonly respond: (
|
|
69
|
+
content: string,
|
|
70
|
+
output: unknown,
|
|
71
|
+
format: OutputFormat,
|
|
72
|
+
) => OutputResult
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export const TOOL_FORMAT_DEFAULTS: Readonly<Record<ToolName, OutputFormat>> = {
|
|
76
|
+
[TOOL.list]: OUTPUT_FORMAT.json,
|
|
77
|
+
[TOOL.usage]: OUTPUT_FORMAT.json,
|
|
78
|
+
[TOOL.cancelDescendants]: OUTPUT_FORMAT.json,
|
|
79
|
+
[TOOL.cancel]: OUTPUT_FORMAT.text,
|
|
80
|
+
[TOOL.steer]: OUTPUT_FORMAT.text,
|
|
81
|
+
[TOOL.queue]: OUTPUT_FORMAT.text,
|
|
82
|
+
[TOOL.context]: OUTPUT_FORMAT.text,
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const TOOL_FORMAT_DEFAULT_MAP: ReadonlyMap<ToolName, OutputFormat> = new Map(
|
|
86
|
+
Object.entries(TOOL_FORMAT_DEFAULTS) as Array<[ToolName, OutputFormat]>,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
const NO_FORMAT_PROPERTY = (): OutputFormatProperty => ({})
|
|
90
|
+
|
|
91
|
+
const handlerFor = (format: OutputFormat): FormatHandler => {
|
|
92
|
+
const handler = FORMAT_HANDLER_MAP.get(format)
|
|
93
|
+
if (!handler) throw new Error(`Unsupported output format: ${format}`)
|
|
94
|
+
return handler
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const resolveOutputStrategy = (
|
|
98
|
+
allowedOutputFormats: readonly OutputFormat[],
|
|
99
|
+
preferredFormat: OutputFormat,
|
|
100
|
+
): OutputStrategy => {
|
|
101
|
+
// Invalid and empty inputs fall back to the default set. The config layer
|
|
102
|
+
// uses the same normalizer, so a malformed option cannot widen the surface.
|
|
103
|
+
const formats = normalizeOutputFormats(allowedOutputFormats)
|
|
104
|
+
const handlers = formats.map(handlerFor)
|
|
105
|
+
const defaultFormat = formats.includes(preferredFormat) ? preferredFormat : formats[0]
|
|
106
|
+
|
|
107
|
+
if (formats.length === 1) {
|
|
108
|
+
const format = formats[0]
|
|
109
|
+
const handler = handlers[0]
|
|
110
|
+
return {
|
|
111
|
+
formats,
|
|
112
|
+
defaultFormat,
|
|
113
|
+
formatProperty: NO_FORMAT_PROPERTY,
|
|
114
|
+
schema: handler.soloSchema,
|
|
115
|
+
selectFormat: () => format,
|
|
116
|
+
respond: (content, output) => handler.solo(content, output),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const handlerByFormat = new Map(
|
|
121
|
+
formats.map((format, index) => [format, handlers[index]] as const),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
formats,
|
|
126
|
+
defaultFormat,
|
|
127
|
+
formatProperty: (description) => ({
|
|
128
|
+
format: {
|
|
129
|
+
type: "string",
|
|
130
|
+
enum: [...formats],
|
|
131
|
+
description,
|
|
132
|
+
},
|
|
133
|
+
}),
|
|
134
|
+
schema: (schema) => ({
|
|
135
|
+
anyOf: handlers.map((handler) => handler.combinedSchema(schema)),
|
|
136
|
+
}),
|
|
137
|
+
selectFormat: (requested) =>
|
|
138
|
+
typeof requested === "string" && handlerByFormat.has(requested as OutputFormat)
|
|
139
|
+
? (requested as OutputFormat)
|
|
140
|
+
: defaultFormat,
|
|
141
|
+
respond: (content, output, format) => {
|
|
142
|
+
const handler = handlerByFormat.get(format)
|
|
143
|
+
if (!handler) throw new Error(`Unsupported output format: ${format}`)
|
|
144
|
+
return handler.combined(content, output)
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export const resolveToolOutputStrategy = (
|
|
150
|
+
allowedOutputFormats: readonly OutputFormat[],
|
|
151
|
+
tool: ToolName,
|
|
152
|
+
): OutputStrategy => {
|
|
153
|
+
const preferred = TOOL_FORMAT_DEFAULT_MAP.get(tool)
|
|
154
|
+
if (!preferred) throw new Error(`Unsupported tool: ${String(tool)}`)
|
|
155
|
+
return resolveOutputStrategy(allowedOutputFormats, preferred)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export const otherOutputFormat = (strategy: OutputStrategy): OutputFormat | undefined =>
|
|
159
|
+
strategy.formats.find((format) => format !== strategy.defaultFormat)
|
|
160
|
+
|
|
161
|
+
export const formatPropertyDescription = (
|
|
162
|
+
strategy: OutputStrategy,
|
|
163
|
+
otherHint: string,
|
|
164
|
+
): string => {
|
|
165
|
+
const other = otherOutputFormat(strategy)
|
|
166
|
+
return other
|
|
167
|
+
? `Response format. Defaults to ${strategy.defaultFormat}; use ${other} for ${otherHint}.`
|
|
168
|
+
: `Response format. Defaults to ${strategy.defaultFormat}.`
|
|
169
|
+
}
|