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,205 @@
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 { errorMessage, toolError } from "../errors"
6
+ import { INTERRUPT_OUTCOME, interruptOutcome } from "../interrupt"
7
+ import type { LiveStore } from "../live-state"
8
+ import { guardTarget, type Guard } from "../permissions"
9
+ import type { SessionInfoLike } from "../session"
10
+ import { CHILD_STATUSES, STATUS, statusIsIdle, type ChildStatus } from "../status"
11
+ import {
12
+ TOKEN_USAGE_SCHEMA,
13
+ normalizeTokens,
14
+ tokensUsed,
15
+ type TokenUsage,
16
+ } from "../tokens"
17
+ import {
18
+ MAX_REASON_LENGTH,
19
+ readTextField,
20
+ readToolInput,
21
+ requireSessionID,
22
+ } from "./input"
23
+ import { TOOL } from "./names"
24
+ import { formatPropertyDescription, resolveToolOutputStrategy } from "./output"
25
+
26
+ export const CANCEL_OUTCOME = {
27
+ accepted: INTERRUPT_OUTCOME.accepted,
28
+ rejected: INTERRUPT_OUTCOME.rejected,
29
+ unknown: INTERRUPT_OUTCOME.unknown,
30
+ } as const
31
+
32
+ export type CancelOutcome = (typeof CANCEL_OUTCOME)[keyof typeof CANCEL_OUTCOME]
33
+
34
+ const CANCEL_PREFIX: Readonly<
35
+ Record<CancelOutcome, (sessionID: string, status: ChildStatus) => string>
36
+ > = {
37
+ [CANCEL_OUTCOME.accepted]: (sessionID) => `Interrupt requested for ${sessionID}`,
38
+ [CANCEL_OUTCOME.rejected]: (sessionID, status) =>
39
+ statusIsIdle(status)
40
+ ? `${sessionID} was not running; no interrupt was needed`
41
+ : `Interrupt was not accepted for ${sessionID}`,
42
+ [CANCEL_OUTCOME.unknown]: (sessionID) => `Interrupt outcome unknown for ${sessionID}`,
43
+ }
44
+
45
+ export interface CancelOutput {
46
+ sessionID: string
47
+ accepted: boolean
48
+ interrupt: CancelOutcome
49
+ status: ChildStatus
50
+ reason?: string
51
+ readBackMayLag: boolean
52
+ cancellationDoesNotCascade: boolean
53
+ costUSD?: number
54
+ tokens?: TokenUsage
55
+ tokensUsed?: number
56
+ }
57
+
58
+ const CANCEL_OUTPUT_SCHEMA = {
59
+ type: "object",
60
+ properties: {
61
+ sessionID: { type: "string" },
62
+ accepted: {
63
+ type: "boolean",
64
+ description: 'Alias for interrupt === "accepted".',
65
+ },
66
+ interrupt: {
67
+ type: "string",
68
+ enum: Object.values(CANCEL_OUTCOME),
69
+ description:
70
+ "accepted: server accepted; rejected: no active execution; unknown: aborted or no definitive answer.",
71
+ },
72
+ status: { type: "string", enum: [...CHILD_STATUSES] },
73
+ reason: { type: "string" },
74
+ readBackMayLag: { type: "boolean" },
75
+ cancellationDoesNotCascade: {
76
+ type: "boolean",
77
+ description: "Always true; cancellation does not cascade.",
78
+ },
79
+ costUSD: { type: "number" },
80
+ tokens: TOKEN_USAGE_SCHEMA,
81
+ tokensUsed: { type: "integer" },
82
+ },
83
+ required: [
84
+ "sessionID",
85
+ "accepted",
86
+ "interrupt",
87
+ "status",
88
+ "readBackMayLag",
89
+ "cancellationDoesNotCascade",
90
+ ],
91
+ additionalProperties: false,
92
+ } as const
93
+
94
+ export interface CancelDeps {
95
+ config: Config
96
+ access: Access
97
+ guard: Guard
98
+ live: LiveStore
99
+ session: Plugin.Context["session"]
100
+ }
101
+
102
+ export const registerCancelTool = (
103
+ editor: ToolEditor,
104
+ { config, access, guard, live, session }: CancelDeps,
105
+ ) => {
106
+ const { allowedOutputFormats } = config
107
+ const outputStrategy = resolveToolOutputStrategy(allowedOutputFormats, TOOL.cancel)
108
+
109
+ editor.add({
110
+ name: TOOL.cancel,
111
+ description:
112
+ "Stop one session by its session ID. " +
113
+ "This is a soft interrupt: it stops only that session, does not cascade, and a long tool call may finish first. " +
114
+ "Jobs owned by an idle session keep running. " +
115
+ "OpenCode may wake the parent with a cancellation notice. " +
116
+ "The reason is recorded in the result and is not delivered to the child.",
117
+ input: {
118
+ type: "object",
119
+ properties: {
120
+ sessionID: {
121
+ type: "string",
122
+ description: "Target session ID, e.g. ses_...",
123
+ },
124
+ reason: {
125
+ type: "string",
126
+ description: `Short reason, recorded in the result. Maximum ${MAX_REASON_LENGTH} characters.`,
127
+ },
128
+ ...outputStrategy.formatProperty(
129
+ formatPropertyDescription(outputStrategy, "structured output"),
130
+ ),
131
+ },
132
+ required: ["sessionID"],
133
+ additionalProperties: false,
134
+ },
135
+ output: outputStrategy.schema(CANCEL_OUTPUT_SCHEMA),
136
+ options: { namespace: config.namespace },
137
+ execute: async (rawInput, context) => {
138
+ const { input, format } = readToolInput(rawInput, outputStrategy)
139
+ const reasonField = readTextField(input?.reason, MAX_REASON_LENGTH, "reason")
140
+ if (reasonField.error) return toolError(reasonField.error)
141
+ const sessionID = requireSessionID(input?.sessionID)
142
+ let info: SessionInfoLike | undefined
143
+ try {
144
+ info = await access.authorize(sessionID, context)
145
+ } catch (error) {
146
+ return toolError(errorMessage(error))
147
+ }
148
+ const reason = reasonField.text
149
+ if (context?.signal?.aborted) {
150
+ return toolError("Aborted before the interrupt was requested.")
151
+ }
152
+ // Guard errors propagate unchanged: a denial surfaces as a tool error,
153
+ // and a plain rejection still ends the step.
154
+ await guard([guardTarget(info, sessionID)], context)
155
+ if (context?.signal?.aborted) {
156
+ return toolError("Aborted before the interrupt was requested.")
157
+ }
158
+ let result: { interrupted?: boolean } | undefined
159
+ try {
160
+ result = (await session.interrupt(
161
+ { sessionID, resume: false },
162
+ { signal: context?.signal },
163
+ )) as { interrupted?: boolean } | undefined
164
+ } catch (error) {
165
+ if (context?.signal?.aborted) {
166
+ const status = live.liveStatusFor(sessionID) ?? STATUS.unknown
167
+ return toolError(
168
+ `Interrupt outcome unknown for ${sessionID}: the call was aborted while the interrupt was in flight; it may or may not have been accepted. Last observed state: ${status}. Run ${config.namespace}_${TOOL.list} to confirm.`,
169
+ )
170
+ }
171
+ return toolError(`Interrupt failed for ${sessionID}: ${errorMessage(error)}`)
172
+ }
173
+ const { info: after } = await access.getSession(sessionID, context?.signal)
174
+ const status = after
175
+ ? live.statusFor(after, sessionID)
176
+ : (live.liveStatusFor(sessionID) ?? STATUS.unknown)
177
+ const interrupt = interruptOutcome(result)
178
+ const accepted = interrupt === CANCEL_OUTCOME.accepted
179
+ const readBackMayLag = accepted && !statusIsIdle(status)
180
+ const prefix = CANCEL_PREFIX[interrupt](sessionID, status)
181
+ const output: CancelOutput = {
182
+ sessionID,
183
+ accepted,
184
+ interrupt,
185
+ status,
186
+ readBackMayLag,
187
+ cancellationDoesNotCascade: true,
188
+ }
189
+ if (reason) output.reason = reason
190
+ if (typeof after?.cost === "number" && Number.isFinite(after.cost))
191
+ output.costUSD = after.cost
192
+ const afterTokens = normalizeTokens(after?.tokens)
193
+ if (afterTokens) {
194
+ output.tokens = afterTokens
195
+ output.tokensUsed = tokensUsed(afterTokens)
196
+ }
197
+ const lagNote = readBackMayLag ? " Read-back may lag; re-run list to confirm." : ""
198
+ return outputStrategy.respond(
199
+ `${prefix}${reason ? ` (${reason})` : ""}. Reported state now: ${status}.${lagNote}`,
200
+ output,
201
+ format,
202
+ )
203
+ },
204
+ })
205
+ }
@@ -0,0 +1,39 @@
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 type { LiveStore } from "../live-state"
7
+ import type { SendMessage } from "../messages"
8
+ import type { Guard } from "../permissions"
9
+ import { registerCancelDescendantsTool } from "./cancel-descendants"
10
+ import { registerCancelTool } from "./cancel"
11
+ import { registerListTool } from "./list"
12
+ import { registerContextTool, registerQueueTool, registerSteerTool } from "./send"
13
+ import { registerUsageTool } from "./usage"
14
+
15
+ export interface ToolDeps {
16
+ config: Config
17
+ access: Access
18
+ discovery: Discovery
19
+ live: LiveStore
20
+ guard: Guard
21
+ sendMessage: SendMessage
22
+ session: Plugin.Context["session"]
23
+ model: Plugin.Context["model"]
24
+ }
25
+
26
+ export const registerTools = (editor: ToolEditor, deps: ToolDeps) => {
27
+ editor.namespace({
28
+ name: deps.config.namespace,
29
+ description: "Inspect, stop, steer and feed context to subagent sessions.",
30
+ })
31
+
32
+ registerListTool(editor, deps)
33
+ registerUsageTool(editor, deps)
34
+ registerCancelTool(editor, deps)
35
+ registerCancelDescendantsTool(editor, deps)
36
+ registerSteerTool(editor, deps)
37
+ registerQueueTool(editor, deps)
38
+ registerContextTool(editor, deps)
39
+ }
@@ -0,0 +1,73 @@
1
+ import type { OutputFormat } from "../config"
2
+ import { REQUIRED_SESSION_ID, REQUIRED_TEXT, toolError } from "../errors"
3
+ import { normalizeSessionID } from "../session"
4
+ import { clipText, maxLengthError } from "../text"
5
+ import type { OutputStrategy } from "./output"
6
+
7
+ export const MAX_REASON_LENGTH = 500
8
+ export const MAX_DESCRIPTION_LENGTH = 200
9
+
10
+ export type ResponseFormat = OutputFormat
11
+
12
+ export interface ToolInput {
13
+ sessionID?: string
14
+ parentID?: string
15
+ text?: string
16
+ reason?: string
17
+ description?: string
18
+ statuses?: string[]
19
+ limit?: number
20
+ cursor?: string
21
+ format?: ResponseFormat
22
+ includeDescendants?: boolean
23
+ resume?: boolean
24
+ }
25
+
26
+ export interface ToolCtx {
27
+ sessionID?: string
28
+ agent?: string
29
+ messageID?: string
30
+ id?: string
31
+ signal?: AbortSignal
32
+ }
33
+
34
+ export const requireSessionID = (value: unknown): string => {
35
+ if (typeof value !== "string" || value.trim().length === 0) {
36
+ return toolError(REQUIRED_SESSION_ID)
37
+ }
38
+ const sessionID = normalizeSessionID(value)
39
+ if (!sessionID) {
40
+ return toolError("sessionID is invalid; use the exact ID reported by the server.")
41
+ }
42
+ return sessionID
43
+ }
44
+
45
+ export const readOptionalSessionID = (value: unknown): string | undefined => {
46
+ if (value === undefined) return undefined
47
+ if (typeof value !== "string" || value.trim().length === 0) return undefined
48
+ return normalizeSessionID(value)
49
+ }
50
+
51
+ export const requireText = (value: unknown, max: number): string => {
52
+ const text = clipText(value, max)
53
+ if (!text) return toolError(REQUIRED_TEXT)
54
+ return text
55
+ }
56
+
57
+ export const readTextField = (
58
+ value: unknown,
59
+ max: number,
60
+ field: string,
61
+ ): { text?: string; error?: string } => {
62
+ const error = maxLengthError(value, max, field)
63
+ if (error) return { error }
64
+ return { text: clipText(value, max) }
65
+ }
66
+
67
+ export const readToolInput = (
68
+ rawInput: unknown,
69
+ outputStrategy: OutputStrategy,
70
+ ): { input: ToolInput; format: ResponseFormat } => {
71
+ const input = (rawInput ?? {}) as ToolInput
72
+ return { input, format: outputStrategy.selectFormat(input.format) }
73
+ }