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,396 @@
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 type { Discovery } from "../discovery"
6
+ import { errorMessage, toolError } from "../errors"
7
+ import { compactNumber, formatCost } from "../format"
8
+ import type { LiveStore } from "../live-state"
9
+ import type {
10
+ ModelInfoLike,
11
+ ModelRefLike,
12
+ SessionInfoLike,
13
+ UsageMessage,
14
+ } from "../session"
15
+ import { CHILD_STATUSES, STATUS, statusUsageMayLag, type ChildStatus } from "../status"
16
+ import {
17
+ CONTEXT_USAGE,
18
+ TOKEN_USAGE_SCHEMA,
19
+ addTokens,
20
+ contextFromMessages,
21
+ normalizeTokens,
22
+ tokensUsed,
23
+ type LastRequestUsage,
24
+ type TokenUsage,
25
+ } from "../tokens"
26
+ import { readToolInput, requireSessionID } from "./input"
27
+ import { TOOL } from "./names"
28
+ import { formatPropertyDescription, resolveToolOutputStrategy } from "./output"
29
+
30
+ export interface TreeUsage {
31
+ /** Total sessions in the tree rooted at the target, including the target. */
32
+ sessions: number
33
+ /** Sessions below the target; excludes the target. */
34
+ descendants: number
35
+ costUSD: number
36
+ tokens?: TokenUsage
37
+ /** Omitted when no session in the tree reported token data. */
38
+ tokensUsed?: number
39
+ /** Whether discovery walked the whole descendant subtree. */
40
+ discoveryComplete: boolean
41
+ /** True when at least one descendant is running or unknown. */
42
+ descendantsMayLag?: boolean
43
+ warning?: string
44
+ }
45
+
46
+ export interface UsageOutput {
47
+ sessionID: string
48
+ parentID?: string
49
+ status: ChildStatus
50
+ /** Usage is as of the last persisted step; running/unknown sessions may lag. */
51
+ usageMayLag?: boolean
52
+ costUSD?: number
53
+ tokens?: TokenUsage
54
+ tokensUsed?: number
55
+ contextTokens?: number
56
+ contextLimit?: number
57
+ contextPercent?: number
58
+ lastRequest?: LastRequestUsage
59
+ model?: ModelRefLike
60
+ tree?: TreeUsage
61
+ warning?: string
62
+ }
63
+
64
+ const USAGE_OUTPUT_SCHEMA = {
65
+ type: "object",
66
+ properties: {
67
+ sessionID: { type: "string" },
68
+ parentID: { type: "string" },
69
+ status: {
70
+ type: "string",
71
+ enum: [...CHILD_STATUSES],
72
+ description: "Observed status; the calling session is reported as running.",
73
+ },
74
+ usageMayLag: {
75
+ type: "boolean",
76
+ description: "True when the session is running or unknown; usage may lag.",
77
+ },
78
+ costUSD: { type: "number" },
79
+ tokens: TOKEN_USAGE_SCHEMA,
80
+ tokensUsed: { type: "integer" },
81
+ contextTokens: { type: "integer" },
82
+ contextLimit: { type: "integer" },
83
+ contextPercent: { type: "number" },
84
+ lastRequest: {
85
+ type: "object",
86
+ properties: {
87
+ input: { type: "integer" },
88
+ output: { type: "integer" },
89
+ reasoning: { type: "integer" },
90
+ cacheRead: { type: "integer" },
91
+ cacheWrite: { type: "integer" },
92
+ total: { type: "integer" },
93
+ },
94
+ required: ["input", "output", "reasoning", "cacheRead", "cacheWrite", "total"],
95
+ additionalProperties: false,
96
+ },
97
+ model: {
98
+ type: "object",
99
+ properties: {
100
+ id: { type: "string" },
101
+ providerID: { type: "string" },
102
+ variant: { type: "string" },
103
+ },
104
+ additionalProperties: false,
105
+ },
106
+ tree: {
107
+ type: "object",
108
+ properties: {
109
+ sessions: {
110
+ type: "integer",
111
+ description: "Sessions in the tree, including the target.",
112
+ },
113
+ descendants: {
114
+ type: "integer",
115
+ description: "Sessions below the target.",
116
+ },
117
+ costUSD: { type: "number" },
118
+ tokens: TOKEN_USAGE_SCHEMA,
119
+ tokensUsed: { type: "integer" },
120
+ discoveryComplete: {
121
+ type: "boolean",
122
+ description:
123
+ "Whether discovery walked the whole descendant subtree; missing descendants are possible when false.",
124
+ },
125
+ descendantsMayLag: {
126
+ type: "boolean",
127
+ description:
128
+ "True when at least one descendant is running or unknown; tree totals may lag, while top-level usageMayLag covers the target.",
129
+ },
130
+ warning: { type: "string" },
131
+ },
132
+ required: ["sessions", "descendants", "costUSD", "discoveryComplete"],
133
+ additionalProperties: false,
134
+ },
135
+ warning: { type: "string" },
136
+ },
137
+ required: ["sessionID", "status"],
138
+ additionalProperties: false,
139
+ } as const
140
+
141
+ export interface UsageDeps {
142
+ config: Config
143
+ access: Access
144
+ discovery: Discovery
145
+ live: LiveStore
146
+ session: Plugin.Context["session"]
147
+ model: Plugin.Context["model"]
148
+ }
149
+
150
+ export const registerUsageTool = (
151
+ editor: ToolEditor,
152
+ { config, access, discovery, live, session, model }: UsageDeps,
153
+ ) => {
154
+ const { allowedOutputFormats } = config
155
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.usage)
156
+
157
+ editor.add({
158
+ name: TOOL.usage,
159
+ description:
160
+ "Read cost, tokens, current context, and status for a session. " +
161
+ "Returns own cumulative cost and tokens, the current context footprint, the model context limit when available, and optional tree totals. " +
162
+ "Read-only; any session ID is accepted. " +
163
+ "Values are as of the last persisted step and may lag while the session is running or unknown.",
164
+ input: {
165
+ type: "object",
166
+ properties: {
167
+ sessionID: { type: "string", description: "Target session ID, e.g. ses_..." },
168
+ includeDescendants: {
169
+ type: "boolean",
170
+ description: "Add tree totals for the target and its descendants.",
171
+ },
172
+ ...outputStrategy.formatProperty(
173
+ formatPropertyDescription(outputStrategy, "a human-readable summary"),
174
+ ),
175
+ },
176
+ required: ["sessionID"],
177
+ additionalProperties: false,
178
+ },
179
+ output: outputStrategy.schema(USAGE_OUTPUT_SCHEMA),
180
+ options: { namespace: config.namespace },
181
+ execute: async (rawInput, context) => {
182
+ const { input, format } = readToolInput(rawInput, outputStrategy)
183
+ const sessionID = requireSessionID(input?.sessionID)
184
+
185
+ let info: SessionInfoLike | undefined
186
+ try {
187
+ info = await access.readTarget(sessionID, context)
188
+ } catch (error) {
189
+ return toolError(errorMessage(error))
190
+ }
191
+ if (!info) {
192
+ const fetched = await access.getSession(sessionID, context?.signal)
193
+ if (!fetched.ok) {
194
+ return toolError(
195
+ `Usage unavailable for ${sessionID}: session could not be read.`,
196
+ )
197
+ }
198
+ info = fetched.info
199
+ }
200
+ if (!info) {
201
+ return toolError(`Usage unavailable for ${sessionID}: session not found.`)
202
+ }
203
+ if (context?.signal?.aborted) {
204
+ return toolError("Aborted before usage was read.")
205
+ }
206
+
207
+ // A tool call proves the caller is executing, even when the last
208
+ // persisted run ended earlier. Do not report a finished status for self.
209
+ const status =
210
+ context?.sessionID === sessionID
211
+ ? STATUS.running
212
+ : live.statusFor(info, sessionID)
213
+ const usageMayLag = statusUsageMayLag(status)
214
+ const ownTokens = normalizeTokens(info.tokens)
215
+ const ownCost =
216
+ typeof info.cost === "number" && Number.isFinite(info.cost)
217
+ ? info.cost
218
+ : undefined
219
+ const warnings: string[] = []
220
+
221
+ let messages: UsageMessage[] | undefined
222
+ try {
223
+ const result = await session.context({ sessionID }, { signal: context?.signal })
224
+ if (Array.isArray(result)) {
225
+ const raw = result as unknown[]
226
+ if (raw.some((message) => !message || typeof message !== "object")) {
227
+ warnings.push("context unavailable: server returned malformed messages")
228
+ } else {
229
+ messages = raw as UsageMessage[]
230
+ }
231
+ } else {
232
+ warnings.push("context unavailable: server returned no message list")
233
+ }
234
+ } catch (error) {
235
+ if (context?.signal?.aborted) {
236
+ return toolError("Aborted while reading context.")
237
+ }
238
+ warnings.push(`context unavailable: ${errorMessage(error)}`)
239
+ }
240
+ const revertBoundaryMissing =
241
+ messages !== undefined &&
242
+ info.revert?.messageID !== undefined &&
243
+ !messages.some((message) => message.id === info.revert?.messageID)
244
+ if (revertBoundaryMissing) {
245
+ warnings.push(
246
+ "context unavailable: staged revert boundary is not present in the session context",
247
+ )
248
+ }
249
+ const contextUsage =
250
+ messages && !revertBoundaryMissing && messages.length > 0
251
+ ? contextFromMessages(messages, info.revert?.messageID)
252
+ : undefined
253
+ if (contextUsage?.kind === CONTEXT_USAGE.missing) {
254
+ warnings.push(
255
+ "context unavailable: token data is missing from the last assistant step",
256
+ )
257
+ }
258
+ const contextTokens =
259
+ messages && !revertBoundaryMissing
260
+ ? contextUsage?.kind === CONTEXT_USAGE.usage
261
+ ? contextUsage.total
262
+ : contextUsage?.kind === CONTEXT_USAGE.missing
263
+ ? undefined
264
+ : 0
265
+ : undefined
266
+
267
+ const modelRef =
268
+ info.model ??
269
+ (contextUsage?.kind === CONTEXT_USAGE.usage ? contextUsage.model : undefined)
270
+ let contextLimit: number | undefined
271
+ if (modelRef?.providerID && modelRef.id) {
272
+ try {
273
+ const catalog = (await model.list()) as { data?: ModelInfoLike[] }
274
+ const models = catalog?.data ?? []
275
+ const found = models.find(
276
+ (item) =>
277
+ item.providerID === modelRef.providerID &&
278
+ (item.id === modelRef.id || item.modelID === modelRef.id),
279
+ )
280
+ if (typeof found?.limit?.context === "number" && found.limit.context > 0) {
281
+ contextLimit = found.limit.context
282
+ }
283
+ } catch {
284
+ // The model catalog is optional; usage still works without a limit.
285
+ }
286
+ }
287
+ if (context?.signal?.aborted) {
288
+ return toolError("Aborted while reading usage.")
289
+ }
290
+ const contextPercent =
291
+ contextTokens !== undefined && contextLimit
292
+ ? Math.round((contextTokens / contextLimit) * 100)
293
+ : undefined
294
+
295
+ let tree: TreeUsage | undefined
296
+ if (input.includeDescendants === true) {
297
+ const found = await discovery.discoverRows(sessionID, context?.signal)
298
+ if (context?.signal?.aborted) {
299
+ return toolError("Aborted while reading tree usage.")
300
+ }
301
+ let sessions = 1
302
+ let descendants = 0
303
+ let costUSD = ownCost ?? 0
304
+ let tokens = ownTokens
305
+ let descendantsMayLag = false
306
+ for (const row of found.rows) {
307
+ sessions++
308
+ descendants++
309
+ if (row.cost !== undefined) costUSD += row.cost
310
+ if (row.tokens) tokens = addTokens(tokens, row.tokens)
311
+ if (statusUsageMayLag(row.status)) descendantsMayLag = true
312
+ }
313
+ tree = {
314
+ sessions,
315
+ descendants,
316
+ costUSD,
317
+ discoveryComplete: found.complete,
318
+ }
319
+ if (tokens) {
320
+ tree.tokens = tokens
321
+ tree.tokensUsed = tokensUsed(tokens)
322
+ }
323
+ if (descendantsMayLag) tree.descendantsMayLag = true
324
+ if (!found.complete) {
325
+ tree.warning = "discovery was incomplete; some descendants may be missing."
326
+ }
327
+ }
328
+
329
+ const output: UsageOutput = { sessionID, status }
330
+ if (info.parentID) output.parentID = info.parentID
331
+ if (usageMayLag) output.usageMayLag = true
332
+ if (ownCost !== undefined) output.costUSD = ownCost
333
+ if (ownTokens) {
334
+ output.tokens = ownTokens
335
+ output.tokensUsed = tokensUsed(ownTokens)
336
+ }
337
+ if (contextTokens !== undefined) output.contextTokens = contextTokens
338
+ if (contextUsage?.kind === CONTEXT_USAGE.usage) {
339
+ output.lastRequest = contextUsage.lastRequest
340
+ }
341
+ if (contextLimit !== undefined) output.contextLimit = contextLimit
342
+ if (contextPercent !== undefined) output.contextPercent = contextPercent
343
+ if (modelRef) {
344
+ const modelOutput: ModelRefLike = {}
345
+ if (modelRef.providerID) modelOutput.providerID = modelRef.providerID
346
+ if (modelRef.id) modelOutput.id = modelRef.id
347
+ if (modelRef.variant) modelOutput.variant = modelRef.variant
348
+ if (Object.keys(modelOutput).length > 0) output.model = modelOutput
349
+ }
350
+ if (tree) {
351
+ output.tree = tree
352
+ if (tree.warning) warnings.push(tree.warning)
353
+ }
354
+ if (warnings.length > 0) output.warning = warnings.join("; ")
355
+
356
+ const lines: string[] = [`Session ${sessionID}`]
357
+ if (info.parentID) lines.push(`parent=${info.parentID}`)
358
+ lines.push(`status=${status}${usageMayLag ? " (usage may lag)" : ""}`)
359
+ if (ownCost !== undefined) lines.push(`cost=${formatCost(ownCost)}`)
360
+ if (ownTokens) {
361
+ lines.push(
362
+ `used=${compactNumber(tokensUsed(ownTokens))} ` +
363
+ `(input=${ownTokens.input}, output=${ownTokens.output}, reasoning=${ownTokens.reasoning}, ` +
364
+ `cache.read=${ownTokens.cache.read}, cache.write=${ownTokens.cache.write})`,
365
+ )
366
+ }
367
+ if (contextTokens !== undefined) {
368
+ lines.push(
369
+ `context=${compactNumber(contextTokens)}` +
370
+ (contextLimit !== undefined ? ` / ${compactNumber(contextLimit)}` : "") +
371
+ (contextPercent !== undefined ? ` (${contextPercent}%)` : ""),
372
+ )
373
+ if (contextUsage?.kind === CONTEXT_USAGE.usage) {
374
+ lines.push(
375
+ `last request: input=${contextUsage.lastRequest.input}, output=${contextUsage.lastRequest.output}, ` +
376
+ `reasoning=${contextUsage.lastRequest.reasoning}, cache.read=${contextUsage.lastRequest.cacheRead}, ` +
377
+ `cache.write=${contextUsage.lastRequest.cacheWrite}`,
378
+ )
379
+ }
380
+ } else {
381
+ lines.push("context=unavailable")
382
+ }
383
+ if (tree) {
384
+ const treeUsed =
385
+ tree.tokensUsed !== undefined ? compactNumber(tree.tokensUsed) : "unknown"
386
+ lines.push(
387
+ `tree: ${tree.sessions} session(s) (${tree.descendants} descendant(s)), cost=${formatCost(tree.costUSD)}, used=${treeUsed}` +
388
+ (tree.descendantsMayLag ? " (descendant usage may lag)" : ""),
389
+ )
390
+ }
391
+ if (warnings.length > 0) lines.push(`warning: ${warnings.join("; ")}`)
392
+ const content = lines.join("\n")
393
+ return outputStrategy.respond(content, output, format)
394
+ },
395
+ })
396
+ }