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